Package gui

Source Code of gui.JLatexPanel$IndexPanel

package gui;


import java.awt.FlowLayout;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetContext;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.text.AttributeSet;

import javax.swing.JScrollBar;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.Border;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.AbstractDocument.DefaultDocumentEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import javax.swing.undo.UndoableEdit;
import javax.swing.undo.CompoundEdit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdesktop.layout.GroupLayout;

import undoedits.AddSweaveTagUndoableEdit;
import undoedits.RemoveSweaveTagUndoableEdit;

// import gui.ItemSelectionFrame;
import gui.MainFrame;
import helper.Helper;
import helper.Constants;
import dao.Controller;
import dao.DatafileSweaveLine;
import dao.DatafilesSweaveTag;
import dao.IViewport;
import dao.ObjectSweaveTag;
import dao.PlotSweaveTag;
import dao.RCommand;
import dao.RObject;
import dao.PlotSweaveTag;
import dao.RObjectViewportTable;
import dao.TableSweaveTag;
import dao.ISweaveTag;
import dao.TableSweaveTag;
import dao.TransferableSweaveTag;
import jeditsyntax.*;

// import java.util.LinkedList;

import java.io.BufferedWriter;
// import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
import java.util.Vector;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.io.IOException;


public class JLatexPanel extends JPanel {

   static JButton jbt_Undo;
   static JButton jbt_Redo;
    private static JLabel lbl_info;
 
    public class IndexPanel extends JPanel {

        public IndexPanel() {// TODO Auto-generated constructor stub
        }
        public IndexPanel(boolean arg0) {
            super(arg0);
            // TODO Auto-generated constructor stub
        }

        public IndexPanel(LayoutManager arg0) {
            super(arg0);
            // TODO Auto-generated constructor stub
        }

        public IndexPanel(LayoutManager arg0, boolean arg1) {
            super(arg0, arg1);
            // TODO Auto-generated constructor stub
        }

        public void drawSweaveBorder(ISweaveTag iSweaveTag, Graphics arg0, int firstline, int lastline) {
            int linerostart = jTextAreaLatexSource.getLineOfOffset(
                    iSweaveTag.getLatexPos());
            int lineroend = jTextAreaLatexSource.getLineOfOffset(
                    iSweaveTag.getLatexEnd())//;
                            + 1;
            int linestart = 0;
            int lineend = jTextAreaLatexSource.lineToY(lastline);
       
            boolean draw = false;
         
            if ((linerostart > firstline) && (linerostart < lastline)) {
                linestart = jTextAreaLatexSource.lineToY(linerostart);
                draw = true;
            }
            if ((lineroend > firstline) && (lineroend < lastline)) {
                lineend = jTextAreaLatexSource.lineToY(lineroend);
                draw = true;
            }
     
            if (draw) {
                arg0.setColor(iSweaveTag.getSidebarTextCol());     
                arg0.drawImage(iSweaveTag.getTypeImageIcon().getImage(), 2, linestart, this);
                arg0.drawString(iSweaveTag.getName(), iSweaveTag.getTypeImageIcon().getImage().getHeight(this) + 4,
                        linestart + arg0.getFont().getSize());

                arg0.setColor(iSweaveTag.getSidebarLineCol());
                final int bracewith = 4;
              
                arg0.drawLine(pan.getWidth(), linestart,
                        pan.getWidth() - bracewith, linestart);
                arg0.drawLine(0, linestart + iSweaveTag.getTypeImageIcon().getImage().getHeight(this) + 2,
                        pan.getWidth() - bracewith,
                        linestart + iSweaveTag.getTypeImageIcon().getImage().getHeight(this) + 2);
                arg0.drawLine(pan.getWidth() - bracewith, linestart,
                        pan.getWidth() - bracewith, lineend);
                arg0.drawLine(pan.getWidth(), lineend,
                        pan.getWidth() - bracewith, lineend);
            }

        }
   
        @Override
        public void paint(Graphics arg0) {
            // TODO Auto-generated method stub
            super.paint(arg0);
     
            int firstline = jTextAreaLatexSource.getFirstLine();
            int lastline = firstline + jTextAreaLatexSource.getVisibleLines();

            if (datafileTag != null ) drawSweaveBorder(datafileTag, arg0, firstline, lastline);
           
            for (ISweaveTag swt : iSweaveTags) {
                drawSweaveBorder(swt, arg0, firstline, lastline);
            }
       
        }

    }

  private static final String TAGSPACE = "\n\n";

    private static Log log = LogFactory.getLog(JLatexPanel.class);

    //private boolean undoNext = false;



    protected static UndoManager undoManager = new UndoManager();
   
   
    private static boolean watchdogon = true;

  // private static JScrollPane jScrollPaneLatex;
    // private static JTextArea jTextAreaLatexSource;
    protected static JEditTextArea jTextAreaLatexSource;
   
   
    private static DatafilesSweaveTag datafileTag = null;
 
    private static List<ISweaveTag> iSweaveTags = new Vector<ISweaveTag>();

