package de.duehl.swing.clipboard;

/*
 * Copyright 2017 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

/**
 * Diese Hilfsklasse stellt Methoden zum Zugriff auf die Zwischenablage bereit.
 *
 * @version 1.01     2017-11-16
 * @author Christian Dühl
 */
public class Clipboard {

    /** Fügt den angegebenen Text in die Zwischenablage ein. */
    public static void insert(String text) {
        java.awt.datatransfer.Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
        StringSelection cont = new StringSelection(text);
        sysClip.setContents(cont, null);
    }

    /** Ermittelt den Text in der Zwischenablage. */
    public static String getContent() {
        try {
            return tryToGetContent();
        }
        catch (UnsupportedFlavorException | IOException e) {
            return "";
        }
    }

    private static String tryToGetContent() throws UnsupportedFlavorException, IOException {
        java.awt.datatransfer.Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable transfer = sysClip.getContents( null );
        String data = (String) transfer.getTransferData( DataFlavor.stringFlavor );
        return data;
    }

}
