Subversion Repositories svnkaklik

Compare Revisions

Regard whitespace Rev 156 → Rev 157

/programy/Java/AVRcamVIEW/src/avr/connection/AbstractConnection.java
0,0 → 1,160
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.connection;
 
import javax.swing.event.*;
 
import avr.connection.event.*;
 
/***********************************************************************
* Defines a Connection that fires events describing if the connection
* was opened or closed.
*/
public abstract class AbstractConnection implements Connection {
 
/**
* The list of registered event listeners.
*/
private EventListenerList listenerList;
 
/**
* Boolean to test if the connection is connected (true) or
* disconnected (false).
*/
private boolean connected;
 
/**
* Initialize this object and set connected to false.
*/
protected AbstractConnection() {
listenerList = new EventListenerList();
connected = false;
}
 
/**
* Set connected to true and fire a connected event.
*/
protected void setConnected() {
setConnected(true);
fireConnectedEvent(this);
}
 
/**
* Set connected to false and fire a disconnected event.
*/
protected void setDisconnected() {
setConnected(false);
fireDisconnectedEvent(this);
}
 
/**
* Set this connected variable to the given value.
* @param connected true if this connection is connected, false otherwise.
*/
private void setConnected(boolean connected) {
this.connected = connected;
}
 
/**
* Tells whether or not this connection is connected.
* @return true if, and only if, this connection is connected.
*/
public boolean isConnected() {
return connected;
}
 
/**
* Adds a listener to the list that's notified each time a connect or
* disconnect occurs.
* @param cl the ConnectionListener
*/
public void addConnectionListener(ConnectionListener cl) {
listenerList.add(ConnectionListener.class, cl);
}
 
/**
* Removes a listener to the list that's notified each time a connect or
* disconnect occurs.
* @param cl the ConnectionListener
*/
public void removeConnectionListener(ConnectionListener cl) {
listenerList.remove(ConnectionListener.class, cl);
}
 
public void removeAllConnectionListeners() {
ConnectionListener[] listeners = getConnectionListeners();
for(int i = 0; i < listeners.length; i++) {
removeConnectionListener(listeners[i]);
}
}
 
/**
* Returns an array of all the connection listeners registered on
* this connection.
* @return all of this connection's ConnectionListeners or
* an empty array if no connection listeners are currently registered
*/
public ConnectionListener[] getConnectionListeners() {
return (ConnectionListener[])
listenerList.getListeners(ConnectionListener.class);
}
 
/**
* Notifies all listeners that a connection has been established.
* @param source This connection.
*/
protected void fireConnectedEvent(Object source) {
ConnectionListener[] listeners = getConnectionListeners();
 
ConnectionEvent event = null;
 
for(int i = 0; i < listeners.length; i++) {
if(event == null) {
event = new ConnectionEvent(this);
}
listeners[i].connected(event);
}
}
 
/**
* Notifies all listeners that a connection has been destroyed.
* @param source This connection.
*/
protected void fireDisconnectedEvent(Object source) {
ConnectionListener[] listeners = getConnectionListeners();
 
ConnectionEvent event = null;
 
for(int i = 0; i < listeners.length; i++) {
if(event == null) {
event = new ConnectionEvent(this);
}
listeners[i].disconnected(event);
}
}
 
}
/programy/Java/AVRcamVIEW/src/avr/connection/Connection.java
0,0 → 1,81
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.connection;
 
import java.io.*;
import java.nio.channels.*;
 
/***********************************************************************
* Defines methods for some type of I/O Connection.
*/
public interface Connection {
 
/**
* Connects this connection.
* @throws IOException If the connection could not be connected.
*/
public void connect() throws Exception;
 
/**
* Disconnects this connection.
* @throws IOException If the connection could not be disconnected.
*/
public void disconnect() throws IOException;
 
/**
* Returns the Object to which this connection is wrapped around.
* @return The Object to which this connection is wrapped around.
*/
public Object getConnectionObject();
 
/**
* Tells whether or not this connection is connected.
* @return true if, and only if, this connection is connected.
*/
public boolean isConnected();
 
/**
* Returns the InputStream associated with this connection.
* @return The InputStream associated with this connection.
* @throws IOException If the InputStream could not be returned.
*/
public InputStream getInputStream() throws IOException;
 
/**
* Returns the OutputStream associated with this connection.
* @return The OutputStream associated with this connection.
* @throws IOException If the OutputStream could not be returned.
*/
public OutputStream getOutputStream() throws IOException;
 
/**
* Returns the ByteChannel associated with this connection.
* @return The ByteChannel associated with this connection.
*/
public ByteChannel getChannel();
 
}
/programy/Java/AVRcamVIEW/src/avr/connection/SerialConnection.java
0,0 → 1,128
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.connection;
 
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
 
import javax.comm.*;
 
/***********************************************************************
* This class represents a Connection to a Serial Port.
*/
public class SerialConnection extends AbstractConnection {
 
private SerialPort serialPort;
private SerialParams params;
private String comPort;
 
public static String[] getSerialPorts() {
 
ArrayList ports = new ArrayList();
 
Enumeration allPorts = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier identifier;
 
while(allPorts.hasMoreElements()) {
identifier = (CommPortIdentifier)allPorts.nextElement();
if(identifier.getPortType() == CommPortIdentifier.PORT_SERIAL) {
ports.add(identifier.getName());
}
}
 
Collections.reverse(ports);
 
return (String[])ports.toArray(new String[ports.size()]);
 
}
 
public SerialConnection(String comPort) {
this(comPort, new SerialParams());
}
 
public SerialConnection(String comPort, SerialParams params) {
this.comPort = comPort;
this.params = params;
}
 
public Object getConnectionObject() {
return serialPort;
}
 
public synchronized void connect() throws Exception {
CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(comPort);
serialPort = (SerialPort)identifier.open("AVRcamView", 2000);
serialPort.setFlowControlMode(params.getFlowControl());
serialPort.setSerialPortParams(params.getBaudRate(),
params.getDataBits(),
params.getStopBits(),
params.getParity());
setConnected();
}
 
public synchronized void disconnect() throws IOException {
serialPort.close();
setDisconnected();
}
 
public InputStream getInputStream() throws IOException {
return serialPort.getInputStream();
}
 
public OutputStream getOutputStream() throws IOException {
return serialPort.getOutputStream();
}
 
public ByteChannel getChannel() {
return null;
}
 
public String toString() {
return serialPort.toString();
}
 
public void setSerialParams(SerialParams params) throws UnsupportedCommOperationException {
serialPort.setFlowControlMode(params.getFlowControl());
serialPort.setSerialPortParams(params.getBaudRate(),
params.getDataBits(),
params.getStopBits(),
params.getParity());
this.params = params;
}
 
public String getComPort() {
return comPort;
}
 
public SerialParams getSerialParams() {
return params;
}
 
}
/programy/Java/AVRcamVIEW/src/avr/connection/SerialParams.java
0,0 → 1,127
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.connection;
 
import java.io.*;
import java.util.*;
import javax.comm.*;
 
public class SerialParams implements Serializable {
 
public static void main(String[] args) {
System.out.println("Flow Control None: " + SerialPort.FLOWCONTROL_NONE);
System.out.println("Flow Control RTSCTS IN: " + SerialPort.FLOWCONTROL_RTSCTS_IN);
System.out.println("Flow Control RTSCTS OUT: " + SerialPort.FLOWCONTROL_RTSCTS_OUT);
System.out.println("Flow Control XON/XOFF IN: " + SerialPort.FLOWCONTROL_XONXOFF_IN);
System.out.println("Flow Control XON/XOFF OUT: " + SerialPort.FLOWCONTROL_XONXOFF_OUT);
 
System.out.println("Data Bits 5: " + SerialPort.DATABITS_5);
System.out.println("Data Bits 6: " + SerialPort.DATABITS_6);
System.out.println("Data Bits 7: " + SerialPort.DATABITS_7);
System.out.println("Data Bits 8: " + SerialPort.DATABITS_8);
 
System.out.println("Parity Even: " + SerialPort.PARITY_EVEN);
System.out.println("Parity Odd: " + SerialPort.PARITY_ODD);
System.out.println("Parity Mark: " + SerialPort.PARITY_MARK);
System.out.println("Parity Space: " + SerialPort.PARITY_SPACE);
System.out.println("Parity None: " + SerialPort.PARITY_NONE);
 
System.out.println("Stop Bits 1: " + SerialPort.STOPBITS_1);
System.out.println("Stop Bits 1.5: " + SerialPort.STOPBITS_1_5);
System.out.println("Stop Bits 2: " + SerialPort.STOPBITS_2);
}
 
private int baudRate;
private int dataBits;
private int stopBits;
private int parity;
private int flowControl;
 
public SerialParams() {
this(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, SerialPort.FLOWCONTROL_NONE);
}
 
public SerialParams(int baudRate, int dataBits,
int stopBits, int parity, int flowControl) {
this.baudRate = baudRate;
this.dataBits = dataBits;
this.stopBits = stopBits;
this.parity = parity;
this.flowControl = flowControl;
}
 
public int getBaudRate() {
return baudRate;
}
 
public int getFlowControl() {
return flowControl;
}
 
public int getDataBits() {
return dataBits;
}
 
public int getParity() {
return parity;
}
 
public int getStopBits() {
return stopBits;
}
 
public void setStopBits(int stopBits) {
this.stopBits = stopBits;
}
 
public void setParity(int parity) {
this.parity = parity;
}
 
public void setFlowControl(int flowControl) {
this.flowControl = flowControl;
}
 
public void setDataBits(int dataBits) {
this.dataBits = dataBits;
}
 
public void setBaudRate(int baudRate) {
this.baudRate = baudRate;
}
 
public String toString() {
StringBuffer builder = new StringBuffer("Serial Parameters[");
builder.append("baudrate=").append(baudRate)
.append("databits=").append(dataBits)
.append("stopbits=").append(stopBits)
.append("parity=").append(parity)
.append("flowcontrol=").append(flowControl);
return builder.toString();
}
 
}
/programy/Java/AVRcamVIEW/src/avr/connection/event/ConnectionEvent.java
0,0 → 1,47
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.connection.event;
 
import java.util.*;
 
import avr.connection.*;
import avr.device.*;
 
/***********************************************************************
* Defines and event to be fired when a Connection is opened or closed.
*/
public class ConnectionEvent extends EventObject {
 
/**
* Constructs a Connection Event created by the given Connection object.
* @param source The object firing this event.
*/
public ConnectionEvent(Object source) {
super(source);
}
 
}
/programy/Java/AVRcamVIEW/src/avr/connection/event/ConnectionListener.java
0,0 → 1,49
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.connection.event;
 
import java.util.*;
 
/***********************************************************************
* This class defines methods that are invoked when a Connection is
* either opened or closed.
*/
public interface ConnectionListener extends EventListener {
 
/**
* Invoked when a Connection is opened.
* @param ce A ConnectionEvent encapsulating the event information.
*/
public void connected(ConnectionEvent ce);
 
/**
* Invoked when a Connection is closed.
* @param ce A ConnectionEvent encapsulating the event information.
*/
public void disconnected(ConnectionEvent ce);
 
}
/programy/Java/AVRcamVIEW/src/avr/device/Device.java
0,0 → 1,601
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.device;
 
import java.io.*;
import java.nio.*;
import java.util.*;
import javax.comm.*;
 
import java.awt.*;
 
import avr.connection.*;
import avr.connection.event.*;
import avr.device.event.*;
import avr.io.*;
import avr.lang.*;
 
public class Device implements ConnectionListener {
 
public static void main(String[] args) throws Exception {
Device device = new Device();
 
SerialParams params = new SerialParams();
 
device.setConnection(new SerialConnection("COM1", params));
 
device.connect();
device.sendPing();
device.sendDumpFrame();
device.sendGetVersion();
device.sendSetRegisters(new HashMap());
device.sendReset();
device.sendEnableTracking();
device.sendDisableTracking();
device.sendSetColorMap(null, null, null);
 
try {
System.in.read();
} catch(IOException ioe) {
ioe.printStackTrace();
}
device.disconnect();
 
}
 
private static final String ACK = "ACK";
private static final String NCK = "NCK";
private static final String VERSION = "AVR";
 
private static final String COLOR_MAP_KEY = "avr.color.map";
 
// timeout after 3 seconds
private static final int RESPONSE_TIMEOUT = 3000;
 
private java.util.List connectionListeners;
private java.util.List dataListeners;
private AbstractConnection con;
 
private InputStream in;
private OutputStream out;
 
private int[][] colorMap;
private Color[] mapColors;
 
private Timer responseTimer;
private TimerTask responseTask;
 
public Device() {
connectionListeners = new ArrayList(3);
dataListeners = new ArrayList(3);
loadMap();
 
responseTimer = new Timer();
}
 
public Color[] getMapColors() {
return mapColors;
}
 
public int[][] getColorMap() {
return colorMap;
}
 
public void setColorMap(int[][] colorMap) {
this.colorMap = colorMap;
setMapColors();
saveMap();
}
 
public void saveMap() {
try {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DataOutputStream dOut = new DataOutputStream(bOut);
 
dOut.writeInt(colorMap.length);
for(int i = 0; i < colorMap.length; i++) {
dOut.writeInt(colorMap[i].length);
for(int j = 0; j < colorMap[i].length; j++) {
dOut.writeInt(colorMap[i][j]);
}
}
 
dOut.close();
 
AVRSystem.PREFS.putByteArray(COLOR_MAP_KEY, bOut.toByteArray());
 
} catch(Exception e) {
e.printStackTrace();
}
}
 
public void loadMap() {
try {
byte[] data = AVRSystem.PREFS.getByteArray(COLOR_MAP_KEY, null);
if(data != null) {
ByteArrayInputStream bIn = new ByteArrayInputStream(data);
DataInputStream dIn = new DataInputStream(bIn);
 
int width = dIn.readInt();
colorMap = new int[width][];
for(int i = 0; i < colorMap.length; i++) {
colorMap[i] = new int[dIn.readInt()];
for(int j = 0; j < colorMap[i].length; j++) {
colorMap[i][j] = dIn.readInt();
}
}
 
dIn.close();
} else {
colorMap = new int[3][AVRSystem.NUM_INTENSITIES];
}
 
setMapColors();
 
} catch(Exception e) {
e.printStackTrace();
}
 
}
 
private void setMapColors() {
mapColors = new Color[8];
 
for(int col = 0; col < mapColors.length; col++) {
int value = 0;
 
int red = 0;
int green = 0;
int blue = 0;
 
int numRed = 0;
int numGreen = 0;
int numBlue = 0;
 
 
for(int i = 0; i < AVRSystem.NUM_INTENSITIES; i++) {
 
if((colorMap[0][i] & (0x01 << (7 - col))) != 0) {
red += i << 4;
numRed++;
}
 
if((colorMap[1][i] & (0x01 << (7 - col))) != 0) {
green += i << 4;
numGreen++;
}
 
if((colorMap[2][i] & (0x01 << (7 - col))) != 0) {
blue += i << 4;
numBlue++;
}
 
}
 
if(numRed > 0) {
red /= numRed;
}
 
if(numGreen > 0) {
green /= numGreen;
}
 
if(numBlue > 0) {
blue /= numBlue;
}
 
value = (red << 16) | (green << 8) | blue;
 
mapColors[col] = new Color(value);
}
 
}
 
public AbstractConnection getConnection() {
return con;
}
 
public void setConnection(AbstractConnection con) {
this.con = con;
}
 
public boolean isConnected() {
return con != null && con.isConnected();
}
 
public void addConnectionListener(ConnectionListener listener) {
AVRSystem.LOG.finest("Added Connection Listener: " + listener);
connectionListeners.add(listener);
}
 
public void removeConnectionListener(ConnectionListener listener) {
AVRSystem.LOG.finest("Removed Connection Listener: " + listener);
connectionListeners.remove(listener);
}
 
public void connected(ConnectionEvent event) {
ConnectionListener[] listeners = (ConnectionListener[])connectionListeners.toArray(new ConnectionListener[connectionListeners.size()]);
for(int i = 0; i < listeners.length; i++) {
((ConnectionListener)listeners[i]).connected(event);
}
}
 
public void disconnected(ConnectionEvent event) {
ConnectionListener[] listeners = (ConnectionListener[])connectionListeners.toArray(new ConnectionListener[connectionListeners.size()]);
for(int i = 0; i < listeners.length; i++) {
((ConnectionListener)listeners[i]).disconnected(event);
}
}
 
public void connect() throws Exception {
 
if(!isConnected()) {
con.connect();
 
if(con instanceof SerialConnection) {
SerialPort serialPort = (SerialPort)con.getConnectionObject();
serialPort.notifyOnDataAvailable(true);
try {
serialPort.addEventListener(new SerialEventHandler(this));
} catch(TooManyListenersException tmle) {
AVRSystem.LOG.severe(tmle.getMessage());
}
}
 
in = new AVRInputStream(con.getInputStream());
out = con.getOutputStream();
 
AVRSystem.LOG.config("Device connected to " + con.toString());
 
connected(new ConnectionEvent(con));
 
}
}
 
public void disconnect() {
 
if(isConnected()) {
try {
con.disconnect();
AVRSystem.LOG.config("Device Disconnected");
disconnected(new ConnectionEvent(con));
con = null;
} catch(IOException ioe) {
AVRSystem.LOG.severe(ioe.getMessage());
}
}
}
 
public InputStream getInputStream() {
return in;
}
 
public void addDataListener(DataListener dl) {
if(dataListeners.add(dl)) {
AVRSystem.LOG.finest("Added Data Listener: " + dl);
}
}
 
public void removeDataListener(DataListener dl) {
if(dataListeners.remove(dl)) {
AVRSystem.LOG.finest("Removed Data Listener: " + dl);
}
}
 
protected void handleString(String data) {
if(data.equals(ACK)) {
fireACKReceived();
} else if(data.equals(NCK)) {
fireNCKReceived();
} else if(data.startsWith(VERSION)) {
fireVERSIONReceived(data);
} else {
StringBuffer builder = new StringBuffer("UNKNOWN PACKET: (");
ByteBuffer bytes = ByteBuffer.wrap(data.getBytes());
builder.append(bytes.remaining()).append(") ");
while(bytes.hasRemaining()) {
builder.append(Integer.toHexString(bytes.get() & 0xFF)).append(' ');
}
AVRSystem.LOG.warning(builder.toString());
}
}
 
protected void handleData(ByteBuffer data) {
if(data.hasRemaining()) {
byte dataType = data.get();
if(dataType == 0x0B) {
fireFrameDataReceived(data);
} else if(dataType == 0x0A) {
fireTrackingDataReceived(data);
} else {
handleString(new String(data.array(), 0, data.limit()));
}
}
}
 
protected void fireACKReceived() {
if(responseTask != null) {
responseTask.cancel();
}
AVRSystem.LOG.info("Received: ACK");
DataListener[] listeners = (DataListener[])dataListeners.toArray(new DataListener[dataListeners.size()]);
for(int i = 0; i < listeners.length; i++) {
((DataListener)listeners[i]).ack();
}
}
 
private void fireResponseTimerExpired() {
AVRSystem.LOG.severe("Response Timer Expired");
DataListener[] listeners = (DataListener[])dataListeners.toArray(new DataListener[dataListeners.size()]);
for(int i = 0; i < listeners.length; i++) {
((DataListener)listeners[i]).responseTimerExpired();
}
}
 
protected void fireNCKReceived() {
if(responseTask != null) {
responseTask.cancel();
}
AVRSystem.LOG.info("Received: NCK");
DataListener[] listeners = (DataListener[])dataListeners.toArray(new DataListener[dataListeners.size()]);
for(int i = 0; i < listeners.length; i++) {
((DataListener)listeners[i]).nck();
}
}
 
protected void fireVERSIONReceived(String version) {
if(responseTask != null) {
responseTask.cancel();
}
AVRSystem.LOG.info("Received: " + version);
DataListener[] listeners = (DataListener[])dataListeners.toArray(new DataListener[dataListeners.size()]);
for(int i = 0; i < listeners.length; i++) {
((DataListener)listeners[i]).version(version);
}
}
 
protected void fireFrameDataReceived(ByteBuffer data) {
 
int position = data.position();
StringBuffer buf = new StringBuffer("Received: Frame Dump (" + (data.get(position) & 0xFF) + ")");
 
data.position(0);
 
while(data.hasRemaining()) {
int b = data.get() & 0xFF;
buf.append(' ').append(((b & 0xF0) == 0) ? "0" : "").append(Integer.toHexString(b).toUpperCase());
}
 
data.position(position);
 
AVRSystem.LOG.info(buf.toString());
// AVRSystem.LOG.info("Received: Frame Dump (" + (data.get(data.position()) & 0xFF) + ")");
DataListener[] listeners = (DataListener[])dataListeners.toArray(new DataListener[dataListeners.size()]);
for(int i = 0; i < listeners.length; i++) {
data.mark();
((DataListener)listeners[i]).frameData(data);
data.reset();
}
}
 
protected void fireTrackingDataReceived(ByteBuffer data) {
 
int position = data.position();
StringBuffer buf = new StringBuffer("Received: Tracking Info (" + (data.get(position) & 0xFF) + ")");
 
data.position(0);
 
while(data.hasRemaining()) {
int b = data.get() & 0xFF;
buf.append(' ').append(((b & 0xF0) == 0) ? "0" : "").append(Integer.toHexString(b).toUpperCase());
}
 
data.position(position);
 
AVRSystem.LOG.info(buf.toString());
DataListener[] listeners = (DataListener[])dataListeners.toArray(new DataListener[dataListeners.size()]);
for(int i = 0; i < listeners.length; i++) {
data.mark();
((DataListener)listeners[i]).trackingData(data);
data.reset();
}
}
 
private void sendRequest(byte[] data) throws IOException {
sendRequest(data, 0, data.length);
}
 
private void sendRequest(byte[] data, int off, int len) throws IOException {
 
responseTask = new ResponseTask();
responseTimer.schedule(responseTask, RESPONSE_TIMEOUT);
 
if(isConnected()) {
 
out.write(data, off, len);
out.write((byte)'\n');
out.flush();
 
StringBuffer builder = new StringBuffer("Sending: ");
for(int i = off; i < len; i++) {
builder.append((char)data[i]);
}
AVRSystem.LOG.info(builder.toString());
} else {
AVRSystem.LOG.warning("AVRcam not connected.");
}
}
 
public void sendSetRegisters(Map registers) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(60);
buffer.put((byte)'C')
.put((byte)'R');
 
Set entries = registers.entrySet();
for(Iterator i = entries.iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
buffer.put((byte)' ').put(entry.getKey().toString().getBytes())
.put((byte)' ').put(entry.getValue().toString().getBytes());
}
 
buffer.put((byte)'\r');
buffer.flip();
sendRequest(buffer.array(), 0, buffer.remaining());
}
 
public void sendDisableTracking() throws IOException {
sendRequest(new byte[] { (byte)'D', (byte)'T', (byte)'\r'} );
}
 
public void sendDumpFrame() throws IOException {
sendRequest(new byte[] { (byte)'D', (byte)'F', (byte)'\r'} );
}
 
public void sendEnableTracking() throws IOException {
sendRequest(new byte[] { (byte)'E', (byte)'T', (byte)'\r'} );
}
 
public void sendGetVersion() throws IOException {
sendRequest(new byte[] { (byte)'G', (byte)'V', (byte)'\r'} );
}
 
public void sendPing() throws IOException {
sendRequest(new byte[] { (byte)'P', (byte)'G', (byte)'\r'} );
}
 
public void sendReset() throws IOException {
sendRequest(new byte[] { (byte)'R', (byte)'S', (byte)'\r'} );
}
 
public void sendSetColorMap(int[] red, int[] green, int[] blue) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(2 + 4 * red.length * 3 + 1);
buffer.put("SM".getBytes());
for(int i = 0; i < red.length; i++) {
buffer.put((" " + red[i] + "").getBytes());
}
for(int i = 0; i < green.length; i++) {
buffer.put((" " + green[i] + "").getBytes());
}
for(int i = 0; i < blue.length; i++) {
buffer.put((" " + blue[i] + "").getBytes());
}
buffer.put("\r".getBytes());
buffer.flip();
sendRequest(buffer.array(), 0, buffer.remaining());
}
 
public void sendCameraData(ByteBuffer data) throws IOException {
 
out.write((byte)0x0A);
out.write(data.array(), 0, data.remaining());
out.write((byte)0xFF);
 
out.flush();
 
}
 
