forked from geosim/QAD
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathqad_utils.py
More file actions
2438 lines (2053 loc) · 94.1 KB
/
qad_utils.py
File metadata and controls
2438 lines (2053 loc) · 94.1 KB
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
/***************************************************************************
QAD Quantum Aided Design plugin
funzioni varie di utilità
-------------------
begin : 2013-05-22
copyright : iiiii
email : hhhhh
developers : bbbbb aaaaa ggggg
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from qgis.PyQt.QtCore import QVariant, QDir, QMetaType
from qgis.PyQt.QtGui import QCursor, QPixmap, QColor, QFont, QPalette
from qgis.PyQt.QtWidgets import QToolTip, QMessageBox, QApplication
from qgis.core import *
import qgis.utils
import os
import math
import sys
from gettext import find
import configparser
import time
import uuid, re
from .qad_variables import QadVariables
from .qad_msg import QadMsg
# Modulo che gestisce varie funzionalità di QAD
def getMacAddress():
return ':'.join(re.findall('..', '%012x' % uuid.getnode())).upper()
def criptPlainText(strValue):
mytable = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz -./0123456789:;<=>?@"', \
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm9:;<=>?@" -./012345678')
return strValue.translate(mytable)
def decriptPlainText(strValue):
mytable = str.maketrans('NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm9:;<=>?@" -./012345678', \
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz -./0123456789:;<=>?@"')
return strValue.translate(mytable)
# ===============================================================================
# FUNZIONI GENERICHE PER LE OPZIONI DEI COMANDI - INIZIO
# ===============================================================================
def extractUpperCaseSubstr(str):
# estraggo la parte maiuscola della stringa
upperPart = ""
for letter in str:
if letter.isupper():
upperPart = upperPart + letter
elif len(upperPart) > 0:
break
return upperPart
def evaluateCmdKeyWords(cmd, keyWordList):
# Riceve un comando e la lista delle parole chiave delle opzioni di un comando
# La funzione ritorna la keyword del comando seguito da un eventuale messaggio di errore se la keyword = None
# The required portion of the keyword is specified in uppercase characters,
# and the remainder of the keyword is specified in lowercase characters.
# The uppercase abbreviation can be anywhere in the keyword
if cmd == "": # se cmd = "" la funzione find ritorna 0 (no comment)
return None, None
upperCmd = cmd.upper()
selectedKeyWords = []
for keyWord in keyWordList:
# estraggo la parte maiuscola della parola chiave
upperPart = extractUpperCaseSubstr(keyWord)
if upperPart.find(upperCmd) == 0: # se la parte maiuscola della parola chiave inizia per upperCmd
if upperPart == upperCmd: # Se uguale
return keyWord, None
else:
selectedKeyWords.append(keyWord)
elif keyWord.upper().find(upperCmd) == 0: # se la parola chiave inizia per cmd (insensitive)
if keyWord.upper() == upperCmd: # Se uguale
return keyWord, None
else:
selectedKeyWords.append(keyWord)
selectedKeyWordsLen = len(selectedKeyWords)
if selectedKeyWordsLen == 0:
return None, None
elif selectedKeyWordsLen == 1:
return selectedKeyWords[0], None
else:
Msg = QadMsg.translate("QAD", "\nAmbiguous answer: specify with more clarity...")
ambiguousMsg = ""
for keyWord in selectedKeyWords:
if ambiguousMsg == "":
ambiguousMsg = keyWord
else:
ambiguousMsg = ambiguousMsg + QadMsg.translate("QAD", " or ") + keyWord
Msg = Msg + "\n" + ambiguousMsg + QadMsg.translate("QAD", " ?\n")
return None, Msg
# ===============================================================================
# FUNZIONI GENERICHE PER LE OPZIONI DEI COMANDI - FINE
# FUNZIONI GENERICHE PER I WIDGET - INIZIO
# ===============================================================================
# ===============================================================================
# setMapCanvasToolTip
# ===============================================================================
# visualizza il testo della tooltip del mapCanvas con l'aspetto determinato da DYNTOOLTIPS
def setMapCanvasToolTip(msg):
canvas = qgis.utils.iface.mapCanvas()
pt = canvas.mapToGlobal(canvas.mouseLastXY())
if QadVariables.get(QadMsg.translate("Environment variables", "DYNTOOLTIPS")) == 1:
font_size = 8 + QadVariables.get(QadMsg.translate("Environment variables", "TOOLTIPSIZE"))
#opacity = 100 - QadVariables.get(QadMsg.translate("Environment variables", "TOOLTIPTRANSPARENCY"))
#fc.setAlphaF(opacity/100.0) # non va
fColor = QColor(QadVariables.get(QadMsg.translate("Environment variables", "DYNEDITFORECOLOR")))
bColor = QColor(QadVariables.get(QadMsg.translate("Environment variables", "DYNEDITBACKCOLOR")))
else:
font_size = QFont().pointSize()
p = QPalette()
fColor = p.color(QPalette.Inactive, QPalette.ToolTipText)
bColor = p.color(QPalette.Inactive, QPalette.ToolTipBase)
toolTipFont = QToolTip.font()
if toolTipFont.pointSize() != font_size:
toolTipFont.setPointSize(font_size)
QToolTip.setFont(toolTipFont)
toolTipPalette = QToolTip.palette()
if toolTipPalette.color(QPalette.Inactive, QPalette.ToolTipText) != fColor or \
toolTipPalette.color(QPalette.Inactive, QPalette.ToolTipBase) != bColor:
toolTipPalette.setColor(QPalette.Inactive, QPalette.ToolTipText, fColor)
toolTipPalette.setColor(QPalette.Inactive, QPalette.ToolTipBase, bColor)
QToolTip.setPalette(toolTipPalette)
QToolTip.showText(pt, msg)
return
# ===============================================================================
# floatLineEditWidgetValidation
# ===============================================================================
# controlla che il valore di un widget di tipo line edit soddisfi l'intervallo ammesso per la variabile di ambiente
def intLineEditWidgetValidation(widget, var, msg):
err = False
string = widget.text()
if str2int(string) is None:
err = True
else:
if var.minNum is not None:
if str2int(string) < var.minNum:
err = True
if var.maxNum is not None:
if str2int(string) > var.maxNum:
err = True
if err:
msg = msg + QadMsg.translate("QAD", ": enter a number")
if var.minNum is not None:
msg = msg + QadMsg.translate("QAD", " >= {0}").format(str(var.minNum))
if var.maxNum is not None:
if var.minNum is not None:
msg = msg + QadMsg.translate("QAD", " and")
msg = msg + QadMsg.translate("QAD", " <= {0}").format(str(var.maxNum))
msg = msg + "."
QMessageBox.critical(None, QadMsg.getQADTitle(), msg)
widget.setFocus()
widget.selectAll()
return False
return True
# ===============================================================================
# floatLineEditWidgetValidation
# ===============================================================================
# controlla che il valore di un widget di tipo line edit soddisfi l'intervallo ammesso per la variabile di ambiente
def floatLineEditWidgetValidation(widget, var, msg):
err = False
string = widget.text()
if str2float(string) is None:
err = True
else:
if var.minNum is not None:
if str2float(string) < var.minNum:
err = True
if var.maxNum is not None:
if str2float(string) > var.maxNum:
err = True
if err:
msg = msg + QadMsg.translate("QAD", ": enter a number")
if var.minNum is not None:
minValMsg = msg + QadMsg.translate("QAD", " > {0}").format(str(var.minNum))
else:
minValMsg = ""
if var.maxNum is not None:
if len(minValMsg) > 0:
msg = msg + QadMsg.translate("QAD", " and")
msg = msg + QadMsg.translate("QAD", " < {0}").format(str(var.maxNum))
msg = msg + "."
QMessageBox.critical(None, QadMsg.getQADTitle(), msg)
widget.setFocus()
widget.selectAll()
return False
return True
# ===============================================================================
# FUNZIONI GENERICHE PER I WIDGET - FINE
# ===============================================================================
# ===============================================================================
# isNumericField
# ===============================================================================
def isNumericField(field):
"""
La funzione verifica che il campo di tipo QgsField sia numerico
"""
fldType = field.type()
if fldType == QMetaType.Double or fldType == QMetaType.LongLong or fldType == QMetaType.Int or \
fldType == QMetaType.ULongLong or fldType == QMetaType.UInt:
return True
else:
return False
# ===============================================================================
# checkUniqueNewName
# ===============================================================================
def checkUniqueNewName(newName, nameList, prefix = None, suffix = None, caseSensitive = True):
"""
La funzione verifica che il nuovo nome non esistà già nella lista <nameList>.
Se nella lista dovesse già esistere allora aggiunge un prefisso (se <> None) o un suffisso (se <> None)
finchè il nome non è più presnete nella lista
"""
ok = False
result = newName
while ok == False:
ok = True
for name in nameList:
if caseSensitive == True:
if name == result:
ok = False
break
else:
if name.upper() == result.upper():
ok = False
break
if ok == True:
return result
if prefix is not None:
result = prefix + result
else:
if suffix is not None:
result = result + suffix
return None
# ===============================================================================
# wildCard2regularExpr
# ===============================================================================
def wildCard2regularExpr(wildCard, ignoreCase = True):
"""
Ritorna la conversione di una stringa con wildcards (es. "gas*")
in forma di regular expression (es. "[g][a][s].*")
"""
# ? -> .
# * -> .*
# altri caratteri -> [carattere]
regularExpr = ""
for ch in wildCard:
if ch == "?":
regularExpr = regularExpr + "."
elif ch == "*":
regularExpr = regularExpr + ".*"
else:
if ignoreCase:
regularExpr = regularExpr + "[" + ch.upper() + ch.lower() + "]"
else:
regularExpr = regularExpr + "[" + ch + "]"
return regularExpr
# ===============================================================================
# str2float
# ===============================================================================
def str2float(s):
"""
Ritorna la conversione di una stringa in numero reale
"""
try:
n = float(s)
return n
except ValueError:
return None
# ===============================================================================
# str2long
# ===============================================================================
def str2long(s):
"""
Ritorna la conversione di una stringa in numero lungo
"""
try:
n = long(s)
return n
except ValueError:
return None
# ===============================================================================
# str2int
# ===============================================================================
def str2int(s):
"""
Ritorna la conversione di una stringa in numero intero
"""
try:
n = int(s)
return n
except ValueError:
return None
# ===============================================================================
# str2bool
# ===============================================================================
def str2bool(s):
"""
Ritorna la conversione di una stringa in bool
"""
try:
upperS = s.upper()
# 16 = "N", 17 = "NO"
# "F" "FALSO"
if upperS == "0" or \
upperS == QadMsg.translate("QAD", "N") or \
upperS == QadMsg.translate("QAD", "NO") or \
upperS == QadMsg.translate("QAD", "F") or \
upperS == QadMsg.translate("QAD", "FALSE") or \
upperS == "FALSE":
return False
else:
return True
except ValueError:
return None
# ===============================================================================
# str2QgsPoint
# ===============================================================================
def str2QgsPoint(s, lastPoint = None, currenPoint = None, oneNumberAllowed = True):
"""
Ritorna la conversione di una stringa in punto QgsPointXY
se <oneNumberAllowed> = False significa che s non può essere un solo numero
che rappresenterebbe la distanza dall'ultimo punto con angolo in base al punto corrente
(questo viene vietato quando si vuole accettare un numero o un punto)
lastPoint viene usato solo per le espressioni tipo @10<45 (dall'ultimo punto, lunghezza 10, angolo 45 gradi)
o @ (dall'ultimo punto)
o @10,20 (dall'ultimo punto, + 10 per la X e + 20 per la Y)
o 100 (dall'ultimo punto, distanza 100, angolo in base al punto corrente)
"""
expression = s.strip() # senza spazi iniziali e finali
if len(expression) == 0:
return None
if expression[0] == "@": # coordinate relative a lastpoint
if lastPoint is None:
return None
if len(expression) == 1:
return lastPoint
expression = expression[1:] # scarto il primo carattere "@"
coords = expression.split(",")
if len(coords) == 2:
OffSetX = str2float(coords[0].strip())
OffSetY = str2float(coords[1].strip())
if (OffSetX is None) or (OffSetY is None):
return None
return QgsPointXY(lastPoint.x() + OffSetX, lastPoint.y() + OffSetY)
else:
if len(coords) != 1:
return None
# verifico se si sta usando la coordinata polare
expression = coords[0].strip()
values = expression.split("<")
if len(values) != 2:
return None
dist = str2float(values[0].strip())
angle = str2float(values[1].strip())
if (dist is None) or (angle is None):
return None
coords = getPolarPointByPtAngle(lastPoint, math.radians(angle), dist)
return QgsPointXY(coords[0], coords[1])
else:
# verifico se è specificato un CRS
CRS, newExpr = strFindCRS(expression)
if CRS is not None:
if CRS.isGeographic():
pt = strLatLon2QgsPoint(newExpr)
else:
coords = newExpr.split(",")
if len(coords) != 2:
return None
x = str2float(coords[0].strip())
y = str2float(coords[1].strip())
if (x is None) or (y is None):
return None
pt = QgsPointXY(x, y)
if pt is not None:
destCRS = qgis.utils.iface.mapCanvas().mapSettings().destinationCrs() # CRS corrente
return QgsCoordinateTransform(CRS, destCRS, QgsProject.instance()).transform(pt) # trasformo le coord
coords = expression.split(",")
if len(coords) == 2: # coordinate assolute
x = str2float(coords[0].strip())
y = str2float(coords[1].strip())
if (x is None) or (y is None):
return None
return QgsPointXY(x, y)
else:
if oneNumberAllowed == False: # vietato che la stringa sia un solo numero
return None
dist = str2float(expression)
if (dist is None) or (lastPoint is None) or (currenPoint is None):
return None
angle = getAngleBy2Pts(lastPoint, currenPoint)
coords = getPolarPointByPtAngle(lastPoint, angle, dist)
return QgsPointXY(coords[0], coords[1])
# ===============================================================================
# pointToStringFmt
# ===============================================================================
def pointToStringFmt(pt):
"""
Ritorna la conversione di un punto QgsPointXY in stringa formattata
"""
return numToStringFmt(pt.x()) + "," + numToStringFmt(pt.y())
# ===============================================================================
# numToStringFmt
# ===============================================================================
def numToStringFmt(n, textDecimals = 4, textDecimalSep = '.', \
textSuppressLeadingZeros = False, textDecimalZerosSuppression = True,
textPrefix = "", textSuffix = ""):
"""
Restituisce la conversione di un numero (int o float) in stringa formattata
"""
strIntPart, strDecPart = getStrIntDecParts(round(n, textDecimals)) # numero di decimali
if strIntPart == "0" and textSuppressLeadingZeros == True: # per sopprimere o meno gli zero all'inizio del testo
strIntPart = ""
for i in range(0, textDecimals - len(strDecPart), 1): # aggiunge "0" per arrivare al numero di decimali
strDecPart = strDecPart + "0"
if textDecimalZerosSuppression == True: # per sopprimere gli zero finali nei decimali
strDecPart = strDecPart.rstrip("0")
formattedText = "-" if n < 0 else "" # segno
formattedText = formattedText + strIntPart # parte intera
if len(strDecPart) > 0: # parte decimale
formattedText = formattedText + textDecimalSep + strDecPart # Separatore dei decimali
# aggiungo prefisso e suffisso per il testo della quota
return textPrefix + formattedText + textSuffix
# ===============================================================================
# strLatLon2QgsPoint
# ===============================================================================
def strFindCRS(s):
"""
Cerca il sistema di coordinate in una stringa indicante un punto (usa authid).
Il sistema di coordinate va espresso in qualsiasi punto della stringa e deve essere
racchiuso tra parentesi tonde (es "111,222 (EPSG:3003)")
Ritorna il SR e la stringa depurata del SR (es "111,222")
"""
initial = s.find("(")
if initial == -1:
return None, s
final = s.find(")")
if initial > final:
return None, s
authId = s[initial+1:final]
authId = authId.strip() # senza spazi iniziali e finali
return QgsCoordinateReferenceSystem(authId), s.replace(s[initial:final+1], "")
# ===============================================================================
# strLatLon2QgsPoint
# ===============================================================================
def strLatLon2QgsPoint(s):
"""
Ritorna la conversione di una stringa contenente una coordinata in latitudine longitudine
in punto QgsPointXY.
Sono supportati i seguenti formati:
DDD gradi decimali (49.11675S o S49.11675 o 49.11675 S o S 49.11675 o -49.1167)
DMS gradi minuti secondi (49 7 20.06)
DMM gradi minuti con secondi decimali (49 7.0055)
Sintassi latitudine longitudine:
Il separatore può essere uno spazio, puoi anche usare ' per i minuti e " per i secondi (47 7'20.06")
La notazione di direzione è N, S, E, W maiuscolo o minuscolo prima o dopo la coordinata
("N 37 24 23.3" o "N37 24 23.3" o "37 24 23.3 N" o "37 24 23.3N")
Puoi usare anche le coordinate negative per l'ovest e il sud.
La prima coordinata viene interpretata come latitudine a meno che specifichi una lettera di direzione (E o W)
("122 05 08.40 W 37 25 19.07 N")
Puoi usare uno spazio, una virgola o una barra per delimitare le coppie di valori
("37.7 N 122.2 W" o "37.7 N,122.2 W" o "37.7 N/122.2 W")
"""
expression = s.strip() # senza spazi iniziali e finali
if len(expression) == 0:
return None
numbers = []
directions = []
word = ""
for ch in s:
if ch.isnumeric() or ch == "." or ch == "-":
word += ch
else:
if len(word) > 0:
n = str2float(word)
if n is None:
return None
numbers.append(n)
word = ""
if ch == "N" or ch == "n" or ch == "S" or ch == "s" or ch == "E" or ch == "e" or ch == "W" or ch == "w":
directions.append(ch.upper())
word = ""
directions_len = len(directions)
if directions_len != 0 and directions_len != 2:
return None
numbers_len = len(numbers)
if numbers_len == 2: # DDD
lat = numbers[0]
lon = numbers[1]
elif numbers_len == 4: # DMM
degrees = numbers[0]
minutes = numbers[1]
lat = degrees + minutes / 60
degrees = numbers[2]
minutes = numbers[3]
lon = degrees + minutes / 60
elif numbers_len == 6: # DMS
degrees = numbers[0]
minutes = numbers[1]
seconds = numbers[2]
lat = degrees + minutes / 60 + seconds / 3600
degrees = numbers[3]
minutes = numbers[4]
seconds = numbers[5]
lon = degrees + minutes / 60 + seconds / 3600
else:
return None
if directions_len == 2:
if lat < 0 or lon < 0:
return None
if directions[0] == "N" or directions[0] == "S": # latitude first
if directions[0] == "S":
lat = -lat
elif directions[0] == "E" or directions[0] == "W": # longitude first
dummy = lat
lat = lon if directions[0] == "E" else -lon
lon = dummy if directions[1] == "S" else -value2
else:
return None
return QgsPointXY(lon, lat)
else: # latitude first
return QgsPointXY(lon, lat)
# ===============================================================================
# strip
# ===============================================================================
def strip(s, stripList):
"""
Rimuove dalla stringa <s> tutte le stringhe nella lista <stripList> che sono
all'inizio e anche alla fine della stringa <s>
"""
for item in stripList:
s = s.strip(item) # rimuovo prima e dopo
return s
# ===============================================================================
# findFile
# ===============================================================================
def findFile(fileName):
"""
Cerca il file indicato usando i percorsi indicati dalla variabile "SUPPORTPATH"
più il percorso locale di QAD. Ritorna il percorso del file in caso di successo
oppure "" in caso di file non trovato
"""
path = QadVariables.get(QadMsg.translate("Environment variables", "SUPPORTPATH"))
if len(path) > 0:
path += ";"
path += QgsApplication.qgisSettingsDirPath() + "python/plugins/qad/"
# lista di directory separate da ";"
dirList = path.strip().split(";")
for _dir in dirList:
_dir = QDir.cleanPath(_dir)
if _dir != "":
if _dir.endswith("/") == False:
_dir = _dir + "/"
_dir = _dir + fileName
if os.path.exists(_dir):
return _dir
return ""
return s
# ===============================================================================
# getQADPath
# ===============================================================================
def getQADPath():
"""
Restituisce la path di installazione di QAD
"""
return os.path.dirname(os.path.realpath(__file__))
# ===============================================================================
# toRadians
# ===============================================================================
def toRadians(angle):
"""
Converte da gradi a radianti
"""
return math.radians(angle)
# ===============================================================================
# toDegrees
# ===============================================================================
def toDegrees(angle):
"""
Converte da radianti a gradi
"""
return math.degrees(angle)
# ===============================================================================
# normalizeAngle
# ===============================================================================
def normalizeAngle(angle, norm = math.pi * 2):
"""
Normalizza un angolo a da [0 - 2pi] o da [0 - pi].
Così, ad esempio, se un angolo é più grande di 2pi viene ridotto all'angolo giusto
(il raffronto in gradi sarebbe da 380 a 20 gradi) o se é negativo diventa positivo
(il raffronto in gradi sarebbe da -90 a 270 gradi)
"""
if angle == 0:
return 0
if angle > 0:
return angle % norm
else:
return norm - ((-angle) % norm)
# ===============================================================================
# getStrIntDecParts
# ===============================================================================
def getStrIntDecParts(n):
"""
Restituisce due stringhe rappresentanti la parte intera senza segno e la parte decimale di un numero
"""
if type(n) == int or type(n) == long or type(n) == float:
nStr = str(n)
if "." in nStr:
parts = nStr.split(".")
return str(abs(int(parts[0]))), parts[1]
else:
return nStr, ""
else:
return None
# ===============================================================================
# distMapToLayerCoordinates
# ===============================================================================
def distMapToLayerCoordinates(dist, canvas, layer):
# trovo il punto centrale dello schermo
boundBox = canvas.extent()
x = (boundBox.xMinimum() + boundBox.xMaximum()) / 2
y = (boundBox.yMinimum() + boundBox.yMaximum()) / 2
pt1 = QgsPointXY(x, y)
pt2 = QgsPointXY(x + dist, y)
transformedPt1 = canvas.mapSettings().mapToLayerCoordinates(layer, pt1)
transformedPt2 = canvas.mapSettings().mapToLayerCoordinates(layer, pt2)
return getDistance(transformedPt1, transformedPt2)
# ===============================================================================
# filterFeaturesByType
# ===============================================================================
def filterFeaturesByType(features, filterByGeomType):
"""
Riceve una lista di features e la tipologia di geometria che deve essere filtrata.
La funzione modifica la lista <features> depurandola dalle geometrie di tipo diverso
da <filterByGeomType>.
Restituisce 3 liste rispettivamente di punti, linee e poligoni.
La lista del tipo indicato dal parametro <filterByGeomType> sarà vuota, le altre
due liste conterranno geometrie.
"""
resultPoint = []
resultLine = []
resultPolygon = []
for i in range(len(features) - 1, -1, -1):
f = features[i]
g = f.geometry()
geomType = g.type()
if geomType != filterByGeomType:
if geomType == QgsWkbTypes.PointGeometry:
resultPoint.append(QgsGeometry(g))
elif geomType == QgsWkbTypes.LineGeometry:
resultLine.append(QgsGeometry(g))
elif geomType == QgsWkbTypes.PolygonGeometry:
resultPolygon.append(QgsGeometry(g))
del features[i]
return resultPoint, resultLine, resultPolygon
# ===============================================================================
# filterGeomsByType
# ===============================================================================
def filterGeomsByType(geoms, filterByGeomType):
"""
Riceve una lista di geometrie e la tipologia di geometria che deve essere filtrata.
La funzine modifica la lista <geoms> depurandola dalle geometrie di tipo diverso
da <filterByGeomType>.
Restituisce 3 liste rispettivamente di punti, linee e poligoni.
La lista del tipo indicato dal parametro <filterByGeomType> sarà vuota, le altre
due liste conterranno geometrie.
"""
resultPoint = []
resultLine = []
resultPolygon = []
for i in range(len(geoms) - 1, -1, -1):
g = geoms[i]
geomType = g.type()
if geomType != filterByGeomType:
if geomType == QgsWkbTypes.PointGeometry:
resultPoint.append(QgsGeometry(g))
elif geomType == QgsWkbTypes.LineGeometry:
resultLine.append(QgsGeometry(g))
elif geomType == QgsWkbTypes.PolygonGeometry:
resultPolygon.append(QgsGeometry(g))
del geoms[i]
return resultPoint, resultLine, resultPolygon
# ===============================================================================
# getEntSelCursor
# ===============================================================================
def getEntSelCursor():
"""
Ritorna l'immagine del cursore per la selezione di un'entità
"""
size = 1 + QadVariables.get(QadMsg.translate("Environment variables", "PICKBOX")) * 2
# <width/cols> <height/rows> <colors> <char on pixel>
row = str(size) + " " + str(size) + " 2 1"
xpm = [row]
# <Colors>
xpm.append(" c None")
xpm.append("+ c " + QadVariables.get(QadMsg.translate("Environment variables", "PICKBOXCOLOR")))
# <Pixels>
# es . "+++++",
# es . "+ +",
# es . "+ +",
# es . "+ +",
# es . "+++++",
xpm.append("+" * size)
if size > 1:
row = "+" + " " * (size - 2) + "+"
for i in range(size - 2): # da 0
xpm.append(row)
xpm.append("+" * size)
return QCursor(QPixmap(xpm))
def getGetPointCursor():
"""
Ritorna l'immagine del cursore per la selezione di un punto
"""
pickBox = QadVariables.get(QadMsg.translate("Environment variables", "CURSORSIZE"))
size = 1 + pickBox * 2
# <width/cols> <height/rows> <colors> <char on pixel>
row = str(size) + " " + str(size) + " 2 1"
xpm = [row]
# <Colors>
xpm.append(" c None")
xpm.append("+ c " + QadVariables.get(QadMsg.translate("Environment variables", "PICKBOXCOLOR")))
# <Pixels>
# es . " + ",
# es . " + ",
# es . "+++++",
# es . " + ",
# es . " + ",
row = (" " * pickBox) + "+" + (" " * pickBox)
xpm.append(row)
if size > 1:
for i in range(pickBox - 1): # da 0
xpm.append(row)
xpm.append("+" * (size))
for i in range(pickBox - 1): # da 0
xpm.append(row)
return QCursor(QPixmap(xpm))
# ===============================================================================
# getFeatureRequest
# ===============================================================================
def getFeatureRequest(fetchAttributes = [], fetchGeometry = True, \
rect = None, useIntersect = False):
# PER ORA <fetchGeometry> NON VIENE USATO PERCHE' NON SO FARE IL CAST in QgsFeatureRequest.Flags
# restituisce un oggetto QgsFeatureRequest per interrogare un layer
# It can get 4 arguments, all of them are optional:
# fetchAttributes: List of attributes which should be fetched.
# None = disable fetching attributes, Empty list means that all attributes are used.
# default: empty list
# fetchGeometry: Whether geometry of the feature should be fetched. Default: True
# rect: Spatial filter by rectangle.
# None = nessuna ricerca spaziale, empty rect means (QgsRectangle()), all features are fetched.
# Default: none
# useIntersect: When using spatial filter, this argument says whether accurate test for intersection
# should be done or whether test on bounding box suffices.
# This is needed e.g. for feature identification or selection. Default: False
request = QgsFeatureRequest()
#flag = QgsFeatureRequest.NoFlags
# if fetchGeometry == False:
# flag = flag | QgsFeatureRequest.NoGeometry
if rect is not None:
r = QgsRectangle(rect)
# non serve più
# # Se il rettangolo é schiacciato in verticale o in orizzontale
# # risulta una linea e la funzione fa casino, allora in questo caso lo allargo un pochino
# if doubleNear(r.xMinimum(), r.xMaximum(), 1.e-6):
# r.setXMaximum(r.xMaximum() + 1.e-6)
# r.setXMinimum(r.xMinimum() - 1.e-6)
# if doubleNear(r.yMinimum(), r.yMaximum(), 1.e-6):
# r.setYMaximum(r.yMaximum() + 1.e-6)
# r.setYMinimum(r.yMinimum() - 1.e-6)
request.setFilterRect(r)
if useIntersect == True:
request.setFlags(QgsFeatureRequest.ExactIntersect)
if fetchAttributes is None:
request.setSubsetOfAttributes([])
else:
if len(fetchAttributes) > 0:
request.setSubsetOfAttributes(fetchAttributes)
return request
# ===============================================================================
# getVisibleVectorLayers
# ===============================================================================
def getVisibleVectorLayers(canvas):
# Tutti i layer vettoriali visibili
layers = canvas.layers()
for i in range(len(layers) - 1, -1, -1):
# se il layer non è vettoriale o non è visibile a questa scala
if layers[i].type() != QgsMapLayer.VectorLayer or \
layers[i].hasScaleBasedVisibility() and \
(canvas.mapSettings().scale() > layers[i].minimumScale() or canvas.mapSettings().scale() < layers[i].maximumScale()):
del layers[i]
return layers
# ===============================================================================
# getSnappableVectorLayers
# ===============================================================================
def getSnappableVectorLayers(canvas):
# make QAD honor QGIS's snap settings (ALL LAYERS, ACTIVE LAYER, ADVANCED).
# proposed by Oliver Dalang
enabled = canvas.snappingUtils().config().enabled()
mode = canvas.snappingUtils().config().mode()
if enabled and mode == QgsSnappingConfig.ActiveLayer:
if qgis.utils.iface.activeLayer() is None:
layers = []
else:
layers = [qgis.utils.iface.activeLayer()]
elif enabled and mode == QgsSnappingConfig.AdvancedConfiguration:
layers = list(cfg.layer for cfg in canvas.snappingUtils().layers())
else: # mode == QgsSnappingConfig.AllLayers:
layers = canvas.layers()
# Solo i layer vettoriali visibili
for i in range(len(layers) - 1, -1, -1):
# se il layer non è vettoriale o non è visibile a questa scala
if layers[i].type() != QgsMapLayer.VectorLayer or \
layers[i].hasScaleBasedVisibility() and \
(canvas.mapSettings().scale() > layers[i].minimumScale() or canvas.mapSettings().scale() < layers[i].maximumScale()):
del layers[i]
return layers
# ===============================================================================
# getEntSel
# ===============================================================================
def getEntSel(point, mQgsMapTool, boxSize, \
layersToCheck = None, checkPointLayer = True, checkLineLayer = True, checkPolygonLayer = True,
onlyBoundary = True, onlyEditableLayers = False, \
firstLayerToCheck = None, layerCacheGeomsDict = None, returnFeatureCached = False):
"""
dato un punto (in screen coordinates) e un QgsMapTool,
la funzione cerca la prima entità dentro il quadrato
di dimensioni <boxSize> (in pixel) centrato sul punto <point>
layersToCheck = opzionale, lista dei layer in cui cercare
checkPointLayer = opzionale, considera i layer di tipo punto
checkLineLayer = opzionale, considera i layer di tipo linea
checkPolygonLayer = opzionale, considera i layer di tipo poligono
onlyBoundary = serve per considerare solo il bordo dei poligoni o anche il loro interno
onlyEditableLayers = per cercare solo nei layer modificabili
firstLayerToCheck = per ottimizzare la ricerca, primo layer da controllare
layerCacheGeomsDict = per ottimizzare la ricerca, è una chache delle geometrie dei layer
returnFeatureCached = per ottimizzare, ritorna la featura letta dalla cache (quando interessa solo la geometria)
Restituisce una lista composta da una QgsFeature e il suo layer e il punto di selezione
in caso di successo altrimenti None
"""
if checkPointLayer == False and checkLineLayer == False and checkPolygonLayer == False:
return None
#QApplication.setOverrideCursor(Qt.WaitCursor)