-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_widget.py
100 lines (72 loc) · 3 KB
/
app_widget.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QTextEdit
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QFileDialog
from find_window import FindWindow
import os
import uuid
from shutil import copyfile
IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.bmp']
HTML_EXTENSIONS = ['.htm', '.html']
class AppWidget(QWidget):
def __init__(self):
super().__init__()
# Create main layout to nest new layouts within
self.mainLayout = QVBoxLayout()
# Create Text box
self.textBox = TextEdit()
self.mainLayout.addWidget(self.textBox)
# Create find window
self.findWindow = FindWindow(self.textBox)
# Set main layout to app widget
self.setLayout(self.mainLayout)
# Opens the image file dialog and inserts an image into the QTextEdit
def insertImage(self):
filePath, _ = QFileDialog.getOpenFileName(
self, 'Select an Image', '', 'PNG (*.png);;JPEG (*.jpg *.jpeg)')
if filePath:
# Create image directory
if not os.path.exists('users/' + self.textBox.mainWindow.user + '/images'):
os.makedirs(
'users/' + self.textBox.mainWindow.user + '/images')
dest = copyfile(filePath, 'users/' + self.textBox.mainWindow.user +
'/images/' + os.path.basename(filePath))
self.textBox.textCursor().insertImage(dest)
def hexuuid():
return uuid.uuid4().hex
def splitext(p):
return os.path.splitext(p)[1].lower()
class TextEdit(QTextEdit):
def canInsertFromMimeData(self, source):
if source.hasImage():
return True
else:
return super(TextEdit, self).canInsertFromMimeData(source)
def insertFromMimeData(self, source):
cursor = self.textCursor()
document = self.document()
if source.hasUrls():
for u in source.urls():
file_ext = splitext(str(u.toLocalFile()))
if u.isLocalFile() and file_ext in IMAGE_EXTENSIONS:
image = QImage(u.toLocalFile())
document.addResource(QTextDocument.ImageResource, u, image)
# Create image directory
if not os.path.exists('users/' + self.mainWindow.user + '/images'):
os.makedirs(
'users/' + self.mainWindow.user + '/images')
dest = copyfile(u.toLocalFile(
), 'users/' + self.mainWindow.user + '/images/' + os.path.basename(u.toLocalFile()))
cursor.insertImage(dest)
else:
break
else:
return
elif source.hasImage():
image = source.imageData()
uuid = hexuuid()
document.addResource(QTextDocument.ImageResource, uuid, image)
cursor.insertImage(uuid)
return
super(TextEdit, self).insertFromMimeData(source)