summaryrefslogtreecommitdiffstats
path: root/gerrit-gwtexpui/src/main/java/com/google/gwtexpui/clippy/client/CopyableLabel.java
blob: 7b70c6a47ca746f06a513ca5b5356c70ccf48f84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 com.google.gwtexpui.clippy.client;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwtexpui.safehtml.client.SafeHtml;
import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder;
import com.google.gwtexpui.user.client.Tooltip;
import com.google.gwtexpui.user.client.UserAgent;

/**
 * Label which permits the user to easily copy the complete content.
 *
 * <p>If the Flash plugin is available a "movie" is embedded that provides one-click copying of the
 * content onto the system clipboard. The label (if visible) can also be clicked, switching from a
 * label to an input box, allowing the user to copy the text with a keyboard shortcut.
 */
public class CopyableLabel extends Composite implements HasText {
  private static final int SWF_WIDTH = 110;
  private static final int SWF_HEIGHT = 14;
  private static boolean flashEnabled = true;

  static {
    ClippyResources.I.css().ensureInjected();
  }

  public static boolean isFlashEnabled() {
    return flashEnabled;
  }

  public static void setFlashEnabled(boolean on) {
    flashEnabled = on;
  }

  private static String swfUrl() {
    return ClippyResources.I.swf().getSafeUri().asString();
  }

  private final FlowPanel content;
  private String text;
  private int visibleLen;
  private Label textLabel;
  private TextBox textBox;
  private Button copier;
  private Element swf;

  public CopyableLabel() {
    this("");
  }

  /**
   * Create a new label
   *
   * @param str initial content
   */
  public CopyableLabel(String str) {
    this(str, true);
  }

  /**
   * Create a new label
   *
   * @param str initial content
   * @param showLabel if true, the content is shown, if false it is hidden from view and only the
   *     copy icon is displayed.
   */
  public CopyableLabel(String str, boolean showLabel) {
    content = new FlowPanel();
    initWidget(content);

    text = str;
    visibleLen = text.length();

    if (showLabel) {
      textLabel = new InlineLabel(getText());
      textLabel.setStyleName(ClippyResources.I.css().label());
      textLabel.addClickHandler(
          new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
              showTextBox();
            }
          });
      content.add(textLabel);
    }

    if (UserAgent.hasJavaScriptClipboard()) {
      copier =
          new Button(
              new SafeHtmlBuilder()
                  .openElement("img")
                  .setAttribute("src", ClippyResources.I.clipboard().getSafeUri().asString())
                  .setWidth(14)
                  .setHeight(14)
                  .closeSelf());
      copier.setStyleName(ClippyResources.I.css().copier());
      Tooltip.addStyle(copier);
      Tooltip.setLabel(copier, CopyableLabelText.I.tooltip());
      copier.addClickHandler(
          new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
              copy();
            }
          });
      copier.addMouseOutHandler(
          new MouseOutHandler() {
            @Override
            public void onMouseOut(MouseOutEvent event) {
              Tooltip.setLabel(copier, CopyableLabelText.I.tooltip());
            }
          });

      FlowPanel p = new FlowPanel();
      p.getElement().getStyle().setDisplay(Display.INLINE_BLOCK);
      p.add(copier);
      content.add(p);
    } else {
      embedMovie();
    }
  }

  /**
   * Change the text which is displayed in the clickable label.
   *
   * @param text the new preview text, should be shorter than the original text which would be
   *     copied to the clipboard.
   */
  public void setPreviewText(String text) {
    if (textLabel != null) {
      textLabel.setText(text);
    }
  }

  private void embedMovie() {
    if (copier == null && flashEnabled && !text.isEmpty() && UserAgent.Flash.isInstalled()) {
      final String flashVars = "text=" + URL.encodeQueryString(getText());
      final SafeHtmlBuilder h = new SafeHtmlBuilder();

      h.openElement("div");
      h.setStyleName(ClippyResources.I.css().swf());

      h.openElement("object");
      h.setWidth(SWF_WIDTH);
      h.setHeight(SWF_HEIGHT);
      h.setAttribute("classid", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000");
      h.paramElement("movie", swfUrl());
      h.paramElement("FlashVars", flashVars);

      h.openElement("embed");
      h.setWidth(SWF_WIDTH);
      h.setHeight(SWF_HEIGHT);
      h.setAttribute("wmode", "transparent");
      h.setAttribute("type", "application/x-shockwave-flash");
      h.setAttribute("src", swfUrl());
      h.setAttribute("FlashVars", flashVars);
      h.closeSelf();

      h.closeElement("object");
      h.closeElement("div");

      if (swf != null) {
        getElement().removeChild(swf);
      }
      DOM.appendChild(getElement(), swf = SafeHtml.parse(h));
    }
  }

  @Override
  public String getText() {
    return text;
  }

  @Override
  public void setText(String newText) {
    text = newText;
    visibleLen = newText.length();

    if (textLabel != null) {
      textLabel.setText(getText());
    }
    if (textBox != null) {
      textBox.setText(getText());
      textBox.selectAll();
    }
    embedMovie();
  }

  private void showTextBox() {
    if (textBox == null) {
      textBox = new TextBox();
      textBox.setText(getText());
      textBox.setVisibleLength(visibleLen);
      textBox.setReadOnly(true);
      textBox.addKeyPressHandler(
          new KeyPressHandler() {
            @Override
            public void onKeyPress(KeyPressEvent event) {
              if (event.isControlKeyDown() || event.isMetaKeyDown()) {
                switch (event.getCharCode()) {
                  case 'c':
                  case 'x':
                    textBox.addKeyUpHandler(
                        new KeyUpHandler() {
                          @Override
                          public void onKeyUp(KeyUpEvent event) {
                            Scheduler.get()
                                .scheduleDeferred(
                                    new Command() {
                                      @Override
                                      public void execute() {
                                        hideTextBox();
                                      }
                                    });
                          }
                        });
                    break;
                }
              }
            }
          });
      textBox.addBlurHandler(
          new BlurHandler() {
            @Override
            public void onBlur(BlurEvent event) {
              hideTextBox();
            }
          });
      content.insert(textBox, 1);
    }

    textLabel.setVisible(false);
    textBox.setVisible(true);
    Scheduler.get()
        .scheduleDeferred(
            new Command() {
              @Override
              public void execute() {
                textBox.selectAll();
                textBox.setFocus(true);
              }
            });
  }

  private void hideTextBox() {
    if (textBox != null) {
      textBox.removeFromParent();
      textBox = null;
    }
    textLabel.setVisible(true);
  }

  private void copy() {
    TextBox t = new TextBox();
    try {
      t.setText(getText());
      content.add(t);
      t.setFocus(true);
      t.selectAll();

      boolean ok = execCommand("copy");
      Tooltip.setLabel(copier, ok ? CopyableLabelText.I.copied() : CopyableLabelText.I.failed());
      if (!ok) {
        // Disable JavaScript clipboard and try flash movie in another instance.
        UserAgent.disableJavaScriptClipboard();
      }
    } finally {
      t.removeFromParent();
    }
  }

  private static boolean execCommand(String command) {
    try {
      return nativeExec(command);
    } catch (Exception e) {
      return false;
    }
  }

  private static native boolean nativeExec(String c) /*-{ return !! $doc.execCommand(c) }-*/;
}