示例#1
0
    def __init__(self,
                 parent,
                 filenames_callable=None,
                 url_callable=None,
                 media_callable=None,
                 page_callable=None):

        wx.DropTarget.__init__(self)

        self._parent = parent

        self._filenames_callable = filenames_callable
        self._url_callable = url_callable
        self._media_callable = media_callable
        self._page_callable = page_callable

        self._receiving_data_object = wx.DataObjectComposite()

        self._hydrus_media_data_object = wx.CustomDataObject(
            'application/hydrus-media')
        self._hydrus_page_tab_data_object = wx.CustomDataObject(
            'application/hydrus-page-tab')
        self._file_data_object = wx.FileDataObject()
        self._text_data_object = wx.TextDataObject()

        self._receiving_data_object.Add(self._hydrus_media_data_object, True)
        self._receiving_data_object.Add(self._hydrus_page_tab_data_object)
        self._receiving_data_object.Add(self._file_data_object)
        self._receiving_data_object.Add(self._text_data_object)

        self.SetDataObject(self._receiving_data_object)
示例#2
0
def get_data_object(widget):
    data = dump_widget(widget)
    # make a data object
    if isinstance(widget, edit_sizers.Sizer):
        do = wx.CustomDataObject(sizer_data_format)
    elif getattr(widget, "_is_toplevel", False):
        do = wx.CustomDataObject(window_data_format)
    else:
        do = wx.CustomDataObject(widget_data_format)
    do.SetData(data)
    return do
示例#3
0
    def test_DataObjectComposite(self):
        do = wx.DataObjectComposite()
        df1 = wx.DataFormat("data type 1")
        df2 = wx.DataFormat("data type 2")
        d1 = wx.CustomDataObject(df1)
        d2 = wx.CustomDataObject(df2)
        do.Add(d1, True)
        do.Add(d2)

        self.assertTrue(do.GetPreferredFormat() == df1)
        d3 = do.GetObject(df2)
        self.assertTrue(isinstance(d3, wx.CustomDataObject))
        self.assertTrue(d3 is d2)
示例#4
0
	def __init__(self, panel):
		wx.PyDropTarget.__init__(self)
		self.panel = panel
		self.tree = self.panel.tree

		self.controllerData = wx.CustomDataObject("xxx")
		self.specialData = wx.CustomDataObject("special")

		self.data = wx.DataObjectComposite()
		self.data.Add(self.controllerData)
		self.data.Add(self.specialData)

		self.SetDataObject(self.data)
    def ClipboardDataObject(self):
        # why is ClipboardDataObject a method and not an attribute?
        if getattr(self, 'clipboard', None) is None:
            self.clipboard = wx.DataObjectComposite()

            self.fileDataObject = wx.FileDataObject()
            self.fileFormat = self.fileDataObject.GetFormat()

            self.itemFormat = wx.CustomDataFormat(self.ClipboardDataFormat())
            self.itemDataObject = wx.CustomDataObject(self.itemFormat)

            self.clipboard.Add(self.itemDataObject)
            self.clipboard.Add(self.fileDataObject)

            self.dataFormats = {}
            self.dataObjects = {}

            def addCustom(name):
                format = self.dataFormats[name] = wx.CustomDataFormat(name)
                obj = self.dataObjects[name] = wx.CustomDataObject(format)
                self.clipboard.Add(obj)
                self.clipboard.SetData(format, '')

            map(addCustom, [OUTLOOK_EXPRESS_DRAG_FORMAT])

            # for some reason compositeObject starts non-empty, empty it
            self.clipboard.SetData(self.itemFormat, '')

        return self.clipboard
    def CopyData(self):
        """
        Called to get a widget's data at the beginning of a Copy or DnD.
        Returns a wxDataObject variant for use in Drag and Drop, or
        Cut and Paste.
        
        This implementation deals with Items using UUIDs, using the Domain Model
        to determine what formats to export.
        """
        compositeObject = wx.DataObjectComposite()

        # Build a dictionary of Item data formats
        self.exportDict = {}
        items = self.SelectedItems()
        for item in items:
            # add to the 'Item' list of our dictionary
            self.ExportItemFormat(item, 'Item')
            try:
                # ask the ContentItem to append its kinds too
                item.ExportItemData(self)
            except AttributeError:
                pass

        # now create a custom data object for each kind
        for format, itemList in self.exportDict.items():
            customData = wx.CustomDataObject(wx.CustomDataFormat(format))
            customData.SetData(self.ExportClipboardItems(itemList))
            compositeObject.Add(customData)

        return compositeObject
