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

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