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 22KB

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