File: utils.py

package info (click to toggle)
grass 8.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 277,040 kB
  • sloc: ansic: 460,798; python: 227,732; cpp: 42,026; sh: 11,262; makefile: 7,007; xml: 3,637; sql: 968; lex: 520; javascript: 484; yacc: 450; asm: 387; perl: 157; sed: 25; objc: 6; ruby: 4
file content (1365 lines) | stat: -rw-r--r-- 38,191 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
"""
@package core.utils

@brief Misc utilities for wxGUI

(C) 2007-2015 by the GRASS Development Team

This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.

@author Martin Landa <landa.martin gmail.com>
@author Jachym Cepicky
"""

import os
import sys
import platform
import glob
import shlex
import re
import inspect
import operator

from grass.script import core as grass
from grass.script import task as gtask

from core.gcmd import RunCommand
from core.debug import Debug
from core.globalvar import ETCDIR, wxPythonPhoenix


def cmp(a, b):
    """cmp function"""
    return (a > b) - (a < b)


def normalize_whitespace(text):
    """Remove redundant whitespace from a string"""
    return (" ").join(text.split())


def split(s):
    """Platform specific shlex.split"""
    try:
        if sys.platform == "win32":
            return shlex.split(s.replace("\\", r"\\"))
        else:
            return shlex.split(s)
    except ValueError as e:
        sys.stderr.write(_("Syntax error: %s") % e)

    return []


def GetTempfile(pref=None):
    """Creates GRASS temporary file using defined prefix.

    .. todo::
        Fix path on MS Windows/MSYS

    :param pref: prefer the given path

    :return: Path to file name (string) or None
    """
    ret = RunCommand("g.tempfile", read=True, pid=os.getpid())

    tempfile = ret.splitlines()[0].strip()

    # FIXME
    # ugly hack for MSYS (MS Windows)
    if platform.system() == "Windows":
        tempfile = tempfile.replace("/", "\\")
    try:
        path, file = os.path.split(tempfile)
        if pref:
            return os.path.join(pref, file)
        else:
            return tempfile
    except:
        return None


def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None, layerType=None):
    """Get map name from GRASS command

    Parameter dcmd can be modified when first parameter is not
    defined.

    :param dcmd: GRASS command (given as list)
    :param fullyQualified: change map name to be fully qualified
    :param param: params directory
    :param str layerType: check also layer type ('raster', 'vector',
                          'raster_3d', ...)

    :return: tuple (name, found)
    """
    mapname = ""
    found = True

    if len(dcmd) < 1:
        return mapname, False

    if "d.grid" == dcmd[0]:
        mapname = "grid"
    elif "d.geodesic" in dcmd[0]:
        mapname = "geodesic"
    elif "d.rhumbline" in dcmd[0]:
        mapname = "rhumb"
    elif "d.graph" in dcmd[0]:
        mapname = "graph"
    else:
        params = list()
        for idx in range(len(dcmd)):
            try:
                p, v = dcmd[idx].split("=", 1)
            except ValueError:
                continue

            if p == param:
                params = [(idx, p, v)]
                break

            # this does not use types, just some (incomplete subset of?) names
            if p in (
                "map",
                "input",
                "layer",
                "red",
                "blue",
                "green",
                "hue",
                "saturation",
                "intensity",
                "shade",
                "labels",
            ):
                params.append((idx, p, v))

        if len(params) < 1:
            if len(dcmd) > 1:
                i = 1
                while i < len(dcmd):
                    if "=" not in dcmd[i] and not dcmd[i].startswith("-"):
                        task = gtask.parse_interface(dcmd[0])
                        # this expects the first parameter to be the right one
                        p = task.get_options()["params"][0].get("name", "")
                        params.append((i, p, dcmd[i]))
                        break
                    i += 1
            else:
                return mapname, False

        if len(params) < 1:
            return mapname, False

        # need to add mapset for all maps
        mapsets = {}
        for i, p, v in params:
            if p == "layer":
                continue
            mapname = v
            mapset = ""
            if fullyQualified and "@" not in mapname:
                if layerType in ("raster", "vector", "raster_3d", "rgb", "his"):
                    try:
                        if layerType in ("raster", "rgb", "his"):
                            findType = "cell"
                        elif layerType == "raster_3d":
                            findType = "grid3"
                        else:
                            findType = layerType
                        mapset = grass.find_file(mapname, element=findType)["mapset"]
                    except AttributeError:  # not found
                        return "", False
                    if not mapset:
                        found = False
                else:
                    mapset = ""  # grass.gisenv()['MAPSET']
            mapsets[i] = mapset

        # update dcmd
        for i, p, v in params:
            if p == "layer":
                continue
            dcmd[i] = p + "=" + v
            if i in mapsets and mapsets[i]:
                dcmd[i] += "@" + mapsets[i]

        maps = list()
        ogr = False
        for i, p, v in params:
            if v.lower().rfind("@ogr") > -1:
                ogr = True
            if p == "layer" and not ogr:
                continue
            maps.append(dcmd[i].split("=", 1)[1])

        mapname = "\n".join(maps)

    return mapname, found