示例#7
0
文件: toolbox.py 项目: thaolt/gui2py
    def start_drag_opperation(self, evt):
        "Event handler for drag&drop functionality"
    
        # get the control
        ctrl = self.menu_ctrl_map[evt.GetToolId()]

        # create our own data format and use it in a custom data object
        ldata = wx.CustomDataObject("gui")
        ldata.SetData(ctrl._meta.name)      # only strings are allowed!

        # Also create a Bitmap version of the drawing
        bmp = ctrl._image.GetBitmap()

        # Now make a data object for the bitmap and also a composite
        # data object holding both of the others.
        bdata = wx.BitmapDataObject(bmp)
        data = wx.DataObjectComposite()
        data.Add(ldata)
        data.Add(bdata)

        # And finally, create the drop source and begin the drag
        # and drop opperation
        dropSource = wx.DropSource(self)
        dropSource.SetData(data)
        if DEBUG: print("Begining DragDrop\n")
        result = dropSource.DoDragDrop(wx.Drag_AllowMove)
        if DEBUG: print("DragDrop completed: %d\n" % result)

        if result == wx.DragMove:
            if DEBUG: print "dragmove!"
            self.Refresh()
示例#8
0
    def OnMotion(self, evt):
        if not evt.LeftIsDown() or not self.leftPressed:
            return
        self.bin.SetFocusIgnoringChildren()
        # Removed for Linux compatibility
        #cursorImg = self.bitmap.ConvertToImage()
        #cursorImg.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_X, int(self.bitmap.Size[0])/2)
        #cursorImg.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, int(self.bitmap.Size[1])/2)
        #cursor = wx.CursorFromImage(cursorImg)

        # wx crashes unless the data object is assigned to a variable.
        data_object = wx.CustomDataObject("ObjectKey")
        data_object.SetData(
            cPickle.dumps((self.bin.GetId(), self.bin.SelectedKeys())))
        source = wx.DropSource(self)  #, copy=cursor, move=cursor)
        source.SetData(data_object)
        result = source.DoDragDrop(wx.Drag_DefaultMove)
        # def cb():
        #     self.bin.RemoveKeys(self.bin.SelectedKeys()) # Hack to fix drag move
        # wx.CallAfter(cb)
        #if result is wx.DragMove:
        self.bin.RemoveSelectedTiles(
        )  # Removes images which stays during drag and drop
        self.bin.UpdateSizer()
        self.bin.UpdateQuantity()
示例#9
0
    def on_add(self, _):
        if self.bdm is None:
            return
        cdo = wx.CustomDataObject("BDMEntry")
        success = False
        if wx.TheClipboard.Open():
            success = wx.TheClipboard.GetData(cdo)
            wx.TheClipboard.Close()
        if not success:
            with wx.MessageDialog(self, 'Unable to get copied data') as dlg:
                dlg.ShowModal()
                return
        paste_data = pickle.loads(cdo.GetData())

        # Get new Id's
        with NewEntryDialog(self, self.get_current_entry_ids()) as dlg:
            if dlg.ShowModal() != wx.ID_OK:
                return
            entry_id = dlg.GetValue()
        current_entry_ids = self.get_current_entry_ids()
        self.entry_list.UnselectAll()

        # Paste
        for paste in paste_data:
            while entry_id in current_entry_ids:
                entry_id += 1
            entry = Entry(entry_id=entry_id)
            entry.paste(paste)
            self.add_entry(entry)
            entry_id += 1

        self.on_select(None)
        pub.sendMessage(f'Pasted {len(paste_data)} new entry(s)')
示例#10
0
    def __init__(self, handler):
        """ Constructor

        The handler can be either a function that will be called when
        *any* data is dropped onto the target, or an instance that supports
        the 'wx_drag_over' and 'wx_dropped_on' methods. The latter case
        allows the target to veto the drop.

        """

        # Base-class constructor.
        super(PythonDropTarget, self).__init__()

        # The handler can either be a function that will be called when
        # any data is dropped onto the target, or an instance that supports
        # the 'wx_drag_over' and 'wx_dropped_on' methods. The latter case
        # allows the target to veto the drop.
        self.handler = handler

        # Specify the type of data we will accept.
        self.data_object = wx.DataObjectComposite()
        self.data = wx.CustomDataObject(PythonObject)
        self.data_object.Add(self.data, preferred=True)
        self.file_data = wx.FileDataObject()
        self.data_object.Add(self.file_data)
        self.SetDataObject(self.data_object)

        return
