/*
   Tamot --- Task Modelling Editor
   Copyright (C) 2000 Commonwealth Scientific and Industrial Research Organisation
   (CSIRO), Australia. All rights reserved. 

   The Software, owned by CSIRO Australia, has been developed by the CSIRO 
   Intelligent Interactive Technology group. 
   For more information, please see http://www.cmis.csiro.au/iit/.

   The Software is a beta-test version for internal research and evaluation purposes 
   by the Licensee. The Software is still at a development stage. 
   It has not undergone complete testing and may have inherent errors,
   bugs or deficiencies that can affect the operation of the Software. 

   We encourage your feedback and suggestions. Any bugs / suggestions found please email to
   Shijian.Lu@cmis.csiro.au and Thomas.Lo@cmis.csiro.au. 

   After you have signed the Beta-Test Software License Agreement with the CSIRO,
   CSIRO grants you a non-exclusive, non-transferable license to use it only for your 
   personal, non-commercial and lawful end use. Implied licenses are negated. 

   Warranty Disclaimer : 

   CSIRO supplies the Software on an "as is" basis and makes no warranties that use of
   the Software by the Licensee will not infringe any third party’s 
   Intellectual Property Rights nor that the Software will be of merchantable quality,
   or suitable for a particular purpose. CSIRO excludes all terms, conditions and
   warranties implied by custom, the general law or statute in relation to the
   Software.
*/

package taskModellingTool;

import java.awt.*;
import java.awt.event.*;

import java.util.*;
import java.io.*;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.rtf.*;
import javax.swing.text.html.*;
import javax.swing.event.*;
import javax.swing.undo.*;

import java.awt.datatransfer.*;
import java.awt.dnd.*;

//Thomas
import java.net.URL;
import java.lang.ClassLoader;

public class RTFPane extends JPanel implements ClipboardOwner, KeyListener,ActionListener{
   	JTextPane textPane;
    JScrollPane scrollPane;
    JToolBar toolBar;
    static DefaultStyledDocument doc;
    static RTFEditorKit kit;
    
    TreeMap _textPane = new TreeMap(), 
    	_kit = new TreeMap(), 
    	_doc = new TreeMap(); 
    static TreeMap	_toolTip = new TreeMap();
    
    static final String TIP1="Enter ";
    static final String TIP2=" of the selected component";
    static final String TIP="Enter the description of the selected component";
    static{
    	//create tool tips
    	String temp, catName;
    	for (int i = 0; i<RTFManager.DBNAMES.length; i++){
    		catName=RTFManager.DBNAMES[i];
			temp=TIP1 + catName + TIP2;
			_toolTip.put(catName, temp);
		}

    }

    //Thomas
    //static final String RENAMING_FILE="cfg"+File.separator+"editor.cfg";
    //static final String USER="cfg"+File.separator+"editor_user.cfg";
    //static final String FOLDER="save";   
    static final String RENAMING_FILE=ClassLoader.getSystemResource("cfg"+File.separator+"editor.cfg").getFile();
    static final String USER=ClassLoader.getSystemResource("cfg"+File.separator+"editor_user.cfg").getFile();
    static final String FOLDER=ClassLoader.getSystemResource("save").getFile();
    
    protected static File currentDir;
    
    static ObjectInputStream userIn;
    static ObjectOutputStream userOut;
    static RTFPane editorFrame;
    
    //static MainFrame editorFrame=MainFrame.mainFrame;
    
    Hashtable actions,actionRenamingTable,iconTable;

    Action[] nactionsArray={new NewDocumentAction(),new OpenRTFAction(),new SaveRTFAction(),
    	new CustomCut(), new CustomPaste(),new CustomStyle(),new Test(),new InsertImage()};
            
    java.awt.datatransfer.Clipboard clipboard = getToolkit().getSystemClipboard();
    

    //undo helpers
    protected UndoAction undoAction;
    protected RedoAction redoAction;
    protected UndoManager undo = new UndoManager();
    
    protected String name=null;
    
    protected static JToggleButton bBold,bItalic,bUnderline;
    protected static JComboBox bSize;
    
