#include "controller/tkrEditorController.h" #include "model/tkrTikzDocument.h" #include "ui/tkrDiagramScene.h" #include #include #include #include #include #include namespace TikzRefinery { tkrEditorController::tkrEditorController(tkrTikzDocument &document, tkrDiagramScene &diagramScene, QObject *pParent) : QObject(pParent), m_refDocument(document), m_refScene(diagramScene) { connect(&m_refScene, &tkrDiagramScene::dragPreviewRequested, this, &tkrEditorController::handleDragPreview); connect(&m_refScene, &tkrDiagramScene::dragCommitRequested, this, &tkrEditorController::handleDragCommit); connect(&m_refScene, &tkrDiagramScene::dragCancelled, this, &tkrEditorController::cancelDrag); } OperationResult tkrEditorController::openDocument(const QString &strFilePath) { QFile fileSource(strFilePath); if (!fileSource.open(QIODevice::ReadOnly)) { return {false, fileSource.errorString()}; } const QByteArray baSource = fileSource.readAll(); if (fileSource.error() != QFileDevice::NoError) { return {false, fileSource.errorString()}; } m_refScene.cancelInteraction(); m_refDocument.loadSource(baSource, QFileInfo(fileSource).absoluteFilePath()); m_baFileBaseline = baSource; const OperationResult resultParse = refreshParsedDocument(); emit documentChanged(); // Reading succeeded even when source interpretation is unavailable. return {true, resultParse.strMessage}; } OperationResult tkrEditorController::saveDocument() { m_refScene.cancelInteraction(); if (!m_refDocument.isLoaded()) { return {false, QStringLiteral("No document is open.")}; } if (!m_refDocument.hasUnsavedChanges()) { return {true, QStringLiteral("No changes to save.")}; } QFile fileExisting(m_refDocument.filePath()); if (!fileExisting.open(QIODevice::ReadOnly)) { return {false, fileExisting.errorString()}; } const QByteArray baExisting = fileExisting.readAll(); if (fileExisting.error() != QFileDevice::NoError) { return {false, fileExisting.errorString()}; } fileExisting.close(); if (baExisting != m_baFileBaseline) { return {false, QStringLiteral("The file changed outside the editor. Saving was cancelled.")}; } QSaveFile fileOutput(m_refDocument.filePath()); fileOutput.setDirectWriteFallback(false); if (!fileOutput.open(QIODevice::WriteOnly)) { return {false, fileOutput.errorString()}; } if (fileOutput.write(m_refDocument.sourceBytes()) != m_refDocument.sourceBytes().size()) { fileOutput.cancelWriting(); return {false, fileOutput.errorString()}; } if (!fileOutput.commit()) { return {false, fileOutput.errorString()}; } m_baFileBaseline = m_refDocument.sourceBytes(); m_refDocument.markSaved(); emit documentChanged(); return {true, QStringLiteral("Document saved.")}; } OperationResult tkrEditorController::refreshParsedDocument() { if (!m_refDocument.isLoaded()) { return {false, QStringLiteral("No document is open.")}; } const ParseResult parseResult = m_parser.parse(m_refDocument.sourceBytes(), m_refDocument.revision()); m_comparisonExtent = parseResult.comparisonExtent; m_refScene.resetDiagram(); // Clear records even on failure, so a failed refresh cannot leave stale geometry. const OperationResult resultClear = m_refDocument.setParsedElements({}, m_refDocument.revision()); if (!resultClear.bSucceeded) { return resultClear; } if (!parseResult.bSafeToEdit) { const QString strMessage = parseResult.listDiagnostics.join(QLatin1Char('\n')); emit statusChanged(strMessage); return {false, strMessage}; } const OperationResult resultStore = m_refDocument.setParsedElements( parseResult.vecElements, m_refDocument.revision()); if (!resultStore.bSucceeded) { emit statusChanged(resultStore.strMessage); return resultStore; } const OperationResult resultDisplay = m_refScene.displayElements( m_refDocument.elements(), m_mapper, parseResult.comparisonExtent); if (!resultDisplay.bSucceeded) { m_refDocument.setParsedElements({}, m_refDocument.revision()); } emit statusChanged(resultDisplay.bSucceeded ? QStringLiteral("Displayed %1 element(s). Drag to move; select a rectangle, then drag a corner to resize. Esc cancels; Ctrl+S saves.") .arg(parseResult.vecElements.size()) : resultDisplay.strMessage); return resultDisplay; } void tkrEditorController::handleDragPreview(const DragUpdate &dragUpdate) { const OperationResult resultValid = validateDrag(dragUpdate); if (!resultValid.bSucceeded) { m_refScene.cancelInteraction(); return; } const GestureGeometry geometry = prepareGesture(dragUpdate); if (!geometry.result.bSucceeded) { m_refScene.cancelInteraction(); return; // Preview failures do not produce repeated rejection banners. } const OperationResult resultPreview = m_refScene.previewGeometry(dragUpdate.uElementId, dragUpdate.uDocumentRevision, m_mapper.mapToScene(geometry.ptFirstTikzPosition), m_mapper.mapToScene(geometry.ptSecondTikzPosition), dragUpdate.dragKind != DragKind::WholeElement); if (!resultPreview.bSucceeded) { m_refScene.cancelInteraction(); return; } emit statusChanged(QStringLiteral("Editing element. Release to apply; Esc cancels.")); } void tkrEditorController::handleDragCommit(const DragUpdate &dragUpdate) try { const OperationResult resultValid = validateDrag(dragUpdate); if (!resultValid.bSucceeded) { rejectDrag(resultValid.strMessage); return; } const auto iterElement = std::find_if(m_refDocument.elements().cbegin(), m_refDocument.elements().cend(), [&dragUpdate](const ElementRecord &element) { return element.uElementId == dragUpdate.uElementId; }); const GestureGeometry geometry = prepareGesture(dragUpdate); QVector vecEdits; const OperationResult resultPrepare = m_editService.prepareEdits(*iterElement, m_refDocument.sourceBytes(), geometry, vecEdits); if (!resultPrepare.bSucceeded) { rejectDrag(resultPrepare.strMessage); return; } if (vecEdits.isEmpty()) { refreshParsedDocument(); m_refScene.selectElement(dragUpdate.uElementId); emit statusChanged(QStringLiteral("No coordinate change.")); return; } // Validate the entire proposed source and display before mutating the model. const QString strDescription = dragUpdate.dragKind == DragKind::WholeElement ? QStringLiteral("Move element") : QStringLiteral("Resize rectangle"); tkrTikzDocument documentCandidate = m_refDocument; const OperationResult resultCandidate = documentCandidate.applyCoordinateEdits(vecEdits, strDescription); if (!resultCandidate.bSucceeded) { rejectDrag(resultCandidate.strMessage); return; } const ParseResult parseCandidate = m_parser.parse(documentCandidate.sourceBytes(), documentCandidate.revision()); if (!parseCandidate.bSafeToEdit) { rejectDrag(parseCandidate.listDiagnostics.join(QLatin1Char('\n'))); return; } const OperationResult resultRecords = documentCandidate.setParsedElements(parseCandidate.vecElements, documentCandidate.revision()); if (!resultRecords.bSucceeded) { rejectDrag(resultRecords.strMessage); return; } const OperationResult resultDisplay = m_refScene.displayElements(documentCandidate.elements(), m_mapper, parseCandidate.comparisonExtent); if (!resultDisplay.bSucceeded) { rejectDrag(resultDisplay.strMessage); return; } const OperationResult resultApply = m_refDocument.acceptPreparedState(documentCandidate, dragUpdate.uDocumentRevision); if (!resultApply.bSucceeded) { rejectDrag(resultApply.strMessage); return; } m_comparisonExtent = parseCandidate.comparisonExtent; m_refScene.selectElement(dragUpdate.uElementId); emit documentChanged(); emit statusChanged(QStringLiteral("Element edited. Ctrl+S saves the updated source.")); } catch (const std::bad_alloc &) { rejectDrag(QStringLiteral("Insufficient memory to prepare this edit.")); } OperationResult tkrEditorController::undo() { return restoreHistory(false); } OperationResult tkrEditorController::redo() { return restoreHistory(true); } OperationResult tkrEditorController::restoreHistory(bool bRedo) try { // A pending mouse release must never commit a preview after restoration. m_refScene.cancelInteraction(); tkrTikzDocument documentCandidate = m_refDocument; const OperationResult resultCandidate = documentCandidate.restoreHistory(bRedo); if (!resultCandidate.bSucceeded) return resultCandidate; const ParseResult parseCandidate = m_parser.parse(documentCandidate.sourceBytes(), documentCandidate.revision()); if (!parseCandidate.bSafeToEdit) { return {false, parseCandidate.listDiagnostics.join(QLatin1Char('\n'))}; } const OperationResult resultRecords = documentCandidate.setParsedElements( parseCandidate.vecElements, documentCandidate.revision()); if (!resultRecords.bSucceeded) return resultRecords; const OperationResult resultDisplay = m_refScene.displayElements(documentCandidate.elements(), m_mapper, parseCandidate.comparisonExtent); if (!resultDisplay.bSucceeded) { refreshParsedDocument(); return resultDisplay; } const OperationResult resultRestore = m_refDocument.acceptPreparedState(documentCandidate, m_refDocument.revision()); if (!resultRestore.bSucceeded) { refreshParsedDocument(); return resultRestore; } m_comparisonExtent = parseCandidate.comparisonExtent; emit documentChanged(); const QString strMessage = bRedo ? QStringLiteral("Edit redone. Ctrl+S saves.") : QStringLiteral("Edit undone. Ctrl+S saves."); emit statusChanged(strMessage); return {true, strMessage}; } catch (const std::bad_alloc &) { refreshParsedDocument(); return {false, QStringLiteral("Insufficient memory to prepare history restoration.")}; } void tkrEditorController::cancelDrag() { refreshParsedDocument(); emit statusChanged(QStringLiteral("Edit cancelled. Source unchanged.")); } OperationResult tkrEditorController::validateDrag(const DragUpdate &dragUpdate) const { if (!m_refDocument.isLoaded() || dragUpdate.uDocumentRevision != m_refDocument.revision()) { return {false, QStringLiteral("The document changed during this drag.")}; } if (!std::isfinite(dragUpdate.ptInitialScenePosition.x()) || !std::isfinite(dragUpdate.ptInitialScenePosition.y()) || !std::isfinite(dragUpdate.ptCurrentScenePosition.x()) || !std::isfinite(dragUpdate.ptCurrentScenePosition.y())) { return {false, QStringLiteral("Unsupported or invalid drag.")}; } for (const ElementRecord &elementRecord : m_refDocument.elements()) { if (elementRecord.uElementId == dragUpdate.uElementId && elementRecord.uDocumentRevision == dragUpdate.uDocumentRevision) { return prepareGesture(dragUpdate).result; } } return {false, QStringLiteral("The dragged element is no longer available.")}; } GestureGeometry tkrEditorController::prepareGesture(const DragUpdate &dragUpdate) const { const auto iterElement = std::find_if(m_refDocument.elements().cbegin(), m_refDocument.elements().cend(), [&dragUpdate](const ElementRecord &element) { return element.uElementId == dragUpdate.uElementId; }); if (iterElement == m_refDocument.elements().cend()) return {{false, QStringLiteral("Element unavailable.")}, {}, {}}; return m_editService.prepareGeometry(*iterElement, dragUpdate, m_mapper, m_comparisonExtent, m_refScene.shapeProvider()); } void tkrEditorController::rejectDrag(const QString &strReason) { refreshParsedDocument(); emit statusChanged(QStringLiteral("Edit rejected: %1 Source unchanged.").arg(strReason)); } } // namespace TikzRefinery