import ij.*;
import ij.gui.*;
import ij.measure.Calibration;
import ij.plugin.filter.PlugInFilter;
import ij.process.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

/** Bob Dougherty 6/1/2002.
	This plugin makes a circular ROI by dragging the cursor across a diameter.
	This capability was requested by Mark Hayworth.
	The plugin uses the blank spot in the toolbar between the text and zoom tools.
	This beta release has some known limitations:
	1. This is a PluginFilter.  It only works on the image that was in front when the plugin was run.
	2. The ability to drag the ROI using the Circle Roi tool is lost if any other tool is selected.
	   Select the Oval Roi tool if dragging is necessary in this case.
	3. Threads are used to orchestrate the work.  This is effective, but it would be more
	   efficient to use events.  A future version may use events.
	4. The tool in the toolbar (between the text and zoom tools, as noted) looks blank.
	Version 0 6/1/2002.
	Version 1 7/14/2002 Improved shutDown.  */

/*	License:
	Copyright (c) 2002, 2005, OptiNav, Inc.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions
	are met:

		Redistributions of source code must retain the above copyright
	notice, this list of conditions and the following disclaimer.
		Redistributions in binary form must reproduce the above copyright
	notice, this list of conditions and the following disclaimer in the
	documentation and/or other materials provided with the distribution.
		Neither the name of OptiNav, Inc. nor the names of its contributors
	may be used to endorse or promote products derived from this software
	without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
	A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
	CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
	PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
	LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
	public class Circle_Roi implements PlugInFilter {
	ImagePlus imp;

	public int setup(String arg, ImagePlus imp) {
		this.imp = imp;
		return DOES_ALL;
	}

	public void run(ImageProcessor ip) {
		final ImageCanvas ic = imp.getWindow().getCanvas();
		final CircleRoi cr = new CircleRoi(imp,ic);
		imp.updateAndDraw();
	}
}


class CircleRoi extends ImageCanvas implements MouseListener, MouseMotionListener, Runnable {
	ImageCanvas ic;
	Graphics g;
	Toolbar tb;
	int xStart, yStart, xStop, yStop;
	int xStartMove,yStartMove;
	boolean done = false;
	int xC,yC,width,height;
	int xOld = 0;
	int yOld = 0;
	int widthOld = 0;
	int heightOld = 0;
	int napTime = 100;
	boolean circleOn = false;
	boolean started = false;
	boolean moving = false;
	protected Thread thread;
	protected long lastUseTime;

	public CircleRoi(ImagePlus imp, ImageCanvas ic) {
		super(imp);
		this.imp = imp;
		this.ic = ic;
		g = ic.getGraphics();
		tb = Toolbar.getInstance();
		tb.addTool("Circle (limited to "+imp.getShortTitle()+")");
		tb.setTool(Toolbar.SPARE1);
		thread = new Thread(this, "CircleRoi");
		thread.start();
		turnCircleOn();
	}

	public void run() {
		while (!done) {
			try {Thread.sleep(napTime);}
			catch(InterruptedException e) {
				shutDown();
			}
			if (imp == null){
				shutDown();
				break;
			}
			if (ic == null){
				shutDown();
				break;
			} else if (!ic.isValid()){
				shutDown();
				break;
			}
			if (g == null){
				shutDown();
				break;
			}
			if (started&&circleOn){
				updateRoi();
			} else {
				int toolID = tb.getToolId();
				if((toolID == Toolbar.SPARE1)&&(!circleOn)) turnCircleOn();
			}
			if((System.currentTimeMillis()-lastUseTime) < 1000){
				napTime = 10;
			} else if (circleOn){
				napTime = 100;
			} else {
				napTime = 200;
			}
		}
	}

	private void updateRoi(){
		if((xC!=xOld)||(yC!=yOld)||(width!=widthOld)||(height!=heightOld)){
			xOld = xC;
			yOld = yC;
			widthOld = width;
			heightOld = height;
			imp.killRoi();
			imp.setRoi(new OvalRoi(xC, yC,width,height,imp));
			lastUseTime = System.currentTimeMillis();
		}
	}

/* Exit.  This does not quit work right yet.  The thread continues to hang around. */
	private void shutDown(){
		if(circleOn){
			if(ic != null){
				ic.removeMouseListener(this);
				ic.removeMouseMotionListener(this);
				ic.addMouseMotionListener(ic);
				ic.addMouseListener(ic);
				circleOn = false;
			}
		}
		tb.addTool("Unassigned");
		this.setEnabled(false);
		circleOn = false;
		done = true;
		if(imp!=null)imp.updateAndDraw();
		this.setVisible(false);
		this.invalidate();
	}

	private void turnCircleOff (){
		if(circleOn){
			ic.removeMouseListener(this);
			ic.removeMouseMotionListener(this);
			ic.addMouseListener(ic);
			ic.addMouseMotionListener(ic);
			circleOn = false;
			this.setEnabled(false);
			napTime = 100;
			imp.updateAndDraw();
		}
	}

	private void turnCircleOn(){
		if(!circleOn){
			ic.removeMouseListener(ic);
			ic.removeMouseMotionListener(ic);
			ic.addMouseListener(this);
			ic.addMouseMotionListener(this);
			circleOn = true;
			this.setEnabled(true);
			napTime = 10;
			imp.updateAndDraw();
			lastUseTime = System.currentTimeMillis();
			height = -1;
			width = -1;
		}
	}

	public void mousePressed(MouseEvent e) {
		int xP = ic.offScreenX(e.getX());
		int yP = ic.offScreenY(e.getY());
		if(tb.getToolId() != Toolbar.SPARE1){
			turnCircleOff();
			return;
		}
		Roi roi = imp.getRoi();
		if ((roi!=null)&&roi.contains(xP,yP)&&(height >= 0)&&(width >= 0)){
			moving = true;
			xStartMove = xP;
			yStartMove = yP;
		} else {
			xStart = xP;
			yStart = yP;
			moving = false;
			imp.killRoi();
		}
	}


	public void updateCircle(){
		double dSq = (xStop - xStart)*(xStop - xStart) + (yStop - yStart)*(yStop - yStart);
		width = (int)Math.round(Math.sqrt(dSq));
		height = width;
		xC = (xStart + xStop - width)/2;
		yC = (yStart + yStop - height)/2;
	}

	public void mouseDragged(MouseEvent e) {
		if(moving){
			int xD = ic.offScreenX(e.getX());
			int yD = ic.offScreenY(e.getY());
			int dx = xD - xStartMove;
			int dy = yD - yStartMove;
			xStart += dx;
			xStop += dx;
			yStart += dy;
			yStop += dy;
			xStartMove = xD;
			yStartMove = yD;
			updateCircle();
			started = true;
		} else {
			xStop = ic.offScreenX(e.getX());
			yStop = ic.offScreenY(e.getY());
			updateCircle();
			started = true;
		}
	}

	public void mouseExited(MouseEvent e) {
		int toolID = tb.getToolId();
		if(toolID != Toolbar.SPARE1) turnCircleOff();//Cannot happen?
		ic.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
	}

	public void mouseEntered(MouseEvent e) {
		int toolID = tb.getToolId();
		if(toolID != Toolbar.SPARE1){
			turnCircleOff();
		} else {
			ic.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
		}
	}

	public void mouseReleased(MouseEvent e) {}
	public void mouseMoved(MouseEvent e) {}
	public void mouseClicked(MouseEvent e) {}

}