private final static class SerialEventHandler implements SerialPortEventListener {
 
private Device device;
 
public SerialEventHandler(Device device) {
this.device = device;
}
 
public void serialEvent(SerialPortEvent spe) {
if(spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
 
try {
 
do {
 
byte[] data = new byte[1024];
 
int bytesRead = device.getInputStream().read(data);
if(bytesRead > 0) {
// take only bytesRead - 1 to remove the
// terminating character '\r' or 0xFF
EventQueue.invokeLater(new GUITask(device, ByteBuffer.wrap(data, 0, bytesRead - 1)));
}
 
} while(device.getInputStream().available() > 0);
 
} catch(IOException ioe) {
AVRSystem.LOG.severe(ioe.getMessage());
device.disconnect();
}
 
}
}
 
}
 
private final static class GUITask implements Runnable {
private ByteBuffer data;
private Device device;
 
public GUITask(Device device, ByteBuffer data) {
this.device = device;
this.data = data;
}
 
public void run() {
device.handleData(data);
}
 
}
 
private final class ResponseTask extends TimerTask {
 
public void run() {
// make sure we fire the timer expired event
// using the Event Dispatch Thread. If not,
// queue this TimerTask in the Event Queue.
if(EventQueue.isDispatchThread()) {
fireResponseTimerExpired();
} else {
EventQueue.invokeLater(this);
}
}
 
}
 
/**
* Only used for debugging purposes, this will simulate an ACK coming from the device.
*/
public void simulateACK() {
fireACKReceived();
}
 
/**
* Only used for debugging purposes, this will simulate an NCK coming from the device.
*/
public void simulateNCK() {
fireNCKReceived();
}
 
}
/programy/Java/AVRcamVIEW/src/avr/device/event/DataAdapter.java
0,0 → 1,42
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.device.event;
 
import java.nio.*;
 
public class DataAdapter implements DataListener {
 
public void ack() {}
public void nck() {}
 
public void responseTimerExpired() {}
 
public void version(String version) {}
public void frameData(ByteBuffer data) {}
public void trackingData(ByteBuffer data) {}
 
}
/programy/Java/AVRcamVIEW/src/avr/device/event/DataListener.java
0,0 → 1,42
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.device.event;
 
import java.nio.*;
 
public interface DataListener {
 
public void ack();
public void nck();
 
public void responseTimerExpired();
 
public void frameData(ByteBuffer data);
public void trackingData(ByteBuffer data);
public void version(String version);
 
}
/programy/Java/AVRcamVIEW/src/avr/io/AVRInputStream.java
0,0 → 1,99
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.io;
 
import java.io.*;
 
public class AVRInputStream extends FilterInputStream {
 
private static final int NEW_LINE = '\r';
private static final int END_DUMP_DATA = 0x0F;
private static final int END_TRACK_DATA = 0xFF;
 
private static final int SEARCHING_STATE = 0x00;
private static final int DUMP_FRAME_STATE = 0x01;
private static final int ACCEPTING_STATE = 0x02;
 
public AVRInputStream(InputStream in) {
super(in);
}
 
public int read(byte[] data, int off, int len) throws IOException {
 
int terminator = NEW_LINE;
int state = SEARCHING_STATE;
 
int value = -1;
int bytesRead = 0;
boolean cont = false;
 
do {
 
value = read();
 
if(value != -1) {
 
switch(state) {
case SEARCHING_STATE:
//System.out.println("(" + Integer.toHexString(value & 0xFF) + ") ");
data[off] = (byte)value;
if(value == 0x0A) {
terminator = END_TRACK_DATA;
state = ACCEPTING_STATE;
bytesRead++;
} else if(value == 0x0B) {
terminator = END_DUMP_DATA;
state = DUMP_FRAME_STATE;
bytesRead++;
} else if(value == 'A' || value == 'N') {
terminator = NEW_LINE;
state = ACCEPTING_STATE;
bytesRead++;
}
cont = false;
break;
case DUMP_FRAME_STATE:
data[off + bytesRead++] = (byte)value;
state = ACCEPTING_STATE;
cont = true;
break;
case ACCEPTING_STATE:
//System.out.println(Integer.toHexString(value & 0xFF) + " ");
data[off + bytesRead++] = (byte)value;
cont = false;
break;
}
 
}
 
 
} while(cont || value != terminator);
 
return bytesRead;
}
 
}
/programy/Java/AVRcamVIEW/src/avr/lang/AVRSystem.java
0,0 → 1,89
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.lang;
 
import java.util.logging.*;
import java.util.prefs.*;
import javax.swing.*;
 
import avr.device.*;
 
public class AVRSystem {
 
public static final Resource RES;
 
public static final Logger LOG;
 
public static final String RELEASE_MINOR;
public static final String RELEASE_MAJOR;
 
public static final String BUILD_DATE;
 
public static final Preferences PREFS;
 
public static final JFileChooser FILE_CHOOSER;
public static final String BAYER_FILE_EXT;
public static final String TRACK_FILE_EXT;
 
public static final int IMAGE_WIDTH;
public static final int IMAGE_HEIGHT;
 
public static final int NUM_INTENSITIES;
 
public static final Device DEVICE;
 
static {
 
LOG = Logger.getLogger("AVRcamVIEW");
LOG.setLevel(Level.ALL);
 
PREFS = Preferences.userRoot().node("AVRcamVIEW");
 
RES = new Resource("avr.resource.avr");
 
FILE_CHOOSER = new JFileChooser(".");
 
BAYER_FILE_EXT = RES.getString("file.ext.byr");
TRACK_FILE_EXT = RES.getString("file.ext.trk");
 
IMAGE_WIDTH = RES.getInt("image.width");
IMAGE_HEIGHT = RES.getInt("image.height");
 
NUM_INTENSITIES = RES.getInt("number.intensities");
 
BUILD_DATE = RES.getString("build.date");
RELEASE_MAJOR = RES.getString("build.major");
RELEASE_MINOR = RES.getString("build.minor");
 
DEVICE = new Device();
 
}
 
private AVRSystem() {
}
 
}
/programy/Java/AVRcamVIEW/src/avr/lang/Resource.java
0,0 → 1,120
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.lang;
 
import java.util.*;
 
/***************************************************************
* This is a convience class wrapped around a ResourceBundle.
*/
public class Resource {
 
/**
* The ResourceBundle to retrieve the key=value mappings.
*/
private final ResourceBundle BUNDLE;
 
/**
* Create an instance of this resource bundle to retrieve the
* key=value pairs from the given file.
* @param file The file containing the key=value pairs.
*/
public Resource(String file) {
BUNDLE = ResourceBundle.getBundle(file);
}
 
/**
* Gets a String for the given key from this resource bundle
* @param key The key for the desired string
* @return The string for the given key
*/
public String getString(String key) {
return BUNDLE.getString(key);
}
 
/**
* Convience method to convert the returned value for the key into
* an integer.
* @param key The key for the desired integer
* @return The integer for the given key.
*/
public int getInt(String key) {
return Integer.parseInt(getString(key));
}
 
/**
* Convience method to convert the returned value for the key into
* an character.
* @param key The key for the desired character
* @return The character for the given key.
*/
public char getChar(String key) {
return getString(key).charAt(0);
}
 
/**
* Convience method to convert the returned value for the key into
* an boolean.
* @param key The key for the desired boolean
* @return The boolean for the given key.
*/
public boolean getBoolean(String key) {
return new Boolean(getString(key)).booleanValue();
}
 
/**
* Convience method to convert the returned value for the key into
* an array of Strings.
* @param key The key for the desired array of Strings
* @return The array of Strings for the given key.
*/
public String[] getStrings(String key) {
// split the value string on every "," or ", "
return getString(key).split(",\\s*");
}
 
/**
* Convience method to convert the returned value for the key into
* an array of Integers.
* @param key The key for the desired array of Integers
* @return The array of Integers for the given key.
*/
public Integer[] getIntegers(String key) {
 
String[] strValues = getStrings(key);
 
Integer[] values = new Integer[strValues.length];
 
for(int i = 0; i < strValues.length; i++) {
values[i] = new Integer(strValues[i]);
}
 
return values;
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/resource/avr.properties
0,0 → 1,38
#
# AVRcamVIEW: A PC application to test out the functionallity of the
# AVRcam real-time image processing engine.
# Copyright (C) 2004 Brent A. Taylor
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# For more information on the AVRcamVIEW, please contact:
#
# taylorba@comcast.net
#
# or go to www.jrobot.net for more details regarding the system.
 
 
build.minor=@MINOR@
build.date=@DATE@
build.major=@MAJOR@
 
file.ext.byr = byr
file.ext.trk = trk
 
image.height = 144
image.width = 176
 
number.intensities = 16
 
/programy/Java/AVRcamVIEW/src/avr/swing/InvalidColorMapException.java
0,0 → 1,34
package avr.swing;
 
public class InvalidColorMapException extends Exception {
 
private int[] indicies;
private int red;
private int green;
private int blue;
 
public InvalidColorMapException(String message, int[] indicies, int red, int green, int blue) {
super(message);
this.indicies = indicies;
this.red = red;
this.green = green;
this.blue = blue;
}
 
public int[] getIndicies() {
return indicies;
}
 
public int getRed() {
return red;
}
 
public int getGreen() {
return green;
}
 
public int getBlue() {
return blue;
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JAVRCamFrame.java
0,0 → 1,1235
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.io.*;
import java.util.prefs.*;
import javax.comm.*;
 
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import javax.swing.*;
import javax.swing.event.*;
 
import avr.connection.*;
import avr.connection.event.*;
import avr.device.event.*;
import avr.lang.*;
import avr.swing.filechooser.*;
import avr.util.*;
import java.beans.*;
 
public class JAVRCamFrame extends JFrame {
 
public static void main(String[] args) {
/*
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
}
*/
 
try {
if(args.length == 1) {
if(args[0].equals("-r")) {
AVRSystem.PREFS.clear();
}
}
} catch(BackingStoreException bse) {
System.out.println("Could not clear preferences: " + bse.getMessage());
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JAVRCamFrame();
frame.setVisible(true);
}
});
}
 
private static final String COLOR_MAP_BOUNDS_KEY = "avr.colormap.bounds";
private static final String COLOR_MAP_SHOWING_KEY = "avr.colormap.showing";
private static final String COM_PORT_KEY = "avr.com.port";
private static final String COM_PARAMS_KEY = "avr.com.params";
private static final String DEVICE_CONNECTED_KEY = "avr.device.connected";
private static final String FRAME_BOUNDS_KEY = "avr.frame.bounds";
private static final String LOG_BOUNDS_KEY = "avr.log.bounds";
private static final String LOG_SHOWING_KEY = "avr.log.showing";
private static final String MESSAGE_SHOWING_KEY = "avr.message.showing";
 
private JFrame logF;
 
private JSerialPanel serialP;
private JRegisterPanel registersP;
private JMessagePanel messageP;
private JColorMapInterface colorMapP;
private JFrame colorMapF;
 
private JMenu windowM;
 
private JDesktopPane desktop;
private JTrackingInternalFrame trackingF;
 
private CaptureInternalFrameHandler captureInternalFrameHandler;
 
private AbstractButton viewLogB;
private AbstractButton viewMessagesB;
private AbstractButton viewColorMapB;
private AbstractButton trackingB;
private AbstractButton passiveTrackingB;
 
private ProxyAction connectAction;
private ProxyAction disconnectAction;
private ProxyAction serialParamsAction;
private ProxyAction setRegistersAction;
private ProxyAction pingAction;
private ProxyAction resetAction;
private ProxyAction captureAction;
private ProxyAction trackingAction;
private ProxyAction passiveTrackingAction;
 
private ProxyAction cascadeAction;
private ProxyAction tileHorizontalAction;
private ProxyAction tileVerticalAction;
private ProxyAction resetAllAction;
private ProxyAction closeAllAction;
 
private ButtonGroup windowBG;
 
public JAVRCamFrame() {
super("AVRcamVIEW");
 
createActions();
windowBG = new ButtonGroup();
captureInternalFrameHandler = new CaptureInternalFrameHandler();
 
// ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("avr/resource/AVRcam.gif"));
// if(icon != null) {
// this.setIconImage(icon.getImage());
// }
 
serialP = new JSerialPanel();
registersP = new JRegisterPanel();
 
messageP = new JMessagePanel();
 
String classVersionString = System.getProperty("java.class.version","44.0");
int classVersion = (int)(Double.parseDouble(classVersionString) * 10.0);
 
// JDK 5.0 class version is 49.0. Since the JNewColorMapPanel requires JDK 5.0
// this will check to make sure that the JVM is 5.0 or better, Otherwise, use
// the old color map.
if(System.getProperty("avr.old.color.map") != null || classVersion < 490) {
colorMapP = new JColorMapPanel(messageP);
} else {
try {
// must load the class using reflection so that the 1.4 compiler does not try
// to compile the JNewColorMapPanel class
Constructor constructor = Class.forName("avr.swing.JNewColorMapPanel").getConstructor(new Class[] { JMessagePanel.class });
colorMapP = (JColorMapInterface)constructor.newInstance(new Object[] {messageP});
// colorMapP = new JNewColorMapPanel(messageP);
} catch(Exception ex) {
// we can't load the new color map, so default to the old one.
colorMapP = new JColorMapPanel(messageP);
ex.printStackTrace(System.err);
}
}
 
messageP.addComponentListener(new MessagePanelHandler());
 
Dimension screen = getToolkit().getScreenSize();
Rectangle bounds = null;
 
JLogApplet logA = new JLogApplet();
logA.init(false);
AVRSystem.LOG.addHandler(new LogHandler(logA.getTableModel(), AVRSystem.LOG.getLevel()));
 
logF = logA.createFrame();
bounds = getBounds(LOG_BOUNDS_KEY);
if(bounds == null) {
bounds = new Rectangle(0, 0, screen.width * 3 / 4, screen.height / 2);
}
logF.setBounds(bounds);
 
 
desktop = new JDesktopPane();
desktop.setBackground(new Color(0x005C5C));
// desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
 
desktop.addMouseListener(new PopupHandler());
 
setJMenuBar(createMenuBar());
getContentPane().add(createToolBar(), BorderLayout.NORTH);
getContentPane().add(desktop, BorderLayout.CENTER);
getContentPane().add(messageP, BorderLayout.EAST);
 
bounds = getBounds(FRAME_BOUNDS_KEY);
if(bounds == null) {
bounds = new Rectangle(screen.width / 8, screen.height / 8,
screen.width * 3 / 4, screen.height * 3 / 4);
}
setBounds(bounds);
 
colorMapF = new JFrame("AVRcamVIEW - Color Map");
colorMapF.addWindowListener(new ColorMapWindowHandler(colorMapF, viewColorMapB));
colorMapF.getContentPane().add(colorMapP, BorderLayout.CENTER);
colorMapF.pack();
colorMapF.setResizable(false);
 
bounds = getBounds(COLOR_MAP_BOUNDS_KEY);
if(bounds == null) {
Dimension dim = colorMapF.getSize();
bounds = new Rectangle((screen.width - dim.width) / 2,
(screen.height - dim.height) / 2,
dim.width, dim.height);
}
 
colorMapF.setLocation(bounds.x, bounds.y);
colorMapF.pack();
 
addWindowListener(new WindowHandler(this));
logF.addWindowListener(new LogWindowHandler(viewLogB));
 
Action action = new ProxyAction(AVRSystem.DEVICE, "simulateNCK", "Simulate NCK");
registerKeyStrokeAction(
KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK),
action);
 
action = new ProxyAction(AVRSystem.DEVICE, "simulateACK", "Simulate ACK");
registerKeyStrokeAction(
KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK),
action);
 
resetAction = new ProxyAction(this, "reset", "Reset");
// registerKeyStrokeAction(
// KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK),
// resetAction);
 
SwingUtilities.invokeLater(new Startup());
 
}
 
private void registerKeyStrokeAction(KeyStroke keyStroke, Action action) {
// attach the action to the Ctrl+A key
getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(keyStroke, action.getValue(Action.NAME));
getRootPane().getActionMap().put(action.getValue(Action.NAME), action);
}
 
private void createActions() {
serialParamsAction = new ProxyAction(this, "showSerialDialog", "Configure Serial", 'S');
setRegistersAction = new ProxyAction(this, "showRegisterDialog", "Set Registers", 'R');
 
connectAction = new ProxyAction(this, "connect", "Connect", 'C');
disconnectAction = new ProxyAction(this, "disconnect", "Disconnect", 'D');
 
pingAction = new ProxyAction(this, "ping", "Ping", 'P');
pingAction.setEnabled(false);
 
// resetAction = new ProxyAction(this, "reset", "Reset", 'R');
 
captureAction = new ProxyAction(this, "capture", "Capture", 'C');
trackingAction = new ProxyAction(this, "tracking", "Enable Tracking", 'E');
 
passiveTrackingAction = new ProxyAction(this, "passiveTracking", "Enable Passive Tracking", 'V');
 
cascadeAction = new ProxyAction(this, "cascadeWindows", "Cascade", 'C');
tileHorizontalAction = new ProxyAction(this, "tileHorizontal", "Tile Horizontal", 'H');
tileVerticalAction = new ProxyAction(this, "tileVertical", "Tile Vertical", 'V');
resetAllAction = new ProxyAction(this, "resetAllWindows", "Reset All", 'R');
closeAllAction = new ProxyAction(this, "closeAllWindows", "Close All", 'L');
 
// resetAction.setEnabled(false);
setRegistersAction.setEnabled(false);
captureAction.setEnabled(false);
disconnectAction.setEnabled(false);
trackingAction.setEnabled(false);
passiveTrackingAction.setEnabled(false);
 
trackingB = new JToggleButton(trackingAction);
passiveTrackingB = new JToggleButton(passiveTrackingAction);
 
serialParamsAction.setToolTipText("Modify the Serial Port Parameters");
setRegistersAction.setToolTipText("Modify the AVRcam Register values");
connectAction.setToolTipText("Open the Serial Connection to the AVRcam");
disconnectAction.setToolTipText("Close the Serial Connection to the AVRcam");
pingAction.setToolTipText("Send a Ping ccommand to the AVRcam");
captureAction.setToolTipText("Capture a image from the AVRcam");
trackingAction.setToolTipText("Command the AVRcam to start tracking");
passiveTrackingAction.setToolTipText("Receive tracking packets from the AVRcam");
 
}
 
private JMenuBar createMenuBar() {
JMenuBar menubar = new JMenuBar();
 
JMenu fileM = new JMenu("File");
JMenu viewM = new JMenu("View");
JMenu deviceM = new JMenu("Device");
JMenu helpM = new JMenu("Help");
 
windowM = new JMenu("Window");
 
fileM.setMnemonic('f');
viewM.setMnemonic('v');
deviceM.setMnemonic('d');
windowM.setMnemonic('w');
helpM.setMnemonic('h');
 
fileM.add(new ProxyAction(this, "openBayer", "Open Bayer Image", 'B'));
fileM.add(new ProxyAction(this, "openTracking", "Open Tracking Data", 'T'));
fileM.addSeparator();
fileM.add(serialParamsAction);
fileM.add(setRegistersAction);
fileM.addSeparator();
fileM.add(new ProxyAction(this, "close", "Exit", 'X'));
 
viewColorMapB = new JCheckBoxMenuItem(new ProxyAction(this, "viewColorMap", true, "Show Color Map", 'C'));
viewM.add(viewColorMapB);
 
viewMessagesB = new JCheckBoxMenuItem(new ProxyAction(this, "viewMessages", true, "Show Messages", 'M'));
viewM.add(viewMessagesB);
 
viewLogB = new JCheckBoxMenuItem(new ProxyAction(this, "viewLog", true, "Show Log", 'L'));
viewM.add(viewLogB);
 
deviceM.add(connectAction);
deviceM.add(disconnectAction);
 
windowM.add(cascadeAction);
windowM.add(tileHorizontalAction);
windowM.add(tileVerticalAction);
windowM.add(resetAllAction);
windowM.add(closeAllAction);
windowM.addSeparator();
 
helpM.add(new ProxyAction(this, "about", "About", 'A'));
 
menubar.add(fileM);
menubar.add(viewM);
menubar.add(deviceM);
menubar.add(windowM);
menubar.add(helpM);
 
return menubar;
}
 
private JToolBar createToolBar() {
JToolBar toolbar = new JToolBar();
 
toolbar.add(connectAction);
toolbar.add(disconnectAction);
toolbar.addSeparator();
toolbar.add(serialParamsAction);
toolbar.add(setRegistersAction);
toolbar.addSeparator();
toolbar.add(pingAction);
// toolbar.add(resetAction);
toolbar.add(captureAction);
toolbar.add(trackingB);
toolbar.add(passiveTrackingB);
 
toolbar.setFloatable(false);
 
return toolbar;
}
 
private static Rectangle getBounds(String key) {
 
byte[] boundsArray = AVRSystem.PREFS.getByteArray(key, null);
Rectangle bounds = null;
 
if(boundsArray != null) {
 
try {
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(boundsArray));
 
bounds = (Rectangle)in.readObject();
 
in.close();
} catch(ClassNotFoundException ex) {
} catch(IOException ex) {
}
}
 
return bounds;
 
}
 
protected JRootPane createRootPane() {
// create a new JRootPane
JRootPane rootPane = new JRootPane() {
 
/**
* Create a new Glass Pane Glass Pane that when visible it captures
* all the mouse events, plays a "beep" when the mouse is clicked
* when the Glass Pane is visible, and changes the mouse depending
* on if the Glass Pane is visible or not.
* @return The Glass Pane
*/
protected Component createGlassPane() {
JComponent c = new JPanel() {
 
/**
* Overridden to change the cursor to a busy cursor when visible
* and a default cursor when not visible.
* @param visible True to show the Glass Pane, false to not
* show the Glass Pane.
*/
public void setVisible(boolean visible) {
super.setVisible(visible);
if(visible) {
// this is possible if it this panel has not been added
// to a JRootPane yet
if(getRootPane() != null) {
// change the cursor to a wait/busy cursor (hour glass)
getRootPane().setCursor(
Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
AVRSystem.LOG.finest("Glass Pane SHOWING... ");
}
} else {
// this is possible if it this panel has not been added
// to a JRootPane yet
if(getRootPane() != null) {
// chage the cursor back to the default cursor
getRootPane().setCursor(Cursor.getDefaultCursor());
AVRSystem.LOG.finest("Glass Pane HIDDEN... ");
}
}
}
};
c.setName(this.getName() + ".glassPane");
c.setVisible(false);
((JPanel)c).setOpaque(false);
// add a mouse listener to capture all the mouse events and play
// a "beep" when the mouse is pressed.
c.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
Toolkit.getDefaultToolkit().beep();
}
});
return c;
}
};
rootPane.setOpaque(true);
return rootPane;
}
 
public void openBayer() {
 
javax.swing.filechooser.FileFilter[] filters = AVRSystem.FILE_CHOOSER.getChoosableFileFilters();
for(int i = 0; i < filters.length; i++) {
AVRSystem.FILE_CHOOSER.removeChoosableFileFilter(filters[i]);
}
 
AVRSystem.FILE_CHOOSER.addChoosableFileFilter(new LogFileFilter("Bayer Image File (*.byr)", ".byr"));
 
int option = AVRSystem.FILE_CHOOSER.showOpenDialog(getRootPane());
if(option == JFileChooser.APPROVE_OPTION) {
JInternalFrame iFrame = new JCaptureInternalFrame(messageP, colorMapP, AVRSystem.FILE_CHOOSER.getSelectedFile());
iFrame.pack();
iFrame.setLocation(10, 10);
desktop.add(iFrame);
iFrame.setVisible(true);
}
}
 
