eric6/WebBrowser/Tools/WebBrowserTools.py

changeset 6942
2602857055c5
parent 6645
ad476851d7e0
child 7192
a22eee00b052
equal deleted inserted replaced
6941:f99d60d6b59b 6942:2602857055c5
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2016 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing tool functions for the web browser.
8 """
9
10 from __future__ import unicode_literals
11 try:
12 str = unicode # __IGNORE_EXCEPTION__
13 except NameError:
14 pass
15
16 import os
17 import re
18
19 from PyQt5.QtCore import QFile, QByteArray, QUrl, QCoreApplication, QBuffer, \
20 QIODevice
21 from PyQt5.QtGui import QPixmap
22
23
24 def readAllFileContents(filename):
25 """
26 Function to read the string contents of the given file.
27
28 @param filename name of the file
29 @type str
30 @return contents of the file
31 @rtype str
32 """
33 return str(readAllFileByteContents(filename), encoding="utf-8")
34
35
36 def readAllFileByteContents(filename):
37 """
38 Function to read the bytes contents of the given file.
39
40 @param filename name of the file
41 @type str
42 @return contents of the file
43 @rtype str
44 """
45 dataFile = QFile(filename)
46 if filename and dataFile.open(QFile.ReadOnly):
47 contents = dataFile.readAll()
48 dataFile.close()
49 return contents
50
51 return QByteArray()
52
53
54 def containsSpace(string):
55 """
56 Function to check, if a string contains whitespace characters.
57
58 @param string string to be checked
59 @type str
60 @return flag indicating the presence of at least one whitespace character
61 @rtype bool
62 """
63 for ch in string:
64 if ch.isspace():
65 return True
66
67 return False
68
69
70 def ensureUniqueFilename(name, appendFormat="({0})"):
71 """
72 Module function to generate an unique file name based on a pattern.
73
74 @param name desired file name (string)
75 @param appendFormat format pattern to be used to make the unique name
76 (string)
77 @return unique file name
78 """
79 if not os.path.exists(name):
80 return name
81
82 tmpFileName = name
83 i = 1
84 while os.path.exists(tmpFileName):
85 tmpFileName = name
86 index = tmpFileName.rfind(".")
87
88 appendString = appendFormat.format(i)
89 if index == -1:
90 tmpFileName += appendString
91 else:
92 tmpFileName = tmpFileName[:index] + appendString + \
93 tmpFileName[index:]
94 i += 1
95
96 return tmpFileName
97
98
99 def getFileNameFromUrl(url):
100 """
101 Module function to generate a file name based on the given URL.
102
103 @param url URL (QUrl)
104 @return file name (string)
105 """
106 fileName = url.toString(QUrl.RemoveFragment | QUrl.RemoveQuery |
107 QUrl.RemoveScheme | QUrl.RemovePort)
108 if fileName.find("/") != -1:
109 pos = fileName.rfind("/")
110 fileName = fileName[pos:]
111 fileName = fileName.replace("/", "")
112
113 fileName = filterCharsFromFilename(fileName)
114
115 if not fileName:
116 fileName = filterCharsFromFilename(url.host().replace(".", "_"))
117
118 return fileName
119
120
121 def filterCharsFromFilename(name):
122 """
123 Module function to filter illegal characters.
124
125 @param name name to be sanitized (string)
126 @return sanitized name (string)
127 """
128 return name\
129 .replace("/", "_")\
130 .replace("\\", "")\
131 .replace(":", "")\
132 .replace("*", "")\
133 .replace("?", "")\
134 .replace('"', "")\
135 .replace("<", "")\
136 .replace(">", "")\
137 .replace("|", "")
138
139
140 def pixmapFromByteArray(data):
141 """
142 Module function to convert a byte array to a pixmap.
143
144 @param data data for the pixmap
145 @type bytes or QByteArray
146 @return extracted pixmap
147 @rtype QPixmap
148 """
149 pixmap = QPixmap()
150 barray = QByteArray.fromBase64(data)
151 pixmap.loadFromData(barray)
152
153 return pixmap
154
155
156 def pixmapToByteArray(pixmap):
157 """
158 Module function to convert a pixmap to a byte array containing the pixmap
159 as a PNG encoded as base64.
160
161 @param pixmap pixmap to be converted
162 @type QPixmap
163 @return byte array containing the pixmap
164 @rtype QByteArray
165 """
166 byteArray = QByteArray()
167 buffer = QBuffer(byteArray)
168 buffer.open(QIODevice.WriteOnly)
169 if pixmap.save(buffer, "PNG"):
170 return buffer.buffer().toBase64()
171
172 return QByteArray()
173
174
175 def pixmapToDataUrl(pixmap):
176 """
177 Module function to convert a pixmap to a data: URL.
178
179 @param pixmap pixmap to be converted
180 @type QPixmap
181 @return data: URL
182 @rtype QUrl
183 """
184 data = bytes(pixmapToByteArray(pixmap)).decode()
185 if data:
186 return QUrl("data:image/png;base64," + data)
187 else:
188 return QUrl()
189
190
191 def getWebEngineVersions():
192 """
193 Module function to extract the web engine version from the default user
194 agent string.
195
196 @return tuple containing the Chrome version and the QtWebEngine version
197 @rtype tuple of str
198 """
199 from PyQt5.QtWebEngineWidgets import QWebEngineProfile
200
201 useragent = QWebEngineProfile.defaultProfile().httpUserAgent()
202 match = re.search(r"""Chrome/([\d.]+)""", useragent)
203 if match:
204 chromeVersion = match.group(1)
205 else:
206 chromeVersion = QCoreApplication.translate(
207 "WebBrowserTools", "<unknown>")
208 match = re.search(r"""QtWebEngine/([\d.]+)""", useragent)
209 if match:
210 webengineVersion = match.group(1)
211 else:
212 webengineVersion = QCoreApplication.translate(
213 "WebBrowserTools", "<unknown>")
214 return (chromeVersion, webengineVersion)

eric ide

mercurial