def GetValidLayerName(name):
    """Make layer name SQL compliant, based on G_str_to_sql()

    .. todo::
        Better use directly Ctypes to reuse venerable libgis C fns...
    """
    retName = name.strip()

    # check if name is fully qualified
    if "@" in retName:
        retName, mapset = retName.split("@")
    else:
        mapset = None

    cIdx = 0
    retNameList = list(retName)
    for c in retNameList:
        if (
            not (c >= "A" and c <= "Z")
            and not (c >= "a" and c <= "z")
            and not (c >= "0" and c <= "9")
        ):
            retNameList[cIdx] = "_"
        cIdx += 1
    retName = "".join(retNameList)

    if (
        retName
        and not (retName[0] >= "A" and retName[0] <= "Z")
        and not (retName[0] >= "a" and retName[0] <= "z")
    ):
        retName = "x" + retName[1:]

    if mapset:
        retName = retName + "@" + mapset

    return retName


def ListOfCatsToRange(cats):
    """Convert list of category number to range(s)

    Used for example for d.vect cats=[range]

    :param cats: category list

    :return: category range string
    :return: '' on error
    """

    catstr = ""

    try:
        cats = list(map(int, cats))
    except:
        return catstr

    i = 0
    while i < len(cats):
        next = 0
        j = i + 1
        while j < len(cats):
            if cats[i + next] == cats[j] - 1:
                next += 1
            else:
                break
            j += 1

        if next > 1:
            catstr += "%d-%d," % (cats[i], cats[i + next])
            i += next + 1
        else:
            catstr += "%d," % (cats[i])
            i += 1

    return catstr.strip(",")


def ListOfMapsets(get="ordered"):
    """Get list of available/accessible mapsets.
    Option 'ordered' returns list of all mapsets, first accessible
    then not accessible. Raises ValueError for wrong paramater value.

    :param str get: method ('all', 'accessible', 'ordered')

    :return: list of mapsets
    :return: [] on error
    """
    if get == "all" or get == "ordered":
        ret = RunCommand("g.mapsets", read=True, quiet=True, flags="l", sep="newline")
        if not ret:
            return []
        mapsets_all = ret.splitlines()
        ListSortLower(mapsets_all)
        if get == "all":
            return mapsets_all

    if get == "accessible" or get == "ordered":
        ret = RunCommand("g.mapsets", read=True, quiet=True, flags="p", sep="newline")
        if not ret:
            return []
        mapsets_accessible = ret.splitlines()
        if get == "accessible":
            return mapsets_accessible

        mapsets_ordered = mapsets_accessible.copy()
        for mapset in mapsets_all:
            if mapset not in mapsets_accessible:
                mapsets_ordered.append(mapset)
        return mapsets_ordered

    raise ValueError("Invalid value for 'get' parameter of ListOfMapsets()")


def ListSortLower(list):
    """Sort list items (not case-sensitive)"""
    list.sort(key=lambda x: x.lower())


def GetVectorNumberOfLayers(vector):
    """Get list of all vector layers"""
    layers = list()
    if not vector:
        return layers

    fullname = grass.find_file(name=vector, element="vector")["fullname"]
    if not fullname:
        Debug.msg(
            5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector
        )
        return layers

    ret, out, msg = RunCommand(
        "v.category", getErrorMsg=True, read=True, input=fullname, option="layers"
    )
    if ret != 0:
        sys.stderr.write(
            _("Vector map <%(map)s>: %(msg)s\n") % {"map": fullname, "msg": msg}
        )
        return layers
    else:
        Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)

    for layer in out.splitlines():
        layers.append(layer)

    Debug.msg(
        3,
        "utils.GetVectorNumberOfLayers(): vector=%s -> %s"
        % (fullname, ",".join(layers)),
    )

    return layers


def Deg2DMS(lon, lat, string=True, hemisphere=True, precision=3):
    """Convert deg value to dms string

    :param lon: longitude (x)
    :param lat: latitude (y)
    :param string: True to return string otherwise tuple
    :param hemisphere: print hemisphere
    :param precision: seconds precision

    :return: DMS string or tuple of values
    :return: empty string on error
    """
    try:
        flat = float(lat)
        flon = float(lon)
    except ValueError:
        if string:
            return ""
        else:
            return None

    # fix longitude
    while flon > 180.0:
        flon -= 360.0
    while flon < -180.0:
        flon += 360.0

    # hemisphere
    if hemisphere:
        if flat < 0.0:
            flat = abs(flat)
            hlat = "S"
        else:
            hlat = "N"

        if flon < 0.0:
            hlon = "W"
            flon = abs(flon)
        else:
            hlon = "E"
    else:
        flat = abs(flat)
        flon = abs(flon)
        hlon = ""
        hlat = ""

    slat = __ll_parts(flat, precision=precision)
    slon = __ll_parts(flon, precision=precision)

    if string:
        return slon + hlon + "; " + slat + hlat

    return (slon + hlon, slat + hlat)


