package de.nplusc.izc.tools.UiToolz;

//import javax.swing.plaf.synth.SynthLookAndFeel;
import com.sun.awt.AWTUtilities;
import de.nplusc.izc.tools.baseTools.RingBuffer;
import de.nplusc.izc.tools.baseTools.Tools;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.*;
import org.apache.commons.exec.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author LH
 */
public class cmdGUI extends javax.swing.JFrame
{
    //51,0:tab1
    //availSize=840:20
    
    /**
     * the definition of the Terminal-font
     */
    public static final Font term = new Font("Lucida Console",Font.BOLD,15);//Terminal
    /**
     * the color of the font
     */
    public static final Color FontColor = new Color(170,220,240,200);//Color(255, 0, 0, 128);
    /**
     * a constant color for transparent bgs
     */
    public static final Color TransBgColor = new Color(0, 0, 0, 0);
    /**
     * where the button is
     */
    public static final Polygon buttonPos = new Polygon(new int[]{27,73,85,152,155,209,229,168,12,6},new int[]{16,16,1,1,8,7,27,47,47,36},10);
    /**
     * instance-id
     */
    public final String id;
    /**
     * number ofTabs
     */
    public static final int tabCount = 4;
    /**
     * position of tabs
     */
    public static final Rectangle[]  tabs = new Rectangle[]
    {
        new Rectangle(50, 0, 200, 20), //0
        new Rectangle(250, 0, 200, 20),//1
        new Rectangle(450, 0, 200, 20),//2
        new Rectangle(650, 0, 200, 20) //3
    };
    /**
     * Instances of the GUI are stored here
     * its part of a hack
     */
    public static HashMap<String,cmdGUI> gac= new HashMap<>();//Part of a haxx
    //public static cmdGUI cgui=null;
    
    //public static boolean sa;
    //public static DefaultExecutor ex;
    //public static boolean bsfin = false;
    //##################################################################################################

    private ArrayList<RingBuffer<String>> screenBuf= new ArrayList<>();
    // /\ new RingBuffer<>(String.class,5000,"")
    // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
    // \/ new RingBuffer<>(String.class,5000,"noCmd")
    private ArrayList<RingBuffer<String>> cmdBuf=new ArrayList<>() ;//noCmd Detektor für leere Zeile
    private boolean[] sil = new boolean[4];
    private boolean[] tp = new boolean[3];
    private boolean[] isInCmd = new boolean[4];
    private String[] cmdForSend = new String[4];
    private String[] cmdInLine = new String[4];
    private int tabSelected=0;
    
    private int[] currLin = new int[]{0,0,0,0};

    private int[] uptypes=new int[]{0,0,0,0};
    private int[] upmax = new int[]{0,0,0,0};
    private boolean[] ud = new boolean[]{false,false,false,false};
    private boolean[] ud1 = new boolean[]{true,true,true,true};
    private JSlider js;
    private JLabel[] line;
    private JTextField ipline;
    private ExtendedJPanel Surface,ButtonArea,tabBar;
    private UIFileAccess guifile;//replace with loader and selection
    //private static String[] RingBuffer = new String[5000];#
    private boolean standalone = true;
    //private static int[] RingBufferCfg = new int[2];//null=pointer;1=previousElement
    

        // <editor-fold defaultstate="collapsed" desc="pflichcode">
    public String getCmdForSend(int targetTab)
    {
        return cmdForSend[targetTab];
    }
    public void setCmdForSend(String cmd,int targetTab)
    {
        this.cmdForSend[targetTab] = cmd;
    }
    public void setIsInCmd(boolean isInCmd,int targetTab)
    {
        this.isInCmd[targetTab] = isInCmd;
    }
    public boolean isStandalone()
    {
        return standalone;
    }

