-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDPSManagerApp_PyQt5
More file actions
2068 lines (1841 loc) · 90.3 KB
/
PDPSManagerApp_PyQt5
File metadata and controls
2068 lines (1841 loc) · 90.3 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 -*-
"""
PDPSManagerApp - PyQt5 GUI 重写版
将原 tkinter GUI 全部替换为 PyQt5,业务逻辑类保持不变。
"""
import os
import sys
import subprocess
import threading
import queue
import traceback
import json
import math
import zipfile
from datetime import datetime
from typing import List, Dict, Optional, Tuple
import pandas as pd
import numpy as np
import winreg
import re
import ctypes
from PIL import Image
# ── PyQt5 ──────────────────────────────────────────────────────────────────
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QTabWidget, QFrame, QSplitter,
QVBoxLayout, QHBoxLayout, QGridLayout, QFormLayout,
QLabel, QPushButton, QLineEdit, QTextEdit, QPlainTextEdit,
QComboBox, QCheckBox, QRadioButton, QButtonGroup,
QTreeWidget, QTreeWidgetItem, QHeaderView,
QTableWidget, QTableWidgetItem, QAbstractItemView,
QProgressBar, QScrollArea, QGroupBox,
QMenu, QAction, QMessageBox, QFileDialog, QDialog,
QStatusBar, QSizePolicy, QDoubleSpinBox, QSpinBox,
QStyleFactory
)
from PyQt5.QtGui import (
QFont, QColor, QPixmap, QIcon, QPalette, QImage,
QStandardItemModel, QStandardItem
)
from PyQt5.QtCore import (
Qt, QThread, pyqtSignal, QTimer, QSize, QMimeData, QModelIndex
)
# ── 全局常量 ────────────────────────────────────────────────────────────────
CONFIG_FILE = "pdps_master_config_v13.xlsx"
REG_PATH = r"Software\TECNOMATIX\TUNE\NewAssembler\Options\EMS"
# ── pycatia 可选导入 ────────────────────────────────────────────────────────
try:
from pycatia import catia as pycatia_catia
from pycatia.mec_mod_interfaces.part_document import PartDocument
PYCATIA_AVAILABLE = True
except Exception:
PYCATIA_AVAILABLE = False
# ============================================================================
# 业务逻辑类(直接从原文件保留,不做任何修改)
# ============================================================================
# ── CATIAWeldPointExtractor ──────────────────────────────────────────────────
class CATIAWeldPointExtractor:
"""CATIA 焊点提取工具类(兼容 win32com 和 pycatia)"""
def __init__(self, catia_app=None):
self.catia_app = catia_app
self.weld_points_data: List[Dict] = []
self.status_message = "就绪"
self.connection_type = None
def connect_catia(self, use_pycatia=False) -> bool:
try:
if use_pycatia:
if not PYCATIA_AVAILABLE:
return False
self.catia_app = pycatia_catia()
self.connection_type = 'pycatia'
self.status_message = "已连接 | CATIA (pycatia)"
return True
else:
import win32com.client
try:
self.catia_app = win32com.client.GetActiveObject("CATIA.Application")
except Exception:
self.catia_app = win32com.client.Dispatch("CATIA.Application")
self.connection_type = 'win32com'
self.status_message = "已连接 | CATIA (win32com)"
return True
except Exception as e:
self.status_message = "连接 CATIA 失败"
return False
def set_catia_app(self, catia_app, connection_type='win32com'):
self.catia_app = catia_app
self.connection_type = connection_type
self.status_message = f"CATIA 应用已设置 ({connection_type})"
def get_status(self):
return self.status_message
def extract_weld_points(self, auto_rename: bool = False) -> List[Dict]:
if not self.catia_app:
self.status_message = "请先连接 CATIA"
return []
self.weld_points_data = []
try:
if self.connection_type == 'pycatia':
doc = self.catia_app.active_document
if not doc or not hasattr(doc, 'part'):
self.status_message = "当前文档不是 Part 文档"
return []
part = doc.part
selection = doc.selection
part_full_name = doc.name
else:
doc = self.catia_app.ActiveDocument
if not doc:
return []
try:
part = doc.Part
except:
self.status_message = "当前文档不是 Part 文档"
return []
selection = doc.Selection
part_full_name = doc.Name
spa_workbench = None
try:
if self.connection_type == 'pycatia':
spa_workbench = doc.spa_workbench()
else:
spa_workbench = doc.GetWorkbench("SPAWorkbench")
except:
pass
if self.connection_type == 'pycatia':
selection.clear()
selection.search("CATGmoSearch.Point,all")
count = selection.count
else:
selection.Clear()
selection.Search("CATGmoSearch.Point,all")
count = selection.Count
# ── 预扫描:构建 {点名称 → 直接父图形集名称} 映射表 ────────────
# 比逐点调用 .Parent 更可靠,避免 win32com/pycatia 的 Parent 属性失效问题
point_parent_map = self._build_point_parent_map(part)
for i in range(1, count + 1):
try:
if self.connection_type == 'pycatia':
item = selection.item(i)
point_obj = item.value
name = getattr(point_obj, 'name', f"Point_{i}")
else:
item = selection.Item(i)
point_obj = item.Value
name = getattr(point_obj, 'Name', f"Point_{i}")
# ── 从映射表获取父图形集名 ──────────────────────────────
# 优先用精确名查询,再去掉 GSMPoint 后缀的基本名匹配
geo_set_name = point_parent_map.get(name, "")
if not geo_set_name:
# 点名可能含 ".N" 后缀,尝试去掉后缀再匹配
base_name = re.sub(r'\.GSMPoint\.\d+$', '', name, flags=re.IGNORECASE)
base_name = re.sub(r'-GSMPoint\.\d+$', '', base_name, flags=re.IGNORECASE)
geo_set_name = point_parent_map.get(base_name, "")
# ── 获取坐标 ────────────────────────────────────────────
x, y, z = 0, 0, 0
try:
if spa_workbench:
if self.connection_type == 'pycatia':
ref = part.create_reference_from_object(point_obj)
m = spa_workbench.get_measurable(ref)
coords = m.get_point()
else:
ref = part.CreateReferenceFromObject(point_obj)
m = spa_workbench.GetMeasurable(ref)
coords = [0, 0, 0]
m.GetPoint(coords)
x, y, z = coords[0], coords[1], coords[2]
except:
pass
# ── 自动重命名 ───────────────────────────────────────────
# geo_set_name 即为图形集名(如 DPUB-501000588-XAX&DPUB-501000592-XAX&...)
# 直接用它提取零件号,无需再向上遍历父节点
std_name = name
if auto_rename:
std_name = self._generate_standard_name(name, geo_set_name)
# ── 根据图形集名称中 & 数量推断焊接层数类型 ────────────
weld_type = self._weld_type_from_location(geo_set_name)
location_str = f"{x:.3f},{y:.3f},{z:.3f}"
self.weld_points_data.append({
"Class": "PmWeldPoint",
"ExternalId": std_name,
"Name": std_name,
"Location": location_str,
"X": round(x, 3),
"Y": round(y, 3),
"Z": round(z, 3),
"Type": weld_type
})
except:
pass
self.status_message = f"已提取 {len(self.weld_points_data)} 个焊点"
except Exception as e:
self.status_message = f"提取失败: {e}"
return self.weld_points_data
def _generate_standard_name(self, original_name: str, geo_set_name: str) -> str:
"""
生成标准命名:{前缀}_{零件数字段}_{焊点数字段}
焊点名示例: T1E-0000010296-RSW-GSMPoint.2
→ 前缀 = T1E,焊点 ID = 10296
图形集名示例:DPUB-501000588-XAX&DPUB-501000592-XAX&DPUB-501001638-XAX
→ 取第一段 DPUB-501000588-XAX,零件 ID = 501000588(首个纯数字段)
结果示例:T1E_501000588_10296
"""
try:
# ── 1. 提取前缀(焊点名第一个"-"之前)──────────────────────────
orig_segs = original_name.split('-')
prefix = orig_segs[0].strip() if orig_segs else "UNK"
# ── 2. 提取零件 ID(从图形集名第一个 & 段中找首个纯数字段)──────
part_id = ""
if geo_set_name:
# 取 & 之前的第一个零件名段,如 "DPUB-501000588-XAX"
first_part_seg = geo_set_name.split('&')[0].strip()
for seg in first_part_seg.split('-'):
seg_clean = seg.split('_')[0] # 去掉下划线后缀,如 "XWS_00" → "XWS"
if seg_clean.isdigit():
part_id = seg_clean
break
if not part_id:
# 降级:取第二段(不要求纯数字)
p_segs = first_part_seg.split('-')
part_id = p_segs[1].split('_')[0] if len(p_segs) > 1 else p_segs[0]
if not part_id:
part_id = re.sub(r'[^A-Za-z0-9]', '', geo_set_name)[:12] or "PART"
# ── 3. 提取焊点数字(第二段去前导零)──────────────────────────
weld_id = "0"
if len(orig_segs) > 1:
raw = orig_segs[1].strip()
weld_id = raw.lstrip('0') or "0"
return f"{prefix}_{part_id}_{weld_id}"
except Exception:
return original_name
@staticmethod
def _weld_type_from_location(location_name: str) -> str:
"""
根据图形集名称中 '&' 的数量推断焊接层数类型:
无 & 或 1 个 & → 双层板 → "2T"
2 个 & → 三层板 → "3T"
N 个 & → (N+1) 层板 → "{N+1}T"
规则:N 个 & 连接 (N+1) 个零件,即 (N+1) 层板。
无 & 时认为只有1个零件段,默认双层板(实际为单零件贴合场景取2T)。
"""
count = location_name.count('&')
layers = max(2, count + 1) # 0 个 & → 1 个零件 → 默认 2T; 2 个 & → 3 个零件 → 3T
return f"{layers}T"
def _build_point_parent_map(self, part) -> Dict[str, str]:
"""
预扫描零件的全部 HybridBodies(图形集)层级,
构建 {点名称: 直接父图形集名称} 映射表。
支持 win32com 和 pycatia 两种连接方式。
"""
point_parent_map: Dict[str, str] = {}
def _scan_body(hb, conn_type: str):
"""递归扫描一个 HybridBody 内的所有点和子图形集。"""
try:
if conn_type == 'pycatia':
hb_name = hb.name
shapes = hb.hybrid_shapes
shape_count = shapes.count
sub_bodies = hb.hybrid_bodies
sub_count = sub_bodies.count
def get_shape(j): return shapes.item(j)
def get_shape_name(s): return s.name
def get_sub(j): return sub_bodies.item(j)
else:
hb_name = hb.Name
shapes = hb.HybridShapes
shape_count = shapes.Count
sub_bodies = hb.HybridBodies
sub_count = sub_bodies.Count
def get_shape(j): return shapes.Item(j)
def get_shape_name(s): return s.Name
def get_sub(j): return sub_bodies.Item(j)
# 登记本 HybridBody 内直属的所有形状
for j in range(1, shape_count + 1):
try:
shape = get_shape(j)
sname = get_shape_name(shape)
if sname:
point_parent_map[sname] = hb_name
except Exception:
pass
# 递归处理子图形集(但子图形集内的点归属子图形集,不覆盖父级)
for j in range(1, sub_count + 1):
try:
_scan_body(get_sub(j), conn_type)
except Exception:
pass
except Exception as e:
print(f"_scan_body error: {e}")
try:
if self.connection_type == 'pycatia':
root_bodies = part.hybrid_bodies
for i in range(1, root_bodies.count + 1):
_scan_body(root_bodies.item(i), 'pycatia')
else:
root_bodies = part.HybridBodies
for i in range(1, root_bodies.Count + 1):
_scan_body(root_bodies.Item(i), 'win32com')
except Exception as e:
print(f"_build_point_parent_map error: {e}")
return point_parent_map
def log_error(self, context, error):
print(f"Error in {context}: {error}")
traceback.print_exc()
self.status_message = f"错误: {context}"
# ── CATIASphereScanner ──────────────────────────────────────────────────────
class CATIASphereScanner:
def __init__(self, catia_app=None):
self.catia_app = catia_app
self.sphere_data = []
def set_catia_app(self, catia_app):
self.catia_app = catia_app
def scan_selected_objects(self) -> List[Dict]:
if not self.catia_app:
raise Exception("CATIA 未连接")
try:
document = self.catia_app.active_document
part_doc = PartDocument(document.com_object)
part = part_doc.part
selection = document.selection
spa_workbench = part_doc.spa_workbench()
count = selection.count
if count == 0:
return []
self.sphere_data = []
for i in range(1, count + 1):
try:
selected_obj = selection.item(i).value
obj_name = getattr(selected_obj, 'name', f"Object_{i}")
reference = part.create_reference_from_object(selected_obj)
measurable = spa_workbench.get_measurable(reference)
cog = measurable.get_cog()
try:
volume = measurable.volume
except:
volume = 0
radius = (volume * 3 / (4 * 3.14159265359)) ** (1 / 3) if volume > 0 else 0
self.sphere_data.append({
"Name": obj_name,
"X": f"{cog[0]:.2f}",
"Y": f"{cog[1]:.2f}",
"Z": f"{cog[2]:.2f}",
"Radius": f"{radius:.2f}",
"Volume": round(volume, 3),
"Type": "实体" if volume > 0 else "几何图形",
"_coords": cog
})
except Exception as e:
print(f"无法测量对象 {i}: {e}")
return self.sphere_data
except Exception as e:
traceback.print_exc()
return []
def scan_all_bodies(self, search_keywords=None):
if not self.catia_app:
raise Exception("CATIA 未连接")
try:
document = self.catia_app.active_document
part_doc = PartDocument(document.com_object)
part = part_doc.part
spa_workbench = part_doc.spa_workbench()
self.sphere_data = []
bodies = part.bodies
for i in range(1, bodies.count + 1):
body = bodies.item(i)
if search_keywords:
if not any(kw.lower() in body.name.lower() for kw in search_keywords):
continue
try:
reference = part.create_reference_from_object(body)
measurable = spa_workbench.get_measurable(reference)
cog = measurable.get_cog()
volume = measurable.volume
self.sphere_data.append({
"Name": body.name,
"X": f"{cog[0]:.2f}",
"Y": f"{cog[1]:.2f}",
"Z": f"{cog[2]:.2f}",
"Radius": f"{(volume * 3 / (4 * 3.14)) ** (1 / 3):.2f}" if volume > 0 else "0",
"Volume": round(volume, 3),
"Type": "Body",
"_coords": cog
})
except:
continue
return self.sphere_data
except Exception as e:
traceback.print_exc()
return []
def generate_points_at_centers(self, geometrical_set_name="Geometry_COG_Points") -> int:
if not self.sphere_data:
return 0
try:
part_doc = PartDocument(self.catia_app.active_document.com_object)
part = part_doc.part
hs_factory = part.hybrid_shape_factory
hybrid_bodies = part.hybrid_bodies
try:
target_hb = hybrid_bodies.item(geometrical_set_name)
except:
target_hb = hybrid_bodies.add()
target_hb.name = geometrical_set_name
for data in self.sphere_data:
x, y, z = data["_coords"]
new_point = hs_factory.add_new_point_coord(x, y, z)
new_point.name = f"COG_{data['Name']}"
target_hb.append_hybrid_shape(new_point)
part.update()
return len(self.sphere_data)
except Exception as e:
print(f"生成点失败: {e}")
return 0
def get_data(self):
return self.sphere_data
# ── CatiaGunPlacer ──────────────────────────────────────────────────────────
class CatiaGunPlacer:
def __init__(self, catia_app=None):
self.catia_app = catia_app
self.connection_type = None
self.status_message = "就绪"
self.gun_template_path = ""
self.rotation_order = 'kuka'
def set_rotation_order(self, order: str):
valid_orders = ['kuka', 'catia_zyx', 'catia_xyz']
if order in valid_orders:
self.rotation_order = order
def set_catia_app(self, catia_app, connection_type='win32com'):
self.catia_app = catia_app
self.connection_type = connection_type
self.status_message = f"CATIA 已连接 ({connection_type})"
def is_catia_connected(self) -> bool:
if not self.catia_app:
return False
try:
if self.connection_type == 'pycatia':
_ = self.catia_app.documents.count
else:
_ = self.catia_app.Documents.Count
return True
except:
return False
def has_active_product(self) -> bool:
if not self.is_catia_connected():
return False
try:
if self.connection_type == 'pycatia':
doc = self.catia_app.active_document
return hasattr(doc, 'product')
else:
doc = self.catia_app.ActiveDocument
try:
_ = doc.Product
return True
except:
return False
except:
return False
def euler_to_rotation_matrix(self, rx, ry, rz, order=None):
if order is None:
order = self.rotation_order
rx_r, ry_r, rz_r = math.radians(rx), math.radians(ry), math.radians(rz)
Rx = np.array([[1,0,0],[0,math.cos(rx_r),-math.sin(rx_r)],[0,math.sin(rx_r),math.cos(rx_r)]])
Ry = np.array([[math.cos(ry_r),0,math.sin(ry_r)],[0,1,0],[-math.sin(ry_r),0,math.cos(ry_r)]])
Rz = np.array([[math.cos(rz_r),-math.sin(rz_r),0],[math.sin(rz_r),math.cos(rz_r),0],[0,0,1]])
if order in ('kuka', 'catia_zyx'):
return Rz @ Ry @ Rx
else:
return Rx @ Ry @ Rz
def euler_to_catia_components(self, x, y, z, rx, ry, rz):
R = self.euler_to_rotation_matrix(rx, ry, rz)
return [R[0,0],R[1,0],R[2,0], R[0,1],R[1,1],R[2,1], R[0,2],R[1,2],R[2,2], x, y, z]
def place_guns_batch(self, gun_template, gun_data, progress_callback=None,
correction_values=None, rotation_order=None):
if not self.is_catia_connected():
QMessageBox.critical(None, "错误", "CATIA 未连接")
return 0, 0, []
if not self.has_active_product():
QMessageBox.critical(None, "错误", "请先打开一个 Product 文档")
return 0, 0, []
if rotation_order:
self.set_rotation_order(rotation_order)
gun_template_normalized = os.path.normpath(gun_template).replace('/', '\\')
success_count, failed_count = 0, 0
status_list = []
try:
if self.connection_type == 'pycatia':
doc = self.catia_app.active_document
product = doc.product
products = product.products
com_products = products.com_object
else:
doc = self.catia_app.ActiveDocument
product = doc.Product
com_products = product.Products
from datetime import datetime as dt
container_name = f"{product.Name if hasattr(product,'Name') else 'Product'}-GUN-{dt.now().strftime('%Y%m%d')}"
try:
container = com_products.AddNewComponent("Product", container_name)
container_products = container.Products
except Exception as e:
print(f"创建容器失败: {e}")
container_products = com_products
total = len(gun_data)
for idx, gun in enumerate(gun_data):
try:
x = float(gun.get('X', 0))
y = float(gun.get('Y', 0))
z = float(gun.get('Z', 0))
rx = float(gun.get('Rx', 0))
ry = float(gun.get('Ry', 0))
rz = float(gun.get('Rz', 0))
if correction_values:
x += correction_values.get('X', 0)
y += correction_values.get('Y', 0)
z += correction_values.get('Z', 0)
rx += correction_values.get('Rx', 0)
ry += correction_values.get('Ry', 0)
rz += correction_values.get('Rz', 0)
file_array = (gun_template_normalized,)
container_products.AddComponentsFromFiles(file_array, "All")
import time
time.sleep(0.3)
count = container_products.Count
new_product = container_products.Item(count)
new_product.Name = gun.get('Name', f'Gun_{idx+1}')
components = self.euler_to_catia_components(x, y, z, rx, ry, rz)
position = new_product.Position
position.SetComponents(components)
success_count += 1
status_list.append("✓ 成功")
if progress_callback:
progress_callback(idx + 1, total, f"插入: {gun.get('Name', '')}")
except Exception as e:
failed_count += 1
status_list.append(f"✗ {str(e)[:30]}")
print(f"插入第{idx+1}个失败: {e}")
try:
if self.connection_type == 'pycatia':
doc.product.update()
else:
doc.Product.Update()
except:
pass
self.status_message = f"完成 | 成功: {success_count} | 失败: {failed_count}"
return success_count, failed_count, status_list
except Exception as e:
QMessageBox.critical(None, "批量插入失败", f"发生错误:\n{str(e)}")
return success_count, failed_count, status_list
# ============================================================================
# 样式助手
# ============================================================================
def _lighten(hex_color: str, factor: float = 1.18) -> str:
"""将 HEX 颜色调亮,用于 hover 状态。"""
h = hex_color.lstrip('#')
r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
return "#{:02x}{:02x}{:02x}".format(min(255, int(r*factor)),
min(255, int(g*factor)),
min(255, int(b*factor)))
def _darken(hex_color: str, factor: float = 0.78) -> str:
"""将 HEX 颜色调暗,用于 pressed 状态。"""
h = hex_color.lstrip('#')
r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
return "#{:02x}{:02x}{:02x}".format(int(r*factor), int(g*factor), int(b*factor))
def make_btn(text, color, callback=None, width=None, height=None):
"""创建带悬停/按下变色特效的按钮。"""
btn = QPushButton(text)
hov = _lighten(color) # 悬停时变亮
prs = _darken(color) # 按下时变暗
btn.setStyleSheet(
f"QPushButton {{"
f" background-color: {color}; color: white;"
f" border: none; border-radius: 4px;"
f" padding: 5px 12px; font-size: 13px;"
f"}}"
f"QPushButton:hover {{"
f" background-color: {hov};"
f" border-bottom: 2px solid {prs};"
f"}}"
f"QPushButton:pressed {{"
f" background-color: {prs};"
f" border-top: 2px solid {hov};"
f" padding-top: 7px;"
f"}}"
f"QPushButton:disabled {{"
f" background-color: #aab7b8; color: #ecf0f1;"
f"}}"
)
if callback:
btn.clicked.connect(callback)
if width:
btn.setFixedWidth(width)
if height:
btn.setFixedHeight(height)
return btn
# ============================================================================
# 页面 1:项目路径管理
# ============================================================================
class ProjectManagerPage(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.search_paths = []
self.df_data = pd.DataFrame(
columns=["Company", "Plant", "Area", "Project Name",
"Project Code", "File Name", "Full Path", "System Root"])
self.current_preview_pixmap = None
self._preview_raw_image = None
self._setup_ui()
self.load_local_config()
def _setup_ui(self):
root_layout = QVBoxLayout(self)
root_layout.setContentsMargins(0, 0, 0, 0)
root_layout.setSpacing(0)
# ── 顶部工具栏 ───────────────────────────────────────────────────────
toolbar = QFrame()
toolbar.setStyleSheet("background-color:#34495e;")
toolbar.setFixedHeight(50)
tb_layout = QHBoxLayout(toolbar)
tb_layout.setContentsMargins(10, 5, 10, 5)
tb_layout.addWidget(QLabel("🔍 搜索项目:", styleSheet="color:white;"))
self.search_edit = QLineEdit()
self.search_edit.setFixedWidth(220)
self.search_edit.textChanged.connect(self.refresh_tree)
tb_layout.addWidget(self.search_edit)
tb_layout.addWidget(QLabel(" 🏢 公司筛选:", styleSheet="color:white;"))
self.combo_company = QComboBox()
self.combo_company.setFixedWidth(140)
self.combo_company.addItem("全部公司")
self.combo_company.currentTextChanged.connect(self.refresh_tree)
tb_layout.addWidget(self.combo_company)
tb_layout.addStretch()
tb_layout.addWidget(make_btn("打开Catia", "#3498db", self.open_catia))
tb_layout.addWidget(make_btn("+ 添加目录", "#3498db", self.add_search_folder))
tb_layout.addWidget(make_btn("🔄 深度扫描", "#27ae60", self.scan_files))
tb_layout.addWidget(make_btn("💾 保存修改", "#f1c40f", self.save_config))
root_layout.addWidget(toolbar)
# ── 主体分割 ─────────────────────────────────────────────────────────
splitter = QSplitter(Qt.Horizontal)
# 左侧树
left = QWidget()
left_layout = QVBoxLayout(left)
left_layout.setContentsMargins(4, 4, 4, 4)
self.tree = QTreeWidget()
self.tree.setColumnCount(7)
self.tree.setHeaderLabels(
["组织架构", "项目代号", "状态", "文件路径", "文件名", "大小", "修改时间"])
self.tree.header().setSectionResizeMode(0, QHeaderView.ResizeToContents)
self.tree.header().setSectionResizeMode(3, QHeaderView.Stretch)
self.tree.setAlternatingRowColors(True)
self.tree.setSelectionMode(QAbstractItemView.SingleSelection)
self.tree.itemSelectionChanged.connect(self.on_item_select)
self.tree.itemDoubleClicked.connect(lambda item, _: self.launch_pdps())
# 右键菜单
self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
self.tree.customContextMenuRequested.connect(self._show_tree_context_menu)
left_layout.addWidget(self.tree)
splitter.addWidget(left)
splitter.setSizes([900, 300])
# 右侧详情
right = QWidget()
right.setStyleSheet("background:#ecf0f1;")
right_layout = QVBoxLayout(right)
right_layout.setContentsMargins(12, 8, 12, 8)
right_layout.addWidget(QLabel("项目预览", styleSheet="font-weight:bold;"))
self.lbl_preview = QLabel()
self.lbl_preview.setMinimumHeight(160)
self.lbl_preview.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.lbl_preview.setAlignment(Qt.AlignCenter)
self.lbl_preview.setStyleSheet("background:black;color:white;border-radius:4px;")
self.lbl_preview.setText("无预览图")
self._preview_raw_image = None # 保存原始 PIL Image 供缩放用
right_layout.addWidget(self.lbl_preview)
# 编辑字段
self.entries: Dict[str, QLineEdit] = {}
form = QFormLayout()
for label, key in [("所属公司:", "Company"), ("所在厂房:", "Plant"),
("所属区域:", "Area"), ("项目名称:", "Project Name"),
("项目代号:", "Project Code")]:
e = QLineEdit()
self.entries[key] = e
form.addRow(label, e)
right_layout.addLayout(form)
lbl_root = QLabel("System Root (修改将同步同级文件):")
lbl_root.setStyleSheet("color:#e67e22;font-weight:bold;")
right_layout.addWidget(lbl_root)
self.txt_root = QTextEdit()
self.txt_root.setFixedHeight(80)
self.txt_root.setFont(QFont("Consolas", 9))
right_layout.addWidget(self.txt_root)
right_layout.addWidget(make_btn("🔥 确认修改并同步", "#34495e",
self.update_metadata_and_sync, height=32))
right_layout.addWidget(make_btn("📂 定位文件位置", "#bdc3c7",
self.open_folder, height=28))
right_layout.addStretch()
right_layout.addWidget(make_btn("🚀 启动项目", "#27ae60",
self.launch_pdps, height=42))
self.status_lbl = QLabel("就绪")
self.status_lbl.setStyleSheet("color:#7f8c8d;font-size:11px;")
right_layout.addWidget(self.status_lbl)
splitter.addWidget(right)
root_layout.addWidget(splitter)
# ── 右键菜单 ─────────────────────────────────────────────────────────────
def _show_tree_context_menu(self, pos):
item = self.tree.itemAt(pos)
if item and item.data(0, Qt.UserRole) is not None:
menu = QMenu(self)
menu.addAction("复制完整路径", self.copy_full_path)
menu.addAction("打开所在文件夹", self.open_folder)
menu.addSeparator()
menu.addAction("查看文件属性", self.show_file_properties)
menu.exec_(self.tree.mapToGlobal(pos))
def copy_full_path(self):
item = self._selected_file_item()
if item:
idx = item.data(0, Qt.UserRole)
path = self.df_data.loc[idx, "Full Path"]
QApplication.clipboard().setText(path)
self.status_lbl.setText(f"已复制: {path}")
def show_file_properties(self):
item = self._selected_file_item()
if not item:
return
idx = item.data(0, Qt.UserRole)
row = self.df_data.loc[idx]
full_path = row["Full Path"]
if os.path.exists(full_path):
size = os.path.getsize(full_path)
mtime = datetime.fromtimestamp(os.path.getmtime(full_path)).strftime('%Y-%m-%d %H:%M:%S')
info = (f"路径: {full_path}\n大小: {size/1024:.2f} KB\n修改时间: {mtime}\n"
f"公司: {row['Company']}\n厂房: {row['Plant']}\n"
f"项目: {row['Project Name']}\n代号: {row['Project Code']}")
QMessageBox.information(self, "文件属性", info)
else:
QMessageBox.warning(self, "警告", "文件不存在")
def _selected_file_item(self):
items = self.tree.selectedItems()
if items and items[0].data(0, Qt.UserRole) is not None:
return items[0]
return None
# ── 核心逻辑 ─────────────────────────────────────────────────────────────
def auto_extract_info(self, psz_path):
path_parts = os.path.normpath(psz_path).split(os.sep)
psz_dir = os.path.dirname(psz_path)
info = {"Company": "", "Plant": "", "Area": "默认区域",
"Project Name": "", "Project Code": "", "System Root": ""}
try:
subfolders = [f for f in os.listdir(psz_dir) if os.path.isdir(os.path.join(psz_dir, f))]
if any("library" in f.lower() for f in subfolders):
lib = next(f for f in subfolders if "library" in f.lower())
info["System Root"] = os.path.normpath(os.path.join(psz_dir, lib))
info["Area"] = "项目根目录" if "项目" in os.path.basename(psz_dir) else os.path.basename(psz_dir)
else:
info["System Root"] = os.path.normpath(os.path.join(psz_dir, ".."))
except:
pass
proj_idx = next((i for i, p in enumerate(path_parts) if "项目" in p), -1)
comp_idx = next((i for i, p in enumerate(path_parts) if "公司" in p), -1)
if proj_idx != -1:
part = path_parts[proj_idx]
bracket = re.search(r'[((]([^))]+)[))]', part)
if bracket:
info["Project Code"] = bracket.group(1).strip()
info["Project Name"] = part[:bracket.start()].strip()
else:
info["Project Name"] = part
if proj_idx > 0:
info["Plant"] = path_parts[proj_idx - 1]
info["Company"] = path_parts[comp_idx] if comp_idx != -1 else (
path_parts[proj_idx - 2] if proj_idx > 1 else "")
elif comp_idx != -1:
info["Company"] = path_parts[comp_idx]
info["Project Name"] = "未识别项目"
if not info["Company"]: info["Company"] = "通用客户"
if not info["Plant"]: info["Plant"] = "未知厂房"
if not info["Project Name"]: info["Project Name"] = os.path.basename(psz_path)
return info
def refresh_tree(self):
self.tree.clear()
df = self.df_data.copy()
company_filter = self.combo_company.currentText()
if company_filter != "全部公司":
df = df[df["Company"] == company_filter]
kw = self.search_edit.text().strip().lower()
if kw:
df = df[df.apply(lambda r: kw in str(r.values).lower(), axis=1)]
# 更新公司下拉框
companies = ["全部公司"] + sorted(self.df_data["Company"].unique().tolist())
current = self.combo_company.currentText()
self.combo_company.blockSignals(True)
self.combo_company.clear()
self.combo_company.addItems(companies)
idx = self.combo_company.findText(current)
self.combo_company.setCurrentIndex(max(0, idx))
self.combo_company.blockSignals(False)
for c, c_grp in df.groupby("Company"):
company_node = QTreeWidgetItem(self.tree, [f"🏢 {c}"])
company_node.setForeground(0, QColor("#2c3e50"))
for p, p_grp in c_grp.groupby("Plant"):
plant_node = QTreeWidgetItem(company_node, [f"🏭 {p}"])
for pr, pr_grp in p_grp.groupby("Project Name"):
proj_node = QTreeWidgetItem(plant_node, [f"📂 {pr}", pr_grp.iloc[0]["Project Code"]])
for a, a_grp in pr_grp.groupby("Area"):
area_node = QTreeWidgetItem(proj_node, [f"📁 {a}"])
for idx2, row in a_grp.iterrows():
fp = row["Full Path"]
size_str, mtime_str, status = "N/A", "N/A", "Missing"
if os.path.exists(fp):
sz = os.path.getsize(fp)
size_str = f"{sz/1024:.1f} KB" if sz < 1024*1024 else f"{sz/1024/1024:.1f} MB"
mtime_str = datetime.fromtimestamp(os.path.getmtime(fp)).strftime('%Y-%m-%d %H:%M')
status = "Ready"
file_node = QTreeWidgetItem(area_node, [
f"📄 {row['File Name']}", "", status, fp,
row['File Name'], size_str, mtime_str])
file_node.setData(0, Qt.UserRole, idx2)
if status == "Missing":
file_node.setForeground(2, QColor("#e74c3c"))
else:
file_node.setForeground(2, QColor("#27ae60"))
if kw:
self.tree.expandAll()
def on_item_select(self):
item = self._selected_file_item()
if not item:
return
idx = item.data(0, Qt.UserRole)
row = self.df_data.loc[idx]
for k, e in self.entries.items():
e.setText(str(row.get(k, "")))
self.txt_root.setPlainText(str(row.get("System Root", "")))
self.load_preview(row["Full Path"])
def update_metadata_and_sync(self):
item = self._selected_file_item()
if not item:
return
idx = item.data(0, Qt.UserRole)
curr_dir = os.path.dirname(self.df_data.loc[idx, "Full Path"])
new_root = self.txt_root.toPlainText().strip()
new_values = {k: e.text() for k, e in self.entries.items()}
new_values["System Root"] = new_root
mask = ((self.df_data.index != idx) &
(self.df_data["Full Path"].apply(lambda x: os.path.dirname(x)) == curr_dir))
sync_indices = self.df_data[mask].index.tolist()
for col, value in new_values.items():
self.df_data.at[idx, col] = value
if col in self.df_data.columns and sync_indices:
self.df_data.loc[sync_indices, col] = value
self.refresh_tree()
if sync_indices:
QMessageBox.information(self, "同步成功", f"已更新同级 {len(sync_indices)} 个文件")
def open_folder(self):
item = self._selected_file_item()
if not item:
return
idx = item.data(0, Qt.UserRole)
fp = os.path.normpath(self.df_data.loc[idx, "Full Path"])
subprocess.run(['explorer', '/select,', fp])
def open_catia(self):
def get_catia_path():
reg_paths = [(r"SOFTWARE\Dassault Systemes\B32\0", "DEST_FOLDER_OSDS"),
(r"SOFTWARE\Dassault Systemes\B28\0", "DEST_FOLDER_OSDS")]
for root_key in [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]:
for rp, val in reg_paths:
try:
with winreg.OpenKey(root_key, rp) as key:
install_dir, _ = winreg.QueryValueEx(key, val)
for exe in [r"code\bin\CNEXT.exe", r"code\bin\CATSTART.exe"]:
p = os.path.join(install_dir, exe)
if os.path.exists(p):
return p
except:
pass
return None
catia_exe = get_catia_path()
if not catia_exe:
catia_exe, _ = QFileDialog.getOpenFileName(
self, "选择 CATIA 可执行文件",
r"C:\Program Files\Dassault Systemes",
"Executable (*.exe)")
if not catia_exe:
return
try:
subprocess.Popen([catia_exe], cwd=os.path.dirname(catia_exe))
QMessageBox.information(self, "成功", "CATIA 正在启动...")
except Exception as e:
QMessageBox.critical(self, "启动失败", f"无法启动 CATIA:\n{str(e)}")
def launch_pdps(self):
item = self._selected_file_item()
if not item:
return