Compare commits

...

3 Commits

Author SHA1 Message Date
d3960cdbf7 Merge pull request #28 from s-diaco/cursor/enter-key-submit-26b5
Some checks failed
Mirror to Gitea / mirror (push) Has been cancelled
Fix Enter key to create QC datasheet
2026-09-27 11:39:02 +03:30
Cursor Agent
a9c31148e0 Fix Enter key to submit QC sheet form
Some checks failed
Mirror to Gitea / mirror (push) Has been cancelled
Wrap fields in a form with type=submit Create button so Enter in
serial (or closed combobox) creates the datasheet without a mouse click.

Co-authored-by: Diaco Soltanpour <s-diaco@users.noreply.github.com>
2026-09-27 07:59:59 +00:00
e4cdb540e9 Fix intermittent win32com CLSIDToPackageMap errors on Windows. (#27)
Some checks failed
Mirror to Gitea / mirror (push) Has been cancelled
Corrupt gen_py early-binding cache is cleared and EnsureDispatch retried
(with late-bound Dispatch fallback), matching the manual Temp\gen_py workaround.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Diaco Soltanpour <s-diaco@users.noreply.github.com>
2026-09-22 23:43:35 +03:30
4 changed files with 226 additions and 53 deletions

View File

@@ -2,17 +2,78 @@
from __future__ import annotations from __future__ import annotations
import logging
import shutil
import sys
from pathlib import Path from pathlib import Path
# Excel xlMaximized — avoid win32.constants when gen_py early-binding cache is corrupt.
_XL_MAXIMIZED = -4137
_log = logging.getLogger("xlsx_clean.create")
def _is_gen_py_cache_error(exc: BaseException) -> bool:
"""True for the known corrupt gen_py AttributeError (CLSIDTo*Map missing)."""
if not isinstance(exc, AttributeError):
return False
msg = str(exc)
return "CLSIDToClassMap" in msg or "CLSIDToPackageMap" in msg
def _clear_gen_py_cache() -> Path | None:
"""Remove win32com's generated typelib cache and drop it from sys.modules."""
import win32com
gen_path = Path(win32com.__gen_path__)
for name in [m for m in sys.modules if m.startswith("win32com.gen_py")]:
del sys.modules[name]
if gen_path.is_dir():
shutil.rmtree(gen_path, ignore_errors=True)
return gen_path
return None
def _excel_application():
"""Return Excel.Application, recovering from a corrupt win32com gen_py cache.
``gencache.EnsureDispatch`` writes early-binding wrappers under ``%TEMP%\\gen_py``.
Interrupted or partial writes leave modules without ``CLSIDToClassMap`` /
``CLSIDToPackageMap``; deleting that folder and retrying fixes it (same as the
manual workaround). Falls back to late-bound ``Dispatch`` if rebuild still fails.
"""
import win32com.client as win32
try:
return win32.gencache.EnsureDispatch("Excel.Application")
except AttributeError as exc:
if not _is_gen_py_cache_error(exc):
raise
cleared = _clear_gen_py_cache()
_log.warning(
"Corrupt win32com gen_py cache (%s); cleared %s and retrying",
exc,
cleared or "(missing)",
)
try:
return win32.gencache.EnsureDispatch("Excel.Application")
except AttributeError as retry_exc:
if not _is_gen_py_cache_error(retry_exc):
raise
_log.warning(
"EnsureDispatch still failing after cache clear (%s); using late-bound Dispatch",
retry_exc,
)
return win32.Dispatch("Excel.Application")
def _bring_excel_to_front(excel, workbook) -> None: def _bring_excel_to_front(excel, workbook) -> None:
"""Maximize and force Excel ahead of other windows (e.g. NiceGUI).""" """Maximize and force Excel ahead of other windows (e.g. NiceGUI)."""
import win32com.client as win32
import win32con import win32con
import win32gui import win32gui
excel.Visible = True excel.Visible = True
excel.WindowState = win32.constants.xlMaximized excel.WindowState = _XL_MAXIMIZED
try: try:
workbook.Activate() workbook.Activate()
except Exception: except Exception:
@@ -57,16 +118,12 @@ def clean_workbook_com(
maximize: bool = True, maximize: bool = True,
) -> None: ) -> None:
"""Clear/set cells via Excel COM, SaveAs destination, leave Excel open.""" """Clear/set cells via Excel COM, SaveAs destination, leave Excel open."""
# Lazy import so Linux never loads pywin32. # Lazy import so Linux never loads pywin32 (only needed if callers import helpers).
import win32com.client as win32
source = Path(source) source = Path(source)
destination = Path(destination) destination = Path(destination)
destination.parent.mkdir(parents=True, exist_ok=True) destination.parent.mkdir(parents=True, exist_ok=True)
# AttributeError: ... has no attribute 'CLSIDToClassMap' excel = _excel_application()
# https://stackoverflow.com/questions/52889704
excel = win32.gencache.EnsureDispatch("Excel.Application")
excel.Visible = visible excel.Visible = visible
workbook = excel.Workbooks.Open(str(source.resolve())) workbook = excel.Workbooks.Open(str(source.resolve()))

