dnd.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package widget
  2. import (
  3. "io"
  4. "gioui.org/f32"
  5. "gioui.org/gesture"
  6. "gioui.org/io/event"
  7. "gioui.org/io/pointer"
  8. "gioui.org/io/transfer"
  9. "gioui.org/layout"
  10. "gioui.org/op"
  11. "gioui.org/op/clip"
  12. )
  13. // Draggable makes a widget draggable.
  14. type Draggable struct {
  15. // Type contains the MIME type and matches transfer.SourceOp.
  16. Type string
  17. drag gesture.Drag
  18. click f32.Point
  19. pos f32.Point
  20. }
  21. func (d *Draggable) Layout(gtx layout.Context, w, drag layout.Widget) layout.Dimensions {
  22. if !gtx.Enabled() {
  23. return w(gtx)
  24. }
  25. dims := w(gtx)
  26. stack := clip.Rect{Max: dims.Size}.Push(gtx.Ops)
  27. d.drag.Add(gtx.Ops)
  28. event.Op(gtx.Ops, d)
  29. stack.Pop()
  30. if drag != nil && d.drag.Pressed() {
  31. rec := op.Record(gtx.Ops)
  32. op.Offset(d.pos.Round()).Add(gtx.Ops)
  33. drag(gtx)
  34. op.Defer(gtx.Ops, rec.Stop())
  35. }
  36. return dims
  37. }
  38. // Dragging returns whether d is being dragged.
  39. func (d *Draggable) Dragging() bool {
  40. return d.drag.Dragging()
  41. }
  42. // Update the draggable and returns the MIME type for which the Draggable was
  43. // requested to offer data, if any
  44. func (d *Draggable) Update(gtx layout.Context) (mime string, requested bool) {
  45. pos := d.pos
  46. for {
  47. ev, ok := d.drag.Update(gtx.Metric, gtx.Source, gesture.Both)
  48. if !ok {
  49. break
  50. }
  51. switch ev.Kind {
  52. case pointer.Press:
  53. d.click = ev.Position
  54. pos = f32.Point{}
  55. case pointer.Drag, pointer.Release:
  56. pos = ev.Position.Sub(d.click)
  57. }
  58. }
  59. d.pos = pos
  60. for {
  61. e, ok := gtx.Event(transfer.SourceFilter{Target: d, Type: d.Type})
  62. if !ok {
  63. break
  64. }
  65. if e, ok := e.(transfer.RequestEvent); ok {
  66. return e.Type, true
  67. }
  68. }
  69. return "", false
  70. }
  71. // Offer the data ready for a drop. Must be called after being Requested.
  72. // The mime must be one in the requested list.
  73. func (d *Draggable) Offer(gtx layout.Context, mime string, data io.ReadCloser) {
  74. gtx.Execute(transfer.OfferCmd{Tag: d, Type: mime, Data: data})
  75. }
  76. // Pos returns the drag position relative to its initial click position.
  77. func (d *Draggable) Pos() f32.Point {
  78. return d.pos
  79. }