/*	Copyright (C) 2000, Geert Vernaeve	*/
package gve.calc.formula;

import java.awt.*;
import gve.calc.formula.*;
import gve.calc.formula.Part;

public class RewriteRuleView extends TabularView {
	public RewriteRuleView(RewriteRule model,FormulaView view) {
		super(model,view);
		TabularLayout layout = (TabularLayout)getLayout();
		layout.setHgap(2);
	}

	public void paint(Graphics g) {
		super.paint(g);
		Dimension siz = getSize();
		FormulaView view = FormulaView.get(this);
		RewriteRule model = (RewriteRule)getModel();
		if (model.getHeight() > 1) {	// Lines beside match identifier
			Component match = view.getView(model.rules[1]);
			int y = match.getLocation().y + match.getSize().height/2;
			int w = match.getSize().width;
			g.drawLine(0,y,(siz.width-w)/2-2,y);
			g.drawLine((siz.width+w)/2+2,y,siz.width,y);
		}
		g.drawRect(0,0,siz.width-1,siz.height-1);
	}

	public boolean keydn(int key) {
		FormulaView view = FormulaView.get(this);
		RewriteRule model = (RewriteRule)getModel();
		if (key == Key_BS) {
			Point p = model.whichOffspring(view.getCursorPart());
			if (p == null) return super.keydn(key);
			if (p.y>0 && Part.isEmpty(model.rules[p.y])) {
				model.removeRow(p.y);
				view.setCursorPart(model.rules[p.y-1]);
				return true;
			}
		}
		if (key != '\n') return super.keydn(key);
		int child;
		{	Point p = model.whichOffspring(view.getCursorPart());
			if (p == null) return super.keydn(key);
			child = p.y;
		}
		if (child == model.rules.length) return super.keydn(key);
		model.insertRow(child+1);
		view.setCursorPart(model.rules[child+1]);
		return true;	
	}
}