-
-
Notifications
You must be signed in to change notification settings - Fork 91
/
utils.py
390 lines (290 loc) · 10.8 KB
/
utils.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# -*- coding: utf-8 -*-
# (C) 2013 Minoru Akagi
# SPDX-License-Identifier: GPL-2.0-or-later
# begin: 2013-12-29
import os
import base64
import configparser
import re
import shutil
from PyQt5.QtCore import qDebug as qDebugA, QBuffer, QByteArray, QDir, QFile, QFileInfo, QIODevice, QObject, QProcess, QSettings, QUrl, QUuid, pyqtSignal
from PyQt5.QtGui import QDesktopServices, QImage
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QFileDialog, QVBoxLayout
from qgis.core import NULL, Qgis, QgsMapLayer, QgsMessageLog, QgsProject
from qgis.gui import QgsCompoundColorWidget
from .conf import DEBUG_MODE, PLUGIN_NAME
# message logging
correspondent = None
class Correspondent(QObject):
messageSent = pyqtSignal(str, str) # message, level
def logMessage(message, warning=False, error=False):
if correspondent:
if warning:
level = "warn"
elif error:
level = "error"
else:
level = "debug"
correspondent.messageSent.emit(message, level)
level = Qgis.Critical if error else (Qgis.Warning if warning else Qgis.Info)
QgsMessageLog.logMessage(str(message), PLUGIN_NAME, level, warning or error)
def qDebug(message):
qDebugA(message.encode("utf-8"))
#
def getLayersInProject():
layers = []
for tl in QgsProject.instance().layerTreeRoot().findLayers():
if tl.layer():
layers.append(tl.layer())
return layers
def getDEMLayersInProject():
layers = []
for layer in getLayersInProject():
if layer.type() == QgsMapLayer.RasterLayer:
if layer.providerType() == "gdal" and layer.bandCount() == 1:
layers.append(layer)
return layers
def getLayersByLayerIds(layerIds):
layers = []
for id in layerIds:
layer = QgsProject.instance().mapLayer(id)
if layer:
layers.append(layer)
return layers
def js_bool(o):
return "true" if o else "false"
def css_color(c):
if isinstance(c, list):
if len(c) == 4 and c[3] != 255:
return "rgba({},{},{},{:.2f})".format(*c[:3], c[3] / 255)
return "rgb({},{},{})".format(*c[:3])
return str(c).replace("0x", "#") if c else "#000000"
def hex_color(c, prefix="#"):
if isinstance(c, list):
return "{}{:02x}{:02x}{:02x}".format(prefix, *c[:3])
if not c and prefix == "#":
return "#000000"
return prefix + str(c or 0).replace("0x", "").replace("#", "")
def int_color(c):
if isinstance(c, list):
return c[0] * 256 * 256 + c[1] * 256 + c[2]
if isinstance(c, str):
return int(c.replace("#", "0x") or "0", 16)
return 0
def pyobj2js(obj, escape=False, quoteHex=True):
if isinstance(obj, dict):
items = ["{0}:{1}".format(k, pyobj2js(v, escape, quoteHex)) for k, v in obj.items()]
return "{" + ",".join(items) + "}"
elif isinstance(obj, list):
items = [str(pyobj2js(v, escape, quoteHex)) for v in obj]
return "[" + ",".join(items) + "]"
elif isinstance(obj, bool):
return "true" if obj else "false"
elif isinstance(obj, str):
if escape:
return '"' + obj.replace("\\", "\\\\").replace('"', '\\"') + '"'
if not quoteHex and re.match("0x[0-9A-Fa-f]+$", obj):
return obj
return '"' + obj + '"'
elif isinstance(obj, bytes):
return pyobj2js(obj.decode("UTF-8"), escape, quoteHex)
elif isinstance(obj, (int, float)):
return obj
elif obj == NULL: # qgis.core.NULL
return "null"
return '"' + str(obj) + '"'
def abchex(number):
h = ""
for c in "{:x}".format(number):
i = ord(c)
if i >= 97: # a - f => k - p
h += chr(i + 10)
else: # 0 - 9 => a - j
h += chr(i + 49)
return h
# parse a string to a integer number. if failed, return def_val.
def parseInt(string, def_val=None):
try:
return int(string)
except (TypeError, ValueError):
return def_val
# parse a string to a floating point number. if failed, return def_val.
def parseFloat(string, def_val=None):
try:
return float(string)
except (TypeError, ValueError):
return def_val
def createUid():
return QUuid.createUuid().toString()[1:9]
def shortTextFromSelectedLayerIds(layerIds):
count = len(layerIds)
return "{0} layer{1} selected".format(count, "s" if count > 1 else "")
#
if count == 0:
return "0 layer"
layer = QgsProject.instance().mapLayer(layerIds[0])
if layer is None:
return "Layer not found"
text = '"{0}"'.format(layer.name())
if count > 1:
text += " and {0} layer".format(count - 1)
if count > 2:
text += "s"
return text
def openUrl(url):
"""url: QUrl object"""
if url.fileName().endswith((".html", ".htm")):
settings = QSettings()
browserPath = settings.value("/Qgis2threejs/browser", "", type=str)
if browserPath:
if QProcess.startDetached(browserPath, [url.toString()]):
return
else:
logMessage("Incorrect web browser path. Open URL using default web browser.", warning=True)
QDesktopServices.openUrl(url)
def openDirectory(dir_path):
QDesktopServices.openUrl(QUrl.fromLocalFile(dir_path))
def image2dataUri(image, fmt="PNG"):
ba = QByteArray()
buffer = QBuffer(ba)
buffer.open(QIODevice.WriteOnly)
image.save(buffer, fmt.upper())
return "data:image/{};base64,".format(fmt.lower()) + ba.toBase64().data().decode("ascii")
def base64file(file_path):
try:
with open(file_path, "rb") as f:
return base64.b64encode(f.read()).decode("ascii")
except:
logMessage("Cannot read file: {}".format(file_path), warning=True)
return ""
def imageFile2dataUri(file_path):
imgType = os.path.splitext(file_path)[1].lower()[1:].replace("jpg", "jpeg")
return "data:image/{};base64,".format(imgType) + base64file(file_path)
def jpegCompressedImage(image):
ba = QByteArray()
buffer = QBuffer(ba)
buffer.open(QIODevice.WriteOnly)
image.save(buffer, "JPEG")
return QImage.fromData(ba, "JPEG")
def getTemplateConfig(template_path):
abspath = os.path.join(templateDir(), template_path)
meta_path = os.path.splitext(abspath)[0] + ".txt"
if not os.path.exists(meta_path):
return {}
parser = configparser.ConfigParser()
parser.read(meta_path)
config = {"path": abspath}
for item in parser.items("general"):
config[item[0]] = item[1]
if DEBUG_MODE:
qDebug("config: " + str(config))
return config
def copyFile(source, dest, overwrite=False):
if os.path.exists(dest):
if overwrite or abs(QFileInfo(source).lastModified().secsTo(QFileInfo(dest).lastModified())) > 5: # use secsTo for different file systems
if DEBUG_MODE:
qDebug("Existing file removed: %s (%s, %s)" % (dest, str(QFileInfo(source).lastModified()), str(QFileInfo(dest).lastModified())))
QFile.remove(dest)
else:
if DEBUG_MODE:
qDebug("File already exists: %s" % dest)
return False
ret = QFile.copy(source, dest)
if DEBUG_MODE:
if ret:
qDebug("File copied: %s to %s" % (source, dest))
else:
qDebug("Failed to copy file: %s to %s" % (source, dest))
return ret
def copyDir(source, dest, overwrite=False):
if os.path.exists(dest):
if overwrite:
if DEBUG_MODE:
qDebug("Existing dir removed: %s" % dest)
shutil.rmtree(dest)
else:
if DEBUG_MODE:
qDebug("Dir already exists: %s" % dest)
return False
shutil.copytree(source, dest)
if DEBUG_MODE:
qDebug("Dir copied: %s to %s" % (source, dest))
return True
def copyFiles(filesToCopy, out_dir):
plugin_dir = pluginDir()
for item in filesToCopy:
dest_dir = os.path.join(out_dir, item.get("dest", ""))
subdirs = item.get("subdirs", False)
overwrite = item.get("overwrite", False)
if DEBUG_MODE:
qDebug(str(item))
qDebug("dest dir: %s" % dest_dir)
# make destination directory
QDir().mkpath(dest_dir)
# copy files
for f in item.get("files", []):
fi = QFileInfo(f)
dest = os.path.join(dest_dir, fi.fileName())
if fi.isRelative():
copyFile(os.path.join(plugin_dir, f), dest, overwrite)
else:
copyFile(f, dest, overwrite)
# copy directories
for d in item.get("dirs", []):
fi = QFileInfo(d)
source = os.path.join(plugin_dir, d) if fi.isRelative() else d
dest = os.path.join(dest_dir, fi.fileName())
if subdirs:
copyDir(source, dest, overwrite)
else:
# make destination directory
QDir().mkpath(dest)
# copy files in the source directory
filenames = QDir(source).entryList(QDir.Files)
for filename in filenames:
copyFile(os.path.join(source, filename), os.path.join(dest, filename), overwrite)
def removeTemporaryFiles(filelist):
for file in filelist:
QFile.remove(file)
def removeTemporaryOutputDir():
removeDir(temporaryOutputDir())
def removeDir(dirName):
d = QDir(dirName)
if d.exists():
for info in d.entryInfoList(QDir.Dirs | QDir.Files | QDir.NoDotAndDotDot):
if info.isDir():
removeDir(info.absoluteFilePath())
else:
d.remove(info.fileName())
d.rmdir(dirName)
def pluginDir(*subdirs):
p = os.path.dirname(__file__)
if subdirs:
return os.path.join(p, *subdirs)
return p
def templateDir():
return pluginDir("html_templates")
def temporaryOutputDir():
return QDir.tempPath() + "/Qgis2threejs"
def settingsFilePath():
proj_path = QgsProject.instance().fileName()
return proj_path + ".qto3settings" if proj_path else ""
def selectColor(parent=None):
dlg = QDialog(parent)
dlg.setWindowTitle("Select a color")
dlg.setLayout(QVBoxLayout())
widget = QgsCompoundColorWidget()
widget.setAllowOpacity(False)
dlg.layout().addWidget(widget)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(dlg.accept)
buttonBox.rejected.connect(dlg.reject)
dlg.layout().addWidget(buttonBox)
if dlg.exec_():
return widget.color()
def selectImageFile(parent=None, directory=None):
if directory is None:
directory = QDir.homePath()
filterString = "Supported image files (*.png *.jpg *.jpeg *.gif *.bmp)"
filename, _ = QFileDialog.getOpenFileName(parent, "Select an image file", directory, filterString)
return filename