-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtilityNetworkMapTools.pyt
More file actions
2018 lines (1696 loc) · 83 KB
/
Copy pathUtilityNetworkMapTools.pyt
File metadata and controls
2018 lines (1696 loc) · 83 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
import csv
import datetime
import json
import os
import re
import traceback
from dataclasses import dataclass
import arcpy
TARGET_ARCGIS_PRO = "3.3"
TARGET_CIM_VERSION = "V3"
FIELD_SETTINGS_COLUMNS = [
"Map Name",
"Class Name",
"Layer Name",
"Subtype Value",
"Field Name",
"Field Order",
"Visible",
"Read Only",
"Highlight",
"Field Alias",
"Map Member URI",
"Long Name",
"Member Kind",
]
LAYER_SCALE_COLUMNS = [
"Map Name",
"Layer Type",
"Group Layer Name",
"Layer Name",
"Long Name",
"Layer URI",
"Layer Min Scale",
"Layer Max Scale",
"Label Min Scale",
"Label Max Scale",
]
DISPLAY_EXPRESSION_POPUP_NAME = "display_expression"
MULTILINE_TEXT_CONTROL = "{E5456E51-0C41-4797-9EE4-5269820C6F0E}"
MULTIVALUE_CHECKBOX_SELECT_ALL_CONTROL = "{38C34610-C7F7-11D5-A693-0008C711C8C1}"
UTILITY_NETWORK_INPUT_DATATYPES = ["GPUtilityNetworkLayer", "DEUtilityNetwork"]
UN_EXPORT_OPTIONS = [
"Utility Network Summary",
"Association And System Sources",
"Domain Networks",
"Tier Groups",
"Tiers",
"Edge Sources",
"Junction Sources",
"Domains",
"Domain Assignments",
"Asset Groups",
"Asset Types",
"Network Category Assignments",
"Network Attributes",
"Network Attribute Assignments",
"Categories",
"Terminal Configurations",
"Terminal Assignments",
"Terminals",
"Valid Configuration Paths",
]
class ToolboxError(RuntimeError):
pass
@dataclass
class MapMemberRecord:
map_name: str
member: object
definition: object
member_kind: str
name: str
long_name: str
class_name: str
uri: str
subtype_value: str
def _sanitize_name(value):
value = value or "CurrentMap"
return re.sub(r"[^A-Za-z0-9._-]+", "_", value).strip("_") or "CurrentMap"
def _get_current_project():
try:
return arcpy.mp.ArcGISProject("CURRENT")
except Exception as exc:
raise ToolboxError(
"This toolbox must be run from inside ArcGIS Pro. The CURRENT project is not available."
) from exc
def _get_active_map():
aprx = _get_current_project()
active_map = aprx.activeMap
if active_map is None:
raise ToolboxError("Open a map view before running this tool.")
return aprx, active_map
def _list_project_maps():
aprx = _get_current_project()
return aprx, aprx.listMaps()
def _get_map_names():
_, maps = _list_project_maps()
return [map_obj.name for map_obj in maps]
def _parse_multivalue_text(value):
if value is None:
return []
if isinstance(value, (list, tuple)):
return [str(item) for item in value if str(item).strip()]
text = str(value).strip()
if not text:
return []
return [item.strip().strip("'").strip('"') for item in text.split(";") if item.strip()]
def _resolve_map(map_name=None):
aprx = _get_current_project()
maps = aprx.listMaps()
if not maps:
raise ToolboxError("The current ArcGIS Pro project does not contain any maps.")
if map_name:
for map_obj in maps:
if map_obj.name == map_name:
return aprx, map_obj
raise ToolboxError("Map '{0}' was not found in the current project.".format(map_name))
active_map = aprx.activeMap
if active_map is not None:
return aprx, active_map
return aprx, maps[0]
def _get_default_output_file(suffix, extension, map_name=None):
aprx, active_map = _resolve_map(map_name)
base_folder = aprx.homeFolder or arcpy.env.scratchFolder or os.getcwd()
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
file_name = "{0}_{1}_{2}.{3}".format(
timestamp,
_sanitize_name(active_map.name),
suffix,
extension,
)
return os.path.join(base_folder, file_name)
def _ensure_parent_folder(file_path):
parent = os.path.dirname(os.path.abspath(file_path))
if parent and not os.path.isdir(parent):
os.makedirs(parent)
def _is_enum_like(value):
return hasattr(value, "name") and hasattr(value, "value") and not hasattr(value, "__dict__")
def _cim_to_jsonable(value):
if value is None or isinstance(value, (bool, int, float, str)):
return value
if isinstance(value, (list, tuple)):
return [_cim_to_jsonable(item) for item in value]
if isinstance(value, dict):
return {str(key): _cim_to_jsonable(item) for key, item in value.items()}
if _is_enum_like(value):
return {"__enum_value__": value.value, "__enum_name__": value.name}
if hasattr(value, "__dict__"):
payload = {"__cim_type__": type(value).__name__}
for key, item in value.__dict__.items():
payload[key] = _cim_to_jsonable(item)
return payload
return value
def _jsonable_to_cim(value, template=None):
if isinstance(value, list):
template_items = template if isinstance(template, list) else []
rebuilt = []
for index, item in enumerate(value):
child_template = template_items[index] if index < len(template_items) else None
rebuilt.append(_jsonable_to_cim(item, child_template))
return rebuilt
if isinstance(value, dict):
if "__enum_value__" in value:
if template is not None and _is_enum_like(template):
try:
return type(template)(value["__enum_value__"])
except Exception:
return value["__enum_value__"]
return value["__enum_value__"]
if "__cim_type__" in value:
cim_object = arcpy.cim.CreateCIMObjectFromClassName(value["__cim_type__"], TARGET_CIM_VERSION)
for key, item in value.items():
if key == "__cim_type__":
continue
current_value = getattr(cim_object, key, None)
setattr(cim_object, key, _jsonable_to_cim(item, current_value))
return cim_object
return {key: _jsonable_to_cim(item) for key, item in value.items()}
if template is not None and _is_enum_like(template):
try:
return type(template)(value)
except Exception:
return value
return value
def _normalize_dataset_name(raw_value):
if not raw_value:
return ""
dataset_name = str(raw_value).replace("\\", "/").rstrip("/")
if "/" in dataset_name:
dataset_name = dataset_name.split("/")[-1]
if "." in dataset_name and not dataset_name.lower().endswith(".csv"):
dataset_name = dataset_name.split(".")[-1]
return dataset_name
def _derive_class_name(member, definition):
candidates = []
feature_table = getattr(definition, "featureTable", None)
if feature_table is not None:
data_connection = getattr(feature_table, "dataConnection", None)
dataset = getattr(data_connection, "dataset", "")
if dataset:
candidates.append(dataset)
data_connection = getattr(definition, "dataConnection", None)
dataset = getattr(data_connection, "dataset", "")
if dataset:
candidates.append(dataset)
data_source = getattr(member, "dataSource", "")
if data_source:
candidates.append(data_source)
candidates.append(getattr(member, "name", ""))
for candidate in candidates:
normalized = _normalize_dataset_name(candidate)
if normalized:
return normalized
return getattr(member, "name", "Unknown")
def _safe_long_name(member, fallback_name):
long_name = getattr(member, "longName", "") or ""
return long_name or fallback_name
def _walk_layers(container):
for layer in container.listLayers():
yield layer
list_layers = getattr(layer, "listLayers", None)
if callable(list_layers):
for child in _walk_layers(layer):
yield child
def _get_all_layers(map_name=None):
_, active_map = _resolve_map(map_name)
return list(_walk_layers(active_map))
def _get_group_layer_name(layer):
long_name = getattr(layer, "longName", "") or ""
if "\\" not in long_name:
return ""
parts = [part for part in long_name.split("\\") if part]
if len(parts) <= 1:
return ""
return parts[-2]
def _get_layer_uri(layer, definition=None):
if definition is None:
definition = layer.getDefinition(TARGET_CIM_VERSION)
return getattr(layer, "URI", "") or getattr(definition, "uRI", "")
def _get_layer_type_description(layer):
if getattr(layer, "isGroupLayer", False):
return "Group Layer"
if getattr(layer, "isFeatureLayer", False):
return "Feature Layer"
if getattr(layer, "isRasterLayer", False):
return "Raster Layer"
if getattr(layer, "isBasemapLayer", False):
return "Basemap Layer"
if getattr(layer, "isWebLayer", False):
return "Web Layer"
return layer.__class__.__name__
def _supports_property(layer, property_name):
supports = getattr(layer, "supports", None)
if callable(supports):
try:
return bool(supports(property_name))
except Exception:
return False
return False
def _scale_to_text(value):
try:
numeric_value = float(value)
except (TypeError, ValueError):
return "None"
if numeric_value == 0:
return "None"
if numeric_value.is_integer():
return str(int(numeric_value))
return str(numeric_value)
def _parse_scale_value(value, keep_existing=False):
text = str(value or "").strip()
if not text:
return None if keep_existing else 0.0
if text.lower() in ("none", "<none>", "null"):
return 0.0
try:
return float(text.replace(",", ""))
except ValueError as exc:
raise ToolboxError("Scale value '{0}' is not valid.".format(value)) from exc
def _get_label_scale_range(layer):
if not _supports_property(layer, "SHOWLABELS"):
return ("N/A", "N/A")
try:
label_classes = layer.listLabelClasses()
except Exception:
return ("N/A", "N/A")
if not label_classes:
return ("None", "None")
minimum_values = []
maximum_values = []
for label_class in label_classes:
label_definition = label_class.getDefinition(TARGET_CIM_VERSION)
minimum_values.append(getattr(label_definition, "minimumScale", 0) or 0)
maximum_values.append(getattr(label_definition, "maximumScale", 0) or 0)
if len(set(minimum_values)) == 1 and len(set(maximum_values)) == 1:
return (_scale_to_text(minimum_values[0]), _scale_to_text(maximum_values[0]))
return ("Multiple", "Multiple")
def _walk_tables(container):
list_tables = getattr(container, "listTables", None)
if callable(list_tables):
for table in container.listTables():
yield table
for child in _walk_tables(table):
yield child
list_layers = getattr(container, "listLayers", None)
if callable(list_layers):
for layer in container.listLayers():
for table in _walk_tables(layer):
yield table
def _build_feature_layer_records(active_map):
records = []
seen_uris = set()
for layer in _walk_layers(active_map):
if not getattr(layer, "isFeatureLayer", False):
continue
if getattr(layer, "isBroken", False):
arcpy.AddWarning("Skipping broken layer: {0}".format(layer.name))
continue
definition = layer.getDefinition(TARGET_CIM_VERSION)
feature_table = getattr(definition, "featureTable", None)
subtype_value = ""
if feature_table is not None and getattr(feature_table, "useSubtypeValue", False):
subtype_value = str(getattr(feature_table, "subtypeValue", ""))
uri = getattr(layer, "URI", "") or getattr(definition, "uRI", "")
if uri in seen_uris:
continue
seen_uris.add(uri)
records.append(
MapMemberRecord(
map_name=active_map.name,
member=layer,
definition=definition,
member_kind="Feature Layer",
name=layer.name,
long_name=_safe_long_name(layer, layer.name),
class_name=_derive_class_name(layer, definition),
uri=uri,
subtype_value=subtype_value,
)
)
return records
def _build_table_records(active_map):
records = []
seen_uris = set()
for table in _walk_tables(active_map):
if getattr(table, "isBroken", False):
arcpy.AddWarning("Skipping broken table: {0}".format(table.name))
continue
definition = table.getDefinition(TARGET_CIM_VERSION)
subtype_value = ""
if getattr(definition, "useSubtypeValue", False):
subtype_value = str(getattr(definition, "subtypeValue", ""))
uri = getattr(table, "URI", "") or getattr(definition, "uRI", "")
if uri in seen_uris:
continue
seen_uris.add(uri)
records.append(
MapMemberRecord(
map_name=active_map.name,
member=table,
definition=definition,
member_kind="Standalone Table",
name=table.name,
long_name=table.name,
class_name=_derive_class_name(table, definition),
uri=uri,
subtype_value=subtype_value,
)
)
return records
def _get_all_supported_members(map_name=None):
_, active_map = _resolve_map(map_name)
return _build_feature_layer_records(active_map) + _build_table_records(active_map)
def _get_selectable_member_names(map_name=None):
return [record.long_name for record in _get_all_supported_members(map_name)]
def _create_default_field_description(field):
field_description = arcpy.cim.CreateCIMObjectFromClassName("CIMFieldDescription", TARGET_CIM_VERSION)
field_description.fieldName = field.name
field_description.alias = getattr(field, "aliasName", None) or field.name
field_description.highlight = False
field_description.visible = True
field_description.readOnly = not bool(getattr(field, "editable", False))
field_description.searchable = False
return field_description
def _get_member_fields(record):
data_source = getattr(record.member, "dataSource", None)
if data_source:
try:
described = arcpy.Describe(data_source)
if hasattr(described, "fields"):
return list(described.fields)
except Exception:
pass
try:
described = arcpy.Describe(record.member)
if hasattr(described, "fields"):
return list(described.fields)
except Exception:
pass
field_descriptions = []
if record.member_kind == "Feature Layer":
field_descriptions = list(getattr(record.definition.featureTable, "fieldDescriptions", []) or [])
else:
field_descriptions = list(getattr(record.definition, "fieldDescriptions", []) or [])
fallback_fields = []
for field_description in field_descriptions:
field_name = getattr(field_description, "fieldName", "")
if field_name:
fallback_fields.append(
type(
"FieldStub",
(),
{
"name": field_name,
"aliasName": getattr(field_description, "alias", "") or field_name,
"editable": not bool(getattr(field_description, "readOnly", False)),
"type": "String",
},
)()
)
return fallback_fields
def _get_complete_field_descriptions(record):
if record.member_kind == "Feature Layer":
existing = list(getattr(record.definition.featureTable, "fieldDescriptions", []) or [])
else:
existing = list(getattr(record.definition, "fieldDescriptions", []) or [])
existing_lookup = {fd.fieldName: fd for fd in existing if getattr(fd, "fieldName", None)}
complete = []
for field in _get_member_fields(record):
field_description = existing_lookup.get(field.name)
if field_description is None:
field_description = _create_default_field_description(field)
complete.append(field_description)
complete_names = {fd.fieldName for fd in complete}
for field_description in existing:
if getattr(field_description, "fieldName", None) not in complete_names:
complete.append(field_description)
return complete
def _set_field_descriptions(record, field_descriptions):
if record.member_kind == "Feature Layer":
record.definition.featureTable.fieldDescriptions = field_descriptions
else:
record.definition.fieldDescriptions = field_descriptions
def _get_display_field(record):
if record.member_kind == "Feature Layer":
return getattr(record.definition.featureTable, "displayField", "")
return getattr(record.definition, "displayField", "")
def _get_popup_info(record):
return getattr(record.definition, "popupInfo", None)
def _set_popup_info(record, popup_info):
record.definition.popupInfo = popup_info
def _get_display_expression_info(record):
if record.member_kind == "Feature Layer":
return getattr(record.definition.featureTable, "displayExpressionInfo", None)
return getattr(record.definition, "displayExpressionInfo", None)
def _set_display_expression_info(record, expression_info):
if record.member_kind == "Feature Layer":
record.definition.featureTable.displayExpressionInfo = expression_info
else:
record.definition.displayExpressionInfo = expression_info
def _save_record_definition(record):
record.member.setDefinition(record.definition)
def _record_to_field_rows(record):
rows = []
for field_order, field_description in enumerate(_get_complete_field_descriptions(record), start=1):
rows.append(
{
"Map Name": record.map_name,
"Class Name": record.class_name,
"Layer Name": record.name,
"Subtype Value": record.subtype_value,
"Field Name": field_description.fieldName,
"Field Order": field_order,
"Visible": bool(getattr(field_description, "visible", True)),
"Read Only": bool(getattr(field_description, "readOnly", False)),
"Highlight": bool(getattr(field_description, "highlight", False)),
"Field Alias": getattr(field_description, "alias", "") or "",
"Map Member URI": record.uri,
"Long Name": record.long_name,
"Member Kind": record.member_kind,
}
)
return rows
def _write_field_settings_csv(output_file, map_name=None):
rows = []
for record in _get_all_supported_members(map_name):
rows.extend(_record_to_field_rows(record))
_ensure_parent_folder(output_file)
with open(output_file, "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=FIELD_SETTINGS_COLUMNS)
writer.writeheader()
for row in rows:
writer.writerow(row)
arcpy.AddMessage("Exported field settings for {0} map members.".format(len({row['Map Member URI'] for row in rows})))
def _normalize_header(value):
return re.sub(r"[^a-z0-9]+", "", (value or "").lower())
def _read_csv_records(input_file):
with open(input_file, "r", newline="", encoding="utf-8-sig") as handle:
lines = handle.readlines()
header_index = None
for index, line in enumerate(lines):
first_cell = line.split(",", 1)[0].strip().strip('"')
if first_cell in ("Class Name", "Map Name"):
header_index = index
break
if header_index is None:
raise ToolboxError("Could not find a recognized header row in {0}.".format(input_file))
reader = csv.DictReader(lines[header_index:])
return [row for row in reader if any((value or "").strip() for value in row.values())]
def _get_row_value(row, *names, default=""):
normalized = {_normalize_header(key): key for key in row.keys()}
for name in names:
key = normalized.get(_normalize_header(name))
if key is not None:
return row.get(key, default)
return default
def _parse_bool(value, default=False):
if isinstance(value, bool):
return value
text = str(value).strip().lower()
if text in ("true", "1", "yes", "y", "t"):
return True
if text in ("false", "0", "no", "n", "f"):
return False
return default
def _build_member_lookup(map_name=None):
records = _get_all_supported_members(map_name)
by_uri = {}
by_fallback = {}
for record in records:
if record.uri:
by_uri[record.uri] = record
fallback_key = (
record.member_kind.lower(),
record.class_name.lower(),
record.name.lower(),
record.subtype_value.lower(),
record.long_name.lower(),
)
by_fallback[fallback_key] = record
short_key = (
record.member_kind.lower(),
record.class_name.lower(),
record.name.lower(),
record.subtype_value.lower(),
"",
)
by_fallback.setdefault(short_key, record)
return by_uri, by_fallback
def _group_field_rows(rows):
grouped = {}
for row in rows:
uri = _get_row_value(row, "Map Member URI")
member_kind = _get_row_value(row, "Member Kind", default="Feature Layer").strip() or "Feature Layer"
class_name = _get_row_value(row, "Class Name").strip()
layer_name = _get_row_value(row, "Layer Name").strip()
subtype_value = _get_row_value(row, "Subtype Value").strip()
long_name = _get_row_value(row, "Long Name").strip()
key = uri or "|".join([member_kind, class_name, layer_name, subtype_value, long_name])
grouped.setdefault(key, []).append(row)
return grouped
def _resolve_record(rows, by_uri, by_fallback):
sample = rows[0]
uri = _get_row_value(sample, "Map Member URI").strip()
if uri and uri in by_uri:
return by_uri[uri]
fallback_key = (
(_get_row_value(sample, "Member Kind", default="Feature Layer").strip() or "Feature Layer").lower(),
_get_row_value(sample, "Class Name").strip().lower(),
_get_row_value(sample, "Layer Name").strip().lower(),
_get_row_value(sample, "Subtype Value").strip().lower(),
_get_row_value(sample, "Long Name").strip().lower(),
)
if fallback_key in by_fallback:
return by_fallback[fallback_key]
short_key = fallback_key[:-1] + ("",)
return by_fallback.get(short_key)
def _apply_field_settings_csv(input_file, map_name=None):
rows = _read_csv_records(input_file)
by_uri, by_fallback = _build_member_lookup(map_name)
updated_count = 0
skipped = []
for _, grouped_rows in _group_field_rows(rows).items():
record = _resolve_record(grouped_rows, by_uri, by_fallback)
if record is None:
sample = grouped_rows[0]
skipped.append(
"{0} / {1}".format(
_get_row_value(sample, "Class Name"),
_get_row_value(sample, "Layer Name"),
)
)
continue
current_field_descriptions = _get_complete_field_descriptions(record)
current_lookup = {fd.fieldName: fd for fd in current_field_descriptions}
ordered_descriptions = []
consumed_names = set()
def _sort_key(row):
try:
return int(_get_row_value(row, "Field Order", default="0") or "0")
except ValueError:
return 0
for row in sorted(grouped_rows, key=_sort_key):
field_name = _get_row_value(row, "Field Name").strip()
field_description = current_lookup.get(field_name)
if field_description is None:
arcpy.AddWarning(
"Field '{0}' was not found on {1} and was skipped.".format(field_name, record.long_name)
)
continue
field_description.visible = _parse_bool(_get_row_value(row, "Visible"), default=True)
field_description.readOnly = _parse_bool(_get_row_value(row, "Read Only", "Read-Only"), default=False)
field_description.highlight = _parse_bool(_get_row_value(row, "Highlight"), default=False)
field_description.alias = _get_row_value(row, "Field Alias") or field_name
ordered_descriptions.append(field_description)
consumed_names.add(field_name)
for field_description in current_field_descriptions:
if field_description.fieldName not in consumed_names:
ordered_descriptions.append(field_description)
_set_field_descriptions(record, ordered_descriptions)
_save_record_definition(record)
updated_count += 1
arcpy.AddMessage("Updated field settings for {0} map members.".format(updated_count))
if skipped:
arcpy.AddWarning(
"Could not find {0} map members from the CSV: {1}".format(
len(skipped),
"; ".join(skipped[:10]),
)
)
def _build_layer_scale_row(map_name, layer, definition):
label_min_scale, label_max_scale = _get_label_scale_range(layer)
return {
"Map Name": map_name,
"Layer Type": _get_layer_type_description(layer),
"Group Layer Name": _get_group_layer_name(layer),
"Layer Name": layer.name,
"Long Name": getattr(layer, "longName", "") or layer.name,
"Layer URI": _get_layer_uri(layer, definition),
"Layer Min Scale": _scale_to_text(getattr(layer, "minThreshold", 0)),
"Layer Max Scale": _scale_to_text(getattr(layer, "maxThreshold", 0)),
"Label Min Scale": label_min_scale,
"Label Max Scale": label_max_scale,
}
def _write_layer_scales_csv(output_file, map_name=None):
_, active_map = _resolve_map(map_name)
rows = []
for layer in _get_all_layers(active_map.name):
if getattr(layer, "isBroken", False):
arcpy.AddWarning("Skipping broken layer: {0}".format(layer.name))
continue
definition = layer.getDefinition(TARGET_CIM_VERSION)
rows.append(_build_layer_scale_row(active_map.name, layer, definition))
_ensure_parent_folder(output_file)
with open(output_file, "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=LAYER_SCALE_COLUMNS)
writer.writeheader()
for row in rows:
writer.writerow(row)
arcpy.AddMessage("Exported layer scales for {0} layers.".format(len(rows)))
def _build_layer_lookup(map_name=None):
by_uri = {}
by_long_name = {}
for layer in _get_all_layers(map_name):
if getattr(layer, "isBroken", False):
continue
definition = layer.getDefinition(TARGET_CIM_VERSION)
uri = _get_layer_uri(layer, definition)
if uri:
by_uri[uri] = layer
long_name = (getattr(layer, "longName", "") or layer.name).lower()
by_long_name[long_name] = layer
return by_uri, by_long_name
def _apply_layer_scales_csv(input_file, map_name=None):
rows = _read_csv_records(input_file)
by_uri, by_long_name = _build_layer_lookup(map_name)
updated_count = 0
skipped = []
for row in rows:
uri = _get_row_value(row, "Layer URI").strip()
layer = by_uri.get(uri)
if layer is None:
long_name = (_get_row_value(row, "Long Name") or _get_row_value(row, "Layer Name")).strip().lower()
layer = by_long_name.get(long_name)
if layer is None:
skipped.append(_get_row_value(row, "Long Name") or _get_row_value(row, "Layer Name"))
continue
min_scale = _parse_scale_value(_get_row_value(row, "Layer Min Scale"), keep_existing=True)
max_scale = _parse_scale_value(_get_row_value(row, "Layer Max Scale"), keep_existing=True)
if min_scale is not None and _supports_property(layer, "MINTHRESHOLD"):
layer.minThreshold = min_scale
if max_scale is not None and _supports_property(layer, "MAXTHRESHOLD"):
layer.maxThreshold = max_scale
label_min_text = _get_row_value(row, "Label Min Scale")
label_max_text = _get_row_value(row, "Label Max Scale")
if _supports_property(layer, "SHOWLABELS") and (str(label_min_text).strip() or str(label_max_text).strip()):
if label_min_text not in ("Multiple", "multiple") and label_max_text not in ("Multiple", "multiple"):
label_min_scale = _parse_scale_value(label_min_text, keep_existing=True)
label_max_scale = _parse_scale_value(label_max_text, keep_existing=True)
for label_class in layer.listLabelClasses():
label_definition = label_class.getDefinition(TARGET_CIM_VERSION)
if label_min_scale is not None:
label_definition.minimumScale = label_min_scale
if label_max_scale is not None:
label_definition.maximumScale = label_max_scale
label_class.setDefinition(label_definition)
updated_count += 1
arcpy.AddMessage("Updated scale settings for {0} layers.".format(updated_count))
if skipped:
arcpy.AddWarning(
"Could not find {0} layers from the CSV: {1}".format(
len(skipped),
"; ".join(skipped[:10]),
)
)
def _normalize_output_name(value):
return re.sub(r"[^A-Za-z0-9._-]+", "_", str(value or "").strip()).strip("_") or "output"
def _write_rows_to_csv(output_file, rows, fieldnames=None):
if fieldnames is None:
fieldnames = []
for row in rows:
for key in row.keys():
if key not in fieldnames:
fieldnames.append(key)
_ensure_parent_folder(output_file)
with open(output_file, "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=fieldnames)
writer.writeheader()
for row in rows:
writer.writerow(row)
def _safe_getattr(value, *names, default=None):
for name in names:
if hasattr(value, name):
return getattr(value, name)
return default
def _stringify_value(value):
if value is None:
return ""
if isinstance(value, datetime.datetime):
return value.isoformat()
if isinstance(value, (list, tuple)):
return "; ".join(_stringify_value(item) for item in value)
return str(value)
def _discover_utility_network_paths(map_name=None):
search_roots = set()
for record in _get_all_supported_members(map_name):
data_source = getattr(record.member, "dataSource", None)
if not data_source:
continue
try:
desc = arcpy.Describe(data_source)
except Exception:
continue
for candidate in [data_source, getattr(desc, "path", None)]:
if candidate:
search_roots.add(candidate)
utility_network_paths = []
seen = set()
for root in search_roots:
try:
for dirpath, dirnames, filenames in arcpy.da.Walk(root, datatype="UtilityNetwork"):
for filename in filenames:
path = _normalize_utility_network_input(os.path.join(dirpath, filename))
if not path:
continue
if path not in seen:
seen.add(path)
utility_network_paths.append(path)
except Exception:
continue
return sorted(utility_network_paths)
def _normalize_utility_network_input(utility_network_input):
if not utility_network_input:
return ""
try:
desc = arcpy.Describe(utility_network_input)
except Exception:
return utility_network_input
if getattr(desc, "dataType", "") == "UtilityNetwork":
direct_catalog_path = _safe_getattr(desc, "catalogPath", "catalogpath")
return direct_catalog_path or utility_network_input
data_element = getattr(desc, "dataElement", None)
if data_element is not None and getattr(data_element, "dataType", "") == "UtilityNetwork":
catalog_path = _safe_getattr(data_element, "catalogPath", "catalogpath")
return catalog_path or utility_network_input
return ""
def _resolve_utility_network_path(map_name=None, utility_network_path=None):
if utility_network_path:
normalized_path = _normalize_utility_network_input(utility_network_path)
if normalized_path:
return normalized_path
raise ToolboxError(
"The Utility Network parameter must reference a utility network layer or a utility network dataset."
)
candidates = _discover_utility_network_paths(map_name)
if not candidates:
raise ToolboxError(
"No utility network dataset could be discovered from the selected map. "
"Use a map with utility network layers or provide a utility network dataset path."
)
if len(candidates) > 1:
raise ToolboxError(
"Multiple utility network datasets were discovered. Select one from the Utility Network parameter."
)
return candidates[0]
def _resolve_utility_network_context(utility_network_path):