001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools.bugreport;
003
004import java.awt.Dimension;
005
006import javax.swing.JScrollPane;
007
008import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils;
009import org.openstreetmap.josm.gui.widgets.JosmTextArea;
010import org.openstreetmap.josm.tools.Utils;
011
012/**
013 * This is a text area that displays the debug text with scroll bars.
014 * @author Michael Zangl
015 * @since 10055
016 */
017public class DebugTextDisplay extends JScrollPane {
018    private static final String CODE_PATTERN = "{{{%n%s%n}}}";
019    private String text;
020    private JosmTextArea textArea;
021
022    /**
023     * Creates a new text area.
024     * @since 10585
025     */
026    private DebugTextDisplay() {
027        textArea = new JosmTextArea();
028        textArea.setCaretPosition(0);
029        textArea.setEditable(false);
030        setViewportView(textArea);
031        setPreferredSize(new Dimension(600, 270));
032    }
033
034    /**
035     * Creates a new text area with an inital text to display
036     * @param textToDisplay The text to display.
037     */
038    public DebugTextDisplay(String textToDisplay) {
039        this();
040        setCodeText(textToDisplay);
041    }
042
043    /**
044     * Creates a new text area that displays the bug report data
045     * @param report The bug report data to display.
046     * @since 10585
047     */
048    public DebugTextDisplay(BugReport report) {
049        this();
050        setCodeText(report.getReportText());
051        report.addChangeListener(e -> setCodeText(report.getReportText()));
052    }
053
054    /**
055     * Sets the text that should be displayed in this view.
056     * @param textToDisplay The text
057     */
058    private void setCodeText(String textToDisplay) {
059        text = Utils.strip(textToDisplay).replaceAll("\r", "");
060        textArea.setText(String.format(CODE_PATTERN, text));
061        textArea.setCaretPosition(0);
062    }
063
064    /**
065     * Copies the debug text to the clipboard. This includes the code tags for trac.
066     * @return <code>true</code> if copy was successful
067     * @since 11102 (typo)
068     */
069    public boolean copyToClipboard() {
070        return ClipboardUtils.copyString(String.format(CODE_PATTERN, text));
071    }
072
073    /**
074     * Gets the text this are displays, without the code tag.
075     * @return The stripped text set by {@link #setCodeText(String)}
076     * @since 10585
077     */
078    public String getCodeText() {
079        return text;
080    }
081}