code
stringlengths
3
1.18M
language
stringclasses
1 value
package client.messages; import LevelObjects.Box; public class MoveBoxRequest extends MoveRequest { // What box needs to be moved public Box box; // Should the box be removed from a goal to enable a solution public boolean removeFromGoal; }
Java
package client; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map.Entry; import java.util.concurrent.LinkedBlockingQueue; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.UIManager; public class GuiClient extends JFrame { private static ActionListener listener = new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { CommandButton c = ( (CommandButton) e.getSource() ); buttonSend( c.t, c.cmd ); } }; // Receiver and Transmitter are not needed for most planners, but may lead to (negligible) speed up as you do not synchronize each // action with the server private class ServerReceiver extends Thread { private GuiClient gui; public ServerReceiver( GuiClient g ) { gui = g; } public void run() { try { BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); while ( true ) { String msg = reader.readLine(); if ( msg == null ) throw new IOException( "End of server messages" ); gui.AddCommunication( "<IN> " + msg ); } } catch ( IOException e ) { gui.AddInformation( e.toString() ); } } } private class ServerTransmitter extends Thread { private GuiClient gui; private LinkedBlockingQueue< String > outbound = new LinkedBlockingQueue< String >(); public ServerTransmitter( GuiClient g ) { gui = g; } public void run() { try { while ( true ) { String msg = outbound.take(); System.out.println( msg ); gui.AddCommunication( "<OUT> " + msg ); } } catch ( InterruptedException e ) { gui.AddInformation( e.toString() ); } } } private class CommandButton extends JButton { public final String cmd; public final ServerTransmitter t; public CommandButton( ServerTransmitter t, String label, String cmd ) { super( label ); this.t = t; this.cmd = cmd; this.addActionListener( listener ); } } public static void buttonSend( ServerTransmitter st, String cmd ) { st.outbound.add( cmd ); } private final String nl = System.getProperty( "line.separator" ); private JTextArea communication = new JTextArea(); private JTextArea information = new JTextArea(); private JPanel fixed = new JPanel(); private JPanel custom = new JPanel(); private JPanel comm = new JPanel(); private JPanel info = new JPanel(); private int msgNo; private int agents; private ServerReceiver receiver; private ServerTransmitter transmitter; private class GBC extends GridBagConstraints { public GBC( int x, int y ) { this( x, y, 1 ); } public GBC( int x, int y, int spanx ) { this.insets = new Insets( 0, 3, 0, 3 ); this.gridx = x; this.gridy = y; this.gridwidth = spanx; this.fill = GridBagConstraints.NONE; } public GBC( int x, int y, int spanx, int sep ) { this.insets = new Insets( sep, 3, sep, 3 ); this.gridx = x; this.gridy = y; this.gridwidth = spanx; this.fill = GridBagConstraints.HORIZONTAL; this.weightx = 0; } } public GuiClient( String[] customs ) throws IOException { super( "02285 Toy Client" ); System.err.println("Hello from GuiClient"); readMap(); // Get agent count receiver = new ServerReceiver( this ); transmitter = new ServerTransmitter( this ); communication.setEditable( false ); communication.setFont( new Font( "Monospaced", Font.PLAIN, 11 ) ); information.setEditable( false ); information.setFont( new Font( "Monospaced", Font.PLAIN, 11 ) ); // Fixed Buttons panel JSeparator sep1 = new JSeparator( JSeparator.HORIZONTAL ); JSeparator sep2 = new JSeparator( JSeparator.HORIZONTAL ); HashMap< String, GBC > buts = new HashMap< String, GBC >(); fixed.setLayout( new GridBagLayout() ); buts.put( "Move(N)", new GBC( 3, 0 ) ); buts.put( "Move(W)", new GBC( 2, 1 ) ); buts.put( "Move(E)", new GBC( 4, 1 ) ); buts.put( "Move(S)", new GBC( 3, 2 ) ); fixed.add( new JLabel( "Navigation" ), new GBC( 2, 1, 3 ) ); fixed.add( sep1, new GBC( 0, 3, 7, 10 ) ); int yoff = 4; buts.put( "Push(N,N)", new GBC( 3, yoff + 1 ) ); buts.put( "Push(N,W)", new GBC( 2, yoff + 1 ) ); buts.put( "Push(W,N)", new GBC( 1, yoff + 2 ) ); buts.put( "Push(W,W)", new GBC( 1, yoff + 3 ) ); buts.put( "Push(W,S)", new GBC( 1, yoff + 4 ) ); buts.put( "Push(S,W)", new GBC( 2, yoff + 5 ) ); buts.put( "Push(N,E)", new GBC( 4, yoff + 1 ) ); buts.put( "Push(E,N)", new GBC( 5, yoff + 2 ) ); buts.put( "Push(E,E)", new GBC( 5, yoff + 3 ) ); buts.put( "Push(E,S)", new GBC( 5, yoff + 4 ) ); buts.put( "Push(S,E)", new GBC( 4, yoff + 5 ) ); buts.put( "Push(S,S)", new GBC( 3, yoff + 5 ) ); fixed.add( new JLabel( "Push" ), new GBC( 2, yoff + 3, 3 ) ); fixed.add( sep2, new GBC( 0, yoff + 7, 7, 10 ) ); yoff = 12; buts.put( "Pull(N,S)", new GBC( 3, yoff + 1 ) ); buts.put( "Pull(N,W)", new GBC( 2, yoff + 1 ) ); buts.put( "Pull(W,N)", new GBC( 1, yoff + 2 ) ); buts.put( "Pull(W,E)", new GBC( 1, yoff + 3 ) ); buts.put( "Pull(W,S)", new GBC( 1, yoff + 4 ) ); buts.put( "Pull(S,W)", new GBC( 2, yoff + 5 ) ); buts.put( "Pull(S,N)", new GBC( 3, yoff + 5 ) ); buts.put( "Pull(N,E)", new GBC( 4, yoff + 1 ) ); buts.put( "Pull(E,N)", new GBC( 5, yoff + 2 ) ); buts.put( "Pull(E,W)", new GBC( 5, yoff + 3 ) ); buts.put( "Pull(E,S)", new GBC( 5, yoff + 4 ) ); buts.put( "Pull(S,E)", new GBC( 4, yoff + 5 ) ); fixed.add( new JLabel( "Pull" ), new GBC( 2, yoff + 3, 3 ) ); for ( Entry< String, GBC > e : buts.entrySet() ) { fixed.add( new CommandButton( transmitter, e.getKey(), "[" + Multify( e.getKey() ) + "]" ), e.getValue() ); } // Custom Panel GridBagConstraints c = new GridBagConstraints(); c.gridy++; custom.setLayout( new GridBagLayout() ); if ( customs.length == 0 ) customs = new String[] { "", "" }; for ( int i = 0; i < customs.length; i++ ) { JButton but = new JButton( "Command " + i ); final JTextField input = new JTextField( customs[i] ); but.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { buttonSend( transmitter, input.getText() ); } } ); c = new GridBagConstraints(); c.gridy = i; c.fill = GridBagConstraints.HORIZONTAL; custom.add( but, c ); c.weightx = 0.80; c.gridx = 1; custom.add( input, c ); } // Communication panel comm.setLayout( new GridBagLayout() ); comm.setMinimumSize(new Dimension(200, 250)); c = new GridBagConstraints(); c.ipadx = 5; comm.add( new JLabel( "Communication Done" ), c ); c.gridy = 1; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; comm.add( new JScrollPane( communication, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ), c ); // Information panel info.setLayout( new GridBagLayout() ); comm.setMinimumSize(new Dimension(200, 100)); c = new GridBagConstraints(); c.ipadx = 5; info.add( new JLabel( "Client Information (e.g. Exceptions)" ), c ); c.gridy = 1; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; info.add( new JScrollPane( information, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ), c ); // Add components to main frame setLayout( new GridBagLayout() ); c = new GridBagConstraints(); c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets( 3, 3, 3, 3 ); add( fixed, c ); c.gridy = 1; add( custom, c ); c.gridy = 2; c.weighty = 0.8; c.fill = GridBagConstraints.BOTH; add( comm, c ); c.gridy = 3; c.weighty = 0.2; add( info, c ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setMinimumSize( new Dimension( 525, 820 ) ); setLocation( 800, 120 ); receiver.start(); transmitter.start(); this.pack(); setVisible( true ); } public void AddCommunication( String m ) { // Append is thread safe.. communication.append( msgNo + ":\t" + m + nl ); synchronized ( this ) { communication.setCaretPosition( communication.getText().length() ); msgNo++; } } public void AddInformation( String m ) { // Append is thread safe.. information.append( m + nl ); synchronized ( this ) { information.setCaretPosition( information.getText().length() ); } } /** * Turns Cmd into Cmd,Cmd,Cmd (..) based on number of agents * * @param cmd * @return Multified cmd */ private String Multify( String cmd ) { String s = ""; for ( int i = 0; i < agents - 1; i++ ) { s += cmd + ","; } return s + cmd; } private void readMap() throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); agents = 0; String line; // Read lines specifying colors while ( ( line = in.readLine() ).matches( "^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$" ) ) { // Skip } // Read lines specifying level layout // By convention levels are ended with an empty newline while ( !line.equals( "" ) ) { for ( int i = 0; i < line.length(); i++ ) { char id = line.charAt( i ); if ( '0' <= id && id <= '9' ) agents++; } line = in.readLine(); if ( line == null ) break; } } public static void main( String[] args ) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); new GuiClient( args ); } catch ( Exception e ) { e.printStackTrace(); } } }
Java
package client; import java.util.Arrays; import java.util.Scanner; public class Output { private static Scanner scan = new Scanner(System.in); /*public Output() { scan = new Scanner(System.in); }*/ public static boolean[] Send(Command[] commands) { // System.err.println("Sending: [" + Arrays.toString(commands) + "]"); String sendString = Arrays.toString(commands); sendString = sendString.replaceAll("null", "NoOp"); System.out.println(sendString); System.out.flush(); String feedback = scan.nextLine(); // [false, false] String[] elements = feedback.substring(1, feedback.length()-1).split(", "); boolean[] result = new boolean[elements.length]; int i = 0; for (String s : elements) result[i++] = Boolean.parseBoolean(s); return result; } }
Java
package client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import constants.Constants.Color; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; public class Parser { // Flaws in current implementation: // - fields outside walls are created. A simple search could easily remove them, but they don't seem to be in the way, yet. public static Level readLevel() throws IOException { Level l = new Level(); //FileReader fR = new FileReader("src/levels/FOMAbispebjerg.lvl"); //BufferedReader in = new BufferedReader(fR); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Read lines specifying colors Map<Character,Color> colors = new HashMap<Character,Color>(); String line; Color color; while ((line = in.readLine()).matches("^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$")) { line = line.replaceAll("\\s", ""); color = Color.valueOf(line.split(":")[0]); for (String id : line.split(":")[1].split(",")) colors.put(id.charAt(0), color); } // Read level layout ArrayList<String> rawLevel = new ArrayList<String>(); while (!line.equals("")) { rawLevel.add(line); line = in.readLine(); } // Set size of field map int maxWidth = 0; for (int y=1; y<rawLevel.size()-1; y++) { if (rawLevel.get(y).length() > maxWidth) { maxWidth = rawLevel.get(y).length(); } } l.setFieldMap(new Field[maxWidth][rawLevel.size()]); // Read lines specifying level layout (skipping the border) for (int y=0; y<rawLevel.size(); y++) { for (int x=0; x<rawLevel.get(y).length(); x++) { char id = rawLevel.get(y).charAt(x); if ('+' == id) continue; // skip if wall Field f; if ('0' <= id && id <= '9') { f = new Field(x,y); Agent a = new Agent(id, colors.get(id), f); l.agents.add(a); f.setObject(a); } else if ('A' <= id && id <= 'Z') { f = new Field(x,y); Box b = new Box(id, colors.get(id), f); l.boxes.add(b); f.setObject(b); } else if ('a' <= id && id <= 'z') { f = new Goal(id,x,y); l.goals.add((Goal)f); } else { f = new Field(x,y); } l.fields.add(f); l.fieldMap[x][y] = f; // Field links if(x!=0 && l.fieldMap[x-1][y] != null){ if (rawLevel.get(y).charAt(x-1) != '+') LinkFieldsHorizontal(f, l.fieldMap[x-1][y]); // link left } if(y!=0 && l.fieldMap[x][y-1] != null){ if (rawLevel.get(y-1).charAt(x) != '+') LinkFieldsVertical(f, l.fieldMap[x][y-1]); // link up (negative y) } } } //THE AGENTS NEED TO BE SORTED Collections.sort(l.agents, new Comparator<Agent>() { @Override public int compare(Agent a1, Agent a2) { int a1Id = Integer.parseInt(""+a1.getId()); int a2Id = Integer.parseInt(""+a2.getId()); return a1Id-a2Id; } }); return l; } private static void LinkFieldsHorizontal(Field east, Field west) { east.neighbours[dir.W.ordinal()] = west; west.neighbours[dir.E.ordinal()] = east; } private static void LinkFieldsVertical(Field south, Field north) { south.neighbours[dir.N.ordinal()] = north; north.neighbours[dir.S.ordinal()] = south; } }
Java
package client.clients; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; import client.Command; import client.Output; import client.Parser; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; public class SmartRandomWalkClient { private static Random rand = new Random(); private Level level; public SmartRandomWalkClient() throws IOException { level = Parser.readLevel(); /*// prints level, badly System.err.println("level.field_map.length: "+level.field_map.length); //System.err.println("level.field_map[y].length: "+level.field_map[y].length); for (int y = 0; y < level.field_map.length; y++) { for (int x = 0; x < level.field_map[y].length; x++) { Field f = level.field_map[x][y]; if (f != null) { if (f instanceof Goal) { System.err.println(((Goal) f).getId() + " Coords: [" + f.x + ":" + f.y + "]"); } } } }*/ } private BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // move some of this to I/O class ! public boolean update() throws IOException { Command[] commands = new Command[level.agents.size()]; //Store the commands and complete them, if server gives true. for (int i = 0; i < level.agents.size(); i++) { commands[i] = level.agents.get(i).act(); } boolean[] result = Output.Send(commands); for (int i = 0; i < result.length; i++) { if(result[i]) completeCommand(commands[i], level.agents.get(i)); } return true; } private void completeCommand(Command c, Agent a){ if (c.cmd.equals("Move")) completeMove(c,a); else if (c.cmd.equals("Pull")) completePull(c, a, (Box) a.getAtField().neighbours[c.dir2.ordinal()].object); else if (c.cmd.equals("Push")) completePush(c, a, (Box) a.getAtField().neighbours[c.dir1.ordinal()].object); } private void completeMove(Command c, Agent a) { a.getAtField().object = null; a.getAtField().neighbours[c.dir1.ordinal()].object = a; a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); } private void completePull(Command c, Agent a, Box o) { // Box moves to Agents' previous field o.getAtField().setObject(null); o.setAtField(a.getAtField()); a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } private void completePush(Command c, Agent a, Box o) { //Agent moves to Box's previous field a.getAtField().setObject(null); a.setAtField(o.getAtField()); o.setAtField(o.getAtField().neighbours[c.dir2.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } public static void main( String[] args ) { try { SmartRandomWalkClient client = new SmartRandomWalkClient(); while ( client.update() ); } catch ( Exception e ) { e.printStackTrace(); } } }
Java
package client.clients; import java.io.IOException; import javax.swing.text.StyledEditorKit.BoldAction; import agent.objectives.DockABox; import agent.objectives.Objective; import constants.Constants; import constants.Constants.dir; import utils.Communication; import utils.Timer; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; import client.Command; import client.Output; import client.Parser; import client.planners.AStarPlanner; import client.planners.ClientPlanner; import client.planners.FOMAPrioritizedGoalPlanner; import client.planners.GoalCountPlanner; import client.planners.Planner; import client.planners.PrioritizedGoalPlanner; import client.planners.ProgressionPlanner; import client.planners.ProgressionPlannerWithGoalPriority; import client.planners.SimplePlanner; public class Client { private static Level level; private static Planner planner; private static boolean timer; public static int stepCount = 0; public static boolean[] agentsFailed; public Client(String plannerName) throws IOException { level = Parser.readLevel(); planner = getPlanner(plannerName, level); } public static void main(String[] args) { try { String plannerName = "simple"; // DEFAULT timer = true; if (args.length==1) plannerName = args[0]; else if (args.length==2 && args[1].toLowerCase().equals("notimer")) timer = false; Timer t1 = new Timer(); t1.takeTime(); Client client = new Client(plannerName); agentsFailed = new boolean[level.agents.size()]; t1.stop(); // System.err.println("Level parsed. Time taken: " + t1.toString()); System.err.println( "Hello from " + planner.getName()); while (client.update()) ; } catch (Exception e) { e.printStackTrace(); } } private static Planner getPlanner(String name, Level l) { //TODO: consider reflection if (name.toLowerCase().contains("compet")) { // if (l.agents.size()==1) // return new ProgressionPlanner(l); // else return new ClientPlanner(l); } else if (name.toLowerCase().contains("star")) { return new AStarPlanner(l); } else if (name.toLowerCase().contains("goal") && name.toLowerCase().contains("count")) { return new GoalCountPlanner(l); } else if (name.toLowerCase().contains("withgoalpriority")) { return new ProgressionPlannerWithGoalPriority(l); } else if (name.toLowerCase().contains("goal") && name.toLowerCase().contains("priori") && name.toLowerCase().contains("foma")) { return new FOMAPrioritizedGoalPlanner(l); } else if (name.toLowerCase().contains("client")) { return new ClientPlanner(l); } else if (name.toLowerCase().contains("goal") && name.toLowerCase().contains("priori")) { return new PrioritizedGoalPlanner(l); } else if (name.toLowerCase().contains("progr")) { return new ProgressionPlanner(l); } else if (name.toLowerCase().contains("simple")) { return new SimplePlanner(l); } return new SimplePlanner(l); } public boolean update() throws IOException { Command[] commands = new Command[level.agents.size()]; // Get commands from agents' commandQueue loadCommands(commands); // Check if all agents have no commands left. If true, plan new commands. boolean noOps = true; for (int i = 0; i < commands.length; i++) { if (commands[i] != null) noOps = false; } if (noOps) { // System.err.println("No ops !"); Timer t = new Timer(); planner.makePlan(); t.stop(); // System.err.println("Plan calculated. Time taken: " + t.toString()); loadCommands(commands); } // Send commands to server, receive results boolean[] result = Output.Send(commands); // Let all commands accepted by the server update the level state boolean failed = false; boolean conflictFound = false; Agent conflictingAgent = null; for (int i = 0; i < result.length; i++) { if(conflictingAgent != null){ if(conflictingAgent.getId() == level.agents.get(i).getId()){ //if the other agent wins, do what he says.. Agent a = level.agents.get(i); Command c = commands[i]; flushAgentCommands(level.agents.get(i), c); } } if (result[i]){ completeCommand(commands[i], level.agents.get(i)); } else { System.err.println("Conflict!!!!! " + i); Agent a = level.agents.get(i); Command c = commands[i]; //if (c.cmd.toLowerCase().equals("move")) if (c.cmd.toLowerCase().equals("move") || c.cmd.toLowerCase().equals("pull"))// agent moves { Object o = a.getAtField().neighbours[c.dir1.ordinal()].object; if (o == null) { Field agents_desired_field = a.getAtField().neighbours[c.dir1.ordinal()]; if(!Utils.CheckIfAnAgentWasOnThisFieldLastTurn(level, agents_desired_field)) removeField(agents_desired_field); } else if(o instanceof Box) { //A box is in the way. find which box Box otherBox = (Box)o; if(otherBox.getColor() == a.getColor()){ Objective newObjective = new DockABox(new Field(3, 6), otherBox, 15); a.objectives.addFirst(newObjective); } //Find an agent to move the box conflictingAgent = Communication.FindAgentToMoveBox(otherBox, level); a.obstacle = o; } else if(o instanceof Agent){ a.obstacle = o; } } else { //We are pushing and should look at the next field.. Object o = a.getAtField().neighbours[c.dir1.ordinal()].neighbours[c.dir1.ordinal()].object; if (o == null) { Field agents_desired_field = a.getAtField().neighbours[c.dir2.ordinal()]; if(!Utils.CheckIfAnAgentWasOnThisFieldLastTurn(level, agents_desired_field)) removeField(agents_desired_field); } else if(o instanceof Agent || o instanceof Box) { a.obstacle = o; } } flushAgentCommands(level.agents.get(i), c); //TODO: if there is no box or agent on the desired place it is a hidden obstacle -> remove it from graph updateBeliefs(commands[i], level.agents.get(i)); failed = true; } } agentsFailed = result; stepCount++; return true; } /** * Removes a field from the graph * @param field the field to be dereferenced. */ private void removeField(Field field) { for (dir direction : dir.values()) { Field neighbour = field.neighbours[direction.ordinal()]; neighbour.neighbours[Constants.oppositeDir(direction).ordinal()] = null; } } /** * Restores the agents objective from last iteration and the command queue from the error * @param agent * @param failedCommand The command on which the program failed */ private void flushAgentCommands(Agent agent, Command failedCommand) { agent.commandsNotCompleted.add(Constants.NOOP); agent.commandsNotCompleted.add(Constants.NOOP); agent.commandsNotCompleted.add(failedCommand); Command c; while ((c = agent.commandQueue.poll()) != null) agent.commandsNotCompleted.add(c); agent.objectives.addFirst(agent.tempObjective); agent.tempObjective = null; } private static void loadCommands(Command[] commands) { for (int i = 0; i < level.agents.size(); i++) { level.agents.get(i).lastLocation = level.agents.get(i).getAtField(); commands[i] = level.agents.get(i).commandQueue.poll(); } } private static void updateBeliefs(Command c, Agent a) { // TODO } // updates level by completing an agent command private static void completeCommand(Command c, Agent a) { if (c != null) { if (c.cmd.equals("Move")) completeMove(c, a); else if (c.cmd.equals("Pull")) completePull(c,a, (Box) a.getAtField().neighbours[c.dir2.ordinal()].object); else if (c.cmd.equals("Push")) completePush(c,a, (Box) a.getAtField().neighbours[c.dir1.ordinal()].object); } } private static void completeMove(Command c, Agent a) { a.getAtField().object = null; a.getAtField().neighbours[c.dir1.ordinal()].object = a; a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); } private static void completePull(Command c, Agent a, Box o) { // Box moves to Agents' previous field o.getAtField().setObject(null); o.setAtField(a.getAtField()); a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } private static void completePush(Command c, Agent a, Box o) { // Agent moves to Box's previous field a.getAtField().setObject(null); a.setAtField(o.getAtField()); o.setAtField(o.getAtField().neighbours[c.dir2.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } }
Java
package client.clients; import java.io.*; import java.util.*; import client.Command; public class RandomWalkClient { private static Random rand = new Random(); public class Agent { // We don't actually use these for Randomly Walking Around private char id; private String color; Agent( char id, String color ) { this.id = id; this.color = color; } public String act() { return Command.every[rand.nextInt( Command.every.length )].toString(); } } private BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); private List< Agent > agents = new ArrayList< Agent >(); public RandomWalkClient() throws IOException { readMap(); } private void readMap() throws IOException { Map< Character, String > colors = new HashMap< Character, String >(); String line, color; // Read lines specifying colors while ( ( line = in.readLine() ).matches( "^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$" ) ) { line = line.replaceAll( "\\s", "" ); color = line.split( ":" )[0]; for ( String id : line.split( ":" )[1].split( "," ) ) colors.put( id.charAt( 0 ), color ); } // Read lines specifying level layout while ( !line.equals( "" ) ) { for ( int i = 0; i < line.length(); i++ ) { char id = line.charAt( i ); if ( '0' <= id && id <= '9' ) agents.add( new Agent( id, colors.get( id ) ) ); } line = in.readLine(); } } public boolean update() throws IOException { String jointAction = "["; for ( int i = 0; i < agents.size() - 1; i++ ) jointAction += agents.get( i ).act() + ","; System.out.println( jointAction + agents.get( agents.size() - 1 ).act() + "]" ); System.out.flush(); // Disregard these for now, but read or the server stalls when outputbuffer gets filled! String percepts = in.readLine(); if ( percepts == null ) return false; return true; } public static void main( String[] args ) { // Use stderr to print to console System.err.println( "Hello from RandomWalkClient. I am sending this using the error outputstream" ); try { RandomWalkClient client = new RandomWalkClient(); while ( client.update() ) ; } catch ( IOException e ) { // Got nowhere to write to probably } } }
Java
package datastructures; import java.util.ArrayList; import java.util.Collection; import java.util.List; import client.Command; import LevelObjects.Box; import LevelObjects.Field; public class MoveActionSequence extends ActionSequence { private Field startField; private Field endField; public List<Box> boxesInTheWay; public MoveActionSequence(Field from, Field to, ArrayList<Command> commands) { startField = from; endField = to; super.commands = commands; } public Field getStartField() { return startField; } public void setStartField(Field startField) { this.startField = startField; } public Field getEndField() { return endField; } public void setEndField(Field endField) { this.endField = endField; } }
Java
package datastructures; import LevelObjects.Field; public class MoveBoxActionSequence extends ActionSequence { private Field agentLocation; private Field boxLocation; private Field targetLocation; public Field getAgentLocation() { return agentLocation; } public void setAgentLocation(Field agentLocation) { this.agentLocation = agentLocation; } public Field getBoxLocation() { return boxLocation; } public void setBoxLocation(Field boxLocation) { this.boxLocation = boxLocation; } public Field getTargetLocation() { return targetLocation; } public void setTargetLocation(Field targetLocation) { this.targetLocation = targetLocation; } }
Java
package datastructures; import LevelObjects.Field; public class GoalActionSequence extends ActionSequence { private Field agentStartLocation; private Field agentEndField; private Field boxStartLocation; private Field boxEndLocation; public Field getBoxStartLocation() { return boxStartLocation; } public void setBoxStartLocation(Field boxStartLocation) { this.boxStartLocation = boxStartLocation; } public Field getBoxEndLocation() { return boxEndLocation; } public void setBoxEndLocation(Field boxEndLocation) { this.boxEndLocation = boxEndLocation; } public Field getAgentEndField() { return agentEndField; } public void setAgentEndField(Field agentEndField) { this.agentEndField = agentEndField; } public Field getAgentStartLocation() { return agentStartLocation; } public void setAgentStartLocation(Field agentStartLocation) { this.agentStartLocation = agentStartLocation; } }
Java
package datastructures; public class FieldBlockedChange { public int time; public boolean changeToBlocked; public FieldBlockedChange(int time, boolean c){ this.time = time; this.changeToBlocked = c; } }
Java
package datastructures; import java.util.ArrayList; import LevelObjects.Agent; import LevelObjects.Field; public class FieldInState extends ObjectInState { public ArrayList<FieldBlockedChange> blockedTimeChangeIndexes; public FieldInState(Field f) { super(); this.f = f; blockedTimeChangeIndexes = new ArrayList<FieldBlockedChange>(); } public FieldInState(Field f, ArrayList<FieldBlockedChange> blockedTimeIndexes) { super(); this.f = f; this.blockedTimeChangeIndexes = blockedTimeIndexes; } public boolean changesStatusInFuture(int timeStep){ for (FieldBlockedChange blockedTime : blockedTimeChangeIndexes) { if (blockedTime.time >= timeStep && blockedTime.changeToBlocked == true) { return true; } } return false; } public boolean freeInInterval(int start, int end){ // System.err.println("Checking " + this.f.toString() + " intervals: " + start + "-" +end); // for (FieldBlockedChange fb : blockedTimeChangeIndexes) { // System.err.print(fb.time+ " "); // } boolean previous = false; for (FieldBlockedChange blockedTime : blockedTimeChangeIndexes) { if (blockedTime.time > start && blockedTime.time <= end) { // System.err.println("HEEER"); return false; } previous = blockedTime.changeToBlocked; if(blockedTime.time > end){ return !previous; } } return !previous; } }
Java
package datastructures; import java.util.ArrayList; import LevelObjects.Field; import client.Command; public abstract class ActionSequence { private ActionSequence parent; public ArrayList<Field> fields; public ActionSequence getParent() { return parent; } public void setParent(ActionSequence parent) { this.parent = parent; } protected ArrayList<Command> commands; public ArrayList<Command> getCommands() { return commands; } public void setCommands(ArrayList<Command> commands) { this.commands = commands; } }
Java
package datastructures; import LevelObjects.Agent; import LevelObjects.Field; public class AgentInState extends ObjectInState { public Agent a; public AgentInState(Agent a, Field f) { super(); this.a = a; this.f = f; } }
Java
package datastructures; import java.util.ArrayList; import LevelObjects.Goal; import client.Command; public class State implements Comparable<State> { public int g; public int f; public ArrayList<AgentInState> agents; public ArrayList<BoxInState> boxes; public ArrayList<FieldInState> fields; public State parent; public ArrayList<Command> commandFromParent; public int heuristicValue; public StateGoal goal; //Used for merging states. We know which step we are in, and all commands from this step should be used for merging. public int indexOfCommands; //Should be FOMA compatible public ArrayList<ActionSequence> actionSequencesFromParent; public State() { agents = new ArrayList<AgentInState>(); boxes = new ArrayList<BoxInState>(); fields = new ArrayList<FieldInState>(); commandFromParent = new ArrayList<Command>(); actionSequencesFromParent = new ArrayList<ActionSequence>(); } @Override public int compareTo(State o) { return this.heuristicValue - o.heuristicValue; } public void printFieldChanges(){ for (FieldInState f : fields) { System.err.print(f.f.toString()); for (FieldBlockedChange fb : f.blockedTimeChangeIndexes) { System.err.print(" " + fb.time + " " + fb.changeToBlocked); } System.err.println(); } } }
Java
package datastructures; import LevelObjects.Box; import LevelObjects.Field; public class BoxInState extends ObjectInState { public Box b; public BoxInState(Box b, Field f) { super(); this.b = b; this.f = f; } }
Java
package datastructures; import LevelObjects.Field; public abstract class ObjectInState implements Comparable<ObjectInState> { public Field f; @Override public int compareTo(ObjectInState o) { if (this.f.x != o.f.y) { return this.f.x-o.f.x; } else{ return this.f.y-o.f.y; } } }
Java
package datastructures; import java.util.ArrayList; import LevelObjects.*; public class BoxCost { public Box box; public int cost; public ArrayList<GoalCost> goalCosts; public BoxCost() { goalCosts = new ArrayList<GoalCost>(); } }
Java
package datastructures; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; public class StateGoal { public Field agentToPos; public Field boxToPos; public BoxInState box; public AgentInState agent; public boolean isMoveToBoxGoal; public boolean isClearPathGoal; public int nextGoalIndex; }
Java
package datastructures; import LevelObjects.Field; import client.Command; public class GoalSequenceNode implements Comparable<GoalSequenceNode> { public GoalSequenceNode parent; public Field boxLocation; public Field agentLocation; public Command action; public int timeStep; public int f; public int g; public GoalSequenceNode(Field boxLocation, Field agentLocation, Command action) { super(); this.boxLocation = boxLocation; this.agentLocation = agentLocation; this.action = action; } @Override public int compareTo(GoalSequenceNode arg0) { return this.f - arg0.f; } }
Java
package datastructures; import LevelObjects.*; public class GoalCost { public GoalCost(Goal goal, int cost) { this.cost = cost; this.goal = goal; } public Goal goal; public int cost; }
Java
package utils; public class Timer { private long _time; public volatile long time; public Timer() { time = 0; _time = System.currentTimeMillis(); } public void takeTime() { time = 0; _time = System.currentTimeMillis(); } public long stop() { time = System.currentTimeMillis() - _time; return time; } public int getElapsedTime() { return (int)(System.currentTimeMillis() - _time); } public void reset() { _time = System.currentTimeMillis(); time = 0; } public String toString() { int elapsed = getElapsedTime(); if (elapsed < 1000) return Integer.toString(elapsed) + " miliseconds"; else if (elapsed < 60000) { int seconds = elapsed/1000; int milis = (int)(elapsed % ((int)(elapsed/1000)*1000)); return Integer.toString(seconds) + "." + Integer.toString(milis) + " seconds"; } else { int minutes = elapsed/60000; int seconds = (int)((((double)elapsed)/60000.0f) % (int)(elapsed/60000)); return Integer.toString(minutes) + " minutes " + Integer.toString(seconds) + " seconds"; } } }
Java
package utils; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import LevelObjects.Field; public class BFS { public enum NodeColour { WHITE, GRAY, BLACK } private static class Node { int data; int distance; Node parent; NodeColour colour; Field field; public Node(int data) { this.data = data; } public String toString() { return "(" + data + ",d=" + distance + ")"; } } Map<Node, List<Node>> nodes; private BFS() { nodes = new HashMap<Node, List<Node>>(); } public static int bfs(Field start_field, Field end_field) { ArrayList<String> fieldList = new ArrayList<String>(); Node start = new Node(0); start.distance = 0; start.parent = null; start.field = start_field; fieldList.add(start.field.toString()); Queue<Node> q = new ArrayDeque<Node>(); q.add(start); while (!q.isEmpty()) { Node u = q.remove(); List<Node> adjacent_u = new ArrayList<Node>(); adjacent_u = getNeighbours(u, fieldList); if (adjacent_u != null) { for (Node v : adjacent_u) { if(v.field.x == end_field.x && v.field.y == end_field.y){ return u.distance + 1; } v.distance = u.distance + 1; v.parent = u; q.add(v); // System.err.println("Field " + v.field + " added to path"); fieldList.add(v.field.toString()); } } } return -1; } public static int bfs(Field start_field, Field end_field, Field blocked_field) { ArrayList<String> fieldList = new ArrayList<String>(); Node start = new Node(0); Node blocked = new Node(0); start.distance = 0; start.parent = null; start.field = start_field; blocked.field = blocked_field; fieldList.add(start.field.toString()); fieldList.add(blocked.field.toString()); Queue<Node> q = new ArrayDeque<Node>(); q.add(start); while (!q.isEmpty()) { Node u = q.remove(); List<Node> adjacent_u = new ArrayList<Node>(); adjacent_u = getNeighbours(u, fieldList); if (adjacent_u != null) { for (Node v : adjacent_u) { if(v.field.x == end_field.x && v.field.y == end_field.y){ return u.distance + 1; } v.distance = u.distance + 1; v.parent = u; q.add(v); // System.err.println("Path found. Field " + v.field + " added to path"); fieldList.add(v.field.toString()); } } } return -1; } private static List<Node> getNeighbours(Node u, ArrayList<String> fieldList){ List<Node> adjacent_u = new ArrayList<Node>(); Node n = null; for (int i = 0; i < 4; i++) { if(u.field.neighbours[i] != null){ Field f = u.field.neighbours[i]; if(!fieldList.contains(f.toString())){ n = new Node(i); n.field = u.field.neighbours[i]; adjacent_u.add(n); } } } return adjacent_u; } }
Java
package utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; public class GoalPriority { /** * Goal prioritization. Checks to see for every goal, how many boxes and goals are disconnected, by placing this goal. * This function can be used at any time. * @param level * @param ignore_goals_completed, if you want to ignore completed goals. * @return a Goal array with the prioritized number in goal.getPriority() */ public static ArrayList<Goal> createGoalPrioritization(Level level, boolean ignore_goals_completed){ // tester(level); Timer t1 = new Timer(); t1.takeTime(); for (Goal goal : level.goals) { //ignore completed goals.. boolean ignore_goal = false; //only enter if completed goals should be ignored if(ignore_goals_completed){ ignore_goal = checkToSeeIfGoalIsOnBox(goal, level); } Timer t2 = new Timer(); t2.takeTime(); if(!(ignore_goal && ignore_goals_completed)){ //first look at fields north and south || east and west are walls or other blocking elements? goals? goals later //If so level has been disconnected //look and see if the disconnect is a problem. int count_free_neighbours = countAdjacentFields(goal); // System.err.println("Goal " + goal.getId() + " has adjacent free fields: " + count_free_neighbours); if(count_free_neighbours == 1){ //Goal only has one Neighbour and should have a low value in goal priority //Know further tests. This is highest priority! } else { List<Field> free_neighbours = getFreeNeighbours(goal); int disconnected_goals = 0; switch(count_free_neighbours){ case 2: goal.setPriority(goal.getPriority() + 1); //Goal only has two Neighbours and has a high posibility of breaking the map into to areas when box on goal //See if path it is possible to get from one neighbour to the other disconnected_goals = getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(1).getClone(), level, goal); goal.setPriority(goal.getPriority() + disconnected_goals); break; case 3: goal.setPriority(goal.getPriority() + 2); //See if path it is possible to get from one neighbour to the other. There are now 3 neighbours. 0,1,2 disconnected_goals = getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(1).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(2).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(2).getClone(), level, goal); goal.setPriority(goal.getPriority() + disconnected_goals); break; case 4: goal.setPriority(goal.getPriority() + 3); //See if path it is possible to get from one neighbour to the other. There are now 4 neighbours. 0,1,2,3 disconnected_goals = getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(1).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(2).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(3).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(0).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(2).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(3).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(2).getClone(), free_neighbours.get(0).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(2).getClone(), free_neighbours.get(1).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(2).getClone(), free_neighbours.get(3).getClone(), level, goal); goal.setPriority(goal.getPriority() + disconnected_goals); break; } } } t2.stop(); // System.err.println("Goal " + goal.getId() +" prioritized.. Time taken: " + t2.toString()); } t1.stop(); // System.err.println("Goals prioritized. Time taken: " + t1.toString()); return level.goals; } private static void tester(Level level){ System.err.println("----------TESTER-----------"); Agent agent = level.agents.get(0); System.err.println("----------testing distance-----------"); for (Goal goal : level.goals) { System.err.println("Agent " + agent.getId() + " is " + BFS.bfs(agent.getAtField(), goal.getClone()) + " from goal " + goal.getId()); } System.err.println("----------TESTER-----------"); Field f = new Field(6,3); for (Goal goal : level.goals) { System.err.println("Agent " + agent.getId() + " at " + agent.getAtField() + " is " + BFS.bfs(agent.getAtField(), goal.getClone(), f) + " from goal " + goal.getId() + " at " + goal.getClone() + ". Field " + f + " is blocked"); } System.err.println("---------------------"); } private static int countGoalDisconnectedFromBox(List<Box> boxes, List<Goal> goals, Goal current_goal){ int goals_disconnecting = 0; boolean box_found = false; for (Goal goal : goals) { if(goal != current_goal){ box_found = false; for (Box box : boxes) { if(box.getId() == goal.getId()){ if(BFS.bfs(box.getAtField(), goal.getClone(), current_goal.getClone()) != -1){ box_found = true; } } } if(!box_found){ goals_disconnecting++; } } } return goals_disconnecting; } private static Goal isAgentDisconnectedFromGoal(Agent agent, List<Goal> goals, Goal current_goal){ for (Goal goal : goals) { if(goal != current_goal){ if(BFS.bfs(agent.getAtField(), goal.getClone(), current_goal.getClone()) == -1){ return goal; } } } return null; } private static List<Field> getFreeNeighbours(Goal goal){ List<Field> free_neighbours = new ArrayList<Field>(); for (int i = 0; i < 4; i++) { if(goal.neighbours[i] != null) free_neighbours.add(goal.neighbours[i]); } return free_neighbours; } private static int countAdjacentFields(Goal goal){ int counter = 0; for (int i = 0; i < 4; i++) { if(goal.neighbours[i] != null) counter++; } return counter; } private static boolean checkToSeeIfGoalIsOnBox(Goal goal, Level level){ boolean ignoreGoal =false; for (Box box : level.boxes) { if(goal.getId() == box.getId()){ if(goal.x == box.getAtField().x && goal.y == box.getAtField().y){ ignoreGoal = true; } } } return ignoreGoal; } private static int getDisconnectedGoalsFromBoxes(Field free_neighbours1, Field free_neighbours2, Level level, Goal goal){ int disconnected_goals = 0; //See if the two neighbours 1 and 2 are disconnected with the middle field blocked. if(BFS.bfs(free_neighbours1, free_neighbours2, goal.getClone()) == -1){ //Okay, there is a disconnect.Now count goals disconnected from boxes with the same id. disconnected_goals = countGoalDisconnectedFromBox(level.boxes, level.goals, goal); goal.setPriority(goal.getPriority() + disconnected_goals); } return disconnected_goals; } /** * Finds the goal with the highest priority for the given agent * @param agent: we want to find best goal for * @param level: containing level.goals to search through * @returns Goal goal with the highest priority */ public static Goal FindGoalWithHighestPriority(Agent agent, Box box, Level level) { char id = box.getId(); Goal candidate = null; for (Goal goal : level.goals) { if(goal.getId() == id){ if(candidate != null){ if(candidate.getPriority() > goal.getPriority()) candidate = goal; } else{ candidate = goal; } } } return candidate; } }
Java
package utils; import constants.Constants.dir; import LevelObjects.Field; import client.Command; public class AStarField implements Comparable<AStarField> { public Field field; public int g; public int f; public int h; public Command c; public int timeStep; public AStarField(Field field) { this.field = field; } @Override public int compareTo(AStarField o) { return this.f - o.f; } public Field neighborTo(dir d) { return field.neighbours[d.ordinal()]; } }
Java
package utils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import constants.Constants; import constants.Constants.Color; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxCost; import datastructures.BoxInState; import datastructures.GoalActionSequence; import datastructures.GoalCost; import datastructures.GoalSequenceNode; import datastructures.MoveActionSequence; import datastructures.MoveBoxActionSequence; import datastructures.State; import datastructures.StateGoal; public class Utils { /** * * @param f The field * @param d The direction * @return true if the neighboring field in the direction is free */ public static boolean isNeighborFree(Field f, dir d){ return (f.neighbours[d.ordinal()] != null && f.neighbours[d.ordinal()].object == null); } /** * * @param l The level * @param from The field to travel from * @param to The field to travel to * @param blockedFields A list of fields inaccessible to the agent * @return a list of commands taking the agent from the from-field to the to-field */ public static MoveActionSequence findRoute(Level l, Field from, Field to, Collection<Field> blockedFields) { HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); AStarField curField = openSet.poll(); while (curField != null) { if (curField.field.equals(to)) break; closedSet.add(curField.field); int tentativeGScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if(blockedFields != null){ if ( neighbor == null || blockedFields.contains(neighbor) || closedSet.contains(neighbor)) continue; } else{ if ( neighbor == null || closedSet.contains(neighbor)) continue; } AStarField neighbourInOpenSet = null; for (AStarField aOpen : openSet) { if (aOpen.field == neighbor) neighbourInOpenSet = aOpen; } if (neighbourInOpenSet != null && tentativeGScore > neighbourInOpenSet.g) { continue; } else if (neighbourInOpenSet == null ){ neighbourInOpenSet = new AStarField(curField.neighborTo(d)); neighbourInOpenSet.g = tentativeGScore; neighbourInOpenSet.f = neighbourInOpenSet.g + heuristicEstimate(neighbourInOpenSet.field, to, HeuristicType.MANHATTAN); neighbourInOpenSet.c = new Command(d); cameFrom.put(neighbourInOpenSet, curField); openSet.add(neighbourInOpenSet); } } curField = openSet.poll(); } //If currentField is null, we didn't find a path. if (curField == null) return null; ArrayList<Command> commands = new ArrayList<Command>(); ArrayList<Field> fields = new ArrayList<Field>(); while (cameFrom.get(curField) != null) { fields.add(curField.field); commands.add(curField.c); curField = cameFrom.get(curField); } Collections.reverse(commands); Collections.reverse(fields); MoveActionSequence mas = new MoveActionSequence(from, to, commands); mas.fields = fields; return mas; } /** * * @param l The level * @param from The field to travel from * @param to The field to travel to * @param blockedFields A list of fields inaccessible to the agent * @return a list of commands taking the agent from the from-field to the to-field */ public static MoveActionSequence findRouteIgnoreObstacles(Level l, Agent agent, Field from, Field to, Collection<Field> blockedFields) { HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); HashSet<Field> ownBoxFields = new HashSet<Field>(); HashSet<Field> othersBoxFields = new HashSet<Field>(); for (Box b : l.boxes) { if (agent.getColor().equals(b.getColor())) ownBoxFields.add(b.getAtField()); else othersBoxFields.add(b.getAtField()); } PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); AStarField curField = openSet.poll(); while (curField != null) { if (curField.field.equals(to)) break; closedSet.add(curField.field); int tentativeGScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if ( neighbor == null || (blockedFields != null && blockedFields.contains(neighbor)) || closedSet.contains(neighbor)) continue; AStarField neighbourInOpenSet = null; for (AStarField aOpen : openSet) { if (aOpen.field == neighbor) neighbourInOpenSet = aOpen; } if (neighbourInOpenSet != null) continue; neighbourInOpenSet = new AStarField(curField.neighborTo(d)); neighbourInOpenSet.g = tentativeGScore; if (ownBoxFields.contains(curField.field)) neighbourInOpenSet.g = tentativeGScore+50; else if (othersBoxFields.contains(curField.field)) neighbourInOpenSet.g = tentativeGScore+200; neighbourInOpenSet.f = neighbourInOpenSet.g + heuristicEstimate(neighbourInOpenSet.field, to, HeuristicType.MANHATTAN); neighbourInOpenSet.c = new Command(d); cameFrom.put(neighbourInOpenSet, curField); openSet.add(neighbourInOpenSet); } curField = openSet.poll(); } //If currentField is null, we didn't find a path. if (curField == null) return null; ArrayList<Command> commands = new ArrayList<Command>(); ArrayList<Field> fields = new ArrayList<Field>(); while (cameFrom.get(curField) != null) { fields.add(curField.field); commands.add(curField.c); //if (ownBoxFields.contains(curField.f)) curField = cameFrom.get(curField); } Collections.reverse(commands); Collections.reverse(fields); MoveActionSequence mas = new MoveActionSequence(from, to, commands); mas.fields = fields; return mas; } /** * * @param l The level * @param from The field to start from * @param to The field to get to * @return */ public static MoveActionSequence findRoute(Level l, Field from, Field to) { return findRoute(l, from, to, null); } public enum HeuristicType { EUCLID, MANHATTAN } public static int heuristicEstimate(Field a, Field goal, HeuristicType h) { switch (h) { case EUCLID: return heuristicEstimateEuclid(a, goal); case MANHATTAN: return heuristicEstimateManhattan(a, goal); default: return heuristicEstimateManhattan(a, goal); } } public static int heuristicEstimateEuclid(Field a, Field goal) { int h = (int) Math.sqrt(Math.pow(Math.abs(a.x - goal.x), 2) + Math.pow(Math.abs(a.y - goal.y), 2)); return h; } // Manhattan distance public static int heuristicEstimateManhattan(Field a, Field goal) { return Math.abs(a.x - goal.x) + Math.abs(a.y - goal.y); } public static boolean allGoalsHasBoxes(State currentState, Level level) { boolean[] goalFulfilled = new boolean[level.goals.size()]; int index = 0; for (Goal g : level.goals) { for (BoxInState bPos : currentState.boxes) { if (bPos.f == g && Character.toLowerCase(bPos.b.getId()) == g.getId()) { goalFulfilled[index] = true; } } index++; } boolean returnBool = true; for (boolean b : goalFulfilled) { if (!b) return false; } return returnBool; } public static boolean allGoalsHasBoxes(Level level) { int goalsFulfilled = 0; int totalGoals = level.goals.size(); for (Goal goal : level.goals) { for (Box box : level.boxes) { if (box.getAtField() == new Field(goal.x,goal.y) && Character.toLowerCase(box.getId()) == goal.getId()) { goalsFulfilled++; } } } if(goalsFulfilled == totalGoals) return true; else return false; } /** * checks if all goals has been fulfilled for the given agent * @param agent * @param level * @returns null if all goals are fulfilled, otherwise the goal with the highest priority */ public static Goal allOfAgentGoalsHasBoxes(Agent agent, Level level) { // Box current_box_color = a.possibleBoxesToGoals.keySet() int goalsFulfilled = 0; int totalBoxes = 0; Goal highestPriority = null; for (Goal goal : level.goals) { for (Box box : level.boxes) { if (agent.possibleBoxesToGoals.containsKey(box) && Utils.boxFitsGoal(box, goal)){ totalBoxes++; if (box.getAtField() == new Field(goal.x,goal.y) && Character.toLowerCase(box.getId()) == goal.getId()) { goalsFulfilled++; } else { if(highestPriority != null){ if(highestPriority.getPriority() > goal.getPriority()) highestPriority = goal; } else{ highestPriority = goal; } } } } } if(goalsFulfilled <= totalBoxes) return null; return highestPriority; } public static MoveBoxActionSequence findEmptyFieldRoute(Level l, Agent a, Box b, Field freeField, Field agentFromField, Field agentToField, Field boxFromField, Collection<Field> blockedFields) { GoalActionSequence ga = findGoalRoute(l, a, b, agentFromField, agentToField, boxFromField, freeField, blockedFields); if (ga == null) return null; MoveBoxActionSequence mb = new MoveBoxActionSequence(); mb.setAgentLocation(ga.getAgentStartLocation()); mb.setBoxLocation(ga.getBoxStartLocation()); mb.setCommands(ga.getCommands()); mb.setTargetLocation(ga.getBoxEndLocation()); return mb; } public static Field getFreeField(Level l, Agent a, Box b, Field agentFromField, Field boxFromField, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); Field current = boxFromField; Field candidate = current; int depth = 0; while (current != null && depth <= maxDepth) { candidate = current; closedSet.add(current); for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if ( neighbor != null && !blockedFields.contains(neighbor) && !closedSet.contains(neighbor) && (neighbor instanceof Goal && includeGoalFields)) openSet.add(neighbor); } current = openSet.poll(); } return candidate; } public static List<Field> getFreeFields(Field boxFromField, Collection<Field> blockedFields, int maxDepth, int maxReturnedFields, boolean includeGoalFields) { List<Field> l = getFreeFields(boxFromField, blockedFields, maxDepth, includeGoalFields); if (l.size()>maxReturnedFields) return l.subList(0, maxReturnedFields-1); return l; } public static ArrayList<Field> getFreeFields(Field boxFromField, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); Field current = boxFromField; ArrayList<Field> candidates = new ArrayList<Field>(); candidates.add(current); int depth = 0; while (current != null && depth <= maxDepth) { closedSet.add(current); int count = 0; for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if ( neighbor != null && !blockedFields.contains(neighbor) && !closedSet.contains(neighbor) && (neighbor instanceof Goal && includeGoalFields)) { count++; openSet.add(neighbor); } } if (count==0) // a dead end is good! candidates.add(current); current = openSet.poll(); } return candidates; } public static Field getFirstFreeField(Field fromField, Collection<Field> escapeFromFields, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); if (!escapeFromFields.contains(fromField)) escapeFromFields.add(fromField); Field current = fromField; int depth = 0; whileloop: while (current != null && depth <= maxDepth) { closedSet.add(current); for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if (neighbor == null) continue; if (!escapeFromFields.contains(neighbor)) { current = neighbor; break whileloop; } if ( escapeFromFields.contains(neighbor) && !closedSet.contains(neighbor) && !blockedFields.contains(neighbor) && (!(neighbor instanceof Goal) || includeGoalFields)) { openSet.add(neighbor); } } current = openSet.poll(); } return current; } public static Field getFirstFreeFieldkcl(Field fromField, Collection<Field> escapeFromFields, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); if (!escapeFromFields.contains(fromField)) escapeFromFields.add(fromField); Field current = fromField; int depth = 0; whileloop: while (current != null && depth <= maxDepth) { closedSet.add(current); for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if (neighbor == null) continue; if (!escapeFromFields.contains(neighbor)) { current = neighbor; break whileloop; } if ( escapeFromFields.contains(neighbor) && !closedSet.contains(neighbor) && !blockedFields.contains(neighbor) && (!(neighbor instanceof Goal) || includeGoalFields)) { openSet.add(neighbor); } } current = openSet.poll(); } return current; } // We know that the agent a has a box. Now we want to move the box to the // goal. public static GoalActionSequence findGoalRoute(Level l, Agent a, Box b, Field agentFromField, Field agentToField, Field boxFromField, Field boxToField, Collection<Field> blockedFields) { dir boxDir = null; GoalSequenceNode root = new GoalSequenceNode(boxFromField, agentFromField, null); PriorityQueue<GoalSequenceNode> queue = new PriorityQueue<GoalSequenceNode>(); // prune looped states (if agent and box ends up in a state already explored) HashMap<Field, ArrayList<Field>> closedSet = new HashMap<Field, ArrayList<Field>>(); //adding initial state to list set of explored states: ArrayList<Field> tempList = new ArrayList<Field>(); tempList.add(boxFromField); closedSet.put(agentFromField, tempList); int g = 0; root.g = g; root.f = root.g + heuristicEstimateManhattan(boxFromField, boxToField); //Add a closed set. queue.add(root); GoalSequenceNode currentNode = queue.poll(); while (currentNode != null && (currentNode.boxLocation != boxToField || currentNode.agentLocation != agentToField)) { boxDir = Agent.getBoxDirection(currentNode.agentLocation,currentNode.boxLocation); ArrayList<Command> foundCommands = addPossibleBoxCommandsForDirection(boxDir, currentNode.agentLocation, currentNode.boxLocation, blockedFields); for (Command command : foundCommands) { Field boxLocation = null; Field agentLocation = null; if (command.cmd.equals("Push")) { agentLocation = currentNode.boxLocation; boxLocation = currentNode.boxLocation.neighbours[command.dir2 .ordinal()]; } else { boxLocation = currentNode.agentLocation; agentLocation = currentNode.agentLocation.neighbours[command.dir1 .ordinal()]; } // Do we already have a way to get to this state? if (closedSet.containsKey(agentLocation)) { if (closedSet.get(agentLocation).contains(boxLocation)) continue; else // the agent has been here before but without the box in same location closedSet.get(agentLocation).add(boxLocation); } else { // neither the agent or the box has been here before. Update DS and create node in BTtree: ArrayList<Field> tempListe = new ArrayList<Field>(); tempListe.add(boxLocation); closedSet.put(agentLocation, tempListe); } GoalSequenceNode node = new GoalSequenceNode(boxLocation,agentLocation, command); node.parent = currentNode; node.g = node.parent.g+1; node.f = node.g + heuristicEstimateManhattan(boxLocation, boxToField); queue.add(node); } if (queue.isEmpty()) { //TODO: we have searched to the end without finding a solution. Move boxes to get access to goals return null; } currentNode = queue.poll(); } GoalActionSequence returnSequence = new GoalActionSequence(); returnSequence.setAgentStartLocation(currentNode.agentLocation); returnSequence.setBoxStartLocation(currentNode.boxLocation); ArrayList<Command> commands = new ArrayList<Command>(); while (currentNode.parent != null) { commands.add(currentNode.action); currentNode = currentNode.parent; } Collections.reverse(commands); returnSequence.setCommands(commands); return returnSequence; } public static ArrayList<Command> addPossibleBoxCommandsForDirection(dir direction, Field agentLocationInPlan, Field boxLocationInPlan, Collection<Field> blockedFields) { ArrayList<Command> possibleCommands = new ArrayList<Command>(); // Find possible pull commands for (dir d : dir.values()) { // we cannot pull a box forward in the box's direction if (d != direction && agentLocationInPlan.neighbours[d.ordinal()] != null && !blockedFields.contains(agentLocationInPlan.neighbours[d.ordinal()])) { possibleCommands.add(new Command("Pull", d, direction)); } } // Find possible push commands for (dir d : dir.values()) { // We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && boxLocationInPlan.neighbours[d.ordinal()] != null && !blockedFields.contains(boxLocationInPlan.neighbours[d.ordinal()])) { possibleCommands.add(new Command("Push", direction, d)); } } return possibleCommands; } public static boolean boxFitsGoal(Box b, Goal g){ return (g.getId() == Character.toLowerCase(b.getId())); } public static State getState(ArrayList<Agent> agents, ArrayList<Box> boxes) { State firstState = new State(); for (Agent a : agents) { firstState.agents.add(new AgentInState(a, a.getAtField())); } for (Box b : boxes) { firstState.boxes.add(new BoxInState(b, b.getAtField())); } return firstState; } public static ArrayList<Box> getBoxesWithId(ArrayList<Box> boxes, char id) { ArrayList<Box> boxesWithId = new ArrayList<Box>(); for (Box b : boxes) if (b.getId() == id) boxesWithId.add(b); return boxesWithId; } public static ArrayList<Agent> getAgents( ArrayList<Agent> agents, Color color) { ArrayList<Agent> returnAgents = new ArrayList<Agent>(); for (Agent agent : agents) { if (agent.getColor() == color) { returnAgents.add(agent); } } return returnAgents; } public static boolean isFieldAvailable(Field f, ArrayList<Field> blockedFields) { for (Field field : blockedFields) { if (field == f) return false; } return true; } public static ArrayList<BoxInState> getBoxesInState(ArrayList<BoxInState> boxes, char id) { ArrayList<BoxInState> boxesWithId = new ArrayList<BoxInState>(); for (BoxInState b : boxes) if (b.b.getId() == id) boxesWithId.add(b); return boxesWithId; } public static ArrayList<Box> getBoxesInLevel(ArrayList<Box> boxes, char id) { ArrayList<Box> boxesWithId = new ArrayList<Box>(); for (Box b : boxes) if (b.getId() == id) boxesWithId.add(b); return boxesWithId; } public static ArrayList<AgentInState> getAgentsInState(ArrayList<AgentInState> agents, Color color) { ArrayList<AgentInState> agentsInState = new ArrayList<AgentInState>(); for (AgentInState agentInState : agents) { if (agentInState.a.getColor() == color) agentsInState.add(agentInState); } return agents; } public static ArrayList<State> getState(ArrayList<AgentInState> agents, ArrayList<BoxInState> boxes, Agent agent, Field agentToPos, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (AgentInState a : agents) { if (a.a != agent) firstState.agents.add(a); else firstState.agents.add(new AgentInState(agent, agentToPos)); } for (BoxInState b : boxes) { firstState.boxes.add(b); } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; returnStates.add(firstState); } return returnStates; } public static ArrayList<State> getStateFromLevel(ArrayList<Agent> agents, ArrayList<Box> boxes, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (Agent a : agents) { firstState.agents.add(new AgentInState(a, a.getAtField())); } for (Box b : boxes) { firstState.boxes.add(new BoxInState(b, b.getAtField())); } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; returnStates.add(firstState); } return returnStates; } public static State getStateFromLevel(ArrayList<Agent> agents, ArrayList<Box> boxes) { State state = new State(); for (Agent a : agents) { state.agents.add(new AgentInState(a, a.getAtField())); } for (Box b : boxes) { state.boxes.add(new BoxInState(b, b.getAtField())); } return state; } public static ArrayList<State> getState(ArrayList<AgentInState> agents, ArrayList<BoxInState> boxes, Box box, Field boxPos, Agent agent, Field agentPos, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (AgentInState a : agents) { if (a.a != agent) firstState.agents.add(a); else firstState.agents.add(new AgentInState(agent, agentPos)); } for (BoxInState b : boxes) { if(b.b != box) firstState.boxes.add(b); else { firstState.boxes.add(new BoxInState(box, boxPos)); } } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; returnStates.add(firstState); } return returnStates; } public static boolean isFieldClear(State currentState, Field field) { for (AgentInState a : currentState.agents) { if(a.f == field) return false; } for (BoxInState b : currentState.boxes) { if(b.f == field) return false; } return true; } public static ArrayList<Field> findFreeField(Level level, ArrayList<Field> fields) { ArrayList<Field> returnFields = new ArrayList<Field>(); for (Field field : level.fields) { if(!fields.contains(field)) returnFields.add(field); } return returnFields; } public static BoxInState getBoxAtField(State currentState, Field firstBoxAtField) { for (BoxInState b : currentState.boxes) { if (b.f.equals(firstBoxAtField)) { return b; } } return null; } public static ArrayList<Box> getBoxesWithColor(ArrayList<Box> boxes, Color color) { ArrayList<Box> returnBoxes = new ArrayList<Box>(); for (Box box : boxes) { if (box.getColor() == color) { returnBoxes.add(box); } } return returnBoxes; } public static ArrayList<Goal> getGoalsWithId(ArrayList<Goal> goals, char id) { ArrayList<Goal> returnGoals = new ArrayList<Goal>(); for (Goal goal : goals) { if (goal.getId() == id) { returnGoals.add(goal); } } return returnGoals; } // public static ArrayList<StateGoal> getStateGoalFromField(Field goal) { // // ArrayList<StateGoal> returnGoals = new ArrayList<StateGoal>(); // // for (dir d : dir.values()) { // if (goal.neighbours[d.ordinal()] == null) continue; // // StateGoal stateGoal = new StateGoal(); // // stateGoal.agentToPos = goal.neighbours[d.ordinal()]; // // returnGoals.add(stateGoal); // } // // return returnGoals; // } public static boolean allGoalsAtHasBoxes(State currentState, Level level, ArrayList<Goal> agentGoals) { boolean[] goalFulfilled = new boolean[agentGoals.size()]; int index = 0; for (Goal g : agentGoals) { for (BoxInState bPos : currentState.boxes) { if (bPos.f == g && Character.toLowerCase(bPos.b.getId()) == g.getId()) { goalFulfilled[index] = true; } } index++; } boolean returnBool = true; for (boolean b : goalFulfilled) { if (!b) return false; } return returnBool; } /** * Calculates an a* like heuristic considering the traveled distance and the goal count * @param state * @param level * @return */ public static int CalculateStateHeuristic(State state, Level level) { int goalCountWeight = 5; int gScoreWeight = 1; int numberOfFulfilledGoals = 0; for (Goal g : level.goals) { for (BoxInState bPos : state.boxes) { if ( bPos.f == g && Character.toLowerCase(bPos.b.getId()) == g.getId()) { numberOfFulfilledGoals++; } } } int gScore = 0; // the g score is the cost of travelling here in terms of actionSequences (NOT actions) State parent = state; while(parent != null) { parent = parent.parent; gScore++; } return 1000 - (goalCountWeight*numberOfFulfilledGoals - gScoreWeight * gScore); } public static BoxInState findBoxInCompletedState(State currentState, Box box) { BoxInState boxInState = currentState.goal.box; for (BoxInState b : currentState.boxes) { if (b.b == boxInState.b && box == b.b) { return new BoxInState(box, currentState.goal.boxToPos); } else if (b.b == box) { return b; } } return null; } public static void findPossibleBoxes(){ } /** * Testing to if an agent can reach its boxes * @param level * @param agent * @param boxes * @return BoxInState it can reach */ public static HashMap<Box, BoxCost> findPossibleBoxes(Level level, Agent agent){ HashMap<Box, BoxCost> possibleBoxes = new HashMap<Box, BoxCost>(); for (Box box : level.boxes) { if(agent.getColor() == box.getColor()) { int cost = Utils.findRouteCostIgnoreBoxes(level, agent, agent.getAtField(), box.getAtField(), null); if (cost==-1) continue; if (possibleBoxes.containsKey(box)) { BoxCost bc = possibleBoxes.get(box); bc.box = box; bc.cost = cost; } else { BoxCost bc = new BoxCost(); bc.box = box; bc.cost = cost; possibleBoxes.put(box, bc); } } } if(possibleBoxes.isEmpty()) return possibleBoxes; for (Box box : possibleBoxes.keySet()) { for (Goal goal : level.goals) { if(!boxFitsGoal(box, goal)) continue; int cost = findRouteCostIgnoreBoxes(level, agent, box.getAtField(), (Field)goal, null)-50; //the box itself costs 50 if (cost==-1) continue; possibleBoxes.get(box).goalCosts.add(new GoalCost(goal, cost)); } } return possibleBoxes; } /** * * @param l The level * @param from The field to travel from * @param to The field to travel to * @param blockedFields A list of fields inaccessible to the agent * @return The cost of getting to the field. -1 if no route */ public static int findRouteCostIgnoreBoxes(Level l, Agent a, Field from, Field to, Collection<Field> blockedFields) { int cost = -1; HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); HashSet<AStarField> openSetCopy = new HashSet<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); HashSet<Field> ownBoxFields = new HashSet<Field>(); HashSet<Field> othersBoxFields = new HashSet<Field>(); for (Box b : l.boxes) { if (a.getColor().equals(b.getColor())) ownBoxFields.add(b.getAtField()); else othersBoxFields.add(b.getAtField()); } AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); openSetCopy.add(start); AStarField curField; while (true) { curField = openSet.poll(); // Are we there yet? if (curField.field.equals(to) || curField == null) break; openSetCopy.remove(curField); closedSet.add(curField.field); int gScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if (neighbor == null || (blockedFields != null && blockedFields.contains(neighbor)) || closedSet.contains(neighbor)) continue; // Is the neighbor already in the open set? As of uniform cost it can not be possible to find a faster route to it if (openSetCopy.contains(neighbor)) continue; // AStarField neighbourInOpenSet = null; // At some point test if it is faster to use this approach in stead of double openSet. // for (AStarField aOpen : openSet) { // if (aOpen.field == neighbor) continue; // } AStarField neighbourField = new AStarField(curField.neighborTo(d)); neighbourField.g = gScore; if (ownBoxFields.contains(curField.field)) neighbourField.g = gScore+50; else if (othersBoxFields.contains(curField.field)) neighbourField.g = gScore+200; neighbourField.f = neighbourField.g + heuristicEstimate(neighbourField.field, to, HeuristicType.MANHATTAN); neighbourField.c = new Command(d); cameFrom.put(neighbourField, curField); openSet.add(neighbourField); openSetCopy.add(neighbourField); } } if (curField != null) { cost = curField.f; } return cost; } public static ArrayList<Box> findRouteCountBoxesInTheWay(Level l, Agent a, Field from, Field to, Collection<Field> blockedFields) { ArrayList<Box> boxesInTheWay = null; HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); HashSet<AStarField> openSetCopy = new HashSet<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); HashSet<Field> ownBoxFields = new HashSet<Field>(); HashSet<Field> othersBoxFields = new HashSet<Field>(); for (Box b : l.boxes) { if (a.getColor().equals(b.getColor())) ownBoxFields.add(b.getAtField()); else othersBoxFields.add(b.getAtField()); } AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); openSetCopy.add(start); AStarField curField; while (true) { curField = openSet.poll(); // Are we there yet? if (curField.field.equals(to) || curField == null) break; openSetCopy.remove(curField); closedSet.add(curField.field); int gScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if (neighbor == null || (blockedFields != null && blockedFields.contains(neighbor)) || closedSet.contains(neighbor)) continue; // Is the neighbor already in the open set? As of uniform cost it can not be possible to find a faster route to it if (openSetCopy.contains(neighbor)) continue; AStarField neighbourField = new AStarField(curField.neighborTo(d)); neighbourField.g = gScore; boxesInTheWay = new ArrayList<Box>(); if (ownBoxFields.contains(curField.field)){ for (Box box : l.boxes) { if(box.getAtField() == curField.field) boxesInTheWay.add(box); } } else if (othersBoxFields.contains(curField.field)){ for (Box box : l.boxes) { if(box.getAtField() == curField.field) boxesInTheWay.add(box); } } neighbourField.f = neighbourField.g + heuristicEstimate(neighbourField.field, to, HeuristicType.MANHATTAN); neighbourField.c = new Command(d); cameFrom.put(neighbourField, curField); openSet.add(neighbourField); openSetCopy.add(neighbourField); } } return boxesInTheWay; } public static List<Field> getEscapeFieldsFromCommands(Agent a, Collection<Command> commandsNotCompleted) { ArrayList<Field> escapeFields = new ArrayList<Field>(); Field current = a.getAtField(); escapeFields.add(current); for (Command c : commandsNotCompleted) { if (c.cmd.equals("Move") || c.cmd.equals("Pull")) { current = current.neighbours[c.dir1.ordinal()]; } else if (c.cmd.equals("Push")) { current = current.neighbours[c.dir2.ordinal()]; } if (current == null) break; escapeFields.add(current); } return escapeFields; } /** * Checks if an agent was at this location last turn. this can happen on FOMA since actions are synchronous * @param level * @param field * @return */ public static boolean CheckIfAnAgentWasOnThisFieldLastTurn(Level level, Field field){ for (Agent agent : level.agents) { if(agent.lastLocation == field) return true; } return false; } public static Box FindBoxForAgent(Agent agent, Level level) { for (Box box : level.boxes) { if(box.getId() == agent.getId()){ return box; } } return null; } }
Java
package utils; import java.util.ArrayList; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; public class Communication { /** * find agent to move a given box that might be in the way for another agent * @param box * @param level * @return */ public static Agent FindAgentToMoveBox(Box box, Level level){ for (Agent candidate_agent : level.agents) { if(box.getColor() == candidate_agent.getColor()) return candidate_agent; } return null; } public static boolean isObsticalStillInTheWay(Agent agent, Object obstacle, ArrayList<Field> avoidFields){ if(obstacle instanceof Agent){ Agent agent_obstical = (Agent) obstacle; for (Field field : avoidFields) { if(agent_obstical.getAtField().equals(field)) return true; } } else if(obstacle instanceof Box){ Box box_obstical = (Box) obstacle; for (Field field : avoidFields) { if(box_obstical.getAtField().equals(field)) return true; } } return false; } }
Java
package utils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; import client.Command; import datastructures.ActionSequence; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class Moves { public static List<Field> getEscapeFieldsFromCommands(Agent a, Collection<Command> commandsNotCompleted) { ArrayList<Field> escapeFields = new ArrayList<Field>(); Field current = a.getAtField(); escapeFields.add(current); for (Command c : commandsNotCompleted) { if (c.cmd.equals("Move") || c.cmd.equals("Pull")) { current = current.neighbours[c.dir1.ordinal()]; } else if (c.cmd.equals("Push")) { current = current.neighbours[c.dir2.ordinal()]; } if (current == null) break; escapeFields.add(current); } return escapeFields; } public static void MoveABoxToLocation(Agent agent, Box box, Field newLocation, Level level){ GoalActionSequence routeToGoal; // if this is not possible due to box in the way call: //reinsert the objective ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(box.getAtField()); for (Agent tempAgent : level.agents) { if(agent != tempAgent && agent.isNooping) blockedFields.add(agent.getAtField()); } for (Box tempBox : level.boxes) { if(!tempBox.equals(box)) blockedFields.add(tempBox.getAtField()); } State newState = null; boxLoop: for (dir d : dir.values()) { Field neighbor = box.getAtField().neighborTo(d); if(neighbor == null) continue; MoveActionSequence moveAction = Utils.findRouteIgnoreObstacles(level, agent, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) continue; //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(box.getAtField()); for (dir goalNeighbourDir : dir.values()) { Field goalNeighbor = newLocation.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbor == null) continue; routeToGoal = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], goalNeighbor, box.getAtField(), newLocation, blockedFields); if (routeToGoal != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); break boxLoop; } } blockedFields.add(box.getAtField()); } for (ActionSequence actionSequence : newState.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { agent.commandQueue.add(command); } } } }
Java
package utils; import java.util.ArrayList; import LevelObjects.Field; import client.Command; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.FieldInState; import datastructures.State; public class PrioriGoalUtils { public static ArrayList<FieldInState> getBlockedFields(State currentState) { ArrayList<FieldInState> blockedFields = new ArrayList<FieldInState>(); for (FieldInState field : currentState.fields) { if (field.blockedTimeChangeIndexes.size() != 0) { blockedFields.add(field); } } return blockedFields; } public static ArrayList<Field> getBlockedFields(State currentState, AgentInState agent, BoxInState box) { ArrayList<Field> blockedFields = new ArrayList<Field>(); for (AgentInState a : currentState.agents) { if (agent.f != a.f) blockedFields.add(a.f); } for (BoxInState b : currentState.boxes) { if (box.f != b.f) blockedFields.add(b.f); } return blockedFields; } }
Java
package utils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Set; import utils.Utils.HeuristicType; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; import client.Command; import constants.Constants; import constants.Constants.dir; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.FieldBlockedChange; import datastructures.FieldInState; import datastructures.GoalActionSequence; import datastructures.GoalSequenceNode; import datastructures.MoveActionSequence; import datastructures.State; import datastructures.StateGoal; public class FOMAUtils { static State state; static int index; static Field agentPos; public static void mergeState(Level level, State currentState, ArrayList<ArrayList<Command>> commands) { state = currentState; if (commands == null) return; int counter = 0; for (ArrayList<Command> commandArray : commands) { System.err.println("MErging agent no " + counter + " size: " + commandArray.size()); index = currentState.indexOfCommands; agentPos = currentState.agents.get(counter).f; for (Command command : commandArray) { completeCommand(command); index++; } counter++; } // state.printFieldChanges(); } private static void completeCommand(Command c) { if (c.cmd.equals("Move")) completeMove(c); else if (c.cmd.equals("Pull")) completePull(c); else if (c.cmd.equals("Push")) completePush(c); } private static void completeMove(Command c) { for (FieldInState field : state.fields) { if (field.f == agentPos) { field.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, false)); for (FieldInState neighbour : state.fields) { if (field.f.neighbours[c.dir1.ordinal()] == neighbour.f) { neighbour.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); agentPos = neighbour.f; break; } } break; } } } private static void completePull(Command c) { for (FieldInState field : state.fields) { if (field.f == agentPos) { field.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, false)); field.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); for (FieldInState neighbour : state.fields) { if (field.f.neighbours[c.dir1.ordinal()] == neighbour.f) { neighbour.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); agentPos = neighbour.f; break; } } break; } } } private static void completePush(Command c) { for (FieldInState field : state.fields) { if (field.f == agentPos) { field.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, false)); for (FieldInState neighbour : state.fields) { if (field.f.neighbours[c.dir1.ordinal()] == neighbour.f) { neighbour.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, false)); neighbour.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); for (FieldInState neighbour2 : state.fields) { if (neighbour.f.neighbours[c.dir2.ordinal()] == neighbour2.f) { neighbour2.blockedTimeChangeIndexes.add(new FieldBlockedChange(index+1, true)); break; } } agentPos = neighbour.f; break; } } break; } } } public static MoveActionSequence findRoute(Level l, Field from, Field to, Collection<FieldInState> blockedFields, int startTimeStep) { HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); // System.err.println("Finding route form " + from.toString() + " to " + to.toString()); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); AStarField start = new AStarField(from); start.timeStep = startTimeStep; start.g = 0; start.f = start.g + Utils.heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); AStarField curField = openSet.poll(); while (curField != null) { if (curField.field.equals(to)) break; // System.err.println("Current field " + curField.field.toString()); closedSet.add(curField.field); int tentativeGScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if (neighbor == null){ continue; } boolean neighborIsBlockedInStep = isNeighbourBlockedInStep( blockedFields, neighbor, curField.timeStep); if (neighborIsBlockedInStep || closedSet.contains(neighbor)) continue; AStarField neighbourInOpenSet = null; for (AStarField aOpen : openSet) { if (aOpen.field == neighbor) neighbourInOpenSet = aOpen; } if (neighbourInOpenSet != null && tentativeGScore > neighbourInOpenSet.g) { continue; } else if (neighbourInOpenSet == null) { neighbourInOpenSet = new AStarField(curField.neighborTo(d)); neighbourInOpenSet.timeStep = curField.timeStep++; neighbourInOpenSet.g = tentativeGScore; neighbourInOpenSet.f = neighbourInOpenSet.g + Utils.heuristicEstimate(neighbourInOpenSet.field, to, HeuristicType.MANHATTAN); neighbourInOpenSet.c = new Command(d); cameFrom.put(neighbourInOpenSet, curField); openSet.add(neighbourInOpenSet); } } curField = openSet.poll(); } // If currentField is null, we didn't find a path. if (curField == null) return null; ArrayList<Command> commands = new ArrayList<Command>(); ArrayList<Field> fields = new ArrayList<Field>(); while (cameFrom.get(curField) != null) { fields.add(curField.field); commands.add(curField.c); curField = cameFrom.get(curField); } Collections.reverse(commands); Collections.reverse(fields); MoveActionSequence mas = new MoveActionSequence(from, to, commands); mas.fields = fields; return mas; } private static boolean isNeighbourBlockedInStep( Collection<FieldInState> blockedFields, Field neighbor, int startTimeStep) { for (FieldInState fieldInState : blockedFields) { if (fieldInState.f == neighbor) { if (fieldInState.changesStatusInFuture(startTimeStep)) return true; else{ return fieldInState.blockedTimeChangeIndexes.get(fieldInState.blockedTimeChangeIndexes.size()-1).changeToBlocked; } } } return false; } public static ArrayList<State> getStateFromLevel(ArrayList<Agent> agents, ArrayList<Box> boxes, ArrayList<Field> fields, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); ArrayList<FieldInState> fieldsInState = new ArrayList<FieldInState>(); for (Field field : fields) { FieldInState newField = new FieldInState(field); if (field.object != null) { newField.blockedTimeChangeIndexes.add(new FieldBlockedChange(0,true)); } else{ newField.blockedTimeChangeIndexes.add(new FieldBlockedChange(0,false)); } fieldsInState.add(newField); } for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (Agent a : agents) { firstState.agents.add(new AgentInState(a, a.getAtField())); } for (Box b : boxes) { firstState.boxes.add(new BoxInState(b, b.getAtField())); } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; firstState.fields = fieldsInState; returnStates.add(firstState); } return returnStates; } private static ArrayList<FieldInState> getNewFieldsInState( State currentState, Agent agent, ActionSequence sequence) { ArrayList<FieldInState> returnFields = new ArrayList<FieldInState>(); if (sequence instanceof MoveActionSequence) { MoveActionSequence routeToGoal = (MoveActionSequence) sequence; FieldInState curField = null; for (FieldInState fieldInState : currentState.fields) { FieldInState newField = new FieldInState(fieldInState.f); for (FieldBlockedChange i : fieldInState.blockedTimeChangeIndexes) { newField.blockedTimeChangeIndexes.add(i); } returnFields.add(newField); if (fieldInState.f == routeToGoal.getStartField()) curField = newField; } int timeStep = currentState.indexOfCommands; for (Command c : routeToGoal.getCommands()) { if (c.cmd.equals("Move")) { curField.blockedTimeChangeIndexes.add(new FieldBlockedChange(timeStep+1,false)); for (FieldInState fieldInState : returnFields) { if (fieldInState.f == curField.f.neighbours[c.dir1 .ordinal()]) { curField = fieldInState; break; } } curField.blockedTimeChangeIndexes.add(new FieldBlockedChange(timeStep+1,true)); } timeStep++; } } else{ GoalActionSequence routeToGoal = (GoalActionSequence) sequence; FieldInState curFieldAgent = null; FieldInState curFieldBox = null; for (FieldInState fieldInState : currentState.fields) { FieldInState newField = new FieldInState(fieldInState.f); for (FieldBlockedChange i : fieldInState.blockedTimeChangeIndexes) { newField.blockedTimeChangeIndexes.add(i); } returnFields.add(newField); if (fieldInState.f == routeToGoal.getAgentStartLocation()) curFieldAgent = newField; if (fieldInState.f == routeToGoal.getBoxStartLocation()) curFieldBox = newField; } int timeStep = currentState.indexOfCommands; for (Command c : routeToGoal.getCommands()) { curFieldAgent.blockedTimeChangeIndexes.add(new FieldBlockedChange(timeStep+1,true)); curFieldBox.blockedTimeChangeIndexes.add(new FieldBlockedChange(timeStep+1,true)); if (c.cmd.equals("Push")) { curFieldAgent = curFieldBox; for (FieldInState fieldInState : returnFields) { if (fieldInState.f == curFieldBox.f.neighbours[c.dir2 .ordinal()]) { curFieldBox = fieldInState; break; } } } if (c.cmd.equals("Pull")) { curFieldBox = curFieldAgent; for (FieldInState fieldInState : returnFields) { if (fieldInState.f == curFieldAgent.f.neighbours[c.dir1 .ordinal()]) { curFieldAgent = fieldInState; break; } } } timeStep++; } } return returnFields; } // We know that the agent a has a box. Now we want to move the box to the // goal. // GoalActionSequence routeToGoal = FOMAUtils.findGoalRoute(level, currentState.goal.agent.a, currentState.goal.box.b, // currentState.goal.agent.f, currentState.goal.agentToPos, currentState.goal.box.f, currentState.goal.boxToPos, blockedFields); public static GoalActionSequence findGoalRoute(Level l, State currentState, Collection<FieldInState> blockedFields) { dir boxDir = null; Field boxFromField = currentState.goal.box.f; Field agentFromField = currentState.goal.agent.f; Field boxToField = currentState.goal.boxToPos; Field agentToField = currentState.goal.agentToPos; GoalSequenceNode root = new GoalSequenceNode(boxFromField, agentFromField, null); LinkedList<GoalSequenceNode> queue = new LinkedList<GoalSequenceNode>(); // prune looped states (if agent and box ends up in a state already explored) HashMap<Field, ArrayList<Field>> closedSet = new HashMap<Field, ArrayList<Field>>(); //adding initial state to list set of explored states: ArrayList<Field> tempList = new ArrayList<Field>(); tempList.add(boxFromField); closedSet.put(agentFromField, tempList); //Add a closed set. queue.add(root); GoalSequenceNode currentNode = queue.poll(); currentNode.timeStep = currentState.indexOfCommands; while (currentNode != null && (currentNode.boxLocation != boxToField || currentNode.agentLocation != agentToField)) { boxDir = Agent.getBoxDirection(currentNode.agentLocation,currentNode.boxLocation); ArrayList<Command> foundCommands = addPossibleBoxCommandsForDirection(boxDir, currentNode.agentLocation, currentNode.boxLocation, blockedFields, currentNode.timeStep); for (Command command : foundCommands) { Field boxLocation = null; Field agentLocation = null; if (command.cmd.equals("Push")) { agentLocation = currentNode.boxLocation; boxLocation = currentNode.boxLocation.neighbours[command.dir2 .ordinal()]; } else { boxLocation = currentNode.agentLocation; agentLocation = currentNode.agentLocation.neighbours[command.dir1 .ordinal()]; } // Do we already have a way to get to this state? if (closedSet.containsKey(agentLocation)) { if (closedSet.get(agentLocation).contains(boxLocation)){ continue; } else { // the agent has been here before but without the box in same location closedSet.get(agentLocation).add(boxLocation); } } else { // neither the agent or the box has been here before. Update DS and create node in BTtree: ArrayList<Field> tempListe = new ArrayList<Field>(); tempListe.add(boxLocation); closedSet.put(agentLocation, tempListe); } GoalSequenceNode node = new GoalSequenceNode(boxLocation,agentLocation, command); node.parent = currentNode; node.timeStep = currentNode.timeStep+1; queue.add(node); } if (queue.isEmpty()) { //TODO: we have searched to the end without finding a solution. Move boxes to get access to goals return null; } currentNode = queue.poll(); } GoalActionSequence returnSequence = new GoalActionSequence(); returnSequence.setAgentStartLocation(currentNode.agentLocation); returnSequence.setBoxStartLocation(currentNode.boxLocation); ArrayList<Command> commands = new ArrayList<Command>(); while (currentNode.parent != null) { commands.add(currentNode.action); currentNode = currentNode.parent; } Collections.reverse(commands); returnSequence.setCommands(commands); return returnSequence; } public static ArrayList<State> getStateFromCompletedMove( State currentState, Agent agent, MoveActionSequence routeToGoal, Field goal) { ArrayList<State> returnStates = new ArrayList<State>(); ArrayList<FieldInState> fieldsInState = getNewFieldsInState( currentState, agent, routeToGoal); ArrayList<AgentInState> agents = currentState.agents; ArrayList<BoxInState> boxes = currentState.boxes; for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (AgentInState a : agents) { if (a.a != agent) firstState.agents.add(a); else firstState.agents.add(new AgentInState(agent, routeToGoal .getEndField())); } for (BoxInState b : boxes) { firstState.boxes.add(b); } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; firstState.fields = fieldsInState; returnStates.add(firstState); } return returnStates; } public static ArrayList<State> getStateFromCompletedGoal( State currentState, Agent agent, Field goal, GoalActionSequence routeToGoal) { ArrayList<AgentInState> agents = currentState.agents; ArrayList<BoxInState> boxes = currentState.boxes; Field agentPos = currentState.goal.agentToPos; Box box = currentState.goal.box.b; Field boxPos = currentState.goal.boxToPos; ArrayList<State> returnStates = new ArrayList<State>(); ArrayList<FieldInState> fieldsInState = getNewFieldsInState( currentState, agent, routeToGoal); // System.err.println("FieldsInState size " + fieldsInState.size() ); for (FieldInState fieldInState : fieldsInState) { // System.err.print("Field " + fieldInState.f.toString()); // System.err.println(); } for (dir d : dir.values()) { if (goal.neighbours[d.ordinal()] == null) continue; State firstState = new State(); for (AgentInState a : agents) { if (a.a != agent) firstState.agents.add(a); else firstState.agents.add(new AgentInState(agent, agentPos)); } for (BoxInState b : boxes) { if (b.b != box) firstState.boxes.add(b); else { firstState.boxes.add(new BoxInState(box, boxPos)); } } firstState.goal = new StateGoal(); firstState.goal.agentToPos = goal.neighbours[d.ordinal()]; firstState.fields = fieldsInState; returnStates.add(firstState); } return returnStates; } public static ArrayList<Command> addPossibleBoxCommandsForDirection(dir direction, Field agentLocationInPlan, Field boxLocationInPlan, Collection<FieldInState> blockedFields, int timeStep) { ArrayList<Command> possibleCommands = new ArrayList<Command>(); // System.err.println("PossibleCommands"); // Find possible pull commands for (dir d : dir.values()) { // we cannot pull a box forward in the box's direction FieldInState agentNeighbour = null; for (FieldInState f : blockedFields) { if (f.f == agentLocationInPlan.neighbours[d.ordinal()]) { agentNeighbour = f; } } if (d != direction && agentNeighbour != null && agentNeighbour.freeInInterval(timeStep, timeStep+2)) { // System.err.println("Making pull"); possibleCommands.add(new Command("Pull", d, direction)); } } for (dir d : dir.values()) { // We cannot push a box backwards in the agents direction FieldInState boxNeighbour = null; for (FieldInState f : blockedFields) { if (f.f == boxLocationInPlan.neighbours[d.ordinal()]) { boxNeighbour = f; } } // if(boxNeighbour.freeInInterval(timeStep, timeStep+2)) System.err.println("OSTEMADDDD"); if (d != Constants.oppositeDir(direction) && boxNeighbour != null && boxNeighbour.freeInInterval(timeStep, timeStep+2)) { // System.err.println("Making push"); possibleCommands.add(new Command("Push", direction, d)); } } return possibleCommands; } }
Java
package utils; import java.util.ArrayList; import java.util.List; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; public class FindFreeSpaces { public static void FindSpaces(Level level){ System.err.println("------------------Fields------------------"); List<Field> fields = new ArrayList<Field>(); fields = level.fields; System.err.println("Field: " + fields.size()); for (Box box : level.boxes) { if(box.getAtField() != null){ fields.remove(box.getAtField()); } } System.err.println("Field: " + fields.size()); for (Field field : fields) { // if(fields) // System.err.println("Field: " + field); } } }
Java
package aStar; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import LevelObjects.*; import client.Command; import constants.Constants.*; public class Pathfinding { // Should be called by planner to find commands for an agent public static Queue<Command> commandsForAgentToField(Level l, Agent a, Field to) { AStar(l,a,a.getAtField(),to); Queue<Command> q = new LinkedList<Command>(); q.add(new Command(dir.N)); q.add(new Command(dir.E)); q.add(new Command(dir.S)); q.add(new Command(dir.W)); return q; } // Should be called by planner to find commands for an agent public static Queue<Command> commandsForAgentAndBoxToFields(Level l, Agent a, Box b, Field aTo, Field bTo) { return new LinkedList<Command>(); } // Is only meant to be used by other functions in this class private static ArrayList<Field> AStar(Level l, Agent a, Field from, Field to) { // Data handling AStarNode[][] nodeMap = new AStarNode[l.fieldMap.length][l.fieldMap[0].length]; PriorityQueue<AStarNode> openSet = new PriorityQueue<AStarNode>(); Set<AStarNode> closedSet = new HashSet<AStarNode>(); // Start node AStarNode start = new AStarNode(from); start.g = 0; start.w = 0; start.h = manhattanDist(start.field, to); start.f = start.g + start.w + start.h; nodeMap[from.x][from.y] = start; openSet.add(start); // A* AStarNode current; while (openSet.size() > 0) { current = openSet.poll(); closedSet.add(current); Field f = current.field; if (f == to) { printNodeMap(nodeMap); return pathFromAStarNode(current); // goal reached } Field n; for (int i=0; i<4; i++) { n = f.neighbours[i]; if (n != null) { int tentative_g = current.g + 1; // check if there's already a node for this neighbour field AStarNode nNode; boolean nNodeIsNew = false; // temp value if (nodeMap[n.x][n.y] != null) { // already created node nNode = nodeMap[n.x][n.y]; if (closedSet.contains(nNode)) { if (tentative_g >= nNode.g) continue; } } else { nNode = new AStarNode(n); nodeMap[n.x][n.y] = nNode; nNodeIsNew = true; } boolean nNodeInOpenSet = false; if (!nNodeIsNew) nNodeInOpenSet = openSet.contains(nNode); // optimize this away ! if (!nNodeInOpenSet || tentative_g < nNode.g) { nNode.field = n; nNode.parent = current; nNode.g = tentative_g; if (nNodeIsNew) { nNode.h = manhattanDist(nNode.field, to); nNode.w = weightOfField(nNode.field, a); } nNode.f = nNode.g + nNode.w + nNode.h; if (!nNodeInOpenSet) openSet.add(nNode); } } } } System.err.println("Simple AStar could not find a path !!!"); return null; } private static void printNodeMap(AStarNode[][] nodeMap) { for (int y=0; y<nodeMap[0].length; y++) { for (int x=0; x<nodeMap.length; x++) { if (nodeMap[x][y] != null) //System.err.print(nodeMap[x][y].f+"\t"); System.err.printf("%3d", nodeMap[x][y].f); else System.err.print("\t"); } System.err.println(); } } private static ArrayList<Field> pathFromAStarNode(AStarNode node) { ArrayList<Field> path = new ArrayList<Field>(); AStarNode current = node; while (current != null) { System.err.println(current.field.x +"x"+ current.field.y + ", g:"+current.g+" w:"+current.w+" h:"+current.h); path.add(current.field); current = current.parent; } Collections.reverse(path); return path; } private static class AStarNode implements Comparable<AStarNode> { AStarNode parent; Field field; int f, g, w, h; public AStarNode(Field f){ field = f; } public int compareTo(AStarNode o) { return f - o.f; } } private static int manhattanDist(Field from, Field to) { return Math.abs(from.x - to.x) + Math.abs(from.y - to.y); } private static int weightOfField(Field f, Agent a) { int weight = 0; if (f instanceof Goal) weight += 1; // Moving over a goal. Should this even give extra weight? Object o = f.object; if (o instanceof Box) { if (((Box) o).getColor() == a.getColor()) weight += 2; // Agent can move box else weight += 20; // Agent can't move box } return weight; } }
Java
package LevelObjects; import java.io.Serializable; import constants.Constants; import constants.Constants.Color; public class Box implements Comparable<Box> { private char id; // stored as lowercase so we can easily compare with goals private Color color; private Field atField; public Box(char id, Color color, Field atField) { this.id = Character.toLowerCase(id); this.color = color==null ? Color.blue : color; this.atField = atField; } // Getter / Setters public Field getAtField() { return atField; } public void setAtField(Field atField) { this.atField = atField; } public char getId() { return id; } public Color getColor() { return color; } @Override public int compareTo(Box o) { if (this.atField.x != o.atField.y) { return this.atField.x-o.atField.x; } else{ return this.atField.y-o.atField.y; } } }
Java
package LevelObjects; import java.awt.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import agent.objectives.*; import agent.planners.AgentPlanner; import utils.Communication; import utils.Moves; import utils.Utils; import constants.Constants; import constants.Constants.Color; import constants.Constants.dir; import client.Command; import client.Desire; import client.planners.Planner; import datastructures.*; public class Agent { private static Random rand = new Random(); // del? private char id; public int number; private Color color; private Field atField; public HashMap<Box, BoxCost> possibleBoxesToGoals = new HashMap<Box, BoxCost>(); public Queue<ActionSequence> actions; public LinkedList<Objective> objectives = new LinkedList<Objective>(); public AgentPlanner planner; public boolean isNooping = false; public int priority; public Queue<Command> commandQueue; public Queue<Command> commandsNotCompleted; public Field lastLocation; public Desire desire; public Objective tempObjective; public Object obstacle; public boolean isTheCauseOfAConflict = false; private Conflict conflict; public Agent(char id, Color color, Field atField) { this.id = id; this.color = color==null ? Color.blue : color; this.atField = atField; this.commandQueue = new LinkedList<Command>(); this.commandsNotCompleted = new LinkedList<Command>(); } public Agent(char id, Color color, Field atField, AgentPlanner planner) { this(id, color, atField); this.planner = planner; } /** * Convert objective to commands and fill them in the commandqueue */ public void planAndExecute(Level level) { isNooping = false; // Check if previous action failed if (obstacle != null) { if (obstacle instanceof Agent) { Agent other = (Agent)obstacle; if (this.priority <= other.priority) { other.commandQueue.clear(); ArrayList<Field> list = new ArrayList<Field>(); list.add(this.getAtField()); other.objectives.addFirst(new Move(Utils.getEscapeFieldsFromCommands(this, commandsNotCompleted), list ,50)); other.obstacle = null; Command c; while ((c = commandsNotCompleted.poll()) != null) commandQueue.add(c); this.objectives.removeFirst(); } else this.commandsNotCompleted.clear(); } else if( obstacle instanceof Box) { //A box is in the way. find which box Box otherBox = (Box)obstacle; if(otherBox.getColor() == this.getColor()){ Objective newObjective = new DockABox(new Field(3, 6), otherBox, 15); this.objectives.addFirst(newObjective); } else { //Find an agent to move the box Agent otherAgent = Communication.FindAgentToMoveBox(otherBox, level); if (this.id<otherAgent.id || otherAgent.commandQueue.isEmpty()) { ArrayList<Field> fieldsToAvoid = new ArrayList<Field>(); fieldsToAvoid.addAll(Moves.getEscapeFieldsFromCommands(this, commandsNotCompleted)); otherAgent.conflict = new Conflict(this, fieldsToAvoid, obstacle, otherBox, this.priority); } } } obstacle = null; return; } // if(this.conflict != null && this.conflict.isPriority() < this.id){ //Another agent has a conflict with this agent if(this.conflict != null && this.conflict.isPriority() <= this.priority){ if(this.conflict.getObstacle() instanceof Box) { //A box is in the way. find which box //Agent has to move the box for another agent Box box = this.conflict.getMoveaBox(); //Get to box if(this.objectives.getFirst() instanceof Move){ //Find a route for the agent and the box. this.commandQueue.clear(); ArrayList<Field> candidates = new ArrayList<Field>(); candidates = Utils.getFreeFields(box.getAtField(),this.conflict.getAvoidFields(),15,false); Queue<Command> commandQueue = null; differentEndLocations: for (Field field : candidates) { Moves.MoveABoxToLocation(this, box, field, level); } } else if(this.objectives.getFirst() instanceof GoalABox){ //Find a route for the agent and the box. this.commandQueue.clear(); ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(this.conflict.getHelpAgent().getAtField()); Field candidates; candidates = Utils.getFirstFreeFieldkcl(box.getAtField(), this.conflict.getAvoidFields(), (Collection<Field>) blockedFields, 25, true); Moves.MoveABoxToLocation(this, box, candidates, level); } else { //Other agent not doing anything - get to the box and move it.. this.commandQueue.clear(); ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(this.conflict.getHelpAgent().getAtField()); for (Box current_box : level.boxes) { blockedFields.add(current_box.getAtField()); } Field candidates; this.conflict.avoidFields.addAll(blockedFields); candidates = Utils.getFirstFreeFieldkcl(box.getAtField(), this.conflict.getAvoidFields(), (Collection<Field>) blockedFields, 25, true); Moves.MoveABoxToLocation(this, box, candidates, level); } } this.conflict = null; } if(!this.commandQueue.isEmpty()){ return; } Objective o = objectives.peek(); if (o==null){ if(!objectives.isEmpty()){ objectives.remove(); } return; } boolean successful = false; if (o instanceof GoalABox) { GoalABox gab = (GoalABox)o; successful = planner.goalABox(this, gab.box, gab.goal); } else if (o instanceof Move) { Move mv = (Move)o; successful = planner.move(this, mv.escapeFromFields, mv.blockedFields, mv.numberOfRounds); } else if (o instanceof DockABox) { DockABox dab = (DockABox)o; successful = planner.dock(this, dab.box, dab.field, dab.blockedFields, dab.numberOfRounds); } else if (o instanceof Move) { Wait mv = (Wait)o; successful = planner.wait(this, mv.numberOfRounds); } if (successful) this.tempObjective = objectives.removeFirst(); } public Field getAtField() { return atField; } public void setAtField(Field atField) { this.atField = atField; } public char getId() { return id; } public Color getColor() { return color; } // Only used by random walk clients. public Command act() { ArrayList<Command> possibleCommands = new ArrayList<Command>(); for (dir d : dir.values()) { randomWalkAddPossibleCommandsForDirection(d, possibleCommands); } if (possibleCommands.size() == 0) possibleCommands.add(new Command(dir.N)); //Dummy command return possibleCommands.get(rand.nextInt(possibleCommands.size())); } private void randomWalkAddPossibleCommandsForDirection(dir direction, ArrayList<Command> possibleCommands){ if (neighbourFree(this.atField,direction)) { possibleCommands.add(new Command(direction)); } else if (neighbourIsBoxOfSameColor(direction)) { //Find possible pull commands for (dir d : dir.values()) { //we cannot pull a box forward in the box's direction if (d != direction && neighbourFree(this.atField,d)){ possibleCommands.add(new Command("Pull",d,direction)); } } //Find possible push commands for (dir d : dir.values()) { //We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && neighbourFree(this.getAtField().neighbours[direction.ordinal()],d)){ possibleCommands.add(new Command("Push",direction,d)); } } } } public ArrayList<Command> addPossibleCommandsForDirection(dir direction, Field agentLocationInPlan, Field boxLocationInPlan) { ArrayList<Command> possibleCommands = new ArrayList<Command>(); /* Commented because we are not interested in move commands at current time. if (neighbourFreeInPlan(agentLocationInPlan, direction, boxLocationInPlan) && this.desire.goal == null) { possibleCommands.add(new Command(direction)); }*/ // Find possible pull commands for (dir d : dir.values()) { // we cannot pull a box forward in the box's direction if (d != direction && neighbourFreeInPlan(agentLocationInPlan, d)) { possibleCommands.add(new Command("Pull", d, direction)); } } // Find possible push commands for (dir d : dir.values()) { // We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && neighbourFreeInPlan(boxLocationInPlan,d)) { possibleCommands.add(new Command("Push", direction, d)); } } return possibleCommands; } public boolean neighbourFree(Field f, dir d){ //System.err.println(f); return (f.neighbours[d.ordinal()] != null && f.neighbours[d.ordinal()].object == null); } //Checks if neighbour is free in the plan. public boolean neighbourFreeInPlan(Field posInPlan, dir d){ if (neighbourFree(posInPlan, d)) { return true; } //If the neighbour is free in actual state then everything is good. If it is not, we need to check if //it is free in the plan, by checking if the neighbour is the agent's or the box's location. else if(posInPlan.neighbours[d.ordinal()] != null && (posInPlan.neighbours[d.ordinal()] == this.getAtField() || (this.desire != null && posInPlan.neighbours[d.ordinal()] == this.desire.box.getAtField()))){ return true; } return false; } private boolean neighbourIsBoxOfSameColor(dir d){ return (this.getAtField().neighbours[d.ordinal()] != null && this.getAtField().neighbours[d.ordinal()].object instanceof Box && ((Box) this.getAtField().neighbours[d.ordinal()].object).getColor() == this.color); } //Find the box's direction, relative to the agent, if they are on adjacent fields. public static dir getBoxDirection(Field agentField, Field boxField){ if (boxField == null) return null; for (dir d : dir.values()) { if (agentField.neighbours[d.ordinal()] != null && agentField.neighbours[d.ordinal()] == boxField) { return d; } } return null; } }
Java
package LevelObjects; import java.util.ArrayList; public class Level { public ArrayList<Agent> agents = new ArrayList<Agent>(); public ArrayList<Box> boxes = new ArrayList<Box>(); public ArrayList<Field> fields = new ArrayList<Field>(); public ArrayList<Goal> goals = new ArrayList<Goal>(); public Field[][] fieldMap; public Field[][] getFieldMap() { return fieldMap; } public void setFieldMap(Field[][] field_map) { this.fieldMap = field_map; } }
Java
package LevelObjects; import java.util.Comparator; import constants.Constants.dir; public class Field implements Comparator<Field> { // Order of directions. /*public static enum dir { N, W, E, S };*/ // Example: neighbours[Constants.Constants.dir.N] public Field[] neighbours = new Field[4]; public int x; //Increases from left to right. public int y; //Increases downwards public Object object; //Can be null (free), or box or agent. public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public Field(int x, int y){ this.x = x; this.y = y; this.object = null; } public Field(int x, int y, Object object){ this.x = x; this.y = y; this.object = object; } public Field neighborTo(dir d) { return neighbours[d.ordinal()]; } public boolean isNeighborFree(dir d){ return (neighbours[d.ordinal()] != null && neighbours[d.ordinal()].object == null); } @Override public int compare(Field arg0, Field arg1) { if (arg0.x==arg1.x && arg0.y == arg1.y) return 0; else return (Math.abs(arg0.x-arg1.x) + Math.abs(arg0.y-arg1.y)); } @Override public String toString(){ return "" + this.x + "." + this.y; } public Field getClone(){ return new Field(this.x, this.y); } }
Java
package LevelObjects; import java.util.ArrayList; public class Conflict { private Agent helpAgent; private Object obstacle; private Box moveaBox; private int priority; public ArrayList<Field> avoidFields = new ArrayList<Field>(); public Conflict(Agent helpAgent, ArrayList<Field> avoidFields, Object obstacle) { super(); this.helpAgent = helpAgent; this.avoidFields = avoidFields; this.obstacle = obstacle; } public Conflict(Agent helpAgent, ArrayList<Field> avoidFields, Object obstacle, Box moveaBox) { super(); this.helpAgent = helpAgent; this.obstacle = obstacle; this.avoidFields = avoidFields; this.moveaBox = moveaBox; } public Conflict(Agent helpAgent, ArrayList<Field> avoidFields, Object obstacle, Box moveaBox, int priority) { super(); this.helpAgent = helpAgent; this.obstacle = obstacle; this.avoidFields = avoidFields; this.moveaBox = moveaBox; this.priority = priority; } public Agent getHelpAgent() { return helpAgent; } public void setHelpAgent(Agent helpAgent) { this.helpAgent = helpAgent; } public Box getMoveaBox() { return moveaBox; } public void setMoveaBox(Box moveaBox) { this.moveaBox = moveaBox; } public int isPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public ArrayList<Field> getAvoidFields() { return avoidFields; } public void setAvoidFields(ArrayList<Field> avoidFields) { this.avoidFields = avoidFields; } public Object getObstacle() { return obstacle; } public void setObstacle(Object obstacle) { this.obstacle = obstacle; } }
Java
package LevelObjects; public class Goal extends Field implements Comparable<Goal> { private char id; public int priority; public char getId() { return id; } public int getPriority() { return priority; } public void setPriority(int priority){ this.priority = priority; } public Goal(char id, int x, int y) { super(x, y); this.id = id; } public Goal(char id, int x, int y, Object object) { super(x, y, object); this.id = id; } @Override public int compareTo(Goal arg0) { return this.priority - arg0.priority; } public Goal(char id, int x, int y, Object object, int priority) { super(x, y, object); this.id = id; this.priority = priority; } }
Java
package agent.planners; import java.util.ArrayList; import java.util.List; import java.util.Random; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import constants.Constants; import constants.Constants.dir; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class AgentProgressionPlanner extends AgentPlanner { Level level; Random rand; private static final String name = "ProgressionPlanner"; public String getName() { return name; } public AgentProgressionPlanner(Level l) { this.level = l; rand = new Random(); } @Override public boolean goalABox(Agent agent, Box box, Goal goal) { // if this is not possible due to box in the way call: //agent.getHelpToMove(boxInTheWay) //reinsert the objective ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(box.getAtField()); // for (Agent tempAgent : level.agents) { // if(agent != tempAgent && agent.isNooping) blockedFields.add(agent.getAtField()); // } for (Agent tempAgent : level.agents) { blockedFields.add(tempAgent.getAtField()); } for (Box tempBox : level.boxes) { blockedFields.add(tempBox.getAtField()); } State newState = null; boxLoop: for (dir d : dir.values()) { Field neighbor = box.getAtField().neighborTo(d); if(neighbor == null) continue; MoveActionSequence moveAction = Utils.findRoute(level, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) continue; //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(box.getAtField()); if(!Utils.boxFitsGoal(box, goal))// Maybe this is the error? && (Field)goal != b.f) { // fits goal but is not the same goal as the box may be at already! continue; for (dir goalNeighbourDir : dir.values()) { Field goalNeighbor = goal.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbor == null) continue; GoalActionSequence routeToGoal = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], goalNeighbor, box.getAtField(), goal, blockedFields); if (routeToGoal != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); break boxLoop; } } blockedFields.add(box.getAtField()); } if (newState == null){ for (Agent tempAgent : level.agents) { blockedFields.remove(tempAgent.getAtField()); } for (Box tempBox : level.boxes) { blockedFields.remove(tempBox.getAtField()); } boxLoop: for (dir d : dir.values()) { Field neighbor = box.getAtField().neighborTo(d); if(neighbor == null) continue; MoveActionSequence moveAction = Utils.findRouteIgnoreObstacles(level, agent, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) continue; //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(box.getAtField()); if(!Utils.boxFitsGoal(box, goal))// Maybe this is the error? && (Field)goal != b.f) { // fits goal but is not the same goal as the box may be at already! continue; for (dir goalNeighbourDir : dir.values()) { Field goalNeighbor = goal.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbor == null) continue; GoalActionSequence routeToGoal = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], goalNeighbor, box.getAtField(), goal, blockedFields); if (routeToGoal != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); break boxLoop; } } blockedFields.add(box.getAtField()); } if (newState == null) return false; } for (ActionSequence actionSequence : newState.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { agent.commandQueue.add(command); } } return true; } @Override public boolean move(Agent agent, List<Field> escapeFromFields, List<Field> blockedFields, int numberOfRounds) { Field toField = Utils.getFirstFreeField(agent.getAtField(), escapeFromFields, blockedFields, 20, true); if (toField == null) return false; MoveActionSequence moveAction = Utils.findRoute(level, agent.getAtField(), toField); if (moveAction == null) return false; for (Command command : moveAction.getCommands()) { agent.commandQueue.add(command); } return true; } @Override public boolean dock(Agent agent, Box box, Field field, List<Field> blockedFields, int numberOfRounds) { // We want to consider moving the box another place //Field freeField = Utils.getFreeField(level, a.a, b.b, a.f, b.f, blockedFields, 15); // TODO: change depth List<Field> freeFields = Utils.getFreeFields(box.getAtField(), blockedFields, 15, 8, false); blockedFields.remove(box.getAtField()); State newState = null; boxLoop: for (dir d : dir.values()) { //The following line will now find a path to adjacent boxes. MoveActionSequence moveAction = Utils.findRoute(level, agent.getAtField(), box.getAtField().neighbours[d.ordinal()], blockedFields); if (moveAction == null) continue; for (Field freeField : freeFields) { //System.err.println("Free field found for "+b.b.getId()+" at: " + freeField); for (dir goalNeighbourDir : dir.values()) { Field freeNeighbour = freeField.neighbours[goalNeighbourDir.ordinal()]; if (freeNeighbour == null) continue; //MoveBoxActionSequence mba = Utils.findEmptyFieldRoute(level, a.a, b.b, freeField, a.f, freeNeighbour, b.f, blockedFields); GoalActionSequence moveBoxAction = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], freeNeighbour, box.getAtField(), freeField, blockedFields); if (moveBoxAction == null) continue; //If we get here, we have found a route to the goal. newState = new State(); if (moveBoxAction != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(moveBoxAction); break boxLoop; } } } } for (ActionSequence actionSequence : newState.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { agent.commandQueue.add(command); } } return true; } @Override public boolean wait(Agent agent, int numberOfRounds) { agent.isNooping = true; if (numberOfRounds>0) for(int i=0; i<numberOfRounds; i++) agent.commandQueue.add(Constants.NOOP); return true; } }
Java
package agent.planners; import java.util.List; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; public abstract class AgentPlanner { public abstract boolean goalABox(Agent agent, Box box, Goal goal); public abstract boolean move(Agent agent, List<Field> escapeFromFields, List<Field> blockedFields, int numberOfRounds); public abstract boolean dock(Agent agent, Box box, Field field, List<Field> blockedFields, int numberOfRounds); public abstract boolean wait(Agent agent, int numberOfRounds); }
Java
package agent.objectives; import java.util.List; import LevelObjects.*; public class Move extends Objective { public List<Field> blockedFields; public int numberOfRounds; public List<Field> escapeFromFields; public Move(List<Field> escapeFromField, List<Field> blockedFields, int numberOfRounds) { super(); this.blockedFields = blockedFields; this.escapeFromFields = escapeFromField; this.numberOfRounds = numberOfRounds; } }
Java
package agent.objectives; public abstract class Objective { }
Java
package agent.objectives; import LevelObjects.*; public class GoalABox extends Objective { public GoalABox(Box b, Goal g) { goal = g; box = b; } public Goal goal; public Box box; }
Java
package agent.objectives; import java.util.List; import LevelObjects.*; public class DockABox extends Objective { public Field field; public List<Field> blockedFields; public Box box; public int numberOfRounds; public DockABox(Field field, Box box, int numberOfRounds) { super(); this.field = field; this.box = box; this.numberOfRounds = numberOfRounds; } }
Java
package agent.objectives; import java.util.List; import LevelObjects.*; public class Wait extends Objective { public int numberOfRounds; public List<Field> blockedFields; }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android.views; import android.content.Context; import android.view.View; /** * @author Harald Schilly */ public class ScrollImageView extends View { /** * @param context */ public ScrollImageView(Context context) { super(context); } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import org.sagemath.android.fx.FunctionEditor; import org.json.JSONArray; import org.json.JSONException; import android.content.Context; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Static global Data. * * @author Harald Schilly */ final public class Global { private Global() { }; private static String FN_SETTINGS = "settings.json"; public static final String TAG = "SageAndroid"; /** * ID used for the Intent to identify a {@link FunctionEditor} */ public static final int FUNC_EDIT = 313245; // directional flags public static final int RIGHT = 1374, LEFT = 1375, FLIP = 1376; // cool number and used for zoom in and zoom out. public static double GOLDEN_RATIO = 1.61803399; private static CalculationAPI api; final static void setCalculationAPI(CalculationAPI api) { Global.api = api; } final public static CalculationAPI getCalculationAPI() { return api; } // Don't try to use localhost, because localhost is the Android // device itself. You always have to connect to some other machine. final static Set<Server> servers = new HashSet<Server>(3); // TODO remove initial list of servers static { servers.add(new Server("sagenb.org", "admin", "test")); } // private static SharedPreferences settings = null; private static Server server = null; private static SageAndroid context = null; static void setContext(SageAndroid context) { Global.context = context; try { loadSettings(); } catch (IOException ex) { // TODO handle this } catch (JSONException ex) { // TODO handle this } } final public static Context getContext() { return context; } /** * writes the list of servers to a json file. for more, read {@link * loadSettings()}. */ final static void saveSettings() { FileOutputStream fos = null; try { fos = context.openFileOutput(FN_SETTINGS, Context.MODE_PRIVATE); BufferedOutputStream bos = new BufferedOutputStream(fos); JSONArray json = new JSONArray(); for (Server s : servers) { JSONArray entry = new JSONArray(); entry.put(s.server); entry.put(s.username); entry.put(s.password); json.put(entry); } bos.write(json.toString().getBytes()); bos.close(); } catch (FileNotFoundException e) { // we just write to the fos, this should never fail, ... } catch (IOException ex) { // TODO handle this } finally { try { fos.close(); } catch (IOException ex) { } } } private final static StringBuilder loadSb = new StringBuilder(); /** * Reads the storead JSON data.<br> * Example: * * <pre> * [ * [ "http://server1", "franz", "99999" ], * [ "http://server2", "susi", "secret" ] * ] * </pre> * * @throws IOException * @throws JSONException */ final static void loadSettings() throws IOException, JSONException { // create "empty" settings file if it does not exist if (context.getFileStreamPath(FN_SETTINGS).exists()) { saveSettings(); return; } // first, read the file FileInputStream fis = context.openFileInput(FN_SETTINGS); try { BufferedReader br = new BufferedReader(new InputStreamReader(fis)); loadSb.setLength(0); for (int c; (c = br.read()) >= 0;) { loadSb.append(c); } } finally { fis.close(); } // then assume everything is readable from the json, otherwise an exception // is thrown List<Server> tmpServers = new ArrayList<Server>(); JSONArray json = new JSONArray(loadSb.toString()); for (int i = json.length() - 1; i >= 0; i--) { JSONArray entry = json.getJSONArray(i); tmpServers.add(new Server(entry.getString(0), entry.getString(1), entry.getString(2))); } // then replace the data (updating it would be better) servers.clear(); servers.addAll(tmpServers); } final static void setServer(Server selServer) { // we probably have to update an entry, remove it and ... for (Server s : servers) { if (selServer.server.equals(s.server)) { servers.remove(s); } } // ... add it servers.add(selServer); // point to the selected one server = selServer; } /** * @return password or if not set, "" */ final static String getPassword() { return (server == null) ? "" : server.password; } /** * @return username or if not set, "" */ final static String getUser() { return (server == null) ? "" : server.username; } /** * @return Server */ final public static Server getServer() { return server; } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android; import android.app.Activity; import android.content.res.Configuration; import android.util.DisplayMetrics; import android.view.Display; /** * @author Harald Schilly */ public class Utils { /** * @param activity * @return 1 is portrait and 2 is landscape */ final public static int screenOrientation(Activity activity) { int orientation = activity.getResources().getConfiguration().orientation; // if undefined if (orientation == Configuration.ORIENTATION_UNDEFINED) { final Display display = activity.getWindowManager().getDefaultDisplay(); if (display.getWidth() == display.getHeight()) { orientation = Configuration.ORIENTATION_SQUARE; } else { if (display.getWidth() < display.getHeight()) { orientation = Configuration.ORIENTATION_PORTRAIT; } else { orientation = Configuration.ORIENTATION_LANDSCAPE; } } } return orientation; } /** * @return */ final public static float getScaledWidth(Activity activity) { DisplayMetrics dm = activity.getResources().getDisplayMetrics(); int absWidth = dm.widthPixels; return absWidth / dm.scaledDensity; } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import android.os.Parcel; import android.os.Parcelable; import java.text.DecimalFormat; import java.util.concurrent.atomic.AtomicInteger; /** * Something to do for the Sage Server. * * @author Harald Schilly */ final public class Calculation { final public static int INIT = 0, STARTED = 1, FINISHED = 2; // for the unique id final private static AtomicInteger ID = new AtomicInteger(0); final private static DecimalFormat decimalSeconds = new DecimalFormat(); static { decimalSeconds.applyPattern("0.#### [s]"); } // id, starttime and code are defacto final and should be // treated as such, but they are not because of the aidl serialization. private int id; private int state = Calculation.INIT; private String result = ""; private long starttime = -1L; private String code = ""; // it's a convention that there has to be this field called CREATOR. final public static Parcelable.Creator<Calculation> CREATOR = new Parcelable.Creator<Calculation>() { @Override final public Calculation createFromParcel(Parcel in) { return new Calculation(in); } @Override final public Calculation[] newArray(int size) { return new Calculation[size]; } }; public Calculation(Parcel in) { readFromParcel(in); } /** * construct a new Calculation object. It is used to communicate between * Server/Client (Background Service) and holds the input, later the output * and a unique id. Additionally, it gives you the total time for the * calculation and it is planned to include a state. */ public Calculation() { id = ID.getAndIncrement(); } final void setCode(String code) { this.code = code; } final public String getCode() { return code; } final public void setResult(String result) { this.result = result; } final void setStartTime(long starttime) { this.starttime = starttime; } /** * AIDL serialization, must match with writeToParcel and used in * {@link CalculationListener} * * @param in */ final void readFromParcel(Parcel in) { id = in.readInt(); state = in.readInt(); result = in.readString(); code = in.readString(); starttime = in.readLong(); } /** * AIDL serialization, must match with readFromParcel and used in * {@link CalculationListener} * * @param reply * @param parcelableWriteReturnValue */ final void writeToParcel(Parcel reply, int parcelableWriteReturnValue) { reply.writeInt(id); reply.writeInt(state); reply.writeString(result); reply.writeString(code); reply.writeLong(starttime); } /** * the result of the calculation or "" * * @return */ final public String getResult() { return result; } /** * ID of the calculation * * @return unique int */ final public int getId() { return id; } /** * timespan between start of calculation and now in seconds. * * @return timespan in seconds */ final public String getElapsed() { double d = System.currentTimeMillis() - starttime; return decimalSeconds.format(d / 1000.0); } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android; import android.os.Parcel; import android.os.Parcelable; /** * @author Harald Schilly */ class Server { String server, username, password; /** * it's a convention that there has to be a field called CREATOR. */ final public static Parcelable.Creator<Server> CREATOR = new Parcelable.Creator<Server>() { @Override final public Server createFromParcel(Parcel in) { return new Server(in); } @Override final public Server[] newArray(int size) { return new Server[size]; } }; public Server(Parcel in) { readFromParcel(in); } public Server(String server, String username, String password) { this.server = server; this.username = username; this.password = password; } /** * */ public Server() { // TODO Auto-generated constructor stub } /** * AIDL serialization, must match with writeToParcel. * * @param in */ final void readFromParcel(Parcel in) { server = in.readString(); username = in.readString(); password = in.readString(); } /** * AIDL serialization, must match with readFromParcel * * @param reply * @param parcelableWriteReturnValue */ final void writeToParcel(Parcel out, int parcelableWriteReturnValue) { out.writeString(server); out.writeString(username); out.writeString(password); } /** * Determine if two probably distinct objects are equal. * * @return true, if they have the same field values. */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof Server) { Server so = (Server) other; if (this.server == so.server && this.username == so.username && this.password == so.password) { return true; } } return false; } /** * This class is used in a HashSet and has no final fields. We also have to * override {@link equals}. */ @Override public int hashCode() { return 0; // no immutable fields! } @Override public String toString() { return server; } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.Global; import org.sagemath.android.R; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import android.widget.ImageView.ScaleType; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.text.DecimalFormat; /** * @author Harald Schilly */ public class Plot extends AbstractInteract { /** * @param resource */ public Plot() { super(R.layout.plot); } private ImageView plot; private Button btnZoomIn, btnZoomOut; private float zoom = 1; private final String FILENAME = "plot.png"; private TextView status; private ScrollView scroll; final private static DecimalFormat decimalPercent = new DecimalFormat(); static { decimalPercent.applyPattern("0.## %"); } final private static BitmapFactory.Options bmOptions = new BitmapFactory.Options(); static { bmOptions.inScaled = false; } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#build() */ @Override protected void init() { plot = (ImageView) myView.findViewById(R.id.imgPlot); status = (TextView) myView.findViewById(R.id.txtPlotStatus); scroll = (ScrollView) myView.findViewById(R.id.plotScrollViewImage); // plot.setImageResource(R.drawable.example_plot); Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.example_plot, bmOptions); plot.setImageBitmap(bm); plot.setScaleType(ScaleType.CENTER); // TODO that does not work this way and we better not use scrolling at all scroll.setHorizontalScrollBarEnabled(true); btnZoomIn = (Button) myView.findViewById(R.id.btnPlotZoomIn); btnZoomOut = (Button) myView.findViewById(R.id.btnPlotZoomOut); OnClickListener nyi = new OnClickListener() { @Override public void onClick(View v) { if (v == btnZoomIn) { zoom *= Global.GOLDEN_RATIO; } else if (v == btnZoomOut) { zoom /= Global.GOLDEN_RATIO; } String width = Integer.toString(myView.getWidth()); calculate("plot(...zoom=" + decimalPercent.format(zoom) + ", width=" + width + ")"); } }; btnZoomIn.setOnClickListener(nyi); btnZoomOut.setOnClickListener(nyi); try { DownloadThread dt = new DownloadThread(downloadProgressHandler, new URI( "http://www.example.com/")); dt.start(); } catch (MalformedURLException ex) { } catch (URISyntaxException ex) { } } final private static int DOWNLOAD_PROGRESS = 239847; /** * Updates UI with download progress */ final private Handler downloadProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case (DOWNLOAD_PROGRESS): int down = msg.arg1; int size = msg.arg2; if (size == 0) { // unknown } else { String percent = decimalPercent.format((double) down / (double) size); if (status != null) { status.setText("progress " + percent); } } break; default: super.handleMessage(msg); } } }; /** * Downloads the image */ private class DownloadThread extends Thread { private static final int MAX_BUFFER = 1024; private Handler handler; private int size = 0; private URL url; int downloaded = 0; DownloadThread(Handler h, URI uri) throws MalformedURLException { handler = h; this.url = uri.toURL(); } private void sendMessage() { Message msg = handler.obtainMessage(); msg.what = DOWNLOAD_PROGRESS; msg.arg1 = downloaded; msg.arg2 = size; handler.sendMessage(msg); } @Override public void run() { RandomAccessFile file = null; InputStream stream = null; try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); stream = connection.getInputStream(); size = connection.getContentLength(); if (connection.getResponseCode() != 200) { // TODO ERROR } if (size < 1) { // TODO ERROR } File f = new File(FILENAME); if (f.exists()) { f.delete(); } f.deleteOnExit(); file = new RandomAccessFile(FILENAME, "rw"); while (true) { byte buffer[] = new byte[(size - downloaded > MAX_BUFFER) ? MAX_BUFFER : size - downloaded]; // Read from server into buffer. int read = stream.read(buffer); if (read == -1) { break; } // Write buffer to file. file.write(buffer, 0, read); downloaded += read; sendMessage(); } } catch (IOException ex) { } } } // ~~~ end DownloadThread /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#onError(java.lang.String) */ @Override protected void onError(String msg) { status.setText(msg); } /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#onResult(java.lang.String) */ @Override protected void onResult(Calculation c) { status.setText(c.getCode() + "\n" + c.getResult()); } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#reset() */ @Override public void reset() { zoom = 1; status.setText("reset"); } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.R; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /** * Calculate the solution to a system of linear equations, e.g. a 3 x 4 Matrix * of numerical value fields that are for a 3x3 matrix A and a 3x1 vector b and * then display the solution vector below. * * @author Harald Schilly */ public class System extends AbstractInteract { public System() { super(R.layout.system); } private Button solve; private TextView output; /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#build() */ @Override protected void init() { solve = (Button) myView.findViewById(R.id.systemBtnSolve); output = (TextView) myView.findViewById(R.id.systemOutput); solve.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { output.setText("calculating ..."); calculate(Integer.toString((int) (42 * Math.random()))); } }); } /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#onError(java.lang.String) */ @Override protected void onError(String error) { output.setText("Error: " + error); } /* * (non-Javadoc) * @see * * org.sagemath.android.interacts.AbstractInteract#onResult(org.sagemath.android * .Calculation) */ @Override protected void onResult(Calculation c) { output.setText(c.getResult()); } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#reset() */ @Override public void reset() { // TODO Auto-generated method stub } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.CalculationAPI; import org.sagemath.android.CalculationListener; import org.sagemath.android.Global; import android.content.Context; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.util.Log; import android.view.LayoutInflater; import android.view.View; /** * @author Harald Schilly */ public abstract class AbstractInteract { private static final int MSG_ID = 2; final protected LayoutInflater layoutInflater; final Handler handler; protected View myView; private CalculationAPI api; protected Context context; /** * callback to update on result. since it comes from another thread (the IPC * mechanism) we have to use the handler to get it on the UI thread. before * that, we check if it actually concerns us. */ private CalculationListener calcListener = new CalculationListener.Stub() { @Override public boolean handleCalculationResult(Calculation c) throws RemoteException { // only react to results that were initiated by me if (id == c.getId()) { handler.sendMessage(handler.obtainMessage(MSG_ID, c)); return true; } return false; } }; /** * This is set to the ID of the {@link Calculation}. When we are called back, * we expect that this ID matches with the one in the answer. */ private int id = -1; /** * This is the base for all interact like interfaces. * It does the basic wireing, adds some thin wrappers around the * API and provides two callbacks: {@link AbstractInteract.onResult} and * {@link AbstractInteract.onError}. * * @param R.layout.[identifyer] */ public AbstractInteract(final int resource) { this.api = Global.getCalculationAPI(); this.context = Global.getContext(); this.layoutInflater = LayoutInflater.from(context); // Handler are called from non-UI threads to update the UI on the UI thread. handler = new Handler() { @Override public void handleMessage(Message msg) { if (MSG_ID == msg.what) { onResult((Calculation) msg.obj); } else { super.handleMessage(msg); } } }; myView = layoutInflater.inflate(resource, null); init(); } public void addCalcListener() { try { api.addCalcListener(calcListener); } catch (RemoteException re) { Log.w(Global.TAG, "Failed to add CalcListener in AbstracInteract", re); } } public void removeCalcListener() { try { api.removeCalcListener(calcListener); } catch (RemoteException re) { Log.w(Global.TAG, "Failed to remove CalcListener in AbstracInteract", re); } } protected void calculate(String code) { try { id = api.calculate(code); } catch (RemoteException ex) { onError(ex.toString()); } } /** * Use this method to get the View of this Interact. * It basically calls {@link build} to wire up the application. * * @return interact view */ public View getView() { reset(); return myView; } /** * Called once when object is created. Get UI elements and bind methods to UI * events, etc. */ abstract protected void init(); /** * Called when {@link Calculation} has finished. * * @param c */ abstract protected void onResult(Calculation c); /** * Called when error happened. * * @param error */ protected abstract void onError(String error); /** * reset is called when it is shown again (view object stays the same * but we have a chance to clean up) */ public abstract void reset(); }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.R; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * A simple interact that executes the given lines of code. * * @author schilly */ public class ExecuteCommand extends AbstractInteract { private TextView output; public ExecuteCommand() { super(R.layout.execute_command); } /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#build() */ @Override protected void init() { final EditText input = (EditText) myView.findViewById(R.id.exInputText); output = (TextView) myView.findViewById(R.id.exOutput); final Button button = (Button) myView.findViewById(R.id.exSend); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { calculate(input.getText().toString()); } }); } @Override public void onResult(Calculation c) { // interpret output and update UI output.setText(c.getResult()); } /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#onError(java.lang.String) */ @Override protected void onError(String msg) { output.setText("Error: " + msg); } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#reset() */ @Override public void reset() { output.setText(""); } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, schilly <email@email.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.R; import android.widget.SeekBar; import android.widget.TextView; import android.widget.SeekBar.OnSeekBarChangeListener; /** * @author Harald Schilly */ public class SliderTest2 extends AbstractInteract { private TextView sliderTV; private int a = 0; /** */ public SliderTest2() { super(R.layout.slider_test); } @Override protected void onResult(Calculation c) { sliderTV.setText("a: " + a + " and result: " + c.getResult()); } @Override protected void onError(String msg) { sliderTV.setText("ERROR: " + msg); } @Override protected void init() { sliderTV = (TextView) myView.findViewById(R.id.SliderTestText); SeekBar sliderSB = (SeekBar) myView.findViewById(R.id.SliderTestSeekBar); sliderSB.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { a = progress; calculate(Integer.toString(progress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#reset() */ @Override public void reset() { onResult(new Calculation()); a = 0; } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.fx; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; /** * @author Harald Schilly */ public class ActionView extends TextView { private Action action; /** * @param context */ public ActionView(Context context) { super(context); } public ActionView(Context context, AttributeSet attrs) { super(context, attrs); } void setAction(Action action) { this.action = action; } Action getAction() { return action; } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.fx; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; /** * @author Harald Schilly */ public class KeyView extends TextView { private Key key; /** * @param context */ public KeyView(Context context) { super(context); } public KeyView(Context context, AttributeSet attrs) { super(context, attrs); } void setKey(Key key) { this.key = key; } Key getKey() { return key; } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.fx; import org.sagemath.android.R; import org.sagemath.android.Utils; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Edit a String to build up a function, like "1 + sin(x * cos(x)) / (1-x)". * This is an {@link Activity} and might also be used from other applications. * * @author Harald Schilly */ final public class FunctionEditor extends Activity { private Button btnDone, btnCancel; private EditText formula; private TableLayout gridFunc, gridNavi, gridOps; final static Pattern wordBoundary = Pattern.compile("\\b"); /** * Operators */ final private static String[] staticOps = { "+", "-", "*", "/", "^", "x", "y", "z", "(", ")", "<", ">", ".", "[", "]", "<", ">" }; /** * Entry point for creating the {@link FunctionEditor} Activity class. * * @return intent with modified text, and the start and end position of the * selection. */ @Override final public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.function_editor); final LayoutInflater inflater = this.getLayoutInflater(); // UI fields formula = (EditText) findViewById(R.id.fx_formula); btnDone = (Button) findViewById(R.id.fx_button_done); btnCancel = (Button) findViewById(R.id.fx_button_cancel); gridOps = (TableLayout) findViewById(R.id.fx_grid_ops); gridFunc = (TableLayout) findViewById(R.id.fx_grid_func); gridNavi = (TableLayout) findViewById(R.id.fx_grid_navi); { // Copy the text and selection state from the intent that started me Bundle bIntent = getIntent().getExtras(); final String func = bIntent.getString("func"); final int start = bIntent.getInt("start"); final int end = bIntent.getInt("end"); formula.setText(func); formula.setSelection(start, end); } // when done return the constructed string with the current selection in a // bundle btnDone.setOnClickListener(new OnClickListener() { @Override final public void onClick(View v) { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("func", formula.getText().toString()); bundle.putInt("start", formula.getSelectionStart()); bundle.putInt("end", formula.getSelectionEnd()); intent.putExtra("data", bundle); setResult(RESULT_OK, intent); finish(); } }); // just signal that it was canceled btnCancel.setOnClickListener(new OnClickListener() { @Override final public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); // The following sets the "keys" which insert something or additionally // deletes something if there is a selection { final int cols = (int) (Utils.getScaledWidth(this) / 60.0); int idx = 0; TableRow row = null; for (Key key : Key.values()) { if (idx % cols == 0) { row = new TableRow(this); gridFunc.addView(row); } idx++; KeyView cell = (KeyView) inflater.inflate(R.layout.function_editor_key, null); cell.setText(key.toString()); cell.setKey(key); cell.setOnClickListener(keyClickListener); row.addView(cell); } } // this part inserts operators like +, -, ... { final int cols = (int) (Utils.getScaledWidth(this) / 40.0); TableRow row = null; int idx = 0; for (String op : staticOps) { if (idx % cols == 0) { row = new TableRow(this); gridOps.addView(row); } idx++; TextView cell = (TextView) inflater.inflate(R.layout.function_editor_textview, null); cell.setText(op); cell.setOnClickListener(opClickListener); row.addView(cell); } } // this part is lengthy and does some actions like cursor move, selections // and deletions { final int cols = (int) (Utils.getScaledWidth(this) / 40.0); TableRow row = null; int idx = 0; for (Action act : Action.values()) { if (idx % cols == 0) { row = new TableRow(this); gridNavi.addView(row); } idx++; ActionView cell = (ActionView) inflater.inflate(R.layout.function_editor_action, null); cell.setText(act.toString()); cell.setAction(act); cell.setOnClickListener(actionClickListener); row.addView(cell); } } } final private OnClickListener opClickListener = new OnClickListener() { @Override public void onClick(View v) { final String op = (String) ((TextView) v).getText(); final int start = formula.getSelectionStart(); final int end = formula.getSelectionEnd(); Editable formulaEdit = formula.getEditableText(); formulaEdit.replace(start, end, " " + op + " "); formula.setText(formulaEdit.toString()); formula.setSelection(start + op.length() + 2); } }; /** * This is the action listener, avoiding to create one for each key. */ final private OnClickListener keyClickListener = new OnClickListener() { @Override public void onClick(View v) { final Key f = ((KeyView) v).getKey(); final int oldPos = formula.getSelectionStart(); String s = formula.getText().replace(oldPos, formula.getSelectionEnd(), f.getInsert()) .toString(); formula.setText(s); formula.setSelection(oldPos + f.getOffset()); } }; /** * This is the action listener, avoiding to create one for each action. */ final private OnClickListener actionClickListener = new OnClickListener() { @Override public void onClick(View v) { final Action curAct = ((ActionView) v).getAction(); final int len = formula.length(); final int selLeft = formula.getSelectionStart(); final int selRght = formula.getSelectionEnd(); final int oneLeft = (selLeft <= 0) ? selLeft : selLeft - 1; final int oneRght = (selRght >= len - 1) ? selRght : selRght + 1; // ~~~ one word left and right final int oneWordRight, oneWordLeft; { // TODO make this correct final CharSequence leftpart = formula.getText().subSequence(0, selLeft); final CharSequence rightpart = formula.getText().subSequence(selRght, len - 1); Matcher matcher = wordBoundary.matcher(rightpart); int onerightmatchtmp; try { onerightmatchtmp = matcher.end(); } catch (IllegalStateException ise) { onerightmatchtmp = oneRght; } final int onerightmatch = onerightmatchtmp; final Matcher leftmatch = wordBoundary.matcher(leftpart); oneWordRight = (onerightmatch >= len - 1) ? len - 1 : onerightmatch; int oneleftmatchtmp; try { oneleftmatchtmp = leftmatch.start(leftmatch.groupCount() - 1); } catch (IllegalStateException ise) { oneleftmatchtmp = oneLeft; } final int oneleftmatch = oneleftmatchtmp; oneWordLeft = (oneleftmatch >= 0) ? oneleftmatch : 0; } // ~~~ end of one word left and right final Editable formulaEdit = formula.getEditableText(); switch (curAct) { case Linebreak: // TODO get the system specific linebreak formulaEdit.insert(selRght, "\n"); break; case Del: if (selLeft == selRght) { formulaEdit.delete(selLeft, oneRght); } else { formulaEdit.delete(selLeft, selRght); } break; case DelLeftOneChar: formulaEdit.delete(oneLeft, selRght); break; case DelRightOneChar: formulaEdit.delete(selLeft, oneRght); break; case SelLeftOneChar: formula.setSelection(oneLeft, selRght); break; case SelRightOneChar: formula.setSelection(selLeft, oneRght); break; case SelLeftOneWord: formula.setSelection(oneWordLeft, selRght); break; case SelRightOneWord: formula.setSelection(selLeft, oneWordRight); break; default: String msg = "ERROR: undefined action " + curAct.toString(); Toast.makeText(FunctionEditor.this, msg, Toast.LENGTH_SHORT).show(); } formula.setText(formulaEdit.toString()); } }; } /** * utf8 arrows for navigation and actions like deleting. * <a href="http://en.wikipedia.org/wiki/Arrow_%28symbol%29">Arrows at * Wikipedia</a> */ enum Action { // "\u00b6" // pilcrow sign Linebreak("\u21b2"), // down left for linebreak Del("\u21af"), // flash light arrow LeftMoveWordBoundary("\u219e"), // left two heads RightMoveWordBoundary("\u21a0"), // right two heads ChangeCase("\u21c5"), // up down double DelLeftOneChar("\u21dc"), // left wriggle DelLeftRightWordBoundary("\u21ad"), // left right wriggle DelRightOneChar("\u21dd"), // right wriggle SelLeftOneChar("\u21e6"), // left thick SelRightOneChar("\u21e8"), // right thick SelLeftOneWord("\u21da"), // left triple SelRightOneWord("\u21db"); // right triple final private String sign; Action(String sign) { this.sign = sign; } @Override public String toString() { return sign; } } /** * Defines the special keys to insert functions. <br> * The argument <code>insert</code> might contain the special character "|" * (pipe symbol) which stands for the insert sign. Otherwise, just specify the * <code>offset</code> parameter. */ enum Key { // zero("0"), one("1"), two("2"), three("3"), four("4"), // // five("5"), six("6"), seven("7"), eight("8"), nine("9"), // sin("sin"), cos("cos"), Tan("tan"), // trig asin("asin"), acos("acos"), atan("atan"), // trig inv infinity("\u221e", "oo"), // special integrate("\u222b", "integrate(|, x)"), diff("dx", "diff(|, x)"), // calc limit("limit", "limit(|, x = 0)"); final private String display, insert; final private int offset; Key(String display, boolean append) { this(display, append ? display + "(|)" : display); } Key(String display) { this(display, true); } Key(String display, String insert) { this(display, insert, 0); } Key(String display, String insert, int offset) { this.display = display; this.insert = insert; this.offset = offset; } /** * @return the relative position where the cursor should be placed from the * current position. * i.e. if we have the string AB|CD with the cursor between B and C, * and we insert XY with an offset of 2, we should end up with * ABXY|CD. */ final int getOffset() { if (offset > 0) { return offset; } int idx = insert.indexOf("|"); if (idx >= 0) { return idx; } return insert.length(); } /** * @return the string that should actually be inserted */ final String getInsert() { return insert.replaceAll("\\|", ""); } @Override final public String toString() { return display; } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * This is our background service to keep a connection with a Sage server. It is * designed to connect to <b>one</b> server with given credentials, or if there * are non, does not connect. If keepAlive is true, it tries to reconnect if the * connection is broken. After a certain time of inactivity it assumes that it * is no longer needed and disconnects. * * @author Harald Schilly */ final public class SageConnection extends Service { final static String TAG = SageConnection.class.getSimpleName(); public final static int DISCONNECTED = 0, CONNECTING = 1, CONNECTED = 2; private int status = SageConnection.DISCONNECTED; private Timer timerCalc, timerConn; private boolean keepAlive = true; private boolean showNotification = false; private List<CalculationListener> calcListeners = new ArrayList<CalculationListener>(2); private ConnectionListener connListener = null; private CountDownLatch countdown = null; private boolean killMeIsScheduled = false; // connection credentials private Server server = null; // TODO once the api and interface is settled, we switch to a longer // queue where all commands are executed in given order. beware, all // interacts need to behave nicely and skip commands if a calculation // is currently running. /** * work queue, restricted to size 1 for now ... so there is only 0 or 1 * {@link Work} object in the queue. */ final private LinkedBlockingQueue<Calculation> work = new LinkedBlockingQueue<Calculation>(1); final private AtomicBoolean calcRunning = new AtomicBoolean(false); public SageConnection() { super(); startConnection(); } /** * This task is repeated by the timer and checks if the connection to the Sage * server is still alive. */ final private TimerTask checkConnectedTask = new TimerTask() { @Override final public void run() { // TODO this task should not take longer than 10 secs. try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } status = (int) (Math.random() * 3); updateConnectonListener(status); } }; /** * This task is started once and runs forever until it is interrupted. It * blocks on the {@link work} queue and waits for new {@link Work} objects to * submit to the Sage server. TODO Some intelligence when there is no * connection. */ final private TimerTask calculationTask = new TimerTask() { private Calculation c; @Override final public void run() { while (true) { try { c = work.take(); } catch (InterruptedException e1) { Log.w(TAG, "Calculation Task interrupted!"); Thread.currentThread().interrupt(); return; } // blocking set calc flag to true before starting calculation calcRunning.set(true); // bogus calculation try { Thread.sleep(500 + (long) (Math.random() * 500.0)); } catch (InterruptedException e) { calcRunning.set(false); Thread.currentThread().interrupt(); return; } int i; try { i = 2 * Integer.parseInt(c.getCode()); } catch (NumberFormatException nfe) { i = 42; } c.setResult(Integer.toString(i)); // end bogus calculation // after calculation, set calc flag to false calcRunning.set(false); // if not null, killMe wants me to count down. if (countdown != null) { countdown.countDown(); } // notify listeners updateListenersResult(c); showNotification(c.getElapsed() + " " + c.getResult()); } } }; /** * This is called when the service is about to shut down or is not needed any * more. It checks if there is still some work to do and waits for it to * finish. */ final private TimerTask killMe = new TimerTask() { @Override final public void run() { killMeIsScheduled = true; // TODO wait for calculation to finish try { while (work.size() > 0 && calcRunning.get()) { // TODO that's not correct, because we will not get the remaining // calculations countdown = new CountDownLatch(1); countdown.await(); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } finally { Log.i(TAG, "stopSelf called by killMe TimerTask"); stopSelf(); } } }; /** * used for reading the content of HTTP responses */ final private StringBuilder calcSb = new StringBuilder(); /** * This stores the session ID. If null, we do not have a session. */ final private AtomicReference<String> sessionID = new AtomicReference<String>(); /** * Communicate with the Sage server. This contains the HTTP communication and * parsing of the returned data. * * @throws CalculationException */ final private String doCalculation(String input) throws CalculationException { String answer = "<error>"; if (sessionID.equals(null)) { // we don't have a session sessionID.set(doEstablishSession()); } // HTTP GET String queryCalc = server + "/simple/compute?" + "session=" + sessionID.get() + "&code=" + Uri.encode(input); // for more read doEstablishSession() // HTTP POST Example HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httpPost = new HttpPost(server + "/simple/compute"); // POST Payload List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("session", sessionID.get())); nameValuePairs.add(new BasicNameValuePair("code", input)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Send to server HttpResponse response = httpclient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status != 200) { // 200 is HTTP OK } // headers, i.e. check if Sage actually did something, eventually retry to // fetch the calculation later, ... Header[] sageStatus = response.getHeaders("SAGE-STATUS"); String sageStatusValue = sageStatus[0].getValue(); // response content, here should be the actual answer answer = readContent(response); } catch (Exception ex) { // TODO: explain what has happened and properly handle exception throw new CalculationException("unable to do a calculation"); } finally { // TODO I think it should be possible to reuse the httpclient object ... httpclient.getConnectionManager().shutdown(); } return answer; } /** * Helper to read the HTTP content of a response and return it as a String * * @throws IOException */ private String readContent(HttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); // The following just copies the content into the StringBuilder BufferedReader reader = new BufferedReader(new InputStreamReader(in)); calcSb.setLength(0); for (String line; (line = reader.readLine()) != null;) { calcSb.append(line + "\n"); // TODO get system specific newline } in.close(); return calcSb.toString(); } /** * Communicate with the Sage to establish a session. * * @return if true, a session has been established * @throws CalculationException */ final private String doEstablishSession() throws CalculationException { if (server == null) { throw new CalculationException("unable to establish a session"); } HttpClient httpclient = new DefaultHttpClient(); try { // HTTP GET String querySession = server + "/simple/login?username=" + server.username + "&password=" + server.password; HttpGet httpget = new HttpGet(querySession); HttpResponse response = httpclient.execute(httpget); String answer = readContent(response); String[] data = answer.split("___S_A_G_E___"); JSONObject json = new JSONObject(data[0]); return json.getString("session"); } catch (Exception ex) { // TODO: explain what has happened and properly handle exception throw new CalculationException("unable to establish a session"); } finally { // TODO I think it should be possible to reuse the httpclient object ... httpclient.getConnectionManager().shutdown(); } } /** * Defines a mapping of what to do when a client issues an action or requests * a calculation. */ final private CalculationAPI.Stub apiEndpoint = new CalculationAPI.Stub() { @Override final public void addCalcListener(CalculationListener listener) throws RemoteException { synchronized (calcListeners) { calcListeners.add(listener); } } @Override final public void removeCalcListener(CalculationListener listener) throws RemoteException { synchronized (calcListeners) { calcListeners.remove(listener); } } @Override final public void addConnListener(ConnectionListener l) throws RemoteException { connListener = l; } @Override final public void removeConnListener(ConnectionListener l) throws RemoteException { connListener = null; } @Override final public void stopService() throws RemoteException { killConnection(); stopSelf(); } @Override final public void killConnection() throws RemoteException { killConnection(); } @Override final public int getStatus() throws RemoteException { return status; } @Override final public void setServer(Server server) throws RemoteException { SageConnection.this.server = server; } @Override final public boolean getKeepAlive() throws RemoteException { return keepAlive; } @Override final public void setKeepAlive(boolean keepAlive) throws RemoteException { SageConnection.this.keepAlive = keepAlive; } /** * background service API hook to start and enqueue a new * {@link Calculation} * * @return the unique ID of the new Calculation */ @Override final public int calculate(String code) throws RemoteException { Calculation c = new Calculation(); c.setCode(code); c.setStartTime(System.currentTimeMillis()); boolean added = false; while (!added) { added = work.offer(c); if (!added) { work.clear(); } } return c.getId(); } @Override final public boolean isCalculationRunning() throws RemoteException { return calcRunning.get(); } @Override final public void clearQueue() throws RemoteException { work.clear(); } @Override final public int getQueueSize() throws RemoteException { return work.size(); } @Override final public void setShowNotification(boolean b) throws RemoteException { showNotification = b; } }; /** * Tell listeners about the connection * * @param b */ final private void updateConnectonListener(int s) { synchronized (connListener) { if (connListener != null) { try { connListener.handleConnectionState(s); } catch (RemoteException e) { Log.w(TAG, "Failed to notify listener about ConnectionState: " + s, e); // TODO I'm no longer needed, except there is a calculation running // make sure that it is only called once (we are synchronized in here) if (!killMeIsScheduled) { timerConn.schedule(killMe, 0); } } } } } /** * Tell listeners about a result, which is stored in the {@link Calculation} * object. * * @param c */ final private void updateListenersResult(Calculation c) { synchronized (calcListeners) { for (Iterator<CalculationListener> li = calcListeners.iterator(); li.hasNext();) { CalculationListener l = li.next(); try { if (l.handleCalculationResult(c)) { return; // true means calculation was consumed } } catch (RemoteException e) { Log.i(TAG, "Failed to notify listener " + l + " - removing", e); li.remove(); } } } } /** * Establish a new connection. * <ol> * <li>check if we have credentials (otherwise send something back to client * ... NYI)</li> * <li>get a session key and store it locally. each subsequent request needs * it</li> * <li>start a periodic async task to check if the connection is still alive</li> * <li>tell the calculation task that it can start doing work</li> * </ol> */ final private void startConnection() { // TODO start actual connection timerCalc = new Timer("Calculation"); timerCalc.schedule(calculationTask, 0); timerConn = new Timer("Connection"); // check connection every 10 secs, with a delay of 1 sec. // it is NOT fixed rate which means that the starting time does not // depend on the execution time. // TODO set this to 30 secs timerConn.schedule(checkConnectedTask, 1000, 1 * 1000); } /** * Kill connection, especially tell Sage goodbye and to kill its current * session and session key. */ final private void killConnection() { // if connection exists, kill it if (timerCalc != null) { calculationTask.cancel(); timerCalc.cancel(); timerCalc = null; } if (timerConn != null) { checkConnectedTask.cancel(); timerConn.cancel(); timerConn = null; } } /** * Server/Client binding mechanism, check if we are really called on the * correct intent. */ @Override final public IBinder onBind(Intent intent) { if (SageConnection.class.getName().equals(intent.getAction())) { return apiEndpoint; } else { return null; } } /** * */ @Override final public void onCreate() { super.onCreate(); // TODO some kind of reset? } /** * */ @Override final public void onDestroy() { super.onDestroy(); killConnection(); } /** * ID for the notification, unique in application service */ final private static int HELLO_ID = 10781; /** * the idea is to show a notification in androids main UI's * notification bar when the main app is currently closed. By clicking on the * notification the main UI is launched again and should show the result. */ final private void showNotification(String result) { if (!showNotification) { return; } // get system's notification manager String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); // what to show in the bar int icon = R.drawable.notification_icon; CharSequence tickerText = "Sage finished."; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); // cancel it after selecting notification.flags |= Notification.FLAG_AUTO_CANCEL; // notification content itself + intent for launching the main app Context context = getApplicationContext(); CharSequence contentTitle = "Sage Calculation finished."; String part = result.substring(0, Math.min(result.length(), 30)) + "..."; CharSequence contentText = "Result: " + part; Intent notificationIntent = new Intent(this, SageAndroid.class); // TODO somehow store an ID which interact should show the result. this // should probably be part of the original calculation. notificationIntent.putExtra("target", 0); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); // show it mNotificationManager.notify(HELLO_ID, notification); } } /** * A CalculationException describes the problem of a failed calculation. */ @SuppressWarnings("serial") final class CalculationException extends Exception { private Calculation c; public CalculationException(String msg) { super(msg); } /** * Creates a new CalculationException and attaches the {@link Calculation} c * to it. * * @param msg * @param c */ public CalculationException(String msg, Calculation c) { super(msg); this.c = c; } final Calculation getCalculation() { return c; } }
Java
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import org.sagemath.android.interacts.AbstractInteract; import org.sagemath.android.interacts.ExecuteCommand; import org.sagemath.android.interacts.Plot; import org.sagemath.android.interacts.SliderTest2; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.GestureDetector.OnGestureListener; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; import android.widget.AdapterView.OnItemSelectedListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Main Activity of the Sage Android application. * * @author Harald Schilly */ final public class SageAndroid extends Activity implements OnGestureListener { private static final int UI_STATE = 0; private static final int UI_OUTPUT = 1; @SuppressWarnings("unused") private static final int[] CONN_COL = new int[] { Color.RED, Color.YELLOW, Color.GREEN }; private LayoutInflater layoutInflater = null; TextView output = null; // , status = null; ViewFlipper vf = null; Animation inLeft, inRight, outLeft, outRight, fadeIn, fadeOut; // we talk with the sage connection service through its API private CalculationAPI api = null; /** * returns the CalculationAPI for the service (could be null) * * @return */ final public CalculationAPI getCalculationAPI() { return api; } final public Context getContext() { return SageAndroid.this; } private GestureDetector gestureDetector; // TODO remove it, just for development mockup private int stored_i = -1; private EditText txtFx; private AbstractInteract currentInteract = null; /** * Starting point of the whole Application: * <ol> * <li>We define an instance of {@link Global} and inject dependencies.</li> * <li>Start a background Service to handle the connection with Sage, i.e. * poll to keep it alive and wait for results. Details will depend on Sage's * Server API. From the perspective of this application, everything is done * via calls to the {@link CalculationAPI} and callbacks via * {@link CalculationListener}. UI updates happen in the local Handler.</li> * <li>There is a collection of "Interacts" to query the server in a certain * way. This is still unclear ...</li> * </ol> */ @Override final public void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_RIGHT_ICON); setContentView(R.layout.main); // store a reference to me globally, a bit hackish Global.setContext(this); // call the background service, we can call this as often as we want // the intent must match the intent-filter in the manifest Intent intent = new Intent(SageConnection.class.getName()); startService(intent); // the connection service does the wiring bindService(intent, sageConnnectionService, Context.BIND_AUTO_CREATE); // dynamic titlebar updateTitlebar(SageConnection.DISCONNECTED, ""); // locally store the ui objects output = (TextView) findViewById(R.id.output); // status = (TextView) findViewById(R.id.status); vf = (ViewFlipper) findViewById(R.id.MainVF); // load the animations inLeft = AnimationUtils.makeInAnimation(this, true); inRight = AnimationUtils.makeInAnimation(this, false); outLeft = AnimationUtils.makeOutAnimation(this, false); outRight = AnimationUtils.makeOutAnimation(this, true); fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out); fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_in); // registers the gesture detector with this view and ourself since we also // listen gestureDetector = new GestureDetector(this, this); layoutInflater = LayoutInflater.from(SageAndroid.this); Button testing = (Button) findViewById(R.id.btnTest); testing.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { api.setServer(new Server("http://www.bogusserver.org/", "admin", "password")); stored_i++; api.calculate(Long.toString(stored_i)); } catch (RemoteException re) { output.setText("calculate remote exeception: \n" + re); } } }); txtFx = (EditText) findViewById(R.id.txtFxTest); Button btnFxTest = (Button) findViewById(R.id.btnFxTest); btnFxTest.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SageAndroid.this, org.sagemath.android.fx.FunctionEditor.class); intent.putExtra("func", txtFx.getText().toString()); intent.putExtra("start", txtFx.getSelectionStart()); intent.putExtra("end", txtFx.getSelectionEnd()); startActivityForResult(intent, Global.FUNC_EDIT); } }); } /** * Listen to results from a started FunctionEditor activity. */ @Override final protected void onActivityResult(int requestCode, int resultCode, Intent data) { // See which child activity is calling us back. switch (requestCode) { case Global.FUNC_EDIT: if (resultCode == RESULT_OK) { Bundle bundle = data.getBundleExtra("data"); String func = bundle.getString("func"); Log.d(Global.TAG, "func = " + func); txtFx.setText(func); txtFx.setSelection(bundle.getInt("start"), bundle.getInt("end")); txtFx.requestFocus(); } default: break; } } /** * Helper * * @see wireButton */ final private void registerInteracts() { wireButton(R.id.btnActCmd, ExecuteCommand.class); wireButton(R.id.btnSlider, SliderTest2.class); wireButton(R.id.btnPlotInteract, Plot.class); wireButton(R.id.btnSystem, org.sagemath.android.interacts.System.class); } final private Map<Class<? extends AbstractInteract>, AbstractInteract> interactCache = new HashMap<Class<? extends AbstractInteract>, AbstractInteract>(); /** * Helper to wire buttons with interact views. * * @param id * @param interactView */ final private void wireButton(final int id, final Class<? extends AbstractInteract> clsInteract) { // we only accept classes that extend the {@link AbstractInteract} abstract // class and when the button is pressed, we either use a cached object or // instantiate a new one. // this postpones the instantiation as long as possible and when opening the // same interact again the current state is preserved. ((Button) findViewById(id)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AbstractInteract interact = null; if (!interactCache.containsKey(clsInteract)) { try { interact = clsInteract.newInstance(); interactCache.put(clsInteract, interact); } catch (Exception ex) { Log.d(Global.TAG, ex.getLocalizedMessage(), ex); } } else { interact = interactCache.get(clsInteract); interact.reset(); } interact.addCalcListener(); showVF(interact); } }); } /** * Helper to update the Titlebar. */ final private void updateTitlebar(int status, String text) { // fyi, for more customization we need our own titlebar, that's possible setTitle(getString(R.string.app_name) + " " + text); // setTitleColor(CONN_COL[status]); switch (status) { case SageConnection.DISCONNECTED: setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON, R.drawable.icon_conn_0); break; case SageConnection.CONNECTING: setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON, R.drawable.icon_conn_1); break; case SageConnection.CONNECTED: setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON, R.drawable.icon_conn_2); break; default: Toast.makeText(this, "Unknown State " + status, Toast.LENGTH_SHORT).show(); } } /** * for the button's onClick, to show the view * * @param v */ final private void showVF(AbstractInteract ai) { vf.setInAnimation(fadeIn); vf.setOutAnimation(fadeOut); if (currentInteract != null) { currentInteract.removeCalcListener(); } currentInteract = ai; // make sure that there is only the main view for (int cc; (cc = vf.getChildCount()) >= 2;) { // TODO unregister calculation listener vf.removeViewAt(cc - 1); } // add the interact and show it vf.addView(ai.getView()); vf.showNext(); } /** * called when application is restored - that's not persistence! */ @Override final protected void onRestoreInstanceState(Bundle icicle) { stored_i = icicle.getInt("i", 0); } /** * called when application should save it's current state - that's not * persistence! */ @Override final protected void onSaveInstanceState(Bundle icicle) { icicle.putInt("i", stored_i); } /** * Android lifecycle, we are back to front after a short break. */ @Override final protected void onResume() { super.onResume(); try { if (api != null) { // tell the service that we will see results on the screen api.setShowNotification(false); } } catch (RemoteException ex) { } } /** * Android lifecycle, we are currently hidden behind another window. */ @Override final protected void onPause() { super.onPause(); try { // tell the service to show notifications in the top bar if (api != null) { api.setShowNotification(true); } } catch (RemoteException ex) { } } /** * Android OS destroys us */ @Override final protected void onDestroy() { super.onDestroy(); try { if (api != null) { api.setShowNotification(true); api.removeCalcListener(calcListener); } unbindService(sageConnnectionService); } catch (Throwable t) { // catch any issues, typical for destroy routines // even if we failed to destroy something, we need to continue // destroying Log.w(Global.TAG, "Failed to unbind from the service", t); } Log.i(Global.TAG, "onDestroy()"); } /** * this is called when the service is connected or disconnected. * we create the api interface here which is used to communicate with * the service. */ final private ServiceConnection sageConnnectionService = new ServiceConnection() { @Override final public void onServiceConnected(ComponentName name, IBinder service) { // that's how we get the client side of the IPC connection api = CalculationAPI.Stub.asInterface(service); Global.setCalculationAPI(api); try { api.setShowNotification(false); api.addConnListener(connListener); api.addCalcListener(calcListener); // TODO remove this below // vf.removeViewAt(vf.getChildCount() - 1); // vf.addView(interacts.getSliderTest()); } catch (RemoteException e) { Log.e(Global.TAG, "Failed to add listener", e); } Log.i(Global.TAG, "Service connection established"); registerInteracts(); } @Override final public void onServiceDisconnected(ComponentName name) { Log.i(Global.TAG, "Service connection closed: " + name.toShortString()); api = null; Global.setCalculationAPI(null); } }; /** * our little helper to update the ui via messages when updates happen on * other threads. it is bound to this thread and used for callbacks from the * service to the main application. */ final private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { msg.getData().getBoolean("status"); switch (msg.what) { case UI_STATE: updateTitlebar((Integer) msg.obj, ""); break; case UI_OUTPUT: output.setText("RECV: " + msg.obj); break; default: super.handleMessage(msg); } } }; /** * this is called by the remote service to tell us about the calculation * result by giving us back the {@link Calculation} object with hopefully * some content in the result field. */ final private CalculationListener.Stub calcListener = new CalculationListener.Stub() { @Override final public boolean handleCalculationResult(Calculation cr) throws RemoteException { handler.sendMessage(handler.obtainMessage(UI_OUTPUT, cr.getResult())); // false means that other listeners should also be informed about this return false; } }; /** * this is called by the remote service to tell us about the connection * state. */ final private ConnectionListener.Stub connListener = new ConnectionListener.Stub() { @Override final public void handleConnectionState(int i) throws RemoteException { handler.sendMessage(handler.obtainMessage(UI_STATE, i)); } }; /** * This is part of the App lifecycle. It is called when the OS wants to get * rid of us. Make the transient data persistent now! */ @Override final protected void onStop() { super.onStop(); Global.saveSettings(); } /** * This is called when the dedicated back button is pressed. */ @Override final public void onBackPressed() { flipViewFlipper(Global.FLIP); } /** * This either displays the last interact again (if there is a * current one) or just goes back to the main view in the view * flipper. */ final private void flipViewFlipper(final int dir) { // check if there is something to show if (currentInteract != null) { // child 0 is main view if (vf.getDisplayedChild() == 0) { if (dir == Global.FLIP || dir == Global.RIGHT) { vf.setInAnimation(inRight); vf.setOutAnimation(outLeft); vf.setDisplayedChild(1); } } else { // case when interact is currently displayed if (dir == Global.FLIP || dir == Global.LEFT) { vf.setInAnimation(inLeft); vf.setOutAnimation(outRight); vf.setDisplayedChild(0); } } } } /** * This is called when we press the menu button on the device. * * @see res/menu/main_menu.xml */ @Override final public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } /** * This is called a button in the options menu is pressed. * This works when showing the main menu and when showing * an interact. The "id" is used to identify the selection. */ @Override final public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.MenuSettingsDialog: showSettingsDialog(); return true; case R.id.MenuQuit: this.finish(); return true; default: return super.onOptionsItemSelected(item); } } /** * called via the menu to show the settings dialog */ final private void showSettingsDialog() { // TODO encapsulate this in it's own class. final View textEntryView = layoutInflater.inflate(R.layout.settings_dialog, null); final AlertDialog dlg = new AlertDialog.Builder(SageAndroid.this) .setTitle("Server Credentials").setView(textEntryView) .setPositiveButton("Connect", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(SageAndroid.this, "Connect ...", Toast.LENGTH_LONG).show(); AlertDialog d = (AlertDialog) dialog; EditText pe = (EditText) d.findViewById(R.id.PasswordEdit); EditText ue = (EditText) d.findViewById(R.id.UsernameEdit); EditText se = (EditText) d.findViewById(R.id.ServerEdit); Server s = new Server(se.getText().toString(), ue.getText().toString(), pe.getText() .toString()); Global.setServer(s); Global.saveSettings(); } }) .setNeutralButton("Test", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { // dialog.dismiss(); ProgressDialog pd = new ProgressDialog(getContext(), ProgressDialog.STYLE_SPINNER); pd.setMessage("Connecting..."); pd.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); pd.show(); } }) .setNegativeButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogMain, int whichButton) { final AlertDialog confirmDelete = new AlertDialog.Builder(getContext()) // .setIcon(android.R.drawable.ic_dialog_alert) // .setTitle("Confirm Delete") // .setMessage("Really delete " + Global.getServer().server) // .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Global.servers.remove(Global.getServer()); } }) // .setNegativeButton("No", null).show(); } }).create(); dlg.show(); // ~~~ Set User/Password EditText ue = (EditText) dlg.findViewById(R.id.UsernameEdit); ue.setText(Global.getUser()); EditText pe = (EditText) dlg.findViewById(R.id.PasswordEdit); pe.setText(Global.getPassword()); // ~~~ start Server Spinner final Spinner serverSpinner = (Spinner) dlg.findViewById(R.id.ServerSpinner); final ArrayList<Server> serverList = new ArrayList<Server>(Global.servers); final ArrayAdapter<Server> adapter = new ArrayAdapter<Server>(this, android.R.layout.simple_spinner_item, serverList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); serverSpinner.setAdapter(adapter); if (Global.getServer() != null) { int selidx = -1; for (int i = 0; i < adapter.getCount(); i++) { if (Global.getServer().equals(adapter.getItem(i))) { selidx = i; break; } } if (selidx < 0) { adapter.add(Global.getServer()); serverSpinner.setSelection(adapter.getCount()); } else { serverSpinner.setSelection(selidx); } } serverSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override final public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { final Server s = serverList.get(position); Global.setServer(s); EditText se = (EditText) dlg.findViewById(R.id.ServerEdit); se.setText(s.server); } @Override final public void onNothingSelected(AdapterView<?> arg0) { } }); // ~~~~ end Server Spinner } // ~~~~ Touch Event business for the OnGestureListener ~~~~ @Override final public boolean onTouchEvent(MotionEvent event) { return gestureDetector.onTouchEvent(event); } @Override final public boolean onDown(MotionEvent e) { return false; } @Override final public boolean onFling(MotionEvent arg0, MotionEvent arg1, float dx, float dy) { // info: dx/dy is measured in pixel/second. that's not a distance. // silly threshold if (Math.hypot(dx, dy) > 100) { if (dx > 200 && Math.abs(dy) < 50) { // right flipViewFlipper(Global.RIGHT); } if (dx < -200 && Math.abs(dy) < 50) { // left flipViewFlipper(Global.LEFT); } } return true; } @Override final public void onLongPress(MotionEvent arg0) { } @Override final public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { return false; } @Override final public void onShowPress(MotionEvent arg0) { } @Override final public boolean onSingleTapUp(MotionEvent arg0) { return false; } }
Java
/** * Copyright (C) 2011, Karsten Priegnitz * * Permission to use, copy, modify, and distribute this piece of software * for any purpose with or without fee is hereby granted, provided that * the above copyright notice and this permission notice appear in the * source code of all copies. * * It would be appreciated if you mention the author in your change log, * contributors list or the like. * * @author: Karsten Priegnitz * @see: http://code.google.com/p/android-change-log/ */ package sheetrock.panda.changelog; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; import android.webkit.WebView; import org.sagemath.droid.R; public class ChangeLog { private final Context context; private String lastVersion, thisVersion; // this is the key for storing the version name in SharedPreferences private static final String VERSION_KEY = "PREFS_VERSION_KEY"; /** * Constructor * * Retrieves the version names and stores the new version name in * SharedPreferences * * @param context */ public ChangeLog(Context context) { this(context, PreferenceManager.getDefaultSharedPreferences(context)); } /** * Constructor * * Retrieves the version names and stores the new version name in * SharedPreferences * * @param context * @param sp the shared preferences to store the last version name into */ public ChangeLog(Context context, SharedPreferences sp) { this.context = context; // get version numbers this.lastVersion = sp.getString(VERSION_KEY, ""); Log.d(TAG, "lastVersion: " + lastVersion); try { this.thisVersion = context.getPackageManager().getPackageInfo( context.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { this.thisVersion = "?"; Log.e(TAG, "could not get version name from manifest!"); e.printStackTrace(); } Log.d(TAG, "appVersion: " + this.thisVersion); // save new version number to preferences SharedPreferences.Editor editor = sp.edit(); editor.putString(VERSION_KEY, this.thisVersion); editor.commit(); } /** * @return The version name of the last installation of this app (as * described in the former manifest). This will be the same as * returned by <code>getThisVersion()</code> the second time * this version of the app is launched (more precisely: the * second time ChangeLog is instantiated). * @see AndroidManifest.xml#android:versionName */ public String getLastVersion() { return this.lastVersion; } /** * @return The version name of this app as described in the manifest. * @see AndroidManifest.xml#android:versionName */ public String getThisVersion() { return this.thisVersion; } /** * @return <code>true</code> if this version of your app is started the * first time */ public boolean firstRun() { return ! this.lastVersion.equals(this.thisVersion); } /** * @return <code>true</code> if your app is started the first time ever. * Also <code>true</code> if your app was deinstalled and * installed again. */ public boolean firstRunEver() { return "".equals(this.lastVersion); } /** * @return an AlertDialog displaying the changes since the previous * installed version of your app (what's new). */ public AlertDialog getLogDialog() { return this.getDialog(false); } /** * @return an AlertDialog with a full change log displayed */ public AlertDialog getFullLogDialog() { return this.getDialog(true); } private AlertDialog getDialog(boolean full) { WebView wv = new WebView(this.context); wv.setBackgroundColor(0); // transparent // wv.getSettings().setDefaultTextEncodingName("utf-8"); wv.loadDataWithBaseURL(null, this.getLog(full), "text/html", "UTF-8", null); AlertDialog.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) builder = new AlertDialog.Builder(this.context, AlertDialog.THEME_HOLO_DARK); else builder = new AlertDialog.Builder(this.context); builder.setTitle(context.getResources().getString(full ? R.string.changelog_full_title : R.string.changelog_title)) .setView(wv) .setCancelable(false) .setPositiveButton( context.getResources().getString( R.string.changelog_ok_button), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); return builder.create(); } /** * @return HTML displaying the changes since the previous * installed version of your app (what's new) */ public String getLog() { return this.getLog(false); } /** * @return HTML which displays full change log */ public String getFullLog() { return this.getLog(true); } /** modes for HTML-Lists (bullet, numbered) */ private enum Listmode { NONE, ORDERED, UNORDERED, }; private Listmode listMode = Listmode.NONE; private StringBuffer sb = null; private static final String EOCL = "END_OF_CHANGE_LOG"; private String getLog(boolean full) { // read changelog.txt file sb = new StringBuffer(); try { InputStream ins = context.getResources().openRawResource(R.raw.changelog); BufferedReader br = new BufferedReader(new InputStreamReader(ins)); String line = null; boolean advanceToEOVS = false; // if true: ignore further version sections while ((line = br.readLine()) != null) { line = line.trim(); char marker = line.length() > 0 ? line.charAt(0) : 0; if (marker == '$') { // begin of a version section this.closeList(); String version = line.substring(1).trim(); // stop output? if (! full) { if (this.lastVersion.equals(version)) { advanceToEOVS = true; } else if (version.equals(EOCL)) { advanceToEOVS = false; } } } else if (! advanceToEOVS) { switch (marker) { case '%': // line contains version title this.closeList(); sb.append("<div class='title'>" + line.substring(1).trim() + "</div>\n"); break; case '_': // line contains version title this.closeList(); sb.append("<div class='subtitle'>" + line.substring(1).trim() + "</div>\n"); break; case '!': // line contains free text this.closeList(); sb.append("<div class='freetext'>" + line.substring(1).trim() + "</div>\n"); break; case '#': // line contains numbered list item this.openList(Listmode.ORDERED); sb.append("<li>" + line.substring(1).trim() + "</li>\n"); break; case '*': // line contains bullet list item this.openList(Listmode.UNORDERED); sb.append("<li>" + line.substring(1).trim() + "</li>\n"); break; default: // no special character: just use line as is this.closeList(); sb.append(line + "\n"); } } } this.closeList(); br.close(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } private void openList(Listmode listMode) { if (this.listMode != listMode) { closeList(); if (listMode == Listmode.ORDERED) { sb.append("<div class='list'><ol>\n"); } else if (listMode == Listmode.UNORDERED) { sb.append("<div class='list'><ul>\n"); } this.listMode = listMode; } } private void closeList() { if (this.listMode == Listmode.ORDERED) { sb.append("</ol></div>\n"); } else if (this.listMode == Listmode.UNORDERED) { sb.append("</ul></div>\n"); } this.listMode = Listmode.NONE; } private static final String TAG = "ChangeLog"; /** * manually set the last version name - for testing purposes only * @param lastVersion */ void setLastVersion(String lastVersion) { this.lastVersion = lastVersion; } }
Java
package org.sagemath.singlecellserver; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.text.DateFormat; import java.util.LinkedList; import java.util.ListIterator; import java.util.Timer; import java.util.UUID; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.sagemath.singlecellserver.SageSingleCell.SageInterruptedException; import android.text.format.Time; import android.util.Log; public class CommandRequest extends Command { private static final String TAG = "CommandRequest"; long time = System.currentTimeMillis(); private int SLEEP_BEFORE_TRY = 20; private boolean error = false; public CommandRequest() { super(); } public CommandRequest(UUID session) { super(session); } public JSONObject toJSON() throws JSONException { JSONObject header = new JSONObject(); header.put("session", session.toString()); header.put("msg_id", msg_id.toString()); JSONObject result = new JSONObject(); result.put("header", header); return result; } protected void sendRequest(SageSingleCell.ServerTask server) { CommandReply reply; try { HttpResponse httpResponse = server.postEval(toJSON()); processInitialReply(httpResponse); return; } catch (JSONException e) { reply = new HttpError(this, e.getLocalizedMessage()); } catch (ClientProtocolException e) { reply = new HttpError(this, e.getLocalizedMessage()); } catch (IOException e) { reply = new HttpError(this, e.getLocalizedMessage()); } catch (SageInterruptedException e) { reply = new HttpError(this, "Interrupted on user request"); } error = true; server.addReply(reply); } public StatusLine processInitialReply(HttpResponse response) throws IllegalStateException, IOException, JSONException { InputStream outputStream = response.getEntity().getContent(); String output = SageSingleCell.streamToString(outputStream); outputStream.close(); System.out.println("output = " + output); JSONObject outputJSON = new JSONObject(output); if (outputJSON.has("session_id")) session = UUID.fromString(outputJSON.getString("session_id")); return response.getStatusLine(); } public void receiveReply(SageSingleCell.ServerTask server) { sendRequest(server); if (error) return; long timeEnd = System.currentTimeMillis() + server.timeout(); int count = 0; while (System.currentTimeMillis() < timeEnd) { count++; LinkedList<CommandReply> result = pollResult(server); // System.out.println("Poll got "+ result.size()); ListIterator<CommandReply> iter = result.listIterator(); while (iter.hasNext()) { CommandReply reply = iter.next(); timeEnd += reply.extendTimeOut(); server.addReply(reply); } if (error) return; if (!result.isEmpty() && (result.getLast().terminateServerConnection())) return; try { Thread.sleep(count*SLEEP_BEFORE_TRY); } catch (InterruptedException e) {} } error = true; server.addReply(new HttpError(this, "Timeout")); } private LinkedList<CommandReply> pollResult(SageSingleCell.ServerTask server) { LinkedList<CommandReply> result = new LinkedList<CommandReply>(); try { int sequence = server.result.size(); result.addAll(pollResult(server, sequence)); return result; } catch (JSONException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (ClientProtocolException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (IOException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (URISyntaxException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (SageInterruptedException e) { CommandReply reply = new HttpError(this, "Interrupted on user request"); result.add(reply); } error = true; return result; } private LinkedList<CommandReply> pollResult(SageSingleCell.ServerTask server, int sequence) throws JSONException, IOException, URISyntaxException, SageInterruptedException { LinkedList<CommandReply> result = new LinkedList<CommandReply>(); try { Thread.sleep(SLEEP_BEFORE_TRY); } catch (InterruptedException e) { Log.e(TAG, e.getLocalizedMessage()); return result; } HttpResponse response = server.pollOutput(this, sequence); error = (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK); HttpEntity entity = response.getEntity(); InputStream outputStream = entity.getContent(); String output = SageSingleCell.streamToString(outputStream); outputStream.close(); //output = output.substring(7, output.length()-2); // strip out "jQuery("...")" System.out.println("output = " + output); JSONObject outputJSON = new JSONObject(output); if (!outputJSON.has("content")) return result; JSONArray content = outputJSON.getJSONArray("content"); for (int i=0; i<content.length(); i++) { JSONObject obj = content.getJSONObject(i); CommandReply command = CommandReply.parse(obj); result.add(command); if (command instanceof DataFile) { DataFile file = (DataFile)command; file.downloadFile(server); } else if (command instanceof HtmlFiles) { HtmlFiles file = (HtmlFiles)command; file.downloadFile(server); } } return result; } public String toLongString() { JSONObject json; try { json = toJSON(); } catch (JSONException e) { return e.getLocalizedMessage(); } JSONWriter writer = new JSONWriter(); writer.write(json.toString()); //try { // json.write(writer); //} catch (JSONException e) { // return e.getLocalizedMessage(); //} StringBuffer str = writer.getBuffer(); return str.toString(); } }
Java
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; /* * * jQuery({ * "content": [{ * "parent_header": { * "username": "", "msg_id": "749529bd-bcfe-43a7-b660-2cea20df3f32", * "session": "7af9a99a-2a0d-438f-8576-5e0bd853501a"}, * "msg_type": "extension", * "sequence": 0, * "output_block": null, * "content": { * "content": { * "interact_id": "8157151862156143292", * "layout": {"top_center": ["n"]}, * "update": {"n": ["n"]}, * "controls": { * "n": { * "ncols": null, * "control_type": "selector", * "raw": true, * "default": 0, * "label": null, * "nrows": null, * "subtype": "list", * "values": 10, "width": "", * "value_labels": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]}}}, * "msg_type": "interact_prepare"}, * "header": {"msg_id": "4744042977225053037"} * }, { * "parent_header": { * "username": "", * "msg_id": "749529bd-bcfe-43a7-b660-2cea20df3f32", * "session": "7af9a99a-2a0d-438f-8576-5e0bd853501a"}, * "msg_type": "stream", "sequence": 1, "output_block": "8157151862156143292", * "content": {"data": "0\n", "name": "stdout"}, "header": {"msg_id": "7423072463567901439"}}, {"parent_header": {"username": "", "msg_id": "749529bd-bcfe-43a7-b660-2cea20df3f32", "session": "7af9a99a-2a0d-438f-8576-5e0bd853501a"}, "msg_type": "execute_reply", "sequence": 2, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "1900046197361249484"}}]}) * * */ public class Interact extends CommandOutput { private final static String TAG = "Interact"; private final String id; protected JSONObject controls, layout; protected Interact(JSONObject json) throws JSONException { super(json); JSONObject content = json.getJSONObject("content").getJSONObject("content"); id = content.getString("interact_id"); controls = content.getJSONObject("controls"); layout = content.getJSONObject("layout"); } public long extendTimeOut() { return 60 * 1000; } public boolean isInteract() { return true; } public String getID() { return id; } public String toString() { return "Prepare interact id=" + getID(); } public JSONObject getControls() { return controls; } public JSONObject getLayout() { return layout; } } /* HTTP/1.1 200 OK Server: nginx/1.0.11 Date: Tue, 10 Jan 2012 21:03:24 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 1225 jQuery150664064213167876_1326208736019({"content": [{ "parent_header": {"username": "", "msg_id": "f0826b78-7aaf-4eea-a5ce-0b10d24c5888", "session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2"}, "msg_type": "extension", "sequence": 0, "output_block": null, "content": {"content": {"interact_id": "5455242645056671226", "layout": {"top_center": ["n"]}, "update": {"n": ["n"]}, "controls": {"n": {"control_type": "slider", "raw": true, "default": 0.0, "step": 0.40000000000000002, "label": null, "subtype": "continuous", "range": [0.0, 100.0], "display_value": true}}}, "msg_type": "interact_prepare"}, "header": {"msg_id": "8880643058896313398"}}, { "parent_header": {"username": "", "msg_id": "f0826b78-7aaf-4eea-a5ce-0b10d24c5888", "session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2"}, "msg_type": "stream", "sequence": 1, "output_block": "5455242645056671226", "content": {"data": "0\n", "name": "stdout"}, "header": {"msg_id": "8823336185428654730"}}, {"parent_header": {"username": "", "msg_id": "f0826b78-7aaf-4eea-a5ce-0b10d24c5888", "session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2"}, "msg_type": "execute_reply", "sequence": 2, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "1224514542068124881"}}]}) POST /eval?callback=jQuery150664064213167876_1326208736022 HTTP/1.1 Host: sagemath.org:5467 Connection: keep-alive Content-Length: 368 Origin: http://sagemath.org:5467 x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7 content-type: application/x-www-form-urlencoded accept: text/javascript, application/javascript, q=0.01 Referer: http://sagemath.org:5467/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,fr;q=0.6,de;q=0.4,ja;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.3 Cookie: __utma=1.260350506.1306546516.1306612711.1306855420.3; HstCfa1579950=1313082432530; HstCmu1579950=1313082432530; c_ref_1579950=http:%2F%2Fboxen.math.washington.edu%2F; HstCla1579950=1314023965352; HstPn1579950=4; HstPt1579950=6; HstCnv1579950=2; HstCns1579950=2; __utma=138969649.2037720324.1307556884.1314205520.1326143310.11; __utmz=138969649.1314205520.10.6.utmcsr=en.wikipedia.org|utmccn=(referral)|utmcmd=referral|utmcct=/wiki/Sage_(mathematics_software) message={"parent_header":{},"header":{"msg_id":"45724d5f-01f8-4d9c-9eb0-d877a8880db8","session":"184c2fb0-1a8d-4c07-aee6-df85183d9ac2"},"msg_type":"execute_request","content":{"code":"_update_interact('5455242645056671226',control_vals=dict(n=23.6,))","sage_mode":true}} GET /output_poll?callback=jQuery150664064213167876_1326208736025&computation_id=184c2fb0-1a8d-4c07-aee6-df85183d9ac2&sequence=3&_=1326229408735 HTTP/1.1 Host: sagemath.org:5467 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7 accept: text/javascript, application/javascript,; q=0.01 Referer: http://sagemath.org:5467/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,fr;q=0.6,de;q=0.4,ja;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: __utma=1.260350506.1306546516.1306612711.1306855420.3; HstCfa1579950=1313082432530; HstCmu1579950=1313082432530; c_ref_1579950=http%3A%2F%2Fboxen.math.washington.edu%2F; HstCla1579950=1314023965352; HstPn1579950=4; HstPt1579950=6; HstCnv1579950=2; HstCns1579950=2; __utma=138969649.2037720324.1307556884.1314205520.1326143310.11; __utmz=138969649.1314205520.10.6.utmcsr=en.wikipedia.org|utmccn=(referral)|utmcmd=referral|utmcct=/wiki/Sage_(mathematics_software) HTTP/1.1 200 OK Server: nginx/1.0.11 Date: Tue, 10 Jan 2012 21:03:29 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 618 jQuery150664064213167876_1326208736025({"content": [{"parent_header": {"session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2", "msg_id": "45724d5f-01f8-4d9c-9eb0-d877a8880db8"}, "msg_type": "stream", "sequence": 3, "output_block": "5455242645056671226", "content": {"data": "23.6000000000000\n", "name": "stdout"}, "header": {"msg_id": "514409474887099253"}}, {"parent_header": {"session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2", "msg_id": "45724d5f-01f8-4d9c-9eb0-d877a8880db8"}, "msg_type": "execute_reply", "sequence": 4, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "7283788905623826736"}}]}) */
Java
package org.sagemath.singlecellserver; import java.util.UUID; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; /** * The base class for a server reply * * @author vbraun * */ public class CommandReply extends Command { private final static String TAG = "CommandReply"; private JSONObject json; protected CommandReply(JSONObject json) throws JSONException { this.json = json; JSONObject parent_header = json.getJSONObject("parent_header"); session = UUID.fromString(parent_header.getString("session")); msg_id = UUID.fromString(parent_header.getString("msg_id")); } protected CommandReply(CommandRequest request) { session = request.session; msg_id = request.msg_id; } public String toString() { return "Command reply base class"; } public void prettyPrint() { prettyPrint(json); } /** * Extend the HTTP timetout receive timeout. This is for interacts to extend the timeout. * @return milliseconds */ public long extendTimeOut() { return 0; } public boolean isInteract() { return false; } /** * Whether to keep polling for more results after receiving this message * @return */ public boolean terminateServerConnection() { return false; } /** * Turn a received JSONObject into the corresponding Command object * * @return a new CommandReply or derived class */ protected static CommandReply parse(JSONObject json) throws JSONException { String msg_type = json.getString("msg_type"); JSONObject content = json.getJSONObject("content"); Log.d(TAG, "content = "+content.toString()); // prettyPrint(json); if (msg_type.equals("pyout")) return new PythonOutput(json); else if (msg_type.equals("display_data")) { JSONObject data = json.getJSONObject("content").getJSONObject("data"); if (data.has("text/filename")) return new DataFile(json); else return new DisplayData(json); } else if (msg_type.equals("stream")) return new ResultStream(json); else if (msg_type.equals("execute_reply")) { if (content.has("traceback")) return new Traceback(json); else return new ExecuteReply(json); } else if (msg_type.equals("extension")) { String ext_msg_type = content.getString("msg_type"); if (ext_msg_type.equals("session_end")) return new SessionEnd(json); if (ext_msg_type.equals("files")) return new HtmlFiles(json); if (ext_msg_type.equals("interact_prepare")) return new Interact(json); } throw new JSONException("Unknown msg_type"); } public String toLongString() { if (json == null) return "null"; JSONWriter writer = new JSONWriter(); writer.write(json.toString()); // try { // does not work on Android // json.write(writer); // } catch (JSONException e) { // return e.getLocalizedMessage(); // } StringBuffer str = writer.getBuffer(); return str.toString(); } /** * Whether the reply is a reply to the given request * @param request * @return boolean */ public boolean isReplyTo(CommandRequest request) { return (request != null) && session.equals(request.session); } }
Java
package org.sagemath.singlecellserver; import java.util.UUID; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; /** * The base class for server communication. All derived classes should * derive from CommandRequest and CommandReply, but not from Command * directly. * * @author vbraun * */ public class Command { private final static String TAG = "Command"; protected UUID session; protected UUID msg_id; protected Command() { this.session = UUID.randomUUID(); msg_id = UUID.randomUUID(); } protected Command(UUID session) { if (session == null) this.session = UUID.randomUUID(); else this.session = session; msg_id = UUID.randomUUID(); } public String toShortString() { return toString(); } public String toLongString() { return toString(); } public String toString() { return "Command base class @" + Integer.toHexString(System.identityHashCode(this)); } /** * Whether or not the command contains data that is supposed to be shown to the user * @return boolean */ public boolean containsOutput() { return false; } protected static void prettyPrint(JSONObject json) { if (json == null) { System.out.println("null"); return; } JSONWriter writer = new JSONWriter(); writer.write(json.toString()); // try { // json.write(writer); // } catch (JSONException e) { // e.printStackTrace(); // } StringBuffer str = writer.getBuffer(); System.out.println(str); } }
Java
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; public class ExecuteReply extends CommandOutput { private final static String TAG = "ExecuteReply"; private String status; protected ExecuteReply(JSONObject json) throws JSONException { super(json); JSONObject content = json.getJSONObject("content"); status = content.getString("status"); } public String toString() { return "Execute reply status = "+status; } public String getStatus() { return status; } }
Java
package org.sagemath.singlecellserver; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class HtmlFiles extends CommandOutput { private final static String TAG = "HtmlFiles"; protected JSONArray files; protected LinkedList<URI> uriList = new LinkedList<URI>(); protected HtmlFiles(JSONObject json) throws JSONException { super(json); files = json.getJSONObject("content").getJSONObject("content").getJSONArray("files"); } public String toString() { if (uriList.isEmpty()) return "Html files (empty list)"; else return "Html files, number = "+uriList.size()+" first = "+getFirstURI().toString(); } public URI getFirstURI() { return uriList.getFirst(); } public void downloadFile(SageSingleCell.ServerTask server) throws IOException, URISyntaxException, JSONException { for (int i=0; i<files.length(); i++) { URI uri = server.downloadFileURI(this, files.get(i).toString()); uriList.add(uri); } } }
Java
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; /** * Roughly, a CommandOutput is any JSON object that has a "output_block" field. These are intended * to be displayed on the screen. * * @author vbraun * */ public class CommandOutput extends CommandReply { private final static String TAG = "CommandOutput"; private String output_block; protected CommandOutput(JSONObject json) throws JSONException { super(json); output_block = json.get("output_block").toString(); // prettyPrint(); // System.out.println("block = " + output_block); } public boolean containsOutput() { return true; } public String outputBlock() { return output_block; } }
Java
package org.sagemath.singlecellserver; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; public class DisplayData extends CommandOutput { private final static String TAG = "DisplayData"; private JSONObject data; protected String value, mime; protected DisplayData(JSONObject json) throws JSONException { super(json); data = json.getJSONObject("content").getJSONObject("data"); mime = data.keys().next().toString(); value = data.getString(mime); // prettyPrint(json); } public String toString() { return "Display data "+value; } public String getData() { return value; } public String getMime() { return mime; } public String toHTML() { if (mime.equals("text/html")) return value; if (mime.equals("text/plain")) return "<pre>"+value+"</pre>"; return null; } }
Java
package org.sagemath.singlecellserver; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.Buffer; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONException; import org.json.JSONObject; import org.sagemath.singlecellserver.SageSingleCell.SageInterruptedException; public class DataFile extends DisplayData { private final static String TAG = "DataFile"; protected DataFile(JSONObject json) throws JSONException { super(json); } public String toString() { if (data == null) return "Data file "+uri.toString(); else return "Data file "+value+" ("+data.length+" bytes)"; } public String mime() { String name = value.toLowerCase(); if (name.endsWith(".png")) return "image/png"; if (name.endsWith(".jpg")) return "image/png"; if (name.endsWith(".jpeg")) return "image/png"; if (name.endsWith(".svg")) return "image/svg"; return null; } protected byte[] data; protected URI uri; public URI getURI() { return uri; } public void downloadFile(SageSingleCell.ServerTask server) throws IOException, URISyntaxException, SageInterruptedException { uri = server.downloadFileURI(this, this.value); if (server.downloadDataFiles()) download(server, uri); } private void download(SageSingleCell.ServerTask server, URI uri) throws IOException, SageInterruptedException { HttpResponse response = server.downloadFile(uri); boolean error = (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); byte[] buffer = new byte[4096]; ByteArrayOutputStream buf = new ByteArrayOutputStream(); try { for (int n; (n = stream.read(buffer)) != -1; ) buf.write(buffer, 0, n); } finally { stream.close(); buf.close(); } data = buf.toByteArray(); } }
Java
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; /** * <h1>Streams (stdout, stderr, etc)</h1> * <p> * <pre><code> * Message type: ``stream``:: * content = { * # The name of the stream is one of 'stdin', 'stdout', 'stderr' * 'name' : str, * * # The data is an arbitrary string to be written to that stream * 'data' : str, * } * </code></pre> * When a kernel receives a raw_input call, it should also broadcast it on the pub * socket with the names 'stdin' and 'stdin_reply'. This will allow other clients * to monitor/display kernel interactions and possibly replay them to their user * or otherwise expose them. * * @author vbraun * */ public class ResultStream extends CommandOutput { private final static String TAG = "ResultStream"; protected JSONObject content; protected String data; protected ResultStream(JSONObject json) throws JSONException { super(json); content = json.getJSONObject("content"); data = content.getString("data"); } public String toString() { return "Result: stream = >>>"+data+"<<<"; } public String toShortString() { return "Stream output"; } public String get() { return data; } }
Java
package org.sagemath.singlecellserver; public class HttpError extends CommandReply { private final static String TAG = "HttpError"; protected String message; protected HttpError(CommandRequest request, String message) { super(request); this.message = message; } public String toString() { return "HTTP error "+message; } @Override public boolean terminateServerConnection() { return true; } }
Java
package org.sagemath.singlecellserver; import java.util.LinkedList; import java.util.UUID; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ExecuteRequest extends CommandRequest { private final static String TAG = "ExecuteRequest"; String input; boolean sage; public ExecuteRequest(String input, boolean sage, UUID session) { super(session); this.input = input; this.sage = sage; } public ExecuteRequest(String input) { super(); this.input = input; sage = true; } public String toString() { return "Request to execute >"+input+"<"; } public String toShortString() { return "Request to execute"; } public JSONObject toJSON() throws JSONException { JSONObject result = super.toJSON(); result.put("parent_header", new JSONArray()); result.put("msg_type", "execute_request"); JSONObject content = new JSONObject(); content.put("code", input); content.put("sage_mode", sage); result.put("content", content); return result; } // {"parent_header":{}, // "header":{ // "msg_id":"1ec1b4b4-722e-42c7-997d-e4a9605f5056", // "session":"c11a0761-910e-4c8c-b94e-803a13e5859a"}, // "msg_type":"execute_request", // "content":{"code":"code to execute", // "sage_mode":true}} }
Java
package org.sagemath.singlecellserver; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.ListIterator; import java.util.UUID; import javax.net.ssl.HandshakeCompletedListener; import junit.framework.Assert; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import android.text.format.Time; /** * Interface with the Sage single cell server * * @author vbraun * */ public class SageSingleCell { private final static String TAG = "SageSingleCell"; private long timeout = 30*1000; // private String server = "http://localhost:8001"; private String server = "http://sagemath.org:5467"; private String server_path_eval = "/eval"; private String server_path_output_poll = "/output_poll"; private String server_path_files = "/files"; protected boolean downloadDataFiles = true; /** * Whether to immediately download data files or only save their URI * * @param value Download immediately if true */ public void setDownloadDataFiles(boolean value) { downloadDataFiles = value; } /** * Set the server * * @param server The server, for example "http://sagemath.org:5467" * @param eval The path on the server for the eval post, for example "/eval" * @param poll The path on the server for the output polling, for example "/output_poll" */ public void setServer(String server, String eval, String poll, String files) { this.server = server; this.server_path_eval = eval; this.server_path_output_poll = poll; this.server_path_files = files; } public interface OnSageListener { /** * Output in a new block or an existing block where all current entries are supposed to be erased * @param output */ public void onSageOutputListener(CommandOutput output); /** * Output to add to an existing output block * @param output */ public void onSageAdditionalOutputListener(CommandOutput output); /** * Callback for an interact_prepare message * @param interact The interact */ public void onSageInteractListener(Interact interact); /** * The Sage session has been closed * @param reason A SessionEnd message or a HttpError */ public void onSageFinishedListener(CommandReply reason); } private OnSageListener listener; /** * Set the result callback, see {@link #query(String)} * * @param listener */ public void setOnSageListener(OnSageListener listener) { this.listener = listener; } public SageSingleCell() { logging(); } public void logging() { // You also have to // adb shell setprop log.tag.httpclient.wire.header VERBOSE // adb shell setprop log.tag.httpclient.wire.content VERBOSE java.util.logging.Logger apacheWireLog = java.util.logging.Logger.getLogger("org.apache.http.wire"); apacheWireLog.setLevel(java.util.logging.Level.FINEST); } protected static String streamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public static class SageInterruptedException extends Exception { private static final long serialVersionUID = -5638564842011063160L; } LinkedList<ServerTask> threads = new LinkedList<ServerTask>(); private void addThread(ServerTask thread) { synchronized (threads) { threads.add(thread); } } private void removeThread(ServerTask thread) { synchronized (threads) { threads.remove(thread); } } public enum LogLevel { NONE, BRIEF, VERBOSE }; private LogLevel logLevel = LogLevel.NONE; public void setLogLevel(LogLevel logLevel) { this.logLevel = logLevel; } public class ServerTask extends Thread { private final static String TAG = "ServerTask"; private final UUID session; private final String sageInput; private boolean sendOnly = false; private final boolean sageMode = true; private boolean interrupt = false; private DefaultHttpClient httpClient; private Interact interact; private CommandRequest request, currentRequest; private LinkedList<String> outputBlocks = new LinkedList<String>(); private long initialTime = System.currentTimeMillis(); protected LinkedList<CommandReply> result = new LinkedList<CommandReply>(); protected void log(Command command) { if (logLevel.equals(LogLevel.NONE)) return; String s; if (command instanceof CommandReply) s = ">> "; else if (command instanceof CommandRequest) s = "<< "; else s = "== "; long t = System.currentTimeMillis() - initialTime; s += "(" + String.valueOf(t) + "ms) "; s += command.toShortString(); if (logLevel.equals(LogLevel.VERBOSE)) { s += " "; s += command.toLongString(); s += "\n"; } System.out.println(s); System.out.flush(); } /** * Whether to only send or also receive the replies * @param sendOnly */ protected void setSendOnly(boolean sendOnly) { this.sendOnly = sendOnly; } protected void addReply(CommandReply reply) { log(reply); result.add(reply); if (reply.isInteract()) { interact = (Interact) reply; listener.onSageInteractListener(interact); } else if (reply.containsOutput() && reply.isReplyTo(currentRequest)) { CommandOutput output = (CommandOutput) reply; if (outputBlocks.contains(output.outputBlock())) listener.onSageAdditionalOutputListener(output); else { outputBlocks.add(output.outputBlock()); listener.onSageOutputListener(output); } } } /** * The timeout for the http request * @return timeout in milliseconds */ public long timeout() { return timeout; } private void init() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpClient = new DefaultHttpClient(params); addThread(this); currentRequest = request = new ExecuteRequest(sageInput, sageMode, session); } public ServerTask() { this.sageInput = null; this.session = null; init(); } public ServerTask(String sageInput) { this.sageInput = sageInput; this.session = null; init(); } public ServerTask(String sageInput, UUID session) { this.sageInput = sageInput; this.session = session; init(); } public void interrupt() { interrupt = true; } public boolean isInterrupted() { return interrupt; } protected HttpResponse postEval(JSONObject request) throws ClientProtocolException, IOException, SageInterruptedException, JSONException { if (interrupt) throw new SageInterruptedException(); HttpPost httpPost = new HttpPost(server + server_path_eval); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (request.has("content")) multipartEntity.addPart("message", new StringBody(request.toString())); else { JSONObject content = request.getJSONObject("content"); JSONObject header = request.getJSONObject("header"); multipartEntity.addPart("commands", new StringBody(JSONObject.quote(content.getString("code")))); multipartEntity.addPart("msg_id", new StringBody(header.getString("msg_id"))); multipartEntity.addPart("sage_mode", new StringBody("on")); } httpPost.setEntity(multipartEntity); HttpResponse httpResponse = httpClient.execute(httpPost); return httpResponse; } protected HttpResponse pollOutput(CommandRequest request, int sequence) throws ClientProtocolException, IOException, SageInterruptedException { if (interrupt) throw new SageInterruptedException(); Time time = new Time(); StringBuilder query = new StringBuilder(); time.setToNow(); // query.append("?callback=jQuery"); query.append("?computation_id=" + request.session.toString()); query.append("&sequence=" + sequence); query.append("&rand=" + time.toMillis(true)); HttpGet httpGet = new HttpGet(server + server_path_output_poll + query); return httpClient.execute(httpGet); } // protected void callSageOutputListener(CommandOutput output) { // listener.onSageOutputListener(output); // } // // protected void callSageReplaceOutputListener(CommandOutput output) { // listener.onSageReplaceOutputListener(output); // } // // protected void callSageInteractListener(Interact interact) { // listener.onSageInteractListener(interact); // } protected URI downloadFileURI(CommandReply reply, String filename) throws URISyntaxException { StringBuilder query = new StringBuilder(); query.append("/"+reply.session.toString()); query.append("/"+filename); return new URI(server + server_path_files + query); } protected HttpResponse downloadFile(URI uri) throws ClientProtocolException, IOException, SageInterruptedException { if (interrupt) throw new SageInterruptedException(); HttpGet httpGet = new HttpGet(uri); return httpClient.execute(httpGet); } protected boolean downloadDataFiles() { return SageSingleCell.this.downloadDataFiles; } @Override public void run() { super.run(); log(request); if (sendOnly) { request.sendRequest(this); removeThread(this); return; } request.receiveReply(this); removeThread(this); listener.onSageFinishedListener(result.getLast()); } } /** * Start an asynchronous query on the Sage server * The result will be handled by the callback set by {@link #setOnSageListener(OnSageListener)} * @param sageInput */ public void query(String sageInput) { ServerTask task = new ServerTask(sageInput); task.start(); } /** * Update an interactive element * @param interact The interact_prepare message we got from the server as we set up the interact * @param name The name of the variable in the interact function declaration * @param value The new value */ public void interact(Interact interact, String name, Object value) { String sageInput = "_update_interact('" + interact.getID() + "',control_vals=dict(" + name + "=" + value.toString() + ",))"; ServerTask task = new ServerTask(sageInput, interact.session); synchronized (threads) { for (ServerTask thread: threads) if (thread.interact == interact) { thread.currentRequest = task.request; thread.outputBlocks.clear(); } } task.setSendOnly(true); task.start(); } /** * Interrupt all pending Sage server transactions */ public void interrupt() { synchronized (threads) { for (ServerTask thread: threads) thread.interrupt(); } } /** * Whether a computation is currently running * * @return */ public boolean isRunning() { synchronized (threads) { for (ServerTask thread: threads) if (!thread.isInterrupted()) return true; } return false; } } /* === Send request === POST /eval HTTP/1.1 Host: localhost:8001 Connection: keep-alive Content-Length: 506 Cache-Control: max-age=0 Origin: http://localhost:8001 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryh9NcFTBy2FksKYpN Accept: text/html,application/xhtml+xml,application/xml;q=0.9,* / *;q=0.8 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="commands" "1+1" ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="session_id" 87013257-7c34-4c83-b7ed-2ec7e7480935 ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="msg_id" 489696dc-ed8d-4cb6-a140-4282a43eda95 ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="sage_mode" True ------WebKitFormBoundaryh9NcFTBy2FksKYpN-- HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:12:14 GMT Content-Type: text/html; charset=utf-8 Connection: keep-alive Content-Length: 0 === Poll for reply (unsuccessfully, try again) === GET /output_poll?callback=jQuery15015045171417295933_1323715011672&computation_id=25508880-6a6a-4353-9439-689468ec679e&sequence=0&_=1323718075839 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:27:55 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 44 jQuery15015045171417295933_1323715011672({}) === Poll for reply (success) === GET /output_poll?callback=jQuery15015045171417295933_1323715011662&computation_id=87013257-7c34-4c83-b7ed-2ec7e7480935&sequence=0&_=1323717134406 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px === Reply with result from server === HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:12:14 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 830 jQuery15015045171417295933_1323715011662( {"content": [{ "parent_header": { "username": "", "msg_id": "489696dc-ed8d-4cb6-a140-4282a43eda95", "session": "87013257-7c34-4c83-b7ed-2ec7e7480935"}, "msg_type": "pyout", "sequence": 0, "output_block": null, "content": { "data": {"text/plain": "2"}}, "header": {"msg_id": "1620524024608841996"}}, { "parent_header": { "username": "", "msg_id": "489696dc-ed8d-4cb6-a140-4282a43eda95", "session": "87013257-7c34-4c83-b7ed-2ec7e7480935"}, "msg_type": "execute_reply", "sequence": 1, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "1501182239947896697"}}, { "parent_header": {"session": "87013257-7c34-4c83-b7ed-2ec7e7480935"}, "msg_type": "extension", "sequence": 2, "content": {"msg_type": "session_end"}, "header": {"msg_id": "1e6db71f-61a0-47f9-9607-f2054243bb67"} }]}) === Reply with Syntax Erorr === GET /output_poll?callback=jQuery15015045171417295933_1323715011664&computation_id=9b3ed6bb-01e8-4a6e-9076-14c71324daf6&sequence=0&_=1323717902557 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:25:02 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 673 jQuery15015045171417295933_1323715011664({"content": [{"parent_header": {"username": "", "msg_id": "df56f48a-d47f-4267-b228-77f051d7d834", "session": "9b3ed6bb-01e8-4a6e-9076-14c71324daf6"}, "msg_type": "execute_reply", "sequence": 0, "output_block": null, "content": {"status": "error", "ename": "SyntaxError", "evalue": "invalid syntax", "traceback": ["\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m Traceback (most recent call last)", "\u001b[1;31mSyntaxError\u001b[0m: invalid syntax (<string>, line 39)"]}, "header": {"msg_id": "2853508955959610959"}}]})GET /output_poll?callback=jQuery15015045171417295933_1323715011665&computation_id=9b3ed6bb-01e8-4a6e-9076-14c71324daf6&sequence=1&_=1323717904769 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:25:04 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 269 jQuery15015045171417295933_1323715011665({"content": [{"parent_header": {"session": "9b3ed6bb-01e8-4a6e-9076-14c71324daf6"}, "msg_type": "extension", "sequence": 1, "content": {"msg_type": "session_end"}, "header": {"msg_id": "e01180d4-934c-4f12-858c-72d52e0330cd"}}]}) */
Java
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; public class SessionEnd extends CommandReply { public final static String TAG = "SessionEnd"; protected SessionEnd(JSONObject json) throws JSONException { super(json); } public String toString() { return "End of Sage session marker"; } @Override public boolean terminateServerConnection() { return true; } }
Java
package org.sagemath.singlecellserver; import java.io.StringWriter; /** * * @author Elad Tabak * @since 28-Nov-2011 * @version 0.1 * */ public class JSONWriter extends StringWriter { private int indent = 0; @Override public void write(int c) { if (((char)c) == '[' || ((char)c) == '{') { super.write(c); super.write('\n'); indent++; writeIndentation(); } else if (((char)c) == ',') { super.write(c); super.write('\n'); writeIndentation(); } else if (((char)c) == ']' || ((char)c) == '}') { super.write('\n'); indent--; writeIndentation(); super.write(c); } else { super.write(c); } } private void writeIndentation() { for (int i = 0; i < indent; i++) { super.write(" "); } } }
Java
package org.sagemath.singlecellserver; import java.util.Iterator; import org.json.JSONException; import org.json.JSONObject; /** * <h1>Python output</h1> * <p> * When Python produces output from code that has been compiled in with the * 'single' flag to :func:`compile`, any expression that produces a value (such as * ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with * this value whatever it wants. The default behavior of ``sys.displayhook`` in * the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of * the value as long as it is not ``None`` (which isn't printed at all). In our * case, the kernel instantiates as ``sys.displayhook`` an object which has * similar behavior, but which instead of printing to stdout, broadcasts these * values as ``pyout`` messages for clients to display appropriately. * <p> * IPython's displayhook can handle multiple simultaneous formats depending on its * configuration. The default pretty-printed repr text is always given with the * ``data`` entry in this message. Any other formats are provided in the * ``extra_formats`` list. Frontends are free to display any or all of these * according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID * string, a type string, and the data. The ID is unique to the formatter * implementation that created the data. Frontends will typically ignore the ID * unless if it has requested a particular formatter. The type string tells the * frontend how to interpret the data. It is often, but not always a MIME type. * Frontends should ignore types that it does not understand. The data itself is * any JSON object and depends on the format. It is often, but not always a string. * <p> * Message type: ``pyout``:: * <p> * <pre><code> * content = { * # The counter for this execution is also provided so that clients can * # display it, since IPython automatically creates variables called _N * # (for prompt N). * 'execution_count' : int, * * # The data dict contains key/value pairs, where the kids are MIME * # types and the values are the raw data of the representation in that * # format. The data dict must minimally contain the ``text/plain`` * # MIME type which is used as a backup representation. * 'data' : dict, * } * </code></pre> * * @author vbraun */ public class PythonOutput extends CommandOutput { private final static String TAG = "PythonOutput"; protected JSONObject content, data; protected String text; protected PythonOutput(JSONObject json) throws JSONException { super(json); content = json.getJSONObject("content"); data = content.getJSONObject("data"); text = data.getString("text/plain"); } public String toString() { return "Python output: "+text; } public String toShortString() { return "Python output"; } /** * Get an iterator for the possible encodings. * * @return */ public Iterator<?> getEncodings() { return data.keys(); } /** * Get the output * * @param encoding Which of possibly multiple representations to return * @return The output in the chosen representation * @throws JSONException */ public String get(String encoding) throws JSONException { return data.getString(encoding); } /** * Return a textual representation of the output * * @return Text representation of the output; */ public String get() { return text; } }
Java
package org.sagemath.singlecellserver; import java.util.LinkedList; import java.util.ListIterator; public class Transaction { protected final SageSingleCell server; protected final CommandRequest request; protected final LinkedList<CommandReply> reply; public static class Factory { public Transaction newTransaction(SageSingleCell server, CommandRequest request, LinkedList<CommandReply> reply) { return new Transaction(server, request, reply); } } protected Transaction(SageSingleCell server, CommandRequest request, LinkedList<CommandReply> reply) { this.server = server; this.request = request; this.reply = reply; } public DataFile getDataFile() { for (CommandReply r: reply) if (r instanceof DataFile) return (DataFile)r; return null; } public HtmlFiles getHtmlFiles() { for (CommandReply r: reply) if (r instanceof HtmlFiles) return (HtmlFiles)r; return null; } public DisplayData getDisplayData() { for (CommandReply r: reply) if (r instanceof DisplayData) return (DisplayData)r; return null; } public ResultStream getResultStream() { for (CommandReply r: reply) if (r instanceof ResultStream) return (ResultStream)r; return null; } public PythonOutput getPythonOutput() { for (CommandReply r: reply) if (r instanceof PythonOutput) return (PythonOutput)r; return null; } public Traceback getTraceback() { for (CommandReply r: reply) if (r instanceof Traceback) return (Traceback)r; return null; } public HttpError getHttpError() { for (CommandReply r: reply) if (r instanceof HttpError) return (HttpError)r; return null; } public ExecuteReply getExecuteReply() { for (CommandReply r: reply) if (r instanceof ExecuteReply) return (ExecuteReply)r; return null; } public String toString() { StringBuilder s = new StringBuilder(); s.append(request); if (reply.isEmpty()) s.append("no reply"); else s.append("\n"); ListIterator<CommandReply> iter = reply.listIterator(); while (iter.hasNext()) { s.append(iter.next()); if (iter.hasNext()) s.append("\n"); } return s.toString(); } }
Java
package org.sagemath.droid; import sheetrock.panda.changelog.ChangeLog; import com.example.android.actionbarcompat.ActionBarActivity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import org.sagemath.singlecellserver.Interact; import org.sagemath.singlecellserver.SageSingleCell; /** * The main activity of the Sage app * * @author vbraun * */ public class SageActivity extends ActionBarActivity implements Button.OnClickListener, OutputView.onSageListener, OnItemSelectedListener { private final static String TAG = "SageActivity"; private ChangeLog changeLog; private EditText input; private Button roundBracket, squareBracket, curlyBracket; private Button runButton; private Spinner insertSpinner; private OutputView outputView; private static SageSingleCell server = new SageSingleCell(); private CellData cell; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CellCollection.initialize(getApplicationContext()); cell = CellCollection.getInstance().getCurrentCell(); server.setServer("http://aleph.sagemath.org", "/eval", "/output_poll", "/files"); setContentView(R.layout.main); changeLog = new ChangeLog(this); if (changeLog.firstRun()) changeLog.getLogDialog().show(); input = (EditText) findViewById(R.id.sage_input); roundBracket = (Button) findViewById(R.id.bracket_round); squareBracket = (Button) findViewById(R.id.bracket_square); curlyBracket = (Button) findViewById(R.id.bracket_curly); runButton = (Button) findViewById(R.id.button_run); outputView = (OutputView) findViewById(R.id.sage_output); insertSpinner = (Spinner) findViewById(R.id.insert_text); server.setOnSageListener(outputView); outputView.setOnSageListener(this); insertSpinner.setOnItemSelectedListener(this); roundBracket.setOnClickListener(this); squareBracket.setOnClickListener(this); curlyBracket.setOnClickListener(this); runButton.setOnClickListener(this); server.setDownloadDataFiles(false); setTitle(cell.getTitle()); if (server.isRunning()) getActionBarHelper().setRefreshActionItemState(true); input.setText(cell.getInput()); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Uri uri; Intent intent; switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.menu_refresh: runButton(); return true; case R.id.menu_search: Toast.makeText(this, "Tapped search", Toast.LENGTH_SHORT).show(); return true; case R.id.menu_share: Toast.makeText(this, "Tapped share", Toast.LENGTH_SHORT).show(); return true; case R.id.menu_changelog: changeLog.getFullLogDialog().show(); return true; case R.id.menu_about_sage: uri = Uri.parse("http://www.sagemath.org"); intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; case R.id.menu_manual_user: uri = Uri.parse("http://www.sagemath.org/doc/tutorial/"); intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; case R.id.menu_manual_dev: uri = Uri.parse("http://http://www.sagemath.org/doc/reference/"); intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } // public void setTitle(String title) { // this.title.setText(title); // } // @Override public void onClick(View v) { int cursor = input.getSelectionStart(); switch (v.getId()) { case R.id.button_run: runButton(); break; case R.id.bracket_round: input.getText().insert(cursor, "( )"); input.setSelection(cursor + 2); break; case R.id.bracket_square: input.getText().insert(cursor, "[ ]"); input.setSelection(cursor + 2); break; case R.id.bracket_curly: input.getText().insert(cursor, "{ }"); input.setSelection(cursor + 2); break; } } private void runButton() { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(input.getWindowToken(), 0); server.interrupt(); outputView.clear(); server.query(input.getText().toString()); getActionBarHelper().setRefreshActionItemState(true); outputView.requestFocus(); } @Override public void onSageFinishedListener() { getActionBarHelper().setRefreshActionItemState(false); } @Override public void onSageInteractListener(Interact interact, String name, Object value) { Log.e(TAG, name + " = " + value); server.interact(interact, name, value); } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); outputView.onResume(); } protected static final int INSERT_PROMPT = 0; protected static final int INSERT_FOR_LOOP = 1; protected static final int INSERT_LIST_COMPREHENSION = 2; @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3) { if (parent != insertSpinner) return; int cursor = input.getSelectionStart(); switch (position) { case INSERT_FOR_LOOP: input.getText().append("\nfor i in range(0,10):\n "); input.setSelection(input.getText().length()); break; case INSERT_LIST_COMPREHENSION: input.getText().insert(cursor, "[ i for i in range(0,10) ]"); input.setSelection(cursor+2, cursor+3); break; } parent.setSelection(0); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }
Java
package org.sagemath.droid; import java.util.LinkedList; import java.util.ListIterator; import junit.framework.Assert; import org.sagemath.singlecellserver.CommandOutput; import org.sagemath.singlecellserver.CommandReply; import org.sagemath.singlecellserver.Interact; import org.sagemath.singlecellserver.SageSingleCell; import org.sagemath.singlecellserver.SageSingleCell.ServerTask; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.webkit.WebSettings; import android.widget.LinearLayout; import android.widget.SeekBar; public class OutputView extends LinearLayout implements SageSingleCell.OnSageListener, InteractView.OnInteractListener { private final static String TAG = "OutputView"; interface onSageListener { public void onSageInteractListener(Interact interact, String name, Object value); public void onSageFinishedListener(); } private onSageListener listener; public void setOnSageListener(onSageListener listener) { this.listener = listener; } private LinkedList<OutputBlock> blocks = new LinkedList<OutputBlock>(); private Context context; private CellData cell; public OutputView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; setOrientation(VERTICAL); setFocusable(true); setFocusableInTouchMode(true); } @Override public void onSageOutputListener(CommandOutput output) { UpdateResult task = new UpdateResult(); task.output = output; handler.post(task); } @Override public void onSageAdditionalOutputListener(CommandOutput output) { UpdateResult task = new UpdateResult(); task.additionalOutput = output; handler.post(task); } @Override public void onSageInteractListener(Interact interact) { UpdateResult task = new UpdateResult(); task.interact = interact; handler.post(task); } @Override public void onSageFinishedListener(CommandReply reason) { UpdateResult task = new UpdateResult(); task.finished = reason; handler.post(task); } private Handler handler = new Handler(); /** * Retrieve the OutputBlock representing the output. Creates a new OutputBlock if necessary. * @param output * @return */ private OutputBlock getOutputBlock(CommandOutput output) { return getOutputBlock(output.outputBlock()); } private OutputBlock getOutputBlock(String output_block) { ListIterator<OutputBlock> iter = blocks.listIterator(); while (iter.hasNext()) { OutputBlock block = iter.next(); if (block.getOutputBlock().equals(output_block)) return block; } return newOutputBlock(); } private OutputBlock newOutputBlock() { OutputBlock block = new OutputBlock(context, cell); addView(block); blocks.add(block); return block; } private class UpdateResult implements Runnable { private CommandOutput output; private CommandOutput additionalOutput; private Interact interact; private CommandReply finished; @Override public void run() { if (output != null) { // Log.d(TAG, "set "+output.toShortString()); OutputBlock block = getOutputBlock(output); block.set(output); } if (additionalOutput != null ) { // Log.d(TAG, "add "+additionalOutput.toShortString()); OutputBlock block = getOutputBlock(additionalOutput); block.add(additionalOutput); } if (interact != null) { InteractView interactView = new InteractView(context); interactView.set(interact); interactView.setOnInteractListener(OutputView.this); addView(interactView); } if (finished != null) listener.onSageFinishedListener(); } } /** * Called during onResume. Reloads the embedded web views from cache. */ protected void onResume() { removeAllViews(); blocks.clear(); cell = CellCollection.getInstance().getCurrentCell(); Assert.assertNotNull(cell); for (String block : cell.getOutputBlocks()) { if (cell.hasCachedOutput(block)) { OutputBlock outputBlock = newOutputBlock(); outputBlock.set(block); } } //block.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // displayResult(); //block.getSettings().setCacheMode(WebSettings.LOAD_NORMAL); } public void clear() { removeAllViews(); blocks.clear(); cell.clearCache(); } @Override public void onInteractListener(Interact interact, String name, Object value) { listener.onSageInteractListener(interact, name, value); } }
Java
package org.sagemath.droid; import java.util.LinkedList; import android.app.Activity; import android.graphics.Color; import android.graphics.PixelFormat; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; public class CellGroupsFragment extends ListFragment { private static final String TAG = "CellGroupsFragment"; interface OnGroupSelectedListener { public void onGroupSelected(String group); } private OnGroupSelectedListener listener; public void setOnGroupSelected(OnGroupSelectedListener listener) { this.listener = listener; } @Override public void onListItemClick(ListView parent, View view, int position, long id) { adapter.setSelectedItem(position); String group = groups.get(position); listener.onGroupSelected(group); } protected LinkedList<String> groups; protected CellGroupsAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); groups = CellCollection.getInstance().groups(); adapter = new CellGroupsAdapter(getActivity().getApplicationContext(), groups); setListAdapter(adapter); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.cell_groups_layout, container); } @Override public void onResume() { super.onResume(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); Window window = activity.getWindow(); window.setFormat(PixelFormat.RGBA_8888); } }
Java
package org.sagemath.droid; import org.sagemath.droid.CellGroupsFragment.OnGroupSelectedListener; import sheetrock.panda.changelog.ChangeLog; import com.example.android.actionbarcompat.ActionBarActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; public class CellActivity extends ActionBarActivity implements OnGroupSelectedListener{ private final static String TAG = "CellActivity"; private ChangeLog changeLog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CellCollection.initialize(getApplicationContext()); setContentView(R.layout.cell_activity); changeLog = new ChangeLog(this); if (changeLog.firstRun()) changeLog.getLogDialog().show(); CellGroupsFragment groupsFragment = (CellGroupsFragment) getSupportFragmentManager().findFragmentById(R.id.cell_groups_fragment); groupsFragment.setOnGroupSelected(this); CellListFragment listFragment = (CellListFragment) getSupportFragmentManager().findFragmentById(R.id.cell_list_fragment); if (listFragment != null && listFragment.isInLayout()) listFragment.switchToGroup(null); } public static final String INTENT_SWITCH_GROUP = "intent_switch_group"; @Override public void onGroupSelected(String group) { CellListFragment listFragment = (CellListFragment) getSupportFragmentManager().findFragmentById(R.id.cell_list_fragment); if (listFragment == null || !listFragment.isInLayout()) { Intent i = new Intent(getApplicationContext(), CellListActivity.class); i.putExtra(INTENT_SWITCH_GROUP, group); startActivity(i); } else { listFragment.switchToGroup(group); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
Java
package org.sagemath.droid; import java.util.LinkedList; import java.util.ListIterator; import junit.framework.Assert; import org.sagemath.singlecellserver.CommandOutput; import org.sagemath.singlecellserver.DataFile; import org.sagemath.singlecellserver.DisplayData; import org.sagemath.singlecellserver.ExecuteReply; import org.sagemath.singlecellserver.HtmlFiles; import org.sagemath.singlecellserver.PythonOutput; import org.sagemath.singlecellserver.ResultStream; import org.sagemath.singlecellserver.Traceback; import android.content.Context; import android.text.TextUtils; import android.util.Log; import android.webkit.WebView; public class OutputBlock extends WebView { private final static String TAG = "OutputBlock"; private final CellData cell; public OutputBlock(Context context, CellData cell) { super(context); this.cell = cell; } // The output_block field of the JSON message protected String name; private static String htmlify(String str) { StringBuilder s = new StringBuilder(); s.append("<pre style=\"font-size:130%\">"); String[] lines = str.split("\n"); for (int i=0; i<lines.length; i++) { if (i>0) s.append("&#13;&#10;"); s.append(TextUtils.htmlEncode(lines[i])); } s.append("</pre>"); return s.toString(); } private LinkedList<String> divs = new LinkedList<String>(); public String getHtml() { StringBuilder s = new StringBuilder(); s.append("<html><body>"); ListIterator<String> iter = divs.listIterator(); while (iter.hasNext()) { s.append("<div>"); s.append(iter.next()); s.append("</div>"); } s.append("</body></html>"); return s.toString(); } private void addDiv(CommandOutput output) { if (output instanceof DataFile) addDivDataFile((DataFile) output); else if (output instanceof HtmlFiles) addDivHtmlFiles((HtmlFiles) output); else if (output instanceof DisplayData) addDivDisplayData((DisplayData) output); else if (output instanceof PythonOutput) addDivPythonOutput((PythonOutput) output); else if (output instanceof ResultStream) addDivResultStream((ResultStream) output); else if (output instanceof Traceback) addDivTraceback((Traceback) output); else if (output instanceof ExecuteReply) addDivExecuteReply((ExecuteReply) output); else divs.add("Unknown output: "+output.toShortString()); } private void addDivDataFile(DataFile dataFile) { String uri = dataFile.getURI().toString(); String div; String mime = dataFile.getMime(); if (dataFile.mime().equals("image/png") || dataFile.mime().equals("image/jpg")) div = "<img src=\"" + uri + "\" alt=\"plot output\"></img>"; else if (dataFile.mime().equals("image/svg")) div = "<object data\"" + uri + "\" type=\"image/svg+xml\"></object>"; else div = "Unknow MIME type "+dataFile.mime(); divs.add(div); } private void addDivHtmlFiles(HtmlFiles htmlFiles) { String div = "HTML"; divs.add(div); } private void addDivDisplayData(DisplayData displayData) { String div = displayData.toHTML(); divs.add(div); } private void addDivPythonOutput(PythonOutput pythonOutput) { String div = htmlify(pythonOutput.get()); divs.add(div); } private void addDivResultStream(ResultStream resultStream) { String div = htmlify(resultStream.get()); divs.add(div); } private void addDivTraceback(Traceback traceback) { String div = htmlify(traceback.toString()); divs.add(div); } private void addDivExecuteReply(ExecuteReply reply) { if (reply.getStatus().equals("ok")) divs.add("<font color=\"green\">ok</font>"); else divs.add(reply.toString()); } public void add(CommandOutput output) { if (name == null) { Log.e(TAG, "adding output without initially setting it"); return; } if (!name.equals(output.outputBlock())) Log.e(TAG, "Output has wrong output_block field"); addDiv(output); // loadData(getHtml(), "text/html", "UTF-8"); cell.saveOutput(getOutputBlock(), getHtml()); loadUrl(cell.getUrlString(getOutputBlock())); } public void set(String output_block) { if (cell.hasCachedOutput(output_block)) loadUrl(cell.getUrlString(output_block)); } public void set(CommandOutput output) { if (name == null) { name = output.outputBlock(); } if (!name.equals(output.outputBlock())) Log.e(TAG, "Output has wrong output_block field"); divs.clear(); add(output); } public String getOutputBlock() { return name; } }
Java
package org.sagemath.droid; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.text.format.Formatter; import android.util.Log; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class InteractContinuousSlider extends InteractControlBase implements OnSeekBarChangeListener { private final static String TAG = "InteractContinuousSlider"; protected String format; protected SeekBar seekBar; protected TextView nameValueText; public InteractContinuousSlider(InteractView interactView, String variable, Context context) { super(interactView, variable, context); nameValueText = new TextView(context); nameValueText.setMaxLines(1); nameValueText.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.0f)); nameValueText.setPadding( nameValueText.getPaddingLeft()+10, nameValueText.getPaddingTop()+5, nameValueText.getPaddingRight()+5, nameValueText.getPaddingBottom()); addView(nameValueText); seekBar = new SeekBar(context); seekBar.setMax(10000); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); seekBar.setLayoutParams(params); // seekBar.setPadding(seekBar.getPaddingLeft() + 10, // seekBar.getPaddingTop(), // seekBar.getPaddingRight(), // seekBar.getPaddingBottom()); addView(seekBar); seekBar.setOnSeekBarChangeListener(this); format = variable + "=%3.2f"; } private double range_min = 0; private double range_max = 1; private double step = 0.1; public void setRange(double range_min, double range_max, double step) { this.range_min = range_min; this.range_max = range_max; this.step = step; updateValueText(); } public void setRange(JSONObject control) { JSONArray range; try { range = control.getJSONArray("range"); this.range_min = range.getDouble(0); this.range_max = range.getDouble(1); this.step = control.getDouble("step"); String s = control.getString("step"); int digits = Math.max( countDigitsAfterComma(control.getString("step")), countDigitsAfterComma(range.getString(0))); format = variable + "=%4." + digits + "f"; } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); setRange(0, 1 , 0.1); } updateValueText(); } public Object getValue() { int raw = seekBar.getProgress(); long i = Math.round(((double)raw) / seekBar.getMax() * (range_max - range_min) / step); double value = i * step + range_min; // range_max-range_min is not necessarily divisible by step value = Math.min(range_max, value); return value; } private void updateValueText() { nameValueText.setText(String.format(format, getValue())); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateValueText(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { interactView.notifyChange(this); } }
Java
package org.sagemath.droid; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.UUID; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import android.util.Log; public class CellCollectionXMLParser { private static final String TAG = "CellCollectionXMLParser"; private Document dom; private LinkedList<CellData> data; protected void parseXML(InputStream inputStream){ dom = null; data = new LinkedList<CellData>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(inputStream); dom = db.parse(is); } catch (ParserConfigurationException e) { Log.e(TAG, "XML parse error: " + e.getLocalizedMessage()); } catch (SAXException e) { Log.e(TAG, "Wrong XML file structure: " + e.getLocalizedMessage()); } catch (IOException e) { Log.e(TAG, "I/O exeption: " + e.getLocalizedMessage()); } } public LinkedList<CellData> parse(InputStream inputStream) { parseXML(inputStream); if (dom != null) parseDocument(); return data; } private void parseDocument(){ Element root = dom.getDocumentElement(); NodeList nl = root.getElementsByTagName("cell"); if(nl != null && nl.getLength() > 0) { for(int i = 0 ; i < nl.getLength();i++) { Element element = (Element)nl.item(i); CellData cell = getCellData(element); data.add(cell); } } } private CellData getCellData(Element cellElement) { CellData cell = new CellData(); cell.group = getTextValue(cellElement, "group"); cell.title = getTextValue(cellElement, "title"); cell.description = getTextValue(cellElement, "description"); cell.input = getTextValue(cellElement, "input"); cell.rank = getIntValue(cellElement, "rank"); cell.uuid = getUuidValue(cellElement, "uuid"); return cell; } private String getTextValue(Element element, String tagName) { String textVal = null; NodeList nl = element.getElementsByTagName(tagName); if(nl != null && nl.getLength() > 0) { Element el = (Element)nl.item(0); textVal = el.getFirstChild().getNodeValue(); } return textVal.trim(); } private Integer getIntValue(Element element, String tagName) { return Integer.parseInt(getTextValue(element, tagName)); } private UUID getUuidValue(Element element, String tagName) { return UUID.fromString(getTextValue(element, tagName)); } }
Java
package org.sagemath.droid; import java.util.LinkedList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class CellListAdapter extends ArrayAdapter<CellData> { private final Context context; private LinkedList<CellData> cells; public CellListAdapter(Context context, LinkedList<CellData> cells) { super(context, R.layout.cell_list_item, cells); this.context = context; this.cells = cells; } static class ViewHolder { protected TextView titleView; protected TextView descriptionView; } @Override public View getView(int position, View convertView, ViewGroup parent) { View item; TextView titleView; TextView descriptionView; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); item = inflater.inflate(R.layout.cell_list_item, parent, false); titleView = (TextView) item.findViewById(R.id.cell_title); descriptionView = (TextView) item.findViewById(R.id.cell_description); final ViewHolder viewHolder = new ViewHolder(); viewHolder.titleView = titleView; viewHolder.descriptionView = descriptionView; item.setTag(viewHolder); } else { item = convertView; ViewHolder viewHolder = (ViewHolder)convertView.getTag(); titleView = viewHolder.titleView; descriptionView = viewHolder.descriptionView; } CellData cell = cells.get(position); titleView.setText(cell.title); descriptionView.setText(cell.description); return item; } }
Java
package org.sagemath.droid; import java.util.LinkedList; import org.sagemath.droid.CellGroupsFragment.OnGroupSelectedListener; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class CellListFragment extends ListFragment { private static final String TAG = "CellListFragment"; protected LinkedList<CellData> cells = new LinkedList<CellData>(); protected CellListAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); adapter = new CellListAdapter(getActivity(), cells); setListAdapter(adapter); } public void switchToGroup(String group) { CellCollection cellCollection = CellCollection.getInstance(); cells.clear(); if (group == null) cells.addAll(cellCollection.getCurrentGroup()); else cells.addAll(cellCollection.getGroup(group)); cellCollection.setCurrentCell(cells.getFirst()); if (adapter != null) adapter.notifyDataSetChanged(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); CellData cell = cells.get(position); CellCollection.getInstance().setCurrentCell(cell); Intent i = new Intent(getActivity().getApplicationContext(), SageActivity.class); startActivity(i); } }
Java
package org.sagemath.droid; import android.content.Context; import android.widget.LinearLayout; public abstract class InteractControlBase extends LinearLayout { private final static String TAG = "InteractControlBase"; protected final String variable; protected final InteractView interactView; public InteractControlBase(InteractView interactView, String variable, Context context) { super(context); this.interactView = interactView; this.variable = variable; setFocusable(true); setFocusableInTouchMode(true); } protected String getVariableName() { return variable; } protected abstract Object getValue(); protected int countDigitsAfterComma(String s) { int pos = s.lastIndexOf('.'); if (pos == -1) return 0; else return s.length() - pos - 1; } }
Java
package org.sagemath.droid; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.LinkedList; import java.util.UUID; import android.net.Uri; import android.util.Log; public class CellData { private final static String TAG = "CellData"; protected UUID uuid; protected String group; protected String title; protected String description; protected String input; protected Integer rank; protected LinkedList<String> outputBlocks; public String getGroup() { return group; } public String getTitle() { return title; } public String getDescription() { return description; } public String getInput() { return input; } private File cache; public File cacheDir() { if (cache != null) return cache; File base = CellCollection.getInstance().getCacheDirBase(); cache = new File(base, uuid.toString()); if (!cache.exists()) { boolean rc = cache.mkdir(); if (!rc) Log.e(TAG, "Unable to create directory "+cache.getAbsolutePath()); } return cache; } protected File cacheDirIndexFile(String output_block) { addOutputBlock(output_block); return new File(cacheDir(), output_block + ".html"); } public void saveOutput(String output_block, String html) { addOutputBlock(output_block); File f = cacheDirIndexFile(output_block); FileOutputStream os; try { os = new FileOutputStream(f); } catch (FileNotFoundException e) { Log.e(TAG, "Unable to save output: " + e.getLocalizedMessage()); return; } try { os.write(html.getBytes()); } catch (IOException e) { Log.e(TAG, "Unable to save output: " + e.getLocalizedMessage()); } finally { try { os.close(); } catch (IOException e) { Log.e(TAG, "Unable to save output: " + e.getLocalizedMessage()); } } } public String getUrlString(String block) { Uri uri = Uri.fromFile(cacheDirIndexFile(block)); return uri.toString(); } public boolean hasCachedOutput(String block) { return cacheDirIndexFile(block).exists(); } public void clearCache() { File[] files = cacheDir().listFiles(); for (File file : files) if (!file.delete()) Log.e(TAG, "Error deleting "+file); } private void addOutputBlock(String block) { if (outputBlocks == null) outputBlocks = new LinkedList<String>(); if (!outputBlocks.contains(block)) { outputBlocks.add(block); saveOutputBlocks(); } } private void saveOutputBlocks() { File file = new File(cacheDir(), "output_blocks"); try { saveOutputBlocks(file); } catch (IOException e) { Log.e(TAG, "Unable to save output_block list: "+e.getLocalizedMessage()); } } private void saveOutputBlocks(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos); dos.writeInt(outputBlocks.size()); for (String block : outputBlocks) { dos.writeUTF(block); } // Log.e(TAG, "saved "+outputBlocks.size()+" output_block fields"); dos.close(); } private LinkedList<String> loadOutputBlocks(File file) throws IOException { LinkedList<String> result = new LinkedList<String>(); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis); int n = dis.readInt(); for (int i=0; i<n; i++) { String block = dis.readUTF(); } // Log.e(TAG, "read "+n+" output_block fields"); dis.close(); return result; } public LinkedList<String> getOutputBlocks() { if (outputBlocks != null) return outputBlocks; outputBlocks = new LinkedList<String>(); File file = new File(cacheDir(), "output_blocks"); if (!file.exists()) return outputBlocks; try { outputBlocks.addAll(loadOutputBlocks(file)); } catch (IOException e) { Log.e(TAG, "Unable to load output_block list: "+e.getLocalizedMessage()); } return outputBlocks; } }
Java
package org.sagemath.droid; import org.sagemath.droid.CellGroupsFragment.OnGroupSelectedListener; import com.example.android.actionbarcompat.ActionBarActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; public class CellListActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CellCollection.initialize(getApplicationContext()); setContentView(R.layout.cell_list_fragment); CellListFragment listFragment = (CellListFragment) getSupportFragmentManager().findFragmentById(R.id.cell_list_fragment); Intent intent = getIntent(); if (intent == null) listFragment.switchToGroup(null); else { String group = intent.getStringExtra(CellActivity.INTENT_SWITCH_GROUP); listFragment.switchToGroup(group); } setTitle(CellCollection.getInstance().getCurrentCell().getGroup()); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
Java
package org.sagemath.droid; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.sagemath.singlecellserver.Interact; import android.content.Context; import android.util.Log; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SlidingDrawer; import android.widget.TableLayout; import android.widget.TableRow; public class InteractView extends TableLayout { private final static String TAG = "InteractView"; private Context context; private TableRow row_top, row_center, row_bottom; public InteractView(Context context) { super(context); this.context = context; setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } interface OnInteractListener { public void onInteractListener(Interact interact, String name, Object value); } private OnInteractListener listener; protected void setOnInteractListener(OnInteractListener listener) { this.listener = listener; } private Interact interact; private JSONObject layout; private List<String> layoutPositions = Arrays.asList( "top_left", "top_center", "top_right", "left", "right", "bottom_left", "bottom_center", "bottom_right"); public void set(Interact interact) { // Log.e(TAG, "set "+interact.toShortString()); this.interact = interact; removeAllViews(); JSONObject layout = interact.getLayout(); ListIterator<String> iter = layoutPositions.listIterator(); while (iter.hasNext()) { JSONArray variables; try { variables = layout.getJSONArray(iter.next()); for (int i=0; i<variables.length(); i++) addInteract(interact, variables.getString(i)); } catch (JSONException e) {} } } public void addInteract(Interact interact, String variable) { JSONObject controls = interact.getControls(); try { JSONObject control = controls.getJSONObject(variable); String control_type = control.getString("control_type"); if (control_type.equals("slider")) { String subtype = control.getString("subtype"); if (subtype.equals("discrete")) addDiscreteSlider(variable, control); else if (subtype.equals("continuous")) addContinuousSlider(variable, control); else Log.e(TAG, "Unknown slider type: "+subtype); } else if (control_type.equals("selector")) { addSelector(variable, control); } } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); } } // String variable = "n"; // JSONObject control = interact.getControls(); // try { // control = new JSONObject( //" {"+ //" \"raw\":true,"+ //" \"control_type\":\"slider\","+ //" \"display_value\":true,"+ //" \"default\":0,"+ //" \"range\":["+ //" 0,"+ //" 100"+ //" ],"+ //" \"subtype\":\"continuous\","+ //" \"label\":null,"+ //" \"step\":0.4"+ //" }"); // addSlider(variable, control); // } catch (JSONException e) { // e.printStackTrace(); // return; // } protected void addContinuousSlider(String variable, JSONObject control) throws JSONException { InteractContinuousSlider slider = new InteractContinuousSlider(this, variable, context); slider.setRange(control); addView(slider); } protected void addDiscreteSlider(String variable, JSONObject control) throws JSONException { InteractDiscreteSlider slider = new InteractDiscreteSlider(this, variable, context); slider.setValues(control); addView(slider); } protected void addSelector(String variable, JSONObject control) throws JSONException { InteractSelector selector = new InteractSelector(this, variable, context); selector.setValues(control); addView(selector); } protected void notifyChange(InteractControlBase view) { listener.onInteractListener(interact, view.getVariableName(), view.getValue()); } }
Java
package org.sagemath.droid; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.ListIterator; import java.util.UUID; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import junit.framework.Assert; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import android.content.Context; import android.util.Log; public class CellCollection { private final static String TAG = "CellCollection"; private static CellCollection instance = new CellCollection(); private LinkedList<CellData> data; private CellData current; private Context context; private CellCollection() {} public static void initialize(Context context) { if (instance.data != null) return; instance.context = context; instance.data = new LinkedList<CellData>(); CellCollectionXMLParser parser = new CellCollectionXMLParser(); InputStream ins = context.getResources().openRawResource(R.raw.cell_collection); instance.data.addAll(parser.parse(ins)); instance.current = instance.getGroup("My Worksheets").getFirst(); } public static CellCollection getInstance() { return instance; } public ListIterator<CellData> listIterator() { return data.listIterator(); } public CellData getCurrentCell() { return current; } public void setCurrentCell(CellData cell) { current = cell; } public LinkedList<CellData> getCurrentGroup() { return getGroup(current.group); } private LinkedList<String> groupsCache; public LinkedList<String> groups() { if (groupsCache != null) return groupsCache; LinkedList<String> g = new LinkedList<String>(); for (CellData cell : data) { if (g.contains(cell.group)) continue; g.add(cell.group); } Collections.sort(g); groupsCache = g; return g; } public LinkedList<CellData> getGroup(String group) { LinkedList<CellData> result = new LinkedList<CellData>(); for (CellData cell : data) if (cell.group.equals(group)) result.add(cell); Collections.sort(result, new CellComparator()); return result; } public static class CellComparator implements Comparator<CellData> { @Override public int compare(CellData c1, CellData c2) { int cmp = c2.rank.compareTo(c1.rank); if (cmp != 0) return cmp; return c1.title.compareToIgnoreCase(c2.title); } } protected File getCacheDirBase() { return context.getCacheDir(); } }
Java
package org.sagemath.droid; import java.util.LinkedList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.text.format.Formatter; import android.util.Log; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class InteractDiscreteSlider extends InteractControlBase implements OnSeekBarChangeListener { private final static String TAG = "InteractDiscreteSlider"; protected SeekBar seekBar; protected TextView nameValueText; public InteractDiscreteSlider(InteractView interactView, String variable, Context context) { super(interactView, variable, context); nameValueText = new TextView(context); nameValueText.setMaxLines(1); nameValueText.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.0f)); nameValueText.setPadding( nameValueText.getPaddingLeft()+10, nameValueText.getPaddingTop()+5, nameValueText.getPaddingRight()+5, nameValueText.getPaddingBottom()); addView(nameValueText); seekBar = new SeekBar(context); seekBar.setMax(1); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); seekBar.setLayoutParams(params); addView(seekBar); seekBar.setOnSeekBarChangeListener(this); } private LinkedList<String> values = new LinkedList<String>(); public void setValues(LinkedList<String> values) { this.values = values; seekBar.setMax(this.values.size()-1); updateValueText(); } public void setValues(JSONObject control) { this.values.clear(); try { JSONArray values= control.getJSONArray("values"); for (int i=0; i<values.length(); i++) this.values.add( values.getString(i) ); } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); this.values.add("0"); this.values.add("1"); } seekBar.setMax(this.values.size()-1); updateValueText(); } public Integer getValue() { int raw = seekBar.getProgress(); return raw; } private void updateValueText() { nameValueText.setText(getVariableName() + "=" + values.get(getValue())); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateValueText(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { interactView.notifyChange(this); } }
Java
package org.sagemath.droid; import java.util.LinkedList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.text.format.Formatter; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.Spinner; import android.widget.TextView; public class InteractSelector extends InteractControlBase implements OnItemSelectedListener { private final static String TAG = "InteractSelector"; protected Spinner spinner; protected ArrayAdapter<String> adapter; protected TextView nameValueText; protected int currentSelection = 0; public InteractSelector(InteractView interactView, String variable, Context context) { super(interactView, variable, context); nameValueText = new TextView(context); nameValueText.setMaxLines(1); // nameValueText.setLayoutParams(new LinearLayout.LayoutParams( // LinearLayout.LayoutParams.WRAP_CONTENT, // LinearLayout.LayoutParams.WRAP_CONTENT, 0.0f)); nameValueText.setPadding( nameValueText.getPaddingLeft()+10, nameValueText.getPaddingTop()+5, nameValueText.getPaddingRight()+5, nameValueText.getPaddingBottom()); addView(nameValueText); spinner = new Spinner(context); // LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( // LinearLayout.LayoutParams.WRAP_CONTENT, // LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); // spinner.setLayoutParams(params); addView(spinner); spinner.setOnItemSelectedListener(this); adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, values); spinner.setAdapter(adapter); } private LinkedList<String> values = new LinkedList<String>(); public void setValues(LinkedList<String> values) { this.values = values; adapter.notifyDataSetChanged(); currentSelection = 0; spinner.setSelection(0); updateValueText(); } public void setValues(JSONObject control) { this.values.clear(); try { JSONArray values= control.getJSONArray("value_labels"); for (int i=0; i<values.length(); i++) this.values.add( values.getString(i) ); } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); this.values.add("0"); this.values.add("1"); } adapter.notifyDataSetChanged(); currentSelection = 0; spinner.setSelection(0); updateValueText(); } public Integer getValue() { int raw = spinner.getSelectedItemPosition(); return raw; } private void updateValueText() { if (values.isEmpty() || getValue()==-1) return; Log.e(TAG, "value = "+getValue()); nameValueText.setText(getVariableName() + ":"); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3) { if (currentSelection == position) return; currentSelection = position; Log.e(TAG, "selected "+position); updateValueText(); interactView.notifyChange(this); } @Override public void onNothingSelected(AdapterView<?> parent) { } }
Java
package org.sagemath.droid; import java.util.LinkedList; import javax.crypto.spec.IvParameterSpec; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class CellGroupsAdapter extends ArrayAdapter<String> { private final Context context; private LinkedList<String> groups; public CellGroupsAdapter(Context context, LinkedList<String> groups) { super(context, R.layout.cell_groups_item, groups); this.context = context; this.groups = groups; selected = groups.indexOf(CellCollection.getInstance().getCurrentCell().getGroup()); } private int selected; public void setSelectedItem(int position) { selected = position; notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView item; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); item = (TextView) inflater.inflate(R.layout.cell_groups_item, parent, false); } else { item = (TextView) convertView; } item.setText(groups.get(position)); if (position == selected) item.setBackgroundResource(R.drawable.white); else item.setBackgroundResource(R.drawable.transparent); return item; } }
Java
/* * Copyright 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 com.example.android.actionbarcompat; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; /** * An abstract class that handles some common action bar-related functionality in the app. This * class provides functionality useful for both phones and tablets, and does not require any Android * 3.0-specific features, although it uses them if available. * * Two implementations of this class are {@link ActionBarHelperBase} for a pre-Honeycomb version of * the action bar, and {@link ActionBarHelperHoneycomb}, which uses the built-in ActionBar features * in Android 3.0 and later. */ public abstract class ActionBarHelper { protected Activity mActivity; /** * Factory method for creating {@link ActionBarHelper} objects for a * given activity. Depending on which device the app is running, either a basic helper or * Honeycomb-specific helper will be returned. */ public static ActionBarHelper createInstance(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { return new ActionBarHelperICS(activity); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return new ActionBarHelperHoneycomb(activity); } else { return new ActionBarHelperBase(activity); } } protected ActionBarHelper(Activity activity) { mActivity = activity; } /** * Action bar helper code to be run in {@link Activity#onCreate(android.os.Bundle)}. */ public void onCreate(Bundle savedInstanceState) { } /** * Action bar helper code to be run in {@link Activity#onPostCreate(android.os.Bundle)}. */ public void onPostCreate(Bundle savedInstanceState) { } /** * Action bar helper code to be run in {@link Activity#onCreateOptionsMenu(android.view.Menu)}. * * NOTE: Setting the visibility of menu items in <em>menu</em> is not currently supported. */ public boolean onCreateOptionsMenu(Menu menu) { return true; } /** * Action bar helper code to be run in {@link Activity#onTitleChanged(CharSequence, int)}. */ public void onTitleChanged(CharSequence title, int color) { } /** * Sets the indeterminate loading state of the item with ID {@link R.id.menu_refresh}. * (where the item ID was menu_refresh). */ public abstract void setRefreshActionItemState(boolean refreshing); /** * Returns a {@link MenuInflater} for use when inflating menus. The implementation of this * method in {@link ActionBarHelperBase} returns a wrapped menu inflater that can read * action bar metadata from a menu resource pre-Honeycomb. */ public MenuInflater getMenuInflater(MenuInflater superMenuInflater) { return superMenuInflater; } }
Java
/* * Copyright 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 com.example.android.actionbarcompat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import java.util.ArrayList; /** * A <em>really</em> dumb implementation of the {@link android.view.Menu} interface, that's only * useful for our actionbar-compat purposes. See * <code>com.android.internal.view.menu.MenuBuilder</code> in AOSP for a more complete * implementation. */ public class SimpleMenu implements Menu { private Context mContext; private Resources mResources; private ArrayList<SimpleMenuItem> mItems; public SimpleMenu(Context context) { mContext = context; mResources = context.getResources(); mItems = new ArrayList<SimpleMenuItem>(); } public Context getContext() { return mContext; } public Resources getResources() { return mResources; } public MenuItem add(CharSequence title) { return addInternal(0, 0, title); } public MenuItem add(int titleRes) { return addInternal(0, 0, mResources.getString(titleRes)); } public MenuItem add(int groupId, int itemId, int order, CharSequence title) { return addInternal(itemId, order, title); } public MenuItem add(int groupId, int itemId, int order, int titleRes) { return addInternal(itemId, order, mResources.getString(titleRes)); } /** * Adds an item to the menu. The other add methods funnel to this. */ private MenuItem addInternal(int itemId, int order, CharSequence title) { final SimpleMenuItem item = new SimpleMenuItem(this, itemId, order, title); mItems.add(findInsertIndex(mItems, order), item); return item; } private static int findInsertIndex(ArrayList<? extends MenuItem> items, int order) { for (int i = items.size() - 1; i >= 0; i--) { MenuItem item = items.get(i); if (item.getOrder() <= order) { return i + 1; } } return 0; } public int findItemIndex(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return i; } } return -1; } public void removeItem(int itemId) { removeItemAtInt(findItemIndex(itemId)); } private void removeItemAtInt(int index) { if ((index < 0) || (index >= mItems.size())) { return; } mItems.remove(index); } public void clear() { mItems.clear(); } public MenuItem findItem(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return item; } } return null; } public int size() { return mItems.size(); } public MenuItem getItem(int index) { return mItems.get(index); } // Unsupported operations. public SubMenu addSubMenu(CharSequence charSequence) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public int addIntentOptions(int i, int i1, int i2, ComponentName componentName, Intent[] intents, Intent intent, int i3, MenuItem[] menuItems) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void removeGroup(int i) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupCheckable(int i, boolean b, boolean b1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupVisible(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupEnabled(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean hasVisibleItems() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void close() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performShortcut(int i, KeyEvent keyEvent, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean isShortcutKey(int i, KeyEvent keyEvent) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performIdentifierAction(int i, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setQwertyMode(boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } }
Java
/* * Copyright 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 com.example.android.actionbarcompat; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ActionProvider; import android.view.ContextMenu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; /** * A <em>really</em> dumb implementation of the {@link android.view.MenuItem} interface, that's only * useful for our actionbar-compat purposes. See * <code>com.android.internal.view.menu.MenuItemImpl</code> in AOSP for a more complete * implementation. */ public class SimpleMenuItem implements MenuItem { private SimpleMenu mMenu; private final int mId; private final int mOrder; private CharSequence mTitle; private CharSequence mTitleCondensed; private Drawable mIconDrawable; private int mIconResId = 0; private boolean mEnabled = true; public SimpleMenuItem(SimpleMenu menu, int id, int order, CharSequence title) { mMenu = menu; mId = id; mOrder = order; mTitle = title; } public int getItemId() { return mId; } public int getOrder() { return mOrder; } public MenuItem setTitle(CharSequence title) { mTitle = title; return this; } public MenuItem setTitle(int titleRes) { return setTitle(mMenu.getContext().getString(titleRes)); } public CharSequence getTitle() { return mTitle; } public MenuItem setTitleCondensed(CharSequence title) { mTitleCondensed = title; return this; } public CharSequence getTitleCondensed() { return mTitleCondensed != null ? mTitleCondensed : mTitle; } public MenuItem setIcon(Drawable icon) { mIconResId = 0; mIconDrawable = icon; return this; } public MenuItem setIcon(int iconResId) { mIconDrawable = null; mIconResId = iconResId; return this; } public Drawable getIcon() { if (mIconDrawable != null) { return mIconDrawable; } if (mIconResId != 0) { return mMenu.getResources().getDrawable(mIconResId); } return null; } public MenuItem setEnabled(boolean enabled) { mEnabled = enabled; return this; } public boolean isEnabled() { return mEnabled; } // No-op operations. We use no-ops to allow inflation from menu XML. public int getGroupId() { // Noop return 0; } public View getActionView() { // Noop return null; } public MenuItem setActionProvider(ActionProvider actionProvider) { // Noop return this; } public ActionProvider getActionProvider() { // Noop return null; } public boolean expandActionView() { // Noop return false; } public boolean collapseActionView() { // Noop return false; } public boolean isActionViewExpanded() { // Noop return false; } @Override public MenuItem setOnActionExpandListener(OnActionExpandListener onActionExpandListener) { // Noop return this; } public MenuItem setIntent(Intent intent) { // Noop return this; } public Intent getIntent() { // Noop return null; } public MenuItem setShortcut(char c, char c1) { // Noop return this; } public MenuItem setNumericShortcut(char c) { // Noop return this; } public char getNumericShortcut() { // Noop return 0; } public MenuItem setAlphabeticShortcut(char c) { // Noop return this; } public char getAlphabeticShortcut() { // Noop return 0; } public MenuItem setCheckable(boolean b) { // Noop return this; } public boolean isCheckable() { // Noop return false; } public MenuItem setChecked(boolean b) { // Noop return this; } public boolean isChecked() { // Noop return false; } public MenuItem setVisible(boolean b) { // Noop return this; } public boolean isVisible() { // Noop return true; } public boolean hasSubMenu() { // Noop return false; } public SubMenu getSubMenu() { // Noop return null; } public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener onMenuItemClickListener) { // Noop return this; } public ContextMenu.ContextMenuInfo getMenuInfo() { // Noop return null; } public void setShowAsAction(int i) { // Noop } public MenuItem setShowAsActionFlags(int i) { // Noop return null; } public MenuItem setActionView(View view) { // Noop return this; } public MenuItem setActionView(int i) { // Noop return this; } }
Java
/* * Copyright 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 com.example.android.actionbarcompat; import android.app.Activity; import android.content.Context; import android.view.Menu; import android.view.MenuItem; /** * An extension of {@link com.example.android.actionbarcompat.ActionBarHelper} that provides Android * 4.0-specific functionality for IceCreamSandwich devices. It thus requires API level 14. */ public class ActionBarHelperICS extends ActionBarHelperHoneycomb { protected ActionBarHelperICS(Activity activity) { super(activity); } @Override protected Context getActionBarThemedContext() { return mActivity.getActionBar().getThemedContext(); } }
Java
/* * Copyright 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 com.example.android.actionbarcompat; import org.sagemath.droid.R; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; /** * An extension of {@link ActionBarHelper} that provides Android 3.0-specific functionality for * Honeycomb tablets. It thus requires API level 11. */ public class ActionBarHelperHoneycomb extends ActionBarHelper { private Menu mOptionsMenu; private View mRefreshIndeterminateProgressView = null; protected ActionBarHelperHoneycomb(Activity activity) { super(activity); } @Override public boolean onCreateOptionsMenu(Menu menu) { mOptionsMenu = menu; return super.onCreateOptionsMenu(menu); } @Override public void setRefreshActionItemState(boolean refreshing) { // On Honeycomb, we can set the state of the refresh button by giving it a custom // action view. if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { if (mRefreshIndeterminateProgressView == null) { LayoutInflater inflater = (LayoutInflater) getActionBarThemedContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); mRefreshIndeterminateProgressView = inflater.inflate( R.layout.actionbar_indeterminate_progress, null); } refreshItem.setActionView(mRefreshIndeterminateProgressView); } else { refreshItem.setActionView(null); } } } /** * Returns a {@link Context} suitable for inflating layouts for the action bar. The * implementation for this method in {@link ActionBarHelperICS} asks the action bar for a * themed context. */ protected Context getActionBarThemedContext() { return mActivity; } }
Java