/*
 * KJASSwingConsole.java
 *
 * Created on 15. Mai 2002, 23:43
 */

package org.kde.kjas.server;
import java.awt.Toolkit;
import java.awt.Image;
import java.util.Enumeration;
import java.util.Properties;

/**
 *
 * @author  till
 */
public class KJASSwingConsole extends javax.swing.JFrame implements Console {
    
    /** Creates new form KJASSwingConsole */
    public KJASSwingConsole() {
        initComponents();
        setSize(500, 300);

        java.io.PrintStream st = new java.io.PrintStream( new KJASConsoleStream(this) );
        System.setOut(st);
        System.setErr(st);
        try {
            java.net.URL iconUrl = getClass().getClassLoader().getResource("images/beanicon.png");
            if (iconUrl != null) {
                Toolkit tk = Toolkit.getDefaultToolkit();
                Image icon = tk.createImage(iconUrl);
                setIconImage(icon);
            }
        } catch (Throwable e) {
        }
        System.out.println( "Java VM version: " +
                            System.getProperty("java.version") );
        System.out.println( "Java VM vendor:  " +
                            System.getProperty("java.vendor") );
        String ph = System.getProperty("http.proxyHost");
        String pp = System.getProperty("http.proxyPort");
        if (ph != null) {
            System.out.println("Proxy: " + ph + ":" + pp);
        }
        SecurityManager sec = System.getSecurityManager();
        Main.debug("SecurityManager=" + sec);
        if (sec == null) {
            System.out.println( "WARNING: Security Manager disabled!" );
            textField.setForeground(java.awt.Color.red);
        }
        showHelp();
    }
    
    /** This method is 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.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        jPanel1 = new javax.swing.JPanel();
        clearButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();
        copyButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textField = new javax.swing.JTextArea();

        setTitle("Konqueror Java Console");
        setFont(new java.awt.Font("Monospaced", 0, 10));
        setName("KJAS Console");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel1.setBorder(new javax.swing.border.EmptyBorder(new java.awt.Insets(1, 1, 1, 1)));
        clearButton.setText("clear");
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });

        jPanel1.add(clearButton, java.awt.BorderLayout.WEST);

        closeButton.setText("close");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        jPanel1.add(closeButton, java.awt.BorderLayout.EAST);

        copyButton.setText("copy");
        copyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyButtonActionPerformed(evt);
            }
        });

        jPanel1.add(copyButton, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);

        textField.setColumns(40);
        textField.setEditable(false);
        textField.setRows(10);
        textField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textFieldKeyPressed(evt);
            }
        });

        jScrollPane1.setViewportView(textField);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pack();
    }//GEN-END:initComponents

    private void textFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldKeyPressed
        // Add your handling code here:
        char key = evt.getKeyChar();
        switch (key) {
            case 'h':
                showHelp();
                break;
            case 'g':
                append("Running Garbage Collection ...\n", true);
                System.gc();
            case 'm': 
                append("Total Memory: " + Runtime.getRuntime().totalMemory() + " bytes\n", true); 
                append("Free Memory : " + Runtime.getRuntime().freeMemory() + " bytes\n", true);
                break;
            case 'c':
                clear();
                break;
            case 's':
                showSystemProperties();
                break;
            case 't':
                showThreads();
                break;
            case 'x':
                KJASAppletClassLoader.removeLoaders();
                append("Emptied Classloader Cache\n", true);
                break;
        }
    }//GEN-LAST:event_textFieldKeyPressed

    private void showHelp() {
        append("Java VM: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + "\n", true);
        String ph = System.getProperty("http.proxyHost");
        if (ph != null) {
            append("Proxy: " + ph + ":" + System.getProperty("java.proxyPort") + "\n", true);
        }
        SecurityManager sec = System.getSecurityManager();
        if (sec == null) {
            append("WARNING: Security Manager disabled!\n", true);
        } else {
            append("SecurityManager=" + sec + "\n", true);
        }
        appendSeparator();
        append("Konqueror Java Console Help\n", true);
        append("  c: clear console\n", true);
        append("  g: run garbage collection\n", true);
        append("  h: show help\n", true);
        append("  m: show memory info\n", true);
        append("  s: print system properties\n", true);
        append("  t: list threads\n", true);
        append("  x: empty classloader cache\n", true);
        appendSeparator();
    }

    private void showSystemProperties() {
        append("Printing System Properties ...\n", true);
        appendSeparator();
        Properties p = System.getProperties();
        for (Enumeration e = p.keys(); e.hasMoreElements();) {
            Object key = e.nextElement();
            if ("line.separator".equals(key)) {
                String value = (String) p.get(key);
                StringBuffer unescaped = new StringBuffer(10);
                for (int i = 0; i < value.length(); i++) {
                    char c = value.charAt(i);
                    if (c == '\n') unescaped.append("\\n");
                    else if (c == '\r') unescaped.append("\\n");
                    else unescaped.append(c);
                }
                append(key + " = " + unescaped + "\n", true);
            } else append(key + " = " + p.get(key) + "\n", true);
        }
        appendSeparator();
    }

    private void showThreads() {
        Thread t = Thread.currentThread();
        ThreadGroup g = t.getThreadGroup();
        ThreadGroup parent;
        while ((parent = g.getParent()) != null) {
            g = parent;
        }
        g.list();
    }

    private void copyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyButtonActionPerformed
        // Add your handling code here:
        textField.selectAll();
        textField.copy();
    }//GEN-LAST:event_copyButtonActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        // Add your handling code here:
        setVisible(false);
    }//GEN-LAST:event_closeButtonActionPerformed

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
        // Add your handling code here:
        clear();
    }//GEN-LAST:event_clearButtonActionPerformed
    
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        setVisible(false);
    }//GEN-LAST:event_exitForm
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        new KJASSwingConsole().setVisible(true);
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton clearButton;
    private javax.swing.JTextArea textField;
    private javax.swing.JButton closeButton;
    private javax.swing.JButton copyButton;
    // End of variables declaration//GEN-END:variables

    public void clear() {
        textField.setText("");
    }

    private void appendSeparator() {
        append("----------------------------------------------------\n", true);
    }

    public void append(String txt) {
        append(txt, false);
    }
    
    public void append(String txt, boolean force) {
        if (txt == null || (!force && !isVisible())) {
            return;
        }
        int length = txt.length();
        synchronized(textField) {
            //get the caret position, and then get the new position
            int old_pos = textField.getCaretPosition();
            textField.append(txt);
            textField.setCaretPosition( old_pos + length );
        }
    }
}

