from pathlib import Path import re import logging import json from collections import Counter, defaultdict from .models import CbbRecord, LibraryReadResult from .network_path import absolute_preserving_drive, validate_library_file logger = logging.getLogger(__name__) CACHE_SCHEMA_VERSION = 2 def infer_image_status_map(tree_images, status_by_name, names): """Derive the current machine's image-ID map from persisted observations.""" observations = defaultdict(set) ready_counts = Counter() for name in tuple(names): image = tree_images.get(name) status = str(status_by_name.get(name, 'UNKNOWN') or 'UNKNOWN').upper() if image is not None and status in {'READY', 'PENDING'}: observations[image].add(status) if status == 'READY': ready_counts[image] += 1 # A current Pending observation is stronger than a stale complete Cert # tree: an item can retain Cert artifacts after a user clicks Unverify. # Resolve mixed observations to Pending so the live icon cannot be hidden # by historical filesystem output. has_pending_anchor = any('PENDING' in statuses for statuses in observations.values()) if has_pending_anchor: return { image: 'PENDING' if 'PENDING' in statuses else 'READY' for image, statuses in observations.items() if statuses } # When every persisted row says Ready, an item manually changed to # Unverify has no filesystem anchor. Keep only the modal Ready ID as the # positive anchor; an additional ID is handled as an unseen Pending ID. if not ready_counts: return {} modal_count = max(ready_counts.values()) modal_ids = {image for image, count in ready_counts.items() if count == modal_count} return {image: 'READY' for image in modal_ids} def _read_image_status_cache(path, library=None): if path is None: return {} try: payload = json.loads(Path(path).read_text(encoding='utf-8')) if isinstance(payload, dict): if payload.get('schema_version') != CACHE_SCHEMA_VERSION: logger.info('image_status_cache_legacy_or_unknown_schema path=%s schema=%s', path, payload.get('schema_version')) return {} if library is not None: stored_library = str(payload.get('library', '') or '') current_library = str(absolute_preserving_drive(library)) if stored_library and stored_library.casefold() != current_library.casefold(): logger.info('image_status_cache_library_mismatch path=%s stored=%s current=%s', path, stored_library, library) return {} raw = payload.get('image_status_map', {}) if isinstance(payload, dict) else {} return {int(image): str(status).upper() for image, status in raw.items() if str(status).upper() in {'READY', 'PENDING'}} except (OSError, ValueError, TypeError): return {} def _write_image_status_cache(path, image_status_map, library=None): if path is None or not image_status_map: return try: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps({ 'schema_version': CACHE_SCHEMA_VERSION, 'library': str(absolute_preserving_drive(library)) if library is not None else '', 'image_status_map': {str(image): status for image, status in image_status_map.items()}, }, ensure_ascii=False, indent=2), encoding='utf-8') except OSError as error: logger.warning('image_status_cache_write_failed path=%s error=%s', path, error) def infer_tree_statuses(tree_images, filesystem_statuses, names, *, image_status_map=None): """Calibrate icon indices from independent persisted evidence. ``iImage`` is a resource-list position, not a stable Mentor API. An index is usable only when all CBBs with that index have the same known Cert-derived status. Ambiguous or unanchored indices remain UNKNOWN. """ calibrated = (dict(image_status_map) if image_status_map is not None else infer_image_status_map(tree_images, filesystem_statuses, names)) ready_ids = {image for image, status in calibrated.items() if status == 'READY'} return { name: calibrated.get( tree_images.get(name), 'PENDING' if tree_images.get(name) is not None and ready_ids else 'UNKNOWN', ) for name in tuple(names) } def reconcile_statuses(tree_statuses, filesystem_statuses, names): """Reconcile live icon evidence with persisted Cert/Work evidence. Complete persisted evidence is sufficient when the tree ID cannot be read (for example when LM is already busy). Once an ID has been calibrated from the current library, the live tree status wins because Cert artifacts can remain after a user clicks Unverify. """ result = {} for name in tuple(names): tree = str(tree_statuses.get(name, 'UNKNOWN') or 'UNKNOWN').upper() filesystem = str(filesystem_statuses.get(name, 'UNKNOWN') or 'UNKNOWN').upper() if tree in {'READY', 'PENDING'}: result[name] = tree elif filesystem in {'READY', 'PENDING'}: result[name] = filesystem else: result[name] = 'UNKNOWN' return result def _item(collection, index): item = getattr(collection, 'Item', None) if callable(item): return item(index) try: return collection(index) except TypeError: return getattr(collection, str(index)) def _value(obj, name, default=None): value = getattr(obj, name, default) return value() if callable(value) else value def filesystem_evidence_map(library: Path, names): """Collect independent persisted dimensions for each CBB. The result deliberately exposes each Work/Cert artifact instead of collapsing the decision into one file check. A complete set of six artifacts is the persisted ``READY`` observation; an otherwise valid Work project with an incomplete Cert set is ``PENDING``. An imported block with no usable Work project is also ``PENDING`` so it can anchor the current machine's unverified icon ID; PCB preflight may still skip it later. """ library = Path(library) root = library.parent / 'ReusableBlocksLP' result = {} for name in tuple(names): evidence = { 'status': 'UNKNOWN', 'project_count': 0, 'work_project': False, 'work_pcb': False, 'work_layout': False, 'cert_project': False, 'cert_pcb': False, 'cert_layout': False, } block = root / str(name) work = block / 'Work' projects = list(work.glob('*.prj')) if work.is_dir() else [] evidence['project_count'] = len(projects) if len(projects) != 1: evidence['status'] = 'PENDING' result[name] = evidence continue project = projects[0] evidence['work_project'] = project.is_file() try: content = project.read_text(encoding='utf-8', errors='replace') match = re.search(r'^KEY PCBDesignPath "([^"]+)"', content, re.M) pcb = absolute_preserving_drive(project.parent / match.group(1)) if match else None if pcb is None or not pcb.is_relative_to(absolute_preserving_drive(work)): evidence['status'] = 'PENDING' result[name] = evidence continue cert = block / 'Cert' cert_project = cert / project.name cert_pcb = cert / pcb.relative_to(work) cert_layout = cert_pcb.parent / 'Layout' / 'LayoutDB.lyt' work_layout = pcb.parent / 'Layout' / 'LayoutDB.lyt' paths = { 'work_project': project, 'work_pcb': pcb, 'work_layout': work_layout, 'cert_project': cert_project, 'cert_pcb': cert_pcb, 'cert_layout': cert_layout, } for key, path in paths.items(): evidence[key] = path.is_file() work_valid = all(evidence[key] for key in ('work_project', 'work_pcb', 'work_layout')) cert_valid = all(evidence[key] for key in ('cert_project', 'cert_pcb', 'cert_layout')) evidence['status'] = 'READY' if work_valid and cert_valid else 'PENDING' result[name] = evidence except (OSError, ValueError): result[name] = evidence return result def filesystem_status_map(library: Path, names): """Return only the persisted status derived from all six artifacts.""" return {name: details['status'] for name, details in filesystem_evidence_map(library, names).items()} def read_library_fast(path: Path, *, status_reader=None): """Discover directories; this does not validate native format/registration.""" try: path = Path(path) validate_library_file(path) folder = path.parent/'ReusableBlocksLP' if folder.exists() and not folder.is_dir(): return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}') entries = [entry for entry in folder.iterdir() if entry.is_dir()] if folder.is_dir() else [] names = tuple(sorted((entry.name for entry in entries), key=str.casefold)) statuses = {} if status_reader is not None and names: try: statuses = dict(status_reader(path, names)) except TypeError: for name in names: try: statuses[name] = status_reader(name) except Exception: statuses[name] = 'UNKNOWN' except Exception as error: # Do not turn a failed authoritative probe into a silent # UNKNOWN list. UNKNOWN is calibration-only; a bridge or # reader failure must remain visible and must not look like a # valid scan that happened to find no statuses. logger.warning('library_status_reader_failed path=%s error=%s', path, error) statuses = {name: 'UNAVAILABLE' for name in names} records = [] for entry in entries: status = str(statuses.get(entry.name, 'UNKNOWN') or 'UNKNOWN') if status not in {'READY', 'PENDING', 'UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT'}: status = 'UNKNOWN' records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status, catalog_source='directory', status_source='status_reader' if status_reader else 'unknown')) return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)), directory_count=len(entries)) except PermissionError as error: return LibraryReadResult((), f'INPUT_PERMISSION: 无权读取中心库: {error}') except Exception as error: return LibraryReadResult((), str(error)) def scan_open_library_status(library: Path, names, *, tree_image_reader=None, mapping_store=None): """Read verification icons from an already-open LM, without launching it.""" names = tuple(names) persisted_evidence = filesystem_evidence_map(library, names) fallback = {name: details['status'] for name, details in persisted_evidence.items()} def finish(tree_images): tree_images = dict(tree_images or {}) current_map = infer_image_status_map(tree_images, fallback, names) cached_map = _read_image_status_cache(mapping_store, library) image_status_map = dict(cached_map) cache_actions = {} has_cached_ready = any(status == 'READY' for status in cached_map.values()) for image, status_value in current_map.items(): # The native image index is the machine-local status key. Once an # index has been calibrated, a transient filesystem snapshot must # not rewrite it: Cert/Work files can lag behind the TreeView # after Verify. New indices are still learned from this scan, so # an Unverify transition remains visible as a new Pending index. if image in cached_map: image_status_map[image] = cached_map[image] cache_actions[image] = 'cached_image_id_authoritative' elif has_cached_ready and status_value == 'READY': # With an existing Ready anchor, an unseen icon cannot be # promoted from stale Cert files alone. Keep it out of the # map so infer_tree_statuses classifies it as Pending. cache_actions[image] = 'unseen_tree_id_pending' else: image_status_map[image] = status_value cache_actions[image] = 'current_evidence_calibrated' if not image_status_map: image_status_map = current_map _write_image_status_cache(mapping_store, image_status_map, library) tree_statuses = infer_tree_statuses(tree_images, fallback, names, image_status_map=image_status_map) status = reconcile_statuses(tree_statuses, fallback, names) uncalibrated = [name for name in names if status.get(name, 'UNKNOWN') == 'UNKNOWN'] # Missing observations remain unknown; eligibility is decided by the caller. effective = {name: (value if tree_images.get(name) is not None else 'UNKNOWN') for name, value in status.items()} logger.info( 'library_status_sources names=%s image_histogram=%s current_image_map=%s cached_image_map=%s image_status_map=%s cache_actions=%s filesystem=%s calibrated_tree=%s final=%s uncalibrated_sample=%s conflicts=%s ready_anchor_ids=%s unseen_tree_ids=%s', len(names), dict(Counter(str(value) for value in tree_images.values() if value is not None)), dict(current_map), dict(cached_map), dict(image_status_map), dict(cache_actions), dict(Counter(fallback.get(name, 'UNKNOWN') for name in names)), dict(Counter(tree_statuses.get(name, 'UNKNOWN') for name in names)), dict(Counter(effective.get(name, 'PENDING') for name in names)), uncalibrated[:20], [name for name in names if tree_statuses.get(name) in {'READY', 'PENDING'} and fallback.get(name) in {'READY', 'PENDING'} and tree_statuses.get(name) != fallback.get(name)][:20], sorted(image for image, value in image_status_map.items() if value == 'READY'), sorted(image for image in tree_images.values() if image is not None and image not in image_status_map), ) for name in names: image_id = tree_images.get(name) persisted = fallback.get(name, 'UNKNOWN') tree = tree_statuses.get(name, 'UNKNOWN') final = effective.get(name, 'PENDING') if image_id is not None and image_id not in image_status_map and tree == 'PENDING': reason = ('unseen_tree_id_vs_cached_ready_anchor' if cached_map else 'unseen_tree_id_vs_ready_anchor') elif persisted in {'READY', 'PENDING'} and tree in {'READY', 'PENDING'}: reason = 'tree_id_and_persisted_match' if persisted == tree else 'tree_id_conflicts_persisted' elif persisted in {'READY', 'PENDING'}: reason = 'persisted_only' elif tree in {'READY', 'PENDING'}: reason = 'tree_id_calibrated' else: reason = 'insufficient_evidence' logger.info( 'library_status_item name=%s image_id=%s filesystem=%s tree=%s final=%s evidence=%s dimensions=%s', name, image_id, persisted, tree, final, reason, persisted_evidence.get(name, {}), ) return effective try: if tree_image_reader is None: from .mentor_adapter import read_library_tree_image_map tree_image_reader = read_library_tree_image_map return finish(tree_image_reader(library, names)) except Exception as error: logger.warning('library_status_probe_failed path=%s error=%s', library, error) return {name: 'UNKNOWN' for name in names} def read_library(path: Path, *, dispatch=None): try: if not Path(path).exists() and dispatch is None: return LibraryReadResult((), f'中心库不存在: {path}') if dispatch is None: import win32com.client dispatch = win32com.client.Dispatch app=dispatch('LibraryManager.Application') lib=app.OpenLibrary(str(path)) out=[] # LibraryManager exposes Partitions as an indexed method (not a COM collection). parts = lib.Partitions(7) count = int(_value(parts, 'Count', 0) or 0) for i in range(1, count + 1): partition = _item(parts, i) for j in range(1, int(_value(partition, 'Count', 0) or 0) + 1): x=_item(partition, j) out.append(CbbRecord(str(_value(x, 'Name', x)), str(_value(x, 'PartitionName', 'Reusable Blocks')))) if not out: folder = Path(path).parent / 'ReusableBlocksLP' if folder.is_dir(): out.extend(CbbRecord(x.name, 'Reusable Blocks') for x in folder.iterdir() if x.is_dir()) return LibraryReadResult(tuple(sorted(set(out), key=lambda x:x.name))) except Exception as error: return LibraryReadResult((), str(error))