    // private static List<RObject> rObjects = new Vector<RObject>();

    public static File reportFile = null;

  private static CompoundEdit compoundEdit;
   
    public static void addDataFileAtCursor(DatafileSweaveLine swl) {
    addDataFile(swl, jTextAreaLatexSource.getCaretPosition());
  }

  public static void addDataFile(DatafileSweaveLine swl, int position) {// TODO: Exception, wenn SweaveTAg =null
      log.info("inserting datafile: " + swl.getSweaveString());
   
      if (datafileTag == null) { //add whole datafile
        System.out.println("Adding... ");
     
        datafileTag = new DatafilesSweaveTag();
         datafileTag.setLatexPos(position);
         //Insert before @\n
        datafileTag.getAttachedSweaveStrings().add(swl);

        addTagAtCursor(datafileTag);
        swl.setLatexPos(datafileTag.getLatexEnd()-2);
       
      }
      else {    //simply add text at bottom
        System.out.println("Modifiying... ");
//        DatafilesSweaveTag datafileTagnew = new DatafilesSweaveTag(datafileTag);
//       
//        datafileTagnew.getAttachedSweaveStrings().add(swl);
//         swl.setLatexPos(datafileTagnew.getLatexEnd()-2);
//
//        alterTag(datafileTag, datafileTag);
       
        // BAUSTELLE

            System.out.println("datafileTag.getLatexStartWithSpacers(): " + datafileTag.getLatexStartWithSpacers());
     
        startMergedUndo();

        addMergedUndo(new RemoveSweaveTagUndoableEdit(datafileTag));
          iSweaveTags.remove(datafileTag);
        removeText(datafileTag.getLatexPos(), datafileTag.getSweaveString().length());
            System.out.println("datafileTag.getLatexStartWithSpacers(): " + datafileTag.getLatexStartWithSpacers());
               
        datafileTag.getAttachedSweaveStrings().add(swl);
            
            System.out.println("datafileTag.getLatexStartWithSpacers(): " + datafileTag.getLatexStartWithSpacers());

           
            addMergedUndo(new AddSweaveTagUndoableEdit(datafileTag));
            System.out.println("datafileTag.getLatexStartWithSpacers(): " + datafileTag.getLatexStartWithSpacers());
        insertText( datafileTag.getSpacers()[0] + datafileTag.getSweaveString() + datafileTag.getSpacers()[1],
            datafileTag.getLatexStartWithSpacers());
        endMergedUndo();
         swl.setLatexPos(datafileTag.getLatexEnd()-2);
 
      }
     
//      watchdogon=true;
        //
        // if ()
        // swt.setLatex(true); // has to be called after insert
    }
 


   
    public static void addTagAtCursor(ISweaveTag swt) {
      addTag(swt, jTextAreaLatexSource.getCaretPosition());
    }

