// Copyright 2005, Danger, Inc.  All Rights Reserved.
// This file is subject to the Danger, Inc. Sample Code License,
// which is provided in the file SAMPLE_CODE_LICENSE.
// Copies are also available from http://developer.danger.com/

package com.danger.text;

import danger.ui.*;
import danger.util.*;
import danger.text.span.*;

/**
 * This window has an EditText with a custom drawing function
 * that gives it a greenbar look and a custom left margin that
 * numbers the lines.
 */
public class
Greenbar
extends DemoWindow
{
	public
	Greenbar()
	{
		EditText et = new GreenbarTextBox();

		et.setSize(getWidth(), getHeight());
		et.setBorderShowsScrolling(true);
		et.setText(getApplication().getString(Resources.ID_HOLMES));
		et.show();
		addChild(et);
		setFocusedChild(et);

		setTitle(getApplication().getString(Resources.ID_DEMO_GREENBAR));
	}

	/**
	 * This text box has a custom drawing function that draws a box
	 * behind every other line of the text and custom left margin
	 * that numbers the lines.  (The line numbering could be done
	 * as part of the drawing function too, but it would require
	 * also overriding other methods to narrow the wrap area to make
	 * room for the numbers.)
	 */
	private static class
	GreenbarTextBox
	extends EditText
	{
		public
		GreenbarTextBox()
		{
			super();
			setSpan(new LineNumberSpan(), 0, length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
		}

		protected int
		drawText(Pen p, int x, int wid, int top, int baseline, int bottom, CharSequence text, int parStart, int lastLineEnd, int lineStart, int lineEnd, int nextLineStart, Object[] paragraphSpans, int alignment, int tabIncrement, int flags, int paragraphDistance)
		{
			if (getLineForOffset(lineStart) % 2 == 0)
			{
				p.push();
				p.setColor(Color.CYAN);
				p.fillRect(x, top, x + wid, bottom);
				p.pop();
			}

			return super.drawText(p, x, wid, top, baseline, bottom, text, parStart, lastLineEnd, lineStart, lineEnd, nextLineStart, paragraphSpans, alignment, tabIncrement, flags, paragraphDistance);
		}

		/**
		 * This left margin dynamically displays the line number of
		 * each line next to which it is drawn.
		 */
		private class
		LineNumberSpan
		implements LeftMarginSpan
		{
			public int
			modifyLeftMargin(int margin, Object[] spans, Font f, CharSequence text, int parStart, int lineStart, int paragraphDistance)
			{
				return margin + MARGIN;
			}

			public int
			drawLeftMargin(Pen p, int x, int top, int baseline, int bottom, Object[] spans, CharSequence text, int parStart, int lineStart, int paragraphDistance, Object[] characterSpans)
			{
				CharacterSpan.Set.drawBlank(p, x, MARGIN, top, baseline, bottom, characterSpans);

				p.push();
				p.setColor(Color.BLUE);

				String s = String.valueOf(getLineForOffset(lineStart) + 1);
				Font f = Font.findFont("Twig8");

				p.setFont(f);
				p.drawText(x + MARGIN - f.getWidth(s) - 5, baseline, s);
				p.pop();

				return MARGIN;
			}

		}

		private static int MARGIN = 30;
	}
}
