from PyQt6.QtCore import QMimeData, QUrl from PyQt6.QtGui import QDragEnterEvent, QDropEvent import os class DragDropHandler: """Обработчик drag-n-drop событий""" def __init__(self, main_window): self.main_window = main_window def handle_drag_enter(self, event: QDragEnterEvent): """Обработчик события перетаскивания в окно""" if event.mimeData().hasUrls() or event.mimeData().hasText(): event.acceptProposedAction() self.main_window.show_drag_drop_interface(event.mimeData()) def handle_drag_leave(self, event): """Обработчик события выхода перетаскивания из окна""" self.main_window.dragLeaveEvent(event) def save_image_by_url(self, url): from PIL import Image import requests from io import BytesIO response = requests.get(url) img = Image.open(BytesIO(response.content)) img.save(f"data/{os.path.basename(url)}") return f"data/{os.path.basename(url)}" def handle_drop(self, event: QDropEvent): """Обработчик события отпускания перетаскиваемого объекта""" mime_data = event.mimeData() if mime_data.hasUrls(): # Обработка файлов urls = mime_data.urls() if urls and urls[0].isLocalFile(): file_path = urls[0].toLocalFile() if self.is_image_file(file_path): self.main_window.handle_dropped_image(file_path) event.acceptProposedAction() else: # Если это не изображение, обрабатываем как текст self.main_window.handle_dropped_text("", 'file_drop', event.position().y()) else: file_path = self.save_image_by_url(mime_data.text()) if self.is_image_file(file_path): self.main_window.handle_dropped_image(file_path) event.acceptProposedAction() else: self.main_window.handle_dropped_text("", 'file_drop', event.position().y()) elif mime_data.hasText(): # Обработка текста text = mime_data.text() self.main_window.handle_dropped_text(text, 'text_drop', event.position().y()) event.acceptProposedAction() def is_image_file(self, file_path): """Проверяет, является ли файл изображением""" image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'} return os.path.splitext(file_path.lower())[1] in image_extensions