    private static int nbImages=0;
    
    //private Style regular;
    
    

    public RTFPane() {
        super();
        editorFrame=this;
 
        
        try {
    	    userIn=new ObjectInputStream(new FileInputStream(USER));
    	    currentDir=(File)userIn.readObject();
    	    userIn.close();
    	} catch (Exception ex){}
    	
        //Create the text pane and configure it.
        textPane = new JTextPane();
        textPane.setToolTipText(TIP);
        kit=new RTFEditorKit();
        textPane.setEditorKit(kit);
        doc=(DefaultStyledDocument)textPane.getStyledDocument();
        
        textPane.setDropTarget(new DropTarget(textPane,new TextPaneTarget(textPane)));
        
        //new TextPaneSource(textPane);
        
        textPane.setCaretPosition(0);
        textPane.setMargin(new Insets(5,5,5,5));
        textPane.addKeyListener(this);
        
        
        scrollPane = new JScrollPane(textPane);

        toolBar=new JToolBar();
	
	
        //Add the components to the frame. 
        setLayout(new BorderLayout());
        //add(scrollPane, BorderLayout.CENTER);
        add(getTabPanel(), BorderLayout.CENTER);
        add(toolBar, BorderLayout.NORTH);



        configure(RENAMING_FILE);

        //Start watching for undoable edits and caret changes.
        ////3-10-2001 doc.addUndoableEditListener(new MyUndoableEditListener());
        
        //listActions();
        
    }
    
        
    public void lostOwnership(java.awt.datatransfer.Clipboard clipboard, Transferable contents) {
       System.out.println("Clipboard contents replaced");
    }



    //This one listens for edits that can be undone.
    protected class MyUndoableEditListener implements UndoableEditListener {
        public void undoableEditHappened(UndoableEditEvent e) {
            //Remember the edit and update the menus.
            undo.addEdit(e.getEdit());
            undoAction.updateUndoState();
            redoAction.updateRedoState();
        }
    }


    protected void listActions() {
        System.out.println("#############################");
        System.out.println("#Possible choices for actions");
        for (Iterator i=actions.keySet().iterator();i.hasNext();){
            System.out.println("#"+i.next());
        }
        System.out.println("#############################");
            
    }

    //associate the actions with a name
    private void createActionTable(JTextComponent textComponent) {
        actions = new Hashtable();
        
        Object obj;
        Action a;
        
        //this is for java actions
        Action[] actionsArray = (new StyledEditorKit()).getActions();        
        for (int i=0; i<actionsArray.length; i++) {
            a=actionsArray[i];
            obj=a.getValue(Action.NAME);
            //System.out.println("RTF actions: "+ a.getValue(Action.NAME));
            if (actionRenamingTable.containsKey(obj)){
            	a.putValue(Action.NAME,actionRenamingTable.get(obj));
            }
            if (iconTable.containsKey(obj)){
            	a.putValue(Action.SMALL_ICON,iconTable.get(obj));
            }
            actions.put(obj,a);
        }
        
        //this is added actions
        
        //undo and redo are special
        String s="Undo";
        Icon icon;
        if (actionRenamingTable.containsKey("Undo")){
            s=(String)actionRenamingTable.get("Undo");
        }
        if (iconTable.containsKey("Undo")){
            icon=(ImageIcon)iconTable.get("Undo");
            undoAction=new UndoAction(s,icon);
            undoAction.putValue(Action.SMALL_ICON,icon);
        } else undoAction=new UndoAction(s);
        actions.put("Undo",undoAction);

        s="Redo";
        if (actionRenamingTable.containsKey("Redo")){
            s=(String)actionRenamingTable.get("Redo");
        }
        if (iconTable.containsKey("Redo")){
            icon=(ImageIcon)iconTable.get("Redo");
            redoAction=new RedoAction(s,icon);
            redoAction.putValue(Action.SMALL_ICON,icon);
        } else redoAction=new RedoAction(s);
        actions.put("Redo",redoAction);


        
        for (int i=0; i<nactionsArray.length; i++) {
            a=nactionsArray[i];
            obj=a.getValue(Action.NAME);
            if (actionRenamingTable.containsKey(obj)){
            	a.putValue(Action.NAME,actionRenamingTable.get(obj));
            }
            if (iconTable.containsKey(obj)){
                icon=(ImageIcon)iconTable.get(obj);
                a.putValue(Action.SMALL_ICON,icon);
            }
            actions.put(obj,a);
        }
        
        
    }
    
    
    private void configure(String s) {
    	boolean tables = true;
    	boolean toolBar = false;
    	actionRenamingTable = new Hashtable();
    	iconTable = new Hashtable();
    	try {
    	    BufferedReader in=new BufferedReader(new FileReader(s));            
    	    String ss;
    	    StringTokenizer st;
    	    char c;
            
    	    while ((ss=in.readLine()) != null) {
    	    	if (ss.length()>=2) {
    	    	    if (ss.charAt(0)=='*') {
    	    	    	if (tables) createActionTable(textPane);
    	    	        tables=false;
    	    	        toolBar=false;
    	    	        c=ss.charAt(1);
    	    	        if ((c=='t')||(c=='T')) toolBar=true;
    	    	    }
    	    	    else if (ss.charAt(0)!='#') {
    	    	        st = new StringTokenizer(ss);
    	    	        if (tables) configureTables(st);
    	    	        if (toolBar) configureToolBar(st);
    	    	    }
    	    	}
    	    }
    	    if (tables) createActionTable(textPane);

    	} catch (IOException e) {}
    }
    