public void openTracking() {
 
javax.swing.filechooser.FileFilter[] filters = AVRSystem.FILE_CHOOSER.getChoosableFileFilters();
for(int i = 0; i < filters.length; i++) {
AVRSystem.FILE_CHOOSER.removeChoosableFileFilter(filters[i]);
}
 
AVRSystem.FILE_CHOOSER.addChoosableFileFilter(new LogFileFilter("AVR Tracking File (*.trk)", ".trk"));
 
int option = AVRSystem.FILE_CHOOSER.showOpenDialog(getRootPane());
if(option == JFileChooser.APPROVE_OPTION) {
try {
JInternalFrame iFrame = new JTrackingInternalFrame(AVRSystem.FILE_CHOOSER.getSelectedFile());
iFrame.pack();
iFrame.setLocation(10, 10);
desktop.add(iFrame);
iFrame.setVisible(true);
} catch(FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(getRootPane(), "File Not Found", fnfe.getMessage(), JOptionPane.ERROR_MESSAGE);
} catch(IOException ioe) {
JOptionPane.showMessageDialog(getRootPane(), "I/O Exception", ioe.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
}
 
public void showSerialDialog() {
if(AVRSystem.DEVICE.getConnection() != null) {
showSerialDialog(((SerialConnection)AVRSystem.DEVICE.getConnection()).getSerialParams());
} else {
showSerialDialog(null);
}
}
 
public void showSerialDialog(SerialParams params) {
int option = serialP.showDialog(this, params);
if(option == JSerialPanel.OK_OPTION) {
try {
if(AVRSystem.DEVICE.isConnected()) {
((SerialConnection)AVRSystem.DEVICE.getConnection()).setSerialParams(serialP.getSerialParameters());
}
saveConnectionPrefs(null, serialP.getSerialParameters());
} catch(UnsupportedCommOperationException ucoe) {
AVRSystem.LOG.severe(ucoe.getMessage());
}
}
}
 
public void showRegisterDialog() {
int option = registersP.showDialog(this);
if(option == JRegisterPanel.OK_OPTION && registersP.getRegisters().size() > 0) {
 
DataListener handler = null;
try {
handler = new SetRegistersHandler();
AVRSystem.DEVICE.addDataListener(handler);
getRootPane().getGlassPane().setVisible(true);
AVRSystem.DEVICE.sendSetRegisters(registersP.getRegisters());
messageP.append("Set Registers");
} catch(IOException ioe) {
AVRSystem.DEVICE.removeDataListener(handler);
getRootPane().getGlassPane().setVisible(false);
AVRSystem.LOG.severe(ioe.getMessage());
messageP.append("Set Registers not sent");
}
}
}
 
public void close() {
 
AVRSystem.PREFS.putBoolean(DEVICE_CONNECTED_KEY, AVRSystem.DEVICE.isConnected());
 
if(AVRSystem.DEVICE.isConnected()) {
saveConnectionPrefs((SerialConnection)AVRSystem.DEVICE.getConnection());
disconnect();
}
 
AVRSystem.PREFS.putBoolean(LOG_SHOWING_KEY, logF.isVisible());
AVRSystem.PREFS.putBoolean(MESSAGE_SHOWING_KEY, messageP.isVisible());
AVRSystem.PREFS.putBoolean(COLOR_MAP_SHOWING_KEY, colorMapF.isVisible());
 
saveBounds(FRAME_BOUNDS_KEY, getBounds());
saveBounds(COLOR_MAP_BOUNDS_KEY, colorMapF.getBounds());
saveBounds(LOG_BOUNDS_KEY, logF.getBounds());
 
System.exit(0);
}
 
private static void saveConnectionPrefs(SerialConnection con) {
saveConnectionPrefs(con.getComPort(), con.getSerialParams());
}
 
private static void saveConnectionPrefs(String comPort, SerialParams params) {
if(comPort != null) {
AVRSystem.PREFS.put(COM_PORT_KEY, comPort);
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oOut = new ObjectOutputStream(out);
 
oOut.writeObject(params);
oOut.close();
 
byte[] serialParams = out.toByteArray();
 
AVRSystem.PREFS.putByteArray(COM_PARAMS_KEY, serialParams);
} catch(IOException ioe) {
ioe.printStackTrace();
AVRSystem.LOG.warning("Could not save serial parameters: " + ioe.getMessage());
}
}
 
private static void saveBounds(String key, Rectangle rect) {
 
try {
ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(arrayOut);
 
out.writeObject(rect);
 
out.close();
 
AVRSystem.PREFS.putByteArray(key, arrayOut.toByteArray());
} catch(IOException ex) {
}
 
}
 
public void viewColorMap(ActionEvent ae) {
colorMapF.setVisible(((AbstractButton)ae.getSource()).isSelected());
}
 
public void viewLog(ActionEvent ae) {
logF.setVisible(((AbstractButton)ae.getSource()).isSelected());
}
 
public void viewMessages(ActionEvent ae) {
messageP.setVisible(((AbstractButton)ae.getSource()).isSelected());
}
 
public void connect() {
String[] ports = SerialConnection.getSerialPorts();
if(ports.length > 0) {
Object option = JOptionPane.showInputDialog(this, "Select a COM Port:", "Serial Port",
JOptionPane.QUESTION_MESSAGE,
null,
ports,
AVRSystem.PREFS.get(COM_PORT_KEY, ports[0]));
if(option != null) {
connect(option.toString(), serialP.getSerialParameters());
}
} else {
JOptionPane.showMessageDialog(this, "No Serial Ports Available", "No Serial Ports",
JOptionPane.ERROR_MESSAGE);
}
}
 
public void connect(String comPort, SerialParams params) {
 
SerialConnection con = new SerialConnection(comPort, params);
AVRSystem.DEVICE.setConnection(con);
AVRSystem.DEVICE.addConnectionListener(new ConnectionHandler());
try {
AVRSystem.DEVICE.connect();
} catch(Exception ioe) {
JOptionPane.showMessageDialog(getRootPane(),
ioe.getMessage(),
"Connect Error",
JOptionPane.ERROR_MESSAGE);
AVRSystem.LOG.severe(ioe.getMessage());
}
}
 
public void disconnect() {
AVRSystem.DEVICE.disconnect();
}
 
public void ping() {
DataListener handler = null;
try {
handler = new PingHandler();
AVRSystem.DEVICE.addDataListener(handler);
getRootPane().getGlassPane().setVisible(true);
AVRSystem.DEVICE.sendPing();
messageP.append("Ping");
} catch(IOException ioe) {
AVRSystem.DEVICE.removeDataListener(handler);
getRootPane().getGlassPane().setVisible(false);
AVRSystem.LOG.severe(ioe.getMessage());
messageP.append("Ping not sent: " + ioe.getMessage());
}
}
 
public void reset() {
DataListener handler = null;
try {
handler = new ResetHandler();
AVRSystem.DEVICE.addDataListener(handler);
getRootPane().getGlassPane().setVisible(true);
AVRSystem.DEVICE.sendReset();
messageP.append("Reset");
} catch(IOException ioe) {
AVRSystem.DEVICE.removeDataListener(handler);
getRootPane().getGlassPane().setVisible(false);
AVRSystem.LOG.severe(ioe.getMessage());
messageP.append("Reset not sent");
}
}
 
public void capture() {
JCaptureInternalFrame captureF = new JCaptureInternalFrame(messageP, colorMapP);
Insets insets = captureF.getInsets();
captureF.pack();
int frameCount = desktop.getAllFrames().length;
captureF.setLocation(10 * frameCount, 10 * frameCount);
 
captureF.addInternalFrameListener(captureInternalFrameHandler);
 
desktop.add(captureF);
 
captureF.setVisible(true);
 
}
 
public void tracking() {
if(trackingB.isSelected()) {
enableTracking();
} else {
disableTracking();
}
}
 
private void enableTracking() {
DataListener handler = new TrackingHandler();
try {
AVRSystem.DEVICE.addDataListener(handler);
AVRSystem.DEVICE.sendEnableTracking();
messageP.append("Enable Tracking");
} catch(IOException ioe) {
AVRSystem.DEVICE.removeDataListener(handler);
AVRSystem.LOG.severe(ioe.getMessage());
messageP.append("Enable Tracking not sent");
}
}
 
private void disableTracking() {
DataListener handler = new TrackingHandler();
try {
AVRSystem.DEVICE.addDataListener(handler);
AVRSystem.DEVICE.sendDisableTracking();
messageP.append("Disable Tracking");
} catch(IOException ioe) {
AVRSystem.DEVICE.removeDataListener(handler);
AVRSystem.LOG.severe(ioe.getMessage());
messageP.append("Disable Tracking not sent");
}
}
 
public void passiveTracking() {
 
if(passiveTrackingB.isSelected()) {
passiveTrackingB.setText("Disable Passive Tracking");
disconnectAction.setEnabled(false);
serialParamsAction.setEnabled(false);
setRegistersAction.setEnabled(false);
pingAction.setEnabled(false);
resetAction.setEnabled(false);
captureAction.setEnabled(false);
trackingAction.setEnabled(false);
 
trackingF = new JTrackingInternalFrame();
Insets insets = trackingF.getInsets();
trackingF.pack();
trackingF.setLocation(10, 10);
 
desktop.add(trackingF);
 
trackingF.setVisible(true);
trackingF.startTracking();
messageP.append("Enable Passive Tracking");
} else {
passiveTrackingB.setText("Enable Passive Tracking");
disconnectAction.setEnabled(true);
serialParamsAction.setEnabled(true);
setRegistersAction.setEnabled(true);
pingAction.setEnabled(true);
resetAction.setEnabled(true);
captureAction.setEnabled(true);
trackingAction.setEnabled(true);
 
trackingF.stopTracking();
desktop.getDesktopManager().closeFrame(trackingF);
 
messageP.append("Disable Passive Tracking");
}
}
 
public void activateWindow(ActionEvent event) {
 
JInternalFrame[] frames = desktop.getAllFrames();
for(int i = 0; i < frames.length; i++) {
if(frames[i].getTitle().equals(event.getActionCommand())) {
desktop.getDesktopManager().activateFrame(frames[i]);
desktop.setSelectedFrame(frames[i]);
frames[i].toFront();
try {
frames[i].setSelected(true);
} catch(PropertyVetoException ex) {
ex.printStackTrace(System.out);
AVRSystem.LOG.severe(ex.getMessage());
}
break;
}
}
 
}
 
public void cascadeWindows() {
 
int x = 0;
int y = 0;
 
JInternalFrame[] frames = desktop.getAllFrames();
for(int i = 0; i < frames.length; i++) {
frames[i].setLocation(x, y);
x += 30;
y += 30;
}
 
}
 
public void tileHorizontal() {
 
JInternalFrame[] frames = desktop.getAllFrames();
 
int frameCount = frames.length;
int nrows = 1;
int ncols = (frameCount + nrows - 1) / nrows;
 
if(frameCount == 0) {
return;
}
 
int w = desktop.getWidth();
int h = desktop.getHeight();
w = (w - (ncols - 1)) / ncols;
h = (h - (nrows - 1)) / nrows;
 
for(int c = 0, x = 0; c < ncols; c++, x += w) {
for(int r = 0, y = 0; r < nrows; r++, y += h) {
int i = r * ncols + c;
if(i < frameCount) {
frames[i].setBounds(x, y, w, h);
}
}
}
 
}
 
public void tileVertical() {
 
JInternalFrame[] frames = desktop.getAllFrames();
 
int frameCount = frames.length;
int ncols = 1;
int nrows = (frameCount + ncols - 1) / ncols;;
 
if(frameCount == 0) {
return;
}
 
int w = desktop.getWidth();
int h = desktop.getHeight();
w = (w - (ncols - 1)) / ncols;
h = (h - (nrows - 1)) / nrows;
 
for(int c = 0, x = 0; c < ncols; c++, x += w) {
for(int r = 0, y = 0; r < nrows; r++, y += h) {
int i = r * ncols + c;
if(i < frameCount) {
frames[i].setBounds(x, y, w, h);
}
}
}
 
}
 
public void resetAllWindows() {
 
JInternalFrame[] frames = desktop.getAllFrames();
for(int i = 0; i < frames.length; i++) {
frames[i].pack();
}
 
}
 
public void closeAllWindows() {
 
JInternalFrame[] frames = desktop.getAllFrames();
for(int i = 0; i < frames.length; i++) {
if(frames[i] != trackingF) {
desktop.getDesktopManager().closeFrame(frames[i]);
}
}
 
}
 
public void about() {
new JAboutDialog(this, messageP).showDialog();
}
 
private final class SetRegistersHandler extends DataAdapter {
 
public void ack() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
}
 
public void nck() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Set Register NCK Received", "NCK Received", JOptionPane.ERROR_MESSAGE);
}
 
public void responseTimerExpired() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Response Timer Expired", "Timer Expired", JOptionPane.ERROR_MESSAGE);
}
 
}
 
private final class CaptureInternalFrameHandler implements InternalFrameListener {
public void internalFrameOpened(InternalFrameEvent e) {
 
String title = e.getInternalFrame().getTitle();
 
JCheckBoxMenuItem windowMI = new JCheckBoxMenuItem(new ProxyAction(JAVRCamFrame.this, "activateWindow", true, title));
windowMI.setActionCommand(title);
 
windowBG.add(windowMI);
 
windowMI.setSelected(true);
 
windowM.add(windowMI);
}
 
public void internalFrameClosing(InternalFrameEvent e) {
}
 
public void internalFrameClosed(InternalFrameEvent e) {
 
String text = null;
String title = e.getInternalFrame().getTitle();
 
for(int i = 0; i < windowM.getItemCount(); i++) {
// need to check for the separator
if(windowM.getItem(i) != null) {
text = windowM.getItem(i).getText();
if((text != null) && (title != null) &&
(text.equals(title))) {
windowM.remove(i);
break;
}
}
}
}
 
public void internalFrameIconified(InternalFrameEvent e) {
}
 
public void internalFrameDeiconified(InternalFrameEvent e) {
}
 
public void internalFrameActivated(InternalFrameEvent e) {
}
 
public void internalFrameDeactivated(InternalFrameEvent e) {
}
 
}
 
private final class PingHandler extends DataAdapter {
 
public void ack() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
}
 
public void nck() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Ping NCK Received", "NCK Received", JOptionPane.ERROR_MESSAGE);
}
 
public void responseTimerExpired() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Response Timer Expired", "Timer Expired", JOptionPane.ERROR_MESSAGE);
}
 
}
 
private final class ResetHandler extends DataAdapter {
 
public void ack() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
}
 
public void nck() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Reset NCK Received", "NCK Received", JOptionPane.ERROR_MESSAGE);
}
 
public void responseTimerExpired() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Response Timer Expired", "Timer Expired", JOptionPane.ERROR_MESSAGE);
}
 
}
 
private final class TrackingHandler extends DataAdapter {
public void ack() {
AVRSystem.DEVICE.removeDataListener(this);
if(trackingB.isSelected()) {
trackingB.setText("Disable Tracking");
disconnectAction.setEnabled(false);
serialParamsAction.setEnabled(false);
setRegistersAction.setEnabled(false);
pingAction.setEnabled(false);
resetAction.setEnabled(false);
captureAction.setEnabled(false);
passiveTrackingAction.setEnabled(false);
 
trackingF = new JTrackingInternalFrame();
Insets insets = trackingF.getInsets();
trackingF.pack();
trackingF.setLocation(10, 10);
 
desktop.add(trackingF);
 
trackingF.setVisible(true);
trackingF.startTracking();
 
} else {
trackingB.setText("Enable Tracking");
disconnectAction.setEnabled(true);
serialParamsAction.setEnabled(true);
setRegistersAction.setEnabled(true);
pingAction.setEnabled(true);
resetAction.setEnabled(true);
captureAction.setEnabled(true);
passiveTrackingAction.setEnabled(true);
 
trackingF.stopTracking();
desktop.getDesktopManager().closeFrame(trackingF);
}
}
 
public void nck() {
AVRSystem.DEVICE.removeDataListener(this);
if(trackingB.isSelected()) {
trackingB.setSelected(false);
} else {
trackingB.setSelected(true);
}
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Disable Tracking NCK Received", "NCK Received", JOptionPane.ERROR_MESSAGE);
}
 
public void responseTimerExpired() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
if(trackingB.isSelected()) {
trackingB.setSelected(false);
} else {
trackingB.setSelected(true);
}
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Response Timer Expired", "Timer Expired", JOptionPane.ERROR_MESSAGE);
 
}
 
}
 
private final class Startup implements Runnable {
 
public void run() {
 
boolean logVisible = AVRSystem.PREFS.getBoolean(LOG_SHOWING_KEY, false);
logF.setVisible(logVisible);
viewLogB.setSelected(logVisible);
 
boolean messagesVisible = AVRSystem.PREFS.getBoolean(MESSAGE_SHOWING_KEY, true);
messageP.setVisible(messagesVisible);
viewMessagesB.setSelected(messagesVisible);
 
boolean colorMapVisible = AVRSystem.PREFS.getBoolean(COLOR_MAP_SHOWING_KEY, false);
viewColorMapB.setSelected(colorMapVisible);
if(colorMapVisible) {
viewColorMap(new ActionEvent(viewColorMapB, ActionEvent.ACTION_PERFORMED, viewColorMapB.getText()));
}
 
try {
 
String comPort = AVRSystem.PREFS.get(COM_PORT_KEY, "COM1");
byte[] serialParams = AVRSystem.PREFS.getByteArray(COM_PARAMS_KEY, null);
 
AVRSystem.LOG.config("Prefs Com Port: " + comPort);
SerialParams params = null;
if(serialParams != null) {
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(serialParams));
params = (SerialParams)in.readObject();
in.close();
 
AVRSystem.LOG.config("Prefs Com Params: " + params);
 
if(AVRSystem.PREFS.getBoolean(DEVICE_CONNECTED_KEY, false)) {
connect(comPort, params);
}
}
} catch(Exception e) {
e.printStackTrace();
AVRSystem.LOG.warning("Could not read serial params: " + e.getMessage());
}
 
}
 
}
 
private final class ConnectionHandler extends DataAdapter implements ConnectionListener {
 
public void connected(ConnectionEvent ce) {
 
SerialConnection con = (SerialConnection)ce.getSource();
 
saveConnectionPrefs(con.getComPort(), con.getSerialParams());
 
try {
AVRSystem.DEVICE.addDataListener(this);
getRootPane().getGlassPane().setVisible(true);
AVRSystem.DEVICE.sendPing();
messageP.append("Ping");
} catch(IOException ioe) {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
AVRSystem.LOG.severe(ioe.getMessage());
messageP.append("Ping not sent: " + ioe.getMessage());
}
}
 
public void ack() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
 
enableButtons(true);
}
 
public void nck() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
enableButtons(true);
 
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Ping NCK Received", "NCK Received", JOptionPane.ERROR_MESSAGE);
}
 
public void responseTimerExpired() {
AVRSystem.DEVICE.removeDataListener(this);
getRootPane().getGlassPane().setVisible(false);
disconnect();
JOptionPane.showMessageDialog(JAVRCamFrame.this, "Response Timer Expired: Please connect the serial port to the computer and make sure the AVRcam is powered.", "Timer Expired", JOptionPane.ERROR_MESSAGE);
}
 
public void disconnected(ConnectionEvent ce) {
AVRSystem.DEVICE.removeConnectionListener(this);
 
enableButtons(false);
}
 
private void enableButtons(boolean enabled) {
connectAction.setEnabled(!enabled);
disconnectAction.setEnabled(enabled);
setRegistersAction.setEnabled(enabled);
pingAction.setEnabled(enabled);
resetAction.setEnabled(enabled);
captureAction.setEnabled(enabled);
trackingAction.setEnabled(enabled);
passiveTrackingAction.setEnabled(enabled);
}
 
}
 
private final class MessagePanelHandler extends ComponentAdapter {
 
public void componentHidden(ComponentEvent e) {
viewMessagesB.setSelected(false);
}
 
}
 
private final class PopupHandler extends MouseAdapter {
 
private JPopupMenu popup;
 
public void mouseReleased(MouseEvent event) {
if(SwingUtilities.isRightMouseButton(event)) {
if(popup == null) {
popup = new JPopupMenu();
popup.add(cascadeAction);
popup.add(tileHorizontalAction);
popup.add(tileVerticalAction);
popup.add(resetAllAction);
popup.add(closeAllAction);
popup.setInvoker(event.getComponent());
}
popup.show(event.getComponent(), event.getX(), event.getY());
}
}
 
}
 
private final static class ColorMapWindowHandler extends WindowAdapter {
 
private JFrame frame;
private AbstractButton viewB;
 
public ColorMapWindowHandler(JFrame frame, AbstractButton viewB) {
this.frame = frame;
this.viewB = viewB;
}
 
public void windowClosed(WindowEvent we) {
viewB.setSelected(false);
}
 
public void windowClosing(WindowEvent we) {
frame.dispose();
}
}
 
private final static class WindowHandler extends WindowAdapter {
 
private JAVRCamFrame frame;
 
public WindowHandler(JAVRCamFrame frame) {
this.frame = frame;
}
 
public void windowClosing(WindowEvent we) {
frame.dispose();
}
 
public void windowClosed(WindowEvent we) {
frame.close();
}
 
}
 
