<<TableOfContents>>

= Introduction =
 . Drag and drop support within wxPython is a conversation between a "drop source" and a "drop target".  The conversation is accomplished by sharing a "data object" which includes certain pieces of metadata (primarily the data types available from the drop source) as well as the actual shared data.

= What Objects are Involved =
 * Source window -- Interprets an event as the beginning of a new drag-and-drop request.  Instantiates a new drop source
 and triggers the drag-and-drop sequence by calling {{{DoDragDrop}}} on the drop source object.  Responds to the result code of the drag-and-drop sequence (move/copy/cancel/fail).

 * {{{wxDropSource}}} -- Provides common functionality for drag-and-drop source windows (UI interactions, data object storage)

 * Destination window -- Advertises acceptable data types by
 calling {{{SetDropTarget}}} with a configured drop target object.

 * {{{wxDropTarget}}} -- Responds to various "pseudo-events" during the drag-and-drop process, most importantly the {{{OnData}}} "event" which indicates that an object has been dropped on the associated window.

 * {{{wxDataObject}}} -- Provides storage and metadata relating to the data being transferred during a drag-and-drop operation.  May support one of the built-in data types (text, bitmap, file), a single declared data type, or multiple data types. Includes: {{{wxTextDataObject}}}, {{{wxBitmapDataObject}}}, {{{wxFileDataObject}}}, {{{wxDataObjectSimple}}}, {{{wxDataObjectComposite}}}, {{{wxDataObject}}}

= Process Overview =
 * Create or choose a {{{wxDataObject}}} subclass appropriate to the data being shared
  * Provide {{{OnData}}} method to handle incoming data and update your application with the results of the drag-and-drop operation.

  * If you are not using a built-in data type, choose a type specifier (a unique string used to identify the datatype).  Only targets whose type specifiers include one of the current data source specifiers will be eligible for drops.

 * Create a {{{wxPyDropTarget}}} subclass (and instance)
  * Provide an {{{OnData}}} method to handle a drop "event"
   * Call {{{self.GetData()}}} to transfer data to the target's {{{wxDataObject}}} instance

   * Call {{{wxDataObject.GetData()}}} to retrieve the actual shared data

   * Update your application to reflect drag-and-drop operation (in many cases you will need a pointer to the target window within the drop target instance to accomplish this).

  * Instantiate an instance of your {{{wxDataObject}}} class

  * Bind a {{{wxDataObject}}} to the drop target by calling {{{SetDataObject}}}. You will also want to keep a pointer to the {{{wxDataObject}}} in the drop target instance, so that you can call {{{wxDataObject.GetData()}}} within the {{{OnData}}} method.

  * Bind the drop target to the target window using {{{wxWindow.SetDropTarget}}}

 * Handle an event on the source window which signals the start of the drag-and-drop cycle
  * Create a {{{wxDropSource}}}

  * Set the data object of the drop source to ''another instance'' of your {{{wxDataObject}}} class

  * Call the drop source {{{DoDragDrop()}}} method to begin the drag-and-drop operation

  * Respond to the result code of the {{{DoDragDrop}}} method as appropriate to your application

= wxDataObjects =
 . Discuss the various concerns relating to the data object. Python pickling options Multiple formats -- currently only works for source in Python (as far as I can see) Format specifiers, do these need to be discussed? Special Data Types

= Code Samples =
 * Simple drag-and-drop

{{{#!python
# A very simple Drag and Drop Example
# provided with no warranty whatsoever for any purpose, ever

# A very simple Drag and Drop Example
# provided with no warranty whatsoever for any purpose, ever

# This code creates a Text Control from which Text can be dragged,
# a Text Control to which Text can be dragged (from the first Text Control or from other applications),
# and a Text Control to which Files can be dragged from outside this application.
# While the later two windows can receive data from outside the application, the first window
# does not appear to be able to provide text to other applications.  Please feel free to fix
# this if you know how, as I think that would be more useful as an example.

# It is designed to demonstrate the fundamentals of very simple drag-and-drop operations.

""" This mini-app is designed to demonstrate simple Drag and Drop functioning in wx.Python """

__author__ = 'David Woods, Wisconsin Center for Education Research <dwoods@wcer.wisc.edu>'

# Import wx.Python
import wx

# Declare GUI Constants
MENU_FILE_EXIT = wx.NewId()
DRAG_SOURCE    = wx.NewId()

# Define Text Drop Target class
class TextDropTarget(wx.TextDropTarget):
   """ This object implements Drop Target functionality for Text """
   def __init__(self, obj):
      """ Initialize the Drop Target, passing in the Object Reference to
          indicate what should receive the dropped text """
      # Initialize the wx.TextDropTarget Object
      wx.TextDropTarget.__init__(self)
      # Store the Object Reference for dropped text
      self.obj = obj

   def OnDropText(self, x, y, data):
      """ Implement Text Drop """
      # When text is dropped, write it into the object specified
      self.obj.WriteText(data + '\n\n')

# Define File Drop Target class
class FileDropTarget(wx.FileDropTarget):
   """ This object implements Drop Target functionality for Files """
   def __init__(self, obj):
      """ Initialize the Drop Target, passing in the Object Reference to
          indicate what should receive the dropped files """
      # Initialize the wxFileDropTarget Object
      wx.FileDropTarget.__init__(self)
      # Store the Object Reference for dropped files
      self.obj = obj

   def OnDropFiles(self, x, y, filenames):
      """ Implement File Drop """
      # For Demo purposes, this function appends a list of the files dropped at the end of the widget's text
      # Move Insertion Point to the end of the widget's text
      self.obj.SetInsertionPointEnd()
      # append a list of the file names dropped
      self.obj.WriteText("%d file(s) dropped at %d, %d:\n" % (len(filenames), x, y))
      for file in filenames:
         self.obj.WriteText(file + '\n')
      self.obj.WriteText('\n')



class MainWindow(wx.Frame):
   """ This window displays the GUI Widgets. """
   def __init__(self,parent,id,title):
       wx.Frame.__init__(self,parent, wx.ID_ANY, title, size = (800,600), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
       self.SetBackgroundColour(wx.WHITE)

       # Menu Bar
       # Create a MenuBar
       menuBar = wx.MenuBar()
       # Build a Menu Object to go into the Menu Bar
       menu1 = wx.Menu()
       menu1.Append(MENU_FILE_EXIT, "E&xit", "Quit Application")
       # Place the Menu Item in the Menu Bar
       menuBar.Append(menu1, "&File")
       # Place the Menu Bar on the ap
       self.SetMenuBar(menuBar)
       #Define Events for the Menu Items
       wx.EVT_MENU(self, MENU_FILE_EXIT, self.CloseWindow)

       # GUI Widgets
       # Define a Text Control from which Text can be dragged for dropping
       # Label the control
       wx.StaticText(self, -1, "Text Drag Source  (left-click to select, right-click to drag)", (10, 1))
       # Create a Text Control
       self.text = wx.TextCtrl(self, DRAG_SOURCE, "", pos=(10,15), size=(350,500), style = wx.TE_MULTILINE|wx.HSCROLL)
       # Make this control a Text Drop Target
       # Create a Text Drop Target object
       dt1 = TextDropTarget(self.text)
       # Link the Drop Target Object to the Text Control
       self.text.SetDropTarget(dt1)
       # Put some text in the control as a starting place to have something to copy
       for x in range(20):
          self.text.WriteText("This is line %d of some text to drag.\n" % x)
       # Define Right-Click as start of Drag
       wx.EVT_RIGHT_DOWN(self.text, self.OnDragInit)

       # Define a Text Control to recieve Dropped Text
       # Label the control
       wx.StaticText(self, -1, "Text Drop Target", (370, 1))
       # Create a read-only Text Control
       self.text2 = wx.TextCtrl(self, -1, "", pos=(370,15), size=(410,235), style = wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY)
       # Make this control a Text Drop Target
       # Create a Text Drop Target object
       dt2 = TextDropTarget(self.text2)
       # Link the Drop Target Object to the Text Control
       self.text2.SetDropTarget(dt2)

       # Define a Text Control to receive Dropped Files
       # Label the control
       wx.StaticText(self, -1, "File Drop Target (from off application only)", (370, 261))
       # Create a read-only Text Control
       self.text3 = wx.TextCtrl(self, -1, "", pos=(370,275), size=(410,235), style = wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY)
       # Make this control a File Drop Target
       # Create a File Drop Target object
       dt3 = FileDropTarget(self.text3)
       # Link the Drop Target Object to the Text Control
       self.text3.SetDropTarget(dt3)

       # Display the Window
       self.Show(True)


   def CloseWindow(self, event):
       """ Close the Window """
       self.Close()

   def OnDragInit(self, event):
       """ Begin a Drag Operation """
       # Create a Text Data Object, which holds the text that is to be dragged
       tdo = wx.PyTextDataObject(self.text.GetStringSelection())
       # Create a Drop Source Object, which enables the Drag operation
       tds = wx.DropSource(self.text)
       # Associate the Data to be dragged with the Drop Source Object
       tds.SetData(tdo)
       # Initiate the Drag Operation
       tds.DoDragDrop(True)



class MyApp(wx.App):
   """ Define the Drag and Drop Example Application """
   def OnInit(self):
      """ Initialize the Application """
      # Declare the Main Application Window
      frame = MainWindow(None, -1, "Drag and Drop Example")
      # Show the Application as the top window
      self.SetTopWindow(frame)
      return True


# Declare the Application and start the Main Loop
app = MyApp(0)
app.MainLoop()
}}}
- David K. Woods, Wisconsin Center for Education Research, University of Wisconsin, Madison

(If you like this example, there's another, more complex example of Drag and Drop behavior in the TreeControls section.)

 * File/bitmap/text

= wxDataObjectComposite =
This class is used when you wish to be able to deal with multiple data formats. The sample code should demonstrate this I've left out any processing, and just show you how to "get" the required data.

{{{#!python
class YourDropTarget(wx.PyDropTarget):
    """Implements drop target functionality to receive files, bitmaps and text"""
    def __init__(self):
        wx.PyDropTarget.__init__(self)
        self.do = wx.DataObjectComposite()  # the dataobject that gets filled with the appropriate data
        self.filedo = wx.FileDataObject()
        self.textdo = wx.TextDataObject()
        self.bmpdo = wx.BitmapDataObject()
        self.do.Add(self.filedo)
        self.do.Add(self.bmpdo)
        self.do.Add(self.textdo)
        self.SetDataObject(self.do)


    def OnData(self, x, y, d):
        """
        Handles drag/dropping files/text or a bitmap
        """
        if self.GetData():
            df = self.do.GetReceivedFormat().GetType()

            if df in [wx.DF_UNICODETEXT, wx.DF_TEXT]:

                text = self.textdo.GetText()

            elif df == wx.DF_FILENAME:
                for name in self.filedo.GetFilenames():
                    print name

            elif df == wx.DF_BITMAP:
                bmp = self.bmpdo.GetBitmap()

        return d  # you must return this
}}}
= Accepting Thunderbird drag and drops =
Here's an example of how to use wx.DataObjectComposite to accept Thunderbird drag and drops as well as text and filenames.

{{{#!python

import wx


class DropTarget(wx.DropTarget):
    def __init__(self, textCtrl, *args, **kwargs):
        super(DropTarget, self).__init__(*args, **kwargs)
        self.textCtrl = textCtrl
        self.composite = wx.DataObjectComposite()
        self.textDropData = wx.TextDataObject()
        self.fileDropData = wx.FileDataObject()
        self.thunderbirdDropData = wx.CustomDataObject('text/x-moz-message')
        self.composite.Add(self.thunderbirdDropData)
        self.composite.Add(self.textDropData)
        self.composite.Add(self.fileDropData)
        self.SetDataObject(self.composite)

    def OnDrop(self, x, y):
        return True

    def OnData(self, x, y, result):
        self.GetData()
        formatType, formatId = self.GetReceivedFormatAndId()
        if formatId == 'text/x-moz-message':
            return self.OnThunderbirdDrop()
        elif formatType in (wx.DF_TEXT, wx.DF_UNICODETEXT):
            return self.OnTextDrop()
        elif formatType == wx.DF_FILENAME:
            return self.OnFileDrop()

    def GetReceivedFormatAndId(self):
        format = self.composite.GetReceivedFormat()
        formatType = format.GetType()
        try:
            formatId = format.GetId() # May throw exception on unknown formats
        except:
            formatId = None
        return formatType, formatId

    def OnThunderbirdDrop(self):
        self.textCtrl.AppendText(self.thunderbirdDropData.GetData().decode('utf-16'))
        self.textCtrl.AppendText('\n')
        return wx.DragCopy

    def OnTextDrop(self):
        self.textCtrl.AppendText(self.textDropData.GetText() + '\n')
        return wx.DragCopy

    def OnFileDrop(self):
        for filename in self.fileDropData.GetFilenames():
            self.textCtrl.AppendText(filename + '\n')
        return wx.DragCopy


class Frame(wx.Frame):
    def __init__(self, *args, **kwargs):
        super(Frame, self).__init__(*args, **kwargs)
        textCtrl = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        textCtrl.SetDropTarget(DropTarget(textCtrl))


app = wx.App(False)
frame = Frame(None)
frame.Show()
app.MainLoop()
}}}
=== Comments... ===
I will add a example for dragging items in a wxTreeCtrl and what is more interesting how to drag a '''branch''' in a wxTreeCtrl. if added it will be found under ListAndTreeControls.

'''--René Freund'''

----

= Files-and-Folders drop target Classes =
The following are reusable classes based on wx.TextCtrl and wx.ListCtrl, each which receive file and folder names dropped from the filesystem GUI. These classes uses the file drag-and-drop technique shown above. When each drop is made to any of these controls, a "drop data" dictionary is created for each drop event that holds the dropFile data processed into more directly useful forms, i.e., the common parent path, a list of basenames and leaf folders, etc.

To be able to get and process the dropped files' data dictionary without altering the base classes a callback-function reference is passed in when instantiating any of the classes.  The drop handler simply calls the main app's callback function with the drop-data dictionary as the only call parameter. This way the app can define a custom callback function that can process the file and folder data uniquely to each instantiated control. Since the drop controls are classes, multiple controls based on these classes may be individual drop targets in the same app having completely separate file/folder drop processing.For instance (no pun intended), Both the multi-files drop control and the multi-folder/directory controls are both derived from the [ FilesDirsDropCtrl.py ] class. One simply filters the drop dictionary for only files and links while the other accepts only folders.

When adding files and folders, duplicate filenames and folders are ignored. Each control displays a simple message in the form of a pseudo (false) row data item. On the first drop this message is replaced by row(s) of true file and folder path info. The multi-line controls have the additional capability in which the user can delete line items using a context (right-click) menu. Deleting all the listed dropped files causes the help message to be redisplayed.More context menu items can easily be added, such as "delete all row data", "save row data to file", "add file contents to row data", etc.

When files and folders are dropped on the multi-line controls, the first column widths undergo true autosizing of both the row data entries and the column headers (whichever is wider) which, unfortunately, is lacking in tha basic wx.ListCtrl column autosizing method.

[[attachment:FilesDirsDrop_Demo.zip]]

{{attachment:FilesDirsDrop_Demo.png}}

Ray Pasco  2012-06-05

----