-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDPSManagerApp.py
More file actions
3978 lines (3292 loc) · 159 KB
/
PDPSManagerApp.py
File metadata and controls
3978 lines (3292 loc) · 159 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 os
import tkinter as tk
import tkinter.font as tkfont
from tkinter import filedialog, messagebox, ttk
import pandas as pd
import zipfile
import winreg
import re
from PIL import Image, ImageTk
import ctypes
# --- 全局常量 ---
CONFIG_FILE = "pdps_master_config_v13.xlsx"
REG_PATH = r"Software\TECNOMATIX\TUNE\NewAssembler\Options\EMS"
# ==========================================
# 页面模块 1:项目管理 (核心路径解析功能)
# ==========================================
class ProjectManagerPage(tk.Frame):
def __init__(self, parent, root):
super().__init__(parent)
self.root = root # 保存根窗口引用
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_image = None
# 搜索与筛选变量
self.search_var = tk.StringVar()
self.filter_company_var = tk.StringVar(value="全部公司")
self.setup_ui()
self.setup_tree_context_menu() # 修复:调用右键菜单设置
self.load_local_config()
def setup_ui(self):
# --- 1. 顶部搜索与筛选栏 ---
filter_frame = tk.Frame(self, pady=8, padx=10, bg="#34495e")
filter_frame.pack(fill=tk.X)
tk.Label(filter_frame, text="🔍 搜索项目:", fg="white", bg="#34495e").pack(side=tk.LEFT, padx=5)
search_entry = tk.Entry(filter_frame, textvariable=self.search_var, width=30)
search_entry.pack(side=tk.LEFT, padx=5)
self.search_var.trace_add("write", lambda *args: self.refresh_tree())
tk.Label(filter_frame, text="🏢 公司筛选:", fg="white", bg="#34495e").pack(side=tk.LEFT, padx=(20, 5))
self.combo_company = ttk.Combobox(filter_frame, textvariable=self.filter_company_var, state="readonly",
width=15)
self.combo_company.pack(side=tk.LEFT)
self.combo_company.bind("<<ComboboxSelected>>", lambda e: self.refresh_tree())
tk.Button(filter_frame, text="💾 保存修改", command=self.save_config, bg="#f1c40f", fg="white", padx=10).pack(
side=tk.RIGHT, padx=5)
tk.Button(filter_frame, text="🔄 深度扫描", command=self.scan_files, bg="#27ae60", fg="white", padx=10).pack(
side=tk.RIGHT, padx=5)
tk.Button(filter_frame, text="+ 添加目录", command=self.add_search_folder, bg="#3498db", fg="white",
padx=10).pack(side=tk.RIGHT, padx=5)
tk.Button(filter_frame, text="打开Catia", command=self.open_catia, bg="#3498db", fg="white",
padx=10).pack(side=tk.RIGHT, padx=5)
# --- 2. 主体布局 (左侧树,右侧详情) ---
main_pane = tk.PanedWindow(self, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=4)
main_pane.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# 左侧列表
left_frame = tk.Frame(main_pane)
main_pane.add(left_frame, width=900)
self.tree = ttk.Treeview(
left_frame,
columns=("Code", "Status", "FilePath", "FileName", "FileSize", "Modified"),
show="tree headings",
height=25
)
# 设置各列标题
self.tree.heading("#0", text="组织架构", anchor="w")
self.tree.heading("Code", text="项目代号")
self.tree.heading("Status", text="状态")
self.tree.heading("FilePath", text="文件路径")
self.tree.heading("FileName", text="文件名")
self.tree.heading("FileSize", text="大小")
self.tree.heading("Modified", text="修改时间")
# 设置列宽度
self.tree.column("#0", width=300, minwidth=200, stretch=False)
self.tree.column("Code", width=80, minwidth=60, stretch=False)
self.tree.column("Status", width=60, minwidth=50, stretch=False)
self.tree.column("FilePath", width=200, minwidth=150, stretch=True)
self.tree.column("FileName", width=150, minwidth=100, stretch=False)
self.tree.column("FileSize", width=80, minwidth=60, stretch=False)
self.tree.column("Modified", width=120, minwidth=100, stretch=False)
scrollbar = ttk.Scrollbar(left_frame, orient=tk.VERTICAL, command=self.tree.yview)
self.tree.configure(yscroll=scrollbar.set)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.pack(fill=tk.BOTH, expand=True)
self.tree.bind("<<TreeviewSelect>>", self.on_item_select)
self.tree.bind("<Double-1>", lambda e: self.launch_pdps())
# 右侧面板
right_frame = tk.Frame(main_pane, bg="#ecf0f1", padx=15)
main_pane.add(right_frame)
# 预览图
tk.Label(right_frame, text="项目预览", font=("微软雅黑", 10, "bold"), bg="#ecf0f1").pack(anchor="w",
pady=(5, 2))
self.preview_container = tk.Frame(right_frame, width=250, height=220, bg="black")
self.preview_container.pack_propagate(False)
self.preview_container.pack(fill=tk.X, pady=5)
self.lbl_image = tk.Label(self.preview_container, bg="black")
self.lbl_image.pack(expand=True)
# 输入字段
self.entries = {}
fields = [("所属公司:", "Company"), ("所在厂房:", "Plant"), ("所属区域:", "Area"),
("项目名称:", "Project Name"), ("项目代号:", "Project Code")]
for label, key in fields:
tk.Label(right_frame, text=label, bg="#ecf0f1").pack(anchor="w", pady=(3, 0))
e = tk.Entry(right_frame)
e.pack(fill=tk.X, ipady=2)
self.entries[key] = e
tk.Label(right_frame, text="System Root (修改将同步同级文件):", bg="#ecf0f1", font=("", 9, "bold"),
fg="#e67e22").pack(anchor="w", pady=(8, 0))
self.txt_root = tk.Text(right_frame, height=5, wrap=tk.WORD, font=("Consolas", 9))
self.txt_root.pack(fill=tk.X)
tk.Button(right_frame, text="🔥 确认修改并同步", command=self.update_metadata_and_sync, bg="#34495e", fg="white",
height=1).pack(fill=tk.X, pady=15)
tk.Button(right_frame, text="📂 定位文件位置", command=self.open_folder, bg="#bdc3c7", height=1).pack(fill=tk.X,
pady=2)
tk.Button(right_frame, text="🚀 启动项目", command=self.launch_pdps, bg="#27ae60", fg="white",
font=("", 12, "bold"), height=2).pack(fill=tk.X, side=tk.BOTTOM, pady=10)
# 修复:添加状态栏
self.status_label = tk.Label(right_frame, text="就绪", bg="#ecf0f1", anchor="w",
font=("微软雅黑", 8), fg="#7f8c8d")
self.status_label.pack(fill=tk.X, pady=(10, 0))
def setup_tree_context_menu(self):
"""设置树形控件的右键菜单"""
self.tree_menu = tk.Menu(self.root, tearoff=0)
self.tree_menu.add_command(label="复制完整路径", command=self.copy_full_path)
self.tree_menu.add_command(label="打开所在文件夹", command=self.open_file_location)
self.tree_menu.add_separator()
self.tree_menu.add_command(label="查看文件属性", command=self.show_file_properties)
# 绑定右键事件
self.tree.bind("<Button-3>", self.show_tree_context_menu)
def show_tree_context_menu(self, event):
"""显示右键菜单"""
item = self.tree.identify_row(event.y)
if item and item.isdigit(): # 只对文件项显示菜单
self.tree.selection_set(item)
self.tree_menu.post(event.x_root, event.y_root)
def copy_full_path(self):
"""复制完整路径到剪贴板"""
sel = self.tree.selection()
if sel and sel[0].isdigit():
idx = int(sel[0])
full_path = self.df_data.loc[idx, "Full Path"] # 修复:从数据源获取
if full_path:
self.root.clipboard_clear()
self.root.clipboard_append(full_path)
self.status_label.config(text=f"已复制: {full_path}")
def open_file_location(self):
"""打开文件所在位置"""
self.open_folder()
def show_file_properties(self):
"""显示文件属性"""
sel = self.tree.selection()
if sel and sel[0].isdigit():
idx = int(sel[0])
row = self.df_data.loc[idx]
full_path = row["Full Path"]
if os.path.exists(full_path):
file_size = os.path.getsize(full_path)
file_time = os.path.getmtime(full_path)
from datetime import datetime
info = f"""文件属性:
路径: {full_path}
大小: {file_size / 1024:.2f} KB
修改时间: {datetime.fromtimestamp(file_time).strftime('%Y-%m-%d %H:%M:%S')}
公司: {row['Company']}
厂房: {row['Plant']}
项目: {row['Project Name']}
代号: {row['Project Code']}"""
messagebox.showinfo("文件属性", info)
else:
messagebox.showwarning("警告", "文件不存在")
# --- 核心逻辑方法 ---
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": ""}
# 1. 基于 Library 的区域识别
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):
info["System Root"] = os.path.normpath(
os.path.join(psz_dir, next(f for f in subfolders if "library" in f.lower())))
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 Exception as e:
pass
# 2. 项目与公司深度识别
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]
# 使用递归匹配所有括号,找到最外层匹配的括号对
def find_last_bracket_pair(text):
stack = []
bracket_pairs = {'(': ')', '(': ')'}
# 从后向前遍历
for i in range(len(text) - 1, -1, -1):
char = text[i]
if char in [')', ')']:
stack.append((char, i))
elif char in ['(', '(']:
if stack and ((char == '(' and stack[-1][0] == ')') or
(char == '(' and stack[-1][0] == ')')):
end_pos = stack[-1][1]
return i, end_pos, char
else:
stack = []
return None
bracket_info = find_last_bracket_pair(part)
if bracket_info:
start_idx, end_idx, bracket_type = bracket_info
info["Project Code"] = part[start_idx + 1:end_idx].strip()
info["Project Name"] = part[:start_idx].strip()
else:
info["Project Name"], info["Project Code"] = 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, target_id=None):
expanded = []
for item in self.tree.get_children(''): self._get_expanded(item, expanded)
# 筛选逻辑
df = self.df_data.copy()
if self.filter_company_var.get() != "全部公司":
df = df[df["Company"] == self.filter_company_var.get()]
kw = self.search_var.get().strip().lower()
if kw:
df = df[df.apply(lambda r: kw in str(r.values).lower(), axis=1)]
self.combo_company['values'] = ["全部公司"] + sorted(list(self.df_data["Company"].unique()))
for item in self.tree.get_children(): self.tree.delete(item)
is_searching = bool(kw)
from datetime import datetime
for c, c_grp in df.groupby("Company"):
company_node = self.tree.insert("", "end", iid=f"c_{c}", text=f"🏢 {c}", open=is_searching)
for p, p_grp in c_grp.groupby("Plant"):
plant_node = self.tree.insert(company_node, "end", iid=f"p_{c}_{p}", text=f"🏭 {p}", open=is_searching)
for pr, pr_grp in p_grp.groupby("Project Name"):
project_node = self.tree.insert(plant_node, "end", iid=f"pr_{c}_{p}_{pr}", text=f"📂 {pr}",
values=(pr_grp.iloc[0]["Project Code"], ""), open=is_searching)
for a, a_grp in pr_grp.groupby("Area"):
area_node = self.tree.insert(project_node, "end", iid=f"a_{c}_{p}_{pr}_{a}", text=f"📁 {a}",
open=is_searching)
for idx, row in a_grp.iterrows():
# 获取文件信息
full_path = row['Full Path']
file_size = ""
modified_time = ""
status = "Ready"
try:
if os.path.exists(full_path):
# 获取文件大小(转换为 KB/MB)
size_bytes = os.path.getsize(full_path)
if size_bytes < 1024:
file_size = f"{size_bytes} B"
elif size_bytes < 1024 * 1024:
file_size = f"{size_bytes / 1024:.1f} KB"
else:
file_size = f"{size_bytes / (1024 * 1024):.1f} MB"
# 获取修改时间
mtime = os.path.getmtime(full_path)
modified_time = datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M')
else:
status = "Missing"
file_size = "N/A"
modified_time = "N/A"
except Exception as e:
status = "Error"
file_size = "N/A"
modified_time = "N/A"
self.tree.insert(area_node, "end", iid=str(idx), text=f"📄 {row['File Name']}",
values=("", status, full_path, row['File Name'], file_size, modified_time))
if not is_searching:
for node_id in expanded:
if self.tree.exists(node_id): self.tree.item(node_id, open=True)
if target_id and self.tree.exists(target_id):
self._expand_to(target_id)
self.tree.selection_set(target_id)
self.tree.see(target_id)
def _get_expanded(self, item, res):
if self.tree.item(item, 'open'): res.append(item)
for c in self.tree.get_children(item): self._get_expanded(c, res)
def _expand_to(self, item):
parent = self.tree.parent(item)
if parent:
self.tree.item(parent, open=True)
self._expand_to(parent)
def update_metadata_and_sync(self):
sel = self.tree.selection()
if not sel or not sel[0].isdigit():
return
idx = int(sel[0])
# 预计算当前目录
current_row = self.df_data.iloc[idx]
curr_dir = os.path.dirname(current_row["Full Path"])
new_root = self.txt_root.get("1.0", tk.END).strip()
# 获取新值
new_values = {k: self.entries[k].get() for k in self.entries}
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 len(sync_indices) > 0:
self.df_data.loc[sync_indices, col] = value
# 刷新显示
self.refresh_tree(target_id=str(idx))
if len(sync_indices) > 0:
messagebox.showinfo("同步成功", f"已更新同级 {len(sync_indices)} 个文件")
def on_item_select(self, event):
sel = self.tree.selection()
if not sel or not sel[0].isdigit(): return
row = self.df_data.loc[int(sel[0])]
for k in self.entries:
self.entries[k].delete(0, tk.END)
self.entries[k].insert(0, str(row[k]))
self.txt_root.delete("1.0", tk.END)
self.txt_root.insert("1.0", str(row["System Root"]))
self.load_preview(row["Full Path"])
def open_folder(self):
sel = self.tree.selection()
if not sel or not sel[0].isdigit(): return
import subprocess
subprocess.run(['explorer', '/select,', os.path.normpath(self.df_data.loc[int(sel[0]), "Full Path"])])
def open_catia(self):
"""打开 CATIA 软件(从注册表获取安装路径)"""
import subprocess
import sys
def get_catia_path_from_registry():
"""从注册表获取 CATIA 安装路径"""
catia_path = None
if sys.platform == 'win32':
try:
# 尝试多个可能的注册表路径
reg_paths = [
(r"SOFTWARE\Dassault Systemes\B32\0", "DEST_FOLDER_OSDS"),
(r"SOFTWARE\Dassault Systemes\B31\0", "DEST_FOLDER_OSDS"),
(r"SOFTWARE\Dassault Systemes\B30\0", "DEST_FOLDER_OSDS"),
(r"SOFTWARE\Dassault Systemes\B29\0", "DEST_FOLDER_OSDS"),
(r"SOFTWARE\Dassault Systemes\B28\0", "DEST_FOLDER_OSDS"),
(r"SOFTWARE\Dassault Systemes\B27\0", "DEST_FOLDER_OSDS"),
(r"SOFTWARE\Wow6432Node\Dassault Systemes\B32\0", "DEST_FOLDER_OSDS"),
(r"SOFTWARE\Wow6432Node\Dassault Systemes\B28\0", "DEST_FOLDER_OSDS"),
]
root_keys = [
(winreg.HKEY_LOCAL_MACHINE, "HKLM"),
(winreg.HKEY_CURRENT_USER, "HKCU"),
]
for root_key, root_name in root_keys:
for reg_path, value_name in reg_paths:
try:
with winreg.OpenKey(root_key, reg_path) as key:
install_dir, reg_type = winreg.QueryValueEx(key, value_name)
possible_executables = [
os.path.join(install_dir, r"code\bin\CNEXT.exe"),
os.path.join(install_dir, r"code\bin\CATSTART.exe"),
os.path.join(install_dir, r"code\bin\CATIA.exe"),
]
for exe_path in possible_executables:
if os.path.exists(exe_path):
return exe_path
except WindowsError:
continue
except Exception as e:
print(f"读取注册表时出错: {e}")
return catia_path
catia_exe = get_catia_path_from_registry()
if not catia_exe:
default_paths = [
r"C:\Program Files\Dassault Systemes\B32\win_b64\code\bin\CNEXT.exe",
r"C:\Program Files\Dassault Systemes\B28\win_b64\code\bin\CNEXT.exe",
r"C:\Program Files\Dassault Systemes\B32\win_b64\code\bin\CATSTART.exe",
r"C:\Program Files\Dassault Systemes\B28\win_b64\code\bin\CATSTART.exe",
]
for path in default_paths:
if os.path.exists(path):
catia_exe = path
break
if not catia_exe:
catia_exe = filedialog.askopenfilename(
title="请选择 CATIA 可执行文件",
initialdir=r"C:\Program Files\Dassault Systemes",
filetypes=[("Executable files", "*.exe"), ("All files", "*.*")]
)
if not catia_exe:
return
try:
if catia_exe.endswith("CATSTART.exe"):
if "B32" in catia_exe.upper():
env = "CATIA_P3.V5-6R2023.B32"
elif "B28" in catia_exe.upper():
env = "CATIA_P3.V5R28.B28"
else:
env = "CATIA_P3"
cmd = [catia_exe, "-env", env]
else:
cmd = [catia_exe]
subprocess.Popen(cmd, shell=False, cwd=os.path.dirname(catia_exe))
version_info = "CATIA"
if "B32" in catia_exe.upper():
version_info = "CATIA V5-6R2023 (B32)"
elif "B28" in catia_exe.upper():
version_info = "CATIA V5R28 (2022)"
messagebox.showinfo("成功", f"{version_info} 正在启动...")
except Exception as e:
messagebox.showerror("启动失败", f"无法启动 CATIA:\n{str(e)}")
def launch_pdps(self):
sel = self.tree.selection()
if not sel or not sel[0].isdigit(): return
row = self.df_data.loc[int(sel[0])]
if str(row["System Root"]).strip():
try:
key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH)
winreg.SetValueEx(key, "System Root Path", 0, winreg.REG_SZ, row["System Root"])
winreg.CloseKey(key)
except Exception as e:
print(f"注册表写入失败: {e}")
if os.path.exists(row["Full Path"]):
os.startfile(row["Full Path"])
else:
messagebox.showerror("错误", "文件不存在")
def scan_files(self):
if not self.search_paths: return
existing = {row["Full Path"]: row.to_dict() for _, row in self.df_data.iterrows()}
new_list = []
for bp in self.search_paths:
for root, _, files in os.walk(bp):
for f in files:
if f.lower().endswith(".psz"):
path = os.path.normpath(os.path.join(root, f))
if path in existing:
new_list.append(existing[path])
else:
rec = {"File Name": f, "Full Path": path}
rec.update(self.auto_extract_info(path))
new_list.append(rec)
self.df_data = pd.DataFrame(new_list).drop_duplicates(subset=["Full Path"])
self.refresh_tree()
def load_preview(self, path):
try:
with zipfile.ZipFile(path, 'r') as z:
if "Preview Images/previmg.jpg" in z.namelist():
with z.open("Preview Images/previmg.jpg") as f:
img = Image.open(f).copy()
tw, th = 350, 220
rw, rh = img.size
ratio = min(tw / rw, th / rh)
self.current_preview_image = ImageTk.PhotoImage(
img.resize((int(rw * ratio), int(rh * ratio)), Image.Resampling.LANCZOS))
self.lbl_image.config(image=self.current_preview_image, text="")
return
except Exception as e:
print(f"预览图加载失败: {e}")
self.lbl_image.config(image='', text="无预览图", fg="white")
def add_search_folder(self):
d = filedialog.askdirectory()
if d:
self.search_paths.append(d)
self.scan_files()
def save_config(self):
self.df_data.to_excel(CONFIG_FILE, index=False)
with open("paths_config.ini", "w") as f: f.write(",".join(self.search_paths))
messagebox.showinfo("保存", "本地数据库已更新")
def load_local_config(self):
if os.path.exists(CONFIG_FILE):
self.df_data = pd.read_excel(CONFIG_FILE).fillna("")
self.refresh_tree()
if os.path.exists("paths_config.ini"):
with open("paths_config.ini", "r") as f:
self.search_paths = f.read().split(",")
# ==========================================
# 页面模块 2:CATIA 工具箱(核心修复版)
# ==========================================
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import pandas as pd
# 尝试导入 pycatia
try:
from pycatia import catia
from pycatia.in_interfaces.application import Application
from pycatia.product_structure_interfaces.product import Product
from pycatia.mec_mod_interfaces.part_document import PartDocument
from pycatia.mec_mod_interfaces.part import Part
from pycatia.knowledge_interfaces.parameter import Parameter
PYCATIA_AVAILABLE = True
except ImportError:
PYCATIA_AVAILABLE = False
print("⚠️ pycatia 未安装,请运行: pip install pycatia")
# ==================== 核心业务逻辑类(使用 pycatia) ====================
import traceback
from typing import List, Dict, Tuple, Optional
# -*- coding: utf-8 -*-
import threading
import queue
import traceback
from typing import List, Dict, Optional, Tuple
import tkinter as tk
from tkinter import messagebox, ttk, simpledialog
import pandas as pd
# 如果你在模块顶部有 PYCATIA_AVAILABLE 标志,请保留
try:
from pycatia import catia as pycatia_catia
PYCATIA_AVAILABLE = True
except Exception:
PYCATIA_AVAILABLE = False
# ---------------------------
# CATIAWeldPointExtractor
# ---------------------------
import threading
import queue
import traceback
from typing import List, Dict, Optional, Tuple
import tkinter as tk
from tkinter import messagebox, ttk, simpledialog, filedialog
import pandas as pd
# pycatia 可选支持检测
try:
from pycatia import catia as pycatia_catia
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 # 'win32com' 或 'pycatia'
def connect_catia(self, use_pycatia=False) -> bool:
"""连接 CATIA 应用(可选 pycatia 或 win32com)"""
try:
if use_pycatia:
if not PYCATIA_AVAILABLE:
print("pycatia 未安装")
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.log_error("连接 CATIA", e)
self.status_message = "连接 CATIA 失败"
return False
def set_catia_app(self, catia_app, connection_type='win32com'):
"""设置 CATIA 应用实例和连接类型"""
self.catia_app = catia_app
self.connection_type = connection_type
self.status_message = f"CATIA 应用已设置 ({connection_type})"
def _generate_standard_name(self, original_name: str, part_name: str) -> str:
"""
根据标准生成新名称: {前缀}_{零件中段}_{焊点中段}
零件: DPUB-501037085-XWS_00 -> 501037085
焊点: EHX-0000028059-RSW-GSMPoint.66 -> 前缀: EHX, 数字: 28059
"""
try:
# 1. 从原始名称中提取前缀(第一个'-'之前的部分)
# 例如:EHX-0000028059-RSW-GSMPoint.66 -> 前缀: EHX
original_segments = original_name.split('-')
if len(original_segments) > 0:
prefix = original_segments[0] # 提取前缀
else:
prefix = "UnknownPrefix"
print(f"警告: 无法从原始名称 '{original_name}' 中提取前缀")
# 2. 提取零件名称中的数字部分
part_segments = part_name.split('-')
if len(part_segments) > 1:
part_id = part_segments[1] # 假设格式为 XXX-数字-XXX
else:
part_id = "UnknownPart"
print(f"警告: 无法从零件名称 '{part_name}' 中提取零件ID")
# 3. 提取焊点名称中的数字部分(去掉前导零)
if len(original_segments) > 1:
weld_id_raw = original_segments[1]
# 去掉前导零,但如果全部是零则保留一个零
weld_id = weld_id_raw.lstrip('0')
if not weld_id: # 如果去掉前导零后为空字符串
weld_id = "0"
else:
weld_id = "UnknownWeld"
print(f"警告: 无法从原始名称 '{original_name}' 中提取焊点ID")
# 返回格式: {前缀}_{零件数字部分}_{焊点数字部分}
return f"{prefix}_{part_id}_{weld_id}"
except Exception as e:
print(f"重命名失败 ({original_name}): {e}")
return original_name # 失败则返回原名
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:
self.status_message = "没有活动的 CATIA 文档"
return []
if not hasattr(doc, 'part'):
self.status_message = "当前文档不是 Part 文档 (.CATPart)"
return []
part = doc.part
selection = doc.selection
part_full_name = doc.name
else: # win32com
doc = self.catia_app.ActiveDocument
if not doc:
self.status_message = "没有活动的 CATIA 文档"
return []
is_part = False
try:
part = doc.Part
is_part = True
except:
pass
if not is_part:
self.status_message = "当前文档不是 Part 文档 (.CATPart)"
return []
selection = doc.Selection
part_full_name = doc.Name
# 准备 SPAWorkbench(可选)
spa_workbench = None
if self.connection_type == 'pycatia':
try:
spa_workbench = doc.spa_workbench()
except:
print("⚠️ 无法加载 SPAWorkbench (pycatia)")
else:
try:
spa_workbench = doc.GetWorkbench("SPAWorkbench")
except:
print("⚠️ 无法加载 SPAWorkbench (win32com)")
# 搜索所有点
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
successful_count = 0
failed_count = 0
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}")
coords = self._get_point_coordinates(point_obj, part, spa_workbench)
if coords:
# --- 执行重命名逻辑 ---
display_name = name
if auto_rename:
display_name = self._generate_standard_name(name, part_full_name)
x, y, z = coords
p_type = "焊点" if ("Weld" in name or "Spot" in name) else "普通点"
class_val = "PmWeldPoint"
ext_id = name
location_str = f"{x:.3f},{y:.3f},{z:.3f}"
x_str = f"{x:.3f}"
y_str = f"{y:.3f}"
z_str = f"{z:.3f}"
type_str = p_type
self.weld_points_data.append({
"Class": class_val,
"ExternalId": ext_id,
"Name": display_name,
"Location": location_str,
"X": x_str,
"Y": y_str,
"Z": z_str,
"Type": type_str
})
successful_count += 1
else:
print(f"❌ 无法提取点 '{name}' 的坐标")
failed_count += 1
except Exception as e:
print(f"处理点 {i} 失败: {e}")
failed_count += 1
continue
msg = f"提取完成: 成功 {successful_count} 个"
if failed_count > 0:
msg += f",失败 {failed_count} 个"
self.status_message = msg
# 清理选择
if self.connection_type == 'pycatia':
selection.clear()
else:
selection.Clear()
except Exception as e:
self.log_error("提取焊点", e)
self.status_message = f"发生意外错误: {str(e)}"
return self.weld_points_data
def _get_point_coordinates(self, point_obj, part, spa_workbench=None) -> Optional[Tuple[float, float, float]]:
"""获取坐标的核心逻辑(兼容两种连接方式)"""
# 尝试 SPAWorkbench
if spa_workbench and part:
try:
if self.connection_type == 'pycatia':
reference = part.create_reference_from_object(point_obj)
measurable = spa_workbench.get_measurable(reference)
coords = measurable.get_point()
else:
reference = part.CreateReferenceFromObject(point_obj)
measurable = spa_workbench.GetMeasurable(reference)
coords = measurable.GetPoint()
if coords and len(coords) == 3:
return coords[0], coords[1], coords[2]
except:
pass
# 尝试直接属性
try:
if hasattr(point_obj, 'X') and hasattr(point_obj, 'Y') and hasattr(point_obj, 'Z'):
if self.connection_type == 'pycatia':
val_x = point_obj.x if hasattr(point_obj, 'x') else point_obj.X
val_y = point_obj.y if hasattr(point_obj, 'y') else point_obj.Y
val_z = point_obj.z if hasattr(point_obj, 'z') else point_obj.Z
else:
val_x = point_obj.X.Value if hasattr(point_obj.X, 'Value') else float(point_obj.X)
val_y = point_obj.Y.Value if hasattr(point_obj.Y, 'Value') else float(point_obj.Y)
val_z = point_obj.Z.Value if hasattr(point_obj.Z, 'Value') else float(point_obj.Z)
return float(val_x), float(val_y), float(val_z)
except:
pass
# 尝试 GetCoordinates
try:
if self.connection_type == 'pycatia':
if hasattr(point_obj, 'get_coordinates'):
coords = point_obj.get_coordinates()
if coords and len(coords) == 3:
return coords[0], coords[1], coords[2]
else:
coords_ret = point_obj.GetCoordinates()
if coords_ret and len(coords_ret) == 3:
return coords_ret[0], coords_ret[1], coords_ret[2]
coords_buf = [0.0, 0.0, 0.0]
point_obj.GetCoordinates(coords_buf)
if coords_buf != [0.0, 0.0, 0.0]:
return coords_buf[0], coords_buf[1], coords_buf[2]
except:
pass
return None
def get_data(self) -> List[Dict]:
"""获取已提取的焊点数据"""
return self.weld_points_data
def get_status(self) -> str:
"""获取当前状态信息"""
return self.status_message
def clear_data(self):
"""清空已提取的数据"""
self.weld_points_data = []
self.status_message = "数据已清空"
def get_document_names(self) -> Dict[str, str]:
"""
获取当前活动文档的名称信息
Returns:
Dict: 包含以下键的字典:
- 'document_name': 文档名称(包括后缀)
- 'document_name_no_ext': 文档名称(不包括后缀)
- 'part_name': Part 名称(仅 CATPart 文件)
- 'product_name': Product 名称(仅 CATProduct 文件)
- 'document_type': 文档类型('CATPart' 或 'CATProduct')
- 'full_path': 文档完整路径
"""
self.document_info = {}
if not self.catia_app:
self.status_message = "请先连接 CATIA"
return self.document_info
try:
if self.connection_type == 'pycatia':
doc = self.catia_app.active_document()
if not doc:
self.status_message = "没有活动的 CATIA 文档"
return self.document_info
# 获取文档名称和路径
doc_name = doc.name
doc_full_path = doc.full_name
else: # win32com
doc = self.catia_app.ActiveDocument
if not doc:
self.status_message = "没有活动的 CATIA 文档"
return self.document_info
doc_name = doc.Name
doc_full_path = doc.FullName
# 提取文件名和扩展名
import os
doc_name_no_ext = os.path.splitext(doc_name)[0]
_, doc_ext = os.path.splitext(doc_name)
# 判断文档类型并获取相应的名称
document_type = self._determine_document_type(doc)
self.document_info = {
'document_name': doc_name,
'document_name_no_ext': doc_name_no_ext,
'part_name': None,
'product_name': None,
'document_type': document_type,
'full_path': doc_full_path
}
# 根据文档类型获取名称
if document_type == 'CATPart':
part_name = self._get_part_name(doc)
self.document_info['part_name'] = part_name
elif document_type == 'CATProduct':
product_name = self._get_product_name(doc)
self.document_info['product_name'] = product_name
self.status_message = f"文档信息已获取: {doc_name}"
return self.document_info
except Exception as e:
self.log_error("获取文档名称", e)
return self.document_info
def _determine_document_type(self, doc) -> str:
"""
判断当前文档的类型
Returns:
str: 'CATPart', 'CATProduct' 或 'Unknown'
"""
try:
if self.connection_type == 'pycatia':
# pycatia 中,有 part 属性的是 CATPart,有 product 属性的是 CATProduct
if hasattr(doc, 'part') and doc.part() is not None:
return 'CATPart'
elif hasattr(doc, 'product') and doc.product() is not None: