package animation; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.Stack; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.SwingUtilities; import animation.Memory.MemoryType; import animation.PseudoCodeNode.CodeStatus; import animation.StackFrame.FrameType; import graph.LayeredGraphNode; public abstract class AnimatedAlgorithm extends Thread implements AlgorithmStage { protected AnimationController ac; protected LayeredGraphNode graph; private JFrame view; protected PseudoCodeNode root; protected Stack activeFunction; protected Memory mem; public AnimatedAlgorithm( AnimationController controller, LayeredGraphNode graph, JFrame view ) { this.ac = controller; this.graph = graph; this.view = view; root = null; mem = new Memory(); mem.declare( "graph", graph, MemoryType.GLOBAL ); mem.addFrame( new StackFrame( FrameType.FUNCTION ) ); activeFunction = new Stack(); } public Memory getMemory() { return mem; } public void addActiveFunction( PseudoCodeNode n ) { if( !activeFunction.empty() ) activeFunction.peek().writeToStack( mem ); activeFunction.push( n ); } public PseudoCodeNode getActiveFunction() { if( activeFunction.empty() ) return null; return activeFunction.peek(); } public boolean isActiveFunction( PseudoCodeNode n ) { if( activeFunction.empty() ) return false; return activeFunction.peek() == n; } private void update() { SwingUtilities.invokeLater(new Runnable() { public void run() { view.repaint(); for( ComponentListener l : view.getComponentListeners() ) { l.componentResized( new ComponentEvent(view, 0) ); } } }); } @Override public void run() { while( true ) // if this loop would end we could not undo steps any more { CodeStatus status = null; try { while( activeFunction.size() == 0 ) Thread.sleep( 100 ); PseudoCodeNode current = activeFunction.peek(); switch( ac.getNextAction() ) { case FORWARD: status = current.forwardStep( mem ); break; case FORWARD_OUT: status = current.forwardStepOut( mem ); break; case FORWARD_OVER: status = current.forwardStepOver( mem ); break; case BACKWARD: status = current.backwardStep( mem ); break; case BACKWARD_OUT: status = current.backwardStepOut( mem ); break; case BACKWARD_OVER: status = current.backwardStepOver( mem ); break; } System.out.println( "Stack Frames: " + mem.getSize() ); } catch (InterruptedException e) { e.printStackTrace(); return; } update(); if( status == CodeStatus.FINISHED ) { if( activeFunction.size() > 1 ) { activeFunction.pop(); activeFunction.peek().loadFromStack( mem ); } else { ac.setContinuous( false ); ac.setNextAction( null ); } } } } @Override public abstract PseudoCodeNode createPseudocodeTree( JTree tree ); }