def DMS2Deg(lon, lat):
    """Convert dms value to deg

    :param lon: longitude (x)
    :param lat: latitude (y)

    :return: tuple of converted values
    :return: ValueError on error
    """
    x = __ll_parts(lon, reverse=True)
    y = __ll_parts(lat, reverse=True)

    return (x, y)


def __ll_parts(value, reverse=False, precision=3):
    """Converts deg to d:m:s string

    :param value: value to be converted
    :param reverse: True to convert from d:m:s to deg
    :param precision: seconds precision (ignored if reverse is True)

    :return: converted value (string/float)
    :return: ValueError on error (reverse == True)
    """
    if not reverse:
        if value == 0.0:
            return "%s%.*f" % ("00:00:0", precision, 0.0)

        d = int(int(value))
        m = int((value - d) * 60)
        s = ((value - d) * 60 - m) * 60
        if m < 0:
            m = "00"
        elif m < 10:
            m = "0" + str(m)
        else:
            m = str(m)
        if s < 0:
            s = "00.0000"
        elif s < 10.0:
            s = "0%.*f" % (precision, s)
        else:
            s = "%.*f" % (precision, s)

        return str(d) + ":" + m + ":" + s
    else:  # -> reverse
        try:
            d, m, s = value.split(":")
            hs = s[-1]
            s = s[:-1]
        except ValueError:
            try:
                d, m = value.split(":")
                hs = m[-1]
                m = m[:-1]
                s = "0.0"
            except ValueError:
                try:
                    d = value
                    hs = d[-1]
                    d = d[:-1]
                    m = "0"
                    s = "0.0"
                except ValueError:
                    raise ValueError

        if hs not in ("N", "S", "E", "W"):
            raise ValueError

        coef = 1.0
        if hs in ("S", "W"):
            coef = -1.0

        fm = int(m) / 60.0
        fs = float(s) / (60 * 60)

        return coef * (float(d) + fm + fs)


def GetCmdString(cmd):
    """Get GRASS command as string.

    :param cmd: GRASS command given as tuple

    :return: command string
    """
    return " ".join(gtask.cmdtuple_to_list(cmd))


def PathJoin(*args):
    """Check path created by os.path.join"""
    path = os.path.join(*args)
    if platform.system() == "Windows" and "/" in path:
        return path[1].upper() + ":\\" + path[3:].replace("/", "\\")

    return path


def ReadEpsgCodes():
    """Read EPSG codes with g.proj

    :return: dictionary of EPSG code
    """
    epsgCodeDict = dict()

    ret = RunCommand("g.proj", read=True, list_codes="EPSG")

    for line in ret.splitlines():
        code, descr, params = line.split("|")
        epsgCodeDict[int(code)] = (descr, params)

    return epsgCodeDict


def ReprojectCoordinates(coord, projOut, projIn=None, flags=""):
    """Reproject coordinates

    :param coord: coordinates given as tuple
    :param projOut: output projection
    :param projIn: input projection (use location projection settings)

    :return: reprojected coordinates (returned as tuple)
    """
    coors = RunCommand(
        "m.proj",
        flags=flags,
        input="-",
        proj_in=projIn,
        proj_out=projOut,
        sep=";",
        stdin="%f;%f" % (coord[0], coord[1]),
        read=True,
    )
    if coors:
        coors = coors.split(";")
        e = coors[0]
        n = coors[1]
        try:
            proj = projOut.split(" ")[0].split("=")[1]
        except IndexError:
            proj = ""
        if proj in ("ll", "latlong", "longlat") and "d" not in flags:
            return (proj, (e, n))
        else:
            try:
                return (proj, (float(e), float(n)))
            except ValueError:
                return (None, None)

    return (None, None)


def GetListOfLocations(dbase):
    """Get list of GRASS locations in given dbase

    :param dbase: GRASS database path

    :return: list of locations (sorted)
    """
    listOfLocations = list()

    try:
        for location in glob.glob(os.path.join(dbase, "*")):
            try:
                if os.path.join(location, "PERMANENT") in glob.glob(
                    os.path.join(location, "*")
                ):
                    listOfLocations.append(os.path.basename(location))
            except:
                pass
    except (UnicodeEncodeError, UnicodeDecodeError) as e:
        raise e

    ListSortLower(listOfLocations)

    return listOfLocations