示例#11
0
 def OnBeginDrag(self, event):
     if not self.fnDndAllow(event): return
     indices = []
     start = stop = -1
     for index in xrange(self.GetItemCount()):
         if self.GetItemState(index, _wx.LIST_STATE_SELECTED):
             if stop >= 0 and self.dndOnlyCont:
                 # Only allow moving selections if they are in a
                 # continuous block...they aren't
                 return
             if start < 0:
                 start = index
             indices.append(index)
         else:
             if start >= 0 > stop:
                 stop = index - 1
     if stop < 0: stop = self.GetItemCount()
     selected = pickle.dumps(indices, 1)
     ldata = _wx.CustomDataObject(u'ListIndexes')
     ldata.SetData(selected)
     data_object = _wx.DataObjectComposite()
     data_object.Add(ldata)
     source = _wx.DropSource(self)
     source.SetData(data_object)
     source.DoDragDrop(flags=_wx.Drag_DefaultMove)
示例#12
0
    def pasteWidgets(self, pos=(0, 0), logicals=False):
        """Pastes widgets from the clipboard."""
        clipFormat = wx.DataFormat(StoryPanel.CLIPBOARD_FORMAT)
        clipData = wx.CustomDataObject(clipFormat)

        if wx.TheClipboard.Open():
            gotData = wx.TheClipboard.IsSupported(
                clipFormat) and wx.TheClipboard.GetData(clipData)
            wx.TheClipboard.Close()

            if gotData:
                data = pickle.loads(clipData.GetData())

                self.eachWidget(lambda w: w.setSelected(False, False))

                if not pos: pos = StoryPanel.INSET
                if not logicals: pos = self.toLogical(pos)

                for widget in data:
                    newPassage = PassageWidget(self,
                                               self.app,
                                               state=widget,
                                               pos=pos,
                                               title=self.untitledName(
                                                   widget['passage'].title))
                    newPassage.findSpace()
                    newPassage.setSelected(True, False)
                    self.widgetDict[newPassage.passage.title] = newPassage
                    self.snapWidget(newPassage, False)

                self.parent.setDirty(True, action='Paste')
                self.resize()
                self.Refresh()
示例#13
0
    def startDrag(self, e):
        # Créer les données à transférer
        l = []
        idx = -1
        # Réccuppérer l'object de la liste sélectionné
        idx = self.GetFocusedItem()

        # Si idx n'a pas d'erreur
        if idx != -1:
            item = self.GetItem(idx, 0).GetText()
            source = self.itemID

            # Sinon, ajouter l'objet à nos données
            l.append(item)
            l.append(source)
            l.append(self.sourceType)

        # Convertir la liste de données en octets
        itemdata = cPickle.dumps(l, 1)

        # Créer un format de données personnalisé
        ldata = wx.CustomDataObject('ListCtrlItems')
        ldata.SetData(itemdata)

        # Créer les données qui vont être transférées
        data = wx.DataObjectComposite()
        data.Add(ldata)

        # Créer une source de Drag and Drop
        self.dropSource.SetData(data)

        # Commencer le drag and drop
        self.dropSource.DoDragDrop()
示例#14
0
    def __init__(self, source):
        wx.DropTarget.__init__(self)
        self.dv = source

        # specify the type of data we will accept
        self.data = wx.CustomDataObject("ListCtrlItems")
        self.SetDataObject(self.data)
示例#15
0
    def __init__(self, window):
        wx.PyDropTarget.__init__(self)
        self._scrollFrame = window

        # specify the type of data we will accept
        self.data = wx.CustomDataObject("Case")
        self.SetDataObject(self.data)
示例#16
0
    def _startDrag(self, e):
        """ Put together a data object for drag-and-drop _from_ this list. """
        l = ['Series']
        # mostly need the ItemData, which is the record ID in the DataSeries table
        idx = self.GetFirstSelected()
        l.append(self.GetItemData(idx))
        # as a convenience, pass the list row text 
        l.append(self.GetItemText(idx))
        # and the ChannelSegment list column to put it in
        l.append(1)

        # Pickle the object
        itemdata = cPickle.dumps(l, 1)
        # create our own data format and use it in a
        # custom data object
        ldata = wx.CustomDataObject("RecIDandTable")
        ldata.SetData(itemdata)
        # Now make a data object for the  item list.
        data = wx.DataObjectComposite()
        data.Add(ldata)

        # Create drop source and begin drag-and-drop.
        dropSource = wx.DropSource(self)
        dropSource.SetData(data)
        res = dropSource.DoDragDrop(flags=wx.Drag_DefaultMove)

        # If move, we could remove the item from this list.
        if res == wx.DragMove:
            pass # disable removing, we only want to assign its info to the other list