View File

@@ -394,51 +394,53 @@
</div> </div>
<p class="subtitle">Create a new QC datasheet from the latest matching workbook.</p> <p class="subtitle">Create a new QC datasheet from the latest matching workbook.</p>
<div class="fields"> <form id="create-form">
<label class="field combobox" for="set-dropdown-input"> <div class="fields">
<span id="set-label" class="field-label">Select Set</span> <label class="field combobox" for="set-dropdown-input">
<input <span id="set-label" class="field-label">Select Set</span>
id="set-dropdown-input" <input
class="combobox-input" id="set-dropdown-input"
type="text" class="combobox-input"
autocomplete="off" type="text"
spellcheck="false" autocomplete="off"
role="combobox" spellcheck="false"
aria-expanded="false" role="combobox"
aria-controls="set-dropdown-panel" aria-expanded="false"
aria-autocomplete="list" aria-controls="set-dropdown-panel"
aria-labelledby="set-label" aria-autocomplete="list"
placeholder=" "> aria-labelledby="set-label"
<select id="set-dropdown" aria-labelledby="set-label" tabindex="-1"></select> placeholder=" ">
<span class="combobox-caret" aria-hidden="true">&#9662;</span> <select id="set-dropdown" aria-labelledby="set-label" tabindex="-1"></select>
<div id="set-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="set-label" hidden></div> <span class="combobox-caret" aria-hidden="true">&#9662;</span>
</label> <div id="set-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="set-label" hidden></div>
<label class="field combobox" for="ink-dropdown-input"> </label>
<span id="ink-label" class="field-label">Select Ink Color</span> <label class="field combobox" for="ink-dropdown-input">
<input <span id="ink-label" class="field-label">Select Ink Color</span>
id="ink-dropdown-input" <input
class="combobox-input" id="ink-dropdown-input"
type="text" class="combobox-input"
autocomplete="off" type="text"
spellcheck="false" autocomplete="off"
role="combobox" spellcheck="false"
aria-expanded="false" role="combobox"
aria-controls="ink-dropdown-panel" aria-expanded="false"
aria-autocomplete="list" aria-controls="ink-dropdown-panel"
aria-labelledby="ink-label" aria-autocomplete="list"
placeholder=" "> aria-labelledby="ink-label"
<select id="ink-dropdown" aria-labelledby="ink-label" tabindex="-1"></select> placeholder=" ">
<span class="combobox-caret" aria-hidden="true">&#9662;</span> <select id="ink-dropdown" aria-labelledby="ink-label" tabindex="-1"></select>
<div id="ink-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="ink-label" hidden></div> <span class="combobox-caret" aria-hidden="true">&#9662;</span>
</label> <div id="ink-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="ink-label" hidden></div>
<label class="field" for="serial-input"> </label>
<span id="serial-label" class="field-label">Serial:</span> <label class="field" for="serial-input">
<input id="serial-input" type="text" placeholder="e.g. 1234/A" aria-labelledby="serial-label"> <span id="serial-label" class="field-label">Serial:</span>
</label> <input id="serial-input" type="text" placeholder="e.g. 1234/A" aria-labelledby="serial-label">
</div> </label>
</div>
<div class="divider"></div> <div class="divider"></div>
<button id="create-button" type="button">Create datasheet</button> <button id="create-button" type="submit">Create datasheet</button>
</form>
<div id="status" class="status status-ready" role="status">Loading configuration...</div> <div id="status" class="status status-ready" role="status">Loading configuration...</div>
<p id="version" class="version"></p> <p id="version" class="version"></p>
</section> </section>
@@ -452,6 +454,7 @@
const setPanel = document.getElementById("set-dropdown-panel"); const setPanel = document.getElementById("set-dropdown-panel");
const inkPanel = document.getElementById("ink-dropdown-panel"); const inkPanel = document.getElementById("ink-dropdown-panel");
const serialInput = document.getElementById("serial-input"); const serialInput = document.getElementById("serial-input");
const createForm = document.getElementById("create-form");
const createBtn = document.getElementById("create-button"); const createBtn = document.getElementById("create-button");
const status = document.getElementById("status"); const status = document.getElementById("status");
const themeToggle = document.getElementById("theme-toggle"); const themeToggle = document.getElementById("theme-toggle");
@@ -738,7 +741,7 @@
} }
}); });
createBtn.addEventListener("click", async () => { async function createDatasheet() {
createBtn.disabled = true; createBtn.disabled = true;
try { try {
const result = await window.pywebview.api.create( const result = await window.pywebview.api.create(
@@ -750,6 +753,11 @@
} finally { } finally {
createBtn.disabled = false; createBtn.disabled = false;
} }
}
createForm.addEventListener("submit", async (event) => {
event.preventDefault();
await createDatasheet();
}); });
window.addEventListener("pywebviewready", initialize); window.addEventListener("pywebviewready", initialize);

105
tests/test_com_backend.py Normal file
View File

@@ -0,0 +1,105 @@
"""Tests for win32com gen_py cache recovery (no real Excel required)."""
from __future__ import annotations
import sys
from types import ModuleType, SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from xlsx_clean.com_backend import (
_clear_gen_py_cache,
_excel_application,
_is_gen_py_cache_error,
)
def _install_fake_win32com(*, ensure, dispatch=None, gen_path="/tmp/gen_py"):
"""Put fake win32com + win32com.client modules into sys.modules."""
win32com = ModuleType("win32com")
win32com.__gen_path__ = gen_path
client = ModuleType("win32com.client")
client.gencache = SimpleNamespace(EnsureDispatch=ensure)
client.Dispatch = dispatch if dispatch is not None else MagicMock()
return patch.dict(sys.modules, {"win32com": win32com, "win32com.client": client})
def test_is_gen_py_cache_error_matches_known_messages():
assert _is_gen_py_cache_error(
AttributeError(
"module 'win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x9' "
"has no attribute 'CLSIDToPackageMap'"
)
)
assert _is_gen_py_cache_error(
AttributeError("... has no attribute 'CLSIDToClassMap'")
)
assert not _is_gen_py_cache_error(AttributeError("something else"))
assert not _is_gen_py_cache_error(RuntimeError("CLSIDToPackageMap"))
def test_clear_gen_py_cache_removes_modules_and_directory(tmp_path):
gen_root = tmp_path / "gen_py"
bad = gen_root / "00020813-0000-0000-C000-000000000046x0x1x9"
bad.mkdir(parents=True)
(bad / "__init__.py").write_text("# corrupt", encoding="utf-8")
mod_name = "win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x9"
fake_mod = ModuleType(mod_name)
fake_win32com = ModuleType("win32com")
fake_win32com.__gen_path__ = str(gen_root)
with patch.dict(sys.modules, {"win32com": fake_win32com, mod_name: fake_mod}):
cleared = _clear_gen_py_cache()
assert cleared == gen_root
assert not gen_root.exists()
assert mod_name not in sys.modules
def test_excel_application_clears_cache_and_retries_ensure_dispatch():
excel = object()
ensure = MagicMock(
side_effect=[
AttributeError(
"module 'win32com.gen_py.00020813x0x1x9' has no attribute 'CLSIDToPackageMap'"
),
excel,
]
)
with (
_install_fake_win32com(ensure=ensure),
patch("xlsx_clean.com_backend._clear_gen_py_cache", return_value=None) as clear,
):
result = _excel_application()
assert result is excel
assert ensure.call_count == 2
clear.assert_called_once_with()
def test_excel_application_falls_back_to_dispatch_after_second_failure():
excel = object()
err = AttributeError("has no attribute 'CLSIDToClassMap'")
ensure = MagicMock(side_effect=[err, err])
dispatch = MagicMock(return_value=excel)
with (
_install_fake_win32com(ensure=ensure, dispatch=dispatch),
patch("xlsx_clean.com_backend._clear_gen_py_cache", return_value=None),
):
result = _excel_application()
assert result is excel
dispatch.assert_called_once_with("Excel.Application")
def test_excel_application_rethrows_unrelated_attribute_error():
ensure = MagicMock(side_effect=AttributeError("unrelated"))
with (
_install_fake_win32com(ensure=ensure),
pytest.raises(AttributeError, match="unrelated"),
):
_excel_application()

View File

@@ -21,6 +21,8 @@ def test_ui_asset_exists_and_has_required_bridge_content():
'id="set-label"', 'id="set-label"',
'id="ink-label"', 'id="ink-label"',
'id="serial-label"', 'id="serial-label"',
'id="create-form"',
'id="create-button" type="submit"',
"Create datasheet", "Create datasheet",
"status-ready", "status-ready",
"status-success", "status-success",
@@ -31,6 +33,7 @@ def test_ui_asset_exists_and_has_required_bridge_content():
"get_initial_data()", "get_initial_data()",
"get_inks(setDropdown.value)", "get_inks(setDropdown.value)",
"api.create(", "api.create(",
'createForm.addEventListener("submit"',
"finally", "finally",
'inputEl.value = selectEl.value || ""', 'inputEl.value = selectEl.value || ""',
'inputEl.addEventListener("mousedown", () => {\n open();\n });', 'inputEl.addEventListener("mousedown", () => {\n open();\n });',