def GetListOfMapsets(dbase, location, selectable=False):
    """Get list of mapsets in given GRASS location

    :param dbase: GRASS database path
    :param location: GRASS location
    :param selectable: True to get list of selectable mapsets, otherwise all

    :return: list of mapsets - sorted (PERMANENT first)
    """
    listOfMapsets = list()

    if selectable:
        ret = RunCommand(
            "g.mapset", read=True, flags="l", project=location, dbase=dbase
        )

        if not ret:
            return listOfMapsets

        for line in ret.rstrip().splitlines():
            listOfMapsets += line.split(" ")
    else:
        for mapset in glob.glob(os.path.join(dbase, location, "*")):
            if os.path.isdir(mapset) and os.path.isfile(
                os.path.join(dbase, location, mapset, "WIND")
            ):
                listOfMapsets.append(os.path.basename(mapset))

    ListSortLower(listOfMapsets)
    return listOfMapsets


def GetColorTables():
    """Get list of color tables"""
    ret = RunCommand("r.colors", read=True, flags="l")
    if not ret:
        return list()

    return ret.splitlines()


def _getGDALFormats():
    """Get dictionary of available GDAL drivers"""
    try:
        ret = grass.read_command("r.in.gdal", quiet=True, flags="f")
    except:
        ret = None

    return _parseFormats(ret), _parseFormats(ret, writableOnly=True)


def _getOGRFormats():
    """Get dictionary of available OGR drivers"""
    try:
        ret = grass.read_command("v.in.ogr", quiet=True, flags="f")
    except:
        ret = None

    return _parseFormats(ret), _parseFormats(ret, writableOnly=True)


def _parseFormats(output, writableOnly=False):
    """Parse r.in.gdal/v.in.ogr -f output"""
    formats = {"file": {}, "database": {}, "protocol": {}}

    if not output:
        return formats

    patt = None
    if writableOnly:
        patt = re.compile(r"\(rw\+?\)$", re.IGNORECASE)

    for line in output.splitlines():
        key, name = map(lambda x: x.strip(), line.strip().split(":", 1))
        if writableOnly and not patt.search(key):
            continue

        if name in ("Memory", "Virtual Raster", "In Memory Raster"):
            continue
        if name in (
            "PostgreSQL",
            "PostgreSQL/PostGIS",
            "SQLite",
            "SQLite / Spatialite",
            "ODBC",
            "ESRI Personal GeoDatabase",
            "Rasterlite",
            "PostGIS WKT Raster driver",
            "PostGIS Raster driver",
            "CouchDB",
            "MSSQLSpatial",
            "FileGDB",
        ):
            formats["database"][key.split(" ")[0]] = name
        elif name in (
            "GeoJSON",
            "OGC Web Coverage Service",
            "OGC Web Map Service",
            "WFS",
            "GeoRSS",
            "HTTP Fetching Wrapper",
        ):
            formats["protocol"][key.split(" ")[0]] = name
        else:
            formats["file"][key.split(" ")[0]] = name

    for k, v in formats.items():
        formats[k] = dict(sorted(v.items(), key=operator.itemgetter(1)))

    return formats


formats = None


def GetFormats(writableOnly=False):
    """Get GDAL/OGR formats"""
    global formats
    if not formats:
        gdalAll, gdalWritable = _getGDALFormats()
        ogrAll, ogrWritable = _getOGRFormats()
        formats = {
            "all": {
                "gdal": gdalAll,
                "ogr": ogrAll,
            },
            "writable": {
                "gdal": gdalWritable,
                "ogr": ogrWritable,
            },
        }

    if writableOnly:
        return formats["writable"]

    return formats["all"]