    public static void addTag(ISweaveTag swt, int position) {

        String preSpace = "";
    String postSpace = "";
    try {
      if (position == 0 ||
          (!jTextAreaLatexSource.getDocument().getText(position-1, 1).equals( "\n" ) )) {
        preSpace = TAGSPACE;
      }

      if (position == jTextAreaLatexSource.getDocument().getLength() ||
          (!jTextAreaLatexSource.getDocument().getText(position+1, 1).equals( "\n" ) )) {
        postSpace = TAGSPACE;
      }
     
      swt.setSpacers(new String[] {preSpace, postSpace});
   
    } catch (BadLocationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    swt.setLatexPos(position + swt.getSpacers()[0].length());       
    
   
    log.info("Adding Object to merged compoudEdit: " + swt.getName());

    //ueBuffer.add();
    startMergedUndo();
    addMergedUndo(new AddSweaveTagUndoableEdit(swt));
    insertText( swt.getSpacers()[0] + swt.getSweaveString() + swt.getSpacers()[1],
            position);
    endMergedUndo();
    addTagToObjMan(swt);
    //jTextAreaLatexSource.setCaretPosition(swt.getLatexEndWithSpacers()-1);
   
    }
 

    public static void addTagToObjMan(ISweaveTag swt) {
    System.out.println("---- DDING DIRECT TAG");
        // TODO: Exception, wenn SweaveTAg =null
        log.debug(
                "Adding Sweave-Tag " + swt.getName() + "\n\n"
                + swt.getSweaveString() + " to Object-Manager.");
       iSweaveTags.add(swt);
       
        // ro.setLatex(true); // has to be called after insert
    }
   
    public static void alterTag(ISweaveTag swtold, ISweaveTag swtnew) {
    startMergedUndo();

    addMergedUndo(new RemoveSweaveTagUndoableEdit(swtold));
    rmTagFromObjMan(swtold);
    removeText(swtold.getLatexPos(), swtold.getSweaveString().length());
    addMergedUndo(new AddSweaveTagUndoableEdit(swtnew));
    insertText( swtnew.getSpacers()[0] + swtnew.getSweaveString() + swtnew.getSpacers()[1],
        swtnew.getLatexStartWithSpacers());
    addTagToObjMan(swtnew);
    endMergedUndo();

     
    }

    public static void startMergedUndo() {
      if ((compoundEdit!= null) && compoundEdit.isInProgress())
        log.error("CompundEdit was not empty when spawning new." +
            " Some Undo-Information could be lost");
      compoundEdit = new CompoundEdit();
     
    }
    public static void addMergedUndo(UndoableEdit ue) {

      compoundEdit.addEdit(ue);
       
    }
    public static void endMergedUndo() {
      compoundEdit.end();
      undoManager.addEdit(compoundEdit);
       
    }
   
    public static void append(String text) {
      try {
      jTextAreaLatexSource.getDocument().insertString(jTextAreaLatexSource.getDocumentLength(), text, null);
    } catch (BadLocationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
        //jTextAreaLatexSource.setText(jTextAreaLatexSource.getText() + text);      
       
    }
    public static void genStdRep() {

    }
    public static void getContentOfTexFileIntoPanel(File f) {
   
        Scanner s;
//      TODO migrate from single to multipe datafiles
        System.out.println("migrate from single to multipe datafiles");
        try {
            s = new Scanner(f);
        } catch (IOException e) {
            Helper.ok("Open error " + e);
            return;
        }

        while (s.hasNextLine()) {
            String str = s.nextLine();

//            JLatexPanel.append(
//                    str.replace(Constants.TAG_FILENAME, dataFile.getName())
//                            + "\n");         
        }          
        s.close();
       
    }
   
    public static void gotoTag(ISweaveTag sweaveTag) {
        jTextAreaLatexSource.setCaretPosition(sweaveTag.getLatexPos());
        jTextAreaLatexSource.scrollToCaret();
    }

    public static void insertAtCursor(String text) {
             
        insertText(text, jTextAreaLatexSource.getCaretPosition());
       
    }
        
   
    public static void insertHeaderFooter() {
        String ltxHead = Constants.LATEX_HEADER
                + "\n\n\n\n";
       
        insertText(ltxHead, 0);
        append(Constants.LATEX_FOOTER);
        jTextAreaLatexSource.setCaretPosition(
                ltxHead.length() - 2 * "\n".length());
       
    }
 
    public static void insertText(String text, int pos) {
   
        try {
            jTextAreaLatexSource.getDocument().insertString(pos, text, null);
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }

    public static boolean isTagShown(ISweaveTag sweaveTag) {
    // TODO Auto-generated method stub
    return iSweaveTags.contains(sweaveTag);
  }
   
    public static void pushContentInFile(File f) {
        try {
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(f)));

            out.write(jTextAreaLatexSource.getText(), 0,
                    jTextAreaLatexSource.getText().length());
            out.close();
        } catch (Exception ex) {
            Helper.ok(ex.toString());
        }
    }

    // public static void rmTable(TableSweaveTag swt) {
    //
    // System.out.println("tables264");
    // jTextAreaLatexSource.getDocument().removeDocumentListener(docListener);
    //
    // tables.remove(swt);
    // jTextAreaLatexSource.getDocument().addDocumentListener(docListener);
    //
    // removeText(swt.getLatexPos(), swt.getSweaveString().length());
    // swt = null;
    // }
    //
    //
    // public static void rmPlot(PlotSweaveTag swt) {
    // jTextAreaLatexSource.getDocument().removeDocumentListener(docListener);
    //
    // plots.remove(swt);
    // jTextAreaLatexSource.getDocument().addDocumentListener(docListener);
    //
    // removeText(swt.getLatexPos(), swt.getSweaveString().length());
    // swt = null;
    //
    // }
   
    // private static LinkedList<String> sHistory = new LinkedList<String>();
    // private static int iHistory;
 
   

    private static void removeText(int pos, int len) {
        try {
            jTextAreaLatexSource.getDocument().remove(pos, len);
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //
    //
    //
    // protected void eventuallyDeAttachPlot(PlotSweaveTag rpo) {
    // if (helper.Helper.yesno(
    // "Altered Sweave-Tag for: " + rpo.getName() +
    // "\nUndo?\nNote: If you don't undo the Text will be \n" +
    // "deattached from the Object")) {
    // undoNext = true;
    // System.out.println("setting undoflag for: " + rpo.getName());
    //
    // } else {
    // deAttachPlot(rpo);
    // }
    // }
    //
    // private void deAttachPlot(PlotSweaveTag swt) {
    // plots.remove(swt);
    // swt = null;
    // //gui.MainFrame.
    // }
    //
    // protected void eventuallyDeAttachTable(RObject ro) {
    // if (helper.Helper.yesno(
    // "Altered Sweave-Tag for: " + ro.getRVarName() +
    // "\nUndo?\nNote: If you don't undo the Text will be \n" +
    // "deattached from the Object")) {
    // //undoManager.
    // //undoManager.undo();
    // System.out.println("setting undoflag for: " + ro.getRVarName());
    // undoNext = true;
    // } else {
    // deAttachTable(ro);
    // }
    // }
    //
    // private void deAttachTable(RObject ro) {
    // System.out.println("tables618");
    // tables.remove(ro);
    // ro.setSweaveTag(null);
    // }
    //
    // protected void eventuallyDeAttachDataSet(SweaveTag ro) {
    // if (helper.Helper.yesno(
    // "Altered Sweave-Tag for: " + ro.getName() +
    // "\nUndo?\nNote: If you don't undo the Text will be \n" +
    // "deattached from the Object")) {
    // //  undoManager.undo();
    // undoNext = true;
    // System.out.println("setting undoflag for: " + ro.getName());
    //
    //
    // } else {
    // deAttachDataSet(ro);
    // }
    // }
    //
    //
    // private void deAttachDataSet(SweaveTag ro) {
    // //  dataFiles.remove(ro);
    // ro = null;
    // }

    //
    // public static void addTable(TableSweaveTag swt) {
    // //TODO: Exception, wenn SweaveTAg =null
    //
    // swt.setLatexPos(jTextAreaLatexSource.getCaretPosition());
    // insertText(swt.getSweaveString(), jTextAreaLatexSource.getCaretPosition());
    // tables.add(swt);
    // //    ro.setLatex(true); // has to be called after insert
    // }
    //
    // public static void addPlot(PlotSweaveTag swt) {
    // swt.setLatexPos(jTextAreaLatexSource.getCaretPosition());
    // insertText(swt.getSweaveString(), jTextAreaLatexSource.getCaretPosition());
    // plots.add(swt);
    // //rpo.setLatex(true); // has to be called after insert
    // }
    //
    public static void rmDataFile(DatafileSweaveLine swl) {// jTextAreaLatexSource.getDocument().removeDocumentListener(docListener);
      if (datafileTag.getAttachedSweaveStrings().size()==1) { //add whole datafile
        rmTag(datafileTag);
       
       
      }
      else {    //simply add text at bottom
//        DatafilesSweaveTag datafileTagnew = datafileTag.clone();
//       
//        datafileTagnew.getAttachedSweaveStrings().remove(swl);
//         swl.setLatexPos(datafileTagnew.getLatexEnd()-2);
//
//        alterTag(datafileTag, datafileTag);
        startMergedUndo();

        addMergedUndo(new RemoveSweaveTagUndoableEdit(datafileTag));
            removeText(datafileTag.getLatexPos(), datafileTag.getSweaveString().length());
       
        datafileTag.getAttachedSweaveStrings().remove(swl);
            

           
            addMergedUndo(new AddSweaveTagUndoableEdit(datafileTag));
        insertText( datafileTag.getSpacers()[0] + datafileTag.getSweaveString() + datafileTag.getSpacers()[1],
            datafileTag.getLatexStartWithSpacers());
        endMergedUndo();
         swl.setLatexPos(datafileTag.getLatexEnd()-2);
      }
     
    }    

    public static void rmTag(ISweaveTag swt) {
    System.out.println("---- REMOVING UNDOABLE TAG");
    rmTagFromObjMan(swt);
    log.info("Adding remove Object to Queue: " + swt.getName());
    startMergedUndo();
    addMergedUndo(new RemoveSweaveTagUndoableEdit(swt));
        removeText(swt.getLatexPos(), swt.getSweaveString().length());
//        for (ISweaveTag swt1 : iSweaveTags)
//          if swt.
    endMergedUndo();

        }    
     
    public static void rmTagFromObjMan(ISweaveTag swt) {
    System.out.println("---- REMOVING Object-Reference");
      iSweaveTags.remove(swt);
      if (swt.equals(datafileTag)){
        System.out.println("no more datafiles, setting datafileTag null");
        datafileTag =null;
      }
    }

    public static void runSweave() {
        // String tmpdir = System.getProperty("user.dir");

        // System.setProperty("user.dir", reportFile.getParent());
        // reportFile.getAbsolutePath()
      log.info("trying to build " + reportFile.getPath());
        // RCommand.eval("setwd(gsub('\\\\', '/','" + reportFile.getParent() + "'))" );
        RCommand.eval("setwd('" + reportFile.getParent().replace('\\', '/') + "')");
        RCommand.runSweave(reportFile.getPath().replace('\\', '/'));
        // System.setProperty("user.dir", tmpdir);
    }
    public static void generatePDF() { 
      //runSweave();
      try {
       
        //TODO: dirty generation of texfilename, should be central projectfilemanager
        String texfilename = reportFile.getPath().substring(0,reportFile.getPath().length()-3).replace('\\', '/') + "tex";
        log.info("trying to make PDF of " + texfilename);
        Runtime.getRuntime().exec("pdflatex " + texfilename );
    } catch (IOException e) {
      e.printStackTrace();
    }
    }
 
   
    public static void savefullReport(File f) {
        String sep = System.getProperty("file.separator");
//      TODO migrate from single to multipe datafiles
       // System.out.println("fixme:migrate from single to multipe datafiles");
       
        try {
            f.mkdir();
     
            reportFile = new File(f.getPath() + sep + f.getName() + ".Rnw");
            pushContentInFile(reportFile);

            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(
                                    new File(
                                            f.getPath() + sep + f.getName()
                                            + ".bat"))));

            out.write(
                    "echo 'Sweave(\"" + reportFile.getName()
                    + "\")' | R --vanilla --quiet");
            out.close();
     
            File tmpfile = new File(f.getPath() + sep + f.getName() + ".sh");

            out = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(tmpfile)));
            out.write(
                    "echo 'Sweave(\"" + reportFile.getName()
                    + "\")' | R --vanilla --quiet");
            out.close();

//          copy data files
            //TODO write.csv und sweaveTags ändern
 
           
     
        } catch (Exception ex) {
            Helper.ok(ex.toString());
        }
    }
   
    private IndexPanel pan;

    private SweaveDropTarget dt;

    //
    //
    // public static void getItemSelFrameFunctionkindIntoPanel(String cmd, String args) {
    // JLatexPanel.insert(
    // "\n<<echo=FALSE" + args + ">>=" + cmd + "\n" + "@" + "\n");   //besser per checkbox
    //
    // // JLatexPanel.jTextAreaLatexSource.append("" + "\\" + "end{Scode}");
    // }
    // public static void getItemSelFrameXtableZeilerIntoPanel(String cmd) {
    //
    // if  (  cmd.equals("\ncalc1set")||cmd.equals("\ncalc2set")||cmd.equals("\nsyschar")||cmd.equals("\nw1")||cmd.equals("\nw2")||cmd.equals("\nitemtest")  ){
    // JLatexPanel.insert("\n<<echo=FALSE>>=" + cmd + "\n" + "@" + "\n");
    // } else{
    // JLatexPanel.insert("\n<<echo=FALSE,results=tex>>=" + cmd + "\n" + "@" + "\n");
    // }
    //
    //
    // // JLatexPanel.jTextAreaLatexSource.append("" + "\\" + "end{Scode}");
    // }
    //
    // public static void getItemSelFramePlot3dZeilerIntoPanel(String cmd, String label, String caption, int intPlot3d) {
    // JLatexPanel.insert(
    // "\n\\begin{figure}\n<<echo=FALSE, label=" + label + intPlot3d + "_fig" + /*", caption=" + caption +*/", include=TRUE, fig=TRUE>>=" + cmd + "\n" + "@" + "\n" + "\\caption{" + caption + "} \n" +
    // "\\label{"+ label +intPlot3d + "} \n"  +             
    // "\\end{figure}\n" );
    // //<<label=labelbsptext, caption=captionbsptext, include=true>>
    // //isop.plot3d(sysc)
    // //@
    // // JLatexPanel.jTextAreaLatexSource.append("" + "\\" + "end{Scode}");
    // }
    // public static void getItemSelFrameFreqOfRespZeilerIntoPanel(String cmd, String label, String caption, int intFreqOfResp) {
    // // JLatexPanel.jTextAreaLatexSource.append("\\" + "begin{Scode}{echo=false,results=hide}");
    // // JLatexPanel.jTextAreaLatexSource.append("\n");
    // // JLatexPanel.jTextAreaLatexSource.append("\n");
    // JLatexPanel.insert(
    // "\n\\begin{figure}\n<<echo=FALSE, label=" + label + intFreqOfResp + "_fig" + /*", caption=" + caption +*/", include=TRUE, fig=TRUE>>=" + cmd + "\n" + "@" + "\n" + "\\caption{" + caption + "} \n" +
    // "\\label{"+ label +intFreqOfResp + "} \n"  +
    // "\\end{figure}\n" );
    // //<<include=true>>
    // //isop.plotFreqs(what=syschar)
    // //@
    //
    // // JLatexPanel.jTextAreaLatexSource.append("" + "\\" + "end{Scode}");
    // }

    private DocumentFilter docFilter;
  protected JMenu menuSweaveTag;



    public JLatexPanel() {
        super();
   
        initComponents();
       
    }

  protected static void displayDotMark(int dot, int mark) {
    String dotmark;
    if (dot == mark) dotmark = "Line: " + jTextAreaLatexSource.getLineOfOffset(dot);
    else dotmark = "Selection: " + jTextAreaLatexSource.getLineOfOffset(mark) + " - "  +
        jTextAreaLatexSource.getLineOfOffset(dot);

    lbl_info.setText( dotmark );
  }
 
  protected static void displayWarning(String string) {
    // TODO Auto-generated method stub
   
    lbl_info.setText( "<html><font color=\"#ff0000\">" + string + "</html>" );
  }
 
    private void initComponents() { 
    
        jTextAreaLatexSource = new JEditTextArea();
        jTextAreaLatexSource.setTokenMarker(new TeXTokenMarker());
        jTextAreaLatexSource.setBorder(null);
        jTextAreaLatexSource.setEditable(true);


        jTextAreaLatexSource.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent e) {
                JLatexPanel.displayDotMark(e.getDot(), e.getMark());               
            }
        });

       
       
        jTextAreaLatexSource.getDocument().addUndoableEditListener(
                new UndoableEditListener() {
             
            public void undoableEditHappened(UndoableEditEvent arg0) {
              if (!watchdogon) {
                log.info("watchdog disabled, skipping undo-handling");
                return;
              }
              if (compoundEdit.isInProgress()) {
                compoundEdit.addEdit(arg0.getEdit());
              }
              else undoManager.addEdit(arg0.getEdit());
             
              updateButtons();
                  
                   
                // if(helper.Helper.yesno("undo?")) arg0.getEdit().undo();
       
            }
       
        });

     
      
      
        docFilter = new DocumentFilter() {
         
      public void insertString(DocumentFilter.FilterBypass fb,
                    int offset,
                    String string,
                    AttributeSet attr)
             throws BadLocationException {
               if ((checkAndShiftAllObjects(offset, string.length(), false) == null) || !watchdogon)
                      fb.insertString(offset, string, attr);
               else {
                 //Raise warning
                 JLatexPanel.displayWarning("You can not modify the Sweave-Tags directly. You may want to deattach it.");
               }
//                  if (Helper.yesno("insert " + string + "@" + offset)) {
//                                
//            }
                pan.repaint();
          }
      
            public void remove(DocumentFilter.FilterBypass fb,
                    int offset,
                    int length)
             throws BadLocationException {
            if (length==0) return;
            if ((checkAndShiftAllObjects(offset, length, true) == null) || !watchdogon)
              fb.remove(offset, length);
            else {
                  //Raise warning
                  JLatexPanel.displayWarning("You can not modify the Sweave-Tags directly. You may want to deattach it.");
                }
//              if (Helper.yesno("remove @" + offset + "len " + length)) {
//                   
//            }
                pan.repaint()
          }

            public void replace(DocumentFilter.FilterBypass fb,
                    int offset,
                    int length,
                    String text,
                    AttributeSet attrs)
             throws BadLocationException {
            Helper.ok("fixme:not implemented yet. encapsulate object manager");
            if (Helper.yesno("replace " + text + "@" + offset)) {
              fb.replace(offset, length, text, attrs);                  
            }
                pan.repaint();
          }

         
        };
       
        jTextAreaLatexSource.getDocument().setDocumentFilter(docFilter);
       
       

     
        jTextAreaLatexSource.getVertical().addAdjustmentListener(
                new AdjustmentListener() {

            public void adjustmentValueChanged(AdjustmentEvent arg0) {
                pan.repaint();
            }
       
        });

        JPopupMenu popup = new JPopupMenu();
            
        JMenuItem menuItemCut = new JMenuItem("Cut");
        menuItemCut.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              jTextAreaLatexSource.cut();
            }
        });
       
        popup.add(menuItemCut);
       
        JMenuItem menuItemCopy = new JMenuItem("Copy");
        menuItemCopy.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              jTextAreaLatexSource.copy();
            }
        });
        popup.add(menuItemCopy);
       
        JMenuItem menuItemPaste = new JMenuItem("Paste");
        menuItemPaste.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              jTextAreaLatexSource.paste();
            }
        });
       
        popup.add(menuItemPaste);

        popup.addSeparator();
       
        menuSweaveTag = new JMenu("Sweave Tag");
        popup.add(menuSweaveTag);
       
        JMenuItem menuItemShow = new JMenuItem("show evaluated values");
        menuItemShow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
