001    /* $Id: IOPane.java 102 2007-11-05 11:28:41Z ringler $
002     * This class is part of the de.mospace.swing library.
003     * Copyright (C) 2005-2006 Moritz Ringler
004     *
005     * This program is free software; you can redistribute it and/or
006     * modify it under the terms of the GNU General Public License
007     * as published by the Free Software Foundation; either version 2
008     * of the License, or (at your option) any later version.
009     *
010     * This program is distributed in the hope that it will be useful,
011     * but WITHOUT ANY WARRANTY; without even the implied warranty of
012     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013     * GNU General Public License for more details.
014     *
015     * You should have received a copy of the GNU General Public License
016     * along with this program; if not, write to the Free Software
017     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
018     */
019    package de.mospace.swing;
020    
021    import java.awt.Color;
022    import java.util.logging.Logger;
023    import java.awt.Component;
024    import java.awt.GridBagConstraints;
025    import java.awt.GridBagLayout;
026    import java.awt.event.ActionEvent;
027    import java.awt.event.ActionListener;
028    import java.awt.event.FocusEvent;
029    import java.awt.event.FocusListener;
030    import java.awt.event.KeyAdapter;
031    import java.awt.event.KeyEvent;
032    import java.util.Vector;
033    import javax.swing.BorderFactory;
034    import javax.swing.BoundedRangeModel;
035    import javax.swing.JLabel;
036    import javax.swing.JPanel;
037    import javax.swing.JScrollPane;
038    import javax.swing.JTextArea;
039    import javax.swing.JTextField;
040    import javax.swing.SwingUtilities;
041    import javax.swing.border.Border;
042    import javax.swing.event.ChangeEvent;
043    import javax.swing.event.ChangeListener;
044    import javax.swing.event.DocumentEvent;
045    import javax.swing.event.DocumentListener;
046    import javax.swing.text.BadLocationException;
047    import javax.swing.text.Document;
048    
049    /** An IOPane consists of an input text field and a scrollable output text area.
050     * The input text field is equipped with a history, i. e. you can access
051     * previously entered items using the cursor keys. The output text area is
052     * automatically scrolled to the bottom when new text is appended. By default
053     * text that is entered in the input field is echoed in the output area and no
054     * other action is taken.
055     *
056     * @version $Revision: 102 $ ($Date: 2007-11-05 12:28:41 +0100 (Mo, 05 Nov 2007) $)
057     * @author Moritz Ringler
058     * @see ProcessIOPane
059    **/
060    public class IOPane extends JPanel {
061        private static final Logger logger = Logger.getLogger(IOPane.class.getPackage().getName());
062        /** whether to prepend a prompt sign to the echoed input **/
063        protected boolean prependPrompt = true;
064        /** holds history items as strings **/
065        private final transient History history = new VectorHistory();
066        /** the input field */
067        private final JTextField input = new JTextField();
068        private final JScrollPane jsp = new JScrollPane(
069                                                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
070                                                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
071        /** the output area **/
072        private final JTextArea jta;
073    
074        /** maximum number of lines in the output area */
075        private int maxLines = 100;
076        /** the JLabel preceding the input field */
077        private JLabel prompt;
078        /** The action listener that echoes input in the output field */
079        protected final ActionListener echoAL = new ActionListener() {
080            public void actionPerformed(ActionEvent e) {
081                if (prependPrompt) {
082                    jta.append(prompt.getText());
083                }
084                jta.append(e.getActionCommand());
085                jta.append("\n");
086                if (e.getSource() == input) {
087                    input.setText("");
088                }
089            }
090        };
091    
092        /**
093         * Creates a new IOPane with no initial text.
094         *
095         * @param rows number of text rows >= 0
096         * @param cols number of text columns >= 0 in a row
097         * @throws IllegalArgumentException if the rows or columns arguments are negative.
098         */
099        public IOPane(int rows, int cols) {
100            jsp.getVerticalScrollBar().getModel().addChangeListener(new ChangeListener() {
101                int max = 0;
102                public void stateChanged(ChangeEvent e){
103                    BoundedRangeModel brm = ((BoundedRangeModel) e.getSource());
104                    if(!brm.getValueIsAdjusting() && brm.getMaximum() != max){
105                        max = brm.getMaximum();
106                        brm.setValue(max);
107                    }
108                }
109                ;});
110            jta = new JTextArea(rows, cols);
111            jta.getDocument().addDocumentListener(new DocumentListener() {
112                public void insertUpdate(DocumentEvent e) {
113                    trim();
114                }
115    
116                public void removeUpdate(DocumentEvent e) {
117                    //does nothing
118                }
119    
120                public void changedUpdate(DocumentEvent e) {
121                    trim();
122                }
123                ;});
124            buildGui();
125            input.addActionListener(echoAL);
126            input.addActionListener(history.getAddListener());
127            input.addKeyListener(new KeyAdapter() {
128                public void keyPressed(KeyEvent e) {
129                    if (e.getKeyCode() == KeyEvent.VK_UP) {
130    
131                        String s = history.next();
132                        if (s != null) {
133                            input.setText(s);
134                        }
135                    }
136                    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
137    
138                        String s = history.previous();
139                        if (s != null) {
140                            input.setText(s);
141                        }
142                    }
143                }
144            });
145            addFocusListener(new FocusListener() {
146                public void focusLost(FocusEvent e) {
147                   //does nothing
148                }
149                ;public void focusGained(FocusEvent e) {
150                    input.requestFocusInWindow();
151                }
152            });
153        }
154    
155        /**
156         * Returns an array of all the ActionListeners added to this
157         * IOPane with {@link #addActionListener}.
158         *
159         * @return all of the ActionListeners added or an empty array if no listeners have been added
160         */
161        public ActionListener[] getActionListeners() {
162            return input.getActionListeners();
163        }
164    
165        /**
166         * Sets the background color of this IOPane, its output area and
167         * its input field.
168         *
169         * @param c the desired background Color
170         */
171        public final void setBackground(Color c) {
172            super.setBackground(c);
173    
174            Component[] comp = getComponents();
175            for (int i = 0; i < comp.length; i++) {
176                comp[i].setBackground(c);
177            }
178        }
179    
180        /**
181         * Fetches the model associated with the output area.
182         *
183         * @return the model of the output area
184         */
185        public Document getDocument() {
186            return jta.getDocument();
187        }
188    
189        /**
190         * Fetches the command history of the input field.
191         *
192         * @return the command history
193         */
194        public History getHistory() {
195            return history;
196        }
197    
198    
199        /**
200         * Sets the maximum number of lines in the output area. When the text in
201         * the output area exceeds the limit set by this method. Lines are removed
202         * from its beginning. The initial limit is 100 lines.
203         *
204         * @param lines the line limit, if lines is negative the number of
205         *              lines is unlimited
206         * @see #getMaxLines
207         */
208        public void setMaxLines(int lines) {
209            maxLines = lines;
210            trim();
211        }
212    
213        /**
214         * Returns the size limit of the output area of this IOPane.
215         *
216         * @return the maximum number of lines in the ouput area
217         * @see #setMaxLines
218         */
219        public int getMaxLines() {
220            return maxLines;
221        }
222    
223        /**
224         * Adds the specified action listener to receive action events from
225         * the input textfield.
226         *
227         * @param a the action listener to be added
228         */
229        public void addActionListener(ActionListener a) {
230            input.addActionListener(a);
231        }
232    
233        /**
234         * Appends the given text to the end of the document of the output area.
235         * @param s the text to append
236         * @see javax.swing.JTextArea#append
237         */
238        public void append(String s) {
239            jta.append(s);
240        }
241    
242        /**
243         * Constructs the GUI of this IOPane.
244         */
245        private void buildGui() {
246    
247            Border eb = BorderFactory.createEmptyBorder(1, 1, 1, 1);
248            jsp.setBorder(eb);
249            jta.setBorder(eb);
250            jsp.setViewportView(jta);
251            jta.setLineWrap(true);
252            jta.setEditable(false);
253            input.setBorder(eb);
254    
255            //Assemble the application GUI
256            GridBagConstraints gbc = new GridBagConstraints();
257            setLayout(new GridBagLayout());
258            prompt = new JLabel(" >");
259            prompt.setOpaque(true);
260    
261            // TextArea
262            gbc.gridx = 0;
263            gbc.gridy = 0;
264            gbc.fill = GridBagConstraints.BOTH;
265            gbc.anchor = GridBagConstraints.CENTER;
266            gbc.gridwidth = GridBagConstraints.REMAINDER;
267            gbc.gridheight = 10;
268            gbc.weightx = 1.;
269            gbc.weighty = 1.;
270            add(jsp, gbc);
271    
272            // Input Prompt
273            gbc.gridx = 0;
274            gbc.gridy = 11;
275            gbc.weighty = 0.;
276            gbc.weightx = 0.;
277            gbc.gridwidth = 1;
278            add(prompt, gbc);
279            gbc.gridx = 2;
280            gbc.weightx = 1.0;
281            gbc.gridwidth = GridBagConstraints.REMAINDER;
282            add(input, gbc);
283            setBackground(Color.white);
284        }
285    
286        /**
287         * Removes the specified action listener so that it no longer receives
288         * action events from the input textfield.
289         *
290         * @param a the action listener to be removed
291         */
292        public void removeActionListener(ActionListener a) {
293            input.removeActionListener(a);
294        }
295    
296        /**
297         * Returns the input text field of this IOPane.
298         *
299         * @return the input text field
300         */
301        protected JTextField getInput() {
302            return input;
303        }
304    
305        /**
306         * Returns the output area of this IOPane.
307         *
308         * @return the output area.
309         */
310        protected JTextArea getOutputArea() {
311            return jta;
312        }
313    
314        /**
315         * Returns the Label preceding the input field of this IOPane.
316         *
317         * @return the JLabel preceding the input field
318         */
319        protected JLabel getPrompt() {
320            return prompt;
321        }
322    
323        /**
324         * Returns the ScrollPane containing the output area of this IOPane.
325         *
326         * @return the scroll pane of the output area
327         */
328        protected JScrollPane getScrollPane() {
329            return jsp;
330        }
331    
332        /**
333         * Removes surplus lines from the start of the text in the output area.
334         */
335        private void trim() {
336            final int max = getMaxLines();
337            final int surplus = jta.getLineCount() - max;
338            if (max > 0 && surplus > 0) {
339                SwingUtilities.invokeLater(new Runnable() {
340                    public void run() {
341                        try {
342                            synchronized (jta.getDocument()) {
343                                jta.getDocument().remove(0,
344                                                         jta.getLineEndOffset(surplus));
345                                jta.getDocument().notifyAll();
346                            }
347                        } catch (BadLocationException ex) {
348                            logger.warning(ex.toString());
349                        }
350                    }
351                });
352            }
353        }
354    
355    
356        /** Minimum requirements for a command line history
357            for the input field of an IOPane. You can navigate this history step by
358            step using the next() and previous() methods. */
359        public static interface History {
360    
361            /**
362             * Returns the ActionListener that adds items to this history.
363             * It should usually {@link #add} the value returned
364             * by {@link ActionEvent#getActionCommand()}.
365             *
366             * @return an action listener that adds new items to this history
367             */
368            public ActionListener getAddListener();
369    
370            /**
371             * Sets the maximum number of items this history can hold.
372             *
373             * @param maxitems the maximum number of items
374             * @see #getLength
375             */
376            public void setLength(int maxitems);
377    
378            /**
379             * Returns the maximum number of items this history can hold.
380             *
381             * @return the maximum number of items
382             * @see #setLength
383             */
384            public int getLength();
385    
386            /**
387             * Adds the specified item to this history. If item is not <code>null</code>
388             * the next call to next() must return item.
389             * @param item the item to add
390             */
391            public void add(String item);
392    
393            /**
394             * Removes all items from this history.
395             */
396            public void clear();
397    
398            /**
399             * If there was no call to next() after the last {@link #add}
400             * this method will return the last item added to this history. Otherwise, it returns
401             * the item added before the item returned by the last call to next() or
402             * {@link #previous()}. It returns <code>null</code> if no such item exists.
403             * @return the next item in this history or <code>null</code> at its end
404             */
405            public String next();
406    
407            /**
408             * Returns the item added after the item returned by the last call to
409             * next() or previous(). Even if no such item exists this method must
410             * return a non-null value, preferably the empty string.
411             *
412             * @return the previous item in this history
413             */
414            public String previous();
415    
416            /**
417             * Resets the current position in this history such that the next item
418             * returned by next()
419             * will be the item last added or null if no such item exists.
420             */
421            public void resetPointer();
422        }
423    
424        /** Default implementation of the IOPane.History interface. **/
425        public static final class VectorHistory extends Vector implements History {
426    
427            private final ActionListener addListener = new ActionListener() {
428                public void actionPerformed(ActionEvent e) {
429                    if (e.getActionCommand() != null &&
430                                !e.getActionCommand().equals("")) {
431                        VectorHistory.this.add(e.getActionCommand());
432                    }
433                }
434            };
435    
436            private int currentItem = 0;
437            private int length = 100;
438    
439            /**
440             * Creates a new VectorHistory object.
441             */
442            public VectorHistory() {
443                super(10);
444                super.add("");
445            }
446    
447            /**
448             * Returns the ActionListener that adds items to this history.
449             * It should usually {@link #add} the value returned
450             * by {@link ActionEvent#getActionCommand()}.
451             *
452             * @return an action listener that adds new items to this history
453             */
454            public ActionListener getAddListener() {
455                return addListener;
456            }
457    
458            /**
459             * Sets the maximum number of items in the history. Default is 100.
460             * when maxitems is &lt;= 0 the history has unlimited size.
461             * @param maxitems the maximum number of items
462             * @see #getLength
463             */
464            public void setLength(int maxitems) {
465                length = maxitems;
466                if (length > 0 && size() > length) {
467                    setSize(length + 1);
468                    trimToSize();
469                }
470            }
471    
472            /**
473             * Returns the maximum number of items this history can hold.
474             *
475             * @return the maximum number of items, default is 100
476             * @see #setLength
477             */
478            public int getLength() {
479                return length;
480            }
481    
482            /**
483             * Adds the specified item to this history.
484             * The next call to next() must return item.
485             * @param item the item to add
486             * @throws NullPointerException if item is <code>null</code>
487             */
488            public void add(String item) {
489                item.length(); //throws a NullPointerException if item is null
490                if (length > 0 && size() == length + 1) {
491                    remove(size() - 1);
492                }
493                add(1, item);
494                currentItem = 0;
495            }
496    
497            /**
498             * Removes all items from this history.
499             */
500            public void clear() {
501                setSize(1);
502            }
503    
504            /**
505             * If there was no call to next() after the last {@link #add}
506             * this method will return the last item added to this history. Otherwise, it returns
507             * the item added before the item returned by the last call to next() or
508             * {@link #previous()}. It returns <code>null</code> if no such item exists.
509             * @return the next item in this history or <code>null</code> at its end
510             */
511            public String next() {
512                if (currentItem + 1 < size()) {
513                    return (String) get(++currentItem);
514                } else {
515                    return null;
516                }
517            }
518    
519            /**
520             * Returns the item added after the item returned by the last call to
521             * next() or previous(). Even if no such item exists this method must
522             * return a non-null value, preferably the empty string.
523             *
524             * @return the previous item in this history
525             */
526            public String previous() {
527                if (currentItem == 0) {
528                    return (String) get(0);
529                } else {
530                    return (String) get(--currentItem);
531                }
532            }
533    
534            /**
535             * Resets the current position in this history such that the next item
536             * returned by next()
537             * will be the item last added or null if no such item exists.
538             */
539            public void resetPointer() {
540                currentItem = 0;
541            }
542        }
543    }