rasterFormatExtension = {
    "GeoTIFF": "tif",
    "Erdas Imagine Images (.img)": "img",
    "Ground-based SAR Applications Testbed File Format (.gff)": "gff",
    "Arc/Info Binary Grid": "adf",
    "Portable Network Graphics": "png",
    "JPEG JFIF": "jpg",
    "Japanese DEM (.mem)": "mem",
    "Graphics Interchange Format (.gif)": "gif",
    "X11 PixMap Format": "xpm",
    "MS Windows Device Independent Bitmap": "bmp",
    "SPOT DIMAP": "dim",
    "RadarSat 2 XML Product": "xml",
    "EarthWatch .TIL": "til",
    "ERMapper .ers Labelled": "ers",
    "ERMapper Compressed Wavelets": "ecw",
    "GRIdded Binary (.grb)": "grb",
    "EUMETSAT Archive native (.nat)": "nat",
    "Idrisi Raster A.1": "rst",
    "Golden Software ASCII Grid (.grd)": "grd",
    "Golden Software Binary Grid (.grd)": "grd",
    "Golden Software 7 Binary Grid (.grd)": "grd",
    "R Object Data Store": "r",
    "USGS DOQ (Old Style)": "doq",
    "USGS DOQ (New Style)": "doq",
    "ENVI .hdr Labelled": "hdr",
    "ESRI .hdr Labelled": "hdr",
    "Generic Binary (.hdr Labelled)": "hdr",
    "PCI .aux Labelled": "aux",
    "EOSAT FAST Format": "fst",
    "VTP .bt (Binary Terrain) 1.3 Format": "bt",
    "FARSITE v.4 Landscape File (.lcp)": "lcp",
    "Swedish Grid RIK (.rik)": "rik",
    "USGS Optional ASCII DEM (and CDED)": "dem",
    "Northwood Numeric Grid Format .grd/.tab": "",
    "Northwood Classified Grid Format .grc/.tab": "",
    "ARC Digitized Raster Graphics": "arc",
    "Magellan topo (.blx)": "blx",
    "SAGA GIS Binary Grid (.sdat)": "sdat",
    "GeoPackage (.gpkg)": "gpkg",
}


vectorFormatExtension = {
    "ESRI Shapefile": "shp",
    "GeoPackage": "gpkg",
    "UK .NTF": "ntf",
    "SDTS": "ddf",
    "DGN": "dgn",
    "VRT": "vrt",
    "REC": "rec",
    "BNA": "bna",
    "CSV": "csv",
    "GML": "gml",
    "GPX": "gpx",
    "KML": "kml",
    "GMT": "gmt",
    "PGeo": "mdb",
    "XPlane": "dat",
    "AVCBin": "adf",
    "AVCE00": "e00",
    "DXF": "dxf",
    "Geoconcept": "gxt",
    "GeoRSS": "xml",
    "GPSTrackMaker": "gtm",
    "VFK": "vfk",
    "SVG": "svg",
}


def GetSettingsPath():
    """Get full path to the settings directory"""
    try:
        verFd = open(os.path.join(ETCDIR, "VERSIONNUMBER"))
        version = int(verFd.readlines()[0].split(" ")[0].split(".")[0])
    except (OSError, ValueError, TypeError, IndexError) as e:
        sys.exit(_("ERROR: Unable to determine GRASS version. Details: %s") % e)

    verFd.close()

    # keep location of settings files rc and wx in sync with lib/init/grass.py
    if sys.platform == "win32":
        return os.path.join(os.getenv("APPDATA"), "GRASS%d" % version)

    return os.path.join(os.getenv("HOME"), ".grass%d" % version)


def StoreEnvVariable(key, value=None, envFile=None):
    """Store environmental variable

    If value is not given (is None) then environmental variable is
    unset.

    :param key: env key
    :param value: env value
    :param envFile: path to the environmental file (None for default location)
    """
    windows = sys.platform == "win32"
    if not envFile:
        gVersion = grass.version()["version"].split(".", 1)[0]
        if not windows:
            envFile = os.path.join(os.getenv("HOME"), ".grass%s" % gVersion, "bashrc")
        else:
            envFile = os.path.join(
                os.getenv("APPDATA"), "GRASS%s" % gVersion, "env.bat"
            )

    # read env file
    environ = dict()
    lineSkipped = list()
    if os.path.exists(envFile):
        try:
            fd = open(envFile)
        except OSError as e:
            sys.stderr.write(_("Unable to open file '%s'\n") % envFile)
            return
        for line in fd.readlines():
            line = line.rstrip(os.linesep)
            try:
                k, v = map(lambda x: x.strip(), line.split(" ", 1)[1].split("=", 1))
            except Exception as e:
                sys.stderr.write(
                    _("%s: line skipped - unable to parse '%s'\n" "Reason: %s\n")
                    % (envFile, line, e)
                )
                lineSkipped.append(line)
                continue
            if k in environ:
                sys.stderr.write(_("Duplicated key: %s\n") % k)
            environ[k] = v

        fd.close()

    # update environmental variables
    if value is None:
        if key in environ:
            del environ[key]
    else:
        environ[key] = value

    # write update env file
    try:
        fd = open(envFile, "w")
    except OSError as e:
        sys.stderr.write(_("Unable to create file '%s'\n") % envFile)
        return
    if windows:
        expCmd = "set"
    else:
        expCmd = "export"

    for key, value in environ.items():
        fd.write("%s %s=%s\n" % (expCmd, key, value))

    # write also skipped lines
    for line in lineSkipped:
        fd.write(line + os.linesep)

    fd.close()