//                showActionPerformed(evt);
            }
        });
        menuSweaveTag.add(menuItemShow);
 
  //      menuSweaveTag.addSeparator();
       
        JMenuItem menuItemEval = new JMenuItem("evaluate");
        menuItemEval.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
//                evalActionPerformed(evt);
            }
        });
        menuSweaveTag.add(menuItemEval);
       
//        JMenuItem menuItemtoLatex = new JMenuItem("insert Sweave tag");
//        menuItemtoLatex.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent evt) {
////                toLatexActionPerformed(evt);
//            }
//        });
//        popup.add(menuItemtoLatex);
       
        // JMenu rmContainer = new JMenu("remove");
        // popup.add(rmContainer);
       
        JMenuItem menuItemRemove = new JMenuItem("remove completly");
        menuItemRemove.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
//                removeActionPerformed(evt);
            }
        });
        menuSweaveTag.add(menuItemRemove);
       
        JMenuItem menuItemRemovefromR = new JMenuItem("remove evaluation");
        menuItemRemovefromR.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
   //             removefromRActionPerformed(evt);
            }
        });
        menuSweaveTag.add(menuItemRemovefromR);
       
        JMenuItem menuItemRemovefromLatex = new JMenuItem("remove Sweave tag");
        menuItemRemovefromLatex.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
  //              removefromLatexActionPerformed(evt);
            }
        });
        menuSweaveTag.add(menuItemRemovefromLatex);


       

        jTextAreaLatexSource.setRightClickPopup(popup);
         
        
        pan = new IndexPanel();
        // pan.setOpaque(false);
        pan.setForeground(Color.black);
        pan.setBackground(Color.white);
        // pan.setSize( jTextAreaLatexSource.getSize().height,120);
         
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, pan,
                jTextAreaLatexSource);

        splitPane.setOneTouchExpandable(true);
        splitPane.setDividerLocation(100);
        this.setSize(new Dimension(800, 600)); //800,600
        // Provide minimum sizes for the two components in the split pane
        Dimension minimumSize = new Dimension(50, 20);

        pan.setMinimumSize(minimumSize);
        jTextAreaLatexSource.setMinimumSize(minimumSize);
        // splitPane.setPreferredSize(this.getSize());

        dt = new SweaveDropTarget(jTextAreaLatexSource);
        JButton jbt_Open;
        JToolBar myToolbar = new JToolBar();
        myToolbar.setFloatable(false);
       
        // Toolbar Buttons   
        jbt_Undo = new JButton();
        ImageIcon iconUndo = new ImageIcon("./images/i16x16/undo16.gif");

        jbt_Undo.setIcon(iconUndo);
        jbt_Undo.setToolTipText("Undo");
        jbt_Undo.setVisible(true);
        jbt_Undo.setEnabled(false);
        jbt_Undo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                undo();
            }
        });
       
        jbt_Redo = new JButton();
        ImageIcon iconRedo = new ImageIcon("./images/i16x16/redo16.gif");

        jbt_Redo.setIcon(iconRedo);
        jbt_Redo.setToolTipText("Redo");
        jbt_Redo.setVisible(true);
        jbt_Redo.setEnabled(false);
        jbt_Redo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                redo();
            }
        });

       
        jbt_Open = new JButton();
        ImageIcon iconOpen = new ImageIcon("./images/i16x16/open16.gif");

        jbt_Open.setIcon(iconOpen);
        jbt_Open.setToolTipText("Tooltip for Button Open");

        myToolbar.add(jbt_Undo);
        myToolbar.add(jbt_Redo);
       
        lbl_info = new JLabel();
        lbl_info.setText("");
        lbl_info.setVisible(true);
       
       
        BorderLayout myLayout = new BorderLayout();
        this.setLayout(myLayout);

        this.add(myToolbar, BorderLayout.NORTH);
        this.add(splitPane, BorderLayout.CENTER);
        this.add(lbl_info, BorderLayout.SOUTH);
         
     

    }
 




  private ISweaveTag checkAndShiftAllObjects(int offset, int length, boolean remove) {
        // All objects after the insert/remove must be shifted
     
        for (ISweaveTag swt : iSweaveTags) {
            if (!checkAndShiftObject(swt, offset, length, remove)) return swt;
        }

    return null;
//        jTextAreaLatexSource.getDocument().addDocumentListener(this);

    }
 
  private boolean checkAndShiftObject(ISweaveTag swt, int offset, int length, boolean remove) {

//      offset conflicting with Tag
//        offset has to be bigger than the Position in Latex OR
        int critstart = swt.getLatexPos();
        if (remove) critstart++;
   
    if (
      (
        (critstart < offset) && (swt.getLatexEnd() > offset)
      ) ||
      (
        remove && (critstart < offset+length) && (swt.getLatexEnd() > offset+length)
      )
    )
    {

     
     
          log.warn("Broken Constraint: " +
              "\nremoving: " + (remove?"yes":"no") +
              "\nPosition: " + offset +
              "\nEnd: " + (offset + length) +
              "\nConflicting Tag: " + swt.getName() +
            "\nTag Start: " + swt.getLatexPos() +
            "\nTag End: " + swt.getLatexEnd()
            );

            return false;
        }
       
       
        if (critstart >= offset) {
          if (remove) swt.setLatexPos(swt.getLatexPos() - length);
          else swt.setLatexPos(swt.getLatexPos() + length);
            log.trace(
                    "Resetting datapos " + swt.getLatexPos()
                    + "offset: " + offset);  
        }
        return true;
    }
 
  static ISweaveTag checkAllObjects(int offset, int length) {
        // All objects after the insert/remove must be shifted
     
        for (ISweaveTag swt : iSweaveTags) {
            if (!checkObject(swt, offset, length)) return swt;
        }

    return null;
//        jTextAreaLatexSource.getDocument().addDocumentListener(this);

    }
 
  private static boolean checkObject(ISweaveTag swt, int offset, int length) {

//      offset conflicting with Tag
//        offset has to be bigger than the Position in Latex OR
        int critstart = swt.getLatexPos();
   
    if (
      (
        (critstart < offset) && (swt.getLatexEnd() > offset)
      ) ||
      (
        (critstart < offset+length) && (swt.getLatexEnd() > offset+length)
      ) || (critstart > offset) && (swt.getLatexEnd() > offset + length)
    )
    {

            return false;
        }
       
       
        return true;
    }
 
 
  public static void deAttachTag(ISweaveTag swt) {
        iSweaveTags.remove(swt);
        // gui.MainFrame.
    }
 
    private void eventuallyDeAttach(ISweaveTag swt) {
        if (!helper.Helper.yesno(
                "Altered Sweave-Tag for: " + swt.getName()
                + "\nUndo?\nNote: If you don't undo the Text will be \n"
                + "deattached from the Object")) {
            deAttachTag(swt);
        }
   
    }
 

   
    protected void redo() {
 
        try {
            undoManager.redo();
        } catch (CannotRedoException cre) {
            cre.printStackTrace();
        }
        updateButtons();
    }

    protected void undo() {
   
        try {
            undoManager.undo();
        } catch (CannotUndoException cre) {
            cre.printStackTrace();
        }
        updateButtons();
    }

  public void updateButtons() {
        JLatexPanel.jbt_Undo.setToolTipText(undoManager.getUndoPresentationName());
        JLatexPanel.jbt_Redo.setToolTipText(undoManager.getRedoPresentationName());
        JLatexPanel.jbt_Undo.setEnabled(undoManager.canUndo());
        JLatexPanel.jbt_Redo.setEnabled(undoManager.canRedo());
    }

}


