001/*
002 * (C) Copyright 2006-2010 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.shell.swing.widgets;
020
021import java.awt.event.KeyEvent;
022import java.util.List;
023
024import javax.swing.JTextField;
025import javax.swing.event.DocumentEvent;
026import javax.swing.event.DocumentListener;
027
028import org.nuxeo.shell.swing.Console;
029
030/**
031 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
032 */
033@SuppressWarnings("serial")
034public class HistoryFinder extends JTextField implements DocumentListener {
035
036    protected Console console;
037
038    public HistoryFinder(Console console) {
039        this.console = console;
040        getDocument().addDocumentListener(this);
041    }
042
043    @Override
044    protected void processComponentKeyEvent(KeyEvent e) {
045        int code = e.getKeyCode();
046        if (code == KeyEvent.VK_ENTER) {
047            setVisible(false);
048            getParent().validate();
049            console.requestFocus();
050            e.consume();
051        } else if (code == KeyEvent.VK_ESCAPE) {
052            console.getCmdLine().setText("");
053            setVisible(false);
054            getParent().validate();
055            console.requestFocus();
056            e.consume();
057        }
058    }
059
060    @SuppressWarnings("unchecked")
061    public String getMatch() {
062        String text = getText();
063        List<String> list = console.getHistory().getHistoryList();
064        for (int i = list.size() - 1; i >= 0; i--) {
065            String entry = list.get(i);
066            int k = entry.indexOf(text);
067            if (k > -1) {
068                return entry;
069            }
070        }
071        return null;
072    }
073
074    public void changedUpdate(DocumentEvent e) {
075        String text = getMatch();
076        if (text != null) {
077            console.getCmdLine().setText(text);
078        }
079    }
080
081    public void insertUpdate(DocumentEvent e) {
082        changedUpdate(e);
083    }
084
085    public void removeUpdate(DocumentEvent e) {
086        changedUpdate(e);
087    }
088
089}