示例#17
0
    def __init__(self, panel):
        wx.PyDropTarget.__init__(self)
        self.panel = panel
        self.tree = self.panel.tree

        self.data = wx.CustomDataObject("record")
        self.SetDataObject(self.data)
示例#18
0
def get_data_object(widget):
    data = dump_widget(widget)
    # make a data object
    if isinstance(widget, edit_sizers.Sizer):
        do = wx.CustomDataObject(sizer_data_format)
    elif getattr(widget, "_is_toplevel", False):
        do = wx.CustomDataObject(window_data_format)
    else:
        do = wx.CustomDataObject(widget_data_format)
    do.SetData(data)
    cdo = wx.DataObjectComposite()
    cdo.Add(do)
    if widget.name:
        cdo.Add(wx.TextDataObject(widget.name),
                True)  # the widget name as text, preferred
    return cdo
示例#19
0
    def __init__(self, target):
        wx.TextDropTarget.__init__(self)
        self.target = target
        self.target.SetEditable(False)

        self.text_obj = wx.CustomDataObject('py_str')
        self.SetDataObject(self.text_obj)
示例#20
0
def paste(widget):
    """Copies a widget (and all its children) from the clipboard to the given
    destination (parent, sizer and position inside the sizer). Returns True on success."""
    error = None
    if not wx.TheClipboard.Open():
        misc.error_message("Clipboard can't be opened.")
        return False

    try:
        data_object = None
        for fmt in [widget_data_format, sizer_data_format, window_data_format]:
            if wx.TheClipboard.IsSupported(fmt):
                data_object = wx.CustomDataObject(fmt)
                break
        if data_object is None:
            misc.info_message(
                "The clipboard doesn't contain wxGlade widget data.")
            return False
        if not wx.TheClipboard.GetData(data_object):
            misc.error_message("Data can't be copied from clipboard.")
            return False
    finally:
        wx.TheClipboard.Close()
    format_name = data_object.GetFormat().GetId().split(".")[
        1]  # e.g. 'wxglade.widget' -> 'widget'
    compatible, message = widget.check_compatibility(None, format_name)
    if not compatible:
        wx.Bell()
        if message:
            misc.error_message(message)
        return False
    if not widget.clipboard_paste(data_object.GetData()):
        misc.error_message("Paste failed")
示例#21
0
    def CanPaste(self):
        if not wx.TheClipboard.Open():
            return False
        try:
            dataObj = wx.CustomDataObject("DragEventItem")
            if wx.TheClipboard.GetData(dataObj):
                if self.DropTest(eg.EventItem):
                    return True

            dataObj = wx.TextDataObject()
            if not wx.TheClipboard.GetData(dataObj):
                return False
            try:
                data = dataObj.GetText().encode("utf-8")
                tagToCls = self.document.XMLTag2ClassDict
                try:
                    rootXmlNode = ElementTree.fromstring(data)
                except SyntaxError:
                    return False
                for childXmlNode in rootXmlNode:
                    childCls = tagToCls[childXmlNode.tag.lower()]
                    if self.DropTest(childCls) & HINT_MOVE_INSIDE:
                        continue
                    if self.parent is None:
                        return False
                    elif not self.parent.DropTest(childCls) & HINT_MOVE_INSIDE:
                        return False
            except:
                if eg.debugLevel:
                    raise
                return False
        finally:
            wx.TheClipboard.Close()
        return True
示例#22
0
    def __init__(self, source, data, handler=None, allow_move=True):
        """ Creates a new drop source.

        A drop source should be created for *every* drag operation.

        If allow_move is False then the operation will default to
        a copy and only copy operations will be allowed.
        """

        # The handler can either be a function that will be called when
        # the data has been dropped onto the target, or an instance that
        # supports the 'on_dropped' method.
        self.handler = handler
        self.allow_move = allow_move

        # Put the data to be dragged on the clipboard.
        clipboard.data = data
        clipboard.source = source
        clipboard.drop_source = self

        # Create our own data format and use it in a custom data object.
        data_object = wx.CustomDataObject(PythonObject)
        data_object.SetData('dummy')

        # And finally, create the drop source and begin the drag
        # and drop opperation.
        wx.DropSource.__init__(self, source)
        self.SetData(data_object)
        if allow_move:
            flags = wx.Drag_DefaultMove | wx.Drag_AllowMove
        else:
            flags = wx.Drag_CopyOnly
        self.result = self.DoDragDrop(flags)

        return