class PopupListenerReport extends MouseAdapter {
    JPopupMenu popup;

    PopupListenerReport(JPopupMenu popupMenu) {
        popup = popupMenu;
    }

    public void mousePressed(MouseEvent e) {
        maybeShowPopup(e);
    }

    public void mouseReleased(MouseEvent e) {
        maybeShowPopup(e);
    }

    private void maybeShowPopup(MouseEvent e) {
   
        if (e.isPopupTrigger()) {
          int start = JLatexPanel.jTextAreaLatexSource.getSelectionStart();
          int end = JLatexPanel.jTextAreaLatexSource.getSelectionEnd();
          ISweaveTag swt;
          if (start < end)
            swt = JLatexPanel.checkAllObjects(start, end - start);
          else swt = JLatexPanel.checkAllObjects(end, start - end);

          popup.getComponent(2).setVisible(swt != null);
         
            popup.show(e.getComponent(), e.getX(), e.getY());
        }
    }

}

// TreeDropTarget.java
// A quick DropTarget that's looking for drops from draggable JTrees.
//

class SweaveDropTarget implements DropTargetListener {

    DropTarget target;

    Component comp;

    public SweaveDropTarget(Component comp) {
        this.comp = comp;
        target = new DropTarget(comp, this);
    }

    public void dragEnter(DropTargetDragEvent dtde) {
        if (isTransferableSweaveTag(dtde)) {
            System.out.println("drag match");
          dtde.acceptDrag(dtde.getDropAction());           
        } else {
            System.out.println("drag no match");
          dtde.rejectDrag();
        }
    }

