def __init__(self, source, files): """ Initializes the object. """ self.handler = None self.allow_move = True # Put the data to be dragged on the clipboard: clipboard.data = files clipboard.source = source clipboard.drop_source = self data_object = wx.FileDataObject() if isinstance(files, str): files = [files] for file in files: data_object.AddFile(file) # Create the drop source and begin the drag and drop operation: super(FileDropSource, self).__init__(source) self.SetData(data_object) self.result = self.DoDragDrop(True)
def OnBeginDrag(self, event): posn = event.GetIndex() if posn == -1: event.Skip() return a = self.root.control.GetPage(posn).GetWindow1() data = a.getlong() if not data: data = a.getshort() ## data = data.encode('ascii') d = wx.FileDataObject() d.AddFile(data) ## print d.GetFilenames() a = wx.DropSource(self) a.SetData(d) if a.DoDragDrop(wx.Drag_AllowMove | wx.Drag_CopyOnly): #we use a time so that users can (almost immediately) click on #another document to switch. self.justdragged = time.time() self.root.control.other_focus = 1
def ClipBoardFiles(): ret = [] try: if wx.TheClipboard.Open(): if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)): do = wx.TextDataObject() wx.TheClipboard.GetData(do) filenames = do.GetText().splitlines() for f in filenames: try: fp = Path(f) if fp.is_dir(): for fp2 in fp.resolve().glob("*"): if fp2.is_file(): ret.append(str(fp2)) else: ret.append(f) except (OSError, IOError): pass elif wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_FILENAME)): do = wx.FileDataObject() wx.TheClipboard.GetData(do) filenames = do.GetFilenames() for f in filenames: try: fp = Path(f) if fp.is_dir(): for fp2 in fp.resolve().glob("*"): if fp2.is_file(): ret.append(str(fp2)) else: ret.append(f) except (OSError, IOError): pass wx.TheClipboard.Close() except (OSError, IOError): pass return ret
def copy(files): """\ Returns True on success, False otherwise. """ global _cornice_cutting _cornice_cutting = False if wx.TheClipboard.Open(): try: cdo = wx.DataObjectComposite() fdo = wx.FileDataObject() for f in files: fdo.AddFile(f) cdo.Add(fdo) cdo.Add(wx.DataObjectSimple(_cornice_marker_format)) if not wx.TheClipboard.SetData(cdo): print(_("Data can't be copied to the clipboard.")) return False return True finally: wx.TheClipboard.Close() else: print(_("The clipboard can't be opened.")) return False
def _startDragEvent(self, e): # create temp folder # folder = libs.config.WORK_PATH + "/temp" # libs.config.mkdirs(folder) text = self.__dataList.GetItem(e.GetIndex()).GetText() text = text if text[0] == "/" else "/" + text # temp_file = os.path.join(folder, os.path.basename(text if text[0] == "/" else "/" + text)) # Create drag data data = wx.FileDataObject() data.AddFile(text) # Create drop source and begin drag-and-drop. dropSource = wx.DropSource(self.__dataList) dropSource.SetData(data) # Get Source res = dropSource.DoDragDrop(flags=wx.Drag_AllowMove) if res == wx.DragMove or res == wx.DragCopy: ## 下载 print("DragMove & DragCopy") return text
def OnFigureSelect(self, event): sender = event.GetEventObject() choice = event.GetString() if choice.isdigit(): num = int(choice) if sender == self.select: P.figure(num) elif sender == self.copy: fig = P.figure(num) if self.copy_as_file: if wx.TheClipboard.Open(): # save to temp file fd, path = tempfile.mkstemp('.pdf', text=True) # os.write(fd, pdf) os.close(fd) logging.debug("Temporary file created at: %s" % path) fig.savefig(path) # copy path # shutil.copyfileobj(f, 'bar.txt') do = wx.FileDataObject() do.AddFile(path) wx.TheClipboard.SetData(do) wx.TheClipboard.Close() else: fig.set_facecolor((1, 1, 1)) P.draw() canvas = fig.canvas if hasattr(canvas, 'Copy_to_Clipboard'): canvas.Copy_to_Clipboard() else: logging.warning("Could Not Copy Figure %s To ClipBoard" % num) else: raise ValueError("URK!") sender.SetSelection(0)
def _handler_files_motion(self, event): """Handler for when user drags a file selection somewhere. """ if not event.Dragging(): event.Skip() return lc = self._view_frame.files_lc selected_idxs = [] s = lc.GetFirstSelected() while s != -1: selected_idxs.append(s) s = lc.GetNextSelected(s) if len(selected_idxs) > 0: data_object = wx.FileDataObject() for idx in selected_idxs: data_object.AddFile(self._item_data_to_file[idx]) drop_source = wx.DropSource(lc) drop_source.SetData(data_object) drop_source.DoDragDrop(False)
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 )
def __init__(self, parent): super().__init__(wx.FileDataObject()) self.parent = parent # tabが入る
def DoFileExportDragDrop(window, page_key, media, cmd_down): drop_source = wx.DropSource(window) data_object = wx.DataObjectComposite() # hydrus_media_data_object = wx.CustomDataObject('application/hydrus-media') hashes = [m.GetHash() for m in media] if page_key is None: encoded_page_key = None else: encoded_page_key = page_key.encode('hex') data = (encoded_page_key, [hash.encode('hex') for hash in hashes]) data = json.dumps(data) hydrus_media_data_object.SetData(data) data_object.Add(hydrus_media_data_object, True) # file_data_object = wx.FileDataObject() client_files_manager = HG.client_controller.client_files_manager original_paths = [] for m in media: hash = m.GetHash() mime = m.GetMime() original_path = client_files_manager.GetFilePath( hash, mime, check_file_exists=False) original_paths.append(original_path) # do_temp_dnd = False new_options = HG.client_controller.new_options if new_options.GetBoolean('discord_dnd_fix'): if len(original_paths) <= 10 and sum( (os.path.getsize(path) for path in original_paths)) < 50 * 1048576: do_temp_dnd = True temp_dir = HG.client_controller.temp_dir if do_temp_dnd and os.path.exists(temp_dir): dnd_paths = [] for original_path in original_paths: filename = os.path.basename(original_path) dnd_path = os.path.join(temp_dir, filename) if not os.path.exists(dnd_path): HydrusPaths.MirrorFile(original_path, dnd_path) dnd_paths.append(dnd_path) flags = wx.Drag_AllowMove else: dnd_paths = original_paths if cmd_down: # secret dangerous discord compat mode flags = wx.Drag_AllowMove else: flags = wx.Drag_CopyOnly for path in dnd_paths: file_data_object.AddFile(path) data_object.Add(file_data_object) # drop_source.SetData(data_object) result = drop_source.DoDragDrop(flags) return result
def __init__(self): super(DummyEditorDataObjectComposite, self).__init__() self.file_data = wx.FileDataObject() self.text_data = wx.TextDataObject() self.Add(self.file_data, True) self.Add(self.text_data)
def _return_if_file(): clip_data = wx.FileDataObject() success = clipboard.GetData(clip_data) if not success: return self.setThrottle("slow") os_file_paths_new = sorted(clip_data.GetFilenames()) try: os_file_sizes_new = map( lambda each_os_path: getFolderSize(each_os_path, max=MAX_FILE_SIZE) if os.path.isdir(each_os_path) else os.path.getsize( each_os_path), os_file_paths_new) except: return if sum(os_file_sizes_new) > MAX_FILE_SIZE: self.sb.toggleStatusIcon( msg= 'Files not uploaded. Maximum files size is 50 megabytes.', icon="bad") return #upload error clip #print os_file_paths_new os_file_hashes_old_set = CLIENT_RECENT_DATA.get() os_file_hashes_new = [] os_file_names_new = [] display_file_names = [] for each_path in os_file_paths_new: each_file_name = os.path.split(each_path)[1] os_file_names_new.append(each_file_name) if os.path.isdir(each_path): display_file_names.append(each_file_name + " folder (%s inside)" % len(os.listdir(each_path)) + "._folder") os_folder_hashes = [] for dirName, subdirList, fileList in os.walk( each_path, topdown=False): subdirList = filter for fname in fileList: if fname.upper( ) not in FILE_IGNORE_LIST: #DO NOT calculate hash for system files as they are always changing, and if a folder is in clipboard, a new upload may be initiated each time a system file is changed each_sub_path = os.path.join(dirName, fname) with open(each_sub_path, 'rb') as each_sub_file: each_relative_path = each_sub_path.split( each_path )[1] #c:/python27/lib/ - c:/python27/lib/bin/abc.pyc = bin/abc.pyc each_relative_hash = each_relative_path + hex( hash128(each_sub_file.read()) ) #WARNING- some files like thumbs.db constantly change, and therefore may cause an infinite upload loop. Need an ignore list. os_folder_hashes.append( each_relative_hash ) #use relative path+filename and hash so that set does not ignore two idenitcal files in different sub-directories. Why? let's say bin/abc.pyc and usr/abc.pyc are identical, without the aforementioned system, a folder with just bin/abc.pyc will yield same hash as bin/abc.pyc + usr/abc.pyc, not good. #gevent.sleep()#print each_relative_hash each_file_name = os.path.split(each_path)[1] os_folder_hashes.sort() each_data = "".join(os_folder_hashes) #whole folder hash else: #single file display_file_names.append(each_file_name) with open(each_path, 'rb') as each_file: each_file_name = os.path.split(each_path)[1] each_data = each_file.read() name_and_data_hash = os_file_hashes_new.append( each_file_name + format(hash128(each_data), "x") + self.websocket_worker.ACCOUNT_SALT ) #append the hash for this file #use filename and hash so that set does not ignore copies of two idenitcal files (but different names) in different directories os_file_hashes_new_set = set(os_file_hashes_new) if os_file_hashes_old_set == set( os_file_hashes_new ): #checks to make sure if name and file are the same return for each_new_path in os_file_paths_new: try: if os.path.isdir(each_new_path): distutils.dir_util.copy_tree( each_new_path, os.path.join(TEMP_DIR, os.path.split(each_new_path)[1])) else: distutils.file_util.copy_file(each_new_path, TEMP_DIR) except distutils.errors.DistutilsFileError: pass print "\nRETURN!!!!\n" clip_hash_secure = hashlib.new( "ripemd160", "".join(os_file_hashes_new) + self.websocket_worker.ACCOUNT_SALT ).hexdigest( ) #MUST use list of files instead of set because set does not guarantee order and therefore will result in a non-deterministic hash return __prepare_for_upload(file_names=os_file_names_new, clip_type="files", clip_display=display_file_names, clip_hash_secure=clip_hash_secure, compare_next=os_file_hashes_new_set)
def setClipboardContent(self, container_name, clip_type): #NEEDS TO BE IN MAIN LOOP FOR WRITING TO WORK, OR ELSE WE WILL #GET SOMETHING LIKE: "Failed to put data on the clipboard #(error 2147221008: coInitialize has not been called.)" success = False try: with wx.TheClipboard.Get() as clipboard: self.sb.toggleStatusIcon( msg='Downloading and decrypting %s data...' % clip_type, icon="unlock") container_path = self.downloadClipFileIfNotExist( container_name) if container_path: print "DECRYPT" with encompress.Encompress(password="******", directory=TEMP_DIR, file_name_decrypt=container_name ) as file_paths_decrypt: #print file_paths_decrypt if clip_type in ["text", "link"]: clip_file_path = file_paths_decrypt[0] with open(clip_file_path, 'r') as clip_file: clip_text = self.decodeClip(clip_file.read()) clip_data = wx.TextDataObject() clip_data.SetText(clip_text) success = clipboard.SetData(clip_data) elif clip_type == "bitmap": clip_file_path = file_paths_decrypt[0] bitmap = wx.Bitmap(clip_file_path, wx.BITMAP_TYPE_BMP) clip_data = wx.BitmapDataObject(bitmap) success = clipboard.SetData(clip_data) elif clip_type == "files": clip_file_paths = file_paths_decrypt clip_data = wx.FileDataObject() for each_file_path in clip_file_paths: clip_data.AddFile(each_file_path) success = clipboard.SetData(clip_data) else: self.destroyBusyDialog() wx.MessageBox( "Unable to download this clip from the server", "Error") except: wx.MessageBox("Unexpected error: %s" % sys.exc_info()[0], "Error", wx.ICON_ERROR) self.destroyBusyDialog() if success: self.sb.toggleStatusIcon(msg='Successfully received %s data.' % clip_type, icon="good") return success
def DoFileExportDragDrop( window, page_key, media, alt_down ): drop_source = wx.DropSource( window ) data_object = wx.DataObjectComposite() # hydrus_media_data_object = wx.CustomDataObject( 'application/hydrus-media' ) hashes = [ m.GetHash() for m in media ] if page_key is None: encoded_page_key = None else: encoded_page_key = page_key.hex() data_obj = ( encoded_page_key, [ hash.hex() for hash in hashes ] ) data_str = json.dumps( data_obj ) data_bytes = bytes( data_str, 'utf-8' ) hydrus_media_data_object.SetData( data_bytes ) data_object.Add( hydrus_media_data_object, True ) # file_data_object = wx.FileDataObject() client_files_manager = HG.client_controller.client_files_manager original_paths = [] total_size = 0 for m in media: hash = m.GetHash() mime = m.GetMime() total_size += m.GetSize() original_path = client_files_manager.GetFilePath( hash, mime, check_file_exists = False ) original_paths.append( original_path ) # new_options = HG.client_controller.new_options secret_discord_dnd_fix_possible = new_options.GetBoolean( 'secret_discord_dnd_fix' ) and alt_down discord_dnd_fix_possible = new_options.GetBoolean( 'discord_dnd_fix' ) and len( original_paths ) <= 50 and total_size < 200 * 1048576 temp_dir = HG.client_controller.temp_dir if secret_discord_dnd_fix_possible: dnd_paths = original_paths flags = wx.Drag_AllowMove elif discord_dnd_fix_possible and os.path.exists( temp_dir ): dnd_paths = [] for original_path in original_paths: filename = os.path.basename( original_path ) dnd_path = os.path.join( temp_dir, filename ) if not os.path.exists( dnd_path ): HydrusPaths.MirrorFile( original_path, dnd_path ) dnd_paths.append( dnd_path ) flags = wx.Drag_AllowMove else: dnd_paths = original_paths flags = wx.Drag_CopyOnly for path in dnd_paths: file_data_object.AddFile( path ) data_object.Add( file_data_object ) # drop_source.SetData( data_object ) result = drop_source.DoDragDrop( flags ) return result
def ToClipboard( self, data_type, data ): # need this cause can't do it in a non-gui thread if data_type == 'paths': paths = data if wx.TheClipboard.Open(): data = wx.DataObjectComposite() file_data = wx.FileDataObject() for path in paths: file_data.AddFile( path ) text_data = wx.TextDataObject( os.linesep.join( paths ) ) data.Add( file_data, True ) data.Add( text_data, False ) wx.TheClipboard.SetData( data ) wx.TheClipboard.Close() else: wx.MessageBox( 'Could not get permission to access the clipboard!' ) elif data_type == 'text': text = data if wx.TheClipboard.Open(): data = wx.TextDataObject( text ) wx.TheClipboard.SetData( data ) wx.TheClipboard.Close() else: wx.MessageBox( 'I could not get permission to access the clipboard.' ) elif data_type == 'bmp': media = data image_renderer = self.GetCache( 'images' ).GetImageRenderer( media ) def CopyToClipboard(): if wx.TheClipboard.Open(): wx_bmp = image_renderer.GetWXBitmap() data = wx.BitmapDataObject( wx_bmp ) wx.TheClipboard.SetData( data ) wx.TheClipboard.Close() else: wx.MessageBox( 'I could not get permission to access the clipboard.' ) def THREADWait(): # have to do this in thread, because the image needs the wx event queue to render start_time = time.time() while not image_renderer.IsReady(): if HydrusData.TimeHasPassed( start_time + 15 ): raise Exception( 'The image did not render in fifteen seconds, so the attempt to copy it to the clipboard was abandoned.' ) time.sleep( 0.1 ) wx.CallAfter( CopyToClipboard ) self.CallToThread( THREADWait )
def __init__(self, window, log): wx.DropTarget.__init__(self) self.log = log self.do = wx.FileDataObject() self.SetDataObject(self.do)
def __init__(self, dicom_reader): wx.PyDropTarget.__init__(self) self._fdo = wx.FileDataObject() self.SetDataObject(self._fdo) self._dicom_reader = dicom_reader