    private void configureTables(StringTokenizer st){
    	ImageIcon icon;
    	String javaName,name;
        
    	int length = st.countTokens();
    	if (length >= 2) {
    	    try {
    	    	javaName = st.nextToken();
    	    	name = st.nextToken();
    	    	actionRenamingTable.put(javaName,name);
    	    	if (length >= 2) {
                     //Thomas
                     String iconFileName = checkFileSeparator(st.nextToken());
                     //System.out.println(iconFileName);
    	    	     //icon=new ImageIcon(st.nextToken());
                     icon = new ImageIcon(ClassLoader.getSystemResource(iconFileName));
    	    	     
    	    	     iconTable.put(javaName,icon);
    	    	}
    	     }
             catch (NoSuchElementException ex) {}
    	 }    	
    }

    private String checkFileSeparator(String buf) {
        //System.out.println("File Separator = "+File.separator);
        
        String result = buf;
        
        if (File.separator.equals("/")) {
            // Unix operating system
            //System.out.println("Unix");

            // convert for correct file separator
            String tmp;
            StringBuffer buf2 = new StringBuffer();
            for (int i=0; i<buf.length(); i++) {
                tmp = buf.substring(i,i+1);
                
                if (tmp.equals("\\"))
                    buf2.append(File.separator);
                else
                    buf2.append(tmp);
            }
            
            result = buf2.toString();
        }
        
        //System.out.println("result = "+result);
        
        return result;
    }
    
    private void configureToolBar(StringTokenizer st){
    	int length=st.countTokens();
    	if (length>=1){
    	    try{
    	    	while (st.hasMoreTokens()){
    	    	    String str=st.nextToken();
                    if (str.equals("/")) toolBar.addSeparator();
                    else if (str.equals("//")) addHardCodedItems();
                    else {
                    	Action a=getActionByName(str);                    	
                    	JButton b=toolBar.add(a);
                    	b.setText(null);
                    	if ( str.equals("cut-to-clipboard") 
                    		|| str.equals("paste-from-clipboard")
                    		|| str.equals("font-bold")
                    		|| str.equals("font-italic")
                    		|| str.equals("font-underline"))
                    	    b.addActionListener(this);
                    }                    
                }
    	     }catch (NoSuchElementException ex){}
    	}
    	//Configured Manualy
    	
        /*bBold=createToggleButton("font-bold");
    	toolBar.add(bBold);    	
        bItalic=createToggleButton("font-italic");
    	toolBar.add(bItalic);
        bUnderline=createToggleButton("font-underline");
    	toolBar.add(bUnderline);
    	    	
    	textPane.addCaretListener(new CaretListener(){
    	    public void caretUpdate(CaretEvent e){
    	    	int pos=e.getDot();
    	    	AttributeSet s=textPane.getCharacterAttributes();
    	    	Enumeration en=s.getAttributeNames();
    	    	String n;
    	    	boolean bold=false;
    	    	boolean italic=false;
    	    	boolean underline=false;
    	    	while (en.hasMoreElements()) {
    	    	    n=en.nextElement().toString();
    	    	    if (n.equals("bold")) bold=true;
    	    	    else if (n.equals("italic")) italic=true;
    	    	    else if (n.equals("underline")) underline=true;
                }
                bBold.setSelected(bold);
                bItalic.setSelected(italic);
                bUnderline.setSelected(underline);
                
    	    }
    	});*/
        
        
    	
    }
    