    public void dragExit(DropTargetEvent dtde) {// TODO Auto-generated method stub
    }

    public void dragOver(DropTargetDragEvent dtde) {
        if (isTransferableSweaveTag(dtde)) {
            System.out.println("drop match");
            dtde.acceptDrag(dtde.getDropAction());
        } else {
            System.out.println("drop no match");
            dtde.rejectDrag();
        }
    }

    public void drop(DropTargetDropEvent dtde) {// TODO Auto-generated method stub
      Transferable tr = dtde.getTransferable();
       
      try {
      DataFlavor[] flavors = tr.getTransferDataFlavors();
          for (int i = 0; i < flavors.length; i++) {
            if (tr.isDataFlavorSupported(flavors[i])) {
              dtde.acceptDrop(dtde.getDropAction());
              ISweaveTag swt = (ISweaveTag)tr.getTransferData(flavors[i]);
          //TODO: ohne string name
              JLatexPanel.addTagAtCursor(swt);
             
              System.out.println(swt.getName());
             
//              TreePath p = (TreePath) tr.getTransferData(flavors[i]);
//              DefaultMutableTreeNode node = (DefaultMutableTreeNode) p
//                  .getLastPathComponent();
//              DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
//              model.insertNodeInto(node, parent, 0);

              dtde.dropComplete(true);
              return;
            }
          }
            dtde.rejectDrop();
            } catch (Exception e) {
              e.printStackTrace();
              dtde.rejectDrop();
            }
   
     
   
   
           dtde.dropComplete(true);
   }

    public void dropActionChanged(DropTargetDragEvent dtde) {// TODO Auto-generated method stub
    }

    public boolean isTransferableSweaveTag(DropTargetDragEvent dtde) {
        for (DataFlavor df : dtde.getCurrentDataFlavorsAsList()) {
            System.out.println(df.getHumanPresentableName());
            System.out.println("Class: " + df.getRepresentationClass().toString());
            if (df.getRepresentationClass().equals(dao.ISweaveTag.class)) {
                return true;
            }
     
        }
        return false;
    }

  
}
TOP

Related Classes of gui.JLatexPanel$IndexPanel

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.