001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.shell.swing.widgets;
018
019import java.awt.event.KeyEvent;
020import java.util.List;
021
022import javax.swing.JTextField;
023import javax.swing.event.DocumentEvent;
024import javax.swing.event.DocumentListener;
025
026import org.nuxeo.shell.swing.Console;
027
028/**
029 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
030 */
031@SuppressWarnings("serial")
032public class HistoryFinder extends JTextField implements DocumentListener {
033
034    protected Console console;
035
036    public HistoryFinder(Console console) {
037        this.console = console;
038        getDocument().addDocumentListener(this);
039    }
040
041    @Override
042    protected void processComponentKeyEvent(KeyEvent e) {
043        int code = e.getKeyCode();
044        if (code == KeyEvent.VK_ENTER) {
045            setVisible(false);
046            getParent().validate();
047            console.requestFocus();
048            e.consume();
049        } else if (code == KeyEvent.VK_ESCAPE) {
050            console.getCmdLine().setText("");
051            setVisible(false);
052            getParent().validate();
053            console.requestFocus();
054            e.consume();
055        }
056    }
057
058    @SuppressWarnings("unchecked")
059    public String getMatch() {
060        String text = getText();
061        List<String> list = console.getHistory().getHistoryList();
062        for (int i = list.size() - 1; i >= 0; i--) {
063            String entry = list.get(i);
064            int k = entry.indexOf(text);
065            if (k > -1) {
066                return entry;
067            }
068        }
069        return null;
070    }
071
072    public void changedUpdate(DocumentEvent e) {
073        String text = getMatch();
074        if (text != null) {
075            console.getCmdLine().setText(text);
076        }
077    }
078
079    public void insertUpdate(DocumentEvent e) {
080        changedUpdate(e);
081    }
082
083    public void removeUpdate(DocumentEvent e) {
084        changedUpdate(e);
085    }
086
087}