/*
 * KillRing.java
 *
 * Copyright (C) 1998-2003 Peter Graves
 * $Id: KillRing.java,v 1.2 2003/08/13 15:16:01 piso Exp $
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package org.armedbear.j;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

public final class KillRing extends Ring implements ClipboardOwner
{
    private ClipboardOwner clipboardOwner; // Either this or null.

    public KillRing()
    {
        super(30);
    }

    public void copyLastKillToSystemClipboard()
    {
        String kill = pop();
        if (kill != null)
            setClipboardContents(kill);
    }

    public void promoteLastPaste()
    {
        promoteLast();
        // Don't change the contents of the system clipboard unless we are the
        // clipboard owner!
        if (clipboardOwner == this)
            setClipboardContents(peek());
    }

    private void setClipboardContents(String s)
    {
        // Work around Java bug 4213197. Make sure the string we put on the
        // system clipboard was not generated by a substring operation.
        StringSelection ss = new StringSelection(new String(s));
        try {
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, this);
            clipboardOwner = this;
        }
        catch (IllegalStateException e) {
            Log.debug(e);
        }
    }

    public void lostOwnership(Clipboard clipboard, Transferable contents)
    {
        clipboardOwner = null;
    }
}
