fix: persist release outcomes and guard active native backup sessions
This commit is contained in:
1 parent
d40192ee58
commit
5eb4b2d7ed
10 files changed
+669
-69
No files matched your search
@@ -31,9 +31,33 @@ def force_block_reason(row):
|
||||
if (row.get('force_user_confirmed') is not True or not row.get('owner_sid')
|
||||
or not isinstance(row.get('session_id'), int)):
|
||||
return '未确认属于当前用户和 Windows 会话,不允许强制结束'
|
||||
activity = row.get('native_activity', {})
|
||||
if activity.get('status') in ('ACTIVE', 'UNCONFIRMED'):
|
||||
return activity.get('detail', '原生操作状态未确认')+';请查看进展或请求原生取消后重新检查'
|
||||
if name == 'icdbprojectbackup.exe' and activity.get('status') != 'IDLE':
|
||||
return '备份/恢复/修复状态未确认,请重新检查'
|
||||
return ''
|
||||
|
||||
|
||||
def native_activity(name, windows):
|
||||
if any(w['class'] == 'UNCONFIRMED' for w in windows):
|
||||
return {'status': 'UNCONFIRMED', 'detail': '原生窗口读取不完整'}
|
||||
if any((name.casefold() == 'icdbprojectbackup.exe' and not w['enabled'])
|
||||
or any(c['class'].casefold() == 'msctls_progress32' for c in w['children']) for w in windows):
|
||||
return {'status': 'ACTIVE', 'detail': '原生窗口显示操作进行中'}
|
||||
if name.casefold() == 'icdbprojectbackup.exe':
|
||||
main = [w for w in windows if w['class'].startswith('Afx:')
|
||||
and w['title'].startswith('iCDB Project Backup')]
|
||||
output = main[0].get('output') if len(main) == 1 else None
|
||||
if not isinstance(output, str) or not output.strip():
|
||||
return {'status': 'UNCONFIRMED', 'detail': '无法确认备份/恢复/修复输出'}
|
||||
active = list(re.finditer(r'(?i)repairing|restoring|backing up|creating (?:a )?backup', output))
|
||||
if active and max(output.rfind('Backup information loaded correctly.'),
|
||||
output.rfind('Repair project error [')) < active[-1].start():
|
||||
return {'status': 'ACTIVE', 'detail': '原生备份/恢复/修复尚未确认结束', 'output': output}
|
||||
return {'status': 'IDLE', 'detail': '未观察到进行中的原生操作'}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _process_handle(pid, *, terminate=False):
|
||||
import win32api, win32con
|
||||
@@ -94,7 +118,7 @@ def _process_windows(pids):
|
||||
from .native_repair_ui import _native_output
|
||||
result = {pid: [] for pid in pids}
|
||||
observed = set()
|
||||
def capture(hwnd, _=None):
|
||||
def capture(hwnd, _=None, *, desktop_name='Default'):
|
||||
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
|
||||
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
|
||||
return
|
||||
@@ -111,6 +135,7 @@ def _process_windows(pids):
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
|
||||
'desktop': desktop_name,
|
||||
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
|
||||
'children': children, 'documents': documents, 'rect': list(win32gui.GetWindowRect(hwnd))}
|
||||
if any(c['class'].casefold().startswith('richedit') for c in children):
|
||||
@@ -136,7 +161,7 @@ def _process_windows(pids):
|
||||
desktop = None
|
||||
try:
|
||||
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
|
||||
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd))
|
||||
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd), desktop_name=name)
|
||||
except Exception:
|
||||
incomplete()
|
||||
finally:
|
||||
@@ -194,15 +219,36 @@ def _save_question(windows):
|
||||
if (window['class'] == '#32770' and 'Expedition' in window['title']
|
||||
and re.search(r'\bsave\b', text, re.I) and re.search(r'changes|modified', text, re.I)
|
||||
and set(buttons) == {6, 7, 2}):
|
||||
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons}
|
||||
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons,
|
||||
'desktop': window.get('desktop', '')}
|
||||
return None
|
||||
|
||||
|
||||
def _cancel_question(name, windows):
|
||||
if name.casefold() != 'icdbprojectbackup.exe' or native_activity(name, windows)['status'] != 'ACTIVE':
|
||||
return None
|
||||
candidates = []
|
||||
for window in windows:
|
||||
if not (window['class'].startswith('Afx:') or window['class'] == '#32770'):
|
||||
continue
|
||||
if not window['title'].startswith('iCDB Project Backup') or not window['enabled']:
|
||||
continue
|
||||
for button in window['children']:
|
||||
if (button['class'] == 'Button' and button.get('id') == 2 and button.get('enabled')
|
||||
and button.get('text', '').replace('&', '').strip() in ('Cancel', '取消')):
|
||||
candidates.append({'hwnd': window['hwnd'], 'button': button,
|
||||
'title': window['title'],
|
||||
'desktop': window.get('desktop', '')})
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
|
||||
|
||||
def inspect_residual_sessions(library, *, block_names=()):
|
||||
from .library_lock import _owner_matches_scope, blocker_path, checkpoint_record, has_retained_library
|
||||
library = Path(library).resolve()
|
||||
if library.suffix.casefold() != '.lmc' or not library.is_file():
|
||||
raise ValueError('请选择有效的中心库 .lmc 文件')
|
||||
if library.suffix.casefold() != '.lmc':
|
||||
raise ValueError('请选择中心库 .lmc 文件')
|
||||
if not library.is_file():
|
||||
raise ValueError('中心库路径当前不可见,请检查文件是否存在及网络盘映射后重新检查')
|
||||
blocks = tuple(dict.fromkeys(str(name) for name in block_names))
|
||||
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks):
|
||||
raise ValueError('残留检查的工程名称无效')
|
||||
@@ -231,6 +277,14 @@ def inspect_residual_sessions(library, *, block_names=()):
|
||||
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
|
||||
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
|
||||
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
|
||||
observed = windows.get(row['pid'], [])
|
||||
item['windows'] = observed
|
||||
item['desktops'] = sorted({w.get('desktop', '') for w in observed if w.get('desktop')})
|
||||
item['native_activity'] = native_activity(row['name'], observed)
|
||||
item['cancel_prompt'] = (_cancel_question(row['name'], observed)
|
||||
if row['scope_confirmed'] and item.get('force_user_confirmed') is True else None)
|
||||
if any(name.startswith('Cbb') for name in item['desktops']) and not item['can_close']:
|
||||
item['detail'] += ';窗口在后台,可查看原生提示并使用已提供的保存/取消操作'
|
||||
item['force_block_reason'] = force_block_reason(item)
|
||||
item['force_allowed'] = not item['force_block_reason']
|
||||
if item['force_block_reason']:
|
||||
@@ -308,6 +362,11 @@ def _force_close(row, *, stop=None):
|
||||
if (not ownership['force_user_confirmed'] or
|
||||
any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))):
|
||||
return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'}
|
||||
activity = native_activity(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
|
||||
if reason := force_block_reason({**row, 'native_activity': activity}):
|
||||
return {'release_status': 'WAITING', 'detail': reason, 'native_activity': activity}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放,未强制结束'}
|
||||
win32api.TerminateProcess(handle, 1)
|
||||
exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0
|
||||
return {'release_status': 'RELEASED' if exited else 'WAITING',
|
||||
@@ -319,75 +378,139 @@ def _finish_library_release(library, evidence):
|
||||
return release_retained_library(library, evidence)
|
||||
|
||||
|
||||
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
def _request_native_cancel(row, *, stop=None):
|
||||
"""Only click the exact currently visible Cancel control the user confirmed."""
|
||||
import win32con, win32gui, win32process
|
||||
if row.get('scope_confirmed') is not True:
|
||||
raise ValueError('取消目标归属未确认,请重新检查')
|
||||
fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None)
|
||||
if fresh is None or any(fresh.get(k) != row.get(k) for k in ('created', 'command', 'executable', 'name')):
|
||||
raise ValueError('取消目标身份已变化,请重新检查')
|
||||
with _process_handle(row['pid']) as handle:
|
||||
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
|
||||
raise ValueError('取消目标身份已变化,请重新检查')
|
||||
owner = _force_ownership(handle, row['pid'])
|
||||
if not owner['force_user_confirmed'] or any(owner[k] != row.get(k) for k in ('owner_sid', 'session_id')):
|
||||
raise ValueError('取消目标用户/会话已变化')
|
||||
prompt = _cancel_question(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
|
||||
if not prompt or prompt != row.get('cancel_prompt'):
|
||||
raise ValueError('原生取消按钮已变化,请重新检查')
|
||||
button = prompt['button']
|
||||
if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']:
|
||||
raise ValueError('原生取消按钮归属已变化')
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止,未请求原生取消'}
|
||||
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
|
||||
return {'release_status': 'WAITING', 'detail': '已请求原生取消,需重新检查实际结果;未强制结束'}
|
||||
|
||||
|
||||
def request_native_cancel(row, library, evidence_dir, *, stop=None):
|
||||
# Reuse serialized admission, consent and incremental evidence for cancellation.
|
||||
plan = {'library': str(library), 'sessions': [row]}
|
||||
return release_residual_sessions(plan, evidence_dir, stop=stop, cancel_native=True)
|
||||
|
||||
|
||||
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
|
||||
library = Path(plan['library']).resolve()
|
||||
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
|
||||
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
|
||||
raise ValueError('释放记录需位于中心库之外')
|
||||
root.mkdir(parents=True)
|
||||
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [], 'force': force,
|
||||
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [
|
||||
{**row, 'release_status': 'NOT_STARTED', 'detail': '尚未执行',
|
||||
'consent_allowed': not force_block_reason(row) if force else row.get('scope_confirmed') is True}
|
||||
for row in plan['sessions']], 'force': force, 'cancel_native': cancel_native,
|
||||
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
|
||||
if force:
|
||||
def save():
|
||||
from .management import _write_json
|
||||
try:
|
||||
result['report_saved'] = True
|
||||
_write_json(root/'result.json', result)
|
||||
return True
|
||||
except OSError as error:
|
||||
result.update(status='PARTIAL', report_saved=False, evidence_error=str(error))
|
||||
return False
|
||||
if not save():
|
||||
return result # No native actions without the initial checkpoint.
|
||||
if force or cancel_native:
|
||||
consent_path = root/'consent.json'
|
||||
consent = {'version': 1, 'mode': 'force_document_clients', 'library': str(library),
|
||||
consent = {'version': 1, 'mode': 'cancel_native' if cancel_native else 'force_document_clients', 'library': str(library),
|
||||
'time_ns': time.time_ns(), 'sessions': [
|
||||
{**row, 'force_allowed': not force_block_reason(row),
|
||||
'cancel_allowed': bool(row.get('cancel_prompt')) and row.get('scope_confirmed') is True,
|
||||
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
|
||||
with consent_path.open('x', encoding='utf-8') as stream:
|
||||
json.dump(consent, stream, ensure_ascii=False, indent=2)
|
||||
stream.flush(); os.fsync(stream.fileno())
|
||||
result['consent_path'] = str(consent_path)
|
||||
fresh = {r['pid']: r for r in query_process_snapshot()}
|
||||
# Close native children first, so their supervisors can finish and drop leases.
|
||||
ordered = sorted(plan['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
|
||||
for original in ordered:
|
||||
current = fresh.get(original['pid'])
|
||||
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
|
||||
if stop is not None and stop.is_set():
|
||||
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
elif current is not None:
|
||||
from .library_lock import _owner_matches_scope
|
||||
scoped = _owner_matches_scope(current, library, (library.parent,)) is True
|
||||
if original.get('scope_confirmed') is not True or not scoped or original['pid'] == os.getpid():
|
||||
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
|
||||
elif any(current.get(key) != original.get(key) for key in ('created', 'executable', 'command', 'name')):
|
||||
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
|
||||
elif force and (reason := force_block_reason(original)):
|
||||
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
|
||||
else:
|
||||
try: outcome = (_force_close if force else _request_close)(original, stop=stop)
|
||||
except Exception as error:
|
||||
outcome = {'release_status': 'WAITING', 'detail': str(error)}
|
||||
result['sessions'].append({**original, **outcome})
|
||||
by_pid = {r['pid']: r for r in result['sessions']}
|
||||
result['sessions'] = [by_pid[r['pid']] for r in plan['sessions']]
|
||||
# Launchers may exit only after the GUI child processed its close request.
|
||||
after = {r['pid']: r for r in query_process_snapshot()}
|
||||
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
|
||||
if r['release_status'] == 'WAITING' and r['pid'] in after})
|
||||
for row in result['sessions']:
|
||||
if row['release_status'] == 'WAITING' and row['pid'] not in after:
|
||||
row.update(release_status='RELEASED', detail='已退出')
|
||||
elif row['release_status'] == 'WAITING':
|
||||
row['prompt'] = _save_question(remaining_windows.get(row['pid'], []))
|
||||
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
|
||||
try:
|
||||
with consent_path.open('x', encoding='utf-8') as stream:
|
||||
json.dump(consent, stream, ensure_ascii=False, indent=2)
|
||||
stream.flush(); os.fsync(stream.fileno())
|
||||
except OSError as error:
|
||||
result['detail'] = f'确认记录保存失败,未执行:{error}'
|
||||
save()
|
||||
raise
|
||||
result['consent_path'] = str(consent_path)
|
||||
try:
|
||||
fresh = {r['pid']: r for r in query_process_snapshot()}
|
||||
blocks = plan.get('block_names', ())
|
||||
roots = (tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks)
|
||||
+ (library.parent/'SymbolLibs',)) if blocks else (library.parent,)
|
||||
# Close native children first; keep output rows in the original preview order.
|
||||
ordered = sorted(result['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
|
||||
for row in ordered:
|
||||
current = fresh.get(row['pid'])
|
||||
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
|
||||
if stop is not None and stop.is_set():
|
||||
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
elif current is not None:
|
||||
from .library_lock import _owner_matches_scope
|
||||
scoped = _owner_matches_scope(current, library, roots) is True
|
||||
if row.get('scope_confirmed') is not True or not scoped or row['pid'] == os.getpid():
|
||||
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
|
||||
elif not row.get('created') or any(current.get(key) != row.get(key)
|
||||
for key in ('created', 'executable', 'command', 'name')):
|
||||
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
|
||||
elif force and (reason := force_block_reason(row)):
|
||||
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
|
||||
else:
|
||||
row.update(release_status='REQUESTING', detail='正在请求原生操作,结果待确认')
|
||||
if not save():
|
||||
return result
|
||||
try:
|
||||
outcome = (_request_native_cancel(row, stop=stop) if cancel_native else
|
||||
(_force_close if force else _request_close)(row, stop=stop))
|
||||
except Exception as error:
|
||||
outcome = {'release_status': 'WAITING', 'detail': str(error)}
|
||||
row.update(outcome)
|
||||
if not save():
|
||||
return result # Preserve completed facts; stop further actions on storage failure.
|
||||
after = {r['pid']: r for r in query_process_snapshot()}
|
||||
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
|
||||
if r['release_status'] == 'WAITING' and r['pid'] in after})
|
||||
for row in result['sessions']:
|
||||
if row['release_status'] == 'WAITING' and row['pid'] not in after:
|
||||
row.update(release_status='RELEASED', detail='已退出')
|
||||
elif row['release_status'] == 'WAITING':
|
||||
windows = remaining_windows.get(row['pid'], [])
|
||||
row.update(prompt=_save_question(windows), windows=windows,
|
||||
cancel_prompt=(_cancel_question(row['name'], windows)
|
||||
if row.get('force_user_confirmed') is True else None),
|
||||
native_activity=native_activity(row['name'], windows))
|
||||
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
|
||||
result['proof'] = _finish_library_release(library, root/'library-proof')
|
||||
proof = result['proof']
|
||||
if (proof.get('status') != 'RELEASE_CONFIRMED'
|
||||
or Path(proof.get('library', '')).resolve() != library):
|
||||
raise ValueError('释放证明与当前库不一致')
|
||||
result['status'] = 'RELEASE_CONFIRMED'
|
||||
except Exception as error:
|
||||
result['detail'] = str(error)
|
||||
try:
|
||||
(root/'result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), 'utf-8')
|
||||
except OSError as error:
|
||||
result['evidence_error'] = str(error)
|
||||
except BaseException as error:
|
||||
result.update(status='PARTIAL', detail=f'{type(error).__name__}: {error}')
|
||||
if not isinstance(error, Exception):
|
||||
raise
|
||||
finally:
|
||||
save()
|
||||
return result
|
||||
|
||||
|
||||
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
|
||||
import win32con, win32event
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
@@ -401,7 +524,7 @@ def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
return {'status': 'PARTIAL', 'library': plan['library'], 'sessions': [
|
||||
{**r, 'release_status': 'WAITING', 'detail': '其它批次尚在执行;请停止该批次后重试'}
|
||||
for r in plan['sessions']], 'detail': '未取得执行通道,未关闭任何进程。'}
|
||||
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force)
|
||||
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force, cancel_native=cancel_native)
|
||||
finally:
|
||||
if acquired: win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
|
||||
@@ -25,13 +25,13 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.pool = QThreadPool(self)
|
||||
self.setWindowTitle('释放残留会话')
|
||||
self.setModal(True)
|
||||
self.resize(760, 350)
|
||||
self.resize(1040, 400)
|
||||
layout = QVBoxLayout(self)
|
||||
self.message = QLabel('正在检查当前库关联的会话…')
|
||||
self.message.setWordWrap(True)
|
||||
layout.addWidget(self.message)
|
||||
self.table = QTableWidget(0, 4)
|
||||
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态'])
|
||||
self.table = QTableWidget(0, 6)
|
||||
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径'])
|
||||
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
|
||||
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
|
||||
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
@@ -40,17 +40,22 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.refresh_button = QPushButton('重新检查')
|
||||
self.confirm_button = QPushButton('确认释放')
|
||||
self.prompt_button = QPushButton('处理保存提示…')
|
||||
self.details_button = QPushButton('查看原生提示…')
|
||||
self.cancel_native_button = QPushButton('请求原生取消…')
|
||||
self.force_button = QPushButton('强制结束客户端…')
|
||||
self.force_button.setEnabled(False)
|
||||
self.prompt_button.setEnabled(False)
|
||||
self.close_button = QPushButton('关闭')
|
||||
for button in (self.refresh_button, self.confirm_button, self.prompt_button, self.force_button, self.close_button): buttons.addWidget(button)
|
||||
for button in (self.refresh_button, self.confirm_button, self.details_button, self.prompt_button,
|
||||
self.cancel_native_button, self.force_button, self.close_button): buttons.addWidget(button)
|
||||
layout.addLayout(buttons)
|
||||
self.refresh_button.clicked.connect(self.refresh)
|
||||
self.confirm_button.clicked.connect(self.confirm_release)
|
||||
self.close_button.clicked.connect(self.close)
|
||||
self.prompt_button.clicked.connect(self.answer_prompt)
|
||||
self.force_button.clicked.connect(self.force_release)
|
||||
self.details_button.clicked.connect(self.show_native_details)
|
||||
self.cancel_native_button.clicked.connect(self.cancel_native)
|
||||
self.table.itemSelectionChanged.connect(self._update_prompt)
|
||||
self.refresh()
|
||||
|
||||
@@ -60,6 +65,7 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.refresh_button.setEnabled(False)
|
||||
self.prompt_button.setEnabled(False)
|
||||
self.force_button.setEnabled(False)
|
||||
self.cancel_native_button.setEnabled(False)
|
||||
self.close_button.setText('停止释放')
|
||||
self.worker = ServiceWorker(action)
|
||||
self.worker.signals.succeeded.connect(completed)
|
||||
@@ -83,7 +89,8 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.table.setRowCount(len(sessions))
|
||||
for index, session in enumerate(sessions):
|
||||
for column, value in enumerate((session.get('project', ''), session['name'],
|
||||
session['pid'], session.get('detail', ''))):
|
||||
session['pid'], session.get('detail', ''), ', '.join(session.get('desktops', [])),
|
||||
session.get('image', session.get('executable', '')))):
|
||||
self.table.setItem(index, column, QTableWidgetItem(str(value)))
|
||||
if sessions: self.table.setCurrentCell(0, 0)
|
||||
|
||||
@@ -91,6 +98,65 @@ class ResidualReleaseDialog(QDialog):
|
||||
row = self.table.currentRow()
|
||||
rows = self.plan['sessions'] if self.plan else []
|
||||
self.prompt_button.setEnabled(not self.busy and 0 <= row < len(rows) and bool(rows[row].get('prompt')))
|
||||
self.cancel_native_button.setEnabled(not self.busy and 0 <= row < len(rows)
|
||||
and bool(rows[row].get('cancel_prompt')))
|
||||
self.details_button.setEnabled(0 <= row < len(rows))
|
||||
|
||||
def show_native_details(self):
|
||||
if not self.plan: return
|
||||
row = self.table.currentRow()
|
||||
if row < 0: return
|
||||
session = self.plan['sessions'][row]
|
||||
box = QMessageBox(self); self.native_details = box
|
||||
box.setWindowTitle('原生会话状态')
|
||||
box.setText(f'{session["name"]} (PID {session["pid"]})\n'+session.get('detail', ''))
|
||||
details = ['程序路径:'+session.get('image', session.get('executable', '')),
|
||||
'窗口位置:'+', '.join(session.get('desktops', [])),
|
||||
session.get('native_activity', {}).get('detail', '')]
|
||||
for window in session.get('windows', []):
|
||||
details.extend(['', window.get('title', ''), window.get('output', '') or ''])
|
||||
details.extend(c.get('text', '') for c in window.get('children', [])
|
||||
if c.get('class') == 'Static')
|
||||
box.setDetailedText('\n'.join(details))
|
||||
box.show()
|
||||
|
||||
def cancel_native(self):
|
||||
if self.busy or not self.plan: return
|
||||
row = self.table.currentRow()
|
||||
if row < 0: return
|
||||
session = self.plan['sessions'][row]
|
||||
if not session.get('cancel_prompt'): return
|
||||
answer = QMessageBox.question(self, '请求原生取消',
|
||||
f'请求 {session["name"]} (PID {session["pid"]}) 当前显示的取消按钮?\n'
|
||||
'取消后的工程状态仍需核对;不会强制结束进程。',
|
||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
||||
if answer != QMessageBox.Yes: return
|
||||
from cbb_refresh_verify.residual_sessions import request_native_cancel
|
||||
self.before_release.emit(); self.stop.clear()
|
||||
def execute():
|
||||
action = lambda: request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop)
|
||||
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
|
||||
def done(result):
|
||||
self.message.setText(result.get('detail') or '\n'.join(r.get('detail', '') for r in result['sessions']))
|
||||
confirmed = self._accept_release_proof(result)
|
||||
if confirmed:
|
||||
self.message.setText('已确认原生会话结束,当前库已释放。')
|
||||
if result.get('evidence_error'):
|
||||
self.message.setText(self.message.text()+'\n记录保存失败:'+result['evidence_error'])
|
||||
elif not confirmed:
|
||||
self._refresh_after = True
|
||||
self._start(execute, done)
|
||||
|
||||
def _accept_release_proof(self, result):
|
||||
proof = result.get('proof', {})
|
||||
# Both paths were canonicalized by the worker; GUI comparison must not touch SMB.
|
||||
if (proof.get('status') != 'RELEASE_CONFIRMED'
|
||||
or Path(proof.get('library', '')).absolute() != self.library.absolute()
|
||||
or any(r.get('release_status') != 'RELEASED' for r in result['sessions'])):
|
||||
return False
|
||||
self.plan = None
|
||||
self.released.emit(proof)
|
||||
return True
|
||||
|
||||
def answer_prompt(self):
|
||||
if self.busy or not self.plan: return
|
||||
@@ -153,13 +219,13 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.plan = {**plan, 'sessions': result['sessions']}
|
||||
self._rows(result['sessions'])
|
||||
count = sum(row['release_status'] == 'RELEASED' for row in result['sessions'])
|
||||
if result['status'] == 'RELEASE_CONFIRMED':
|
||||
self.plan = None
|
||||
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。')
|
||||
self.released.emit(result['proof'])
|
||||
if self._accept_release_proof(result):
|
||||
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。'
|
||||
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
|
||||
else:
|
||||
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。'
|
||||
+ ('\n'+result['detail'] if result.get('detail') else '请处理原生窗口后重新检查。'))
|
||||
+ ('\n'+result['detail'] if result.get('detail') else '可查看原生提示、处理保存或请求取消后重新检查。')
|
||||
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
|
||||
def execute():
|
||||
action = lambda: release_residual_sessions(plan, self.evidence_dir, stop=self.stop, force=force)
|
||||
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
|
||||
|
||||
Reference in new issue
Block a user