    public void setStandalone(boolean standalone)
    {
        this.standalone = standalone;
    }
        // </editor-fold>
    
    
    //baseOffs=200|120
    //size=960*480
    @SuppressWarnings("CallToThreadDumpStack")
    public cmdGUI(UIFileAccess g) 
    {
        super();//HAX;tst.needd
        guifile=g;
        try 
        {
            if(guifile.zipBased)
            {
            setIconImage(ImageIO.read(guifile.loadFileFromZip(guifile.ResourceURLs.get("icon"))));
            }
            else
            {
                setIconImage(ImageIO.read(new File(guifile.ResourceURLs.get("icon"))));
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        for(int i=0;i<tabCount;i++)
        {
            RingBuffer<String>rb = new RingBuffer<>(String.class,5000,"");
            screenBuf.add(rb);
            rb = new RingBuffer<>(String.class,5000,"noCmd");
            cmdBuf.add(rb);
        }
        id= this.toString();
        System.err.println(id);
        Tools.DebugHelperPrint(id, true, "Toolkit.enableCoreDebug");
        this.setUndecorated(true);
        //initComponents();
        buildGUI();
        tp[1] = AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.PERPIXEL_TRANSLUCENT);
        //cgui=this;//hack
        gac.put(id,this);
        if(tp[1])
        {
            AWTUtilities.setWindowOpaque(this, false);
            //AWTUtilities.
        }
        //Point p = this.getLocation();//
        //p.setLocation();     //Setzt Fenster an Zielkkordinaten
        this.setLocation(guifile.windowBasePoint);    
        //ButtonArea.setLocation(630, 432);
  
        //this.revalidate();
        //630;432==Button
    }

    
    /**
     * the Form initializer
     */
    private void buildGUI()
    {
        int[] wincfg = guifile.windowSize;
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(wincfg[0], wincfg[1]));
        setPreferredSize(new java.awt.Dimension(wincfg[0], wincfg[1]));
        Container cp = getContentPane();
        cp.setLayout(null);
        
        Surface = new ExtendedJPanel(1,guifile);
        Surface.setBounds(0,0,wincfg[0], wincfg[1]);
        Surface.setLayout(null);
        cp.add(Surface);
        /*addToSurface*/
      //{
        /*
         MysteryError.
         There was no Constructor-CAll anywhere
          a
           cmdGUI[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder@106def2,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
        ???
        Exception in thread "AWT-EventQueue-0" java.lang.VerifyError: Constructor must call super() or this() before return in method FontEngine.<init>()V at offset 0
	at cmdGUI.buildGUI(cmdGUI.java:178)
	at cmdGUI.<init>(cmdGUI.java:139)
	at cmdGUI$9$1.run(cmdGUI.java:1047)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
	at java.awt.EventQueue.access$000(EventQueue.java:101)
	at java.awt.EventQueue$3.run(EventQueue.java:666)
	at java.awt.EventQueue$3.run(EventQueue.java:664)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
         */
        
            int[]tbc = guifile.tabBarPos;
            tabBar = new ExtendedJPanel(3,guifile);
            tabBar.setBounds(tbc[0],tbc[1],tbc[2],tbc[3]);
            tabBar.initOVL();
            updateTabBarMessages(0);
            
            Surface.add(tabBar);
            int[] lcf = guifile.lineCfg;
        
        
            js = new JSlider(0, 5000-lcf[3]);//H@XX
            js.setInverted(true);
            js.setOrientation(SwingConstants.VERTICAL);
            js.setUI(new HoloSliderUi(js));
            js.setOpaque(false);
            int[] scfg = guifile.ScrollBar;
            js.setBounds(scfg[0],scfg[1],scfg[2],scfg[3]);
            Surface.add(js);
        
            ButtonArea = new ExtendedJPanel(2,guifile);//ExtebdeedJPanel(2);
            //ButtonArea.setLocation(630, 432);
            int[] bacfg = guifile.buttonPanel;
            ButtonArea.setBounds(bacfg[0],bacfg[1],bacfg[2],bacfg[3]);
           // ButtonArea.setBounds(630,432,233,48);
            Surface.add(ButtonArea);
            
            int[] ipc = guifile.ipLineArea;
            ipline = new JTextField();
            ipline.setBounds(ipc[0],ipc[1],ipc[2],ipc[3]);
            ipline.setBorder(null);
            ipline.setOpaque(false);
            ipline.setFont(term);
            ipline.setForeground(FontColor);
            ipline.setBackground(TransBgColor);
            Surface.add(ipline);
            
            int lmx = guifile.lineCount;
            line = new JLabel[lmx];
            // <editor-fold defaultstate="collapsed" desc="Altlast">
            /*
            * Disabled old variant
            * JLabel line2 = new JLabel();
            * JLabel line3 = new JLabel();
            * JLabel line4 = new JLabel();
            * JLabel line5 = new JLabel();
            * JLabel line6 = new JLabel();
            * JLabel line7 = new JLabel();
            * JLabel line8 = new JLabel();
            * JLabel line9 = new JLabel();
            * JLabel line10 = new JLabel();
            * JLabel line11 = new JLabel();
            * JLabel line12 = new JLabel();
            * JLabel line13 = new JLabel();
            * JLabel line14 = new JLabel();
            * JLabel line15 = new JLabel();
            */
            //</editor-fold>
            //for( int i=0,i<tabCount,i++)
            //{
                for (int i=0;i<lmx;i++)
                {
                    JLabel linel = line[i];
                    linel = new JLabel();
                    linel.setFont(term);
                    //line1.setOpaque(true);//Fliegenklatsche

                    linel.setForeground(FontColor);
                    //linel.setText("test.lm("+i+")");
                    if(i==13)
                    {
                        //linel.setText("llll.lm("+i+")");
                    }
                    linel.setBounds(lcf[0], lcf[1]+i*lcf[3], lcf[2], lcf[3]);
                   // if(k==0)//KEin I hier!!!!!!!!!
                   // {
                        Surface.add(linel);
                        //Surface.remove()
                    //}
                    line[i]=linel;
                }
          //}

      //}
       // MouseMotionAdapter MMA = ;
        ButtonArea.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                ButtonAreaHover(evt,false);
            }
        });
        ipline.addKeyListener(new java.awt.event.KeyAdapter()
        {

            @Override
            public void keyPressed(java.awt.event.KeyEvent evt)
            {
                keyPressAtIpLine(evt);
                
            }
        });
        ButtonArea.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ButtonAreaClicked(evt);
            }
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                ButtonAreaHover(evt,true);
            }
            
            @Override
            public void mouseExited(java.awt.event.MouseEvent evt)
            {
                ButtonAreaHover(evt,true);
            }
            
        });
                js.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            @Override
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                refreshLines(evt,tabSelected);
            }
        });
        tabBar.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TabBarClicked(evt);
            }/*
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                ButtonAreaHover(evt,true);
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt)
            {
                ButtonAreaHover(evt,true);
            }*/
            
        });
        //js.
        //54,412:Po:Sizs
        //860*17
        Surface.repaint();
        cp.repaint();
        cp.revalidate();

    }
    
    /**
     * Handeles the Glow
     * @param evt mouse pos
     * @param forceX1t override
     */
    private void ButtonAreaHover(java.awt.event.MouseEvent evt,boolean forceX1t)
    {
        if(buttonPos.contains(evt.getPoint())&&!forceX1t)
        {
            ButtonArea.cmdButtonGlow(true);
        }
        else
        {
            ButtonArea.cmdButtonGlow(false);
        }
        ButtonArea.repaint(/*null*/);//niemals nullen
    }
    /**
     * @see ButtonAreaClicked(evt,entered)
     * @param evt 
     */
    private void ButtonAreaClicked(java.awt.event.MouseEvent evt)
    {
        ButtonAreaClicked(evt,false);
    }
    
    
    /**
     * the Tab-Bar event handler
     * @param evt ClickEvent
     */
    private void TabBarClicked(java.awt.event.MouseEvent evt)
    {
        cmdInLine[tabSelected] = ipline.getText();
        for (int i = 0; i < tabs.length; i++)
        {
            Rectangle r = tabs[i];
            if(r.contains(evt.getPoint()))
            {
                tabSelected=i;
            }
        }
        refreshLines(evt, tabSelected);
        refreshCmd();
        updateTabBarMessages(tabSelected);
        Surface.repaint();
    }
    /**
     * Handles the addit features of IpLine;
     * @param evt keypress
     */
    public void keyPressAtIpLine(java.awt.event.KeyEvent evt)
    {
        int kc = evt.getKeyCode();
        if(kc==KeyEvent.VK_ENTER)
        {
            //Tools.dlg(true,"Enter","...");
            ButtonAreaClicked(new java.awt.event.MouseEvent(Surface, kc, kc, 0, kc, kc, 0, true),true);
            //^No NPX here^\\
            
        }
        if(kc==KeyEvent.VK_UP)
        {
            if(!ud[tabSelected]&&!ud1[tabSelected])
            {
                uptypes[tabSelected]++;
            }
            ud1[tabSelected]=false;
            ud[tabSelected]=true;
            int get = upmax[tabSelected]-(uptypes[tabSelected]+1);
            //System.err.println("uptypes|"+uptypes);
            if(get>=0&&!(uptypes[tabSelected]>upmax[tabSelected]))
            {
                String ldcmd = cmdBuf.get(tabSelected).getContentAt(get);
                Tools.DebugHelperPrint("get|"+get, true, "Toolkit.enableFinerDebug");
                if(!ldcmd.equals("noCmd"))
                {
                    uptypes[tabSelected]++;
                    ipline.setText(ldcmd);
                }
            }

        }
        if(kc==KeyEvent.VK_DOWN)
        {
            /*
            if(uptypes>0)
            {
                uptypes--;
            }
            if(uptypes>=0)
            {
                            int get = upmax-(uptypes+1);
            if(!(get<0))
            {
                get=0;
            }
            String ldcmd = cmdBuf.getContentAt(get);
                ipline.setText(ldcmd);
            }
            else
            {
                ipline.setText(ipline.getText());
            }*/
            if(ud[tabSelected])
            {
                uptypes[tabSelected]--;
            }
            ud[tabSelected]=false;
            uptypes[tabSelected]--;
            if(uptypes[tabSelected]<0)
            {
                uptypes[tabSelected]++;
            }     
            int get = upmax[tabSelected]-(uptypes[tabSelected]+1);
            Tools.DebugHelperPrint("uptypes|"+uptypes, true, "Toolkit.enableFinerDebug");
            if(get>=0&&!(uptypes[tabSelected]>upmax[tabSelected]))
            {
                String ldcmd = cmdBuf.get(tabSelected).getContentAt(get);
                Tools.DebugHelperPrint("get|"+get, true, "Toolkit.enableFinerDebug");
                if(!ldcmd.equals("noCmd"))
                {
                    //uptypes++;
                    ipline.setText(ldcmd);
                }
            }

        }
    }
    
    /**
     * Handles Button
     * @param evt where clicked
     * @param entered if enter key pressed
     */
    @SuppressWarnings("CallToThreadDumpStack")
    private void ButtonAreaClicked(java.awt.event.MouseEvent evt,boolean entered)//für Enter-Eingabe
    {
        if(buttonPos.contains(evt.getPoint())||entered)
        {
            cmdBuf.get(tabSelected).addItem(ipline.getText());
            if(upmax[tabSelected]<5000)
            {
                upmax[tabSelected]++;
            }
            uptypes[tabSelected]=0;
            Tools.DebugHelperPrint("tabForTrg|"+tabSelected+"|"+isInCmd[tabSelected], true, "Toolkit.enableFinerDebug");
            if(!isInCmd[tabSelected])
            {
                runCmd();
            }
            else
            {
                Tools.DebugHelperPrint("toCmdatTab|"+tabSelected+"|"+isInCmd[tabSelected], true, "Toolkit.enableFinerDebug");
            
                String t = ipline.getText();
                if(t == null)
                {
                    t = "";
                }
                if(t.equals(""))
                {
                    t=" ";
                }
                ipline.setText("");
                cmdForSend[tabSelected]=t;
                if(t.equals("exit")&&standalone)
                {
                    try
                    {
                        Thread.sleep(200);
                        cmdForSend[tabSelected]=" ";//HAKK
                    }
                    catch (InterruptedException exc)
                    {
                        exc.printStackTrace();
                    }
                           
                }
            }
        }
    }
     
    /**
     * reloads the command of previous tab
     */
    private void refreshCmd()//ynchroniszeUpTypes()
    {
        ipline.setText(cmdInLine[tabSelected]);
    }
    
    /**
     * This method is not called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    
    public void updateTabBarMessages(int targetTab)
    {
           /* tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_T, 50, 0);
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_A, 70, 0);
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_B, 90, 0);
            
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_A, 130, 0);
            
            
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_T, 250, 0);
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_A, 270, 0);
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_B, 290, 0);
            
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_B, 330, 0);
            
            
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_T, 450, 0);
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_A, 470, 0);
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_B, 490, 0);
            
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_C, 530, 0);
            
            
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_T, 650, 0);
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_A, 670, 0);
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_B, 690, 0);
            
            tabBar.setLetter(FontEngine.FONT_LAUNCHPAD, FontEngine.LETTER_D, 630, 0);
            */
            //marker for active Tab
            tabBar.initOVL();
            tabBar.setLetter(FontEngine.FONT_DECEPTICON_GRAFFITTI,FontEngine.LETTER_N,
                    (targetTab*200)+150,0);
            tabBar.repaint();
                    
            
            
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(960, 480));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 964, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 516, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

        /**
     * runs the cmd which is in the ipLine
     */
    public void runCmd()
    {

        final String cmd = ipline.getText();
        addLine(cmd,tabSelected);
        ipline.setText("");
        Tools.DebugHelperPrint("cmdLoaded|"+cmd+"|"+tabSelected, true, "Toolkit.enableFinerDebug");
            
        if(cmd.equals("quit"))
        {
            System.exit(0);
        }
        //runCode here;
        Thread t = new Thread(new Runnable()
        {
            
            //@SuppressWarnings("SleepWhileInLoop")//Hx
            @SuppressWarnings("CallToThreadDumpStack")
            @Override
            public void run()
            {
                Tools.DebugHelperPrint("cmdLoaded2|"+cmd+"|"+tabSelected, true, "Toolkit.enableFinerDebug");
                runCmd(cmd);
            }
       });
       t.start();
        
    }
    
    /**
     * Runs a cmd and sets inCmd mode.
     * 
     * @param args the command line arguments
     */
    @SuppressWarnings("CallToThreadDumpStack")
    public void runCmd(String cmd)//synchronized gint nen fetten Bug
    {
        final HashMap<Integer,Object> t = new HashMap<>();
        int belongingTab = tabSelected;
        t.put(0,belongingTab);
        Tools.DebugHelperPrint("cmd|"+belongingTab, true, "Toolkit.enableFinerDebug");
        cmdGUI cG = this;
        String[] cmdp = cmd.split(" ");
       // BufferedInputStream log = new BufferedInputStream
       // (
       //     new ByteArrayInputStream(new byte[]{0})
       // );//das einzelne Byte ist n(ö|ä)tig um ne NPX zu verhindern
        
        ExecuteStreamHandler s;
        final DefaultExecuteResultHandler devnull = new DefaultExecuteResultHandler();
       /* {

            @Override
            public void onProcessComplete(int exitValue)
            {
                System.err.println("fin");
                cmdGUI.sil=false;
                cmdGUI.cgui.setIsInCmd(false);
            }

            @Override
            public void onProcessFailed(ExecuteException e)
            {
                System.err.println("Urrgs");
                cmdGUI.sil=false;
                cmdGUI.cgui.setIsInCmd(false);
            }
        };*/
        String[] fexg = cmd.split("\\.");
        Tools.DebugHelperPrint(cmd, true, "Toolkit.enableFinerDebug");
        Tools.DebugHelperPrint("cmd2|"+belongingTab, true, "Toolkit.enableFinerDebug");
        if(fexg[fexg.length-1].equalsIgnoreCase("bat")||cmd.equals("dir"))
        {
            cmd = "cmd.exe /c "+cmd;
            Tools.DebugHelperPrint("cmdtrigger", true, "Toolkit.enableFinerDebug");
        }
        CommandLine cl = CommandLine.parse(cmdp[0]);
        for (int i = 1; i < cmdp.length; i++)
        {
            cl.addArgument(cmdp[i]);
        }
        Executor e = new DefaultExecutor();
        //ex=(DefaultExecutor)e;
        try
        {
            setIsInCmd(true,(int)t.get(0));
            final PipedInputStream in = new PipedInputStream();
            PipedOutputStream out = new PipedOutputStream();
            final PipedOutputStream txOut = new PipedOutputStream();
            PipedInputStream txIn = new PipedInputStream();
            Tools.DebugHelperPrint("cmd3|"+belongingTab, true, "Toolkit.enableFinerDebug");
            
            txIn.connect(txOut);
            out.connect(in);
           // txOut.write((byte)0);//??//
            //System.err.pri
            s = new PumpStreamHandler(out,out,txIn);
            //final OutputStream txOut = ((DefaultExecutor)e).stdin;
           // i.
            
            //s.setProcessOutputStream(log);
            Tools.DebugHelperPrint("???", true, "Toolkit.enableFinerDebug");
            e.setStreamHandler(s);
            
            //^HAck da sonst zwodeitich//VOID
            Tools.DebugHelperPrint("Wennhier was ist...", true, "Toolkit.enableFinerDebug");
            
            //log.


            //cG.
            sil[(int)t.get(0)]=true;
            Tools.DebugHelperPrint("cmd4|"+belongingTab, true, "Toolkit.enableFinerDebug");
            /*new Thread(new Runnable()
            {
                @Override
                @SuppressWarnings("SleepWhileInLoop")
                public void run()
                {
                   // while(!devnull.hasResult())
                   // {
                        try
                        {
                            ex.p.waitFor();
                            Thread.sleep(50);
                            //System.err.println("AA");
                        }
                        catch (InterruptedException ex)
                        {
                            ex.printStackTrace();
                        }
                              
                    //}
                    System.err.println("fin");
                    cmdGUI.sil=false;
                    cmdGUI.cgui.setIsInCmd(false);
                    System.err.println("Wr");
                    System.setProperty("fin", "true");
                }
            }).start();*/
            new Thread(new Runnable()
            {
                cmdGUI cG =cmdGUI.gac.get(id);
                //BufferedOutputStream txOut=(BufferedOutputStream)((DefaultExecutor)ex).getStdin();

                
                @Override
                @SuppressWarnings({"SleepWhileInLoop", "SleepWhileInLoop"})
                public void run()
                {
                   while(sil[(int)t.get(0)])
                   {
                       // try
                       // {
                            //txOut.write("x\b".getBytes());
                            //txOut.flush();
                             String chk = cG.getCmdForSend((int)t.get(0));
                          //   System.err.println(chk);
                             Tools.DebugHelperPrint(chk, true, "Toolkit.enableFinerDebug");
                             if(chk==null)
                             {
                                 chk="";
                             }
                             //if((!System.getProperty("fin", "lm").equals("lm")))
                             //{
                              //       System.clearProperty("fin");
                              //       chk="\r";
                             //}
                             if(!chk.equals(""))
                             {

                                 try
                                 {
                                     chk+="\n";
                                     //o=txOut
                                     txOut.write(chk.getBytes());
                                     txOut.flush();
                                     //System.err.println(">>"+chk);
                                     Tools.DebugHelperPrint(">>"+chk, true, "Toolkit.enableFinerDebug");
                                     //in.mark(1);
                                     //in.reset();Funzen nicht;
                                 }
                                 catch (IOException ex)
                                 {
                                     ex.printStackTrace();
                                 }
                                 cG.setCmdForSend(null,(int)t.get(0));//Nicht vergessen.sonst Bugschleuder
                                 chk=null;
                             }
                             Tools.wait(50);
                                    
                       //  }
                        //catch (IOException ex)
                       // {
                        //    System.err.println("Kakk");
                       //     ex.printStackTrace();
                       // }
                               
                    }
                }
                }).start();
            new Thread(new Runnable()
            {
                cmdGUI cG =cmdGUI.gac.get(id);
                @Override
                public void run()
                {
                    try
                    {
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        //String s2 = br.readLine();
                        //if(in.)
                        while(sil[(int)t.get(0)])
                        {
                            while (in.available()>0)//||(cmdGUI.sil))
                            {
                                byte rb = (byte) in.read();
                                String ln = ""+(char)rb;
                                //in.
                                rb = (byte) in.read();
                                Tools.DebugHelperPrint((char)rb+"|"+0, true, "Toolkit.enableFinerDebug");
                                int i=0;
                                while(((char)rb!='\n')&&((char)rb!='>'))
                                {
                                    ln +=(char)rb;
                                 //   System.err.println((char)rb+"|"+i+1);
                                    Tools.DebugHelperPrint((char)rb+"|"+i+1, true, "Toolkit.enableFinerDebug");
                                
                                    rb = (byte) in.read();//DONOTFORGET!!!!!
                                 //   System.err.println((char)rb+"|"+i+2);
                                    Tools.DebugHelperPrint((char)rb+"|"+i+2, true, "Toolkit.enableFinerDebug");
                                
                                    i++;
                                }
                                if((char)rb=='>')
                                {
                                    ln+=">";
                                }
                                cG.addLine(ln,(int)t.get(0));
                                 Tools.DebugHelperPrint("trg2|"+(int)t.get(0), true, "Toolkit.enableFinerDebug");
                                
 
                                  Tools.DebugHelperPrint(ln, true, "Toolkit.enableFinerDebug");
                                
                                //s2 = br.readLine();
                                   Tools.DebugHelperPrint("Fotze", true, "Toolkit.enableFinerDebug");
                                
                            }
                            Tools.wait(50);
                        }
                         Tools.DebugHelperPrint("Hira?",true, "Toolkit.enableFinerDebug");
                                
                    }
                    catch (IOException ex)
                    {
                        ex.printStackTrace();
                    }
                    cG.setIsInCmd(false,(int)t.get(0));
                }
            }).start();
            Tools.DebugHelperPrint("X XX|"+(int)t.get(0), true, "Toolkit.enableFinerDebug");
            try{
            e.execute(cl/*,devnull*/);//HACKALERT
            }
            catch (org.apache.commons.exec.ExecuteException exc)
            {
                //Do nothing. Cmd steigt ja bei Error auch nicht aus
                //exc.printStackTrace();
            }
            Tools.DebugHelperPrint("fin", true, "Toolkit.enableFinerDebug");
            
            sil[(int)t.get(0)]=false;
            
            cG.setIsInCmd(false,(int)t.get(0));
            if(standalone)
            {
                if(gac.size()<=1)
                {
                System.exit(0);
                }
                else
                {
                    gac.get(id).setVisible(false);
                    gac.remove(id);
                }
            }
            
        }
        catch (ExecuteException exc)
        {
            exc.printStackTrace();
        }
        catch (IOException exc)
        {
            exc.printStackTrace();
        }
        Tools.DebugHelperPrint("FIN", true, "Toolkit.enableFinerDebug");
        //sil=false;
    }
    
    /**
     * runs a cmd in a specific tab
     * @param cmd the command to run
     * @param targetTab the tab in which it should run
     * @throws Error when the parameter is out od range (<0 or >4)
     *  and exits the current console
     */
    public void runCmd(String cmd,int targetTab)
    {
        if(targetTab<0||targetTab>4)
        {
            Tools.DebugHelperPrint("xyxyx", true, "Toolkit.enableCoreDebug");
            gac.put(id,null);
            this.setVisible(false);
            this.dispose();
           throw new Error("The tabCount has to be >=0 and <=4");
           
        }
        tabSelected = targetTab;
        runCmd(cmd);
        updateTabBarMessages(targetTab);
    }

    
    /**
     * updates the shown lines
     * @param evt currently igged
     */
    public void refreshLines(java.awt.event.MouseEvent evt,int targetTab)
    {
        Tools.DebugHelperPrint("refreshAt|"+targetTab, true, "Toolkit.enableFinerDebug");
        Tools.DebugHelperPrint(js.getValue()+"", true, "Toolkit.enableFinerDebug");
        int os = js.getValue();
        RingBuffer<String> lb = screenBuf.get(targetTab);
        for(int i=0;i<line.length;i++)
        {
            JLabel linew = line[i];
            String tx = lb.getContentAt(os+i);
            linew.setText(tx);
            
        }
        //Surface.revalidate();
        //Surface.repaint();
    }
    
    /**
     * Adds a line to the Screen
     * @param cmd the line to add 
     */
    public void addLine(String cmd,int targetTab)
    {
        Tools.DebugHelperPrint(cmd+"|"+targetTab, true, "Toolkit.enableFinerDebug");
        RingBuffer<String> lb = screenBuf.get(targetTab);
        lb.addItem(cmd);//CMD here
        
        if(currLin[targetTab]<5000)
        {
            currLin[targetTab]++;
        }
        int setLin;
        setLin=currLin[targetTab]-line.length;
        if(currLin[targetTab]<0)
        {
            setLin=0;
        }
        js.setValue(setLin);
        refreshLines(null,targetTab);
        
        
        /*
        if(linPos==line.length-1)
        {
            
            int ip = 1;
            for (int i = 1; i < line.length-1; i++)
            {
                line[i].setText(line[i+1].getText());
                ip=i;
            }
            line[ip].setText(cmd);
        }
        else
        {
            
            line[linPos].setText(cmd);
            linPos++;
        }*/
    }
    
  //  public static void main(final String args[])
  //  {
  //      main2(args);
  //  }
    /**
     * Main procedure for intenal use only
     * @param args The command lie args of this proggy
     */
   @SuppressWarnings({"CallToThreadDumpStack", "SleepWhileInLoop"})
    public static void main2(final String args[])//musste MethodenSig ändern wg final
    {
        //if(true)
        //{
            /*
                try
                {
                //  File f = new File();
                    System.err.println();
                }
                catch (URISyntaxException ex)
                {
                    ex.printStackTrace();
                }
                return;*/
        //}
        new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                final HashMap<Integer, Object> t = new HashMap<>();
                t.put(0, false);
                //final HashMap<Integer,Boolean> t = new HashMap<>();
                String cmd = "cmd";
                // boolean sa=false;
                if (args.length > 0)
                {
                    Tools.DebugHelperPrint("1", true, "Toolkit.enableFinerDebug");
                    if ((args[0].equals("--cmd")) || (args[0].equals("--standalone")))
                    {
                        Tools.DebugHelperPrint("12", true, "Toolkit.enableFinerDebug");
                        //sa=false;
                        if (args.length > 1)
                        {
                            Tools.DebugHelperPrint("123", true, "Toolkit.enableFinerDebug");
                            t.put(3,true);
                            cmd = args[1];
                        }
                        else
                        {
                            Tools.DebugHelperPrint("123e", true, "Toolkit.enableFinerDebug");
                            t.put(3,true);
                            cmd = "cmd";
                        }
                    }
                    else
                    {
                        Tools.DebugHelperPrint("12e", true, "Toolkit.enableFinerDebug");
                        t.put(3,false);
                    }
                }
                else
                {
                    Tools.DebugHelperPrint("1e", true, "Toolkit.enableFinerDebug");
                    t.put(3,true);
                }
                t.put(2, cmd);
                /*
                 * Set the Nimbus look and feel
                 */
                //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
                 * If Nimbus (introduced in Java SE 6) is not available, stay
                 * with the
                 * default look and feel.
                 * For details see
                 * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
                 */
                try
                {
                    Icon icon = new ImageIcon("C:/users/LH/Desktop/jp/GUI-File-CMD-IP-SLDR.png");
                    UIDefaults defaults = UIManager.getDefaults();
                    defaults.put("Slider.verticalThumbIcon", icon);
                    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
                    {
                        if ("Nimbus".equals(info.getName()))
                        {
                            javax.swing.UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }/*
                     * SynthLookAndFeel laf = new SynthLookAndFeel();
                     * laf.load(new File("SynthSlider.xml").toURI().toURL());
                     * javax.swing.UIManager.setLookAndFeel(laf);
                     */
                }
                catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException exc)
                {/*
                     * IOException|java.net.MalformedURLException|
                     */
                    //java.util.logging.Logger.getLogger(cmdGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

                }
                // Icon icon = new ImageIcon("C:/users/LH/Desktop/jp/GUI-File-CMD-IP-SLDR.png");
                // UIDefaults defaults = UIManager.getLookAndFeelDefaults();
                // defaults.put("Slider.verticalThumbIcon", icon);
                // Slider.


                //C:/users/LH/Desktop/jp/GUI-File-CMD-IP-SLDR.png
                //</editor-fold>

                /*
                 * Create and display the form
                 */

                java.awt.EventQueue.invokeLater(new Runnable()
                {

                    @Override
                    public void run()
                    {
                        cmdGUI g = new cmdGUI(new UIFileAccess(/**/de.nplusc.izc.tools.UIToolz.rsrc.UIFile.class));
                                //
                        /*Ü*//*new File("C:\\Users\\LH\\Desktop\\jp\\uiexamole\\ui.zip")));*/
                        g.setVisible(true);
                        if (((boolean) t.get(3)))
                        {
                            Tools.DebugHelperPrint("sacall2", true, "Toolkit.enableFinerDebug");
                            g.setStandalone(true);
                        }//V:HAXX
                        t.put(1, g);/*
                         * bsfin=true;
                         */
                        t.put(0, true);/*
                         * new Thread(new Runnable()
                         * {
                         * @Override
                         * public void run()
                         * {
                         *
                         *
                         * }
                         *
                         * }).start();
                         */

                    }
                });//Dieser Häck funzt nur in main()!!!!!//VOID
                while (!((boolean) t.get(0)))//Hack
                {
                    try
                    {
                        Thread.sleep(50);
                    }
                    catch (InterruptedException exc)
                    {
                        exc.printStackTrace();
                    }
                }
                try         //BUG-ALERT:HACK_USED
                {           //REQUIRED da sonst Deadlock...
                    //vermutlich ne Race-Condition...
                    //ergibt nämlich nen fetten Hänger...
                    Thread.sleep(500);
                }
                catch (InterruptedException exc)
                {
                    exc.printStackTrace();
                }
                if (((boolean)t.get(3)))
                {
                    Tools.DebugHelperPrint("sacall2", true, "Toolkit.enableFinerDebug");
                    // cmdGUI.cgui.runCmd(cmd);
                    ((cmdGUI) t.get(1)).runCmd((String)t.get(2));
                }
            }
        }).start();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
