<commit_before>/**
 * Copyright 2011 multibit.org
 *
 * Licensed under the MIT license (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://opensource.org/licenses/mit-license.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.multibit.viewsystem.swing.view;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.StringTokenizer;

import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.TransferHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageSelection extends TransferHandler implements Transferable {
    private static final long serialVersionUID = 756395092284264645L;

    private static final Logger log = LoggerFactory.getLogger(ImageSelection.class);

    private DataFlavor urlFlavor;
    private DataFlavor uriListAsStringFlavor;
    private DataFlavor uriListAsReaderFlavor;

    private DataFlavor flavors[];

    private Image image;

    private AbstractTradePanel abstractTradePanel;
    private boolean canImport;

    public ImageSelection(AbstractTradePanel abstractTradePanel, boolean canImport) {
        this.abstractTradePanel = abstractTradePanel;
        this.canImport = canImport;

        try {
            urlFlavor = new DataFlavor("application/x-java-url; class=java.net.URL");
            uriListAsStringFlavor = new DataFlavor("text/uri-list; class=java.lang.String");
            uriListAsReaderFlavor = new DataFlavor("text/uri-list;class=java.io.Reader");
            flavors = new DataFlavor[] { DataFlavor.imageFlavor, urlFlavor, uriListAsStringFlavor, uriListAsReaderFlavor };
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public int getSourceActions(JComponent c) {
        return TransferHandler.COPY;
    }

    public boolean canImport(JComponent comp, DataFlavor flavor[]) {
        if (!canImport) {
            return false;
        }

        if (!(comp instanceof JLabel) && !(comp instanceof AbstractButton)) {
            return false;
        }

        for (int i = 0, n = flavor.length; i < n; i++) {
            for (int j = 0, m = flavors.length; j < m; j++) {
                if (flavor[i].equals(flavors[j])) {
                    return true;
                }
            }
        }
        return false;
    }

    public Transferable createTransferable(JComponent comp) {
        // Clear
        image = null;

        if (comp instanceof JLabel) {
            JLabel label = (JLabel) comp;
            Icon icon = label.getIcon();
            if (icon instanceof ImageIcon) {
                image = ((ImageIcon) icon).getImage();
                return this;
            }
        }
        return null;
    }

    public boolean importData(JComponent comp, Transferable transferable) {
        if (comp instanceof JLabel) {
            log.debug("importData - 1");

            JLabel label = (JLabel) comp;
            image = getDropData(transferable, label);
            log.debug("importData - 2 - image = {}", image);

            return abstractTradePanel.processDroppedImage(image);

        }
        return false;
    }

    // Transferable
    public Object getTransferData(DataFlavor flavor) {
        if (isDataFlavorSupported(flavor)) {
            if (DataFlavor.imageFlavor.equals(flavor) && image != null && image.getHeight(null) > 0) {
                return image;
            }

            if (DataFlavor.javaFileListFlavor.equals(flavor)) {
                java.util.List<File> list = new java.util.LinkedList<File>();

                // write the image to the output stream
                File swatchFile;
                try {
                    swatchFile = File.createTempFile("swatch", ".png");
                    ImageIO.write(toBufferedImage(image, -1, -1), "png", swatchFile);
                    list.add(swatchFile);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                return list;
            }

            if (uriListAsStringFlavor.equals(flavor)) {
                log.debug("uriListAsStringFlavor is supported");
                // write the image to the output stream
                File swatchFile;
                try {
                    swatchFile = File.createTempFile("swatch", ".png");
                    ImageIO.write(toBufferedImage(image, -1, -1), "png", swatchFile);
                    return "file://" + swatchFile.getAbsolutePath() + "\r\n";
                 } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

        }
        return null;
    }

    public DataFlavor[] getTransferDataFlavors() {
        return flavors;
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
        for (int j = 0, m = flavors.length; j < m; j++) {
            if (flavor.equals(flavors[j])) {
                if (DataFlavor.imageFlavor.equals(flavor)) {
                    if ( image != null && image.getHeight(null) > 0) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                   return true;
                }
            }
        }
        return false;
    }

    @SuppressWarnings("rawtypes")
    private Image getDropData(Transferable transferable, JComponent label) {
        try {
            // try to get an image
            if (transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                log.debug("image flavor is supported");
                Image img = (Image) transferable.getTransferData(DataFlavor.imageFlavor);
                if (img != null && img.getWidth(null) != -1) {
                    return img;
                }
            }
            if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                log.debug("javaFileList is supported");
                java.util.List list = (java.util.List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
                for (Object aList : list) {
                    File f = (File) aList;
                    ImageIcon icon = new ImageIcon(f.getAbsolutePath());
                    if (icon.getImage() != null) {
                        return icon.getImage();
                    }
                }
            }

            if (transferable.isDataFlavorSupported(uriListAsStringFlavor)) {
                log.debug("uriListAsStringFlavor is supported");
                String uris = (String) transferable.getTransferData(uriListAsStringFlavor);

                // url-lists are defined by rfc 2483 as crlf-delimited
                // TODO iterate over list for all of them
                StringTokenizer tokenizer = new StringTokenizer(uris, "\r\n");
                if (tokenizer.hasMoreTokens()) {
                    String uri = tokenizer.nextToken();<commit_msg>fix for drag onto desktop on Mac<commit_after>/**
 * Copyright 2011 multibit.org
 *
 * Licensed under the MIT license (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://opensource.org/licenses/mit-license.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.multibit.viewsystem.swing.view;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.StringTokenizer;

import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.TransferHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageSelection extends TransferHandler implements Transferable {
    private static final long serialVersionUID = 756395092284264645L;

    private static final Logger log = LoggerFactory.getLogger(ImageSelection.class);

    private DataFlavor urlFlavor;
    private DataFlavor uriListAsStringFlavor;
    private DataFlavor uriListAsReaderFlavor;

    private DataFlavor flavors[];

    private Image image;

    private AbstractTradePanel abstractTradePanel;
    private boolean canImport;

    public ImageSelection(AbstractTradePanel abstractTradePanel, boolean canImport) {
        this.abstractTradePanel = abstractTradePanel;
        this.canImport = canImport;

        try {
            urlFlavor = new DataFlavor("application/x-java-url; class=java.net.URL");
            uriListAsStringFlavor = new DataFlavor("text/uri-list; class=java.lang.String");
            uriListAsReaderFlavor = new DataFlavor("text/uri-list;class=java.io.Reader");
            flavors = new DataFlavor[] { DataFlavor.imageFlavor, DataFlavor.javaFileListFlavor, urlFlavor, uriListAsStringFlavor, uriListAsReaderFlavor };
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public int getSourceActions(JComponent c) {
        return TransferHandler.COPY;
    }

    public boolean canImport(JComponent comp, DataFlavor flavor[]) {
        if (!canImport) {
            return false;
        }

        if (!(comp instanceof JLabel) && !(comp instanceof AbstractButton)) {
            return false;
        }

        for (int i = 0, n = flavor.length; i < n; i++) {
            for (int j = 0, m = flavors.length; j < m; j++) {
                if (flavor[i].equals(flavors[j])) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public Transferable createTransferable(JComponent comp) {
        // Clear
        image = null;

        if (comp instanceof JLabel) {
            JLabel label = (JLabel) comp;
            Icon icon = label.getIcon();
            if (icon instanceof ImageIcon) {
                image = ((ImageIcon) icon).getImage();
                return this;
            }
        }
        return null;
    }

    public boolean importData(JComponent comp, Transferable transferable) {
        if (comp instanceof JLabel) {
            log.debug("importData - 1");

            JLabel label = (JLabel) comp;
            image = getDropData(transferable, label);
            log.debug("importData - 2 - image = {}", image);

            return abstractTradePanel.processDroppedImage(image);

        }
        return false;
    }

    // Transferable
    public Object getTransferData(DataFlavor flavor) {
        if (isDataFlavorSupported(flavor)) {
            if (DataFlavor.imageFlavor.equals(flavor) && image != null && image.getHeight(null) > 0) {
                return image;
            }

            if (DataFlavor.javaFileListFlavor.equals(flavor)) {
                java.util.List<File> list = new java.util.LinkedList<File>();

                // write the image to the output stream
                File qrCodeFile;
                try {
                    String suffix = "";
                    if (abstractTradePanel != null) {
                        if (abstractTradePanel.getLabel() != null) {
                            suffix = "-" + abstractTradePanel.getLabel();
                        }
                        if (abstractTradePanel.getAddress() != null) {
                            suffix = suffix + "-" + abstractTradePanel.getAddress();
                        }
                        if (abstractTradePanel.getAmount() != null) {
                            suffix = suffix + "-" + abstractTradePanel.getAmount();
                        }
                        
                        if (suffix.length() > 0) {
                            suffix = suffix + "-";
                        }
                    }
                     
                    qrCodeFile = File.createTempFile("qrcode" + suffix, ".png");
                    ImageIO.write(toBufferedImage(image, -1, -1), "png", qrCodeFile);
                    list.add(qrCodeFile);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                return list;
            }

            if (uriListAsStringFlavor.equals(flavor)) {
                log.debug("uriListAsStringFlavor is supported");
                // write the image to the output stream
                File qrcodeFile;
                try {
                    qrcodeFile = File.createTempFile("qrcode", ".png");
                    ImageIO.write(toBufferedImage(image, -1, -1), "png", qrcodeFile);
                    return "file://" + qrcodeFile.getAbsolutePath() + "\r\n";
                 } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

        }
        return null;
    }

    public DataFlavor[] getTransferDataFlavors() {
        return flavors;
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
        for (int j = 0, m = flavors.length; j < m; j++) {
            if (flavor.equals(flavors[j])) {
                if (DataFlavor.imageFlavor.equals(flavor)) {
                    if ( image != null && image.getHeight(null) > 0) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                   return true;
                }
            }
        }
        return false;
    }

    @SuppressWarnings("rawtypes")
    private Image getDropData(Transferable transferable, JComponent label) {
        try {
            // try to get an image
            if (transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                log.debug("image flavor is supported");
                Image img = (Image) transferable.getTransferData(DataFlavor.imageFlavor);
                if (img != null && img.getWidth(null) != -1) {
                    return img;
                }
            }
            
            if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                log.debug("javaFileList is supported");
                java.util.List list = (java.util.List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
                for (Object aList : list) {
                    File f = (File) aList;
                    ImageIcon icon = new ImageIcon(f.getAbsolutePath());
                    if (icon.getImage() != null) {
                        return icon.getImage();
                    }
                }
            }

            if (transferable.isDataFlavorSupported(uriListAsStringFlavor)) {
                log.debug("uriListAsStringFlavor is supported");
                String uris = (String) transferable.getTransferData(uriListAsStringFlavor);

                // url-lists are defined by rfc 2483 as crlf-delimited
                // TODO iterate over list for all of them
                StringTokenizer tokenizer = new StringTokenizer(uris, "\r\n");
                if (tokenizer.hasMoreTokens()) {
                    String uri = tokenizer.nextToken();
{'fraction_non_alphanumeric': 0.09351636229930138, 'fraction_numerical': 0.005576663806839074, 'mean_word_length': 1.8375934620066074, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1793384', 'n_tokens_mistral': 4421, 'n_tokens_neox': 4186, 'n_words': 1051}