first method
This commit is contained in:
parent
6f0a50ccff
commit
a922331793
30
bridge.py
30
bridge.py
|
@ -5,6 +5,8 @@ from PyQt6.QtCore import QObject, QVariant, pyqtSlot, pyqtSignal, QTimer
|
|||
from PyQt6.QtWebChannel import QWebChannel
|
||||
from PyQt6.QtWebEngineWidgets import QWebEngineView
|
||||
|
||||
from enums import KompasCommand
|
||||
from parser.main import KompasDocumentParser
|
||||
|
||||
class PythonEventEmitter(QObject):
|
||||
onEvent = pyqtSignal(str, "QVariantMap") # событие: тип + данные
|
||||
|
@ -22,31 +24,17 @@ class PythonJSBridge(QObject):
|
|||
|
||||
self.channel.registerObject("pyjs", self)
|
||||
self.channel.registerObject("pyjs_events", self.emitter)
|
||||
|
||||
# Запуск таймера для отправки событий
|
||||
self.timer = QTimer()
|
||||
self.timer.timeout.connect(self.send_timer_event)
|
||||
self.timer.start(1000) # раз в секунду
|
||||
|
||||
self.kompas = KompasDocumentParser()
|
||||
|
||||
@pyqtSlot(str, str, result=str)
|
||||
def callFromJS(self, command: str, data_json: str):
|
||||
print(f"[Python] Получена команда: {command}")
|
||||
data = None
|
||||
if command == KompasCommand.OPEN_KOMPAS:
|
||||
data = self.kompas.get_open_documents()
|
||||
|
||||
if command == "init":
|
||||
return json.dumps({"status": "ok", "message": "Инициализация завершена"})
|
||||
|
||||
elif command == "get_data":
|
||||
return json.dumps([["A1", "B1"], ["A2", "B2"]])
|
||||
|
||||
elif command == "get_sheets":
|
||||
return json.dumps(["Sheet1", "Sheet2"])
|
||||
|
||||
return json.dumps(None)
|
||||
return json.dumps(data)
|
||||
|
||||
def send_event_to_js(self, event_type: str, data: dict):
|
||||
self.emitter.onEvent.emit(event_type, data)
|
||||
|
||||
def send_timer_event(self):
|
||||
current_time = time.strftime("%H:%M:%S")
|
||||
print(f"[Python] Отправка события: {current_time}")
|
||||
self.emitter.onEvent.emit("timer", {"time": current_time})
|
||||
self.emitter.onEvent.emit(event_type, data)
|
|
@ -0,0 +1,8 @@
|
|||
from enum import Enum
|
||||
|
||||
class KompasCommand(str, Enum):
|
||||
OPEN_KOMPAS = "open_kompas"
|
||||
|
||||
@classmethod
|
||||
def has_value(cls, value):
|
||||
return any(value == item.value for item in cls)
|
13
main.py
13
main.py
|
@ -1,11 +1,19 @@
|
|||
# main.py
|
||||
import sys
|
||||
import pythoncom
|
||||
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
|
||||
from PyQt6.QtWebEngineWidgets import QWebEngineView
|
||||
from PyQt6.QtCore import QUrl
|
||||
from PyQt6.QtCore import QUrl, QThread
|
||||
|
||||
from config import MAIN_URL
|
||||
from bridge import PythonJSBridge
|
||||
from parser.main import KompasDocumentParser
|
||||
|
||||
|
||||
class KompasWorker(QThread):
|
||||
def run(self):
|
||||
pythoncom.CoInitialize()
|
||||
self.parser = KompasDocumentParser()
|
||||
|
||||
|
||||
class BrowserWindow(QMainWindow):
|
||||
|
@ -14,6 +22,9 @@ class BrowserWindow(QMainWindow):
|
|||
self.setWindowTitle("QT6 Браузер")
|
||||
self.resize(1000, 800)
|
||||
|
||||
self.kompas_thread = KompasWorker()
|
||||
self.kompas_thread.start()
|
||||
|
||||
container = QWidget()
|
||||
layout = QVBoxLayout()
|
||||
|
||||
|
|
|
@ -0,0 +1,78 @@
|
|||
import os
|
||||
import traceback
|
||||
import pythoncom
|
||||
from win32com.client import Dispatch, gencache
|
||||
|
||||
ids = {
|
||||
"api_5": "{0422828C-F174-495E-AC5D-D31014DBBE87}",
|
||||
"api_7": "{69AC2981-37C0-4379-84FD-5DD2F3C0A520}",
|
||||
"const": "{75C9F5D0-B5B8-4526-8681-9903C567D2ED}",
|
||||
}
|
||||
|
||||
|
||||
class KompasDocumentParser:
|
||||
def __init__(self):
|
||||
self.api5 = None
|
||||
self.api7 = None
|
||||
self.constants = None
|
||||
self.application = None
|
||||
self._init_kompas()
|
||||
|
||||
def _init_kompas(self):
|
||||
"""Инициализация API КОМПАС версий 5 и 7"""
|
||||
try:
|
||||
import pythoncom
|
||||
pythoncom.CoInitialize()
|
||||
|
||||
# Получаем API версии 5
|
||||
self.api5_module = gencache.EnsureModule(ids["api_5"], 0, 1, 0)
|
||||
self.api5 = self.api5_module.KompasObject(
|
||||
Dispatch("Kompas.Application.5")._oleobj_.QueryInterface(
|
||||
self.api5_module.KompasObject.CLSID, pythoncom.IID_IDispatch
|
||||
)
|
||||
)
|
||||
|
||||
# Получаем API версии 7
|
||||
self.api7_module = gencache.EnsureModule(ids["api_7"], 0, 1, 0)
|
||||
self.api7 = self.api7_module.IKompasAPIObject(
|
||||
Dispatch("Kompas.Application.7")._oleobj_.QueryInterface(
|
||||
self.api7_module.IKompasAPIObject.CLSID, pythoncom.IID_IDispatch
|
||||
)
|
||||
)
|
||||
|
||||
# Получаем константы
|
||||
constants_module = gencache.EnsureModule(ids["const"], 0, 1, 0)
|
||||
self.constants = constants_module.constants
|
||||
|
||||
# Правильное получение IApplication
|
||||
self.application = self.api7_module.IApplication(self.api7)
|
||||
self.application.Visible = True
|
||||
|
||||
except Exception as e:
|
||||
# Выводим полный traceback и сообщение об ошибке
|
||||
print("[ERROR] Ошибка при подключении к КОМПАС:")
|
||||
traceback.print_exc() # <-- Выводит номер строки, файл и стек
|
||||
raise RuntimeError(f"Ошибка при подключении к КОМПАС: {e}")
|
||||
|
||||
def get_open_documents(self):
|
||||
"""Возвращает список информации о всех открытых документах"""
|
||||
|
||||
documents = []
|
||||
docs_collection = self.application.Documents
|
||||
|
||||
for i in range(docs_collection.Count):
|
||||
try:
|
||||
doc = docs_collection.Item(i + 1) # Индексация с 1
|
||||
|
||||
documents.append(
|
||||
{
|
||||
"type": doc.DocumentType,
|
||||
"name": doc.Name,
|
||||
"path": doc.Path,
|
||||
"active": doc.Active,
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Ошибка при обработке документа #{i + 1}: {e}")
|
||||
|
||||
return documents
|
|
@ -0,0 +1,27 @@
|
|||
# kompas_worker.py
|
||||
from PyQt6.QtCore import QObject, pyqtSignal
|
||||
import pythoncom
|
||||
from parser.main import KompasDocumentParser
|
||||
|
||||
|
||||
class KompasWorker(QObject):
|
||||
result_ready = pyqtSignal(object)
|
||||
error_occurred = pyqtSignal(str)
|
||||
|
||||
def run_kompas(self):
|
||||
try:
|
||||
# Инициализируем COM правильно
|
||||
pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
|
||||
|
||||
# Выполняем работу с КОМПАС
|
||||
parser = KompasDocumentParser()
|
||||
documents = parser.get_open_documents()
|
||||
|
||||
# Отправляем результат обратно
|
||||
self.result_ready.emit(documents)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
error_msg = f"[Ошибка] {e}\n{traceback.format_exc()}"
|
||||
self.error_occurred.emit(error_msg)
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
Loading…
Reference in New Issue