package com.algomagic.atn; import java.util.*; import javax.swing.*; public class PlayBackController extends Observable implements Observer, VisualizationConstants { private int _delay; private boolean _loop; private List _updates; private int _index = 0; private boolean _clear = true; private boolean _playing = false; public PlayBackController( List updates, Properties properties ) { _delay = Integer.parseInt( properties.getProperty( DELAY_PROP, DELAY_DEFAULT ) ); _loop = (new Boolean( properties.getProperty( LOOP_PROP, LOOP_DEFAULT ) )).booleanValue( ); _updates = updates; } public void update( Observable o, Object arg ) { if( arg instanceof String ) { String cmd = (String)arg; if( cmd.equals( "play" ) ) { _playing = true; new Thread( new PlayThread( ) ).start( ); } else if( cmd.equals( "pause" ) ) { _playing = false; } else if( cmd.equals( "stepf" ) ) { stepf( ); } else if( cmd.equals( "stepb" ) ) { stepb( ); } else if( cmd.equals( "ff" ) ) { ff( ); } else if( cmd.equals( "rewind" ) ) { rewind( ); } } else if( arg instanceof JSpinner ) { SpinnerNumberModel snm = (SpinnerNumberModel)((JSpinner)arg).getModel( ); _delay = snm.getNumber( ).intValue( ); } else if (arg instanceof Boolean ) { _loop = ((Boolean)arg).booleanValue( ); } } public int getIndex( ) { return _index; } private synchronized void stepf( ) { if( _index == _updates.size( ) ) { _index = 0; if( _playing == true && _loop == false ) { _playing = false; } } if( _index == 0 && _clear == false ) { _clear = true; setChanged( ); notifyObservers( "CLEAR" ); return; } _clear = false; PanelUpdate u = (PanelUpdate)_updates.get(_index); u.setUndo( false ); setChanged( ); notifyObservers( u ); _index++; } private synchronized void stepb( ) { // System.out.println( "steck back " + _index ); // System.out.print( "stepb: " + _index + " " ); if( _index == 0 ) { ff( ); // System.out.println( _index ); return; } _index--; PanelUpdate u = (PanelUpdate)_updates.get( _index ); u.setUndo( true ); setChanged( ); notifyObservers( u ); // System.out.println( _index ); if( _index == 0 ) { _clear = true; } } private synchronized void ff( ) { int i; // System.out.print( "ff: " + _index + " " ); for( i=_index; i < _updates.size( ); i++ ) { setChanged( ); PanelUpdate u = (PanelUpdate)_updates.get(i); u.setUndo( false ); _index=i; notifyObservers( u ); // System.out.println( "here" ); } _clear = false; _index=i; // System.out.println( _index ); } private synchronized void rewind( ) { _index = 0; _clear = true; setChanged( ); notifyObservers( "CLEAR" ); } private class PlayThread implements Runnable { public void run( ) { while( _playing ) { try { stepf( ); Thread.currentThread( ).sleep( _delay ); } catch( InterruptedException ie ) { throw new RuntimeException( ie ); } } } } }