def SetAddOnPath(addonPath=None, key="PATH"):
    """Set default AddOn path

    :param addonPath: path to addons (None for default)
    :param key: env key - 'PATH' or 'BASE'
    """
    gVersion = grass.version()["version"].split(".", 1)[0]
    # update env file
    if not addonPath:
        if sys.platform != "win32":
            addonPath = os.path.join(
                os.path.join(os.getenv("HOME"), ".grass%s" % gVersion, "addons")
            )
        else:
            addonPath = os.path.join(
                os.path.join(os.getenv("APPDATA"), "GRASS%s" % gVersion, "addons")
            )

    StoreEnvVariable(key="GRASS_ADDON_" + key, value=addonPath)
    os.environ["GRASS_ADDON_" + key] = addonPath

    # update path
    if addonPath not in os.environ["PATH"]:
        os.environ["PATH"] = addonPath + os.pathsep + os.environ["PATH"]


# predefined colors and their names
# must be in sync with lib/gis/color_str.c
str2rgb = {
    "aqua": (100, 128, 255),
    "black": (0, 0, 0),
    "blue": (0, 0, 255),
    "brown": (180, 77, 25),
    "cyan": (0, 255, 255),
    "gray": (128, 128, 128),
    "grey": (128, 128, 128),
    "green": (0, 255, 0),
    "indigo": (0, 128, 255),
    "magenta": (255, 0, 255),
    "orange": (255, 128, 0),
    "red": (255, 0, 0),
    "violet": (128, 0, 255),
    "purple": (128, 0, 255),
    "white": (255, 255, 255),
    "yellow": (255, 255, 0),
}
rgb2str = {}
for s, r in str2rgb.items():
    rgb2str[r] = s
# ensure that gray value has 'gray' string and not 'grey'
rgb2str[str2rgb["gray"]] = "gray"
# purple is defined as nickname for violet in lib/gis
# (although Wikipedia says that purple is (128, 0, 128))
# we will prefer the defined color, not nickname
rgb2str[str2rgb["violet"]] = "violet"


def color_resolve(color):
    if len(color) > 0 and color[0] in "0123456789":
        rgb = tuple(map(int, color.split(":")))
        label = color
    else:
        # Convert color names to RGB
        try:
            rgb = str2rgb[color]
            label = color
        except KeyError:
            rgb = (200, 200, 200)
            label = _("Select Color")
    return (rgb, label)


command2ltype = {
    "d.rast": "raster",
    "d.rast3d": "raster_3d",
    "d.rgb": "rgb",
    "d.his": "his",
    "d.shade": "shaded",
    "d.legend": "rastleg",
    "d.rast.arrow": "rastarrow",
    "d.rast.num": "rastnum",
    "d.rast.leg": "maplegend",
    "d.vect": "vector",
    "d.vect.thematic": "thememap",
    "d.vect.chart": "themechart",
    "d.grid": "grid",
    "d.geodesic": "geodesic",
    "d.rhumbline": "rhumb",
    "d.labels": "labels",
    "d.barscale": "barscale",
    "d.redraw": "redraw",
    "d.wms": "wms",
    "d.histogram": "histogram",
    "d.colortable": "colortable",
    "d.graph": "graph",
    "d.out.file": "export",
    "d.to.rast": "torast",
    "d.text": "text",
    "d.northarrow": "northarrow",
    "d.polar": "polar",
    "d.legend.vect": "vectleg",
}
ltype2command = {}
for cmd, ltype in command2ltype.items():
    ltype2command[ltype] = cmd


def GetGEventAttribsForHandler(method, event):
    """Get attributes from event, which can be used by handler method.

    Be aware of event class attributes.

    :param method: handler method (including self arg)
    :param event: event

    :return: (valid kwargs for method,
             list of method's args without default value
             which were not found among event attributes)
    """
    args_spec = inspect.getargspec(method)

    args = args_spec[0]

    defaults = []
    if args_spec[3]:
        defaults = args_spec[3]

    # number of arguments without def value
    req_args = len(args) - 1 - len(defaults)

    kwargs = {}
    missing_args = []

    for i, a in enumerate(args):
        if hasattr(event, a):
            kwargs[a] = getattr(event, a)
        elif i < req_args:
            missing_args.append(a)

    return kwargs, missing_args


