view test/editortest/REPTextImpl.java @ 414:784a4d67e6a5

(no commit message)
author one
date Tue, 09 Dec 2008 15:44:28 +0900
parents
children b7f42fc75a36
line wrap: on
line source

package test.editortest;

import java.util.LinkedList;
import java.util.List;

import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;

import rep.REP;
import rep.REPCommand;

public class REPTextImpl implements REPText {
	
	private JTextArea textArea;
	private String BR = System.getProperty("line.separator");

	public REPTextImpl(JTextArea area){
		this.textArea = area;
	}

	public String delete(int lineno, String text) {
		increaseLine(lineno);
		
		String deleted = "";
		try {
			int start = textArea.getLineStartOffset(lineno);
			int end = textArea.getLineEndOffset(lineno);
			int length = end - start;
			deleted = textArea.getText(start, length);
			textArea.replaceRange("", start, end);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		return deleted;
	}

	public void insert(int lineno, String text) {
		increaseLine(lineno);
		
		String text2 = text + BR;
		try {
			int offset = textArea.getLineStartOffset(lineno);
			textArea.insert(text2, offset);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}

	private void increaseLine(int lineno) {
		while(true){
			int lines = textArea.getLineCount();
			Logger.print(lineno + " : " + lines);
			if(lineno >= lines){
				textArea.append(BR);
			}else{
				break;
			}
		}
	}
	
	public void edit(REPCommand command){
		int lineno = command.lineno;
		String text = command.string;
		if(command.cmd == REP.REPCMD_INSERT){
			insert(lineno, text);
		}else if(command.cmd == REP.REPCMD_DELETE){
			delete(lineno, text);
		}else{
			Logger.print(command);
		}
	}

	public List<String> list() {
		int count = textArea.getLineCount();
		LinkedList<String> list = new LinkedList<String>();
		for(int i = 0; i < count; i++){
			try {
				int start = textArea.getLineStartOffset(i);
				int end = textArea.getLineEndOffset(i);
				String text = textArea.getText(start, end - start);
				list.add(text);
			} catch (BadLocationException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

}