Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d65d1fdf5c | ||
|
|
3cb1201b32 | ||
|
|
d37297b889 | ||
|
|
d9a616cdfb | ||
|
|
8e06815bc9 | ||
|
|
27b82c169e |
@@ -9,3 +9,8 @@ delivery/evidence/*.txt -whitespace
|
||||
# Keep captured observer CSV bytes and public runtime hashes reproducible.
|
||||
delivery/evidence/recovery-*.csv -text
|
||||
delivery/evidence/recovery-*.json text eol=lf
|
||||
|
||||
# Keep the frozen upstream blobs and their provenance byte-identical on checkout.
|
||||
demo/tikzrefinery/** -text -whitespace
|
||||
demo/snapshot.json -text
|
||||
demo/ci/*.sh text eol=lf
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
|
||||
# Intermediate documents and automatic conversions
|
||||
*.dvi
|
||||
# This exact upstream asset is part of the frozen, hash-verified demo input.
|
||||
!/demo/tikzrefinery/documents/assets/loop-example/loop-boxes.dvi
|
||||
*.xdv
|
||||
*-converted-to.*
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Add frozen TikZRefinery baseline and demo build pipeline
|
||||
|
||||
Provide a reproducible C++/Qt workload for the DevOps demonstration by importing
|
||||
TikZRefinery checkpoint `f4e3193d49a98efcf2f16c2aa22d6085ebe70f36`, baseline
|
||||
0.1.4-alpha. Preserve all 435 committed files, attribution and original byte
|
||||
identities, with a Git-blob/SHA-256 verification manifest. Keep upstream version
|
||||
and source identity separate from `1.0.<build>` delivery artifacts.
|
||||
|
||||
Add an artifact-only Jenkins definition and repeatable build helpers for native
|
||||
Qt compilation, eight CTest suites, both LaTeX report editions, Doxygen/Graphviz
|
||||
source extraction, load sampling and a versioned application image archive.
|
||||
Include a Windows packaging helper and bounded, non-root/offscreen package
|
||||
checks. Existing pricing deployments, release/recovery jobs and runner identities
|
||||
are retained. The separate provider-class naming change is not included.
|
||||
|
||||
Validation: fresh Windows and Droplet builds each passed all eight suites;
|
||||
the portable Windows package loaded its bundled provider without the development
|
||||
PATH. Both Windows report editions rebuilt and all 585 rendered pages matched
|
||||
the frozen reports. Cloud report builds resolved all 51 authored figure mappings;
|
||||
source extraction generated 25 class/collaboration graphs. Rehearsal image
|
||||
1.0.1 passed its read-only, network-isolated smoke check; downloaded archive,
|
||||
manifest, configuration and layer hashes were verified.
|
||||
|
||||
These results are command-line rehearsals. After review/merge, configure the
|
||||
separate Jenkins job from protected main with script path `demo/Jenkinsfile`
|
||||
and verify actual SCM checkout, stage/JUnit display, artifact archiving and
|
||||
download. Hold the issue-linked provider rename until that baseline run passes.
|
||||
See `demo/README.md` and `demo/evidence/baseline-20261125.json`.
|
||||
@@ -0,0 +1,295 @@
|
||||
# TikZRefinery DevOps demonstration script
|
||||
|
||||
Vincent Sun and Billy Ye | SSW 590 | December 2, 2026
|
||||
|
||||
Plan for **16 minutes of presentation and 4 minutes for questions or delays**.
|
||||
Demonstrate an issue becoming a reviewed source change, a cloud build, automated
|
||||
test results and a versioned application artifact. TikZRefinery supplies the C++/Qt
|
||||
workload; Gitea, Jenkins and Grafana supply the workflow and operational view.
|
||||
|
||||
This is a rehearsal plan. Before the final rehearsal, complete the reviewed
|
||||
baseline Jenkins run and record the actual issue, change, job URL and build number.
|
||||
The proposed provider naming refactor remains a candidate from the senior-project
|
||||
handoff. Prepare its issue/comment and patch only after that baseline succeeds.
|
||||
Zammad is a separate assignment. The unfinished VPN is outside this demonstration.
|
||||
|
||||
## Preparation before the presentation
|
||||
|
||||
Suggested roles: Vincent operates Git, Jenkins and the application; Billy explains
|
||||
configuration and the tool comparison, and performs his own peer review. Agree on
|
||||
the split together and rehearse the handovers. Approval must reflect Billy's actual
|
||||
review, even during the timed demonstration.
|
||||
|
||||
Complete these steps before calling the walkthrough ready:
|
||||
|
||||
- Merge the reviewed security and baseline PRs, preserving both manual records.
|
||||
Their current references are [security PR 30](https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/pulls/30)
|
||||
and [baseline PR 31](https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/pulls/31).
|
||||
- Configure the separate artifact job to load `demo/Jenkinsfile` from reviewed
|
||||
`main`. Run it once and verify SCM checkout, stage execution, JUnit display,
|
||||
artifact archiving, a downloaded artifact and its provenance/checksum. The
|
||||
existing PR check and the new artifact job are separate checks.
|
||||
- After that baseline passes, agree on the live issue/change and rehearse the
|
||||
feature-branch, review, merge and artifact-build sequence. Reserve the actual
|
||||
demonstration commit/push for the assessed workflow.
|
||||
- Preserve the original snapshot manifest. The current verifier deliberately
|
||||
rejects any changed imported byte. An intentional product increment needs an
|
||||
explicit, tested provenance record for its changed files; do not simply disable
|
||||
verification or continue claiming all files are unchanged from the original.
|
||||
- Record the real demo issue URL, branch, expected behavior, baseline build URL,
|
||||
artifact job URL and last successful fallback build. These values are pending.
|
||||
- Sign in to Gitea, Jenkins and Grafana privately before screen sharing. Check Git
|
||||
authentication beforehand; pause sharing if a password/token prompt appears.
|
||||
- Test HTTPS from the actual classroom network. The cloud workers avoid the
|
||||
laptop-to-Droplet SSH connection that previously failed on school Wi-Fi.
|
||||
- Ensure the trusted agent is online and idle, toolchain images are present and
|
||||
disk/memory headroom is adequate. Avoid overlapping manual and delivery builds
|
||||
on this single-CPU host. Use normal build settings; do not clear shared caches.
|
||||
- Open the issue, source diff, PR, artifact job, Grafana dashboard and artifact
|
||||
output tabs in advance. Use the same build number throughout the presentation.
|
||||
- Keep a completed Jenkins run and its downloaded artifacts available as a
|
||||
clearly labelled fallback. Earlier SSH rehearsals are not Jenkins results.
|
||||
|
||||
The November 25 cloud rehearsal sampled approximately 146 seconds for native
|
||||
build/tests, 75 seconds for reports, 10 seconds for architecture and 49 seconds for
|
||||
the final package. These are sampled phase spans, not a measured Jenkins duration.
|
||||
Measure the real job before accepting this timing plan.
|
||||
|
||||
## Timed walkthrough
|
||||
|
||||
| Time | Lead | Show and do |
|
||||
| --- | --- | --- |
|
||||
| 0:00-1:00 | Vincent | Introduce the application and the issue-to-artifact workflow. |
|
||||
| 1:00-2:00 | Vincent | Select the existing demo issue and post the planned-change comment. |
|
||||
| 2:00-4:00 | Both | Make the agreed meaningful change, inspect the diff, commit/push, then review and merge through Gitea. |
|
||||
| 4:00-4:30 | Vincent | Trigger the artifact job from the reviewed main revision. |
|
||||
| 4:30-6:45 | Billy | Explain configuration while the build runs. |
|
||||
| 6:45-8:45 | Billy | Present the two-tool SWOT chart below. |
|
||||
| 8:45-10:00 | Vincent | Show live stages and cloud CPU/memory observations. |
|
||||
| 10:00-12:00 | Vincent | Show tests, compiled report, versioned image archive and source identity. |
|
||||
| 12:00-13:15 | Billy | Open the source-generated architecture output for the bonus. |
|
||||
| 13:15-14:30 | Vincent | Illustrate the desktop workload using the verified Windows package. |
|
||||
| 14:30-16:00 | Both | Recap traceability, protections and measured limits. |
|
||||
| 16:00-20:00 | Both | Questions and timing reserve. |
|
||||
|
||||
### Opening and issue tracking
|
||||
|
||||
**Vincent:** "TikZRefinery is a desktop editor for a supported subset of TikZ. We
|
||||
use a frozen senior-project checkpoint as the application workload in our DevOps
|
||||
repository. The application's upstream baseline is 0.1.4-alpha. Our delivery
|
||||
artifact has a separate version, so we can trace a build without rewriting the
|
||||
senior project's history."
|
||||
|
||||
"We will follow one issue through a source change, Git review, cloud compilation,
|
||||
automated tests and a packaged result. This lets us explain how the tools work
|
||||
together using a real application."
|
||||
|
||||
Open the agreed existing issue. Show its acceptance criterion and submit a short
|
||||
comment describing the work about to happen and how it will be checked. Prepare
|
||||
the final wording after baseline verification, using the actual agreed change.
|
||||
Read its intent aloud rather than reading every field.
|
||||
|
||||
### Source update and review
|
||||
|
||||
Perform the rehearsed edit after the issue comment. Show the meaningful source
|
||||
diff and explain the effect in one sentence. Run these checks from the demo
|
||||
checkout, then stage only the agreed files:
|
||||
|
||||
```powershell
|
||||
git status --short --branch
|
||||
git diff --check
|
||||
git diff --stat
|
||||
```
|
||||
|
||||
Use a commit message that describes the actual change and references the real
|
||||
issue. Push the feature branch using the established Gitea login flow. Keep
|
||||
credentials off screen. Show the pushed commit and PR. Billy reviews it, checks
|
||||
the configured checks and submits his own decision. Vincent merges only after
|
||||
the required approval and successful checks.
|
||||
|
||||
**Billy:** "Gitea keeps the issue, source revision, review and merge connected.
|
||||
The required PR checks protect main. Our artifact job then builds from that
|
||||
reviewed main revision on the trusted cloud worker."
|
||||
|
||||
If review or checks take longer than rehearsed, use the explanation/SWOT slots
|
||||
while waiting. Keep their actual result visible; do not force a merge or present
|
||||
an earlier green result as the current one.
|
||||
|
||||
### Trigger and configuration explanation
|
||||
|
||||
Open the separate artifact job and trigger its normal build after main contains
|
||||
the reviewed increment. Show the build URL and checked-out revision.
|
||||
|
||||
**Vincent:** "The job checks source provenance before compiling. It runs the
|
||||
application tests, builds both LaTeX report editions, extracts diagrams from C++
|
||||
and packages an application image. A failed gate prevents a successful package."
|
||||
|
||||
**Billy:** "We keep the orchestration in source control, so a reviewer can see
|
||||
the build policy alongside the application. The job uses our existing trusted
|
||||
agent. Docker access makes that worker privileged with respect to the host, so
|
||||
unreviewed source does not belong on it."
|
||||
|
||||
Use this configuration tour; explain purpose rather than reading syntax aloud:
|
||||
|
||||
| File | Point to explain |
|
||||
| --- | --- |
|
||||
| `demo/Jenkinsfile` | Reviewed-main ancestry check, named stages, one concurrent build per job, timeout, JUnit and archived artifacts. |
|
||||
| `demo/ci/run-cloud.sh` | Agent-volume path mapping; sequential work; offline, read-only build containers with CPU, RAM and PID limits. The native/report/architecture limit is 768 MiB RAM and 0.75 CPU. |
|
||||
| `demo/toolchain.json` and `demo/ci/toolchain.Dockerfile` | Verified image IDs plus the compiler, Qt, LaTeX, Doxygen and Graphviz environment. Package inventory records what was installed. |
|
||||
| `demo/ci/build-report.sh` | Disposable report build, bibliography/index/reference work and figure-index validation. Historical canonical PDFs remain preserved. |
|
||||
| `demo/ci/package.py` and `demo/ci/application.Dockerfile` | Eight required passing suites, versioned image, real provider module, non-root runtime and bounded headless smoke check. |
|
||||
| `.gitea/workflows/manual.yml` | The existing Actions job builds the cumulative manual on main using `latex-local` and uploads its PDF and diagnostics. Its pinned action revisions make dependencies explicit. |
|
||||
|
||||
### Gitea Actions and Jenkins SWOT comparison
|
||||
|
||||
Use this as the required chart. The tradeoffs describe this group's deployment;
|
||||
they do not claim one tool is universally better.
|
||||
|
||||
| SWOT | Gitea Actions in this project | Jenkins in this project |
|
||||
| --- | --- | --- |
|
||||
| Strengths | Workflow YAML, source history and PDF artifacts are reached from the same Gitea project. The existing manual build is a compact, repeatable use case. | Named stages, test reports and artifacts make the multi-stage Qt/report/package workflow visible. The group also has established release and approval workflows. |
|
||||
| Weaknesses | The workflow depends on the runner label and compiler image being available. Our pinned legacy artifact action needs deliberate compatibility maintenance. | The controller, agents, plugins and Java runtime add maintenance work. The trusted worker's Docker access needs careful separation from unreviewed builds. |
|
||||
| Opportunities | Reuse the manual workflow for other course documents and strengthen source/artifact traceability without adding another control service. | Extend the verified baseline into rehearsed issue-linked increments and retain test, load and provenance records for each release. |
|
||||
| Threats | Runner outages or incompatible action changes can block builds. Overlapping heavy jobs compete for the same Droplet resources. | Runtime/plugin vulnerabilities, resource contention and an incorrectly scoped trusted job can affect the shared host. The team must keep review and runtime updates effective. |
|
||||
|
||||
**Billy:** "We use Actions for the cumulative manual and Jenkins for the richer
|
||||
application workflow. Both delegate work to separately operated workers, so
|
||||
availability, maintenance and trust still belong to us. We compare them using the
|
||||
work we actually operate."
|
||||
|
||||
For the tool mechanics, see the official
|
||||
[Gitea Actions overview](https://docs.gitea.com/usage/actions/overview/) and
|
||||
[Jenkins Pipeline handbook](https://www.jenkins.io/doc/book/pipeline/).
|
||||
The chart's deployment tradeoffs are the group's engineering assessment.
|
||||
|
||||
### Cloud execution and load
|
||||
|
||||
Open [the Group 1 SRE dashboard](https://metrics.yebilly.me/d/group1-sre/group-1-sre)
|
||||
with a time window covering the build. Show Jenkins' executing stage alongside
|
||||
the CPU and available-memory panels. If a panel refresh is too coarse, show the
|
||||
job's per-phase load CSV as additional evidence.
|
||||
|
||||
**Vincent:** "These processes run on The-Ocean, our 2 GiB, single-CPU Droplet.
|
||||
The stage limits bound the build containers while Gitea, Jenkins, monitoring and
|
||||
the earlier applications share the host. We observe CPU and available memory
|
||||
before and during the build, and check available disk for the output."
|
||||
|
||||
"The measurements describe the shared host. Other services and dashboard refresh
|
||||
intervals affect what we see, so we do not attribute every change solely to this
|
||||
job. We keep the actual build times and samples together."
|
||||
|
||||
Do not promise a particular peak or a cold build. Use the real chart and CSV
|
||||
values, units and timestamps; identify cache reuse if it affects the duration.
|
||||
|
||||
### Tests and deployment artifact
|
||||
|
||||
Open the current build's JUnit page. Explain the actual result. The baseline
|
||||
registers eight suites covering the provider contract, core foundations,
|
||||
rectangle/segment display, whole-element movement, rectangle resize, sidebar and
|
||||
session history. Module loading and compatibility checks exercise the real
|
||||
provider. These automated checks do not establish complete interactive acceptance.
|
||||
|
||||
Open the compiled `TikZRefinery-report.pdf` from that build. Then show:
|
||||
|
||||
- `TikZRefinery-1.0.N-linux-image.tar.gz`, using the actual Jenkins build number
|
||||
in place of `N`, and the matching `ssw590-tikzrefinery:1.0.N` image tag.
|
||||
- `delivery-info.json`: actual delivery version, upstream identity, downstream
|
||||
commit, execution kind and image ID.
|
||||
- `SHA256SUMS` and the package verification result.
|
||||
- The same build's test and load records.
|
||||
|
||||
**Vincent:** "Here major and minor identify the delivery line; the final component
|
||||
is the Jenkins build number. This is the required major.minor.changelist format.
|
||||
The metadata connects the artifact to its source and toolchain. SHA-256 checks
|
||||
detect byte changes during transfer; they do not establish authenticity by
|
||||
themselves."
|
||||
|
||||
"The image is a deployable Linux desktop application package with a headless
|
||||
runtime check. It is not a new website. The source is reviewed, the tests passed
|
||||
and the saved image's manifest, configuration and layers were verified."
|
||||
|
||||
Download the small metadata/report files live. Downloading the full image during
|
||||
the timed presentation is optional; its download/checksum procedure must already
|
||||
have passed in the baseline rehearsal. Cite the current build's real results.
|
||||
|
||||
### Source architecture bonus
|
||||
|
||||
Open the current `TikZRefinery-1.0.N-architecture.zip`, extract it and open
|
||||
`html/index.html`. Show one generated provider relationship graph and explain the
|
||||
interface/implementation relationship. The baseline rehearsal produced 25 source
|
||||
graphs; quote the current build's actual count if the increment changes it.
|
||||
|
||||
**Billy:** "Doxygen reads the C++ declarations and Graphviz draws the relationships.
|
||||
These graphs are included with the build output. The separately authored TikZ/UML
|
||||
report diagrams communicate the design; this output supplies source extraction."
|
||||
|
||||
### Windows application illustration
|
||||
|
||||
Use the verified portable Windows package to illustrate the workload. It is a
|
||||
separate Windows baseline build, not the Linux artifact just produced by Jenkins.
|
||||
Keep its `build-info.json` and source identity available if asked.
|
||||
|
||||
Before presenting, copy `demo/tikzrefinery/code/examples/explicit-coordinates/boxes-initial.tex`
|
||||
to an ignored rehearsal folder. Open that copy, move the right rectangle, resize a
|
||||
corner and use session undo/redo. Show how the source pane follows a committed
|
||||
edit. Save only the disposable copy if demonstrating Save.
|
||||
|
||||
**Vincent:** "The application edits existing supported shapes. The rectangle
|
||||
implementation is loaded as a separate module. Creation, folder browsing, plugin
|
||||
updating and an integrated LaTeX/PDF viewer remain planned. Our DevOps workflow
|
||||
builds and tests the implemented subset."
|
||||
|
||||
### Closing and questions
|
||||
|
||||
**Billy:** "We can trace the issue comment to a source change, reviewed main
|
||||
revision, cloud run, automated result and versioned artifact. The configuration
|
||||
and observed resource use explain how that workflow runs on our host."
|
||||
|
||||
**Vincent:** "We preserve failed results and prior artifacts rather than rewriting
|
||||
them. The next increments can use the same review and artifact trail. We have
|
||||
four minutes for questions."
|
||||
|
||||
Useful short answers:
|
||||
|
||||
- **Why two CI tools?** Actions builds the group manual; Jenkins orchestrates the
|
||||
application, report, tests and package with the group's established agent model.
|
||||
- **Does the laptop need Docker during the presentation?** The build workers run
|
||||
on the Droplet. The Windows GUI package runs natively on the laptop.
|
||||
- **What happens when a test fails?** The job stops before successful packaging;
|
||||
Jenkins retains available test results and diagnostics. Inspect that failure.
|
||||
- **Is the Linux GUI running in the browser?** No. The container is checked
|
||||
offscreen; the classroom GUI illustration uses the separate Windows package.
|
||||
- **Why keep two versions?** Upstream identifies the imported application
|
||||
checkpoint; the delivery version identifies an artifact produced by this job.
|
||||
|
||||
## Recovery within the time limit
|
||||
|
||||
| Observed problem | Response |
|
||||
| --- | --- |
|
||||
| Jenkins waits for the agent or another job | Show the queue/agent state, continue the explanation and retain the real timing. Do not start competing heavy jobs. |
|
||||
| Current build fails | Show the failed stage and diagnostics. Use the identified previous successful Jenkins build to explain the later stages, clearly distinguishing both runs. |
|
||||
| Classroom web request returns 403 | Check the actual source network against the approved web allowlist through the established maintenance procedure. Keep authentication and source restrictions enabled. |
|
||||
| Network or artifact download stalls | Show the completed run and pre-downloaded fallback files with their matching build/version. Do not label them as this live run. |
|
||||
| Live review takes longer than planned | Continue the configuration/SWOT explanation. Preserve the real review requirement and use the timing reserve. |
|
||||
| Time reaches 16 minutes | Stop optional GUI detail and additional graphs. Preserve time for questions. |
|
||||
|
||||
## Rubric evidence checklist
|
||||
|
||||
| Assessed area | Visible evidence |
|
||||
| --- | --- |
|
||||
| Issue tracking | Existing issue and newly posted plan comment before the edit. |
|
||||
| Version control | Meaningful diff, purpose-specific commit, push and real review/merge. |
|
||||
| Pipeline trigger | Current artifact build URL and triggering action. |
|
||||
| Build visibility | Native compilation, LaTeX and packaging stage progress. |
|
||||
| Automated tests | Current JUnit pass/fail page. |
|
||||
| Versioned deployment artifact | Current `1.0.N` image archive and provenance. |
|
||||
| Two-tool SWOT | The complete four-row comparison above. |
|
||||
| Configuration | Explain the Jenkins, workflow, Docker and build-script roles. |
|
||||
| Demo quality | Rehearsed handovers, clear source identities and timing. |
|
||||
| Cloud execution | Droplet worker, stage timing and real load observations. |
|
||||
| Architecture bonus | Source-generated graph opened from the current artifact. |
|
||||
|
||||
Assignment source: [Canvas Final Project Demo](https://sit.instructure.com/courses/188774/assignments/703597),
|
||||
checked November 25, 2026. Canvas lists December 2 at 11:59 p.m.; the demonstration
|
||||
itself has a 20-minute limit including questions. The script's speaker split and
|
||||
minute-by-minute allocation are rehearsal choices.
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
// Separate artifact-only demo job. Keep existing delivery/recovery jobs intact.
|
||||
pipeline {
|
||||
agent { label 'delivery-trusted' }
|
||||
options {
|
||||
disableConcurrentBuilds()
|
||||
timeout(time: 45, unit: 'MINUTES')
|
||||
buildDiscarder(logRotator(numToKeepStr: '10'))
|
||||
}
|
||||
environment { DELIVERY_VERSION = "1.0.${BUILD_NUMBER}" }
|
||||
stages {
|
||||
stage('Verify reviewed source and frozen baseline') {
|
||||
steps {
|
||||
sh 'python3 demo/ci/reset-output.py'
|
||||
sh 'git merge-base --is-ancestor HEAD origin/main'
|
||||
sh 'python3 demo/ci/verify-snapshot.py --require-tracked'
|
||||
}
|
||||
}
|
||||
stage('Build application and test provider') {
|
||||
steps { sh 'sh demo/ci/run-cloud.sh native' }
|
||||
}
|
||||
stage('Compile LaTeX reports') {
|
||||
steps { sh 'sh demo/ci/run-cloud.sh report' }
|
||||
}
|
||||
stage('Extract source architecture') {
|
||||
steps { sh 'sh demo/ci/run-cloud.sh architecture' }
|
||||
}
|
||||
stage('Package versioned artifact') {
|
||||
steps { sh 'sh demo/ci/run-cloud.sh package' }
|
||||
}
|
||||
}
|
||||
post {
|
||||
always {
|
||||
archiveArtifacts artifacts: 'build/demo/artifacts/*,build/demo/reports/*',
|
||||
allowEmptyArchive: true, fingerprint: true
|
||||
junit testResults: 'build/demo/reports/tests.xml', allowEmptyResults: true
|
||||
}
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
# TikZRefinery DevOps demo baseline
|
||||
|
||||
This directory imports the exact source checkpoint
|
||||
`f4e3193d49a98efcf2f16c2aa22d6085ebe70f36` from
|
||||
`https://github.com/Generic-Sun/TikZRefinery.git`. Its application/report baseline
|
||||
is **0.1.4-alpha**. The senior-design repository remains the development home.
|
||||
Its notices, author attribution and historical evidence are retained. No new
|
||||
project-wide licence is granted by this import.
|
||||
|
||||
`snapshot.json` records all 435 original Git blob IDs, SHA-256 hashes and sizes.
|
||||
`tikzrefinery/` contains raw committed blobs, not the senior checkout's untracked
|
||||
work or old package binaries. Git attributes preserve those bytes on Windows
|
||||
and Linux. Run `python demo/ci/verify-snapshot.py --require-tracked` from a Git
|
||||
checkout before and after a build. This checks the index as well as the files on
|
||||
disk, so an ignored but locally present upstream asset cannot hide an incomplete
|
||||
commit. Stage intended snapshot files before using that check. Exported SSH
|
||||
rehearsals without Git metadata can use the command without `--require-tracked`.
|
||||
Do not regenerate canonical PDFs or change product source during baseline verification.
|
||||
|
||||
The proposed provider-class naming correction remains reserved for a separate
|
||||
issue-linked demo increment after the baseline pipeline is verified. It is not
|
||||
part of this import. Keep that increment and the import distinguishable in Git.
|
||||
Neither a repository rename nor a commit/push is performed by these scripts.
|
||||
|
||||
## Build identities
|
||||
|
||||
The upstream `0.1.4-alpha` version and full source commit remain separate from
|
||||
the demo's `major.minor.changelist` delivery identifier. Jenkins uses
|
||||
`1.0.<BUILD_NUMBER>`. A command-line rehearsal defaults to `1.0.0` and explicitly
|
||||
records that it is not a Jenkins run. It uses a separate rehearsal image name.
|
||||
|
||||
Keep `build-info.json`, `delivery-info.json` and `upstream-snapshot.json` with
|
||||
the built application. BuildInfo reports the actual checkout seen by CMake;
|
||||
an exported cloud rehearsal with no Git checkout truthfully reports that identity
|
||||
as unavailable. Delivery metadata separately retains the upstream commit,
|
||||
downstream commit or parent, modified state, input hashes and execution kind.
|
||||
An old binary is never relabelled as the frozen source build.
|
||||
|
||||
## Windows application and report checks
|
||||
|
||||
Use the already-installed matching Qt kit, CMake, Ninja, MinGW and TinyTeX:
|
||||
|
||||
```powershell
|
||||
./demo/ci/build-windows.ps1 -DeliveryVersion 1.0.0
|
||||
```
|
||||
|
||||
The helper builds Release, runs all eight CTests, bundles the real rectangle DLL,
|
||||
uses `windeployqt` for compiler/Qt dependencies and includes the matching offscreen
|
||||
platform plugin for automated package checks. It refuses to overwrite a previous
|
||||
package. Override tool paths or `-OutputDirectory` for another workstation.
|
||||
The normal Windows platform plugin remains included for interactive use.
|
||||
|
||||
For a report rehearsal, copy the frozen tree into one task-local work directory
|
||||
and run its `documents/build-report.ps1` there with an explicit output directory.
|
||||
Its diagram-index generation writes to that disposable copy. Use the existing
|
||||
shared TinyTeX installation and the complete upstream sequence. Do not replace
|
||||
the imported canonical PDFs or historical index.
|
||||
|
||||
## Existing Droplet worker
|
||||
|
||||
The artifact-only `Jenkinsfile` uses the existing trusted delivery agent. It
|
||||
does not bind registry or deployment credentials and does not deploy to the
|
||||
pricing application environments. Its SCM definition must select reviewed
|
||||
`main`; its first stage verifies ancestry before executing the build scripts.
|
||||
Existing pricing release/recovery and manual-build jobs remain separate.
|
||||
|
||||
One-time administrator preparation:
|
||||
|
||||
```sh
|
||||
sh demo/ci/prepare-images.sh
|
||||
```
|
||||
|
||||
This verifies the existing manual compiler's full image ID, then builds a
|
||||
Qt/CMake/compiler/Doxygen image and a separate runtime base on the existing
|
||||
Droplet. Debian package versions are inventoried; rebuilding later may resolve
|
||||
newer packages and produce different image IDs. `toolchain.json` records the
|
||||
images actually verified for this baseline. The preparation output goes to
|
||||
`build/demo/toolchain-observed.json`; review it before updating that record.
|
||||
The ordinary pipeline refuses an unexpected local toolchain/runtime image ID.
|
||||
|
||||
Run stages sequentially from the checkout root:
|
||||
|
||||
```sh
|
||||
sh demo/ci/run-cloud.sh native
|
||||
sh demo/ci/run-cloud.sh report
|
||||
sh demo/ci/run-cloud.sh architecture
|
||||
DELIVERY_VERSION=1.0.0 sh demo/ci/run-cloud.sh package
|
||||
```
|
||||
|
||||
The wrapper accounts for the delivery agent's named-volume workspace: Docker
|
||||
bind sources must use the volume's host path, not its container-visible path.
|
||||
Application/report containers have no network, a read-only checkout/root,
|
||||
dropped capabilities, a private temporary filesystem and bounded CPU/RAM/PIDs.
|
||||
Only their dedicated output directory is writable. Each run clears its staging
|
||||
artifacts and reports, retaining compiled caches and Jenkins' archived history;
|
||||
a failure must not upload an older run's successful output. Heavy stages are sequential;
|
||||
do not overlap them with another manual or delivery build on this single-CPU host.
|
||||
|
||||
The native stage compiles the application and real provider and runs all eight
|
||||
offscreen suites, including incompatible-module rejection. The report stage
|
||||
builds both editions with latexmk's bibliography/index/reference passes and
|
||||
checks the upstream source/figure index. Architecture output comes from C++ via
|
||||
Doxygen/Graphviz, distinct from the authored TikZ diagrams.
|
||||
|
||||
Packaging requires the eight passing suites, compiled report and generated
|
||||
architecture. It builds a non-root application image, checks that its offscreen
|
||||
event loop stays running, and emits an image archive, architecture ZIP, reports,
|
||||
provenance and checksums under `build/demo/artifacts/`. Image names are immutable
|
||||
within this workflow; select a new delivery version instead of overwriting one.
|
||||
`verify-artifacts.py` checks every downloaded/staged checksum and the saved OCI
|
||||
manifest, configuration and layer digests, plus the architecture ZIP's entry point.
|
||||
It targets the existing Docker 29/containerd archive format and does not confuse
|
||||
the engine's manifest ID with the separate configuration digest.
|
||||
|
||||
The Linux image is a desktop application container, not a web service. Its
|
||||
default offscreen backend permits headless checks; displaying a real Linux GUI
|
||||
requires an appropriate display backend. Use the freshly built Windows package
|
||||
for the classroom's interactive application view. GUI-process and automated
|
||||
tests do not establish complete product acceptance.
|
||||
The application image directs its writable home/font cache into the bounded
|
||||
temporary mount; its root filesystem remains read-only during the smoke check.
|
||||
|
||||
## Verification boundary and current evidence
|
||||
|
||||
The task's ignored records are under `build/evidence/demo-baseline-20261125/`.
|
||||
Windows Release passed eight suites. The fresh portable package loaded its
|
||||
bundled Qt and rectangle module with the development toolchain absent from PATH.
|
||||
Both report editions rebuilt and all 585 rendered pages matched the frozen
|
||||
baseline at the comparison resolution. Cloud stage results are recorded as they
|
||||
actually complete; command-line execution is not labelled as a Jenkins build.
|
||||
|
||||
A real Jenkins run must additionally prove SCM checkout, stage scheduling,
|
||||
JUnit display, artifact archiving/download and the corresponding source/version
|
||||
identity. Publish the reviewed baseline before selecting it in a job. The
|
||||
provider rename remains pending until that verification succeeds.
|
||||
|
||||
The first real run, [Jenkins build 1](https://ci.yebilly.me/job/tikzrefinery-demo/1/),
|
||||
checked out merged main `d37297b` and stopped at the frozen-file gate: the global
|
||||
`*.dvi` ignore rule had excluded one original asset from the 434-file Git input,
|
||||
although the local and exported rehearsals contained all 435 files. It also
|
||||
exposed a missing JUnit reporting plugin. The correction retains the original
|
||||
1,268-byte blob, adds an exact ignore exception and checks tracked provenance.
|
||||
This failed run does not establish application compilation or artifact delivery.
|
||||
The [job setup and verification runbook](jenkins/README.md) records prerequisites
|
||||
and the remaining checks for the reviewed rerun.
|
||||
|
||||
## Demonstration and ownership
|
||||
|
||||
Use [the timed demonstration script](DEMO_SCRIPT.md) for the proposed speaker
|
||||
handoffs, configuration tour, two-tool SWOT and rubric evidence checklist.
|
||||
Finalize its live issue/change and build references after the baseline Jenkins
|
||||
run passes. The [November 25 web-access record](evidence/web-access-20261125.json)
|
||||
captures the authorized home-source addition without publishing the address.
|
||||
|
||||
The professor's stated evaluation scope is the DevOps workflow. Zammad remains
|
||||
a separate assignment and the unfinished VPN is not represented as implemented.
|
||||
The final demonstration must show an existing issue and planned-change comment,
|
||||
meaningful source change, commit/push, visible pipeline build/test/package,
|
||||
versioned output, configuration explanations and cloud load. Present a SWOT
|
||||
comparison of two tools actually used, such as Gitea Actions and Jenkins.
|
||||
Doxygen output is a candidate for the optional source-extraction bonus.
|
||||
|
||||
Per-stage CSVs sample the host CPU counters and memory available through the
|
||||
cloud agent's `/proc`, plus free space on its workspace filesystem. These are
|
||||
observations of the shared host, not proof every change was caused by this job.
|
||||
Use the existing Grafana dashboard during rehearsal to show the build window.
|
||||
Keep the complete demonstration, explanation and questions within 20 minutes.
|
||||
|
||||
No new Droplet or plan is required by this preparation; the existing paid host
|
||||
incurs transient build, storage and network use. Vincent owns the host and local
|
||||
runtime availability; Billy reviews group changes. Retain source, artifacts,
|
||||
test reports and required grading evidence. Remove only identified current-task
|
||||
build scratch after review. Never prune shared images/volumes, runner identities,
|
||||
older packages or unrelated coursework as part of demo cleanup.
|
||||
@@ -0,0 +1,5 @@
|
||||
ARG RUNTIME_IMAGE
|
||||
FROM ${RUNTIME_IMAGE}
|
||||
ENV HOME=/tmp XDG_CACHE_HOME=/tmp/.cache
|
||||
COPY --chown=1000:1000 . /opt/tikzrefinery/
|
||||
ENTRYPOINT ["/opt/tikzrefinery/TikZRefinery"]
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# Compile disposable copies; never refresh the frozen source's canonical PDFs/index.
|
||||
set -eu
|
||||
source=/workspace/demo/tikzrefinery
|
||||
out=/output/report
|
||||
mkdir -p "$out/source" "$out/results"
|
||||
cp -a "$source/." "$out/source/"
|
||||
cd "$out/source/documents/latex"
|
||||
for edition in TikZRefinerySubmission TikZRefinery; do
|
||||
folder="$out/results/$edition"
|
||||
mkdir -p "$folder"
|
||||
echo "Compiling $edition: LaTeX, bibliography, index and cross-references"
|
||||
if ! latexmk -pdf -interaction=nonstopmode -halt-on-error -file-line-error \
|
||||
-outdir="$folder" "$edition.tex" > "$folder/console.txt" 2>&1; then
|
||||
tail -60 "$folder/console.txt"; exit 1
|
||||
fi
|
||||
if grep -Eq '(^!|undefined references|undefined citations|Citation .* undefined|Reference .* undefined|Rerun to get cross-references right|Label\(s\) may have changed)' "$folder/$edition.log"; then
|
||||
echo "Unresolved report diagnostics: $edition" >&2; exit 1
|
||||
fi
|
||||
test -s "$folder/$edition.pdf"
|
||||
done
|
||||
# The upstream checker binds its index to all source inputs and final shipout maps.
|
||||
python3 ../update-diagram-index.py --build-directory "$out/results" --record-sources
|
||||
python3 ../update-diagram-index.py --build-directory "$out/results"
|
||||
cp "$out/results/TikZRefinerySubmission/TikZRefinerySubmission.pdf" /output/artifacts/TikZRefinery-report.pdf
|
||||
cp ../diagram-index.json /output/artifacts/diagram-index.json
|
||||
@@ -0,0 +1,56 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$QtKit = 'C:/Qt/6.12.0/mingw_64',
|
||||
[string]$CompilerBin = 'C:/Qt/Tools/mingw1310_64/bin',
|
||||
[string]$CMakeBin = 'C:/Qt/Tools/CMake_64/bin',
|
||||
[string]$NinjaBin = 'C:/Qt/Tools/Ninja',
|
||||
[string]$DeliveryVersion = '1.0.0',
|
||||
[string]$OutputDirectory = 'build/demo-windows',
|
||||
[string]$BuildDirectory,
|
||||
[string]$PythonExecutable = 'python'
|
||||
)
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$PSNativeCommandUseErrorActionPreference = $true
|
||||
$repository = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
|
||||
if ($DeliveryVersion -notmatch '^\d+\.\d+\.\d+$') { throw 'Use major.minor.changelist' }
|
||||
Push-Location $repository
|
||||
try {
|
||||
& $PythonExecutable demo/ci/verify-snapshot.py
|
||||
$output = (New-Item -ItemType Directory -Force $OutputDirectory).FullName
|
||||
$build = if ($BuildDirectory) { [IO.Path]::GetFullPath($BuildDirectory) } else { Join-Path $output 'build' }
|
||||
$package = Join-Path $output "TikZRefinery-windows-$DeliveryVersion"
|
||||
if (Test-Path $package) { throw "Preserve existing package; choose another output directory: $package" }
|
||||
$env:Path = "$QtKit/bin;$CompilerBin;$NinjaBin;" + $env:Path
|
||||
$cmake = Join-Path $CMakeBin 'cmake.exe'
|
||||
& $cmake -S demo/tikzrefinery/code -B $build -G Ninja -DCMAKE_BUILD_TYPE=Release `
|
||||
"-DCMAKE_PREFIX_PATH=$QtKit" "-DCMAKE_CXX_COMPILER=$CompilerBin/g++.exe" `
|
||||
"-DCMAKE_MAKE_PROGRAM=$NinjaBin/ninja.exe"
|
||||
& $cmake --build $build --parallel 4
|
||||
& (Join-Path $CMakeBin 'ctest.exe') --test-dir $build --output-on-failure `
|
||||
--output-junit (Join-Path $output 'tests.xml')
|
||||
New-Item -ItemType Directory -Path "$package/shape-plugins" -Force | Out-Null
|
||||
Copy-Item "$build/TikZRefinery.exe" $package
|
||||
Copy-Item "$build/shape-plugins/tkr_rectangle.dll" "$package/shape-plugins"
|
||||
& "$QtKit/bin/windeployqt.exe" --release --compiler-runtime --no-translations `
|
||||
--no-opengl-sw --no-system-d3d-compiler "$package/TikZRefinery.exe"
|
||||
# windeployqt selects qwindows for normal desktop use. Include the matching
|
||||
# offscreen plugin as well so package smoke checks need no visible window.
|
||||
Copy-Item "$QtKit/plugins/platforms/qoffscreen.dll" "$package/platforms"
|
||||
Copy-Item "$build/build-info.json" $package
|
||||
Copy-Item demo/snapshot.json "$package/upstream-snapshot.json"
|
||||
Copy-Item demo/tikzrefinery/code/examples "$package/examples" -Recurse
|
||||
$downstream = (& git rev-parse HEAD).Trim()
|
||||
$state = (& git status --porcelain --untracked-files=normal) -join "`n"
|
||||
[ordered]@{
|
||||
delivery_version = $DeliveryVersion
|
||||
upstream_commit = 'f4e3193d49a98efcf2f16c2aa22d6085ebe70f36'
|
||||
application_baseline = '0.1.4-alpha'
|
||||
downstream_commit = $downstream
|
||||
downstream_modified = [bool]$state
|
||||
execution = 'Windows command-line rehearsal; not a Jenkins run'
|
||||
} | ConvertTo-Json | Set-Content "$package/delivery-info.json" -Encoding utf8
|
||||
& $PythonExecutable demo/ci/verify-snapshot.py
|
||||
Compress-Archive -LiteralPath $package -DestinationPath "$package.zip"
|
||||
Get-FileHash "$package.zip" -Algorithm SHA256 | Format-List
|
||||
} finally { Pop-Location }
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Generate source-based diagrams, separate from the authored architecture."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
output = Path('/output/architecture')
|
||||
output.mkdir(exist_ok=True)
|
||||
configuration = output / 'Doxyfile'
|
||||
configuration.write_text('''PROJECT_NAME = TikZRefinery
|
||||
OUTPUT_DIRECTORY = /output/architecture
|
||||
INPUT = /workspace/demo/tikzrefinery/code/src /workspace/demo/tikzrefinery/code/plugins /workspace/demo/tikzrefinery/code/plugin-api
|
||||
RECURSIVE = YES
|
||||
FILE_PATTERNS = *.h *.cpp
|
||||
EXTRACT_ALL = YES
|
||||
EXTRACT_PRIVATE = YES
|
||||
GENERATE_HTML = YES
|
||||
GENERATE_LATEX = NO
|
||||
HAVE_DOT = YES
|
||||
CLASS_GRAPH = YES
|
||||
COLLABORATION_GRAPH = YES
|
||||
DOT_IMAGE_FORMAT = svg
|
||||
INTERACTIVE_SVG = NO
|
||||
QUIET = YES
|
||||
WARN_IF_UNDOCUMENTED = NO
|
||||
WARN_LOGFILE = /output/reports/doxygen-warnings.txt
|
||||
''')
|
||||
subprocess.run(['doxygen', str(configuration)], check=True)
|
||||
graphs = list((output / 'html').glob('*coll*graph.svg')) + list((output / 'html').glob('*inherit*graph.svg'))
|
||||
assert graphs, 'No source-based class graph was generated'
|
||||
print(f'PASS: generated {len(graphs)} class/collaboration graphs from C++ source')
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Package only successful tested builds; keep delivery and upstream identities separate."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
|
||||
root = Path.cwd()
|
||||
out = root / 'build/demo'
|
||||
version = os.environ.get('DELIVERY_VERSION', '1.0.0')
|
||||
assert re.fullmatch(r'\d+\.\d+\.\d+', version), 'Use major.minor.changelist'
|
||||
|
||||
def run(*args, **kwargs):
|
||||
return subprocess.check_output(args, text=True, stderr=subprocess.STDOUT, **kwargs).strip()
|
||||
|
||||
def digest(path):
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
tests = ET.parse(out / 'reports/tests.xml')
|
||||
cases = tests.findall('.//testcase')
|
||||
assert len(cases) == 8 and all(case.find('failure') is None and case.find('error') is None
|
||||
and case.find('skipped') is None for case in cases), 'Require all eight baseline suites'
|
||||
expected = {'rectangle_plugin_contract','core_foundations','rectangle_display',
|
||||
'segment_display','whole_element_drag','rectangle_resize','workspace_sidebar','session_history'}
|
||||
assert {case.attrib['name'] for case in cases} == expected, 'Wrong suite set'
|
||||
assert (out / 'artifacts/TikZRefinery-report.pdf').is_file()
|
||||
assert (out / 'architecture/html/index.html').is_file()
|
||||
snapshot = json.loads((root / 'demo/snapshot.json').read_text())
|
||||
jenkins = bool(os.environ.get('BUILD_URL'))
|
||||
try:
|
||||
downstream = run('git', 'rev-parse', 'HEAD')
|
||||
modified = bool(run('git', 'status', '--porcelain', '--untracked-files=normal'))
|
||||
except subprocess.CalledProcessError:
|
||||
assert not jenkins, 'Jenkins must retain its real checkout identity'
|
||||
downstream = os.environ.get('DOWNSTREAM_PARENT_COMMIT', 'unavailable')
|
||||
modified = True
|
||||
source_hashes = {p.relative_to(root / 'demo').as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in sorted((root / 'demo').rglob('*')) if p.is_file()}
|
||||
record = dict(delivery_version=version, application_baseline=snapshot['application_baseline'],
|
||||
upstream_repository=snapshot['upstream_repository'], upstream_commit=snapshot['upstream_commit'],
|
||||
downstream_commit_or_parent=downstream, downstream_modified=modified,
|
||||
execution='Jenkins' if jenkins else 'SSH command-line rehearsal; not a Jenkins run',
|
||||
build_url=os.environ.get('BUILD_URL'), source_sha256=source_hashes,
|
||||
toolchain=json.loads((root / 'demo/toolchain.json').read_text()))
|
||||
bundle = out / 'application-bundle'
|
||||
bundle.mkdir(exist_ok=True)
|
||||
(bundle / 'shape-plugins').mkdir(exist_ok=True)
|
||||
for source, destination in [(out/'native/TikZRefinery',bundle/'TikZRefinery'),
|
||||
(out/'native/shape-plugins/tkr_rectangle.so',bundle/'shape-plugins/tkr_rectangle.so'),
|
||||
(out/'native/build-info.json',bundle/'build-info.json'),
|
||||
(root/'demo/snapshot.json',bundle/'upstream-snapshot.json')]:
|
||||
shutil.copy2(source, destination)
|
||||
(bundle / 'delivery-info.json').write_text(json.dumps(record, indent=2) + '\n')
|
||||
image = ('ssw590-tikzrefinery' if jenkins else 'ssw590-tikzrefinery-rehearsal') + ':' + version
|
||||
exists = subprocess.run(['docker','image','inspect',image], stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode == 0
|
||||
assert not exists, f'Preserve existing artifact {image}; select a new delivery version'
|
||||
environment = dict(os.environ, DOCKER_BUILDKIT='0')
|
||||
subprocess.run(['docker','build','--memory=512m','--memory-swap=768m','--cpu-quota=50000',
|
||||
'--build-arg','RUNTIME_IMAGE=ssw590-demo-runtime:20261125',
|
||||
'-t',image,'-f','demo/ci/application.Dockerfile',str(bundle)],check=True,env=environment)
|
||||
record['application_image'] = image
|
||||
record['application_image_id'] = run('docker','image','inspect','-f','{{.Id}}',image)
|
||||
smoke = subprocess.run(['docker','run','--rm','--network','none','--read-only','--cap-drop','ALL',
|
||||
'--security-opt','no-new-privileges','--memory=256m','--memory-swap=384m',
|
||||
'--cpus=0.5','--pids-limit=128','--tmpfs','/tmp:rw,nosuid,nodev,size=32m',
|
||||
'--entrypoint','sh',image,'-c','timeout 5s ./TikZRefinery'],
|
||||
stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
|
||||
(out/'reports/application-smoke.txt').write_text(smoke.stdout)
|
||||
assert smoke.returncode == 124, ('Expected GUI event loop to remain running offscreen',smoke.returncode,smoke.stdout)
|
||||
archive = out / 'artifacts' / f'TikZRefinery-{version}-linux-image.tar.gz'
|
||||
with subprocess.Popen(['docker','save',image],stdout=subprocess.PIPE) as process:
|
||||
import gzip
|
||||
with gzip.open(archive, 'wb') as stream:
|
||||
shutil.copyfileobj(process.stdout,stream)
|
||||
assert process.wait() == 0
|
||||
with tarfile.open(archive,'r:gz') as tar:
|
||||
manifest = json.load(tar.extractfile('manifest.json'))
|
||||
assert image in manifest[0]['RepoTags']
|
||||
record['image_archive_sha256'] = digest(archive)
|
||||
(out/'artifacts/delivery-info.json').write_text(json.dumps(record,indent=2)+'\n')
|
||||
with zipfile.ZipFile(out/'artifacts'/f'TikZRefinery-{version}-architecture.zip','w',zipfile.ZIP_DEFLATED) as archive_docs:
|
||||
for file in sorted((out/'architecture/html').rglob('*')):
|
||||
if file.is_file():
|
||||
archive_docs.write(file,file.relative_to(out/'architecture'))
|
||||
checksums = []
|
||||
for path in sorted((out/'artifacts').iterdir()):
|
||||
if path.is_file() and path.name != 'SHA256SUMS':
|
||||
checksums.append(digest(path) + ' ' + path.name)
|
||||
(out/'artifacts/SHA256SUMS').write_text('\n'.join(checksums)+'\n')
|
||||
print(json.dumps({key:record[key] for key in ['delivery_version','execution','application_image','application_image_id']},indent=2))
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
# Administrator preparation on the existing host; no application/service restart.
|
||||
set -eu
|
||||
base=ssw590-manual-ci:20261007
|
||||
expected=sha256:5d24657a4578977fc7709165b82fc869f09a654a58ab4a0c8defd9d2cd662d5d
|
||||
[ "$(docker image inspect -f '{{.Id}}' "$base")" = "$expected" ] || {
|
||||
echo 'Existing manual toolchain ID differs; investigate before building.' >&2; exit 1;
|
||||
}
|
||||
mkdir -p build/demo
|
||||
export DOCKER_BUILDKIT=0
|
||||
docker build --force-rm --memory=512m --memory-swap=768m --cpu-quota=50000 \
|
||||
-t ssw590-demo-toolchain:20261125 -f demo/ci/toolchain.Dockerfile demo/ci
|
||||
docker build --force-rm --memory=512m --memory-swap=768m --cpu-quota=50000 \
|
||||
-t ssw590-demo-runtime:20261125 -f demo/ci/runtime.Dockerfile demo/ci
|
||||
python3 - <<'PY'
|
||||
import json, subprocess
|
||||
from pathlib import Path
|
||||
def identity(name):
|
||||
return subprocess.check_output(['docker','image','inspect','-f','{{.Id}}',name],text=True).strip()
|
||||
record = {name: identity(name) for name in ['ssw590-demo-toolchain:20261125','ssw590-demo-runtime:20261125']}
|
||||
Path('build/demo/toolchain-observed.json').write_text(json.dumps(record,indent=2)+'\n')
|
||||
print(json.dumps(record,indent=2))
|
||||
PY
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Clear per-run staging outputs, retaining compiler/report caches and archived runs."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
root = Path.cwd().resolve()
|
||||
assert (root / 'demo/snapshot.json').is_file(), 'Run from the demo repository root'
|
||||
for name in ('artifacts', 'reports'):
|
||||
target = root / 'build/demo' / name
|
||||
resolved = target.resolve()
|
||||
assert not target.is_symlink() and resolved == root / 'build/demo' / name
|
||||
assert resolved.is_relative_to(root / 'build/demo')
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
target.mkdir(parents=True)
|
||||
print('Fresh per-run artifacts/reports; build caches retained')
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/bin/sh
|
||||
# The same stages are used by Jenkins and explicitly labelled SSH rehearsals.
|
||||
set -eu
|
||||
phase=${1:?choose native, report, architecture or package}
|
||||
root=$(pwd)
|
||||
out="$root/build/demo"
|
||||
if [ "$phase" = native ]; then python3 demo/ci/reset-output.py; fi
|
||||
# The Docker daemon resolves bind sources on the host. Jenkins' workspace lives
|
||||
# inside its named volume, so its container-visible path is not a host path.
|
||||
case "$root" in
|
||||
/home/jenkins/agent/*)
|
||||
volume_root=$(docker volume inspect -f '{{.Mountpoint}}' ssw590-delivery-workspace)
|
||||
host_root="$volume_root/${root#/home/jenkins/agent/}"
|
||||
;;
|
||||
*) host_root="$root";;
|
||||
esac
|
||||
mkdir -p "$out/artifacts" "$out/reports"
|
||||
python3 demo/ci/verify-snapshot.py
|
||||
test -s demo/toolchain.json || { echo 'Prepare and verify the host images before this pipeline.' >&2; exit 1; }
|
||||
python3 - <<'PY'
|
||||
import json, subprocess
|
||||
for name, expected in json.load(open('demo/toolchain.json')).items():
|
||||
actual=subprocess.check_output(['docker','image','inspect','-f','{{.Id}}',name],text=True).strip()
|
||||
assert actual==expected, (name, 'local toolchain changed')
|
||||
PY
|
||||
toolchain=ssw590-demo-toolchain:20261125
|
||||
python3 demo/ci/sample-load.py "$out/reports/$phase-load.csv" &
|
||||
sampler=$!
|
||||
trap 'kill "$sampler" 2>/dev/null || true; wait "$sampler" 2>/dev/null || true' EXIT HUP INT TERM
|
||||
run() {
|
||||
docker run --rm --network none --read-only --cap-drop ALL \
|
||||
--security-opt no-new-privileges --memory=768m --memory-swap=1536m \
|
||||
--cpus=0.75 --pids-limit=256 --user "$(id -u):$(id -g)" \
|
||||
--tmpfs /tmp:rw,nosuid,nodev,size=128m -e HOME=/tmp -e QT_QPA_PLATFORM=offscreen \
|
||||
-e GIT_CONFIG_COUNT=1 -e GIT_CONFIG_KEY_0=safe.directory -e GIT_CONFIG_VALUE_0=/workspace \
|
||||
--mount "type=bind,source=$host_root,target=/workspace,readonly" \
|
||||
--mount "type=bind,source=$host_root/build/demo,target=/output" \
|
||||
-w /workspace "$toolchain" sh -eu -c "$1"
|
||||
}
|
||||
case "$phase" in
|
||||
native)
|
||||
echo '=== Build C++/Qt application and provider; run all registered CTests ==='
|
||||
run 'cmake -S demo/tikzrefinery/code -B /output/native -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build /output/native --parallel 1
|
||||
ctest --test-dir /output/native --output-on-failure --output-junit /output/reports/tests.xml
|
||||
cp /opt/demo-toolchain/packages.txt /output/reports/toolchain-packages.txt'
|
||||
;;
|
||||
report)
|
||||
echo '=== Compile both authored report editions ==='
|
||||
run 'sh demo/ci/build-report.sh'
|
||||
;;
|
||||
architecture)
|
||||
echo '=== Extract architecture from the frozen C++ source ==='
|
||||
run 'python3 demo/ci/extract-architecture.py'
|
||||
;;
|
||||
package)
|
||||
echo '=== Package versioned deployable application image and reports ==='
|
||||
python3 demo/ci/package.py
|
||||
python3 demo/ci/verify-artifacts.py
|
||||
;;
|
||||
*) echo 'Unknown phase' >&2; exit 1;;
|
||||
esac
|
||||
python3 demo/ci/verify-snapshot.py
|
||||
@@ -0,0 +1,8 @@
|
||||
FROM node:22-bookworm-slim@sha256:c3de60bf2f9dd0ac6370e6117950ff62d6e339527e7472301c9c78a017978392
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
libqt6widgets6 libqt6gui6 libqt6core6 qt6-qpa-plugins fonts-dejavu-core \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
ENV QT_QPA_PLATFORM=offscreen
|
||||
USER node
|
||||
WORKDIR /opt/tikzrefinery
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Read /proc host counters visible to the cloud agent; never inspect processes."""
|
||||
import csv
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
running = True
|
||||
def stop(*_):
|
||||
global running
|
||||
running = False
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
|
||||
def cpu():
|
||||
fields = [int(n) for n in Path('/proc/stat').read_text().splitlines()[0].split()[1:9]]
|
||||
return sum(fields), fields[3] + fields[4]
|
||||
|
||||
last_total, last_idle = cpu()
|
||||
with open(sys.argv[1], 'w', newline='') as stream:
|
||||
writer = csv.writer(stream)
|
||||
writer.writerow(['utc','host_cpu_percent','host_mem_available_kib','filesystem_free_bytes'])
|
||||
while running:
|
||||
time.sleep(1)
|
||||
total, idle = cpu()
|
||||
memory = dict(line.split(':', 1) for line in Path('/proc/meminfo').read_text().splitlines())
|
||||
usage = 100 * (1 - (idle-last_idle) / max(1, total-last_total))
|
||||
writer.writerow([datetime.now(timezone.utc).isoformat(),round(usage,2),
|
||||
int(memory['MemAvailable'].split()[0]),shutil.disk_usage('.').free])
|
||||
stream.flush()
|
||||
last_total, last_idle = total, idle
|
||||
@@ -0,0 +1,11 @@
|
||||
# Existing, tested TeX compiler image transferred to The-Ocean on November 14.
|
||||
# prepare-images.sh verifies its complete local image ID before this build.
|
||||
FROM ssw590-manual-ci:20261007
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
build-essential cmake ninja-build qt6-base-dev qt6-qpa-plugins \
|
||||
fonts-dejavu-core doxygen graphviz \
|
||||
&& mkdir -p /opt/demo-toolchain \
|
||||
&& dpkg-query -W -f='${Package} ${Version}\n' > /opt/demo-toolchain/packages.txt \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /workspace
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Check transport hashes and the saved OCI manifest/configuration/layer chain."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import tarfile
|
||||
import zipfile
|
||||
|
||||
folder = Path(sys.argv[1] if len(sys.argv) > 1 else 'build/demo/artifacts').resolve()
|
||||
for line in (folder / 'SHA256SUMS').read_text().splitlines():
|
||||
expected, name = line.split(' ', 1)
|
||||
assert Path(name).name == name and re.fullmatch(r'[0-9a-f]{64}', expected)
|
||||
with (folder / name).open('rb') as stream:
|
||||
assert hashlib.file_digest(stream, 'sha256').hexdigest() == expected, name
|
||||
record = json.loads((folder / 'delivery-info.json').read_text())
|
||||
version = record['delivery_version']
|
||||
assert re.fullmatch(r'\d+\.\d+\.\d+', version)
|
||||
with tarfile.open(folder / f'TikZRefinery-{version}-linux-image.tar.gz', 'r:gz') as archive:
|
||||
compatibility = json.load(archive.extractfile('manifest.json'))[0]
|
||||
assert record['application_image'] in compatibility['RepoTags']
|
||||
index = json.load(archive.extractfile('index.json'))
|
||||
descriptor = next(row for row in index['manifests'] if row['digest'] == record['application_image_id'])
|
||||
def blob_name(digest):
|
||||
assert re.fullmatch(r'sha256:[0-9a-f]{64}', digest)
|
||||
return 'blobs/sha256/' + digest.split(':')[1]
|
||||
manifest_bytes = archive.extractfile(blob_name(descriptor['digest'])).read()
|
||||
assert 'sha256:' + hashlib.sha256(manifest_bytes).hexdigest() == descriptor['digest']
|
||||
manifest = json.loads(manifest_bytes)
|
||||
references = [manifest['config'], *manifest['layers']]
|
||||
members = {member.name: member for member in archive.getmembers()}
|
||||
for reference in sorted(references, key=lambda row: members[blob_name(row['digest'])].offset_data):
|
||||
name = blob_name(reference['digest'])
|
||||
assert members[name].isfile(), name
|
||||
with archive.extractfile(name) as stream:
|
||||
assert 'sha256:' + hashlib.file_digest(stream, 'sha256').hexdigest() == reference['digest'], name
|
||||
with zipfile.ZipFile(folder / f'TikZRefinery-{version}-architecture.zip') as docs:
|
||||
assert 'html/index.html' in docs.namelist()
|
||||
print(f'PASS: version {version}, artifact checksums, OCI manifest/config/{len(manifest["layers"])} layers and architecture ZIP')
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Verify the exact frozen source input, independent of either Git checkout."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--require-tracked', action='store_true',
|
||||
help='Also verify that the Git index contains every original blob.')
|
||||
args = parser.parse_args()
|
||||
|
||||
DEMO = Path(__file__).resolve().parents[1]
|
||||
SOURCE = DEMO / 'tikzrefinery'
|
||||
manifest = json.loads((DEMO / 'snapshot.json').read_text(encoding='utf-8'))
|
||||
expected = manifest['files']
|
||||
if args.require_tracked:
|
||||
index = subprocess.check_output(
|
||||
['git', 'ls-files', '--stage', '-z', '--', 'demo/tikzrefinery'], cwd=DEMO.parent)
|
||||
tracked = {}
|
||||
for row in index.decode('utf-8').split('\0'):
|
||||
if not row:
|
||||
continue
|
||||
metadata, path = row.split('\t', 1)
|
||||
mode, blob, stage = metadata.split()
|
||||
assert stage == '0', ('Unresolved snapshot index entry', path)
|
||||
tracked[path.removeprefix('demo/tikzrefinery/')] = (mode, blob)
|
||||
assert set(tracked) == set(expected), {
|
||||
'untracked_snapshot_files': sorted(set(expected) - set(tracked)),
|
||||
'unexpected_tracked_files': sorted(set(tracked) - set(expected))}
|
||||
for name, identity in expected.items():
|
||||
assert tracked[name] == (identity['mode'], identity['git_blob']), (
|
||||
'Git index differs from the frozen upstream blob', name)
|
||||
actual = {p.relative_to(SOURCE).as_posix() for p in SOURCE.rglob('*') if p.is_file()}
|
||||
assert actual == set(expected), {'missing': sorted(set(expected) - actual),
|
||||
'extra': sorted(actual - set(expected))}
|
||||
for name, identity in expected.items():
|
||||
data = (SOURCE / name).read_bytes()
|
||||
assert hashlib.sha256(data).hexdigest() == identity['sha256'], name
|
||||
git_blob = hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest()
|
||||
assert git_blob == identity['git_blob'], name
|
||||
print(json.dumps({'result': 'passed', 'upstream_commit': manifest['upstream_commit'],
|
||||
'application_baseline': manifest['application_baseline'],
|
||||
'verified_files': len(expected),
|
||||
'git_index_verified': args.require_tracked}, indent=2))
|
||||
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"recorded_at_utc": "2026-11-26T00:35:06.371423+00:00",
|
||||
"upstream_commit": "f4e3193d49a98efcf2f16c2aa22d6085ebe70f36",
|
||||
"upstream_repository": "https://github.com/Generic-Sun/TikZRefinery.git",
|
||||
"application_baseline": "0.1.4-alpha",
|
||||
"verified_upstream_files": 435,
|
||||
"windows": {
|
||||
"tests_passed": 8,
|
||||
"portable_module_load": "passed without development PATH",
|
||||
"artifact": "TikZRefinery-windows-1.0.0.zip",
|
||||
"sha256": "f1ec99e422d960a82b341b5c5f3cbb5443208f5479c79420fe863cf9a5b169e6"
|
||||
},
|
||||
"cloud": {
|
||||
"execution": "SSH command-line rehearsal; not a Jenkins run",
|
||||
"tests_passed": 8,
|
||||
"image": "ssw590-tikzrefinery-rehearsal:1.0.1",
|
||||
"image_id": "sha256:be98447bc0128ea294e1d65467c107fe752fe15e98c9e733ff6d062b3802b6dc",
|
||||
"archive_sha256": "df81c32154fa8233d7cb78b6733525c5dce1c07662b588bd78437f4ee7969507",
|
||||
"source_graphs": 25,
|
||||
"figure_index_entries": 51,
|
||||
"loads": {
|
||||
"architecture-load": {
|
||||
"samples": 11,
|
||||
"first_utc": "2026-11-26T00:11:21.260377+00:00",
|
||||
"last_utc": "2026-11-26T00:11:31.267178+00:00",
|
||||
"sampled_span_seconds": 10.007,
|
||||
"host_cpu_peak_percent": 100.0,
|
||||
"host_mem_available_min_kib": 882268
|
||||
},
|
||||
"native-load": {
|
||||
"samples": 147,
|
||||
"first_utc": "2026-11-26T00:02:27.557402+00:00",
|
||||
"last_utc": "2026-11-26T00:04:53.692922+00:00",
|
||||
"sampled_span_seconds": 146.136,
|
||||
"host_cpu_peak_percent": 100.0,
|
||||
"host_mem_available_min_kib": 551432
|
||||
},
|
||||
"package-load": {
|
||||
"samples": 50,
|
||||
"first_utc": "2026-11-26T00:25:01.675756+00:00",
|
||||
"last_utc": "2026-11-26T00:25:50.842932+00:00",
|
||||
"sampled_span_seconds": 49.167,
|
||||
"host_cpu_peak_percent": 100.0,
|
||||
"host_mem_available_min_kib": 857376
|
||||
},
|
||||
"report-load": {
|
||||
"samples": 76,
|
||||
"first_utc": "2026-11-26T00:06:16.498330+00:00",
|
||||
"last_utc": "2026-11-26T00:07:31.564264+00:00",
|
||||
"sampled_span_seconds": 75.066,
|
||||
"host_cpu_peak_percent": 100.0,
|
||||
"host_mem_available_min_kib": 821652
|
||||
}
|
||||
}
|
||||
},
|
||||
"windows_report_render_comparison": [
|
||||
{
|
||||
"edition": "submission",
|
||||
"pages": 258,
|
||||
"render_dpi": 65,
|
||||
"identical_pages": 258,
|
||||
"differing_pages": [],
|
||||
"output_sha256": "850f98a70d286b94f2de3a857f1ed183cbce715a873f87f7c14930daa060f954"
|
||||
},
|
||||
{
|
||||
"edition": "developer",
|
||||
"pages": 327,
|
||||
"render_dpi": 65,
|
||||
"identical_pages": 327,
|
||||
"differing_pages": [],
|
||||
"output_sha256": "f002e78fa9cf6562e9ecf98cc31e3f6136a1961b8f45fb411ed262f695a9c937"
|
||||
}
|
||||
],
|
||||
"jenkins_verification": "pending reviewed baseline commit/merge, SCM run and artifact download",
|
||||
"remote_main_observed": "72bf10dcecc8db65dce4750c05bf841bea9b0834",
|
||||
"downstream_parent": "fbda9516fe384e245a311386f72c73480fafbfaa",
|
||||
"downstream_modified": true,
|
||||
"provider_rename": "not prepared or implemented; reserved until baseline Jenkins verification",
|
||||
"ownership": "Vincent handles commits/pushes; no publication performed"
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
{
|
||||
"observations_completed_utc": "2026-11-26T05:23:22Z",
|
||||
"job_url": "https://ci.yebilly.me/job/tikzrefinery-demo/",
|
||||
"settings": {
|
||||
"disabled": "false",
|
||||
"definition": "org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition",
|
||||
"url": "https://git.yebilly.me/ssw590-group1/vpn-dns-gateway.git",
|
||||
"branch": "*/main",
|
||||
"script_path": "demo/Jenkinsfile",
|
||||
"lightweight": "true",
|
||||
"trigger_count": 0
|
||||
},
|
||||
"existing_checkout_credential_reused": true,
|
||||
"readiness": {
|
||||
"observed_utc": "2026-11-26T05:23:22Z",
|
||||
"toolchain_images": {
|
||||
"ssw590-demo-toolchain:20261125": "sha256:b09f82b3ba76f4445ff596c8c9423ed97d1d4e0fb6de1a3396a43bea972a4471",
|
||||
"ssw590-demo-runtime:20261125": "sha256:ae1ded13e2320283ddc1f18892e3aebd5ce005c949bb56c62964313f37475dd9"
|
||||
},
|
||||
"memory_available_kib": 599628,
|
||||
"swap_free_kib": 1490012,
|
||||
"root_free_bytes": 5586022400,
|
||||
"agent_running": true,
|
||||
"manual_action_active": false
|
||||
},
|
||||
"first_run": {
|
||||
"build_url": "https://ci.yebilly.me/job/tikzrefinery-demo/1/",
|
||||
"revision": "d37297b88993fd8c5428c2e732f32f4c9324b51b",
|
||||
"result": "FAILURE",
|
||||
"duration_ms": 26453,
|
||||
"scm_checkout_verified": true,
|
||||
"main_ancestry_passed": true,
|
||||
"source_gate_error": "Missing original documents/assets/loop-example/loop-boxes.dvi; 434 of 435 originals tracked",
|
||||
"post_action_error": "No such DSL method junit; required plugin was absent",
|
||||
"native_report_architecture_package_stages": "skipped after source-gate failure",
|
||||
"deployable_artifact_produced": false
|
||||
},
|
||||
"reporting_plugin_preparation": {
|
||||
"observed_utc": "2026-11-26T05:21:32Z",
|
||||
"official_update_center": true,
|
||||
"plugins": {
|
||||
"junit": {
|
||||
"version": "1458.1460.vd53b_087eeb_2c",
|
||||
"required_core": "2.555.3"
|
||||
},
|
||||
"plugin-util-api": {
|
||||
"version": "7.1403.vd380b_c42e90c",
|
||||
"required_core": "2.555.3"
|
||||
},
|
||||
"font-awesome-api": {
|
||||
"version": "7.3.1-1013.v0835a_879ec6d",
|
||||
"required_core": "2.555.3"
|
||||
},
|
||||
"bootstrap5-api": {
|
||||
"version": "5.3.9-1156.va_4c7fef67c56",
|
||||
"required_core": "2.555.3"
|
||||
},
|
||||
"jquery3-api": {
|
||||
"version": "3.7.1-687.v68d468e40b_30",
|
||||
"required_core": "2.555.1"
|
||||
},
|
||||
"echarts-api": {
|
||||
"version": "6.1.0-1321.v86c4c5114494",
|
||||
"required_core": "2.555.3"
|
||||
},
|
||||
"antisamy-markup-formatter": {
|
||||
"version": "173.v680e3a_b_69ff3",
|
||||
"required_core": "2.479.1"
|
||||
},
|
||||
"prism-api": {
|
||||
"version": "1.30.0-741.v034eb_0b_0a_a_fa_",
|
||||
"required_core": "2.555.1"
|
||||
},
|
||||
"checks-api": {
|
||||
"version": "441.v54e82638ca_71",
|
||||
"required_core": "2.555.3"
|
||||
}
|
||||
},
|
||||
"installation_and_extensions_ui": "Success",
|
||||
"junit_enabled_ui": true,
|
||||
"junit_step_visible_in_snippet_generator": true,
|
||||
"controller_started_at": "2026-11-23T06:31:09.102475939Z",
|
||||
"restart_requested": false
|
||||
},
|
||||
"local_repair_validation": {
|
||||
"result": "passed",
|
||||
"indexed_snapshot": {
|
||||
"result": "passed",
|
||||
"upstream_commit": "f4e3193d49a98efcf2f16c2aa22d6085ebe70f36",
|
||||
"application_baseline": "0.1.4-alpha",
|
||||
"verified_files": 435,
|
||||
"git_index_verified": true
|
||||
},
|
||||
"missing_index_entry_rejected": true,
|
||||
"clean_index_export": {
|
||||
"result": "passed",
|
||||
"upstream_commit": "f4e3193d49a98efcf2f16c2aa22d6085ebe70f36",
|
||||
"application_baseline": "0.1.4-alpha",
|
||||
"verified_files": 435,
|
||||
"git_index_verified": false
|
||||
},
|
||||
"upstream_asset_sha256": "3e06555552c50c1f5abcac8a1d3fb2eedf7ff4a34c40d94859aa7d5082009a21",
|
||||
"clean_export_bytes": 11050972,
|
||||
"real_index_sha256_after_negative_test": "2633ae6ac5822ce1389418cf4faba97fbbfcc1eb7172c2852652f67060515000"
|
||||
},
|
||||
"monitoring_view": {
|
||||
"url": "https://metrics.yebilly.me/d/group1-sre/group-1-sre",
|
||||
"chrome_charts_rendered": [
|
||||
"CPU utilization",
|
||||
"available memory",
|
||||
"root filesystem availability",
|
||||
"HTTPS availability"
|
||||
],
|
||||
"window": "Last 30 minutes; 30-second refresh; America/New_York",
|
||||
"attribution_limit": "Shared host; build 1 did not execute application compilation"
|
||||
},
|
||||
"remaining": [
|
||||
"Human commit/push/review/merge of the asset and verifier correction",
|
||||
"Real Jenkins rerun from corrected reviewed main",
|
||||
"JUnit, stage, archive, download and source/version verification",
|
||||
"Separate Jenkins core 2.580.2 security maintenance",
|
||||
"Issue-linked product increment only after the baseline passes"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"authorized_by": "Vincent Sun",
|
||||
"event_date_eastern": "2026-11-25",
|
||||
"applied_at_utc": "2026-11-26T04:22:34.316662+00:00",
|
||||
"change": "Append current SSH connection IPv4 as /32 to existing CI_TEAM_IPS web allowlist",
|
||||
"personal_address_values_recorded": false,
|
||||
"existing_team_entries": 1,
|
||||
"new_team_entries": 2,
|
||||
"existing_entries_preserved": true,
|
||||
"compose_change_scope": "caddy environment CI_TEAM_IPS only",
|
||||
"recreated_service": "caddy",
|
||||
"validation": "passed",
|
||||
"proxy_image_and_persistent_mounts_preserved": true,
|
||||
"other_running_container_ids_preserved": true,
|
||||
"proxy_and_compose_source_files_unchanged": true,
|
||||
"root_only_rollback_directory": "/root/ssw590-web-access-20261125",
|
||||
"public_checks_at_utc": "2026-11-26T04:25:17.0999004Z",
|
||||
"home_anonymous_https": {
|
||||
"https://ci.yebilly.me/login": 200,
|
||||
"https://ci.yebilly.me/api/json": 403,
|
||||
"https://metrics.yebilly.me/login": 200,
|
||||
"https://metrics.yebilly.me/api/user": 401,
|
||||
"https://git.yebilly.me/": 200,
|
||||
"https://app.yebilly.me/health": 200,
|
||||
"https://staging.yebilly.me/health": 200
|
||||
},
|
||||
"unlisted_droplet_source_https": {
|
||||
"https://ci.yebilly.me/login": 403,
|
||||
"https://metrics.yebilly.me/login": 403
|
||||
},
|
||||
"chrome_observation": {
|
||||
"jenkins": "Sign in to Jenkins form visible",
|
||||
"grafana": "Existing authenticated session reached Grafana home"
|
||||
},
|
||||
"account_permissions_or_credentials_changed": false,
|
||||
"new_cloud_resources_or_plan_changes": false,
|
||||
"source_commit_or_push_performed_by_codex": false
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
# TikZRefinery Jenkins job
|
||||
|
||||
Use the separate [tikzrefinery-demo job](https://ci.yebilly.me/job/tikzrefinery-demo/).
|
||||
It was created after verification of baseline PR #31's merge `d37297b`.
|
||||
Existing pricing, recovery and multibranch jobs retain their configurations.
|
||||
|
||||
| Setting | Value |
|
||||
| --- | --- |
|
||||
| Item type | Pipeline |
|
||||
| Definition | Pipeline script from SCM; Git |
|
||||
| Repository | `https://git.yebilly.me/ssw590-group1/vpn-dns-gateway.git` |
|
||||
| Checkout credential | Existing `gitea-jenkins-bot`; no new credential |
|
||||
| Branch | `*/main` |
|
||||
| Script path | `demo/Jenkinsfile` |
|
||||
| Lightweight checkout | Enabled |
|
||||
| Triggers and parameters | None; trigger manually after review/merge |
|
||||
| Agent | Existing `delivery-trusted` label, one executor |
|
||||
| Concurrent builds | Disabled |
|
||||
| Pipeline timeout and retention | 45 minutes; ten builds |
|
||||
|
||||
The pipeline definition supplies the label, timeout, retention, source gates,
|
||||
stage sequence and report/artifact publishers. It binds no pricing deployment
|
||||
or registry credentials and performs no pricing promotion. Keep reviewed `main`
|
||||
as its SCM selection; do not switch it to a PR branch or use Replay to bypass
|
||||
the source gate.
|
||||
|
||||
## Controller and worker prerequisites
|
||||
|
||||
The controller must provide the JUnit Pipeline step, in addition to the existing
|
||||
Git, Declarative Pipeline and artifact archiving capabilities. Its official
|
||||
[JUnit plugin](https://plugins.jenkins.io/junit/) consumes the CTest XML report;
|
||||
it does not execute or replace the C++ tests. Use the compatible release offered
|
||||
by this controller's official update center, with its required dependencies.
|
||||
Record the actual installed version after verifying that installation completed.
|
||||
Do not install a release requiring a newer Jenkins core by forcing compatibility.
|
||||
|
||||
On November 26, the official update center installed JUnit
|
||||
`1458.1460.vd53b_087eeb_2c` and its eight required dependency plugins; installation
|
||||
and loading extensions each reported success, and the installed JUnit entry was
|
||||
enabled. The Pipeline Snippet Generator also lists the `junit` step, confirming
|
||||
that it is available to pipelines. No restart was requested. This is the compatible version offered to the
|
||||
existing Jenkins 2.580.1 controller, rather than a forced newer-core release.
|
||||
|
||||
The controller separately advertises a core update to 2.580.2 for the
|
||||
[October 28 security advisory](https://www.jenkins.io/security/advisory/2026-10-28/).
|
||||
That maintenance is still pending; installing JUnit does not apply a core update.
|
||||
|
||||
The existing worker needs Git, Python 3, Docker, its workspace volume and the two
|
||||
image identities in `demo/toolchain.json`. `demo/ci/run-cloud.sh` verifies those
|
||||
identities and maps its container workspace to the volume's actual host path.
|
||||
Do not run `prepare-images.sh` merely to check readiness; rebuilding can change
|
||||
the verified identities.
|
||||
|
||||
Before starting, confirm the agent is connected and idle, no manual Actions or
|
||||
other heavy delivery build is running, and the existing host has space for the
|
||||
new checkout, compiler outputs, image archive and Jenkins archive copy. Observe
|
||||
available RAM and swap alongside the configured stage limits. The November 26
|
||||
preflight observed 5.3 GiB available disk and about 687 MiB available RAM with
|
||||
swap after the Actions build completed; these are historical observations, not
|
||||
a permanent capacity guarantee. No new instance or plan is required.
|
||||
|
||||
The existing [Group 1 SRE dashboard](https://metrics.yebilly.me/d/group1-sre/group-1-sre?from=now-30m&to=now&refresh=30s&timezone=America%2FNew_York)
|
||||
was checked in Chrome: CPU, available-memory, root-filesystem and HTTPS charts
|
||||
rendered. Retain the 30-minute window and 30-second refresh for rehearsal, then
|
||||
adjust the window to include the real build. These charts describe the shared
|
||||
host; build 1 never reached application compilation, so its graph window must
|
||||
not be presented as successful native-build load evidence.
|
||||
|
||||
## First run and correction
|
||||
|
||||
[Build 1](https://ci.yebilly.me/job/tikzrefinery-demo/1/) used reviewed main
|
||||
`d37297b88993fd8c5428c2e732f32f4c9324b51b` and the real cloud agent. Checkout and
|
||||
main ancestry verification passed. The snapshot gate correctly rejected the
|
||||
missing `documents/assets/loop-example/loop-boxes.dvi`: the local file existed,
|
||||
but `*.dvi` excluded it from Git. Its original upstream SHA-256 is
|
||||
`3e06555552c50c1f5abcac8a1d3fb2eedf7ff4a34c40d94859aa7d5082009a21`.
|
||||
Compilation and later stages were skipped. Post-processing then reported that
|
||||
the `junit` step was unavailable. Preserve this failed build as evidence.
|
||||
|
||||
The prepared correction adds the exact upstream blob and a narrow ignore
|
||||
exception, verifies both all 435 working files and their indexed blob identities,
|
||||
and archives diagnostics before publishing test results. The original source
|
||||
manifest and product code stay unchanged. Commit/push/review the correction
|
||||
before the next baseline run from `main`.
|
||||
|
||||
## Verification after the reviewed correction
|
||||
|
||||
1. Record the triggering identity, current build URL, main revision and agent.
|
||||
2. Confirm the first stage verifies the main ancestry and all 435 indexed/raw
|
||||
upstream blobs. Observe the native, report, architecture and package stages.
|
||||
3. Check the JUnit interface shows the eight expected passing suites. Keep
|
||||
failures visible and inspect diagnostics rather than marking them successful.
|
||||
4. Download this build's image archive, architecture ZIP, report, provenance and
|
||||
`SHA256SUMS` through Jenkins. Run `demo/ci/verify-artifacts.py` against the
|
||||
downloaded artifact folder, and compare its source/build identity with the UI.
|
||||
5. Open a source-generated diagram and report. Show live shared-host monitoring
|
||||
and retain the actual per-stage load CSVs and elapsed times.
|
||||
6. Record the result, including cache reuse and shared-host limitations. A prior
|
||||
Windows/SSH rehearsal is not a substitute for this Jenkins verification.
|
||||
|
||||
Only after the baseline passes should the separate issue-linked product
|
||||
increment be prepared. Retain artifacts and required grading evidence; remove
|
||||
only reproducible scratch from the current task. Never prune shared images,
|
||||
volumes, runner identities or older evidence during preparation.
|
||||
+2619
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,267 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py.cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
# Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
# poetry.lock
|
||||
# poetry.toml
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
||||
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
||||
# pdm.lock
|
||||
# pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# pixi
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
||||
# pixi.lock
|
||||
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
||||
# in the .venv directory. It is recommended not to include this directory in version control.
|
||||
.pixi
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# Redis
|
||||
*.rdb
|
||||
*.aof
|
||||
*.pid
|
||||
|
||||
# RabbitMQ
|
||||
mnesia/
|
||||
rabbitmq/
|
||||
rabbitmq-data/
|
||||
|
||||
# ActiveMQ
|
||||
activemq-data/
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
# .idea/
|
||||
|
||||
# Abstra
|
||||
# Abstra is an AI-powered process automation framework.
|
||||
# Ignore directories containing user credentials, local state, and settings.
|
||||
# Learn more at https://abstra.io/docs
|
||||
.abstra/
|
||||
|
||||
# Visual Studio Code
|
||||
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||
# you could uncomment the following to ignore the entire vscode folder
|
||||
# .vscode/
|
||||
# Temporary file for partial code execution
|
||||
tempCodeRunnerFile.py
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# TikZRefinery: LaTeX-generated files
|
||||
*.aux
|
||||
*.bbl
|
||||
*.bcf
|
||||
*.blg
|
||||
*.fdb_latexmk
|
||||
*.fls
|
||||
*.glg
|
||||
*.glo
|
||||
*.gls
|
||||
*.idx
|
||||
*.ilg
|
||||
*.ind
|
||||
*.ist
|
||||
*.lof
|
||||
*.lot
|
||||
*.out
|
||||
*.run.xml
|
||||
*.synctex.gz
|
||||
*.toc
|
||||
*.xdv
|
||||
|
||||
# PDFs created beside LaTeX sources are disposable. The reviewed report at
|
||||
# documents/TikZRefinery.pdf remains tracked.
|
||||
documents/latex/*.pdf
|
||||
documents/template/SeniorDesignReportTemplate.pdf
|
||||
|
||||
# Workspace-local document tools and caches
|
||||
.tectonic-cache/
|
||||
tools/tectonic*/
|
||||
|
||||
# Qt/C++ build products and local CMake configuration
|
||||
code/build*/
|
||||
code/packages/
|
||||
code/CMakeUserPresets.json
|
||||
*.user
|
||||
|
||||
# Completed coursework, local review material and workstation settings
|
||||
/documents/submissions/
|
||||
/documents/slides/
|
||||
/code/tests/fixtures/demo2-pre-correction/
|
||||
/.vscode/
|
||||
/work/
|
||||
|
||||
# Operating-system metadata
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
|
||||
# Marimo
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
# Streamlit
|
||||
.streamlit/secrets.toml
|
||||
@@ -0,0 +1,101 @@
|
||||
# TikZRefinery - Agent Instructions
|
||||
|
||||
## Working relationship
|
||||
- A chat may span design, implementation, documentation and review. Continue
|
||||
successive work items there; new chats and compaction-based restarts are optional.
|
||||
- Explain significant design choices clearly, one decision at a time when asked.
|
||||
Check existing decisions before reopening settled questions.
|
||||
- Distinguish discussion, approved design and authorization to implement.
|
||||
Once work is authorized, complete routine steps without repeated permission
|
||||
requests; raise material scope changes or unresolved design choices.
|
||||
|
||||
## Authority and starting context
|
||||
- Follow Vincent's current instructions and the controlled project requirements.
|
||||
- Before modifying the project, read README.md and these authoritative sources:
|
||||
- documents/latex/tkrAIAgentRequirements.tex (AI Directives; stable filename)
|
||||
- documents/latex/tkrAIAgentGuide.tex
|
||||
- documents/latex/tkrReportRoadmap.tex
|
||||
- Read the smallest sufficient set of affected sources; expand for dependencies
|
||||
or inconsistencies. Reuse current context already established and refresh it
|
||||
when sources change or the task requires it.
|
||||
- When resuming work, read HANDOFF.md and verify it against files and Git state.
|
||||
Its proposed next action is not new authorization to implement.
|
||||
- This file is the concise entry point. Detailed requirements and procedures
|
||||
remain in their controlled sources; flag conflicts rather than silently
|
||||
changing rules or maintaining contradictory copies.
|
||||
|
||||
## Preserve work and respect scope
|
||||
- Inspect Git status before editing. Preserve unrelated uncommitted changes,
|
||||
user-edited examples, submissions, evidence and designated baseline packages.
|
||||
- Commit or push only when explicitly authorized for the current work.
|
||||
- Focused audit, coursework and workflow chats stay within their assignment.
|
||||
Do not replace the main development handoff's next action merely because
|
||||
the chat was forked from it; preserve that state during authorized cleanup.
|
||||
- A review request authorizes investigation and findings, not automatic fixes.
|
||||
|
||||
## Sources, evidence and readable documentation
|
||||
- Use authored TeX for report information and generated PDFs for visual checks.
|
||||
Do not extract PDF text to look up requirements or design decisions.
|
||||
- Put settled decisions in the appropriate requirement registers, use cases,
|
||||
tests and diagrams. Preserve stable IDs and reciprocal traceability.
|
||||
- Use applicable UML notation in editable TikZ; route relationships with
|
||||
horizontal/vertical segments and elbows, preserving arrow/ownership semantics.
|
||||
- Prefer concise requirements and TikZ diagrams to duplicated narrative.
|
||||
Use linked overview/detail views when they improve understanding.
|
||||
- Separate implemented behavior, planned design and verified results. Attribute
|
||||
recollections, stakeholder statements, sources and assumptions accurately.
|
||||
AI-generated statements are not evidence.
|
||||
- Record material assistance and decisions as required by the AI guide.
|
||||
- For material design/code changes, follow its bidirectional change-impact review:
|
||||
update affected records or record unchanged reviews and reasoned deferrals.
|
||||
- Explicit design approval authorizes routine documentation updates under
|
||||
AI-REQ-017 unless narrower instructions apply. Flag unclear approval or approved
|
||||
decisions left undocumented; check linked diagram contents and status. This
|
||||
does not authorize code, commits, pushing or external publication.
|
||||
|
||||
## Implementation conventions
|
||||
- Follow code/CODING_GUIDE.md and applicable Developer Requirements: tkr class
|
||||
names, descriptive identifier prefixes, private m_ members, named numeric
|
||||
values, separate class files, inheritance limits and explicit ownership.
|
||||
- Keep responsibilities bounded. Do not add inheritance or abstractions solely
|
||||
to satisfy a naming pattern or arbitrary class/file size.
|
||||
- Keep code and architectural documentation aligned. Identify which side needs
|
||||
correction rather than assuming either is always current.
|
||||
|
||||
## Builds, checks and versions
|
||||
- Use existing local toolchains before downloading or installing software.
|
||||
- Configure the Qt/MinGW environment as described in code/README.md, then run:
|
||||
- Build: cmake --build code/build --parallel 4
|
||||
- Test: ctest --test-dir code/build --output-on-failure
|
||||
- Use shared TinyTeX: C:\Users\vince\Documents\Projects\Tools\LaTeX\TinyTeX
|
||||
- Report build from the repository root: ./documents/build-report.ps1
|
||||
- For diagram lookup use documents/DIAGRAM_INDEX.md (generated source/status/
|
||||
page index); classify new figures in documents/diagram-manifest.json. An index
|
||||
does not replace whole-document review for material design changes/additions.
|
||||
- After material report changes, build both editions, inspect diagnostics,
|
||||
render affected pages and verify layout and navigation.
|
||||
- Run checks appropriate to the change; report actual results and limitations.
|
||||
- For visible application increments, refresh and launch a runnable package for
|
||||
Vincent's review, following current package/baseline instructions.
|
||||
- After Windows computer use, send the required completion summary and reset
|
||||
the CUA session to release capture bindings. Do not recapture to check the border.
|
||||
- Follow the version policy in Document History and the AI guide. Read current
|
||||
metadata; do not hard-code the current version or test count here.
|
||||
|
||||
## Reviews and continuity
|
||||
- Code reviews examine defects and regressions in a defined change. Architecture
|
||||
audits compare requirements, diagrams, code and test evidence in both directions;
|
||||
planned features are not automatically defects.
|
||||
- Report actionable findings with references, evidence and unresolved questions.
|
||||
- Refresh HANDOFF.md at meaningful stopping points and before transferring
|
||||
unfinished work. Include date, branch/commit, uncommitted work, verified results,
|
||||
limits, open decisions and the next proposed or authorized action.
|
||||
- Keep that file a concise checkpoint. Put durable decisions and historical
|
||||
evidence in their authoritative records; retain a dated snapshot when stale.
|
||||
|
||||
## Workspace cleanup
|
||||
- Keep reproducible scratch in a clearly named task-local work directory.
|
||||
- Remove only verified, reproducible scratch created for the current work;
|
||||
validate absolute cleanup paths and preserve anything awaiting review.
|
||||
- Retain deliverables, editable sources and required evidence. Report cleanup
|
||||
and intentionally retained temporary material.
|
||||
@@ -0,0 +1,99 @@
|
||||
# Changelog
|
||||
|
||||
Notable project changes are recorded here, newest first. Entries distinguish
|
||||
implemented application behavior from reviewed designs and documentation changes.
|
||||
Detailed report revisions remain in
|
||||
[Document History](documents/latex/tkrDocumentHistory.tex).
|
||||
|
||||
## 0.1.4-alpha - November 24, 2026
|
||||
|
||||
Documentation audit (version retained at Vincent's request):
|
||||
|
||||
- Matched the reviewed course template's front-matter order: contents, generated
|
||||
List of Tables, then List of Figures; refreshed both editions and diagram pages.
|
||||
- Reconciled all active report figures with current code and reviewed design;
|
||||
replaced the active frozen deployment with current 3D physical/module views.
|
||||
- Added the current Undo/Redo candidate sequence and corrected edit/Open/Save
|
||||
history boundaries, typed lifelines, planned labels and connector spacing.
|
||||
- Added a List of Figures and a build-generated source/status/page index, with
|
||||
an explicit manifest for new diagrams. Whole-document design review remains
|
||||
required; the application, packages and historical evidence are unchanged.
|
||||
|
||||
Implementation follow-up against the agreed report baseline:
|
||||
|
||||
- Refreshed Demo 3 for the working Alpha; moved the live demonstration directly
|
||||
after progress. Moved full Document History to Appendix A with a separate
|
||||
front-matter version paragraph/link, and recorded Milestone 3 coverage.
|
||||
|
||||
- Added document-owned session undo/redo for completed moves and rectangle
|
||||
resizing, exact source snapshots, atomic acceptance and standard Edit shortcuts.
|
||||
- Save retains history; successful Open clears it; changed edits after Undo drop
|
||||
the abandoned redo branch. No automatic eviction yet, as approved.
|
||||
- Passed eight Debug and eight Release suites; built the matching runnable
|
||||
package. Added a viewport repaint to clear stale selection handles after restoration.
|
||||
- Updated current architecture/evidence while retaining generic transactions and
|
||||
file-store extraction as planned. Preserved prior packages and report baselines.
|
||||
|
||||
Earlier documentation-only reconciliation:
|
||||
|
||||
- Reconciled agreed undo/redo architecture with planned class, activity and
|
||||
separate new-edit and history-restoration sequence views.
|
||||
- Corrected stale class labels/counts, provider/source boundaries and the future
|
||||
compile-on-save path. Clarified that implementation details remain open.
|
||||
- Strengthened AI-REQ-017 and AGENTS.md: approved designs trigger routine report
|
||||
updates; unclear approval or missing documentation must be flagged.
|
||||
- Preserved the 0.1.3-alpha app, Demo 3 and matching reports. Documentation only;
|
||||
no undo/redo implementation, package rebuild or new application test results.
|
||||
|
||||
## 0.1.3-alpha — November 23, 2026 implementation follow-up
|
||||
|
||||
- Implemented the collapsible Shapes/Files sidebar shell with Qt standard icons,
|
||||
retained session page/width, rectangle-provider status and guarded Open.
|
||||
- Kept creation disabled and folder browsing as an explicit placeholder.
|
||||
Catalogue/creation and shared-service ownership remain planned.
|
||||
- Passed all seven Debug and Release suites; checked the running package,
|
||||
collapse/reopen, page switching, unsaved-work guard and About identity.
|
||||
- Refreshed current architecture/UI views, both report editions and local Demo 3
|
||||
material. Preserved the prior reports and identity-only demo binary evidence,
|
||||
older packages and edited examples. No commit/push/upload in this follow-up.
|
||||
|
||||
## 0.1.3-alpha — November 22, 2026
|
||||
|
||||
Documentation release, completed November 23. The application and its packages
|
||||
remain at 0.1.2-alpha; the frozen 0.10.3 demonstration package is preserved.
|
||||
|
||||
### Added
|
||||
|
||||
- Reviewed designs for a collapsible Shapes/Files sidebar, shape catalogue,
|
||||
click/drag creation, cancellation, boundary fitting and rejection/retry.
|
||||
- Planned shared-service ownership, class responsibilities, MVC allocation,
|
||||
catalogue data records and creation activity, with editable UML and UI sketches.
|
||||
- Seven product requirements, linked planned checks and reciprocal traceability.
|
||||
- AI directive AI-REQ-017 and a bidirectional change-impact review checklist.
|
||||
|
||||
### Changed
|
||||
|
||||
- Renamed the displayed AI requirements appendix and register to AI Directives,
|
||||
preserving existing identifiers and references.
|
||||
- Updated architecture, use cases, validation plans, roadmap, glossary and project
|
||||
guidance; rebuilt both architectural report editions.
|
||||
- Recorded default Qt styling, deferred Qlementine and kept icon selection open.
|
||||
|
||||
The sidebar and creation workflow are planned, not implemented. New-document
|
||||
behavior, insertion contexts, folder interactions and API/construction details
|
||||
remain open. The original documentation pass changed no application source or
|
||||
package.
|
||||
|
||||
### Demo preparation — November 23, 2026
|
||||
|
||||
- Updated Demo 3 around the required diagrams and a live Alpha showcase, opening
|
||||
with progress since Demo 2. Retained the earlier demo sources and packages.
|
||||
- Preserved vector diagrams in the demo PDF and live slide assets to improve
|
||||
clarity when enlarged, without changing the presentation content.
|
||||
- Built a fresh 0.1.3-alpha Windows package from the unchanged feature source at
|
||||
checkpoint `7a2965a`, matching the architectural baseline. Sidebar and creation
|
||||
remain planned. Six Release test suites and a bounded native edit/save/reopen
|
||||
check passed. This rebuild adds no application feature implementation.
|
||||
|
||||
This changelog begins with 0.1.3-alpha. Earlier changes remain in Document History
|
||||
and Git history; historical versions have not been renumbered.
|
||||
@@ -0,0 +1,131 @@
|
||||
# TikZRefinery snapshot for the DevOps demonstration
|
||||
|
||||
Prepared November 25, 2026 for Vincent's SSW 590 workflow demonstration.
|
||||
The application and architectural baseline remain **0.1.4-alpha**.
|
||||
Use the full Git commit ID supplied with this checkpoint as the frozen upstream
|
||||
identity. This is an input to the DevOps project, not a new pipeline or release.
|
||||
|
||||
## What the snapshot provides
|
||||
|
||||
- C++17/Qt Widgets editor, separate rectangle provider module, constrained
|
||||
move/resize, collapsible sidebar shell and exact-source session undo/redo.
|
||||
- Eight CTest suites, including actual module loading and negative compatibility
|
||||
cases. Offscreen GUI tests do not establish interactive or full product acceptance.
|
||||
- Authored LaTeX, editable UML/TikZ, report build script, diagram manifest/index
|
||||
and the two reviewed report PDFs.
|
||||
- Existing project attribution, course-material notices and dependency information.
|
||||
No project-wide licence has been selected; this checkpoint does not grant one.
|
||||
|
||||
Creation, folder browsing, generic transactions, plugin updating and integrated
|
||||
LaTeX/PDF viewing remain planned. Do not present the sidebar shell as creation.
|
||||
|
||||
## Transfer and provenance
|
||||
|
||||
Keep TikZRefinery's main development here. Import the exact checkpoint into the
|
||||
existing DevOps repository, retaining the upstream repository URL, full commit
|
||||
ID, baseline version and attribution in that repository's import record.
|
||||
|
||||
The other local chat can fetch from
|
||||
`C:/Users/vince/Documents/Projects/TikZRefinery` without a GitHub push. A Git
|
||||
fetch transfers objects and refs; an unrelated DevOps history should consume a
|
||||
documented snapshot rather than merging TikZRefinery's main branch blindly.
|
||||
GitHub remote: `https://github.com/Generic-Sun/TikZRefinery.git`.
|
||||
|
||||
The old runnable packages and their build metadata are historical evidence.
|
||||
They still identify their original parent commit and modified working tree;
|
||||
creating this checkpoint does not relabel or rebuild those binaries. Build the
|
||||
new demonstration artifact from the frozen source. If importing into another
|
||||
repository, retain this upstream identity separately from that pipeline's commit.
|
||||
|
||||
## Verified Windows build
|
||||
|
||||
Run from the TikZRefinery checkout root in PowerShell with the installed matching
|
||||
Qt/MinGW kit. These are the existing workstation paths, not portable defaults:
|
||||
|
||||
```powershell
|
||||
$env:Path = 'C:\Qt\6.12.0\mingw_64\bin;C:\Qt\Tools\mingw1310_64\bin;C:\Qt\Tools\Ninja;' + $env:Path
|
||||
& C:\Qt\Tools\CMake_64\bin\cmake.exe -S code -B work/devops-build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=C:/Qt/6.12.0/mingw_64 -DCMAKE_CXX_COMPILER=C:/Qt/Tools/mingw1310_64/bin/g++.exe -DCMAKE_MAKE_PROGRAM=C:/Qt/Tools/Ninja/ninja.exe
|
||||
& C:\Qt\Tools\CMake_64\bin\cmake.exe --build work/devops-build --parallel 4
|
||||
& C:\Qt\Tools\CMake_64\bin\ctest.exe --test-dir work/devops-build --output-on-failure
|
||||
```
|
||||
|
||||
Stop on any failed command. The verified kit is Qt 6.12.0, GCC 13.1.0,
|
||||
CMake 3.30.5 and Ninja 1.12.1. Project minima are CMake 3.21, C++17 and Qt 6.2
|
||||
Core/Widgets. A Linux/cloud application build is **not verified** by this record;
|
||||
the DevOps chat must select and prove its own worker configuration.
|
||||
|
||||
Use the runnable package procedure in [code/README.md](code/README.md): deploy
|
||||
the Qt/compiler runtime and matching `shape-plugins/tkr_rectangle.dll` alongside
|
||||
the application. A standalone development executable is not a portable artifact.
|
||||
Build the host/provider with compatible kit and configuration. Keep fresh
|
||||
`build-info.json` with the artifact and retain pipeline test reports.
|
||||
|
||||
## Report stage
|
||||
|
||||
```powershell
|
||||
./documents/build-report.ps1 -OutputDirectory work/devops-report
|
||||
```
|
||||
|
||||
The script uses shared TinyTeX at
|
||||
`C:/Users/vince/Documents/Projects/Tools/LaTeX/TinyTeX/bin/windows`, PowerShell
|
||||
and standard-library Python. It runs the bibliography/index and final LaTeX
|
||||
passes, builds both editions, generates a versioned report ZIP, and refreshes
|
||||
the diagram index. For a different worker, provide its TinyTeX path using
|
||||
`-TinyTeXBin`; do not assume this workstation's installation exists there.
|
||||
|
||||
## Workflow boundaries and checks
|
||||
|
||||
The DevOps chat's reviewed direction is a frozen input followed by an issue,
|
||||
planned-change comment, meaningful enhancement, commit/push, pipeline, tests and
|
||||
versioned artifact. That enhancement and pipeline integration are separate work;
|
||||
this source checkpoint alone does not demonstrate the complete workflow.
|
||||
|
||||
The pipeline's required `major.minor.changelist` delivery identifier must be
|
||||
recorded separately from the upstream `0.1.4-alpha` baseline, not used to rewrite
|
||||
TikZRefinery's historical version. Authored TikZ diagrams are not evidence of
|
||||
architecture extraction from source; the optional extraction bonus needs its own
|
||||
tool and verified output.
|
||||
|
||||
Keep the requested provider naming correction for the separate demo change:
|
||||
`tkrRectangleShapeProvider` to `tkrShapeProviderRectangle`. Update the class,
|
||||
matching header/implementation names, both CMake target references and affected
|
||||
current documentation together; run the eight suites and verify the actual
|
||||
module still loads. The class name is distinct from the DLL filename, provider
|
||||
ID and interface contract; this proposal does not require changing those public
|
||||
identities. Have the DevOps chat confirm this choice, prepare the issue/comment
|
||||
and rehearse the change after its baseline pipeline works. It is not implemented
|
||||
in this checkpoint. The assignment permits a code or LaTeX change and manual or
|
||||
automatic pipeline triggering; reserve the final commit/push for that workflow.
|
||||
|
||||
November 25 checks: a fresh Windows Release build passed all eight suites;
|
||||
the existing Debug build also passed all eight. Report sources and the canonical
|
||||
PDFs match the November 24 complete TinyTeX/visual/navigation checks (258-page
|
||||
submission, 327-page developer edition, 51 figures). No new report build,
|
||||
native application review, package refresh or cloud build is claimed here.
|
||||
Machine-readable checks and test output are under
|
||||
`code/tests/evidence/devops-snapshot-2026-11-25/`.
|
||||
The audit script there checks this workstation's retained protected files as
|
||||
well as staged build inputs; it is not a portable CI test. Use CTest for the
|
||||
imported application and establish the DevOps pipeline's own artifact checks.
|
||||
|
||||
This commit includes source, reports and compact evidence. Existing local
|
||||
contact sheets, backup patches, submissions, slides and installed packages are
|
||||
preserved outside the snapshot selection. Their omission does not remove the
|
||||
application, report inputs or automated tests required to reproduce builds.
|
||||
|
||||
## Maintenance impact and AI-assistance record
|
||||
|
||||
Vincent authorized a commit usable by his DevOps chat and permitted reading it
|
||||
for context. The relevant chat is **Main**, in `vpn-dns-gateway`; its latest
|
||||
discussion chooses a frozen TikZRefinery input for the existing DevOps repository.
|
||||
It was read without sending a message or changing that project.
|
||||
|
||||
This is a repository checkpoint of previously implemented, documented and logged
|
||||
work, with fresh build checks and transfer guidance. Product requirements,
|
||||
stories, use cases, contracts, class/MVC/behavior diagrams, test definitions and
|
||||
verification/validation statuses were reviewed unchanged. No design or product
|
||||
behavior is added. Report metadata, historical prompt log and canonical PDFs are
|
||||
preserved at their already-reviewed baseline; this maintenance record and the
|
||||
Git commit record the new assistance without regenerating graded artifacts.
|
||||
README and HANDOFF link the checkpoint. No push, external publication, package
|
||||
deletion, pipeline execution or message to the DevOps chat is authorized here.
|
||||
@@ -0,0 +1,84 @@
|
||||
# TikZRefinery - current checkpoint
|
||||
|
||||
Updated November 25, 2026. Branch main; checkpoint parent
|
||||
7a2965a4f14e8ac8ca6dbb531e605b91ee6dccb3. Vincent authorized a local commit
|
||||
of the current 0.1.4-alpha baseline for his DevOps demonstration. Its resulting
|
||||
identity is available from Git history; no push is authorized.
|
||||
Read AGENTS.md, README and controlled directives/guide/roadmap; verify Git/files.
|
||||
|
||||
## DevOps source checkpoint
|
||||
|
||||
Read the DevOps chat Main in vpn-dns-gateway: use an exact TikZRefinery input
|
||||
with provenance in the existing DevOps repository. DEVOPS_SNAPSHOT.md provides
|
||||
the handoff, build/report prerequisites, package/identity boundaries and reviewed
|
||||
unchanged impact record. Fresh Windows Release build: eight suites passed;
|
||||
existing Debug build: eight passed. Evidence: code/tests/evidence/devops-snapshot-2026-11-25/.
|
||||
No application feature or report-source changes were made for this checkpoint;
|
||||
canonical PDFs remain the verified November 24 outputs. No package is rebuilt,
|
||||
relabelled or deleted. Existing large review images and backup patches remain
|
||||
local, outside the compact commit selection; coursework/slides/packages remain
|
||||
ignored. No other chat was messaged and no DevOps project file was changed.
|
||||
|
||||
Next action for DevOps: fetch this local checkpoint or, after Vincent pushes it,
|
||||
the GitHub commit; prove its chosen worker's build/test/package stages before
|
||||
the issue-to-artifact rehearsal. Reserve the proposed provider-class suffix
|
||||
rename for the separately issue-linked demo change; it is not implemented here.
|
||||
Main TikZRefinery feature work remains a separate
|
||||
authorization. All earlier package-cleanup limits below still apply.
|
||||
|
||||
## Completed: course-template front-matter lists
|
||||
|
||||
Vincent requested inspection of his previous-course DesignBook template open in
|
||||
Chrome/Overleaf. Read its prologue without editing: contentspage, tablelistpage,
|
||||
figurelistpage. The retained local template and active Cornell class support the
|
||||
same order. Browser control was released and CUA reset; Overleaf is unchanged.
|
||||
|
||||
Both canonical reports remain 0.1.4-alpha. Front matter is now Contents -> List of
|
||||
Tables -> List of Figures, with generated captions, numbering, hyperlinks and
|
||||
PDF bookmarks. Added captions/stable labels to fourteen existing technical tables
|
||||
(including seven use-case specifications). Three local 11-point table formats
|
||||
avoid orphaned rows/following text. Original table bodies and product mappings
|
||||
are preserved. RPT-049 is Done; product and AI directive statuses are unchanged.
|
||||
|
||||
Canonical PDFs: documents/TikZRefinery.pdf (258 pages, 61 listed tables/51 figures)
|
||||
and TikZRefinery-Developers-Edition.pdf (327 pages, 65 tables/51 figures).
|
||||
The diagram index was regenerated for the new pagination. The reader-facing
|
||||
lists complement its editable-source/status data, not replace it. Broader design
|
||||
changes/additions still require whole-document impact and visual review.
|
||||
|
||||
Checks: complete TinyTeX sequence in both editions; all list and internal named
|
||||
links and all 51 diagram page mappings resolve. No errors, unresolved references/
|
||||
citations, duplicate destinations, overfull boxes or oversized floats. Five
|
||||
underfull notices each were visually checked. Affected navigation, captioned
|
||||
tables, history, roadmap and internal guide/log pages reviewed. All 756 protected
|
||||
source, diagram, package, slide and archive files match their recorded hashes.
|
||||
No application tests rerun, code/package change, commit, push or cloud edit.
|
||||
|
||||
Evidence/checks/contact sheets/cleanup and the previous checkpoint:
|
||||
documents/assets/front-matter-lists-2026-11-24/.
|
||||
Pre-task reports: documents/submissions/baselines/architecture-0.1.4-alpha-before-table-list-2026-11-24/.
|
||||
Final dated reports: documents/submissions/architecture-0.1.4-alpha-front-matter-lists-2026-11-24/.
|
||||
|
||||
## Previous completed audit and implementation state
|
||||
|
||||
The diagram audit reconciled all 51 active figures, current 3D physical/module
|
||||
deployment, candidate/source/history acceptance, current Undo/Redo, Open/Save
|
||||
history effects, typed lifelines and planned-design labels. Its evidence and
|
||||
frozen predecessor sources remain in documents/assets/diagram-audit-2026-11-24/.
|
||||
Use documents/DIAGRAM_INDEX.md and diagram-index.json for current page locations;
|
||||
maintain diagram-manifest.json when adding views. Complete report builds refresh
|
||||
these using final auxiliary/shipout records and reject changed build inputs.
|
||||
|
||||
Existing uncommitted 0.1.4-alpha implementation is preserved: rectangle DLL,
|
||||
sidebar shell and bounded session history; eight Debug/eight Release suites in
|
||||
prior dated evidence. Thirteen host classes plus provider interface/module.
|
||||
Scene-owned plugin store; creation disabled. Catalogue/shared services, generic
|
||||
transactions, folder browsing, provider updating and compiler/PDF remain planned.
|
||||
Actual tkrRectangleShapeProvider still needs the coordinated requested
|
||||
tkrShapeProviderRectangle rename in a later authorized code/files/build/test task.
|
||||
DLL filename/plugin ID are separate. Prior reports/decks/packages remain intact.
|
||||
|
||||
Next proposed action: Vincent reviews the refreshed reports, then authorizes any
|
||||
implementation or final-demo work. Earlier package cleanup remains unresolved
|
||||
because his request ended at 'though add'. Do not infer deletion or commit/push
|
||||
permission from this documentation follow-up.
|
||||
@@ -0,0 +1,135 @@
|
||||
# TikZRefinery
|
||||
|
||||
TikZRefinery is a Stevens Senior Design project developing a desktop editor for
|
||||
graphically refining TikZ diagrams while preserving editable TikZ source.
|
||||
It aims to make precise layout changes easier, including corrections to diagrams
|
||||
that begin as AI-generated code. The project uses C++17 and Qt Widgets.
|
||||
|
||||
## Current capabilities
|
||||
|
||||
The Alpha supports a conservative subset of explicit-coordinate TikZ:
|
||||
|
||||
- Display rectangles, straight lines and default arrows in centimetres.
|
||||
- Load rectangle presentation, selection, movement and resizing from a separate
|
||||
native shape plugin through the Qt Core SDK.
|
||||
- Move supported shapes and resize rectangles using corner handles.
|
||||
- Flip rectangles when corners cross, retain thin minimum dimensions, and stop
|
||||
edits at the furthest valid position inside a declared editing boundary.
|
||||
- Collapse/reopen a Shapes/Files sidebar, retain its page/width during the session,
|
||||
inspect rectangle-provider status and open files through the existing unsaved-work guard.
|
||||
- Fit the canvas to its pane, preview gestures, cancel edits, and save/reopen
|
||||
source while preserving unrelated bytes and checking observed external changes.
|
||||
|
||||
Session undo/redo restores exact source for completed moves/resizes; Save retains
|
||||
history and successful Open clears it. History has no automatic eviction yet.
|
||||
|
||||
Broader TikZ syntax, label and endpoint editing, provider management, manual
|
||||
zoom controls, and integrated LaTeX compilation/PDF viewing remain unfinished.
|
||||
Existing test evidence covers the bounded subset; it does not establish full
|
||||
product acceptance. See [the code overview](code/README.md) for details.
|
||||
|
||||
## Build and run
|
||||
|
||||
Use the matching Qt 6/MinGW kit, CMake and Ninja described in
|
||||
[code/README.md](code/README.md). That guide provides the verified Windows setup,
|
||||
build/test commands, startup examples and portable package procedure.
|
||||
|
||||
For an already configured environment, from the repository root:
|
||||
|
||||
```powershell
|
||||
cmake --build code/build --parallel 4
|
||||
ctest --test-dir code/build --output-on-failure
|
||||
```
|
||||
|
||||
The development executable needs the Qt/compiler runtime environment. A deployed
|
||||
Windows package includes those dependencies; keep its executable with its runtime
|
||||
files. Preserve user-edited examples when refreshing a package.
|
||||
|
||||
## Repository structure
|
||||
|
||||
```text
|
||||
TikZRefinery/
|
||||
|-- README.md Project introduction and getting started
|
||||
|-- CHANGELOG.md Notable changes by version
|
||||
|-- AGENTS.md Instructions for AI-assisted work
|
||||
|-- HANDOFF.md Current unfinished-work checkpoint
|
||||
|-- documents/
|
||||
| |-- TikZRefinery.pdf Submission edition of the architectural report
|
||||
| |-- TikZRefinery-Developers-Edition.pdf
|
||||
| |-- latex/ Authoritative report sources
|
||||
| |-- assets/ Editable diagrams and retained evidence
|
||||
| `-- template/ Original course materials
|
||||
`-- code/
|
||||
|-- src/ Application source
|
||||
|-- tests/ Automated checks and evidence
|
||||
|-- examples/ Supported TikZ samples
|
||||
`-- resources/ Application resources
|
||||
```
|
||||
|
||||
## Architecture and documentation
|
||||
|
||||
- [Changelog](CHANGELOG.md), distinguishing delivered behavior from planned design
|
||||
- [Submission report](documents/TikZRefinery.pdf)
|
||||
- [Developer's edition](documents/TikZRefinery-Developers-Edition.pdf), including
|
||||
the internal AI directives, operating guide and assistance log
|
||||
- [Coding conventions](code/CODING_GUIDE.md)
|
||||
|
||||
The authored TeX and editable TikZ diagrams are the documentation sources.
|
||||
[Diagram index](documents/DIAGRAM_INDEX.md) locates every active figure, source,
|
||||
reviewed status and page in both report editions. After its contents, the report
|
||||
provides generated Lists of Tables and Figures with linked page locations.
|
||||
Builds refresh the index from the [manifest](documents/diagram-manifest.json)
|
||||
and final LaTeX records using standard-library Python. Classify new figures in
|
||||
the manifest. Broader design changes still require whole-document review.
|
||||
Build both report editions using the existing shared TinyTeX installation:
|
||||
|
||||
```powershell
|
||||
./documents/build-report.ps1
|
||||
```
|
||||
|
||||
The script completes the bibliography/index sequence and writes PDFs, a versioned
|
||||
submission ZIP and build results under `work/`. After a material report change,
|
||||
check diagnostics, layout and navigation before replacing the published PDFs.
|
||||
Version policy and revision history are maintained in
|
||||
[Document History](documents/latex/tkrDocumentHistory.tex); the application build
|
||||
reads its architectural baseline from the report metadata. Feature-based
|
||||
numbering and the frozen-package exception are controlled in Document History;
|
||||
rectangle extraction is implemented in `code/packages/0.1.2-alpha/`; the
|
||||
frozen 0.10.3 demonstration package is preserved.
|
||||
|
||||
The [reviewed plugin contract](documents/latex/tkrPluginDesign.tex) separates
|
||||
the current rectangle extraction and later palette/creation
|
||||
and update features. Its requirements, UML views and planned checks are linked
|
||||
from the report. The [sidebar and creation design](documents/latex/tkrSidebarDesign.tex)
|
||||
now includes an implemented shell in `code/packages/0.1.3-alpha/`. Creation is
|
||||
disabled and folder browsing is a placeholder; catalogue/creation and shared
|
||||
service ownership remain planned. Seven suites pass in Debug and Release.
|
||||
[Shell evidence](code/tests/evidence/sidebar-shell-2026-11-23/README.md) records
|
||||
the scope and native review. Earlier packages remain unchanged; Qt standard
|
||||
icons are used. Demo materials remain local under `documents/slides/demo3/`.
|
||||
|
||||
The report and application now share **0.1.4-alpha**, implementing bounded
|
||||
session undo/redo for completed coordinate edits. Generic transactions remain
|
||||
planned. Demo 3 now presents **0.1.4-alpha**, with the live showcase immediately
|
||||
after progress. Earlier slides/reports remain preserved. Submit the slide PDF
|
||||
for Demo 3 and the canonical submission report for Milestone 3; neither has been
|
||||
uploaded by the agent. The complete Document History is now Appendix A, linked
|
||||
from its distinct front-matter version page.
|
||||
|
||||
## Working on the project
|
||||
|
||||
For the frozen 0.1.4-alpha input to the separate DevOps demonstration, see
|
||||
[snapshot and build guidance](DEVOPS_SNAPSHOT.md). Its source checkpoint does
|
||||
not relabel the preserved packages or establish a cloud-build result.
|
||||
|
||||
AI agents start with [AGENTS.md](AGENTS.md). For continuation of unfinished work,
|
||||
consult [HANDOFF.md](HANDOFF.md) and verify it against current sources and Git
|
||||
state. One chat may cover design, implementation and review across several work
|
||||
items; starting another chat is optional. The handoff is a dated checkpoint,
|
||||
while requirements and architectural decisions remain in the report.
|
||||
|
||||
## License
|
||||
|
||||
No project-wide license has been selected. Original project work remains under
|
||||
the applicable default copyright rules. Third-party and course-provided
|
||||
materials retain their own terms and notices.
|
||||
@@ -0,0 +1,147 @@
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
set(strReportSource "${CMAKE_CURRENT_SOURCE_DIR}/../documents/latex/TikZRefinery.tex")
|
||||
file(STRINGS "${strReportSource}" strVersionLine REGEX "^\\\\newcommand\{\\\\DocumentVersion\}")
|
||||
string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+(-[A-Za-z0-9.-]+)?" strDocumentVersion "${strVersionLine}")
|
||||
string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" strProjectVersion "${strDocumentVersion}")
|
||||
if(NOT strProjectVersion)
|
||||
message(FATAL_ERROR "Cannot read the shared project version from the report source")
|
||||
endif()
|
||||
project(TikZRefinery VERSION ${strProjectVersion} LANGUAGES CXX)
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${strReportSource}")
|
||||
|
||||
find_package(Git QUIET)
|
||||
add_custom_target(tikzrefinery_build_info
|
||||
COMMAND "${CMAKE_COMMAND}"
|
||||
"-DSOURCE_ROOT=${CMAKE_CURRENT_SOURCE_DIR}/.."
|
||||
"-DBINARY_ROOT=${CMAKE_CURRENT_BINARY_DIR}"
|
||||
"-DPROJECT_VERSION=${PROJECT_VERSION}"
|
||||
"-DREPORT_VERSION=${strDocumentVersion}"
|
||||
"-DGIT_EXECUTABLE=${GIT_EXECUTABLE}"
|
||||
-P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/WriteBuildInfo.cmake"
|
||||
BYPRODUCTS "${CMAKE_CURRENT_BINARY_DIR}/generated/BuildInfo.h"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/build-info.json"
|
||||
VERBATIM)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
|
||||
find_package(Qt6 6.2 REQUIRED COMPONENTS Core Widgets)
|
||||
|
||||
add_library(tikzrefinery_shape_api INTERFACE)
|
||||
target_include_directories(tikzrefinery_shape_api INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/plugin-api")
|
||||
target_link_libraries(tikzrefinery_shape_api INTERFACE Qt6::Core)
|
||||
set(strShapeBuildKey "${CMAKE_CXX_COMPILER_ID}-${CMAKE_CXX_COMPILER_VERSION}-${CMAKE_SYSTEM_NAME}-${CMAKE_SIZEOF_VOID_P}-${CMAKE_BUILD_TYPE}-Qt${Qt6Core_VERSION}")
|
||||
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/generated/ShapeBuildContract.h"
|
||||
"#pragma once\nnamespace TikzRefinery::ShapeBuildContract { inline constexpr char pBuildKey[] = \"${strShapeBuildKey}\"; }\n")
|
||||
configure_file(plugins/rectangle/rectangle-plugin.json.in
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/generated/rectangle-plugin.json" @ONLY)
|
||||
add_library(tkr_rectangle_plugin MODULE
|
||||
plugins/rectangle/tkrRectangleShapeProvider.h plugins/rectangle/tkrRectangleShapeProvider.cpp)
|
||||
target_include_directories(tkr_rectangle_plugin PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||
target_link_libraries(tkr_rectangle_plugin PRIVATE tikzrefinery_shape_api)
|
||||
set_target_properties(tkr_rectangle_plugin PROPERTIES PREFIX "" OUTPUT_NAME "tkr_rectangle"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/shape-plugins"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/shape-plugins")
|
||||
|
||||
# Source interpretation and editing remain usable without a GUI application.
|
||||
add_library(tikzrefinery_core STATIC
|
||||
src/model/EditorTypes.h
|
||||
src/model/tkrTikzDocument.h src/model/tkrTikzDocument.cpp
|
||||
src/parsing/tkrTikzParserExplicit.h src/parsing/tkrTikzParserExplicit.cpp
|
||||
src/geometry/tkrCoordinateMapper.h src/geometry/tkrCoordinateMapper.cpp
|
||||
src/geometry/ShapeGeometryLimits.h
|
||||
src/editing/tkrEditService.h src/editing/tkrEditService.cpp
|
||||
src/editing/tkrEditHistory.h src/editing/tkrEditHistory.cpp
|
||||
)
|
||||
target_include_directories(tikzrefinery_core PUBLIC src)
|
||||
target_link_libraries(tikzrefinery_core PUBLIC Qt6::Core tikzrefinery_shape_api)
|
||||
|
||||
add_library(tikzrefinery_editor STATIC
|
||||
src/controller/tkrEditorController.h src/controller/tkrEditorController.cpp
|
||||
src/ui/tkrDiagramScene.h src/ui/tkrDiagramScene.cpp
|
||||
src/ui/tkrDiagramView.h src/ui/tkrDiagramView.cpp
|
||||
src/ui/tkrMainWindow.h src/ui/tkrMainWindow.cpp
|
||||
src/ui/tkrWorkspaceSidebar.h src/ui/tkrWorkspaceSidebar.cpp
|
||||
src/ui/tkrShapePalette.h src/ui/tkrShapePalette.cpp
|
||||
src/ui/tkrFolderBrowser.h src/ui/tkrFolderBrowser.cpp
|
||||
src/plugins/tkrShapePluginStore.h src/plugins/tkrShapePluginStore.cpp
|
||||
src/plugins/ShapeProviderAdapter.h
|
||||
)
|
||||
target_include_directories(tikzrefinery_editor PUBLIC src "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||
add_dependencies(tikzrefinery_editor tikzrefinery_build_info tkr_rectangle_plugin)
|
||||
target_link_libraries(tikzrefinery_editor PUBLIC tikzrefinery_core Qt6::Widgets)
|
||||
|
||||
qt_add_executable(TikZRefinery src/main.cpp)
|
||||
add_dependencies(TikZRefinery tikzrefinery_build_info)
|
||||
target_link_libraries(TikZRefinery PRIVATE tikzrefinery_editor)
|
||||
set_target_properties(TikZRefinery PROPERTIES WIN32_EXECUTABLE TRUE)
|
||||
|
||||
foreach(strTarget IN ITEMS tikzrefinery_core tikzrefinery_editor TikZRefinery tkr_rectangle_plugin)
|
||||
if(MSVC)
|
||||
target_compile_options(${strTarget} PRIVATE /W4 /permissive- /utf-8)
|
||||
else()
|
||||
target_compile_options(${strTarget} PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
include(CTest)
|
||||
if(BUILD_TESTING)
|
||||
# A real second module with incompatible metadata exercises rejection before activation.
|
||||
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test-plugin-metadata")
|
||||
file(READ "${CMAKE_CURRENT_BINARY_DIR}/generated/rectangle-plugin.json" strBadMetadata)
|
||||
set(iIncompatibleApiVersion 99)
|
||||
string(REPLACE "\"apiVersion\": 1" "\"apiVersion\": ${iIncompatibleApiVersion}" strBadMetadata "${strBadMetadata}")
|
||||
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test-plugin-metadata/rectangle-plugin.json" "${strBadMetadata}")
|
||||
add_library(tkr_incompatible_rectangle_plugin MODULE
|
||||
plugins/rectangle/tkrRectangleShapeProvider.h plugins/rectangle/tkrRectangleShapeProvider.cpp)
|
||||
target_include_directories(tkr_incompatible_rectangle_plugin PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/test-plugin-metadata")
|
||||
target_link_libraries(tkr_incompatible_rectangle_plugin PRIVATE tikzrefinery_shape_api)
|
||||
set_target_properties(tkr_incompatible_rectangle_plugin PROPERTIES PREFIX "" OUTPUT_NAME "tkr_bad_rectangle"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test-plugins"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test-plugins")
|
||||
add_executable(tikzrefinery_plugin_tests tests/PluginTests.cpp)
|
||||
target_link_libraries(tikzrefinery_plugin_tests PRIVATE tikzrefinery_editor)
|
||||
target_compile_definitions(tikzrefinery_plugin_tests PRIVATE
|
||||
TKR_RECTANGLE_PLUGIN_PATH="$<TARGET_FILE:tkr_rectangle_plugin>"
|
||||
TKR_INCOMPATIBLE_PLUGIN_PATH="$<TARGET_FILE:tkr_incompatible_rectangle_plugin>")
|
||||
add_dependencies(tikzrefinery_plugin_tests tkr_incompatible_rectangle_plugin)
|
||||
add_test(NAME rectangle_plugin_contract COMMAND tikzrefinery_plugin_tests)
|
||||
set_tests_properties(rectangle_plugin_contract PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||
add_executable(tikzrefinery_core_tests tests/CoreTests.cpp)
|
||||
target_link_libraries(tikzrefinery_core_tests PRIVATE tikzrefinery_core)
|
||||
add_test(NAME core_foundations COMMAND tikzrefinery_core_tests)
|
||||
add_executable(tikzrefinery_rectangle_tests tests/RectangleTests.cpp)
|
||||
target_link_libraries(tikzrefinery_rectangle_tests PRIVATE tikzrefinery_editor)
|
||||
target_compile_definitions(tikzrefinery_rectangle_tests PRIVATE
|
||||
TKR_CORPUS_DIRECTORY="${CMAKE_CURRENT_SOURCE_DIR}/examples/explicit-coordinates")
|
||||
add_test(NAME rectangle_display COMMAND tikzrefinery_rectangle_tests)
|
||||
set_tests_properties(rectangle_display PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||
add_executable(tikzrefinery_segment_tests tests/SegmentTests.cpp)
|
||||
target_link_libraries(tikzrefinery_segment_tests PRIVATE tikzrefinery_editor)
|
||||
target_compile_definitions(tikzrefinery_segment_tests PRIVATE
|
||||
TKR_CORPUS_DIRECTORY="${CMAKE_CURRENT_SOURCE_DIR}/examples/explicit-coordinates")
|
||||
add_test(NAME segment_display COMMAND tikzrefinery_segment_tests)
|
||||
set_tests_properties(segment_display PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||
add_executable(tikzrefinery_drag_tests tests/DragTests.cpp)
|
||||
target_link_libraries(tikzrefinery_drag_tests PRIVATE tikzrefinery_editor)
|
||||
target_compile_definitions(tikzrefinery_drag_tests PRIVATE
|
||||
TKR_CORPUS_DIRECTORY="${CMAKE_CURRENT_SOURCE_DIR}/examples/explicit-coordinates"
|
||||
TKR_TEST_WORK_DIRECTORY="${CMAKE_CURRENT_BINARY_DIR}/test-work")
|
||||
add_test(NAME whole_element_drag COMMAND tikzrefinery_drag_tests)
|
||||
set_tests_properties(whole_element_drag PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||
add_executable(tikzrefinery_resize_tests tests/ResizeTests.cpp)
|
||||
target_link_libraries(tikzrefinery_resize_tests PRIVATE tikzrefinery_editor)
|
||||
add_test(NAME rectangle_resize COMMAND tikzrefinery_resize_tests)
|
||||
set_tests_properties(rectangle_resize PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||
add_executable(tikzrefinery_sidebar_tests tests/SidebarTests.cpp)
|
||||
target_link_libraries(tikzrefinery_sidebar_tests PRIVATE tikzrefinery_editor)
|
||||
add_test(NAME workspace_sidebar COMMAND tikzrefinery_sidebar_tests)
|
||||
set_tests_properties(workspace_sidebar PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||
add_executable(tikzrefinery_history_tests tests/HistoryTests.cpp)
|
||||
target_link_libraries(tikzrefinery_history_tests PRIVATE tikzrefinery_editor)
|
||||
add_test(NAME session_history COMMAND tikzrefinery_history_tests)
|
||||
set_tests_properties(session_history PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||
endif()
|
||||
@@ -0,0 +1,168 @@
|
||||
# C++ and Qt coding guide
|
||||
|
||||
These conventions implement Vincent's naming and structure decisions from
|
||||
October 1-15, 2026. Instructor suggestions are recorded through Vincent's account.
|
||||
|
||||
## Names
|
||||
|
||||
- Project-owned classes use `tkr<MainClassName><Specification>`: a literal
|
||||
lowercase `tkr` prefix followed by PascalCase components. The specification
|
||||
suffix is optional and identifies a specialization: `tkrMainWindow` and
|
||||
`tkrTikzParserExplicit`. Existing Qt/vendor types retain their names.
|
||||
- Structs and enums use PascalCase: `SourceRange`, `DragKind`.
|
||||
- Methods use camelCase and describe an operation: `applyCoordinateEdits()`.
|
||||
- Variables and parameters combine a type/category prefix with a descriptive
|
||||
name. Include coordinate space or units where relevant: `ptTikzPosition`,
|
||||
`rSceneUnitsPerCentimeter`.
|
||||
- Private member variables add `m_`: `m_baSource`, `m_pScene`.
|
||||
`m_` means member; restricting it to private members is our project convention.
|
||||
- Header and implementation filenames match their primary class.
|
||||
- Enum values use PascalCase: `DragKind::WholeElement`.
|
||||
|
||||
| Prefix | Type or category | Example |
|
||||
|---|---|---|
|
||||
| `i` | `int` | `iArgumentCount` |
|
||||
| `n` | `qsizetype` size or index | `nStart` |
|
||||
| `u` | `quint64` ID or revision | `uDocumentRevision` |
|
||||
| `b` | `bool` | `bSafeToEdit` |
|
||||
| `r` | `qreal` | `rLineWidthPoints` |
|
||||
| `str` | `QString` | `strFilePath` |
|
||||
| `ba` | `QByteArray` | `baSource` |
|
||||
| `pt` | `QPointF` | `ptScenePosition` |
|
||||
| `vec` | `QVector<T>` | `vecElements` |
|
||||
| `list` | `QStringList` | `listDiagnostics` |
|
||||
| `p` | Raw pointer | `pParent` |
|
||||
| `ref` | Reference to another object | `m_refDocument` |
|
||||
| `up` | `std::unique_ptr<T>` | `m_upController` |
|
||||
| `iter` | Iterator | `iterEdit` |
|
||||
|
||||
For domain records and concrete objects, use a readable type/category word,
|
||||
such as `coordinateEdit`, `parseResult`, `resultSave`, `mapper`, or `fileSource`.
|
||||
Extend this table when a new category appears. Update names when types change.
|
||||
Prefixes do not establish ownership; declarations and documented lifetimes do.
|
||||
|
||||
## Files and dependencies
|
||||
|
||||
Each primary class has its own `.h` and `.cpp`, grouped by responsibility:
|
||||
`model`, `parsing`, `geometry`, `editing`, `controller`, and `ui`.
|
||||
Small cross-component records share `model/EditorTypes.h`.
|
||||
|
||||
An inheritance path may contain at most three project-defined class levels:
|
||||
main/base class, child, and grandchild (two levels after the main class).
|
||||
Qt's existing ancestry is excluded. This is a maximum, not a target. The
|
||||
initial classes are `final` and introduce no custom inheritance chains.
|
||||
The extracted rectangle implementation is also `final` and realizes
|
||||
`tkrShapeProvider`, a two-level project-defined interface chain.
|
||||
Favor composition and explicit references. A specialization suffix describes
|
||||
the role; it does not itself imply inheritance. The explicit parser has no
|
||||
project-defined base. Do not create base classes solely to satisfy a name.
|
||||
|
||||
The report's Developer Requirements subsection controls these conventions:
|
||||
REQ-A-005 retains its historical ID after moving out of Architecture;
|
||||
REQ-DEV-001 through REQ-DEV-005 govern class names, other identifiers,
|
||||
inheritance depth, documented ownership, and named numeric values. Checks
|
||||
TC-030 through TC-033 and TC-066 are planned review/build procedures.
|
||||
|
||||
The document, parser and mapper depend on Qt Core, without widgets or a LaTeX
|
||||
process. Widgets request actions; parsing identifies source; the model applies
|
||||
validated edits; the controller coordinates them and performs file I/O.
|
||||
|
||||
## Named numeric values
|
||||
|
||||
Keep numeric literals in named definitions. Give each value a name that
|
||||
describes its purpose and units, such as `iHitRadiusViewportPixels`. Use a
|
||||
local `constexpr` when one method needs it, a file-local constant when
|
||||
several helpers share it, or a class member when the class owns the value.
|
||||
Use named enum values for numeric keys. Derive related values from the same
|
||||
definition instead of giving each occurrence of a number a separate name.
|
||||
|
||||
Start the review in `tkrDiagramScene`: name the default scene dimensions,
|
||||
the hit radius, and the item-data keys. Keep related PGF arrow geometry
|
||||
coefficients together in a named definition with their source reference.
|
||||
These are review examples, not a claim that the existing code conforms.
|
||||
|
||||
## Ownership
|
||||
|
||||
- `main.cpp` owns one `tkrMainWindow` on the stack. The accepted final-window close
|
||||
ends the event loop, then stack destruction releases the window.
|
||||
- The document owns `tkrEditHistory` by value; only the document records/traverses
|
||||
its session snapshots. Candidate source, parsed records and history are prepared
|
||||
before document acceptance publishes them with non-allocating swaps.
|
||||
- The window owns its document by value and controller through `unique_ptr`.
|
||||
The controller is destroyed before the document.
|
||||
- The window owns its scene through QObject parenting. Widgets and actions
|
||||
also have Qt parents. The scene owns its graphics items.
|
||||
- The window's central widget tree owns `tkrWorkspaceSidebar`, which parents
|
||||
its tab strip, content stack and Shapes/Files pages. The pages own their
|
||||
controls. Provider description text is copied; no provider pointer is retained.
|
||||
- The controller holds non-owning document/scene references and owns its parser,
|
||||
mapper and stateless edit service by value. Referenced objects must outlive it.
|
||||
- The scene owns its `tkrShapePluginStore` and mapper calibration by value. The
|
||||
store owns a `QPluginLoader` and borrows its root provider interface. The
|
||||
binding is fixed for the scene lifetime; the native module remains resident.
|
||||
The edit service borrows the interface only for a request. API records contain
|
||||
values, without private source ranges, widgets or graphics pointers.
|
||||
- Do not combine QObject-parent ownership and `unique_ptr` ownership of the
|
||||
same object. `WA_DeleteOnClose` must not be set on this stack-owned window.
|
||||
|
||||
## Source and editing contracts
|
||||
|
||||
- Preserve source as bytes. Use byte offsets consistently for source ranges.
|
||||
Decoding the read-only source view must never become the saved representation.
|
||||
- Coordinate values are in centimeters; scene positions use scene units.
|
||||
Viewport pixels and zoom must not alter source geometry.
|
||||
- Element IDs are scoped to a document revision. Reparse after a committed
|
||||
edit and discard stale element records. IDs are not yet persistent identities.
|
||||
- Apply coordinate replacements as one validated batch, from the end backwards.
|
||||
Check revision, bounds, overlaps and expected original text before mutation.
|
||||
- Whole-element and rectangle-corner dragging preview geometry during movement and commits source
|
||||
once on release. Escape, focus loss, or cancelling an interaction restores
|
||||
geometry from the unchanged document. Endpoint dragging remains unimplemented.
|
||||
- Drag displacement is rounded to 0.000001 cm on release. Decimal string
|
||||
addition preserves the original coordinate precision and element dimensions;
|
||||
only values on changed axes are replaced. A candidate source/scene is validated
|
||||
before the model is changed. The edit service constrains both preview and
|
||||
release to the same stroke-aware extent and independent 0.01 cm rectangle
|
||||
minima; crossing flips around the fixed corner. Limits are normal interaction.
|
||||
- Saving uses `QSaveFile` with direct-write fallback disabled. Mark saved only
|
||||
after successful replacement. A baseline comparison detects observed external
|
||||
changes, but does not eliminate a concurrent-write race after that comparison.
|
||||
|
||||
## Implementation status
|
||||
|
||||
The parser conservatively interprets explicit-coordinate rectangles, lines and arrows,
|
||||
retaining numeric byte ranges and a separate non-movable comparison extent.
|
||||
The scene draws these records through the mapper, including PGF's default curved
|
||||
`to` arrowheads for `->`, `<-` and `<->`. Items are selectable; scene event
|
||||
handlers control whole-element movement instead of Qt's `ItemIsMovable` flag.
|
||||
The edit service prepares geometry and source replacements; the controller
|
||||
coordinates candidate validation and the document applies guarded source changes. No item
|
||||
pointers survive a reparse/rebuild. Endpoint handlers remain unsupported.
|
||||
Unsupported input returns diagnostics without a partial diagram. Core parsing
|
||||
remains independent of Widgets. The separate rectangle module supplies geometry,
|
||||
presentation, selection and operations; host validation/source rewriting and
|
||||
document acceptance stay in the application. See [the SDK](plugin-api/README.md).
|
||||
No integrated LaTeX/PDF, undo stack, provider management, creation, zoom controls
|
||||
or loop support is implemented. General product acceptance remains pending.
|
||||
|
||||
Keep TODOs specific, and return a clear unavailable/failure result from unfinished
|
||||
operations. Avoid reporting an empty parse as successful editable interpretation.
|
||||
|
||||
## Reference documentation
|
||||
|
||||
- [Qt CMake setup](https://doc.qt.io/qt-6/cmake-get-started.html)
|
||||
- [QObject ownership](https://doc.qt.io/qt-6/objecttrees.html)
|
||||
- [Window close behavior](https://doc.qt.io/qt-6/qwidget.html#close)
|
||||
- [QSaveFile replacement and failure behavior](https://doc.qt.io/qt-6/qsavefile.html)
|
||||
|
||||
|
||||
## Current sidebar shell and planned shared-service refactor
|
||||
|
||||
The [planned sidebar design](../documents/latex/tkrSidebarDesign.tex) moves shared
|
||||
store/catalogue ownership to the main window and gives views borrowed access.
|
||||
The current shell already has bounded sidebar, palette and folder-placeholder
|
||||
classes, parented through the main window central widget tree. Provider summary
|
||||
text is copied; the scene still owns the store. The catalogue and shared-service
|
||||
refactor remain planned. The current
|
||||
ownership list above remains the code's actual contract. Concrete constructor,
|
||||
teardown and API signatures require review before implementation.
|
||||
@@ -0,0 +1,287 @@
|
||||
# TikZRefinery application
|
||||
|
||||
This directory contains the C++/Qt Alpha implementation of the desktop
|
||||
graphical TikZ editor. Vincent selected C++ with Qt on October 1, 2026.
|
||||
|
||||
- `src/` contains application source code.
|
||||
- `tests/` contains automated tests.
|
||||
- `examples/` contains sample TikZ documents and demonstrations.
|
||||
- `resources/` contains application-owned icons, fixtures, and other resources.
|
||||
|
||||
## Class organization
|
||||
|
||||
| Class | Location | Responsibility |
|
||||
|---|---|---|
|
||||
| `tkrTikzDocument` | `src/model/` | Preserve source bytes, parsed records, revisions and minimal edits |
|
||||
| `tkrTikzParserExplicit` | `src/parsing/` | Interpret explicit cm rectangles/segments, byte ranges and fixed extent |
|
||||
| `tkrEditService` | `src/editing/` | Prepare constrained move/resize geometry and coordinate replacements |
|
||||
| `tkrCoordinateMapper` | `src/geometry/` | Convert centimeter coordinates and scene positions |
|
||||
| `tkrEditorController` | `src/controller/` | Coordinate model/scene, parsing, file I/O and saving |
|
||||
| `tkrDiagramScene` | `src/ui/` | Display/select elements, report body/corner gestures and preview geometry |
|
||||
| `tkrDiagramView` | `src/ui/` | Fit the canvas to the pane and paint the fixed editing extent |
|
||||
| `tkrMainWindow` | `src/ui/` | Own the document/controller/scene and provide application controls |
|
||||
| `tkrWorkspaceSidebar` | `src/ui/` | Own tab strip/pages; retain collapsed, selected-page and width state |
|
||||
| `tkrShapePalette` | `src/ui/` | Show copied rectangle-provider status; creation disabled |
|
||||
| `tkrFolderBrowser` | `src/ui/` | Show folder placeholder and request the existing guarded Open flow |
|
||||
| `tkrShapePluginStore` | `src/plugins/` | Validate, load and pin the rectangle module |
|
||||
| `tkrShapeProvider` | `plugin-api/` | Shared value-only provider Strategy interface |
|
||||
| `tkrRectangleShapeProvider` | `plugins/rectangle/` | Supply rectangle presentation and constrained operations in a separate DLL |
|
||||
|
||||
Each concrete class has a header and implementation; the pure provider interface is header-only. `src/model/EditorTypes.h` holds
|
||||
shared data records. See [CODING_GUIDE.md](CODING_GUIDE.md) for naming, ownership,
|
||||
source ranges and editing contracts.
|
||||
|
||||
On October 15, the six project classes and their matching files were renamed
|
||||
to use `tkr<MainClassName><Specification>`. The optional suffix describes a
|
||||
specialization, as in `tkrTikzParserExplicit`; it does not introduce a base
|
||||
class. The allowed maximum is three project-defined inheritance levels, but
|
||||
the concrete classes remain `final`. The rectangle implementation realizes the
|
||||
provider interface; that project-defined chain has two levels.
|
||||
The source-module rule now appears under Developer Requirements with its
|
||||
existing REQ-A-005 ID. Four new DEV requirements and proposed checks record
|
||||
class naming, other identifiers, depth, and ownership documentation.
|
||||
|
||||
The report's Software Architecture chapter includes an MVC allocation and a
|
||||
class responsibility overview with linked detail diagrams, including the edit service. Supporting
|
||||
activities remain in its Design Documents appendix.
|
||||
Their editable TikZ sources are under
|
||||
[`documents/assets/design-diagrams/`](../documents/assets/design-diagrams/).
|
||||
The diagrams distinguish whole-element editing from remaining endpoint work.
|
||||
|
||||
## Current behavior and limits
|
||||
|
||||
The source defines a window with Open/Save controls, a read-only source viewer,
|
||||
and a graphics scene. The controller reads original bytes and provides
|
||||
safe-save plumbing; the model validates source replacements. The mapper handles
|
||||
origin, scale and the inverted y axis. The explicit-coordinate parser preserves numeric
|
||||
byte ranges and displays outlines; the bounding path sets the fixed comparison
|
||||
extent and creates no item. Elements can be selected and dragged as a whole. Opening
|
||||
a file preserves its bytes and clean state, so Save remains disabled.
|
||||
|
||||
Drag a box (including its interior), line or arrow body to translate it. The
|
||||
scene previews movement while source stays unchanged. Release validates and
|
||||
commits one coordinate batch, updates the source pane and enables Save.
|
||||
Escape or focus loss cancels the preview. Save, opening another file or closing
|
||||
also cancels an active preview. Ctrl+S saves committed edits; the existing close
|
||||
guard handles unsaved changes. Click-only selection does not dirty the file.
|
||||
The hit allowance is about five viewport pixels. Displacement is rounded to
|
||||
0.000001 cm on release, with exact decimal translation of the original numbers;
|
||||
unchanged-axis spellings and all unrelated bytes are preserved. Move and resize
|
||||
preview and release stop at the furthest valid position inside a fixed extent,
|
||||
including stroke. Reaching that limit is an accepted edit, not a rejection.
|
||||
|
||||
Select a rectangle, then drag one of its four blue corner handles to resize.
|
||||
The opposite corner stays fixed; crossing it flips the rectangle. Width and
|
||||
height each stop at 0.01 cm (0.1 mm), independently, so thin fillers are allowed.
|
||||
Handles retain their screen size under view transforms. Escape, focus loss
|
||||
and Save cancel an active resize preview. A changed release applies one batch.
|
||||
Aspect-ratio locking and edge-only handles remain unimplemented. Session
|
||||
undo/redo now covers completed coordinate edits in 0.1.4-alpha.
|
||||
See `tests/evidence/resize-2026-11-12/README.md` for bounded automated evidence.
|
||||
|
||||
The whole-element increment passed all four CTest entries. Qt viewport mouse
|
||||
events exercise contact, line/arrow movement, cancellation, source changes and
|
||||
save/reopen; all three actual saved results match independently compiled output
|
||||
within the prototype one-pixel allowance. See
|
||||
[`tests/evidence/whole-element-drag-2026-10-21.md`](tests/evidence/whole-element-drag-2026-10-21.md).
|
||||
The interactive demo is `code/build/demo/boxes-drag-demo.tex`; keep its edits
|
||||
for review and avoid saving over the corpus fixtures when experimenting.
|
||||
|
||||
The first October 21 increment passed both then-registered tests and a fixed-extent
|
||||
TinyTeX raster comparison for the initial and touching-reference boxes. The
|
||||
automated window Open check also reaches the source, scene and status widgets.
|
||||
See [`tests/evidence/rectangle-display-2026-10-21.md`](tests/evidence/rectangle-display-2026-10-21.md)
|
||||
for observations, the one-pixel prototype comparison threshold, retained
|
||||
images/metrics, reproduction commands, and limits. Loading the touching
|
||||
reference does not establish a working drag/contact workflow.
|
||||
|
||||
The subsequent line/arrow increment passed all three registered tests and
|
||||
fixed-extent comparisons for all eight corpus files. The reference files were
|
||||
valid TikZ; the editor previously rejected their unsupported segment syntax.
|
||||
It now displays single straight `--` segments and the default `->`, `<-`, `<->`
|
||||
arrowheads. See [`tests/evidence/segment-display-2026-10-21.md`](tests/evidence/segment-display-2026-10-21.md).
|
||||
|
||||
Accepted input is a bare supported-command fragment, a single unconfigured
|
||||
`tikzpicture`, or the exact `article`/`tikz`/empty-page wrapper in the corpus.
|
||||
Absolute signed decimal/integer `cm` pairs and reversed corners are supported.
|
||||
Options may contain `black`, `solid`, and one positive literal `line width` in
|
||||
`pt`, in any order; a segment may also have one arrow-direction option. The
|
||||
default width is 0.4pt. Comments, UTF-8 comment bytes, CRLF,
|
||||
and an initial UTF-8 BOM retain their original offsets. One optional bounding
|
||||
path must precede drawings and enclose their outlines. Unsupported syntax,
|
||||
wrappers, custom arrow tips/styles, curves, polylines, transforms, loops and
|
||||
macros yield a diagnostic and an empty canvas. Zero-length segments and arrows
|
||||
whose tip insets consume their shaft are refused. This remains a bounded prototype.
|
||||
|
||||
The first native build passed on October 20, 2026 using Qt 6.12.0, matching
|
||||
MinGW/GCC 13.1.0, CMake 3.30.5, and Ninja 1.12.1 on Windows. CTest passed the
|
||||
one registered `core_foundations` test. Vincent opened `boxes-initial.tex` in
|
||||
the running application and confirmed the source display. This does not verify
|
||||
parsing, dragging, filesystem saves, timing, or canvas/PDF agreement. See
|
||||
[`tests/evidence/first-run-2026-10-20.md`](tests/evidence/first-run-2026-10-20.md).
|
||||
|
||||
## Build and run
|
||||
|
||||
### Recommended first Windows setup
|
||||
|
||||
Use the [Qt Online Installer](https://www.qt.io/development/download-open-source)
|
||||
and its open-source installation route. The recommended starting kit is desktop
|
||||
Qt 6 with the matching MinGW-w64 64-bit compiler, installed together. MSVC is
|
||||
also supported; it needs a separate Visual Studio C++ installation and the
|
||||
matching MSVC Qt package.
|
||||
|
||||
1. Create/sign in to a Qt account and choose a folder such as `C:\Qt`.
|
||||
2. Choose Custom Installation to inspect the components. Select one stable
|
||||
released Qt 6 desktop version and its **MinGW 64-bit** package. Qt 6.2 is
|
||||
the project's minimum, not a request to install that old release. Avoid
|
||||
beta, preview, or release-candidate builds.
|
||||
3. Include **Qt Creator**, the **MinGW compiler matching that Qt kit**,
|
||||
**CMake** (3.21 or later), and **Ninja**. Use the supplied matching compiler;
|
||||
its version depends on the selected Qt release. Core and Widgets are required.
|
||||
4. Open this directory's `CMakeLists.txt` in Qt Creator and select the desktop
|
||||
Qt 6 MinGW 64-bit kit. Check Preferences > Kits: Qt, compiler, debugger and
|
||||
CMake must resolve without errors. Keep the build directory under `code/build/`.
|
||||
5. Configure, build, and run. Open `boxes-initial.tex` to see two outlined boxes
|
||||
and the read-only source view; move/resize are available for the supported subset. Run the
|
||||
core tests separately before treating their checks as passed.
|
||||
|
||||
Qt Creator is the IDE, Qt supplies libraries, and MinGW supplies the compiler.
|
||||
Installing the IDE alone is insufficient. Confirm the installed versions and
|
||||
paths before running the command-line build below.
|
||||
|
||||
References: [Qt installation](https://doc.qt.io/qt-6/qt-online-installation.html),
|
||||
[Windows configurations](https://doc.qt.io/qt-6/windows.html),
|
||||
[opening CMake projects](https://doc.qt.io/qtcreator/creator-project-opening.html).
|
||||
|
||||
### Verified local Windows commands (October 20, 2026)
|
||||
|
||||
From the repository root in PowerShell, using the installed paths:
|
||||
|
||||
```powershell
|
||||
$env:Path = 'C:\Qt\6.12.0\mingw_64\bin;C:\Qt\Tools\mingw1310_64\bin;C:\Qt\Tools\Ninja;' + $env:Path
|
||||
& C:\Qt\Tools\CMake_64\bin\cmake.exe -S code -B code/build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=C:/Qt/6.12.0/mingw_64 -DCMAKE_CXX_COMPILER=C:/Qt/Tools/mingw1310_64/bin/g++.exe -DCMAKE_MAKE_PROGRAM=C:/Qt/Tools/Ninja/ninja.exe
|
||||
& C:\Qt\Tools\CMake_64\bin\cmake.exe --build code/build --parallel 4
|
||||
& C:\Qt\Tools\CMake_64\bin\ctest.exe --test-dir code/build --output-on-failure
|
||||
& .\code\build\TikZRefinery.exe
|
||||
```
|
||||
|
||||
An optional source-file argument opens that file on startup, for example:
|
||||
|
||||
```powershell
|
||||
& .\code\build\TikZRefinery.exe .\code\examples\explicit-coordinates\arrow-initial.tex
|
||||
```
|
||||
|
||||
Stop after any failed command and inspect its output. Close the running app
|
||||
before rebuilding it. The PATH change applies only to this PowerShell session;
|
||||
it lets Windows find Qt and MinGW DLLs without copying them into the repository.
|
||||
The executable in `code/build/` is a development build, not a deployed package.
|
||||
|
||||
### Refresh the Windows prototype package
|
||||
|
||||
Use the Demo 3 Release package at
|
||||
[`code/packages/0.1.4-alpha/`](packages/0.1.4-alpha/)
|
||||
for interactive review. Open `TikZRefinery.exe` from that folder in Explorer.
|
||||
It carries the Qt and MinGW runtime files and can be reopened without the
|
||||
development shell. Keep the executable with the package contents.
|
||||
Current policy uses `0.feature.revision-alpha`. A build retains the document
|
||||
baseline it implements even as the report advances. Completed document/code
|
||||
revisions advance the final number; completed feature releases advance the middle
|
||||
number and reset revision. Normal titles and versioned package folders omit Git
|
||||
hashes; About exposes short/full identity, source state and the loaded provider.
|
||||
|
||||
**Preserve `packages/TikZRefinery-windows-x64/`, the frozen Alpha 0.10.3 package,
|
||||
and its edited examples.** Its matching reports remain separate. The extracted
|
||||
rectangle module is delivered in `0.1.2-alpha/`; `0.2.0-alpha` is the later
|
||||
shape-discovery/creation milestone. See [the SDK](plugin-api/README.md) and
|
||||
[extraction evidence](tests/evidence/plugin-extraction-2026-11-20/README.md).
|
||||
Both Debug and Release pass six CTest suites, including actual DLL loading,
|
||||
negative compatibility cases and host validation. This is bounded evidence,
|
||||
not completed product acceptance.
|
||||
|
||||
The November 23 follow-up implements the bounded 0.1.3-alpha sidebar shell:
|
||||
Shapes/Files icons, collapse/reopen, retained session page/width, provider status
|
||||
and the existing guarded Open action. Creation remains disabled; no folder tree,
|
||||
catalogue API or service-ownership refactor is claimed. The scene still owns the
|
||||
plugin store. All seven suites pass in Debug and Release; native review checks
|
||||
the visible shell and unsaved-work guard. About truthfully records checkpoint
|
||||
`7a2965a4f14e` with modified working tree. See [shell evidence](tests/evidence/sidebar-shell-2026-11-23/README.md).
|
||||
The preceding [identity-only demo evidence](tests/evidence/demo3-package-2026-11-23/README.md)
|
||||
is historical and does not describe the replacement executable. Older packages
|
||||
and existing edited examples remain preserved.
|
||||
|
||||
For a visual increment, close the packaged app normally, then configure a
|
||||
Release build with the same Qt kit and run CTest. Use the commands in the
|
||||
previous section with a separate task-local build path under `work/` and
|
||||
`-DCMAKE_BUILD_TYPE=Release`. Check deployment with that kit's
|
||||
`windeployqt --release --compiler-runtime --no-translations --no-opengl-sw --no-system-d3d-compiler`.
|
||||
Add `--dry-run --list relative --dir <package-folder> <built-exe>` to see the
|
||||
required files before copying. Reuse the installed files if the kit is
|
||||
unchanged and the list is complete; redeploy the runtime and plugins if the kit
|
||||
or dependencies change.
|
||||
|
||||
For an authorized application increment, update only its designated development
|
||||
package and manifest; do not replace the frozen demo executable.
|
||||
Preserve any edited examples. Verify close and reopen with a Windows-only
|
||||
PATH before leaving the packaged app open for review, then remove the task's
|
||||
reproducible build scratch. See the
|
||||
[latest package check](tests/evidence/package-2026-11-05.md) and the
|
||||
[original Week 8 package evidence](tests/evidence/package-2026-10-23.md).
|
||||
|
||||
### Command-line build
|
||||
|
||||
Requires CMake 3.21+, a C++17 compiler, and a compatible Qt 6 development kit
|
||||
(Core and Widgets; project minimum 6.2). Choose a Qt kit matching the compiler
|
||||
and architecture. Python/PySide6 alone is not the C++ development kit.
|
||||
|
||||
In a shell configured for that kit, from the repository root:
|
||||
|
||||
```powershell
|
||||
cmake -S code -B code/build -DCMAKE_PREFIX_PATH="<Qt kit directory>"
|
||||
cmake --build code/build --config Debug
|
||||
ctest --test-dir code/build -C Debug --output-on-failure
|
||||
```
|
||||
|
||||
The executable is typically `code/build/Debug/TikZRefinery.exe` for a
|
||||
multi-configuration generator, or `code/build/TikZRefinery.exe` for a
|
||||
single-configuration generator. Run from the Qt kit's environment so Qt DLLs
|
||||
and platform plugins are available. Use the package above for interactive
|
||||
review outside that environment.
|
||||
|
||||
The `core_foundations` checks cover independent mapping expectations (TC-028),
|
||||
untouched UTF-8/CRLF bytes, variable-length replacements, stale revisions,
|
||||
overlapping ranges and atomic rejection of invalid batches. They do not cover
|
||||
GUI interaction, filesystem saves or canvas/PDF fidelity. The separate
|
||||
`rectangle_display` test covers parser/model/controller/scene geometry and an
|
||||
offscreen window Open action. `segment_display` covers all six line/arrow
|
||||
fixtures, direction flags, endpoints/ranges, mixed geometry, refused syntax,
|
||||
and startup-file windows. `whole_element_drag` covers viewport pointer gestures,
|
||||
exact minimal byte edits, cancellation, save/reopen, external-change refusal,
|
||||
precision and a 2x scaled/panned view. `tests/CompareRectangles.py` performs the external raster comparison
|
||||
separately, using the bundled Python/Pillow runtime and installed TinyTeX/Poppler.
|
||||
|
||||
The **Canvas** pane now uses a bordered white drawing surface so black TikZ
|
||||
geometry stays visible in either theme. The adjacent **TikZ source** pane
|
||||
still follows the window palette. The canvas fits the pane by default; for
|
||||
documents with a fixed editing extent, white paper matches that extent and
|
||||
the grey surround is outside it. See the
|
||||
[fit and boundary checks](tests/evidence/canvas-fit-2026-11-05/README.md) and
|
||||
[earlier palette checks](tests/evidence/canvas-contrast-2026-11-05/README.md).
|
||||
|
||||
## Next increment
|
||||
|
||||
1. Review the separately packaged rectangle plugin and actual UI screenshot.
|
||||
2. Review shape discovery, creation gestures and source insertion before the
|
||||
later 0.2.0-alpha milestone.
|
||||
3. Keep the planned transaction and history boundaries; generic transactions,
|
||||
endpoint editing, zoom/pan and integrated compilation remain pending.
|
||||
|
||||
The 0.1.4-alpha package implements session undo/redo for completed coordinate
|
||||
edits. Edit > Undo (Ctrl+Z) and Redo (Ctrl+Y) restore exact source bytes. Save
|
||||
retains history; successful Open/Reload clears it. A changed edit after Undo
|
||||
discards the redo branch. Snapshots have no automatic eviction; memory use grows
|
||||
with the session. Allocation failure before publication rejects the edit.
|
||||
See [history evidence](tests/evidence/undo-redo-2026-11-24/README.md).
|
||||
|
||||
The LaTeX report records the selected class and language decisions in the
|
||||
Development Plan and architectural requirements context. Product verification
|
||||
remains pending.
|
||||
@@ -0,0 +1,47 @@
|
||||
# Invoked on every build; replace generated files only when the identity changes.
|
||||
set(strCheckpoint "unavailable")
|
||||
set(strSourceState "source state unavailable")
|
||||
if(GIT_EXECUTABLE AND EXISTS "${GIT_EXECUTABLE}")
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${SOURCE_ROOT}" rev-parse HEAD
|
||||
OUTPUT_VARIABLE strHash OUTPUT_STRIP_TRAILING_WHITESPACE RESULT_VARIABLE iGitResult)
|
||||
if(iGitResult EQUAL 0 AND strHash MATCHES "^[0-9a-f]+$")
|
||||
set(strCheckpoint "${strHash}")
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${SOURCE_ROOT}" status --porcelain --untracked-files=normal
|
||||
OUTPUT_VARIABLE strStatus OUTPUT_STRIP_TRAILING_WHITESPACE RESULT_VARIABLE iStatusResult)
|
||||
if(iStatusResult EQUAL 0)
|
||||
if(strStatus STREQUAL "")
|
||||
set(strSourceState "clean checkpoint")
|
||||
else()
|
||||
set(strSourceState "modified working tree")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
if(NOT REPORT_VERSION)
|
||||
set(REPORT_VERSION "${PROJECT_VERSION}")
|
||||
endif()
|
||||
set(strShortCheckpoint "${strCheckpoint}")
|
||||
set(iShortCheckpointLength 12)
|
||||
if(NOT strCheckpoint STREQUAL "unavailable")
|
||||
string(SUBSTRING "${strCheckpoint}" 0 ${iShortCheckpointLength} strShortCheckpoint)
|
||||
endif()
|
||||
file(MAKE_DIRECTORY "${BINARY_ROOT}/generated")
|
||||
set(strHeader "#pragma once\nnamespace TikzRefinery::BuildInfo {\ninline constexpr char pVersion[] = \"${REPORT_VERSION}\";\ninline constexpr char pMaturity[] = \"Alpha\";\ninline constexpr char pCheckpoint[] = \"${strCheckpoint}\";\ninline constexpr char pShortCheckpoint[] = \"${strShortCheckpoint}\";\ninline constexpr char pSourceState[] = \"${strSourceState}\";\n}\n")
|
||||
set(strJson "{\n \"applicationVersion\": \"${REPORT_VERSION}\",\n \"maturity\": \"Alpha\",\n \"sourceCheckpoint\": \"${strCheckpoint}\",\n \"sourceCheckpointShort\": \"${strShortCheckpoint}\",\n \"sourceState\": \"${strSourceState}\"\n}\n")
|
||||
foreach(strOutput IN ITEMS header json)
|
||||
if(strOutput STREQUAL "header")
|
||||
set(strPath "${BINARY_ROOT}/generated/BuildInfo.h")
|
||||
set(strContent "${strHeader}")
|
||||
else()
|
||||
set(strPath "${BINARY_ROOT}/build-info.json")
|
||||
set(strContent "${strJson}")
|
||||
endif()
|
||||
if(EXISTS "${strPath}")
|
||||
file(READ "${strPath}" strExisting)
|
||||
else()
|
||||
set(strExisting "")
|
||||
endif()
|
||||
if(NOT strExisting STREQUAL strContent)
|
||||
file(WRITE "${strPath}" "${strContent}")
|
||||
endif()
|
||||
endforeach()
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
# Initial explicit-coordinate reference corpus
|
||||
|
||||
Vincent selected explicit coordinates and individual drawing commands as the
|
||||
first feasibility inputs on October 1, 2026. These are reference sources and
|
||||
expected revisions, not results produced by an implemented editor.
|
||||
|
||||
## Syntax boundary
|
||||
|
||||
Each editable element has one `\draw` command using absolute numeric Cartesian
|
||||
coordinates with explicit `cm` units. The examples use solid black outlines
|
||||
with `line width=0.6pt`, straight `--` segments, the arrow options `->`, `<-`,
|
||||
and `<->`, and `rectangle` between opposite corners. Whitespace, line breaks,
|
||||
comments, and the order of allowed options do not define different geometry.
|
||||
|
||||
The `\path[use as bounding box]` declaration is fixed calibration data.
|
||||
It keeps every picture's extent at (-2,-2) to (5,3) cm, so rendering each
|
||||
picture cannot recenter the changed geometry through independent tight crops.
|
||||
It is not a movable element. Preserve it, the wrapper, and unrelated source.
|
||||
|
||||
Nodes, named coordinates, relative coordinates, other units, coordinate
|
||||
expressions, transformations, macros, loops, fills, and custom styles await
|
||||
later coverage. This initial boundary is not a mandatory input format for
|
||||
all future diagrams. Instructor examples may guide expansion when available.
|
||||
|
||||
## Reference edits
|
||||
|
||||
| Planned test | Initial source | Gesture and expected geometry (cm) | Expected source |
|
||||
|---|---|---|---|
|
||||
| TC-021 | `line-initial.tex` | Translate by (0.5,0.5): (-1,-0.5), (1,0.5) become (-0.5,0), (1.5,1). | `line-translated.tex` |
|
||||
| TC-023 | `line-initial.tex` | Move only the second endpoint from (1,0.5) to (1,1.5). | `line-endpoint.tex` |
|
||||
| TC-022 | `arrow-initial.tex` | Translate only the first arrow by (0.5,0.5): (0,0), (2,1) become (0.5,0.5), (2.5,1.5). | `arrow-translated.tex` |
|
||||
| TC-024 | `arrow-initial.tex` | Move only the first arrow's second endpoint from (2,1) to (2,1.5). | `arrow-endpoint.tex` |
|
||||
| TC-025, TC-029 | `boxes-initial.tex` | Move only the right box left by 1 cm: corners (2,0), (3,1) become (1,0), (2,1). | `boxes-touching.tex` |
|
||||
|
||||
The arrow sample contains unchanged backward and double arrows to detect
|
||||
unintended edits. Repeat body and endpoint gestures on those variants during
|
||||
TC-022/TC-024 coverage. Expected files define numeric geometry and changes
|
||||
limited to the target coordinates; an editor may preserve a different valid
|
||||
decimal spelling while keeping comments, whitespace, and unrelated bytes.
|
||||
|
||||
For TC-029, the initial boxes are 1 cm square with a 1 cm gap between edge
|
||||
centerlines. After movement, their edge centerlines coincide at x=1 cm;
|
||||
the left box and both sizes remain unchanged. Account for stroke thickness
|
||||
when judging visible contact.
|
||||
|
||||
Use the same fixed extent, origin, and scale for canvas/PDF overlays (TC-027)
|
||||
and document the zoom range and geometric/rendering tolerances before product
|
||||
test execution (TC-026). Compile and visually review these sources with the
|
||||
shared TinyTeX toolchain; put output and intermediates under task-local `work`.
|
||||
The report contains the box illustrations, so no separate fixture PDFs need
|
||||
to be tracked. Rendering a fixture does not verify graphical editing.
|
||||
|
||||
## Independent coordinate checks (TC-028)
|
||||
|
||||
One proposed test configuration places the TikZ origin at scene position
|
||||
(200,300) and uses 100 scene units per cm, with scene y increasing downward:
|
||||
|
||||
`x_scene = 200 + 100*x_cm`, `y_scene = 300 - 100*y_cm`.
|
||||
|
||||
| TikZ point (cm) | Independently expected scene position |
|
||||
|---|---|
|
||||
| (0,0) | (200,300) |
|
||||
| (1,0) | (300,300) |
|
||||
| (0,1) | (200,200) |
|
||||
| (-1,-0.5) | (100,350) |
|
||||
|
||||
These constants are test inputs, not mandated application settings. Check
|
||||
forward and inverse conversions against the listed values, then round trips.
|
||||
Changing zoom or pan must not change those scene positions or source bytes.
|
||||
Map view/pointer coordinates into the scene before interpreting a drag.
|
||||
|
||||
## Later syntax coverage
|
||||
|
||||
Equivalent shapes expressed as nodes, named or relative coordinates,
|
||||
transformations, and generated loop instances need separate interpretation
|
||||
and edit tests. A successful compile can establish rendering even when
|
||||
graphical editing remains unsupported. Preserve source and provide a clear
|
||||
diagnostic in that case; do not infer safe editing from appearance alone.
|
||||
@@ -0,0 +1,17 @@
|
||||
% Initial explicit-coordinate reference corpus. See README.md.
|
||||
\documentclass{article}
|
||||
\usepackage{tikz}
|
||||
\pagestyle{empty}
|
||||
\begin{document}
|
||||
\noindent
|
||||
\begin{tikzpicture}
|
||||
% Fixed comparison extent; this is not a movable diagram element.
|
||||
\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);
|
||||
% First arrow is the target for the recorded edit.
|
||||
\draw[->,line width=0.6pt] (0cm,0cm) -- (2cm,1.5cm);
|
||||
% Unchanged start-arrow and double-arrow references.
|
||||
\draw[line width=0.6pt,<-] (0cm,-1cm) -- (2cm,-1cm);
|
||||
\draw[<->,line width=0.6pt] (0cm,2cm) -- (2cm,2cm);
|
||||
\end{tikzpicture}
|
||||
\end{document}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
% Initial explicit-coordinate reference corpus. See README.md.
|
||||
\documentclass{article}
|
||||
\usepackage{tikz}
|
||||
\pagestyle{empty}
|
||||
\begin{document}
|
||||
\noindent
|
||||
\begin{tikzpicture}
|
||||
% Fixed comparison extent; this is not a movable diagram element.
|
||||
\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);
|
||||
% First arrow is the target for the recorded edit.
|
||||
\draw[->,line width=0.6pt] (0cm,0cm) -- (2cm,1cm);
|
||||
% Unchanged start-arrow and double-arrow references.
|
||||
\draw[line width=0.6pt,<-] (0cm,-1cm) -- (2cm,-1cm);
|
||||
\draw[<->,line width=0.6pt] (0cm,2cm) -- (2cm,2cm);
|
||||
\end{tikzpicture}
|
||||
\end{document}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
% Initial explicit-coordinate reference corpus. See README.md.
|
||||
\documentclass{article}
|
||||
\usepackage{tikz}
|
||||
\pagestyle{empty}
|
||||
\begin{document}
|
||||
\noindent
|
||||
\begin{tikzpicture}
|
||||
% Fixed comparison extent; this is not a movable diagram element.
|
||||
\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);
|
||||
% First arrow is the target for the recorded edit.
|
||||
\draw[->,line width=0.6pt] (0.5cm,0.5cm) -- (2.5cm,1.5cm);
|
||||
% Unchanged start-arrow and double-arrow references.
|
||||
\draw[line width=0.6pt,<-] (0cm,-1cm) -- (2cm,-1cm);
|
||||
\draw[<->,line width=0.6pt] (0cm,2cm) -- (2cm,2cm);
|
||||
\end{tikzpicture}
|
||||
\end{document}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
% Initial explicit-coordinate reference corpus. See README.md.
|
||||
\documentclass{article}
|
||||
\usepackage{tikz}
|
||||
\pagestyle{empty}
|
||||
\begin{document}
|
||||
\noindent
|
||||
\begin{tikzpicture}
|
||||
% Fixed comparison extent; this is not a movable diagram element.
|
||||
\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);
|
||||
% Stationary left box.
|
||||
\draw[line width=0.6pt] (0cm,0cm) rectangle (1cm,1cm);
|
||||
% Move only this right box.
|
||||
\draw[line width=0.6pt] (2cm,0cm) rectangle (3cm,1cm);
|
||||
\end{tikzpicture}
|
||||
\end{document}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
% Initial explicit-coordinate reference corpus. See README.md.
|
||||
\documentclass{article}
|
||||
\usepackage{tikz}
|
||||
\pagestyle{empty}
|
||||
\begin{document}
|
||||
\noindent
|
||||
\begin{tikzpicture}
|
||||
% Fixed comparison extent; this is not a movable diagram element.
|
||||
\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);
|
||||
% Stationary left box.
|
||||
\draw[line width=0.6pt] (0cm,0cm) rectangle (1cm,1cm);
|
||||
% Move only this right box.
|
||||
\draw[line width=0.6pt] (1cm,0cm) rectangle (2cm,1cm);
|
||||
\end{tikzpicture}
|
||||
\end{document}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
% Initial explicit-coordinate reference corpus. See README.md.
|
||||
\documentclass{article}
|
||||
\usepackage{tikz}
|
||||
\pagestyle{empty}
|
||||
\begin{document}
|
||||
\noindent
|
||||
\begin{tikzpicture}
|
||||
% Fixed comparison extent; this is not a movable diagram element.
|
||||
\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);
|
||||
% Editable line; negative coordinates are intentional.
|
||||
\draw[line width=0.6pt] (-1cm,-0.5cm) -- (1cm,1.5cm);
|
||||
\end{tikzpicture}
|
||||
\end{document}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
% Initial explicit-coordinate reference corpus. See README.md.
|
||||
\documentclass{article}
|
||||
\usepackage{tikz}
|
||||
\pagestyle{empty}
|
||||
\begin{document}
|
||||
\noindent
|
||||
\begin{tikzpicture}
|
||||
% Fixed comparison extent; this is not a movable diagram element.
|
||||
\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);
|
||||
% Editable line; negative coordinates are intentional.
|
||||
\draw[line width=0.6pt] (-1cm,-0.5cm) -- (1cm,0.5cm);
|
||||
\end{tikzpicture}
|
||||
\end{document}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
% Initial explicit-coordinate reference corpus. See README.md.
|
||||
\documentclass{article}
|
||||
\usepackage{tikz}
|
||||
\pagestyle{empty}
|
||||
\begin{document}
|
||||
\noindent
|
||||
\begin{tikzpicture}
|
||||
% Fixed comparison extent; this is not a movable diagram element.
|
||||
\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);
|
||||
% Editable line; negative coordinates are intentional.
|
||||
\draw[line width=0.6pt] (-0.5cm,0cm) -- (1.5cm,1cm);
|
||||
\end{tikzpicture}
|
||||
\end{document}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
% Rectangle display, selection, move and resize use the loaded shape provider.
|
||||
% The arrow retains the built-in explicit-syntax display route.
|
||||
\path[use as bounding box] (-1cm,-1cm) rectangle (6.5cm,3.5cm);
|
||||
\draw[line width=0.6pt] (0cm,0cm) rectangle (2cm,2cm);
|
||||
\draw[line width=0.6pt] (3.5cm,0.5cm) rectangle (5.5cm,2.5cm);
|
||||
\draw[->,line width=0.6pt] (2cm,1cm) -- (3.5cm,1.5cm);
|
||||
@@ -0,0 +1,42 @@
|
||||
# Shape API v1 - initial rectangle extraction
|
||||
|
||||
`tikzrefinery_shape_api` exports only these public headers and Qt Core.
|
||||
The module implements `tkrShapeProvider`; the host loads it with Qt's native
|
||||
plugin mechanism. Widgets, graphics items, byte ranges, files and history are
|
||||
outside the API. This is a same-toolchain C++ contract, not a stable cross-vendor
|
||||
ABI, sandbox or adapter layer. Use the exact API/schema, Qt, compiler, platform,
|
||||
pointer size and Debug/Release build key in the module metadata.
|
||||
|
||||
Records use document centimetres and TeX-point stroke widths. An element has
|
||||
document UUID, revision-scoped element ID/revision, family/type/schema, opposite
|
||||
corners and appearance/content. The first provider supports black, unfilled,
|
||||
empty-content rectangles. Other geometry/presentation schemas remain future work.
|
||||
|
||||
Operations are `tkr.move` and `tkr.resize`, parameter schema 1. Move supplies total
|
||||
displacement from initial geometry; resize also supplies one of four semantic
|
||||
corner IDs. Constraints contain optional fixed bounds and independent minimum
|
||||
dimensions. Requests never contain source spellings or ranges. Results distinguish
|
||||
PreparedChange, Unchanged and CannotPrepare with reason. A result is not acceptance.
|
||||
|
||||
Presentation contains an outline rectangle, selection rectangle, readable name
|
||||
and four identified handle positions. The scene maps these values into its own
|
||||
graphics items and constant-screen-size handles. It owns no plugin graphics item.
|
||||
The edit service checks capabilities and proposal invariants, prepares exact
|
||||
source replacements and the document applies guarded coordinate batches.
|
||||
|
||||
`tkrShapePluginStore` selects only the explicitly configured rectangle module
|
||||
under `shape-plugins/`. It validates identity, role, API/data/parameter schemas,
|
||||
operations and build key before activation, then pins its binding for the scene
|
||||
lifetime (the Qt module remains resident for the process). A host UUID identifies
|
||||
that runtime binding separately from the declared plugin ID/version. It does not
|
||||
scan competing providers or choose one by load order. Candidate selection UI,
|
||||
multiple-provider registration, hot updates and migration remain planned.
|
||||
|
||||
To build a provider, link the INTERFACE target, implement the three const methods,
|
||||
use `Q_PLUGIN_METADATA` / `Q_INTERFACES`, and declare compatible metadata. The
|
||||
working reference is `plugins/rectangle/`; compile a MODULE target with matching
|
||||
headers/toolchain and deploy its DLL beside the app in `shape-plugins/`.
|
||||
No provider function may mutate a live document, scene, history or file.
|
||||
|
||||
Reference: [Qt application plugins](https://doc.qt.io/qt-6/plugins-howto.html),
|
||||
[QPluginLoader](https://doc.qt.io/qt-6/qpluginloader.html).
|
||||
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include <QMetaType>
|
||||
#include <QPointF>
|
||||
#include <QRectF>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QUuid>
|
||||
#include <QVector>
|
||||
|
||||
namespace TikzRefinery::ShapeApi {
|
||||
|
||||
inline constexpr int iApiVersion = 1;
|
||||
inline constexpr int iRectangleSchemaVersion = 1;
|
||||
inline constexpr int iParameterSchemaVersion = 1;
|
||||
inline constexpr int iCoordinateDecimals = 6;
|
||||
inline constexpr qreal rCoordinateStepsPerCentimeter = 1000000.0;
|
||||
inline constexpr qreal rMinimumRectangleCentimeters = 0.01;
|
||||
inline constexpr qreal rCentimetersPerTexPoint = 2.54 / 72.27;
|
||||
inline constexpr qreal rHalfStroke = 0.5;
|
||||
inline constexpr qreal rDefaultLineWidthPoints = 0.4;
|
||||
inline const QString strMoveOperation = QStringLiteral("tkr.move");
|
||||
inline const QString strResizeOperation = QStringLiteral("tkr.resize");
|
||||
inline const QString strRectangleFamily = QStringLiteral("rectangle");
|
||||
inline const QString strRectangleType = QStringLiteral("tkr.rectangle.opposite-corners");
|
||||
|
||||
enum class HandleId { FirstFirst, FirstSecond, SecondFirst, SecondSecond };
|
||||
enum class PreparationOutcome { PreparedChange, Unchanged, CannotPrepare };
|
||||
|
||||
// Value records in document centimetres. No source ranges, widgets or item pointers.
|
||||
struct ElementDescription
|
||||
{
|
||||
QUuid documentId;
|
||||
quint64 uElementId = 0;
|
||||
quint64 uRevision = 0;
|
||||
QString strFamily = strRectangleFamily;
|
||||
QString strType = strRectangleType;
|
||||
int iSchemaVersion = iRectangleSchemaVersion;
|
||||
QPointF ptFirstCentimeters;
|
||||
QPointF ptSecondCentimeters;
|
||||
qreal rLineWidthPoints = rDefaultLineWidthPoints;
|
||||
QString strStrokeColor = QStringLiteral("black");
|
||||
QString strContent;
|
||||
};
|
||||
|
||||
struct HandleDescription
|
||||
{
|
||||
HandleId handleId = HandleId::FirstFirst;
|
||||
QPointF ptPositionCentimeters;
|
||||
};
|
||||
|
||||
struct PresentationDescription
|
||||
{
|
||||
bool bAvailable = false;
|
||||
QString strReason;
|
||||
QString strReadableDescription;
|
||||
QRectF rectOutlineCentimeters;
|
||||
QRectF rectSelectionCentimeters;
|
||||
QVector<HandleDescription> vecHandles;
|
||||
};
|
||||
|
||||
struct EditingConstraints
|
||||
{
|
||||
bool bHasFixedBounds = false;
|
||||
QRectF rectBoundsCentimeters;
|
||||
qreal rMinimumWidthCentimeters = rMinimumRectangleCentimeters;
|
||||
qreal rMinimumHeightCentimeters = rMinimumRectangleCentimeters;
|
||||
};
|
||||
|
||||
struct OperationRequest
|
||||
{
|
||||
QUuid documentId;
|
||||
quint64 uElementId = 0;
|
||||
quint64 uRevision = 0;
|
||||
ElementDescription initial;
|
||||
QString strOperationId;
|
||||
int iParameterSchemaVersion = ShapeApi::iParameterSchemaVersion;
|
||||
QPointF ptTotalDisplacementCentimeters;
|
||||
HandleId handleId = HandleId::SecondSecond;
|
||||
EditingConstraints constraints;
|
||||
};
|
||||
|
||||
struct PreparationResult
|
||||
{
|
||||
PreparationOutcome outcome = PreparationOutcome::CannotPrepare;
|
||||
ElementDescription proposed;
|
||||
QString strReason;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery::ShapeApi
|
||||
|
||||
Q_DECLARE_METATYPE(TikzRefinery::ShapeApi::ElementDescription)
|
||||
Q_DECLARE_METATYPE(TikzRefinery::ShapeApi::PresentationDescription)
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include "ShapeTypes.h"
|
||||
#include <QtPlugin>
|
||||
|
||||
#define TKR_SHAPE_PROVIDER_IID "org.tikzrefinery.ShapeProvider/1.0"
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
// Strategy interface; native modules require the exact documented build contract.
|
||||
class tkrShapeProvider
|
||||
{
|
||||
public:
|
||||
virtual ~tkrShapeProvider() = default;
|
||||
virtual QStringList availableOperations(const ShapeApi::ElementDescription &description) const = 0;
|
||||
virtual ShapeApi::PresentationDescription describePresentation(
|
||||
const ShapeApi::ElementDescription &description) const = 0;
|
||||
virtual ShapeApi::PreparationResult prepareOperation(const ShapeApi::OperationRequest &request) const = 0;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
|
||||
Q_DECLARE_INTERFACE(TikzRefinery::tkrShapeProvider, TKR_SHAPE_PROVIDER_IID)
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"id": "org.tikzrefinery.rectangle",
|
||||
"name": "TikZRefinery Rectangle",
|
||||
"version": "@strDocumentVersion@",
|
||||
"role": "shape",
|
||||
"apiVersion": 1,
|
||||
"shapeType": "tkr.rectangle.opposite-corners",
|
||||
"geometrySchemaVersion": 1,
|
||||
"parameterSchemaVersion": 1,
|
||||
"operations": ["tkr.move", "tkr.resize"],
|
||||
"buildKey": "@strShapeBuildKey@"
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
#include "tkrRectangleShapeProvider.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace TikzRefinery {
|
||||
namespace {
|
||||
using namespace ShapeApi;
|
||||
|
||||
bool finitePoint(const QPointF &ptPosition)
|
||||
{
|
||||
return std::isfinite(ptPosition.x()) && std::isfinite(ptPosition.y());
|
||||
}
|
||||
|
||||
bool supported(const ElementDescription &description)
|
||||
{
|
||||
return description.strFamily == strRectangleFamily && description.strType == strRectangleType
|
||||
&& description.iSchemaVersion == iRectangleSchemaVersion
|
||||
&& description.strStrokeColor == QStringLiteral("black") && description.strContent.isEmpty()
|
||||
&& finitePoint(description.ptFirstCentimeters) && finitePoint(description.ptSecondCentimeters)
|
||||
&& finitePoint(description.ptSecondCentimeters - description.ptFirstCentimeters)
|
||||
&& std::isfinite(description.rLineWidthPoints) && description.rLineWidthPoints > 0
|
||||
&& description.ptFirstCentimeters.x() != description.ptSecondCentimeters.x()
|
||||
&& description.ptFirstCentimeters.y() != description.ptSecondCentimeters.y();
|
||||
}
|
||||
|
||||
qreal rounded(qreal rValue)
|
||||
{
|
||||
return std::round(rValue * rCoordinateStepsPerCentimeter) / rCoordinateStepsPerCentimeter;
|
||||
}
|
||||
|
||||
bool boundedOffset(qreal rRequested, qreal rLow, qreal rHigh, qreal &rResult)
|
||||
{
|
||||
const qreal rLowStep = std::isfinite(rLow)
|
||||
? std::ceil(rLow * rCoordinateStepsPerCentimeter) / rCoordinateStepsPerCentimeter : rLow;
|
||||
const qreal rHighStep = std::isfinite(rHigh)
|
||||
? std::floor(rHigh * rCoordinateStepsPerCentimeter) / rCoordinateStepsPerCentimeter : rHigh;
|
||||
if (rLowStep > rHighStep) return false;
|
||||
rResult = std::clamp(rounded(rRequested), rLowStep, rHighStep);
|
||||
return std::isfinite(rResult);
|
||||
}
|
||||
|
||||
bool resizeAxis(qreal rOriginal, qreal rFixed, qreal rRequested, qreal rLow, qreal rHigh,
|
||||
qreal rMinimum, qreal &rResult)
|
||||
{
|
||||
const bool bPositive = rRequested == rFixed ? rOriginal > rFixed : rRequested > rFixed;
|
||||
const auto trySide = [&](bool bSide) {
|
||||
const qreal rMin = bSide ? std::max(rLow, rFixed + rMinimum) : rLow;
|
||||
const qreal rMax = bSide ? rHigh : std::min(rHigh, rFixed - rMinimum);
|
||||
qreal rOffset = 0;
|
||||
if (!boundedOffset(rRequested - rOriginal, rMin - rOriginal, rMax - rOriginal, rOffset)) return false;
|
||||
rResult = rOriginal + rOffset;
|
||||
return true;
|
||||
};
|
||||
return trySide(bPositive) || trySide(!bPositive);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
QStringList tkrRectangleShapeProvider::availableOperations(const ShapeApi::ElementDescription &description) const
|
||||
{
|
||||
return supported(description) ? QStringList{strMoveOperation, strResizeOperation} : QStringList{};
|
||||
}
|
||||
|
||||
ShapeApi::PresentationDescription tkrRectangleShapeProvider::describePresentation(
|
||||
const ShapeApi::ElementDescription &description) const
|
||||
{
|
||||
PresentationDescription presentation;
|
||||
if (!supported(description)) {
|
||||
presentation.strReason = QStringLiteral("Unsupported rectangle description/schema or geometry.");
|
||||
return presentation;
|
||||
}
|
||||
const QPointF &ptFirst = description.ptFirstCentimeters;
|
||||
const QPointF &ptSecond = description.ptSecondCentimeters;
|
||||
presentation.bAvailable = true;
|
||||
presentation.strReadableDescription = QStringLiteral("Rectangle %1").arg(description.uElementId);
|
||||
presentation.rectOutlineCentimeters = QRectF(ptFirst, ptSecond).normalized();
|
||||
presentation.rectSelectionCentimeters = presentation.rectOutlineCentimeters;
|
||||
presentation.vecHandles = {{HandleId::FirstFirst, ptFirst},
|
||||
{HandleId::FirstSecond, {ptFirst.x(), ptSecond.y()}},
|
||||
{HandleId::SecondFirst, {ptSecond.x(), ptFirst.y()}},
|
||||
{HandleId::SecondSecond, ptSecond}};
|
||||
return presentation;
|
||||
}
|
||||
|
||||
ShapeApi::PreparationResult tkrRectangleShapeProvider::prepareOperation(const ShapeApi::OperationRequest &request) const
|
||||
{
|
||||
PreparationResult result;
|
||||
result.proposed = request.initial;
|
||||
if (!availableOperations(request.initial).contains(request.strOperationId)
|
||||
|| request.iParameterSchemaVersion != iParameterSchemaVersion
|
||||
|| request.documentId != request.initial.documentId
|
||||
|| request.documentId.isNull() || !request.uElementId || !request.uRevision
|
||||
|| request.uElementId != request.initial.uElementId || request.uRevision != request.initial.uRevision
|
||||
|| !finitePoint(request.ptTotalDisplacementCentimeters)) {
|
||||
result.strReason = QStringLiteral("Unsupported operation/schema, stale target or non-finite displacement.");
|
||||
return result;
|
||||
}
|
||||
const EditingConstraints &constraints = request.constraints;
|
||||
if (!std::isfinite(constraints.rMinimumWidthCentimeters) || constraints.rMinimumWidthCentimeters <= 0
|
||||
|| !std::isfinite(constraints.rMinimumHeightCentimeters) || constraints.rMinimumHeightCentimeters <= 0
|
||||
|| (constraints.bHasFixedBounds && (!constraints.rectBoundsCentimeters.isValid()
|
||||
|| !finitePoint(constraints.rectBoundsCentimeters.topLeft())
|
||||
|| !finitePoint(constraints.rectBoundsCentimeters.bottomRight())))) {
|
||||
result.strReason = QStringLiteral("Invalid editing constraints.");
|
||||
return result;
|
||||
}
|
||||
const qreal rInfinity = std::numeric_limits<qreal>::infinity();
|
||||
qreal rLeft = -rInfinity, rRight = rInfinity, rBottom = -rInfinity, rTop = rInfinity;
|
||||
if (constraints.bHasFixedBounds) {
|
||||
const qreal rMargin = request.initial.rLineWidthPoints * rCentimetersPerTexPoint * rHalfStroke;
|
||||
rLeft = constraints.rectBoundsCentimeters.left() + rMargin;
|
||||
rRight = constraints.rectBoundsCentimeters.right() - rMargin;
|
||||
rBottom = constraints.rectBoundsCentimeters.top() + rMargin;
|
||||
rTop = constraints.rectBoundsCentimeters.bottom() - rMargin;
|
||||
}
|
||||
const QPointF &ptDelta = request.ptTotalDisplacementCentimeters;
|
||||
if (request.strOperationId == strMoveOperation) {
|
||||
const QRectF rectInitial(request.initial.ptFirstCentimeters, request.initial.ptSecondCentimeters);
|
||||
const QRectF rectNormalized = rectInitial.normalized();
|
||||
qreal rX = 0, rY = 0;
|
||||
if (!boundedOffset(ptDelta.x(), rLeft - rectNormalized.left(), rRight - rectNormalized.right(), rX)
|
||||
|| !boundedOffset(ptDelta.y(), rBottom - rectNormalized.top(), rTop - rectNormalized.bottom(), rY)) {
|
||||
result.strReason = QStringLiteral("No valid position inside the editing extent.");
|
||||
return result;
|
||||
}
|
||||
result.proposed.ptFirstCentimeters += QPointF(rX, rY);
|
||||
result.proposed.ptSecondCentimeters += QPointF(rX, rY);
|
||||
} else {
|
||||
const bool bFirstX = request.handleId == HandleId::FirstFirst || request.handleId == HandleId::FirstSecond;
|
||||
const bool bFirstY = request.handleId == HandleId::FirstFirst || request.handleId == HandleId::SecondFirst;
|
||||
if (request.handleId != HandleId::FirstFirst && request.handleId != HandleId::FirstSecond
|
||||
&& request.handleId != HandleId::SecondFirst && request.handleId != HandleId::SecondSecond) {
|
||||
result.strReason = QStringLiteral("Unsupported resize handle.");
|
||||
return result;
|
||||
}
|
||||
const QPointF &ptFirst = request.initial.ptFirstCentimeters;
|
||||
const QPointF &ptSecond = request.initial.ptSecondCentimeters;
|
||||
const qreal rOriginalX = bFirstX ? ptFirst.x() : ptSecond.x();
|
||||
const qreal rOriginalY = bFirstY ? ptFirst.y() : ptSecond.y();
|
||||
const qreal rFixedX = bFirstX ? ptSecond.x() : ptFirst.x();
|
||||
const qreal rFixedY = bFirstY ? ptSecond.y() : ptFirst.y();
|
||||
qreal rX = 0, rY = 0;
|
||||
if (!resizeAxis(rOriginalX, rFixedX, rOriginalX + ptDelta.x(), rLeft, rRight,
|
||||
constraints.rMinimumWidthCentimeters, rX)
|
||||
|| !resizeAxis(rOriginalY, rFixedY, rOriginalY + ptDelta.y(), rBottom, rTop,
|
||||
constraints.rMinimumHeightCentimeters, rY)) {
|
||||
result.strReason = QStringLiteral("The extent cannot accommodate the minimum rectangle size.");
|
||||
return result;
|
||||
}
|
||||
(bFirstX ? result.proposed.ptFirstCentimeters : result.proposed.ptSecondCentimeters).setX(rX);
|
||||
(bFirstY ? result.proposed.ptFirstCentimeters : result.proposed.ptSecondCentimeters).setY(rY);
|
||||
}
|
||||
result.outcome = result.proposed.ptFirstCentimeters == request.initial.ptFirstCentimeters
|
||||
&& result.proposed.ptSecondCentimeters == request.initial.ptSecondCentimeters
|
||||
? PreparationOutcome::Unchanged : PreparationOutcome::PreparedChange;
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include "tkrShapeProvider.h"
|
||||
#include <QObject>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
class tkrRectangleShapeProvider final : public QObject, public tkrShapeProvider
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PLUGIN_METADATA(IID TKR_SHAPE_PROVIDER_IID FILE "rectangle-plugin.json")
|
||||
Q_INTERFACES(TikzRefinery::tkrShapeProvider)
|
||||
public:
|
||||
QStringList availableOperations(const ShapeApi::ElementDescription &description) const override;
|
||||
ShapeApi::PresentationDescription describePresentation(
|
||||
const ShapeApi::ElementDescription &description) const override;
|
||||
ShapeApi::PreparationResult prepareOperation(const ShapeApi::OperationRequest &request) const override;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
#include "controller/tkrEditorController.h"
|
||||
|
||||
#include "model/tkrTikzDocument.h"
|
||||
#include "ui/tkrDiagramScene.h"
|
||||
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QSaveFile>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <new>
|
||||
|
||||
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<CoordinateEdit> 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
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
|
||||
#include "geometry/tkrCoordinateMapper.h"
|
||||
#include "parsing/tkrTikzParserExplicit.h"
|
||||
#include "editing/tkrEditService.h"
|
||||
|
||||
#include <QObject>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
class tkrDiagramScene;
|
||||
class tkrTikzDocument;
|
||||
|
||||
// References document/scene; owns parser/mapper as value members.
|
||||
class tkrEditorController final : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
tkrEditorController(tkrTikzDocument &document, tkrDiagramScene &diagramScene,
|
||||
QObject *pParent = nullptr);
|
||||
OperationResult openDocument(const QString &strFilePath);
|
||||
OperationResult saveDocument();
|
||||
OperationResult refreshParsedDocument();
|
||||
OperationResult undo();
|
||||
OperationResult redo();
|
||||
|
||||
public slots:
|
||||
void handleDragPreview(const TikzRefinery::DragUpdate &dragUpdate);
|
||||
void handleDragCommit(const TikzRefinery::DragUpdate &dragUpdate);
|
||||
void cancelDrag();
|
||||
|
||||
signals:
|
||||
void documentChanged();
|
||||
void statusChanged(const QString &strMessage);
|
||||
|
||||
private:
|
||||
OperationResult validateDrag(const DragUpdate &dragUpdate) const;
|
||||
GestureGeometry prepareGesture(const DragUpdate &dragUpdate) const;
|
||||
void rejectDrag(const QString &strReason);
|
||||
OperationResult restoreHistory(bool bRedo);
|
||||
tkrTikzDocument &m_refDocument;
|
||||
tkrDiagramScene &m_refScene;
|
||||
tkrTikzParserExplicit m_parser;
|
||||
tkrCoordinateMapper m_mapper;
|
||||
tkrEditService m_editService;
|
||||
ComparisonExtent m_comparisonExtent;
|
||||
QByteArray m_baFileBaseline;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "editing/tkrEditHistory.h"
|
||||
#include <utility>
|
||||
|
||||
namespace TikzRefinery {
|
||||
namespace { constexpr qsizetype nEntryStep = 1; }
|
||||
bool tkrEditHistory::canUndo() const { return m_nCursor > 0; }
|
||||
bool tkrEditHistory::canRedo() const { return m_nCursor < m_vecEntries.size(); }
|
||||
QString tkrEditHistory::undoDescription() const
|
||||
{ return canUndo() ? m_vecEntries.at(m_nCursor - nEntryStep).strDescription : QString(); }
|
||||
QString tkrEditHistory::redoDescription() const
|
||||
{ return canRedo() ? m_vecEntries.at(m_nCursor).strDescription : QString(); }
|
||||
void tkrEditHistory::record(const QByteArray &baBefore, const QByteArray &baAfter,
|
||||
const QString &strDescription)
|
||||
{
|
||||
// Prepare detached storage first. Allocation failure cannot discard the redo branch.
|
||||
QVector<Entry> vecPrepared = m_vecEntries;
|
||||
vecPrepared.resize(m_nCursor);
|
||||
vecPrepared.append({baBefore, baAfter, strDescription});
|
||||
m_vecEntries.swap(vecPrepared);
|
||||
m_nCursor = m_vecEntries.size();
|
||||
}
|
||||
void tkrEditHistory::clear() { QVector<Entry>().swap(m_vecEntries); m_nCursor = 0; }
|
||||
QByteArray tkrEditHistory::restorationSource(bool bRedo) const
|
||||
{
|
||||
return bRedo ? m_vecEntries.at(m_nCursor).baAfter
|
||||
: m_vecEntries.at(m_nCursor - nEntryStep).baBefore;
|
||||
}
|
||||
void tkrEditHistory::advance(bool bRedo) { m_nCursor += bRedo ? nEntryStep : -nEntryStep; }
|
||||
void tkrEditHistory::swap(tkrEditHistory &historyOther) noexcept
|
||||
{
|
||||
m_vecEntries.swap(historyOther.m_vecEntries);
|
||||
std::swap(m_nCursor, historyOther.m_nCursor);
|
||||
}
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
|
||||
namespace TikzRefinery {
|
||||
class tkrTikzDocument;
|
||||
|
||||
// Session-only value storage. Only the document may publish or traverse entries.
|
||||
class tkrEditHistory final
|
||||
{
|
||||
friend class tkrTikzDocument;
|
||||
public:
|
||||
bool canUndo() const;
|
||||
bool canRedo() const;
|
||||
QString undoDescription() const;
|
||||
QString redoDescription() const;
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
QByteArray baBefore;
|
||||
QByteArray baAfter;
|
||||
QString strDescription;
|
||||
};
|
||||
void record(const QByteArray &baBefore, const QByteArray &baAfter,
|
||||
const QString &strDescription);
|
||||
void clear();
|
||||
QByteArray restorationSource(bool bRedo) const;
|
||||
void advance(bool bRedo);
|
||||
void swap(tkrEditHistory &historyOther) noexcept;
|
||||
QVector<Entry> m_vecEntries;
|
||||
qsizetype m_nCursor = 0;
|
||||
};
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,268 @@
|
||||
#include "editing/tkrEditService.h"
|
||||
#include "geometry/ShapeGeometryLimits.h"
|
||||
#include "plugins/ShapeProviderAdapter.h"
|
||||
#include "tkrShapeProvider.h"
|
||||
|
||||
#include <QRectF>
|
||||
#include <QRegularExpression>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace TikzRefinery {
|
||||
namespace {
|
||||
|
||||
struct DecimalValue
|
||||
{
|
||||
bool bNegative = false;
|
||||
QByteArray baDigits;
|
||||
qsizetype nDecimals = 0;
|
||||
};
|
||||
|
||||
QByteArray trimLeadingZeros(const QByteArray &baDigits)
|
||||
{
|
||||
qsizetype nFirst = 0;
|
||||
while (nFirst + 1 < baDigits.size() && baDigits.at(nFirst) == '0') {
|
||||
++nFirst;
|
||||
}
|
||||
return baDigits.mid(nFirst);
|
||||
}
|
||||
|
||||
bool readDecimal(const QByteArray &baText, DecimalValue &decimalValue)
|
||||
{
|
||||
static const QRegularExpression expressionNumber(
|
||||
QStringLiteral(R"(\A[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z)"));
|
||||
if (!expressionNumber.match(QString::fromLatin1(baText)).hasMatch()) {
|
||||
return false;
|
||||
}
|
||||
decimalValue.baDigits = baText;
|
||||
decimalValue.bNegative = baText.startsWith('-');
|
||||
if (baText.startsWith('-') || baText.startsWith('+')) {
|
||||
decimalValue.baDigits.remove(0, 1);
|
||||
}
|
||||
const qsizetype nDot = decimalValue.baDigits.indexOf('.');
|
||||
if (nDot >= 0) {
|
||||
decimalValue.nDecimals = decimalValue.baDigits.size() - nDot - 1;
|
||||
decimalValue.baDigits.remove(nDot, 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Exact decimal addition preserves the element's size even when the original
|
||||
// coordinate has more fractional digits than the drag's 0.000001 cm precision.
|
||||
bool translateCoordinate(const QByteArray &baOriginal, const QByteArray &baDelta, QByteArray &baResult)
|
||||
{
|
||||
DecimalValue decimalOriginal;
|
||||
DecimalValue decimalDelta;
|
||||
if (!readDecimal(baOriginal, decimalOriginal) || !readDecimal(baDelta, decimalDelta)) {
|
||||
return false;
|
||||
}
|
||||
const qsizetype nDecimals = std::max(decimalOriginal.nDecimals, decimalDelta.nDecimals);
|
||||
decimalOriginal.baDigits.append(QByteArray(nDecimals - decimalOriginal.nDecimals, '0'));
|
||||
decimalDelta.baDigits.append(QByteArray(nDecimals - decimalDelta.nDecimals, '0'));
|
||||
decimalOriginal.baDigits = trimLeadingZeros(decimalOriginal.baDigits);
|
||||
decimalDelta.baDigits = trimLeadingZeros(decimalDelta.baDigits);
|
||||
bool bNegative = decimalOriginal.bNegative;
|
||||
const bool bAdd = decimalOriginal.bNegative == decimalDelta.bNegative;
|
||||
if (!bAdd && (decimalOriginal.baDigits.size() < decimalDelta.baDigits.size()
|
||||
|| (decimalOriginal.baDigits.size() == decimalDelta.baDigits.size()
|
||||
&& decimalOriginal.baDigits.compare(decimalDelta.baDigits) < 0))) {
|
||||
std::swap(decimalOriginal, decimalDelta);
|
||||
bNegative = decimalOriginal.bNegative;
|
||||
}
|
||||
qsizetype nOriginal = decimalOriginal.baDigits.size();
|
||||
qsizetype nDelta = decimalDelta.baDigits.size();
|
||||
int iCarry = 0;
|
||||
QByteArray baReversed;
|
||||
while (nOriginal > 0 || nDelta > 0 || (bAdd && iCarry != 0)) {
|
||||
const int iOriginal = nOriginal > 0 ? decimalOriginal.baDigits.at(--nOriginal) - '0' : 0;
|
||||
const int iDelta = nDelta > 0 ? decimalDelta.baDigits.at(--nDelta) - '0' : 0;
|
||||
int iDigit = bAdd ? iOriginal + iDelta + iCarry : iOriginal - iDelta - iCarry;
|
||||
iCarry = bAdd ? iDigit / 10 : (iDigit < 0 ? 1 : 0);
|
||||
if (iDigit < 0) {
|
||||
iDigit += 10;
|
||||
}
|
||||
baReversed.append(static_cast<char>('0' + iDigit % 10));
|
||||
}
|
||||
std::reverse(baReversed.begin(), baReversed.end());
|
||||
baResult = trimLeadingZeros(baReversed);
|
||||
if (nDecimals > 0) {
|
||||
if (baResult.size() <= nDecimals) {
|
||||
baResult.prepend(QByteArray(nDecimals + 1 - baResult.size(), '0'));
|
||||
}
|
||||
baResult.insert(baResult.size() - nDecimals, '.');
|
||||
while (baResult.endsWith('0')) {
|
||||
baResult.chop(1);
|
||||
}
|
||||
if (baResult.endsWith('.')) {
|
||||
baResult.chop(1);
|
||||
}
|
||||
}
|
||||
if (bNegative && baResult != "0") {
|
||||
baResult.prepend('-');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
|
||||
namespace {
|
||||
using Limits = ShapeGeometryLimits;
|
||||
|
||||
qreal rounded(qreal rValue)
|
||||
{
|
||||
return std::round(rValue * Limits::rCoordinateStepsPerCentimeter)
|
||||
/ Limits::rCoordinateStepsPerCentimeter;
|
||||
}
|
||||
|
||||
// Quantize an offset inward, keeping the original decimal coordinate as anchor.
|
||||
bool boundedOffset(qreal rRequested, qreal rLow, qreal rHigh, qreal &rResult)
|
||||
{
|
||||
const qreal rLowStep = std::isfinite(rLow)
|
||||
? std::ceil(rLow * Limits::rCoordinateStepsPerCentimeter) / Limits::rCoordinateStepsPerCentimeter : rLow;
|
||||
const qreal rHighStep = std::isfinite(rHigh)
|
||||
? std::floor(rHigh * Limits::rCoordinateStepsPerCentimeter) / Limits::rCoordinateStepsPerCentimeter : rHigh;
|
||||
if (rLowStep > rHighStep) return false;
|
||||
rResult = std::clamp(rounded(rRequested), rLowStep, rHighStep);
|
||||
return std::isfinite(rResult);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
GestureGeometry tkrEditService::prepareGeometry(const ElementRecord &element, const DragUpdate &drag,
|
||||
const tkrCoordinateMapper &mapper,
|
||||
const ComparisonExtent &extent,
|
||||
const tkrShapeProvider *pShapeProvider) const
|
||||
{
|
||||
GestureGeometry geometry{{true, {}}, element.ptFirstTikzPosition, element.ptSecondTikzPosition};
|
||||
const QPointF ptDelta = mapper.mapToTikz(drag.ptCurrentScenePosition)
|
||||
- mapper.mapToTikz(drag.ptInitialScenePosition);
|
||||
if (!std::isfinite(ptDelta.x()) || !std::isfinite(ptDelta.y())) {
|
||||
geometry.result = {false, QStringLiteral("Gesture displacement must be finite.")};
|
||||
return geometry;
|
||||
}
|
||||
if (element.elementKind == ElementKind::Rectangle) {
|
||||
const bool bResize = drag.dragKind == DragKind::RectangleFirstFirst
|
||||
|| drag.dragKind == DragKind::RectangleFirstSecond
|
||||
|| drag.dragKind == DragKind::RectangleSecondFirst
|
||||
|| drag.dragKind == DragKind::RectangleSecondSecond;
|
||||
if (!pShapeProvider || (!bResize && drag.dragKind != DragKind::WholeElement)) {
|
||||
geometry.result = {false, QStringLiteral("Rectangle provider or supported operation is unavailable.")};
|
||||
return geometry;
|
||||
}
|
||||
ShapeApi::OperationRequest request;
|
||||
request.initial = describeShape(element);
|
||||
request.documentId = element.documentId;
|
||||
request.uElementId = element.uElementId;
|
||||
request.uRevision = element.uDocumentRevision;
|
||||
request.strOperationId = bResize ? ShapeApi::strResizeOperation : ShapeApi::strMoveOperation;
|
||||
request.ptTotalDisplacementCentimeters = ptDelta;
|
||||
request.handleId = shapeHandle(drag.dragKind);
|
||||
request.constraints.bHasFixedBounds = extent.bIsPresent;
|
||||
request.constraints.rectBoundsCentimeters = QRectF(extent.ptFirstTikzPosition, extent.ptSecondTikzPosition).normalized();
|
||||
if (!pShapeProvider->availableOperations(request.initial).contains(request.strOperationId)) {
|
||||
geometry.result = {false, QStringLiteral("The rectangle provider does not support this operation.")};
|
||||
return geometry;
|
||||
}
|
||||
const ShapeApi::PreparationResult prepared = pShapeProvider->prepareOperation(request);
|
||||
const auto &proposed = prepared.proposed;
|
||||
const QRectF rectProposed = QRectF(proposed.ptFirstCentimeters, proposed.ptSecondCentimeters).normalized();
|
||||
constexpr qreal rValidationToleranceCentimeters = 0.000000001;
|
||||
const qreal rMargin = outlineMarginCentimeters(element);
|
||||
const QRectF rectAllowed = request.constraints.rectBoundsCentimeters.adjusted(rMargin, rMargin, -rMargin, -rMargin);
|
||||
const bool bSameDescription = proposed.documentId == request.documentId
|
||||
&& proposed.uElementId == request.uElementId && proposed.uRevision == request.uRevision
|
||||
&& proposed.strFamily == request.initial.strFamily && proposed.strType == request.initial.strType
|
||||
&& proposed.iSchemaVersion == request.initial.iSchemaVersion
|
||||
&& proposed.rLineWidthPoints == request.initial.rLineWidthPoints
|
||||
&& proposed.strStrokeColor == request.initial.strStrokeColor && proposed.strContent == request.initial.strContent;
|
||||
const bool bFinite = std::isfinite(rectProposed.left()) && std::isfinite(rectProposed.right())
|
||||
&& std::isfinite(rectProposed.top()) && std::isfinite(rectProposed.bottom())
|
||||
&& std::isfinite(rectProposed.width()) && std::isfinite(rectProposed.height());
|
||||
const bool bWithinBounds = !extent.bIsPresent || (rectAllowed.isValid() && rectAllowed.adjusted(-rValidationToleranceCentimeters,
|
||||
-rValidationToleranceCentimeters, rValidationToleranceCentimeters, rValidationToleranceCentimeters).contains(rectProposed));
|
||||
const bool bValidSize = rectProposed.width() > 0 && rectProposed.height() > 0
|
||||
&& (!bResize || (rectProposed.width() + rValidationToleranceCentimeters >= request.constraints.rMinimumWidthCentimeters
|
||||
&& rectProposed.height() + rValidationToleranceCentimeters >= request.constraints.rMinimumHeightCentimeters));
|
||||
const bool bChanged = proposed.ptFirstCentimeters != request.initial.ptFirstCentimeters
|
||||
|| proposed.ptSecondCentimeters != request.initial.ptSecondCentimeters;
|
||||
const bool bValidOutcome = (prepared.outcome == ShapeApi::PreparationOutcome::PreparedChange && bChanged)
|
||||
|| (prepared.outcome == ShapeApi::PreparationOutcome::Unchanged && !bChanged);
|
||||
const bool bFirstX = drag.dragKind == DragKind::RectangleFirstFirst || drag.dragKind == DragKind::RectangleFirstSecond;
|
||||
const bool bFirstY = drag.dragKind == DragKind::RectangleFirstFirst || drag.dragKind == DragKind::RectangleSecondFirst;
|
||||
const QPointF ptFirstOffset = proposed.ptFirstCentimeters - request.initial.ptFirstCentimeters;
|
||||
const QPointF ptSecondOffset = proposed.ptSecondCentimeters - request.initial.ptSecondCentimeters;
|
||||
const bool bPreservedOperation = bResize
|
||||
? (bFirstX ? proposed.ptSecondCentimeters.x() == request.initial.ptSecondCentimeters.x()
|
||||
: proposed.ptFirstCentimeters.x() == request.initial.ptFirstCentimeters.x())
|
||||
&& (bFirstY ? proposed.ptSecondCentimeters.y() == request.initial.ptSecondCentimeters.y()
|
||||
: proposed.ptFirstCentimeters.y() == request.initial.ptFirstCentimeters.y())
|
||||
: std::abs(ptFirstOffset.x() - ptSecondOffset.x()) <= rValidationToleranceCentimeters
|
||||
&& std::abs(ptFirstOffset.y() - ptSecondOffset.y()) <= rValidationToleranceCentimeters;
|
||||
if (prepared.outcome == ShapeApi::PreparationOutcome::CannotPrepare || !bSameDescription
|
||||
|| !bFinite || !bWithinBounds || !bValidSize || !bValidOutcome || !bPreservedOperation) {
|
||||
geometry.result = {false, prepared.strReason.isEmpty()
|
||||
? QStringLiteral("The provider proposal failed host validation.") : prepared.strReason};
|
||||
return geometry;
|
||||
}
|
||||
geometry.ptFirstTikzPosition = proposed.ptFirstCentimeters;
|
||||
geometry.ptSecondTikzPosition = proposed.ptSecondCentimeters;
|
||||
return geometry;
|
||||
}
|
||||
const qreal rInfinity = std::numeric_limits<qreal>::infinity();
|
||||
qreal rLeft = -rInfinity, rRight = rInfinity, rBottom = -rInfinity, rTop = rInfinity;
|
||||
if (extent.bIsPresent) {
|
||||
const QRectF rectExtent = QRectF(extent.ptFirstTikzPosition, extent.ptSecondTikzPosition).normalized();
|
||||
const qreal rMargin = outlineMarginCentimeters(element);
|
||||
rLeft = rectExtent.left() + rMargin;
|
||||
rRight = rectExtent.right() - rMargin;
|
||||
rBottom = rectExtent.top() + rMargin;
|
||||
rTop = rectExtent.bottom() - rMargin;
|
||||
}
|
||||
if (drag.dragKind == DragKind::WholeElement) {
|
||||
const QRectF rectElement = QRectF(element.ptFirstTikzPosition, element.ptSecondTikzPosition).normalized();
|
||||
qreal rX = 0, rY = 0;
|
||||
if (!boundedOffset(ptDelta.x(), rLeft - rectElement.left(), rRight - rectElement.right(), rX)
|
||||
|| !boundedOffset(ptDelta.y(), rBottom - rectElement.top(), rTop - rectElement.bottom(), rY)) {
|
||||
geometry.result = {false, QStringLiteral("No valid position inside the editing extent.")};
|
||||
return geometry;
|
||||
}
|
||||
geometry.ptFirstTikzPosition += QPointF(rX, rY);
|
||||
geometry.ptSecondTikzPosition += QPointF(rX, rY);
|
||||
return geometry;
|
||||
}
|
||||
geometry.result = {false, QStringLiteral("Unsupported edit handle.")};
|
||||
return geometry;
|
||||
}
|
||||
|
||||
OperationResult tkrEditService::prepareEdits(const ElementRecord &element, const QByteArray &baSource,
|
||||
const GestureGeometry &geometry,
|
||||
QVector<CoordinateEdit> &vecEdits) const
|
||||
{
|
||||
vecEdits.clear();
|
||||
if (!geometry.result.bSucceeded) return geometry.result;
|
||||
const SourceRange ranges[] = {element.rangeFirstX, element.rangeFirstY,
|
||||
element.rangeSecondX, element.rangeSecondY};
|
||||
const QPointF offsets[] = {geometry.ptFirstTikzPosition - element.ptFirstTikzPosition,
|
||||
geometry.ptSecondTikzPosition - element.ptSecondTikzPosition};
|
||||
constexpr int iCoordinatesPerPoint = 2;
|
||||
constexpr int iCoordinateCount = 4;
|
||||
for (int iCoordinate = 0; iCoordinate < iCoordinateCount; ++iCoordinate) {
|
||||
const QPointF &offset = offsets[iCoordinate / iCoordinatesPerPoint];
|
||||
const qreal rDelta = iCoordinate % iCoordinatesPerPoint == 0 ? offset.x() : offset.y();
|
||||
const QByteArray baDelta = QByteArray::number(rDelta, 'f', Limits::iCoordinateDecimals);
|
||||
if (baDelta.toDouble() == 0) continue;
|
||||
const SourceRange &range = ranges[iCoordinate];
|
||||
const QByteArray baOriginal = baSource.mid(range.nStart, range.nLength);
|
||||
QByteArray baReplacement;
|
||||
if (!translateCoordinate(baOriginal, baDelta, baReplacement)) {
|
||||
vecEdits.clear();
|
||||
return {false, QStringLiteral("A coordinate cannot be changed safely.")};
|
||||
}
|
||||
vecEdits.append({range, baOriginal, baReplacement, element.uDocumentRevision});
|
||||
}
|
||||
return {true, {}};
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/EditorTypes.h"
|
||||
#include "geometry/tkrCoordinateMapper.h"
|
||||
|
||||
namespace TikzRefinery {
|
||||
class tkrShapeProvider;
|
||||
|
||||
// Prepares geometry and source replacements. Never mutates a document or widget.
|
||||
class tkrEditService final
|
||||
{
|
||||
public:
|
||||
GestureGeometry prepareGeometry(const ElementRecord &element, const DragUpdate &drag,
|
||||
const tkrCoordinateMapper &mapper,
|
||||
const ComparisonExtent &extent,
|
||||
const tkrShapeProvider *pShapeProvider = nullptr) const;
|
||||
OperationResult prepareEdits(const ElementRecord &element, const QByteArray &baSource,
|
||||
const GestureGeometry &geometry,
|
||||
QVector<CoordinateEdit> &vecEdits) const;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/EditorTypes.h"
|
||||
#include "ShapeTypes.h"
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
// Shared with parsing: gesture bounds must include the same ink envelope.
|
||||
struct ShapeGeometryLimits
|
||||
{
|
||||
static constexpr qreal rMinimumRectangleCentimeters = ShapeApi::rMinimumRectangleCentimeters;
|
||||
static constexpr int iCoordinateDecimals = ShapeApi::iCoordinateDecimals;
|
||||
static constexpr qreal rCoordinateStepsPerCentimeter = ShapeApi::rCoordinateStepsPerCentimeter;
|
||||
static constexpr qreal rCentimetersPerInch = 2.54;
|
||||
static constexpr qreal rTexPointsPerInch = 72.27;
|
||||
static constexpr qreal rHalfStroke = 0.5;
|
||||
static constexpr qreal rArrowTipBasePoints = 0.28;
|
||||
static constexpr qreal rArrowTipWidthFactor = 0.3;
|
||||
static constexpr qreal rArrowTipSpanFactor = 4.0;
|
||||
static constexpr qreal rArrowStrokeFactor = 0.4;
|
||||
};
|
||||
|
||||
inline qreal outlineMarginCentimeters(const ElementRecord &element)
|
||||
{
|
||||
using Limits = ShapeGeometryLimits;
|
||||
const qreal rEnvelopePoints = element.elementKind == ElementKind::Arrow
|
||||
? Limits::rArrowTipSpanFactor * (Limits::rArrowTipBasePoints
|
||||
+ Limits::rArrowTipWidthFactor * element.rLineWidthPoints)
|
||||
+ Limits::rArrowStrokeFactor * element.rLineWidthPoints
|
||||
: Limits::rHalfStroke * element.rLineWidthPoints;
|
||||
return rEnvelopePoints * Limits::rCentimetersPerInch / Limits::rTexPointsPerInch;
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,31 @@
|
||||
#include "geometry/tkrCoordinateMapper.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
OperationResult tkrCoordinateMapper::configure(const QPointF &ptSceneOrigin,
|
||||
qreal rSceneUnitsPerCentimeter)
|
||||
{
|
||||
if (!std::isfinite(ptSceneOrigin.x()) || !std::isfinite(ptSceneOrigin.y())
|
||||
|| !std::isfinite(rSceneUnitsPerCentimeter) || rSceneUnitsPerCentimeter <= 0.0) {
|
||||
return {false, QStringLiteral("Coordinate mapping needs a finite origin and positive scale.")};
|
||||
}
|
||||
m_ptSceneOrigin = ptSceneOrigin;
|
||||
m_rSceneUnitsPerCentimeter = rSceneUnitsPerCentimeter;
|
||||
return {true, {}};
|
||||
}
|
||||
|
||||
QPointF tkrCoordinateMapper::mapToScene(const QPointF &ptTikzPosition) const
|
||||
{
|
||||
return QPointF(m_ptSceneOrigin.x() + m_rSceneUnitsPerCentimeter * ptTikzPosition.x(),
|
||||
m_ptSceneOrigin.y() - m_rSceneUnitsPerCentimeter * ptTikzPosition.y());
|
||||
}
|
||||
|
||||
QPointF tkrCoordinateMapper::mapToTikz(const QPointF &ptScenePosition) const
|
||||
{
|
||||
return QPointF((ptScenePosition.x() - m_ptSceneOrigin.x()) / m_rSceneUnitsPerCentimeter,
|
||||
(m_ptSceneOrigin.y() - ptScenePosition.y()) / m_rSceneUnitsPerCentimeter);
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/EditorTypes.h"
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
// Scene units are independent of viewport pixels, zoom and pan.
|
||||
class tkrCoordinateMapper final
|
||||
{
|
||||
public:
|
||||
OperationResult configure(const QPointF &ptSceneOrigin, qreal rSceneUnitsPerCentimeter);
|
||||
QPointF mapToScene(const QPointF &ptTikzPosition) const;
|
||||
QPointF mapToTikz(const QPointF &ptScenePosition) const;
|
||||
|
||||
private:
|
||||
QPointF m_ptSceneOrigin = QPointF(200.0, 300.0);
|
||||
qreal m_rSceneUnitsPerCentimeter = 100.0;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,18 @@
|
||||
#include "ui/tkrMainWindow.h"
|
||||
#include "BuildInfo.h"
|
||||
|
||||
#include <QApplication>
|
||||
#include <QCoreApplication>
|
||||
#include <QString>
|
||||
|
||||
int main(int iArgumentCount, char *pArguments[])
|
||||
{
|
||||
QApplication application(iArgumentCount, pArguments);
|
||||
QCoreApplication::setApplicationName(QStringLiteral("TikZRefinery"));
|
||||
QCoreApplication::setApplicationVersion(QString::fromLatin1(TikzRefinery::BuildInfo::pVersion));
|
||||
QCoreApplication::setOrganizationName(QStringLiteral("TikZRefinery"));
|
||||
QApplication::setQuitOnLastWindowClosed(true);
|
||||
TikzRefinery::tkrMainWindow mainWindow(nullptr, application.arguments().value(1));
|
||||
mainWindow.show();
|
||||
return application.exec();
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
#pragma once
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QMetaType>
|
||||
#include <QPointF>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QVector>
|
||||
#include <QUuid>
|
||||
#include <QtGlobal>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
enum class ElementKind { Line, Arrow, Rectangle };
|
||||
enum class DragKind {
|
||||
WholeElement, FirstEndpoint, SecondEndpoint,
|
||||
RectangleFirstFirst, RectangleFirstSecond, RectangleSecondFirst, RectangleSecondSecond
|
||||
};
|
||||
|
||||
// Byte offsets into the document's original/current QByteArray, never QString indices.
|
||||
struct SourceRange
|
||||
{
|
||||
qsizetype nStart = 0;
|
||||
qsizetype nLength = 0;
|
||||
};
|
||||
|
||||
struct ElementRecord
|
||||
{
|
||||
quint64 uElementId = 0; // Valid only within uDocumentRevision.
|
||||
quint64 uDocumentRevision = 0;
|
||||
ElementKind elementKind = ElementKind::Line;
|
||||
QPointF ptFirstTikzPosition;
|
||||
QPointF ptSecondTikzPosition;
|
||||
SourceRange rangeFirstX;
|
||||
SourceRange rangeFirstY;
|
||||
SourceRange rangeSecondX;
|
||||
SourceRange rangeSecondY;
|
||||
bool bArrowAtStart = false;
|
||||
bool bArrowAtEnd = false;
|
||||
qreal rLineWidthPoints = 0.4;
|
||||
QUuid documentId; // Assigned by the document, outside the syntax parser.
|
||||
};
|
||||
|
||||
// Calibration data only; never assigned an element ID or coordinate edit ranges.
|
||||
struct ComparisonExtent
|
||||
{
|
||||
bool bIsPresent = false;
|
||||
QPointF ptFirstTikzPosition;
|
||||
QPointF ptSecondTikzPosition;
|
||||
};
|
||||
|
||||
struct ParseResult
|
||||
{
|
||||
bool bSafeToEdit = false;
|
||||
QVector<ElementRecord> vecElements;
|
||||
ComparisonExtent comparisonExtent;
|
||||
QStringList listDiagnostics;
|
||||
};
|
||||
|
||||
struct DragUpdate
|
||||
{
|
||||
quint64 uElementId = 0;
|
||||
quint64 uDocumentRevision = 0;
|
||||
DragKind dragKind = DragKind::WholeElement;
|
||||
QPointF ptInitialScenePosition;
|
||||
QPointF ptCurrentScenePosition;
|
||||
};
|
||||
|
||||
struct CoordinateEdit
|
||||
{
|
||||
SourceRange rangeSource;
|
||||
QByteArray baExpectedText;
|
||||
QByteArray baReplacementText;
|
||||
quint64 uDocumentRevision = 0;
|
||||
};
|
||||
|
||||
struct OperationResult
|
||||
{
|
||||
bool bSucceeded = false;
|
||||
QString strMessage;
|
||||
};
|
||||
|
||||
struct GestureGeometry
|
||||
{
|
||||
OperationResult result;
|
||||
QPointF ptFirstTikzPosition;
|
||||
QPointF ptSecondTikzPosition;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
|
||||
Q_DECLARE_METATYPE(TikzRefinery::DragUpdate)
|
||||
@@ -0,0 +1,136 @@
|
||||
#include "model/tkrTikzDocument.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <new>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
void tkrTikzDocument::loadSource(const QByteArray &baSource, const QString &strFilePath)
|
||||
{
|
||||
m_baSource = baSource;
|
||||
m_baSavedSource = baSource;
|
||||
m_strFilePath = strFilePath;
|
||||
QVector<ElementRecord>().swap(m_vecElements);
|
||||
m_history.clear();
|
||||
m_documentId = QUuid::createUuid();
|
||||
++m_uRevision; // Opening another file also invalidates old edits.
|
||||
m_bIsLoaded = true;
|
||||
}
|
||||
|
||||
const QByteArray &tkrTikzDocument::sourceBytes() const { return m_baSource; }
|
||||
const QString &tkrTikzDocument::filePath() const { return m_strFilePath; }
|
||||
const QVector<ElementRecord> &tkrTikzDocument::elements() const { return m_vecElements; }
|
||||
quint64 tkrTikzDocument::revision() const { return m_uRevision; }
|
||||
const QUuid &tkrTikzDocument::identity() const { return m_documentId; }
|
||||
bool tkrTikzDocument::isLoaded() const { return m_bIsLoaded; }
|
||||
bool tkrTikzDocument::hasUnsavedChanges() const { return m_baSource != m_baSavedSource; }
|
||||
void tkrTikzDocument::markSaved() { m_baSavedSource = m_baSource; }
|
||||
|
||||
OperationResult tkrTikzDocument::setParsedElements(const QVector<ElementRecord> &vecElements,
|
||||
quint64 uExpectedRevision)
|
||||
{
|
||||
if (!m_bIsLoaded || uExpectedRevision != m_uRevision) {
|
||||
return {false, QStringLiteral("Parsed elements belong to an outdated document.")};
|
||||
}
|
||||
for (const ElementRecord &elementRecord : vecElements) {
|
||||
if (elementRecord.uDocumentRevision != m_uRevision) {
|
||||
return {false, QStringLiteral("An element belongs to an outdated document.")};
|
||||
}
|
||||
}
|
||||
m_vecElements = vecElements;
|
||||
for (ElementRecord &element : m_vecElements) element.documentId = m_documentId;
|
||||
return {true, {}};
|
||||
}
|
||||
|
||||
OperationResult tkrTikzDocument::applyCoordinateEdits(const QVector<CoordinateEdit> &vecEdits,
|
||||
const QString &strDescription) try
|
||||
{
|
||||
if (!m_bIsLoaded) {
|
||||
return {false, QStringLiteral("No document is open.")};
|
||||
}
|
||||
QVector<CoordinateEdit> vecSortedEdits = vecEdits;
|
||||
std::sort(vecSortedEdits.begin(), vecSortedEdits.end(),
|
||||
[](const CoordinateEdit &editLeft, const CoordinateEdit &editRight) {
|
||||
return editLeft.rangeSource.nStart < editRight.rangeSource.nStart;
|
||||
});
|
||||
|
||||
qsizetype nPreviousEnd = 0;
|
||||
for (const CoordinateEdit &coordinateEdit : vecSortedEdits) {
|
||||
const SourceRange &rangeSource = coordinateEdit.rangeSource;
|
||||
if (coordinateEdit.uDocumentRevision != m_uRevision) {
|
||||
return {false, QStringLiteral("The document changed after this edit was prepared.")};
|
||||
}
|
||||
// Subtract only after validating the start, avoiding integer overflow.
|
||||
if (rangeSource.nStart < 0 || rangeSource.nLength <= 0
|
||||
|| rangeSource.nStart > m_baSource.size()
|
||||
|| rangeSource.nLength > m_baSource.size() - rangeSource.nStart) {
|
||||
return {false, QStringLiteral("A coordinate source range is invalid.")};
|
||||
}
|
||||
if (rangeSource.nStart < nPreviousEnd) {
|
||||
return {false, QStringLiteral("Coordinate replacement ranges overlap.")};
|
||||
}
|
||||
if (m_baSource.mid(rangeSource.nStart, rangeSource.nLength)
|
||||
!= coordinateEdit.baExpectedText) {
|
||||
return {false, QStringLiteral("The expected coordinate text no longer matches.")};
|
||||
}
|
||||
nPreviousEnd = rangeSource.nStart + rangeSource.nLength;
|
||||
}
|
||||
|
||||
// Validate the complete batch first, then replace backwards to preserve offsets.
|
||||
QByteArray baUpdatedSource = m_baSource;
|
||||
for (auto iterEdit = vecSortedEdits.crbegin(); iterEdit != vecSortedEdits.crend(); ++iterEdit) {
|
||||
baUpdatedSource.replace(iterEdit->rangeSource.nStart, iterEdit->rangeSource.nLength,
|
||||
iterEdit->baReplacementText);
|
||||
}
|
||||
if (baUpdatedSource != m_baSource) {
|
||||
m_history.record(m_baSource, baUpdatedSource, strDescription);
|
||||
// From here, publication consists only of non-allocating changes.
|
||||
m_baSource.swap(baUpdatedSource);
|
||||
// Qt clear() may allocate on a shared container; an empty swap cannot.
|
||||
QVector<ElementRecord>().swap(m_vecElements); // Reparse before another edit.
|
||||
++m_uRevision;
|
||||
}
|
||||
return {true, {}};
|
||||
}
|
||||
catch (const std::bad_alloc &)
|
||||
{
|
||||
return {false, QStringLiteral("Insufficient memory to record this edit. Source unchanged.")};
|
||||
}
|
||||
|
||||
bool tkrTikzDocument::canUndo() const { return m_history.canUndo(); }
|
||||
OperationResult tkrTikzDocument::acceptPreparedState(tkrTikzDocument &documentCandidate,
|
||||
quint64 uExpectedRevision)
|
||||
{
|
||||
constexpr quint64 uRevisionStep = 1;
|
||||
if (m_uRevision != uExpectedRevision || documentCandidate.m_documentId != m_documentId
|
||||
|| documentCandidate.m_uRevision != m_uRevision + uRevisionStep) {
|
||||
return {false, QStringLiteral("The document changed during preparation.")};
|
||||
}
|
||||
// Source, parsed records and history were all prepared before publication.
|
||||
m_baSource.swap(documentCandidate.m_baSource);
|
||||
m_vecElements.swap(documentCandidate.m_vecElements);
|
||||
m_history.swap(documentCandidate.m_history);
|
||||
m_uRevision = documentCandidate.m_uRevision;
|
||||
return {true, {}};
|
||||
}
|
||||
bool tkrTikzDocument::canRedo() const { return m_history.canRedo(); }
|
||||
QString tkrTikzDocument::undoDescription() const { return m_history.undoDescription(); }
|
||||
QString tkrTikzDocument::redoDescription() const { return m_history.redoDescription(); }
|
||||
OperationResult tkrTikzDocument::restoreHistory(bool bRedo) try
|
||||
{
|
||||
if (bRedo ? !canRedo() : !canUndo()) {
|
||||
return {false, QStringLiteral("No history entry is available.")};
|
||||
}
|
||||
QByteArray baRestored = m_history.restorationSource(bRedo);
|
||||
m_baSource.swap(baRestored);
|
||||
m_history.advance(bRedo);
|
||||
QVector<ElementRecord>().swap(m_vecElements);
|
||||
++m_uRevision; // Revisions are fresh even when earlier bytes return.
|
||||
return {true, {}};
|
||||
}
|
||||
catch (const std::bad_alloc &)
|
||||
{
|
||||
return {false, QStringLiteral("Insufficient memory to restore history. Source unchanged.")};
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/EditorTypes.h"
|
||||
#include "editing/tkrEditHistory.h"
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
// Owns source bytes and parsed data. No widgets, filesystem access, or compiler.
|
||||
class tkrTikzDocument final
|
||||
{
|
||||
friend class tkrEditorController;
|
||||
public:
|
||||
void loadSource(const QByteArray &baSource, const QString &strFilePath);
|
||||
const QByteArray &sourceBytes() const;
|
||||
const QString &filePath() const;
|
||||
const QVector<ElementRecord> &elements() const;
|
||||
quint64 revision() const;
|
||||
const QUuid &identity() const;
|
||||
bool isLoaded() const;
|
||||
bool hasUnsavedChanges() const;
|
||||
void markSaved();
|
||||
|
||||
OperationResult setParsedElements(const QVector<ElementRecord> &vecElements,
|
||||
quint64 uExpectedRevision);
|
||||
OperationResult applyCoordinateEdits(const QVector<CoordinateEdit> &vecEdits,
|
||||
const QString &strDescription = QStringLiteral("Edit coordinates"));
|
||||
bool canUndo() const;
|
||||
bool canRedo() const;
|
||||
QString undoDescription() const;
|
||||
QString redoDescription() const;
|
||||
OperationResult restoreHistory(bool bRedo);
|
||||
|
||||
private:
|
||||
OperationResult acceptPreparedState(tkrTikzDocument &documentCandidate, quint64 uExpectedRevision);
|
||||
QByteArray m_baSource;
|
||||
QByteArray m_baSavedSource;
|
||||
QString m_strFilePath;
|
||||
QVector<ElementRecord> m_vecElements;
|
||||
quint64 m_uRevision = 0;
|
||||
bool m_bIsLoaded = false;
|
||||
QUuid m_documentId;
|
||||
tkrEditHistory m_history;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,215 @@
|
||||
#include "geometry/ShapeGeometryLimits.h"
|
||||
#include "parsing/tkrTikzParserExplicit.h"
|
||||
|
||||
#include <QRegularExpression>
|
||||
#include <QRectF>
|
||||
#include <cmath>
|
||||
|
||||
namespace TikzRefinery {
|
||||
namespace {
|
||||
|
||||
ParseResult rejectSource(const QString &strReason, qsizetype nByteOffset = 0)
|
||||
{
|
||||
ParseResult parseResult;
|
||||
parseResult.listDiagnostics.append(
|
||||
QStringLiteral("Diagram display unavailable at byte %1: %2 Source was preserved.")
|
||||
.arg(nByteOffset).arg(strReason));
|
||||
return parseResult; // Never return a misleading partial diagram.
|
||||
}
|
||||
|
||||
bool parseAppearance(const QString &strOptions, qreal &rLineWidthPoints,
|
||||
bool &bArrowAtStart, bool &bArrowAtEnd)
|
||||
{
|
||||
if (strOptions.isNull()) {
|
||||
return true;
|
||||
}
|
||||
// No style lookup, transformations, fills, or executable TeX options.
|
||||
const QRegularExpression expressionWidth(
|
||||
QStringLiteral(R"(^line\s+width\s*=\s*((?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+))\s*pt$)"));
|
||||
bool bWidthSeen = false;
|
||||
bool bArrowSeen = false;
|
||||
const QStringList listOptions = strOptions.split(QLatin1Char(','));
|
||||
for (const QString &strOption : listOptions) {
|
||||
const QString strTrimmed = strOption.trimmed();
|
||||
if (strTrimmed == QStringLiteral("black") || strTrimmed == QStringLiteral("solid")) {
|
||||
continue;
|
||||
}
|
||||
if (strTrimmed == QStringLiteral("->") || strTrimmed == QStringLiteral("<-")
|
||||
|| strTrimmed == QStringLiteral("<->")) {
|
||||
if (bArrowSeen) {
|
||||
return false;
|
||||
}
|
||||
bArrowAtStart = strTrimmed.startsWith(QLatin1Char('<'));
|
||||
bArrowAtEnd = strTrimmed.endsWith(QLatin1Char('>'));
|
||||
bArrowSeen = true;
|
||||
continue;
|
||||
}
|
||||
const QRegularExpressionMatch matchWidth = expressionWidth.match(strTrimmed);
|
||||
if (!matchWidth.hasMatch() || bWidthSeen) {
|
||||
return false;
|
||||
}
|
||||
bool bConverted = false;
|
||||
rLineWidthPoints = matchWidth.captured(1).toDouble(&bConverted);
|
||||
if (!bConverted || !std::isfinite(rLineWidthPoints) || rLineWidthPoints <= 0.0) {
|
||||
return false;
|
||||
}
|
||||
bWidthSeen = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ParseResult tkrTikzParserExplicit::parse(const QByteArray &baSource,
|
||||
quint64 uDocumentRevision) const
|
||||
{
|
||||
// One Latin-1 code unit per byte, including UTF-8 comments. Mask rather than
|
||||
// delete comments so regex captures remain offsets in the original QByteArray.
|
||||
QByteArray baMasked = baSource;
|
||||
if (baMasked.startsWith(QByteArray::fromHex("efbbbf"))) {
|
||||
baMasked.replace(0, 3, " ");
|
||||
}
|
||||
bool bInComment = false;
|
||||
for (qsizetype nByte = 0; nByte < baMasked.size(); ++nByte) {
|
||||
const char chByte = baMasked.at(nByte);
|
||||
if (chByte == '\r' || chByte == '\n') {
|
||||
bInComment = false;
|
||||
} else if (bInComment || chByte == '%') {
|
||||
// Escaped percent is deliberately unsupported by the grammar below.
|
||||
bInComment = true;
|
||||
baMasked[nByte] = ' ';
|
||||
}
|
||||
}
|
||||
const QString strSource = QString::fromLatin1(baMasked);
|
||||
for (qsizetype nByte = 0; nByte < baMasked.size(); ++nByte) {
|
||||
const unsigned char chByte = static_cast<unsigned char>(baMasked.at(nByte));
|
||||
if ((chByte < 32 && chByte != '\t' && chByte != '\r' && chByte != '\n') || chByte > 126) {
|
||||
return rejectSource(QStringLiteral("unsupported non-ASCII source outside comments."), nByte);
|
||||
}
|
||||
}
|
||||
QString strBody = strSource;
|
||||
qsizetype nBodyOffset = 0;
|
||||
// Recognize the corpus wrapper as a whole. Never search for draw commands
|
||||
// inside arbitrary TeX (macros, loops, scopes, or altered catcodes/units).
|
||||
const QRegularExpression expressionDocument(QStringLiteral(
|
||||
R"(\A\s*\\documentclass\s*\{article\}\s*\\usepackage\s*\{tikz\}\s*\\pagestyle\s*\{empty\}\s*\\begin\s*\{document\}\s*(?:\\noindent\s*)?\\begin\s*\{tikzpicture\}([\s\S]*)\\end\s*\{tikzpicture\}\s*\\end\s*\{document\}\s*\z)"));
|
||||
const QRegularExpression expressionPicture(QStringLiteral(
|
||||
R"(\A\s*\\begin\s*\{tikzpicture\}([\s\S]*)\\end\s*\{tikzpicture\}\s*\z)"));
|
||||
QRegularExpressionMatch matchEnvelope = expressionDocument.match(strSource);
|
||||
if (!matchEnvelope.hasMatch()) {
|
||||
matchEnvelope = expressionPicture.match(strSource);
|
||||
}
|
||||
if (matchEnvelope.hasMatch()) {
|
||||
strBody = matchEnvelope.captured(1);
|
||||
nBodyOffset = matchEnvelope.capturedStart(1);
|
||||
}
|
||||
|
||||
const QString strNumber = QStringLiteral(R"(([+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)))");
|
||||
const QString strPoint = QStringLiteral(R"(\(\s*)") + strNumber
|
||||
+ QStringLiteral(R"(\s*cm\s*,\s*)") + strNumber + QStringLiteral(R"(\s*cm\s*\))");
|
||||
const QString strCorners = strPoint + QStringLiteral(R"(\s*(rectangle|--)\s*)")
|
||||
+ strPoint + QStringLiteral(R"(\s*;)");
|
||||
const QRegularExpression expressionDraw(
|
||||
QStringLiteral(R"(\\draw\s*(?:\[([^\[\]]*)\]\s*)?)") + strCorners);
|
||||
const QRegularExpression expressionExtent(
|
||||
QStringLiteral(R"(\\path\s*\[\s*use\s+as\s+bounding\s+box\s*\]\s*)")
|
||||
+ strPoint + QStringLiteral(R"(\s*rectangle\s*)") + strPoint + QStringLiteral(R"(\s*;)"));
|
||||
|
||||
ParseResult parseResult;
|
||||
qsizetype nPosition = 0;
|
||||
while (nPosition < strBody.size()) {
|
||||
const QChar chCurrent = strBody.at(nPosition);
|
||||
if (chCurrent == QLatin1Char(' ') || chCurrent == QLatin1Char('\t')
|
||||
|| chCurrent == QLatin1Char('\r') || chCurrent == QLatin1Char('\n')) {
|
||||
++nPosition;
|
||||
continue;
|
||||
}
|
||||
const QRegularExpressionMatch matchDraw = expressionDraw.match(
|
||||
strBody, nPosition, QRegularExpression::NormalMatch,
|
||||
QRegularExpression::AnchorAtOffsetMatchOption);
|
||||
const bool bIsDraw = matchDraw.hasMatch();
|
||||
const QRegularExpressionMatch matchCommand = bIsDraw ? matchDraw : expressionExtent.match(
|
||||
strBody, nPosition, QRegularExpression::NormalMatch,
|
||||
QRegularExpression::AnchorAtOffsetMatchOption);
|
||||
if (!matchCommand.hasMatch()) {
|
||||
return rejectSource(QStringLiteral("unsupported syntax or wrapper; expected an absolute cm rectangle or straight segment."),
|
||||
nBodyOffset + nPosition);
|
||||
}
|
||||
qreal rLineWidthPoints = 0.4;
|
||||
bool bArrowAtStart = false;
|
||||
bool bArrowAtEnd = false;
|
||||
if (bIsDraw && !parseAppearance(matchCommand.captured(1), rLineWidthPoints,
|
||||
bArrowAtStart, bArrowAtEnd)) {
|
||||
return rejectSource(QStringLiteral("unsupported appearance options."), nBodyOffset + nPosition);
|
||||
}
|
||||
const bool bIsRectangle = !bIsDraw || matchCommand.captured(4) == QStringLiteral("rectangle");
|
||||
const int iFirstCoordinate = bIsDraw ? 2 : 1;
|
||||
qreal rCoordinates[4];
|
||||
SourceRange rangesCoordinates[4];
|
||||
for (int iCoordinate = 0; iCoordinate < 4; ++iCoordinate) {
|
||||
const int iCapture = iFirstCoordinate + iCoordinate + (bIsDraw && iCoordinate >= 2 ? 1 : 0);
|
||||
bool bConverted = false;
|
||||
rCoordinates[iCoordinate] = matchCommand.captured(iCapture).toDouble(&bConverted);
|
||||
if (!bConverted || !std::isfinite(rCoordinates[iCoordinate])) {
|
||||
return rejectSource(QStringLiteral("coordinate is not finite."), nBodyOffset + nPosition);
|
||||
}
|
||||
rangesCoordinates[iCoordinate] = {nBodyOffset + matchCommand.capturedStart(iCapture),
|
||||
matchCommand.capturedLength(iCapture)};
|
||||
}
|
||||
const QPointF ptFirst(rCoordinates[0], rCoordinates[1]);
|
||||
const QPointF ptSecond(rCoordinates[2], rCoordinates[3]);
|
||||
if ((bIsRectangle && (ptFirst.x() == ptSecond.x() || ptFirst.y() == ptSecond.y()))
|
||||
|| (!bIsRectangle && ptFirst == ptSecond)) {
|
||||
return rejectSource(QStringLiteral("degenerate geometry."), nBodyOffset + nPosition);
|
||||
}
|
||||
if (bIsRectangle && (bArrowAtStart || bArrowAtEnd)) {
|
||||
return rejectSource(QStringLiteral("arrow options require a straight segment."), nBodyOffset + nPosition);
|
||||
}
|
||||
if (bIsDraw) {
|
||||
ElementRecord elementRecord;
|
||||
elementRecord.uElementId = static_cast<quint64>(parseResult.vecElements.size()) + 1;
|
||||
elementRecord.uDocumentRevision = uDocumentRevision;
|
||||
elementRecord.elementKind = bIsRectangle ? ElementKind::Rectangle
|
||||
: (bArrowAtStart || bArrowAtEnd ? ElementKind::Arrow : ElementKind::Line);
|
||||
elementRecord.bArrowAtStart = bArrowAtStart;
|
||||
elementRecord.bArrowAtEnd = bArrowAtEnd;
|
||||
elementRecord.ptFirstTikzPosition = ptFirst;
|
||||
elementRecord.ptSecondTikzPosition = ptSecond;
|
||||
elementRecord.rangeFirstX = rangesCoordinates[0];
|
||||
elementRecord.rangeFirstY = rangesCoordinates[1];
|
||||
elementRecord.rangeSecondX = rangesCoordinates[2];
|
||||
elementRecord.rangeSecondY = rangesCoordinates[3];
|
||||
elementRecord.rLineWidthPoints = rLineWidthPoints;
|
||||
parseResult.vecElements.append(elementRecord);
|
||||
} else {
|
||||
if (parseResult.comparisonExtent.bIsPresent || !parseResult.vecElements.isEmpty()) {
|
||||
return rejectSource(QStringLiteral("comparison extent must occur once, before drawing."),
|
||||
nBodyOffset + nPosition);
|
||||
}
|
||||
parseResult.comparisonExtent = {true, ptFirst, ptSecond};
|
||||
}
|
||||
nPosition = matchCommand.capturedEnd();
|
||||
}
|
||||
if (parseResult.vecElements.isEmpty()) {
|
||||
return rejectSource(QStringLiteral("no supported drawing elements found."));
|
||||
}
|
||||
if (parseResult.comparisonExtent.bIsPresent) {
|
||||
const QRectF rectExtent = QRectF(parseResult.comparisonExtent.ptFirstTikzPosition,
|
||||
parseResult.comparisonExtent.ptSecondTikzPosition).normalized();
|
||||
for (const ElementRecord &elementRecord : parseResult.vecElements) {
|
||||
// A conservative envelope also includes the default curved 'to' tip.
|
||||
const qreal rHalfStrokeCentimeters = outlineMarginCentimeters(elementRecord);
|
||||
const QRectF rectOutline = QRectF(elementRecord.ptFirstTikzPosition,
|
||||
elementRecord.ptSecondTikzPosition).normalized()
|
||||
.adjusted(-rHalfStrokeCentimeters, -rHalfStrokeCentimeters,
|
||||
rHalfStrokeCentimeters, rHalfStrokeCentimeters);
|
||||
if (!rectExtent.contains(rectOutline)) {
|
||||
return rejectSource(QStringLiteral("drawing exceeds the fixed comparison extent."));
|
||||
}
|
||||
}
|
||||
}
|
||||
parseResult.bSafeToEdit = true; // Safe source records; gestures are still unavailable.
|
||||
return parseResult;
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/EditorTypes.h"
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
// Conservative rectangle/straight-segment interpretation; offsets refer to source bytes.
|
||||
class tkrTikzParserExplicit final
|
||||
{
|
||||
public:
|
||||
ParseResult parse(const QByteArray &baSource, quint64 uDocumentRevision) const;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/EditorTypes.h"
|
||||
#include "ShapeTypes.h"
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
inline ShapeApi::ElementDescription describeShape(const ElementRecord &element)
|
||||
{
|
||||
ShapeApi::ElementDescription description;
|
||||
description.documentId = element.documentId;
|
||||
description.uElementId = element.uElementId;
|
||||
description.uRevision = element.uDocumentRevision;
|
||||
description.ptFirstCentimeters = element.ptFirstTikzPosition;
|
||||
description.ptSecondCentimeters = element.ptSecondTikzPosition;
|
||||
description.rLineWidthPoints = element.rLineWidthPoints;
|
||||
return description;
|
||||
}
|
||||
|
||||
inline ShapeApi::HandleId shapeHandle(DragKind dragKind)
|
||||
{
|
||||
switch (dragKind) {
|
||||
case DragKind::RectangleFirstFirst: return ShapeApi::HandleId::FirstFirst;
|
||||
case DragKind::RectangleFirstSecond: return ShapeApi::HandleId::FirstSecond;
|
||||
case DragKind::RectangleSecondFirst: return ShapeApi::HandleId::SecondFirst;
|
||||
default: return ShapeApi::HandleId::SecondSecond;
|
||||
}
|
||||
}
|
||||
|
||||
inline DragKind sceneHandle(ShapeApi::HandleId handleId)
|
||||
{
|
||||
switch (handleId) {
|
||||
case ShapeApi::HandleId::FirstFirst: return DragKind::RectangleFirstFirst;
|
||||
case ShapeApi::HandleId::FirstSecond: return DragKind::RectangleFirstSecond;
|
||||
case ShapeApi::HandleId::SecondFirst: return DragKind::RectangleSecondFirst;
|
||||
default: return DragKind::RectangleSecondSecond;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,55 @@
|
||||
#include "plugins/tkrShapePluginStore.h"
|
||||
#include "ShapeBuildContract.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDir>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
tkrShapePluginStore::tkrShapePluginStore(const QString &strModulePath)
|
||||
: m_loader(strModulePath.isEmpty()
|
||||
? QDir(QCoreApplication::applicationDirPath()).filePath(QStringLiteral("shape-plugins/tkr_rectangle"))
|
||||
: strModulePath)
|
||||
{
|
||||
const QJsonObject root = m_loader.metaData();
|
||||
const QJsonObject metadata = root.value(QStringLiteral("MetaData")).toObject();
|
||||
const QJsonArray operations = metadata.value(QStringLiteral("operations")).toArray();
|
||||
if (root.value(QStringLiteral("IID")).toString() != QString::fromLatin1(TKR_SHAPE_PROVIDER_IID)
|
||||
|| metadata.value(QStringLiteral("id")).toString() != QStringLiteral("org.tikzrefinery.rectangle")
|
||||
|| metadata.value(QStringLiteral("name")).toString().isEmpty()
|
||||
|| metadata.value(QStringLiteral("version")).toString().isEmpty()
|
||||
|| metadata.value(QStringLiteral("role")).toString() != QStringLiteral("shape")
|
||||
|| metadata.value(QStringLiteral("apiVersion")).toInt() != ShapeApi::iApiVersion
|
||||
|| metadata.value(QStringLiteral("shapeType")).toString() != ShapeApi::strRectangleType
|
||||
|| metadata.value(QStringLiteral("geometrySchemaVersion")).toInt() != ShapeApi::iRectangleSchemaVersion
|
||||
|| metadata.value(QStringLiteral("parameterSchemaVersion")).toInt() != ShapeApi::iParameterSchemaVersion
|
||||
|| metadata.value(QStringLiteral("buildKey")).toString() != QString::fromLatin1(ShapeBuildContract::pBuildKey)
|
||||
|| !operations.contains(ShapeApi::strMoveOperation) || !operations.contains(ShapeApi::strResizeOperation)) {
|
||||
m_result = {false, QStringLiteral("Rectangle plugin missing or incompatible (API, schema, operations or toolchain). %1")
|
||||
.arg(m_loader.fileName())};
|
||||
return;
|
||||
}
|
||||
m_pProvider = qobject_cast<tkrShapeProvider *>(m_loader.instance());
|
||||
if (!m_pProvider) {
|
||||
m_result = {false, QStringLiteral("Rectangle plugin could not load: %1").arg(m_loader.errorString())};
|
||||
return;
|
||||
}
|
||||
m_strName = metadata.value(QStringLiteral("name")).toString();
|
||||
m_strVersion = metadata.value(QStringLiteral("version")).toString();
|
||||
m_strRuntimeIdentity = QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
m_result = {true, QStringLiteral("Loaded %1 %2").arg(m_strName, m_strVersion)};
|
||||
}
|
||||
|
||||
const tkrShapeProvider *tkrShapePluginStore::provider() const { return m_pProvider; }
|
||||
const OperationResult &tkrShapePluginStore::loadResult() const { return m_result; }
|
||||
const QString &tkrShapePluginStore::runtimeIdentity() const { return m_strRuntimeIdentity; }
|
||||
QString tkrShapePluginStore::modulePath() const { return m_loader.fileName(); }
|
||||
QString tkrShapePluginStore::description() const
|
||||
{
|
||||
return m_result.bSucceeded ? QStringLiteral("%1 %2\n%3\nInstance: %4")
|
||||
.arg(m_strName, m_strVersion, modulePath(), m_strRuntimeIdentity) : m_result.strMessage;
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/EditorTypes.h"
|
||||
#include "tkrShapeProvider.h"
|
||||
#include <QPluginLoader>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
// Owns one immutable module binding for this initial extraction. No hot unloading.
|
||||
class tkrShapePluginStore final
|
||||
{
|
||||
public:
|
||||
explicit tkrShapePluginStore(const QString &strModulePath = {});
|
||||
const tkrShapeProvider *provider() const;
|
||||
const OperationResult &loadResult() const;
|
||||
const QString &runtimeIdentity() const;
|
||||
QString description() const;
|
||||
QString modulePath() const;
|
||||
private:
|
||||
QPluginLoader m_loader;
|
||||
const tkrShapeProvider *m_pProvider = nullptr; // Borrowed from the pinned loader.
|
||||
OperationResult m_result;
|
||||
QString m_strRuntimeIdentity;
|
||||
QString m_strName;
|
||||
QString m_strVersion;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,434 @@
|
||||
#include "ui/tkrDiagramScene.h"
|
||||
|
||||
#include "geometry/tkrCoordinateMapper.h"
|
||||
#include "geometry/ShapeGeometryLimits.h"
|
||||
#include "plugins/ShapeProviderAdapter.h"
|
||||
|
||||
#include <QGraphicsRectItem>
|
||||
#include <QGraphicsPathItem>
|
||||
#include <QPainterPathStroker>
|
||||
#include <QTransform>
|
||||
#include <QPen>
|
||||
#include <QPainter>
|
||||
#include <array>
|
||||
#include <limits>
|
||||
#include <QGraphicsSceneMouseEvent>
|
||||
#include <QGraphicsView>
|
||||
#include <QKeyEvent>
|
||||
#include <QFocusEvent>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace TikzRefinery {
|
||||
namespace {
|
||||
enum ItemDataKey { ElementId = 0, DocumentRevision = 1, Kind = 2, FirstScene = 3, SecondScene = 4,
|
||||
ShapeDescription = 5, Presentation = 6, ProviderInstance = 7 };
|
||||
constexpr qreal rDefaultSceneWidth = 700.0;
|
||||
constexpr qreal rDefaultSceneHeight = 500.0;
|
||||
constexpr int iSelectionRadiusPixels = 5;
|
||||
constexpr int iHandleRadiusPixels = 4;
|
||||
constexpr int iHandleHitRadiusPixels = 6;
|
||||
constexpr int iDiameterFactor = 2;
|
||||
// Installed PGF default 'to' tip coefficients, in units of its tip width.
|
||||
struct DefaultArrowTip {
|
||||
static constexpr qreal rInsetBasePoints = 0.21;
|
||||
static constexpr qreal rInsetWidthFactor = 0.625;
|
||||
static constexpr qreal rTailX = -3.0;
|
||||
static constexpr qreal rTailHalfHeight = 4.0;
|
||||
static constexpr qreal rControlTailX = -2.75;
|
||||
static constexpr qreal rControlTailY = 2.5;
|
||||
static constexpr qreal rControlHeadY = 0.25;
|
||||
static constexpr qreal rHeadX = 0.75;
|
||||
static constexpr qreal rStrokeFactor = 0.8;
|
||||
};
|
||||
|
||||
struct CornerHandle { QPointF ptScene; DragKind dragKind; };
|
||||
|
||||
QVector<CornerHandle> providerHandles(const QGraphicsItem *pItem, const tkrCoordinateMapper &mapper)
|
||||
{
|
||||
QVector<CornerHandle> vecHandles;
|
||||
const auto presentation = pItem->data(Presentation).value<ShapeApi::PresentationDescription>();
|
||||
for (const auto &handle : presentation.vecHandles)
|
||||
vecHandles.append({mapper.mapToScene(handle.ptPositionCentimeters) + pItem->pos(), sceneHandle(handle.handleId)});
|
||||
return vecHandles;
|
||||
}
|
||||
|
||||
QRectF sceneRectangle(const QRectF &rectCentimeters, const tkrCoordinateMapper &mapper)
|
||||
{
|
||||
return QRectF(mapper.mapToScene(rectCentimeters.topLeft()),
|
||||
mapper.mapToScene(rectCentimeters.bottomRight())).normalized();
|
||||
}
|
||||
|
||||
bool usablePresentation(const ShapeApi::PresentationDescription &presentation)
|
||||
{
|
||||
if (!presentation.bAvailable || presentation.strReadableDescription.isEmpty()
|
||||
|| !presentation.rectOutlineCentimeters.isValid() || !presentation.rectSelectionCentimeters.isValid()) return false;
|
||||
for (const auto &handle : presentation.vecHandles) {
|
||||
if (!std::isfinite(handle.ptPositionCentimeters.x()) || !std::isfinite(handle.ptPositionCentimeters.y())) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isFiniteRect(const QRectF &rectScene)
|
||||
{
|
||||
return std::isfinite(rectScene.left()) && std::isfinite(rectScene.top())
|
||||
&& std::isfinite(rectScene.right()) && std::isfinite(rectScene.bottom())
|
||||
&& std::isfinite(rectScene.width()) && std::isfinite(rectScene.height())
|
||||
&& rectScene.width() > 0.0 && rectScene.height() > 0.0;
|
||||
}
|
||||
|
||||
QPainterPath defaultArrowOutline(const QPointF &ptTipScene, const QPointF &ptDirection,
|
||||
qreal rLineWidthPoints, qreal rSceneUnitsPerPoint)
|
||||
{
|
||||
// PGF's default 'to' tip: dimensions and cubic control points from the
|
||||
// installed pgfcorearrows.code.tex (\pgfarrowsdeclare{to}{to}). Explicit
|
||||
// styles/tips are refused by the parser rather than silently approximated.
|
||||
const qreal rTipUnit = (ShapeGeometryLimits::rArrowTipBasePoints + ShapeGeometryLimits::rArrowTipWidthFactor * rLineWidthPoints) * rSceneUnitsPerPoint;
|
||||
const qreal rTipInset = (DefaultArrowTip::rInsetBasePoints + DefaultArrowTip::rInsetWidthFactor * rLineWidthPoints) * rSceneUnitsPerPoint;
|
||||
const QPointF ptArrowOrigin = ptTipScene - ptDirection * rTipInset;
|
||||
QPainterPath pathTip;
|
||||
pathTip.moveTo(DefaultArrowTip::rTailX * rTipUnit, DefaultArrowTip::rTailHalfHeight * rTipUnit);
|
||||
pathTip.cubicTo(DefaultArrowTip::rControlTailX * rTipUnit, DefaultArrowTip::rControlTailY * rTipUnit,
|
||||
0, DefaultArrowTip::rControlHeadY * rTipUnit, DefaultArrowTip::rHeadX * rTipUnit, 0);
|
||||
pathTip.cubicTo(0, -DefaultArrowTip::rControlHeadY * rTipUnit,
|
||||
DefaultArrowTip::rControlTailX * rTipUnit, -DefaultArrowTip::rControlTailY * rTipUnit,
|
||||
DefaultArrowTip::rTailX * rTipUnit, -DefaultArrowTip::rTailHalfHeight * rTipUnit);
|
||||
QPainterPathStroker strokerTip;
|
||||
strokerTip.setWidth(DefaultArrowTip::rStrokeFactor * rLineWidthPoints * rSceneUnitsPerPoint);
|
||||
strokerTip.setCapStyle(Qt::RoundCap);
|
||||
strokerTip.setJoinStyle(Qt::RoundJoin);
|
||||
const QTransform transformTip(ptDirection.x(), ptDirection.y(), -ptDirection.y(), ptDirection.x(),
|
||||
ptArrowOrigin.x(), ptArrowOrigin.y());
|
||||
return transformTip.map(strokerTip.createStroke(pathTip));
|
||||
}
|
||||
|
||||
QPainterPath segmentOutline(const ElementRecord &elementRecord, const QPointF &ptFirstScene,
|
||||
const QPointF &ptSecondScene, qreal rSceneUnitsPerPoint)
|
||||
{
|
||||
const QPointF ptDisplacement = ptSecondScene - ptFirstScene;
|
||||
const qreal rLength = std::hypot(ptDisplacement.x(), ptDisplacement.y());
|
||||
const qreal rTipInset = (DefaultArrowTip::rInsetBasePoints + DefaultArrowTip::rInsetWidthFactor * elementRecord.rLineWidthPoints) * rSceneUnitsPerPoint;
|
||||
const qreal rFirstInset = elementRecord.bArrowAtStart ? rTipInset : 0;
|
||||
const qreal rSecondInset = elementRecord.bArrowAtEnd ? rTipInset : 0;
|
||||
if (!std::isfinite(rLength) || rLength <= rFirstInset + rSecondInset) {
|
||||
return {}; // Overlapping short-arrow tips need a separate rendering contract.
|
||||
}
|
||||
const QPointF ptDirection = ptDisplacement / rLength;
|
||||
QPainterPath pathShaft;
|
||||
pathShaft.moveTo(ptFirstScene + ptDirection * rFirstInset);
|
||||
pathShaft.lineTo(ptSecondScene - ptDirection * rSecondInset);
|
||||
QPainterPathStroker strokerShaft;
|
||||
strokerShaft.setWidth(elementRecord.rLineWidthPoints * rSceneUnitsPerPoint);
|
||||
strokerShaft.setCapStyle(Qt::FlatCap); // TikZ's default butt line caps.
|
||||
QPainterPath pathOutline = strokerShaft.createStroke(pathShaft);
|
||||
if (elementRecord.bArrowAtStart) {
|
||||
pathOutline = pathOutline.united(defaultArrowOutline(ptFirstScene, -ptDirection,
|
||||
elementRecord.rLineWidthPoints, rSceneUnitsPerPoint));
|
||||
}
|
||||
if (elementRecord.bArrowAtEnd) {
|
||||
pathOutline = pathOutline.united(defaultArrowOutline(ptSecondScene, ptDirection,
|
||||
elementRecord.rLineWidthPoints, rSceneUnitsPerPoint));
|
||||
}
|
||||
return pathOutline;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
tkrDiagramScene::tkrDiagramScene(QObject *pParent, const QString &strRectangleModule)
|
||||
: QGraphicsScene(pParent), m_shapePlugins(strRectangleModule)
|
||||
{
|
||||
setSceneRect(0.0, 0.0, rDefaultSceneWidth, rDefaultSceneHeight);
|
||||
}
|
||||
|
||||
OperationResult tkrDiagramScene::displayElements(const QVector<ElementRecord> &vecElements,
|
||||
const tkrCoordinateMapper &coordinateMapper,
|
||||
const ComparisonExtent &comparisonExtent)
|
||||
{
|
||||
resetDiagram();
|
||||
m_mapper = coordinateMapper;
|
||||
const qreal rSceneUnitsPerCentimeter = coordinateMapper.mapToScene(QPointF(1.0, 0.0)).x()
|
||||
- coordinateMapper.mapToScene(QPointF()).x();
|
||||
// TeX points are 1/72.27 inch, rather than PDF's 1/72 inch.
|
||||
const qreal rSceneUnitsPerPoint = rSceneUnitsPerCentimeter * ShapeGeometryLimits::rCentimetersPerInch / ShapeGeometryLimits::rTexPointsPerInch;
|
||||
QVector<QPainterPath> vecSegmentOutlines;
|
||||
QVector<ShapeApi::PresentationDescription> vecPresentations;
|
||||
for (const ElementRecord &elementRecord : vecElements) {
|
||||
const QPointF ptFirstScene = coordinateMapper.mapToScene(elementRecord.ptFirstTikzPosition);
|
||||
const QPointF ptSecondScene = coordinateMapper.mapToScene(elementRecord.ptSecondTikzPosition);
|
||||
const QRectF rectScene = QRectF(ptFirstScene, ptSecondScene).normalized();
|
||||
const qreal rSceneLineWidth = elementRecord.rLineWidthPoints * rSceneUnitsPerPoint;
|
||||
if (!std::isfinite(ptFirstScene.x()) || !std::isfinite(ptFirstScene.y())
|
||||
|| !std::isfinite(ptSecondScene.x()) || !std::isfinite(ptSecondScene.y())
|
||||
|| !std::isfinite(rSceneLineWidth) || rSceneLineWidth <= 0.0
|
||||
|| (elementRecord.elementKind != ElementKind::Rectangle && elementRecord.elementKind != ElementKind::Line
|
||||
&& elementRecord.elementKind != ElementKind::Arrow)
|
||||
|| ((elementRecord.elementKind == ElementKind::Arrow)
|
||||
!= (elementRecord.bArrowAtStart || elementRecord.bArrowAtEnd))) {
|
||||
return {false, QStringLiteral("Diagram display received unsupported or invalid geometry.")};
|
||||
}
|
||||
QPainterPath pathOutline;
|
||||
ShapeApi::PresentationDescription presentation;
|
||||
if (elementRecord.elementKind == ElementKind::Rectangle) {
|
||||
if (!m_shapePlugins.provider()) return m_shapePlugins.loadResult();
|
||||
presentation = m_shapePlugins.provider()->describePresentation(describeShape(elementRecord));
|
||||
if (!isFiniteRect(rectScene) || !usablePresentation(presentation)
|
||||
|| !isFiniteRect(sceneRectangle(presentation.rectOutlineCentimeters, coordinateMapper))
|
||||
|| !isFiniteRect(sceneRectangle(presentation.rectSelectionCentimeters, coordinateMapper))) {
|
||||
return {false, QStringLiteral("Invalid provider presentation: %1").arg(presentation.strReason)};
|
||||
}
|
||||
} else {
|
||||
pathOutline = segmentOutline(elementRecord, ptFirstScene, ptSecondScene, rSceneUnitsPerPoint);
|
||||
if (pathOutline.isEmpty() || !isFiniteRect(pathOutline.boundingRect())) {
|
||||
return {false, QStringLiteral("Invalid segment or arrow too short for its tips.")};
|
||||
}
|
||||
}
|
||||
vecSegmentOutlines.append(pathOutline);
|
||||
vecPresentations.append(presentation);
|
||||
}
|
||||
QRectF rectComparison;
|
||||
if (comparisonExtent.bIsPresent) {
|
||||
rectComparison = QRectF(coordinateMapper.mapToScene(comparisonExtent.ptFirstTikzPosition),
|
||||
coordinateMapper.mapToScene(comparisonExtent.ptSecondTikzPosition)).normalized();
|
||||
if (!isFiniteRect(rectComparison)) {
|
||||
return {false, QStringLiteral("Invalid comparison extent.")};
|
||||
}
|
||||
}
|
||||
for (qsizetype nElement = 0; nElement < vecElements.size(); ++nElement) {
|
||||
const ElementRecord &elementRecord = vecElements.at(nElement);
|
||||
const ShapeApi::PresentationDescription &presentation = vecPresentations.at(nElement);
|
||||
QPen penOutline(Qt::black);
|
||||
penOutline.setWidthF(elementRecord.rLineWidthPoints * rSceneUnitsPerPoint);
|
||||
penOutline.setJoinStyle(Qt::MiterJoin);
|
||||
QGraphicsItem *pElement = elementRecord.elementKind == ElementKind::Rectangle
|
||||
? static_cast<QGraphicsItem *>(addRect(sceneRectangle(presentation.rectOutlineCentimeters, coordinateMapper), penOutline, QBrush(Qt::NoBrush)))
|
||||
: static_cast<QGraphicsItem *>(addPath(vecSegmentOutlines.at(nElement), QPen(Qt::NoPen), QBrush(Qt::black)));
|
||||
pElement->setData(ElementId, QVariant::fromValue(elementRecord.uElementId));
|
||||
pElement->setData(DocumentRevision, QVariant::fromValue(elementRecord.uDocumentRevision));
|
||||
pElement->setData(Kind, static_cast<int>(elementRecord.elementKind));
|
||||
pElement->setData(FirstScene, coordinateMapper.mapToScene(elementRecord.ptFirstTikzPosition));
|
||||
pElement->setData(SecondScene, coordinateMapper.mapToScene(elementRecord.ptSecondTikzPosition));
|
||||
if (presentation.bAvailable) {
|
||||
pElement->setData(ShapeDescription, QVariant::fromValue(describeShape(elementRecord)));
|
||||
pElement->setData(Presentation, QVariant::fromValue(presentation));
|
||||
pElement->setData(ProviderInstance, m_shapePlugins.runtimeIdentity());
|
||||
pElement->setToolTip(presentation.strReadableDescription);
|
||||
}
|
||||
// The scene controls movement; Qt's implicit ItemIsMovable is not used.
|
||||
pElement->setFlag(QGraphicsItem::ItemIsSelectable);
|
||||
}
|
||||
if (comparisonExtent.bIsPresent) {
|
||||
m_bFixedBounds = true;
|
||||
setSceneRect(rectComparison); // No graphics item for the calibration path.
|
||||
} else if (!vecElements.isEmpty()) {
|
||||
setSceneRect(sceneRect().united(itemsBoundingRect()));
|
||||
}
|
||||
return {true, {}};
|
||||
}
|
||||
|
||||
void tkrDiagramScene::resetDiagram()
|
||||
{
|
||||
m_bFixedBounds = false;
|
||||
m_bDragActive = false;
|
||||
m_dragUpdate = {};
|
||||
clear(); // QGraphicsScene deletes its owned graphics items.
|
||||
setSceneRect(0.0, 0.0, rDefaultSceneWidth, rDefaultSceneHeight);
|
||||
}
|
||||
|
||||
bool tkrDiagramScene::hasFixedBounds() const
|
||||
{
|
||||
return m_bFixedBounds;
|
||||
}
|
||||
|
||||
const tkrShapeProvider *tkrDiagramScene::shapeProvider() const { return m_shapePlugins.provider(); }
|
||||
QString tkrDiagramScene::pluginDescription() const { return m_shapePlugins.description(); }
|
||||
|
||||
OperationResult tkrDiagramScene::previewGeometry(quint64 uElementId, quint64 uDocumentRevision,
|
||||
const QPointF &ptFirstScene, const QPointF &ptSecondScene, bool bResize)
|
||||
{
|
||||
for (QGraphicsItem *pItem : items()) {
|
||||
if (pItem->data(ElementId).toULongLong() != uElementId
|
||||
|| pItem->data(DocumentRevision).toULongLong() != uDocumentRevision) continue;
|
||||
auto *pRectangle = qgraphicsitem_cast<QGraphicsRectItem *>(pItem);
|
||||
if (pRectangle && bResize && pItem->data(ShapeDescription).isValid()) {
|
||||
if (!shapeProvider() || pItem->data(ProviderInstance).toString() != m_shapePlugins.runtimeIdentity())
|
||||
return {false, QStringLiteral("The bound rectangle provider is unavailable.")};
|
||||
auto description = pItem->data(ShapeDescription).value<ShapeApi::ElementDescription>();
|
||||
description.ptFirstCentimeters = m_mapper.mapToTikz(ptFirstScene);
|
||||
description.ptSecondCentimeters = m_mapper.mapToTikz(ptSecondScene);
|
||||
const auto presentation = shapeProvider()->describePresentation(description);
|
||||
if (!usablePresentation(presentation)) return {false, presentation.strReason};
|
||||
pRectangle->setPos(QPointF());
|
||||
pRectangle->setRect(sceneRectangle(presentation.rectOutlineCentimeters, m_mapper));
|
||||
pRectangle->setData(FirstScene, ptFirstScene);
|
||||
pRectangle->setData(SecondScene, ptSecondScene);
|
||||
pRectangle->setData(ShapeDescription, QVariant::fromValue(description));
|
||||
pRectangle->setData(Presentation, QVariant::fromValue(presentation));
|
||||
} else {
|
||||
pItem->setPos(ptFirstScene - pItem->data(FirstScene).toPointF());
|
||||
}
|
||||
update(); // Includes old screen-sized handles outside the item's own bounds.
|
||||
return {true, {}};
|
||||
}
|
||||
return {false, QStringLiteral("The edited element is no longer available.")};
|
||||
}
|
||||
|
||||
void tkrDiagramScene::selectElement(quint64 uElementId)
|
||||
{
|
||||
clearSelection();
|
||||
for (QGraphicsItem *pItem : items()) {
|
||||
if (pItem->data(ElementId).toULongLong() == uElementId) pItem->setSelected(true);
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
void tkrDiagramScene::drawForeground(QPainter *pPainter, const QRectF &rectExposed)
|
||||
{
|
||||
QGraphicsScene::drawForeground(pPainter, rectExposed);
|
||||
pPainter->save();
|
||||
QPen penHandle(QColor(Qt::blue));
|
||||
penHandle.setCosmetic(true);
|
||||
pPainter->setPen(penHandle);
|
||||
pPainter->setBrush(Qt::white);
|
||||
const QTransform transformScene = pPainter->worldTransform();
|
||||
bool bInvertible = false;
|
||||
const QTransform transformInverse = transformScene.inverted(&bInvertible);
|
||||
if (bInvertible) {
|
||||
for (QGraphicsItem *pItem : selectedItems()) {
|
||||
if (!shapeProvider() || !pItem->data(ShapeDescription).isValid()
|
||||
|| !shapeProvider()->availableOperations(pItem->data(ShapeDescription).value<ShapeApi::ElementDescription>())
|
||||
.contains(ShapeApi::strResizeOperation)) continue;
|
||||
for (const CornerHandle &handle : providerHandles(pItem, m_mapper)) {
|
||||
const QPointF center = transformScene.map(handle.ptScene);
|
||||
const QRectF rectPixels(center - QPointF(iHandleRadiusPixels, iHandleRadiusPixels),
|
||||
QSizeF(iDiameterFactor * iHandleRadiusPixels, iDiameterFactor * iHandleRadiusPixels));
|
||||
pPainter->drawPolygon(transformInverse.map(QPolygonF(rectPixels)));
|
||||
}
|
||||
}
|
||||
}
|
||||
pPainter->restore();
|
||||
}
|
||||
|
||||
void tkrDiagramScene::cancelInteraction()
|
||||
{
|
||||
if (m_bDragActive) {
|
||||
m_bDragActive = false;
|
||||
m_dragUpdate = {};
|
||||
emit dragCancelled(); // Controller restores the authoritative geometry.
|
||||
}
|
||||
}
|
||||
|
||||
void tkrDiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *pEvent)
|
||||
{
|
||||
if (pEvent->button() != Qt::LeftButton) {
|
||||
QGraphicsScene::mousePressEvent(pEvent);
|
||||
return;
|
||||
}
|
||||
cancelInteraction();
|
||||
const QGraphicsView *pView = pEvent->widget()
|
||||
? qobject_cast<QGraphicsView *>(pEvent->widget()->parentWidget()) : nullptr;
|
||||
const auto toViewport = [pView](const QPointF &point) {
|
||||
return pView ? pView->viewportTransform().map(point) : point;
|
||||
};
|
||||
QGraphicsItem *pTarget = nullptr;
|
||||
DragKind dragKind = DragKind::WholeElement;
|
||||
qreal rClosest = std::numeric_limits<qreal>::infinity();
|
||||
for (QGraphicsItem *pItem : selectedItems()) {
|
||||
if (!shapeProvider() || !pItem->data(ShapeDescription).isValid()
|
||||
|| !shapeProvider()->availableOperations(pItem->data(ShapeDescription).value<ShapeApi::ElementDescription>())
|
||||
.contains(ShapeApi::strResizeOperation)) continue;
|
||||
for (const CornerHandle &handle : providerHandles(pItem, m_mapper)) {
|
||||
const QPointF ptOffset = toViewport(handle.ptScene) - toViewport(pEvent->scenePos());
|
||||
const qreal rDistance = std::hypot(ptOffset.x(), ptOffset.y());
|
||||
if (rDistance <= iHandleHitRadiusPixels && rDistance < rClosest) {
|
||||
pTarget = pItem;
|
||||
dragKind = handle.dragKind;
|
||||
rClosest = rDistance;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!pTarget) {
|
||||
clearSelection();
|
||||
QRectF rectHit(pEvent->scenePos() - QPointF(iSelectionRadiusPixels, iSelectionRadiusPixels),
|
||||
QSizeF(iDiameterFactor * iSelectionRadiusPixels, iDiameterFactor * iSelectionRadiusPixels));
|
||||
if (pView) {
|
||||
const QPoint ptViewport = pView->mapFromScene(pEvent->scenePos());
|
||||
rectHit = pView->mapToScene(QRect(ptViewport - QPoint(iSelectionRadiusPixels, iSelectionRadiusPixels),
|
||||
QSize(iDiameterFactor * iSelectionRadiusPixels, iDiameterFactor * iSelectionRadiusPixels))).boundingRect();
|
||||
}
|
||||
for (QGraphicsItem *pCandidate : items()) {
|
||||
if (pCandidate->data(Presentation).isValid()) {
|
||||
const auto presentation = pCandidate->data(Presentation).value<ShapeApi::PresentationDescription>();
|
||||
if (sceneRectangle(presentation.rectSelectionCentimeters, m_mapper).translated(pCandidate->pos()).intersects(rectHit)) {
|
||||
pTarget = pCandidate;
|
||||
break;
|
||||
}
|
||||
} else if (pCandidate->sceneTransform().map(pCandidate->shape()).intersects(rectHit)) {
|
||||
pTarget = pCandidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pTarget) {
|
||||
pTarget->setSelected(true);
|
||||
setFocus(Qt::MouseFocusReason);
|
||||
m_dragUpdate = {pTarget->data(ElementId).toULongLong(), pTarget->data(DocumentRevision).toULongLong(),
|
||||
dragKind, pEvent->scenePos(), pEvent->scenePos()};
|
||||
m_bDragActive = !pTarget->data(ShapeDescription).isValid()
|
||||
|| (shapeProvider() && shapeProvider()->availableOperations(
|
||||
pTarget->data(ShapeDescription).value<ShapeApi::ElementDescription>())
|
||||
.contains(dragKind == DragKind::WholeElement ? ShapeApi::strMoveOperation : ShapeApi::strResizeOperation));
|
||||
}
|
||||
update();
|
||||
pEvent->accept();
|
||||
}
|
||||
|
||||
void tkrDiagramScene::mouseMoveEvent(QGraphicsSceneMouseEvent *pEvent)
|
||||
{
|
||||
if (m_bDragActive) {
|
||||
if (!pEvent->buttons().testFlag(Qt::LeftButton)) {
|
||||
cancelInteraction();
|
||||
} else {
|
||||
m_dragUpdate.ptCurrentScenePosition = pEvent->scenePos();
|
||||
const DragUpdate dragUpdate = m_dragUpdate;
|
||||
emit dragPreviewRequested(dragUpdate);
|
||||
}
|
||||
pEvent->accept();
|
||||
return;
|
||||
}
|
||||
QGraphicsScene::mouseMoveEvent(pEvent);
|
||||
}
|
||||
|
||||
void tkrDiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *pEvent)
|
||||
{
|
||||
if (m_bDragActive && pEvent->button() == Qt::LeftButton) {
|
||||
m_dragUpdate.ptCurrentScenePosition = pEvent->scenePos();
|
||||
const DragUpdate dragUpdate = m_dragUpdate;
|
||||
// A synchronous commit reparses and deletes graphics items. Retain no
|
||||
// item pointers or active gesture state across that call.
|
||||
m_bDragActive = false;
|
||||
m_dragUpdate = {};
|
||||
emit dragCommitRequested(dragUpdate);
|
||||
pEvent->accept();
|
||||
return;
|
||||
}
|
||||
QGraphicsScene::mouseReleaseEvent(pEvent);
|
||||
}
|
||||
|
||||
void tkrDiagramScene::keyPressEvent(QKeyEvent *pEvent)
|
||||
{
|
||||
if (pEvent->key() == Qt::Key_Escape) {
|
||||
cancelInteraction();
|
||||
clearSelection();
|
||||
pEvent->accept();
|
||||
return;
|
||||
}
|
||||
QGraphicsScene::keyPressEvent(pEvent);
|
||||
}
|
||||
|
||||
void tkrDiagramScene::focusOutEvent(QFocusEvent *pEvent)
|
||||
{
|
||||
QGraphicsScene::focusOutEvent(pEvent);
|
||||
cancelInteraction();
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/EditorTypes.h"
|
||||
#include "geometry/tkrCoordinateMapper.h"
|
||||
#include "plugins/tkrShapePluginStore.h"
|
||||
|
||||
#include <QGraphicsScene>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
class tkrCoordinateMapper;
|
||||
|
||||
// Owns graphics items. Source bytes, file access and parsing stay outside the scene.
|
||||
class tkrDiagramScene final : public QGraphicsScene
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit tkrDiagramScene(QObject *pParent = nullptr, const QString &strRectangleModule = {});
|
||||
OperationResult displayElements(const QVector<ElementRecord> &vecElements,
|
||||
const tkrCoordinateMapper &coordinateMapper,
|
||||
const ComparisonExtent &comparisonExtent = {});
|
||||
void resetDiagram();
|
||||
bool hasFixedBounds() const;
|
||||
OperationResult previewGeometry(quint64 uElementId, quint64 uDocumentRevision,
|
||||
const QPointF &ptFirstScene, const QPointF &ptSecondScene, bool bResize);
|
||||
void selectElement(quint64 uElementId);
|
||||
void cancelInteraction();
|
||||
const tkrShapeProvider *shapeProvider() const;
|
||||
QString pluginDescription() const;
|
||||
|
||||
protected:
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *pEvent) override;
|
||||
void mouseMoveEvent(QGraphicsSceneMouseEvent *pEvent) override;
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *pEvent) override;
|
||||
void keyPressEvent(QKeyEvent *pEvent) override;
|
||||
void focusOutEvent(QFocusEvent *pEvent) override;
|
||||
void drawForeground(QPainter *pPainter, const QRectF &rectExposed) override;
|
||||
|
||||
signals:
|
||||
// Initial and current positions are scene coordinates, not viewport pixels.
|
||||
void dragPreviewRequested(const TikzRefinery::DragUpdate &dragUpdate);
|
||||
void dragCommitRequested(const TikzRefinery::DragUpdate &dragUpdate);
|
||||
void dragCancelled();
|
||||
|
||||
private:
|
||||
bool m_bFixedBounds = false;
|
||||
bool m_bDragActive = false;
|
||||
DragUpdate m_dragUpdate;
|
||||
tkrShapePluginStore m_shapePlugins;
|
||||
tkrCoordinateMapper m_mapper;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,71 @@
|
||||
#include "ui/tkrDiagramView.h"
|
||||
|
||||
#include <QColor>
|
||||
#include <QPainter>
|
||||
#include <QTransform>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
tkrDiagramView::tkrDiagramView(QGraphicsScene *pScene, QWidget *pParent)
|
||||
: QGraphicsView(pScene, pParent)
|
||||
{
|
||||
setAlignment(Qt::AlignCenter);
|
||||
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
|
||||
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
|
||||
setCanvasBounds(pScene->sceneRect(), false);
|
||||
}
|
||||
|
||||
void tkrDiagramView::setCanvasBounds(const QRectF &rectCanvas, bool bFixedBounds)
|
||||
{
|
||||
if (m_rectCanvas == rectCanvas && m_bFixedBounds == bFixedBounds) {
|
||||
return;
|
||||
}
|
||||
m_rectCanvas = rectCanvas;
|
||||
m_bFixedBounds = bFixedBounds;
|
||||
setSceneRect(rectCanvas);
|
||||
fitCanvas();
|
||||
viewport()->update();
|
||||
}
|
||||
|
||||
void tkrDiagramView::drawBackground(QPainter *pPainter, const QRectF &rectExposed)
|
||||
{
|
||||
// Antialiasing partial background fills can leave a blended rim at the
|
||||
// edges of a repaint patch. Preserve smoothing for the diagram items.
|
||||
pPainter->save();
|
||||
pPainter->setRenderHint(QPainter::Antialiasing, false);
|
||||
if (m_bFixedBounds) {
|
||||
// Only the actual editing area is paper; the gutter is part of the view.
|
||||
pPainter->fillRect(rectExposed, QColor(91, 100, 112));
|
||||
// The viewport already clips painting to the exposed pixels. Keep the
|
||||
// paper edge fixed instead of making a new edge at each dirty patch.
|
||||
pPainter->fillRect(m_rectCanvas, Qt::white);
|
||||
} else {
|
||||
pPainter->fillRect(rectExposed, Qt::white);
|
||||
}
|
||||
pPainter->restore();
|
||||
}
|
||||
|
||||
void tkrDiagramView::resizeEvent(QResizeEvent *pEvent)
|
||||
{
|
||||
QGraphicsView::resizeEvent(pEvent);
|
||||
fitCanvas();
|
||||
}
|
||||
|
||||
void tkrDiagramView::fitCanvas()
|
||||
{
|
||||
if (m_rectCanvas.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
constexpr int iMarginPixels = 20;
|
||||
const qreal rScale = std::min(
|
||||
std::max(1, viewport()->width() - 2 * iMarginPixels) / m_rectCanvas.width(),
|
||||
std::max(1, viewport()->height() - 2 * iMarginPixels) / m_rectCanvas.height());
|
||||
if (std::isfinite(rScale) && rScale > 0.0) {
|
||||
setTransform(QTransform::fromScale(rScale, rScale));
|
||||
centerOn(m_rectCanvas.center());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <QGraphicsView>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
// Fits the drawing into the viewport without changing the scene or source.
|
||||
class tkrDiagramView final : public QGraphicsView
|
||||
{
|
||||
public:
|
||||
explicit tkrDiagramView(QGraphicsScene *pScene, QWidget *pParent = nullptr);
|
||||
void setCanvasBounds(const QRectF &rectCanvas, bool bFixedBounds);
|
||||
|
||||
protected:
|
||||
void drawBackground(QPainter *pPainter, const QRectF &rectExposed) override;
|
||||
void resizeEvent(QResizeEvent *pEvent) override;
|
||||
|
||||
private:
|
||||
void fitCanvas();
|
||||
|
||||
QRectF m_rectCanvas;
|
||||
bool m_bFixedBounds = false;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "ui/tkrFolderBrowser.h"
|
||||
|
||||
#include <QLabel>
|
||||
#include <QPushButton>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
namespace TikzRefinery {
|
||||
namespace {
|
||||
constexpr int iPageMargin = 10;
|
||||
constexpr int iPageSpacing = 10;
|
||||
constexpr int iStretchWeight = 1;
|
||||
}
|
||||
|
||||
tkrFolderBrowser::tkrFolderBrowser(QWidget *pParent) : QWidget(pParent)
|
||||
{
|
||||
setObjectName(QStringLiteral("folderBrowser"));
|
||||
QVBoxLayout *pLayout = new QVBoxLayout(this);
|
||||
pLayout->setContentsMargins(iPageMargin, iPageMargin, iPageMargin, iPageMargin);
|
||||
pLayout->setSpacing(iPageSpacing);
|
||||
QLabel *pPlaceholder = new QLabel(tr("Working-folder browsing is in development. You can open an existing TikZ document here."), this);
|
||||
pPlaceholder->setWordWrap(true);
|
||||
pLayout->addWidget(pPlaceholder);
|
||||
QPushButton *pOpenButton = new QPushButton(tr("Open document..."), this);
|
||||
pOpenButton->setObjectName(QStringLiteral("sidebarOpenDocumentButton"));
|
||||
connect(pOpenButton, &QPushButton::clicked, this, &tkrFolderBrowser::openDocumentRequested);
|
||||
pLayout->addWidget(pOpenButton);
|
||||
pLayout->addStretch(iStretchWeight);
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <QWidget>
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
// Files-page shell. Requests the existing guarded Open flow; no folder tree yet.
|
||||
class tkrFolderBrowser final : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit tkrFolderBrowser(QWidget *pParent = nullptr);
|
||||
|
||||
signals:
|
||||
void openDocumentRequested();
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,215 @@
|
||||
#include "ui/tkrMainWindow.h"
|
||||
#include "BuildInfo.h"
|
||||
|
||||
#include "controller/tkrEditorController.h"
|
||||
#include "ui/tkrDiagramScene.h"
|
||||
#include "ui/tkrDiagramView.h"
|
||||
#include "ui/tkrWorkspaceSidebar.h"
|
||||
|
||||
#include <QAction>
|
||||
#include <QCloseEvent>
|
||||
#include <QFileDialog>
|
||||
#include <QFileInfo>
|
||||
#include <QKeySequence>
|
||||
#include <QLabel>
|
||||
#include <QMenu>
|
||||
#include <QMenuBar>
|
||||
#include <QMessageBox>
|
||||
#include <QPainter>
|
||||
#include <QPlainTextEdit>
|
||||
#include <QSplitter>
|
||||
#include <QStatusBar>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
namespace TikzRefinery {
|
||||
namespace {
|
||||
constexpr int iCanvasInitialWidth = 650;
|
||||
constexpr int iSourceInitialWidth = 430;
|
||||
constexpr int iWindowInitialWidth = 1380;
|
||||
constexpr int iWindowInitialHeight = 800;
|
||||
constexpr int iSidebarPaneIndex = 0;
|
||||
constexpr int iEditorPaneIndex = 1;
|
||||
QString applicationIdentity()
|
||||
{
|
||||
return QStringLiteral("TikZRefinery - %1").arg(QString::fromLatin1(BuildInfo::pVersion));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
tkrMainWindow::tkrMainWindow(QWidget *pParent, const QString &strInitialFilePath) : QMainWindow(pParent)
|
||||
{
|
||||
m_pScene = new tkrDiagramScene(this);
|
||||
m_upController = std::make_unique<tkrEditorController>(m_document, *m_pScene);
|
||||
QSplitter *pWorkspaceSplitter = new QSplitter(this);
|
||||
pWorkspaceSplitter->setObjectName(QStringLiteral("workspaceSplitter"));
|
||||
m_pSidebar = new tkrWorkspaceSidebar(pWorkspaceSplitter);
|
||||
m_pSidebar->setProviderDescription(m_pScene->pluginDescription(), m_pScene->shapeProvider() != nullptr);
|
||||
connect(m_pSidebar, &tkrWorkspaceSidebar::openDocumentRequested, this, &tkrMainWindow::openDocument);
|
||||
QSplitter *pSplitter = new QSplitter(pWorkspaceSplitter);
|
||||
QWidget *pCanvasPane = new QWidget(pSplitter);
|
||||
QVBoxLayout *pCanvasLayout = new QVBoxLayout(pCanvasPane);
|
||||
QLabel *pCanvasLabel = new QLabel(tr("Canvas"), pCanvasPane);
|
||||
m_pView = new tkrDiagramView(m_pScene, pCanvasPane);
|
||||
m_pView->setStyleSheet(QStringLiteral("QGraphicsView { border: 1px solid #64748b; }"));
|
||||
m_pView->setRenderHint(QPainter::Antialiasing);
|
||||
m_pView->setAccessibleName(pCanvasLabel->text());
|
||||
pCanvasLabel->setBuddy(m_pView);
|
||||
pCanvasLayout->addWidget(pCanvasLabel);
|
||||
pCanvasLayout->addWidget(m_pView, 1);
|
||||
|
||||
QWidget *pSourcePane = new QWidget(pSplitter);
|
||||
QVBoxLayout *pSourceLayout = new QVBoxLayout(pSourcePane);
|
||||
QLabel *pSourceLabel = new QLabel(tr("TikZ source"), pSourcePane);
|
||||
m_pSourceView = new QPlainTextEdit(pSourcePane);
|
||||
m_pSourceView->setReadOnly(true);
|
||||
m_pSourceView->setAccessibleName(pSourceLabel->text());
|
||||
m_pSourceView->setPlaceholderText(tr("Open a TikZ source file to inspect it."));
|
||||
pSourceLabel->setBuddy(m_pSourceView);
|
||||
pSourceLayout->addWidget(pSourceLabel);
|
||||
pSourceLayout->addWidget(m_pSourceView, 1);
|
||||
|
||||
pSplitter->addWidget(pCanvasPane);
|
||||
pSplitter->addWidget(pSourcePane);
|
||||
pSplitter->setChildrenCollapsible(false);
|
||||
pSplitter->setSizes({iCanvasInitialWidth, iSourceInitialWidth});
|
||||
pWorkspaceSplitter->addWidget(m_pSidebar);
|
||||
pWorkspaceSplitter->addWidget(pSplitter);
|
||||
pWorkspaceSplitter->setChildrenCollapsible(false);
|
||||
pWorkspaceSplitter->setSizes({m_pSidebar->expandedWidth(), iCanvasInitialWidth + iSourceInitialWidth});
|
||||
connect(m_pSidebar, &tkrWorkspaceSidebar::widthRequested, this,
|
||||
[pWorkspaceSplitter](int iWidth) {
|
||||
const QList<int> listSizes = pWorkspaceSplitter->sizes();
|
||||
const int iTotalWidth = listSizes.at(iSidebarPaneIndex) + listSizes.at(iEditorPaneIndex);
|
||||
pWorkspaceSplitter->setSizes({iWidth, iTotalWidth - iWidth});
|
||||
});
|
||||
setCentralWidget(pWorkspaceSplitter);
|
||||
|
||||
QMenu *pFileMenu = menuBar()->addMenu(tr("&File"));
|
||||
QAction *pOpenAction = pFileMenu->addAction(tr("&Open..."));
|
||||
pOpenAction->setShortcut(QKeySequence::Open);
|
||||
connect(pOpenAction, &QAction::triggered, this, &tkrMainWindow::openDocument);
|
||||
m_pSaveAction = pFileMenu->addAction(tr("&Save"));
|
||||
m_pSaveAction->setShortcut(QKeySequence::Save);
|
||||
m_pSaveAction->setEnabled(false);
|
||||
connect(m_pSaveAction, &QAction::triggered, this, [this]() { saveDocument(); });
|
||||
pFileMenu->addSeparator();
|
||||
QAction *pCloseAction = pFileMenu->addAction(tr("&Exit"));
|
||||
connect(pCloseAction, &QAction::triggered, this, [this]() { close(); });
|
||||
|
||||
QMenu *pEditMenu = menuBar()->addMenu(tr("&Edit"));
|
||||
m_pUndoAction = pEditMenu->addAction(tr("&Undo"));
|
||||
m_pRedoAction = pEditMenu->addAction(tr("&Redo"));
|
||||
m_pUndoAction->setObjectName(QStringLiteral("undoAction"));
|
||||
m_pRedoAction->setObjectName(QStringLiteral("redoAction"));
|
||||
m_pUndoAction->setShortcuts(QKeySequence::keyBindings(QKeySequence::Undo));
|
||||
m_pRedoAction->setShortcuts(QKeySequence::keyBindings(QKeySequence::Redo));
|
||||
m_pUndoAction->setEnabled(false);
|
||||
m_pRedoAction->setEnabled(false);
|
||||
const auto handleHistoryResult = [this](const OperationResult &result) {
|
||||
statusBar()->showMessage(result.bSucceeded ? result.strMessage
|
||||
: tr("Edit rejected: %1 Source unchanged.").arg(result.strMessage));
|
||||
};
|
||||
connect(m_pUndoAction, &QAction::triggered, this, [this, handleHistoryResult]() {
|
||||
handleHistoryResult(m_upController->undo());
|
||||
});
|
||||
connect(m_pRedoAction, &QAction::triggered, this, [this, handleHistoryResult]() {
|
||||
handleHistoryResult(m_upController->redo());
|
||||
});
|
||||
|
||||
connect(m_upController.get(), &tkrEditorController::documentChanged,
|
||||
this, &tkrMainWindow::updateDocumentView);
|
||||
connect(m_upController.get(), &tkrEditorController::statusChanged,
|
||||
this, [this](const QString &strMessage) { statusBar()->showMessage(strMessage); });
|
||||
QMenu *pHelpMenu = menuBar()->addMenu(tr("&Help"));
|
||||
QAction *pAboutAction = pHelpMenu->addAction(tr("&About TikZRefinery"));
|
||||
connect(pAboutAction, &QAction::triggered, this, [this]() {
|
||||
QMessageBox::about(this, tr("About TikZRefinery"),
|
||||
tr("%1 (%2)\n\nFull source checkpoint: %3\nSource state: %4\n\nShape provider:\n%5")
|
||||
.arg(applicationIdentity(), QString::fromLatin1(BuildInfo::pShortCheckpoint),
|
||||
QString::fromLatin1(BuildInfo::pCheckpoint), QString::fromLatin1(BuildInfo::pSourceState),
|
||||
m_pScene->pluginDescription()));
|
||||
});
|
||||
setWindowTitle(applicationIdentity());
|
||||
resize(iWindowInitialWidth, iWindowInitialHeight);
|
||||
statusBar()->showMessage(tr("Open a TikZ document, then select and drag an element. %1")
|
||||
.arg(m_pScene->pluginDescription().section(QLatin1Char('\n'), 0, 0)));
|
||||
if (!strInitialFilePath.isEmpty()) {
|
||||
const OperationResult resultOpen = m_upController->openDocument(strInitialFilePath);
|
||||
if (!resultOpen.bSucceeded) {
|
||||
QMessageBox::warning(this, tr("Could not open document"), resultOpen.strMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tkrMainWindow::~tkrMainWindow() = default;
|
||||
|
||||
void tkrMainWindow::openDocument()
|
||||
{
|
||||
if (!confirmDiscardOrSave()) {
|
||||
return;
|
||||
}
|
||||
const QString strFilePath = QFileDialog::getOpenFileName(
|
||||
this, tr("Open TikZ document"), {}, tr("TeX source (*.tex *.tikz);;All files (*)"));
|
||||
if (strFilePath.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
const OperationResult resultOpen = m_upController->openDocument(strFilePath);
|
||||
if (!resultOpen.bSucceeded) {
|
||||
QMessageBox::warning(this, tr("Could not open document"), resultOpen.strMessage);
|
||||
}
|
||||
}
|
||||
|
||||
bool tkrMainWindow::saveDocument()
|
||||
{
|
||||
const OperationResult resultSave = m_upController->saveDocument();
|
||||
if (!resultSave.bSucceeded) {
|
||||
QMessageBox::warning(this, tr("Could not save document"), resultSave.strMessage);
|
||||
return false;
|
||||
}
|
||||
statusBar()->showMessage(resultSave.strMessage);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool tkrMainWindow::confirmDiscardOrSave()
|
||||
{
|
||||
if (!m_document.hasUnsavedChanges()) {
|
||||
return true;
|
||||
}
|
||||
const QMessageBox::StandardButton buttonChoice = QMessageBox::question(
|
||||
this, tr("Unsaved changes"), tr("Save your changes before continuing?"),
|
||||
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel,
|
||||
QMessageBox::Cancel);
|
||||
if (buttonChoice == QMessageBox::Save) {
|
||||
return saveDocument();
|
||||
}
|
||||
return buttonChoice == QMessageBox::Discard;
|
||||
}
|
||||
|
||||
void tkrMainWindow::updateDocumentView()
|
||||
{
|
||||
m_pView->setCanvasBounds(m_pScene->sceneRect(), m_pScene->hasFixedBounds());
|
||||
// Restored geometry can keep identical bounds. Repaint foreground handles too.
|
||||
m_pView->viewport()->update();
|
||||
// Display is decoded for viewing only; saving always uses preserved source bytes.
|
||||
m_pSourceView->setPlainText(QString::fromUtf8(m_document.sourceBytes()));
|
||||
m_pSaveAction->setEnabled(m_document.hasUnsavedChanges());
|
||||
m_pUndoAction->setEnabled(m_document.canUndo());
|
||||
m_pRedoAction->setEnabled(m_document.canRedo());
|
||||
m_pUndoAction->setText(m_document.canUndo() ? tr("&Undo %1").arg(m_document.undoDescription()) : tr("&Undo"));
|
||||
m_pRedoAction->setText(m_document.canRedo() ? tr("&Redo %1").arg(m_document.redoDescription()) : tr("&Redo"));
|
||||
setWindowModified(m_document.hasUnsavedChanges());
|
||||
setWindowTitle(QFileInfo(m_document.filePath()).fileName() + QStringLiteral("[*] - ") + applicationIdentity());
|
||||
}
|
||||
|
||||
void tkrMainWindow::closeEvent(QCloseEvent *pEvent)
|
||||
{
|
||||
m_pScene->cancelInteraction();
|
||||
if (!confirmDiscardOrSave()) {
|
||||
pEvent->ignore();
|
||||
return;
|
||||
}
|
||||
pEvent->accept();
|
||||
// main.cpp owns this window on the stack. Event-loop exit destroys the window,
|
||||
// then its controller/document members and QObject-owned scene/widgets.
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/tkrTikzDocument.h"
|
||||
|
||||
#include <QMainWindow>
|
||||
#include <memory>
|
||||
|
||||
class QAction;
|
||||
class QCloseEvent;
|
||||
class QPlainTextEdit;
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
class tkrDiagramScene;
|
||||
class tkrDiagramView;
|
||||
class tkrEditorController;
|
||||
class tkrWorkspaceSidebar;
|
||||
|
||||
class tkrMainWindow final : public QMainWindow
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit tkrMainWindow(QWidget *pParent = nullptr, const QString &strInitialFilePath = {});
|
||||
~tkrMainWindow() override;
|
||||
|
||||
protected:
|
||||
void closeEvent(QCloseEvent *pEvent) override;
|
||||
|
||||
private:
|
||||
void openDocument();
|
||||
bool saveDocument();
|
||||
bool confirmDiscardOrSave();
|
||||
void updateDocumentView();
|
||||
|
||||
// Reverse member destruction releases the controller before its document.
|
||||
tkrTikzDocument m_document;
|
||||
tkrDiagramScene *m_pScene = nullptr; // Owned by this window through QObject parenting.
|
||||
tkrDiagramView *m_pView = nullptr;
|
||||
tkrWorkspaceSidebar *m_pSidebar = nullptr; // Owned through the central widget's Qt parent tree.
|
||||
QPlainTextEdit *m_pSourceView = nullptr;
|
||||
QAction *m_pSaveAction = nullptr;
|
||||
QAction *m_pUndoAction = nullptr;
|
||||
QAction *m_pRedoAction = nullptr;
|
||||
// No QObject parent: unique_ptr is this controller's single owning mechanism.
|
||||
std::unique_ptr<tkrEditorController> m_upController;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,53 @@
|
||||
#include "ui/tkrShapePalette.h"
|
||||
|
||||
#include <QGroupBox>
|
||||
#include <QLabel>
|
||||
#include <QPushButton>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
namespace TikzRefinery {
|
||||
namespace {
|
||||
constexpr int iPageMargin = 10;
|
||||
constexpr int iPageSpacing = 10;
|
||||
constexpr int iStretchWeight = 1;
|
||||
constexpr int iProviderSummaryLine = 0;
|
||||
}
|
||||
|
||||
tkrShapePalette::tkrShapePalette(QWidget *pParent) : QWidget(pParent)
|
||||
{
|
||||
setObjectName(QStringLiteral("shapePalette"));
|
||||
QVBoxLayout *pLayout = new QVBoxLayout(this);
|
||||
pLayout->setContentsMargins(iPageMargin, iPageMargin, iPageMargin, iPageMargin);
|
||||
pLayout->setSpacing(iPageSpacing);
|
||||
QGroupBox *pShapeGroup = new QGroupBox(tr("Rectangle support"), this);
|
||||
QVBoxLayout *pShapeLayout = new QVBoxLayout(pShapeGroup);
|
||||
m_pProviderLabel = new QLabel(pShapeGroup);
|
||||
m_pProviderLabel->setTextFormat(Qt::PlainText);
|
||||
m_pProviderLabel->setWordWrap(true);
|
||||
pShapeLayout->addWidget(m_pProviderLabel);
|
||||
m_pAvailabilityLabel = new QLabel(pShapeGroup);
|
||||
m_pAvailabilityLabel->setWordWrap(true);
|
||||
pShapeLayout->addWidget(m_pAvailabilityLabel);
|
||||
QPushButton *pCreateButton = new QPushButton(tr("Create rectangle"), pShapeGroup);
|
||||
pCreateButton->setObjectName(QStringLiteral("createShapeButton"));
|
||||
pCreateButton->setEnabled(false);
|
||||
pCreateButton->setToolTip(tr("Shape creation is in development. Open a supported TikZ file to edit existing shapes."));
|
||||
pShapeLayout->addWidget(pCreateButton);
|
||||
pLayout->addWidget(pShapeGroup);
|
||||
QLabel *pDevelopmentLabel = new QLabel(tr("Shape creation is in development. For now, open a TikZ file to move or resize existing shapes."), this);
|
||||
pDevelopmentLabel->setWordWrap(true);
|
||||
pLayout->addWidget(pDevelopmentLabel);
|
||||
pLayout->addStretch(iStretchWeight);
|
||||
setProviderDescription({}, false);
|
||||
}
|
||||
|
||||
void tkrShapePalette::setProviderDescription(const QString &strDescription, bool bAvailable)
|
||||
{
|
||||
// Keep paths and runtime identity in About, not in the normal palette flow.
|
||||
m_pProviderLabel->setText(bAvailable ? strDescription.section(QLatin1Char('\n'), iProviderSummaryLine, iProviderSummaryLine)
|
||||
: tr("Rectangle plugin unavailable"));
|
||||
m_pAvailabilityLabel->setText(bAvailable ? tr("Loaded for display, selection, movement and resizing.")
|
||||
: tr("See Help > About for plugin details. Creation remains unavailable."));
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include <QWidget>
|
||||
|
||||
class QLabel;
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
// Presents current fixed-provider support. A general creation catalogue is still planned.
|
||||
class tkrShapePalette final : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit tkrShapePalette(QWidget *pParent = nullptr);
|
||||
void setProviderDescription(const QString &strDescription, bool bAvailable);
|
||||
|
||||
private:
|
||||
QLabel *m_pProviderLabel = nullptr; // Owned by this widget through Qt parenting.
|
||||
QLabel *m_pAvailabilityLabel = nullptr;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,152 @@
|
||||
#include "ui/tkrWorkspaceSidebar.h"
|
||||
#include "ui/tkrFolderBrowser.h"
|
||||
#include "ui/tkrShapePalette.h"
|
||||
|
||||
#include <QButtonGroup>
|
||||
#include <QHBoxLayout>
|
||||
#include <QLabel>
|
||||
#include <QResizeEvent>
|
||||
#include <QStackedWidget>
|
||||
#include <QStyle>
|
||||
#include <QToolButton>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
namespace TikzRefinery {
|
||||
namespace {
|
||||
constexpr int iTabStripWidth = 52;
|
||||
constexpr int iTabMargin = 4;
|
||||
constexpr int iTabSpacing = 4;
|
||||
constexpr int iHeaderMargin = 8;
|
||||
constexpr int iNoMargin = 0;
|
||||
constexpr int iStretchWeight = 1;
|
||||
constexpr int iDefaultExpandedWidth = 300;
|
||||
constexpr int iMinimumExpandedWidth = 220;
|
||||
}
|
||||
|
||||
tkrWorkspaceSidebar::tkrWorkspaceSidebar(QWidget *pParent)
|
||||
: QWidget(pParent), m_iExpandedWidth(iDefaultExpandedWidth)
|
||||
{
|
||||
setObjectName(QStringLiteral("workspaceSidebar"));
|
||||
setAccessibleName(tr("Workspace sidebar"));
|
||||
setMinimumWidth(iMinimumExpandedWidth);
|
||||
QHBoxLayout *pLayout = new QHBoxLayout(this);
|
||||
pLayout->setContentsMargins(iNoMargin, iNoMargin, iNoMargin, iNoMargin);
|
||||
pLayout->setSpacing(iNoMargin);
|
||||
QWidget *pTabStrip = new QWidget(this);
|
||||
pTabStrip->setObjectName(QStringLiteral("workspaceTabStrip"));
|
||||
pTabStrip->setFixedWidth(iTabStripWidth);
|
||||
QVBoxLayout *pTabsLayout = new QVBoxLayout(pTabStrip);
|
||||
pTabsLayout->setContentsMargins(iTabMargin, iTabMargin, iTabMargin, iTabMargin);
|
||||
pTabsLayout->setSpacing(iTabSpacing);
|
||||
const int iIconExtent = style()->pixelMetric(QStyle::PM_LargeIconSize);
|
||||
m_pShapesButton = new QToolButton(pTabStrip);
|
||||
m_pFilesButton = new QToolButton(pTabStrip);
|
||||
const QList<QToolButton *> listButtons = {m_pShapesButton, m_pFilesButton};
|
||||
QButtonGroup *pPageGroup = new QButtonGroup(this);
|
||||
for (QToolButton *pButton : listButtons) {
|
||||
pButton->setCheckable(true);
|
||||
pButton->setAutoRaise(true);
|
||||
pButton->setIconSize(QSize(iIconExtent, iIconExtent));
|
||||
pButton->setFixedSize(iTabStripWidth - iTabMargin - iTabMargin,
|
||||
iTabStripWidth - iTabMargin - iTabMargin);
|
||||
pPageGroup->addButton(pButton);
|
||||
pTabsLayout->addWidget(pButton);
|
||||
}
|
||||
m_pShapesButton->setObjectName(QStringLiteral("workspaceShapesTab"));
|
||||
m_pShapesButton->setText(tr("Shapes"));
|
||||
m_pShapesButton->setAccessibleName(tr("Shapes"));
|
||||
m_pShapesButton->setToolTip(tr("Shapes — click the selected tab to collapse or reopen"));
|
||||
m_pShapesButton->setIcon(style()->standardIcon(QStyle::SP_FileDialogContentsView));
|
||||
m_pFilesButton->setObjectName(QStringLiteral("workspaceFilesTab"));
|
||||
m_pFilesButton->setText(tr("Files"));
|
||||
m_pFilesButton->setAccessibleName(tr("Files"));
|
||||
m_pFilesButton->setToolTip(tr("Files — click the selected tab to collapse or reopen"));
|
||||
m_pFilesButton->setIcon(style()->standardIcon(QStyle::SP_DirClosedIcon));
|
||||
connect(m_pShapesButton, &QToolButton::clicked, this, [this]() { selectOrToggle(Page::Shapes); });
|
||||
connect(m_pFilesButton, &QToolButton::clicked, this, [this]() { selectOrToggle(Page::Files); });
|
||||
pTabsLayout->addStretch(iStretchWeight);
|
||||
pLayout->addWidget(pTabStrip);
|
||||
|
||||
m_pContent = new QWidget(this);
|
||||
m_pContent->setObjectName(QStringLiteral("workspaceSidebarContent"));
|
||||
QVBoxLayout *pContentLayout = new QVBoxLayout(m_pContent);
|
||||
pContentLayout->setContentsMargins(iNoMargin, iNoMargin, iNoMargin, iNoMargin);
|
||||
QHBoxLayout *pHeaderLayout = new QHBoxLayout;
|
||||
pHeaderLayout->setContentsMargins(iHeaderMargin, iHeaderMargin, iHeaderMargin, iNoMargin);
|
||||
m_pHeading = new QLabel(m_pContent);
|
||||
QFont fontHeading = m_pHeading->font();
|
||||
fontHeading.setBold(true);
|
||||
m_pHeading->setFont(fontHeading);
|
||||
pHeaderLayout->addWidget(m_pHeading, iStretchWeight);
|
||||
QToolButton *pCollapseButton = new QToolButton(m_pContent);
|
||||
pCollapseButton->setObjectName(QStringLiteral("workspaceCollapseButton"));
|
||||
pCollapseButton->setAccessibleName(tr("Collapse sidebar"));
|
||||
pCollapseButton->setToolTip(tr("Collapse sidebar"));
|
||||
pCollapseButton->setIcon(style()->standardIcon(QStyle::SP_ArrowLeft));
|
||||
pCollapseButton->setAutoRaise(true);
|
||||
connect(pCollapseButton, &QToolButton::clicked, this, [this]() { setCollapsed(true); });
|
||||
pHeaderLayout->addWidget(pCollapseButton);
|
||||
pContentLayout->addLayout(pHeaderLayout);
|
||||
m_pPages = new QStackedWidget(m_pContent);
|
||||
m_pShapePalette = new tkrShapePalette(m_pPages);
|
||||
m_pFolderBrowser = new tkrFolderBrowser(m_pPages);
|
||||
m_pPages->addWidget(m_pShapePalette);
|
||||
m_pPages->addWidget(m_pFolderBrowser);
|
||||
connect(m_pFolderBrowser, &tkrFolderBrowser::openDocumentRequested,
|
||||
this, &tkrWorkspaceSidebar::openDocumentRequested);
|
||||
pContentLayout->addWidget(m_pPages, iStretchWeight);
|
||||
pLayout->addWidget(m_pContent, iStretchWeight);
|
||||
updatePage();
|
||||
}
|
||||
|
||||
void tkrWorkspaceSidebar::setCollapsed(bool bCollapsed)
|
||||
{
|
||||
if (m_bCollapsed == bCollapsed) return;
|
||||
if (bCollapsed && width() >= iMinimumExpandedWidth) m_iExpandedWidth = width();
|
||||
const int iRequestedWidth = bCollapsed ? iTabStripWidth : m_iExpandedWidth;
|
||||
m_bCollapsed = bCollapsed;
|
||||
m_pContent->setVisible(!bCollapsed);
|
||||
setMinimumWidth(bCollapsed ? iTabStripWidth : iMinimumExpandedWidth);
|
||||
setMaximumWidth(bCollapsed ? iTabStripWidth : QWIDGETSIZE_MAX);
|
||||
emit widthRequested(iRequestedWidth);
|
||||
}
|
||||
|
||||
bool tkrWorkspaceSidebar::isCollapsed() const { return m_bCollapsed; }
|
||||
tkrWorkspaceSidebar::Page tkrWorkspaceSidebar::selectedPage() const { return m_pageSelected; }
|
||||
int tkrWorkspaceSidebar::expandedWidth() const { return m_iExpandedWidth; }
|
||||
|
||||
void tkrWorkspaceSidebar::activatePage(Page page)
|
||||
{
|
||||
m_pageSelected = page;
|
||||
updatePage();
|
||||
setCollapsed(false);
|
||||
}
|
||||
|
||||
void tkrWorkspaceSidebar::selectOrToggle(Page page)
|
||||
{
|
||||
if (m_pageSelected == page) setCollapsed(!m_bCollapsed);
|
||||
else activatePage(page);
|
||||
}
|
||||
|
||||
void tkrWorkspaceSidebar::updatePage()
|
||||
{
|
||||
const bool bShapes = m_pageSelected == Page::Shapes;
|
||||
m_pShapesButton->setChecked(bShapes);
|
||||
m_pFilesButton->setChecked(!bShapes);
|
||||
m_pHeading->setText(bShapes ? tr("Shapes") : tr("Files"));
|
||||
m_pPages->setCurrentWidget(bShapes ? static_cast<QWidget *>(m_pShapePalette)
|
||||
: static_cast<QWidget *>(m_pFolderBrowser));
|
||||
}
|
||||
|
||||
void tkrWorkspaceSidebar::setProviderDescription(const QString &strDescription, bool bAvailable)
|
||||
{
|
||||
m_pShapePalette->setProviderDescription(strDescription, bAvailable);
|
||||
}
|
||||
|
||||
void tkrWorkspaceSidebar::resizeEvent(QResizeEvent *pEvent)
|
||||
{
|
||||
QWidget::resizeEvent(pEvent);
|
||||
if (!m_bCollapsed && width() >= iMinimumExpandedWidth) m_iExpandedWidth = width();
|
||||
}
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <QWidget>
|
||||
|
||||
class QLabel;
|
||||
class QResizeEvent;
|
||||
class QStackedWidget;
|
||||
class QToolButton;
|
||||
|
||||
namespace TikzRefinery {
|
||||
|
||||
class tkrShapePalette;
|
||||
class tkrFolderBrowser;
|
||||
|
||||
// Owns its pages and remembers only this window session's expansion state.
|
||||
class tkrWorkspaceSidebar final : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
enum class Page { Shapes, Files };
|
||||
Q_ENUM(Page)
|
||||
|
||||
explicit tkrWorkspaceSidebar(QWidget *pParent = nullptr);
|
||||
void setCollapsed(bool bCollapsed);
|
||||
bool isCollapsed() const;
|
||||
void activatePage(Page page);
|
||||
Page selectedPage() const;
|
||||
int expandedWidth() const;
|
||||
void setProviderDescription(const QString &strDescription, bool bAvailable);
|
||||
|
||||
signals:
|
||||
void widthRequested(int iWidth);
|
||||
void openDocumentRequested();
|
||||
|
||||
protected:
|
||||
void resizeEvent(QResizeEvent *pEvent) override;
|
||||
|
||||
private:
|
||||
void selectOrToggle(Page page);
|
||||
void updatePage();
|
||||
|
||||
bool m_bCollapsed = false;
|
||||
Page m_pageSelected = Page::Shapes;
|
||||
int m_iExpandedWidth;
|
||||
QWidget *m_pContent = nullptr; // All UI pointers are Qt-parent owned by this sidebar.
|
||||
QLabel *m_pHeading = nullptr;
|
||||
QToolButton *m_pShapesButton = nullptr;
|
||||
QToolButton *m_pFilesButton = nullptr;
|
||||
QStackedWidget *m_pPages = nullptr;
|
||||
tkrShapePalette *m_pShapePalette = nullptr;
|
||||
tkrFolderBrowser *m_pFolderBrowser = nullptr;
|
||||
};
|
||||
|
||||
} // namespace TikzRefinery
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Compare retained Qt canvas renders with fixed-extent TinyTeX renders.
|
||||
|
||||
Run after the rectangle/segment tests have written *-canvas.png to the work directory.
|
||||
No tight crops or fitted translations: both renderers use the declared 7 x 5 cm
|
||||
extent, with 100 pixels/cm. The one-pixel edge tolerance is a prototype check,
|
||||
not a stakeholder-approved product acceptance threshold.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
from PIL import Image, ImageChops, ImageDraw, ImageFilter
|
||||
|
||||
|
||||
def run_checked(arguments, cwd):
|
||||
result = subprocess.run(arguments, cwd=cwd, capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stdout + result.stderr)
|
||||
|
||||
|
||||
def compare(work, evidence, pdflatex, pdftoppm, fixtures, output_stem, source_directory=None):
|
||||
corpus = source_directory or Path(__file__).resolve().parents[1] / "examples" / "explicit-coordinates"
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
evidence.mkdir(parents=True, exist_ok=True)
|
||||
rows = []
|
||||
metrics = {}
|
||||
for name in fixtures:
|
||||
source = corpus / f"{name}.tex"
|
||||
# Compile the untouched original from its own directory first.
|
||||
run_checked([pdflatex, "-interaction=nonstopmode", "-halt-on-error",
|
||||
f"-output-directory={work}", str(source)], corpus)
|
||||
text = source.read_bytes().decode("utf-8")
|
||||
picture = text[text.index(r"\begin{tikzpicture}"):text.index(r"\end{tikzpicture}")
|
||||
+ len(r"\end{tikzpicture}")]
|
||||
# Only the page wrapper changes. The complete original picture, including
|
||||
# its invisible fixed extent, is placed at page origin without cropping.
|
||||
calibrated = work / f"{name}-calibrated.tex"
|
||||
calibrated.write_text(
|
||||
"\\documentclass{article}\n\\usepackage{tikz}\n"
|
||||
"\\pdfhorigin=0pt \\pdfvorigin=0pt\n"
|
||||
"\\begin{document}\n\\setbox0=\\hbox{%\n" + picture + "%\n}\n"
|
||||
"\\pdfpagewidth=7cm \\pdfpageheight=5cm\n"
|
||||
"\\shipout\\box0\n\\end{document}\n", encoding="utf-8")
|
||||
run_checked([pdflatex, "-interaction=nonstopmode", "-halt-on-error", calibrated.name], work)
|
||||
prefix = work / f"{name}-pdf"
|
||||
run_checked([pdftoppm, "-singlefile", "-r", "254", "-png",
|
||||
str(calibrated.with_suffix(".pdf")), str(prefix)], work)
|
||||
for log in (work / f"{name}.log", calibrated.with_suffix(".log")):
|
||||
diagnostics = log.read_text(encoding="utf-8", errors="replace")
|
||||
if any(term in diagnostics for term in ("! ", "Undefined control", "undefined references",
|
||||
"undefined citations", "not found")):
|
||||
raise RuntimeError(f"Unexpected diagnostics in {log}")
|
||||
canvas = Image.open(work / f"{name}-canvas.png").convert("RGB")
|
||||
pdf = Image.open(prefix.with_suffix(".png")).convert("RGB")
|
||||
# Poppler may ceil a fractional page dimension by one background pixel.
|
||||
if pdf.width not in (700, 701) or pdf.height not in (500, 501):
|
||||
raise AssertionError(f"Unexpected fixed-extent raster size: {pdf.size}")
|
||||
background = Image.new("RGB", pdf.size, "white")
|
||||
background.paste(canvas, (0, 0))
|
||||
canvas = background
|
||||
mask_canvas = canvas.convert("L").point(lambda value: 255 if value < 128 else 0)
|
||||
mask_pdf = pdf.convert("L").point(lambda value: 255 if value < 128 else 0)
|
||||
if mask_canvas.getbbox() is None or mask_pdf.getbbox() is None:
|
||||
raise AssertionError("A renderer produced an empty image")
|
||||
# Every dark edge pixel must have a counterpart within one pixel. This
|
||||
# detects translation, wrong size, scale, axis, or missing/extra boxes.
|
||||
unmatched_canvas = ImageChops.subtract(mask_canvas, mask_pdf.filter(ImageFilter.MaxFilter(3)))
|
||||
unmatched_pdf = ImageChops.subtract(mask_pdf, mask_canvas.filter(ImageFilter.MaxFilter(3)))
|
||||
count_canvas = unmatched_canvas.width * unmatched_canvas.height - unmatched_canvas.histogram()[0]
|
||||
count_pdf = unmatched_pdf.width * unmatched_pdf.height - unmatched_pdf.histogram()[0]
|
||||
metrics[name] = {"pdf_pixels": list(pdf.size), "pixels_per_centimeter": 100,
|
||||
"edge_tolerance_pixels": 1,
|
||||
"unmatched_canvas_pixels": count_canvas, "unmatched_pdf_pixels": count_pdf}
|
||||
if count_canvas or count_pdf:
|
||||
raise AssertionError(json.dumps(metrics[name]))
|
||||
row = Image.new("RGB", (2130, 550), "#eeeeee")
|
||||
draw = ImageDraw.Draw(row)
|
||||
draw.text((15, 12), name + ": Qt canvas | TinyTeX | aligned overlay", fill="black")
|
||||
overlay = Image.blend(canvas, pdf, 0.5)
|
||||
for index, image in enumerate((canvas, pdf, overlay)):
|
||||
row.paste(image, (index * 710 + 5, 40))
|
||||
rows.append(row)
|
||||
for start in range(0, len(rows), 2):
|
||||
sheet = Image.new("RGB", (2130, min(2, len(rows)-start) * 550), "white")
|
||||
for index, row in enumerate(rows[start:start+2]):
|
||||
sheet.paste(row, (0, index * 550))
|
||||
suffix = "" if start == 0 else f"-{start//2+1}"
|
||||
sheet.save(evidence / f"{output_stem}{suffix}.png")
|
||||
(evidence / f"{output_stem}.json").write_text(
|
||||
json.dumps(metrics, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(metrics, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--work", type=Path, required=True)
|
||||
parser.add_argument("--evidence", type=Path, required=True)
|
||||
parser.add_argument("--pdflatex", required=True)
|
||||
parser.add_argument("--pdftoppm", required=True)
|
||||
parser.add_argument("--fixtures", nargs="+", default=["boxes-initial", "boxes-touching"])
|
||||
parser.add_argument("--output-stem", default="rectangle-comparison-2026-10-21")
|
||||
parser.add_argument("--source-directory", type=Path)
|
||||
options = parser.parse_args()
|
||||
compare(options.work.resolve(), options.evidence.resolve(), options.pdflatex, options.pdftoppm,
|
||||
options.fixtures, options.output_stem,
|
||||
options.source_directory.resolve() if options.source_directory else None)
|
||||
@@ -0,0 +1,85 @@
|
||||
#include "geometry/tkrCoordinateMapper.h"
|
||||
#include "model/tkrTikzDocument.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDebug>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
using namespace TikzRefinery;
|
||||
|
||||
namespace {
|
||||
|
||||
void require(bool bCondition, const char *pMessage)
|
||||
{
|
||||
if (!bCondition) {
|
||||
qFatal("%s", pMessage);
|
||||
}
|
||||
}
|
||||
|
||||
void checkCoordinateMapping()
|
||||
{
|
||||
tkrCoordinateMapper mapper;
|
||||
require(mapper.configure(QPointF(200.0, 300.0), 100.0).bSucceeded, "Valid mapping rejected");
|
||||
// TC-028: independent expectations catch a wrong origin or inverted axis.
|
||||
require(mapper.mapToScene(QPointF(0.0, 0.0)) == QPointF(200.0, 300.0), "Origin mismatch");
|
||||
require(mapper.mapToScene(QPointF(1.0, 0.0)) == QPointF(300.0, 300.0), "X scale mismatch");
|
||||
require(mapper.mapToScene(QPointF(0.0, 1.0)) == QPointF(200.0, 200.0), "Y direction mismatch");
|
||||
require(mapper.mapToScene(QPointF(-1.0, -0.5)) == QPointF(100.0, 350.0), "Negative coordinate mismatch");
|
||||
require(mapper.mapToTikz(QPointF(100.0, 350.0)) == QPointF(-1.0, -0.5), "Inverse mismatch");
|
||||
require(!mapper.configure(QPointF(), 0.0).bSucceeded, "Zero scale accepted");
|
||||
require(!mapper.configure(QPointF(), std::numeric_limits<qreal>::infinity()).bSucceeded,
|
||||
"Infinite scale accepted");
|
||||
require(mapper.mapToScene(QPointF(1.0, 0.0)) == QPointF(300.0, 300.0), "Rejected configuration changed state");
|
||||
}
|
||||
|
||||
void checkSourceEdits()
|
||||
{
|
||||
tkrTikzDocument document;
|
||||
// CRLF, UTF-8 comment bytes, whitespace and unrelated source must survive.
|
||||
const QByteArray baSource = QByteArray::fromHex("25c3a90d0a")
|
||||
+ "\\draw (2cm,0cm) rectangle (3cm,1cm); % keep\r\n";
|
||||
document.loadSource(baSource, QStringLiteral("fixture.tex"));
|
||||
const quint64 uRevision = document.revision();
|
||||
const qsizetype nFirstX = baSource.indexOf("2cm");
|
||||
const qsizetype nSecondX = baSource.indexOf("3cm");
|
||||
// Variable-length replacements must not shift the next replacement's source range.
|
||||
QVector<CoordinateEdit> vecEdits = {
|
||||
{{nFirstX, 1}, "2", "1.25", uRevision},
|
||||
{{nSecondX, 1}, "3", "2.25", uRevision}
|
||||
};
|
||||
QByteArray baExpected = QByteArray::fromHex("25c3a90d0a")
|
||||
+ "\\draw (1.25cm,0cm) rectangle (2.25cm,1cm); % keep\r\n";
|
||||
require(document.applyCoordinateEdits(vecEdits).bSucceeded, "Valid batch rejected");
|
||||
require(document.sourceBytes() == baExpected, "Unrelated bytes changed or offsets shifted");
|
||||
require(document.hasUnsavedChanges(), "Edit not marked dirty");
|
||||
require(!document.applyCoordinateEdits(vecEdits).bSucceeded, "Stale batch accepted");
|
||||
require(document.sourceBytes() == baExpected, "Rejected batch mutated source");
|
||||
document.markSaved();
|
||||
require(!document.hasUnsavedChanges(), "Successful save did not clear dirty state");
|
||||
|
||||
document.loadSource(baSource, QStringLiteral("fixture.tex"));
|
||||
const quint64 uNewRevision = document.revision();
|
||||
require(!document.applyCoordinateEdits(vecEdits).bSucceeded, "Reopening reused a revision");
|
||||
vecEdits = {{{nFirstX, 1}, "2", "1", uNewRevision},
|
||||
{{nSecondX, 1}, "wrong", "2", uNewRevision}};
|
||||
require(!document.applyCoordinateEdits(vecEdits).bSucceeded, "Mismatched text accepted");
|
||||
require(document.sourceBytes() == baSource, "Failed batch partially applied");
|
||||
vecEdits = {{{nFirstX, 3}, "2cm", "1cm", uNewRevision},
|
||||
{{nFirstX + 1, 2}, "cm", "cm", uNewRevision}};
|
||||
require(!document.applyCoordinateEdits(vecEdits).bSucceeded, "Overlapping ranges accepted");
|
||||
vecEdits = {{{baSource.size(), 1}, "", "1", uNewRevision}};
|
||||
require(!document.applyCoordinateEdits(vecEdits).bSucceeded, "Out-of-bounds range accepted");
|
||||
require(document.sourceBytes() == baSource, "Invalid ranges mutated source");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int iArgumentCount, char *pArguments[])
|
||||
{
|
||||
QCoreApplication application(iArgumentCount, pArguments);
|
||||
checkCoordinateMapping();
|
||||
checkSourceEdits();
|
||||
qInfo("Core foundation checks passed. Parser, GUI, saving and product acceptance remain untested.");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
#include "controller/tkrEditorController.h"
|
||||
#include "model/tkrTikzDocument.h"
|
||||
#include "ui/tkrDiagramScene.h"
|
||||
#include "ui/tkrMainWindow.h"
|
||||
#include "ui/tkrWorkspaceSidebar.h"
|
||||
|
||||
#include <QAction>
|
||||
#include <QApplication>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFocusEvent>
|
||||
#include <QFontDatabase>
|
||||
#include <QGraphicsView>
|
||||
#include <QGraphicsItem>
|
||||
#include <QImage>
|
||||
#include <QKeyEvent>
|
||||
#include <QMouseEvent>
|
||||
#include <QPainter>
|
||||
#include <QPlainTextEdit>
|
||||
#include <QScrollBar>
|
||||
#include <QTemporaryDir>
|
||||
|
||||
using namespace TikzRefinery;
|
||||
|
||||
namespace {
|
||||
|
||||
void require(bool bCondition, const char *pMessage)
|
||||
{
|
||||
if (!bCondition) {
|
||||
qFatal("%s", pMessage);
|
||||
}
|
||||
}
|
||||
|
||||
QByteArray readFile(const QString &strPath)
|
||||
{
|
||||
QFile fileSource(strPath);
|
||||
require(fileSource.open(QIODevice::ReadOnly), "Cannot open test source");
|
||||
const QByteArray baSource = fileSource.readAll();
|
||||
require(fileSource.error() == QFileDevice::NoError, "Cannot read test source");
|
||||
return baSource;
|
||||
}
|
||||
|
||||
void writeFile(const QString &strPath, const QByteArray &baSource)
|
||||
{
|
||||
QFile fileOutput(strPath);
|
||||
require(fileOutput.open(QIODevice::WriteOnly) && fileOutput.write(baSource) == baSource.size(),
|
||||
"Cannot write test source");
|
||||
}
|
||||
|
||||
QString corpusPath(const QString &strName)
|
||||
{
|
||||
return QStringLiteral(TKR_CORPUS_DIRECTORY) + QLatin1Char('/') + strName + QStringLiteral(".tex");
|
||||
}
|
||||
|
||||
void pointerEvent(QGraphicsView &view, QEvent::Type eventType, const QPointF &ptScene,
|
||||
Qt::MouseButton mouseButton, Qt::MouseButtons mouseButtons)
|
||||
{
|
||||
const QPoint ptViewport = view.mapFromScene(ptScene);
|
||||
QMouseEvent eventPointer(eventType, QPointF(ptViewport), QPointF(view.viewport()->mapToGlobal(ptViewport)),
|
||||
mouseButton, mouseButtons, Qt::NoModifier);
|
||||
QApplication::sendEvent(view.viewport(), &eventPointer);
|
||||
QApplication::processEvents();
|
||||
}
|
||||
|
||||
void press(QGraphicsView &view, const QPointF &ptScene)
|
||||
{
|
||||
view.setFocus();
|
||||
pointerEvent(view, QEvent::MouseButtonPress, ptScene, Qt::LeftButton, Qt::LeftButton);
|
||||
}
|
||||
|
||||
void move(QGraphicsView &view, const QPointF &ptScene)
|
||||
{
|
||||
pointerEvent(view, QEvent::MouseMove, ptScene, Qt::NoButton, Qt::LeftButton);
|
||||
}
|
||||
|
||||
void release(QGraphicsView &view, const QPointF &ptScene)
|
||||
{
|
||||
pointerEvent(view, QEvent::MouseButtonRelease, ptScene, Qt::LeftButton, Qt::NoButton);
|
||||
}
|
||||
|
||||
void showView(QGraphicsView &view)
|
||||
{
|
||||
view.resize(900, 650);
|
||||
view.setRenderHint(QPainter::Antialiasing);
|
||||
view.show();
|
||||
view.activateWindow();
|
||||
view.setFocus();
|
||||
QApplication::processEvents();
|
||||
}
|
||||
|
||||
void saveCanvas(tkrDiagramScene &diagramScene, const QString &strDirectory, const QString &strName)
|
||||
{
|
||||
if (strDirectory.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
QImage imageCanvas(700, 500, QImage::Format_ARGB32_Premultiplied);
|
||||
imageCanvas.fill(Qt::white);
|
||||
QPainter painter(&imageCanvas);
|
||||
painter.setRenderHint(QPainter::Antialiasing);
|
||||
diagramScene.render(&painter, QRectF(0, 0, 700, 500), QRectF(0, 0, 700, 500));
|
||||
painter.end();
|
||||
require(imageCanvas.save(strDirectory + QLatin1Char('/') + strName + QStringLiteral("-canvas.png")),
|
||||
"Cannot save drag canvas evidence");
|
||||
}
|
||||
|
||||
void checkMove(const QString &strDirectory, const QString &strInitial, const QString &strExpected,
|
||||
const QPointF &ptPress, const QPointF &ptOffset, const QString &strEvidenceDirectory)
|
||||
{
|
||||
const QByteArray baOriginal = readFile(corpusPath(strInitial));
|
||||
const QByteArray baExpected = readFile(corpusPath(strExpected));
|
||||
const QString strWorking = strDirectory + QLatin1Char('/') + strExpected + QStringLiteral(".tex");
|
||||
writeFile(strWorking, baOriginal);
|
||||
tkrTikzDocument document;
|
||||
tkrDiagramScene diagramScene;
|
||||
tkrEditorController controller(document, diagramScene);
|
||||
require(controller.openDocument(strWorking).bSucceeded, "Cannot open drag fixture");
|
||||
const quint64 uRevision = document.revision();
|
||||
int iChangeSignals = 0;
|
||||
QObject::connect(&controller, &tkrEditorController::documentChanged, [&iChangeSignals]() { ++iChangeSignals; });
|
||||
QGraphicsView view(&diagramScene);
|
||||
showView(view);
|
||||
press(view, ptPress);
|
||||
require(diagramScene.selectedItems().size() == 1, "Pointer press did not select element");
|
||||
move(view, ptPress + ptOffset / 2);
|
||||
move(view, ptPress + ptOffset);
|
||||
require(document.sourceBytes() == baOriginal && document.revision() == uRevision
|
||||
&& !document.hasUnsavedChanges() && iChangeSignals == 0, "Preview changed authoritative source");
|
||||
require(diagramScene.selectedItems().first()->pos() == ptOffset, "Preview did not track scene displacement");
|
||||
release(view, ptPress + ptOffset);
|
||||
require(document.sourceBytes() == baExpected && document.revision() == uRevision + 1
|
||||
&& document.hasUnsavedChanges() && iChangeSignals == 1, "Release did not make one minimal source update");
|
||||
require(readFile(strWorking) == baOriginal, "Release saved without an explicit save");
|
||||
require(controller.saveDocument().bSucceeded && !document.hasUnsavedChanges()
|
||||
&& readFile(strWorking) == baExpected, "Guarded save did not preserve expected bytes");
|
||||
require(controller.openDocument(strWorking).bSucceeded && document.sourceBytes() == baExpected
|
||||
&& !document.hasUnsavedChanges(), "Saved source did not reopen cleanly");
|
||||
saveCanvas(diagramScene, strEvidenceDirectory, strExpected);
|
||||
if (!strEvidenceDirectory.isEmpty()) {
|
||||
writeFile(strEvidenceDirectory + QLatin1Char('/') + strExpected + QStringLiteral(".tex"), readFile(strWorking));
|
||||
}
|
||||
}
|
||||
|
||||
void checkCancellationAndGuards(const QString &strDirectory)
|
||||
{
|
||||
const QByteArray baOriginal = readFile(corpusPath(QStringLiteral("boxes-initial")));
|
||||
const QString strWorking = strDirectory + QStringLiteral("/guards.tex");
|
||||
writeFile(strWorking, baOriginal);
|
||||
tkrTikzDocument document;
|
||||
tkrDiagramScene diagramScene;
|
||||
tkrEditorController controller(document, diagramScene);
|
||||
require(controller.openDocument(strWorking).bSucceeded, "Cannot open cancellation fixture");
|
||||
QGraphicsView view(&diagramScene);
|
||||
showView(view);
|
||||
const quint64 uRevision = document.revision();
|
||||
press(view, QPointF(450,250));
|
||||
move(view, QPointF(350,250));
|
||||
QKeyEvent eventEscape(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier);
|
||||
QApplication::sendEvent(&view, &eventEscape);
|
||||
release(view, QPointF(350,250));
|
||||
require(document.sourceBytes() == baOriginal && document.revision() == uRevision
|
||||
&& !document.hasUnsavedChanges(), "Escape/release changed source");
|
||||
for (QGraphicsItem *pItem : diagramScene.items()) {
|
||||
require(pItem->pos().isNull(), "Escape did not restore geometry");
|
||||
}
|
||||
press(view, QPointF(450,250));
|
||||
move(view, QPointF(350,250));
|
||||
QFocusEvent eventFocusOut(QEvent::FocusOut, Qt::ActiveWindowFocusReason);
|
||||
QApplication::sendEvent(&diagramScene, &eventFocusOut);
|
||||
release(view, QPointF(350,250));
|
||||
require(document.sourceBytes() == baOriginal && document.revision() == uRevision,
|
||||
"Focus loss committed a preview");
|
||||
press(view, QPointF(450,250));
|
||||
move(view, QPointF(350,250));
|
||||
require(controller.saveDocument().bSucceeded && readFile(strWorking) == baOriginal,
|
||||
"Save during preview wrote proposed geometry");
|
||||
release(view, QPointF(350,250));
|
||||
require(document.sourceBytes() == baOriginal, "Release after save cancellation committed");
|
||||
press(view, QPointF(450,250));
|
||||
release(view, QPointF(450,250));
|
||||
require(document.revision() == uRevision && !document.hasUnsavedChanges(), "Click-only selection dirtied source");
|
||||
press(view, QPointF(450,250));
|
||||
move(view, QPointF(-550,250));
|
||||
require(diagramScene.selectedItems().size() == 1
|
||||
&& diagramScene.sceneRect().contains(diagramScene.selectedItems().first()->sceneBoundingRect()),
|
||||
"Preview crossed the fixed editing boundary");
|
||||
release(view, QPointF(-550,250));
|
||||
require(document.sourceBytes() != baOriginal && document.revision() == uRevision + 1
|
||||
&& diagramScene.sceneRect().contains(diagramScene.selectedItems().first()->sceneBoundingRect()),
|
||||
"Out-of-extent release did not accept the constrained preview");
|
||||
writeFile(strWorking, baOriginal);
|
||||
require(controller.openDocument(strWorking).bSucceeded, "Cannot reset boundary fixture");
|
||||
controller.handleDragCommit({2, document.revision()-1, DragKind::WholeElement, {450,250}, {350,250}});
|
||||
controller.handleDragCommit({2, document.revision(), DragKind::FirstEndpoint, {450,250}, {350,250}});
|
||||
require(document.sourceBytes() == baOriginal, "Stale/unsupported drag mutated source");
|
||||
// Equivalent viewport gestures after scale and pan still mean -1 cm in source.
|
||||
view.scale(2, 2);
|
||||
view.horizontalScrollBar()->setValue(view.horizontalScrollBar()->value()+35);
|
||||
view.centerOn(350, 250);
|
||||
press(view, QPointF(450,250));
|
||||
move(view, QPointF(350,250));
|
||||
release(view, QPointF(350,250));
|
||||
require(document.sourceBytes() == readFile(corpusPath(QStringLiteral("boxes-touching"))),
|
||||
"View scale/pan altered source displacement");
|
||||
const QByteArray baExternal = baOriginal + "% external change\r\n";
|
||||
writeFile(strWorking, baExternal);
|
||||
require(!controller.saveDocument().bSucceeded && readFile(strWorking) == baExternal
|
||||
&& document.hasUnsavedChanges(), "Save overwrote an observed external change");
|
||||
}
|
||||
|
||||
void checkDecimalAndArrowDirections(const QString &strDirectory)
|
||||
{
|
||||
const QString strWorking = strDirectory + QStringLiteral("/precision.tex");
|
||||
const QByteArray baOriginal = QByteArray::fromHex("25c3a90d0a")
|
||||
+ "\\draw (+0.123456789012345678cm,-.5cm) rectangle (1.123456789012345678cm,+.5cm);\r\n";
|
||||
writeFile(strWorking, baOriginal);
|
||||
tkrTikzDocument document;
|
||||
tkrDiagramScene diagramScene;
|
||||
tkrEditorController controller(document, diagramScene);
|
||||
require(controller.openDocument(strWorking).bSucceeded, "Cannot open decimal fixture");
|
||||
controller.handleDragCommit({1, document.revision(), DragKind::WholeElement, {0,0}, {-50,-25}});
|
||||
const QByteArray baExpected = QByteArray::fromHex("25c3a90d0a")
|
||||
+ "\\draw (-0.376543210987654322cm,-0.25cm) rectangle (0.623456789012345678cm,0.75cm);\r\n";
|
||||
require(document.sourceBytes() == baExpected, "Translation lost decimal precision or unrelated bytes");
|
||||
for (int iElement = 1; iElement <= 2; ++iElement) {
|
||||
const QByteArray baArrows = readFile(corpusPath(QStringLiteral("arrow-initial")));
|
||||
writeFile(strWorking, baArrows);
|
||||
require(controller.openDocument(strWorking).bSucceeded, "Cannot open arrow-direction fixture");
|
||||
const QVector<ElementRecord> vecBefore = document.elements();
|
||||
const QPointF ptPress(300, iElement == 1 ? 400 : 100);
|
||||
QGraphicsView view(&diagramScene);
|
||||
showView(view);
|
||||
press(view, ptPress);
|
||||
move(view, ptPress + QPointF(50,-25));
|
||||
release(view, ptPress + QPointF(50,-25));
|
||||
require(document.hasUnsavedChanges(), "Backward/double arrow did not move");
|
||||
for (int iOther = 0; iOther < 3; ++iOther) {
|
||||
const ElementRecord &elementAfter = document.elements().at(iOther);
|
||||
const ElementRecord &elementBefore = vecBefore.at(iOther);
|
||||
const QPointF ptExpectedOffset = iOther == iElement ? QPointF(0.5,0.25) : QPointF();
|
||||
require(elementAfter.ptFirstTikzPosition == elementBefore.ptFirstTikzPosition + ptExpectedOffset
|
||||
&& elementAfter.ptSecondTikzPosition == elementBefore.ptSecondTikzPosition + ptExpectedOffset
|
||||
&& elementAfter.bArrowAtStart == elementBefore.bArrowAtStart
|
||||
&& elementAfter.bArrowAtEnd == elementBefore.bArrowAtEnd, "Arrow move changed direction or another element");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void checkWindowSave(const QString &strDirectory, const QString &strEvidenceDirectory)
|
||||
{
|
||||
const QString strWorking = strDirectory + QStringLiteral("/window.tex");
|
||||
writeFile(strWorking, readFile(corpusPath(QStringLiteral("boxes-initial"))));
|
||||
tkrMainWindow mainWindow(nullptr, strWorking);
|
||||
mainWindow.show();
|
||||
mainWindow.activateWindow();
|
||||
QApplication::processEvents();
|
||||
QGraphicsView *pView = mainWindow.findChild<QGraphicsView *>();
|
||||
require(pView, "Window canvas missing");
|
||||
const QRectF rectEditing = pView->scene()->sceneRect();
|
||||
const QPlainTextEdit *pSource = mainWindow.findChild<QPlainTextEdit *>();
|
||||
require(pSource, "Window source pane missing");
|
||||
const QString strOriginal = pSource->toPlainText();
|
||||
const auto checkFit = [&]() {
|
||||
const QRect rectViewport = pView->viewport()->rect();
|
||||
const QRect rectVisible = pView->mapFromScene(rectEditing).boundingRect();
|
||||
require(rectViewport.adjusted(12, 12, -12, -12).contains(rectVisible),
|
||||
"All editing edges should fit with a visible gutter");
|
||||
require((rectVisible.center() - rectViewport.center()).manhattanLength() <= 3
|
||||
&& qAbs(rectVisible.width() * rectEditing.height()
|
||||
- rectVisible.height() * rectEditing.width()) <= 2 * rectEditing.width(),
|
||||
"Fit should preserve the centered canvas and its aspect ratio");
|
||||
};
|
||||
mainWindow.resize(850, 480);
|
||||
QApplication::processEvents();
|
||||
checkFit();
|
||||
const qreal rSmallScale = pView->transform().m11();
|
||||
// Keep the same large editor area when the new sidebar occupies window space.
|
||||
const int iLargeEditorWindowWidth = 1450;
|
||||
const int iLargeEditorWindowHeight = 940;
|
||||
const auto *pSidebar = mainWindow.findChild<tkrWorkspaceSidebar *>();
|
||||
require(pSidebar != nullptr, "Window sidebar missing");
|
||||
mainWindow.resize(iLargeEditorWindowWidth + pSidebar->width(), iLargeEditorWindowHeight);
|
||||
QApplication::processEvents();
|
||||
checkFit();
|
||||
require(rSmallScale < 1.0 && pView->transform().m11() > 1.0
|
||||
&& pView->scene()->sceneRect() == rectEditing
|
||||
&& pSource->toPlainText() == strOriginal && !mainWindow.isWindowModified(),
|
||||
"Fitting should scale both ways without changing the source or editing bounds");
|
||||
|
||||
// Use an exact 1:1 transform for the existing byte-for-byte move fixture.
|
||||
// Integer pointer pixels at the fitted scale can land between scene units.
|
||||
pView->resetTransform();
|
||||
pView->centerOn(rectEditing.center());
|
||||
press(*pView, QPointF(450,250));
|
||||
move(*pView, QPointF(350,250));
|
||||
release(*pView, QPointF(350,250));
|
||||
require(mainWindow.isWindowModified(), "Window did not show unsaved edit");
|
||||
require(pSource && pSource->toPlainText().contains(QStringLiteral("(1cm,0cm) rectangle (2cm,1cm)")),
|
||||
"Window source pane did not update on release");
|
||||
if (!strEvidenceDirectory.isEmpty()) {
|
||||
require(mainWindow.grab().save(strEvidenceDirectory + QStringLiteral("/drag-contact-window.png")),
|
||||
"Cannot save window drag evidence");
|
||||
}
|
||||
QAction *pSaveAction = nullptr;
|
||||
for (QAction *pAction : mainWindow.findChildren<QAction *>()) {
|
||||
if (pAction->shortcut() == QKeySequence(QKeySequence::Save)) {
|
||||
pSaveAction = pAction;
|
||||
}
|
||||
}
|
||||
require(pSaveAction && pSaveAction->isEnabled(), "Move did not enable Save");
|
||||
pSaveAction->trigger();
|
||||
require(!mainWindow.isWindowModified() && !pSaveAction->isEnabled()
|
||||
&& readFile(strWorking) == readFile(corpusPath(QStringLiteral("boxes-touching"))),
|
||||
"Window Save action did not persist edit and clear dirty state");
|
||||
mainWindow.close();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int iArgumentCount, char *pArguments[])
|
||||
{
|
||||
QApplication application(iArgumentCount, pArguments);
|
||||
#ifdef Q_OS_WIN
|
||||
const int iFontId = QFontDatabase::addApplicationFont(qEnvironmentVariable("SystemRoot") + QStringLiteral("/Fonts/segoeui.ttf"));
|
||||
if (iFontId >= 0) {
|
||||
QApplication::setFont(QFont(QFontDatabase::applicationFontFamilies(iFontId).first(), 9));
|
||||
}
|
||||
#endif
|
||||
require(QDir().mkpath(QStringLiteral(TKR_TEST_WORK_DIRECTORY)), "Cannot create task-local test directory");
|
||||
QTemporaryDir directoryWork(QStringLiteral(TKR_TEST_WORK_DIRECTORY "/drag-XXXXXX"));
|
||||
require(directoryWork.isValid(), "Cannot create isolated drag fixtures");
|
||||
const QString strEvidenceDirectory = iArgumentCount > 1 ? QString::fromLocal8Bit(pArguments[1]) : QString();
|
||||
checkMove(directoryWork.path(), QStringLiteral("boxes-initial"), QStringLiteral("boxes-touching"),
|
||||
{450,250}, {-100,0}, strEvidenceDirectory);
|
||||
checkMove(directoryWork.path(), QStringLiteral("line-initial"), QStringLiteral("line-translated"),
|
||||
{200,300}, {50,-50}, strEvidenceDirectory);
|
||||
checkMove(directoryWork.path(), QStringLiteral("arrow-initial"), QStringLiteral("arrow-translated"),
|
||||
{300,250}, {50,-50}, strEvidenceDirectory);
|
||||
checkCancellationAndGuards(directoryWork.path());
|
||||
checkDecimalAndArrowDirections(directoryWork.path());
|
||||
checkWindowSave(directoryWork.path(), strEvidenceDirectory);
|
||||
qInfo("Whole-element pointer drag, cancellation, source updates, save/reopen and guarded-save checks passed.");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
#include "controller/tkrEditorController.h"
|
||||
#include "model/tkrTikzDocument.h"
|
||||
#include "ui/tkrDiagramScene.h"
|
||||
#include "ui/tkrMainWindow.h"
|
||||
#include <QAction>
|
||||
#include <QApplication>
|
||||
#include <QFile>
|
||||
#include <QGraphicsView>
|
||||
#include <QKeyEvent>
|
||||
#include <QMouseEvent>
|
||||
#include <QPlainTextEdit>
|
||||
#include <QStatusBar>
|
||||
#include <QTemporaryDir>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
using namespace TikzRefinery;
|
||||
namespace {
|
||||
constexpr quint64 uOneRevision = 1;
|
||||
constexpr quint64 uFirstElement = 1;
|
||||
constexpr int iNoNotifications = 0;
|
||||
constexpr int iOneNotification = 1;
|
||||
constexpr int iLongSessionEdits = 150;
|
||||
constexpr qreal rMoveSceneUnits = 50;
|
||||
const QByteArray baFixture = QByteArray::fromHex("efbbbf") +
|
||||
"% UTF-8 caf\xc3\xa9; exact CRLF and numeric spelling\r\n"
|
||||
"\\path[use as bounding box] (-2cm,-2cm) rectangle (8cm,6cm);\r\n"
|
||||
"\\draw (+0.00cm,0cm) rectangle (2cm,1cm); % preserved\r\n"
|
||||
"\\draw[->] (3cm,0cm) -- (4cm,1cm);\r\n";
|
||||
void require(bool bCondition, const char *pMessage)
|
||||
{ if (!bCondition) { std::fprintf(stderr, "%s\n", pMessage); std::exit(EXIT_FAILURE); } }
|
||||
void write(const QString &strPath, const QByteArray &baSource)
|
||||
{
|
||||
QFile file(strPath);
|
||||
require(file.open(QIODevice::WriteOnly) && file.write(baSource) == baSource.size(), "Fixture write failed");
|
||||
}
|
||||
QByteArray read(const QString &strPath)
|
||||
{ QFile file(strPath); require(file.open(QIODevice::ReadOnly), "Fixture read failed"); return file.readAll(); }
|
||||
void move(tkrEditorController &controller, const tkrTikzDocument &document)
|
||||
{ controller.handleDragCommit({uFirstElement, document.revision(), DragKind::WholeElement, {}, {rMoveSceneUnits, 0}}); }
|
||||
void pointer(QGraphicsView &view, QEvent::Type type, const QPointF &ptScene)
|
||||
{
|
||||
const QPoint ptPixel = view.mapFromScene(ptScene);
|
||||
QMouseEvent event(type, QPointF(ptPixel), QPointF(view.viewport()->mapToGlobal(ptPixel)),
|
||||
type == QEvent::MouseMove ? Qt::NoButton : Qt::LeftButton,
|
||||
type == QEvent::MouseButtonRelease ? Qt::NoButton : Qt::LeftButton, Qt::NoModifier);
|
||||
QApplication::sendEvent(view.viewport(), &event);
|
||||
QApplication::processEvents();
|
||||
}
|
||||
void checkSession(const QString &strPath)
|
||||
{
|
||||
write(strPath, baFixture);
|
||||
tkrTikzDocument document; tkrDiagramScene scene; tkrEditorController controller(document, scene);
|
||||
require(controller.openDocument(strPath).bSucceeded && scene.shapeProvider(), "Plugin-backed open failed");
|
||||
int iNotifications = iNoNotifications;
|
||||
QObject::connect(&controller, &tkrEditorController::documentChanged, [&]() { ++iNotifications; });
|
||||
const quint64 uOpenedRevision = document.revision();
|
||||
move(controller, document);
|
||||
const QByteArray baMoved = document.sourceBytes();
|
||||
require(baMoved != baFixture && document.canUndo() && !document.canRedo(), "Move did not record history");
|
||||
require(iNotifications == iOneNotification && document.revision() == uOpenedRevision + uOneRevision,
|
||||
"Move must publish once");
|
||||
require(controller.saveDocument().bSucceeded && !document.hasUnsavedChanges() && document.canUndo(), "Save erased history");
|
||||
const quint64 uBeforeUndo = document.revision();
|
||||
iNotifications = iNoNotifications;
|
||||
require(controller.undo().bSucceeded, "Undo failed");
|
||||
require(document.sourceBytes() == baFixture && document.hasUnsavedChanges() && document.canRedo()
|
||||
&& !document.canUndo() && document.revision() == uBeforeUndo + uOneRevision
|
||||
&& iNotifications == iOneNotification, "Undo did not restore exact bytes or advance revision");
|
||||
require(read(strPath) == baMoved, "Undo wrote to disk");
|
||||
require(document.elements().first().ptFirstTikzPosition == QPointF(0, 0), "Undo did not refresh geometry");
|
||||
// No-op, cancellation and stale rejection must preserve the redo branch.
|
||||
controller.handleDragCommit({uFirstElement, document.revision(), DragKind::WholeElement, {}, {}});
|
||||
controller.handleDragPreview({uFirstElement, document.revision(), DragKind::WholeElement, {}, {rMoveSceneUnits, 0}});
|
||||
controller.cancelDrag();
|
||||
controller.handleDragCommit({uFirstElement, uOpenedRevision, DragKind::WholeElement, {}, {rMoveSceneUnits, 0}});
|
||||
require(document.sourceBytes() == baFixture && document.canRedo() && iNotifications == iOneNotification,
|
||||
"Unchanged/cancelled/rejected edit changed history");
|
||||
require(controller.redo().bSucceeded && document.sourceBytes() == baMoved
|
||||
&& !document.hasUnsavedChanges(), "Redo failed to return to saved baseline");
|
||||
controller.handleDragCommit({uFirstElement, document.revision(), DragKind::RectangleSecondSecond, {}, {rMoveSceneUnits, 0}});
|
||||
const QByteArray baResized = document.sourceBytes();
|
||||
require(baResized != baMoved && document.undoDescription().contains(QStringLiteral("Resize")), "Resize not recorded separately");
|
||||
require(controller.undo().bSucceeded && document.sourceBytes() == baMoved, "Resize undo failed");
|
||||
require(controller.undo().bSucceeded && document.sourceBytes() == baFixture, "Move undo failed");
|
||||
require(controller.redo().bSucceeded && controller.redo().bSucceeded && document.sourceBytes() == baResized,
|
||||
"Multiple redo failed");
|
||||
require(controller.undo().bSucceeded, "Branch undo failed");
|
||||
move(controller, document);
|
||||
require(!document.canRedo(), "Changed edit retained abandoned redo branch");
|
||||
const QByteArray baBranch = document.sourceBytes();
|
||||
write(strPath, baFixture); // External changes cause save failure, without resetting baseline/history.
|
||||
require(!controller.saveDocument().bSucceeded && document.sourceBytes() == baBranch && document.canUndo()
|
||||
&& document.hasUnsavedChanges(), "Failed save altered document/history");
|
||||
require(!controller.openDocument(strPath + QStringLiteral(".missing")).bSucceeded
|
||||
&& document.sourceBytes() == baBranch && document.canUndo(), "Failed open erased history");
|
||||
require(controller.openDocument(strPath).bSucceeded && !document.canUndo() && !document.canRedo()
|
||||
&& !document.hasUnsavedChanges(), "Successful reload retained history");
|
||||
}
|
||||
void checkFailureAndLongSession(const QString &strPath)
|
||||
{
|
||||
write(strPath, baFixture);
|
||||
tkrTikzDocument document; tkrDiagramScene scene; tkrEditorController controller(document, scene);
|
||||
controller.openDocument(strPath);
|
||||
const qsizetype nStart = document.sourceBytes().indexOf("+0.00");
|
||||
constexpr qsizetype nCoordinateLength = 5;
|
||||
require(document.applyCoordinateEdits({{{nStart, nCoordinateLength}, "+0.00", "invalid", document.revision()}}).bSucceeded,
|
||||
"Cannot arrange restoration failure");
|
||||
require(controller.undo().bSucceeded, "Cannot restore valid source");
|
||||
const quint64 uRevision = document.revision();
|
||||
require(!controller.redo().bSucceeded && document.sourceBytes() == baFixture && document.canRedo()
|
||||
&& document.revision() == uRevision, "Failed restoration changed cursor/source/revision");
|
||||
// Model-only exact snapshots exercise a longer session with no automatic eviction.
|
||||
tkrTikzDocument longDocument;
|
||||
longDocument.loadSource("0", {});
|
||||
constexpr qsizetype nStartOfSource = 0;
|
||||
for (int iEdit = 0; iEdit < iLongSessionEdits; ++iEdit) {
|
||||
const QByteArray baNext = QByteArray::number(iEdit + iOneNotification);
|
||||
const QByteArray baCurrent = longDocument.sourceBytes();
|
||||
require(longDocument.applyCoordinateEdits({{{nStartOfSource, baCurrent.size()}, baCurrent, baNext,
|
||||
longDocument.revision()}}).bSucceeded, "Long-session edit failed");
|
||||
}
|
||||
for (int iEdit = 0; iEdit < iLongSessionEdits; ++iEdit)
|
||||
require(longDocument.restoreHistory(false).bSucceeded, "History was evicted");
|
||||
require(longDocument.sourceBytes() == "0" && !longDocument.canUndo(), "Long-session restoration failed");
|
||||
}
|
||||
void checkWindowAndActiveGesture(const QString &strPath)
|
||||
{
|
||||
write(strPath, baFixture);
|
||||
tkrMainWindow window(nullptr, strPath); window.show(); QApplication::processEvents();
|
||||
auto *pUndo = window.findChild<QAction *>(QStringLiteral("undoAction"));
|
||||
auto *pRedo = window.findChild<QAction *>(QStringLiteral("redoAction"));
|
||||
auto *pView = window.findChild<QGraphicsView *>();
|
||||
auto *pSource = window.findChild<QPlainTextEdit *>();
|
||||
require(pUndo && pRedo && pView && pSource && !pUndo->isEnabled() && !pRedo->isEnabled(), "History controls missing");
|
||||
window.activateWindow(); pView->setFocus(); QApplication::processEvents();
|
||||
require(pUndo->shortcuts().contains(QKeySequence(Qt::CTRL | Qt::Key_Z))
|
||||
&& pRedo->shortcuts().contains(QKeySequence(Qt::CTRL | Qt::Key_Y)), "Windows history shortcuts missing");
|
||||
tkrCoordinateMapper mapper;
|
||||
const QPointF ptInitial = mapper.mapToScene({0, 0.5});
|
||||
const QPointF ptMoved = ptInitial + QPointF(rMoveSceneUnits, 0);
|
||||
const QPointF ptPreview = ptMoved + QPointF(rMoveSceneUnits, 0);
|
||||
pointer(*pView, QEvent::MouseButtonPress, ptInitial);
|
||||
pointer(*pView, QEvent::MouseMove, ptMoved);
|
||||
pointer(*pView, QEvent::MouseButtonRelease, ptMoved);
|
||||
if (!pUndo->isEnabled()) std::fprintf(stderr, "Status: %s; source: %s\n",
|
||||
qPrintable(window.statusBar()->currentMessage()), qPrintable(pSource->toPlainText()));
|
||||
require(pUndo->isEnabled() && window.isWindowModified(), "Pointer edit did not enable Undo");
|
||||
const QString strMoved = pSource->toPlainText();
|
||||
// Undo while mouse is held must cancel preview, then undo the completed edit.
|
||||
pointer(*pView, QEvent::MouseButtonPress, ptMoved);
|
||||
pointer(*pView, QEvent::MouseMove, ptPreview);
|
||||
pUndo->trigger();
|
||||
pointer(*pView, QEvent::MouseButtonRelease, ptPreview);
|
||||
require(!pUndo->isEnabled() && pRedo->isEnabled() && !window.isWindowModified(), "Undo during gesture committed preview");
|
||||
require(pSource->toPlainText() != strMoved, "Source pane did not follow Undo");
|
||||
pRedo->trigger();
|
||||
require(pSource->toPlainText() == strMoved && pUndo->isEnabled() && !pRedo->isEnabled(), "Redo source/UI mismatch");
|
||||
pUndo->trigger(); window.close();
|
||||
}
|
||||
}
|
||||
int main(int iArgumentCount, char **ppArguments)
|
||||
{
|
||||
QApplication application(iArgumentCount, ppArguments);
|
||||
QTemporaryDir directory; require(directory.isValid(), "No test directory");
|
||||
const QString strPath = directory.filePath(QStringLiteral("history.tex"));
|
||||
checkSession(strPath); checkFailureAndLongSession(strPath); checkWindowAndActiveGesture(strPath);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
#include "BuildInfo.h"
|
||||
#include "controller/tkrEditorController.h"
|
||||
#include "editing/tkrEditService.h"
|
||||
#include "model/tkrTikzDocument.h"
|
||||
#include "plugins/ShapeProviderAdapter.h"
|
||||
#include "plugins/tkrShapePluginStore.h"
|
||||
#include "ui/tkrDiagramScene.h"
|
||||
#include "ui/tkrMainWindow.h"
|
||||
|
||||
#include <QAction>
|
||||
#include <QApplication>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QMenuBar>
|
||||
#include <QMessageBox>
|
||||
#include <QRegularExpression>
|
||||
#include <QTemporaryDir>
|
||||
#include <QTimer>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <limits>
|
||||
|
||||
using namespace TikzRefinery;
|
||||
namespace {
|
||||
constexpr int iInvalidSchema = 99;
|
||||
constexpr int iInvalidOutcome = 77;
|
||||
constexpr int iNextEventLoopTurn = 0;
|
||||
constexpr qsizetype nCornerCount = 4;
|
||||
constexpr qreal rOutsideBoundsCentimeters = 100;
|
||||
const QByteArray baRectangle = "\\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);\r\n"
|
||||
"\\draw[line width=0.6pt] (2cm,0cm) rectangle (3cm,1cm); % preserve me\r\n";
|
||||
|
||||
void require(bool bCondition, const char *pMessage)
|
||||
{
|
||||
if (!bCondition) { std::fprintf(stderr, "%s\n", pMessage); std::abort(); }
|
||||
}
|
||||
|
||||
ShapeApi::OperationRequest requestFor(const ShapeApi::ElementDescription &description)
|
||||
{
|
||||
ShapeApi::OperationRequest request;
|
||||
request.initial = description;
|
||||
request.documentId = description.documentId;
|
||||
request.uElementId = description.uElementId;
|
||||
request.uRevision = description.uRevision;
|
||||
request.strOperationId = ShapeApi::strMoveOperation;
|
||||
return request;
|
||||
}
|
||||
|
||||
void checkLoadedProvider()
|
||||
{
|
||||
tkrShapePluginStore store;
|
||||
require(store.loadResult().bSucceeded && store.provider(), "Real rectangle module did not load");
|
||||
require(QFileInfo(store.modulePath()).canonicalFilePath() == QFileInfo(QString::fromUtf8(TKR_RECTANGLE_PLUGIN_PATH)).canonicalFilePath(),
|
||||
"Host loaded an unexpected module");
|
||||
require(!store.runtimeIdentity().isEmpty() && store.description().contains(QStringLiteral("Rectangle")), "Missing provider binding identity");
|
||||
ShapeApi::ElementDescription description;
|
||||
description.documentId = QUuid::createUuid();
|
||||
description.uElementId = 7;
|
||||
description.uRevision = 9;
|
||||
description.ptFirstCentimeters = {2, 0};
|
||||
description.ptSecondCentimeters = {3, 1};
|
||||
description.rLineWidthPoints = 0.6;
|
||||
const tkrShapeProvider &provider = *store.provider();
|
||||
require(provider.availableOperations(description).contains(ShapeApi::strResizeOperation), "Resize capability unavailable");
|
||||
const auto presentation = provider.describePresentation(description);
|
||||
require(presentation.bAvailable && presentation.rectOutlineCentimeters == QRectF(2, 0, 1, 1)
|
||||
&& presentation.rectSelectionCentimeters == presentation.rectOutlineCentimeters
|
||||
&& presentation.vecHandles.size() == nCornerCount, "Provider did not supply rectangle display/selection/handles");
|
||||
require(presentation.vecHandles.first().ptPositionCentimeters == QPointF(2, 0)
|
||||
&& presentation.vecHandles.last().ptPositionCentimeters == QPointF(3, 1), "Handle geometry mismatch");
|
||||
auto request = requestFor(description);
|
||||
require(provider.prepareOperation(request).outcome == ShapeApi::PreparationOutcome::Unchanged, "Zero move is not unchanged");
|
||||
request.ptTotalDisplacementCentimeters = {1.25, -0.5};
|
||||
auto prepared = provider.prepareOperation(request);
|
||||
require(prepared.outcome == ShapeApi::PreparationOutcome::PreparedChange
|
||||
&& prepared.proposed.ptFirstCentimeters == QPointF(3.25, -0.5)
|
||||
&& prepared.proposed.ptSecondCentimeters == QPointF(4.25, 0.5), "Loaded module move calculation mismatch");
|
||||
request.strOperationId = ShapeApi::strResizeOperation;
|
||||
request.handleId = ShapeApi::HandleId::SecondSecond;
|
||||
request.ptTotalDisplacementCentimeters = {1, 1};
|
||||
prepared = provider.prepareOperation(request);
|
||||
require(prepared.outcome == ShapeApi::PreparationOutcome::PreparedChange
|
||||
&& prepared.proposed.ptFirstCentimeters == QPointF(2, 0)
|
||||
&& prepared.proposed.ptSecondCentimeters == QPointF(4, 2), "Loaded module resize calculation mismatch");
|
||||
request.iParameterSchemaVersion = iInvalidSchema;
|
||||
require(provider.prepareOperation(request).outcome == ShapeApi::PreparationOutcome::CannotPrepare, "Unknown parameter schema accepted");
|
||||
request = requestFor(description); ++request.uRevision;
|
||||
require(provider.prepareOperation(request).outcome == ShapeApi::PreparationOutcome::CannotPrepare, "Stale target accepted");
|
||||
request = requestFor(description); request.strOperationId = QStringLiteral("unknown.move");
|
||||
require(provider.prepareOperation(request).outcome == ShapeApi::PreparationOutcome::CannotPrepare, "Unknown operation accepted");
|
||||
request = requestFor(description); request.ptTotalDisplacementCentimeters.setX(std::numeric_limits<qreal>::infinity());
|
||||
require(provider.prepareOperation(request).outcome == ShapeApi::PreparationOutcome::CannotPrepare, "Infinite displacement accepted");
|
||||
request = requestFor(description); request.constraints.rMinimumWidthCentimeters = 0;
|
||||
require(provider.prepareOperation(request).outcome == ShapeApi::PreparationOutcome::CannotPrepare, "Invalid constraints accepted");
|
||||
auto overflowDescription = description;
|
||||
overflowDescription.ptFirstCentimeters.setX(-std::numeric_limits<qreal>::max());
|
||||
overflowDescription.ptSecondCentimeters.setX(std::numeric_limits<qreal>::max());
|
||||
require(provider.availableOperations(overflowDescription).isEmpty()
|
||||
&& !provider.describePresentation(overflowDescription).bAvailable, "Overflowing rectangle span accepted");
|
||||
description.iSchemaVersion = iInvalidSchema;
|
||||
require(provider.availableOperations(description).isEmpty() && !provider.describePresentation(description).bAvailable,
|
||||
"Unsupported element schema guessed");
|
||||
}
|
||||
|
||||
void checkUnavailableModule(const QString &strModulePath, const QString &strSourcePath)
|
||||
{
|
||||
QFile file(strSourcePath);
|
||||
require(file.open(QIODevice::WriteOnly) && file.write(baRectangle) == baRectangle.size(), "Cannot write fixture");
|
||||
file.close();
|
||||
tkrTikzDocument document;
|
||||
tkrDiagramScene scene(nullptr, strModulePath);
|
||||
tkrEditorController controller(document, scene);
|
||||
const auto opened = controller.openDocument(strSourcePath);
|
||||
require(opened.bSucceeded && opened.strMessage.contains(QStringLiteral("incompatible"))
|
||||
&& !scene.shapeProvider() && scene.items().isEmpty() && document.elements().isEmpty()
|
||||
&& document.sourceBytes() == baRectangle && !document.hasUnsavedChanges(),
|
||||
"Missing/incompatible plugin used fallback or lost source");
|
||||
controller.handleDragCommit({1, document.revision(), DragKind::WholeElement, {}, {100, 0}});
|
||||
require(document.sourceBytes() == baRectangle && !document.hasUnsavedChanges(), "Unavailable provider edited source");
|
||||
require(file.open(QIODevice::WriteOnly), "Cannot replace temporary fixture");
|
||||
file.write("\\draw (0cm,0cm) -- (1cm,1cm);\n"); file.close();
|
||||
require(controller.openDocument(strSourcePath).bSucceeded && scene.items().size() == 1,
|
||||
"Missing rectangle provider disabled the built-in segment route");
|
||||
}
|
||||
|
||||
enum class Fault { Identity, Bounds, Outcome, Appearance, Unchanged, FixedCorner, MoveScaling };
|
||||
class tkrInvalidShapeProvider final : public tkrShapeProvider
|
||||
{
|
||||
public:
|
||||
explicit tkrInvalidShapeProvider(Fault fault) : m_fault(fault) {}
|
||||
QStringList availableOperations(const ShapeApi::ElementDescription &) const override
|
||||
{ return {ShapeApi::strMoveOperation, ShapeApi::strResizeOperation}; }
|
||||
ShapeApi::PresentationDescription describePresentation(const ShapeApi::ElementDescription &) const override { return {}; }
|
||||
ShapeApi::PreparationResult prepareOperation(const ShapeApi::OperationRequest &request) const override
|
||||
{
|
||||
ShapeApi::PreparationResult result{ShapeApi::PreparationOutcome::PreparedChange, request.initial, {}};
|
||||
result.proposed.ptSecondCentimeters += QPointF(1, 1);
|
||||
switch (m_fault) {
|
||||
case Fault::Identity: ++result.proposed.uRevision; break;
|
||||
case Fault::Bounds: result.proposed.ptSecondCentimeters.setX(rOutsideBoundsCentimeters); break;
|
||||
case Fault::Outcome: result.outcome = static_cast<ShapeApi::PreparationOutcome>(iInvalidOutcome); break;
|
||||
case Fault::Appearance: result.proposed.strStrokeColor = QStringLiteral("red"); break;
|
||||
case Fault::Unchanged: result.outcome = ShapeApi::PreparationOutcome::Unchanged; break;
|
||||
case Fault::FixedCorner: result.proposed.ptFirstCentimeters += QPointF(1, 1); break;
|
||||
case Fault::MoveScaling: break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private:
|
||||
Fault m_fault;
|
||||
};
|
||||
|
||||
void checkHostAcceptance()
|
||||
{
|
||||
ElementRecord element;
|
||||
element.documentId = QUuid::createUuid(); element.uElementId = 1; element.uDocumentRevision = 1;
|
||||
element.elementKind = ElementKind::Rectangle; element.ptFirstTikzPosition = {0, 0}; element.ptSecondTikzPosition = {1, 1};
|
||||
const ComparisonExtent extent{true, {-2, -2}, {5, 3}};
|
||||
tkrEditService service; tkrCoordinateMapper mapper;
|
||||
DragUpdate drag{1, 1, DragKind::RectangleSecondSecond, {}, {100, -100}};
|
||||
const Fault faults[] = {Fault::Identity, Fault::Bounds, Fault::Outcome, Fault::Appearance,
|
||||
Fault::Unchanged, Fault::FixedCorner, Fault::MoveScaling};
|
||||
for (Fault fault : faults) {
|
||||
tkrInvalidShapeProvider provider(fault);
|
||||
drag.dragKind = fault == Fault::MoveScaling ? DragKind::WholeElement : DragKind::RectangleSecondSecond;
|
||||
require(!service.prepareGeometry(element, drag, mapper, extent, &provider).result.bSucceeded,
|
||||
"Host accepted an invalid provider proposal");
|
||||
}
|
||||
require(!service.prepareGeometry(element, drag, mapper, extent).result.bSucceeded, "Host has a hidden rectangle implementation");
|
||||
}
|
||||
|
||||
void checkBuildIdentity()
|
||||
{
|
||||
tkrMainWindow window;
|
||||
const QString strVersion = QString::fromLatin1(BuildInfo::pVersion);
|
||||
const QRegularExpression expressionVersion(QStringLiteral(R"(^0\.[0-9]+\.[0-9]+-alpha$)"));
|
||||
require(expressionVersion.match(strVersion).hasMatch() && window.windowTitle().contains(strVersion)
|
||||
&& !window.windowTitle().contains(QString::fromLatin1(BuildInfo::pShortCheckpoint)), "Normal title/build version mismatch");
|
||||
QAction *pAbout = nullptr;
|
||||
for (QAction *pAction : window.findChildren<QAction *>())
|
||||
if (pAction->text().contains(QStringLiteral("About TikZRefinery"))) pAbout = pAction;
|
||||
require(pAbout, "About action missing");
|
||||
QString strAbout;
|
||||
QTimer::singleShot(iNextEventLoopTurn, [&] {
|
||||
auto *pDialog = qobject_cast<QMessageBox *>(QApplication::activeModalWidget());
|
||||
if (pDialog) { strAbout = pDialog->text(); pDialog->accept(); }
|
||||
});
|
||||
pAbout->trigger();
|
||||
require(strAbout.contains(strVersion) && strAbout.contains(QString::fromLatin1(BuildInfo::pShortCheckpoint))
|
||||
&& strAbout.contains(QString::fromLatin1(BuildInfo::pCheckpoint))
|
||||
&& strAbout.contains(QString::fromLatin1(BuildInfo::pSourceState))
|
||||
&& strAbout.contains(QStringLiteral("TikZRefinery Rectangle")), "About omitted source/provider identity");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int iArgumentCount, char **pArguments)
|
||||
{
|
||||
QApplication application(iArgumentCount, pArguments);
|
||||
QTemporaryDir directory; require(directory.isValid(), "Temporary directory unavailable");
|
||||
checkLoadedProvider();
|
||||
checkUnavailableModule(directory.filePath(QStringLiteral("missing.dll")), directory.filePath(QStringLiteral("missing.tex")));
|
||||
checkUnavailableModule(QString::fromUtf8(TKR_INCOMPATIBLE_PLUGIN_PATH), directory.filePath(QStringLiteral("incompatible.tex")));
|
||||
checkHostAcceptance();
|
||||
checkBuildIdentity();
|
||||
std::puts("Loaded DLL presentation/handles/move/resize, schemas/outcomes, unavailable modules, host validation and About identity passed.");
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
#include "controller/tkrEditorController.h"
|
||||
#include "model/tkrTikzDocument.h"
|
||||
#include "ui/tkrDiagramScene.h"
|
||||
#include "ui/tkrMainWindow.h"
|
||||
|
||||
#include <QAction>
|
||||
#include <QApplication>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QGraphicsRectItem>
|
||||
#include <QGraphicsView>
|
||||
#include <QFileDialog>
|
||||
#include <QFontDatabase>
|
||||
#include <QImage>
|
||||
#include <QPainter>
|
||||
#include <QPlainTextEdit>
|
||||
#include <QStatusBar>
|
||||
#include <QTimer>
|
||||
#include <cmath>
|
||||
|
||||
using namespace TikzRefinery;
|
||||
|
||||
namespace {
|
||||
|
||||
void require(bool bCondition, const char *pMessage)
|
||||
{
|
||||
if (!bCondition) {
|
||||
qFatal("%s", pMessage);
|
||||
}
|
||||
}
|
||||
|
||||
QByteArray readCorpus(const QString &strName)
|
||||
{
|
||||
QFile fileSource(QStringLiteral(TKR_CORPUS_DIRECTORY) + QLatin1Char('/') + strName);
|
||||
require(fileSource.open(QIODevice::ReadOnly), "Cannot open corpus fixture");
|
||||
const QByteArray baSource = fileSource.readAll();
|
||||
require(fileSource.error() == QFileDevice::NoError, "Cannot read corpus fixture");
|
||||
return baSource;
|
||||
}
|
||||
|
||||
void checkCorpus(const QString &strName, qreal rRightFirstX, const QString &strEvidenceDirectory)
|
||||
{
|
||||
const QString strPath = QStringLiteral(TKR_CORPUS_DIRECTORY) + QLatin1Char('/') + strName;
|
||||
const QByteArray baSource = readCorpus(strName);
|
||||
tkrTikzDocument document;
|
||||
tkrDiagramScene diagramScene;
|
||||
tkrEditorController controller(document, diagramScene);
|
||||
QString strStatus;
|
||||
QObject::connect(&controller, &tkrEditorController::statusChanged,
|
||||
[&strStatus](const QString &strMessage) { strStatus = strMessage; });
|
||||
require(controller.openDocument(strPath).bSucceeded, "Corpus open failed");
|
||||
require(document.sourceBytes() == baSource && !document.hasUnsavedChanges(), "Open altered bytes");
|
||||
require(document.elements().size() == 2 && diagramScene.items().size() == 2,
|
||||
"Expected exactly two rectangles; bounding path must not become an item");
|
||||
require(strStatus.contains(QStringLiteral("Displayed 2 element(s)"))
|
||||
&& strStatus.contains(QStringLiteral("drag a corner to resize")), "Display status is misleading");
|
||||
require(diagramScene.sceneRect() == QRectF(0, 0, 700, 500), "Fixed comparison extent changed");
|
||||
for (int iElement = 0; iElement < 2; ++iElement) {
|
||||
const ElementRecord &elementRecord = document.elements().at(iElement);
|
||||
const qreal rFirstX = iElement == 0 ? 0.0 : rRightFirstX;
|
||||
require(elementRecord.elementKind == ElementKind::Rectangle
|
||||
&& elementRecord.uElementId == static_cast<quint64>(iElement + 1)
|
||||
&& elementRecord.uDocumentRevision == document.revision(), "Element identity mismatch");
|
||||
require(elementRecord.ptFirstTikzPosition == QPointF(rFirstX, 0)
|
||||
&& elementRecord.ptSecondTikzPosition == QPointF(rFirstX + 1, 1), "Corpus geometry mismatch");
|
||||
const SourceRange rangesCoordinates[] = {elementRecord.rangeFirstX, elementRecord.rangeFirstY,
|
||||
elementRecord.rangeSecondX, elementRecord.rangeSecondY};
|
||||
const qreal rExpected[] = {rFirstX, 0, rFirstX + 1, 1};
|
||||
for (int iCoordinate = 0; iCoordinate < 4; ++iCoordinate) {
|
||||
const SourceRange &rangeSource = rangesCoordinates[iCoordinate];
|
||||
bool bConverted = false;
|
||||
const qreal rActual = baSource.mid(rangeSource.nStart, rangeSource.nLength).toDouble(&bConverted);
|
||||
require(bConverted && rActual == rExpected[iCoordinate], "Numeric byte range mismatch");
|
||||
}
|
||||
QGraphicsRectItem *pRectangle = nullptr;
|
||||
for (QGraphicsItem *pItem : diagramScene.items()) {
|
||||
if (pItem->data(0).toULongLong() == elementRecord.uElementId) {
|
||||
pRectangle = qgraphicsitem_cast<QGraphicsRectItem *>(pItem);
|
||||
}
|
||||
}
|
||||
require(pRectangle && pRectangle->rect() == QRectF(200 + 100 * rFirstX, 200, 100, 100),
|
||||
"Scene rectangle origin/size mismatch");
|
||||
require(std::abs(pRectangle->pen().widthF() - 0.6 * 100 * 2.54 / 72.27) < 1e-10,
|
||||
"TeX point width mismatch");
|
||||
require(!pRectangle->pen().isCosmetic() && pRectangle->brush().style() == Qt::NoBrush,
|
||||
"Rectangle appearance mismatch");
|
||||
require(!pRectangle->flags().testFlag(QGraphicsItem::ItemIsMovable)
|
||||
&& pRectangle->flags().testFlag(QGraphicsItem::ItemIsSelectable), "Selection/scene-controlled movement mismatch");
|
||||
}
|
||||
if (!strEvidenceDirectory.isEmpty()) {
|
||||
QImage imageCanvas(700, 500, QImage::Format_ARGB32_Premultiplied);
|
||||
imageCanvas.fill(Qt::white);
|
||||
QPainter painter(&imageCanvas);
|
||||
painter.setRenderHint(QPainter::Antialiasing);
|
||||
diagramScene.render(&painter, QRectF(0, 0, 700, 500), QRectF(0, 0, 700, 500));
|
||||
painter.end();
|
||||
require(imageCanvas.save(strEvidenceDirectory + QLatin1Char('/')
|
||||
+ strName.chopped(4) + QStringLiteral("-canvas.png")), "Cannot save display evidence");
|
||||
}
|
||||
// Failed refresh must clear both the scene and stored records, even if the
|
||||
// model still contains records from a prior successful interpretation.
|
||||
ElementRecord elementUnsupported = document.elements().first();
|
||||
elementUnsupported.elementKind = static_cast<ElementKind>(99);
|
||||
tkrCoordinateMapper mapper;
|
||||
require(!diagramScene.displayElements({document.elements().first(), elementUnsupported}, mapper).bSucceeded
|
||||
&& diagramScene.items().isEmpty(), "Display failure left partial items");
|
||||
document.loadSource("\\draw (0cm,0cm) to (1cm,1cm);", QStringLiteral("unsupported.tex"));
|
||||
elementUnsupported.uDocumentRevision = document.revision();
|
||||
require(document.setParsedElements({elementUnsupported}, document.revision()).bSucceeded,
|
||||
"Cannot prepare stale-record regression");
|
||||
require(!controller.refreshParsedDocument().bSucceeded && document.elements().isEmpty()
|
||||
&& diagramScene.items().isEmpty(), "Parse failure retained stale records/items");
|
||||
}
|
||||
|
||||
void checkByteRangesAndVariants()
|
||||
{
|
||||
tkrTikzParserExplicit parser;
|
||||
const QByteArray baSource = QByteArray::fromHex("efbbbf25c3a90d0a")
|
||||
+ "% \\draw (99cm,99cm) rectangle (100cm,100cm);\r\n"
|
||||
"\\begin{tikzpicture}\r\n"
|
||||
"\\draw[solid, line width = 0.6pt, black]\r\n"
|
||||
" (+2.50cm, % corner\r\n -.5cm) rectangle (-1.cm, +1.25cm); % keep\r\n"
|
||||
"\\end{tikzpicture}\r\n";
|
||||
const ParseResult parseResult = parser.parse(baSource, 42);
|
||||
require(parseResult.bSafeToEdit && parseResult.vecElements.size() == 1, "Whitespace/comments/options rejected");
|
||||
const ElementRecord &elementRecord = parseResult.vecElements.first();
|
||||
require(elementRecord.ptFirstTikzPosition == QPointF(2.5, -0.5)
|
||||
&& elementRecord.ptSecondTikzPosition == QPointF(-1, 1.25), "Signed/reversed corners mismatch");
|
||||
const SourceRange rangesCoordinates[] = {elementRecord.rangeFirstX, elementRecord.rangeFirstY,
|
||||
elementRecord.rangeSecondX, elementRecord.rangeSecondY};
|
||||
const QByteArray baExpected[] = {"+2.50", "-.5", "-1.", "+1.25"};
|
||||
for (int iCoordinate = 0; iCoordinate < 4; ++iCoordinate) {
|
||||
require(baSource.mid(rangesCoordinates[iCoordinate].nStart, rangesCoordinates[iCoordinate].nLength)
|
||||
== baExpected[iCoordinate], "UTF-8/CRLF/BOM shifted byte ranges");
|
||||
}
|
||||
tkrTikzDocument document;
|
||||
document.loadSource(baSource, QStringLiteral("ranges.tex"));
|
||||
require(document.applyCoordinateEdits({{elementRecord.rangeFirstX, "+2.50", "3.75", document.revision()}})
|
||||
.bSucceeded, "Parsed range could not drive guarded byte replacement");
|
||||
QByteArray baExpectedSource = baSource;
|
||||
baExpectedSource.replace(baSource.indexOf("+2.50"), 5, "3.75");
|
||||
require(document.sourceBytes() == baExpectedSource, "Parsed range changed unrelated bytes");
|
||||
const ParseResult parseDefault = parser.parse("\\draw (0cm,0cm) rectangle (1cm,1cm);", 1);
|
||||
require(parseDefault.bSafeToEdit && parseDefault.vecElements.first().rLineWidthPoints == 0.4,
|
||||
"Default rectangle width rejected");
|
||||
tkrDiagramScene diagramScene;
|
||||
tkrCoordinateMapper mapper;
|
||||
require(mapper.configure(QPointF(10, 20), 50).bSucceeded, "Cannot configure alternate mapping");
|
||||
require(diagramScene.displayElements(parseResult.vecElements, mapper).bSucceeded, "Reversed corners not displayed");
|
||||
const QGraphicsRectItem *pRectangle = qgraphicsitem_cast<QGraphicsRectItem *>(diagramScene.items().first());
|
||||
require(pRectangle && pRectangle->rect() == QRectF(-40, -42.5, 175, 87.5), "Alternate mapping/reversed rectangle mismatch");
|
||||
}
|
||||
|
||||
void checkUnsupportedSyntax()
|
||||
{
|
||||
tkrTikzParserExplicit parser;
|
||||
const QByteArray baValid = "\\draw (0cm,0cm) rectangle (1cm,1cm);";
|
||||
const QList<QByteArray> listUnsupported = {
|
||||
"", "% only a comment", "\\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);",
|
||||
"\\draw (0,0) rectangle (1,1);", "\\draw (0mm,0cm) rectangle (1cm,1cm);",
|
||||
"\\draw (0cm,0cm) rectangle +(1cm,1cm);", "\\draw (0cm,0cm) rectangle (1+1cm,1cm);",
|
||||
"\\draw (A) rectangle (B);", "\\draw (0cm,0cm) to (1cm,1cm);",
|
||||
"\\draw[->] (0cm,0cm) rectangle (1cm,1cm);", "\\draw[fill=red] (0cm,0cm) rectangle (1cm,1cm);",
|
||||
"\\draw[scale=2] (0cm,0cm) rectangle (1cm,1cm);", "\\draw[custom] (0cm,0cm) rectangle (1cm,1cm);",
|
||||
"\\draw[line width=0pt] (0cm,0cm) rectangle (1cm,1cm);",
|
||||
"\\draw[line width=0.6pt,line width=1pt] (0cm,0cm) rectangle (1cm,1cm);",
|
||||
"\\draw (0cm,0cm) rectangle (0cm,1cm);", baValid.chopped(1),
|
||||
"\\foreach \\x in {1,2} {" + baValid + "}", "\\def\\box{" + baValid + "}",
|
||||
"\\begin{scope}[shift={(1cm,0cm)}]" + baValid + "\\end{scope}",
|
||||
"\\begin{tikzpicture}[scale=2]" + baValid + "\\end{tikzpicture}",
|
||||
"\\tikzset{every path/.style={scale=2}}" + baValid,
|
||||
baValid + "\\node at (0cm,0cm) {text};", baValid + "\\input{other.tex}",
|
||||
baValid + "\\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);",
|
||||
"\\path[use as bounding box] (0cm,0cm) rectangle (1cm,1cm);" + baValid,
|
||||
"\\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);"
|
||||
"\\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);" + baValid,
|
||||
QByteArray::fromHex("c2a0") + baValid
|
||||
};
|
||||
for (const QByteArray &baUnsupported : listUnsupported) {
|
||||
const ParseResult parseResult = parser.parse(baUnsupported, 5);
|
||||
require(!parseResult.bSafeToEdit && parseResult.vecElements.isEmpty()
|
||||
&& !parseResult.comparisonExtent.bIsPresent && !parseResult.listDiagnostics.isEmpty(),
|
||||
"Unsupported input produced a partial/successful interpretation");
|
||||
}
|
||||
QByteArray baAlteredPreamble = readCorpus(QStringLiteral("boxes-initial.tex"));
|
||||
baAlteredPreamble.replace("\\usepackage{tikz}", "\\usepackage{tikz}\n\\tikzset{every picture/.style={scale=2}}");
|
||||
require(!parser.parse(baAlteredPreamble, 1).bSafeToEdit, "Altered preamble accepted");
|
||||
}
|
||||
|
||||
void checkWindowOpen(const QString &strEvidenceDirectory)
|
||||
{
|
||||
tkrMainWindow mainWindow;
|
||||
mainWindow.show();
|
||||
QAction *pOpenAction = nullptr;
|
||||
QAction *pSaveAction = nullptr;
|
||||
for (QAction *pAction : mainWindow.findChildren<QAction *>()) {
|
||||
if (pAction->shortcut() == QKeySequence(QKeySequence::Open)) {
|
||||
pOpenAction = pAction;
|
||||
} else if (pAction->shortcut() == QKeySequence(QKeySequence::Save)) {
|
||||
pSaveAction = pAction;
|
||||
}
|
||||
}
|
||||
require(pOpenAction && pSaveAction, "Window file actions missing");
|
||||
QTimer timerDialog;
|
||||
QObject::connect(&timerDialog, &QTimer::timeout, [&timerDialog]() {
|
||||
for (QWidget *pWidget : QApplication::topLevelWidgets()) {
|
||||
QFileDialog *pDialog = qobject_cast<QFileDialog *>(pWidget);
|
||||
if (pDialog && pDialog->isVisible()) {
|
||||
pDialog->selectFile(QStringLiteral(TKR_CORPUS_DIRECTORY "/boxes-initial.tex"));
|
||||
QMetaObject::invokeMethod(pDialog, "accept", Qt::QueuedConnection);
|
||||
timerDialog.stop();
|
||||
}
|
||||
}
|
||||
});
|
||||
QTimer timerTimeout;
|
||||
timerTimeout.setSingleShot(true);
|
||||
QObject::connect(&timerTimeout, &QTimer::timeout, []() { qFatal("Window open test timed out"); });
|
||||
timerTimeout.start(10000);
|
||||
timerDialog.start(20);
|
||||
pOpenAction->trigger(); // Exercise the actual window Open -> controller -> view wiring.
|
||||
timerTimeout.stop();
|
||||
QApplication::processEvents();
|
||||
const QGraphicsView *pView = mainWindow.findChild<QGraphicsView *>();
|
||||
const QPlainTextEdit *pSourceView = mainWindow.findChild<QPlainTextEdit *>();
|
||||
require(pView && pView->scene()->items().size() == 2, "Window canvas did not receive rectangles");
|
||||
require(pSourceView && pSourceView->isReadOnly()
|
||||
&& pSourceView->toPlainText().contains(QStringLiteral("rectangle (3cm,1cm)")),
|
||||
"Window source view did not load");
|
||||
require(!pSaveAction->isEnabled() && !mainWindow.isWindowModified(), "Display dirtied window");
|
||||
require(mainWindow.statusBar()->currentMessage().contains(QStringLiteral("Displayed 2 element(s)")),
|
||||
"Window display status missing");
|
||||
if (!strEvidenceDirectory.isEmpty()) {
|
||||
require(mainWindow.grab().save(strEvidenceDirectory + QStringLiteral("/rectangle-window-2026-10-21.png")),
|
||||
"Cannot save window evidence");
|
||||
}
|
||||
mainWindow.close();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int iArgumentCount, char *pArguments[])
|
||||
{
|
||||
QApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
|
||||
QApplication application(iArgumentCount, pArguments);
|
||||
#ifdef Q_OS_WIN
|
||||
// The offscreen platform does not always enumerate Windows fonts. Load an
|
||||
// existing system font explicitly so retained window evidence is readable.
|
||||
const int iFontId = QFontDatabase::addApplicationFont(
|
||||
qEnvironmentVariable("SystemRoot") + QStringLiteral("/Fonts/segoeui.ttf"));
|
||||
if (iFontId >= 0) {
|
||||
QApplication::setFont(QFont(QFontDatabase::applicationFontFamilies(iFontId).first(), 9));
|
||||
}
|
||||
#endif
|
||||
const QString strEvidenceDirectory = iArgumentCount > 1 ? QString::fromLocal8Bit(pArguments[1]) : QString();
|
||||
checkCorpus(QStringLiteral("boxes-initial.tex"), 2, strEvidenceDirectory);
|
||||
checkCorpus(QStringLiteral("boxes-touching.tex"), 1, strEvidenceDirectory);
|
||||
checkByteRangesAndVariants();
|
||||
checkUnsupportedSyntax();
|
||||
checkWindowOpen(strEvidenceDirectory);
|
||||
qInfo("Rectangle parsing, byte ranges, controller and scene checks passed. Gestures and product acceptance remain untested.");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
#include "controller/tkrEditorController.h"
|
||||
#include "editing/tkrEditService.h"
|
||||
#include "geometry/ShapeGeometryLimits.h"
|
||||
#include "model/tkrTikzDocument.h"
|
||||
#include "ui/tkrDiagramScene.h"
|
||||
#include "ui/tkrMainWindow.h"
|
||||
|
||||
#include <QApplication>
|
||||
#include <QFile>
|
||||
#include <QGraphicsRectItem>
|
||||
#include <QGraphicsView>
|
||||
#include <QKeyEvent>
|
||||
#include <QMouseEvent>
|
||||
#include <QTemporaryDir>
|
||||
#include <QDir>
|
||||
#include <QFontDatabase>
|
||||
#include <QFocusEvent>
|
||||
#include <cmath>
|
||||
|
||||
using namespace TikzRefinery;
|
||||
namespace {
|
||||
constexpr qreal rTolerance = 0.000001;
|
||||
void require(bool bCondition, const char *pMessage) { if (!bCondition) qFatal("%s", pMessage); }
|
||||
bool close(qreal rFirst, qreal rSecond) { return std::abs(rFirst - rSecond) < rTolerance; }
|
||||
const QByteArray baSource =
|
||||
"% Preserve comments and spelling\r\n"
|
||||
"\\path[use as bounding box] (-2cm,-2cm) rectangle (5cm,3cm);\r\n"
|
||||
"\\draw[line width=0.6pt] (+0.00cm,0cm) rectangle (1cm,1cm); % stationary\r\n"
|
||||
"\\draw[line width=0.6pt] (2.000000000001cm,0cm) rectangle (3cm,1cm); % resize me\r\n";
|
||||
|
||||
void write(const QString &path, const QByteArray &source) {
|
||||
QFile file(path); require(file.open(QIODevice::WriteOnly) && file.write(source) == source.size(), "Cannot write fixture");
|
||||
}
|
||||
QByteArray read(const QString &path) {
|
||||
QFile file(path); require(file.open(QIODevice::ReadOnly), "Cannot read fixture"); return file.readAll();
|
||||
}
|
||||
void pointer(QGraphicsView &view, QEvent::Type type, const QPointF &point) {
|
||||
const QPoint pixel = view.mapFromScene(point);
|
||||
const bool bRelease = type == QEvent::MouseButtonRelease;
|
||||
QMouseEvent event(type, QPointF(pixel), QPointF(view.viewport()->mapToGlobal(pixel)),
|
||||
type == QEvent::MouseMove ? Qt::NoButton : Qt::LeftButton,
|
||||
bRelease ? Qt::NoButton : Qt::LeftButton, Qt::NoModifier);
|
||||
QApplication::sendEvent(view.viewport(), &event); QApplication::processEvents();
|
||||
}
|
||||
|
||||
void checkGeometryAndSource(const QString &path)
|
||||
{
|
||||
tkrTikzDocument document; tkrDiagramScene scene; tkrEditorController controller(document, scene);
|
||||
const DragKind kinds[] = {DragKind::RectangleFirstFirst, DragKind::RectangleFirstSecond,
|
||||
DragKind::RectangleSecondFirst, DragKind::RectangleSecondSecond};
|
||||
for (const DragKind kind : kinds) {
|
||||
write(path, baSource); require(controller.openDocument(path).bSucceeded, "Open failed");
|
||||
const quint64 revision = document.revision();
|
||||
const bool bFirstX = kind == DragKind::RectangleFirstFirst || kind == DragKind::RectangleFirstSecond;
|
||||
const bool bFirstY = kind == DragKind::RectangleFirstFirst || kind == DragKind::RectangleSecondFirst;
|
||||
const QPointF fixed(bFirstX ? 3 : 2.000000000001, bFirstY ? 1 : 0);
|
||||
// Cross both axes with independently specified deltas; source positions remain in their original slots.
|
||||
const QPointF delta(bFirstX ? 1.5 : -1.5, bFirstY ? 1.5 : -1.5);
|
||||
DragUpdate drag{2, revision, kind, {0,0}, {delta.x()*100, -delta.y()*100}};
|
||||
controller.handleDragPreview(drag);
|
||||
require(document.sourceBytes() == baSource && document.revision() == revision, "Preview changed source");
|
||||
controller.handleDragCommit(drag);
|
||||
require(document.revision() == revision + 1, "Resize did not apply one batch");
|
||||
const ElementRecord after = document.elements().at(1);
|
||||
require(close(bFirstX ? after.ptSecondTikzPosition.x() : after.ptFirstTikzPosition.x(), fixed.x())
|
||||
&& close(bFirstY ? after.ptSecondTikzPosition.y() : after.ptFirstTikzPosition.y(), fixed.y()), "Opposite corner moved");
|
||||
QByteArray expected = baSource;
|
||||
if (bFirstX) expected.replace("2.000000000001cm", "3.500000000001cm");
|
||||
else expected.replace("(3cm,1cm)", "(1.5cm,1cm)");
|
||||
if (bFirstY) expected.replace("(2.000000000001cm,0cm)", "(2.000000000001cm,1.5cm)").replace("(3.500000000001cm,0cm)", "(3.500000000001cm,1.5cm)");
|
||||
else expected.replace("(3cm,1cm)", "(3cm,-0.5cm)").replace("(1.5cm,1cm)", "(1.5cm,-0.5cm)");
|
||||
require(document.sourceBytes() == expected, "Resize changed unrelated bytes or fixed-coordinate precision");
|
||||
require(controller.saveDocument().bSucceeded && read(path) == expected, "Resize save failed");
|
||||
require(controller.openDocument(path).bSucceeded && document.sourceBytes() == expected, "Resize reopen failed");
|
||||
}
|
||||
// One-axis crossing and an unchanged coordinate spelling.
|
||||
write(path, baSource); controller.openDocument(path);
|
||||
controller.handleDragCommit({2, document.revision(), DragKind::RectangleSecondSecond, {0,0}, {-150,0}});
|
||||
require(document.sourceBytes().contains("(1.5cm,1cm)"), "Horizontal crossing failed");
|
||||
write(path, baSource); controller.openDocument(path);
|
||||
controller.handleDragCommit({2, document.revision(), DragKind::RectangleSecondSecond, {0,0}, {0,150}});
|
||||
require(document.sourceBytes().contains("(3cm,-0.5cm)"), "Vertical crossing failed");
|
||||
// Minimum on both axes, exact coincidence and fixed-boundary expansion.
|
||||
write(path, baSource); controller.openDocument(path);
|
||||
controller.handleDragCommit({2, document.revision(), DragKind::RectangleSecondSecond, {0,0}, {-100,100}});
|
||||
const ElementRecord minimum = document.elements().at(1);
|
||||
require(close(std::abs(minimum.ptSecondTikzPosition.x() - minimum.ptFirstTikzPosition.x()), 0.01)
|
||||
&& close(std::abs(minimum.ptSecondTikzPosition.y() - minimum.ptFirstTikzPosition.y()), 0.01), "Minimum dimensions failed");
|
||||
write(path, baSource); controller.openDocument(path);
|
||||
controller.handleDragCommit({2, document.revision(), DragKind::RectangleSecondSecond, {0,0}, {0,100}});
|
||||
require(document.sourceBytes().contains("(3cm,0.01cm)"), "Thin filler changed the independent width");
|
||||
const QByteArray reversed = "\\draw (3cm,1cm) rectangle (2cm,0cm);";
|
||||
write(path, reversed); controller.openDocument(path);
|
||||
controller.handleDragCommit({1, document.revision(), DragKind::RectangleFirstFirst, {0,0}, {-150,150}});
|
||||
require(document.sourceBytes() == "\\draw (1.5cm,-0.5cm) rectangle (2cm,0cm);", "Reversed coordinate slots were normalized in source");
|
||||
write(path, baSource); controller.openDocument(path);
|
||||
controller.handleDragCommit({2, document.revision(), DragKind::RectangleSecondSecond, {0,0}, {10000,-10000}});
|
||||
const ElementRecord expanded = document.elements().at(1);
|
||||
const qreal margin = outlineMarginCentimeters(expanded);
|
||||
require(expanded.ptSecondTikzPosition.x() <= 5-margin && expanded.ptSecondTikzPosition.x() > 5-margin-rTolerance
|
||||
&& expanded.ptSecondTikzPosition.y() <= 3-margin && expanded.ptSecondTikzPosition.y() > 3-margin-rTolerance,
|
||||
"Resize release did not reach furthest valid boundary");
|
||||
const quint64 boundaryRevision = document.revision();
|
||||
controller.handleDragCommit({2, boundaryRevision, DragKind::RectangleSecondSecond, {0,0}, {10000,-10000}});
|
||||
require(document.revision() == boundaryRevision, "Repeated boundary resize created an edit");
|
||||
// Stale, unsupported and nonfinite requests preserve source.
|
||||
const QByteArray before = document.sourceBytes();
|
||||
controller.handleDragCommit({2, boundaryRevision-1, DragKind::RectangleSecondSecond, {0,0}, {20,20}});
|
||||
controller.handleDragCommit({2, boundaryRevision, DragKind::FirstEndpoint, {0,0}, {20,20}});
|
||||
controller.handleDragCommit({2, boundaryRevision, DragKind::RectangleSecondSecond, {0,0}, {qQNaN(),20}});
|
||||
require(document.sourceBytes() == before && document.revision() == boundaryRevision, "Invalid gesture mutated source");
|
||||
}
|
||||
|
||||
void checkPointerGestures(const QString &path, const QString &evidence)
|
||||
{
|
||||
write(path, baSource);
|
||||
tkrTikzDocument document; tkrDiagramScene scene; tkrEditorController controller(document, scene);
|
||||
controller.openDocument(path);
|
||||
QGraphicsView view(&scene); view.resize(1000,800); view.show(); view.activateWindow(); view.setFocus();
|
||||
QApplication::processEvents();
|
||||
scene.selectElement(2);
|
||||
int changes = 0;
|
||||
QObject::connect(&controller, &tkrEditorController::documentChanged, [&](){ ++changes; });
|
||||
pointer(view, QEvent::MouseButtonPress, {500,200});
|
||||
pointer(view, QEvent::MouseMove, {350,350}); // Cross both axes, then return during the same gesture.
|
||||
pointer(view, QEvent::MouseMove, {550,150});
|
||||
require(document.sourceBytes() == baSource && changes == 0, "Pointer preview mutated source");
|
||||
auto *item = qgraphicsitem_cast<QGraphicsRectItem *>(scene.selectedItems().first());
|
||||
require(item && item->rect().bottomRight() == QPointF(550,300), "Corner handle did not resize preview");
|
||||
pointer(view, QEvent::MouseButtonRelease, {550,150});
|
||||
require(changes == 1 && document.sourceBytes().contains("(3.5cm,1.5cm)"), "Pointer release did not resize");
|
||||
const QByteArray accepted = document.sourceBytes();
|
||||
const quint64 revision = document.revision();
|
||||
pointer(view, QEvent::MouseButtonPress, {550,150});
|
||||
pointer(view, QEvent::MouseMove, {600,100});
|
||||
QKeyEvent escape(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier);
|
||||
QApplication::sendEvent(&view, &escape);
|
||||
pointer(view, QEvent::MouseButtonRelease, {600,100});
|
||||
require(document.sourceBytes() == accepted && document.revision() == revision, "Escape committed resize");
|
||||
scene.selectElement(2);
|
||||
pointer(view, QEvent::MouseButtonPress, {550,150});
|
||||
pointer(view, QEvent::MouseMove, {600,100});
|
||||
QFocusEvent focusOut(QEvent::FocusOut, Qt::ActiveWindowFocusReason);
|
||||
QApplication::sendEvent(&scene, &focusOut);
|
||||
pointer(view, QEvent::MouseButtonRelease, {600,100});
|
||||
require(document.sourceBytes() == accepted && document.revision() == revision, "Focus loss committed resize");
|
||||
scene.selectElement(2);
|
||||
pointer(view, QEvent::MouseButtonPress, {550,150});
|
||||
pointer(view, QEvent::MouseMove, {600,100});
|
||||
controller.saveDocument();
|
||||
pointer(view, QEvent::MouseButtonRelease, {600,100});
|
||||
require(document.sourceBytes() == accepted && read(path) == accepted, "Save during resize committed preview");
|
||||
// A transformed view still produces the same source geometry.
|
||||
view.scale(2,2); view.centerOn(450,250); scene.selectElement(2);
|
||||
pointer(view, QEvent::MouseButtonPress, {550,150});
|
||||
pointer(view, QEvent::MouseMove, {600,100});
|
||||
pointer(view, QEvent::MouseButtonRelease, {600,100});
|
||||
require(document.sourceBytes().contains("(4cm,2cm)"), "View transform changed resize dimensions");
|
||||
require(controller.saveDocument().bSucceeded && read(path) == document.sourceBytes(), "Final resize save failed");
|
||||
if (!evidence.isEmpty()) {
|
||||
require(QDir().mkpath(evidence), "Cannot create evidence directory");
|
||||
tkrMainWindow window(nullptr, path); window.resize(1100,750); window.show();
|
||||
QApplication::processEvents();
|
||||
auto *canvas = window.findChild<tkrDiagramScene *>(); canvas->selectElement(2);
|
||||
QApplication::processEvents();
|
||||
require(window.grab().save(evidence + "/resize-window.png"), "Cannot save resize screenshot");
|
||||
write(evidence + "/resized.tex", document.sourceBytes());
|
||||
window.close();
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
QApplication application(argc, argv);
|
||||
const int font = QFontDatabase::addApplicationFont(qEnvironmentVariable("SystemRoot") + "/Fonts/segoeui.ttf");
|
||||
if (font >= 0) QApplication::setFont(QFont(QFontDatabase::applicationFontFamilies(font).first(), 9));
|
||||
QTemporaryDir directory; require(directory.isValid(), "Cannot create temporary test directory");
|
||||
const QString path = directory.filePath("resize.tex");
|
||||
checkGeometryAndSource(path);
|
||||
checkPointerGestures(path, argc > 1 ? QString::fromLocal8Bit(argv[1]) : QString());
|
||||
qInfo("Rectangle corner gestures, crossing, minima, boundaries, exact source edits, cancellation and save/reopen passed.");
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
#include "controller/tkrEditorController.h"
|
||||
#include "model/tkrTikzDocument.h"
|
||||
#include "ui/tkrDiagramScene.h"
|
||||
#include "ui/tkrMainWindow.h"
|
||||
|
||||
#include <QAction>
|
||||
#include <QApplication>
|
||||
#include <QFile>
|
||||
#include <QFontDatabase>
|
||||
#include <QGraphicsPathItem>
|
||||
#include <QGraphicsView>
|
||||
#include <QImage>
|
||||
#include <QPainter>
|
||||
#include <QPlainTextEdit>
|
||||
#include <QStatusBar>
|
||||
|
||||
using namespace TikzRefinery;
|
||||
|
||||
namespace {
|
||||
|
||||
void require(bool bCondition, const char *pMessage)
|
||||
{
|
||||
if (!bCondition) {
|
||||
qFatal("%s", pMessage);
|
||||
}
|
||||
}
|
||||
|
||||
struct SegmentExpectation
|
||||
{
|
||||
QPointF ptFirstTikz;
|
||||
QPointF ptSecondTikz;
|
||||
QPointF ptFirstScene;
|
||||
QPointF ptSecondScene;
|
||||
bool bArrowAtStart = false;
|
||||
bool bArrowAtEnd = false;
|
||||
};
|
||||
|
||||
void checkCorpus(const QString &strName, const QVector<SegmentExpectation> &vecExpected,
|
||||
const QString &strEvidenceDirectory)
|
||||
{
|
||||
const QString strPath = QStringLiteral(TKR_CORPUS_DIRECTORY) + QLatin1Char('/') + strName + QStringLiteral(".tex");
|
||||
QFile fileSource(strPath);
|
||||
require(fileSource.open(QIODevice::ReadOnly), "Cannot open segment fixture");
|
||||
const QByteArray baOriginal = fileSource.readAll();
|
||||
require(fileSource.error() == QFileDevice::NoError, "Cannot read segment fixture");
|
||||
tkrTikzDocument document;
|
||||
tkrDiagramScene diagramScene;
|
||||
tkrEditorController controller(document, diagramScene);
|
||||
require(controller.openDocument(strPath).bSucceeded, "Segment file open failed");
|
||||
require(document.elements().size() == vecExpected.size()
|
||||
&& diagramScene.items().size() == vecExpected.size(), "Wrong segment count or calibration item drawn");
|
||||
require(document.sourceBytes() == baOriginal && !document.hasUnsavedChanges(), "Segment display mutated source");
|
||||
require(diagramScene.sceneRect() == QRectF(0, 0, 700, 500), "Segment comparison extent mismatch");
|
||||
for (qsizetype nElement = 0; nElement < vecExpected.size(); ++nElement) {
|
||||
const SegmentExpectation &expected = vecExpected.at(nElement);
|
||||
const ElementRecord &elementRecord = document.elements().at(nElement);
|
||||
require(elementRecord.uElementId == static_cast<quint64>(nElement + 1)
|
||||
&& elementRecord.uDocumentRevision == document.revision(), "Segment identity/revision mismatch");
|
||||
require(elementRecord.ptFirstTikzPosition == expected.ptFirstTikz
|
||||
&& elementRecord.ptSecondTikzPosition == expected.ptSecondTikz, "Segment source endpoints mismatch");
|
||||
require(elementRecord.bArrowAtStart == expected.bArrowAtStart
|
||||
&& elementRecord.bArrowAtEnd == expected.bArrowAtEnd, "Arrow direction mismatch");
|
||||
require(elementRecord.elementKind == (expected.bArrowAtStart || expected.bArrowAtEnd
|
||||
? ElementKind::Arrow : ElementKind::Line), "Line/arrow kind mismatch");
|
||||
const SourceRange rangesCoordinates[] = {elementRecord.rangeFirstX, elementRecord.rangeFirstY,
|
||||
elementRecord.rangeSecondX, elementRecord.rangeSecondY};
|
||||
const qreal rExpected[] = {expected.ptFirstTikz.x(), expected.ptFirstTikz.y(),
|
||||
expected.ptSecondTikz.x(), expected.ptSecondTikz.y()};
|
||||
for (int iCoordinate = 0; iCoordinate < 4; ++iCoordinate) {
|
||||
const SourceRange &rangeSource = rangesCoordinates[iCoordinate];
|
||||
bool bConverted = false;
|
||||
const qreal rActual = baOriginal.mid(rangeSource.nStart, rangeSource.nLength).toDouble(&bConverted);
|
||||
require(bConverted && rActual == rExpected[iCoordinate], "Segment numeric byte range mismatch");
|
||||
}
|
||||
QGraphicsPathItem *pSegment = nullptr;
|
||||
for (QGraphicsItem *pItem : diagramScene.items()) {
|
||||
if (pItem->data(0).toULongLong() == elementRecord.uElementId) {
|
||||
pSegment = qgraphicsitem_cast<QGraphicsPathItem *>(pItem);
|
||||
}
|
||||
}
|
||||
require(pSegment && pSegment->path().contains((expected.ptFirstScene + expected.ptSecondScene) / 2),
|
||||
"Segment shaft not at independent expected scene position");
|
||||
require(pSegment->brush().color() == QColor(Qt::black) && pSegment->pen().style() == Qt::NoPen,
|
||||
"Segment outline appearance mismatch");
|
||||
require(!pSegment->flags().testFlag(QGraphicsItem::ItemIsMovable)
|
||||
&& pSegment->flags().testFlag(QGraphicsItem::ItemIsSelectable), "Segment selection/scene-controlled movement mismatch");
|
||||
}
|
||||
if (!strEvidenceDirectory.isEmpty()) {
|
||||
QImage imageCanvas(700, 500, QImage::Format_ARGB32_Premultiplied);
|
||||
imageCanvas.fill(Qt::white);
|
||||
QPainter painter(&imageCanvas);
|
||||
painter.setRenderHint(QPainter::Antialiasing);
|
||||
diagramScene.render(&painter, QRectF(0, 0, 700, 500), QRectF(0, 0, 700, 500));
|
||||
painter.end();
|
||||
require(imageCanvas.save(strEvidenceDirectory + QLatin1Char('/') + strName + QStringLiteral("-canvas.png")),
|
||||
"Cannot save segment canvas evidence");
|
||||
}
|
||||
// Exercise the same startup-file route used when launching the visible app.
|
||||
tkrMainWindow mainWindow(nullptr, strPath);
|
||||
mainWindow.show();
|
||||
QApplication::processEvents();
|
||||
const QGraphicsView *pView = mainWindow.findChild<QGraphicsView *>();
|
||||
const QPlainTextEdit *pSourceView = mainWindow.findChild<QPlainTextEdit *>();
|
||||
require(pView && pView->scene()->items().size() == vecExpected.size(), "Startup file did not reach window canvas");
|
||||
require(pSourceView && pSourceView->isReadOnly()
|
||||
&& pSourceView->toPlainText().contains(QStringLiteral("--")), "Startup source not displayed");
|
||||
require(mainWindow.statusBar()->currentMessage().startsWith(QStringLiteral("Displayed "))
|
||||
&& !mainWindow.isWindowModified(), "Segment window status/clean state mismatch");
|
||||
for (const QAction *pAction : mainWindow.findChildren<QAction *>()) {
|
||||
if (pAction->shortcut() == QKeySequence(QKeySequence::Save)) {
|
||||
require(!pAction->isEnabled(), "Segment display enabled Save");
|
||||
}
|
||||
}
|
||||
if (!strEvidenceDirectory.isEmpty() && strName.endsWith(QStringLiteral("initial"))) {
|
||||
require(mainWindow.grab().save(strEvidenceDirectory + QLatin1Char('/') + strName + QStringLiteral("-window.png")),
|
||||
"Cannot save segment window evidence");
|
||||
}
|
||||
mainWindow.close();
|
||||
}
|
||||
|
||||
void checkVariantsAndRefusals()
|
||||
{
|
||||
tkrTikzParserExplicit parser;
|
||||
const QByteArray baSource = QByteArray::fromHex("efbbbf25c3a90d0a")
|
||||
+ "\\draw[black, <-, solid, line width = 0.6pt] (+1.25cm, % keep\r\n -.5cm) -- (-2.cm,+3.50cm);\r\n"
|
||||
"\\draw (0cm,0cm) -- (0cm,1cm);\r\n"
|
||||
"\\draw (1cm,0cm) -- (-1cm,0cm);\r\n"
|
||||
"\\draw (0cm,0cm) rectangle (1cm,1cm);\r\n";
|
||||
const ParseResult parseResult = parser.parse(baSource, 17);
|
||||
require(parseResult.bSafeToEdit && parseResult.vecElements.size() == 4, "Mixed geometry/comments rejected");
|
||||
const ElementRecord &elementFirst = parseResult.vecElements.first();
|
||||
require(elementFirst.uDocumentRevision == 17 && elementFirst.bArrowAtStart && !elementFirst.bArrowAtEnd,
|
||||
"Variant arrow identity/direction mismatch");
|
||||
require(baSource.mid(elementFirst.rangeFirstX.nStart, elementFirst.rangeFirstX.nLength) == "+1.25"
|
||||
&& baSource.mid(elementFirst.rangeSecondY.nStart, elementFirst.rangeSecondY.nLength) == "+3.50",
|
||||
"UTF-8/BOM/comments shifted segment byte offsets");
|
||||
tkrTikzDocument document;
|
||||
document.loadSource(baSource, QStringLiteral("variants.tex"));
|
||||
require(document.applyCoordinateEdits({{elementFirst.rangeSecondY, "+3.50", "4.125", document.revision()}})
|
||||
.bSucceeded, "Parsed segment range could not drive guarded edit");
|
||||
QByteArray baExpected = baSource;
|
||||
baExpected.replace(baSource.indexOf("+3.50"), 5, "4.125");
|
||||
require(document.sourceBytes() == baExpected, "Segment coordinate replacement changed unrelated bytes");
|
||||
tkrCoordinateMapper mapper;
|
||||
require(mapper.configure(QPointF(10, 20), 50).bSucceeded, "Alternate segment mapper rejected");
|
||||
tkrDiagramScene diagramScene;
|
||||
require(diagramScene.displayElements(parseResult.vecElements, mapper).bSucceeded, "Mixed/vertical/reversed display failed");
|
||||
const QList<QByteArray> listUnsupported = {
|
||||
"\\draw (0cm,0cm) -- (0cm,0cm);", "\\draw[->,<-] (0cm,0cm) -- (1cm,1cm);",
|
||||
"\\draw[-latex] (0cm,0cm) -- (1cm,1cm);", "\\draw[>=stealth,->] (0cm,0cm) -- (1cm,1cm);",
|
||||
"\\draw[->] (0cm,0cm) rectangle (1cm,1cm);", "\\draw[dashed] (0cm,0cm) -- (1cm,1cm);",
|
||||
"\\draw (0cm,0cm) -- (1cm,1cm) -- (2cm,0cm);", "\\draw (0cm,0cm) -- +(1cm,1cm);",
|
||||
"\\draw (0cm,0cm) to (1cm,1cm);", "\\draw (0cm,0cm) .. controls (1cm,0cm) .. (1cm,1cm);",
|
||||
"\\begin{scope}[scale=2]\\draw (0cm,0cm) -- (1cm,1cm);\\end{scope}",
|
||||
baSource + "\\input{other.tex}"
|
||||
};
|
||||
for (const QByteArray &baUnsupported : listUnsupported) {
|
||||
const ParseResult parseRejected = parser.parse(baUnsupported, 1);
|
||||
require(!parseRejected.bSafeToEdit && parseRejected.vecElements.isEmpty()
|
||||
&& !parseRejected.listDiagnostics.isEmpty(), "Unsupported segment context accepted/partially displayed");
|
||||
}
|
||||
const ParseResult parseShort = parser.parse("\\draw[<->] (0cm,0cm) -- (0.001cm,0cm);", 1);
|
||||
require(parseShort.bSafeToEdit && !diagramScene.displayElements(parseShort.vecElements, mapper).bSucceeded
|
||||
&& diagramScene.items().isEmpty(), "Unsupported short arrow left stale/partial items");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int iArgumentCount, char *pArguments[])
|
||||
{
|
||||
QApplication application(iArgumentCount, pArguments);
|
||||
#ifdef Q_OS_WIN
|
||||
const int iFontId = QFontDatabase::addApplicationFont(
|
||||
qEnvironmentVariable("SystemRoot") + QStringLiteral("/Fonts/segoeui.ttf"));
|
||||
if (iFontId >= 0) {
|
||||
QApplication::setFont(QFont(QFontDatabase::applicationFontFamilies(iFontId).first(), 9));
|
||||
}
|
||||
#endif
|
||||
const QString strEvidenceDirectory = iArgumentCount > 1 ? QString::fromLocal8Bit(pArguments[1]) : QString();
|
||||
checkCorpus(QStringLiteral("line-initial"), {{{-1,-0.5},{1,0.5},{100,350},{300,250}}}, strEvidenceDirectory);
|
||||
checkCorpus(QStringLiteral("line-translated"), {{{-0.5,0},{1.5,1},{150,300},{350,200}}}, strEvidenceDirectory);
|
||||
checkCorpus(QStringLiteral("line-endpoint"), {{{-1,-0.5},{1,1.5},{100,350},{300,150}}}, strEvidenceDirectory);
|
||||
const SegmentExpectation backward = {{0,-1},{2,-1},{200,400},{400,400},true,false};
|
||||
const SegmentExpectation doubleArrow = {{0,2},{2,2},{200,100},{400,100},true,true};
|
||||
checkCorpus(QStringLiteral("arrow-initial"), {{{0,0},{2,1},{200,300},{400,200},false,true}, backward, doubleArrow}, strEvidenceDirectory);
|
||||
checkCorpus(QStringLiteral("arrow-translated"), {{{0.5,0.5},{2.5,1.5},{250,250},{450,150},false,true}, backward, doubleArrow}, strEvidenceDirectory);
|
||||
checkCorpus(QStringLiteral("arrow-endpoint"), {{{0,0},{2,1.5},{200,300},{400,150},false,true}, backward, doubleArrow}, strEvidenceDirectory);
|
||||
checkVariantsAndRefusals();
|
||||
qInfo("Line/arrow parsing, byte ranges, scene and startup-window checks passed. Gestures remain untested.");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
#include "ui/tkrFolderBrowser.h"
|
||||
#include "ui/tkrMainWindow.h"
|
||||
#include "ui/tkrShapePalette.h"
|
||||
#include "ui/tkrWorkspaceSidebar.h"
|
||||
|
||||
#include <QApplication>
|
||||
#include <QFile>
|
||||
#include <QPlainTextEdit>
|
||||
#include <QPointer>
|
||||
#include <QPushButton>
|
||||
#include <QSplitter>
|
||||
#include <QTemporaryDir>
|
||||
#include <QToolButton>
|
||||
#include <QtDebug>
|
||||
#include <cstdlib>
|
||||
|
||||
using namespace TikzRefinery;
|
||||
|
||||
namespace {
|
||||
constexpr int iSidebarTestWidth = 350;
|
||||
constexpr int iWorkspaceTestWidth = 1000;
|
||||
constexpr int iSidebarPaneIndex = 0;
|
||||
constexpr int iWidthTolerancePixels = 2;
|
||||
constexpr int iNoRequests = 0;
|
||||
constexpr int iOneRequest = 1;
|
||||
const QByteArray baFixture("\\path[use as bounding box] (-2cm,-2cm) rectangle (8cm,6cm);\n"
|
||||
"\\draw (0cm,0cm) rectangle (2cm,1cm);\n");
|
||||
|
||||
void require(bool bCondition, const char *pMessage)
|
||||
{
|
||||
if (!bCondition) qFatal("%s", pMessage);
|
||||
}
|
||||
|
||||
void checkSidebar()
|
||||
{
|
||||
QTemporaryDir directory;
|
||||
require(directory.isValid(), "Cannot create sidebar fixture directory");
|
||||
const QString strPath = directory.filePath(QStringLiteral("sidebar.tex"));
|
||||
QFile file(strPath);
|
||||
require(file.open(QIODevice::WriteOnly), "Cannot write sidebar fixture");
|
||||
require(file.write(baFixture) == baFixture.size(), "Incomplete sidebar fixture write");
|
||||
file.close();
|
||||
QPointer<tkrWorkspaceSidebar> pObservedSidebar;
|
||||
QPointer<tkrShapePalette> pObservedPalette;
|
||||
{
|
||||
tkrMainWindow window(nullptr, strPath);
|
||||
window.show();
|
||||
QApplication::processEvents();
|
||||
auto *pSidebar = window.findChild<tkrWorkspaceSidebar *>();
|
||||
auto *pSplitter = window.findChild<QSplitter *>(QStringLiteral("workspaceSplitter"));
|
||||
auto *pSource = window.findChild<QPlainTextEdit *>();
|
||||
require(pSidebar && pSplitter && pSource, "Sidebar or editor assembly missing");
|
||||
auto *pShapes = pSidebar->findChild<QToolButton *>(QStringLiteral("workspaceShapesTab"));
|
||||
auto *pFiles = pSidebar->findChild<QToolButton *>(QStringLiteral("workspaceFilesTab"));
|
||||
auto *pCollapse = pSidebar->findChild<QToolButton *>(QStringLiteral("workspaceCollapseButton"));
|
||||
auto *pContent = pSidebar->findChild<QWidget *>(QStringLiteral("workspaceSidebarContent"));
|
||||
auto *pCreate = pSidebar->findChild<QPushButton *>(QStringLiteral("createShapeButton"));
|
||||
require(pShapes && pFiles && pCollapse && pContent && pCreate, "Sidebar controls missing");
|
||||
require(!pShapes->icon().isNull() && !pFiles->icon().isNull(), "Tab icons missing");
|
||||
require(pShapes->accessibleName() != pFiles->accessibleName()
|
||||
&& !pShapes->toolTip().isEmpty() && !pFiles->toolTip().isEmpty(), "Tab identification missing");
|
||||
require(!pCreate->isEnabled() && !pCreate->toolTip().isEmpty(), "Unimplemented creation must be unavailable");
|
||||
const QString strSource = pSource->toPlainText();
|
||||
require(strSource.toUtf8() == baFixture && !window.isWindowModified(), "Opening fixture changed source");
|
||||
pSplitter->setSizes({iSidebarTestWidth, iWorkspaceTestWidth});
|
||||
QApplication::processEvents();
|
||||
const int iExpandedWidth = pSplitter->sizes().at(iSidebarPaneIndex);
|
||||
pCollapse->click();
|
||||
QApplication::processEvents();
|
||||
require(pSidebar->isCollapsed() && !pContent->isVisible() && pShapes->isVisible()
|
||||
&& pFiles->isVisible(), "Collapse must retain a visible tab strip");
|
||||
pFiles->click();
|
||||
QApplication::processEvents();
|
||||
require(!pSidebar->isCollapsed() && pSidebar->selectedPage() == tkrWorkspaceSidebar::Page::Files
|
||||
&& pFiles->isChecked() && !pShapes->isChecked(), "Files tab did not reopen its page");
|
||||
require(qAbs(pSidebar->width() - iExpandedWidth) <= iWidthTolerancePixels, "Expanded width was not restored");
|
||||
pFiles->click();
|
||||
QApplication::processEvents();
|
||||
require(pSidebar->isCollapsed() && pSidebar->selectedPage() == tkrWorkspaceSidebar::Page::Files,
|
||||
"Selected tab must toggle collapse without losing the page");
|
||||
pFiles->click();
|
||||
QApplication::processEvents();
|
||||
require(!pSidebar->isCollapsed() && pSidebar->selectedPage() == tkrWorkspaceSidebar::Page::Files,
|
||||
"Selected collapsed tab must reopen the retained page");
|
||||
pShapes->click();
|
||||
QApplication::processEvents();
|
||||
require(pSidebar->selectedPage() == tkrWorkspaceSidebar::Page::Shapes && pShapes->isChecked(),
|
||||
"Shapes tab did not activate");
|
||||
require(pSource->toPlainText() == strSource && !window.isWindowModified(),
|
||||
"Sidebar navigation must not edit or dirty the document");
|
||||
pObservedSidebar = pSidebar;
|
||||
pObservedPalette = window.findChild<tkrShapePalette *>();
|
||||
require(pObservedPalette, "Shapes page missing");
|
||||
}
|
||||
require(pObservedSidebar.isNull() && pObservedPalette.isNull(), "Window teardown did not release sidebar/pages");
|
||||
QFile saved(strPath);
|
||||
require(saved.open(QIODevice::ReadOnly) && saved.readAll() == baFixture, "Sidebar browsing changed the file");
|
||||
}
|
||||
|
||||
void checkFilesRequest()
|
||||
{
|
||||
tkrFolderBrowser browser;
|
||||
int iRequests = iNoRequests;
|
||||
QObject::connect(&browser, &tkrFolderBrowser::openDocumentRequested, &browser, [&iRequests]() { ++iRequests; });
|
||||
auto *pOpen = browser.findChild<QPushButton *>(QStringLiteral("sidebarOpenDocumentButton"));
|
||||
require(pOpen && pOpen->isEnabled(), "Files shell must retain an available Open entry point");
|
||||
pOpen->click();
|
||||
require(iRequests == iOneRequest, "Open request must be emitted exactly once");
|
||||
}
|
||||
}
|
||||
|
||||
int main(int iArgumentCount, char **pArguments)
|
||||
{
|
||||
QApplication application(iArgumentCount, pArguments);
|
||||
checkSidebar();
|
||||
checkFilesRequest();
|
||||
qInfo("Sidebar collapse/reopen, page/width retention, accessible tabs, unavailable creation, source preservation and teardown passed.");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# Shared Alpha version - November 16, 2026
|
||||
|
||||
Bounded evidence for REQ-DEV-006 / TC-067 / VER-080. Product acceptance remains
|
||||
pending. The application and report baseline is Alpha 0.10.2.
|
||||
|
||||
- CMake reads `DocumentVersion` from the report source; both configured builds
|
||||
generated 0.10.2. Build metadata matches the actual Git HEAD and correctly
|
||||
identifies this source as a modified working tree.
|
||||
- `build-info.json` retains the actual build identity. `no-git-info.json` records
|
||||
the explicit unavailable-checkpoint/source-state fallback, which was checked
|
||||
by running the same generator with no Git executable.
|
||||
- All five Debug and Release CTests passed; transcripts are retained here.
|
||||
- A task-local Qt harness linked the actual Release editor libraries, opened the
|
||||
real Help > About action, compared the displayed version/checkpoint/state with
|
||||
the generated JSON, captured `about.png`, and closed its own windows. The
|
||||
offscreen capture was visually reviewed. The disposable harness was removed.
|
||||
- Native package startup with a Windows-only PATH showed Alpha 0.10.2 in its
|
||||
window title. The native window closed before About inspection, so native
|
||||
About-dialog verification is not claimed. The CUA session was reset afterward.
|
||||
- The existing package was moved to `code/packages/TikZRefinery-windows-x64/`;
|
||||
both example-file hashes were checked unchanged. The same-kit DLLs were reused.
|
||||
Its manifest and copied build identity match the Release executable.
|
||||
- Historical 1.x history entries are preserved. The new history entry explains
|
||||
major zero, weekly-report-based minor numbering and the shared baseline.
|
||||
|
||||
The clean-checkpoint condition must be rechecked after a future authorized
|
||||
commit and rebuild. This run does not claim a clean release, a clean-machine
|
||||
deployment, or that the pending deployment diagram has been completed.
|
||||
|
||||
Reproduction: build with the existing Qt/MinGW commands in `code/README.md`, run
|
||||
CTest, compare `build-info.json` with the report version and Git status, and open
|
||||
Help > About in the packaged application. The identity generator runs on each
|
||||
build and updates the header only when its contents change.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"applicationVersion": "0.10.2",
|
||||
"maturity": "Alpha",
|
||||
"sourceCheckpoint": "5a776cb24b0a0adb6caee674a253ce8d8a36d593",
|
||||
"sourceState": "modified working tree"
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
Start testing: Nov 16 13:53 Eastern Standard Time
|
||||
----------------------------------------------------------
|
||||
1/5 Testing: core_foundations
|
||||
1/5 Test: core_foundations
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/code/build/tikzrefinery_core_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/code/build
|
||||
"core_foundations" start time: Nov 16 13:53 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.15 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"core_foundations" end time: Nov 16 13:53 Eastern Standard Time
|
||||
"core_foundations" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
2/5 Testing: rectangle_display
|
||||
2/5 Test: rectangle_display
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/code/build/tikzrefinery_rectangle_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/code/build
|
||||
"rectangle_display" start time: Nov 16 13:53 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.78 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"rectangle_display" end time: Nov 16 13:53 Eastern Standard Time
|
||||
"rectangle_display" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
3/5 Testing: segment_display
|
||||
3/5 Test: segment_display
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/code/build/tikzrefinery_segment_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/code/build
|
||||
"segment_display" start time: Nov 16 13:53 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.56 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"segment_display" end time: Nov 16 13:53 Eastern Standard Time
|
||||
"segment_display" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
4/5 Testing: whole_element_drag
|
||||
4/5 Test: whole_element_drag
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/code/build/tikzrefinery_drag_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/code/build
|
||||
"whole_element_drag" start time: Nov 16 13:53 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.62 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"whole_element_drag" end time: Nov 16 13:53 Eastern Standard Time
|
||||
"whole_element_drag" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
5/5 Testing: rectangle_resize
|
||||
5/5 Test: rectangle_resize
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/code/build/tikzrefinery_resize_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/code/build
|
||||
"rectangle_resize" start time: Nov 16 13:53 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.57 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"rectangle_resize" end time: Nov 16 13:53 Eastern Standard Time
|
||||
"rectangle_resize" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
End testing: Nov 16 13:53 Eastern Standard Time
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"applicationVersion": "0.10.2",
|
||||
"maturity": "Alpha",
|
||||
"sourceCheckpoint": "unavailable",
|
||||
"sourceState": "source state unavailable"
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
Start testing: Nov 16 13:54 Eastern Standard Time
|
||||
----------------------------------------------------------
|
||||
1/5 Testing: core_foundations
|
||||
1/5 Test: core_foundations
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release/tikzrefinery_core_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release
|
||||
"core_foundations" start time: Nov 16 13:54 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.09 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"core_foundations" end time: Nov 16 13:54 Eastern Standard Time
|
||||
"core_foundations" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
2/5 Testing: rectangle_display
|
||||
2/5 Test: rectangle_display
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release/tikzrefinery_rectangle_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release
|
||||
"rectangle_display" start time: Nov 16 13:54 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.35 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"rectangle_display" end time: Nov 16 13:54 Eastern Standard Time
|
||||
"rectangle_display" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
3/5 Testing: segment_display
|
||||
3/5 Test: segment_display
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release/tikzrefinery_segment_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release
|
||||
"segment_display" start time: Nov 16 13:54 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.17 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"segment_display" end time: Nov 16 13:54 Eastern Standard Time
|
||||
"segment_display" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
4/5 Testing: whole_element_drag
|
||||
4/5 Test: whole_element_drag
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release/tikzrefinery_drag_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release
|
||||
"whole_element_drag" start time: Nov 16 13:54 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.23 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"whole_element_drag" end time: Nov 16 13:54 Eastern Standard Time
|
||||
"whole_element_drag" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
5/5 Testing: rectangle_resize
|
||||
5/5 Test: rectangle_resize
|
||||
Command: "C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release/tikzrefinery_resize_tests.exe"
|
||||
Directory: C:/Users/vince/Documents/Projects/TikZRefinery/work/alpha-version/release
|
||||
"rectangle_resize" start time: Nov 16 13:54 Eastern Standard Time
|
||||
Output:
|
||||
----------------------------------------------------------
|
||||
<end of output>
|
||||
Test time = 0.23 sec
|
||||
----------------------------------------------------------
|
||||
Test Passed.
|
||||
"rectangle_resize" end time: Nov 16 13:54 Eastern Standard Time
|
||||
"rectangle_resize" time elapsed: 00:00:00
|
||||
----------------------------------------------------------
|
||||
|
||||
End testing: Nov 16 13:54 Eastern Standard Time
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"TikZRefinerySubmission": {
|
||||
"pages": 179,
|
||||
"linksChecked": 2535,
|
||||
"targets": {
|
||||
"Table:DocumentHistory": 4,
|
||||
"Requirement:REQ-DEV-006": 59,
|
||||
"TestCase:TC-067": 113,
|
||||
"Table:TraceabilityMatrix": 125,
|
||||
"Verification:VER-080": 138
|
||||
},
|
||||
"renderedPages": [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
59,
|
||||
77,
|
||||
113,
|
||||
125,
|
||||
138
|
||||
]
|
||||
},
|
||||
"TikZRefinery": {
|
||||
"pages": 236,
|
||||
"linksChecked": 2732,
|
||||
"targets": {
|
||||
"Section:AlphaVersionReview": 230,
|
||||
"Table:DocumentHistory": 4,
|
||||
"Requirement:REQ-DEV-006": 60,
|
||||
"TestCase:TC-067": 114,
|
||||
"Table:TraceabilityMatrix": 126,
|
||||
"Verification:VER-080": 139
|
||||
},
|
||||
"renderedPages": [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
60,
|
||||
78,
|
||||
114,
|
||||
126,
|
||||
139,
|
||||
230
|
||||
]
|
||||
},
|
||||
"historicalEntriesUnchanged": true,
|
||||
"supplementalRenderedPages": {
|
||||
"TikZRefinerySubmission": [
|
||||
126,
|
||||
127,
|
||||
128
|
||||
],
|
||||
"TikZRefinery": [
|
||||
127,
|
||||
128,
|
||||
129,
|
||||
186,
|
||||
187
|
||||
]
|
||||
},
|
||||
"submissionSha256": "AD94E2288D3180585A7D2843FDE9486D984BBA1976EECE1093D5D2FC13D379E7",
|
||||
"developerSha256": "B94D47DF24F94C4393FB54BA33C3128FCCB3EEA2BDDC1455F249475B60DAD6B9"
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user