You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VDragAndDropWrapper.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.client.ui;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.Map;
  8. import com.google.gwt.core.client.GWT;
  9. import com.google.gwt.core.client.JsArrayString;
  10. import com.google.gwt.core.client.Scheduler;
  11. import com.google.gwt.dom.client.NativeEvent;
  12. import com.google.gwt.event.dom.client.MouseDownEvent;
  13. import com.google.gwt.event.dom.client.MouseDownHandler;
  14. import com.google.gwt.event.dom.client.TouchStartEvent;
  15. import com.google.gwt.event.dom.client.TouchStartHandler;
  16. import com.google.gwt.user.client.Command;
  17. import com.google.gwt.user.client.Element;
  18. import com.google.gwt.user.client.Event;
  19. import com.google.gwt.user.client.Timer;
  20. import com.google.gwt.user.client.ui.Widget;
  21. import com.google.gwt.xhr.client.ReadyStateChangeHandler;
  22. import com.google.gwt.xhr.client.XMLHttpRequest;
  23. import com.vaadin.terminal.gwt.client.ApplicationConnection;
  24. import com.vaadin.terminal.gwt.client.ComponentConnector;
  25. import com.vaadin.terminal.gwt.client.ConnectorMap;
  26. import com.vaadin.terminal.gwt.client.LayoutManager;
  27. import com.vaadin.terminal.gwt.client.MouseEventDetailsBuilder;
  28. import com.vaadin.terminal.gwt.client.Util;
  29. import com.vaadin.terminal.gwt.client.VConsole;
  30. import com.vaadin.terminal.gwt.client.VTooltip;
  31. import com.vaadin.terminal.gwt.client.ValueMap;
  32. import com.vaadin.terminal.gwt.client.ui.dd.DDUtil;
  33. import com.vaadin.terminal.gwt.client.ui.dd.HorizontalDropLocation;
  34. import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler;
  35. import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback;
  36. import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
  37. import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent;
  38. import com.vaadin.terminal.gwt.client.ui.dd.VDropHandler;
  39. import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
  40. import com.vaadin.terminal.gwt.client.ui.dd.VHtml5DragEvent;
  41. import com.vaadin.terminal.gwt.client.ui.dd.VHtml5File;
  42. import com.vaadin.terminal.gwt.client.ui.dd.VTransferable;
  43. import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
  44. /**
  45. *
  46. * Must have features pending:
  47. *
  48. * drop details: locations + sizes in document hierarchy up to wrapper
  49. *
  50. */
  51. public class VDragAndDropWrapper extends VCustomComponent implements
  52. VHasDropHandler {
  53. public static final String DRAG_START_MODE = "dragStartMode";
  54. public static final String HTML5_DATA_FLAVORS = "html5-data-flavors";
  55. private static final String CLASSNAME = "v-ddwrapper";
  56. protected static final String DRAGGABLE = "draggable";
  57. public VDragAndDropWrapper() {
  58. super();
  59. sinkEvents(VTooltip.TOOLTIP_EVENTS);
  60. hookHtml5Events(getElement());
  61. setStyleName(CLASSNAME);
  62. addDomHandler(new MouseDownHandler() {
  63. public void onMouseDown(MouseDownEvent event) {
  64. if (startDrag(event.getNativeEvent())) {
  65. event.preventDefault(); // prevent text selection
  66. }
  67. }
  68. }, MouseDownEvent.getType());
  69. addDomHandler(new TouchStartHandler() {
  70. public void onTouchStart(TouchStartEvent event) {
  71. if (startDrag(event.getNativeEvent())) {
  72. /*
  73. * Dont let eg. panel start scrolling.
  74. */
  75. event.stopPropagation();
  76. }
  77. }
  78. }, TouchStartEvent.getType());
  79. sinkEvents(Event.TOUCHEVENTS);
  80. }
  81. @Override
  82. public void onBrowserEvent(Event event) {
  83. super.onBrowserEvent(event);
  84. if (client != null) {
  85. client.handleTooltipEvent(event, this);
  86. }
  87. }
  88. /**
  89. * Starts a drag and drop operation from mousedown or touchstart event if
  90. * required conditions are met.
  91. *
  92. * @param event
  93. * @return true if the event was handled as a drag start event
  94. */
  95. private boolean startDrag(NativeEvent event) {
  96. if (dragStartMode == WRAPPER || dragStartMode == COMPONENT) {
  97. VTransferable transferable = new VTransferable();
  98. transferable.setDragSource(ConnectorMap.get(client).getConnector(
  99. VDragAndDropWrapper.this));
  100. ComponentConnector paintable = Util.findPaintable(client,
  101. (Element) event.getEventTarget().cast());
  102. Widget widget = paintable.getWidget();
  103. transferable.setData("component", paintable);
  104. VDragEvent dragEvent = VDragAndDropManager.get().startDrag(
  105. transferable, event, true);
  106. transferable.setData("mouseDown", MouseEventDetailsBuilder
  107. .buildMouseEventDetails(event).serialize());
  108. if (dragStartMode == WRAPPER) {
  109. dragEvent.createDragImage(getElement(), true);
  110. } else {
  111. dragEvent.createDragImage(widget.getElement(), true);
  112. }
  113. return true;
  114. }
  115. return false;
  116. }
  117. protected final static int NONE = 0;
  118. protected final static int COMPONENT = 1;
  119. protected final static int WRAPPER = 2;
  120. protected final static int HTML5 = 3;
  121. protected int dragStartMode;
  122. ApplicationConnection client;
  123. VAbstractDropHandler dropHandler;
  124. private VDragEvent vaadinDragEvent;
  125. int filecounter = 0;
  126. Map<String, String> fileIdToReceiver;
  127. ValueMap html5DataFlavors;
  128. private Element dragStartElement;
  129. protected void initDragStartMode() {
  130. Element div = getElement();
  131. if (dragStartMode == HTML5) {
  132. if (dragStartElement == null) {
  133. dragStartElement = getDragStartElement();
  134. dragStartElement.setPropertyBoolean(DRAGGABLE, true);
  135. VConsole.log("draggable = "
  136. + dragStartElement.getPropertyBoolean(DRAGGABLE));
  137. hookHtml5DragStart(dragStartElement);
  138. VConsole.log("drag start listeners hooked.");
  139. }
  140. } else {
  141. dragStartElement = null;
  142. if (div.hasAttribute(DRAGGABLE)) {
  143. div.removeAttribute(DRAGGABLE);
  144. }
  145. }
  146. }
  147. protected Element getDragStartElement() {
  148. return getElement();
  149. }
  150. private boolean uploading;
  151. private ReadyStateChangeHandler readyStateChangeHandler = new ReadyStateChangeHandler() {
  152. public void onReadyStateChange(XMLHttpRequest xhr) {
  153. if (xhr.getReadyState() == XMLHttpRequest.DONE) {
  154. // visit server for possible
  155. // variable changes
  156. client.sendPendingVariableChanges();
  157. uploading = false;
  158. startNextUpload();
  159. xhr.clearOnReadyStateChange();
  160. }
  161. }
  162. };
  163. private Timer dragleavetimer;
  164. void startNextUpload() {
  165. Scheduler.get().scheduleDeferred(new Command() {
  166. public void execute() {
  167. if (!uploading) {
  168. if (fileIds.size() > 0) {
  169. uploading = true;
  170. final Integer fileId = fileIds.remove(0);
  171. VHtml5File file = files.remove(0);
  172. final String receiverUrl = client
  173. .translateVaadinUri(fileIdToReceiver
  174. .remove(fileId.toString()));
  175. ExtendedXHR extendedXHR = (ExtendedXHR) ExtendedXHR
  176. .create();
  177. extendedXHR
  178. .setOnReadyStateChange(readyStateChangeHandler);
  179. extendedXHR.open("POST", receiverUrl);
  180. extendedXHR.postFile(file);
  181. }
  182. }
  183. }
  184. });
  185. }
  186. public boolean html5DragStart(VHtml5DragEvent event) {
  187. if (dragStartMode == HTML5) {
  188. /*
  189. * Populate html5 payload with dataflavors from the serverside
  190. */
  191. JsArrayString flavors = html5DataFlavors.getKeyArray();
  192. for (int i = 0; i < flavors.length(); i++) {
  193. String flavor = flavors.get(i);
  194. event.setHtml5DataFlavor(flavor,
  195. html5DataFlavors.getString(flavor));
  196. }
  197. event.setEffectAllowed("copy");
  198. return true;
  199. }
  200. return false;
  201. }
  202. public boolean html5DragEnter(VHtml5DragEvent event) {
  203. if (dropHandler == null) {
  204. return true;
  205. }
  206. try {
  207. if (dragleavetimer != null) {
  208. // returned quickly back to wrapper
  209. dragleavetimer.cancel();
  210. dragleavetimer = null;
  211. }
  212. if (VDragAndDropManager.get().getCurrentDropHandler() != getDropHandler()) {
  213. VTransferable transferable = new VTransferable();
  214. transferable.setDragSource(ConnectorMap.get(client)
  215. .getConnector(this));
  216. vaadinDragEvent = VDragAndDropManager.get().startDrag(
  217. transferable, event, false);
  218. VDragAndDropManager.get().setCurrentDropHandler(
  219. getDropHandler());
  220. }
  221. try {
  222. event.preventDefault();
  223. event.stopPropagation();
  224. } catch (Exception e) {
  225. // VConsole.log("IE9 fails");
  226. }
  227. return false;
  228. } catch (Exception e) {
  229. GWT.getUncaughtExceptionHandler().onUncaughtException(e);
  230. return true;
  231. }
  232. }
  233. public boolean html5DragLeave(VHtml5DragEvent event) {
  234. if (dropHandler == null) {
  235. return true;
  236. }
  237. try {
  238. dragleavetimer = new Timer() {
  239. @Override
  240. public void run() {
  241. // Yes, dragleave happens before drop. Makes no sense to me.
  242. // IMO shouldn't fire leave at all if drop happens (I guess
  243. // this
  244. // is what IE does).
  245. // In Vaadin we fire it only if drop did not happen.
  246. if (vaadinDragEvent != null
  247. && VDragAndDropManager.get()
  248. .getCurrentDropHandler() == getDropHandler()) {
  249. VDragAndDropManager.get().interruptDrag();
  250. }
  251. }
  252. };
  253. dragleavetimer.schedule(350);
  254. try {
  255. event.preventDefault();
  256. event.stopPropagation();
  257. } catch (Exception e) {
  258. // VConsole.log("IE9 fails");
  259. }
  260. return false;
  261. } catch (Exception e) {
  262. GWT.getUncaughtExceptionHandler().onUncaughtException(e);
  263. return true;
  264. }
  265. }
  266. public boolean html5DragOver(VHtml5DragEvent event) {
  267. if (dropHandler == null) {
  268. return true;
  269. }
  270. if (dragleavetimer != null) {
  271. // returned quickly back to wrapper
  272. dragleavetimer.cancel();
  273. dragleavetimer = null;
  274. }
  275. vaadinDragEvent.setCurrentGwtEvent(event);
  276. getDropHandler().dragOver(vaadinDragEvent);
  277. String s = event.getEffectAllowed();
  278. if ("all".equals(s) || s.contains("opy")) {
  279. event.setDropEffect("copy");
  280. } else {
  281. event.setDropEffect(s);
  282. }
  283. try {
  284. event.preventDefault();
  285. event.stopPropagation();
  286. } catch (Exception e) {
  287. // VConsole.log("IE9 fails");
  288. }
  289. return false;
  290. }
  291. public boolean html5DragDrop(VHtml5DragEvent event) {
  292. if (dropHandler == null || !currentlyValid) {
  293. return true;
  294. }
  295. try {
  296. VTransferable transferable = vaadinDragEvent.getTransferable();
  297. JsArrayString types = event.getTypes();
  298. for (int i = 0; i < types.length(); i++) {
  299. String type = types.get(i);
  300. if (isAcceptedType(type)) {
  301. String data = event.getDataAsText(type);
  302. if (data != null) {
  303. transferable.setData(type, data);
  304. }
  305. }
  306. }
  307. int fileCount = event.getFileCount();
  308. if (fileCount > 0) {
  309. transferable.setData("filecount", fileCount);
  310. for (int i = 0; i < fileCount; i++) {
  311. final int fileId = filecounter++;
  312. final VHtml5File file = event.getFile(i);
  313. transferable.setData("fi" + i, "" + fileId);
  314. transferable.setData("fn" + i, file.getName());
  315. transferable.setData("ft" + i, file.getType());
  316. transferable.setData("fs" + i, file.getSize());
  317. queueFilePost(fileId, file);
  318. }
  319. }
  320. VDragAndDropManager.get().endDrag();
  321. vaadinDragEvent = null;
  322. try {
  323. event.preventDefault();
  324. event.stopPropagation();
  325. } catch (Exception e) {
  326. // VConsole.log("IE9 fails");
  327. }
  328. return false;
  329. } catch (Exception e) {
  330. GWT.getUncaughtExceptionHandler().onUncaughtException(e);
  331. return true;
  332. }
  333. }
  334. protected String[] acceptedTypes = new String[] { "Text", "Url",
  335. "text/html", "text/plain", "text/rtf" };
  336. private boolean isAcceptedType(String type) {
  337. for (String t : acceptedTypes) {
  338. if (t.equals(type)) {
  339. return true;
  340. }
  341. }
  342. return false;
  343. }
  344. static class ExtendedXHR extends XMLHttpRequest {
  345. protected ExtendedXHR() {
  346. }
  347. public final native void postFile(VHtml5File file)
  348. /*-{
  349. this.setRequestHeader('Content-Type', 'multipart/form-data');
  350. this.send(file);
  351. }-*/;
  352. }
  353. /**
  354. * Currently supports only FF36 as no other browser supports natively File
  355. * api.
  356. *
  357. * @param fileId
  358. * @param data
  359. */
  360. List<Integer> fileIds = new ArrayList<Integer>();
  361. List<VHtml5File> files = new ArrayList<VHtml5File>();
  362. private void queueFilePost(final int fileId, final VHtml5File file) {
  363. fileIds.add(fileId);
  364. files.add(file);
  365. }
  366. public VDropHandler getDropHandler() {
  367. return dropHandler;
  368. }
  369. protected VerticalDropLocation verticalDropLocation;
  370. protected HorizontalDropLocation horizontalDropLocation;
  371. private VerticalDropLocation emphasizedVDrop;
  372. private HorizontalDropLocation emphasizedHDrop;
  373. /**
  374. * Flag used by html5 dd
  375. */
  376. private boolean currentlyValid;
  377. private static final String OVER_STYLE = "v-ddwrapper-over";
  378. public class CustomDropHandler extends VAbstractDropHandler {
  379. @Override
  380. public void dragEnter(VDragEvent drag) {
  381. updateDropDetails(drag);
  382. currentlyValid = false;
  383. super.dragEnter(drag);
  384. }
  385. @Override
  386. public void dragLeave(VDragEvent drag) {
  387. deEmphasis(true);
  388. dragleavetimer = null;
  389. }
  390. @Override
  391. public void dragOver(final VDragEvent drag) {
  392. boolean detailsChanged = updateDropDetails(drag);
  393. if (detailsChanged) {
  394. currentlyValid = false;
  395. validate(new VAcceptCallback() {
  396. public void accepted(VDragEvent event) {
  397. dragAccepted(drag);
  398. }
  399. }, drag);
  400. }
  401. }
  402. @Override
  403. public boolean drop(VDragEvent drag) {
  404. deEmphasis(true);
  405. Map<String, Object> dd = drag.getDropDetails();
  406. // this is absolute layout based, and we may want to set
  407. // component
  408. // relatively to where the drag ended.
  409. // need to add current location of the drop area
  410. int absoluteLeft = getAbsoluteLeft();
  411. int absoluteTop = getAbsoluteTop();
  412. dd.put("absoluteLeft", absoluteLeft);
  413. dd.put("absoluteTop", absoluteTop);
  414. if (verticalDropLocation != null) {
  415. dd.put("verticalLocation", verticalDropLocation.toString());
  416. dd.put("horizontalLocation", horizontalDropLocation.toString());
  417. }
  418. return super.drop(drag);
  419. }
  420. @Override
  421. protected void dragAccepted(VDragEvent drag) {
  422. currentlyValid = true;
  423. emphasis(drag);
  424. }
  425. @Override
  426. public ComponentConnector getConnector() {
  427. return ConnectorMap.get(client).getConnector(
  428. VDragAndDropWrapper.this);
  429. }
  430. public ApplicationConnection getApplicationConnection() {
  431. return client;
  432. }
  433. }
  434. protected native void hookHtml5DragStart(Element el)
  435. /*-{
  436. var me = this;
  437. el.addEventListener("dragstart", function(ev) {
  438. return me.@com.vaadin.terminal.gwt.client.ui.VDragAndDropWrapper::html5DragStart(Lcom/vaadin/terminal/gwt/client/ui/dd/VHtml5DragEvent;)(ev);
  439. }, false);
  440. }-*/;
  441. /**
  442. * Prototype code, memory leak risk.
  443. *
  444. * @param el
  445. */
  446. protected native void hookHtml5Events(Element el)
  447. /*-{
  448. var me = this;
  449. el.addEventListener("dragenter", function(ev) {
  450. return me.@com.vaadin.terminal.gwt.client.ui.VDragAndDropWrapper::html5DragEnter(Lcom/vaadin/terminal/gwt/client/ui/dd/VHtml5DragEvent;)(ev);
  451. }, false);
  452. el.addEventListener("dragleave", function(ev) {
  453. return me.@com.vaadin.terminal.gwt.client.ui.VDragAndDropWrapper::html5DragLeave(Lcom/vaadin/terminal/gwt/client/ui/dd/VHtml5DragEvent;)(ev);
  454. }, false);
  455. el.addEventListener("dragover", function(ev) {
  456. return me.@com.vaadin.terminal.gwt.client.ui.VDragAndDropWrapper::html5DragOver(Lcom/vaadin/terminal/gwt/client/ui/dd/VHtml5DragEvent;)(ev);
  457. }, false);
  458. el.addEventListener("drop", function(ev) {
  459. return me.@com.vaadin.terminal.gwt.client.ui.VDragAndDropWrapper::html5DragDrop(Lcom/vaadin/terminal/gwt/client/ui/dd/VHtml5DragEvent;)(ev);
  460. }, false);
  461. }-*/;
  462. public boolean updateDropDetails(VDragEvent drag) {
  463. VerticalDropLocation oldVL = verticalDropLocation;
  464. verticalDropLocation = DDUtil.getVerticalDropLocation(getElement(),
  465. drag.getCurrentGwtEvent(), 0.2);
  466. drag.getDropDetails().put("verticalLocation",
  467. verticalDropLocation.toString());
  468. HorizontalDropLocation oldHL = horizontalDropLocation;
  469. horizontalDropLocation = DDUtil.getHorizontalDropLocation(getElement(),
  470. drag.getCurrentGwtEvent(), 0.2);
  471. drag.getDropDetails().put("horizontalLocation",
  472. horizontalDropLocation.toString());
  473. if (oldHL != horizontalDropLocation || oldVL != verticalDropLocation) {
  474. return true;
  475. } else {
  476. return false;
  477. }
  478. }
  479. protected void deEmphasis(boolean doLayout) {
  480. if (emphasizedVDrop != null) {
  481. VDragAndDropWrapper.setStyleName(getElement(), OVER_STYLE, false);
  482. VDragAndDropWrapper.setStyleName(getElement(), OVER_STYLE + "-"
  483. + emphasizedVDrop.toString().toLowerCase(), false);
  484. VDragAndDropWrapper.setStyleName(getElement(), OVER_STYLE + "-"
  485. + emphasizedHDrop.toString().toLowerCase(), false);
  486. }
  487. if (doLayout) {
  488. notifySizePotentiallyChanged();
  489. }
  490. }
  491. private void notifySizePotentiallyChanged() {
  492. LayoutManager.get(client).setNeedsMeasure(
  493. ConnectorMap.get(client).getConnector(getElement()));
  494. }
  495. protected void emphasis(VDragEvent drag) {
  496. deEmphasis(false);
  497. VDragAndDropWrapper.setStyleName(getElement(), OVER_STYLE, true);
  498. VDragAndDropWrapper.setStyleName(getElement(), OVER_STYLE + "-"
  499. + verticalDropLocation.toString().toLowerCase(), true);
  500. VDragAndDropWrapper.setStyleName(getElement(), OVER_STYLE + "-"
  501. + horizontalDropLocation.toString().toLowerCase(), true);
  502. emphasizedVDrop = verticalDropLocation;
  503. emphasizedHDrop = horizontalDropLocation;
  504. notifySizePotentiallyChanged();
  505. }
  506. }