def PilImageToWxImage(pilImage, copyAlpha=True):
    """Convert PIL image to wx.Image

    Based on http://wiki.wxpython.org/WorkingWithImages
    """
    from gui_core.wrap import EmptyImage

    hasAlpha = pilImage.mode[-1] == "A"
    if copyAlpha and hasAlpha:  # Make sure there is an alpha layer copy.
        wxImage = EmptyImage(*pilImage.size)
        pilImageCopyRGBA = pilImage.copy()
        pilImageCopyRGB = pilImageCopyRGBA.convert("RGB")  # RGBA --> RGB
        wxImage.SetData(pilImageCopyRGB.tobytes())
        # Create layer and insert alpha values.
        if wxPythonPhoenix:
            wxImage.SetAlpha(pilImageCopyRGBA.tobytes()[3::4])
        else:
            wxImage.SetAlphaData(pilImageCopyRGBA.tobytes()[3::4])

    else:  # The resulting image will not have alpha.
        wxImage = EmptyImage(*pilImage.size)
        pilImageCopy = pilImage.copy()
        # Discard any alpha from the PIL image.
        pilImageCopyRGB = pilImageCopy.convert("RGB")
        wxImage.SetData(pilImageCopyRGB.tobytes())

    return wxImage


def autoCropImageFromFile(filename):
    """Loads image from file and crops it automatically.

    If PIL is not installed, it does not crop it.

    :param filename: path to file
    :return: wx.Image instance
    """
    try:
        from PIL import Image

        pilImage = Image.open(filename)
        imageBox = pilImage.getbbox()
        cropped = pilImage.crop(imageBox)
        return PilImageToWxImage(cropped, copyAlpha=True)
    except ImportError:
        import wx

        return wx.Image(filename)


def isInRegion(regionA, regionB):
    """Tests if 'regionA' is inside of 'regionB'.

    For example, region A is a display region and region B is some reference
    region, e.g., a computational region.

    >>> displayRegion = {'n': 223900, 's': 217190, 'w': 630780, 'e': 640690}
    >>> compRegion = {'n': 228500, 's': 215000, 'w': 630000, 'e': 645000}
    >>> isInRegion(displayRegion, compRegion)
    True
    >>> displayRegion = {'n':226020, 's': 212610, 'w': 626510, 'e': 646330}
    >>> isInRegion(displayRegion, compRegion)
    False

    :param regionA: input region A as dictionary
    :param regionB: input region B as dictionary

    :return: True if region A is inside of region B
    :return: False otherwise
    """
    if (
        regionA["s"] >= regionB["s"]
        and regionA["n"] <= regionB["n"]
        and regionA["w"] >= regionB["w"]
        and regionA["e"] <= regionB["e"]
    ):
        return True

    return False


def do_doctest_gettext_workaround():
    """Setups environment for doing a doctest with gettext usage.

    When using gettext with dynamically defined underscore function
    (`_("For translation")`), doctest does not work properly. One option is to
    use `import as` instead of dynamically defined underscore function but this
    would require change all modules which are used by tested module. This
    should be considered for the future. The second option is to define dummy
    underscore function and one other function which creates the right
    environment to satisfy all. This is done by this function.
    """

    def new_displayhook(string):
        """A replacement for default `sys.displayhook`"""
        if string is not None:
            sys.stdout.write("%r\n" % (string,))

    def new_translator(string):
        """A fake gettext underscore function."""
        return string

    sys.displayhook = new_displayhook

    import builtins

    builtins.__dict__["_"] = new_translator


def doc_test():
    """Tests the module using doctest

    :return: a number of failed tests
    """
    import doctest

    do_doctest_gettext_workaround()
    return doctest.testmod().failed


def registerPid(pid):
    """Register process id as GUI_PID GRASS variable

    :param: pid process id
    """
    env = grass.gisenv()
    guiPid = []
    if "GUI_PID" in env:
        guiPid = env["GUI_PID"].split(",")
    guiPid.append(str(pid))
    grass.run_command("g.gisenv", set="GUI_PID={0}".format(",".join(guiPid)))


def unregisterPid(pid):
    """Unregister process id from GUI_PID GRASS variable

    :param: pid process id
    """
    env = grass.gisenv()
    if "GUI_PID" not in env:
        return

    guiPid = env["GUI_PID"].split(",")
    pid = str(os.getpid())
    if pid in guiPid:
        guiPid.remove(pid)
        grass.run_command("g.gisenv", set="GUI_PID={0}".format(",".join(guiPid)))


def get_shell_pid(env=None):
    """Get shell PID from the GIS environment or None"""
    try:
        shell_pid = int(grass.gisenv(env=env)["PID"])
        return shell_pid
    except (KeyError, ValueError) as error:
        Debug.msg(
            1, "No PID for GRASS shell (assuming no shell running): {}".format(error)
        )
        return None


def is_shell_running():
    """Return True if a separate shell is registered in the GIS environment"""
    if get_shell_pid() is None:
        return False
    return True


