' Current-sheet automatic DxDesigner 7.9.5 replacement helper. ASCII-only. Option Explicit Const VDM_COMP = 128 Const VDM_COMPPIN = 4096 Const VD_ALL = 0 Const QP_COMPONENT_COORDINATE_TOLERANCE = 10 Const QP_ATTRIBUTE_COORDINATE_TOLERANCE = 10 Dim QP_Fso Dim QP_Root Dim QP_RootTemplate Dim QP_CurrentJobId Dim QP_App Dim QP_ExitCode Dim QP_HelperExecutable Dim QP_HelperScript Dim QP_NativeMutationPossible Dim QP_ExpectedJobId Dim QP_Stage Dim QP_ErrorMessage Dim QP_AttemptToken Dim QP_ProgressSequence Dim QP_RestoreTransactionOpen Dim QP_PinIndex Dim QP_PinContext Dim QP_ComponentUidIndex, QP_ComponentRefdesIndex, QP_ComponentLocationIndex Dim QP_ComponentIndexContext Dim QP_NativeCallActive Dim QP_BatchMode, QP_OwnedProject, QP_BatchState, QP_BatchCode, QP_BatchMessage Dim QP_BatchSaveCommitted, QP_BatchSaveRequested Dim QP_DiscoveryMode, QP_TargetSchematic, QP_TargetSheet Dim QP_FailureNumber, QP_FailureSource, QP_FailureDescription Dim QP_NcSyncSummary Dim QP_SessionMode, QP_SessionToken, QP_SessionProject, QP_MonitorJobId Dim QP_OwnedProjectPath, QP_SessionWaiting, QP_SessionExternalChange Dim QP_CheckpointSchematic, QP_CheckpointSheet Dim QP_ProjectAccess, QP_AccessProject Dim FailureState, CloseError Set QP_Fso = CreateObject("Scripting.FileSystemObject") QP_RootTemplate = "%LOCALAPPDATA%\DxProductivity\trial-task-center\quick-run" If WScript.Arguments.Count > 0 Then QP_Root = CStr(WScript.Arguments(0)) Else QP_Root = CreateObject("WScript.Shell").ExpandEnvironmentStrings(QP_RootTemplate) End If QP_HelperExecutable = "" QP_HelperScript = "" QP_NativeMutationPossible = False If WScript.Arguments.Count > 1 Then QP_HelperExecutable = CStr(WScript.Arguments(1)) If WScript.Arguments.Count > 2 Then QP_HelperScript = CStr(WScript.Arguments(2)) QP_ExpectedJobId = "" If WScript.Arguments.Count > 3 Then QP_ExpectedJobId = CStr(WScript.Arguments(3)) QP_AttemptToken = "" If WScript.Arguments.Count > 4 Then QP_AttemptToken = CStr(WScript.Arguments(4)) QP_ProgressSequence = 0 QP_RestoreTransactionOpen = False QP_NativeCallActive = False QP_BatchMode = False QP_OwnedProject = False QP_BatchState = "" QP_BatchSaveCommitted = False QP_BatchSaveRequested = False QP_DiscoveryMode = False QP_TargetSchematic = "" QP_TargetSheet = "" Set QP_PinIndex = Nothing Set QP_ComponentUidIndex = Nothing Set QP_ComponentRefdesIndex = Nothing Set QP_ComponentLocationIndex = Nothing QP_ComponentIndexContext = "" QP_CurrentJobId = "" QP_ExitCode = 0 QP_Stage = "session_startup" QP_SessionMode = False QP_OwnedProjectPath = "" QP_SessionWaiting = False QP_SessionExternalChange = False QP_MonitorJobId = QP_ExpectedJobId Set QP_App = Nothing On Error Resume Next QPBootstrapSession If Err.Number <> 0 Or QP_App Is Nothing Then QP_FailureNumber = Err.Number QP_FailureSource = Err.Source QP_FailureDescription = Err.Description QP_ErrorMessage = "stage=" & QP_Stage & " " & CStr(QP_FailureSource) & ": " & CStr(QP_FailureDescription) If QP_DiscoveryMode Then QPCleanupDiscoveryFailure QPFail QP_Root, "hard_failure", QP_FailureNumber, QP_FailureSource, QP_FailureDescription WScript.StdErr.WriteLine QP_ErrorMessage Err.Clear QP_ExitCode = 2 Else Err.Clear If QP_DiscoveryMode Then QPDiscoverSheets Else Do QPMain If Err.Number <> 0 Then Exit Do If QP_BatchMode Then QPFinishBatchItem If Err.Number <> 0 Or Not QP_SessionMode Then Exit Do QPSessionNext If Err.Number <> 0 Or Not QP_SessionMode Then Exit Do Loop End If If Err.Number <> 0 Then QP_FailureNumber = Err.Number QP_FailureSource = Err.Source QP_FailureDescription = Err.Description If QP_DiscoveryMode Then QPCleanupDiscoveryFailure FailureState = "hard_failure" If QP_BatchSaveRequested Then FailureState = "batch_saved_unverified" QP_FailureDescription = "save was requested; persisted outcome requires reconciliation. " & QP_FailureDescription End If CloseError = "" If QP_BatchMode Or QP_SessionMode Then QPDiscardFailedBatchProject CloseError If Len(CloseError) = 0 Then If QP_BatchSaveCommitted Then FailureState = "batch_saved_unverified" QP_FailureDescription = "project was saved before readback verification failed; the project was closed without additional saving. " & QP_FailureDescription Else FailureState = "batch_failed" QP_FailureDescription = "failed project was closed without saving; native rollback was not executed. " & QP_FailureDescription End If Else QP_FailureDescription = QP_FailureDescription & "; failed project close was not verified: " & CloseError End If End If WScript.StdErr.WriteLine "stage=" & QP_Stage & " " & CStr(QP_FailureSource) & ": " & CStr(QP_FailureDescription) QPFail QP_Root, FailureState, QP_FailureNumber, QP_FailureSource, QP_FailureDescription If Len(CStr(QP_CurrentJobId)) = 0 Then QP_ExitCode = 3 Else QP_ExitCode = 1 End If End If End If On Error GoTo 0 Set QP_App = Nothing WScript.Quit QP_ExitCode Sub QPMain() Dim Command Dim SnapshotPath Dim State If Not QP_Fso.FolderExists(QP_Root) Then Err.Raise vbObjectError + 795, "QuickPartReplace", _ "quick-run directory does not exist" End If Set Command = QPReadCommand(QP_Fso.BuildPath(QP_Root, "command.tsv")) QP_CurrentJobId = CStr(Command("job_id")) QPRequireProject Command SnapshotPath = QPJobSnapshotPath(CStr(Command("job_id"))) State = QPReadState(QP_Fso.BuildPath(QP_Root, "status.tsv"), _ CStr(Command("job_id"))) If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then If Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "recovery.request"))) <> QP_CurrentJobId Then _ Err.Raise vbObjectError + 864, "QuickPartReplace.Recovery", "recovery job mismatch" If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) > 0 Then QP_BatchMode = True QPRecoverSavedJob Command, SnapshotPath If QP_BatchMode Then If QP_BatchState = "restored_ok" Then QPFinishBatchItem Else QP_BatchMode = False End If End If QPProgress "finished", 1, 1 Exit Sub End If If Not QP_Fso.FileExists(SnapshotPath) Then QPCaptureAndSelect Command, SnapshotPath If QPReadState(QP_Fso.BuildPath(QP_Root, "status.tsv"), QP_CurrentJobId) = "no_match" Then Exit Sub QPAutomaticReplaceAndRestore Command, SnapshotPath ElseIf State = "awaiting_native_replace" Then QPAutomaticReplaceAndRestore Command, SnapshotPath Else Err.Raise vbObjectError + 796, "QuickPartReplace", _ "snapshot exists but state does not allow continuation" End If QPProgress "finished", 1, 1 End Sub Sub QPBootstrapSession() Dim TargetPath QPWaitForMonitor If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "batch.request")) Then If Len(CStr(QP_ExpectedJobId)) = 0 Or Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "batch.request"))) <> QP_ExpectedJobId Then _ Err.Raise vbObjectError + 870, "QuickPartReplace.Batch", "batch authorization does not match this job" QP_BatchMode = True End If If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "sheet-discovery.request")) Then If Not QP_BatchMode Or Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "sheet-discovery.request"))) <> QP_ExpectedJobId Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "sheet discovery authorization does not match this job" QP_DiscoveryMode = True End If QPReadSessionRequest QPProgress "session_startup", 0, 0 TargetPath = QPConfirmedProjectPath() If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) = 0 And QPDesignerProcessCount() <> 0 Then _ Err.Raise vbObjectError + 864, "QuickPartReplace.Recovery", _ "recovery requires a fresh CAD session; close existing DxDesigner first without discarding wanted edits" If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) > 0 Then QP_BatchMode = True End If If Len(TargetPath) = 0 Then Set QP_App = QPAttachOrStart(QPDesignerProcessCount()) Else Set QP_App = QPAttachOrStart(QPDesignerProcessCount()) If QP_SessionMode Then WScript.ConnectObject QP_App, "QPEvent_" QPEnsureProject QP_App, TargetPath End If QP_Stage = "session_ready" QPLog QP_Root, "INFO", "stage=session_ready" QPProgress "session_ready", 1, 1 End Sub Sub QPCleanupDiscoveryFailure() On Error Resume Next If QP_OwnedProject And Not QP_App Is Nothing Then If QPCanonicalPath(QPProjectPath()) = QPCanonicalPath(QP_OwnedProjectPath) Then QP_App.CloseProject End If QP_OwnedProject = False Err.Clear On Error GoTo 0 End Sub Sub QPWaitForMonitor() Dim Index, Character, ReadyPath, Attempt If Len(CStr(QP_AttemptToken)) = 0 Then Exit Sub If Len(CStr(QP_AttemptToken)) <> 32 Then _ Err.Raise vbObjectError + 861, "QuickPartReplace.Monitor", "invalid monitor token" For Index = 1 To 32 Character = Mid(CStr(QP_AttemptToken), Index, 1) If InStr(1, "0123456789abcdef", Character, vbBinaryCompare) = 0 Then _ Err.Raise vbObjectError + 861, "QuickPartReplace.Monitor", "invalid monitor token" Next ReadyPath = QP_Fso.BuildPath(QP_Root, "monitor-" & QP_AttemptToken & ".ready") For Attempt = 1 To 200 If QP_Fso.FileExists(ReadyPath) Then If Trim(QPReadUtf8(ReadyPath)) = CStr(QP_AttemptToken) Then Exit Sub End If WScript.Sleep 100 Next Err.Raise vbObjectError + 861, "QuickPartReplace.Monitor", "supervisor did not authorize startup" End Sub Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total) Dim Safe, StopPath, Job, Suffix If Len(CStr(QP_AttemptToken)) = 0 Then Exit Sub Safe = 0 If Not CBool(QP_NativeMutationPossible) And Not CBool(QP_RestoreTransactionOpen) And _ Not CBool(QP_NativeCallActive) Then Safe = 1 QP_ProgressSequence = CLng(QP_ProgressSequence) + 1 Job = QP_ExpectedJobId Suffix = "" If QP_SessionMode Then Job = QP_MonitorJobId Suffix = vbTab & QP_ExpectedJobId End If WScript.StdOut.WriteLine "DX_PROGRESS" & vbTab & QP_AttemptToken & vbTab & _ Job & vbTab & CStr(QP_ProgressSequence) & vbTab & Stage & _ vbTab & CStr(Done) & vbTab & CStr(Total) & vbTab & CStr(Safe) & Suffix If Safe = 1 And Stage <> "finished" Then StopPath = QP_Fso.BuildPath(QP_Root, "monitor-" & QP_AttemptToken & ".stop") If QP_Fso.FileExists(StopPath) Then If Trim(QPReadUtf8(StopPath)) = CStr(QP_AttemptToken) Then _ Err.Raise vbObjectError + 860, "QuickPartReplace.SafeStop", _ "stopped at a safe boundary before native mutation after inactivity" End If End If End Sub Sub QPReadSessionRequest() Dim Path, Fields, Index, Character Path = QP_Fso.BuildPath(QP_Root, "project-session.request") If Not QP_Fso.FileExists(Path) Then Exit Sub If Not QP_BatchMode Or QP_DiscoveryMode Or _ QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid project session mode" Fields = Split(Trim(QPReadUtf8(Path)), vbTab) If UBound(Fields) <> 2 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid session request" QP_SessionToken = CStr(Fields(0)) If Len(QP_SessionToken) <> 32 Or Fields(2) <> QP_ExpectedJobId Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "session authorization mismatch" For Index = 1 To 32 Character = Mid(QP_SessionToken, Index, 1) If InStr(1, "0123456789abcdef", Character, vbBinaryCompare) = 0 Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid session token" Next QP_SessionProject = CStr(Fields(1)) If QPCanonicalPath(QPConfirmedProjectPath()) <> QPCanonicalPath(QP_SessionProject) Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "session project mismatch" QP_SessionMode = True End Sub Sub QPSessionNext() Dim Path, Fields, Attempt, TargetPath, Documents, Document, View Path = QP_Fso.BuildPath(QP_Root, "project-session-next.tsv") QPProgress "session_wait", 1, 1 For Attempt = 1 To 1500 If QP_Fso.FileExists(Path) Then Fields = Split(Trim(QPReadContinuation(Path)), vbTab) If UBound(Fields) <> 1 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid continuation" If Fields(0) <> QP_SessionToken Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "continuation token mismatch" QP_Fso.DeleteFile Path, True QPRequireSessionCheckpoint QP_SessionWaiting = False If Fields(1) = "close" Then QPCloseBatchProject QP_SessionProject, False QP_SessionMode = False Exit Sub End If QP_ExpectedJobId = CStr(Fields(1)) QP_CurrentJobId = QP_ExpectedJobId QP_BatchMode = True QP_BatchState = "" QP_BatchSaveCommitted = False QP_BatchSaveRequested = False QP_NativeMutationPossible = False If Trim(QPReadUtf8(QP_Fso.BuildPath(QP_Root, "batch.request"))) <> QP_ExpectedJobId Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "next batch authorization mismatch" TargetPath = QPConfirmedProjectPath() If QPCanonicalPath(TargetPath) <> QPCanonicalPath(QP_SessionProject) Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "cannot switch project inside a session" Set View = QP_App.ActiveView If Not View Is Nothing Then If CStr(View.GetName(0)) <> QP_TargetSchematic Or CStr(View.Block.SheetNum) <> QP_TargetSheet Then Set Documents = QP_App.SchematicSheetDocuments() If Documents.Count <> 1 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "owned sheet set changed" Set Document = Documents.Item(1) Document.Close False, "" End If End If QPEnsureProject QP_App, TargetPath Exit Sub End If WScript.Sleep 100 Next Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "supervisor did not release project checkpoint" End Sub Sub QPEvent_DocumentModified() If QP_SessionWaiting Then QP_SessionExternalChange = True End Sub Sub QPEvent_BlockModified(ByVal Block) If QP_SessionWaiting Then QP_SessionExternalChange = True End Sub Sub QPEvent_ProjectModified(ByVal NewProject) If QP_SessionWaiting Then QP_SessionExternalChange = True End Sub Sub QPEvent_BeforeProjectModified() If QP_SessionWaiting Then QP_SessionExternalChange = True End Sub Sub QPEvent_SourceFileModified(ByVal FileName) If QP_SessionWaiting Then QP_SessionExternalChange = True End Sub Sub QPRequireSessionCheckpoint() Dim Documents, View If Not QP_OwnedProject Or Len(QP_OwnedProjectPath) = 0 Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "session project ownership was lost" If QPCanonicalPath(QPProjectPath()) <> QPCanonicalPath(QP_OwnedProjectPath) Or _ QPCanonicalPath(QP_OwnedProjectPath) <> QPCanonicalPath(QP_SessionProject) Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "active project changed; no automatic save or close" If QP_SessionExternalChange Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "project modified outside worker at checkpoint; no automatic save or close" Set Documents = QP_App.SchematicSheetDocuments() Set View = QP_App.ActiveView If Documents.Count <> 1 Or View Is Nothing Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "owned sheet set changed at checkpoint" If CStr(View.GetName(0)) <> QP_CheckpointSchematic Or CStr(View.Block.SheetNum) <> QP_CheckpointSheet Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "active sheet changed at checkpoint" End Sub Sub QPInvalidatePinIndex() Set QP_PinIndex = Nothing QP_PinContext = "" End Sub Sub QPInvalidateComponentIndex() Set QP_ComponentUidIndex = Nothing Set QP_ComponentRefdesIndex = Nothing Set QP_ComponentLocationIndex = Nothing QP_ComponentIndexContext = "" End Sub Sub QPAddComponentIndexEntry(ByRef Index, ByVal Key, ByRef Comp) Dim Bucket If Not Index.Exists(CStr(Key)) Then Set Bucket = CreateObject("Scripting.Dictionary") Index.Add CStr(Key), Bucket End If Set Bucket = Index.Item(CStr(Key)) Bucket.Add CStr(Bucket.Count), Comp End Sub Sub QPBuildComponentIndex(ByRef Components) Dim Uids, Comp, Context, Count Context = QPCanonicalPath(QPProjectPath()) & "|" & QPSheetIdentity() Set Uids = CreateObject("Scripting.Dictionary") Count = 0 For Each Comp In Components QPAddComponentIndexEntry Uids, CStr(Comp.UID), Comp Count = Count + 1 If Count Mod 25 = 0 Then QPProgress "index_components", Count, 0 Next If Context <> QPCanonicalPath(QPProjectPath()) & "|" & QPSheetIdentity() Then _ Err.Raise vbObjectError + 864, "QuickPartReplace", "active context changed during component indexing" Set QP_ComponentUidIndex = Uids Set QP_ComponentRefdesIndex = Nothing Set QP_ComponentLocationIndex = Nothing QP_ComponentIndexContext = Context QPLog QP_Root, "INFO", "component_index_built count=" & Count End Sub Function QPBuildComponentAssociationIndex(ByVal UseLocation) Dim Result, Uid, Bucket, Index, Comp, Point, Key, Context, Count Context = QPCanonicalPath(QPProjectPath()) & "|" & QPSheetIdentity() If Context <> CStr(QP_ComponentIndexContext) Then _ Err.Raise vbObjectError + 864, "QuickPartReplace", "active context changed before component association indexing" Set Result = CreateObject("Scripting.Dictionary") Count = 0 For Each Uid In QP_ComponentUidIndex.Keys Set Bucket = QP_ComponentUidIndex.Item(CStr(Uid)) For Each Index In Bucket.Keys Set Comp = Bucket.Item(CStr(Index)) If UseLocation Then Set Point = Comp.GetLocation() Key = CStr(Point.X) & "|" & CStr(Point.Y) Else Key = CStr(Comp.Refdes) End If If Len(Key) > 0 Then QPAddComponentIndexEntry Result, Key, Comp Count = Count + 1 If Count Mod 25 = 0 Then QPProgress "index_components", Count, 0 Next Next If Context <> QPCanonicalPath(QPProjectPath()) & "|" & QPSheetIdentity() Then _ Err.Raise vbObjectError + 864, "QuickPartReplace", "active context changed during component association indexing" Set QPBuildComponentAssociationIndex = Result End Function Sub QPEnsureComponentIndex() Dim Context, Components Context = QPCanonicalPath(QPProjectPath()) & "|" & QPSheetIdentity() If Not IsObject(QP_ComponentUidIndex) Then Set QP_ComponentUidIndex = Nothing If Not QP_ComponentUidIndex Is Nothing Then If CStr(QP_ComponentIndexContext) <> Context Then QPInvalidateComponentIndex End If If QP_ComponentUidIndex Is Nothing Then Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL) QPBuildComponentIndex Components End If End Sub Function QPComponentPins(ByVal ComponentUid) Dim Context, LocalIndex, AllPins, CmpPin, Owner, Bucket, Count Context = QPCanonicalPath(QPProjectPath()) & "|" & QPSheetIdentity() If Not IsObject(QP_PinIndex) Then Set QP_PinIndex = Nothing If Not QP_PinIndex Is Nothing Then If CStr(QP_PinContext) <> Context Then QPInvalidatePinIndex End If If QP_PinIndex Is Nothing Then QPProgress "index_pins", 0, 0 Set LocalIndex = CreateObject("Scripting.Dictionary") Set AllPins = QP_App.ActiveView.Query(VDM_COMPPIN, VD_ALL) Count = 0 For Each CmpPin In AllPins Owner = CStr(CmpPin.Component.UID) If Len(Owner) = 0 Then Err.Raise vbObjectError + 862, "QuickPartReplace", "pin owner UID is empty" If Not LocalIndex.Exists(Owner) Then Set Bucket = CreateObject("Scripting.Dictionary") LocalIndex.Add Owner, Bucket End If Set Bucket = LocalIndex.Item(Owner) Bucket.Add CStr(Bucket.Count), CmpPin Count = Count + 1 If Count Mod 25 = 0 Then QPProgress "index_pins", Count, 0 Next If Context <> QPCanonicalPath(QPProjectPath()) & "|" & QPSheetIdentity() Then _ Err.Raise vbObjectError + 863, "QuickPartReplace", "active context changed during pin indexing" Set QP_PinIndex = LocalIndex QP_PinContext = Context QPLog QP_Root, "INFO", "pin_index_built count=" & Count QPProgress "index_pins", Count, Count End If If QP_PinIndex.Exists(ComponentUid) Then Set QPComponentPins = QP_PinIndex.Item(ComponentUid) Else Set QPComponentPins = CreateObject("Scripting.Dictionary") End If End Function Function QPConfirmedProjectPath() Dim Lines, Keys, Values, Index, JobIndex, ProjectIndex, SchematicIndex, SheetIndex, Found, TargetPath QPConfirmedProjectPath = "" If Len(CStr(QP_ExpectedJobId)) = 0 Then Exit Function Lines = Split(QPReadUtf8(QPActiveCommandPath( _ QP_Fso.BuildPath(QP_Root, "command.tsv"))), vbLf) Keys = Split(Replace(Lines(0), vbCr, ""), vbTab) JobIndex = -1 ProjectIndex = -1 SchematicIndex = -1 SheetIndex = -1 For Index = 0 To UBound(Keys) If Keys(Index) = "job_id" Then If JobIndex <> -1 Then Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "duplicate job_id header" JobIndex = Index End If If Keys(Index) = "project_path" Then If ProjectIndex <> -1 Then Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "duplicate project_path header" ProjectIndex = Index End If If Keys(Index) = "schematic_name" Then SchematicIndex = Index If Keys(Index) = "sheet_number" Then SheetIndex = Index Next If JobIndex < 0 Or ProjectIndex < 0 Then _ Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "missing confirmed project fields" Found = 0 For Index = 1 To UBound(Lines) If Len(Replace(Lines(Index), vbCr, "")) > 0 Then Values = Split(Replace(Lines(Index), vbCr, ""), vbTab) If UBound(Values) <> UBound(Keys) Then _ Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "invalid command field count" If Values(JobIndex) = CStr(QP_ExpectedJobId) Then Found = Found + 1 TargetPath = Values(ProjectIndex) If SchematicIndex >= 0 Then QP_TargetSchematic = Values(SchematicIndex) If SheetIndex >= 0 Then QP_TargetSheet = Values(SheetIndex) End If End If Next If Found <> 1 Then Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed job must match exactly one project" If (SchematicIndex >= 0) <> (SheetIndex >= 0) Then _ Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed sheet columns are incomplete" If (Len(QP_TargetSchematic) = 0) <> (Len(QP_TargetSheet) = 0) Then _ Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed sheet identity is incomplete" TargetPath = QPProjectAccessPath(TargetPath) If Not QP_Fso.FileExists(TargetPath) Then _ Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath If LCase(QP_Fso.GetExtensionName(TargetPath)) <> "prj" Then _ Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project must be a .prj file" QPConfirmedProjectPath = QP_Fso.GetAbsolutePathName(TargetPath) End Function Function QPDesignerProcessCount() Dim Service, Processes Set Service = GetObject("winmgmts:\\.\root\cimv2") Set Processes = Service.ExecQuery("SELECT ProcessId FROM Win32_Process WHERE Name='viewdraw.exe'") QPDesignerProcessCount = Processes.Count End Function Function QPTryAttach() On Error Resume Next Set QPTryAttach = Nothing Set QPTryAttach = GetObject(, "Viewdraw.Application") Err.Clear On Error GoTo 0 End Function Function QPAttachOrStart(ByVal ProcessCount) Dim App, Attempt, Environment, PrivateDesktop, ExpectedGuid Set Environment = CreateObject("WScript.Shell").Environment("PROCESS") PrivateDesktop = CStr(Environment("DXPART_DESKTOP")) ExpectedGuid = CStr(Environment("DXPART_CAD_GUID")) If Len(PrivateDesktop) = 0 And (Len(ExpectedGuid) > 0 Or Len(CStr(Environment("DXPART_CAD_PID"))) > 0 Or _ Len(CStr(Environment("DXPART_SESSION_TOKEN"))) > 0) Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "incomplete private CAD identity" If Len(PrivateDesktop) > 0 Then If Len(ExpectedGuid) = 0 Or Len(CStr(Environment("DXPART_CAD_PID"))) = 0 Or _ Len(CStr(Environment("DXPART_SESSION_TOKEN"))) <> 32 Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "incomplete private CAD identity" Set App = QPTryAttach() If App Is Nothing Then Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "owned private CAD is unavailable" If LCase(CStr(App.Guid())) <> LCase(ExpectedGuid) Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.PrivateDesktop", "private CAD GUID mismatch; no project was changed" Set QPAttachOrStart = App Exit Function End If If ProcessCount > 1 Then _ Err.Raise vbObjectError + 851, "QuickPartReplace.Session", "multiple DxDesigner instances; no project was changed" Set App = QPTryAttach() If App Is Nothing Then If ProcessCount = 0 Then QP_Stage = "launch_designer" QPLog QP_Root, "INFO", "stage=launch_designer method=COM" QPProgress "launch_designer", 0, 1 Set App = CreateObject("Viewdraw.Application") App.Visible = True Else QP_Stage = "wait_designer" QPLog QP_Root, "INFO", "stage=wait_designer existing_process=true" For Attempt = 1 To 60 WScript.Sleep 500 Set App = QPTryAttach() If Not App Is Nothing Then Exit For Next End If End If If App Is Nothing Then Err.Raise vbObjectError + 852, "QuickPartReplace.Session", _ "existing DxDesigner did not become available within 30 seconds; no duplicate instance was started" Set QPAttachOrStart = App End Function Sub QPEnsureProject(ByRef App, ByVal TargetPath) Dim ProjectData, CurrentPath, Opened, View, Documents Dim Schematics, Schematic, Sheets, Sheet, SheetCount, OnlySchematic, OnlySheet, Document TargetPath = QPProjectAccessPath(TargetPath) If Not QP_Fso.FileExists(TargetPath) Then _ Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath QP_Stage = "check_project" QPLog QP_Root, "INFO", "stage=check_project target=" & QPLogField(TargetPath) QPProgress "check_project", 0, 1 Set ProjectData = App.GetProjectData() CurrentPath = "" If Not ProjectData Is Nothing Then CurrentPath = CStr(ProjectData.GetProjectFilePath()) If Len(Trim(CurrentPath)) > 0 Then If QP_BatchMode And Not (QP_SessionMode And QP_OwnedProject) Then Err.Raise vbObjectError + 870, "QuickPartReplace.Batch", _ "batch cannot take over an already open project; save your wanted edits and close the project before starting the queue" If QPCanonicalPath(CurrentPath) <> QPCanonicalPath(TargetPath) Then _ Err.Raise vbObjectError + 853, "QuickPartReplace.Session", _ "another project is already open; save and close it before retrying. Current=" & CurrentPath & "; target=" & TargetPath Else QP_Stage = "open_project" QPLog QP_Root, "INFO", "stage=open_project target=" & QPLogField(TargetPath) QPProgress "open_project", 0, 1 Opened = App.OpenProject(CStr(TargetPath)) If Not Opened Then Err.Raise vbObjectError + 854, "QuickPartReplace.Session", "DxDesigner refused to open the target project" QP_OwnedProject = True QP_OwnedProjectPath = TargetPath End If Set ProjectData = App.GetProjectData() If ProjectData Is Nothing Then _ Err.Raise vbObjectError + 854, "QuickPartReplace.Session", "target project is not ready" If QPCanonicalPath(CStr(ProjectData.GetProjectFilePath())) <> QPCanonicalPath(TargetPath) Then _ Err.Raise vbObjectError + 854, "QuickPartReplace.Session", "opened project does not match the confirmed target" If QP_DiscoveryMode Then Exit Sub QP_Stage = "open_sheet" QPProgress "open_sheet", 0, 1 Set View = App.ActiveView If Not View Is Nothing And Not QP_BatchMode Then Exit Sub Set Documents = App.SchematicSheetDocuments() If Len(QP_TargetSchematic) > 0 Then QPRequireSheetManifest TargetPath, Documents, QP_TargetSchematic, QP_TargetSheet OnlySchematic = QP_TargetSchematic OnlySheet = QP_TargetSheet Else Set Schematics = Documents.GetAvailableSchematics() SheetCount = 0 For Each Schematic In Schematics Set Sheets = Documents.GetAvailableSheets(CStr(Schematic)) For Each Sheet In Sheets SheetCount = SheetCount + 1 OnlySchematic = CStr(Schematic) OnlySheet = CStr(Sheet) Next Next If SheetCount = 0 Then Err.Raise vbObjectError + 855, "QuickPartReplace.Session", "target project has no available schematic sheets" If SheetCount > 1 Then Err.Raise vbObjectError + 856, "QuickPartReplace.Session", _ "project has multiple sheets but the queue has no confirmed sheet identity" End If QPLog QP_Root, "INFO", "stage=open_sheet schematic=" & QPLogField(OnlySchematic) & " sheet=" & QPLogField(OnlySheet) Set Document = Documents.Open(OnlySchematic, OnlySheet) If Document Is Nothing Then Err.Raise vbObjectError + 857, "QuickPartReplace.Session", "target sheet could not be opened" Document.Activate Set View = App.ActiveView If View Is Nothing Then Err.Raise vbObjectError + 857, "QuickPartReplace.Session", "target sheet did not become active" If CStr(View.GetName(0)) <> OnlySchematic Or CStr(View.Block.SheetNum) <> OnlySheet Then _ Err.Raise vbObjectError + 857, "QuickPartReplace.Session", "active sheet does not match the requested sheet" End Sub Sub QPDiscoverSheets() Dim Documents, Schematics, Schematic, Sheets, Sheet, Text, Count If Not QP_DiscoveryMode Or Not QP_OwnedProject Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "sheet discovery does not own the project" QP_Stage = "discovery_enumerate_sheets" Set Documents = QP_App.SchematicSheetDocuments() Set Schematics = Documents.GetAvailableSchematics() Text = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbCrLf Count = 0 For Each Schematic In Schematics Set Sheets = Documents.GetAvailableSheets(CStr(Schematic)) For Each Sheet In Sheets QPRequireTsvField CStr(Schematic), "schematic name" QPRequireTsvField CStr(Sheet), "sheet number" Text = Text & QPProjectPath() & vbTab & CStr(Schematic) & vbTab & CStr(Sheet) & vbCrLf Count = Count + 1 QPProgress "discover_sheets", Count, 0 Next Next If Count = 0 Then Err.Raise vbObjectError + 855, "QuickPartReplace.Discovery", "target project has no available schematic sheets" QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "sheets.tsv"), Text If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "inventory-request.tsv")) Then _ QPDiscoverInventory Documents QP_Stage = "discovery_close_project" QP_App.CloseProject If Len(CStr(QP_App.GetProjectData().GetProjectFilePath())) > 0 Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "project did not close after sheet discovery" QP_OwnedProject = False QPProgress "finished", Count, Count End Sub Sub QPDiscoverInventory(ByRef Documents) Dim Requested, Schematics, Schematic, Sheets, Sheet, Document, View Dim Components, Comp, PartAttr, ValueAttr, PartNumber, PartKey, HitKey, Seen, Text, Count Dim ComponentText, ValueText, ComponentMode Set Requested = QPReadInventoryRequest() Set Seen = CreateObject("Scripting.Dictionary") Text = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & "old_part" & vbCrLf ComponentMode = QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "component-inventory.request")) ComponentText = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & _ "uid" & vbTab & "refdes" & vbTab & "old_part" & vbTab & "old_value" & vbCrLf Count = 0 Set Schematics = Documents.GetAvailableSchematics() For Each Schematic In Schematics Set Sheets = Documents.GetAvailableSheets(CStr(Schematic)) For Each Sheet In Sheets QP_Stage = "inventory_open_sheet " & CStr(Schematic) & ":" & CStr(Sheet) Set Document = Documents.Open(CStr(Schematic), CStr(Sheet)) If Document Is Nothing Then Err.Raise vbObjectError + 872, _ "QuickPartReplace.Discovery", "inventory sheet could not be opened" Document.Activate Set View = QP_App.ActiveView If View Is Nothing Then Err.Raise vbObjectError + 872, _ "QuickPartReplace.Discovery", "inventory sheet did not become active" If CStr(View.GetName(0)) <> CStr(Schematic) Or CStr(View.Block.SheetNum) <> CStr(Sheet) Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "inventory sheet identity changed" QP_Stage = "inventory_query " & CStr(Schematic) & ":" & CStr(Sheet) Set Components = View.Query(VDM_COMP, VD_ALL) For Each Comp In Components QP_Stage = "inventory_read_component " & CStr(Schematic) & ":" & CStr(Sheet) PartNumber = "" Set PartAttr = QPFindCurrentAttribute(Comp, "Part Number") If Not PartAttr Is Nothing Then PartNumber = QPEffectiveAttributeValue(PartAttr) PartKey = LCase(CStr(PartNumber)) If Requested.Exists(PartKey) Then If ComponentMode Then ValueText = "" Set ValueAttr = QPFindCurrentAttribute(Comp, "Value") If Not ValueAttr Is Nothing Then ValueText = QPEffectiveAttributeValue(ValueAttr) If Len(CStr(Comp.UID)) = 0 Or Len(CStr(Comp.Refdes)) = 0 Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "component identity is incomplete" ComponentText = ComponentText & QPEncode(QPProjectPath()) & vbTab & _ QPEncode(CStr(Schematic)) & vbTab & QPEncode(CStr(Sheet)) & vbTab & _ QPEncode(CStr(Comp.UID)) & vbTab & QPEncode(CStr(Comp.Refdes)) & vbTab & _ QPEncode(CStr(PartNumber)) & vbTab & QPEncode(CStr(ValueText)) & vbCrLf End If HitKey = QPSheetKey(Schematic, Sheet) & Chr(30) & PartKey If Not Seen.Exists(HitKey) Then Seen.Add HitKey, True Text = Text & QPEncode(QPProjectPath()) & vbTab & _ QPEncode(CStr(Schematic)) & vbTab & QPEncode(CStr(Sheet)) & vbTab & _ QPEncode(CStr(Requested(PartKey))) & vbCrLf End If End If Next QP_Stage = "inventory_close_sheet " & CStr(Schematic) & ":" & CStr(Sheet) Document.Close False, "" Count = Count + 1 QPProgress "inventory_sheets", Count, 0 Next Next QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "inventory.tsv"), Text If ComponentMode Then QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "components.tsv"), ComponentText End Sub Function QPReadInventoryRequest() Dim Path, Lines, Header, Result, Index, Fields, OldPart, Key Path = QP_Fso.BuildPath(QP_Root, "inventory-request.tsv") Lines = Split(QPReadUtf8(Path), vbLf) Header = Replace(Lines(0), vbCr, "") If Header <> "old_part" Then Err.Raise vbObjectError + 872, _ "QuickPartReplace.Discovery", "inventory request header is invalid" Set Result = CreateObject("Scripting.Dictionary") For Index = 1 To UBound(Lines) If Len(Replace(Lines(Index), vbCr, "")) > 0 Then Fields = Split(Replace(Lines(Index), vbCr, ""), vbTab) If UBound(Fields) <> 0 Then Err.Raise vbObjectError + 872, _ "QuickPartReplace.Discovery", "inventory request field count is invalid" OldPart = QPDecode(Fields(0)) QPRequireTsvField OldPart, "inventory old Part Number" Key = LCase(CStr(OldPart)) If Result.Exists(Key) Then Err.Raise vbObjectError + 872, _ "QuickPartReplace.Discovery", "inventory request contains duplicate old Part Number" Result.Add Key, OldPart End If Next If Result.Count = 0 Then Err.Raise vbObjectError + 872, _ "QuickPartReplace.Discovery", "inventory request is empty" Set QPReadInventoryRequest = Result End Function Sub QPRequireTsvField(ByVal Value, ByVal Label) If Len(CStr(Value)) = 0 Or InStr(CStr(Value), vbTab) > 0 Or _ InStr(CStr(Value), vbCr) > 0 Or InStr(CStr(Value), vbLf) > 0 Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "invalid " & Label End Sub Function QPSheetKey(ByVal Schematic, ByVal Sheet) QPSheetKey = LCase(CStr(Schematic)) & Chr(30) & LCase(CStr(Sheet)) End Function Sub QPRequireSheetManifest(ByVal TargetPath, ByRef Documents, ByVal WantedSchematic, ByVal WantedSheet) Dim Path, Lines, Keys, Values, Index, LineIndex, ProjectIndex, SchematicIndex, SheetIndex Dim Expected, Actual, Schematics, Schematic, Sheets, Sheet, Key, TargetKey Path = QP_Fso.BuildPath(QP_Root, "sheets.tsv") If Not QP_Fso.FileExists(Path) Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Session", "confirmed sheet manifest is missing" Lines = Split(QPReadUtf8(Path), vbLf) Keys = Split(Replace(Lines(0), vbCr, ""), vbTab) ProjectIndex = -1 SchematicIndex = -1 SheetIndex = -1 For Index = 0 To UBound(Keys) If Keys(Index) = "project_path" Then ProjectIndex = Index If Keys(Index) = "schematic_name" Then SchematicIndex = Index If Keys(Index) = "sheet_number" Then SheetIndex = Index Next If ProjectIndex < 0 Or SchematicIndex < 0 Or SheetIndex < 0 Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Session", "confirmed sheet manifest is malformed" Set Expected = CreateObject("Scripting.Dictionary") For LineIndex = 1 To UBound(Lines) If Len(Replace(Lines(LineIndex), vbCr, "")) > 0 Then Values = Split(Replace(Lines(LineIndex), vbCr, ""), vbTab) If UBound(Values) <> UBound(Keys) Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Session", "confirmed sheet manifest field count" If QPCanonicalPath(Values(ProjectIndex)) = QPCanonicalPath(TargetPath) Then Key = QPSheetKey(Values(SchematicIndex), Values(SheetIndex)) If Expected.Exists(Key) Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Session", "duplicate confirmed sheet identity" Expected.Add Key, True End If End If Next TargetKey = QPSheetKey(WantedSchematic, WantedSheet) If Not Expected.Exists(TargetKey) Then _ Err.Raise vbObjectError + 856, "QuickPartReplace.Session", "target sheet is not in the confirmed sheet manifest" Set Actual = CreateObject("Scripting.Dictionary") Set Schematics = Documents.GetAvailableSchematics() For Each Schematic In Schematics Set Sheets = Documents.GetAvailableSheets(CStr(Schematic)) For Each Sheet In Sheets Key = QPSheetKey(Schematic, Sheet) If Actual.Exists(Key) Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Session", "duplicate available sheet identity" Actual.Add Key, True Next Next If Expected.Count = 0 Or Expected.Count <> Actual.Count Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Session", "project sheet set changed after discovery" For Each Key In Actual.Keys If Not Expected.Exists(Key) Then _ Err.Raise vbObjectError + 872, "QuickPartReplace.Session", "project sheet set changed after discovery" Next End Sub Sub QPCloseBatchProject(ByVal ExpectedPath, ByVal SaveChanges) Dim Documents, Document If Not QP_OwnedProject Or QP_RestoreTransactionOpen Then _ Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project ownership or restoration transaction is not safe to close" If QPCanonicalPath(ExpectedPath) <> QPCanonicalPath(QP_OwnedProjectPath) Or QP_SessionExternalChange Then _ Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "owned project changed; no automatic close" If QPCanonicalPath(QPProjectPath()) <> QPCanonicalPath(ExpectedPath) Then _ Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "active project changed before save and close" Set Documents = QP_App.SchematicSheetDocuments() If Documents.Count <> 1 Then Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "open sheet set changed; no automatic close" Set Document = Documents.Item(1) QPProgress "save_and_close", 0, 1 If SaveChanges Then QP_BatchSaveRequested = True QPLog QP_Root, "INFO", "save_requested job=" & QP_CurrentJobId End If Document.Close CBool(SaveChanges), "" If SaveChanges Then QP_BatchSaveCommitted = True QPLog QP_Root, "INFO", "save_returned job=" & QP_CurrentJobId End If If QPCanonicalPath(QPProjectPath()) <> QPCanonicalPath(ExpectedPath) Then _ Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project changed during sheet save" QP_App.CloseProject If Len(CStr(QP_App.GetProjectData().GetProjectFilePath())) > 0 Then _ Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "project did not close; queue stopped" QPLog QP_Root, "INFO", "project_closed job=" & QP_CurrentJobId QP_OwnedProject = False QP_OwnedProjectPath = "" QPInvalidatePinIndex QPInvalidateComponentIndex End Sub Sub QPDiscardFailedBatchProject(ByRef ErrorDescription) Dim ErrorNumber, ErrorSource, Description ErrorDescription = "" If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub If QP_NativeMutationPossible Or QP_BatchSaveRequested Or QP_BatchSaveCommitted Then ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard" Exit Sub End If On Error Resume Next QPCloseBatchProject QP_OwnedProjectPath, False ErrorNumber = Err.Number ErrorSource = Err.Source Description = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then ErrorDescription = CStr(ErrorSource) & ": " & CStr(Description) Else If QP_BatchSaveCommitted Then QPLog QP_Root, "WARN", "batch project was already saved; failed readback project closed without additional saving" Else QPLog QP_Root, "WARN", "batch failed project closed without saving; native rollback not executed" End If End If End Sub Sub QPFinishBatchItem() Dim Command, SnapshotPath, Records, Plans, ValueStates, Index, Record, Candidate, TargetPath, FinalState If QP_BatchState <> "restored_ok" And QP_BatchState <> "no_match" Then _ Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "worker has no verified terminal result" FinalState = QP_BatchState QP_BatchState = "" Set Command = QPReadCommand(QP_Fso.BuildPath(QP_Root, "command.tsv")) QP_BatchState = FinalState TargetPath = CStr(Command("project_path")) If FinalState = "restored_ok" Then SnapshotPath = QPJobSnapshotPath(QP_CurrentJobId) QPRequireCommandSnapshot Command, SnapshotPath Set Records = QPReadSnapshot(SnapshotPath) QPVerifyUntouched Records Set ValueStates = CreateObject("Scripting.Dictionary") For Index = 0 To Records.Item("components").Count - 1 Set Record = Records.Item("components").Item(CStr(Index)) Set Candidate = QPFindUniqueByOldLocation(Record) ValueStates.Add CStr(Index), QPCaptureValueState(Candidate) QPSetRequiredNc ValueStates.Item(CStr(Index)), Record, Records.Item("attributes"), QPSyncNc(Command) ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command) Next End If If FinalState = "restored_ok" Then QPMarkBatchMutation Command QPCloseBatchProject TargetPath, True ElseIf Not QP_SessionMode Then QPCloseBatchProject TargetPath, False End If If FinalState = "restored_ok" Then QPProgress "verify_saved_project", 0, 1 QPEnsureProject QP_App, TargetPath QPRequireCommandSnapshot Command, SnapshotPath QPVerifyUntouched Records Set Plans = CreateObject("Scripting.Dictionary") For Index = 0 To Records.Item("components").Count - 1 Set Record = Records.Item("components").Item(CStr(Index)) Set Candidate = QPFindUniqueByOldLocation(Record) If CStr(Candidate.UID) <> CStr(Record("uid")) Then _ Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "saved component UID differs" Plans.Add CStr(Index), Candidate Next QPVerifyRestoredPlans Command, Records, Plans, ValueStates If Not QP_SessionMode Then QPCloseBatchProject TargetPath, False FinalState = "saved_ok" QPLog QP_Root, "INFO", "saved_readback_verified job=" & QP_CurrentJobId If QP_SessionMode Then QP_BatchMessage = QP_BatchMessage & " Saved and reopened for readback; owned project checkpoint verified." Else QP_BatchMessage = QP_BatchMessage & " Saved, reopened for readback, and closed." End If End If QP_BatchMode = False If QP_SessionMode Then QP_NativeMutationPossible = False QP_SessionExternalChange = False QP_CheckpointSchematic = QP_TargetSchematic QP_CheckpointSheet = QP_TargetSheet QP_SessionWaiting = True QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "session_verified", QP_BatchMessage QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "project-session-result.tsv"), _ QP_SessionToken & vbTab & QP_CurrentJobId & vbTab & FinalState & vbTab & "session_verified" ElseIf QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then QPWriteStatus QP_Root, QP_CurrentJobId, "restored_ok", "recovery_saved_verified", QP_BatchMessage Else QPWriteStatus QP_Root, QP_CurrentJobId, FinalState, "batch_closed", QP_BatchMessage End If QPProgress "finished", 1, 1 End Sub Sub QPMarkBatchMutation(ByRef Command) Dim Shell, Entry, Required, CommandLine, Key, Value, ExitCode Set Shell = CreateObject("WScript.Shell") Required = False For Each Entry In Shell.Environment("Process") If InStr(1, CStr(Entry), "DXPART_ATTEMPT_FILE=", vbTextCompare) = 1 Or _ InStr(1, CStr(Entry), "DXPART_BATCH_SESSION_ID=", vbTextCompare) = 1 Or _ InStr(1, CStr(Entry), "DXPART_BATCH_GENERATION=", vbTextCompare) = 1 Or _ InStr(1, CStr(Entry), "DXPART_ATTEMPT_ID=", vbTextCompare) = 1 Then Required = True Next If Not Required Then Exit Sub If Len(QP_HelperExecutable) = 0 Or Not QP_Fso.FileExists(QP_HelperExecutable) Then _ Err.Raise vbObjectError + 879, "QuickPartReplace.Attempt", "mutation proof helper is unavailable" CommandLine = Chr(34) & QP_HelperExecutable & Chr(34) If Len(QP_HelperScript) > 0 Then If Not QP_Fso.FileExists(QP_HelperScript) Then _ Err.Raise vbObjectError + 879, "QuickPartReplace.Attempt", "mutation proof script is unavailable" CommandLine = CommandLine & " " & Chr(34) & QP_HelperScript & Chr(34) End If CommandLine = CommandLine & " --mark-batch-attempt" For Each Key In Array("job_id", "task_id", "project_path") Value = CStr(Command(Key)) If Len(Value) = 0 Or InStr(Value, Chr(34)) > 0 Or InStr(Value, vbCr) > 0 Or InStr(Value, vbLf) > 0 Then _ Err.Raise vbObjectError + 879, "QuickPartReplace.Attempt", "invalid mutation proof identity" Select Case Key Case "job_id": CommandLine = CommandLine & " --attempt-job " Case "task_id": CommandLine = CommandLine & " --attempt-task " Case "project_path": CommandLine = CommandLine & " --attempt-project " End Select CommandLine = CommandLine & Chr(34) & Value & Chr(34) Next ExitCode = Shell.Run(CommandLine, 0, True) If ExitCode <> 0 Then Err.Raise vbObjectError + 879, "QuickPartReplace.Attempt", _ "durable mutation proof failed; no CAD write allowed" End Sub Sub QPAutomaticReplaceAndRestore(ByRef Command, ByVal SnapshotPath) Dim ErrorNumber, ErrorSource, ErrorDescription QPRequireCommandSnapshot Command, SnapshotPath On Error Resume Next QPNativeReplace Command, SnapshotPath If Err.Number = 0 Then QPRestoreAfterOperatorReplace Command, SnapshotPath ErrorNumber = Err.Number ErrorSource = Err.Source ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then If QP_NativeMutationPossible And Not QP_BatchMode Then On Error Resume Next QPRollbackNativeReplacement SnapshotPath If Err.Number <> 0 Then ErrorDescription = "NATIVE ROLLBACK UNVERIFIED; use the disposable project copy only. " & _ ErrorDescription & "; rollback: " & Err.Description ErrorNumber = vbObjectError + 841 ErrorSource = "QuickPartReplace" Err.Clear Else ErrorDescription = "Replacement validation failed; native rollback was verified and the original sheet state was restored. No replacement remains. Original failure: " & ErrorDescription End If On Error GoTo 0 ElseIf QP_NativeMutationPossible And QP_BatchMode Then ErrorDescription = "Replacement validation failed; batch mode kept the native result unsaved and closed the failed project. " & ErrorDescription End If QPRaiseCaptured ErrorNumber, ErrorSource, ErrorDescription, "QuickPartReplace.Automatic" End If QP_NativeMutationPossible = False End Sub Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath) Dim Shell, ExitCode, CommandLine, ErrorPath, ErrorDetail QPProgress "before_native", 0, 1 QPInvalidatePinIndex If Len(QP_HelperExecutable) = 0 Or Not QP_Fso.FileExists(QP_HelperExecutable) Then _ Err.Raise vbObjectError + 838, "QuickPartReplace", "native helper executable is unavailable" CommandLine = Chr(34) & QP_HelperExecutable & Chr(34) If Len(QP_HelperScript) > 0 Then If Not QP_Fso.FileExists(QP_HelperScript) Then _ Err.Raise vbObjectError + 838, "QuickPartReplace", "native helper script is unavailable" CommandLine = CommandLine & " " & Chr(34) & QP_HelperScript & Chr(34) End If CommandLine = CommandLine & " --native-helper --snapshot " & Chr(34) & SnapshotPath & Chr(34) Set Shell = CreateObject("WScript.Shell") QP_NativeCallActive = True QPProgress "native_replace", 0, 1 ExitCode = Shell.Run(CommandLine, 0, True) QPLog QP_Root, "INFO", "native_helper_exit code=" & CStr(ExitCode) QP_NativeMutationPossible = QPNativeReportShowsMutation(SnapshotPath & ".native.json") QP_NativeCallActive = False QPInvalidatePinIndex QPProgress "native_replace", 1, 1 If ExitCode <> 0 Then ErrorPath = SnapshotPath & ".native.error.txt" ErrorDetail = "" If QP_Fso.FileExists(ErrorPath) Then ErrorDetail = Trim(QPReadUtf8(ErrorPath)) If Len(ErrorDetail) > 0 Then Err.Raise vbObjectError + 839, "QuickPartReplace", _ "automatic native replacement failed: " & ErrorDetail & _ "; report: " & SnapshotPath & ".native.json" Else Err.Raise vbObjectError + 839, "QuickPartReplace", _ "automatic native replacement failed (exit=" & CStr(ExitCode) & "); see " & SnapshotPath & ".native.json" End If End If End Sub Function QPNativeReportShowsMutation(ByVal ReportPath) Dim Text QPNativeReportShowsMutation = False If Not QP_Fso.FileExists(ReportPath) Then Exit Function Text = QPReadUtf8(ReportPath) QPNativeReportShowsMutation = _ (InStr(1, Text, """stage"": ""native_replace_started""", vbTextCompare) > 0) Or _ (InStr(1, Text, """stage"": ""native_replace_applied""", vbTextCompare) > 0) Or _ (InStr(1, Text, """stage"": ""pin_promotion_started""", vbTextCompare) > 0) Or _ (InStr(1, Text, """stage"": ""native_replace_verified""", vbTextCompare) > 0) End Function Sub QPRequireSnapshotContext(ByVal SnapshotPath) Dim Records Set Records = QPReadSnapshot(SnapshotPath) QPRequireRecordsContext Records End Sub Sub QPRequireRecordsContext(ByRef Records) Dim Meta Set Meta = Records.Item("meta") If QPCanonicalPath(CStr(Meta("project_path"))) <> QPCanonicalPath(QPProjectPath()) Or _ CStr(Meta("sheet_name")) <> QPSheetIdentity() Then _ Err.Raise vbObjectError + 799, "QuickPartReplace", "snapshot project or sheet mismatch" End Sub Sub QPRollbackNativeReplacement(ByVal SnapshotPath) Dim Records, ComponentRecord, Candidate, Index, Expected, Actual, Lines Dim LineIndex, UndoResult If Len(CStr(QP_CurrentJobId)) = 0 Or _ QPCanonicalPath(SnapshotPath) <> QPCanonicalPath(QPJobSnapshotPath(CStr(QP_CurrentJobId))) Then _ Err.Raise vbObjectError + 843, "QuickPartReplace", "native rollback transaction mismatch" QPRequireSnapshotContext SnapshotPath Set Records = QPReadSnapshot(SnapshotPath) UndoResult = QP_App.ExecuteCommand("undo") QPInvalidatePinIndex QPInvalidateComponentIndex Lines = Split(QPReadUtf8(SnapshotPath), vbLf) Expected = "" For LineIndex = 1 To UBound(Lines) If Len(Replace(Lines(LineIndex), vbCr, "")) > 0 Then If Left(CStr(Lines(LineIndex)), 2) = "C" & vbTab Or _ Left(CStr(Lines(LineIndex)), 2) = "A" & vbTab Then _ Expected = Expected & Replace(Lines(LineIndex), vbCr, "") & vbCrLf End If Next Actual = "" For Index = 0 To Records.Item("components").Count - 1 Set ComponentRecord = Records.Item("components").Item(CStr(Index)) Set Candidate = QPFindUniqueByOldLocation(ComponentRecord) Actual = Actual & QPSnapshotComponent(Candidate) QPProgress "verify_native_rollback", Index + 1, Records.Item("components").Count Next QPVerifyUntouched Records If Actual <> Expected Then Err.Raise vbObjectError + 842, _ "QuickPartReplace", "native undo does not match the original snapshot" QPWriteUtf8 SnapshotPath & ".native.rolled-back", _ "native replacement rollback verified" & vbCrLf QP_NativeMutationPossible = False QPLog QP_Root, "WARN", "native replacement rolled back and verified" End Sub Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath) Dim Components Dim Comp Dim Matches Dim PartNumber Dim Snapshot Dim Index Dim Selectors, Selector, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount, NativeRead If StrComp(CStr(Command("old_part_number")), CStr(Command("new_part_number")), vbTextCompare) = 0 Then _ Err.Raise vbObjectError + 829, "QuickPartReplace", "source and target must differ" QPInvalidatePinIndex QPInvalidateComponentIndex QPProgress "query_components", 0, 0 Set Matches = CreateObject("Scripting.Dictionary") QP_Stage = "query_components" QPLog QP_Root, "INFO", "stage=query_components" Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL) ' Capture walks the queried collection directly. Build lookup indexes only ' when restoration needs them, from fresh proxies after native mutation. Set Selectors = QPCommandTargets(Command) For Each Comp In Components Uid = CStr(Comp.UID) If Selectors Is Nothing Then PartNumber = QPEffectiveComponentAttribute(Comp, "Part Number") If StrComp(PartNumber, CStr(Command("old_part_number")), _ vbTextCompare) = 0 Then Matches.Add CStr(Matches.Count), Comp ElseIf Selectors.Exists(Uid) Then PartNumber = QPEffectiveComponentAttribute(Comp, "Part Number") Selector = Selectors.Item(Uid) ValueText = "" Set ValueAttr = QPFindCurrentAttribute(Comp, "Value") If Not ValueAttr Is Nothing Then ValueText = QPEffectiveAttributeValue(ValueAttr) If CStr(Comp.Refdes) <> CStr(Selector(0)) Or _ StrComp(PartNumber, CStr(Command("old_part_number")), vbTextCompare) <> 0 Or _ ValueText <> CStr(Selector(1)) Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component changed since inventory" Matches.Add CStr(Matches.Count), Comp End If QPProgress "find_components", Matches.Count, 0 Next If Not Selectors Is Nothing Then If Matches.Count <> Selectors.Count Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component is missing" End If If Matches.Count = 0 Then If Not Selectors Is Nothing Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "target scope is empty" QPWriteStatus QP_Root, CStr(Command("job_id")), "no_match", "", _ "No components match old Part Number on the current sheet; no replacement was performed. " & _ "Project=" & QPProjectPath() & "; sheet=" & QPSheetIdentity() & "; old_part=" & CStr(Command("old_part_number")) QPLog QP_Root, "INFO", "no_match current_sheet=" & QPLogField(QPSheetIdentity()) & _ " old_part=" & QPLogField(CStr(Command("old_part_number"))) Exit Sub End If Snapshot = "M" & vbTab & QPEncode(QPProjectPath()) & _ vbTab & QPEncode(CStr(Command("old_part_number"))) & vbTab & _ QPEncode(CStr(Command("new_part_number"))) & vbTab & _ QPEncode(QPSheetIdentity()) If QPValueMode(Command) <> "legacy_part_label" Then _ Snapshot = Snapshot & vbTab & QPEncode(QPValueMode(Command)) & _ vbTab & QPEncode(QPCustomValue(Command)) & vbTab & _ QPEncode(QPBooleanText(QPSyncNc(Command))) If Not Selectors Is Nothing Then _ Snapshot = Snapshot & vbTab & QPEncode("targets") & vbTab & CStr(Command("target_selectors")) Snapshot = Snapshot & vbCrLf If Len(QPTargetCell(Command)) > 0 Then _ Snapshot = Snapshot & "L" & vbTab & QPEncode(QPTargetCell(Command)) & vbCrLf Set MatchedUids = CreateObject("Scripting.Dictionary") For Index = 0 To Matches.Count - 1 Set Comp = Matches.Item(CStr(Index)) MatchedUids.Add CStr(Comp.UID), True Next Set NativeRead = Nothing If QPUseNativeSnapshot() Then QPRequireProject Command Set NativeRead = QPNativeCapture(MatchedUids) If Not NativeRead Is Nothing Then If NativeRead("total") <> Components.Count Then _ Err.Raise vbObjectError + 875, "QuickPartReplace.NativeRead", "component count changed during capture" End If End If For Index = 0 To Matches.Count - 1 Set Comp = Matches.Item(CStr(Index)) Uid = CStr(Comp.UID) QPLog QP_Root, "INFO", "stage=snapshot_component uid=" & QPLogField(Uid) If NativeRead Is Nothing Then Snapshot = Snapshot & QPSnapshotComponent(Comp) Else QPRequireNativeCapturedTarget CStr(NativeRead("selected")(Uid)), Command, Uid, Selectors Snapshot = Snapshot & CStr(NativeRead("selected")(Uid)) End If QPProgress "capture", Index + 1, Matches.Count Next ' U remains the seven-field native-helper identity baseline. X/G extend it ' with complete unselected state for every scope, including all-match jobs. Snapshot = Snapshot & "X" & vbTab & "untouched_full_v1" & vbCrLf UntouchedCount = 0 If NativeRead Is Nothing Then For Each Comp In Components If Not MatchedUids.Exists(CStr(Comp.UID)) Then QPProgress "capture_untouched", UntouchedCount, Components.Count - Matches.Count Snapshot = Snapshot & QPUntouchedComponent(Comp) UntouchedCount = UntouchedCount + 1 QPProgress "capture_untouched", UntouchedCount, Components.Count - Matches.Count End If Next Else Snapshot = Snapshot & CStr(NativeRead("text")) End If QPWriteUtf8 SnapshotPath, Snapshot For Each Comp In Components Comp.Selected = False Next For Index = 0 To Matches.Count - 1 Set Comp = Matches.Item(CStr(Index)) Comp.Selected = True Next QPWriteStatus QP_Root, CStr(Command("job_id")), _ "awaiting_native_replace", "", _ "Snapshot captured; automatic native replacement is starting." QPLog QP_Root, "INFO", "awaiting_native_replace count=" & Matches.Count End Sub Sub QPRequireNativeCapturedTarget(ByVal State, ByRef Command, ByVal Uid, ByRef Selectors) Dim Fields, Selector Fields = Split(QPUntouchedIdentity(State), vbTab) If QPDecode(Fields(1)) <> Uid Or StrComp(QPDecode(Fields(3)), _ CStr(Command("old_part_number")), vbTextCompare) <> 0 Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component changed during native capture" If Not Selectors Is Nothing Then Selector = Selectors(Uid) If QPDecode(Fields(2)) <> CStr(Selector(0)) Or QPDecode(Fields(4)) <> CStr(Selector(1)) Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component changed during native capture" End If End Sub Function QPUseNativeSnapshot() Dim Reader, Number QPUseNativeSnapshot = False If Not QP_BatchMode Or Not QP_OwnedProject Then Exit Function If Len(CStr(CreateObject("WScript.Shell").Environment("PROCESS")("DXPART_DESKTOP"))) = 0 Then Exit Function On Error Resume Next Set Reader = GetRef("QPNativeReadUntouched") Number = Err.Number Err.Clear On Error GoTo 0 If Number <> 0 Then Exit Function If QPCanonicalPath(QP_OwnedProjectPath) <> QPProjectPath() Then _ Err.Raise vbObjectError + 875, "QuickPartReplace.NativeRead", "native reader does not own the active project" QPUseNativeSnapshot = True End Function Function QPUntouchedComponent(ByRef Comp) Dim State, Identity, Fields State = QPUntouchedFullState(Comp) Identity = QPUntouchedIdentity(State) Fields = Split(Identity, vbTab) QPUntouchedComponent = Identity & vbCrLf & "G" & vbTab & Fields(1) & _ vbTab & QPEncode(State) & vbCrLf End Function Function QPUntouchedIdentity(ByVal State) Dim Values, Seen, Line, Fields, Header, Name, Value Set Values = CreateObject("Scripting.Dictionary") Set Seen = CreateObject("Scripting.Dictionary") Values.CompareMode = vbTextCompare Seen.CompareMode = vbTextCompare For Each Name In Array("Part Number", "Value", "Part Name", "Part Label") Values.Add Name, "" Next Header = "" For Each Line In Split(State, vbCrLf) If Len(Line) > 0 Then Fields = Split(Line, vbTab) If Fields(0) = "C" Then Header = "U" & vbTab & Fields(1) & vbTab & Fields(2) ElseIf Fields(0) = "A" Then Name = QPDecode(Fields(2)) If Values.Exists(Name) Then If Seen.Exists(Name) Then Err.Raise vbObjectError + 874, _ "QuickPartReplace.Target", "duplicate unselected identity attribute" Seen.Add Name, True Value = Fields(4) If Len(Value) = 0 Then Value = Fields(3) Values(Name) = Value End If End If End If Next QPUntouchedIdentity = Header & vbTab & Values("Part Number") & vbTab & _ Values("Value") & vbTab & Values("Part Name") & vbTab & Values("Part Label") End Function Function QPUntouchedFullState(ByRef Comp) Dim Point, Pins, Connections, Attr, AttributeText, Result, Uid Uid = CStr(Comp.UID) Set Point = Comp.GetLocation() Set Pins = QPComponentPins(Uid) If Pins.Count = 0 Then ' A genuinely empty query is valid for annotation symbols; COM errors ' still propagate. Selected replacement symbols continue to require pins. Connections = "NO_PINS" Else Connections = QPConnectionSignatureFromPins(Uid, Pins) End If Result = "C" & vbTab & QPEncode(Uid) & vbTab & QPEncode(CStr(Comp.Refdes)) & _ vbTab & QPEncode(CStr(Point.X)) & vbTab & QPEncode(CStr(Point.Y)) & _ vbTab & QPEncode(CStr(Comp.Orientation)) & vbTab & QPEncode(CStr(Comp.Scale)) & _ vbTab & QPEncode(Connections) & vbCrLf AttributeText = "" For Each Attr In Comp.Attributes AttributeText = AttributeText & QPSnapshotAttribute(Uid, Attr) Next QPUntouchedFullState = Result & QPSortSnapshotLines(AttributeText) End Function Function QPEffectiveComponentAttribute(ByRef Comp, ByVal Name) Dim Attr QPEffectiveComponentAttribute = "" Set Attr = QPFindCurrentAttribute(Comp, Name) If Not Attr Is Nothing Then QPEffectiveComponentAttribute = QPEffectiveAttributeValue(Attr) End Function Sub QPVerifyUntouched(ByRef Records) Dim Baseline, FullBaseline, Components, Comp, Uid, Actual, Expected, Matched, Total, Seen If Not Records.Exists("untouched_full_version") Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "legacy snapshot has no complete unselected-state proof; recovery requires manual verification" Set Baseline = Records.Item("untouched") Set FullBaseline = Records.Item("untouched_full") If Baseline.Count <> FullBaseline.Count Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "unselected full-state baseline is incomplete" ' Read new component/pin proxies after each native mutation, restore or reopen. QPInvalidatePinIndex QPInvalidateComponentIndex If QPUseNativeSnapshot() Then If QPTryNativeVerifyUntouched(Records) Then Exit Sub End If Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL) Matched = 0 Total = 0 Set Seen = CreateObject("Scripting.Dictionary") For Each Comp In Components Total = Total + 1 Uid = CStr(Comp.UID) If Seen.Exists(Uid) Then Err.Raise vbObjectError + 874, _ "QuickPartReplace.Target", "duplicate component UID" Seen.Add Uid, True If Baseline.Exists(Uid) Then QPProgress "verify_untouched", Matched, Baseline.Count Matched = Matched + 1 If Not FullBaseline.Exists(Uid) Then Err.Raise vbObjectError + 874, _ "QuickPartReplace.Target", "unselected full-state baseline is missing" Actual = QPUntouchedComponent(Comp) Expected = CStr(Baseline.Item(Uid)) & vbCrLf & "G" & vbTab & QPEncode(Uid) & _ vbTab & QPEncode(CStr(FullBaseline.Item(Uid))) & vbCrLf If Actual <> Expected Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "unselected component changed" QPProgress "verify_untouched", Matched, Baseline.Count End If Next If Total <> Baseline.Count + Records.Item("components").Count Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "component count changed outside selected targets" If Matched <> Baseline.Count Then Err.Raise vbObjectError + 874, _ "QuickPartReplace.Target", "unselected component is missing" End Sub Function QPCommandTargets(ByRef Command) Dim Scope, Text, Entries, Entry, Fields, Result, Index Set QPCommandTargets = Nothing If Not Command.Exists("target_scope") Then Exit Function Scope = CStr(Command("target_scope")) If Scope = "all" Then If Len(CStr(Command("target_selectors"))) <> 0 Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "all-match scope has selectors" Exit Function End If If Scope <> "targets" Then Err.Raise vbObjectError + 873, _ "QuickPartReplace.Target", "target scope is invalid" Text = QPDecode(CStr(Command("target_selectors"))) If Len(Text) = 0 Then Err.Raise vbObjectError + 873, _ "QuickPartReplace.Target", "target scope is empty" Set Result = CreateObject("Scripting.Dictionary") Entries = Split(Text, Chr(30)) For Index = 0 To UBound(Entries) Fields = Split(Entries(Index), Chr(31)) If UBound(Fields) <> 2 Or Len(CStr(Fields(0))) = 0 Or _ Len(CStr(Fields(1))) = 0 Then Err.Raise vbObjectError + 873, _ "QuickPartReplace.Target", "target selector is malformed" If Result.Exists(CStr(Fields(0))) Then Err.Raise vbObjectError + 873, _ "QuickPartReplace.Target", "duplicate target UID" Result.Add CStr(Fields(0)), Array(CStr(Fields(1)), CStr(Fields(2))) Next Set QPCommandTargets = Result End Function Function QPSnapshotComponent(ByRef Comp) Dim AttributeCount Dim Point Dim AttributeText Dim Attr Dim Result Dim Connections Dim ErrorNumber Dim ErrorSource Dim ErrorDescription Dim Uid, Pins Uid = CStr(Comp.UID) Set Point = Comp.GetLocation() Set Pins = QPComponentPins(Uid) Connections = QPConnectionSignatureFromPins(Uid, Pins) Result = "C" & vbTab & QPEncode(Uid) & vbTab & _ QPEncode(CStr(Comp.Refdes)) & vbTab & QPEncode(CStr(Point.X)) & _ vbTab & QPEncode(CStr(Point.Y)) & vbTab & _ QPEncode(CStr(Comp.Orientation)) & vbTab & QPEncode(CStr(Comp.Scale)) & _ vbTab & QPEncode(Connections) & vbCrLf On Error Resume Next QP_Stage = "snapshot_attributes" AttributeText = "" AttributeCount = 0 For Each Attr In Comp.Attributes AttributeText = AttributeText & QPSnapshotAttribute(Uid, Attr) If Err.Number <> 0 Then Exit For AttributeCount = AttributeCount + 1 QPProgress "snapshot_attributes", AttributeCount, 0 If Err.Number <> 0 Then Exit For Next ErrorNumber = Err.Number ErrorSource = Err.Source ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then If Len(ErrorSource) = 0 Then _ ErrorSource = "QuickPartReplace.AttributeEnumeration" Err.Raise ErrorNumber, ErrorSource, ErrorDescription End If If Len(AttributeText) = 0 Then Err.Raise vbObjectError + 798, "QuickPartReplace", _ "cannot enumerate every component attribute" End If QPSnapshotComponent = Result & QPSortSnapshotLines(AttributeText) End Function Function QPSortSnapshotLines(ByVal Text) Dim Lines, Index, InnerIndex, Swap Lines = Split(CStr(Text), vbCrLf) For Index = 0 To UBound(Lines) - 1 For InnerIndex = Index + 1 To UBound(Lines) If StrComp(Lines(Index), Lines(InnerIndex), vbBinaryCompare) > 0 Then Swap = Lines(Index) Lines(Index) = Lines(InnerIndex) Lines(InnerIndex) = Swap End If Next Next QPSortSnapshotLines = "" For Index = 0 To UBound(Lines) If Len(Lines(Index)) > 0 Then QPSortSnapshotLines = QPSortSnapshotLines & Lines(Index) & vbCrLf Next End Function Function QPSnapshotAttribute(ByVal ComponentUid, ByRef Attr) Dim Instance, Point, ErrorNumber, ErrorDescription Dim LocationX Dim LocationY Dim Color Dim Font Dim Size Dim Orientation Dim Visible Instance = Attr.InstanceValue On Error Resume Next Set Point = Attr.GetLocation() LocationX = CStr(Point.X) LocationY = CStr(Point.Y) ErrorNumber = Err.Number ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then Err.Raise ErrorNumber, "QuickPartReplace.Snapshot", _ "Cannot capture " & CStr(Attr.Name) & ".location: " & ErrorDescription Color = QPOptionalAttributeField(Attr, "color") Font = QPOptionalAttributeField(Attr, "font") Size = QPOptionalAttributeField(Attr, "size") Orientation = QPOptionalAttributeField(Attr, "orientation") Visible = QPOptionalAttributeField(Attr, "visible") QPSnapshotAttribute = "A" & vbTab & QPEncode(ComponentUid) & vbTab & _ QPEncode(CStr(Attr.Name)) & vbTab & QPEncode(CStr(Attr.Value)) & _ vbTab & QPEncode(CStr(Instance)) & vbTab & QPEncode(LocationX) & _ vbTab & QPEncode(LocationY) & vbTab & QPEncode(Color) & _ vbTab & QPEncode(Font) & vbTab & QPEncode(Size) & vbTab & _ QPEncode(Orientation) & vbTab & QPEncode(Visible) & vbCrLf End Function Function QPOptionalAttributeField(ByRef Attr, ByVal FieldName) Dim Point Dim Value Dim ErrorNumber Dim ErrorSource Dim ErrorDescription On Error Resume Next Select Case CStr(FieldName) Case "location_x" Set Point = Attr.GetLocation() Value = CStr(Point.X) Case "location_y" Set Point = Attr.GetLocation() Value = CStr(Point.Y) Case "color" Value = CStr(Attr.Color) Case "font" Value = CStr(Attr.Font) Case "size" Value = CStr(Attr.Size) Case "orientation" Value = CStr(Attr.Orientation) Case "visible" Value = CStr(Attr.Visible) Case Else Err.Raise vbObjectError + 826, "QuickPartReplace", _ "unknown optional attribute field" End Select ErrorNumber = Err.Number ErrorSource = Err.Source ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then Err.Raise ErrorNumber, "QuickPartReplace.Snapshot", _ "Cannot capture " & CStr(Attr.Name) & "." & FieldName & ": " & ErrorDescription Else QPOptionalAttributeField = Value End If End Function Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath) Dim Records, Meta, ComponentRecord, Candidate, Plans, Used, Index Dim BeforeRestore, AfterRestore, ErrorNumber, ErrorDescription, UndoResult, SuccessMessage, ReplacementSummary QPInvalidatePinIndex QPInvalidateComponentIndex QP_NcSyncSummary = "" QPProgress "restore_preflight", 0, 0 Set Records = QPReadSnapshot(SnapshotPath) QPRequireCommandSnapshot Command, SnapshotPath ' Owned batches perform full-page checks immediately before saving and ' after disk reopen in QPFinishBatchItem, before publishing completion. ' Manual restoration keeps full checks on both sides of its writes. If Not QP_BatchMode Then QPVerifyUntouched Records Set Meta = Records.Item("meta") If QPCanonicalPath(CStr(Meta("project_path"))) <> QPCanonicalPath(QPProjectPath()) Or _ CStr(Meta("sheet_name")) <> QPSheetIdentity() Then _ Err.Raise vbObjectError + 799, "QuickPartReplace", "snapshot project or sheet mismatch" If CStr(Meta("old_part_number")) <> CStr(Command("old_part_number")) Or _ CStr(Meta("new_part_number")) <> CStr(Command("new_part_number")) Then _ Err.Raise vbObjectError + 830, "QuickPartReplace", "snapshot rule mismatch" If QPValueMode(Meta) <> QPValueMode(Command) Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "snapshot Value policy mismatch" If QPCustomValue(Meta) <> QPCustomValue(Command) Or _ QPSyncNc(Meta) <> QPSyncNc(Command) Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "snapshot Value or NC option mismatch" Set Plans = CreateObject("Scripting.Dictionary") Set Used = CreateObject("Scripting.Dictionary") BeforeRestore = "" For Index = 0 To Records.Item("components").Count - 1 Set ComponentRecord = Records.Item("components").Item(CStr(Index)) Set Candidate = QPFindUniqueByOldLocation(ComponentRecord) If Used.Exists(CStr(Candidate.UID)) Then _ Err.Raise vbObjectError + 831, "QuickPartReplace", "duplicate replacement association" Used.Add CStr(Candidate.UID), True QPRestorePreflight Candidate, ComponentRecord, Records.Item("attributes"), _ CStr(Command("new_part_number")), QPValueMode(Command) Plans.Add CStr(Index), Candidate BeforeRestore = BeforeRestore & QPSnapshotComponent(Candidate) QPProgress "restore_preflight", Index + 1, Records.Item("components").Count Next QPProgress "before_restore_transaction", 0, Plans.Count QPMarkBatchMutation Command QP_RestoreTransactionOpen = True QP_App.ActiveView.Block.StartUndoTransaction On Error Resume Next QPRestorePlans Command, Records, Plans ErrorNumber = Err.Number ErrorDescription = Err.Description Err.Clear QP_App.ActiveView.Block.EndUndoTransaction If Err.Number <> 0 Then ErrorNumber = Err.Number ErrorDescription = "Cannot end restoration transaction: " & Err.Description Else QP_RestoreTransactionOpen = False End If Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then QPInvalidatePinIndex AfterRestore = "" For Index = 0 To Plans.Count - 1 Set Candidate = Plans.Item(CStr(Index)) AfterRestore = AfterRestore & QPSnapshotComponent(Candidate) QPProgress "inspect_restore_failure", Index + 1, Plans.Count Next If AfterRestore <> BeforeRestore Then QPRequireSnapshotContext SnapshotPath UndoResult = QP_App.ExecuteCommand("undo") QPInvalidatePinIndex AfterRestore = "" For Index = 0 To Records.Item("components").Count - 1 Set ComponentRecord = Records.Item("components").Item(CStr(Index)) Set Candidate = QPFindUniqueByOldLocation(ComponentRecord) AfterRestore = AfterRestore & QPSnapshotComponent(Candidate) QPProgress "verify_restore_rollback", Index + 1, Records.Item("components").Count Next If AfterRestore <> BeforeRestore Then _ Err.Raise vbObjectError + 832, "QuickPartReplace", "RESTORE ROLLBACK UNVERIFIED; do not save. " & ErrorDescription End If Err.Raise ErrorNumber, "QuickPartReplace", "Restoration failed; native replacement remains, do not save. " & ErrorDescription End If ReplacementSummary = QPReplacementSummary(Records, Plans, CStr(Command("old_part_number")), _ CStr(Command("new_part_number"))) SuccessMessage = "Native replacement and parameter readback passed on current sheet. Replacements: " & _ ReplacementSummary & " " & QPDisplayVerificationSummary(Records) If Len(QPTargetCell(Command)) > 0 Then SuccessMessage = SuccessMessage & _ " Target Cell verified: " & QPTargetCell(Command) & "." If Len(QP_NcSyncSummary) > 0 Then SuccessMessage = SuccessMessage & _ " NC synced: " & QP_NcSyncSummary QPWriteStatus QP_Root, CStr(Command("job_id")), "restored_ok", "", SuccessMessage QPLog QP_Root, "INFO", "verified replacement count=" & Plans.Count & " value_mode=" & QPValueMode(Command) End Sub Function QPReplacementSummary(ByRef Records, ByRef Plans, ByVal OldPartNumber, ByVal NewPartNumber) Dim Index, Candidate, ComponentRecord, Identity, Entry QPReplacementSummary = "" For Index = 0 To Plans.Count - 1 Set Candidate = Plans.Item(CStr(Index)) Set ComponentRecord = Records.Item("components").Item(CStr(Index)) Identity = CStr(ComponentRecord("refdes")) If Len(Identity) = 0 Then Identity = "UID=" & CStr(ComponentRecord("uid")) Entry = QPLogField(Identity) & " " & QPLogField(OldPartNumber) & _ " -> " & QPLogField(NewPartNumber) If Len(QPReplacementSummary) > 0 Then QPReplacementSummary = QPReplacementSummary & "; " QPReplacementSummary = QPReplacementSummary & Entry QPLog QP_Root, "INFO", "replacement " & Entry Next End Function Sub QPRestorePlans(ByRef Command, ByRef Records, ByRef Plans) Dim Index, ComponentRecord, Candidate, AttributeIndex, Record, Attr, ValueStates Set ValueStates = CreateObject("Scripting.Dictionary") For Index = 0 To Plans.Count - 1 Set ComponentRecord = Records.Item("components").Item(CStr(Index)) Set Candidate = Plans.Item(CStr(Index)) ValueStates.Add CStr(Index), QPCaptureValueState(Candidate) QPSetRequiredNc ValueStates.Item(CStr(Index)), ComponentRecord, Records.Item("attributes"), QPSyncNc(Command) ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command) QPRestoreComponent Candidate, ComponentRecord, Records.Item("attributes"), _ QPValueMode(Command), QPCustomValue(Command), QPSyncNc(Command) QPSetTargetCell Candidate, Command QPProgress "restore_attributes", Index + 1, Plans.Count Next QPVerifyRestoredPlans Command, Records, Plans, ValueStates If Not QP_BatchMode Then QPVerifyUntouched Records End Sub Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef ValueStates) Dim Index, ComponentRecord, Candidate, AttributeIndex, Record, Attr, Before QPProgress "verify_restoration", 0, Plans.Count For Index = 0 To Plans.Count - 1 Set ComponentRecord = Records.Item("components").Item(CStr(Index)) Set Candidate = Plans.Item(CStr(Index)) QPVerifyTargetCell Candidate, Command ' Captured only after native library identity validation (or recovery ' command validation), before restoration/save; never derive this expected ' identity from the reopened result or from its current Value. Set Before = ValueStates.Item(CStr(Index)) If QPRequiredAttributeValue(Candidate, "Part Name") <> CStr(Before("part_name")) Or _ QPEffectiveComponentAttribute(Candidate, "Part Label") <> CStr(Before("part_label")) Then _ Err.Raise vbObjectError + 865, "QuickPartReplace", "target library identity changed during restoration or save" QPRestorePreflight Candidate, ComponentRecord, Records.Item("attributes"), _ CStr(Command("new_part_number")), QPValueMode(Command) QPVerifyTransform Candidate, ComponentRecord For AttributeIndex = 0 To Records.Item("attributes").Count - 1 Set Record = Records.Item("attributes").Item(CStr(AttributeIndex)) If CStr(Record("uid")) = CStr(ComponentRecord("uid")) Then Set Attr = QPFindCurrentAttribute(Candidate, CStr(Record("name"))) If Attr Is Nothing Then If Not QPNativeAttributeAbsenceAllowed(CStr(Record("name")), QPValueMode(Command)) Then _ Err.Raise vbObjectError + 840, "QuickPartReplace", "final attribute missing" Else QPVerifyDisplay Attr, Record, CStr(ComponentRecord("refdes")) If QPIsInstanceAttribute(CStr(Record("name"))) Then If QPEffectiveAttributeValue(Attr) <> QPSavedEffectiveValue(Record) Then _ Err.Raise vbObjectError + 834, "QuickPartReplace", "final instance value mismatch" End If End If QPProgress "verify_attribute_fields", AttributeIndex + 1, Records.Item("attributes").Count End If Next QPVerifyValuePolicy Candidate, QPValueMode(Command), ValueStates.Item(CStr(Index)) QPProgress "verify_restoration", Index + 1, Plans.Count Next End Sub Sub QPRecoverSavedJob(ByRef Command, ByVal SnapshotPath) Dim Records, Plans, Used, ValueStates, Index, Record, Candidate, PartNumber Dim OldCount, NewCount, ErrorNumber, ErrorDescription, RecoveryDocuments, RecoveryDocument, RecoveryProjectData QPRequireCommandSnapshot Command, SnapshotPath If Len(QPTargetCell(Command)) > 0 Then If Not Command.Exists("recovery_library_path") Then _ Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "recovery Cell library proof missing" If QPCanonicalPath(CStr(QP_App.GetProjectData().CentralLibraryPath)) <> _ QPCanonicalPath(QPDecode(CStr(Command("recovery_library_path")))) Then _ Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "recovery active library changed" End If Set Records = QPReadSnapshot(SnapshotPath) QPVerifyUntouched Records Set Plans = CreateObject("Scripting.Dictionary") Set Used = CreateObject("Scripting.Dictionary") Set ValueStates = CreateObject("Scripting.Dictionary") OldCount = 0 NewCount = 0 QPInvalidatePinIndex For Index = 0 To Records.Item("components").Count - 1 QPRequireSnapshotContext SnapshotPath Set Record = Records.Item("components").Item(CStr(Index)) Set Candidate = QPFindUniqueByOldLocation(Record) If CStr(Candidate.UID) <> CStr(Record("uid")) Or Used.Exists(CStr(Candidate.UID)) Then _ Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "saved component UID changed or duplicated" Used.Add CStr(Candidate.UID), True PartNumber = QPRequiredAttributeValue(Candidate, "Part Number") If StrComp(PartNumber, CStr(Command("old_part_number")), vbTextCompare) = 0 Then OldCount = OldCount + 1 QPRestorePreflight Candidate, Record, Records.Item("attributes"), _ CStr(Command("old_part_number")), "preserve" QPVerifyOriginalComponent Candidate, Record, Records.Item("attributes") ElseIf StrComp(PartNumber, CStr(Command("new_part_number")), vbTextCompare) = 0 Then NewCount = NewCount + 1 If StrComp(QPRequiredAttributeValue(Candidate, "Part Name"), _ CStr(Command("recovery_part_name")), vbBinaryCompare) <> 0 Then _ Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "saved target library identity differs" If Len(CStr(Command("recovery_part_label"))) > 0 Or _ QPValueMode(Command) = "part_label" Or QPValueMode(Command) = "legacy_part_label" Then If StrComp(QPEffectiveComponentAttribute(Candidate, "Part Label"), _ CStr(Command("recovery_part_label")), vbBinaryCompare) <> 0 Then _ Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "saved target library identity differs" End If QPRestorePreflight Candidate, Record, Records.Item("attributes"), _ CStr(Command("new_part_number")), QPValueMode(Command) Else Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "saved component is neither source nor target" End If Plans.Add CStr(Index), Candidate ValueStates.Add CStr(Index), QPCaptureValueState(Candidate) QPSetRequiredNc ValueStates.Item(CStr(Index)), Record, Records.Item("attributes"), QPSyncNc(Command) ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command) QPProgress "recovery_preflight", Index + 1, Records.Item("components").Count Next If OldCount > 0 And NewCount > 0 Then _ Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "mixed source and target components; no recovery writes performed" If OldCount = Plans.Count Then QPRequireCommandSnapshot Command, SnapshotPath Set RecoveryDocuments = QP_App.SchematicSheetDocuments() If RecoveryDocuments.Count <> 1 Then _ Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "read-only recovery document ownership changed" Set RecoveryDocument = RecoveryDocuments.Item(1) RecoveryDocument.Close False, "" QP_App.CloseProject Set RecoveryProjectData = QP_App.GetProjectData() If Not RecoveryProjectData Is Nothing Then If Len(CStr(RecoveryProjectData.GetProjectFilePath())) <> 0 Then _ Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "read-only recovery project did not close" End If QPWriteStatus QP_Root, QP_CurrentJobId, "retry_ready", "", "Saved source matches snapshot; replacement was not persisted." Exit Sub End If On Error Resume Next QPVerifyRestoredPlans Command, Records, Plans, ValueStates ErrorNumber = Err.Number ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber = 0 Then If QP_BatchMode Then If QP_SessionMode Then Err.Raise vbObjectError + 865, _ "QuickPartReplace.Recovery", "read-only recovery cannot reuse a project session" ' A fresh owned recovery session has already verified the disk state. ' Closing without saving avoids a second save/reopen cycle for no writes. QPRequireCommandSnapshot Command, SnapshotPath QPCloseBatchProject CStr(Command("project_path")), False QP_BatchMode = False QPWriteStatus QP_Root, QP_CurrentJobId, "restored_ok", "recovery_saved_verified", _ "Saved replacement verified from disk and owned project closed without additional saving." Else QPWriteStatus QP_Root, QP_CurrentJobId, "restored_ok", "recovery_verified", "Saved replacement already passes all restoration checks; no CAD writes." End If Else If ErrorNumber <> vbObjectError + 833 And ErrorNumber <> vbObjectError + 834 And _ ErrorNumber <> vbObjectError + 837 And ErrorNumber <> vbObjectError + 840 And _ ErrorNumber <> vbObjectError + 818 And ErrorNumber <> vbObjectError + 806 Then _ Err.Raise ErrorNumber, "QuickPartReplace.Recovery", ErrorDescription QPRequireCommandSnapshot Command, SnapshotPath QPLog QP_Root, "INFO", "recovery_restore_only reason=" & QPLogField(ErrorDescription) QPRestoreAfterOperatorReplace Command, SnapshotPath End If End Sub Sub QPVerifyOriginalComponent(ByRef Comp, ByRef ComponentRecord, ByRef Attributes) Dim Index, Record, Attr, SavedCount, ActualCount QPVerifyTransform Comp, ComponentRecord SavedCount = 0 For Index = 0 To Attributes.Count - 1 Set Record = Attributes.Item(CStr(Index)) If CStr(Record("uid")) = CStr(ComponentRecord("uid")) Then SavedCount = SavedCount + 1 Set Attr = QPFindCurrentAttribute(Comp, CStr(Record("name"))) If Attr Is Nothing Then Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "source attribute missing" QPVerifyDisplay Attr, Record, CStr(ComponentRecord("refdes")) If CStr(Attr.Value) <> CStr(Record("value")) Or CStr(Attr.InstanceValue) <> CStr(Record("instance_value")) Then _ Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "source attribute value differs from snapshot" End If Next ActualCount = 0 For Each Attr In Comp.Attributes ActualCount = ActualCount + 1 Next If ActualCount <> SavedCount Then Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "source attribute set changed" End Sub Function QPSavedEffectiveValue(ByRef Record) QPSavedEffectiveValue = CStr(Record("instance_value")) If Len(QPSavedEffectiveValue) = 0 Then QPSavedEffectiveValue = CStr(Record("value")) End Function Sub QPRestorePreflight(ByRef Comp, ByRef ComponentRecord, _ ByRef Attributes, ByVal NewPartNumber, ByVal ValueMode) Dim Index Dim Record Dim LabelAttr Dim ValueAttr Dim ValueRecord Dim HasOldValue Dim LabelValue Dim CurrentConnections Dim SavedConnections If CStr(Comp.UID) <> CStr(ComponentRecord("uid")) Or _ CStr(Comp.Refdes) <> CStr(ComponentRecord("refdes")) Then _ Err.Raise vbObjectError + 831, "QuickPartReplace", "replacement component UID or Refdes differs from snapshot; no restoration writes allowed" If StrComp(QPRequiredAttributeValue(Comp, "Part Number"), _ CStr(NewPartNumber), vbTextCompare) <> 0 Then Err.Raise vbObjectError + 800, "QuickPartReplace", _ "replacement Part Number does not equal command target" End If CurrentConnections = QPConnectionSignature(Comp) SavedConnections = CStr(ComponentRecord("connections")) If Not QPConnectionsMatch(CurrentConnections, SavedConnections) Then QPLog QP_Root, "ERROR", "connection_mismatch uid=" & _ CStr(ComponentRecord("uid")) & " saved=" & _ QPLogField(SavedConnections) & " current=" & _ QPLogField(CurrentConnections) Err.Raise vbObjectError + 804, "QuickPartReplace", _ "connection validation failed" End If If ValueMode = "preserve" Or ValueMode = "custom" Then Exit Sub HasOldValue = False Set ValueRecord = Nothing For Index = 0 To Attributes.Count - 1 Set Record = Attributes.Item(CStr(Index)) If CStr(Record("uid")) = CStr(ComponentRecord("uid")) And _ StrComp(CStr(Record("name")), "Value", vbTextCompare) = 0 Then HasOldValue = True Set ValueRecord = Record End If Next Set LabelAttr = QPFindCurrentAttribute(Comp, "Part Label") If LabelAttr Is Nothing Then Err.Raise vbObjectError + 805, "QuickPartReplace", _ "Part Label readback failed: attribute is unavailable; refdes=" & _ QPComponentIdentity(Comp) & "; uid=" & CStr(Comp.UID) End If LabelValue = QPEffectiveAttributeValue(LabelAttr) If Len(LabelValue) = 0 Then Err.Raise vbObjectError + 805, _ "QuickPartReplace", "Part Label readback failed: value is blank; refdes=" & _ QPComponentIdentity(Comp) & "; uid=" & CStr(Comp.UID) Set ValueAttr = QPFindCurrentAttribute(Comp, "Value") If ValueAttr Is Nothing Then If Not HasOldValue Or ValueRecord Is Nothing Then Set ValueRecord = QPHiddenValueStyle(LabelAttr) End If End Sub Function QPFindUniqueByOldLocation(ByRef ComponentRecord) Dim Bucket, Key QPEnsureComponentIndex Key = CStr(ComponentRecord("uid")) If QP_ComponentUidIndex.Exists(Key) Then Set Bucket = QP_ComponentUidIndex.Item(Key) If Bucket.Count > 1 Then Err.Raise vbObjectError + 802, "QuickPartReplace", "ambiguous replacement association" Set QPFindUniqueByOldLocation = Bucket.Item("0") Exit Function End If Key = CStr(ComponentRecord("refdes")) If QP_ComponentRefdesIndex Is Nothing Then _ Set QP_ComponentRefdesIndex = QPBuildComponentAssociationIndex(False) If Len(Key) > 0 And QP_ComponentRefdesIndex.Exists(Key) Then Set Bucket = QP_ComponentRefdesIndex.Item(Key) If Bucket.Count > 1 Then Err.Raise vbObjectError + 802, "QuickPartReplace", "ambiguous replacement association" Set QPFindUniqueByOldLocation = Bucket.Item("0") Exit Function End If Key = CStr(ComponentRecord("x")) & "|" & CStr(ComponentRecord("y")) If QP_ComponentLocationIndex Is Nothing Then _ Set QP_ComponentLocationIndex = QPBuildComponentAssociationIndex(True) If QP_ComponentLocationIndex.Exists(Key) Then Set Bucket = QP_ComponentLocationIndex.Item(Key) If Bucket.Count > 1 Then Err.Raise vbObjectError + 802, "QuickPartReplace", "ambiguous replacement association" Set QPFindUniqueByOldLocation = Bucket.Item("0") Exit Function End If Err.Raise vbObjectError + 802, "QuickPartReplace", "replacement component not found" End Function Function QPDisplayVerificationSummary(ByRef Records) Dim Colors, Index, Record, Color, Text, Key Set Colors = CreateObject("Scripting.Dictionary") For Index = 0 To Records.Item("attributes").Count - 1 Set Record = Records.Item("attributes").Item(CStr(Index)) Color = CStr(Record("color")) If Colors.Exists(Color) Then Colors(Color) = Colors(Color) + 1 Else Colors.Add Color, 1 End If Next Text = "" For Each Key In Colors.Keys If Len(Text) > 0 Then Text = Text & "," Text = Text & QPLogField(CStr(Key)) & "(" & CStr(Colors(Key)) & ")" Next QPDisplayVerificationSummary = "Display verified: attributes=" & _ CStr(Records.Item("attributes").Count) & "; colors=" & Text & "." End Function Sub QPVerifyTransform(ByRef Comp, ByRef Record) Dim Point, Mismatch, ToleratedDrift, ActualRefdes Set Point = Comp.GetLocation() ActualRefdes = CStr(Comp.Refdes) Mismatch = "" ToleratedDrift = "" If Abs(CDbl(Point.X) - CDbl(Record("x"))) > QP_COMPONENT_COORDINATE_TOLERANCE Then Mismatch = Mismatch & " x=" & CStr(Record("x")) & "->" & CStr(Point.X) ElseIf CDbl(Point.X) <> CDbl(Record("x")) Then ToleratedDrift = ToleratedDrift & " x=" & CStr(Record("x")) & "->" & CStr(Point.X) End If If Abs(CDbl(Point.Y) - CDbl(Record("y"))) > QP_COMPONENT_COORDINATE_TOLERANCE Then Mismatch = Mismatch & " y=" & CStr(Record("y")) & "->" & CStr(Point.Y) ElseIf CDbl(Point.Y) <> CDbl(Record("y")) Then ToleratedDrift = ToleratedDrift & " y=" & CStr(Record("y")) & "->" & CStr(Point.Y) End If If CDbl(Comp.Orientation) <> CDbl(Record("orientation")) Then Mismatch = Mismatch & " orientation=" & CStr(Record("orientation")) & "->" & CStr(Comp.Orientation) If CDbl(Comp.Scale) <> CDbl(Record("scale")) Then Mismatch = Mismatch & " scale=" & CStr(Record("scale")) & "->" & CStr(Comp.Scale) If StrComp(ActualRefdes, CStr(Record("refdes")), vbBinaryCompare) <> 0 Then Mismatch = Mismatch & " refdes=" & CStr(Record("refdes")) & "->" & ActualRefdes If Len(ToleratedDrift) > 0 Then QPLog QP_Root, "WARN", "transform_coordinate_tolerated uid=" & QPLogField(CStr(Record("uid"))) & _ " refdes=" & QPLogField(CStr(Record("refdes"))) & " tolerance=" & _ CStr(QP_COMPONENT_COORDINATE_TOLERANCE) & " fields=" & QPLogField(Trim(ToleratedDrift)) End If If Len(Mismatch) > 0 Then QPLog QP_Root, "ERROR", "transform_mismatch uid=" & QPLogField(CStr(Record("uid"))) & _ " refdes=" & QPLogField(CStr(Record("refdes"))) & " fields=" & QPLogField(Trim(Mismatch)) Err.Raise vbObjectError + 833, "QuickPartReplace", _ "component transform or Refdes readback failed: uid=" & CStr(Record("uid")) & _ " refdes=" & CStr(Record("refdes")) & " fields=" & Trim(Mismatch) End If End Sub Function QPIsInstanceAttribute(ByVal Name) Dim LowerName LowerName = LCase(CStr(Name)) QPIsInstanceAttribute = (LowerName = "comment" Or LowerName = "notes" Or Left(LowerName, 5) = "user_") End Function Sub QPRestoreComponent(ByRef Comp, ByRef ComponentRecord, ByRef Attributes, _ ByVal ValueMode, ByVal CustomValue, ByVal SyncNc) Dim Index Dim Record Dim Attr Dim LabelAttr Dim LabelValue Dim ValueAttr Dim ValueRecord Dim Point Dim ErrorNumber Dim ErrorSource Dim ErrorDescription Dim ValueX Dim ValueY Dim ValueVisible Dim DefaultedFields Dim HasOldNc Comp.Orientation = CLng(ComponentRecord("orientation")) Comp.Scale = CDbl(ComponentRecord("scale")) Comp.SetLocation CLng(ComponentRecord("x")), CLng(ComponentRecord("y")) Comp.Refdes = CStr(ComponentRecord("refdes")) If StrComp(CStr(Comp.Refdes), CStr(ComponentRecord("refdes")), _ vbBinaryCompare) <> 0 Then Err.Raise vbObjectError + 803, "QuickPartReplace", "Refdes restore failed" End If LabelValue = "" HasOldNc = False Set ValueRecord = Nothing For Index = 0 To Attributes.Count - 1 Set Record = Attributes.Item(CStr(Index)) If CStr(Record("uid")) = CStr(ComponentRecord("uid")) Then Set Attr = QPFindCurrentAttribute(Comp, CStr(Record("name"))) If StrComp(CStr(Record("name")), "Value", vbTextCompare) = 0 Then Set ValueRecord = Record HasOldNc = CBool(SyncNc) And QPValueHasNcMarker(QPSavedEffectiveValue(Record)) End If If QPIsInstanceAttribute(CStr(Record("name"))) Then If Attr Is Nothing Then Set Attr = Comp.AddAttribute(CStr(Record("name")) & "=" & CStr(Record("value")), _ CLng(Record("x")), CLng(Record("y")), CLng(Record("visible"))) If Len(CStr(Record("instance_value"))) > 0 Then Attr.InstanceValue = CStr(Record("instance_value")) Else Attr.InstanceValue = CStr(Record("value")) End If If QPEffectiveAttributeValue(Attr) <> QPSavedEffectiveValue(Record) Then _ Err.Raise vbObjectError + 834, "QuickPartReplace", "instance attribute readback failed" End If If Attr Is Nothing Then If Not QPNativeAttributeAbsenceAllowed(CStr(Record("name")), ValueMode) Then _ Err.Raise vbObjectError + 835, "QuickPartReplace", "target is missing original display attribute: " & CStr(Record("name")) Else QPRestoreDisplay Attr, Record, CStr(ComponentRecord("refdes")) End If QPProgress "restore_attribute_fields", Index + 1, Attributes.Count End If Next Set ValueAttr = QPFindCurrentAttribute(Comp, "Value") If ValueMode = "preserve" Then If Not HasOldNc Then Exit Sub If Not ValueAttr Is Nothing Then LabelValue = QPEffectiveAttributeValue(ValueAttr) If QPValueHasNcMarker(LabelValue) Then QPRecordNcSync Comp, QPSavedEffectiveValue(ValueRecord), LabelValue Exit Sub End If End If LabelValue = QPAppendNcMarker(LabelValue) Else Set LabelAttr = QPFindCurrentAttribute(Comp, "Part Label") If ValueMode = "custom" Then LabelValue = CStr(CustomValue) ElseIf ValueMode = "part_number" Then LabelValue = QPRequiredAttributeValue(Comp, "Part Number") Else If LabelAttr Is Nothing Then Err.Raise vbObjectError + 805, "QuickPartReplace", _ "Part Label readback failed: attribute is unavailable; refdes=" & _ QPComponentIdentity(Comp) & "; uid=" & CStr(Comp.UID) End If LabelValue = QPEffectiveAttributeValue(LabelAttr) End If If Len(LabelValue) = 0 Then Err.Raise vbObjectError + 805, _ "QuickPartReplace", "Part Label readback failed: selected Value source is blank; refdes=" & _ QPComponentIdentity(Comp) & "; uid=" & CStr(Comp.UID) If HasOldNc Then LabelValue = QPAppendNcMarker(LabelValue) End If If ValueAttr Is Nothing Then If ValueRecord Is Nothing Then If LabelAttr Is Nothing Then Set ValueRecord = QPDefaultValueStyle(Comp) Else Set ValueRecord = QPHiddenValueStyle(LabelAttr) End If End If DefaultedFields = "" If Len(CStr(ValueRecord("x"))) = 0 Or Len(CStr(ValueRecord("y"))) = 0 Then Set Point = Comp.GetLocation() End If If Len(CStr(ValueRecord("x"))) = 0 Then ValueX = Point.X DefaultedFields = "x" Else ValueX = ValueRecord("x") End If If Len(CStr(ValueRecord("y"))) = 0 Then ValueY = Point.Y If Len(DefaultedFields) > 0 Then DefaultedFields = DefaultedFields & "," DefaultedFields = DefaultedFields & "y" Else ValueY = ValueRecord("y") End If If Len(CStr(ValueRecord("visible"))) = 0 Then ValueVisible = 1 If Len(DefaultedFields) > 0 Then DefaultedFields = DefaultedFields & "," DefaultedFields = DefaultedFields & "visible" Else ValueVisible = ValueRecord("visible") End If If Len(DefaultedFields) > 0 Then QPLog QP_Root, "WARN", "value_style_defaulted fields=" & DefaultedFields End If Set ValueAttr = Comp.AddAttribute("Value=" & LabelValue, _ CLng(ValueX), CLng(ValueY), CLng(ValueVisible)) QPRestoreDisplay ValueAttr, ValueRecord, CStr(ComponentRecord("refdes")) Else On Error Resume Next ValueAttr.InstanceValue = LabelValue ErrorNumber = Err.Number ErrorSource = Err.Source ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then If Len(ErrorSource) = 0 Then ErrorSource = "QuickPartReplace.Value" Err.Raise ErrorNumber, ErrorSource, ErrorDescription End If End If If StrComp(QPEffectiveAttributeValue(ValueAttr), LabelValue, _ vbBinaryCompare) <> 0 Then Err.Raise vbObjectError + 818, "QuickPartReplace", _ "Value readback does not equal the selected source" End If If HasOldNc Then QPRecordNcSync Comp, QPSavedEffectiveValue(ValueRecord), _ QPEffectiveAttributeValue(ValueAttr) End Sub Function QPComponentIdentity(ByRef Comp) QPComponentIdentity = CStr(Comp.Refdes) If Len(Trim(QPComponentIdentity)) = 0 Then _ QPComponentIdentity = "UID=" & CStr(Comp.UID) End Function Function QPNativeAttributeAbsenceAllowed(ByVal Name, ByVal ValueMode) QPNativeAttributeAbsenceAllowed = _ (StrComp(CStr(Name), "Value", vbTextCompare) = 0) If QPNativeAttributeAbsenceAllowed Or ValueMode <> "preserve" Then Exit Function QPNativeAttributeAbsenceAllowed = _ (StrComp(CStr(Name), "Part Label", vbTextCompare) = 0) End Function Function QPValueHasNcMarker(ByVal Value) Dim Parts, Index QPValueHasNcMarker = False If InStr(CStr(Value), "/") = 0 Then Exit Function Parts = Split(CStr(Value), "/") For Index = 1 To UBound(Parts) If StrComp(Trim(CStr(Parts(Index))), "NC", vbTextCompare) = 0 Then QPValueHasNcMarker = True Exit Function End If Next End Function Function QPAppendNcMarker(ByVal Value) QPAppendNcMarker = RTrim(CStr(Value)) If QPValueHasNcMarker(QPAppendNcMarker) Then Exit Function If Len(QPAppendNcMarker) = 0 Then QPAppendNcMarker = "/NC" ElseIf Right(QPAppendNcMarker, 1) = "/" Then QPAppendNcMarker = QPAppendNcMarker & "NC" Else QPAppendNcMarker = QPAppendNcMarker & "/NC" End If End Function Sub QPSetRequiredNc(ByRef State, ByRef ComponentRecord, ByRef Attributes, ByVal Enabled) Dim Index, Record State("nc_required") = False If Not CBool(Enabled) Then Exit Sub For Index = 0 To Attributes.Count - 1 Set Record = Attributes.Item(CStr(Index)) If CStr(Record("uid")) = CStr(ComponentRecord("uid")) And _ StrComp(CStr(Record("name")), "Value", vbTextCompare) = 0 Then State("nc_required") = QPValueHasNcMarker(QPSavedEffectiveValue(Record)) Exit Sub End If Next End Sub Sub QPRecordNcSync(ByRef Comp, ByVal OldValue, ByVal NewValue) Dim Entry Entry = QPLogField(CStr(Comp.Refdes)) & " " & QPLogField(OldValue) & _ " -> " & QPLogField(NewValue) & " (detected /NC and synchronized)" If Len(QP_NcSyncSummary) > 0 Then QP_NcSyncSummary = QP_NcSyncSummary & "; " QP_NcSyncSummary = QP_NcSyncSummary & Entry QPLog QP_Root, "INFO", "nc_sync " & Entry End Sub Sub QPRequireCommandSnapshot(ByRef Command, ByVal SnapshotPath) Dim Records, Meta Set Records = QPReadSnapshot(SnapshotPath) Set Meta = Records.Item("meta") QPRequireRecordsContext Records If CStr(Meta("old_part_number")) <> CStr(Command("old_part_number")) Or _ CStr(Meta("new_part_number")) <> CStr(Command("new_part_number")) Then _ Err.Raise vbObjectError + 830, "QuickPartReplace", "snapshot rule mismatch" If QPValueMode(Meta) <> QPValueMode(Command) Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "snapshot Value policy mismatch" If QPTargetCell(Meta) <> QPTargetCell(Command) Then _ Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "target Cell changed since snapshot" If QPCustomValue(Meta) <> QPCustomValue(Command) Or _ QPSyncNc(Meta) <> QPSyncNc(Command) Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "snapshot Value or NC option mismatch" If Command.Exists("target_scope") Then If CStr(Command("target_scope")) = "targets" Then If Not Meta.Exists("target_scope") Then Err.Raise vbObjectError + 873, _ "QuickPartReplace.Target", "target selector missing from snapshot" If CStr(Meta("target_scope")) <> "targets" Or _ CStr(Meta("target_selectors")) <> CStr(Command("target_selectors")) Then _ Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "target selector changed since snapshot" ElseIf Meta.Exists("target_scope") Then Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "snapshot scope changed" End If ElseIf Meta.Exists("target_scope") Then Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "target scope missing from command" End If End Sub Function QPTargetCell(ByRef Record) Dim Value, Index QPTargetCell = "" If Not Record.Exists("target_cell") Then Exit Function Value = QPDecode(CStr(Record("target_cell"))) If Len(Value) = 0 Then Exit Function If Trim(Value) <> Value Then _ Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "target Cell selection is invalid" For Index = 1 To Len(Value) If AscW(Mid(Value, Index, 1)) >= 0 And AscW(Mid(Value, Index, 1)) < 32 Then _ Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "invalid control character in target Cell" Next QPTargetCell = Value End Function Sub QPSetTargetCell(ByRef Comp, ByRef Command) Dim Value, Attr Value = QPTargetCell(Command) If Len(Value) = 0 Then Exit Sub Set Attr = QPFindCurrentAttribute(Comp, "Cell Name") If Attr Is Nothing Then Err.Raise vbObjectError + 878, _ "QuickPartReplace.Cell", "replaced target has no Cell Name attribute" Attr.InstanceValue = Value QPVerifyTargetCell Comp, Command End Sub Sub QPVerifyTargetCell(ByRef Comp, ByRef Command) Dim Value Value = QPTargetCell(Command) If Len(Value) = 0 Then Exit Sub If QPRequiredAttributeValue(Comp, "Cell Name") <> Value Then _ Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "effective target Cell does not match explicit selection" End Sub Function QPValueMode(ByRef Record) QPValueMode = "legacy_part_label" If Not Record.Exists("value_mode") Then Exit Function QPValueMode = CStr(Record("value_mode")) If QPValueMode <> "preserve" And QPValueMode <> "part_label" And _ QPValueMode <> "part_number" And QPValueMode <> "custom" Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "invalid Value policy" End Function Function QPCustomValue(ByRef Record) QPCustomValue = "" If Record.Exists("custom_value") Then QPCustomValue = CStr(Record("custom_value")) If QPValueMode(Record) = "custom" And Len(QPCustomValue) = 0 Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "custom Value is blank" If QPValueMode(Record) <> "custom" And Len(QPCustomValue) > 0 Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "unexpected custom Value" End Function Function QPSyncNc(ByRef Record) Dim Value QPSyncNc = True If Not Record.Exists("sync_nc") Then Exit Function Value = CStr(Record("sync_nc")) If Value <> "0" And Value <> "1" Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "invalid NC option" QPSyncNc = (Value = "1") End Function Function QPBooleanText(ByVal Value) If CBool(Value) Then QPBooleanText = "1" Else QPBooleanText = "0" End If End Function Function QPCaptureValueState(ByRef Comp) Dim State, Attr Set State = CreateObject("Scripting.Dictionary") Set Attr = QPFindCurrentAttribute(Comp, "Value") State.Add "exists", Not (Attr Is Nothing) State.Add "value", "" State.Add "nc_required", False State.Add "part_name", QPRequiredAttributeValue(Comp, "Part Name") State.Add "part_label", QPEffectiveComponentAttribute(Comp, "Part Label") If Not Attr Is Nothing Then State("value") = QPEffectiveAttributeValue(Attr) Set QPCaptureValueState = State End Function Sub QPVerifyValuePolicy(ByRef Comp, ByVal ValueMode, ByRef Before) Dim Current, SourceName, ExpectedValue, ExpectedExists If ValueMode = "preserve" Then Set Current = QPCaptureValueState(Comp) ExpectedExists = Before("exists") ExpectedValue = Before("value") If Before("nc_required") Then ExpectedExists = True ExpectedValue = QPAppendNcMarker(ExpectedValue) End If If Current("exists") <> ExpectedExists Or Current("value") <> ExpectedValue Then _ Err.Raise vbObjectError + 818, "QuickPartReplace", "native target Value changed while copy was disabled" Else SourceName = "Part Label" If ValueMode = "custom" Then If Not Before.Exists("custom_value") Then _ Err.Raise vbObjectError + 818, "QuickPartReplace", "custom Value verification context is missing" ExpectedValue = CStr(Before("custom_value")) Else If ValueMode = "part_number" Then SourceName = "Part Number" ExpectedValue = QPRequiredAttributeValue(Comp, SourceName) End If If Before("nc_required") Then ExpectedValue = QPAppendNcMarker(ExpectedValue) If QPRequiredAttributeValue(Comp, "Value") <> ExpectedValue Then _ Err.Raise vbObjectError + 818, "QuickPartReplace", "final Value mismatch" End If End Sub Function QPDefaultValueStyle(ByRef Comp) Dim Record, Point Set Record = CreateObject("Scripting.Dictionary") Set Point = Comp.GetLocation() Record.Add "name", "Value" Record.Add "x", CStr(Point.X) Record.Add "y", CStr(Point.Y) Record.Add "color", "0" Record.Add "font", "0" Record.Add "size", "0" Record.Add "orientation", "0" Record.Add "visible", "0" Set QPDefaultValueStyle = Record End Function Function QPHiddenValueStyle(ByRef LabelAttr) Dim Record, Point, Field Set Record = CreateObject("Scripting.Dictionary") Record.Add "name", "Value" Set Point = LabelAttr.GetLocation() Record.Add "x", CStr(Point.X) Record.Add "y", CStr(Point.Y) For Each Field In Array("color", "font", "size", "orientation") Record.Add Field, QPOptionalAttributeField(LabelAttr, Field) Next Record.Add "visible", "0" Set QPHiddenValueStyle = Record End Function Function QPConnectionsMatch(ByVal Current, ByVal Saved) Dim Actual, Expected, Line, Index, ActualLine, SavedLine, OffsetX, OffsetY Set Actual = CreateObject("Scripting.Dictionary") Set Expected = CreateObject("Scripting.Dictionary") QPConnectionsMatch = False For Each Line In Split(CStr(Current), vbLf) If Len(Trim(Line)) > 0 Then If Not QPConnectionLineValid(Line, True) Then Exit Function Actual.Add CStr(Actual.Count), Line End If Next For Each Line In Split(CStr(Saved), vbLf) If Len(Trim(Line)) > 0 Then If Not QPConnectionLineValid(Line, False) Then Exit Function Expected.Add CStr(Expected.Count), Line End If Next If Expected.Count = 0 Or Expected.Count <> Actual.Count Then Exit Function SavedLine = Expected.Item("0") For Index = 0 To Actual.Count - 1 ActualLine = Actual.Item(CStr(Index)) OffsetX = QPConnectionCoordinate(ActualLine, 1) - QPConnectionCoordinate(SavedLine, 1) OffsetY = QPConnectionCoordinate(ActualLine, 2) - QPConnectionCoordinate(SavedLine, 2) If QPConnectionsMatchOffset(Actual, Expected, OffsetX, OffsetY) Then QPConnectionsMatch = True Exit Function End If Next ' Unknown source numbers permit only the same one-to-one physical/net map, ' up to one common translation. Network counts alone cannot prove pin mapping. End Function Function QPConnectionLineValid(ByVal Line, ByVal RequireNumber) Dim Fields, X, Y, ErrorNumber QPConnectionLineValid = False Fields = Split(CStr(Line), "|") If UBound(Fields) <> 3 And UBound(Fields) <> 4 Then Exit Function If UBound(Fields) = 3 Then If CStr(Fields(3)) <> "UNCONNECTED" Then Exit Function Else If Len(CStr(Fields(3))) = 0 Then Exit Function End If If RequireNumber And Len(Trim(CStr(Fields(0)))) = 0 Then Exit Function If Len(Trim(CStr(Fields(1)))) = 0 Or Len(Trim(CStr(Fields(2)))) = 0 Then Exit Function On Error Resume Next X = CDbl(Fields(1)) Y = CDbl(Fields(2)) ErrorNumber = Err.Number Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then Exit Function QPConnectionLineValid = True End Function Function QPConnectionCoordinate(ByVal Line, ByVal FieldIndex) Dim Fields Fields = Split(CStr(Line), "|") QPConnectionCoordinate = CDbl(Fields(FieldIndex)) End Function Function QPConnectionNumber(ByVal Line) Dim Fields Fields = Split(CStr(Line), "|") QPConnectionNumber = CStr(Fields(0)) End Function Function QPConnectionNetIdentity(ByVal Line) Dim Fields Fields = Split(CStr(Line), "|") If UBound(Fields) = 3 Then QPConnectionNetIdentity = "UNCONNECTED" Else QPConnectionNetIdentity = CStr(Fields(3)) & "|" & CStr(Fields(4)) End If End Function Function QPConnectionsMatchOffset(ByRef Actual, ByRef Expected, ByVal OffsetX, ByVal OffsetY) Dim Used, ExpectedIndex, ActualIndex, Found, Candidate, SavedLine, Number, Match Set Used = CreateObject("Scripting.Dictionary") QPConnectionsMatchOffset = False For ExpectedIndex = 0 To Expected.Count - 1 SavedLine = Expected.Item(CStr(ExpectedIndex)) Found = -1 For ActualIndex = 0 To Actual.Count - 1 If Not Used.Exists(CStr(ActualIndex)) Then Candidate = Actual.Item(CStr(ActualIndex)) Match = (Abs(QPConnectionCoordinate(Candidate, 1) - _ QPConnectionCoordinate(SavedLine, 1) - OffsetX) < 0.0001 And _ Abs(QPConnectionCoordinate(Candidate, 2) - _ QPConnectionCoordinate(SavedLine, 2) - OffsetY) < 0.0001 And _ StrComp(QPConnectionNetIdentity(Candidate), _ QPConnectionNetIdentity(SavedLine), vbBinaryCompare) = 0) Number = QPConnectionNumber(SavedLine) If Len(Trim(Number)) > 0 Then _ Match = Match And StrComp(QPConnectionNumber(Candidate), Number, vbBinaryCompare) = 0 If Match Then If Found >= 0 Then Exit Function Found = ActualIndex End If End If Next If Found < 0 Then Exit Function Used.Add CStr(Found), True Next QPConnectionsMatchOffset = True End Function Sub QPRestoreDisplay(ByRef Attr, ByRef Record, ByVal Refdes) Dim Point, Field For Each Field In Array("x", "y", "color", "font", "size", "orientation", "visible") If Len(CStr(Record(Field))) = 0 Then _ Err.Raise vbObjectError + 836, "QuickPartReplace", "incomplete attribute style snapshot" Next Attr.Color = CLng(Record("color")) Attr.Font = CLng(Record("font")) Attr.Size = CLng(Record("size")) Attr.Orientation = CLng(Record("orientation")) Attr.Visible = CLng(Record("visible")) Attr.SetLocation CLng(Record("x")), CLng(Record("y")) QPVerifyDisplay Attr, Record, Refdes End Sub Sub QPVerifyDisplay(ByRef Attr, ByRef Record, ByVal Refdes) Dim Point, Mismatch, ToleratedDrift, Name, Uid Set Point = Attr.GetLocation() Name = CStr(Record("name")) Uid = CStr(Record("uid")) Mismatch = "" ToleratedDrift = "" If Abs(CDbl(Point.X) - CDbl(Record("x"))) > QP_ATTRIBUTE_COORDINATE_TOLERANCE Then Mismatch = Mismatch & " x=" & CStr(Record("x")) & "->" & CStr(Point.X) ElseIf CDbl(Point.X) <> CDbl(Record("x")) Then ToleratedDrift = ToleratedDrift & " x=" & CStr(Record("x")) & "->" & CStr(Point.X) End If If Abs(CDbl(Point.Y) - CDbl(Record("y"))) > QP_ATTRIBUTE_COORDINATE_TOLERANCE Then Mismatch = Mismatch & " y=" & CStr(Record("y")) & "->" & CStr(Point.Y) ElseIf CDbl(Point.Y) <> CDbl(Record("y")) Then ToleratedDrift = ToleratedDrift & " y=" & CStr(Record("y")) & "->" & CStr(Point.Y) End If If CLng(Attr.Color) <> CLng(Record("color")) Then Mismatch = Mismatch & " color=" & CStr(Record("color")) & "->" & CStr(Attr.Color) If CLng(Attr.Font) <> CLng(Record("font")) Then Mismatch = Mismatch & " font=" & CStr(Record("font")) & "->" & CStr(Attr.Font) If CLng(Attr.Size) <> CLng(Record("size")) Then Mismatch = Mismatch & " size=" & CStr(Record("size")) & "->" & CStr(Attr.Size) If CLng(Attr.Orientation) <> CLng(Record("orientation")) Then Mismatch = Mismatch & " orientation=" & CStr(Record("orientation")) & "->" & CStr(Attr.Orientation) If CLng(Attr.Visible) <> CLng(Record("visible")) Then Mismatch = Mismatch & " visible=" & CStr(Record("visible")) & "->" & CStr(Attr.Visible) If Len(ToleratedDrift) > 0 Then QPLog QP_Root, "WARN", "display_coordinate_tolerated uid=" & QPLogField(Uid) & _ " refdes=" & QPLogField(CStr(Refdes)) & " attribute=" & QPLogField(Name) & _ " tolerance=" & CStr(QP_ATTRIBUTE_COORDINATE_TOLERANCE) & _ " fields=" & QPLogField(Trim(ToleratedDrift)) End If If Len(Mismatch) > 0 Then QPLog QP_Root, "ERROR", "display_readback_mismatch uid=" & QPLogField(Uid) & _ " refdes=" & QPLogField(CStr(Refdes)) & " attribute=" & QPLogField(Name) & _ " fields=" & QPLogField(Trim(Mismatch)) Err.Raise vbObjectError + 837, "QuickPartReplace", _ "display readback failed: " & Name & "; refdes=" & CStr(Refdes) & _ "; uid=" & Uid & "; fields=" & Trim(Mismatch) End If End Sub Function QPFindCurrentAttribute(ByRef Comp, ByVal Name) Dim Attr Set Attr = Comp.FindAttribute(CStr(Name)) Set QPFindCurrentAttribute = Attr End Function Function QPRequiredAttributeValue(ByRef Comp, ByVal Name) Dim Attr Set Attr = QPFindCurrentAttribute(Comp, Name) If Attr Is Nothing Then Err.Raise vbObjectError + 806, "QuickPartReplace", _ "required attribute missing: " & CStr(Name) End If QPRequiredAttributeValue = QPEffectiveAttributeValue(Attr) End Function Function QPEffectiveAttributeValue(ByRef Attr) Dim Instance Dim Value Dim ErrorNumber Dim ErrorSource Dim ErrorDescription On Error Resume Next Instance = CStr(Attr.InstanceValue) ErrorNumber = Err.Number ErrorSource = Err.Source ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber = 0 And Len(Instance) > 0 Then QPEffectiveAttributeValue = Instance Exit Function End If If ErrorNumber <> 0 Then Err.Raise ErrorNumber, ErrorSource, ErrorDescription End If On Error Resume Next Value = CStr(Attr.Value) ErrorNumber = Err.Number ErrorSource = Err.Source ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then If Len(ErrorSource) = 0 Then _ ErrorSource = "QuickPartReplace.EffectiveAttributeValue" Err.Raise ErrorNumber, ErrorSource, ErrorDescription End If QPEffectiveAttributeValue = Value End Function Function QPConnectionSignature(ByRef Comp) Dim Pins, Uid Uid = CStr(Comp.UID) Set Pins = QPComponentPins(Uid) QPConnectionSignature = QPConnectionSignatureFromPins(Uid, Pins) End Function Function QPConnectionSignatureFromPins(ByVal ComponentUid, ByRef Pins) Dim PinIndexKey Dim PinReadCount Dim CmpPin Dim Point Dim Connection Dim Net Dim Signatures Dim PinKey Dim PinValue Dim ErrorNumber Dim ErrorSource Dim ErrorDescription Dim Keys Dim Index Dim InnerIndex Dim Swap Dim Result Set Signatures = CreateObject("Scripting.Dictionary") QP_Stage = "query_pins" PinReadCount = 0 For Each PinIndexKey In Pins.Keys Set CmpPin = Pins.Item(CStr(PinIndexKey)) If StrComp(CStr(CmpPin.Component.UID), ComponentUid, _ vbBinaryCompare) = 0 Then Set Point = CmpPin.GetLocation() PinKey = CStr(CmpPin.Number) & "|" & CStr(Point.X) & "|" & _ CStr(Point.Y) Set Connection = Nothing On Error Resume Next Set Connection = CmpPin.Connection ErrorNumber = Err.Number ErrorSource = Err.Source ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then If Len(ErrorSource) = 0 Then _ ErrorSource = "QuickPartReplace.CmpPinConnection" Err.Raise ErrorNumber, ErrorSource, ErrorDescription End If If Connection Is Nothing Then PinValue = PinKey & "|UNCONNECTED" Else Set Net = Nothing On Error Resume Next Set Net = Connection.Net ErrorNumber = Err.Number ErrorSource = Err.Source ErrorDescription = Err.Description Err.Clear On Error GoTo 0 If ErrorNumber <> 0 Then If Len(ErrorSource) = 0 Then _ ErrorSource = "QuickPartReplace.ConnectionNet" Err.Raise ErrorNumber, ErrorSource, ErrorDescription End If If Net Is Nothing Then Err.Raise vbObjectError + 822, "QuickPartReplace", _ "connected pin has no readable Net object" End If PinValue = PinKey & "|" & CStr(Net.UID) & "|" & _ CStr(Net.LogicalNetName) End If QPAddSortedSignature Signatures, PinKey, PinValue PinReadCount = PinReadCount + 1 If PinReadCount Mod 25 = 0 Then QPProgress "read_pin_connections", PinReadCount, Pins.Count End If Next If Signatures.Count = 0 Then Err.Raise vbObjectError + 819, "QuickPartReplace", _ "cannot establish component pin connection signature" End If Keys = Signatures.Keys For Index = 0 To UBound(Keys) - 1 For InnerIndex = Index + 1 To UBound(Keys) If StrComp(CStr(Keys(InnerIndex)), CStr(Keys(Index)), _ vbBinaryCompare) < 0 Then Swap = Keys(Index) Keys(Index) = Keys(InnerIndex) Keys(InnerIndex) = Swap End If Next Next Result = "" For Index = 0 To UBound(Keys) Result = Result & Signatures.Item(CStr(Keys(Index))) & vbLf Next QPConnectionSignatureFromPins = Result End Function Sub QPAddSortedSignature(ByRef Signatures, ByVal PinKey, ByVal PinValue) If Signatures.Exists(CStr(PinKey)) Then Err.Raise vbObjectError + 823, "QuickPartReplace", _ "duplicate component pin number and location" End If Signatures.Add CStr(PinKey), CStr(PinValue) End Sub Function QPProjectPath() Dim ProjectPath ProjectPath = CStr(QP_App.GetProjectData().GetProjectFilePath()) If Len(Trim(ProjectPath)) = 0 Then Err.Raise vbObjectError + 827, "QuickPartReplace", "no active project" End If QPProjectPath = QPCanonicalPath(ProjectPath) End Function Function QPSheetIdentity() Dim View Set View = QP_App.ActiveView If View Is Nothing Then Err.Raise vbObjectError + 828, "QuickPartReplace", "no active schematic sheet" End If QPSheetIdentity = CStr(View.GetName(0)) & ":" & CStr(View.Block.SheetNum) End Function Sub QPRequireProject(ByRef Command) If QPCanonicalPath(QPProjectPath()) <> _ QPCanonicalPath(CStr(Command("project_path"))) Then Err.Raise vbObjectError + 807, "QuickPartReplace", _ "Viewdraw.Application.ProjectPath does not match command.tsv" End If End Sub Function QPReadCommand(ByVal Path) Dim Lines Dim Keys Dim Result Dim Candidate Dim StatusPath Dim PreviousState Dim Rules Dim Index Dim AwaitingCount Dim AwaitingRule Dim EmptyRule Path = QPActiveCommandPath(Path) Lines = Split(QPReadUtf8(Path), vbLf) If UBound(Lines) < 1 Then Err.Raise vbObjectError + 808, "QuickPartReplace", _ "command.tsv must contain header and one record" End If Keys = Split(Replace(Lines(0), vbCr, ""), vbTab) StatusPath = QP_Fso.BuildPath(QP_Root, "status.tsv") Set Rules = QPReadProjectRuleStates(Lines, Keys, StatusPath) Set Result = Nothing AwaitingCount = 0 Set AwaitingRule = Nothing Set EmptyRule = Nothing For Index = 0 To Rules.Count - 1 Set Candidate = Rules.Item(CStr(Index)) PreviousState = CStr(Candidate("qp_state")) If PreviousState = "hard_failure" Then QP_CurrentJobId = CStr(Candidate("job_id")) Err.Raise vbObjectError + 824, "QuickPartReplace", _ "hard_failure blocks this project queue" ElseIf PreviousState = "awaiting_native_replace" Then AwaitingCount = AwaitingCount + 1 Set AwaitingRule = Candidate ElseIf QPIsNextRuleState(PreviousState) And EmptyRule Is Nothing Then Set EmptyRule = Candidate End If Next If AwaitingCount > 1 Then Err.Raise vbObjectError + 825, "QuickPartReplace", _ "multiple awaiting_native_replace rules" ElseIf AwaitingCount = 1 Then Set Result = AwaitingRule ElseIf Not EmptyRule Is Nothing Then Set Result = EmptyRule End If If Result Is Nothing Then Err.Raise vbObjectError + 812, "QuickPartReplace", _ "no pending command.tsv rule matches Viewdraw.Application.ProjectPath" End If If QPValueMode(Result) <> "legacy_part_label" And Len(CStr(QP_ExpectedJobId)) = 0 Then _ Err.Raise vbObjectError + 843, "QuickPartReplace", "confirmed queue job is required" If Len(CStr(QP_ExpectedJobId)) > 0 Then If CStr(Result("job_id")) <> CStr(QP_ExpectedJobId) Then _ Err.Raise vbObjectError + 843, "QuickPartReplace", "active project does not match confirmed queue job" End If Set QPReadCommand = Result End Function Function QPActiveCommandPath(ByVal QueuePath) Dim CurrentPath QPActiveCommandPath = CStr(QueuePath) If Not QP_BatchMode Or Len(CStr(QP_ExpectedJobId)) = 0 Then Exit Function CurrentPath = QP_Fso.BuildPath(QP_Root, "current-command.tsv") If QP_Fso.FileExists(CurrentPath) Then QPActiveCommandPath = CurrentPath End Function Function QPReadProjectRuleStates(ByRef Lines, ByRef Keys, ByVal StatusPath) Dim Result Dim Values Dim Candidate Dim Index Dim LineIndex Dim Key Set Result = CreateObject("Scripting.Dictionary") For LineIndex = 1 To UBound(Lines) If Len(Replace(Lines(LineIndex), vbCr, "")) > 0 Then Values = Split(Replace(Lines(LineIndex), vbCr, ""), vbTab) If UBound(Keys) <> UBound(Values) Then Err.Raise vbObjectError + 809, "QuickPartReplace", _ "command.tsv field count" End If Set Candidate = CreateObject("Scripting.Dictionary") For Index = 0 To UBound(Keys) Key = LCase(Trim(CStr(Keys(Index)))) If Candidate.Exists(Key) Then Err.Raise vbObjectError + 810, "QuickPartReplace", _ "duplicate command.tsv header" End If Candidate.Add Key, CStr(Values(Index)) Next For Each Key In Array("task_id", "job_id", "project_path", "old_part", "new_part") If Not Candidate.Exists(CStr(Key)) Or _ Len(CStr(Candidate(CStr(Key)))) = 0 Then Err.Raise vbObjectError + 811, "QuickPartReplace", _ "missing required command.tsv field: " & CStr(Key) End If Next If QPCanonicalPath(CStr(Candidate("project_path"))) = _ QPCanonicalPath(QPProjectPath()) Then Candidate.Add "old_part_number", Candidate("old_part") Candidate.Add "new_part_number", Candidate("new_part") Candidate.Add "qp_state", QPReadState(StatusPath, _ CStr(Candidate("job_id"))) Result.Add CStr(Result.Count), Candidate End If End If Next Set QPReadProjectRuleStates = Result End Function Function QPIsNextRuleState(ByVal State) QPIsNextRuleState = (Len(CStr(State)) = 0) End Function Function QPJobSnapshotPath(ByVal JobId) Dim Index Dim Character Dim SafeId If Len(CStr(JobId)) = 0 Then Err.Raise vbObjectError + 820, _ "QuickPartReplace", "job_id is blank" SafeId = "" For Index = 1 To Len(CStr(JobId)) Character = Mid(CStr(JobId), Index, 1) If InStr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_", _ Character) = 0 Then Err.Raise vbObjectError + 821, "QuickPartReplace", _ "job_id contains an unsafe snapshot filename character" End If SafeId = SafeId & Character Next QPJobSnapshotPath = QP_Fso.BuildPath(QP_Root, _ "snapshot-" & SafeId & ".tsv") End Function Function QPReadLegacyCommand(ByVal Path) Dim Lines Dim Keys Dim Values Dim Result Dim Index Dim Key Lines = Split(QPReadUtf8(Path), vbLf) Keys = Split(Replace(Lines(0), vbCr, ""), vbTab) Values = Split(Replace(Lines(1), vbCr, ""), vbTab) Set Result = CreateObject("Scripting.Dictionary") For Index = 0 To UBound(Keys) Key = LCase(Trim(CStr(Keys(Index)))) If Result.Exists(Key) Then Err.Raise vbObjectError + 810, "QuickPartReplace", _ "duplicate command.tsv header" End If Result.Add Key, CStr(Values(Index)) Next Set QPReadLegacyCommand = Result End Function Function QPReadSnapshot(ByVal Path) Dim Lines Dim Result Dim Components Dim Attributes Dim Untouched, UntouchedFull Dim Fields Dim Index Dim Record Dim Meta Set Result = CreateObject("Scripting.Dictionary") Set Components = CreateObject("Scripting.Dictionary") Set Attributes = CreateObject("Scripting.Dictionary") Set Untouched = CreateObject("Scripting.Dictionary") Set UntouchedFull = CreateObject("Scripting.Dictionary") Lines = Split(QPReadUtf8(Path), vbLf) For Index = 0 To UBound(Lines) If Len(Replace(Lines(Index), vbCr, "")) > 0 Then Fields = Split(Replace(Lines(Index), vbCr, ""), vbTab) Select Case Fields(0) Case "M" If UBound(Fields) <> 4 And UBound(Fields) <> 5 And UBound(Fields) <> 7 And UBound(Fields) <> 9 Then Err.Raise vbObjectError + 812, _ "QuickPartReplace", "invalid snapshot meta" Set Meta = CreateObject("Scripting.Dictionary") Meta.Add "project_path", QPDecode(Fields(1)) Meta.Add "old_part_number", QPDecode(Fields(2)) Meta.Add "new_part_number", QPDecode(Fields(3)) Meta.Add "sheet_name", QPDecode(Fields(4)) If UBound(Fields) = 5 Then Meta.Add "value_mode", QPDecode(Fields(5)) If UBound(Fields) >= 7 Then Meta.Add "value_mode", QPDecode(Fields(5)) Meta.Add "custom_value", QPDecode(Fields(6)) Meta.Add "sync_nc", QPDecode(Fields(7)) End If If UBound(Fields) = 9 Then Meta.Add "target_scope", QPDecode(Fields(8)) Meta.Add "target_selectors", CStr(Fields(9)) End If Result.Add "meta", Meta Case "L" If UBound(Fields) <> 1 Or Not Result.Exists("meta") Then _ Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "invalid target Cell snapshot" Result.Item("meta").Add "target_cell", CStr(Fields(1)) If Len(QPTargetCell(Result.Item("meta"))) = 0 Then _ Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "missing target Cell snapshot" Case "C" If UBound(Fields) <> 7 Then Err.Raise vbObjectError + 813, _ "QuickPartReplace", "invalid snapshot component" Set Record = CreateObject("Scripting.Dictionary") Record.Add "uid", QPDecode(Fields(1)) Record.Add "refdes", QPDecode(Fields(2)) Record.Add "x", QPDecode(Fields(3)) Record.Add "y", QPDecode(Fields(4)) Record.Add "orientation", QPDecode(Fields(5)) Record.Add "scale", QPDecode(Fields(6)) Record.Add "connections", QPDecode(Fields(7)) Components.Add CStr(Components.Count), Record Case "A" If UBound(Fields) <> 11 Then Err.Raise vbObjectError + 814, _ "QuickPartReplace", "invalid snapshot attribute" Set Record = CreateObject("Scripting.Dictionary") Record.Add "uid", QPDecode(Fields(1)) Record.Add "name", QPDecode(Fields(2)) Record.Add "value", QPDecode(Fields(3)) Record.Add "instance_value", QPDecode(Fields(4)) Record.Add "x", QPDecode(Fields(5)) Record.Add "y", QPDecode(Fields(6)) Record.Add "color", QPDecode(Fields(7)) Record.Add "font", QPDecode(Fields(8)) Record.Add "size", QPDecode(Fields(9)) Record.Add "orientation", QPDecode(Fields(10)) Record.Add "visible", QPDecode(Fields(11)) Attributes.Add CStr(Attributes.Count), Record Case "U" If UBound(Fields) <> 6 Then Err.Raise vbObjectError + 874, _ "QuickPartReplace.Target", "invalid unselected component snapshot" If Untouched.Exists(QPDecode(Fields(1))) Then Err.Raise vbObjectError + 874, _ "QuickPartReplace.Target", "duplicate unselected component UID" Untouched.Add QPDecode(Fields(1)), Replace(Lines(Index), vbCr, "") Case "X" If UBound(Fields) <> 1 Or Fields(1) <> "untouched_full_v1" Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid unselected-state protocol" Result.Add "untouched_full_version", CStr(Fields(1)) Case "G" If UBound(Fields) <> 2 Or Len(QPDecode(Fields(1))) = 0 Or Len(QPDecode(Fields(2))) = 0 Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid unselected full-state snapshot" UntouchedFull.Add QPDecode(Fields(1)), QPDecode(Fields(2)) End Select End If Next If Not Result.Exists("meta") Or Components.Count = 0 Or Attributes.Count = 0 Then Err.Raise vbObjectError + 815, "QuickPartReplace", "incomplete snapshot" End If Result.Add "components", Components Result.Add "attributes", Attributes Result.Add "untouched", Untouched Result.Add "untouched_full", UntouchedFull Set QPReadSnapshot = Result End Function Function QPReadState(ByVal Path, ByVal JobId) Dim Lines Dim Fields Dim Index Dim CurrentPath If QP_BatchMode And CStr(JobId) = CStr(QP_CurrentJobId) And Len(CStr(QP_BatchState)) > 0 Then QPReadState = QP_BatchState Exit Function End If If QP_BatchMode And CStr(JobId) = CStr(QP_ExpectedJobId) Then CurrentPath = QP_Fso.BuildPath(QP_Root, "current-state.tsv") If QP_Fso.FileExists(CurrentPath) Then Path = CurrentPath End If If Not QP_Fso.FileExists(Path) Then QPReadState = "" Exit Function End If Lines = Split(QPReadUtf8(Path), vbLf) QPReadState = "" For Index = 1 To UBound(Lines) If Len(Replace(Lines(Index), vbCr, "")) > 0 Then Fields = Split(Replace(Lines(Index), vbCr, ""), vbTab) If UBound(Fields) = 3 And QPDecode(Fields(0)) = CStr(JobId) Then QPReadState = QPDecode(Fields(1)) End If End If Next End Function Sub QPWriteStatus(ByVal Root, ByVal JobId, ByVal State, ByVal Code, ByVal Message) If QP_BatchMode And (State = "restored_ok" Or State = "no_match") Then QP_BatchState = State QP_BatchCode = Code QP_BatchMessage = Message Exit Sub End If Dim Path Path = QP_Fso.BuildPath(Root, "status.tsv") If Not QP_Fso.FileExists(Path) Then QPAppendAscii Path, _ "job_id" & vbTab & "state" & vbTab & "code" & vbTab & "message" & vbCrLf QPAppendAscii Path, QPEncode(JobId) & vbTab & QPEncode(State) & _ vbTab & QPEncode(Code) & vbTab & QPEncode(Message) & vbCrLf If QP_BatchMode And CStr(JobId) = CStr(QP_ExpectedJobId) Then QPWriteUtf8 QP_Fso.BuildPath(Root, "current-state.tsv"), _ "job_id" & vbTab & "state" & vbTab & "code" & vbTab & _ "message" & vbCrLf & QPEncode(JobId) & vbTab & _ QPEncode(State) & vbTab & QPEncode(Code) & vbTab & _ QPEncode(Message) & vbCrLf End If End Sub Sub QPFail(ByVal Root, ByVal State, ByVal Number, ByVal Source, ByVal Description) On Error Resume Next If Len(CStr(QP_CurrentJobId)) > 0 Then QPWriteStatus Root, QP_CurrentJobId, State, CStr(Number), _ CStr(Source) & ": " & CStr(Description) End If QPLog Root, "ERROR", "stage=" & CStr(QP_Stage) & " number=" & Number & " source=" & Source & _ " description=" & Description On Error GoTo 0 End Sub Sub QPLog(ByVal Root, ByVal Level, ByVal Message) Dim Path Path = QP_Fso.BuildPath(Root, "quick-part-replace.log") QPAppendAscii Path, QPEncode(CStr(Now)) & vbTab & QPEncode(Level) & _ vbTab & QPEncode(Message) & vbCrLf End Sub Function QPLogField(ByVal Value) QPLogField = Replace(Replace(Replace(CStr(Value), vbCr, ""), _ vbLf, "\n"), vbTab, "\t") End Function Function QPReadUtf8(ByVal Path) Dim Stream Set Stream = CreateObject("ADODB.Stream") Stream.Type = 2 Stream.Charset = "utf-8" Stream.Open Stream.LoadFromFile CStr(Path) QPReadUtf8 = Stream.ReadText Stream.Close End Function Function QPReadContinuation(ByVal Path) Dim Attempt, Text, Number, Description ' Atomic Windows replacement and background readers may briefly deny access. ' Only the continuation read retries; token and checkpoint checks remain strict. For Attempt = 1 To 20 On Error Resume Next Err.Clear Text = QPReadUtf8(Path) Number = Err.Number Description = Err.Description Err.Clear On Error GoTo 0 If Number = 0 Then QPReadContinuation = Text Exit Function End If WScript.Sleep 50 Next Err.Raise Number, "QuickPartReplace.ProjectSession", Description End Function Sub QPWriteUtf8(ByVal Path, ByVal Text) Dim Stream Set Stream = CreateObject("ADODB.Stream") Stream.Type = 2 Stream.Charset = "utf-8" Stream.Open Stream.WriteText CStr(Text) Stream.SaveToFile CStr(Path), 2 Stream.Close End Sub Sub QPAppendAscii(ByVal Path, ByVal Text) Dim Stream Set Stream = QP_Fso.OpenTextFile(CStr(Path), 8, True, 0) Stream.Write CStr(Text) Stream.Close End Sub Function QPEncode(ByVal Value) Dim Text Dim Index Dim Code Dim Character Text = CStr(Value) QPEncode = "" For Index = 1 To Len(Text) Character = Mid(Text, Index, 1) Code = AscW(Character) If Code < 0 Then Code = Code + 65536 If Character = "%" Or Code < 32 Or Code > 126 Then QPEncode = QPEncode & "%" & Right("0000" & Hex(Code), 4) Else QPEncode = QPEncode & Character End If Next End Function Function QPDecode(ByVal Value) Dim Text Dim Index Dim Code Text = CStr(Value) QPDecode = "" Index = 1 Do While Index <= Len(Text) If Mid(Text, Index, 1) = "%" And Index + 4 <= Len(Text) Then Code = CLng("&H" & Mid(Text, Index + 1, 4)) If Code > 32767 Then Code = Code - 65536 QPDecode = QPDecode & ChrW(Code) Index = Index + 5 Else QPDecode = QPDecode & Mid(Text, Index, 1) Index = Index + 1 End If Loop End Function Function QPCanonicalPath(ByVal Value) Dim Identity QPEnsureProjectAccess Identity = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), "/", "\")) If QP_AccessProject.Exists(Identity) Then Identity = QP_AccessProject(Identity) QPCanonicalPath = Identity End Function Sub QPEnsureProjectAccess() Dim Path, Lines, Fields, Index, Canonical, Access If IsObject(QP_ProjectAccess) Then Exit Sub Set QP_ProjectAccess = CreateObject("Scripting.Dictionary") Set QP_AccessProject = CreateObject("Scripting.Dictionary") QP_ProjectAccess.CompareMode = 1 QP_AccessProject.CompareMode = 1 Path = QP_Fso.BuildPath(QP_Root, "project-access.tsv") If Not QP_Fso.FileExists(Path) Then Exit Sub Lines = Split(QPReadUtf8(Path), vbLf) If Replace(Lines(0), vbCr, "") <> "project_path" & vbTab & "access_path" Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "invalid project access header" For Index = 1 To UBound(Lines) If Len(Replace(Lines(Index), vbCr, "")) > 0 Then Fields = Split(Replace(Lines(Index), vbCr, ""), vbTab) If UBound(Fields) <> 1 Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "invalid project access row" Canonical = LCase(Replace(QP_Fso.GetAbsolutePathName(Fields(0)), "/", "\")) Access = LCase(Replace(QP_Fso.GetAbsolutePathName(Fields(1)), "/", "\")) If QP_ProjectAccess.Exists(Canonical) Or QP_AccessProject.Exists(Access) Then _ Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "duplicate project access identity" QP_ProjectAccess.Add Canonical, Fields(1) QP_AccessProject.Add Access, Canonical End If Next End Sub Function QPProjectAccessPath(ByVal Value) Dim Identity QPEnsureProjectAccess Identity = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), "/", "\")) If QP_ProjectAccess.Exists(Identity) Then QPProjectAccessPath = QP_ProjectAccess(Identity) Else QPProjectAccessPath = Value End If End Function Sub QPRaiseCaptured(ByVal Number, ByVal Source, ByVal Description, ByVal Fallback) If Len(CStr(Source)) = 0 Then Source = Fallback Err.Clear Err.Raise Number, Source, Description End Sub