    private void addHardCodedItems(){
	toolBar.add(createSizeChooser());    	
    }
  /*  
    private JToggleButton createToggleButton(String s){
    	JToggleButton b=new JToggleButton();
    	Action a=getActionByName(s);
    	Object o=a.getValue(Action.SMALL_ICON);
    	if (o!=null) b.setIcon((Icon)o);
    	b.addActionListener(a);
    	return b;
    }
    
  */
    private Component createSizeChooser(){
        Container c=new Container();
        c.setLayout(null);
        Integer [] tab={new Integer(8),
        		new Integer(10),
        		new Integer(12),
        		new Integer(14),
        		new Integer(16),
        		new Integer(18),
        		new Integer(24),
        		new Integer(36),
        		new Integer(48)};
        JComboBox bSize=new JComboBox(tab);
        bSize.setSelectedItem(tab[2]);
        bSize.setBounds(0,0,50,23);

        
        final JComboBox b=bSize;
        /*bSize.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent e){
            	System.out.println("size changed");
            	Integer i=(Integer)b.getSelectedItem();
            	Action a=getActionByName("font-size-"+i);
            	a.actionPerformed(null);                    	

		//StyleConstants.setFontSize(textPane.getLogicalStyle(),i);
		

            }
        });*/
        bSize.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            	Integer i=(Integer)b.getSelectedItem();
            	Action a=getActionByName("font-size-"+i);
            	a.actionPerformed(null);                    	
    		FileManager.MODIFIED=true; 
            }
        });
        
        c.add(bSize);
    	return c;
    }


    private Action getActionByName(Object name) {
        return (Action)(actions.get(name));
    }


    //******************* New actions **********************
    class UndoAction extends AbstractAction {
    	private String undoName;
        public UndoAction() {
            super("Undo");
            undoName="Undo";
            setEnabled(false);
        }
        public UndoAction(String name) {
            super(name);
            undoName=name;
            setEnabled(false);
        }
        public UndoAction(String name,Icon icon) {
            super(name,icon);
            undoName=name;
            setEnabled(false);
        }
          
        public void actionPerformed(ActionEvent e) {
            try {
                undo.undo();
            } catch (CannotUndoException ex) {
                System.out.println("Unable to undo: " + ex);
                ex.printStackTrace();
            }
            updateUndoState();
            redoAction.updateRedoState();
        }
          
        protected void updateUndoState() {
            if (undo.canUndo()) {
                setEnabled(true);
                putValue(Action.NAME, undo.getUndoPresentationName());
            } else {
                setEnabled(false);
                putValue(Action.NAME,undoName);
            }
        }      
    }    

    class RedoAction extends AbstractAction {
    	private String redoName;
        public RedoAction() {
            super("Redo");
            redoName="Redo";
            setEnabled(false);
        }
        public RedoAction(String name) {
            super(name);
            redoName=name;
            setEnabled(false);
        }
        public RedoAction(String name,Icon icon) {
            super(name,icon);
            redoName=name;
            setEnabled(false);
        }

        public void actionPerformed(ActionEvent e) {
            try {
                undo.redo();
            } catch (CannotRedoException ex) {
                System.out.println("Unable to redo: " + ex);
                ex.printStackTrace();
            }
            updateRedoState();
            undoAction.updateUndoState();
        }

        protected void updateRedoState() {
            if (undo.canRedo()) {
                setEnabled(true);
                putValue(Action.NAME, undo.getRedoPresentationName());
            } else {
                setEnabled(false);
                putValue(Action.NAME, redoName);
            }
        }
    }    

    class NewDocumentAction extends AbstractAction{
        public NewDocumentAction(){
            super("new-document");
        }
        
        public void actionPerformed(ActionEvent e) {
            kit=new RTFEditorKit();
            textPane.setEditorKit(kit);
            doc=(DefaultStyledDocument)textPane.getStyledDocument();
            if (name!=null) Manager.RTFDB.put(name,doc);            
        }
    }

    class OpenRTFAction extends AbstractAction{
        public OpenRTFAction(){
            super("open-RTF");
        }
        
        public void actionPerformed(ActionEvent e) {    	    
    	    final JFileChooser fc=new JFileChooser(currentDir);
    	    int returnVal=fc.showOpenDialog(editorFrame);
    	    repaint();
            if (returnVal==JFileChooser.APPROVE_OPTION)
    	    try {
    	    	currentDir=new File(fc.getSelectedFile().getParent());
    	        BufferedInputStream in=new BufferedInputStream(
    	          new FileInputStream(fc.getSelectedFile()));
    	        
    	        kit=new RTFEditorKit();
                textPane.setEditorKit(kit);
                doc=(DefaultStyledDocument)textPane.getStyledDocument();            
                if (name!=null) Manager.RTFDB.put(name,doc);            

    	        kit.read(in,doc,0);
    	        in.close();
    	    } catch (Exception ex){System.err.println(ex);}
    	        
        }
    }


    class SaveRTFAction extends AbstractAction{
        public SaveRTFAction(){
            super("save-RTF");
        }
        
        public void actionPerformed(ActionEvent e) {
            
    	    final JFileChooser fc=new JFileChooser(currentDir);
    	    int returnVal=fc.showSaveDialog(editorFrame);
    	    repaint();
            if (returnVal==JFileChooser.APPROVE_OPTION)
    	    try {
    	    	currentDir=new File(fc.getSelectedFile().getParent());
    	        BufferedOutputStream out=new BufferedOutputStream(
    	          new FileOutputStream(fc.getSelectedFile()));
    	        kit.write(out,doc,0,doc.getLength());
    	        out.close();
    	    } catch (Exception ex){System.err.println(ex);}
        }
    }




    class CustomCut extends AbstractAction{
        public CustomCut(){
            super("custom-cut");
        }
        
        public void actionPerformed(ActionEvent e) {
            //selected=doc
            /*if ( (flavor = (DataFlavor)selected.get("enriched")) != null ){
            InputStream in = (InputStream)trans.getTransferData(flavor);
            RTFEditorKit ed = new RTFEditorKit();
            ed.read(in,doc, 0);
            }*/
            //System.out.println(textPane.getSelectedText()+"   "+textPane.getContentType());        
            String srcData=textPane.getSelectedText();
            if (srcData != null) {
                StringSelection contents = new StringSelection(srcData);
                clipboard.setContents(contents,editorFrame);
    		FileManager.MODIFIED=true; 
    		System.out.println("Cutting text: "+ srcData);
            }
            
            
            
            /*FlavorMap flavorMap = SystemFlavorMap.getDefaultFlavorMap();
	    Map map = flavorMap.getFlavorsForNatives(null);
	    System.out.println(map.get("Rich Text Format"));
	    
	    Set keys = map.keySet();
	    Iterator keysIterator = keys.iterator();
	    while(keysIterator.hasNext()){
	        Object key = keysIterator.next();
		Object value = map.get(key);
		System.out.println("Key: '" + key + "'; Value: '" + value + "'");
	    }*/

        }        

    }

    class CustomPaste extends AbstractAction{
        public CustomPaste(){
            super("custom-paste");
        }
        
        public void actionPerformed(ActionEvent e) {
          try{            
            Transferable content = clipboard.getContents(editorFrame);
            
            FlavorMap flavorMap = SystemFlavorMap.getDefaultFlavorMap();
	    	java.util.Map map = flavorMap.getFlavorsForNatives(null);
            DataFlavor flavor=(DataFlavor)map.get("Rich Text Format");

            if (content!=null){
           	
            	/*DataFlavor[] flavors = content.getTransferDataFlavors();
                for (int i = 0; i < flavors.length; i++){
		    String mime = flavors[i].getMimeType();
                    String name = flavors[i].getHumanPresentableName();
                    System.out.println("Mime: '" + mime + "'; Name: '" + name + "'");
		}*/

                InputStream in = (InputStream)content.getTransferData(flavor);
                RTFEditorKit ed=(RTFEditorKit)textPane.getEditorKit();
                ed.read(in,doc,0/*textPane.getCaretPosition()*/);
    			FileManager.MODIFIED=true; 
                
                /*String dstData = (String)content.getTransferData(DataFlavor.stringFlavor);
                RTFEditorKit ed=(RTFEditorKit)textPane.getEditorKit();                
                PipedWriter out=new PipedWriter();
                PipedReader in=new PipedReader(out);
                out.write(dstData); */               
                //ed.read(in,doc,0/*textPane.getCaretPosition()*/);
            }
          } catch (Exception ex){System.err.println(ex);}
        }
    }



    class CustomStyle  extends AbstractAction{
        public CustomStyle(){
            super("custom-style");
        }
        
        public void actionPerformed(ActionEvent e) 
        {
        }        
    }

    class Test  extends AbstractAction{
        public Test(){
            super("test");
        }
        
        public void actionPerformed(ActionEvent e) {
            try{
                doc.remove(textPane.getCaretPosition()-1,1);
            } catch (BadLocationException excep){System.err.println("Bad location!");}
            /* Element element=textPane.getStyledDocument().getDefaultRootElement();
            AttributeSet attributes;
            System.out.println("Name: "+element.getName()+"  "+element+"  nb children: "+element.getElementCount());
            int nb=element.getElementCount();
            Element child;
            for (int i=0;i<nb;i++){
                System.out.println("------------- "+i+" ---------------");
                
            	child=element.getElement(i);
                System.out.println("name: "+child.getName()+"  nb children: "+child.getElementCount());
            	attributes=child.getAttributes();
                Enumeration en=attributes.getAttributeNames();
                while (en.hasMoreElements())
                    System.out.println(en.nextElement());
            }
            doc.addDocumentListener(new DocListener());
            */
            
            
        }        
    }

    class InsertImage  extends AbstractAction{
        public InsertImage(){
            super("insert-image");
        }
        
        public void actionPerformed(ActionEvent e) {
            final JFileChooser fc=new JFileChooser(FOLDER);
    	    fc.addChoosableFileFilter(new ImageFilter());
            fc.setFileView(new ImageFileView());
            fc.setAccessory(new ImagePreview(fc));
    	    int returnVal=fc.showOpenDialog(MainFrame.mainFrame);
            if (returnVal==JFileChooser.APPROVE_OPTION) {
                addImage(fc.getSelectedFile().toString());
            }
        }
            
    }
    
    private void addImage(String f){
    	String name="icon"+nbImages;
    	nbImages++;
        Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);    	
        Style s = textPane.addStyle(name, def);
        StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
        StyleConstants.setIcon(s, new ImageIcon(f));
        try {
            doc.insertString(textPane.getCaretPosition()," ",textPane.getStyle(name));
        } catch (BadLocationException ex){}
    	FileManager.MODIFIED=true; 
    	
    }



    /*protected SimpleAttributeSet[] initAttributes(int length) {
        //Hard-code some attributes.
        SimpleAttributeSet[] attrs = new SimpleAttributeSet[length];

        attrs[0] = new SimpleAttributeSet();
        StyleConstants.setFontFamily(attrs[0], "SansSerif");
        StyleConstants.setFontSize(attrs[0], 16);

        attrs[1] = new SimpleAttributeSet(attrs[0]);
        StyleConstants.setBold(attrs[1], true);

        attrs[2] = new SimpleAttributeSet(attrs[0]);
        StyleConstants.setItalic(attrs[2], true);

        attrs[3] = new SimpleAttributeSet(attrs[0]);
        StyleConstants.setFontSize(attrs[3], 20);

        attrs[4] = new SimpleAttributeSet(attrs[0]);
        StyleConstants.setFontSize(attrs[4], 12);

        attrs[5] = new SimpleAttributeSet(attrs[0]);
        StyleConstants.setForeground(attrs[5], Color.red);

        return attrs;
    }*/




    protected void initStylesForTextPane(JTextPane textPane) {
        //Initialize some styles.
        /*Style def = StyleContext.getDefaultStyleContext().
                                        getStyle(StyleContext.DEFAULT_STYLE);

        Style regular = textPane.addStyle("regular", def);
        StyleConstants.setFontFamily(def, "SansSerif");

        Style s = textPane.addStyle("italic", regular);
        StyleConstants.setItalic(s, true);

        s = textPane.addStyle("bold", regular);
        StyleConstants.setBold(s, true);

        s = textPane.addStyle("small", regular);
        StyleConstants.setFontSize(s, 10);

        s = textPane.addStyle("large", regular);
        StyleConstants.setFontSize(s, 16);

        s = textPane.addStyle("icon", regular);
        StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
        StyleConstants.setIcon(s, new ImageIcon("icons"+File.separator+"delete.gif"));

        s = textPane.addStyle("button", regular);
        StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
        JButton button = new JButton(new ImageIcon("images/sound.gif"));
        button.setMargin(new Insets(0,0,0,0));
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Toolkit.getDefaultToolkit().beep();
            }
        });
        StyleConstants.setComponent(s, button);*/
    }

    public void load(DefaultStyledDocument doc){
    	textPane.setEditable(true);
        textPane.setCursor(Cursor.getDefaultCursor());
    	kit=new RTFEditorKit();
        textPane.setEditorKit(kit);
        this.doc=doc;
        textPane.setStyledDocument(doc);            
    	
    }

    public void load(String comName){
        JTextPane textPane;
    	String catName;
    	DefaultStyledDocument doc;
    	
    	for (int i = 0; i<RTFManager.DBNAMES.length; i++){
    		catName=RTFManager.DBNAMES[i];
			textPane = (JTextPane )_textPane.get(catName);
			textPane.setEditable(true);
        	textPane.setCursor(Cursor.getDefaultCursor());
        	textPane.setEditorKit(new RTFEditorKit());
        	doc = Manager.RTFDBM.getDocument(comName,catName);
        	if(doc != null)
        		textPane.setStyledDocument(doc);            
    	}
    	
    }

    public void load(String cat,DefaultStyledDocument doc){
        JTextPane textPane = (JTextPane )_textPane.get(cat);
       	textPane.setEditable(true);
        textPane.setCursor(Cursor.getDefaultCursor());

        RTFEditorKit kit=(RTFEditorKit)_kit.get(cat);
        textPane.setEditorKit(kit);
        _doc.put(cat,doc);
        textPane.setStyledDocument(doc);            

        /*
    	textPane.setEditable(true);
        textPane.setCursor(Cursor.getDefaultCursor());
    	kit=new RTFEditorKit();
        textPane.setEditorKit(kit);
        this.doc=doc;
        textPane.setStyledDocument(doc);            
    	*/
    }
    
    public void reset(){
        JTextPane textPane;
    	String catName;
    	
    	for (int i = 0; i<RTFManager.DBNAMES.length; i++){
    		catName=RTFManager.DBNAMES[i];
			textPane = (JTextPane )_textPane.get(catName);
        	textPane.setEditorKit(new RTFEditorKit());
        //	doc=(DefaultStyledDocument)textPane.getStyledDocument();
        	_doc.put(catName,(DefaultStyledDocument)textPane.getStyledDocument());
		    textPane.setEditable(false);
		    textPane.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
    	}
    	
    	/*
        kit=new RTFEditorKit();
        textPane.setEditorKit(kit);
        doc=(DefaultStyledDocument)textPane.getStyledDocument();
        textPane.setEditable(false);
        textPane.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
		*/
                      
    }
    public void closing(){
        try {
    	    userOut=new ObjectOutputStream(new FileOutputStream(USER));
    	    userOut.writeObject(currentDir);
    	    userOut.close();
    	} catch (Exception ex){}
    }
    
    
    
        /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {
        System.out.println(e.getKeyChar()+ " KEY TYEPED: ");
    	FileManager.MODIFIED=true; 
    }

    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) 
    {
    	if (e.getKeyText(e.getKeyCode()).equals("Delete"))
    		FileManager.MODIFIED=true;
        //System.out.println(e.getKeyChar()+ " KEY PRESSED: ");
    }

    /** Handle the key released event from the text field. */
    public void keyReleased(KeyEvent e) {
        //System.out.println(e.getKeyChar()+ " KEY RELEASED: ");
    }
    /** Handle the tool bar mouce pressing event. */
    public void actionPerformed(ActionEvent e)
    {
	//System.out.println(" presssed cut: ");
    	FileManager.MODIFIED=true;     	
    	
    }
    
	private JTabbedPane getTabPanel(){
		JTabbedPane _tabPane= new JTabbedPane();
    	String catName;
    	for (int i = 0; i<RTFManager.DBNAMES.length; i++){
    		catName=RTFManager.DBNAMES[i];
			_tabPane.addTab(catName, null, getRTF(catName));
		}
	/*	
		// Add the different tabs 
		_tabPane.addTab("Background",	//DmConcept.getDefaultActionConcept().getName(),
			null, getBGTab());
			
		_tabPane.addTab("Note",
			null, getBGTab());
		_tabPane.addTab("Warning",
			null, 	getBGTab());
		_tabPane.addTab("Tip",
			null, getBGTab());
		_tabPane.addTab("Annotation",
			null, getBGTab());
			
		//add listener
		//_tabPane.addChangeListener(tabListener);
		
 	*/	return _tabPane;	
  
	}
	
	private JScrollPane getBGTab(){
		//JPanel _userPanel= new JPanel();
        //Create the text pane and configure it.
        JTextPane textPane = new JTextPane();
        textPane.setToolTipText(TIP);
        RTFEditorKit kit=new RTFEditorKit();
        textPane.setEditorKit(kit);
        DefaultStyledDocument doc=(DefaultStyledDocument)textPane.getStyledDocument();
        
        textPane.setDropTarget(new DropTarget(textPane,new TextPaneTarget(textPane)));
        
        //new TextPaneSource(textPane);
        
        textPane.setCaretPosition(0);
        textPane.setMargin(new Insets(5,5,5,5));
        textPane.addKeyListener(this);
        
        
        JScrollPane scrollPane = new JScrollPane(textPane);
		return scrollPane;	
	}
	
	private JScrollPane getRTF(String cat){
		//JPanel _userPanel= new JPanel();
        //Create the text pane and configure it.
        JTextPane textPane = new JTextPane();
        textPane.setToolTipText(((String)_toolTip.get(cat)));
        RTFEditorKit kit=new RTFEditorKit();
        textPane.setEditorKit(kit);
        DefaultStyledDocument doc=(DefaultStyledDocument)textPane.getStyledDocument();
        //Start watching for undoable edits and caret changes.
        doc.addUndoableEditListener(new MyUndoableEditListener());
        textPane.setDropTarget(new DropTarget(textPane,new TextPaneTarget(textPane)));
        
        //new TextPaneSource(textPane);
        
        textPane.setCaretPosition(0);
        textPane.setMargin(new Insets(5,5,5,5));
        textPane.addKeyListener(this);
        
        JScrollPane scrollPane = new JScrollPane(textPane);
        
        _textPane.put(cat,textPane);
        _kit.put(cat,kit);
        _doc.put(cat,doc);

		return scrollPane;	
	}
	
	
}