示例#23
0
def copy(widget):
    """\
    Store a widget copy into the clipboard

    @param widget: Widget to copy

    @return: True on success
    @rtype: bool
    """
    if wx.TheClipboard.Open():
        try:
            xml_unicode = StringIO.StringIO()
            widget.node.write(xml_unicode, 0)
            flag = widget.esm_border.get_string_style()
            option = widget.get_option()
            border = widget.get_border()
            clipboard_data = widget2clipboard(option, flag, border,
                                              xml_unicode.getvalue())
            wdo = wx.CustomDataObject(widget_data_format)
            wdo.SetData(clipboard_data)
            if not wx.TheClipboard.SetData(wdo):
                logging.debug(_("Data can't be copied to clipboard."))
                return False
            return True
        finally:
            wx.TheClipboard.Close()
    else:
        logging.info(_("Clipboard can't be opened."))
        return False
示例#24
0
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.bdm = None
        self.parent = parent

        self.entry_list = TreeListCtrl(self, style=TL_MULTIPLE)
        self.entry_list.AppendColumn("Entry")
        self.entry_list.Bind(EVT_TREELIST_ITEM_CONTEXT_MENU,
                             self.on_right_click)
        self.entry_list.Bind(EVT_TREELIST_SELECTION_CHANGED, self.on_select)
        self.cdo = wx.CustomDataObject("BDMEntry")

        self.Bind(wx.EVT_MENU, self.on_delete, id=wx.ID_DELETE)
        self.Bind(wx.EVT_MENU, self.on_copy, id=wx.ID_COPY)
        self.Bind(wx.EVT_MENU, self.on_paste, id=wx.ID_PASTE)
        self.Bind(wx.EVT_MENU, self.on_new, id=wx.ID_NEW)
        accelerator_table = wx.AcceleratorTable([
            (wx.ACCEL_CTRL, ord('c'), wx.ID_COPY),
            (wx.ACCEL_CTRL, ord('v'), wx.ID_PASTE),
            (wx.ACCEL_NORMAL, wx.WXK_DELETE, wx.ID_DELETE),
        ])
        self.entry_list.SetAcceleratorTable(accelerator_table)

        pub.subscribe(self.on_select, 'on_select')
        pub.subscribe(self.convert_for_skill_creator,
                      'convert_for_skill_creator')

        # Use some sizers to see layout options
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.entry_list, 1, wx.ALL | wx.EXPAND, 10)

        # Layout sizers
        self.SetSizer(sizer)
        self.SetAutoLayout(1)
示例#25
0
    def on_copy(self, _):
        items_to_copy = self.get_selected_root_nodes()
        if not items_to_copy:
            return
        # Check to make sure all items are the same
        data = [self.entry_list.GetItemData(item) for item in items_to_copy]
        item_type, actual_type = self.get_item_type_of_item_list(items_to_copy)
        if not item_type:
            with wx.MessageDialog(self, 'All copied items must be of the same type') as dlg:
                dlg.ShowModal()
            return

        self.cdo = wx.CustomDataObject("BCSEntry")
        self.cdo.SetData(pickle.dumps(data))
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(self.cdo)
            wx.TheClipboard.Flush()
            wx.TheClipboard.Close()

        pub.sendMessage("enable_add_copy")

        if isinstance(data[0], list):
            pub.sendMessage('set_status_bar', text=f'Copied {len(data)} {item_type.get_readable_name()} lists')
        else:
            pub.sendMessage('set_status_bar', text=f'Copied {len(data)} {item_type.get_readable_name()} items')
示例#26
0
 def test_CustomDataObject(self):
     import pickle
     data1 = list(range(10))
     obj = wx.CustomDataObject('my custom format')
     obj.SetData(pickle.dumps(data1))
     data2 = pickle.loads(obj.GetData().tobytes())
     self.assertEqual(data1, data2)