def parse_mapcalc_cmd(command):
    """Parse r.mapcalc/r3.mapcalc module command

    >>> parse_mapcalc_cmd(command="r.mapcalc map = 1")
    "r.mapcalc expression='map = 1'"

    >>> parse_mapcalc_cmd(command="r.mapcalc map =    1")
    "r.mapcalc expression='map = 1'"

    >>> parse_mapcalc_cmd(command="r.mapcalc map=1")
    "r.mapcalc expression='map=1'"

    >>> parse_mapcalc_cmd(command="r.mapcalc map = a - b")
    "r.mapcalc expression='map = a - b'"

    >>> parse_mapcalc_cmd(command="r.mapcalc expression=map = a - b")
    "r.mapcalc expression='map = a - b'"

    >>> parse_mapcalc_cmd(command="r.mapcalc expression=map = a -     b")
    "r.mapcalc expression='map = a - b'"

    >>> cmd = "r.mapcalc expr='map = a - b' region=clip --overwrite"
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite expr='map = a - b' region=clip"

    >>> cmd = 'r.mapcalc expr="map = a - b" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite expr='map = a - b' region=clip"

    >>> cmd = "r.mapcalc -s map = (a - b) / c region=clip --overwrite --verbose"
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc -s --overwrite --verbose expression='map = (a - b) / c' region=clip"

    >>> cmd = 'r.mapcalc e="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite e='map = 1' region=clip"

    >>> cmd = 'r.mapcalc ex="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite ex='map = 1' region=clip"

    >>> cmd = 'r.mapcalc exp="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite exp='map = 1' region=clip"

    >>> cmd = 'r.mapcalc expr="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite expr='map = 1' region=clip"

    >>> cmd = 'r.mapcalc expre="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite expre='map = 1' region=clip"

    >>> cmd = 'r.mapcalc expres="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite expres='map = 1' region=clip"

    >>> cmd = 'r.mapcalc express="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite express='map = 1' region=clip"

    >>> cmd = 'r.mapcalc expressi="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite expressi='map = 1' region=clip"

    >>> cmd = 'r.mapcalc expressio="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite expressio='map = 1' region=clip"

    >>> cmd = 'r.mapcalc expression="map = 1" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite expression='map = 1' region=clip"

    >>> cmd = 'r.mapcalc exp="map = a + e" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite exp='map = a + e' region=clip"

    >>> cmd = 'r.mapcalc exp="map = a + exp(5)" region=clip --overwrite'
    >>> parse_mapcalc_cmd(command=cmd)
    "r.mapcalc --overwrite exp='map = a + exp(5)' region=clip"

    :param str command: r.mapcalc command string

    :return str: parsed r.mapcalc command string
    """
    flags = []
    others_params_args = []
    expr_param_regex = re.compile(r"e.*?=")
    flag_regex = re.compile(
        r"^-[a-z]|^--overwrite|^--quiet|^--verbose|^--help|^--o|^--q|^--v|^--h",
    )

    command = split(command)
    module = command.pop(0)

    for arg in command[:]:
        flag = flag_regex.search(arg)
        if flag:
            flags.append(command.pop(command.index(flag.group())))
        elif "region=" in arg or "file=" in arg or "seed=" in arg:
            others_params_args.append(command.pop(command.index(arg)))

    cmd = " ".join(command)
    expr_param = expr_param_regex.search(cmd)
    if not expr_param:
        expr_param_name = "expression="
    else:
        # Remove expression param
        command = split(cmd.replace(expr_param.group(), ""))
        expr_param_name = expr_param.group()
    # Add quotes
    if "'" not in cmd or '"' not in cmd:
        cmd = f"'{' '.join(command)}'"
    expression_param_arg = f"{expr_param_name}{cmd}"

    return " ".join(
        [
            module,
            *flags,
            expression_param_arg,
            *others_params_args,
        ]
    )


def replace_module_cmd_special_flags(command):
    """Replace module command special flags short version with
    full version

    Flags:

    --o -> --overwrite
    --q -> --quiet
    --v -> --verbose
    --h -> --help

    >>> cmd = "r.mapcalc -s --o --v expression='map = 1' region=clip"
    >>> replace_module_cmd_special_flags(command=cmd)
    "r.mapcalc -s --overwrite --verbose expression='map = 1' region=clip"

    >>> cmd = "r.mapcalc -s --o --q expression='map = 1' region=clip"
    >>> replace_module_cmd_special_flags(command=cmd)
    "r.mapcalc -s --overwrite --quiet expression='map = 1' region=clip"

    :param str command: module command string

    :return str: module command string with replaced flags
    """
    flags_regex = re.compile(
        r"(--o(\s+|$))|(--q(\s+|$))|(--v(\s+|$))|(--h(\s+|$))",
    )
    replace = {
        "--o": "--overwrite ",
        "--q": "--quiet ",
        "--v": "--verbose ",
        "--h": "--help ",
    }
    return flags_regex.sub(
        lambda flag: replace[flag.group().strip()],
        command,
    )


if __name__ == "__main__":
    sys.exit(doc_test())