private final static class LogWindowHandler extends WindowAdapter {
 
private AbstractButton button;
 
public LogWindowHandler(AbstractButton button) {
this.button = button;
}
 
public void windowClosing(WindowEvent we) {
button.setSelected(false);
}
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JAboutDialog.java
0,0 → 1,133
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.*;
 
import avr.device.event.*;
import avr.lang.*;
 
public class JAboutDialog extends JDialog {
 
private static final String ABOUT_INFO =
"AVRcamVIEW:<br>" +
"&nbsp;&nbsp;&nbsp;Version: " + AVRSystem.RELEASE_MAJOR + "." + AVRSystem.RELEASE_MINOR + "<br>" +
"&nbsp;&nbsp;&nbsp;Build Date: " + AVRSystem.BUILD_DATE;
 
private JLabel aboutL;
private DataListener handler;
private JMessagePanel messageP;
 
public JAboutDialog(Frame owner, JMessagePanel messageP) {
super(owner, "About", true);
 
this.messageP = messageP;
 
Font labelFont = new Font("Dialog", Font.BOLD, 12);
 
aboutL = new JLabel("<html>" + ABOUT_INFO + "</html>");
aboutL.setFont(labelFont);
aboutL.setBorder(new EmptyBorder(20, 40, 20, 40));
 
Container contentPane = getContentPane();
 
JPanel southP = new JPanel();
southP.add(new JButton( new ProxyAction(this, "dispose", "OK", 'o')));
 
contentPane.add(aboutL, BorderLayout.CENTER);
contentPane.add(southP, BorderLayout.SOUTH);
 
setResizable(false);
 
pack();
 
}
 
public void setVersion(String version) {
StringBuffer builder = new StringBuffer();
builder.append("<html>")
.append(ABOUT_INFO)
.append("<br><br><hr><br>AVRcam")
.append("<BR>&nbsp;&nbsp;&nbsp;&nbsp;")
.append(version)
.append("<html>");
aboutL.setText(builder.toString());
pack();
}
 
public void showDialog() {
 
setLocationRelativeTo(getOwner());
 
if(AVRSystem.DEVICE.isConnected()) {
try {
handler = new DataHandler(this);
AVRSystem.DEVICE.addDataListener(handler);
messageP.append("Get Version");
AVRSystem.DEVICE.sendGetVersion();
} catch(IOException ioe) {
AVRSystem.LOG.severe("Could not get version: " + ioe.getMessage());
AVRSystem.DEVICE.removeDataListener(handler);
}
}
setVisible(true);
}
 
public void dispose() {
AVRSystem.DEVICE.removeDataListener(handler);
super.dispose();
}
 
private final static class DataHandler extends DataAdapter {
 
private JAboutDialog dialog;
 
public DataHandler(JAboutDialog dialog) {
this.dialog = dialog;
}
 
public void nck() {
AVRSystem.DEVICE.removeDataListener(this);
dialog.setVersion("Unable to retrieve version.");
}
 
public void responseTimerExpired() {
AVRSystem.DEVICE.removeDataListener(this);
dialog.setVersion("Response Timer Expired.");
}
 
public void version(String version) {
AVRSystem.DEVICE.removeDataListener(this);
dialog.setVersion(version);
}
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JCaptureInternalFrame.java
0,0 → 1,406
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
 
import avr.device.event.*;
import avr.lang.*;
import avr.swing.filechooser.LogFileFilter;
 
public class JCaptureInternalFrame extends JInternalFrame {
 
private static final Format DATE_FORMAT;
private static final Format DATE_FILE_NAME_FORMAT;
 
static {
DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
DATE_FILE_NAME_FORMAT = new SimpleDateFormat("yyyyMMdd hhmmss");
}
 
private JMessagePanel messageP;
private JColorMapInterface colorMapP;
private JCapturePanel captureP;
private DataListener dataHandler;
 
private String filename;
 
private JLabel redValueL;
private JLabel greenValueL;
private JLabel blueValueL;
 
private boolean fromCamera;
 
public JCaptureInternalFrame(JMessagePanel messageP) {
this(messageP, null);
}
 
public JCaptureInternalFrame(JMessagePanel messageP, JColorMapInterface colorMapP) {
this(messageP, colorMapP, null);
}
 
public JCaptureInternalFrame(JMessagePanel messageP, JColorMapInterface colorMapP, File file) {
super("Capture Frame" + ((file == null) ? ": " + DATE_FORMAT.format(new Date())
: " " + file.toString()),
true, true, true, true);
 
this.filename = DATE_FILE_NAME_FORMAT.format(new Date()) + ".byr";
this.fromCamera = file == null;
 
this.messageP = messageP;
this.colorMapP = colorMapP;
 
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setJMenuBar(createMenuBar());
 
redValueL = new JLabel("");
greenValueL = new JLabel("");
blueValueL = new JLabel("");
 
captureP = new JCapturePanel();
 
if(file != null) {
try {
captureP.openBayer(file);
} catch(IOException ioe) {
AVRSystem.LOG.severe(ioe.getMessage());
ioe.printStackTrace();
}
}
 
captureP.addMouseMotionListener(new MouseMotionHandler());
 
Box southBox = new Box(BoxLayout.X_AXIS);
southBox.setBorder(new EmptyBorder(5, 5, 5, 5));
 
southBox.add(Box.createHorizontalGlue());
southBox.add(new JLabel("Red: "));
southBox.add(redValueL);
southBox.add(Box.createHorizontalStrut(5));
southBox.add(new JLabel("Green: "));
southBox.add(greenValueL);
southBox.add(Box.createHorizontalStrut(5));
southBox.add(new JLabel("Blue: "));
southBox.add(blueValueL);
southBox.add(Box.createHorizontalGlue());
 
getContentPane().add(captureP, BorderLayout.CENTER);
getContentPane().add(southBox, BorderLayout.SOUTH);
 
if(colorMapP != null) {
captureP.addMouseListener(new MouseHandler());
}
 
}
 
private JMenuBar createMenuBar() {
JMenuBar menubar = new JMenuBar();
 
JMenu fileM = new JMenu("File");
 
fileM.add(new ProxyAction(this, "save", "Save", 's'));
fileM.add(new ProxyAction(this, "pack", "Reset Size", 'r'));
fileM.addSeparator();
fileM.add(new ProxyAction(this, "dispose", "Exit", 'x'));
 
menubar.add(fileM);
 
return menubar;
}
 
public void save() {
 
javax.swing.filechooser.FileFilter[] filters = AVRSystem.FILE_CHOOSER.getChoosableFileFilters();
for(int i = 0; i < filters.length; i++) {
AVRSystem.FILE_CHOOSER.removeChoosableFileFilter(filters[i]);
}
 
AVRSystem.FILE_CHOOSER.addChoosableFileFilter(
new LogFileFilter("Bayer Image File (*." + AVRSystem.BAYER_FILE_EXT + ")",
"." + AVRSystem.BAYER_FILE_EXT));
 
AVRSystem.FILE_CHOOSER.setSelectedFile(new File(filename));
int option = AVRSystem.FILE_CHOOSER.showSaveDialog(getDesktopPane().getRootPane());
if(option == JFileChooser.APPROVE_OPTION) {
try {
File file = AVRSystem.FILE_CHOOSER.getSelectedFile();
if(!file.getName().toLowerCase().endsWith(AVRSystem.BAYER_FILE_EXT)) {
file = new File(file.getName() + "." + AVRSystem.BAYER_FILE_EXT);
}
captureP.saveBayer(file);
} catch(IOException ioe) {
ioe.printStackTrace();
AVRSystem.LOG.severe(ioe.getMessage());
}
}
}
 
public void setVisible(boolean visible) {
if(fromCamera) {
if(visible) {
try {
dataHandler = new DumpFrameHandler();
AVRSystem.DEVICE.addDataListener(dataHandler);
getDesktopPane().getRootPane().getGlassPane().setVisible(true);
AVRSystem.DEVICE.sendDumpFrame();
messageP.append("Capture Snapshot");
} catch(IOException ioe) {
AVRSystem.DEVICE.removeDataListener(dataHandler);
AVRSystem.LOG.severe(ioe.getMessage());
messageP.append("Capture not sent");
}
} else {
AVRSystem.DEVICE.removeDataListener(dataHandler);
}
}
 
super.setVisible(visible);
}
 
private Point translatePointToImage(Point mouse) {
 
Dimension size = captureP.getSize();
Insets insets = captureP.getInsets();
Dimension preferredSize = captureP.getPreferredSize();
 
double scaleX = size.width / (double)preferredSize.width;
double scaleY = size.height / (double)preferredSize.height;
double scale = Math.min(scaleX, scaleY);
 
int imageX = (int)(insets.left + ((5 + AVRSystem.IMAGE_WIDTH + 10) * scale));
int imageY = (int)(insets.top + (5 * scale));
int imageWidth = (int)(AVRSystem.IMAGE_WIDTH * scale);
int imageHeight = (int)(AVRSystem.IMAGE_HEIGHT * scale);
 
Point imagePoint = null;
 
if(((mouse.x >= imageX) && (mouse.x < (imageX + imageWidth))) &&
((mouse.y >= imageY) && (mouse.y < (imageY + imageHeight)))) {
 
scale = 1 / scale;
 
int x = (int)((mouse.x * scale) - (insets.left + 5 + AVRSystem.IMAGE_WIDTH + 10));
int y = (int)((mouse.y * scale) - (insets.top + 5));
 
imagePoint = new Point(x, y);
}
 
return imagePoint;
 
}
 
private final class DumpFrameHandler extends DataAdapter {
 
private int frameCount;
 
public DumpFrameHandler() {
frameCount = 0;
}
 
public void ack() {
frameCount = 0;
}
 
public void nck() {
getDesktopPane().getRootPane().getGlassPane().setVisible(false);
AVRSystem.DEVICE.removeDataListener(this);
JOptionPane.showMessageDialog(messageP.getRootPane(), "Capture NCK Received", "NCK Received", JOptionPane.ERROR_MESSAGE);
}
 
public void responseTimerExpired() {
getDesktopPane().getRootPane().getGlassPane().setVisible(false);
AVRSystem.DEVICE.removeDataListener(this);
JOptionPane.showMessageDialog(messageP.getRootPane(), "Response Timer Expired", "Timer Expired", JOptionPane.ERROR_MESSAGE);
}
 
public void frameData(ByteBuffer data) {
 
frameCount++;
captureP.setRow(data.get() & 0xFF, data, frameCount == 0x48);
 
if(frameCount == 0x48) {
AVRSystem.DEVICE.removeDataListener(this);
getDesktopPane().getRootPane().getGlassPane().setVisible(false);
}
 
}
 
}
 
private final class MouseHandler extends MouseAdapter {
 
private JPopupMenu popupM;
private int color;
 
public void mouseReleased(MouseEvent me) {
if(SwingUtilities.isRightMouseButton(me)) {
Point imagePoint = translatePointToImage(me.getPoint());
 
if(imagePoint != null) {
 
color = captureP.getRGB(imagePoint.x, imagePoint.y);
 
if(popupM == null) {
popupM = new JPopupMenu();
try {
 
JMenuItem colorMapMI = new JMenuItem("Add to Color Map");
colorMapMI.addActionListener(new ActionHandler());
popupM.add(colorMapMI);
} catch(Exception e) {
}
}
 
popupM.show((Component)me.getSource(), me.getX(), me.getY());
 
}
 
}
 
}
 
public final class ActionHandler implements ActionListener {
 
private JPanel displayP = null;
private JRadioButton[] colRB = null;
 
public void actionPerformed(ActionEvent ae) {
 
int column = 0;
int option = JOptionPane.YES_OPTION;
 
do {
 
option = JOptionPane.YES_OPTION;
column = getColorMapColumn();
 
if(column != -1) {
 
if(!colorMapP.isColumnClear(column)) {
 
option = JOptionPane.showConfirmDialog(getRootPane(),
"Index " + column + " is already set. Overwrite current value?",
"Overwrite current index value?",
JOptionPane.
YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
 
}
} else {
option = JOptionPane.CANCEL_OPTION;
}
 
} while(option == JOptionPane.NO_OPTION);
 
if(option == JOptionPane.YES_OPTION) {
SwingUtilities.getWindowAncestor(colorMapP).setVisible(true);
colorMapP.setColor(column, color);
}
}
 
private int getColorMapColumn() {
if(displayP == null) {
displayP = new JPanel(new BorderLayout());
 
JPanel selectColP = new JPanel();
 
ButtonGroup bg = new ButtonGroup();
 
colRB = new JRadioButton[8];
for(int i = 0; i < colRB.length; i++) {
colRB[i] = new JRadioButton((i + 1) + "");
bg.add(colRB[i]);
selectColP.add(colRB[i]);
}
 
colRB[0].setSelected(true);
 
displayP.add(new JLabel("Select Color Map Column:"), BorderLayout.NORTH);
displayP.add(selectColP, BorderLayout.SOUTH);
}
 
int option = JOptionPane.showConfirmDialog(getRootPane(),
displayP,
"Add to Color Map Column",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
 
int selected = -1;
 
if(option == JOptionPane.OK_OPTION) {
for(int i = 0; selected == -1 && i < colRB.length; i++) {
if(colRB[i].isSelected()) {
selected = i;
}
}
 
}
 
return selected;
 
}
 
}
 
}
 
private final class MouseMotionHandler implements MouseMotionListener {
 
public void mouseMoved(MouseEvent me) {
 
Point imagePoint = translatePointToImage(me.getPoint());
 
if(imagePoint != null) {
 
int color = captureP.getRGB(imagePoint.x, imagePoint.y);
 
redValueL.setText(((color & 0xFF0000) >> 16) + "");
greenValueL.setText(((color & 0x00FF00) >> 8) + "");
blueValueL.setText(((color & 0x0000FF) >> 0) + "");
 
} else {
 
redValueL.setText("");
greenValueL.setText("");
blueValueL.setText("");
 
}
 
}
 
public void mouseDragged(MouseEvent me) {
}
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JCapturePanel.java
0,0 → 1,411
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import javax.swing.*;
 
import avr.lang.*;
 
public class JCapturePanel extends JPanel {
 
// constant variables for the interpolate state machine
private static final int RED = 0x01;
private static final int BLUE = 0x02;
private static final int GREEN_EVEN = 0x04;
private static final int GREEN_ODD = 0x08;
 
private BufferedImage bayerImage;
private BufferedImage image;
 
public JCapturePanel() {
super(null);
 
bayerImage = new BufferedImage(AVRSystem.IMAGE_WIDTH, AVRSystem.IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
image = new BufferedImage(AVRSystem.IMAGE_WIDTH, AVRSystem.IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
 
}
 
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(bayerImage != null) {
 
Dimension size = getSize();
Insets insets = getInsets();
 
Image offscreenImage = this.createImage(size.width, size.height);
 
Graphics2D g2d = (Graphics2D)offscreenImage.getGraphics();
 
// scale the images so they fit side by side for either the full
// width or full height of the window
double xScale = size.width / (double)(insets.left + 5 + AVRSystem.IMAGE_WIDTH + 10 + AVRSystem.IMAGE_WIDTH + 5 + insets.right);
double yScale = size.height / (double)(insets.top + 5 + AVRSystem.IMAGE_HEIGHT + 5 + insets.bottom);
double scale = Math.min(xScale, yScale);
 
g2d.scale(scale, scale);
 
g2d.drawImage(bayerImage, insets.left + 5, insets.top + 5, null);
g2d.drawImage(image, insets.left + 5 + AVRSystem.IMAGE_WIDTH + 10, insets.top + 5, null);
 
g.drawImage(offscreenImage, 0, 0, null);
 
}
}
 
public Dimension getMinimumSize() {
return getPreferredSize();
}
 
public Dimension getPreferredSize() {
Insets insets = getInsets();
return new Dimension(insets.left + 5 + AVRSystem.IMAGE_WIDTH + 10 + AVRSystem.IMAGE_WIDTH + 5 + insets.right,
insets.top + 5 + AVRSystem.IMAGE_HEIGHT + 5 + insets.bottom);
}
 
public Dimension getMaximumSize() {
return getPreferredSize();
}
 
public int getRGB(int x, int y) {
return image.getRGB(x, y);
}
 
public void openBayer(File file) throws IOException {
 
FileInputStream inStream = new FileInputStream(file);
FileChannel inChannel = inStream.getChannel();
 
ByteBuffer[] buffers = new ByteBuffer[bayerImage.getWidth()];
 
for(int x = 0; x < buffers.length; x++) {
buffers[x] = ByteBuffer.allocate(bayerImage.getHeight() * 4);
}
 
inChannel.read(buffers);
 
inStream.close();
inChannel.close();
 
int[] pixels = new int[bayerImage.getHeight()];
 
for(int x = 0; x < bayerImage.getWidth(); x++) {
buffers[x].flip();
buffers[x].asIntBuffer().get(pixels);
bayerImage.setRGB(x, 0, 1, pixels.length, pixels, 0, 1);
}
 
interpolate();
 
}
 
public void saveBayer(File file) throws IOException {
 
ByteBuffer[] buffers = new ByteBuffer[bayerImage.getWidth()];
 
for(int x = 0; x < buffers.length; x++) {
buffers[x] = ByteBuffer.allocate(bayerImage.getHeight() * 4);
for(int y = 0; y < bayerImage.getHeight(); y++) {
buffers[x].putInt(bayerImage.getRGB(x, y));
}
buffers[x].flip();
}
 
FileOutputStream outStream = new FileOutputStream(file);
FileChannel outChannel = outStream.getChannel();
 
outChannel.write(buffers);
 
outStream.close();
outChannel.close();
 
}
 
public void setRow(int row, ByteBuffer data, boolean finished) {
 
int[] pixels = new int[AVRSystem.IMAGE_WIDTH * 2];
 
int x = 0;
 
while(data.hasRemaining()) {
 
byte pixel = data.get();
 
if((x & 1) == 0) {
 
// green
pixels[x] = (pixel & 0xF0) << 8;
 
// blue
pixels[AVRSystem.IMAGE_WIDTH + x] = (pixel & 0x0F) << 4;
 
} else {
 
// green
pixels[AVRSystem.IMAGE_WIDTH + x] = ((pixel & 0x0F) << 4) << 8;
 
// red
pixels[x] = (pixel & 0xF0) << 16;
 
}
 
x++;
 
}
 
bayerImage.setRGB(0, row * 2, AVRSystem.IMAGE_WIDTH, 2, pixels, 0, AVRSystem.IMAGE_WIDTH);
 
if(finished) {
interpolate();
}
 
repaint();
 
}
 
/* ********************************************************
* The bayerImage is in the bayer format shown below.
*
* | | | | | | | | | | . | 1 | 1 |
* | | | | | | | | | | . | 7 | 7 |
* | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | . | 4 | 5 |
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
* 0 | G | R | G | R | G | R | G | R | G | . | G | R |
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
* 1 | B | G | B | G | B | G | B | G | B | . | B | G |
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
* 2 | G | R | G | R | G | R | G | R | G | . | G | R |
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
* 3 | B | G | B | G | B | G | B | G | B | . | B | G |
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
* 4 | G | R | G | R | G | R | G | R | G | . | G | R |
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
* 5 | B | G | B | G | B | G | B | G | B | . | B | G |
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
* . . . . . . . . . . . . .
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
* 142 | G | R | G | R | G | R | G | R | G | . | G | R |
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
* 143 | B | G | B | G | B | G | B | G | B | . | B | G |
* -----+---+---+---+---+---+---+---+---+---+ . +---+---+
*
* The corners are calculated, then the edges, then the center.
*
*/
 
private void interpolate() {
 
int red = 0;
int green = 0;
int blue = 0;
 
int currColor = GREEN_ODD;
int nextColor = RED;
 
int width = AVRSystem.IMAGE_WIDTH;
int height = AVRSystem.IMAGE_HEIGHT;
 
// *** do the corners of the image ***
// upper left corner
red = bayerImage.getRGB(1, 0);
green = bayerImage.getRGB(0, 0);
blue = bayerImage.getRGB(0, 1);
image.setRGB(0, 0, red | green | blue);
 
// upper right corner
red = bayerImage.getRGB(width - 1, 0);
green = (bayerImage.getRGB(width - 2, 0) + bayerImage.getRGB(width - 1, 1)) / 2;
blue = bayerImage.getRGB(width - 2, 1);
image.setRGB(width - 1, 0, red | green | blue);
 
// lower left corner
red = bayerImage.getRGB(1, height - 2);
green = (bayerImage.getRGB(0, height - 2) + bayerImage.getRGB(1, height - 1)) / 2;
blue = bayerImage.getRGB(0, height - 1);
image.setRGB(0, height - 1, red | green | blue);
 
// lower right corner
red = bayerImage.getRGB(width - 1, height - 2);
green = bayerImage.getRGB(width - 1, height - 1);
blue = bayerImage.getRGB(width - 2, height - 1);
image.setRGB(width - 1, height - 1, red | green | blue);
 
// *** do the north edge
currColor = RED;
for(int x = 1, y = 0; x < width - 1; x++) {
switch(currColor) {
case RED:
red = bayerImage.getRGB(x, y);
green = (bayerImage.getRGB(x + 1, y) + bayerImage.getRGB(x, y + 1) + bayerImage.getRGB(x - 1, y)) / 3;
blue = (bayerImage.getRGB(x + 1, y + 1) + bayerImage.getRGB(x - 1, y + 1)) / 2;
nextColor = GREEN_EVEN;
break;
case GREEN_EVEN:
red = (bayerImage.getRGB(x - 1, y) + bayerImage.getRGB(x + 1, y)) / 2;
green = bayerImage.getRGB(x, y);
blue = bayerImage.getRGB(x, y + 1);
nextColor = RED;
break;
default:
AVRSystem.LOG.warning("Invalid color for row start: " + currColor);
}
currColor = nextColor;
image.setRGB(x, y, red | green | blue);
}
 
// *** do the west edge
currColor = BLUE;
for(int y = 1, x = 0; y < height - 1; y++) {
switch(currColor) {
case BLUE:
red = (bayerImage.getRGB(x + 1, y + 1) + bayerImage.getRGB(x + 1, y - 1)) / 2;
green = (bayerImage.getRGB(x, y - 1) + bayerImage.getRGB(x + 1, y) + bayerImage.getRGB(x, y + 1)) / 3;
blue = bayerImage.getRGB(x, y);
nextColor = GREEN_EVEN;
break;
case GREEN_EVEN:
red = bayerImage.getRGB(x + 1, y);
green = bayerImage.getRGB(x, y);
blue = (bayerImage.getRGB(x, y - 1) + bayerImage.getRGB(x, y + 1)) / 2;
nextColor = BLUE;
break;
}
currColor = nextColor;
image.setRGB(x, y, red | green | blue);
}
 
// *** do the east edge
currColor = GREEN_ODD;
for(int y = 1, x = width - 1; y < height - 1; y++) {
switch(currColor) {
case RED:
blue = (bayerImage.getRGB(x - 1, y + 1) + bayerImage.getRGB(x - 1, y - 1)) / 2;
green = (bayerImage.getRGB(x, y - 1) + bayerImage.getRGB(x - 1, y) + bayerImage.getRGB(x, y + 1)) / 3;
red = bayerImage.getRGB(x, y);
nextColor = GREEN_EVEN;
break;
case GREEN_ODD:
blue = bayerImage.getRGB(x - 1, y);
green = bayerImage.getRGB(x, y);
red = (bayerImage.getRGB(x, y - 1) + bayerImage.getRGB(x, y + 1)) / 2;
nextColor = BLUE;
break;
}
currColor = nextColor;
image.setRGB(x, y, red | green | blue);
}
 
// *** do the south edge
currColor = GREEN_ODD;
for(int x = 1, y = height - 1; x < width - 1; x++) {
switch(currColor) {
case GREEN_ODD:
red = bayerImage.getRGB(x, y - 1);
green = bayerImage.getRGB(x, y);
blue = (bayerImage.getRGB(x - 1, y) + bayerImage.getRGB(x + 1, y)) / 2;
nextColor = BLUE;
break;
case BLUE:
red = (bayerImage.getRGB(x - 1, y - 1) + bayerImage.getRGB(x + 1, y - 1)) / 2;
green = (bayerImage.getRGB(x, y - 1) + bayerImage.getRGB(x + 1, y) + bayerImage.getRGB(x - 1, y)) / 3;
blue = bayerImage.getRGB(x, y);
nextColor = GREEN_ODD;
break;
default:
AVRSystem.LOG.warning("Invalid color for row start: " + currColor);
}
currColor = nextColor;
image.setRGB(x, y, red | green | blue);
}
 
// *** do the center box ***
currColor = RED;
for(int y = 1; y < height - 1; y++) {
// change the starting color for the row
switch(currColor) {
case RED:
currColor = GREEN_ODD;
break;
case GREEN_ODD:
currColor = RED;
break;
default:
AVRSystem.LOG.warning("Invalid color for row start: " + currColor);
 
}
for(int x = 1; x < width - 1; x++) {
 
switch(currColor) {
case RED:
red = bayerImage.getRGB(x, y);
 
green = (bayerImage.getRGB(x, y - 1) + bayerImage.getRGB(x + 1, y) +
bayerImage.getRGB(x, y + 1) + bayerImage.getRGB(x - 1, y)) / 4;
 
blue = (bayerImage.getRGB(x - 1, y - 1) + bayerImage.getRGB(x + 1, y + 1) +
bayerImage.getRGB(x + 1, y - 1) + bayerImage.getRGB(x - 1, y + 1)) / 4;
nextColor = GREEN_EVEN;
break;
case GREEN_EVEN:
red = (bayerImage.getRGB(x - 1, y) + bayerImage.getRGB(x + 1, y)) / 2;
green = bayerImage.getRGB(x, y);
blue = (bayerImage.getRGB(x, y - 1) + bayerImage.getRGB(x, y + 1)) / 2;
nextColor = RED;
break;
case GREEN_ODD:
red = (bayerImage.getRGB(x, y - 1) + bayerImage.getRGB(x, y + 1)) / 2;
green = bayerImage.getRGB(x, y);
blue = (bayerImage.getRGB(x - 1, y) + bayerImage.getRGB(x + 1, y)) / 2;
nextColor = BLUE;
break;
case BLUE:
red = (bayerImage.getRGB(x - 1, y - 1) + bayerImage.getRGB(x + 1, y + 1) +
bayerImage.getRGB(x + 1, y - 1) + bayerImage.getRGB(x - 1, y + 1)) / 4;
 
green = (bayerImage.getRGB(x, y - 1) + bayerImage.getRGB(x + 1, y) +
bayerImage.getRGB(x, y + 1) + bayerImage.getRGB(x - 1, y)) / 4;
 
blue = bayerImage.getRGB(x, y);
nextColor = GREEN_ODD;
break;
default:
AVRSystem.LOG.warning("Invalid color: " + currColor);
}
 
currColor = nextColor;
 
image.setRGB(x, y, red | green | blue);
}
}
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JColorMapInterface.java
0,0 → 1,15
package avr.swing;
 
import java.awt.*;
import javax.swing.*;
 
public abstract class JColorMapInterface extends JPanel {
 
public JColorMapInterface(LayoutManager lm) {
super(lm);
}
 
public abstract boolean isColumnClear(int column);
public abstract void setColor(int index, int color);
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JColorMapPanel.java
0,0 → 1,500
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
 
import avr.connection.event.*;
import avr.device.event.*;
import avr.swing.*;
 
import avr.lang.*;
 
public class JColorMapPanel extends JColorMapInterface {
 
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JColorMapPanel(null));
frame.pack();
frame.setVisible(true);
}
 
private JLabel[] systemColorsL;
 
private JMessagePanel messageP;
private JSelectionPanel[] redColorPanels;
private JSelectionPanel[] greenColorPanels;
private JSelectionPanel[] blueColorPanels;
 
private Action checkAction;
private Action clearColumnAction;
private Action clearAction;
private Action resetAction;
private Action sendAction;
 
public JColorMapPanel(JMessagePanel messageP) {
super(new BorderLayout());
 
this.messageP = messageP;
 
checkAction = new ProxyAction(this, "check", "Auto Check", 'a');
clearColumnAction = new ProxyAction(this, "clearColumn", "Clear Column(s)", 'l');
clearAction = new ProxyAction(this, "clear", "Clear All", 'c');
resetAction = new ProxyAction(this, "reset", "Reset", 'r');
sendAction = new ProxyAction(this, "send", "Send", 's');
 
sendAction.setEnabled(false);
 
redColorPanels = new JSelectionPanel[AVRSystem.NUM_INTENSITIES];
greenColorPanels = new JSelectionPanel[AVRSystem.NUM_INTENSITIES];
blueColorPanels = new JSelectionPanel[AVRSystem.NUM_INTENSITIES];
 
JPanel titleP = new JPanel();
 
JLabel titleL = new JLabel("System Colors: ");
titleL.setFont(titleL.getFont().deriveFont(16.0f));
 
titleP.add(titleL);
 
systemColorsL = new JLabel[8];
for(int i = 0; i < systemColorsL.length; i++) {
systemColorsL[i] = new JLabel();
systemColorsL[i].setBorder(new LineBorder(Color.BLACK));
systemColorsL[i].setOpaque(true);
systemColorsL[i].setPreferredSize(new Dimension(20, 20));
 
titleP.add(systemColorsL[i]);
}
 
// set the number of rows one less than the number of intensities because we
// do not use the first row.
JPanel centerP = new JPanel(new GridLayout(AVRSystem.NUM_INTENSITIES - 1, 1, 0, 5));
centerP.setBorder(new EmptyBorder(0, 5, 5, 5));
 
Box row;
 
Dimension rowLabelSize = null;
int intensityIncrement = (int)(256 / AVRSystem.NUM_INTENSITIES);
 
for(int i = 0; i < AVRSystem.NUM_INTENSITIES; i++) {
redColorPanels[i] = new JSelectionPanel(Color.RED);
greenColorPanels[i] = new JSelectionPanel(Color.GREEN);
blueColorPanels[i] = new JSelectionPanel(Color.BLUE);
 
row = new Box(BoxLayout.X_AXIS);
 
JLabel rowL = new JLabel("" + (i * intensityIncrement), JLabel.CENTER);
 
// set all the labels to the same size
if(rowLabelSize == null) {
rowLabelSize = new Dimension(rowL.getPreferredSize().width * 4,
rowL.getPreferredSize().height);
}
 
rowL.setPreferredSize(rowLabelSize);
rowL.setMinimumSize(rowLabelSize);
 
row.add(rowL);
row.add(Box.createHorizontalStrut(5));
row.add(redColorPanels[i]);
row.add(Box.createHorizontalStrut(5));
row.add(greenColorPanels[i]);
row.add(Box.createHorizontalStrut(5));
row.add(blueColorPanels[i]);
 
// we do not use the first row
if(i != 0) {
centerP.add(row);
}
}
 
Box southBox = new Box(BoxLayout.X_AXIS);
southBox.setBorder(new CompoundBorder(new EtchedBorder(), new EmptyBorder(5, 5, 5, 5)));
 
southBox.add(new JButton(checkAction));
southBox.add(Box.createHorizontalGlue());
southBox.add(new JButton(clearColumnAction));
southBox.add(Box.createHorizontalStrut(5));
southBox.add(new JButton(clearAction));
southBox.add(Box.createHorizontalStrut(5));
southBox.add(new JButton(resetAction));
southBox.add(Box.createHorizontalStrut(5));
southBox.add(new JButton(sendAction));
 
add(titleP, BorderLayout.NORTH);
add(centerP, BorderLayout.CENTER);
add(southBox, BorderLayout.SOUTH);
 
// load the current color map
reset();
 
AVRSystem.DEVICE.addConnectionListener(new ConnectionHandler());
}
 
private static String formatColorMapException(InvalidColorMapException icme) {
 
StringBuffer builder = new StringBuffer("Invalid Color Map: ");
 
int[] indicies = icme.getIndicies();
 
builder.append("Indicies ");
 
for(int i = 0; i < indicies.length; i++) {
 
builder.append(indicies[i]);
 
if((i + 1) < indicies.length) {
builder.append(" and ");
}
 
}
 
builder.append(" intersect at values Red: ")
.append(icme.getRed())
.append(" Green: ")
.append(icme.getGreen())
.append(" Blue: ")
.append(icme.getBlue());
 
return builder.toString();
 
}
 
public void check() {
 
try {
checkMap();
 
JOptionPane.showMessageDialog(getRootPane(),
"Color Map is valid.",
"Color Map Validated",
JOptionPane.INFORMATION_MESSAGE);
} catch(InvalidColorMapException icme) {
JOptionPane.showMessageDialog(getRootPane(),
formatColorMapException(icme),
"Check Failed",
JOptionPane.ERROR_MESSAGE);
}
 
}
 
public boolean isColumnClear(int column) {
 
int value = 0;
 
/* *********************************************
* NOTE: This one loop is only checking hte
* length of the red color panels but is also
* looping over the green and blue ones!!!!
**/
for(int r = 0; r < redColorPanels.length; r++) {
value |= redColorPanels[r].getValue() |
greenColorPanels[r].getValue() |
blueColorPanels[r].getValue();
}
 
return (value & (0x01 << (7 - column))) == 0;
}
 
/* *************************************
* Copied from java.lang.Integer class
* from the JDK 1.5 version.
*/
private int bitCount(int i) {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
 
private void checkMap() throws InvalidColorMapException {
for(int r = 0; r < redColorPanels.length; r++) {
int red = redColorPanels[r].getValue();
for(int g = 0; g < greenColorPanels.length; g++) {
int green = greenColorPanels[g].getValue();
for(int b = 0; b < blueColorPanels.length; b++) {
int blue = blueColorPanels[b].getValue();
int value = red & green & blue;
 
// In JDk 1.5 the Integer class has the bitCount
// method. To be backward compatible, use the bitCount
// method above.
// if(value != 0 && (Integer.bitCount(value) > 1)) {
if(value != 0 && (bitCount(value) > 1)) {
int[] indicies = new int[bitCount(value)];
int count = 0;
for(int i = 0; i < 8; i++) {
if((value & (0x80 >>> i)) != 0) {
indicies[count++] = (i + 1);
}
}
 
throw new InvalidColorMapException("Color Map is invalid.", indicies, r * 16, g * 16, b * 16);
}
}
}
}
 
}
 
public void clearColumn() {
 
JPanel displayP = new JPanel(new BorderLayout());
 
JPanel selectColP = new JPanel();
 
JCheckBox[] colCB = new JCheckBox[8];
for(int i = 0; i < colCB.length; i++) {
colCB[i] = new JCheckBox((i + 1) + "");
selectColP.add(colCB[i]);
}
 
displayP.add(new JLabel("Select Color Map Column:"), BorderLayout.NORTH);
displayP.add(selectColP, BorderLayout.SOUTH);
 
int option = JOptionPane.showConfirmDialog(getRootPane(),
displayP,
"Select Column(s) to clear:",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
 
if(option == JOptionPane.OK_OPTION) {
 
/* *********************************************
* NOTE: This one loop is only checking hte
* length of the red color panels but is also
* looping over the green and blue ones!!!!
**/
for(int col = 0; col < 8; col++) {
if(colCB[col].isSelected()) {
for(int i = 0; i < redColorPanels.length; i++) {
redColorPanels[i].set(col, false);
greenColorPanels[i].set(col, false);
blueColorPanels[i].set(col, false);
}
}
}
}
}
 
public void clear() {
/* *********************************************
* NOTE: This one loop is only checking the
* length of the red color panels but is also
* looping over the green and blue ones!!!!
**/
for(int col = 0; col < redColorPanels.length; col++) {
redColorPanels[col].setValue(0);
greenColorPanels[col].setValue(0);
blueColorPanels[col].setValue(0);
}
}
 
public void reset() {
int[][] colorMap = AVRSystem.DEVICE.getColorMap();
 
/* *********************************************
* NOTE: This one loop is only checking the
* length of the red color panels but is also
* looping over the green and blue ones!!!!
**/
for(int col = 0; col < redColorPanels.length; col++) {
redColorPanels[col].setValue(colorMap[0][col]);
greenColorPanels[col].setValue(colorMap[1][col]);
blueColorPanels[col].setValue(colorMap[2][col]);
}
 
for(int i = 0; i < systemColorsL.length; i++) {
systemColorsL[i].setBackground(AVRSystem.DEVICE.getMapColors()[i]);
}
}
 
public void send() {
 
try {
 
checkMap();
 
int[][] newColorMap = new int[3][AVRSystem.NUM_INTENSITIES];
for(int r = 0; r < redColorPanels.length; r++) {
newColorMap[0][r] = redColorPanels[r].getValue();
}
for(int g = 0; g < greenColorPanels.length; g++) {
newColorMap[1][g] = greenColorPanels[g].getValue();
}
for(int b = 0; b < blueColorPanels.length; b++) {
newColorMap[2][b] = blueColorPanels[b].getValue();
}
 
DataListener handler = new DataHandler(newColorMap);
try {
 
AVRSystem.DEVICE.addDataListener(handler);
getRootPane().getGlassPane().setVisible(true);
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(true);
AVRSystem.DEVICE.sendSetColorMap(newColorMap[0], newColorMap[1], newColorMap[2]);
messageP.append("Sent Color Map");
} catch(IOException ioe) {
AVRSystem.DEVICE.removeDataListener(handler);
getRootPane().getGlassPane().setVisible(false);
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(false);
ioe.printStackTrace();
AVRSystem.LOG.severe(ioe.getMessage());
}
} catch(InvalidColorMapException icme) {
JOptionPane.showMessageDialog(getRootPane(),
formatColorMapException(icme),
"Check Failed",
JOptionPane.ERROR_MESSAGE);
}
}
 
public void setColor(int index, int color) {
 
int red = (color >>> 20) & 0x0F;
int green = (color >>> 12) & 0x0F;
int blue = (color >>> 4) & 0x0F;
 
/* *********************************************
* NOTE: This one loop is only checking the
* length of the red color panels but is also
* looping over the green and blue ones!!!!
**/
for(int i = 0; i < redColorPanels.length; i++) {
redColorPanels[i].set(index, i == red);
greenColorPanels[i].set(index, i == green);
blueColorPanels[i].set(index, i == blue);
}
 
}
 
private final static class JSelectionPanel extends JPanel {
 
private JCheckBox[] boxes;
 
public JSelectionPanel(Color rowColor) {
super();
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setBackground(rowColor);
 
boxes = new JCheckBox[8];
 
add(Box.createHorizontalGlue());
for(int i = 0; i < boxes.length; i++) {
boxes[i] = new JCheckBox();
boxes[i].setBackground(rowColor);
if((i != 0) && ((i % 4) == 0)) {
add(Box.createHorizontalStrut(5));
}
add(boxes[i]);
}
add(Box.createHorizontalGlue());
 
}
 
public void set(int index, boolean selected) {
boxes[index].setSelected(selected);
}
 
public void setValue(int value) {
for(int i = 0; i < boxes.length; i++) {
if((value & (1 << (7 - i))) > 0) {
boxes[i].setSelected(true);
} else {
boxes[i].setSelected(false);
}
}
}
 
public int getValue() {
int value = 0;
 
for(int i = 0; i < boxes.length; i++) {
if(boxes[i].isSelected()) {
value |= 1 << (7 - i);
value &= 0xFF;
}
}
 
return value;
}
 
}
 
private final class DataHandler extends DataAdapter {
 
private int[][] colorMap;
 
public DataHandler(int[][] colorMap) {
this.colorMap = colorMap;
}
 
public void ack() {
AVRSystem.DEVICE.setColorMap(colorMap);
reset();
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(false);
getRootPane().getGlassPane().setVisible(false);
AVRSystem.DEVICE.removeDataListener(this);
}
 
public void nck() {
getRootPane().getGlassPane().setVisible(false);
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(false);
AVRSystem.DEVICE.removeDataListener(this);
JOptionPane.showMessageDialog(getRootPane(), "Set Color Map NCK Received", "NCK Received", JOptionPane.ERROR_MESSAGE);
}
 
public void responseTimerExpired() {
getRootPane().getGlassPane().setVisible(false);
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(false);
AVRSystem.DEVICE.removeDataListener(this);
JOptionPane.showMessageDialog(messageP.getRootPane(), "Response Timer Expired", "Timer Expired", JOptionPane.ERROR_MESSAGE);
}
 
}
 
private final class ConnectionHandler implements ConnectionListener {
public void connected(ConnectionEvent ce) {
sendAction.setEnabled(true);
}
 
public void disconnected(ConnectionEvent ce) {
sendAction.setEnabled(false);
}
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JLogApplet.java
0,0 → 1,454
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.logging.*;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
 
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
 
import avr.lang.AVRSystem;
import avr.swing.filechooser.*;
import avr.swing.table.*;
 
public class JLogApplet extends JApplet {
 
public static void main(String[] args) throws Exception {
 
final JLogApplet log = new JLogApplet();
 
// The JFileChooser takes about 2 seconds to fully load.
// to keep the user from waiting, load the JFileChooser
// in a background thread while the JLogFrame is loading.
Thread loadFileChooser = new Thread(new Runnable() {
public void run() {
log.createJFileChooser();
}
});
 
loadFileChooser.setName("Load File Chooser");
loadFileChooser.start();
 
JFrame frame = new JFrame("System Log");
 
 
log.init();
 
Dimension dim = log.getToolkit().getScreenSize();
// set the log size to 3/4 the screen size and
// center the log window to the middle of the screen.
frame.setBounds(dim.width / 8, dim.height / 8,
dim.width * 3 / 4, dim.height * 3 / 4);
 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(log);
frame.setVisible(true);
 
}
 
private static final LogFileFilter XML_FILE_FILTER;
private static final LogFileFilter TXT_FILE_FILTER;
private static final DateFormat DATE_FORMAT;
 
static {
 
DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
XML_FILE_FILTER = new LogFileFilter("XML Format (*.xml)", ".xml");
TXT_FILE_FILTER = new LogFileFilter("Text Format (*.txt)", ".txt");
 
}
 
private LogTableModel model;
private boolean isStandAlone;
private JFileChooser fileChooser;
 
public String getParameter(String key) {
return isStandAlone ? System.getProperty(key) : super.getParameter(key);
}
 
public void init() {
init(true);
}
 
public void init(boolean isStandAlone) {
this.isStandAlone = isStandAlone;
 
String selectedLevel = AVRSystem.PREFS.get("avr.log.level", Level.CONFIG.getLocalizedName());
boolean onlyShowLevel = AVRSystem.PREFS.getBoolean("avr.log.onlyshowlevel.selected", false);
 
JPanel logLevelP = new JPanel();
 
JRadioButton severeRB = new JRadioButton(Level.SEVERE.getLocalizedName(), Level.SEVERE.getLocalizedName().equals(selectedLevel));
JRadioButton warningRB = new JRadioButton(Level.WARNING.getLocalizedName(), Level.WARNING.getLocalizedName().equals(selectedLevel));
JRadioButton infoRB = new JRadioButton(Level.INFO.getLocalizedName(), Level.INFO.getLocalizedName().equals(selectedLevel));
JRadioButton configRB = new JRadioButton(Level.CONFIG.getLocalizedName(), Level.CONFIG.getLocalizedName().equals(selectedLevel));
JRadioButton fineRB = new JRadioButton(Level.FINE.getLocalizedName(), Level.FINE.getLocalizedName().equals(selectedLevel));
JRadioButton finerRB = new JRadioButton(Level.FINER.getLocalizedName(), Level.FINER.getLocalizedName().equals(selectedLevel));
JRadioButton finestRB = new JRadioButton(Level.FINEST.getLocalizedName(), Level.FINEST.getLocalizedName().equals(selectedLevel));
 
JCheckBox onlyShowLevelCB = new JCheckBox("Show Only Level", onlyShowLevel);
onlyShowLevelCB.addActionListener(new OnlyShowLevelAction());
 
ButtonGroup bg = new ButtonGroup();
bg.add(severeRB);
bg.add(warningRB);
bg.add(infoRB);
bg.add(configRB);
bg.add(fineRB);
bg.add(finerRB);
bg.add(finestRB);
 
LogAction logAction = new LogAction();
 
severeRB.addActionListener(logAction);
warningRB.addActionListener(logAction);
infoRB.addActionListener(logAction);
configRB.addActionListener(logAction);
fineRB.addActionListener(logAction);
finerRB.addActionListener(logAction);
finestRB.addActionListener(logAction);
 
logLevelP.add(new JLabel("Level: "));
logLevelP.add(severeRB);
logLevelP.add(warningRB);
logLevelP.add(infoRB);
logLevelP.add(configRB);
logLevelP.add(fineRB);
logLevelP.add(finerRB);
logLevelP.add(finestRB);
logLevelP.add(Box.createHorizontalStrut(20));
logLevelP.add(onlyShowLevelCB);
 
getContentPane().add(logLevelP, BorderLayout.NORTH);
 
model = new LogTableModel(Level.parse(selectedLevel));
model.setOnlyShowSelectedLevel(onlyShowLevel);
 
JTable table = new JTable(model);
table.setFont(new Font("Courier New", Font.PLAIN, 12));
 
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setDefaultRenderer(String.class, new LogTableCellRenderer());
table.setRowHeight(table.getRowHeight() + 5);
table.getTableHeader().setReorderingAllowed(false);
 
model.addTableModelListener(new LogModelHandler(table));
 
TableColumn column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(200);
column.setMaxWidth(200);
 
column = table.getColumnModel().getColumn(1);
column.setPreferredWidth(75);
column.setMaxWidth(75);
 
column = table.getColumnModel().getColumn(2);
column.setPreferredWidth(800);
 
JScrollPane tableScroll = new JScrollPane(table);
tableScroll.getViewport().setBackground(table.getBackground());
 
setJMenuBar(createMenuBar());
 
getContentPane().add(tableScroll, BorderLayout.CENTER);
 
}
 
// overwritten so this applet can be resized using javascript
public void setSize(int width, int height) {
Dimension size = getSize();
if(size.width != width || size.height != height) {
super.setSize(width, height);
validate();
}
}
 
public JFrame createFrame() {
JFrame frame = new JFrame("AVRcamVIEW - System Log");
 
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.getContentPane().add(this);
 
return frame;
}
 
public JDialog createDialog(Frame owner) {
 
JDialog dialog = new JDialog(owner,
"AVRcamVIEW - System Log",
false);
 
dialog.getContentPane().add(this);
 
return dialog;
 
}
 
private JMenuBar createMenuBar() {
 
JMenuBar menubar = new JMenuBar();
 
JMenu fileM = new JMenu("File");
fileM.setMnemonic('f');
 
if(isStandAlone) {
// only allow user to open a log file if the log is running stand-alone
fileM.add(new ProxyAction(this, "open",
"Open",
'o'));
} else {
// only allow the user to clear the log if the log is NOT running stand-alone
fileM.add(new ProxyAction(this, "clear",
"Clear",
'c'));
fileM.addSeparator();
fileM.add(new ProxyAction(this, "save",
"Save",
's'));
}
 
menubar.add(fileM);
 
return menubar;
}
 
public LogTableModel getTableModel() {
return model;
}
 
// public void open() {
//
// if(fileChooser == null) {
// createJFileChooser();
// }
//
// int option = fileChooser.showOpenDialog(getRootPane());
// if(option == JFileChooser.APPROVE_OPTION) {
//
// clear();
//
// try {
//
// getRootPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// File logFile = fileChooser.getSelectedFile();
//
// SAXBuilder builder = new SAXBuilder();
// Document doc = builder.build(new GZIPInputStream(new FileInputStream(logFile)));
//
// Element root = doc.getRootElement();
//
// Iterator records = root.getChildren("record").iterator();
// Element recordElement;
// LogRecord record;
//
// while(records.hasNext()) {
//
// recordElement = (Element)records.next();
//
// record = new LogRecord(Level.parse(recordElement.getChildText("level")), recordElement.getChildText("message"));
// record.setMillis(Long.parseLong(recordElement.getChildText("millis")));
// record.setSequenceNumber(Long.parseLong(recordElement.getChildText("sequence")));
// record.setLoggerName(recordElement.getChildText("logger"));
// record.setSourceClassName(recordElement.getChildText("class"));
// record.setSourceMethodName(recordElement.getChildText("method"));
// record.setThreadID(Integer.parseInt(recordElement.getChildText("thread")));
//
// model.addRecord(record);
//
// }
//
//
// } catch(Exception e) {
// e.printStackTrace(System.err);
// }
//
// getRootPane().setCursor(Cursor.getDefaultCursor());
//
// }
//
// }
//
public void save() {
 
if(model.getRowCount() == 0) {
return;
}
 
if(fileChooser == null) {
createJFileChooser();
}
 
int option = fileChooser.showSaveDialog(getRootPane());
if(option == JFileChooser.APPROVE_OPTION) {
try {
File logFile = fileChooser.getSelectedFile();
 
if(fileChooser.getFileFilter().equals(TXT_FILE_FILTER)) {
if(!logFile.getName().endsWith(TXT_FILE_FILTER.getExtension())) {
logFile = new File(logFile.getAbsolutePath() + TXT_FILE_FILTER.getExtension());
}
 
saveTXT(logFile);
 
} else if(fileChooser.getFileFilter().equals(XML_FILE_FILTER)) {
if(!logFile.getName().endsWith(XML_FILE_FILTER.getExtension())) {
logFile = new File(logFile.getAbsolutePath() + XML_FILE_FILTER.getExtension());
}
 
saveXML(logFile);
 
}
 
// FileOutputStream outStream = new FileOutputStream(logFile);
// ObjectOutputStream out = new ObjectOutputStream(outStream);
//
// int rows = model.getRowCount();
// out.writeInt(rows);
//
// for(int i = 0; i < rows; i++) {
// out.writeObject(model.getValueAt(i, 0));
// }
//
// out.close();
 
} catch(Exception e) {
e.printStackTrace(System.err);
}
}
 
}
 
private void saveTXT(File file) throws Exception {
 
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file)));
 
for(int i = 0; i < model.getRecordCount(); i++) {
LogRecord record = model.getRecord(i);
writer.print(DATE_FORMAT.format(new Date(record.getMillis())));
writer.print('\t');
writer.print(record.getLevel().toString());
writer.print('\t');
writer.println(record.getMessage());
}
 
writer.close();
 
}
 
private void saveXML(File file) throws Exception {
 
Element root = new Element("Log");
 
for(int i = 0; i < model.getRecordCount(); i++) {
LogRecord record = model.getRecord(i);
 
Element recordE = new Element("Record");
recordE.addContent(new Element("TimeStamp").addContent(DATE_FORMAT.format(new Date(record.getMillis()))));
recordE.addContent(new Element("Level").addContent(record.getLevel().toString()));
recordE.addContent(new Element("Message").addContent(record.getMessage()));
 
root.addContent(recordE);
}
 
FileOutputStream writer = new FileOutputStream(file);
 
new XMLOutputter().output(new Document(root), writer);
 
writer.close();
 
}
 
private void createJFileChooser() {
 
getRootPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
System.out.println("Loading File Chooser... " + Thread.currentThread().getName());
 
if(fileChooser != null) {
return;
}
 
fileChooser = new JFileChooser();
fileChooser.removeChoosableFileFilter(fileChooser.getFileFilter());
fileChooser.addChoosableFileFilter(TXT_FILE_FILTER);
fileChooser.addChoosableFileFilter(XML_FILE_FILTER);
 
fileChooser.setFileFilter(TXT_FILE_FILTER);
 
System.out.println("File Chooser Loaded... " + Thread.currentThread().getName());
getRootPane().setCursor(Cursor.getDefaultCursor());
 
}
 
public void clear() {
model.clear();
}
 
private final class LogAction implements ActionListener {
 
public void actionPerformed(ActionEvent ae) {
String level = ae.getActionCommand();
AVRSystem.PREFS.put("avr.log.level", level);
model.setFilter(Level.parse(ae.getActionCommand()));
}
 
}
 
private final class OnlyShowLevelAction implements ActionListener {
 
public void actionPerformed(ActionEvent event) {
boolean selected = ((JCheckBox)event.getSource()).isSelected();
AVRSystem.PREFS.putBoolean("avr.log.onlyshowlevel.selected", selected);
model.setOnlyShowSelectedLevel(selected);
}
 
}
 
private final static class LogModelHandler implements TableModelListener {
 
private JTable table;
 
public LogModelHandler(JTable table) {
this.table = table;
}
 
public void tableChanged(TableModelEvent tableModelEvent) {
table.scrollRectToVisible(table.getCellRect(table.getRowCount() - 1, 0, true));
}
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JMessagePanel.java
0,0 → 1,120
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.*;
import java.nio.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
 
import avr.device.event.*;
import avr.lang.*;
 
public class JMessagePanel extends JPanel {
 
private JTextArea messageTA;
 
public JMessagePanel() {
super(new BorderLayout());
 
JLabel titleL = new JLabel("System Messages", JLabel.CENTER);
titleL.setFont(titleL.getFont().deriveFont(16.0f));
 
JButton closeB = new JButton(new ProxyAction(this, "close", UIManager.getIcon("InternalFrame.paletteCloseIcon")));
closeB.setBackground(MetalLookAndFeel.getPrimaryControlShadow());
closeB.setBorder(new EmptyBorder(0, 0, 0, 0));
 
messageTA = new JTextArea(6, 20);
messageTA.setEditable(false);
 
Box titleBox = new Box(BoxLayout.X_AXIS);
titleBox.setBorder(new EmptyBorder(5, 5, 5, 5));
titleBox.add(titleL);
titleBox.add(Box.createHorizontalGlue());
titleBox.add(closeB);
 
JPanel southP = new JPanel(new FlowLayout(FlowLayout.RIGHT));
southP.setBorder(new EtchedBorder());
southP.add(new JButton(new ProxyAction(this, "clear", "Clear", 'c')));
 
add(titleBox, BorderLayout.NORTH);
add(new JScrollPane(messageTA), BorderLayout.CENTER);
add(southP, BorderLayout.SOUTH);
 
AVRSystem.DEVICE.addDataListener(new DataHandler(messageTA));
}
 
public void append(String message) {
messageTA.append(message);
messageTA.append("\n");
}
 
public void clear() {
messageTA.setText("");
}
 
public void close() {
setVisible(false);
}
 
private final static class DataHandler implements DataListener {
 
private JTextArea messageTA;
 
public DataHandler(JTextArea messageTA) {
this.messageTA = messageTA;
}
 
public void ack() {
messageTA.append("ACK\n");
}
 
public void nck() {
messageTA.append("NCK\n");
}
 
public void version(String version) {
messageTA.append(version);
messageTA.append("\n");
}
 
public void responseTimerExpired() {
messageTA.append("Response Timer Expired\n");
}
 
public void frameData(ByteBuffer data) {
messageTA.append("Frame Data (" + (data.get() & 0xFF) + ")\n");
}
 
public void trackingData(ByteBuffer data) {
messageTA.append("Tracking Data (" + (data.get() & 0xFF) + ")\n");
}
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JNewColorMapPanel.java
0,0 → 1,975
package avr.swing;
 
import com.sun.java.swing.SwingUtilities2;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.plaf.metal.*;
 
import avr.lang.*;
import avr.swing.*;
import avr.connection.event.ConnectionListener;
import avr.connection.event.ConnectionEvent;
import avr.device.event.DataAdapter;
import avr.device.event.DataListener;
import java.io.IOException;
 
public class JNewColorMapPanel extends JColorMapInterface {
 
public static void main(String[] args) {
 
JFrame frame = new JFrame("Testing");
 
// frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new JNewColorMapPanel(null), BorderLayout.CENTER);
frame.pack();
 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
frame.show();
}
 
private JSelectionPanel redP;
private JSelectionPanel greenP;
private JSelectionPanel blueP;
private JIndexRadioButton indicies[];
 
private static final int RED_INDEX = 0;
private static final int GREEN_INDEX = 1;
private static final int BLUE_INDEX = 2;
 
private static final int RED_MASK = 0xFF0000;
private static final int GREEN_MASK = 0x00FF00;
private static final int BLUE_MASK = 0x0000FF;
 
private static final int MIN_INDEX = 0;
private static final int MAX_INDEX = 1;
 
private int[][][] cachedMap;
 
private JMessagePanel messageP;
 
private Action checkAction;
private Action clearColumnAction;
private Action clearAction;
private Action resetAction;
private Action sendAction;
 
public JNewColorMapPanel(JMessagePanel messageP) {
super(null);
 
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
 
this.messageP = messageP;
 
cachedMap = new int[8][3][2];
 
redP = new JSelectionPanel(JSelectionPanel.RED_INDEX);
greenP = new JSelectionPanel(JSelectionPanel.GREEN_INDEX);
blueP = new JSelectionPanel(JSelectionPanel.BLUE_INDEX);
 
JPanel topP = new JPanel();
topP.add(new JLabel("Color Index:"));
 
ButtonGroup bg = new ButtonGroup();
 
indicies = new JIndexRadioButton[8];
 
ProxyAction indexAction = new ProxyAction(this, "updateSliders", (String)null);
ItemListener itemHandler = new ItemHandler();
 
for(int i = 0; i < 8; i++) {
indicies[i] = new JIndexRadioButton("" + (i + 1), i == 0);
indicies[i].addActionListener(indexAction);
indicies[i].addItemListener(itemHandler);
indicies[i].setOpaque(false);
bg.add(indicies[i]);
topP.add(indicies[i]);
}
 
checkAction = new ProxyAction(this, "check", "Auto Check", 'a');
clearColumnAction = new ProxyAction(this, "clearColumn", "Clear Indicies", 'l');
clearAction = new ProxyAction(this, "clear", "Clear All", 'c');
resetAction = new ProxyAction(this, "reset", "Reset", 'r');
sendAction = new ProxyAction(this, "send", "Send", 's');
 
sendAction.setEnabled(false);
 
Box southBox = new Box(BoxLayout.X_AXIS);
southBox.setBorder(new CompoundBorder(new EtchedBorder(), new EmptyBorder(5, 5, 5, 5)));
 
southBox.add(new JButton(checkAction));
southBox.add(Box.createHorizontalGlue());
southBox.add(Box.createHorizontalStrut(5));
southBox.add(new JButton(clearColumnAction));
southBox.add(Box.createHorizontalStrut(5));
southBox.add(new JButton(clearAction));
southBox.add(Box.createHorizontalStrut(5));
southBox.add(new JButton(resetAction));
southBox.add(Box.createHorizontalStrut(5));
southBox.add(new JButton(sendAction));
 
add(topP);
add(Box.createVerticalStrut(5));
add(redP);
add(Box.createVerticalStrut(5));
add(greenP);
add(Box.createVerticalStrut(5));
add(blueP);
add(Box.createVerticalStrut(5));
add(southBox);
 
reset();
 
AVRSystem.DEVICE.addConnectionListener(new ConnectionHandler());
}
 
private static String formatColorMapException(InvalidColorMapException icme) {
 
StringBuffer builder = new StringBuffer("Invalid Color Map: ");
 
int[] indicies = icme.getIndicies();
 
builder.append("Indicies ");
 
for(int i = 0; i < indicies.length; i++) {
 
builder.append(indicies[i]);
 
if((i + 1) < indicies.length) {
builder.append(" and ");
}
 
}
 
builder.append(" intersect at values Red: ")
.append(icme.getRed())
.append(" Green: ")
.append(icme.getGreen())
.append(" Blue: ")
.append(icme.getBlue());
 
return builder.toString();
 
}
 
public void check() {
 
try {
checkMap();
 
JOptionPane.showMessageDialog(getRootPane(),
"Color Map is valid.",
"Color Map Validated",
JOptionPane.INFORMATION_MESSAGE);
} catch(InvalidColorMapException icme) {
JOptionPane.showMessageDialog(getRootPane(), formatColorMapException(icme));
}
 
}
 
/* *************************************
* Copied from java.lang.Integer class
* from the JDK 1.5 version.
*/
private int bitCount(int i) {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
 
private void checkMap() throws InvalidColorMapException {
 
updateCacheMap();
 
int[][] colorMap = convert();
 
for(int redI = 0; redI < AVRSystem.NUM_INTENSITIES; redI++) {
int red = colorMap[0][redI];
for(int greenI = 0; greenI < AVRSystem.NUM_INTENSITIES; greenI++) {
int green = colorMap[1][greenI];
for(int blueI = 0; blueI < AVRSystem.NUM_INTENSITIES; blueI++) {
int blue = colorMap[2][blueI];
 
int value = red & green & blue;
 
// In JDk 1.5 the Integer class has the bitCount
// method. To be backward compatible, use the bitCount
// method above.
// if(value != 0 && (Integer.bitCount(value) > 1)) {
if(value != 0 && (bitCount(value) > 1)) {
 
int[] indicies = new int[bitCount(value)];
int count = 0;
for(int i = 0; i < 8; i++) {
if((value & (0x80 >>> i)) != 0) {
indicies[count++] = (i + 1);
}
}
 
throw new InvalidColorMapException("Color Map is invalid.", indicies, redI * 16, greenI * 16, blueI * 16);
}
 
}
 
}
}
 
}
 
private int[][] convert() {
 
int[][] colorMap = new int[3][AVRSystem.NUM_INTENSITIES];
 
for(int color = 0; color < 3; color++) {
for(int col = 0; col < 8; col++) {
for(int i = 1; i < AVRSystem.NUM_INTENSITIES; i++) {
 
int min = cachedMap[col][color][MIN_INDEX];
int max = cachedMap[col][color][MAX_INDEX];
 
if((min <= (i * 16)) && ((i * 16) <= max)) {
colorMap[color][i] |= (0x01 << (7 - col));
}
 
}
 
}
}
 
return colorMap;
 
}
 
public boolean isColumnClear(int column) {
 
return cachedMap[column][RED_INDEX][MIN_INDEX] == 0 &&
cachedMap[column][RED_INDEX][MAX_INDEX] == 0 &&
cachedMap[column][GREEN_INDEX][MIN_INDEX] == 0 &&
cachedMap[column][GREEN_INDEX][MAX_INDEX] == 0 &&
cachedMap[column][BLUE_INDEX][MIN_INDEX] == 0 &&
cachedMap[column][BLUE_INDEX][MAX_INDEX] == 0;
 
}
 
public void clear() {
cachedMap = new int[8][3][2];
 
updateSliders();
updateBackgrounds();
}
 
public void reset() {
 
int[][] colorMap = AVRSystem.DEVICE.getColorMap();
 
for(int c = 0; c < 8; c++) {
int minRed = 0;
int maxRed = 0;
int minGreen = 0;
int maxGreen = 0;
int minBlue = 0;
int maxBlue = 0;
 
for(int i = 0; i < AVRSystem.NUM_INTENSITIES; i++) {
 
int value = i * 16;
 
if((colorMap[0][i] & (0x01 << (7 - c))) != 0) {
if(minRed == 0 || value < minRed) {
minRed = value;
}
if(maxRed < (value)) {
maxRed = value;
}
}
 
if((colorMap[1][i] & (0x01 << (7 - c))) != 0) {
if(minGreen == 0 || value < minGreen) {
minGreen = value;
}
if(maxGreen < (value)) {
maxGreen = value;
}
}
 
if((colorMap[2][i] & (0x01 << (7 - c))) != 0) {
if(minBlue == 0 || value < minBlue) {
minBlue = value;
}
if(maxBlue < (value)) {
maxBlue = value;
}
}
 
}
 
int col = c;
 
cachedMap[col][RED_INDEX][MIN_INDEX] = minRed;
cachedMap[col][RED_INDEX][MAX_INDEX] = maxRed;
 
cachedMap[col][GREEN_INDEX][MIN_INDEX] = minGreen;
cachedMap[col][GREEN_INDEX][MAX_INDEX] = maxGreen;
 
cachedMap[col][BLUE_INDEX][MIN_INDEX] = minBlue;
cachedMap[col][BLUE_INDEX][MAX_INDEX] = maxBlue;
 
}
 
updateSliders();
updateBackgrounds();
 
}
 
public void clearColumn() {
 
JPanel displayP = new JPanel(new BorderLayout());
 
JPanel selectColP = new JPanel();
 
JCheckBox[] colCB = new JCheckBox[8];
for(int i = 0; i < colCB.length; i++) {
colCB[i] = new JCheckBox((i + 1) + "");
selectColP.add(colCB[i]);
}
 
displayP.add(new JLabel("Select Color Map Index:"), BorderLayout.NORTH);
displayP.add(selectColP, BorderLayout.SOUTH);
 
int option = JOptionPane.showConfirmDialog(getRootPane(),
displayP,
"Select Indicies to clear:",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
 
if(option == JOptionPane.OK_OPTION) {
 
/* *********************************************
* NOTE: This one loop is only checking the
* length of the red color panels but is also
* looping over the green and blue ones!!!!
**/
for(int col = 0; col < 8; col++) {
if(colCB[col].isSelected()) {
cachedMap[col][RED_INDEX][MIN_INDEX] = 0;
cachedMap[col][RED_INDEX][MAX_INDEX] = 0;
cachedMap[col][GREEN_INDEX][MIN_INDEX] = 0;
cachedMap[col][GREEN_INDEX][MAX_INDEX] = 0;
cachedMap[col][BLUE_INDEX][MIN_INDEX] = 0;
cachedMap[col][BLUE_INDEX][MAX_INDEX] = 0;
}
}
 
updateSliders();
updateBackgrounds();
}
}
 
public void send() {
 
try {
 
checkMap();
 
int[][] newColorMap = convert();
 
DataListener handler = new DataHandler(newColorMap);
try {
 
AVRSystem.DEVICE.addDataListener(handler);
getRootPane().getGlassPane().setVisible(true);
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(true);
AVRSystem.DEVICE.sendSetColorMap(newColorMap[0], newColorMap[1], newColorMap[2]);
messageP.append("Sent Color Map");
} catch(IOException ioe) {
AVRSystem.DEVICE.removeDataListener(handler);
getRootPane().getGlassPane().setVisible(false);
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(false);
ioe.printStackTrace();
AVRSystem.LOG.severe(ioe.getMessage());
}
} catch(InvalidColorMapException icme) {
JOptionPane.showMessageDialog(getRootPane(),
formatColorMapException(icme),
"Check Failed",
JOptionPane.ERROR_MESSAGE);
}
 
}
 
public void setColor(int index, int color) {
 
int minRed = (color & RED_MASK) >>> 16;
int minGreen = (color & GREEN_MASK) >>> 8;
int minBlue = (color & BLUE_MASK) >>> 0;
 
int maxRed = minRed;
int maxGreen = minGreen;
int maxBlue = minBlue;
 
if(minRed == 16) {
maxRed *= 3;
} else if(minRed == 240) {
minRed -= (16 * 2);
} else {
minRed -= 16;
maxRed += 16;
}
 
if(minGreen == 16) {
maxGreen *= 3;
} else if(minGreen == 240) {
minGreen -= (16 * 2);
} else {
minGreen -= 16;
maxGreen += 16;
}
 
if(minBlue == 16) {
maxBlue *= 3;
} else if(minBlue == 240) {
minBlue -= (16 * 2);
} else {
minBlue -= 16;
maxBlue += 16;
}
 
cachedMap[index][RED_INDEX][MIN_INDEX] = minRed;
cachedMap[index][RED_INDEX][MAX_INDEX] = maxRed;
 
cachedMap[index][GREEN_INDEX][MIN_INDEX] = minGreen;
cachedMap[index][GREEN_INDEX][MAX_INDEX] = maxGreen;
 
cachedMap[index][BLUE_INDEX][MIN_INDEX] = minBlue;
cachedMap[index][BLUE_INDEX][MAX_INDEX] = maxBlue;
 
indicies[index].setSelected(true);
 
updateSliders();
// updateBackgrounds();
 
}
 
private void updateCacheMap() {
 
for(int i = 0; i < 8; i++) {
if(indicies[i].isSelected()) {
cachedMap[i][RED_INDEX][MIN_INDEX] = redP.getMin();
cachedMap[i][RED_INDEX][MAX_INDEX] = redP.getMax();
cachedMap[i][GREEN_INDEX][MIN_INDEX] = greenP.getMin();
cachedMap[i][GREEN_INDEX][MAX_INDEX] = greenP.getMax();
cachedMap[i][BLUE_INDEX][MIN_INDEX] = blueP.getMin();
cachedMap[i][BLUE_INDEX][MAX_INDEX] = blueP.getMax();
}
}
 
}
 
public void update() {
updateCacheMap();
updateSliders();
}
 
public void updateBackgrounds() {
 
for(int i = 0; i < indicies.length; i++) {
 
int avgRed = (cachedMap[i][RED_INDEX][MIN_INDEX] +
cachedMap[i][RED_INDEX][MAX_INDEX]) / 2;
int avgGreen = (cachedMap[i][GREEN_INDEX][MIN_INDEX] +
cachedMap[i][GREEN_INDEX][MAX_INDEX]) / 2;
int avgBlue = (cachedMap[i][BLUE_INDEX][MIN_INDEX] +
cachedMap[i][BLUE_INDEX][MAX_INDEX]) / 2;
 
indicies[i].setToolTipText("Average Color: Red (" + avgRed + ") Green (" + avgGreen + ") Blue (" + avgBlue + ")");
 
indicies[i].setMinColor(
new Color(cachedMap[i][RED_INDEX][MIN_INDEX],
cachedMap[i][GREEN_INDEX][MIN_INDEX],
cachedMap[i][BLUE_INDEX][MIN_INDEX]));
indicies[i].setMaxColor(
new Color(cachedMap[i][RED_INDEX][MAX_INDEX],
cachedMap[i][GREEN_INDEX][MAX_INDEX],
cachedMap[i][BLUE_INDEX][MAX_INDEX]));
indicies[i].repaint();
 
}
 
}
 
public void updateSliders() {
 
for(int i = 0; i < indicies.length; i++) {
 
if(indicies[i].isSelected()) {
 
redP.setMin(cachedMap[i][RED_INDEX][MIN_INDEX]);
redP.setMax(cachedMap[i][RED_INDEX][MAX_INDEX]);
greenP.setMin(cachedMap[i][GREEN_INDEX][MIN_INDEX]);
greenP.setMax(cachedMap[i][GREEN_INDEX][MAX_INDEX]);
blueP.setMin(cachedMap[i][BLUE_INDEX][MIN_INDEX]);
blueP.setMax(cachedMap[i][BLUE_INDEX][MAX_INDEX]);
 
}
 
}
 
 
}
 
private static final class JIndexRadioButton extends JRadioButton {
 
private Color min;
private Color max;
 
public JIndexRadioButton(String text, boolean selected) {
super(text, selected);
min = Color.BLACK;
max = Color.BLACK;
}
 
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width += 20;
return size;
}
 
public void setMinColor(Color min) {
this.min = min;
}
 
public void setMaxColor(Color max) {
this.max = max;
}
 
public void paintComponent(Graphics g) {
 
AbstractButton b = (AbstractButton) this;
JComponent c = this;
 
Dimension size = c.getSize();
 
Font f = c.getFont();
FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, f);
 
Rectangle viewRect = new Rectangle(size);
Rectangle iconRect = new Rectangle();
Rectangle textRect = new Rectangle();
 
Insets i = c.getInsets();
viewRect.x += i.left;
viewRect.y += i.top;
viewRect.width -= (i.right + viewRect.x);
viewRect.height -= (i.bottom + viewRect.y);
 
Icon altIcon = b.getIcon();
 
String text = SwingUtilities.layoutCompoundLabel(
c, fm, b.getText(), altIcon != null ? altIcon : UIManager.getIcon("RadioButton.icon"),
b.getVerticalAlignment(), b.getHorizontalAlignment(),
b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
viewRect, iconRect, textRect, b.getIconTextGap());
 
Graphics2D g2d = (Graphics2D)g;
 
Paint paint = g2d.getPaint();
Stroke stroke = g2d.getStroke();
 
g2d.setPaint(new GradientPaint(0, 0, min, size.width, 0, max));
g2d.setStroke(new BasicStroke(size.height));
g2d.fillRect(0, 0, size.width, size.height);
 
g2d.setPaint(paint);
g2d.setStroke(stroke);
 
super.paintComponent(g);
 
g.setColor(Color.WHITE);
g.fillRect(textRect.x - 1, textRect.y + 2, textRect.width + 2, textRect.height - 4);
paintText(g, c, textRect, text);
 
 
}
 
protected void paintText(Graphics g, JComponent c, Rectangle textRect,
String text) {
AbstractButton b = (AbstractButton)c;
ButtonModel model = b.getModel();
FontMetrics fm = SwingUtilities2.getFontMetrics(c, g);
int mnemonicIndex = b.getDisplayedMnemonicIndex();
 
/* Draw the Text */
if(model.isEnabled()) {
/*** paint the text normally */
g.setColor(b.getForeground());
SwingUtilities2.drawStringUnderlineCharAt(c, g, text, mnemonicIndex,
textRect.x + UIManager.getInt("Button.textShiftOffset"),
textRect.y + fm.getAscent() + UIManager.getInt("Button.textShiftOffset"));
} else {
/*** paint the text disabled ***/
g.setColor(b.getBackground().brighter());
SwingUtilities2.drawStringUnderlineCharAt(c, g, text, mnemonicIndex,
textRect.x, textRect.y + fm.getAscent());
g.setColor(b.getBackground().darker());
SwingUtilities2.drawStringUnderlineCharAt(c, g, text, mnemonicIndex,
textRect.x - 1, textRect.y + fm.getAscent() - 1);
}
}
 
}
 
private final class ItemHandler implements ItemListener {
 
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.DESELECTED) {
for(int i = 0; i < 8; i++) {
if(indicies[i] == e.getSource()) {
cachedMap[i][RED_INDEX][MIN_INDEX] = redP.getMin();
cachedMap[i][RED_INDEX][MAX_INDEX] = redP.getMax();
cachedMap[i][GREEN_INDEX][MIN_INDEX] = greenP.getMin();
cachedMap[i][GREEN_INDEX][MAX_INDEX] = greenP.getMax();
cachedMap[i][BLUE_INDEX][MIN_INDEX] = blueP.getMin();
cachedMap[i][BLUE_INDEX][MAX_INDEX] = blueP.getMax();
}
}
 
}
}
 
}
 
private static final class JSelectionPanel extends Box {
 
public static final int RED_INDEX = 0;
public static final int GREEN_INDEX = 1;
public static final int BLUE_INDEX = 2;
 
private JSlider minS;
private JSlider maxS;
private JColorLabel colorL;
 
private int index;
 
public JSelectionPanel(int index) {
super(BoxLayout.Y_AXIS);
 
this.index = index;
 
minS = new JSlider(0, 16 * (AVRSystem.NUM_INTENSITIES - 1), 16);
maxS = new JSlider(0, 16 * (AVRSystem.NUM_INTENSITIES - 1), 16);
 
minS.setUI(new AVRSliderUI(AVRSliderUI.RIGHT));
maxS.setUI(new AVRSliderUI(AVRSliderUI.LEFT));
 
colorL = new JColorLabel(index);
 
minS.setMajorTickSpacing(16);
minS.setSnapToTicks(true);
minS.setOpaque(false);
 
maxS.setPaintTicks(true);
maxS.setMajorTickSpacing(16);
maxS.setSnapToTicks(true);
maxS.setOpaque(false);
maxS.setPaintLabels(true);
 
minS.addChangeListener(new MinChangeHandler());
maxS.addChangeListener(new MaxChangeHandler());
 
minS.setForeground(Color.WHITE);
maxS.setForeground(Color.WHITE);
 
int sliderWidth = Math.max(minS.getPreferredSize().width,
maxS.getPreferredSize().width);
 
sliderWidth = (int)(sliderWidth * 1.75);
 
minS.setBorder(new CompoundBorder(minS.getBorder(), new EmptyBorder(0, 3, 0, 3)));
 
Dimension sliderDim = minS.getPreferredSize();
sliderDim.width = sliderWidth;
minS.setPreferredSize(sliderDim);
 
sliderDim = maxS.getPreferredSize();
sliderDim.width = sliderWidth;
maxS.setPreferredSize(sliderDim);
 
Enumeration labels = maxS.getLabelTable().elements();
 
while(labels.hasMoreElements()) {
((JLabel)labels.nextElement()).setForeground(Color.WHITE);
}
 
add(minS);
add(maxS);
 
}
 
public int getMin() {
return minS.getValue();
}
 
public void setMin(int min) {
minS.setValue(min);
}
 
public int getMax() {
return maxS.getValue();
}
 
public void setMax(int max) {
maxS.setValue(max);
}
 
public void paintComponent(Graphics g) {
 
Insets insets = getInsets();
Dimension size = getSize();
 
Graphics2D g2d = (Graphics2D)g;
 
int minRed = 0;
int minGreen = 0;
int minBlue = 0;
 
int maxRed = 0;
int maxGreen = 0;
int maxBlue = 0;
 
switch(index) {
case RED_INDEX:
maxRed = maxS.getValue();
minRed = minS.getValue();
break;
case GREEN_INDEX:
maxGreen = maxS.getValue();
minGreen = minS.getValue();
break;
case BLUE_INDEX:
maxBlue = maxS.getValue();
minBlue = minS.getValue();
break;
}
 
Color minColor = new Color(minRed, minGreen, minBlue);
Color maxColor = new Color(maxRed, maxGreen, maxBlue);
 
Paint paint = new GradientPaint(insets.left, insets.top, minColor,
size.width - insets.right, insets.top, maxColor);
g2d.setPaint(paint);
g2d.fillRect(insets.left, insets.top,
size.width - insets.left - insets.right,
size.height - insets.top - insets.bottom);
 
}
 
private final class MinChangeHandler implements ChangeListener {
 
public void stateChanged(ChangeEvent e) {
if(maxS.getValue() < minS.getValue()) {
maxS.setValue(minS.getValue());
}
// colorL.setMin(minS.getValue());
repaint();
}
 
}
 
private final class MaxChangeHandler implements ChangeListener {
 
public void stateChanged(ChangeEvent e) {
if(maxS.getValue() < minS.getValue()) {
minS.setValue(maxS.getValue());
}
// colorL.setMax(maxS.getValue());
repaint();
}
 
}
 
private static final class JColorLabel extends JLabel {
 
private int index;
 
private int max;
private int min;
 
public JColorLabel(int index) {
this.index = index;
setBorder(new LineBorder(Color.BLACK));
setOpaque(true);
min = 0;
max = 0;
}
 
public void setMin(int min) {
this.min = min;
repaint();
}
 
public void setMax(int max) {
this.max = max;
repaint();
}
 
public void paintComponent(Graphics g) {
 
Insets insets = getInsets();
Dimension size = getSize();
 
Graphics2D g2d = (Graphics2D)g;
 
int minRed = 0;
int minGreen = 0;
int minBlue = 0;
 
int maxRed = 0;
int maxGreen = 0;
int maxBlue = 0;
 
switch(index) {
case RED_INDEX:
maxRed = max;
minRed = min;
break;
case GREEN_INDEX:
maxGreen = max;
minGreen = min;
break;
case BLUE_INDEX:
maxBlue = max;
minBlue = min;
break;
}
 
Color minColor = new Color(minRed, minGreen, minBlue);
Color maxColor = new Color(maxRed, maxGreen, maxBlue);
 
Paint paint = new GradientPaint(insets.left, insets.top, minColor,
size.width - insets.right, insets.top, maxColor);
g2d.setPaint(paint);
g2d.fillRect(insets.left, insets.top,
size.width - insets.left - insets.right,
size.height - insets.top - insets.bottom);
 
}
 
}
 
private static final class AVRSliderUI extends MetalSliderUI {
 
public static final int LEFT = 0;
public static final int RIGHT = 1;
 
private int direction;
 
public AVRSliderUI(int direction) {
this.direction = direction;
filledSlider = false;
}
 
// overridden to not fill in the track
public void paintTrack(Graphics g) {
 
boolean drawInverted = this.drawInverted();
 
Rectangle paintRect = avrGetPaintTrackRect();
g.translate(paintRect.x, paintRect.y);
 
int w = paintRect.width;
int h = paintRect.height;
 
g.setColor(MetalLookAndFeel.getPrimaryControlDarkShadow());
g.drawRect(0, 0, w - 1, h - 1);
 
g.translate(-paintRect.x, -paintRect.y);
 
}
 
// overridden to point the thumb to the left or the right
public void paintThumb(Graphics g) {
Rectangle knobBounds = thumbRect;
if(direction == LEFT) {
g.translate( knobBounds.x, knobBounds.y );
((Graphics2D)g).rotate(Math.PI, knobBounds.width / 2, knobBounds.height / 2);
 
vertThumbIcon.paintIcon( slider, g, 0, 0 );
 
((Graphics2D)g).rotate(-Math.PI, knobBounds.width / 2, knobBounds.height / 2);
g.translate( -knobBounds.x, -knobBounds.y );
} else {
g.translate( knobBounds.x, knobBounds.y );
 
vertThumbIcon.paintIcon( slider, g, 0, 0 );
 
g.translate( -knobBounds.x, -knobBounds.y );
}
}
 
// this method is private in the MetalSliderUI class, so I have recreated
// the method so I can use it
private Rectangle avrGetPaintTrackRect() {
int trackLeft = 0, trackRight = 0, trackTop = 0, trackBottom = 0;
trackBottom = (trackRect.height - 1) - getThumbOverhang();
trackTop = trackBottom - (getTrackWidth() - 1);
trackRight = trackRect.width - 1;
return new Rectangle(trackRect.x + trackLeft, trackRect.y + trackTop,
trackRight - trackLeft, trackBottom - trackTop);
}
}
 
}
 
private final class ConnectionHandler implements ConnectionListener {
public void connected(ConnectionEvent ce) {
sendAction.setEnabled(true);
}
 
public void disconnected(ConnectionEvent ce) {
sendAction.setEnabled(false);
}
 
}
 
private final class DataHandler extends DataAdapter {
 
private int[][] colorMap;
 
public DataHandler(int[][] colorMap) {
this.colorMap = colorMap;
}
 
public void ack() {
AVRSystem.DEVICE.setColorMap(colorMap);
reset();
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(false);
getRootPane().getGlassPane().setVisible(false);
AVRSystem.DEVICE.removeDataListener(this);
}
 
public void nck() {
getRootPane().getGlassPane().setVisible(false);
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(false);
AVRSystem.DEVICE.removeDataListener(this);
JOptionPane.showMessageDialog(getRootPane(), "Set Color Map NCK Received", "NCK Received", JOptionPane.ERROR_MESSAGE);
}
 
public void responseTimerExpired() {
getRootPane().getGlassPane().setVisible(false);
SwingUtilities.getRootPane(messageP).getGlassPane().setVisible(false);
AVRSystem.DEVICE.removeDataListener(this);
JOptionPane.showMessageDialog(messageP.getRootPane(), "Response Timer Expired", "Timer Expired", JOptionPane.ERROR_MESSAGE);
}
 
}
 
 
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JRegisterPanel.java
0,0 → 1,281
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
 
public class JRegisterPanel extends JPanel {
 
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
int option = new JRegisterPanel().showDialog(null);
System.out.println(option);
}
 
private static final String WARNING_TEXT = "WARNING!!! Changing the registers may cause the AVRcam to no longer respond. If this happens, simply power cycle the AVRcam.";
private static final int UNKNOWN_OPTION = 0x00;
public static final int OK_OPTION = 0x01;
public static final int CANCEL_OPTION = 0x02;
 
private JDialog dialog;
private JRegister[] registers;
private int option;
 
private JTabbedPane tabs;
 
private JRadioButton enableAutoWhiteBalanceRB;
private JRadioButton disableAutoWhiteBalanceRB;
private JRadioButton enableAutoAdjustModeRB;
private JRadioButton disableAutoAdjustModeRB;
private JRadioButton enableFlourescentLightFilterRB;
private JRadioButton disableFlourescentLightFilterRB;
 
public JRegisterPanel() {
super(new BorderLayout());
 
tabs = new JTabbedPane();
 
enableAutoWhiteBalanceRB = new JRadioButton("Enable", true);
disableAutoWhiteBalanceRB = new JRadioButton("Disable");
enableAutoAdjustModeRB = new JRadioButton("Enable");
disableAutoAdjustModeRB = new JRadioButton("Disable", true);
enableFlourescentLightFilterRB = new JRadioButton("Enable");
disableFlourescentLightFilterRB = new JRadioButton("Disable", true);
 
ButtonGroup autoWhiteBalanceBG = new ButtonGroup();
autoWhiteBalanceBG.add(enableAutoWhiteBalanceRB);
autoWhiteBalanceBG.add(disableAutoWhiteBalanceRB);
 
ButtonGroup autoAdjustModeBG = new ButtonGroup();
autoAdjustModeBG.add(enableAutoAdjustModeRB);
autoAdjustModeBG.add(disableAutoAdjustModeRB);
 
ButtonGroup flourescentLightFilterBG = new ButtonGroup();
flourescentLightFilterBG.add(enableFlourescentLightFilterRB);
flourescentLightFilterBG.add(disableFlourescentLightFilterRB);
 
// Box generalP = new Box(BoxLayout.Y_AXIS);
JPanel generalP = new JPanel();
generalP.setLayout(new BoxLayout(generalP, BoxLayout.Y_AXIS));
 
Border emptyBorder = new EmptyBorder(5, 5, 5, 5);
 
Box autoWhiteBalanceBox = new Box(BoxLayout.X_AXIS);
autoWhiteBalanceBox.setBorder(emptyBorder);
autoWhiteBalanceBox.add(new JLabel("Auto White Balance:"));
autoWhiteBalanceBox.add(Box.createHorizontalGlue());
autoWhiteBalanceBox.add(enableAutoWhiteBalanceRB);
autoWhiteBalanceBox.add(disableAutoWhiteBalanceRB);
 
Box autoAdjustModeBox = new Box(BoxLayout.X_AXIS);
autoAdjustModeBox.setBorder(emptyBorder);
autoAdjustModeBox.add(new JLabel("Auto Adjust Mode:"));
autoAdjustModeBox.add(Box.createHorizontalGlue());
autoAdjustModeBox.add(enableAutoAdjustModeRB);
autoAdjustModeBox.add(disableAutoAdjustModeRB);
 
Box flourescentLightFilterBox = new Box(BoxLayout.X_AXIS);
flourescentLightFilterBox.setBorder(emptyBorder);
flourescentLightFilterBox.add(new JLabel("Flourescent Light Filter:"));
flourescentLightFilterBox.add(Box.createHorizontalGlue());
flourescentLightFilterBox.add(enableFlourescentLightFilterRB);
flourescentLightFilterBox.add(disableFlourescentLightFilterRB);
 
generalP.add(autoWhiteBalanceBox);
generalP.add(autoAdjustModeBox);
generalP.add(flourescentLightFilterBox);
 
JPanel advancedP = new JPanel();
advancedP.setLayout(new BoxLayout(advancedP, BoxLayout.Y_AXIS));
 
JTextArea warningTA = new JTextArea(WARNING_TEXT);
warningTA.setEditable(false);
warningTA.setWrapStyleWord(true);
warningTA.setLineWrap(true);
warningTA.setForeground(Color.RED);
warningTA.setRows(4);
warningTA.setFont(warningTA.getFont().deriveFont(16F));
warningTA.setBackground(advancedP.getBackground());
warningTA.setBorder(new EmptyBorder(0, 10, 0, 10));
 
registers = new JRegister[8];
 
for(int i = 0; i < registers.length; i++) {
registers[i] = new JRegister();
advancedP.add(registers[i]);
advancedP.add(Box.createVerticalStrut(5));
}
advancedP.add(warningTA);
 
tabs.addTab("General", generalP);
tabs.addTab("Advanced", advancedP);
 
add(tabs, BorderLayout.CENTER);
 
}
 
public int showDialog(Frame owner) {
reset();
 
option = UNKNOWN_OPTION;
if(dialog == null) {
dialog = new JDialog(owner, "AVRcamVIEW - Set Registers", true);
 
dialog.getContentPane().add(this, BorderLayout.CENTER);
dialog.getContentPane().add(createButtonPanel(), BorderLayout.SOUTH);
dialog.pack();
dialog.setResizable(false);
}
 
dialog.setLocationRelativeTo(owner);
dialog.setVisible(true);
 
return option;
 
}
 
public void reset() {
for(int i = 0; i < registers.length; i++) {
registers[i].reset();
}
}
 
public Map getRegisters() {
Map info = new HashMap();
 
if(tabs.getSelectedIndex() == 0) {
 
if(enableAutoWhiteBalanceRB.isSelected()) {
info.put(new Integer(0x12), new Integer(0x2C));
} else {
info.put(new Integer(0x12), new Integer(0x28));
}
 
if(enableAutoAdjustModeRB.isSelected()) {
info.put(new Integer(0x13), new Integer(0x01));
} else {
info.put(new Integer(0x13), new Integer(0x00));
}
 
if(enableFlourescentLightFilterRB.isSelected()) {
info.put(new Integer(0x2D), new Integer(0x07));
} else {
info.put(new Integer(0x2D), new Integer(0x03));
}
 
} else {
for(int i = 0; i < registers.length; i++) {
JRegister r = registers[i];
if(r.isChecked()) {
info.put(r.getRegister(), r.getValue());
}
}
}
 
return Collections.unmodifiableMap(info);
}
 
public void ok() {
option = OK_OPTION;
dialog.setVisible(false);
}
 
public void cancel() {
option = CANCEL_OPTION;
dialog.setVisible(false);
}
 
private JComponent createButtonPanel() {
 
JPanel buttonP = new JPanel(new FlowLayout(FlowLayout.RIGHT));
 
buttonP.setBorder(new EtchedBorder());
 
buttonP.add(new JButton(new ProxyAction(this, "ok", "OK", 'o')));
buttonP.add(new JButton(new ProxyAction(this, "cancel", "Cancel", 'c')));
 
return buttonP;
}
 
private static final class JRegister extends JPanel {
 
private JCheckBox enableCB;
private JSpinner registerS;
private JSpinner valueS;
 
public JRegister() {
super(new FlowLayout(FlowLayout.CENTER));
 
// remove the default insets of the JPanel
setBorder(new EmptyBorder(-5, -5, -5, -5));
 
enableCB = new JCheckBox(new ProxyAction(this, "setEnabled", "Register"));
 
registerS = new JSpinner(new SpinnerNumberModel(0, 0, 0x90, 1));
valueS = new JSpinner(new SpinnerNumberModel(0, 0, 0xFF, 1));
 
reset();
 
add(enableCB);
add(registerS);
add(new JLabel(" = "));
add(valueS);
}
 
public void reset() {
enableCB.setSelected(false);
registerS.setEnabled(false);
valueS.setEnabled(false);
registerS.setValue(new Integer(0));
valueS.setValue(new Integer(0));
}
 
public boolean isChecked() {
return enableCB.isSelected();
}
 
public String getRegister() {
return registerS.getValue().toString();
}
 
public String getValue() {
return valueS.getValue().toString();
}
 
public void setEnabled() {
boolean enabled = enableCB.isSelected();
registerS.setEnabled(enabled);
valueS.setEnabled(enabled);
}
 
}
 
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JSerialPanel.java
0,0 → 1,222
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import javax.comm.*;
 
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
 
import avr.connection.*;
 
public class JSerialPanel extends JPanel {
 
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
int option = new JSerialPanel().showDialog(null, null);
System.out.println(option);
}
 
private static final Integer[] BAUD_RATES = {
new Integer(115200),
new Integer(57600),
new Integer(38400),
new Integer(19200),
new Integer(9600),
new Integer(4800)
};
 
private static final Integer[] DATA_BITS = {
new Integer(8),
new Integer(7),
new Integer(6),
new Integer(5)
};
 
private static final String[] PARITY = {
"None",
"Odd",
"Even",
"Mark",
"Space"
};
 
private static final Number[] STOP_BITS = {
new Integer(1),
new Double(1.5),
new Integer(2)
};
 
public static final String[] FLOW_CONTROL = {
"None",
"Hardware",
"Xon / Xoff"
};
 
 
private static final int UNKNOWN_OPTION = 0x00;
public static final int OK_OPTION = 0x01;
public static final int CANCEL_OPTION = 0x02;
 
private JComboBox baudRateCB;
private JComboBox dataBitsCB;
private JComboBox stopBitsCB;
private JComboBox parityCB;
private JComboBox flowControlCB;
 
private JDialog dialog;
private int option;
 
public JSerialPanel() {
super(new GridLayout(5, 2, 10, 10));
setBorder(new EmptyBorder(5, 5, 5, 5));
 
baudRateCB = new JComboBox(BAUD_RATES);
dataBitsCB = new JComboBox(DATA_BITS);
stopBitsCB = new JComboBox(STOP_BITS);
parityCB = new JComboBox(PARITY);
flowControlCB = new JComboBox(FLOW_CONTROL);
 
add(new JLabel("Baud Rate:", JLabel.RIGHT));
add(baudRateCB);
add(new JLabel("Data Bits:", JLabel.RIGHT));
add(dataBitsCB);
add(new JLabel("Stop Bits:", JLabel.RIGHT));
add(stopBitsCB);
add(new JLabel("Parity:", JLabel.RIGHT));
add(parityCB);
add(new JLabel("Flow Control:", JLabel.RIGHT));
add(flowControlCB);
}
 
public void setSerialParameters(SerialParams params) {
if(params != null) {
baudRateCB.setSelectedItem(new Integer(params.getBaudRate()));
dataBitsCB.setSelectedItem(new Integer(params.getDataBits()));
parityCB.setSelectedIndex(params.getParity());
 
switch(params.getStopBits()) {
case 1:
stopBitsCB.setSelectedIndex(0);
break;
case 2:
stopBitsCB.setSelectedIndex(2);
break;
case 3:
stopBitsCB.setSelectedIndex(1);
break;
}
 
if(params.getFlowControl() == SerialPort.FLOWCONTROL_NONE) {
flowControlCB.setSelectedIndex(0);
} else if(params.getFlowControl() == (SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT)) {
flowControlCB.setSelectedIndex(1);
} else if(params.getFlowControl() == (SerialPort.FLOWCONTROL_XONXOFF_IN | SerialPort.FLOWCONTROL_XONXOFF_OUT)) {
flowControlCB.setSelectedIndex(2);
}
}
}
 
public SerialParams getSerialParameters() {
int baudRate = ((Integer)baudRateCB.getSelectedItem()).intValue();
int dataBits = ((Integer)dataBitsCB.getSelectedItem()).intValue();
int parity = parityCB.getSelectedIndex();
int stopBits = 0;
int flowControl = 0;
 
switch(stopBitsCB.getSelectedIndex()) {
case 0:
stopBits = 1;
break;
case 1:
stopBits = 3;
break;
case 2:
stopBits = 2;
break;
}
 
switch(flowControlCB.getSelectedIndex()) {
case 0:
flowControl = SerialPort.FLOWCONTROL_NONE;
break;
case 1:
flowControl = SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT;
break;
case 2:
flowControl = SerialPort.FLOWCONTROL_XONXOFF_IN | SerialPort.FLOWCONTROL_XONXOFF_OUT;
break;
}
 
return new SerialParams(baudRate, dataBits, stopBits, parity, flowControl);
}
 
public void ok() {
option = OK_OPTION;
dialog.setVisible(false);
}
 
public void cancel() {
option = CANCEL_OPTION;
dialog.setVisible(false);
}
 
public int showDialog(Frame owner, SerialParams params) {
 
if(dialog == null) {
dialog = new JDialog(owner, "Serial Port Parameters", true);
 
dialog.getContentPane().add(this, BorderLayout.CENTER);
dialog.getContentPane().add(createButtonPanel(), BorderLayout.SOUTH);
dialog.pack();
dialog.setResizable(false);
}
 
option = UNKNOWN_OPTION;
 
setSerialParameters(params);
dialog.setLocationRelativeTo(owner);
dialog.setVisible(true);
 
return option;
 
}
 
private JComponent createButtonPanel() {
 
JPanel buttonP = new JPanel(new FlowLayout(FlowLayout.RIGHT));
 
buttonP.setBorder(new EtchedBorder());
 
buttonP.add(new JButton(new ProxyAction(this, "ok", "OK", 'o')));
buttonP.add(new JButton(new ProxyAction(this, "cancel", "Cancel", 'c')));
 
return buttonP;
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JTrackingInternalFrame.java
0,0 → 1,354
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
 
import avr.lang.*;
import avr.connection.event.ConnectionListener;
import avr.connection.event.ConnectionEvent;
 
public class JTrackingInternalFrame extends JInternalFrame {
 
private static final int BLOB_LENGTH = 5;
 
private JTrackingPanel trackingP;
 
private AbstractButton recordB;
private AbstractButton sendCameraDataB;
 
private Action recordAction;
private Action playAction;
private Action pauseAction;
private Action stopAction;
 
private FileInputStream inStream;
private FileChannel inChannel;
 
private Map indexMap;
private int numTracked;
 
private boolean paused;
 
private javax.swing.Timer timer;
 
private JSlider playbackS;
 
private ConnectionListener connectionHandler;
 
// common initializer for both constructors
{
trackingP = new JTrackingPanel();
 
createActions();
 
setJMenuBar(createMenuBar());
getContentPane().add(trackingP, BorderLayout.CENTER);
}
 
public JTrackingInternalFrame() {
super("Tracking", true, false, true, false);
getContentPane().add(createToolBar(), BorderLayout.NORTH);
}
 
public JTrackingInternalFrame(File trackingData) throws FileNotFoundException, IOException {
super("Tracking: " + trackingData.toString(), true, true, true, true);
 
inStream = new FileInputStream(trackingData);
inChannel = inStream.getChannel();
 
indexMap = new HashMap();
numTracked = -1;
 
paused = false;
 
// build an index map to map an index to a position in a file
indexMap.put(new Integer(0), new Integer(0));
 
ByteBuffer numTrackedBuffer = ByteBuffer.allocate(1);
int currentIndex = 0;
 
while(inChannel.read(numTrackedBuffer) != -1) {
 
numTrackedBuffer.flip();
numTracked = numTrackedBuffer.get() & 0xFF;
 
currentIndex++;
int position = (int)(inChannel.position() + (numTracked * BLOB_LENGTH));
 
indexMap.put(new Integer(currentIndex), new Integer(position));
 
inChannel.position(position);
numTrackedBuffer.clear();
 
}
 
sendCameraDataB = new JCheckBox(new ProxyAction(this, "sendCameraData", "Send To Serial Port"));
sendCameraDataB.setEnabled(AVRSystem.DEVICE.isConnected());
 
playbackS = new JSlider(JSlider.HORIZONTAL, 0, currentIndex - 1, 0);
playbackS.setMinorTickSpacing(1);
playbackS.setMajorTickSpacing(20);
playbackS.setPaintTicks(true);
playbackS.setPaintTrack(true);
playbackS.setPaintLabels(true);
playbackS.setSnapToTicks(true);
playbackS.addChangeListener(new PlaybackHandler());
 
JPanel southP = new JPanel(new BorderLayout());
southP.setBorder(new EmptyBorder(5, 0, 0, 0));
 
// JPanel controlP = new JPanel(new BorderLayout());
JPanel controlP = new JPanel();
 
controlP.add(new JButton(playAction));
controlP.add(new JButton(pauseAction));
controlP.add(new JButton(stopAction));
 
//
// JPanel controlNorthP = new JPanel();
// controlNorthP.add(new JButton(playAction));
// controlNorthP.add(new JButton(pauseAction));
// controlNorthP.add(new JButton(stopAction));
//
// JPanel controlSouthP = new JPanel();
// controlSouthP.add(sendCameraDataB);
//
// controlP.add(controlNorthP, BorderLayout.NORTH);
// controlP.add(controlSouthP, BorderLayout.SOUTH);
 
southP.add(playbackS, BorderLayout.NORTH);
southP.add(controlP, BorderLayout.SOUTH);
 
getContentPane().add(southP, BorderLayout.SOUTH);
 
trackingP.setTrackingData(read(0));
 
connectionHandler = new ConnectionHandler();
AVRSystem.DEVICE.addConnectionListener(connectionHandler);
 
}
 
private void createActions() {
recordAction = new ProxyAction(this, "record", "Start Recording", 's');
playAction = new ProxyAction(this, "play", "Play", 'p');
stopAction = new ProxyAction(this, "stop", "Stop", 's');
pauseAction = new ProxyAction(this, "pause", "Pause");
 
stopAction.setEnabled(false);
pauseAction.setEnabled(false);
 
}
 
private JMenuBar createMenuBar() {
 
JMenuBar menubar = new JMenuBar();
 
JMenu fileM = new JMenu("File");
 
fileM.add(new ProxyAction(this, "pack", "Reset Size", 'R'));
fileM.addSeparator();
fileM.add(new ProxyAction(this, "dispose", "Exit", 'X'));
 
menubar.add(fileM);
 
return menubar;
 
}
 
private JToolBar createToolBar() {
 
JToolBar toolbar = new JToolBar();
toolbar.setFloatable(false);
 
recordB = new JToggleButton(recordAction);
 
toolbar.add(recordB);
 
return toolbar;
 
}
 
public void dispose() {
if(inStream != null) {
if(timer != null) {
stop();
}
try {
inStream.close();
inChannel.close();
} catch(Exception e) {
e.printStackTrace();
}
}
AVRSystem.DEVICE.removeConnectionListener(connectionHandler);
super.dispose();
}
 
public void play() {
if(timer == null) {
// set the timer to fire for 30 frames per second
timer = new javax.swing.Timer((int)(1000 / 30), new UpdateSliderHandler());
}
timer.start();
playAction.setEnabled(false);
stopAction.setEnabled(true);
pauseAction.setEnabled(true);
}
 
public void pause() {
if(!paused) {
timer.stop();
playAction.setEnabled(false);
stopAction.setEnabled(false);
pauseAction.putValue(Action.NAME, "Resume");
paused = true;
} else {
timer.start();
playAction.setEnabled(false);
stopAction.setEnabled(true);
pauseAction.putValue(Action.NAME, "Pause");
paused = false;
}
}
 
public void stop() {
timer.stop();
playAction.setEnabled(true);
stopAction.setEnabled(false);
pauseAction.setEnabled(false);
playbackS.setValue(0);
}
 
public void sendCameraData() {
if(sendCameraDataB.isSelected()) {
trackingP.startSendingCameraData();
} else {
trackingP.stopSendingCameraData();
}
}
 
private ByteBuffer read(int position) throws IOException {
 
inChannel.position(position);
 
ByteBuffer numTrackedBuffer = ByteBuffer.allocate(1);
inChannel.read(numTrackedBuffer);
numTrackedBuffer.flip();
 
int numTracked = numTrackedBuffer.get() & 0xFF;
 
ByteBuffer blobBuffer = ByteBuffer.allocate(1 + (numTracked * BLOB_LENGTH));
 
inChannel.position(inChannel.position() - 1);
inChannel.read(blobBuffer);
blobBuffer.flip();
 
return blobBuffer;
 
}
 
public void record() {
if(recordB.isSelected()) {
try {
trackingP.startRecording();
recordB.setText("Stop Recording");
} catch(Exception e) {
recordB.setSelected(false);
}
} else {
stopRecording();
}
}
 
private void stopRecording() {
try {
trackingP.stopRecording();
recordB.setText("Start Recording");
} catch(Exception e) {
recordB.setSelected(true);
}
}
 
public void startTracking() {
trackingP.startTracking();
}
 
public void stopTracking() {
if(recordB.isSelected()) {
stopRecording();
}
trackingP.stopTracking();
}
 
private final class PlaybackHandler implements ChangeListener {
public void stateChanged(ChangeEvent ce) {
try {
trackingP.setTrackingData(read(((Integer)indexMap.get(new Integer(playbackS.getValue()))).intValue()));
} catch(IOException ioe) {
ioe.printStackTrace();
AVRSystem.LOG.severe(ioe.getMessage());
}
}
}
 
private final class UpdateSliderHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if(playbackS.getValue() == playbackS.getMaximum()) {
stop();
} else {
try {
playbackS.setValue(playbackS.getValue() + 1);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
 
private final class ConnectionHandler implements ConnectionListener {
public void connected(ConnectionEvent ce) {
sendCameraDataB.setEnabled(true);
}
 
public void disconnected(ConnectionEvent ce) {
trackingP.stopSendingCameraData();
sendCameraDataB.setSelected(false);
sendCameraDataB.setEnabled(false);
}
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/JTrackingPanel.java
0,0 → 1,245
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
 
import avr.device.event.*;
import avr.lang.*;
 
public class JTrackingPanel extends JPanel {
 
private static final DateFormat DATE_FORMAT;
 
static {
DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss");
}
 
private ColorBlob[] blobs;
private DataListener dataHandler;
 
private Dimension preferredSize;
 
private boolean recording;
private boolean sendCameraData;
 
private FileOutputStream outStream;
private FileChannel outChannel;
 
public JTrackingPanel() {
super(null);
 
recording = false;
sendCameraData = false;
 
setBackground(Color.BLACK);
dataHandler = new TrackingHandler();
 
preferredSize = null;
}
 
public void startRecording() throws FileNotFoundException {
File recordFile = new File(DATE_FORMAT.format(new Date()) + ".trk");
outStream = new FileOutputStream(recordFile);
outChannel = outStream.getChannel();
 
recording = true;
 
AVRSystem.LOG.info("Started Recording");
}
 
public void stopRecording() throws IOException {
 
recording = false;
 
outStream.close();
outChannel.close();
 
AVRSystem.LOG.info("Stopped Recording");
 
}
 
public void startTracking() {
AVRSystem.DEVICE.addDataListener(dataHandler);
}
 
public void stopTracking() {
AVRSystem.DEVICE.removeDataListener(dataHandler);
}
 
public void startSendingCameraData() {
sendCameraData = true;
}
 
public void stopSendingCameraData() {
sendCameraData = false;
}
 
public Dimension getMinimumSize() {
return getPreferredSize();
}
 
public Dimension getPreferredSize() {
if(preferredSize == null) {
Insets insets = this.getInsets();
preferredSize = new Dimension(insets.left + AVRSystem.IMAGE_WIDTH + insets.right,
insets.top + AVRSystem.IMAGE_HEIGHT + insets.bottom);
}
 
return preferredSize;
}
 
public Dimension getMaximumSize() {
return getPreferredSize();
}
 
public void paintComponent(Graphics g) {
 
super.paintComponent(g);
 
Dimension size = getSize();
 
Insets insets = getInsets();
 
double xScale = size.width /
(double)(insets.left + 5 + AVRSystem.IMAGE_WIDTH + 5 +
insets.right);
double yScale = size.height /
(double)(insets.top + 5 + AVRSystem.IMAGE_HEIGHT + 5 +
insets.bottom);
double scale = Math.min(xScale, yScale);
 
int imageWidth = (int)(AVRSystem.IMAGE_WIDTH * scale);
int imageHeight = (int)(AVRSystem.IMAGE_HEIGHT * scale);
 
// it is possible for the width or height to be 0 when
// the window is resized. If this occurs, don't try
// to paint anything. just return
if(imageWidth <= 0 || imageHeight <= 0) {
return;
}
 
Image bufferedImage = createImage(imageWidth, imageHeight);
 
Graphics2D bufferGraphics = (Graphics2D)bufferedImage.getGraphics();
 
bufferGraphics.setColor(Color.WHITE);
bufferGraphics.fillRect(0, 0, imageWidth, imageHeight);
 
bufferGraphics.scale(scale, scale);
 
for(int i = 0; (blobs != null) && (i < blobs.length); i++) {
ColorBlob blob = blobs[i];
if(blob != null) {
bufferGraphics.setColor(AVRSystem.DEVICE.getMapColors()[blob.
colorIndex]);
bufferGraphics.fillRect(blob.center.x - 2, blob.center.y - 2, 4, 4);
bufferGraphics.setColor(Color.BLACK);
bufferGraphics.drawRect(blob.bounds.x, blob.bounds.y,
blob.bounds.width, blob.bounds.height);
}
}
 
g.drawImage(bufferedImage,
(size.width - imageWidth) / 2, (size.height - imageHeight) / 2,
imageWidth, imageHeight, this);
 
 
}
 
public void setTrackingData(ByteBuffer data) {
blobs = new ColorBlob[data.get() & 0xFF];
 
for(int i = 0; i < blobs.length; i++) {
blobs[i] = new ColorBlob(data);
}
 
repaint();
 
if(sendCameraData) {
data.position(0);
try {
AVRSystem.DEVICE.sendCameraData(data);
} catch(IOException ioe) {
ioe.printStackTrace(System.err);
AVRSystem.LOG.warning(ioe.getMessage());
}
}
 
}
 
private final class TrackingHandler extends DataAdapter {
 
public void trackingData(ByteBuffer data) {
setTrackingData(data);
 
if(recording) {
data.reset();
try {
outChannel.write(data);
} catch(IOException ioe) {
AVRSystem.LOG.warning("TRACKING: " + ioe.getMessage());
}
}
 
}
 
}
 
private final static class ColorBlob {
 
public final int colorIndex;
public final Point center;
public final Rectangle bounds;
 
public ColorBlob(ByteBuffer data) {
colorIndex = data.get();
 
int x = data.get() & 0xFF;
int y = data.get() & 0xFF;
int width = (data.get() & 0xFF) - x;
int height = (data.get() & 0xFF) - y;
bounds = new Rectangle(x, y, width, height);
 
center = new Point(x + (width / 2), y + (height / 2));
}
 
public String toString() {
return "ColorBlob: " + colorIndex + " (" + center.x + ", " + center.y + ") " +
" [" + bounds.x + ", " + bounds.y + ", " + bounds.width + ", " + bounds.height + "]";
}
 
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/ProxyAction.java
0,0 → 1,296
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import java.awt.event.*;
import java.lang.reflect.*;
import javax.swing.*;
 
/**
* Utility class for defining Actions that can be attached as an ActionListener.
* It also provides many convience methods for setting the Icon, Keystroke,
* and Mnemonic.
*/
public class ProxyAction extends AbstractAction {
 
/**
* The object to which the action is to be invoked upon.
*/
private Object target;
 
/**
* The method of the target to call when the action is invoked.
*/
private Method method;
 
/**
* Create a Proxy Action.
* @param target The object to which the action is to be invoked upon.
* @param methodName The method to call.
* @param icon The icon to display on the control this action is attached to.
* in the object "target".
*/
public ProxyAction(Object target,
String methodName,
Icon icon) {
this(target, methodName, null, icon);
}
 
/**
* Create a Proxy Action.
* @param target The object to which the action is to be invoked upon.
* @param methodName The method to call.
* @param name The text string to display on the control this action is
* attached to.
* in the object "target".
*/
public ProxyAction(Object target,
String methodName,
String name) {
this(target, methodName, name, null);
}
 
/**
* Create a Proxy Action.
* @param target The object to which the action is to be invoked upon.
* @param methodName The method to call.
* @param name The text string to display on the control this action is
* attached to.
* @param key The mnemonic key used to invoke this action. (Alt + key)
* in the object "target".
*/
public ProxyAction(Object target,
String methodName,
String name,
int key) {
this(target, methodName, name, key, null);
}
 
/**
* Create a Proxy Action.
* @param target The object to which the action is to be invoked upon.
* @param methodName The method to call.
* @param name The text string to display on the control this action is
* attached to.
* @param icon The icon to display on the control this action is attached to.
* in the object "target".
*/
public ProxyAction(Object target,
String methodName,
String name,
Icon icon) {
this(target, methodName, false, name, -1, icon);
}
 
/**
* Create a Proxy Action.
* @param target The object to which the action is to be invoked upon.
* @param methodName The method to call.
* @param name The text string to display on the control this action is
* attached to.
* @param key The mnemonic key used to invoke this action. (Alt + key)
* @param icon The icon to display on the control this action is attached to.
* in the object "target".
*/
public ProxyAction(Object target,
String methodName,
String name,
int key,
Icon icon) {
this(target, methodName, false, name, key, icon);
}
 
/**
* Create a Proxy Action.
* @param target The object to which the action is to be invoked upon.
* @param methodName The method to call.
* @param passEvent True if the ActionEvent is to be passed to the method
* defined by "methodName"
* @param name The text string to display on the control this action is
* attached to.
*/
public ProxyAction(Object target,
String methodName,
boolean passEvent,
String name) {
this(target, methodName, passEvent, name, -1, null);
}
 
/**
* Create a Proxy Action.
* @param target The object to which the action is to be invoked upon.
* @param methodName The method to call.
* @param passEvent True if the ActionEvent is to be passed to the method
* defined by "methodName"
* @param name The text string to display on the control this action is
* attached to.
* @param key The mnemonic key used to invoke this action. (Alt + key)
* in the object "target".
*/
public ProxyAction(Object target,
String methodName,
boolean passEvent,
String name,
int key) {
this(target, methodName, passEvent, name, key, null);
}
 
/**
* Create a Proxy Action.
* @param target The object to which the action is to be invoked upon.
* @param methodName The method to call.
* @param passEvent True if the ActionEvent is to be passed to the method
* defined by "methodName"
* @param name The text string to display on the control this action is
* attached to.
* @param key The mnemonic key used to invoke this action. (Alt + key)
* @param icon The icon to display on the control this action is attached to.
* in the object "target".
*/
public ProxyAction(Object target,
String methodName,
boolean passEvent,
String name,
int key,
Icon icon) {
super(name);
// this(target,
// target.getClass().getMethod(methodName,
// (passEvent) ? new Class[] { ActionEvent.class }
// : null),
// name,
// key,
// icon);
 
Method method = null;
 
try {
method = target.getClass().getMethod(methodName,
(passEvent) ? new Class[] {ActionEvent.class}
: null);
} catch(NoSuchMethodException ex) {
throw new NoSuchMethodError(ex.getMessage());
}
 
if(method.getParameterTypes().length > 1) {
throw new IllegalArgumentException(
"Method can have only one ActionEvent argument.");
 
} else if(method.getParameterTypes().length == 1) {
if(!method.getParameterTypes()[0].getName().equals(
ActionEvent.class.getName())) {
 
throw new IllegalArgumentException(
method.getParameterTypes()[0].getName() + " != " +
ActionEvent.class.getName() +
" Parameter must be an ActionEvent.");
}
}
 
this.target = target;
this.method = method;
 
if(key != -1) {
setMnemonic(key);
}
 
if(icon != null) {
setIcon(icon);
}
 
}
 
/**
* Set the mnemonic key to be the given key.
* @param key The key identifier used to set the Mnemonic to
* @see KeyEvent
*/
public void setMnemonic(int key) {
putValue(MNEMONIC_KEY, new Integer(key));
}
 
/**
* Set the Shortcut KeyStroke to attach to this action.
* @param keyCode The key identifier to use.
* @param modifiers Any modifiers that need to be used along with the key.
* @see KeyStroke
* @see KeyEvent
*/
public void setKeyStroke(int keyCode, int modifiers) {
setKeyStroke(KeyStroke.getKeyStroke(keyCode, modifiers));
}
 
/**
* Set the Shortcut KeyStroke to attach to this action.
* @param keystroke The KeyStroke to use
*/
public void setKeyStroke(KeyStroke keystroke) {
putValue(ACCELERATOR_KEY, keystroke);
}
 
/**
* Set the Icon of this Action
* @param icon The icon to use.
*/
public void setIcon(Icon icon) {
putValue(SMALL_ICON, icon);
 
}
 
/**
* Sets the Tool Tip Text for this Action
*
* @param text String
*/
public void setToolTipText(String text) {
putValue(SHORT_DESCRIPTION, text);
}
 
/**
* This method is called when an Action Event occurs on the control this
* action is attached to.
* @param ae The ActionEvent created.
*/
public void actionPerformed(ActionEvent ae) {
 
try {
if(method.getParameterTypes().length == 0) {
// invoke the given method on the given target with no parameters
method.invoke(target, null);
} else {
// invoke the given method on the given target with the ActionEvent
// as a parameter
method.invoke(target, new Object[] {ae});
}
} catch(Exception e) {
// should never happen
e.printStackTrace(System.err);
}
 
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/WrapSpinnerNumberModel.java
0,0 → 1,89
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing;
 
import javax.swing.SpinnerNumberModel;
 
public class WrapSpinnerNumberModel extends SpinnerNumberModel {
 
public WrapSpinnerNumberModel(Number value, Comparable minimum,
Comparable maximum, Number stepSize) {
super(value, minimum, maximum, stepSize);
}
 
public WrapSpinnerNumberModel(int value, int minimum,
int maximum, int stepSize) {
super(new Integer(value), new Integer(minimum),
new Integer(maximum), new Integer(stepSize));
}
 
public Object getNextValue() {
return increment(+1);
}
 
public Object getPreviousValue() {
return increment(-1);
}
 
private Number increment(int dir) {
Number newValue;
if ((getValue() instanceof Float) || (getValue() instanceof Double)) {
double v = ((Number)getValue()).doubleValue() +
(((Number)getStepSize()).doubleValue() * (double)dir);
if (getValue() instanceof Double) {
newValue = new Double(v);
} else {
newValue = new Float(v);
}
} else {
long v = ((Number)getValue()).longValue() +
(((Number)getStepSize()).longValue() * (long)dir);
 
if (getValue() instanceof Long) {
newValue = new Long(v);
} else if (getValue() instanceof Integer) {
newValue = new Integer((int)v);
} else if (getValue() instanceof Short) {
newValue = new Short((short)v);
} else {
newValue = new Byte((byte)v);
}
}
 
if ((getMaximum() != null) && (((Comparable)getMaximum()).compareTo(newValue) < 0)) {
return (Number)getMinimum();
}
 
if ((getMinimum() != null) && (((Comparable)getMinimum()).compareTo(newValue) > 0)) {
return (Number)getMaximum();
}
 
return newValue;
}
 
}
 
/programy/Java/AVRcamVIEW/src/avr/swing/filechooser/LogFileFilter.java
0,0 → 1,62
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing.filechooser;
 
import javax.swing.filechooser.*;
import java.io.*;
 
 
public class LogFileFilter extends javax.swing.filechooser.FileFilter {
 
private String description;
private String extension;
 
public LogFileFilter(String description, String extension) {
this.description = description;
this.extension = extension;
}
 
public boolean accept(File file) {
return file.isDirectory() || file.getName().endsWith(extension);
}
 
public String getDescription() {
return description;
}
 
public String getExtension() {
return extension;
}
 
public boolean equals(Object obj) {
if(obj == null) return false;
 
return description.equals(((LogFileFilter)obj).description) &&
extension.equals(((LogFileFilter)obj).extension);
}
 
}
/programy/Java/AVRcamVIEW/src/avr/swing/table/LogTableCellRenderer.java
0,0 → 1,126
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing.table;
 
import java.awt.*;
import java.text.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
 
public class LogTableCellRenderer extends DefaultTableCellRenderer {
 
private Color defaultBackground;
private Color defaultForeground;
 
private static final DateFormat DATE_FORMAT;
 
static {
 
DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
 
}
 
public LogTableCellRenderer() {
super();
defaultBackground = getBackground();
defaultForeground = getForeground();
}
 
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
 
String text = null;
 
switch(column) {
case 0:
text = DATE_FORMAT.format(new Date(((LogRecord)value).getMillis()));
break;
case 1:
text = ((LogRecord)value).getLevel().toString();
break;
case 2:
LogRecord record = (LogRecord)value;
 
if(record.getMessage() == null) {
text = "No Message...";
} else {
text = record.getMessage();
}
 
if(!(text.startsWith("Sending") || text.startsWith("Received"))) {
StringBuffer buffer = new StringBuffer(text);
 
buffer.append(" ");
if(record.getSourceClassName() != null) {
buffer.append(record.getSourceClassName());
}
 
if(record.getSourceMethodName() != null) {
buffer.append(":");
buffer.append(record.getSourceMethodName());
}
buffer.append(" ");
 
text = buffer.toString();
}
 
break;
}
 
super.getTableCellRendererComponent(table, text, isSelected, hasFocus, row, column);
 
if(!isSelected) {
if(((LogRecord)value).getLevel().equals(Level.SEVERE)) {
setBackground(Color.RED.darker());
setForeground(Color.WHITE);
} else if(((LogRecord)value).getLevel().equals(Level.WARNING)) {
setBackground(Color.ORANGE);
setForeground(Color.BLACK);
} else if(((LogRecord)value).getLevel().equals(Level.INFO)) {
setBackground(Color.YELLOW);
setForeground(Color.BLACK);
} else if(((LogRecord)value).getLevel().equals(Level.CONFIG)) {
setBackground(Color.CYAN);
setForeground(Color.BLACK);
} else {
setBackground(defaultBackground);
setForeground(defaultForeground);
}
}
 
if(column != 2) {
setHorizontalAlignment(JLabel.CENTER);
} else {
setHorizontalAlignment(JLabel.LEFT);
}
 
return this;
 
}
}
/programy/Java/AVRcamVIEW/src/avr/swing/table/LogTableModel.java
0,0 → 1,131
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.swing.table;
 
import java.util.*;
import java.util.logging.*;
import javax.swing.table.*;
 
public class LogTableModel extends AbstractTableModel {
 
public static final String[] COLUMN_NAMES = {
"Time Stamp",
"Level",
"Message"
};
 
private List allRecords;
private List filteredRecords;
 
private Level level;
private boolean selectedLabel;
 
public LogTableModel(Level filterLevel) {
this(filterLevel, false);
}
 
public LogTableModel(Level filterLevel, boolean selectedLabel) {
super();
allRecords = new ArrayList(10);
filteredRecords = new ArrayList(10);
this.level = filterLevel;
}
 
public void setFilter(Level level) {
this.level = level;
filteredRecords = new ArrayList(allRecords.size());
Iterator i = allRecords.iterator();
LogRecord record = null;
while(i.hasNext()) {
record = (LogRecord)i.next();
if(selectedLabel) {
if(level.intValue() == record.getLevel().intValue()) {
filteredRecords.add(record);
}
} else {
if(level.intValue() <= record.getLevel().intValue()) {
filteredRecords.add(record);
}
}
}
fireTableDataChanged();
}
 
public void setOnlyShowSelectedLevel(boolean selectedLabel) {
this.selectedLabel = selectedLabel;
setFilter(level);
}
 
public void addRecord(LogRecord record) {
allRecords.add(record);
if(selectedLabel) {
if(level.intValue() == record.getLevel().intValue()) {
filteredRecords.add(record);
}
} else {
if(level.intValue() <= record.getLevel().intValue()) {
filteredRecords.add(record);
}
}
this.fireTableRowsInserted(filteredRecords.size() - 1, filteredRecords.size() - 1);
}
 
public void clear() {
allRecords.clear();
filteredRecords.clear();
fireTableDataChanged();
}
 
public int getRowCount() {
return filteredRecords.size();
}
 
public int getColumnCount() {
return COLUMN_NAMES.length;
}
 
public String getColumnName(int col) {
return COLUMN_NAMES[col];
}
 
public Class getColumnClass(int col) {
return String.class;
}
 
public Object getValueAt(int rowIndex, int columnIndex) {
return filteredRecords.get(rowIndex);
}
 
public LogRecord getRecord(int row) {
return (LogRecord)allRecords.get(row);
}
 
public int getRecordCount() {
return allRecords.size();
}
 
}
/programy/Java/AVRcamVIEW/src/avr/util/LogHandler.java
0,0 → 1,90
/*
AVRcamVIEW: A PC application to test out the functionallity of the
AVRcam real-time image processing engine.
Copyright (C) 2004 Brent A. Taylor
 
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
For more information on the AVRcamVIEW, please contact:
 
taylorba@comcast.net
 
or go to www.jrobot.net for more details regarding the system.
*/
 
package avr.util;
 
import java.util.logging.*;
 
import avr.swing.table.*;
 
/***********************************************************************
* Defines a Handler for the Log to publish the log records to a
* Table Model.
*/
public class LogHandler extends Handler {
 
/**
* The Table Model to publish the log records to.
*/
private LogTableModel model;
 
/**
* Create a Log Handler that will publish the log records to a
* Table Model
* @param model The table model to publish the log records to.
* @param level The initial log level this handler will log.
*/
public LogHandler(LogTableModel model, Level level) {
super();
 
setLevel(level);
 
this.model = model;
}
 
/**
* Publish the given record to the table model.
* @param record The log record to publish.
*/
public synchronized void publish(LogRecord record) {
 
if(!isLoggable(record)) {
return;
}
 
// pass the record to the table.
model.addRecord(record);
 
}
 
/**
* Flush the contents of this Handler. Nothing is done here since
* the record is automatically displayed in the table.
*/
public void flush() {
// nothing needs to be done here
}
 
/**
* Releases any resources taken up by this Handler. Nothing is done here
* since there are no resources allocated.
* @throws java.lang.SecurityException
*/
public void close() throws java.lang.SecurityException {
// nothing needs to be done here
}
 
}