示例#27
0
    def OnCmdCopy(self, dummyEvent=None):
        text = ""
        lines = 1
        firstItem = item = self.GetNextItem(-1, wx.LIST_NEXT_ALL,
                                            wx.LIST_STATE_SELECTED)
        if item != -1:
            text = self.OnGetItemText(item, 0)[1:]
            item = self.GetNextItem(item, wx.LIST_NEXT_ALL,
                                    wx.LIST_STATE_SELECTED)
            while item != -1:
                lines += 1
                text += "\r\n" + self.OnGetItemText(item, 0)[1:]
                item = self.GetNextItem(item, wx.LIST_NEXT_ALL,
                                        wx.LIST_STATE_SELECTED)
        if text != "" and wx.TheClipboard.Open():
            textDataObject = wx.TextDataObject(text)
            dataObjectComposite = wx.DataObjectComposite()
            dataObjectComposite.Add(textDataObject)
            if lines == 1:
                eventstring, icon = self.GetItemData(firstItem)[:2]
                if icon == EVENT_ICON:
                    customDataObject = wx.CustomDataObject("DragEventItem")
                    customDataObject.SetData(eventstring.encode("UTF-8"))
                    dataObjectComposite.Add(customDataObject)

            wx.TheClipboard.SetData(dataObjectComposite)
            wx.TheClipboard.Close()
            wx.TheClipboard.Flush()
示例#28
0
    def on_paste(self, _):
        item = self.select_single_item()
        if not item or item == self.entry_list.GetRootItem():
            return

        success = False
        cdo = wx.CustomDataObject("BCMEntry")
        if wx.TheClipboard.Open():
            success = wx.TheClipboard.GetData(cdo)
            wx.TheClipboard.Close()
        if not success:
            return

        paste_data = pickle.loads(cdo.GetData())[0]
        entry = self.entry_list.GetItemData(item)

        # Keep address/parent/child
        paste_data.address = entry.address
        paste_data.parent = entry.parent
        paste_data.child = entry.child
        paste_data.sibling = entry.sibling

        self.entry_list.SetItemData(item, paste_data)
        self.reindex()
        pub.sendMessage('load_entry', entry=self.entry_list.GetItemData(item))
        pub.sendMessage('set_status_bar',
                        text='Pasted to ' + self.entry_list.GetItemText(item))
示例#29
0
    def on_copy(self, _):
        item = self.select_single_item()
        if not item or item == self.entry_list.GetRootItem():
            return
        selections = [item]
        if self.entry_list.GetChildrenCount(item) > 0:
            with wx.MessageDialog(self, 'Copy children entries as well?', '',
                                  wx.YES | wx.NO) as dlg:
                if dlg.ShowModal() == wx.ID_YES:
                    selections.extend(self.get_children(item))

        entries = sorted(
            [self.entry_list.GetItemData(item) for item in selections],
            key=lambda data: data.address)

        self.cdo = wx.CustomDataObject("BCMEntry")
        self.cdo.SetData(pickle.dumps(entries))
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(self.cdo)
            wx.TheClipboard.Flush()
            wx.TheClipboard.Close()
        msg = 'Copied ' + self.entry_list.GetItemText(item)
        if len(entries) > 1:
            msg += f' and {len(entries) - 1} children'
        pub.sendMessage('set_status_bar', text=msg)
示例#30
0
    def getHtmlFromClipboard():
        """
        Retrieve HTML source from clipboard. Returns a tuple (source, URL)
        where source is the HTML sourcecode and URL is the URL where it came
        from. Both or one of the items may be None.
        """
        from StringOps import lineendToInternal, mbcsDec

        cb = wx.TheClipboard
        cb.Open()
        try:
            df = wx.CustomDataFormat("HTML Format")
            dataob = wx.CustomDataObject(df)

            if cb.GetData(dataob):
                if dataob.GetSize() > 0:
                    raw = dataob.GetData()

                    # Windows HTML clipboard format contains a header with additional
                    # information
                    start = None
                    end = None
                    sourceUrl = None

                    canBreak = lambda : start is not None and end is not None \
                            and sourceUrl is not None

                    pos = 0
                    try:
                        for line in raw.split("\r\n"):
                            if line.startswith("StartFragment:"):
                                start = int(line[14:])
                                if canBreak():
                                    break
                            elif line.startswith("EndFragment:"):
                                end = int(line[14:])
                                if canBreak():
                                    break
                            elif line.startswith("SourceURL:"):
                                sourceUrl = line[10:]
                                if canBreak():
                                    break
                            pos += len(line) + 2
                            if start is not None and pos >= start:
                                break

                    except ValueError:
                        return (None, None)

                    if start is None or end is None:
                        return (None, None)

                    return (lineendToInternal(
                        dataob.GetData()[start:end]).decode(
                            "utf-8", "replace"), sourceUrl)

            return (None, None)
        finally:
            cb.Close()