diff --git a/.github/workflows/code-visualizer.yml b/.github/workflows/code-visualizer.yml new file mode 100644 index 00000000000..7b079ceaf9a --- /dev/null +++ b/.github/workflows/code-visualizer.yml @@ -0,0 +1,115 @@ +name: Code Visualizer + +# The Code Visualizer lives outside the Maven reactor (scripts/code-visualizer) and PR +# CI ignores scripts/**, so nothing else compiles or tests it. Its tests drive the app +# through its MCP tools over a small git repository, under xvfb. +# +# A pull request runs it only when the visualizer's own files change. It is an ordinary +# application over core and the JavaSE port, whose API stays compatible, so a change +# there does not run it; the nightly run catches one that breaks it anyway. + +on: + workflow_dispatch: + schedule: + - cron: '11 0 * * *' + pull_request: + branches: + - master + paths: + - '.github/workflows/code-visualizer.yml' + - 'scripts/code-visualizer/**' + - 'scripts/code-visualizer.sh' + - '!scripts/code-visualizer/**/*.md' + - 'maven/code-model/**' + - 'maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/OpenCodeVisualizerMojo.java' + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + # The gate every PR workflow waits on: a PR missing a golden is known to + # fail as a whole, so nothing here runs until Golden capture + # (golden-capture.yml) has committed them. + golden-plan: + uses: ./.github/workflows/golden-plan.yml + permissions: + contents: read + + code-visualizer: + needs: golden-plan + if: needs.golden-plan.outputs.run == 'true' + runs-on: ubuntu-24.04 + timeout-minutes: 60 + container: ghcr.io/codenameone/codenameone/pr-ci-container:latest + defaults: + run: + shell: bash + + steps: + - uses: actions/checkout@v6 + + - name: Cache Maven dependencies + uses: actions/cache@v5 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-m2 + + - name: Use Google's copy of Maven Central first + uses: ./.github/actions/maven-central-mirror + + - name: Prepare Codename One binaries + # The JavaSE port needs jfxrt.jar from cn1-binaries; without it the + # build fails with a large, misleading set of missing javafx.* errors. + run: | + set -euo pipefail + rm -rf maven/target/cn1-binaries + mkdir -p maven/target + cp -r /opt/cn1-binaries maven/target/cn1-binaries + + - name: Install Codename One artifacts (JDK 8) + # JAVA_HOME_8 / JAVA_HOME_17 are container image environment variables, + # so they are expanded by the shell rather than the env context. + run: | + set -euo pipefail + export JAVA_HOME="${JAVA_HOME_8}" + export PATH="${JAVA_HOME}/bin:${PATH}" + cd maven + # Retried: Central has been answering 403 on this runner pool, and Maven treats a + # failed build-extension resolution as permanent -- the job dies in setup having + # proved nothing. Same rationale as setup-workspace.sh's mvn_retry. + bash ../scripts/ci/retry.sh mvn -B install -Plocal-dev-javase -DskipTests \ + -Darchetype.test.skip=true -Dmaven.javadoc.skip=true \ + -Dcn1.binaries="${GITHUB_WORKSPACE}/maven/target/cn1-binaries" + + # JDK 17: the analyzer parses with the in-tree compiler, which needs it at run time. + - name: Run Code Visualizer tests (JDK 17) + run: | + set -euo pipefail + git config --global --add safe.directory '*' + export JAVA_HOME="${JAVA_HOME_17}" + export PATH="${JAVA_HOME}/bin:${PATH}" + cd scripts/code-visualizer + xvfb-run -a mvn -B -pl javase -am -Pexecutable-jar clean test -Dcodename1.platform=javase + + - name: Package the executable Code Visualizer (JDK 17) + run: | + set -euo pipefail + export JAVA_HOME="${JAVA_HOME_17}" + export PATH="${JAVA_HOME}/bin:${PATH}" + cd scripts/code-visualizer + xvfb-run -a bash ../../scripts/ci/retry.sh \ + mvn -B -pl javase -am -Pexecutable-jar package \ + -Dcodename1.platform=javase -Dmaven.test.skip=true + ls javase/target/codenameone-code-visualizer-*.jar + + - name: Upload Code Visualizer test reports + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v7 + with: + name: code-visualizer-test-reports + path: scripts/code-visualizer/javase/target/surefire-reports + if-no-files-found: warn + retention-days: 14 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 17b7094b6c7..f294a470333 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -269,7 +269,7 @@ jobs: -Dcn1.binaries="${CN1_BINARIES}" \ -Pcompile-android \ -DbackendAnalysis \ - -pl android,ios,project-model,build-engine,codenameone-maven-plugin,codenameone-gradle-plugin,backend,backend-test,backend-parparvm,javac,android-res-compiler,android-compat,swing-compat,javafx-compat,compose-compat,rive-runtime,fxml-compiler,desktop-compat-runtime,cn1-app-kit/backend,cn1-app-kit/common,python-transpiler -am verify + -pl android,ios,project-model,build-engine,codenameone-maven-plugin,codenameone-gradle-plugin,backend,backend-test,backend-parparvm,javac,code-model,android-res-compiler,android-compat,swing-compat,javafx-compat,compose-compat,rive-runtime,fxml-compiler,desktop-compat-runtime,cn1-app-kit/backend,cn1-app-kit/common,python-transpiler -am verify # The step above skips tests, so the Android port's pure-Java unit tests # (maven/android/src/test) run here, against the classes it just built. - name: Run Android port unit tests @@ -516,7 +516,7 @@ jobs: - name: Generate static analysis HTML summaries if: ${{ !cancelled() && matrix.java-version == 8 }} env: - QUALITY_REPORT_TARGET_DIRS: maven/core-unittests/target:maven/android/target:maven/ios/target:vm/ByteCodeTranslator/target:maven/codenameone-maven-plugin/target:maven/build-engine/target:maven/project-model/target:maven/codenameone-gradle-plugin/target:maven/build-hint-catalog/target:maven/build-hint-tools/target:maven/backend/target:maven/backend-test/target:maven/backend-parparvm/target:maven/javac/target:maven/android-res-compiler/target:maven/android-compat/target:maven/swing-compat/target:maven/javafx-compat/target:maven/compose-compat/target:maven/fxml-compiler/target:maven/desktop-compat-runtime/target:maven/python-transpiler/target:maven/python-runtime/target:maven/rive-runtime/target + QUALITY_REPORT_TARGET_DIRS: maven/core-unittests/target:maven/android/target:maven/ios/target:vm/ByteCodeTranslator/target:maven/codenameone-maven-plugin/target:maven/build-engine/target:maven/project-model/target:maven/codenameone-gradle-plugin/target:maven/build-hint-catalog/target:maven/build-hint-tools/target:maven/backend/target:maven/backend-test/target:maven/backend-parparvm/target:maven/javac/target:maven/code-model/target:maven/android-res-compiler/target:maven/android-compat/target:maven/swing-compat/target:maven/javafx-compat/target:maven/compose-compat/target:maven/fxml-compiler/target:maven/desktop-compat-runtime/target:maven/python-transpiler/target:maven/python-runtime/target:maven/rive-runtime/target QUALITY_REPORT_SERVER_URL: ${{ github.server_url }} QUALITY_REPORT_REPOSITORY: ${{ github.repository }} QUALITY_REPORT_REF: ${{ github.event.pull_request.head.sha || github.sha }} @@ -548,7 +548,8 @@ jobs: "gradle-plugin:maven/codenameone-gradle-plugin/target" \ "backend:maven/backend/target" \ "backend-test:maven/backend-test/target" \ - "javac:maven/javac/target"; do + "javac:maven/javac/target" \ + "code-model:maven/code-model/target"; do label="${entry%%:*}" dir="${entry#*:}" for filename in spotbugsXml.xml spotbugs.xml; do @@ -674,11 +675,11 @@ jobs: - name: Generate quality report summary if: ${{ !cancelled() && matrix.java-version == 8 }} env: - QUALITY_REPORT_TARGET_DIRS: maven/core-unittests/target:maven/android/target:maven/ios/target:vm/ByteCodeTranslator/target:maven/codenameone-maven-plugin/target:maven/build-engine/target:maven/project-model/target:maven/codenameone-gradle-plugin/target:maven/build-hint-catalog/target:maven/build-hint-tools/target:maven/backend/target:maven/backend-test/target:maven/backend-parparvm/target:maven/javac/target:maven/android-res-compiler/target:maven/android-compat/target:maven/swing-compat/target:maven/javafx-compat/target:maven/compose-compat/target:maven/fxml-compiler/target:maven/desktop-compat-runtime/target:maven/python-transpiler/target:maven/python-runtime/target:maven/rive-runtime/target + QUALITY_REPORT_TARGET_DIRS: maven/core-unittests/target:maven/android/target:maven/ios/target:vm/ByteCodeTranslator/target:maven/codenameone-maven-plugin/target:maven/build-engine/target:maven/project-model/target:maven/codenameone-gradle-plugin/target:maven/build-hint-catalog/target:maven/build-hint-tools/target:maven/backend/target:maven/backend-test/target:maven/backend-parparvm/target:maven/javac/target:maven/code-model/target:maven/android-res-compiler/target:maven/android-compat/target:maven/swing-compat/target:maven/javafx-compat/target:maven/compose-compat/target:maven/fxml-compiler/target:maven/desktop-compat-runtime/target:maven/python-transpiler/target:maven/python-runtime/target:maven/rive-runtime/target # Every project listed here must produce a SpotBugs report and that # report must be empty. A missing report fails the gate too, so a # SpotBugs run that silently stops running is not mistaken for clean. - QUALITY_REPORT_REQUIRED_SPOTBUGS: core-unittests:android:ios:ByteCodeTranslator:codenameone-maven-plugin:build-engine:project-model:codenameone-gradle-plugin:build-hint-catalog:build-hint-tools:backend:backend-test:javac:android-res-compiler:android-compat:swing-compat:javafx-compat:compose-compat:fxml-compiler:desktop-compat-runtime:python-transpiler:python-runtime:rive-runtime + QUALITY_REPORT_REQUIRED_SPOTBUGS: core-unittests:android:ios:ByteCodeTranslator:codenameone-maven-plugin:build-engine:project-model:codenameone-gradle-plugin:build-hint-catalog:build-hint-tools:backend:backend-test:javac:code-model:android-res-compiler:android-compat:swing-compat:javafx-compat:compose-compat:fxml-compiler:desktop-compat-runtime:python-transpiler:python-runtime:rive-runtime # PMD and Checkstyle run on the core, the backend runtime and the Python # transpiler and runtime, and each must produce its report: without one, # the PMD gate below it has nothing to read and passes. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5fadbd75e30..94d4544476f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -204,6 +204,7 @@ jobs: codenameone-build-hint-catalog codenameone-build-hint-tools \ codenameone-cil-translator codenameone-unity-compat \ codenameone-rive-runtime codenameone-rive-transcoder \ + codenameone-code-model \ cn1app-archetype cn1lib-archetype \ cn1-app-kit-common cn1-app-kit-backend cn1-app-kit-lib; do url="${R2_BASE_URL}/com/codenameone/${artifact}/${GITHUB_REF_NAME}/${artifact}-${GITHUB_REF_NAME}.pom?cb=${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" @@ -442,6 +443,38 @@ jobs: [ "$code" = "200" ] || { echo "MISSING on R2: codenameone-guibuilder (HTTP $code)" >&2; exit 1; } echo "ok: codenameone-guibuilder ${GITHUB_REF_NAME} on R2" + # --- Code Visualizer ---------------------------------------------------- + # cn1:visualize resolves the visualizer and the analyzer (codenameone-code-model, + # published by the core reactor) at the plugin's own version, like cn1:guibuilder. + - name: Build and stage the Code Visualizer + id: deploy_codevisualizer + continue-on-error: true + if: >- + always() && (steps.deploy.outcome == 'success' || + steps.r2_core.outcome == 'success') + run: | + export GPG_TTY=$(tty) + cd scripts/code-visualizer + xvfb-run -a mvn -Pexecutable-jar -Pcodevisualizer-central deploy \ + -DskipPublishing=true \ + -Dcodename1.platform=javase \ + -Dgpg.passphrase=$MAVEN_GPG_PASSPHRASE \ + -Dcn1.version=$GITHUB_REF_NAME -Dcn1.plugin.version=$GITHUB_REF_NAME \ + -Dmaven.test.skip=true + env: + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + + - name: Publish Code Visualizer to R2 + id: r2_codevisualizer + continue-on-error: true + if: always() && steps.deploy_codevisualizer.conclusion != 'skipped' + run: | + bash maven/scripts/r2/publish-staging-to-r2.sh scripts/code-visualizer/target/central-staging + url="${R2_BASE_URL}/com/codenameone/codenameone-code-visualizer/${GITHUB_REF_NAME}/codenameone-code-visualizer-${GITHUB_REF_NAME}.pom?cb=${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + code=$(curl -s -o /dev/null -w "%{http_code}" "$url") + [ "$code" = "200" ] || { echo "MISSING on R2: codenameone-code-visualizer (HTTP $code)" >&2; exit 1; } + echo "ok: codenameone-code-visualizer ${GITHUB_REF_NAME} on R2" + # --- Flutter runtime and Dart runtime ----------------------------------- # codenameone-dart-runtime and codenameone-flutter-runtime compile at # release 17, so the maven/ reactor only includes them on JDK 17 (the @@ -513,6 +546,7 @@ jobs: steps.deploy_certificatewizard.outcome == 'success' && steps.deploy_settings.outcome == 'success' && steps.deploy_guibuilder.outcome == 'success' && + steps.deploy_codevisualizer.outcome == 'success' && steps.deploy_flutter.outcome == 'success' && steps.r2_core.outcome == 'success' && steps.r2_core_confirm.outcome == 'success' && @@ -520,6 +554,7 @@ jobs: steps.r2_certificatewizard.outcome == 'success' && steps.r2_settings.outcome == 'success' && steps.r2_guibuilder.outcome == 'success' && + steps.r2_codevisualizer.outcome == 'success' && steps.r2_flutter.outcome == 'success' run: bash maven/scripts/r2/mark-release-complete.sh "${GITHUB_REF_NAME}" @@ -573,6 +608,7 @@ jobs: bad "${{ steps.deploy_certificatewizard.outcome }}" && fail "Signing Wizard build" bad "${{ steps.deploy_settings.outcome }}" && fail "Settings build" bad "${{ steps.deploy_guibuilder.outcome }}" && fail "GUI Builder build" + bad "${{ steps.deploy_codevisualizer.outcome }}" && fail "Code Visualizer build" bad "${{ steps.deploy_flutter.outcome }}" && fail "Flutter runtimes build" bad "${{ steps.r2_core.outcome }}" && fail "core reactor -> R2" bad "${{ steps.r2_core_confirm.outcome }}" && fail "core artifacts missing on R2" @@ -580,6 +616,7 @@ jobs: bad "${{ steps.r2_certificatewizard.outcome }}" && fail "Signing Wizard -> R2" bad "${{ steps.r2_settings.outcome }}" && fail "Settings -> R2" bad "${{ steps.r2_guibuilder.outcome }}" && fail "GUI Builder -> R2" + bad "${{ steps.r2_codevisualizer.outcome }}" && fail "Code Visualizer -> R2" bad "${{ steps.r2_flutter.outcome }}" && fail "Flutter runtimes -> R2" bad "${{ steps.r2_mark_complete.outcome }}" && fail "marking the R2 release complete" bad "${{ steps.r2_metadata.outcome }}" && fail "R2 metadata regeneration" diff --git a/CLAUDE.md b/CLAUDE.md index 15a6e241c79..f0acc7fb374 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -114,7 +114,7 @@ PR CI (`.github/workflows/pr.yml`, Java 8 leg) runs SpotBugs over build plugins share), `project-model` (the project-layout API), `android-res-compiler` and `android-compat` (the Android compatibility runtime), `codenameone-gradle-plugin`, `javac` (the in-tree Java compiler, -`vm/JavaCompiler`) and `python-transpiler`, plus `python-runtime` in a step of +`vm/JavaCompiler`), `code-model` (the code visualizer's analyzer) and `python-transpiler`, plus `python-runtime` in a step of its own on JDK 17 (it compiles at release 17), then enforces the result in `.github/scripts/generate-quality-report.py`. `cil-translator` and `unity-compat` (the Unity compatibility translator and runtime) are held to the @@ -133,7 +133,7 @@ it runs only when the Unity tree itself changes, so a change to the core's `vm/ByteCodeTranslator/`, `maven/codenameone-maven-plugin/`, `maven/build-engine/`, `maven/project-model/`, `maven/android-res-compiler/`, `maven/android-compat/`, - `maven/codenameone-gradle-plugin/`, `maven/javac/`, + `maven/codenameone-gradle-plugin/`, `maven/javac/`, `maven/code-model/`, `maven/python-transpiler/`, `maven/python-runtime/`, `maven/cil-translator/`, `maven/unity-compat/`), scoped to the class or method it applies to and with a comment explaining why. Keep the @@ -148,7 +148,7 @@ To reproduce the SpotBugs gate locally: ```bash source tools/env.sh # JDK 8 cd maven && mvn -B -DskipTests=true -Pcompile-android \ - -pl android,ios,project-model,android-res-compiler,android-compat,build-engine,codenameone-maven-plugin,codenameone-gradle-plugin,javac -am verify + -pl android,ios,project-model,android-res-compiler,android-compat,build-engine,codenameone-maven-plugin,codenameone-gradle-plugin,javac,code-model -am verify mvn -B -DunitTests -DskipTests=true -pl core-unittests verify mvn -B -DskipTests=true -f ../vm/ByteCodeTranslator/pom.xml verify ``` diff --git a/CodenameOne/src/com/codename1/components/CoachMarks.java b/CodenameOne/src/com/codename1/components/CoachMarks.java index e0f66bcc970..3e935e5edd7 100644 --- a/CodenameOne/src/com/codename1/components/CoachMarks.java +++ b/CodenameOne/src/com/codename1/components/CoachMarks.java @@ -35,6 +35,7 @@ import com.codename1.ui.events.ActionEvent; import com.codename1.ui.events.ActionListener; import com.codename1.ui.geom.Dimension; +import com.codename1.ui.geom.Rectangle; import com.codename1.ui.layouts.BorderLayout; import com.codename1.ui.layouts.BoxLayout; import com.codename1.ui.layouts.FlowLayout; @@ -119,7 +120,29 @@ public CoachMarks(Form form) { /// /// this, for chaining public CoachMarks add(Component target, String title, String text) { - steps.add(new Step(target, title, text)); + steps.add(new Step(target, null, title, text)); + return this; + } + + /// Adds a step that lights part of a component: one box of a chart, one line of a + /// list or an editor, a region of a canvas. + /// + /// #### Parameters + /// + /// - `target`: the component holding the part; it must be on the form when its + /// step shows + /// + /// - `area`: the part to light, in pixels relative to the target's top left corner + /// + /// - `title`: a short title, or null + /// + /// - `text`: what the part is + /// + /// #### Returns + /// + /// this, for chaining + public CoachMarks add(Component target, Rectangle area, String title, String text) { + steps.add(new Step(target, area == null ? null : new Rectangle(area), title, text)); return this; } @@ -305,13 +328,21 @@ public void actionPerformed(ActionEvent evt) { } } + /// The lit area of the current step as {x, y, width, height} relative to the overlay, + /// or null; for tests. + int[] litArea() { + return overlay == null ? null : overlay.hole(); + } + private static final class Step { final Component target; + final Rectangle area; final String title; final String text; - Step(Component target, String title, String text) { + Step(Component target, Rectangle area, String title, String text) { this.target = target; + this.area = area; this.title = title; this.text = text; } @@ -481,6 +512,18 @@ int[] hole() { int pad = CN.convertToPixels(1.5f); int x = t.getAbsoluteX() - getAbsoluteX() + getX() - pad; int y = t.getAbsoluteY() - getAbsoluteY() + getY() - pad; + Rectangle a = step.area; + if (a != null) { + // Part of the target, clipped to what of the target is visible. + int ax = Math.max(0, a.getX()); + int ay = Math.max(0, a.getY()); + int aw = Math.min(t.getWidth(), a.getX() + a.getWidth()) - ax; + int ah = Math.min(t.getHeight(), a.getY() + a.getHeight()) - ay; + if (aw <= 0 || ah <= 0) { + return null; + } + return new int[]{x + ax, y + ay, aw + pad * 2, ah + pad * 2}; + } return new int[]{x, y, t.getWidth() + pad * 2, t.getHeight() + pad * 2}; } diff --git a/CodenameOne/src/com/codename1/graph/GraphEdge.java b/CodenameOne/src/com/codename1/graph/GraphEdge.java index 590cd3fa416..5e1affb3225 100644 --- a/CodenameOne/src/com/codename1/graph/GraphEdge.java +++ b/CodenameOne/src/com/codename1/graph/GraphEdge.java @@ -54,6 +54,7 @@ public class GraphEdge { private final String targetId; private final String targetPortId; private String label; + private String tooltip; private boolean directed = true; private String styleKey; private Object userData; @@ -215,4 +216,15 @@ public GraphEdge copy(String newId, String newSourceId, String newTargetId) { public boolean touches(String nodeId) { return nodeId != null && (nodeId.equals(sourceId) || nodeId.equals(targetId)); } + + /// The text a `NodeGraph` shows beside the pointer while it rests on this edge, or null for + /// none. Desktop and other hovering pointers only; a touch screen never shows it. + public String getTooltip() { + return tooltip; + } + + /// Sets the hover text; null removes it. + public void setTooltip(String tooltip) { + this.tooltip = tooltip; + } } diff --git a/CodenameOne/src/com/codename1/graph/GraphNode.java b/CodenameOne/src/com/codename1/graph/GraphNode.java index 7d24d60c240..6924c38ab98 100644 --- a/CodenameOne/src/com/codename1/graph/GraphNode.java +++ b/CodenameOne/src/com/codename1/graph/GraphNode.java @@ -33,6 +33,7 @@ public class GraphNode { private final String id; private String label; + private String tooltip; private String description; private double x; private double y; @@ -299,4 +300,15 @@ public GraphNode copy(String newId) { public boolean contains(double px, double py) { return px >= x && py >= y && px < x + width && py < y + height; } + + /// The text a `NodeGraph` shows beside the pointer while it rests on this node, or null for + /// none. Desktop and other hovering pointers only; a touch screen never shows it. + public String getTooltip() { + return tooltip; + } + + /// Sets the hover text; null removes it. + public void setTooltip(String tooltip) { + this.tooltip = tooltip; + } } diff --git a/CodenameOne/src/com/codename1/ui/CodeEditor.java b/CodenameOne/src/com/codename1/ui/CodeEditor.java index 7abf71dead7..cd7bb636f52 100644 --- a/CodenameOne/src/com/codename1/ui/CodeEditor.java +++ b/CodenameOne/src/com/codename1/ui/CodeEditor.java @@ -311,6 +311,44 @@ public void setDiagnostics(List diagnostics) { command("setDiagnostics", diagnosticsJson(diagnostics)); } + /// Paints bands of whole lines behind the text, replacing any set before; pass an empty list + /// (or null) to clear them. Useful to show what a change touched or which lines a tool is + /// pointing at. A port's native editor may not support bands and then ignores them. + /// + /// #### Parameters + /// + /// - `highlights`: the bands to paint + public void setLineHighlights(List highlights) { + StringBuilder sb = new StringBuilder("["); + if (highlights != null) { + for (CodeLineHighlight h : highlights) { + if (h == null) { + continue; + } + if (sb.length() > 1) { + sb.append(','); + } + sb.append("{\"l\":").append(h.getStartLine()) + .append(",\"el\":").append(h.getEndLine()) + .append(",\"c\":").append(h.getColor()) + .append(",\"a\":").append(h.getAlpha()) + .append('}'); + } + } + sb.append(']'); + command("setLineHighlights", sb.toString()); + } + + /// Scrolls so that a line is in view, with the caret at its start, as a go-to-line command does. + /// A line past the end of the document goes to the last line. + /// + /// #### Parameters + /// + /// - `line`: the 1-based line + public void scrollToLine(int line) { + command("scrollToLine", String.valueOf(Math.max(1, line))); + } + private static String diagnosticsJson(List diagnostics) { StringBuilder sb = new StringBuilder("["); if (diagnostics != null) { diff --git a/CodenameOne/src/com/codename1/ui/CodeLineHighlight.java b/CodenameOne/src/com/codename1/ui/CodeLineHighlight.java new file mode 100644 index 00000000000..854defcac10 --- /dev/null +++ b/CodenameOne/src/com/codename1/ui/CodeLineHighlight.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.ui; + +/// A band of whole lines painted behind the text of a `CodeEditor`: the lines a change +/// touched, the body of a method being inspected, the lines a search found. +/// +/// Lines are 1-based and the range is inclusive. The color is `0xRRGGBB`, painted at +/// the given opacity so the syntax colors stay readable on top of it. Where two bands +/// overlap, the one given later is painted over the earlier one. +public final class CodeLineHighlight { + private final int startLine; + private final int endLine; + private final int color; + private final int alpha; + + /// A band from `startLine` to `endLine`, inclusive, at the default opacity. + /// + /// #### Parameters + /// + /// - `startLine`: the first 1-based line + /// + /// - `endLine`: the last 1-based line; a value below `startLine` paints `startLine` alone + /// + /// - `color`: the band's color, `0xRRGGBB` + public CodeLineHighlight(int startLine, int endLine, int color) { + this(startLine, endLine, color, 64); + } + + /// A band with an explicit opacity. + /// + /// #### Parameters + /// + /// - `startLine`: the first 1-based line + /// + /// - `endLine`: the last 1-based line + /// + /// - `color`: the band's color, `0xRRGGBB` + /// + /// - `alpha`: the opacity, 0 (invisible) to 255 (opaque) + public CodeLineHighlight(int startLine, int endLine, int color, int alpha) { + this.startLine = Math.max(1, startLine); + this.endLine = Math.max(this.startLine, endLine); + this.color = color & 0xffffff; + this.alpha = Math.max(0, Math.min(255, alpha)); + } + + /// The first 1-based line. + public int getStartLine() { + return startLine; + } + + /// The last 1-based line, inclusive. + public int getEndLine() { + return endLine; + } + + /// The color, `0xRRGGBB`. + public int getColor() { + return color; + } + + /// The opacity, 0 to 255. + public int getAlpha() { + return alpha; + } +} diff --git a/CodenameOne/src/com/codename1/ui/ContextMenu.java b/CodenameOne/src/com/codename1/ui/ContextMenu.java index fe8b88e3e69..1304e370de3 100644 --- a/CodenameOne/src/com/codename1/ui/ContextMenu.java +++ b/CodenameOne/src/com/codename1/ui/ContextMenu.java @@ -93,7 +93,7 @@ public static Command show(Component anchor, int x, int y, Command... commands) // A one-pixel rectangle at the pointer: the popup points at where the user clicked, // not at the middle of whatever they clicked on. Anchoring to the component would put // a menu for a full-width row in the centre of the screen. - menu.showPopupDialog(new Rectangle(x, y, 1, 1)); + showUndimmed(menu, host != null ? host : CN.getCurrentForm(), new Rectangle(x, y, 1, 1), null); return chosen[0]; } @@ -115,10 +115,44 @@ public static Command show(Component anchor, Command... commands) { return null; } Command[] chosen = new Command[1]; - build(commands, chosen).showPopupDialog(anchor); + showUndimmed(build(commands, chosen), anchor.getTopLevelContainer(), null, anchor); return chosen[0]; } + /// Shows the popup without dimming what is behind it. + /// + /// A popup dialog dims its host with the host's tint, which suits a dialog that asks a + /// question and does not suit a context menu: no desktop or mobile platform greys the + /// window out for one, and it read as the whole application freezing. `ComboBox` + /// opts out the same way, by zeroing the host's tint while its popup is up. + /// + /// #### Parameters + /// + /// - `menu`: the popup + /// + /// - `host`: the top level it opens over, possibly null + /// + /// - `at`: the point to open at, or null to point at `anchor` + /// + /// - `anchor`: the component to point at when `at` is null + private static void showUndimmed(Dialog menu, TopLevelContainer host, Rectangle at, Component anchor) { + int tint = host != null ? host.getTintColor() : 0; + if (host != null) { + host.setTintColor(0); + } + try { + if (at != null) { + menu.showPopupDialog(at); + } else { + menu.showPopupDialog(anchor); + } + } finally { + if (host != null) { + host.setTintColor(tint); + } + } + } + /// True when the array holds at least one command to show. /// /// Length alone is not the question. `build` skips null entries, so an array that is diff --git a/CodenameOne/src/com/codename1/ui/ScrollSurface.java b/CodenameOne/src/com/codename1/ui/ScrollSurface.java index 7d11bc9ccaa..32dd843570f 100644 --- a/CodenameOne/src/com/codename1/ui/ScrollSurface.java +++ b/CodenameOne/src/com/codename1/ui/ScrollSurface.java @@ -1151,7 +1151,11 @@ protected boolean pinch(float scale) { pinchBase = 1f; } float step = scale / pinchBase; - if (zoomBy(step, lastX, lastY)) { + // A trackpad pinch comes with no button down: zoom around the pointer, not the + // place last pressed. + int ax = pressed || hoverX < 0 ? lastX : hoverX; + int ay = pressed || hoverX < 0 ? lastY : hoverY; + if (zoomBy(step, ax, ay)) { pinchBase = scale; pinching = true; if (gesture == EDIT) { diff --git a/CodenameOne/src/com/codename1/ui/editor/CodePureEditor.java b/CodenameOne/src/com/codename1/ui/editor/CodePureEditor.java index 9d1dd019f3d..72036abcac2 100644 --- a/CodenameOne/src/com/codename1/ui/editor/CodePureEditor.java +++ b/CodenameOne/src/com/codename1/ui/editor/CodePureEditor.java @@ -26,6 +26,7 @@ import com.codename1.io.JSONParser; import com.codename1.ui.CodeCompletion; import com.codename1.ui.CodeDiagnostic; +import com.codename1.ui.CodeLineHighlight; import java.util.ArrayList; import java.util.List; @@ -78,6 +79,14 @@ public void cmd(String name, String arg) { codeView.setDiagnostics(parseDiagnostics(arg)); return; } + if ("setLineHighlights".equals(name)) { + codeView.setLineHighlights(parseLineHighlights(arg)); + return; + } + if ("scrollToLine".equals(name)) { + codeView.scrollToLine(parseInt(arg, 1)); + return; + } if ("setProtectedMarkers".equals(name)) { int separator = arg == null ? -1 : arg.indexOf('\n'); codeView.setProtectedRegionMarkers( @@ -140,6 +149,20 @@ private List parseDiagnostics(String json) { return out; } + private List parseLineHighlights(String json) { + List out = new ArrayList(); + for (Object o : parseArray(json)) { + if (!(o instanceof Map)) { + continue; + } + Map m = (Map) o; + int line = intVal(m.get("l"), 1); + out.add(new CodeLineHighlight(line, intVal(m.get("el"), line), intVal(m.get("c"), 0xffff00), + intVal(m.get("a"), 64))); + } + return out; + } + private List parseCompletions(String json) { List out = new ArrayList(); List arr = parseArray(json); diff --git a/CodenameOne/src/com/codename1/ui/editor/CodeView.java b/CodenameOne/src/com/codename1/ui/editor/CodeView.java index 442b14f443d..25f48a75fe9 100644 --- a/CodenameOne/src/com/codename1/ui/editor/CodeView.java +++ b/CodenameOne/src/com/codename1/ui/editor/CodeView.java @@ -27,6 +27,7 @@ import com.codename1.util.Bidi; import com.codename1.ui.CodeCompletion; import com.codename1.ui.CodeDiagnostic; +import com.codename1.ui.CodeLineHighlight; import com.codename1.ui.Display; import com.codename1.ui.Font; import com.codename1.ui.Graphics; @@ -54,6 +55,7 @@ public class CodeView extends EditorView { private int validUpTo; private List diagnostics; + private List lineHighlights; private boolean completionEnabled; private List completionAll; @@ -112,6 +114,19 @@ public void setTabSize(int tabSize) { this.tabSize = Math.max(1, tabSize); } + /// Sets the bands of whole lines painted behind the text; null or empty clears them. + public void setLineHighlights(List highlights) { + this.lineHighlights = highlights == null || highlights.isEmpty() ? null : highlights; + repaint(); + } + + /// Moves the caret to the start of a 1-based line, which scrolls it into view. + public void scrollToLine(int line) { + EditorDocument d = getDocument(); + int ln = Math.max(0, Math.min(d.getLineCount() - 1, line - 1)); + moveCaret(d.getLineStart(ln), false); + } + /// Sets the diagnostics to render. public void setDiagnostics(List diagnostics) { this.diagnostics = diagnostics; @@ -285,6 +300,7 @@ private int gutterWidth() { @Override protected void paintBeforeContent(Graphics g, int originX, int originY, int firstLine, int lastLine, int lineHeight, Font f) { + paintLineHighlights(g, originX, originY, firstLine, lastLine, lineHeight); if (!showLineNumbers) { return; } @@ -306,6 +322,26 @@ protected void paintBeforeContent(Graphics g, int originX, int originY, int firs } } + private void paintLineHighlights(Graphics g, int originX, int originY, int firstLine, int lastLine, + int lineHeight) { + if (lineHighlights == null) { + return; + } + int oldAlpha = g.getAlpha(); + int right = getX() + getWidth(); + for (CodeLineHighlight h : lineHighlights) { + int from = Math.max(firstLine, h.getStartLine() - 1); + int to = Math.min(lastLine, h.getEndLine() - 1); + if (from > to) { + continue; + } + g.setColor(h.getColor()); + g.setAlpha(h.getAlpha()); + g.fillRect(originX, originY + from * lineHeight, right - originX, (to - from + 1) * lineHeight); + } + g.setAlpha(oldAlpha); + } + private int gutterMarkerColor(int line) { if (diagnostics == null) { return -1; diff --git a/CodenameOne/src/com/codename1/ui/graph/NodeGraph.java b/CodenameOne/src/com/codename1/ui/graph/NodeGraph.java index ac186586e46..53de4df0e17 100644 --- a/CodenameOne/src/com/codename1/ui/graph/NodeGraph.java +++ b/CodenameOne/src/com/codename1/ui/graph/NodeGraph.java @@ -2255,6 +2255,7 @@ void paintGraphOverlay(Graphics g, int w, int h) { if (minimapVisible) { paintMinimap(g, w, h); } + paintTooltip(g, w, h); g.setAntiAliased(aa); } @@ -2582,7 +2583,111 @@ private void minimapJump(int sx, int sy) { // ---------------------------------------------------------------- pointer + // ------------------------------------------------------------------ hover tooltip + + /// The item under a resting pointer whose tooltip is showing, a node or an edge, or null. + private Object tipItem; + private int tipX; + private int tipY; + + /// A hovering pointer at `sx, sy` of the view: shows the tooltip of the node or edge + /// there, the node winning where they overlap. + void hovered(int sx, int sy) { + if (gesture != G_NONE) { + return; + } + Object item = null; + GraphNode n = nodeAt(sx, sy); + if (n != null) { + item = n.getTooltip() == null ? null : n; + } else { + GraphEdge e = edgeAt(sx, sy); + item = e == null || e.getTooltip() == null ? null : e; + } + boolean same = item == tipItem; // NOPMD CompareObjectsWithEquals - the same node or edge + if (!same || item != null && (Math.abs(sx - tipX) > GraphLook.mm(4) + || Math.abs(sy - tipY) > GraphLook.mm(4))) { + tipItem = item; + tipX = sx; + tipY = sy; + canvas.repaint(); + } + } + + private void hideTooltip() { + if (tipItem != null) { + tipItem = null; + canvas.repaint(); + } + } + + /// The text of the tooltip showing, or null: what a test or an accessibility layer reads. + public String getVisibleTooltip() { + if (tipItem instanceof GraphNode) { + return ((GraphNode) tipItem).getTooltip(); + } + return tipItem instanceof GraphEdge ? ((GraphEdge) tipItem).getTooltip() : null; + } + + /// Simulates a hovering pointer at `x, y` of the view, as a desktop mouse would. + public void hoverAt(int x, int y) { + hovered(x, y); + } + + private void paintTooltip(Graphics g, int w, int h) { + String text = getVisibleTooltip(); + if (text == null || text.length() == 0) { + return; + } + Font f = GraphLook.font("NodeGraphNode", 1f); + int pad = GraphLook.mm(1.8f); + int maxW = Math.min(GraphLook.mm(80), w - pad * 4); + List lines = wrapTooltip(f, text, maxW); + int lh = f.getHeight(); + int tw = 0; + for (int i = 0; i < lines.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: painted every frame + tw = Math.max(tw, f.stringWidth(lines.get(i))); + } + int bw = tw + pad * 2; + int bh = lh * lines.size() + pad * 2; + int bx = Math.max(pad, Math.min(tipX + GraphLook.mm(3), w - bw - pad)); + int by = tipY + GraphLook.mm(4); + if (by + bh > h - pad) { + by = Math.max(pad, tipY - bh - GraphLook.mm(2)); + } + int alpha = g.getAlpha(); + g.setAlpha(240); + g.setColor(0x26282c); + g.fillRoundRect(bx, by, bw, bh, pad * 2, pad * 2); + g.setAlpha(alpha); + g.setColor(0xf2f2f2); + g.setFont(f); + for (int i = 0; i < lines.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: painted every frame + g.drawString(lines.get(i), bx + pad, by + pad + i * lh); + } + } + + private static List wrapTooltip(Font f, String text, int maxW) { + List out = new ArrayList(); + for (String para : com.codename1.util.StringUtil.tokenize(text, '\n')) { + StringBuilder line = new StringBuilder(); + for (String word : com.codename1.util.StringUtil.tokenize(para, ' ')) { + if (line.length() > 0 && f.stringWidth(line + " " + word) > maxW) { + out.add(line.toString()); + line.setLength(0); + } + if (line.length() > 0) { + line.append(' '); + } + line.append(word); + } + out.add(line.toString()); + } + return out; + } + void pressed(int x, int y) { + hideTooltip(); endLabelEdit(); gesture = G_NONE; shiftDown = Display.getInstance().isShiftKeyDown(); @@ -3443,6 +3548,12 @@ protected void pressStarted(int x, int y) { pressed(x, y); } + @Override + public void pointerHover(int[] x, int[] y) { + super.pointerHover(x, y); + hovered(x[0] - getAbsoluteX(), y[0] - getAbsoluteY()); + } + @Override protected boolean editStarted(int x, int y, EditTrigger trigger) { // nodes and ports are handles of their own, so a plain drag and a diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java index 9924d08d6fb..ca43fb64531 100644 --- a/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java +++ b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java @@ -4718,6 +4718,9 @@ protected class C extends JPanel implements KeyListener, MouseListener, MouseMot private java.awt.Dimension forcedSize; private boolean releaseLock; private double magnificationAccumulator; + // The last hover position in surface pixels, -1 before the pointer entered. + private int hoverX = -1; + private int hoverY = -1; private Set nativeMagnificationTargets = Collections.newSetFromMap(new IdentityHashMap()); private java.util.List nativeMagnificationListeners = new ArrayList(); private AWTEventListener magnificationWheelFallbackListener; @@ -4930,8 +4933,11 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl Object value = getMagnification.invoke(args[0]); if (value instanceof Number) { debugGesture("native magnification " + value); - handleMagnification(scaleCoordinateX(getWidth() / 2), - scaleCoordinateY(getHeight() / 2), + // A trackpad magnify carries no position. It used to be + // reported at the window centre, which sent every pinch to + // the component in the middle; the pointer is where it is. + handleMagnification(hoverX >= 0 ? hoverX : scaleCoordinateX(getWidth() / 2), + hoverY >= 0 ? hoverY : scaleCoordinateY(getHeight() / 2), ((Number)value).doubleValue()); } } @@ -5387,6 +5393,59 @@ public void blit(int x, int y, int w, int h) { protected void paintChildren(java.awt.Graphics g) { } + /// Paints the Swing children into the screen raster, which is in Codename One + /// pixels. The native editor's bounds are in AWT points -- they have to be, + /// because they are also where AWT delivers its mouse events -- so it is + /// painted scaled by this canvas's backing scale, and clipped out of the + /// regular pass. Its bounds used to be left in Codename One pixels instead, + /// which drew it in the right place but made it twice its size to the mouse: + /// a text area in a dialog covered the dialog's buttons. + private void paintChildrenScaledEditor(Graphics2D bg) { + double scale = canvasScale(); + JComponent editor = textCmp; + java.awt.Component legacy = legacyEditor; + boolean ownEditor = editor != null && editor.getParent() == this && editor.isVisible(); + boolean ownLegacy = legacy != null && legacy.getParent() == this && legacy.isVisible(); + if (scale == 1 || (!ownEditor && !ownLegacy)) { + super.paintChildren(bg); + return; + } + // Leave the editors out of the regular pass: their bounds are points, and + // painted there they would land at 1/scale of their place. + java.awt.Shape oldClip = bg.getClip(); + java.awt.geom.Area rest = new java.awt.geom.Area(oldClip != null ? oldClip + : new Rectangle(0, 0, buffer.getWidth(), buffer.getHeight())); + if (ownEditor) { + rest.subtract(new java.awt.geom.Area(editor.getBounds())); + } + if (ownLegacy) { + rest.subtract(new java.awt.geom.Area(legacy.getBounds())); + } + bg.setClip(rest); + super.paintChildren(bg); + bg.setClip(oldClip); + if (ownEditor) { + paintScaled(bg, editor, scale); + } + if (ownLegacy) { + paintScaled(bg, legacy, scale); + } + } + + /// Paints `c`, whose bounds are AWT points, at `scale` into the pixel raster. + private void paintScaled(Graphics2D bg, java.awt.Component c, double scale) { + Rectangle eb = c.getBounds(); + Graphics2D eg = (Graphics2D) bg.create(); + try { + eg.scale(scale, scale); + eg.translate(eb.x, eb.y); + eg.clipRect(0, 0, eb.width, eb.height); + c.paint(eg); + } finally { + eg.dispose(); + } + } + /// Paints the Swing children into the screen raster. In the simulated /// keyboard's Android pan mode the native editor's bounds are raised by the /// pan offset, so that it sits, and takes clicks, where the panned field is @@ -5551,13 +5610,16 @@ private boolean drawScreenBuffer(java.awt.Graphics g) { } else { if(getComponentCount() > 0) { Graphics2D bg = buffer.createGraphics(); + // zoomLevel only differs from 1 with a skin (set from the skin's size and + // restored after a screenshot), so without a skin the native editor is + // always painted by paintChildrenScaledEditor below. if(zoomLevel != 1) { AffineTransform af = bg.getTransform(); bg.setTransform(AffineTransform.getScaleInstance(1, 1)); super.paintChildren(bg); bg.setTransform(af); } else { - super.paintChildren(bg); + paintChildrenScaledEditor(bg); } bg.dispose(); painted = true; @@ -6429,6 +6491,8 @@ public void mouseMoved(MouseEvent e) { int x = scaleCoordinateX(e.getX()); int y = scaleCoordinateY(e.getY()); if (x >= 0 && x < surfaceWidth() && y >= 0 && y < surfaceHeight()) { + hoverX = x; + hoverY = y; JavaSEPort.this.windowPointerHover(windowId, x, y); } @@ -13303,7 +13367,8 @@ public void editStringLegacy(final Component cmp, int maxSize, int constraint, S double legacyScale = editorCanvas.canvasScale(); tf.setBounds((int) (cmp.getAbsoluteX() / legacyScale), (int) (cmp.getAbsoluteY() / legacyScale), (int) (cmp.getWidth() / legacyScale), (int) (cmp.getHeight() / legacyScale)); - tf.setFont(font(cmp.getStyle().getFont().getNativeFont())); + // In points like the bounds; paintChildrenScaledEditor paints it scaled. + tf.setFont(editorFont(font(cmp.getStyle().getFont().getNativeFont()), editorFontScale(legacyScale))); } setCaretPosition(tf, getText(tf).length()); tf.requestFocus(); @@ -13455,15 +13520,48 @@ private void applyEditorBounds(com.codename1.ui.Component cmp) { if (textCmp == null || cmp == null) { return; } + textCmp.setBounds(editorBounds(cmp)); + } + + /** + * Where the Swing editor goes over {@code cmp}, in AWT points of the canvas it is + * attached to: the field less its padding, divided by that canvas's scale. Every + * placement of the Swing editor goes through here, so none can disagree with it. + */ + private Rectangle editorBounds(com.codename1.ui.Component cmp) { int marginTop = cmp.getSelectedStyle().getPadding(Component.TOP); int marginLeft = cmp.getSelectedStyle().getPadding(Component.LEFT); int marginRight = cmp.getSelectedStyle().getPadding(Component.RIGHT); int marginBottom = cmp.getSelectedStyle().getPadding(Component.BOTTOM); - double editorScale = editorCanvasFor(cmp).canvasScale(); - textCmp.setBounds((int) ((cmp.getAbsoluteX() + cmp.getScrollX() + marginLeft) / editorScale), - (int) ((cmp.getAbsoluteY() + cmp.getScrollY() + marginTop) / editorScale), - (int) ((cmp.getWidth() - marginRight - marginLeft) / editorScale), - (int) ((cmp.getHeight() - marginTop - marginBottom) / editorScale)); + return editorBounds(cmp.getAbsoluteX() + cmp.getScrollX(), cmp.getAbsoluteY() + cmp.getScrollY(), + cmp.getWidth(), cmp.getHeight(), marginTop, marginLeft, marginBottom, marginRight, + editorCanvasFor(cmp).canvasScale()); + } + + /** + * The arithmetic of {@link #editorBounds(com.codename1.ui.Component)}: a field at + * {@code x, y} of {@code width x height} Codename One pixels, less its padding, in + * AWT points of a canvas with backing scale {@code scale}. + */ + static Rectangle editorBounds(int x, int y, int width, int height, int padTop, int padLeft, + int padBottom, int padRight, double scale) { + return new Rectangle((int) ((x + padLeft) / scale), (int) ((y + padTop) / scale), + (int) ((width - padLeft - padRight) / scale), (int) ((height - padTop - padBottom) / scale)); + } + + /// The scale the native editor's font is divided by: the canvas scale where the editor is + /// painted scaled back up into the canvas (no skin), and 1 with a skin, whose paint path + /// draws the editor unscaled. + private double editorFontScale(double canvasScale) { + return getSkin() != null ? 1 : canvasScale; + } + + /** + * The editor's font in AWT points: the editor is painted scaled by its canvas, so a + * font sized in Codename One pixels would come out {@code scale} times too large. + */ + static java.awt.Font editorFont(java.awt.Font cn1Font, double scale) { + return cn1Font.deriveFont((float) (cn1Font.getSize2D() / scale)); } /** @@ -14719,7 +14817,13 @@ void repaint(long tm, int x, int y, int width, int height) { (int) ((cmp.getHeight() - marginTop - marginBottom) * zoomLevel)); } else { - bounds = new Rectangle(cmp.getAbsoluteX() + cmp.getScrollX() + marginLeft, cmp.getAbsoluteY() + cmp.getScrollY() + marginTop, cmp.getWidth() - marginRight - marginLeft, cmp.getHeight() - marginTop - marginBottom); + // The placement applyEditorBounds gives the editor, not the field's + // raw bounds. These are Codename One pixels: on a backing scale of 2 + // this doubled the editor on the first repaint, and a multi-line + // editor repaints on every key -- so typing one character grew it + // over everything below the field. In a dialog that was the + // buttons, which then took no clicks until the edit ended. + bounds = editorBounds(cmp); } if (!jcmp.getBounds().equals(bounds)) { jcmp.setBounds(bounds); @@ -14730,7 +14834,12 @@ void repaint(long tm, int x, int y, int width, int height) { // origBorder, // BorderFactory.createEmptyBorder(paddingTop, paddingLeft, paddingBottom, paddingRight)) //); - jcmp.setBorder( BorderFactory.createEmptyBorder(paddingTop, paddingLeft, paddingBottom, paddingRight)); + if (getSkin() != null) { + jcmp.setBorder( BorderFactory.createEmptyBorder(paddingTop, paddingLeft, paddingBottom, paddingRight)); + } else { + // editorBounds already leaves the padding out of the bounds. + jcmp.setBorder(BorderFactory.createEmptyBorder()); + } } showEDTWarnings = oldShowEdtWarnings; @@ -14876,10 +14985,30 @@ public void repaint(long tm, int x, int y, int width, int height) { txt.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { + // Tab moves focus (keyReleased); it is never text, or a multi-line + // field takes a tab character on its way out. + if (e.getKeyChar() == '\t') { + e.consume(); + } } @Override public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_TAB) { + e.consume(); + return; + } + // Cmd-Enter on the Mac, Ctrl-Enter elsewhere: submit the dialog or + // form. Consumed so a multi-line editor does not also add a line. + // Only when there is a default command to fire: elsewhere the key keeps + // its usual meaning, such as committing a single-line field. + if (e.getKeyCode() == KeyEvent.VK_ENTER + && (e.isMetaDown() || e.isControlDown()) + && cmp.getComponentForm() != null + && cmp.getComponentForm().getDefaultCommand() != null) { + e.consume(); + TextEditUtil.submitDefaultCommand(); + } } @Override @@ -14926,7 +15055,9 @@ public void keyReleased(KeyEvent e) { tf.setFont(f.deriveFont(f.getSize2D() * zoomLevel)); } else { applyEditorBounds(cmp); - tf.setFont(font(cmp.getStyle().getFont().getNativeFont())); + // In points, like the bounds: the editor is painted scaled by the canvas. + tf.setFont(editorFont(font(cmp.getStyle().getFont().getNativeFont()), + editorFontScale(editorCanvasFor(cmp).canvasScale()))); } if (tf instanceof JPasswordField && tf.getFont() != null && tf.getFont().getFontName().contains("Roboto")) { java.awt.Font fallback = new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.PLAIN, tf.getFont().getSize()); diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/TextEditUtil.java b/Ports/JavaSE/src/com/codename1/impl/javase/TextEditUtil.java index 5d82b445993..1f42c6ba03f 100644 --- a/Ports/JavaSE/src/com/codename1/impl/javase/TextEditUtil.java +++ b/Ports/JavaSE/src/com/codename1/impl/javase/TextEditUtil.java @@ -25,7 +25,10 @@ import com.codename1.ui.Component; import com.codename1.ui.Display; +import com.codename1.ui.Command; import com.codename1.ui.Form; +import com.codename1.ui.TextArea; +import com.codename1.ui.events.ActionEvent; /** * Helper method for textfield onscreen keyboard (editStringAt) @@ -62,20 +65,7 @@ public static void editNextTextArea() { Runnable task = new Runnable() { public void run() { - Component next = getNextEditComponent(); - if (next != null) { - if (next.isFocusable()) { - next.requestFocus(); - next.startEditingAsync(); - } - /* - if (next instanceof TextArea) { - TextArea text = (TextArea) next; - text.requestFocus(); - Display.getInstance().editString(next, - text.getMaxSize(), text.getConstraint(), text.getText(), 0); - }*/ - } + moveFocus(getNextEditComponent()); } }; Display.getInstance().callSerially(task); @@ -89,25 +79,73 @@ public static void editPrevTextArea() { Runnable task = new Runnable() { public void run() { - Component next = getPrevEditComponent(); - if (next != null) { - if (next.isFocusable()) { - next.requestFocus(); - next.startEditingAsync(); - } - /* - if (next instanceof TextArea) { - TextArea text = (TextArea) next; - text.requestFocus(); - Display.getInstance().editString(next, - text.getMaxSize(), text.getConstraint(), text.getText(), 0); - }*/ - } + moveFocus(getPrevEditComponent()); } }; Display.getInstance().callSerially(task); } + /** + * Moves keyboard focus to {@code next}. Editing continues there only when it + * is a text component; anything else -- a button, a check box -- ends the + * current edit first, or the native editor keeps the keyboard and Tab can + * never leave the last field of a form or dialog. + */ + private static void moveFocus(final Component next) { + final Component current = curEditedComponent; + if (next == null || !next.isFocusable()) { + if (next == null && current != null) { + Display.getInstance().stopEditing(current); + } + return; + } + if (next instanceof TextArea && ((TextArea) next).isEditable()) { + next.requestFocus(); + next.startEditingAsync(); + return; + } + // startEditingAsync does nothing on a plain component, and opens one that edits in a + // popup, such as a Picker, as Tab always has. + if (current == null) { + next.requestFocus(); + next.startEditingAsync(); + return; + } + Display.getInstance().stopEditing(current, new Runnable() { + public void run() { + next.requestFocus(); + next.startEditingAsync(); + } + }); + } + + /** + * Ends the current edit and fires the default command of its form or dialog, + * the way Cmd-Enter (Ctrl-Enter elsewhere) submits a dialog on the desktop. + */ + public static void submitDefaultCommand() { + Display.getInstance().callSerially(new Runnable() { + public void run() { + final Component current = curEditedComponent; + if (current == null) { + return; + } + final Form f = current.getComponentForm(); + if (f == null || f.getDefaultCommand() == null) { + return; + } + Display.getInstance().stopEditing(current, new Runnable() { + public void run() { + Command c = f.getDefaultCommand(); + if (c != null) { + f.dispatchCommand(c, new ActionEvent(c)); + } + } + }); + } + }); + } + /** * * @return the next editable TextArea after the currently edited component. diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/InputAndProgressSnippets.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/InputAndProgressSnippets.java index b75ba8c8f4d..3b560c84466 100644 --- a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/InputAndProgressSnippets.java +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/InputAndProgressSnippets.java @@ -172,14 +172,18 @@ public void activityTimeline() { tracking.setState(2, ActivityTimeline.DONE); tracking.setState(3, ActivityTimeline.CURRENT); // end::activity-timeline[] + } + public void activityTimelineHorizontal() { // tag::activity-timeline-horizontal[] + Form form = new Form("Checkout", BoxLayout.y()); ActivityTimeline checkout = new ActivityTimeline(true) .addStep("Cart", null, null, ActivityTimeline.DONE) .addStep("Shipping", null, null, ActivityTimeline.CURRENT) .addStep("Payment", null, null, ActivityTimeline.PENDING) .addStep("Review", null, null, ActivityTimeline.PENDING); form.add(checkout); + form.show(); // end::activity-timeline-horizontal[] } diff --git a/docs/demos/common/src/main/snippets/developer-guide/appendix-goal-visualize.sh b/docs/demos/common/src/main/snippets/developer-guide/appendix-goal-visualize.sh new file mode 100644 index 00000000000..34eda3a124e --- /dev/null +++ b/docs/demos/common/src/main/snippets/developer-guide/appendix-goal-visualize.sh @@ -0,0 +1,10 @@ +// Generated from docs/developer-guide source blocks. Edit the guide snippets here, not inline. + +// tag::appendix-goal-visualize-bash-001[] +mvn cn1:visualize -Dcodevisualizer.base=master +// end::appendix-goal-visualize-bash-001[] + +// tag::appendix-goal-visualize-bash-002[] +mvn cn1:visualize -Dcodevisualizer.base=master & +java .agent-skills/codename-one/tools/Sim.java --visualizer call visualizer_model '{"request":"summary"}' +// end::appendix-goal-visualize-bash-002[] diff --git a/docs/developer-guide/Maven-Appendix-Goals.adoc b/docs/developer-guide/Maven-Appendix-Goals.adoc index 422af13a0d0..e4347e4b11c 100644 --- a/docs/developer-guide/Maven-Appendix-Goals.adoc +++ b/docs/developer-guide/Maven-Appendix-Goals.adoc @@ -43,6 +43,8 @@ include::appendix_goal_prepare_simulator_classpath.adoc[] include::appendix_goal_settings.adoc[] +include::appendix_goal_visualize.adoc[] + include::appendix_goal_test.adoc[] include::appendix_goal_update.adoc[] diff --git a/docs/developer-guide/appendix_goal_visualize.adoc b/docs/developer-guide/appendix_goal_visualize.adoc new file mode 100644 index 00000000000..eec82457188 --- /dev/null +++ b/docs/developer-guide/appendix_goal_visualize.adoc @@ -0,0 +1,82 @@ +[#visualize] +=== Visualize goal (`visualize`) + +The `visualize` goal opens the Code Visualizer on the project: charts and clickable diagrams of the code, and of what a branch changed. Every chart bar and diagram node leads one level deeper, and the last level is the source itself, opened in a read-only code editor with the lines in question highlighted. + +It's meant for reviewing code you didn't write line by line, such as a large change produced with an AI assistant. The overview shows where the code is, by module, language and complexity, and how it has changed week by week. The changes view shows which files and methods a branch touched, what it removed, and which methods call into the change, ordered by how many calls away they are. + +==== Usage + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/appendix-goal-visualize.sh[tag=appendix-goal-visualize-bash-001,indent=0] +---- + +This indexes the project and opens on the changes between `master` and the working tree, uncommitted and untracked files included. Without `codevisualizer.base` it opens on the overview. + +==== Reviewing a branch + +.The Summary view: the counts, where the change is, change per commit, and the methods to look at first +image::img/code-visualizer-summary.png[The Summary view of a branch,scaledwidth=90%] + +The toolbar switches between five views and narrows them all to one commit: + +* *Summary*: what the branch amounts to. A sentence names where most of the change is and its largest single change, followed by the counts of files, lines, methods and commits. A treemap shows the volume of change by module and file, a bar chart shows lines added and removed per commit, and a ranked list shows the methods with the most new or changed lines. Click a file for its diff, a method for its flow, or a commit to review only that commit. +* *Highlights*: the methods most worth studying, one at a time, most important first. A method whose control flow changed shows its flowchart before and after; one that now calls, or no longer calls, other methods shows its call graph; new code with many decisions shows its flowchart. A strip names the method and says why it matters, for example "4 steps added, decisions 6 -> 2," and Previous and Next step through the list. The short line above the charts says how to read them; *More* shows the summary, the steps added and removed and the reason the commit gives. The side panel shows the commit that made the change, the comment it added and the untouched callers that now run the new code. Tests and calls into the JDK are left out. +* *Graph*: the classes the branch changed and the classes they call. Green is new, amber changed. Hover over an arrow to see the newest call along it, the comment written at that call and the commit that added it. Select a class to see the commits that wrote it, the comments they added and each changed method with its diff in place. Select an arrow to see every call the branch added along it, grouped by commit, each with its comment and diff. +* *Calls* and *Flow*: the call graph and the flowchart of the method selected last. For a changed method the flowchart shows the method before and after the branch, with removed steps in red and added ones in green. + +.A highlight: the flowchart before and after, the diff beside it, and the commit and calls in the side panel +image::img/code-visualizer-highlights.png[A highlight of a method whose control flow changed,scaledwidth=90%] + +.The Graph view: the modules the branch changed and the calls between them +image::img/code-visualizer-graph.png[The Graph view of the modules a branch changed,scaledwidth=90%] + +The commit picker beside the views lists the branch's commits, uncommitted changes first. Choosing one narrows every view to it: counts, charts, the change marks and the calls drawn as new. + +Charts that follow code show it beside them: select a box and the code scrolls to its line and lights it, or click a line and the box for it's selected. In the before and after flowcharts both charts share one diff, so a removed step scrolls to the removed line. A step the code comments has the comment in a folded note beside it, and each chart names the commits that changed the method, so a removed or added step says why. Every chart has buttons at its top to zoom in and out, and a label cut short shows in full when you hover over it. + +The first launch offers a short tour of the window; the question mark in the toolbar shows it again. The magnifier opens Find, which suggests classes and methods as you type; pick one to open it. + +To narrow a large change down step by step, approve what you have reviewed. Pressing *Approve* at the top of a highlight, a method or a file records it as reviewed, and the toolbar switch reading *All Changes* or *Unapproved Only* chooses between the whole change and what's not approved yet. Approvals are kept in the application's storage for each directory indexed (so another `codevisualizer.root` starts with none), with a fingerprint of the code approved: when later commits change an approved method again, for example after review feedback, it comes back marked "Changed Since Approval." Approving switches the toolbar to *Unapproved Only* if it's not already, so what you approved leaves the view at once; *All Changes* brings it back. A highlight's side panel also lists *Related* links: other highlights in the same file, the methods it now calls or no longer calls, and its callers. + +==== What you can open + +* *Packages*: a graph of the packages and their dependencies. Box width is size; green is added, amber modified, and blue reached by the change. +* *A package*: its classes with extends, implements and uses arrows. +* *A class*: a UML class box with its supertypes above, subtypes below, the classes it uses on the right and the ones that use it on the left. +* *A method*: its callers on the left and callees on the right, one or two calls deep, plus its overrides and, for a `native` method, the C or Objective-C function that implements it. +* *A flow chart* of a method: decisions, loops, try blocks, calls, returns and throws, with the steps on changed lines marked. + +Double click a node to open it, or select it to see its details in the side panel. + +==== Driving it from an assistant + +The visualizer always serves Codename One's built-in MCP tools, so an assistant such as Claude can show you a view while it explains the code, and answer what you ask about in the window. It listens on port 8766, or on a free port when that one is taken, and writes the port to `target/cn1-visualizer.port` (`build/cn1-visualizer.port` in a Gradle project) while it runs; `-Dcodevisualizer.mcp.port` chooses one. A project created from the Initializr or the Maven and Gradle templates ships the agent skill that explains all this to the assistant, including `Sim.java`, the command line client it connects with: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/appendix-goal-visualize.sh[tag=appendix-goal-visualize-bash-002,indent=0] +---- + +Besides the standard `ui_*` tools and the screenshot resource, it adds `visualizer_model` (queries the code model without changing the screen), `visualizer_show` (puts a view on screen and waits until it's drawn, optionally narrowed to one commit), `visualizer_back`, `visualizer_annotate` (shows the assistant's explanation above the view), `visualizer_settings` (the theme and the font size) and `visualizer_state`. + +An assistant can also listen for questions. Right-click (or Control-click, or long-press) a chart box, a line of code or any text and choose *Explain This* or *Ask About This*; the Ask button in the toolbar followed by a click does the same. In the Ask dialog, Tab moves between the question and the buttons and Cmd+Enter (Ctrl+Enter elsewhere) sends it. While the assistant works on a question, a status with a spinner shows at the bottom of the window; click it to hide it. When no assistant is listening it says so after about 20 seconds, and a question an assistant took but didn't answer within three minutes waits for the next one. The question reaches an assistant waiting in `visualizer_listen`, with what you pointed at and the surrounding view, and `visualizer_explain` answers in place: a callout next to the element, optionally a walk through several steps that each move to and pulse the box or line it's about, and optionally a small diagram. To walk you through a view it uses `visualizer_coach`, which dims the window and lights one control, chart box or line of code at a time with a note beside it. + +==== Parameters + +`codevisualizer.base`:: + +The branch, tag or commit to compare against. Optional. With Gradle, pass it as `-Pcodevisualizer.base=master`. + +`codevisualizer.root`:: + +The directory to index. Defaults to the top of the project. + +codevisualizer.mcp.port:: + +A loopback port on which to serve the MCP tools. Optional. + +==== Supported sources + +Java sources are parsed with the Java compiler, so classes, members, calls and control flow come from the real syntax tree; calls are matched by name and argument count without full type checking. C, C++ and Objective-C sources are scanned for function definitions, and ParparVM native functions are linked to the Java methods they implement. diff --git a/docs/developer-guide/img/code-visualizer-graph.png b/docs/developer-guide/img/code-visualizer-graph.png new file mode 100644 index 00000000000..7e4053f1544 Binary files /dev/null and b/docs/developer-guide/img/code-visualizer-graph.png differ diff --git a/docs/developer-guide/img/code-visualizer-highlights.png b/docs/developer-guide/img/code-visualizer-highlights.png new file mode 100644 index 00000000000..4f77c264ea2 Binary files /dev/null and b/docs/developer-guide/img/code-visualizer-highlights.png differ diff --git a/docs/developer-guide/img/code-visualizer-summary.png b/docs/developer-guide/img/code-visualizer-summary.png new file mode 100644 index 00000000000..7bf47099b5d Binary files /dev/null and b/docs/developer-guide/img/code-visualizer-summary.png differ diff --git a/docs/developer-guide/languagetool-accept.txt b/docs/developer-guide/languagetool-accept.txt index acb25bc3bbd..b2b40be4511 100644 --- a/docs/developer-guide/languagetool-accept.txt +++ b/docs/developer-guide/languagetool-accept.txt @@ -964,3 +964,5 @@ fils Xposed EdXposed Shamiko +callees +supertypes diff --git a/maven/build-engine/src/main/java/com/codename1/maven/DesktopTool.java b/maven/build-engine/src/main/java/com/codename1/maven/DesktopTool.java index c2252d34a0d..1847736b3cc 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/DesktopTool.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/DesktopTool.java @@ -63,6 +63,12 @@ public final class DesktopTool { "com.codename1.certificatewizard.CertificateWizardLauncher", "Certificate Wizard", "CertificateWizard", "certificatewizard", ".certificateWizard", "certificate-wizard-icon.png", true, true); + /// `mvn cn1:visualize` / `./gradlew visualize`: diagrams and charts of the project's + /// code and of what the current branch changed, each drilling down to the lines. + public static final DesktopTool CODE_VISUALIZER = new DesktopTool("codenameone-code-visualizer", + "com.codename1.codevisualizer.CodeVisualizerLauncher", "Codename One Code Visualizer", + "CodenameOneCodeVisualizer", "codevisualizer", ".codenameoneCodeVisualizer", null, false, true); + private final String artifactId; private final String mainClass; private final String displayName; diff --git a/maven/code-model/pom.xml b/maven/code-model/pom.xml new file mode 100644 index 00000000000..c5521e897c9 --- /dev/null +++ b/maven/code-model/pom.xml @@ -0,0 +1,94 @@ + + + + + com.codenameone + codenameone + 8.0-SNAPSHOT + + 4.0.0 + com.codenameone + codenameone-code-model + 8.0-SNAPSHOT + jar + Codename One Code Model + + UTF-8 + 1.8 + 1.8 + + + + com.codenameone + codenameone-javac + ${project.version} + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + jar-with-dependencies + + + + com.codename1.tools.codemodel.CodeModelCLI + + + + + + cli-jar + package + + single + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + 4.7.3.4 + + Max + Low + false + true + ${project.build.directory} + ${project.basedir}/spotbugs-exclude.xml + + + + spotbugs + verify + + spotbugs + + + + + + + diff --git a/maven/code-model/spotbugs-exclude.xml b/maven/code-model/spotbugs-exclude.xml new file mode 100644 index 00000000000..e8a2357aca9 --- /dev/null +++ b/maven/code-model/spotbugs-exclude.xml @@ -0,0 +1,3 @@ + + + diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/Approvals.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Approvals.java new file mode 100644 index 00000000000..14ed82523af --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Approvals.java @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Map; + +/// The reviewer's approvals: changed methods and files they have read and accepted. An +/// approval names an item and the fingerprint of its text when it was approved, so an item +/// the branch changes again (after review feedback, say) no longer matches and comes back. +/// +/// While approvals are hidden, an approved item is treated as unchanged by every query: +/// its change mark is cleared, so the graph, the summary, the highlights and the diff all +/// leave it out, and the impact of what is left is traced again. The original marks are +/// kept, so showing everything again is exact. +final class Approvals { + private final CodeModel model; + private final Map original = new IdentityHashMap(); + private final Map texts = new HashMap(); + + Approvals(CodeModel model) { + this.model = model; + for (CodeModel.SourceFile f : model.files) { + original.put(f, f.change); + } + for (CodeModel.Type t : model.types) { + original.put(t, t.change); + } + for (CodeModel.Method m : model.methods) { + original.put(m, m.change); + } + } + + /// The key an approval of `m` is stored under: its type and signature, stable across + /// edits that move it within the file. + static String key(CodeModel.Method m) { + return m.owner.qualifiedName + "#" + m.signature(); + } + + /// The key an approval of a whole file is stored under. + static String key(CodeModel.SourceFile f) { + return "file:" + f.path; + } + + /// The fingerprint of `m`'s text as it is now; whitespace is ignored, so reformatting + /// alone does not undo an approval. + String fingerprint(CodeModel.Method m) { + String text = text(m.owner.file.path); + String[] lines = text.split("\n", -1); + StringBuilder sb = new StringBuilder(); + for (int i = Math.max(1, m.line); i <= Math.min(lines.length, m.endLine); i++) { + // The line break ends a // comment for hash; without it the rest of the method + // would read as comment and lose the whitespace inside its strings. + sb.append(lines[i - 1]).append('\n'); + } + return hash(sb.toString()); + } + + /// The fingerprint of a whole file as it is now. + String fingerprint(CodeModel.SourceFile f) { + return hash(text(f.path)); + } + + /// Hides every item of `approved` (key to fingerprint) that still matches, or shows + /// everything again when `approved` is empty. + void apply(Map approved, int depth) { + // The commit filter narrows the marks this sets, so it is lifted first and laid + // over the result again. + String commit = model.commits == null ? null : model.commits.focus(); + if (commit != null) { + model.commits.focus(null); + } + for (Map.Entry e : original.entrySet()) { + Object o = e.getKey(); + if (o instanceof CodeModel.SourceFile) { + ((CodeModel.SourceFile) o).change = e.getValue(); + } else if (o instanceof CodeModel.Type) { + ((CodeModel.Type) o).change = e.getValue(); + } else { + ((CodeModel.Method) o).change = e.getValue(); + } + } + if (!approved.isEmpty()) { + hide(approved); + } + if (commit != null) { + model.commits.focus(commit); + } + for (CodeModel.Method m : model.methods) { + m.impact = -1; + } + for (CodeModel.Type t : model.types) { + t.impact = -1; + } + Impact.compute(model, depth); + } + + private void hide(Map approved) { + for (CodeModel.Method m : model.methods) { + if (m.change != null && fingerprint(m).equals(approved.get(key(m)))) { + m.change = null; + } + } + for (CodeModel.SourceFile f : model.files) { + if (f.change == null) { + continue; + } + boolean whole = fingerprint(f).equals(approved.get(key(f))); + if (whole || allApproved(f)) { + f.change = null; + for (CodeModel.Method m : model.methods) { + if (m.owner.file == f) { + m.change = null; + } + } + } + } + for (CodeModel.Type t : model.types) { + if (t.change != null && (t.file == null || t.file.change == null || !anyChanged(t))) { + t.change = null; + } + } + } + + /// Whether every changed line of `f` lies inside a method that is no longer marked. + private boolean allApproved(CodeModel.SourceFile f) { + for (int[] r : f.changedRanges) { + boolean covered = false; + for (CodeModel.Method m : model.methods) { + if (m.owner.file == f && m.change == null && original.get(m) != null + && r[0] >= m.line && r[1] <= m.endLine) { + covered = true; + break; + } + } + if (!covered) { + return false; + } + } + return !f.changedRanges.isEmpty(); + } + + private boolean anyChanged(CodeModel.Type t) { + for (CodeModel.Method m : model.methods) { + if (m.owner == t && m.change != null) { + return true; + } + } + return "A".equals(t.change) && t.file.change != null; + } + + private String text(String path) { + String t = texts.get(path); + if (t == null) { + try { + t = new String(Files.readAllBytes(new File(model.root, path).toPath()), StandardCharsets.UTF_8); + } catch (IOException e) { + t = ""; + } + texts.put(path, t); + } + return t; + } + + static String hash(String text) { + // Whitespace is dropped so reformatting keeps an approval, except inside a string, + // char or text-block literal, where a changed space changes what the code does. + // Comments keep their words but not their layout, so reflowing one keeps it too. + StringBuilder stripped = new StringBuilder(text.length()); + int n = text.length(); + int pos = 0; + while (pos < n) { + char c = text.charAt(pos); + if (c == '/' && pos + 1 < n && (text.charAt(pos + 1) == '/' || text.charAt(pos + 1) == '*')) { + boolean line = text.charAt(pos + 1) == '/'; + int end = line ? text.indexOf('\n', pos) : text.indexOf("*/", pos + 2); + end = end < 0 ? n : line ? end : end + 2; + for (int k = pos; k < end; k++) { + if (!Character.isWhitespace(text.charAt(k))) { + stripped.append(text.charAt(k)); + } + } + pos = end; + } else if (text.startsWith("\"\"\"", pos)) { + int end = text.indexOf("\"\"\"", pos + 3); + end = end < 0 ? n : end + 3; + stripped.append(text, pos, end); + pos = end; + } else if (c == '"' || c == '\'') { + int k = pos + 1; + while (k < n && text.charAt(k) != c && text.charAt(k) != '\n') { + k += text.charAt(k) == '\\' ? 2 : 1; + } + k = Math.min(n, k + 1); + stripped.append(text, pos, k); + pos = k; + } else { + if (!Character.isWhitespace(c)) { + stripped.append(c); + } + pos++; + } + } + try { + byte[] d = MessageDigest.getInstance("SHA-256").digest(stripped.toString().getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 12; i++) { + sb.append(Character.forDigit((d[i] >> 4) & 15, 16)).append(Character.forDigit(d[i] & 15, 16)); + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/ChangeQueries.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ChangeQueries.java new file mode 100644 index 00000000000..5273672971f --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ChangeQueries.java @@ -0,0 +1,744 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/// The answers that explain a change rather than list it: how the changed classes fit +/// together with each other and with the code around them (`changegraph`), and what a +/// file declares and what it is wired to (`outline`). +final class ChangeQueries { + /// Above this many changed classes the graph starts at modules. + static final int TYPE_LIMIT = 40; + /// Unchanged classes shown around the changed ones. + private static final int NEIGHBOUR_LIMIT = 8; + /// Strongest relations drawn out of each class; the rest is noise at this scale. + private static final int EDGES_PER_NODE = 4; + private static final int REF_LIMIT = 6; + + private final CodeModel model; + + ChangeQueries(CodeModel model) { + this.model = model; + } + + // ------------------------------------------------------------------ graph + + /// One directed relation between two nodes, with how many uses make it up. + private static final class Edge { + final String from; + final String to; + String kind; + int weight; + /// Relations counted into this edge, and how many of them the branch introduced. + int parts; + int fresh; + + /// `A` when the branch introduced every relation on the edge, `M` some, else empty. + String change() { + return fresh == 0 ? "" : fresh >= parts ? "A" : "M"; + } + + Edge(String from, String to, String kind) { + this.from = from; + this.to = to; + this.kind = kind; + } + } + + static CodeModel.Type top(CodeModel.Type t) { + CodeModel.Type o = t; + while (o.outer != null) { + o = o.outer; + } + return o; + } + + private static boolean changed(CodeModel.Type t) { + return t.change != null; + } + + /// Every top-level type that changed itself or in one of its nested types. + private Set changedTypes(String module) { + Set out = new LinkedHashSet(); + for (CodeModel.Type t : model.types) { + if (changed(t) && (module == null || module.equals(t.file.module))) { + out.add(top(t)); + } + } + return out; + } + + /// Relations between top-level types: extends/implements first, then calls, then other + /// uses (fields, parameters). Keyed `from \n to`. + private Map typeEdges() { + Map edges = new LinkedHashMap(); + for (CodeModel.Type t : model.types) { + CodeModel.Type from = top(t); + boolean isNew = "A".equals(t.change); + if (t.superType != null) { + add(edges, from, top(t.superType), "extends", 1, isNew); + } + for (CodeModel.Type i : t.interfaces) { + add(edges, from, top(i), "extends", 1, isNew); + } + for (CodeModel.Type d : t.dependencies) { + add(edges, from, top(d), "uses", 1, isNew); + } + } + for (CodeModel.Method m : model.methods) { + CodeModel.Type from = top(m.owner); + for (CodeModel.Method c : m.calls) { + add(edges, from, top(c.owner), "calls", 1, m.isNewCall(c)); + } + } + return edges; + } + + private static void add(Map edges, CodeModel.Type from, CodeModel.Type to, String kind, int w, + boolean isNew) { + if (from == to) { + return; + } + String key = from.qualifiedName + "\n" + to.qualifiedName; + Edge e = edges.get(key); + if (e == null) { + e = new Edge(from.qualifiedName, to.qualifiedName, kind); + edges.put(key, e); + } else if ("extends".equals(kind) || ("calls".equals(kind) && "uses".equals(e.kind))) { + e.kind = kind; + } + if (!"uses".equals(kind)) { + e.weight += w; + } + e.parts++; + if (isNew) { + e.fresh++; + } + } + + /// `changegraph [module]`: the changed classes and how they relate, with the unchanged + /// classes they touch most; or, when that is too many to read, the changed modules. + void changeGraph(Json.Writer w, String module) { + String mod = module == null || module.length() == 0 ? null : ROOT_MODULE.equals(module) ? "" : module; + Set changedTypes = changedTypes(mod); + Map edges = typeEdges(); + if (mod == null && changedTypes.size() > TYPE_LIMIT) { + moduleGraph(w, changedTypes, edges); + return; + } + edges = strongest(edges); + Map byName = new HashMap(); + for (CodeModel.Type t : model.types) { + byName.put(t.qualifiedName, t); + } + Set inGraph = new LinkedHashSet(); + for (CodeModel.Type t : changedTypes) { + inGraph.add(t.qualifiedName); + } + // Unchanged neighbours, the most connected first. + final Map score = new HashMap(); + for (Edge e : edges.values()) { + boolean fromIn = inGraph.contains(e.from); + boolean toIn = inGraph.contains(e.to); + if (fromIn != toIn) { + String other = fromIn ? e.to : e.from; + CodeModel.Type o = byName.get(other); + if (o != null && !changed(o) && !library(other)) { + Integer s = score.get(other); + score.put(other, (s == null ? 0 : s) + Math.max(1, e.weight) + ("extends".equals(e.kind) ? 5 : 0)); + } + } + } + List neighbours = new ArrayList(score.keySet()); + Collections.sort(neighbours, (a, b) -> { + int d = score.get(b) - score.get(a); + return d != 0 ? d : a.compareTo(b); + }); + Set shownNeighbours = new LinkedHashSet(); + for (int i = 0; i < neighbours.size() && i < NEIGHBOUR_LIMIT; i++) { + shownNeighbours.add(neighbours.get(i)); + } + w.beginObject(); + w.name("level").value("type"); + if (mod != null) { + w.name("module").value(mod); + } + w.name("more").value(Math.max(0, neighbours.size() - shownNeighbours.size())); + w.name("nodes").beginArray(); + for (CodeModel.Type t : changedTypes) { + typeNode(w, t, false); + } + for (String n : shownNeighbours) { + typeNode(w, byName.get(n), true); + } + w.endArray(); + Set all = new LinkedHashSet(inGraph); + all.addAll(shownNeighbours); + w.name("edges").beginArray(); + for (Edge e : edges.values()) { + boolean between = all.contains(e.from) && all.contains(e.to); + boolean touchesChange = inGraph.contains(e.from) || inGraph.contains(e.to); + if (between && touchesChange) { + w.beginObject().name("f").value(e.from).name("t").value(e.to).name("k").value(e.kind) + .name("w").value(e.weight).name("ch").value(e.change()); + if (e.fresh > 0) { + tip(w, e.from, e.to); + } + w.endObject(); + } + } + w.endArray(); + w.endObject(); + } + + /// Drops plain type uses (a field or parameter type says little a call does not), and + /// keeps each class's `EDGES_PER_NODE` heaviest calls; `extends` is always kept. + private static Map strongest(Map edges) { + Map> bySource = new LinkedHashMap>(); + for (Edge e : edges.values()) { + if ("uses".equals(e.kind)) { + continue; + } + List l = bySource.get(e.from); + if (l == null) { + l = new ArrayList(); + bySource.put(e.from, l); + } + l.add(e); + } + Map out = new LinkedHashMap(); + for (List l : bySource.values()) { + Collections.sort(l, new Comparator() { + @Override + public int compare(Edge a, Edge b) { + return b.weight - a.weight; + } + }); + int calls = 0; + for (Edge e : l) { + if ("extends".equals(e.kind) || calls++ < EDGES_PER_NODE) { + out.put(e.from + "\n" + e.to, e); + } + } + } + return out; + } + + /// The platform library and test frameworks: every class uses them, so as context they + /// crowd out the project's own code without saying anything about the change. + static boolean library(String qualifiedName) { + return qualifiedName.startsWith("java.") || qualifiedName.startsWith("javax.") + || qualifiedName.startsWith("org.junit.") || qualifiedName.startsWith("kotlin."); + } + + private void typeNode(Json.Writer w, CodeModel.Type t, boolean neighbour) { + int changedMethods = 0; + int methods = 0; + for (CodeModel.Method m : model.methods) { + if (top(m.owner) == t) { + methods++; + if (m.change != null) { + changedMethods++; + } + } + } + String change = t.change; + if (change == null && !neighbour) { + change = "M"; + } + w.beginObject(); + w.name("id").value(t.qualifiedName); + w.name("n").value(t.name); + w.name("k").value(t.kind); + w.name("mod").value(t.file.module); + w.name("p").value(t.file.path); + w.name("l").value(t.line); + w.name("e").value(t.endLine); + if (change != null) { + w.name("ch").value(change); + } + w.name("nb").value(neighbour); + w.name("cm").value(changedMethods); + w.name("nm").value(methods); + w.name("add").value(t.file.added); + w.name("del").value(t.file.deleted); + String doc = docLine(t.file, t.line); + if (doc != null) { + w.name("doc").value(doc); + } + w.endObject(); + } + + /// The id of the files outside any module in the module graph; "" would open the module + /// graph again instead of those files' classes. + static final String ROOT_MODULE = "."; + + private static String moduleId(String module) { + return module == null || module.length() == 0 ? ROOT_MODULE : module; + } + + private void moduleGraph(Json.Writer w, Set changedTypes, Map typeEdges) { + Map modules = new LinkedHashMap(); + Map moduleOf = new HashMap(); + for (CodeModel.Type t : model.types) { + moduleOf.put(t.qualifiedName, moduleId(t.file.module)); + } + for (CodeModel.Type t : changedTypes) { + int[] c = modules.get(moduleId(t.file.module)); + if (c == null) { + c = new int[3]; + modules.put(moduleId(t.file.module), c); + } + c[0]++; + if ("A".equals(t.change)) { + c[1]++; + } + } + for (CodeModel.SourceFile f : model.files) { + int[] c = modules.get(moduleId(f.module)); + if (c != null && f.change != null) { + c[2] += f.added + f.deleted; + } + } + Set changedNames = new LinkedHashSet(); + for (CodeModel.Type t : changedTypes) { + changedNames.add(t.qualifiedName); + } + Map edges = new LinkedHashMap(); + Map outside = new HashMap(); + for (Edge e : typeEdges.values()) { + if (!changedNames.contains(e.from) && !changedNames.contains(e.to)) { + continue; + } + String a = moduleOf.get(e.from); + String b = moduleOf.get(e.to); + if (a == null || b == null || a.equals(b)) { + continue; + } + if (!modules.containsKey(a) || !modules.containsKey(b)) { + String other = modules.containsKey(a) ? b : a; + Integer n = outside.get(other); + outside.put(other, (n == null ? 0 : n) + 1); + if (!modules.containsKey(a) && !modules.containsKey(b)) { + continue; + } + } + String key = a + "\n" + b; + Edge m = edges.get(key); + if (m == null) { + m = new Edge(a, b, e.kind); + edges.put(key, m); + } + m.weight += Math.max(1, e.weight); + m.parts += e.parts; + m.fresh += e.fresh; + } + w.beginObject(); + w.name("level").value("module"); + w.name("nodes").beginArray(); + for (Map.Entry m : modules.entrySet()) { + int[] c = m.getValue(); + w.beginObject().name("id").value(m.getKey()).name("n").value(m.getKey()).name("k").value("module") + .name("mod").value(m.getKey()).name("ch").value(c[1] == c[0] ? "A" : "M").name("nb").value(false) + .name("types").value(c[0]).name("addedTypes").value(c[1]).name("lines").value(c[2]).endObject(); + } + List> out = new ArrayList>(outside.entrySet()); + Collections.sort(out, (a, b) -> b.getValue() - a.getValue()); + for (int i = 0; i < out.size() && i < 6; i++) { + w.beginObject().name("id").value(out.get(i).getKey()).name("n").value(out.get(i).getKey()) + .name("k").value("module").name("mod").value(out.get(i).getKey()).name("nb").value(true) + .endObject(); + } + w.endArray(); + w.name("edges").beginArray(); + for (Edge e : edges.values()) { + w.beginObject().name("f").value(e.from).name("t").value(e.to).name("k").value(e.kind) + .name("w").value(e.weight).name("ch").value(e.change()).endObject(); + } + w.endArray(); + w.endObject(); + } + + // ------------------------------------------------------------------ outline + + /// `outline PATH`: every class the file declares, with its supertypes, each method's + /// signature and doc line, and the code outside the file each one calls and is called + /// by -- what a reviewer wants of a new file instead of hundreds of green lines. + String outline(String path) { + CodeModel.SourceFile file = model.filesByPath.get(path); + if (file == null) { + return ModelQueries.error("no file " + path); + } + StringBuilder sb = new StringBuilder(4096); + Json.Writer w = new Json.Writer(sb); + w.beginObject(); + w.name("p").value(path); + w.name("mod").value(file.module); + if (file.change != null) { + w.name("ch").value(file.change); + } + w.name("add").value(file.added); + w.name("del").value(file.deleted); + w.name("lines").value(file.lines); + w.name("types").beginArray(); + for (CodeModel.Type t : model.types) { + if (t.file != file) { + continue; + } + w.beginObject(); + w.name("id").value(t.id); + w.name("n").value(t.name); + w.name("q").value(t.qualifiedName); + w.name("k").value(t.kind); + w.name("l").value(t.line); + w.name("e").value(t.endLine); + if (t.change != null) { + w.name("ch").value(t.change); + } + String doc = docLine(file, t.line); + if (doc != null) { + w.name("doc").value(doc); + } + w.name("supers").beginArray(); + if (t.superType != null) { + ref(w, t.superType); + } + for (CodeModel.Type i : t.interfaces) { + ref(w, i); + } + w.endArray(); + Set usedBy = new LinkedHashSet(); + for (CodeModel.Type o : model.types) { + if (o.file != file && o.dependencies.contains(t)) { + usedBy.add(top(o)); + } + } + w.name("usedBy").beginArray(); + int n = 0; + for (CodeModel.Type o : usedBy) { + if (n++ < REF_LIMIT * 2) { + ref(w, o); + } + } + w.endArray(); + w.name("usedByCount").value(usedBy.size()); + w.name("methods").beginArray(); + for (CodeModel.Method m : t.methods) { + method(w, file, m); + } + w.endArray(); + w.endObject(); + } + w.endArray(); + w.endObject(); + return sb.toString(); + } + + private void method(Json.Writer w, CodeModel.SourceFile file, CodeModel.Method m) { + w.beginObject(); + w.name("id").value(m.id); + w.name("n").value(m.name); + StringBuilder sig = new StringBuilder(); + if (m.returnType != null) { + sig.append(m.returnType).append(' '); + } + sig.append(m.name).append('('); + for (int i = 0; i < m.paramTypes.size(); i++) { + if (i > 0) { + sig.append(", "); + } + sig.append(m.paramTypes.get(i)); + if (i < m.paramNames.size()) { + sig.append(' ').append(m.paramNames.get(i)); + } + } + w.name("sig").value(sig.append(')').toString()); + w.name("l").value(m.line); + w.name("e").value(m.endLine); + w.name("cx").value(m.complexity); + w.name("m").value(m.modifiers); + if (m.change != null) { + w.name("ch").value(m.change); + } + String doc = docLine(file, m.line); + if (doc != null) { + w.name("doc").value(doc); + } + List outCalls = new ArrayList(); + for (CodeModel.Method c : m.calls) { + if (c.owner.file != file) { + outCalls.add(c); + } + } + List inCalls = new ArrayList(); + for (CodeModel.Method c : m.callers) { + if (c.owner.file != file) { + inCalls.add(c); + } + } + refs(w, "calls", outCalls, m, true); + refs(w, "callers", inCalls, m, false); + w.endObject(); + } + + private static void refs(Json.Writer w, String name, List all, CodeModel.Method self, + boolean outgoing) { + // The platform library says nothing about how the change is wired; List.add in every + // method's list buried the project's own calls. + List ms = new ArrayList(); + for (CodeModel.Method c : all) { + if (!library(top(c.owner).qualifiedName)) { + ms.add(c); + } + } + w.name(name).beginArray(); + for (int i = 0; i < ms.size() && i < REF_LIMIT; i++) { + CodeModel.Method c = ms.get(i); + w.beginObject().name("id").value(c.id).name("n").value(c.name).name("on").value(c.owner.name) + .name("mod").value(c.owner.file.module); + if (c.change != null) { + w.name("ch").value(c.change); + } + if (outgoing ? self.isNewCall(c) : c.isNewCall(self)) { + w.name("new").value(true); + } + w.endObject(); + } + w.endArray(); + w.name(name + "Count").value(ms.size()); + // Every class reached, not just the listed few: the graph lights these up. + w.name(name + "Types").beginArray(); + Set seen = new HashSet(); + for (CodeModel.Method c : ms) { + String q = top(c.owner).qualifiedName; + if (seen.add(q)) { + w.value(q); + } + } + w.endArray(); + } + + /// `edgecalls FROM TO`: every call from a method of top-level class FROM (or its nested + /// classes) to one of TO, each `{f, t, new}` with `f` and `t` method references: what an + /// arrow of the change graph stands for. + void edgeCalls(Json.Writer w, String from, String to) { + w.beginObject(); + w.name("from").value(from); + w.name("to").value(to); + w.name("calls").beginArray(); + int n = 0; + for (CodeModel.Method m : model.methods) { + if (!from.equals(top(m.owner).qualifiedName)) { + continue; + } + for (CodeModel.Method c : m.calls) { + if (to.equals(top(c.owner).qualifiedName) && n++ < 60) { + w.beginObject(); + w.name("f"); + callRef(w, m); + w.name("t"); + callRef(w, c); + w.name("new").value(m.isNewCall(c)); + Integer line = m.callLines.get(c); + if (line != null) { + String path = m.owner.file.path; + w.name("p").value(path).name("l").value(line); + if (model.commits != null) { + String sha = model.commits.at(path, line); + Commits.Info info = model.commits.get(sha); + if (info != null) { + w.name("c").value(sha).name("cshort").value(ReviewQueries.shortSha(sha)) + .name("cs").value(info.subject).name("cb").value(info.body); + } + String note = model.commits.commentAt(path, line); + if (note != null) { + w.name("note").value(note); + } + } + } + w.endObject(); + } + } + } + w.endArray(); + w.name("count").value(n); + w.endObject(); + } + + /// What the arrow's hover tip says: the newest call the branch added along it, the + /// comment written at that call, the commit that added it, and how many more there are. + private void tip(Json.Writer w, String from, String to) { + CodeModel.Method bestFrom = null; + CodeModel.Method bestTo = null; + int bestRank = Integer.MAX_VALUE; + int count = 0; + List order = model.commits == null ? new ArrayList() : model.commits.all(); + for (CodeModel.Method m : model.methods) { + if (!from.equals(top(m.owner).qualifiedName)) { + continue; + } + for (CodeModel.Method c : m.calls) { + if (!to.equals(top(c.owner).qualifiedName) || !m.isNewCall(c)) { + continue; + } + count++; + int rank = order.size(); + Integer line = m.callLines.get(c); + if (line != null && model.commits != null) { + rank = order.indexOf(model.commits.get(model.commits.at(m.owner.file.path, line))); + rank = rank < 0 ? order.size() : rank; + } + if (rank < bestRank) { + bestRank = rank; + bestFrom = m; + bestTo = c; + } + } + } + if (bestFrom == null) { + return; + } + w.name("tipCall").value(bestFrom.name + "() -> " + bestTo.owner.name + "." + bestTo.name + "()"); + w.name("tipMore").value(count - 1); + Integer line = bestFrom.callLines.get(bestTo); + if (line != null && model.commits != null) { + String note = model.commits.commentAt(bestFrom.owner.file.path, line); + if (note != null) { + w.name("tipNote").value(note); + } + Commits.Info info = model.commits.get(model.commits.at(bestFrom.owner.file.path, line)); + if (info != null) { + w.name("tipCommit").value(info.subject); + } + } + } + + private static void callRef(Json.Writer w, CodeModel.Method c) { + w.beginObject().name("id").value(c.id).name("n").value(c.name).name("on").value(c.owner.name) + .name("sig").value(c.signature()); + if (c.change != null) { + w.name("ch").value(c.change); + } + w.endObject(); + } + + private static void ref(Json.Writer w, CodeModel.Type t) { + w.beginObject().name("n").value(t.name).name("q").value(t.qualifiedName).name("mod").value(t.file.module); + if (t.change != null) { + w.name("ch").value(t.change); + } + w.endObject(); + } + + // ------------------------------------------------------------------ doc lines + + private final Map> sources = new HashMap>(); + + private List lines(CodeModel.SourceFile f) { + List l = sources.get(f.path); + if (l == null) { + try { + l = Files.readAllLines(new File(model.root, f.path).toPath(), StandardCharsets.UTF_8); + } catch (IOException | RuntimeException e) { + l = new ArrayList(); + } + sources.put(f.path, l); + } + return l; + } + + /// The first sentence of the doc comment above a declaration at `line` (1-based), skipping + /// annotations; null when there is none. + String docLine(CodeModel.SourceFile f, int line) { + List src = lines(f); + int i = line - 2; + while (i >= 0 && src.get(i).trim().startsWith("@")) { + i--; + } + if (i < 0 || i >= src.size()) { + return null; + } + List text = new ArrayList(); + String last = src.get(i).trim(); + if (last.startsWith("///")) { + while (i >= 0 && src.get(i).trim().startsWith("///")) { + text.add(0, src.get(i).trim().substring(3).trim()); + i--; + } + } else if (last.endsWith("*/")) { + int end = i; + while (i >= 0 && !src.get(i).trim().startsWith("/*")) { + i--; + } + // A plain /* */ comment is not documentation; walking past its opening line + // would take the previous member's javadoc and the code between. + if (i < 0 || !src.get(i).trim().startsWith("/**")) { + return null; + } + for (int k = i; k <= end; k++) { + String s = src.get(k).trim(); + s = s.replace("/**", "").replace("*/", ""); + if (s.startsWith("*")) { + s = s.substring(1); + } + text.add(s.trim()); + } + } else { + return null; + } + StringBuilder sb = new StringBuilder(); + for (String s : text) { + if (s.length() == 0) { + if (sb.length() > 0) { + break; + } + continue; + } + if (sb.length() > 0) { + sb.append(' '); + } + sb.append(s); + } + String all = sb.toString().replace("`", ""); + int dot = all.indexOf(". "); + String first = dot > 0 ? all.substring(0, dot + 1) : all; + if (first.length() > 160) { + first = first.substring(0, 157) + "..."; + } + return first.length() == 0 ? null : first; + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/CodeModel.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/CodeModel.java new file mode 100644 index 00000000000..07178d63ba9 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/CodeModel.java @@ -0,0 +1,533 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// The indexed form of a source tree: its files, the Java types and members declared +/// in them, the calls between members and, when a base revision was given, what the +/// branch changed and what those changes reach. +/// +/// Built by `ModelBuilder` and `Resolver`, annotated by `GitChanges` and `Impact`, and +/// written by `toJson`, which is the visualizer's (and an LLM's) only view of it. +public final class CodeModel { + /// Format version of the JSON, bumped on an incompatible change. + static final int FORMAT = 1; + + final String root; + String layout = "generic"; + final List files = new ArrayList(); + final List types = new ArrayList(); + final List methods = new ArrayList(); + final Map typesByName = new HashMap(); + final Map filesByPath = new HashMap(); + /// The base revision's text of each changed Java file that existed there, by model path. + final Map baseText = new HashMap(); + /// Native functions (Objective-C, C, C++), with the Java native they implement. + final List natives = new ArrayList(); + GitInfo git; + /// Which commit wrote each line; null without a base. + Commits commits; + final List removed = new ArrayList(); + /// The reviewer's approvals; null without a base. + Approvals approvals; + + CodeModel(String root) { + this.root = root; + this.git = null; + } + + /// The root directory the paths are relative to. + public String getRoot() { + return root; + } + + /// Number of indexed files. + public int getFileCount() { + return files.size(); + } + + /// Number of Java types. + public int getTypeCount() { + return types.size(); + } + + /// Number of Java methods and constructors. + public int getMethodCount() { + return methods.size(); + } + + SourceFile addFile(String path, String language) { + SourceFile f = new SourceFile(files.size(), path, language); + files.add(f); + filesByPath.put(path, f); + return f; + } + + /// One file of the tree. + static final class SourceFile { + final int id; + final String path; + final String language; + String module = ""; + boolean test; + int lines; + int codeLines; + String pkg = ""; + final List imports = new ArrayList(); + final List onDemandImports = new ArrayList(); + final List staticImports = new ArrayList(); + final List types = new ArrayList(); + /// Set by `GitChanges`: `A`dded, `M`odified, `R`enamed; null when unchanged. + String change; + int added; + int deleted; + /// New-side line ranges the branch added or changed, as `[start, end]` pairs. + final List changedRanges = new ArrayList(); + + SourceFile(int id, String path, String language) { + this.id = id; + this.path = path; + this.language = language; + } + + boolean touches(int start, int end) { + for (int[] r : changedRanges) { + if (r[0] <= end && r[1] >= start) { + return true; + } + } + return false; + } + } + + /// A Java class, interface, enum, record or annotation type. + static final class Type { + int id; + final String name; + final String qualifiedName; + final String kind; + final int modifiers; + final SourceFile file; + final int line; + final int endLine; + final Type outer; + final String extendsName; + final List implementsNames; + final List fields = new ArrayList(); + final List methods = new ArrayList(); + final List nested = new ArrayList(); + /// Calls made by field initializers and initializer blocks. + final List initCalls = new ArrayList(); + Type superType; + final List interfaces = new ArrayList(); + /// Types this one depends on: supertypes, field, parameter and return types, + /// and the owners of what it calls or creates. + final Set dependencies = new LinkedHashSet(); + String change; + int impact = -1; + + Type(String name, String qualifiedName, String kind, int modifiers, SourceFile file, int line, + int endLine, Type outer, String extendsName, List implementsNames) { + this.name = name; + this.qualifiedName = qualifiedName; + this.kind = kind; + this.modifiers = modifiers; + this.file = file; + this.line = line; + this.endLine = endLine; + this.outer = outer; + this.extendsName = extendsName; + this.implementsNames = implementsNames; + } + + String pkg() { + return file.pkg; + } + } + + /// A field or record component. + static final class Field { + final String name; + final String typeName; + final int modifiers; + final int line; + Type resolved; + + Field(String name, String typeName, int modifiers, int line) { + this.name = name; + this.typeName = typeName; + this.modifiers = modifiers; + this.line = line; + } + } + + /// A method or constructor (``). + static final class Method { + int id; + final Type owner; + final String name; + final String returnType; + final List paramTypes; + final List paramNames; + final int modifiers; + final int line; + final int endLine; + int complexity = 1; + final Map locals = new LinkedHashMap(); + final List rawCalls = new ArrayList(); + final Set calls = new LinkedHashSet(); + final Set callers = new LinkedHashSet(); + /// The line of the first call this method makes to each callee. + final Map callLines = new HashMap(); + /// Supertype methods this one overrides (same name and arity). + final Set overrides = new LinkedHashSet(); + String change; + int impact = -1; + /// For a changed method, its declaration line at the base revision; 0 otherwise. + int oldLine; + /// For a changed method, its complexity at the base revision; 0 otherwise. + int oldComplexity; + /// For a changed method, the names it called at the base revision; null otherwise. + Set oldCalls; + /// While a commit is focused, the calls that commit wrote; null otherwise. + Set focusNewCalls; + + /// Whether the call to `callee` is one the branch introduced: every call of a new + /// method, and a call of a changed one whose name the base version never called. + boolean isNewCall(Method callee) { + if (focusNewCalls != null) { + return focusNewCalls.contains(callee); + } + return "A".equals(change) || oldCalls != null && !oldCalls.contains(callee.name); + } + + /// The names the base version called that this one no longer calls. + List droppedCalls() { + List out = new ArrayList(); + // Removal cannot be placed on one commit (see Commits), so it shows unfocused only. + if (oldCalls == null || focusNewCalls != null) { + return out; + } + Set now = new HashSet(); + for (Call c : rawCalls) { + now.add(c.name); + } + for (String n : oldCalls) { + if (!now.contains(n)) { + out.add(n); + } + } + return out; + } + + Method(Type owner, String name, String returnType, List paramTypes, List paramNames, + int modifiers, int line, int endLine) { + this.owner = owner; + this.name = name; + this.returnType = returnType; + this.paramTypes = paramTypes; + this.paramNames = paramNames; + this.modifiers = modifiers; + this.line = line; + this.endLine = endLine; + } + + /// `name(T1,T2)`, how the method is matched across revisions. + String signature() { + StringBuilder sb = new StringBuilder(name).append('('); + for (int i = 0; i < paramTypes.size(); i++) { + if (i > 0) { + sb.append(','); + } + sb.append(paramTypes.get(i)); + } + return sb.append(')').toString(); + } + + boolean isStatic() { + return (modifiers & 0x0008) != 0; + } + } + + /// A call or instance creation as written, before resolution. + static final class Call { + final String receiver; + final String name; + final int argCount; + final int line; + final boolean creation; + + Call(String receiver, String name, int argCount, int line, boolean creation) { + this.receiver = receiver; + this.name = name; + this.argCount = argCount; + this.line = line; + this.creation = creation; + } + } + + /// A native function and, when its name is a ParparVM native name, the Java method + /// it implements. + static final class NativeFunction { + final String name; + final SourceFile file; + final int line; + final int endLine; + Method javaMethod; + String change; + + NativeFunction(String name, SourceFile file, int line, int endLine) { + this.name = name; + this.file = file; + this.line = line; + this.endLine = endLine; + } + } + + /// A type or member the base revision had and the branch removed. + static final class Removed { + final String kind; + final String owner; + final String signature; + final String path; + final int line; + + Removed(String kind, String owner, String signature, String path, int line) { + this.kind = kind; + this.owner = owner; + this.signature = signature; + this.path = path; + this.line = line; + } + } + + /// The revisions a change set was computed between. + static final class GitInfo { + String base; + String mergeBase; + String head; + String branch; + final List commits = new ArrayList(); + /// The model root's path inside the repository, ending in "/", or "". + String prefix = ""; + /// Renamed files: the base's path for each new one, both relative to the repository. + final java.util.Map renamedFrom = new java.util.HashMap(); + } + + // ------------------------------------------------------------------ JSON + + /// The whole model as JSON (see the visualizer's `ModelData` for the reading side). + public String toJson() { + StringBuilder sb = new StringBuilder(1 << 16); + Json.Writer w = new Json.Writer(sb); + w.beginObject(); + w.name("format").value(FORMAT); + w.name("root").value(root); + w.name("layout").value(layout); + if (git != null) { + w.name("git").beginObject(); + w.name("base").value(git.base); + w.name("mergeBase").value(git.mergeBase); + w.name("head").value(git.head); + w.name("branch").value(git.branch); + w.name("commits").beginArray(); + for (String c : git.commits) { + w.value(c); + } + w.endArray(); + w.endObject(); + } + w.name("files").beginArray(); + for (SourceFile f : files) { + w.beginObject(); + w.name("p").value(f.path); + w.name("lang").value(f.language); + w.name("mod").value(f.module); + if (f.test) { + w.name("test").value(true); + } + w.name("loc").value(f.lines); + w.name("sloc").value(f.codeLines); + if (f.pkg.length() > 0) { + w.name("pkg").value(f.pkg); + } + if (f.change != null) { + w.name("ch").value(f.change); + w.name("add").value(f.added); + w.name("del").value(f.deleted); + w.name("rg").beginArray(); + for (int[] r : f.changedRanges) { + w.beginArray().value(r[0]).value(r[1]).endArray(); + } + w.endArray(); + } + w.endObject(); + } + w.endArray(); + w.name("types").beginArray(); + for (Type t : types) { + w.beginObject(); + w.name("n").value(t.name); + w.name("q").value(t.qualifiedName); + w.name("k").value(t.kind); + w.name("m").value(t.modifiers); + w.name("f").value(t.file.id); + w.name("l").value(t.line); + w.name("e").value(t.endLine); + if (t.outer != null) { + w.name("o").value(t.outer.id); + } + if (t.extendsName != null) { + w.name("ext").value(t.extendsName); + } + if (t.superType != null) { + w.name("sup").value(t.superType.id); + } + if (!t.interfaces.isEmpty()) { + w.name("ifs").beginArray(); + for (Type i : t.interfaces) { + w.value(i.id); + } + w.endArray(); + } + if (!t.implementsNames.isEmpty()) { + w.name("impl").beginArray(); + for (String i : t.implementsNames) { + w.value(i); + } + w.endArray(); + } + w.name("deps").beginArray(); + for (Type d : t.dependencies) { + w.value(d.id); + } + w.endArray(); + w.name("fl").beginArray(); + for (Field f : t.fields) { + w.beginObject(); + w.name("n").value(f.name); + w.name("t").value(f.typeName); + if (f.resolved != null) { + w.name("ti").value(f.resolved.id); + } + w.name("m").value(f.modifiers); + w.name("l").value(f.line); + w.endObject(); + } + w.endArray(); + w.name("ms").beginArray(); + for (Method m : t.methods) { + w.value(m.id); + } + w.endArray(); + if (t.change != null) { + w.name("ch").value(t.change); + } + if (t.impact >= 0) { + w.name("imp").value(t.impact); + } + w.endObject(); + } + w.endArray(); + w.name("methods").beginArray(); + for (Method m : methods) { + w.beginObject(); + w.name("o").value(m.owner.id); + w.name("n").value(m.name); + if (m.returnType != null) { + w.name("r").value(m.returnType); + } + w.name("p").beginArray(); + for (String p : m.paramTypes) { + w.value(p); + } + w.endArray(); + w.name("pn").beginArray(); + for (String p : m.paramNames) { + w.value(p); + } + w.endArray(); + w.name("m").value(m.modifiers); + w.name("l").value(m.line); + w.name("e").value(m.endLine); + w.name("cx").value(m.complexity); + w.name("c").beginArray(); + for (Method c : m.calls) { + w.value(c.id); + } + w.endArray(); + if (!m.overrides.isEmpty()) { + w.name("ov").beginArray(); + for (Method o : m.overrides) { + w.value(o.id); + } + w.endArray(); + } + if (m.change != null) { + w.name("ch").value(m.change); + } + if (m.impact >= 0) { + w.name("imp").value(m.impact); + } + w.endObject(); + } + w.endArray(); + w.name("natives").beginArray(); + for (NativeFunction n : natives) { + w.beginObject(); + w.name("n").value(n.name); + w.name("f").value(n.file.id); + w.name("l").value(n.line); + w.name("e").value(n.endLine); + if (n.javaMethod != null) { + w.name("jm").value(n.javaMethod.id); + } + if (n.change != null) { + w.name("ch").value(n.change); + } + w.endObject(); + } + w.endArray(); + w.name("removed").beginArray(); + for (Removed r : removed) { + w.beginObject(); + w.name("k").value(r.kind); + w.name("o").value(r.owner); + w.name("s").value(r.signature); + w.name("p").value(r.path); + w.name("l").value(r.line); + w.endObject(); + } + w.endArray(); + w.endObject(); + return sb.toString(); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/CodeModelCLI.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/CodeModelCLI.java new file mode 100644 index 00000000000..1e4cb8e096f --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/CodeModelCLI.java @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import com.codename1.tools.javac.SourceOutliner; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +/// The code model's command line. The visualizer forks it, and an LLM can run it +/// directly and read the JSON it prints. +/// +/// ``` +/// index --root DIR [--base REF] [--depth N] [--no-tests] [--exclude PREFIX]... [--out FILE] +/// serve --root DIR [--base REF] [--depth N] [--no-tests] [--exclude PREFIX]... +/// flow --file FILE --line N [--out FILE] +/// ``` +/// +/// `index` writes the whole model (`CodeModel.toJson`); with `--base` it also marks +/// what the branch changed since its merge base with `REF` and how far that reaches. +/// `flow` writes the flow chart of the method declared on line `N` of `FILE`. +/// +/// `serve` indexes once and then answers requests, one per line on standard input, +/// each with one line of JSON on standard output; the first line it prints is the +/// `summary`, once the index is ready. The requests are those of `ModelQueries` +/// (`summary`, `packages [MODULE]`, `package NAME`, `type NAME|ID`, `method ID|Type#name`, +/// `callgraph ID [DEPTH]`, `diff`, `search TEXT`) plus `flow LINE PATH` (a path +/// relative to the root, or absolute), `history [WEEKS]`, `reload [REF|-]` (index +/// again, against another base or none) and `quit`. This is how the visualizer talks +/// to the model: a framework-sized tree is tens of megabytes of JSON as a whole, and a +/// view needs a few kilobytes of it. +/// +/// Exit status is 0 on success, 1 when the work failed and 2 for a bad command line. +public final class CodeModelCLI { + private CodeModelCLI() { + } + + /// Runs the command line. + public static void main(String[] args) { + int code; + try { + code = run(args, System.out, System.err); + } catch (IOException e) { + System.err.println("code-model: " + e.getMessage()); + code = 1; + } + if (code != 0) { + System.exit(code); + } + } + + static int run(String[] args, PrintStream out, PrintStream err) throws IOException { + if (args.length == 0) { + usage(err); + return 2; + } + String command = args[0]; + String root = "."; + String base = null; + String file = null; + String output = null; + int line = -1; + int depth = Impact.DEFAULT_DEPTH; + boolean tests = true; + java.util.List excludes = new java.util.ArrayList(); + for (int i = 1; i < args.length; i++) { + String a = args[i]; + boolean hasValue = i + 1 < args.length; + if ("--no-tests".equals(a)) { + tests = false; + } else if (!hasValue) { + err.println("code-model: " + a + " needs a value"); + return 2; + } else if ("--root".equals(a)) { + root = args[++i]; + } else if ("--base".equals(a)) { + base = args[++i]; + } else if ("--file".equals(a)) { + file = args[++i]; + } else if ("--line".equals(a)) { + line = parseInt(args[++i]); + } else if ("--depth".equals(a)) { + depth = parseInt(args[++i]); + } else if ("--exclude".equals(a)) { + excludes.add(args[++i]); + } else if ("--out".equals(a)) { + output = args[++i]; + } else { + err.println("code-model: unknown option " + a); + return 2; + } + } + String json; + if ("index".equals(command)) { + json = build(root, base, depth, tests, excludes).toJson(); + } else if ("serve".equals(command)) { + serve(root, base, depth, tests, excludes, out); + return 0; + } else if ("flow".equals(command)) { + if (file == null || line < 1) { + err.println("code-model: flow needs --file and --line"); + return 2; + } + String text = new String(Files.readAllBytes(new File(file).toPath()), StandardCharsets.UTF_8); + FlowNode flow = SourceOutliner.flow(file, text, line); + if (flow == null) { + err.println("code-model: no method is declared on line " + line + " of " + file); + return 1; + } + StringBuilder sb = new StringBuilder(); + flow.toJson(new Json.Writer(sb)); + json = sb.toString(); + } else { + usage(err); + return 2; + } + byte[] bytes = json.getBytes(StandardCharsets.UTF_8); + if (output == null) { + OutputStream o = out; + o.write(bytes); + o.flush(); + } else { + Files.write(new File(output).toPath(), bytes); + } + return 0; + } + + static CodeModel build(String root, String base, int depth, boolean tests, java.util.List excludes) + throws IOException { + ProjectScanner scanner = new ProjectScanner(new File(root)).includeTests(tests); + for (String e : excludes) { + scanner.exclude(e); + } + CodeModel model = scanner.scan(); + if (base != null) { + new GitChanges(model).apply(base); + Impact.compute(model, depth); + } + return model; + } + + private static void serve(String root, String base, int depth, boolean tests, java.util.List excludes, + PrintStream rawOut) throws IOException { + PrintStream out = new PrintStream(rawOut, false, "UTF-8"); + java.io.BufferedReader in = new java.io.BufferedReader( + new java.io.InputStreamReader(System.in, StandardCharsets.UTF_8)); + CodeModelSession session = CodeModelSession.open(root, base, depth, tests, excludes); + reply(out, session.ask("summary")); + String line; + while ((line = in.readLine()) != null) { + String req = line.trim(); + if (req.length() == 0) { + continue; + } + if ("quit".equals(req)) { + break; + } + reply(out, session.ask(req)); + } + out.flush(); + } + + private static void reply(PrintStream out, String json) { + // The writer escapes every control character, so a document is always one line. + out.print(json); + out.print('\n'); + out.flush(); + } + + private static int parseInt(String s) { + try { + return Integer.parseInt(s); + } catch (NumberFormatException e) { + return -1; + } + } + + private static void usage(PrintStream err) { + err.println("usage: code-model index --root DIR [--base REF] [--depth N] [--no-tests] " + + "[--exclude PREFIX]... [--out FILE]"); + err.println(" code-model serve --root DIR [--base REF] [--depth N] [--no-tests] [--exclude PREFIX]..."); + err.println(" code-model flow --file FILE --line N [--out FILE]"); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/CodeModelSession.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/CodeModelSession.java new file mode 100644 index 00000000000..190722d0bd1 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/CodeModelSession.java @@ -0,0 +1,338 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import com.codename1.tools.javac.SourceOutliner; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/// An indexed tree that answers requests: the line protocol of `CodeModelCLI serve`, +/// callable in process. Each answer is one JSON document; a request that fails answers +/// an object with an `error` member instead of throwing. +/// +/// The requests are `summary`, `packages [MODULE]`, `package NAME`, `type NAME|ID`, +/// `method ID|Type#name`, `callgraph ID [DEPTH]`, `diff`, `search TEXT`, `flow LINE PATH`, +/// `flowdiff ID`, `filediff PATH`, `highlights` (a path relative to the root, or absolute), `history [WEEKS]` and `reload [REF|-]` +/// (index again against another base, or with `-` against none). +/// +/// A session is not thread safe; callers ask one question at a time. +public final class CodeModelSession { + private final String root; + private final int depth; + private final boolean tests; + private final List excludes; + private String base; + private CodeModel model; + private ModelQueries queries; + private Progress progress; + /// The approvals hidden from every answer, key to fingerprint; kept across reloads. + private Map hidden = new HashMap(); + + private CodeModelSession(String root, String base, int depth, boolean tests, List excludes) { + this.root = root; + this.base = base; + this.depth = depth; + this.tests = tests; + this.excludes = new ArrayList(excludes); + } + + /// Indexes `root`, and with a non-null `base` marks what changed since the merge base + /// with it, test sources included. + public static CodeModelSession open(String root, String base) throws IOException { + return open(root, base, Impact.DEFAULT_DEPTH, true, new ArrayList()); + } + + /// As `open(String, String)`, with the impact depth, whether test sources count, and + /// path prefixes to leave out. + public static CodeModelSession open(String root, String base, int depth, boolean tests, List excludes) + throws IOException { + return open(root, base, depth, tests, excludes, null); + } + + /// As the five-argument `open`, reporting each indexing phase to `progress` (may be null), + /// which is also told about every later `reload`. + public static CodeModelSession open(String root, String base, int depth, boolean tests, List excludes, + Progress progress) throws IOException { + CodeModelSession s = new CodeModelSession(root, base, depth, tests, excludes); + s.progress = progress; + s.index(); + return s; + } + + private void index() throws IOException { + ProjectScanner scanner = new ProjectScanner(new File(root)).includeTests(tests).progress(progress); + for (String e : excludes) { + scanner.exclude(e); + } + CodeModel m = scanner.scan(); + if (base != null) { + report("Comparing with " + base); + new GitChanges(m).apply(base); + report("Tracing the impact of the changes"); + Impact.compute(m, depth); + report("Reading the commits"); + m.commits = new Commits(m, new File(root)); + m.approvals = new Approvals(m); + if (!hidden.isEmpty()) { + m.approvals.apply(hidden, depth); + } + } + model = m; + queries = new ModelQueries(m); + } + + private void report(String phase) { + if (progress != null) { + progress.progress(phase, 0, 0); + } + } + + /// The model as indexed, for tests in this package. + CodeModel model() { + return model; + } + + /// The indexed root, as given. + public String getRoot() { + return root; + } + + /// The revision changes are measured against, or null. + public String getBase() { + return base; + } + + /// The whole model, `CodeModel.toJson`'s format. + public String toJson() { + return model.toJson(); + } + + /// Answers one request. + public String ask(String request) { + String req = request.trim(); + try { + if (req.startsWith("filediff ")) { + return FileDiff.of(model, req.substring(9).trim()); + } + if (req.startsWith("flowdiff ")) { + return flowDiff(req.substring(9).trim()); + } + if (req.startsWith("flow ")) { + return flow(req.substring(5).trim()); + } + if ("history".equals(req) || req.startsWith("history ")) { + int weeks = req.length() > 8 ? parseInt(req.substring(8), 26) : 26; + return History.churn(new File(root), weeks < 1 ? 26 : Math.min(weeks, 520)); + } + if ("hide".equals(req) || req.startsWith("hide ")) { + return hide(req.substring(4).trim()); + } + if ("highlights".equals(req)) { + return new Highlights(model).answer(); + } + if (model.commits != null && ("commits".equals(req) || "prsummary".equals(req) + || req.startsWith("commit ") || req.startsWith("why "))) { + return new ReviewQueries(model).answer(req); + } + if ("reload".equals(req) || req.startsWith("reload ")) { + String arg = req.length() > 7 ? req.substring(7).trim() : ""; + String previous = base; + if (arg.length() > 0) { + base = "-".equals(arg) ? null : arg; + } + try { + index(); + } catch (IOException | RuntimeException e) { + // A ref that does not resolve leaves the session on the base it had. + base = previous; + throw e; + } + return queries.answer("summary"); + } + return queries.answer(req); + } catch (IOException | RuntimeException e) { + return ModelQueries.error(e.getClass().getSimpleName() + ": " + e.getMessage()); + } + } + + /// `hide KEY=FINGERPRINT|KEY=FINGERPRINT...`: treats those approved items as unchanged + /// in every later answer while they still match; a bare `hide` shows everything again. + private String hide(String arg) { + if (model.approvals == null) { + return ModelQueries.error("the model was indexed without a base revision"); + } + Map next = new HashMap(); + for (String pair : arg.split("\\|")) { + int eq = pair.lastIndexOf('='); + if (eq > 0) { + next.put(pair.substring(0, eq).trim(), pair.substring(eq + 1).trim()); + } + } + hidden = next; + model.approvals.apply(hidden, depth); + return queries.answer("summary"); + } + + private String flow(String arg) throws IOException { + int sp = arg.indexOf(' '); + if (sp < 0) { + return ModelQueries.error("usage: flow LINE PATH"); + } + int line = parseInt(arg.substring(0, sp), -1); + File f = new File(arg.substring(sp + 1).trim()); + if (!f.isAbsolute()) { + f = new File(model.root, f.getPath()); + } + String text = new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8); + FlowNode flow = SourceOutliner.flow(f.getPath(), text, line); + if (flow == null) { + return ModelQueries.error("no method is declared on line " + line + " of " + f.getPath()); + } + StringBuilder sb = new StringBuilder(); + flow.toJson(new Json.Writer(sb)); + return sb.toString(); + } + + /// The flow chart of method `id` as the base revision had it (`before`, absent for a new + /// method) and as it is now (`after`), so a reviewer sees the logic change. + private String flowDiff(String id) throws IOException { + CodeModel.Method m = queries.findMethod(id); + if (m == null) { + return ModelQueries.error("no method " + id); + } + String path = m.owner.file.path; + File root = new File(model.root); + String now = new String(Files.readAllBytes(new File(root, path).toPath()), StandardCharsets.UTF_8); + FlowNode after = SourceOutliner.flow(path, now, m.line); + FlowNode before = null; + int oldLine = 0; + int oldEnd = 0; + String old = null; + if (model.git != null && !"A".equals(m.change)) { + old = model.baseText.get(path); + if (old == null) { + try { + old = Git.run(root, "show", model.git.mergeBase + ":./" + path); + } catch (IOException e) { + old = null; + } + } + if (old != null) { + CodeModel was = new CodeModel(model.root); + ModelBuilder.add(was, was.addFile(path, "java"), old); + String key = m.owner.qualifiedName + "#" + m.signature(); + for (CodeModel.Method o : was.methods) { + if (key.equals(o.owner.qualifiedName + "#" + o.signature())) { + oldLine = o.line; + oldEnd = o.endLine; + before = SourceOutliner.flow(path, old, o.line); + } + } + } + } + StringBuilder sb = new StringBuilder(); + Json.Writer w = new Json.Writer(sb); + w.beginObject(); + w.name("path").value(path); + w.name("ch").value(m.change == null ? "" : m.change); + w.name("line").value(m.line); + w.name("end").value(m.endLine); + w.name("oldLine").value(oldLine); + notes(w, "notes", path, now.split("\r?\n", -1), m.line, m.endLine, true); + if (old != null && oldLine > 0) { + notes(w, "oldNotes", path, old.split("\r?\n", -1), oldLine, oldEnd, false); + } + if (model.commits != null) { + w.name("commits").beginArray(); + for (String sha : model.commits.in(path, m.line, m.endLine)) { + Commits.Info c = model.commits.get(sha); + if (c != null) { + w.beginObject(); + w.name("sha").value(sha.length() > 10 ? sha.substring(0, 10) : sha); + w.name("subject").value(c.subject); + String body = c.body == null ? "" : c.body.trim(); + w.name("body").value(body.length() > 600 ? body.substring(0, 597) + "..." : body); + w.endObject(); + } + } + w.endArray(); + } + sb.append(",\"after\":"); + writeFlow(sb, after); + sb.append(",\"before\":"); + writeFlow(sb, before); + sb.append('}'); + return sb.toString(); + } + + /// Per code line of `from..to`: the comment that explains it and, on the new side, the + /// branch commit that wrote it, so a flow chart can say why a step is there or was removed. + private void notes(Json.Writer w, String name, String path, String[] text, int from, int to, boolean now) { + w.name(name).beginArray(); + for (int line = Math.max(1, from); line <= to && line <= text.length; line++) { + String code = text[line - 1].trim(); + if (code.length() == 0 || code.startsWith("//") || code.startsWith("*") || code.startsWith("/*")) { + continue; + } + String comment = Commits.commentIn(text, line); + String sha = now && model.commits != null ? model.commits.at(path, line) : null; + Commits.Info c = sha == null ? null : model.commits.get(sha); + if (comment == null && c == null) { + continue; + } + w.beginObject(); + w.name("line").value(line); + if (comment != null) { + w.name("comment").value(comment); + } + if (c != null) { + w.name("subject").value(c.subject); + } + w.endObject(); + } + w.endArray(); + } + + private static void writeFlow(StringBuilder sb, FlowNode f) { + if (f == null) { + sb.append("null"); + } else { + f.toJson(new Json.Writer(sb)); + } + } + + private static int parseInt(String s, int def) { + try { + return Integer.parseInt(s.trim()); + } catch (NumberFormatException e) { + return def; + } + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/Commits.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Commits.java new file mode 100644 index 00000000000..23e6c735506 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Commits.java @@ -0,0 +1,482 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Which commit of the branch wrote each line: the material of "why did this change". +/// +/// One primitive answers every question: `git blame` of the working tree, so uncommitted +/// edits appear too, lazily per file and cached, keeping only the commits of +/// `mergeBase..HEAD`. A line older than the branch answers null; an uncommitted line answers [#UNCOMMITTED], which is listed +/// as a commit of its own ("Uncommitted changes") because that is what a branch in progress +/// has. From it come the commit of a call, the commits of a method, the comments the +/// branch added, and the commit filter ([#focus]). +/// +/// Deletions are not on HEAD, so blame cannot place them: a removed method or call belongs +/// to the whole range and is shown only when no commit is focused, never guessed at. +final class Commits { + /// The id git gives a line that is not committed. + static final String UNCOMMITTED = "0000000000000000000000000000000000000000"; + + /// One commit of the branch. + static final class Info { + final String sha; + final long time; + final String author; + final String subject; + final String body; + int added; + int deleted; + final List files = new ArrayList(); + /// Model path to {added, deleted} in this commit. + final Map perFile = new LinkedHashMap(); + + Info(String sha, long time, String author, String subject, String body) { + this.sha = sha; + this.time = time; + this.author = author; + this.subject = subject; + this.body = body; + } + } + + private final CodeModel model; + private final File root; + private final String prefix; + private final Map bySha = new LinkedHashMap(); + private final Map blames = new HashMap(); + private final Map texts = new HashMap(); + private String focus; + private Map saved; + + Commits(CodeModel model, File root) throws IOException { + this.model = model; + this.root = root; + this.prefix = Git.run(root, "rev-parse", "--show-prefix").trim(); + String range = model.git.mergeBase + "..HEAD"; + String log = Git.run(root, "-c", "core.quotePath=false", "log", "--numstat", "--no-renames", + "--format=%x1e%H%x1f%ct%x1f%an%x1f%s%x1f%b%x1f", range, "--", "."); + for (String rec : log.split("\u001e")) { + String[] p = rec.split("\u001f", -1); + if (p.length < 6) { + continue; + } + Info c = new Info(p[0].trim(), parseLong(p[1]), p[2], p[3], trailerless(p[4])); + numstat(c, p[5]); + bySha.put(c.sha, c); + } + String dirty = Git.run(root, "-c", "core.quotePath=false", "diff", "--numstat", "--no-renames", "HEAD", + "--", "."); + Info u = new Info(UNCOMMITTED, System.currentTimeMillis() / 1000, "", "Uncommitted changes", + "Edits in the working tree that are not committed yet."); + numstat(u, dirty); + for (String untracked : Git.lines(Git.run(root, "-c", "core.quotePath=false", "ls-files", "--others", + "--exclude-standard", "--", "."), '\n')) { + if (ProjectScanner.languageOf(untracked) != null) { + int n = lines(strip(untracked)).length; + u.files.add(strip(untracked)); + u.perFile.put(strip(untracked), new int[]{n, 0}); + u.added += n; + } + } + if (!u.files.isEmpty()) { + // Newest first, like the log: the working tree is newer than any commit. + Map all = new LinkedHashMap(); + all.put(UNCOMMITTED, u); + all.putAll(bySha); + bySha.clear(); + bySha.putAll(all); + } + } + + /// The body without its trailers (co-authors, sign-offs), which say nothing about why. + private static String trailerless(String body) { + StringBuilder sb = new StringBuilder(); + for (String l : body.split("\n", -1)) { + String t = l.trim().toLowerCase(java.util.Locale.ROOT); + if (!t.startsWith("co-authored-by:") && !t.startsWith("signed-off-by:")) { + sb.append(l).append('\n'); + } + } + return sb.toString().replaceAll("\n{3,}", "\n\n").trim(); + } + + /// The first line of the comment and annotations directly above `line`, or `line`. + int docStart(String path, int line) { + String[] t = lines(path); + int i = line - 1; + while (i >= 1) { + String s = t[i - 1].trim(); + if (s.startsWith("//") || s.startsWith("*") || s.startsWith("/*") || s.startsWith("@")) { + i--; + } else { + break; + } + } + return i + 1; + } + + private void numstat(Info c, String text) { + for (String l : Git.lines(text, '\n')) { + String[] parts = l.split("\t"); + if (parts.length < 3 || ProjectScanner.languageOf(parts[2]) == null) { + continue; + } + int a = "-".equals(parts[0]) ? 0 : Integer.parseInt(parts[0]); + int d = "-".equals(parts[1]) ? 0 : Integer.parseInt(parts[1]); + c.added += a; + c.deleted += d; + c.files.add(strip(parts[2])); + c.perFile.put(strip(parts[2]), new int[]{a, d}); + } + } + + private String strip(String gitPath) { + return gitPath.startsWith(prefix) ? gitPath.substring(prefix.length()) : gitPath; + } + + private static long parseLong(String s) { + try { + return Long.parseLong(s.trim()); + } catch (NumberFormatException e) { + return 0; + } + } + + /// The branch's commits, newest first, the working tree first of all when it is dirty. + List all() { + return new ArrayList(bySha.values()); + } + + Info get(String sha) { + return sha == null ? null : bySha.get(sha); + } + + /// The commit currently focused, or null for the whole branch. + String focus() { + return focus; + } + + /// Resolves an abbreviated id (or `uncommitted`) to a commit of the branch. + String resolve(String id) { + if ("uncommitted".equalsIgnoreCase(id) && bySha.containsKey(UNCOMMITTED)) { + return UNCOMMITTED; + } + for (String sha : bySha.keySet()) { + if (id.length() >= 4 && sha.startsWith(id)) { + return sha; + } + } + return null; + } + + /// The source text of a model path, one entry per line. + String[] lines(String path) { + String[] t = texts.get(path); + if (t == null) { + try { + t = new String(Files.readAllBytes(new File(model.root, path).toPath()), StandardCharsets.UTF_8) + .split("\r?\n", -1); + } catch (IOException e) { + t = new String[0]; + } + texts.put(path, t); + } + return t; + } + + /// The commit that wrote line `line` (1-based) of `path`, or null when it predates the branch. + String at(String path, int line) { + String[] b = blame(path); + return line >= 1 && line <= b.length ? b[line - 1] : null; + } + + /// The commits that wrote any line in `from..to` of `path`, newest first. + List in(String path, int from, int to) { + Set seen = new HashSet(); + String[] b = blame(path); + for (int i = Math.max(1, from); i <= to && i <= b.length; i++) { + if (b[i - 1] != null) { + seen.add(b[i - 1]); + } + } + List out = new ArrayList(); + for (String sha : bySha.keySet()) { + if (seen.contains(sha)) { + out.add(sha); + } + } + return out; + } + + private String[] blame(String path) { + String[] b = blames.get(path); + if (b != null) { + return b; + } + int n = lines(path).length; + b = new String[n]; + CodeModel.SourceFile f = file(path); + if (f != null && "A".equals(f.change) && !tracked(path)) { + // Untracked: every line is the working tree's. + java.util.Arrays.fill(b, UNCOMMITTED); + } else if (f != null && f.change != null) { + try { + // Not "mergeBase..": a range blames HEAD, and the working tree's edits are + // exactly what a branch in progress has. Older commits fall out below. + String out = Git.run(root, "blame", "--line-porcelain", "--", path); + String sha = null; + boolean boundary = false; + int at = 0; + for (String l : Git.lines(out, '\n')) { + if (l.startsWith("\t")) { + if (at < n) { + b[at] = boundary || sha == null ? null : bySha.containsKey(sha) ? sha : null; + } + at++; + } else if (l.length() > 41 && l.charAt(40) == ' ' && isHex(l, 40)) { + sha = l.substring(0, 40); + boundary = false; + } else if (l.startsWith("boundary")) { + boundary = true; + } + } + } catch (IOException e) { + // A file git cannot blame keeps no attribution; its change still shows. + java.util.Arrays.fill(b, null); + } + } + blames.put(path, b); + return b; + } + + private boolean tracked(String path) { + try { + return Git.run(root, "ls-files", "--", path).trim().length() > 0; + } catch (IOException e) { + return false; + } + } + + private static boolean isHex(String s, int n) { + for (int i = 0; i < n; i++) { + char c = s.charAt(i); + if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f')) { + return false; + } + } + return true; + } + + private CodeModel.SourceFile file(String path) { + for (CodeModel.SourceFile f : model.files) { + if (f.path.equals(path)) { + return f; + } + } + return null; + } + + // ------------------------------------------------------------------ comments + + /// The comment that explains line `line`: its own end-of-line comment, else the + /// comment lines directly above it. Null when there is none. + String commentAt(String path, int line) { + return commentIn(lines(path), line); + } + + /// `#commentAt(String, int)` over any text, one entry per line: the base revision's too. + static String commentIn(String[] t, int line) { + if (line < 1 || line > t.length) { + return null; + } + String own = t[line - 1]; + int eol = lineComment(own); + if (eol >= 0) { + return own.substring(eol + 2).trim(); + } + List above = new ArrayList(); + for (int i = line - 2; i >= 0 && above.size() < 8; i--) { + String s = t[i].trim(); + if (s.startsWith("//") || s.startsWith("*") || s.startsWith("/*")) { + above.add(0, clean(s)); + } else { + break; + } + } + StringBuilder sb = new StringBuilder(); + for (String s : above) { + if (s.length() > 0) { + sb.append(sb.length() == 0 ? "" : " ").append(s); + } + } + return sb.length() == 0 ? null : sb.toString(); + } + + /// Where the `//` comment of a line starts, outside string and char literals, or -1. + static int lineComment(String s) { + char quote = 0; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (quote != 0) { + if (c == '\\') { + i++; + } else if (c == quote) { + quote = 0; + } + } else if (c == '"' || c == '\'') { + quote = c; + } else if (c == '/' && i + 1 < s.length() && s.charAt(i + 1) == '/') { + return i; + } + } + return -1; + } + + private static String clean(String s) { + String r = s; + while (r.startsWith("/") || r.startsWith("*")) { + r = r.substring(1); + } + if (r.endsWith("*/")) { + r = r.substring(0, r.length() - 2); + } + return r.trim(); + } + + /// The comments the branch wrote inside `from..to` of `path`: runs of comment lines + /// whose lines the range (or the focused commit) wrote, each `{line, text, commit}`. + List addedComments(String path, int from, int to) { + List out = new ArrayList(); + String[] t = lines(path); + StringBuilder run = null; + int runLine = 0; + String runSha = null; + for (int i = Math.max(1, from); i <= to + 1 && i <= t.length + 1; i++) { + String s = i <= t.length && i <= to ? t[i - 1].trim() : ""; + String sha = i <= t.length ? at(path, i) : null; + boolean comment = (s.startsWith("//") || s.startsWith("*") || s.startsWith("/*")) + && sha != null && (focus == null || focus.equals(sha)); + if (comment) { + if (run == null) { + run = new StringBuilder(); + runLine = i; + runSha = sha; + } + String c = clean(s); + if (c.length() > 0) { + run.append(run.length() == 0 ? "" : " ").append(c); + } + } else if (run != null) { + if (run.length() > 0) { + out.add(new Object[]{runLine, run.toString(), runSha}); + } + run = null; + } + } + return out; + } + + // ------------------------------------------------------------------ the filter + + /// Narrows the model's change marks to what commit `sha` wrote, or restores the whole + /// branch with null. A file, class or method stays marked only when that commit wrote + /// one of its lines; it stays "new" only when that commit wrote all of the branch's + /// lines in it. A call counts as new only when that commit wrote its line. + void focus(String sha) { + restore(); + focus = sha; + if (sha == null) { + return; + } + saved = new IdentityHashMap(); + for (CodeModel.SourceFile f : model.files) { + if (f.change == null) { + continue; + } + saved.put(f, f.change); + boolean any = in(f.path, 1, Integer.MAX_VALUE).contains(sha); + for (CodeModel.Type t : f.types) { + mark(t, t.change, f.path, t.line, t.endLine, sha); + for (CodeModel.Method m : t.methods) { + saved.put(m, m.change == null ? "" : m.change); + m.change = narrowed(m.change, f.path, m.line, m.endLine, sha); + m.focusNewCalls = new HashSet(); + for (Map.Entry e : m.callLines.entrySet()) { + if (sha.equals(at(f.path, e.getValue()))) { + m.focusNewCalls.add(e.getKey()); + } + } + } + } + f.change = any ? f.change : null; + } + } + + private void mark(CodeModel.Type t, String change, String path, int from, int to, String sha) { + saved.put(t, change == null ? "" : change); + t.change = narrowed(change, path, from, to, sha); + } + + private String narrowed(String change, String path, int from, int to, String sha) { + if (change == null) { + return null; + } + List c = in(path, from, to); + if (!c.contains(sha)) { + return null; + } + return "A".equals(change) && c.size() == 1 ? "A" : "M"; + } + + private void restore() { + if (saved == null) { + return; + } + for (Map.Entry e : saved.entrySet()) { + String v = e.getValue().length() == 0 ? null : e.getValue(); + Object o = e.getKey(); + if (o instanceof CodeModel.SourceFile) { + ((CodeModel.SourceFile) o).change = e.getValue(); + } else if (o instanceof CodeModel.Type) { + ((CodeModel.Type) o).change = v; + } else if (o instanceof CodeModel.Method) { + ((CodeModel.Method) o).change = v; + ((CodeModel.Method) o).focusNewCalls = null; + } + } + saved = null; + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/FileDiff.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/FileDiff.java new file mode 100644 index 00000000000..85b352e907a --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/FileDiff.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +/// The whole of one file as a unified diff against the merge base: every line of the +/// new file, with the lines the branch removed placed where they were. +/// +/// The answer is `{"path", "lines": [[kind, oldLine, newLine, text], ...]}`, where kind is +/// `+` (added, old line 0), `-` (removed, new line 0) or a space (unchanged). A file the +/// base does not have is all `+`; with no base, or no change, all spaces. +final class FileDiff { + private FileDiff() { + } + + static String of(CodeModel model, String path) throws IOException { + CodeModel.SourceFile f = model.filesByPath.get(path); + if (f == null) { + return ModelQueries.error("no indexed file " + path); + } + File root = new File(model.root); + String current = new String(Files.readAllBytes(new File(root, path).toPath()), StandardCharsets.UTF_8); + String diff = ""; + if (model.git != null && f.change != null && !"A".equals(f.change)) { + // Full context, so the answer holds every line; the caller folds unchanged runs. + // A renamed file needs its old path too, or git cannot pair the two and shows + // every line as added. The old path is the repository's, hence :(top). + String gitPath = model.git.renamedFrom.get(model.git.prefix + path); + diff = gitPath == null + ? Git.run(root, "diff", "-U1000000", "--no-color", "-M", model.git.mergeBase, "--", path) + : Git.run(root, "diff", "-U1000000", "--no-color", "-M", model.git.mergeBase, "--", + ":(top)" + gitPath, path); + } + StringBuilder sb = new StringBuilder(); + Json.Writer w = new Json.Writer(sb); + w.beginObject(); + w.name("path").value(path); + w.name("ch").value(f.change == null ? "" : f.change); + w.name("lines").beginArray(); + if (diff.indexOf("\n@@") < 0 && !diff.startsWith("@@")) { + String kind = "A".equals(f.change) ? "+" : " "; + String[] lines = split(current); + for (int i = 0; i < lines.length; i++) { + line(w, kind, "+".equals(kind) ? 0 : i + 1, i + 1, lines[i]); + } + } else { + boolean body = false; + int oldNo = 0; + int newNo = 0; + for (String l : split(diff)) { + if (l.startsWith("@@")) { + int minus = l.indexOf('-', 2); + int plus = l.indexOf('+', minus); + oldNo = start(l.substring(minus + 1, l.indexOf(' ', minus))); + newNo = start(l.substring(plus + 1, l.indexOf(' ', plus))); + body = true; + } else if (!body || l.startsWith("\\")) { + continue; + } else if (l.startsWith("+")) { + line(w, "+", 0, newNo++, l.substring(1)); + } else if (l.startsWith("-")) { + line(w, "-", oldNo++, 0, l.substring(1)); + } else if (l.length() > 0 || newNo > 0) { + line(w, " ", oldNo++, newNo++, l.length() > 0 ? l.substring(1) : ""); + } + } + } + w.endArray(); + w.endObject(); + return sb.toString(); + } + + private static void line(Json.Writer w, String kind, int oldNo, int newNo, String text) { + w.beginArray().value(kind).value(oldNo).value(newNo).value(text).endArray(); + } + + private static int start(String spec) { + int comma = spec.indexOf(','); + return Integer.parseInt(comma < 0 ? spec : spec.substring(0, comma)); + } + + private static String[] split(String s) { + String t = s.endsWith("\n") ? s.substring(0, s.length() - 1) : s; + return t.length() == 0 ? new String[0] : t.split("\r?\n", -1); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/FlowNode.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/FlowNode.java new file mode 100644 index 00000000000..3220fd929e1 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/FlowNode.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/// One step of a method's structured control flow, the material of a flow chart. +/// +/// A step is a statement (`kind` such as `stmt`, `return`, `throw`, `call`) or a +/// construct with branches: `if` has a `then` and possibly an `else` branch, a loop +/// one `body` branch, `switch` one branch per case, `try` a `try` branch, one per +/// `catch` and a `finally`. Each branch is a labelled sequence of steps. +public final class FlowNode { + private final String kind; + private final String label; + private final int line; + private final List branchLabels = new ArrayList(); + private final List> branches = new ArrayList>(); + + /// A step of the given kind, labelled with the source text it stands for. + public FlowNode(String kind, String label, int line) { + this.kind = kind; + this.label = label; + this.line = line; + } + + /// Adds an empty branch and returns its list, to which the caller appends steps. + public List addBranch(String branchLabel) { + List b = new ArrayList(); + branchLabels.add(branchLabel); + branches.add(b); + return b; + } + + /// The step's kind. + public String getKind() { + return kind; + } + + /// The source text the step stands for, shortened to one line. + public String getLabel() { + return label; + } + + /// The 1 based line the step starts on. + public int getLine() { + return line; + } + + /// The labels of the branches, in order. + public List getBranchLabels() { + return Collections.unmodifiableList(branchLabels); + } + + /// The branches, parallel to `getBranchLabels()`. + public List> getBranches() { + return Collections.unmodifiableList(branches); + } + + /// Writes this step and its branches as JSON. + void toJson(Json.Writer w) { + w.beginObject(); + w.name("k").value(kind); + w.name("t").value(label); + w.name("l").value(line); + if (!branches.isEmpty()) { + w.name("b").beginArray(); + for (int i = 0; i < branches.size(); i++) { + w.beginObject(); + w.name("t").value(branchLabels.get(i)); + w.name("s").beginArray(); + for (FlowNode n : branches.get(i)) { + n.toJson(w); + } + w.endArray(); + w.endObject(); + } + w.endArray(); + } + w.endObject(); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/Git.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Git.java new file mode 100644 index 00000000000..7acdc974da7 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Git.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/// Runs `git` in a directory and returns what it prints. +final class Git { + private Git() { + } + + /// Runs `git args...` in `dir`; an exit status other than 0, or no git at all, is an + /// `IOException`. + static String run(File dir, String... args) throws IOException { + List cmd = new ArrayList(); + cmd.add("git"); + for (String a : args) { + cmd.add(a); + } + ProcessBuilder pb = new ProcessBuilder(cmd); + pb.directory(dir); + // Discarded: git's stderr is advice and progress, and an unread pipe can block it. + pb.redirectError(new File(File.separatorChar == '\\' ? "NUL" : "/dev/null")); + Process p = pb.start(); + String out = read(p.getInputStream()); + try { + int code = p.waitFor(); + if (code != 0) { + throw new IOException("git " + String.join(" ", args) + " exited with " + code); + } + } catch (InterruptedException e) { + p.destroy(); + Thread.currentThread().interrupt(); + throw new IOException("interrupted", e); + } + return out; + } + + /// `s` split at `separator`, empty pieces dropped. + static List lines(String s, char separator) { + List out = new ArrayList(); + int start = 0; + for (int i = 0; i <= s.length(); i++) { + if (i == s.length() || s.charAt(i) == separator) { + if (i > start) { + out.add(s.substring(start, i)); + } + start = i + 1; + } + } + return out; + } + + private static String read(InputStream in) throws IOException { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + try { + while ((n = in.read(buf)) > 0) { + bo.write(buf, 0, n); + } + } finally { + in.close(); + } + return new String(bo.toByteArray(), StandardCharsets.UTF_8); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/GitChanges.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/GitChanges.java new file mode 100644 index 00000000000..fedbd6478ce --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/GitChanges.java @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Marks what a branch changed, relative to a base revision, on a `CodeModel`. +/// +/// The comparison is between the merge base of `base` and `HEAD` and the **working +/// tree**, so uncommitted and untracked work is reviewed too, and the base's own later +/// commits are not mistaken for the branch's. Every changed file is marked with its +/// changed line ranges; a type or member whose lines intersect them is `M`odified, one +/// the base did not declare is `A`dded, and one the base declared that is gone is +/// recorded in `CodeModel.removed`. +final class GitChanges { + private final CodeModel model; + private final File root; + /// The model root relative to the git root, `""` or ending in `/`. + private String prefix = ""; + + GitChanges(CodeModel model) { + this.model = model; + this.root = new File(model.root); + } + + void apply(String base) throws IOException { + String top = git("rev-parse", "--show-toplevel").trim(); + String rel = new File(top).getCanonicalFile().toURI().relativize(root.getCanonicalFile().toURI()).getPath(); + prefix = rel; + CodeModel.GitInfo info = new CodeModel.GitInfo(); + info.base = base; + info.mergeBase = git("merge-base", base, "HEAD").trim(); + info.head = git("rev-parse", "HEAD").trim(); + info.branch = git("rev-parse", "--abbrev-ref", "HEAD").trim(); + for (String l : lines(git("log", "--format=%h %s", info.mergeBase + "..HEAD"))) { + info.commits.add(l); + } + info.prefix = prefix; + model.git = info; + + Map renamedFrom = info.renamedFrom; + Set deleted = new HashSet(); + for (String l : lines(git("diff", "--name-status", "-M", info.mergeBase, "--", "."))) { + String[] parts = l.split("\t"); + if (parts.length < 2) { + continue; + } + char status = parts[0].charAt(0); + if (status == 'D') { + deleted.add(parts[1]); + } else if (status == 'R' && parts.length >= 3) { + renamedFrom.put(parts[2], parts[1]); + } + } + parseDiff(git("diff", "-U0", "--no-color", "-M", info.mergeBase, "--", ".")); + // A rename with no edit has no hunks, so parseDiff never saw it; it is still a change. + for (String newPath : renamedFrom.keySet()) { + CodeModel.SourceFile f = model.filesByPath.get(toModelPath(newPath)); + if (f != null && f.change == null) { + f.change = "M"; + } + } + for (String l : lines(git("ls-files", "--full-name", "--others", "--exclude-standard", "--", "."))) { + CodeModel.SourceFile f = model.filesByPath.get(toModelPath(l)); + if (f != null) { + f.change = "A"; + f.added = f.lines; + f.changedRanges.add(new int[]{1, Math.max(1, f.lines)}); + } + } + for (CodeModel.SourceFile f : model.files) { + if (f.change != null) { + markMembers(f, renamedFrom.get(gitPath(f.path)), info.mergeBase); + } + } + for (String d : deleted) { + String mp = toModelPath(d); + if (mp != null && "java".equals(ProjectScanner.languageOf(mp))) { + recordAllRemoved(d, info.mergeBase, mp); + } + } + } + + private String gitPath(String modelPath) { + return prefix + modelPath; + } + + /// A git path as a model path, or null when it is outside the model root. + private String toModelPath(String gitPath) { + return gitPath.startsWith(prefix) ? gitPath.substring(prefix.length()) : null; + } + + /// The path of a `---` or `+++` header line. Git ends the line with a TAB when the + /// path holds a space, so a project under "My App" would otherwise match no file. + static String headerPath(String line) { + String p = line.substring(4); + return p.endsWith("\t") ? p.substring(0, p.length() - 1) : p; + } + + private void parseDiff(String diff) { + CodeModel.SourceFile current = null; + for (String l : lines(diff)) { + if (l.startsWith("+++ ")) { + String p = headerPath(l); + current = p.startsWith("b/") ? model.filesByPath.get(toModelPath(p.substring(2))) : null; + if (current != null && current.change == null) { + current.change = "M"; + } + } else if (l.startsWith("@@") && current != null) { + // @@ -a,b +c,d @@ + int plus = l.indexOf('+', 2); + int end = l.indexOf(' ', plus); + int minus = l.indexOf('-', 2); + int[] oldR = range(l.substring(minus + 1, l.indexOf(' ', minus))); + int[] newR = range(l.substring(plus + 1, end < 0 ? l.length() : end)); + current.deleted += oldR[1]; + current.added += newR[1]; + if (newR[1] > 0) { + current.changedRanges.add(new int[]{newR[0], newR[0] + newR[1] - 1}); + } else { + // A pure deletion: mark the line it happened after, so the member that + // lost lines still reads as modified. + current.changedRanges.add(new int[]{Math.max(1, newR[0]), Math.max(1, newR[0])}); + } + } + } + // A file the base did not have: its "---" header names /dev/null. + String last = null; + for (String l : lines(diff)) { + if (l.startsWith("--- ")) { + last = headerPath(l); + } else if (l.startsWith("+++ b/") && "/dev/null".equals(last)) { + CodeModel.SourceFile f = model.filesByPath.get(toModelPath(headerPath(l).substring(2))); + if (f != null) { + f.change = "A"; + } + } + } + } + + private static int[] range(String spec) { + int comma = spec.indexOf(','); + if (comma < 0) { + return new int[]{Integer.parseInt(spec), 1}; + } + return new int[]{Integer.parseInt(spec.substring(0, comma)), Integer.parseInt(spec.substring(comma + 1))}; + } + + private void markMembers(CodeModel.SourceFile f, String oldPath, String mergeBase) throws IOException { + boolean added = "A".equals(f.change); + CodeModel old = null; + if (!added && "java".equals(f.language)) { + old = outlineAt(mergeBase, oldPath != null ? oldPath : gitPath(f.path), f.path); + } + Set oldTypes = new HashSet(); + Set oldMethods = new HashSet(); + Map oldByKey = new HashMap(); + if (old != null) { + for (CodeModel.Type t : old.types) { + oldTypes.add(t.qualifiedName); + } + for (CodeModel.Method m : old.methods) { + oldMethods.add(m.owner.qualifiedName + "#" + m.signature()); + oldByKey.put(m.owner.qualifiedName + "#" + m.signature(), m); + } + } + Set newTypes = new HashSet(); + Set newMethods = new HashSet(); + for (CodeModel.Type t : f.types) { + newTypes.add(t.qualifiedName); + if (added || old != null && !oldTypes.contains(t.qualifiedName)) { + t.change = "A"; + } + for (CodeModel.Method m : t.methods) { + String key = t.qualifiedName + "#" + m.signature(); + newMethods.add(key); + if (added || old != null && !oldMethods.contains(key)) { + m.change = "A"; + } else if (f.touches(m.line, m.endLine)) { + m.change = "M"; + CodeModel.Method was = oldByKey.get(key); + if (was != null) { + m.oldLine = was.line; + m.oldComplexity = was.complexity; + m.oldCalls = new LinkedHashSet(); + for (CodeModel.Call c : was.rawCalls) { + m.oldCalls.add(c.name); + } + } + } + if (m.change != null && t.change == null) { + t.change = "M"; + } + } + if (t.change == null && f.touches(t.line, t.endLine)) { + t.change = "M"; + } + } + for (CodeModel.NativeFunction n : model.natives) { + if (n.file == f) { + if (added) { + n.change = "A"; + } else if (f.touches(n.line, n.endLine)) { + n.change = "M"; + } + } + } + if (old != null) { + for (CodeModel.Type t : old.types) { + if (!newTypes.contains(t.qualifiedName)) { + model.removed.add(new CodeModel.Removed("type", t.qualifiedName, t.name, f.path, t.line)); + } + } + for (CodeModel.Method m : old.methods) { + String key = m.owner.qualifiedName + "#" + m.signature(); + if (!newMethods.contains(key) && newTypes.contains(m.owner.qualifiedName)) { + model.removed.add(new CodeModel.Removed("method", m.owner.qualifiedName, m.signature(), f.path, + m.line)); + } + } + } + } + + private void recordAllRemoved(String gitPath, String mergeBase, String modelPath) throws IOException { + CodeModel old = outlineAt(mergeBase, gitPath, modelPath); + if (old == null) { + return; + } + for (CodeModel.Type t : old.types) { + model.removed.add(new CodeModel.Removed("type", t.qualifiedName, t.name, modelPath, t.line)); + } + } + + /// The outline of a file as it was at `rev`, or null when it did not exist there. + private CodeModel outlineAt(String rev, String gitPath, String modelPath) throws IOException { + String text; + try { + text = git("show", rev + ":" + gitPath); + } catch (IOException e) { + return null; + } + model.baseText.put(modelPath, text); + CodeModel old = new CodeModel(model.root); + CodeModel.SourceFile sf = old.addFile(modelPath, "java"); + ModelBuilder.add(old, sf, text); + return old; + } + + private static List lines(String s) { + return Git.lines(s, '\n'); + } + + /// Runs git with paths printed unquoted, so a path with non-ASCII characters + /// matches the model's spelling of it. + private String git(String... args) throws IOException { + String[] all = new String[args.length + 2]; + all[0] = "-c"; + all[1] = "core.quotePath=false"; + System.arraycopy(args, 0, all, 2, args.length); + return Git.run(root, all); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/Highlights.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Highlights.java new file mode 100644 index 00000000000..70aa558910c --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Highlights.java @@ -0,0 +1,414 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import com.codename1.tools.javac.SourceOutliner; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// The `highlights` request: the few changes of a branch a reviewer should study, ranked +/// by how much they change what the code does rather than by how many lines they add. +/// +/// A changed method scores for the steps its flow chart gained or lost and for decisions +/// added or removed (`flow`), for calls it started or stopped making (`wiring`), and for +/// callers outside its file the branch left alone, which now run different code +/// (`ripple`). A new method scores only for its own decisions and for the existing code it +/// calls into (`logic`), so a branch of mostly new boilerplate does not crowd out the one +/// existing method it rewrote. Each item names the view that shows it best. +final class Highlights { + private static final int MAX_ITEMS = 15; + private static final int MIN_SCORE = 3; + private static final int NAMES = 4; + private static final int LOGIC_CAP = 12; + private static final int REACH_CAP = 8; + + private final CodeModel model; + private final Commits commits; + private final Map current = new HashMap(); + private Map projectNames; + + Highlights(CodeModel model) { + this.model = model; + this.commits = model.commits; + } + + /// One ranked finding. + static final class Item { + final CodeModel.Method method; + String kind; + String view; + int score; + int stepsAdded; + int stepsRemoved; + int decisionsBefore; + int decisionsAfter; + final List newCalls = new ArrayList(); + final List dropped = new ArrayList(); + final List ripple = new ArrayList(); + String why; + + Item(CodeModel.Method method) { + this.method = method; + } + } + + String answer() { + List items = rank(); + StringBuilder sb = new StringBuilder(4096); + Json.Writer w = new Json.Writer(sb); + w.beginObject(); + w.name("items").beginArray(); + for (Item it : items) { + write(w, it); + } + w.endArray(); + w.endObject(); + return sb.toString(); + } + + List rank() { + String focus = commits == null ? null : commits.focus(); + Map> byFile = new LinkedHashMap>(); + for (CodeModel.Method m : model.methods) { + // Tests are read to check the change, not studied to understand it. + if (m.change == null || !"java".equals(m.owner.file.language) || m.owner.file.test) { + continue; + } + if (focus != null && !commits.in(m.owner.file.path, m.line, m.endLine).contains(focus)) { + continue; + } + List l = byFile.get(m.owner.file.path); + if (l == null) { + l = new ArrayList(); + byFile.put(m.owner.file.path, l); + } + l.add(m); + } + List out = new ArrayList(); + for (Map.Entry> e : byFile.entrySet()) { + score(e.getKey(), e.getValue(), out); + } + Collections.sort(out, (a, b) -> b.score != a.score ? b.score - a.score : a.method.id - b.method.id); + return out.size() > MAX_ITEMS ? new ArrayList(out.subList(0, MAX_ITEMS)) : out; + } + + private void score(String path, List methods, List out) { + int[] now = new int[methods.size()]; + List oldLines = new ArrayList(); + for (int i = 0; i < now.length; i++) { + now[i] = methods.get(i).line; + if (methods.get(i).oldLine > 0) { + oldLines.add(methods.get(i).oldLine); + } + } + FlowNode[] after = flows(path, text(path), now); + FlowNode[] before = null; + String old = model.baseText.get(path); + if (old != null && !oldLines.isEmpty()) { + int[] ol = new int[oldLines.size()]; + for (int i = 0; i < ol.length; i++) { + ol[i] = oldLines.get(i); + } + before = flows(path, old, ol); + } + int b = 0; + for (int i = 0; i < methods.size(); i++) { + CodeModel.Method m = methods.get(i); + Item it = new Item(m); + FlowNode was = null; + if (m.oldLine > 0) { + was = before == null ? null : before[b]; + b++; + } + FlowNode is = after == null ? null : after[i]; + if ("A".equals(m.change)) { + newMethod(it, is); + } else { + changedMethod(it, was, is); + } + if (it.score >= MIN_SCORE) { + out.add(it); + } + } + } + + private void newMethod(Item it, FlowNode is) { + CodeModel.Method m = it.method; + it.decisionsAfter = is == null ? Math.max(0, m.complexity - 1) : decisions(is); + for (CodeModel.Method c : m.calls) { + if (c.change == null && c.owner.file != m.owner.file && own(c) && !it.newCalls.contains(label(c))) { + it.newCalls.add(label(c)); + } + } + // Capped: a long new parser is worth a look, but a rewritten existing method changes + // what callers already rely on, and should not be pushed off the list by it. + int logic = it.decisionsAfter >= 3 ? Math.min(it.decisionsAfter, LOGIC_CAP) : 0; + int reach = it.newCalls.size() >= 3 ? Math.min(it.newCalls.size(), REACH_CAP) / 2 : 0; + it.score = logic + reach; + it.kind = "logic"; + it.view = "flow"; + StringBuilder sb = new StringBuilder("New logic with ") + .append(count(it.decisionsAfter, " decision", " decisions")); + if (!it.newCalls.isEmpty()) { + sb.append(", calling existing code: ").append(names(it.newCalls)); + } + it.why = sb.append('.').toString(); + } + + private void changedMethod(Item it, FlowNode was, FlowNode is) { + CodeModel.Method m = it.method; + if (was != null && is != null) { + int[] c = compare(flatten(was), flatten(is)); + it.stepsRemoved = c[0]; + it.stepsAdded = c[1]; + it.decisionsBefore = decisions(was); + it.decisionsAfter = decisions(is); + } + for (CodeModel.Method c : m.calls) { + if (m.isNewCall(c) && own(c) && !it.newCalls.contains(label(c))) { + it.newCalls.add(label(c)); + } + } + // Only the project's own methods: a JDK call dropped is rarely what a reviewer studies. + for (String d : m.droppedCalls()) { + if (!"".equals(d) && projectNames().containsKey(d)) { + it.dropped.add(d + "()"); + } + } + for (CodeModel.Method c : m.callers) { + if (c.change == null && c.owner.file != m.owner.file && !c.owner.file.test + && !it.ripple.contains(label(c))) { + it.ripple.add(label(c)); + } + } + int flow = it.stepsAdded + it.stepsRemoved + 3 * Math.abs(it.decisionsAfter - it.decisionsBefore); + // A dropped call is matched by name alone, so it weighs half what a resolved new one does. + int wiring = 2 * it.newCalls.size() + it.dropped.size(); + int ripple = Math.min(it.ripple.size(), 8); + // A caller elsewhere matters only once the method really does something different. + it.score = flow + wiring + (flow + wiring > 0 ? ripple : 0); + if (flow >= wiring && flow >= ripple) { + it.kind = "flow"; + it.view = "change"; + } else if (wiring >= ripple) { + it.kind = "wiring"; + it.view = "calls"; + } else { + it.kind = "ripple"; + it.view = "calls"; + } + List parts = new ArrayList(); + if (flow > 0) { + StringBuilder sb = new StringBuilder("control flow reworked: ") + .append(count(it.stepsAdded, " step added, ", " steps added, ")).append(it.stepsRemoved) + .append(" removed"); + if (it.decisionsAfter != it.decisionsBefore) { + sb.append(", decisions ").append(it.decisionsBefore).append(" -> ").append(it.decisionsAfter); + } + parts.add(sb.toString()); + } + if (!it.newCalls.isEmpty()) { + parts.add("now calls " + names(it.newCalls)); + } + if (!it.dropped.isEmpty()) { + parts.add("no longer calls " + names(it.dropped)); + } + if (!it.ripple.isEmpty() && flow + wiring > 0) { + parts.add(count(it.ripple.size(), " untouched caller elsewhere runs", " untouched callers elsewhere run") + + " the new code: " + names(it.ripple)); + } + if (parts.isEmpty()) { + it.why = "Edited inside expressions; the steps and calls are the same."; + return; + } + StringBuilder sb = new StringBuilder(); + for (String p : parts) { + sb.append(sb.length() == 0 ? Character.toUpperCase(p.charAt(0)) + p.substring(1) : "; " + p); + } + it.why = sb.append('.').toString(); + } + + private void write(Json.Writer w, Item it) { + CodeModel.Method m = it.method; + String path = m.owner.file.path; + w.beginObject().name("id").value(m.id).name("n").value(m.name).name("on").value(m.owner.name) + .name("sig").value(m.signature()).name("q").value(ChangeQueries.top(m.owner).qualifiedName) + .name("p").value(path).name("ch").value(m.change).name("l").value(m.line).name("e").value(m.endLine) + .name("kind").value(it.kind).name("view").value(it.view).name("score").value(it.score) + .name("k").value(Approvals.key(m)) + .name("h").value(model.approvals == null ? "" : model.approvals.fingerprint(m)) + .name("why").value(it.why).name("sa").value(it.stepsAdded).name("sr").value(it.stepsRemoved) + .name("db").value(it.decisionsBefore).name("da").value(it.decisionsAfter) + .name("cx").value(m.complexity).name("ocx").value(m.oldComplexity); + list(w, "newCalls", it.newCalls); + list(w, "dropped", it.dropped); + list(w, "ripple", it.ripple); + w.name("commits").beginArray(); + if (commits != null) { + String focus = commits.focus(); + for (String sha : commits.in(path, m.line, m.endLine)) { + Commits.Info c = commits.get(sha); + if (c != null && (focus == null || focus.equals(sha))) { + ReviewQueries.ref(w, c); + } + } + } + w.endArray(); + if (commits != null) { + List cs = commits.addedComments(path, commits.docStart(path, m.line), m.endLine); + if (!cs.isEmpty()) { + w.name("comment").value((String) cs.get(0)[1]); + } + } + w.endObject(); + } + + private static void list(Json.Writer w, String name, List values) { + w.name(name).beginArray(); + for (String v : values) { + w.value(v); + } + w.endArray(); + } + + /// Whether `m` is the project's own code rather than the JDK's or a library's. + private static boolean own(CodeModel.Method m) { + return !"".equals(m.name) && m.owner.file != null + && !ChangeQueries.library(m.owner.qualifiedName); + } + + private static String label(CodeModel.Method m) { + return m.owner.name + "." + m.name; + } + + private static String names(List all) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < all.size() && i < NAMES; i++) { + if (i > 0) { + sb.append(", "); + } + sb.append(all.get(i)); + } + if (all.size() > NAMES) { + sb.append(" and ").append(all.size() - NAMES).append(" more"); + } + return sb.toString(); + } + + private Map projectNames() { + if (projectNames == null) { + projectNames = new HashMap(); + for (CodeModel.Method m : model.methods) { + projectNames.put(m.name, Boolean.TRUE); + } + } + return projectNames; + } + + private static String count(int n, String one, String many) { + return n + (n == 1 ? one : many); + } + + private String text(String path) { + String t = current.get(path); + if (t == null) { + try { + t = new String(Files.readAllBytes(new File(model.root, path).toPath()), StandardCharsets.UTF_8); + } catch (IOException e) { + t = ""; + } + current.put(path, t); + } + return t; + } + + private static FlowNode[] flows(String path, String text, int[] lines) { + return text.length() == 0 ? null : SourceOutliner.flows(path, text, lines); + } + + // ------------------------------------------------------------------ step matching + + /// The steps of a chart in reading order, as `ChangeLens` in the app flattens them, so the + /// counts here are the ones the before-and-after chart colours. + static List flatten(FlowNode root) { + List out = new ArrayList(); + walk(root, out); + return out; + } + + private static void walk(FlowNode n, List out) { + for (List b : n.getBranches()) { + for (FlowNode s : b) { + out.add(s); + walk(s, out); + } + } + } + + static int decisions(FlowNode root) { + int n = 0; + for (FlowNode s : flatten(root)) { + String k = s.getKind(); + if ("if".equals(k) || "switch".equals(k) || "loop".equals(k)) { + n++; + } + } + return n; + } + + /// {removed, added}: the steps left over once both sequences are matched by their + /// longest common subsequence of kind and text. + static int[] compare(List was, List now) { + int n = was.size(); + int m = now.size(); + String[] a = new String[n]; + String[] b = new String[m]; + for (int i = 0; i < n; i++) { + a[i] = key(was.get(i)); + } + for (int j = 0; j < m; j++) { + b[j] = key(now.get(j)); + } + int[][] len = new int[n + 1][m + 1]; + for (int i = n - 1; i >= 0; i--) { + for (int j = m - 1; j >= 0; j--) { + len[i][j] = a[i].equals(b[j]) ? len[i + 1][j + 1] + 1 : Math.max(len[i + 1][j], len[i][j + 1]); + } + } + int common = len[0][0]; + return new int[]{n - common, m - common}; + } + + private static String key(FlowNode s) { + return s.getKind() + "|" + s.getLabel().replaceAll("\\s+", " ").trim(); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/History.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/History.java new file mode 100644 index 00000000000..71742db62b9 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/History.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.io.File; +import java.io.IOException; +import java.util.Map; +import java.util.TreeMap; + +/// Line churn per week and module from `git log --numstat`, the material of the +/// "how has this code been changing" chart. +final class History { + private static final long WEEK_SECONDS = 7L * 24 * 3600; + + private History() { + } + + /// The last `weeks` weeks of churn under `root`, oldest week first. + static String churn(File root, int weeks) throws IOException { + weeks = Math.max(1, weeks); + String prefix = Git.run(root, "rev-parse", "--show-prefix").trim(); + String log = Git.run(root, "-c", "core.quotePath=false", "log", "--since=" + weeks + ".weeks", + "--numstat", "--no-renames", "--format=@%ct", "--", "."); + long now = System.currentTimeMillis() / 1000; + // module -> per-week [added, deleted] + Map byModule = new TreeMap(); + int[] commitsPerWeek = new int[weeks]; + int week = -1; + for (String l : Git.lines(log, '\n')) { + if (l.startsWith("@")) { + long t = Long.parseLong(l.substring(1).trim()); + week = weeks - 1 - (int) ((now - t) / WEEK_SECONDS); + if (week >= 0 && week < weeks) { + commitsPerWeek[week]++; + } + continue; + } + String[] parts = l.split("\t"); + if (parts.length < 3 || week < 0 || week >= weeks || "-".equals(parts[0])) { + continue; + } + String path = parts[2].startsWith(prefix) ? parts[2].substring(prefix.length()) : parts[2]; + if (ProjectScanner.languageOf(path) == null) { + continue; + } + String module = ProjectScanner.moduleOf(path); + long[][] series = byModule.get(module.length() == 0 ? "(root)" : module); + if (series == null) { + series = new long[weeks][2]; + byModule.put(module.length() == 0 ? "(root)" : module, series); + } + series[week][0] += Long.parseLong(parts[0]); + series[week][1] += Long.parseLong(parts[1]); + } + StringBuilder sb = new StringBuilder(); + Json.Writer w = new Json.Writer(sb); + w.beginObject(); + w.name("weeks").value(weeks); + w.name("commits").beginArray(); + for (int c : commitsPerWeek) { + w.value(c); + } + w.endArray(); + w.name("modules").beginArray(); + for (Map.Entry e : byModule.entrySet()) { + w.beginObject(); + w.name("n").value(e.getKey()); + w.name("add").beginArray(); + for (long[] wk : e.getValue()) { + w.value(wk[0]); + } + w.endArray(); + w.name("del").beginArray(); + for (long[] wk : e.getValue()) { + w.value(wk[1]); + } + w.endArray(); + w.endObject(); + } + w.endArray(); + w.endObject(); + return sb.toString(); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/Impact.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Impact.java new file mode 100644 index 00000000000..61641429b9f --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Impact.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.util.ArrayDeque; +import java.util.Deque; + +/// Computes how far a branch's changes reach: every method that calls a changed one, +/// directly or through a chain of callers, gets the length of the shortest such chain +/// as its `impact` (0 for a changed method itself). +/// +/// A call through a supertype reaches an override at run time, so a changed method's +/// impact also flows to the callers of every method it overrides. A type's impact is +/// the nearest of its methods'. +final class Impact { + /// Callers further than this are not marked: past a few hops nearly everything is + /// reachable in a framework-sized tree and the mark stops meaning anything. + static final int DEFAULT_DEPTH = 4; + + private Impact() { + } + + static void compute(CodeModel model, int maxDepth) { + Deque queue = new ArrayDeque(); + for (CodeModel.Method m : model.methods) { + if (m.change != null) { + m.impact = 0; + queue.add(m); + } + } + while (!queue.isEmpty()) { + CodeModel.Method m = queue.poll(); + if (m.impact >= maxDepth) { + continue; + } + int next = m.impact + 1; + for (CodeModel.Method caller : m.callers) { + reach(caller, next, queue); + } + for (CodeModel.Method over : m.overrides) { + for (CodeModel.Method caller : over.callers) { + reach(caller, next, queue); + } + } + } + for (CodeModel.Method m : model.methods) { + if (m.impact >= 0 && (m.owner.impact < 0 || m.impact < m.owner.impact)) { + m.owner.impact = m.impact; + } + } + for (CodeModel.Type t : model.types) { + if (t.change != null) { + t.impact = 0; + } + } + } + + private static void reach(CodeModel.Method m, int distance, Deque queue) { + if (m.impact < 0 || distance < m.impact) { + m.impact = distance; + queue.add(m); + } + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/Json.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Json.java new file mode 100644 index 00000000000..431e16e14f1 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Json.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +/// A minimal streaming JSON writer: the module has no dependencies, and the model +/// it writes can be tens of megabytes for a large tree, so it is never built as a +/// tree of maps first. +final class Json { + private Json() { + } + + /// Appends JSON to a `StringBuilder`, inserting commas itself. + static final class Writer { + private final StringBuilder out; + /// Whether the innermost open container already holds a value. + private boolean[] filled = new boolean[32]; + private int depth; + private boolean afterName; + + Writer(StringBuilder out) { + this.out = out; + } + + private void separate() { + if (afterName) { + afterName = false; + return; + } + if (depth > 0) { + if (filled[depth]) { + out.append(','); + } + filled[depth] = true; + } + } + + private void open(char c) { + separate(); + out.append(c); + depth++; + if (depth >= filled.length) { + boolean[] grown = new boolean[filled.length * 2]; + System.arraycopy(filled, 0, grown, 0, filled.length); + filled = grown; + } + filled[depth] = false; + } + + Writer beginObject() { + open('{'); + return this; + } + + Writer endObject() { + depth--; + out.append('}'); + return this; + } + + Writer beginArray() { + open('['); + return this; + } + + Writer endArray() { + depth--; + out.append(']'); + return this; + } + + Writer name(String n) { + separate(); + string(n); + out.append(':'); + afterName = true; + return this; + } + + Writer value(String v) { + separate(); + if (v == null) { + out.append("null"); + } else { + string(v); + } + return this; + } + + Writer value(long v) { + separate(); + out.append(v); + return this; + } + + Writer value(boolean v) { + separate(); + out.append(v); + return this; + } + + private void string(String s) { + out.append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"': + out.append("\\\""); + break; + case '\\': + out.append("\\\\"); + break; + case '\n': + out.append("\\n"); + break; + case '\r': + out.append("\\r"); + break; + case '\t': + out.append("\\t"); + break; + default: + if (c < 0x20 || c > 0x7e) { + // Escaped so the output is ASCII whatever the reader's charset. + String hex = Integer.toHexString(c); + out.append("\\u"); + for (int p = hex.length(); p < 4; p++) { + out.append('0'); + } + out.append(hex); + } else { + out.append(c); + } + } + } + out.append('"'); + } + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/ModelBuilder.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ModelBuilder.java new file mode 100644 index 00000000000..d88778ffd67 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ModelBuilder.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import com.codename1.tools.javac.SourceOutliner; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; + +/// Adds the outline of one Java file to a `CodeModel`. +final class ModelBuilder implements OutlineSink { + private final CodeModel model; + private final CodeModel.SourceFile file; + private final Deque typeStack = new ArrayDeque(); + /// The open method. Anonymous and local classes are never opened as types: their + /// bodies arrive as the enclosing method's own calls. + private CodeModel.Method method; + + private ModelBuilder(CodeModel model, CodeModel.SourceFile file) { + this.model = model; + this.file = file; + } + + /// Outlines `text` into `model` as `file`; false when it could not be parsed. + static boolean add(CodeModel model, CodeModel.SourceFile file, String text) { + return SourceOutliner.outline(file.path, text, new ModelBuilder(model, file)); + } + + @Override + public void packageName(String name) { + file.pkg = name; + } + + @Override + public void importDecl(String name, boolean isStatic, boolean onDemand) { + if (isStatic) { + file.staticImports.add(onDemand ? name + ".*" : name); + } else if (onDemand) { + file.onDemandImports.add(name); + } else { + file.imports.add(name); + } + } + + @Override + public void beginType(String name, String kind, int modifiers, int line, int endLine, String extendsName, + List implementsNames) { + CodeModel.Type outer = typeStack.peek(); + String qn; + if (outer != null) { + qn = outer.qualifiedName + "." + name; + } else { + qn = file.pkg.length() == 0 ? name : file.pkg + "." + name; + } + CodeModel.Type t = new CodeModel.Type(name, qn, kind, modifiers, file, line, endLine, outer, extendsName, + new ArrayList(implementsNames)); + t.id = model.types.size(); + model.types.add(t); + if (!model.typesByName.containsKey(qn)) { + model.typesByName.put(qn, t); + } + file.types.add(t); + if (outer != null) { + outer.nested.add(t); + } + typeStack.push(t); + } + + @Override + public void endType() { + typeStack.pop(); + } + + @Override + public void field(String name, String typeName, int modifiers, int line) { + CodeModel.Type t = typeStack.peek(); + if (t != null) { + t.fields.add(new CodeModel.Field(name, typeName, modifiers, line)); + } + } + + @Override + public void beginMethod(String name, String returnType, List paramTypes, List paramNames, + int modifiers, int line, int endLine) { + CodeModel.Type t = typeStack.peek(); + CodeModel.Method m = new CodeModel.Method(t, name, returnType, new ArrayList(paramTypes), + new ArrayList(paramNames), modifiers, line, endLine); + m.id = model.methods.size(); + model.methods.add(m); + t.methods.add(m); + method = m; + } + + @Override + public void local(String name, String typeName) { + if (method != null && typeName != null && !method.locals.containsKey(name)) { + method.locals.put(name, typeName); + } + } + + @Override + public void call(String receiver, boolean receiverIsCall, String name, int argCount, int line) { + record(new CodeModel.Call(receiver, name, argCount, line, false)); + } + + @Override + public void instantiation(String typeName, int argCount, int line) { + record(new CodeModel.Call(typeName, "", argCount, line, true)); + } + + private void record(CodeModel.Call c) { + if (method != null) { + method.rawCalls.add(c); + } else if (!typeStack.isEmpty()) { + typeStack.peek().initCalls.add(c); + } + } + + @Override + public void endMethod(int complexity) { + if (method != null) { + method.complexity = complexity; + } + method = null; + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/ModelQueries.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ModelQueries.java new file mode 100644 index 00000000000..060267a7063 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ModelQueries.java @@ -0,0 +1,864 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/// Answers the questions a view asks of a `CodeModel`, each as one JSON document sized +/// for what that view shows. `CodeModelCLI serve` puts these behind a line protocol; the +/// whole model, which runs to tens of megabytes for a framework-sized tree, never has to +/// cross the process boundary. +/// +/// Every answer names members by their numeric `id` (the index into the model's method +/// list) and types by both `id` and qualified name, so a follow-up query can take either. +final class ModelQueries { + private static final int SEARCH_LIMIT = 60; + private static final int TOP_LIMIT = 25; + + private static final Comparator> MOST_USED_FIRST = + new Comparator>() { + @Override + public int compare(Map.Entry a, Map.Entry b) { + return b.getValue() - a.getValue(); + } + }; + private static final Comparator NEAREST_IMPACT_FIRST = new Comparator() { + @Override + public int compare(CodeModel.Method a, CodeModel.Method b) { + return a.impact != b.impact ? a.impact - b.impact : b.callers.size() - a.callers.size(); + } + }; + + private final CodeModel model; + private final Map> subtypes = new HashMap>(); + private final Map> dependents = new HashMap>(); + + ModelQueries(CodeModel model) { + this.model = model; + for (CodeModel.Type t : model.types) { + if (t.superType != null) { + listOf(subtypes, t.superType).add(t); + } + for (CodeModel.Type i : t.interfaces) { + listOf(subtypes, i).add(t); + } + for (CodeModel.Type d : t.dependencies) { + Set s = dependents.get(d); + if (s == null) { + s = new LinkedHashSet(); + dependents.put(d, s); + } + s.add(t); + } + } + } + + private static List listOf(Map> m, CodeModel.Type k) { + List l = m.get(k); + if (l == null) { + l = new ArrayList(); + m.put(k, l); + } + return l; + } + + /// Runs one request line, `verb arg...`; the answer is one JSON document, or an + /// object with an `error` member. + String answer(String request) { + String r = request.trim(); + int sp = r.indexOf(' '); + String verb = sp < 0 ? r : r.substring(0, sp); + String arg = sp < 0 ? "" : r.substring(sp + 1).trim(); + StringBuilder sb = new StringBuilder(4096); + Json.Writer w = new Json.Writer(sb); + if ("summary".equals(verb)) { + summary(w); + } else if ("packages".equals(verb)) { + packages(w, arg); + } else if ("package".equals(verb)) { + pkg(w, arg); + } else if ("type".equals(verb)) { + CodeModel.Type t = findType(arg); + if (t == null) { + return error("no type " + arg); + } + type(w, t); + } else if ("method".equals(verb)) { + CodeModel.Method m = findMethod(arg); + if (m == null) { + return error("no method " + arg); + } + method(w, m); + } else if ("callgraph".equals(verb)) { + String[] parts = arg.split("\\s+"); + CodeModel.Method m = findMethod(parts[0]); + if (m == null) { + return error("no method " + parts[0]); + } + int depth = parts.length > 1 ? parseInt(parts[1], 2) : 2; + callGraph(w, m, Math.max(1, Math.min(4, depth))); + } else if ("diff".equals(verb)) { + if (model.git == null) { + return error("the model was indexed without a base revision"); + } + diff(w); + } else if ("impactflow".equals(verb)) { + if (model.git == null) { + return error("the model was indexed without a base revision"); + } + impactFlow(w); + } else if ("search".equals(verb)) { + search(w, arg); + } else if ("changegraph".equals(verb)) { + new ChangeQueries(model).changeGraph(w, arg); + } else if ("outline".equals(verb)) { + return new ChangeQueries(model).outline(arg); + } else if ("edgecalls".equals(verb)) { + String[] ft = arg.split("\\s+"); + if (ft.length != 2) { + return error("usage: edgecalls FROM TO"); + } + new ChangeQueries(model).edgeCalls(w, ft[0], ft[1]); + } else { + return error("unknown request " + verb); + } + return sb.toString(); + } + + static String error(String message) { + StringBuilder sb = new StringBuilder(); + new Json.Writer(sb).beginObject().name("error").value(message).endObject(); + return sb.toString(); + } + + private static int parseInt(String s, int def) { + try { + return Integer.parseInt(s.trim()); + } catch (NumberFormatException e) { + return def; + } + } + + // ------------------------------------------------------------------ lookup + + /// A type by qualified name, numeric id, or unique simple name. + CodeModel.Type findType(String key) { + CodeModel.Type t = model.typesByName.get(key); + if (t != null) { + return t; + } + int id = parseInt(key, -1); + if (id >= 0 && id < model.types.size() && key.trim().matches("\\d+")) { + return model.types.get(id); + } + CodeModel.Type found = null; + for (CodeModel.Type c : model.types) { + if (c.name.equals(key)) { + if (found != null) { + return null; + } + found = c; + } + } + return found; + } + + /// A method by numeric id, or `Type#name` (the first declaration of that name). + CodeModel.Method findMethod(String key) { + String k = key.trim(); + if (k.matches("\\d+")) { + int id = Integer.parseInt(k); + return id < model.methods.size() ? model.methods.get(id) : null; + } + int hash = k.indexOf('#'); + if (hash <= 0) { + return null; + } + CodeModel.Type t = findType(k.substring(0, hash)); + if (t == null) { + return null; + } + String name = k.substring(hash + 1); + int paren = name.indexOf('('); + for (CodeModel.Method m : t.methods) { + if (paren < 0 ? m.name.equals(name) : m.signature().equals(name)) { + return m; + } + } + return null; + } + + // ------------------------------------------------------------------ writers + + private static String pkgOf(CodeModel.Type t) { + return t.file.pkg.length() == 0 ? "(default)" : t.file.pkg; + } + + private void typeRef(Json.Writer w, CodeModel.Type t) { + w.beginObject(); + w.name("id").value(t.id); + w.name("n").value(t.name); + w.name("q").value(t.qualifiedName); + w.name("k").value(t.kind); + if (t.change != null) { + w.name("ch").value(t.change); + } + if (t.impact >= 0) { + w.name("imp").value(t.impact); + } + w.endObject(); + } + + private void methodRef(Json.Writer w, CodeModel.Method m) { + w.beginObject(); + w.name("id").value(m.id); + w.name("n").value(m.name); + w.name("sig").value(m.signature()); + w.name("o").value(m.owner.id); + w.name("on").value(m.owner.name); + w.name("oq").value(m.owner.qualifiedName); + w.name("p").value(m.owner.file.path); + w.name("mod").value(m.owner.file.module); + w.name("l").value(m.line); + w.name("e").value(m.endLine); + w.name("cx").value(m.complexity); + w.name("m").value(m.modifiers); + if (m.returnType != null) { + w.name("r").value(m.returnType); + } + if (m.change != null) { + w.name("ch").value(m.change); + if (model.approvals != null) { + w.name("k").value(Approvals.key(m)); + w.name("h").value(model.approvals.fingerprint(m)); + } + } + if (m.impact >= 0) { + w.name("imp").value(m.impact); + } + w.endObject(); + } + + private static int typeLines(CodeModel.Type t) { + return Math.max(1, t.endLine - t.line + 1); + } + + private void summary(Json.Writer w) { + Map languages = new TreeMap(); + Map modules = new TreeMap(); + int sloc = 0; + int tests = 0; + for (CodeModel.SourceFile f : model.files) { + sloc += f.codeLines; + if (f.test) { + tests += f.codeLines; + } + add(languages, f.language, f); + add(modules, f.module.length() == 0 ? "(root)" : f.module, f); + } + w.beginObject(); + w.name("root").value(model.root); + w.name("layout").value(model.layout); + w.name("files").value(model.files.size()); + w.name("types").value(model.types.size()); + w.name("methods").value(model.methods.size()); + w.name("natives").value(model.natives.size()); + w.name("sloc").value(sloc); + w.name("testSloc").value(tests); + breakdown(w, "languages", languages); + breakdown(w, "modules", modules); + int[] cx = new int[6]; + for (CodeModel.Method m : model.methods) { + cx[m.complexity <= 1 ? 0 : m.complexity <= 3 ? 1 : m.complexity <= 6 ? 2 : m.complexity <= 10 ? 3 + : m.complexity <= 20 ? 4 : 5]++; + } + w.name("complexity").beginArray(); + for (int c : cx) { + w.value(c); + } + w.endArray(); + if (model.git != null) { + w.name("git").beginObject(); + w.name("base").value(model.git.base); + w.name("branch").value(model.git.branch); + w.name("mergeBase").value(model.git.mergeBase); + w.name("commits").value(model.git.commits.size()); + int added = 0; + int deleted = 0; + int files = 0; + for (CodeModel.SourceFile f : model.files) { + if (f.change != null) { + files++; + added += f.added; + deleted += f.deleted; + } + } + w.name("changedFiles").value(files); + w.name("added").value(added); + w.name("deleted").value(deleted); + w.name("removed").value(model.removed.size()); + w.endObject(); + } + w.endObject(); + } + + private static void add(Map m, String key, CodeModel.SourceFile f) { + int[] v = m.get(key); + if (v == null) { + v = new int[4]; + m.put(key, v); + } + v[0]++; + v[1] += f.codeLines; + if (f.change != null) { + v[2] += f.added; + v[3] += f.deleted; + } + } + + private static void breakdown(Json.Writer w, String name, Map m) { + List> entries = new ArrayList>(m.entrySet()); + Collections.sort(entries, new Comparator>() { + @Override + public int compare(Map.Entry a, Map.Entry b) { + return b.getValue()[1] - a.getValue()[1]; + } + }); + w.name(name).beginArray(); + for (Map.Entry e : entries) { + int[] v = e.getValue(); + w.beginObject(); + w.name("n").value(e.getKey()); + w.name("files").value(v[0]); + w.name("sloc").value(v[1]); + if (v[2] + v[3] > 0) { + w.name("add").value(v[2]); + w.name("del").value(v[3]); + } + w.endObject(); + } + w.endArray(); + } + + /// Every package (optionally only those of one module), with size, change counts, + /// and the dependencies between packages weighted by the type edges behind them. + private void packages(Json.Writer w, String module) { + Map stats = new TreeMap(); + Map moduleOf = new HashMap(); + Map edges = new LinkedHashMap(); + for (CodeModel.Type t : model.types) { + if (module.length() > 0 && !module.equals(t.file.module)) { + continue; + } + String p = pkgOf(t); + moduleOf.put(p, t.file.module); + int[] s = stats.get(p); + if (s == null) { + s = new int[]{0, 0, 0, 0, Integer.MAX_VALUE}; + stats.put(p, s); + } + s[0]++; + if (t.outer == null) { + s[1] += typeLines(t); + } + if ("A".equals(t.change)) { + s[2]++; + } else if ("M".equals(t.change)) { + s[3]++; + } + if (t.impact >= 0) { + s[4] = Math.min(s[4], t.impact); + } + for (CodeModel.Type d : t.dependencies) { + String dp = pkgOf(d); + if (!dp.equals(p) && (module.length() == 0 || module.equals(d.file.module))) { + String key = p + "\n" + dp; + Integer c = edges.get(key); + edges.put(key, c == null ? 1 : c + 1); + } + } + } + w.beginObject(); + w.name("packages").beginArray(); + for (Map.Entry e : stats.entrySet()) { + int[] s = e.getValue(); + w.beginObject(); + w.name("n").value(e.getKey()); + w.name("mod").value(moduleOf.get(e.getKey())); + w.name("types").value(s[0]); + w.name("lines").value(s[1]); + if (s[2] > 0) { + w.name("added").value(s[2]); + } + if (s[3] > 0) { + w.name("modified").value(s[3]); + } + if (s[4] != Integer.MAX_VALUE) { + w.name("imp").value(s[4]); + } + w.endObject(); + } + w.endArray(); + w.name("edges").beginArray(); + for (Map.Entry e : edges.entrySet()) { + int nl = e.getKey().indexOf('\n'); + if (stats.containsKey(e.getKey().substring(nl + 1))) { + w.beginArray().value(e.getKey().substring(0, nl)).value(e.getKey().substring(nl + 1)) + .value(e.getValue()).endArray(); + } + } + w.endArray(); + w.endObject(); + } + + /// The top-level and nested types of one package, the edges among them, and the + /// types outside the package they lean on. + private void pkg(Json.Writer w, String pkgName) { + List in = new ArrayList(); + for (CodeModel.Type t : model.types) { + if (pkgOf(t).equals(pkgName)) { + in.add(t); + } + } + Set inside = new LinkedHashSet(in); + w.beginObject(); + w.name("n").value(pkgName); + w.name("types").beginArray(); + for (CodeModel.Type t : in) { + w.beginObject(); + w.name("id").value(t.id); + w.name("n").value(t.outer == null ? t.name + : pkgName.length() == 0 ? t.qualifiedName : t.qualifiedName.substring(pkgName.length() + 1)); + w.name("q").value(t.qualifiedName); + w.name("k").value(t.kind); + w.name("m").value(t.modifiers); + w.name("p").value(t.file.path); + w.name("l").value(t.line); + w.name("e").value(t.endLine); + w.name("lines").value(typeLines(t)); + w.name("methods").value(t.methods.size()); + w.name("fields").value(t.fields.size()); + if (t.outer != null) { + w.name("o").value(t.outer.id); + } + if (t.change != null) { + w.name("ch").value(t.change); + } + if (t.impact >= 0) { + w.name("imp").value(t.impact); + } + w.endObject(); + } + w.endArray(); + w.name("edges").beginArray(); + Map outside = new LinkedHashMap(); + for (CodeModel.Type t : in) { + for (CodeModel.Type d : t.dependencies) { + if (inside.contains(d)) { + String kind = d == t.superType ? "extends" : t.interfaces.contains(d) ? "implements" : "uses"; + w.beginArray().value(t.id).value(d.id).value(kind).endArray(); + } else { + Integer c = outside.get(d); + outside.put(d, c == null ? 1 : c + 1); + } + } + } + w.endArray(); + w.name("external").beginArray(); + List> ext = new ArrayList>( + outside.entrySet()); + Collections.sort(ext, MOST_USED_FIRST); + for (int i = 0; i < ext.size() && i < TOP_LIMIT; i++) { + typeRef(w, ext.get(i).getKey()); + } + w.endArray(); + w.endObject(); + } + + /// Everything a UML box and its neighbourhood need. + private void type(Json.Writer w, CodeModel.Type t) { + w.beginObject(); + w.name("id").value(t.id); + w.name("n").value(t.name); + w.name("q").value(t.qualifiedName); + w.name("k").value(t.kind); + w.name("m").value(t.modifiers); + w.name("pkg").value(pkgOf(t)); + w.name("p").value(t.file.path); + w.name("l").value(t.line); + w.name("e").value(t.endLine); + if (t.change != null) { + w.name("ch").value(t.change); + } + if (t.impact >= 0) { + w.name("imp").value(t.impact); + } + if (t.outer != null) { + w.name("outer"); + typeRef(w, t.outer); + } + w.name("supers").beginArray(); + Set seen = new LinkedHashSet(); + for (CodeModel.Type s = t.superType; s != null && seen.add(s); s = s.superType) { + typeRef(w, s); + } + w.endArray(); + if (t.superType == null && t.extendsName != null) { + w.name("extExtends").value(t.extendsName); + } + w.name("interfaces").beginArray(); + for (CodeModel.Type i : t.interfaces) { + typeRef(w, i); + } + w.endArray(); + w.name("extImplements").beginArray(); + for (String i : t.implementsNames) { + boolean resolved = false; + for (CodeModel.Type r : t.interfaces) { + if (i.equals(r.name) || i.equals(r.qualifiedName) || i.endsWith("." + r.name)) { + resolved = true; + } + } + if (!resolved) { + w.value(i); + } + } + w.endArray(); + w.name("subtypes").beginArray(); + List subs = subtypes.get(t); + if (subs != null) { + for (CodeModel.Type s : subs) { + typeRef(w, s); + } + } + w.endArray(); + w.name("nested").beginArray(); + for (CodeModel.Type n : t.nested) { + typeRef(w, n); + } + w.endArray(); + w.name("fields").beginArray(); + for (CodeModel.Field f : t.fields) { + w.beginObject(); + w.name("n").value(f.name); + w.name("t").value(f.typeName); + w.name("m").value(f.modifiers); + w.name("l").value(f.line); + if (f.resolved != null) { + w.name("ti").value(f.resolved.id); + } + w.endObject(); + } + w.endArray(); + w.name("methods").beginArray(); + for (CodeModel.Method m : t.methods) { + methodRef(w, m); + } + w.endArray(); + w.name("dependencies").beginArray(); + for (CodeModel.Type d : t.dependencies) { + typeRef(w, d); + } + w.endArray(); + w.name("dependents").beginArray(); + Set deps = dependents.get(t); + if (deps != null) { + for (CodeModel.Type d : deps) { + typeRef(w, d); + } + } + w.endArray(); + w.endObject(); + } + + private void method(Json.Writer w, CodeModel.Method m) { + w.beginObject(); + w.name("method"); + methodRef(w, m); + w.name("params").beginArray(); + for (int i = 0; i < m.paramTypes.size(); i++) { + w.beginObject().name("t").value(m.paramTypes.get(i)).name("n").value(m.paramNames.get(i)).endObject(); + } + w.endArray(); + w.name("callers").beginArray(); + for (CodeModel.Method c : m.callers) { + methodRef(w, c); + } + w.endArray(); + w.name("callees").beginArray(); + for (CodeModel.Method c : m.calls) { + methodRef(w, c); + } + w.endArray(); + // Parallel to callees: the line in this method where each callee is first called. + w.name("calledAt").beginArray(); + for (CodeModel.Method c : m.calls) { + Integer at = m.callLines.get(c); + w.value(at == null ? m.line : at); + } + w.endArray(); + // Parallel to callees: whether the branch introduced the call. + w.name("newCall").beginArray(); + for (CodeModel.Method c : m.calls) { + w.value(m.isNewCall(c)); + } + w.endArray(); + w.name("dropped").beginArray(); + for (String d : m.droppedCalls()) { + w.value(d); + } + w.endArray(); + w.name("overrides").beginArray(); + for (CodeModel.Method o : m.overrides) { + methodRef(w, o); + } + w.endArray(); + w.name("overriddenBy").beginArray(); + for (CodeModel.Method o : model.methods) { + if (o.overrides.contains(m)) { + methodRef(w, o); + } + } + w.endArray(); + w.name("natives").beginArray(); + for (CodeModel.NativeFunction n : model.natives) { + if (n.javaMethod == m) { + w.beginObject().name("n").value(n.name).name("p").value(n.file.path).name("l").value(n.line) + .name("e").value(n.endLine).endObject(); + } + } + w.endArray(); + w.endObject(); + } + + /// The methods within `depth` calls of `m`, in both directions, and the call edges + /// among them. + private void callGraph(Json.Writer w, CodeModel.Method root, int depth) { + Map level = new LinkedHashMap(); + level.put(root, 0); + List frontier = new ArrayList(); + frontier.add(root); + for (int d = 1; d <= depth && !frontier.isEmpty(); d++) { + List next = new ArrayList(); + for (CodeModel.Method m : frontier) { + int side = level.get(m); + if (side >= 0) { + for (CodeModel.Method c : m.calls) { + if (!level.containsKey(c) && level.size() < 400) { + level.put(c, d); + next.add(c); + } + } + } + if (side <= 0) { + for (CodeModel.Method c : m.callers) { + if (!level.containsKey(c) && level.size() < 400) { + level.put(c, -d); + next.add(c); + } + } + } + } + frontier = next; + } + w.beginObject(); + w.name("root").value(root.id); + w.name("nodes").beginArray(); + for (Map.Entry e : level.entrySet()) { + methodRef(w, e.getKey()); + } + w.endArray(); + w.name("levels").beginArray(); + for (Integer v : level.values()) { + w.value(v); + } + w.endArray(); + w.name("edges").beginArray(); + for (CodeModel.Method m : level.keySet()) { + for (CodeModel.Method c : m.calls) { + if (level.containsKey(c)) { + w.beginArray().value(m.id).value(c.id).endArray(); + } + } + } + w.endArray(); + w.endObject(); + } + + private void diff(Json.Writer w) { + w.beginObject(); + w.name("base").value(model.git.base); + w.name("branch").value(model.git.branch); + w.name("commits").beginArray(); + for (String c : model.git.commits) { + w.value(c); + } + w.endArray(); + w.name("files").beginArray(); + for (CodeModel.SourceFile f : model.files) { + if (f.change != null) { + w.beginObject(); + w.name("p").value(f.path); + w.name("lang").value(f.language); + w.name("mod").value(f.module); + w.name("ch").value(f.change); + w.name("add").value(f.added); + w.name("del").value(f.deleted); + if (model.approvals != null && !"D".equals(f.change)) { + w.name("k").value(Approvals.key(f)); + w.name("h").value(model.approvals.fingerprint(f)); + } + w.name("rg").beginArray(); + for (int[] r : f.changedRanges) { + w.beginArray().value(r[0]).value(r[1]).endArray(); + } + w.endArray(); + w.endObject(); + } + } + w.endArray(); + w.name("types").beginArray(); + for (CodeModel.Type t : model.types) { + if (t.change != null) { + typeRef(w, t); + } + } + w.endArray(); + w.name("methods").beginArray(); + for (CodeModel.Method m : model.methods) { + if (m.change != null) { + methodRef(w, m); + } + } + w.endArray(); + int[] rings = new int[Impact.DEFAULT_DEPTH + 2]; + List reached = new ArrayList(); + for (CodeModel.Method m : model.methods) { + if (m.impact >= 0) { + rings[Math.min(rings.length - 1, m.impact)]++; + if (m.impact > 0) { + reached.add(m); + } + } + } + w.name("impactRings").beginArray(); + for (int r : rings) { + w.value(r); + } + w.endArray(); + Collections.sort(reached, NEAREST_IMPACT_FIRST); + w.name("impacted").beginArray(); + for (int i = 0; i < reached.size() && i < 200; i++) { + methodRef(w, reached.get(i)); + } + w.endArray(); + w.name("removed").beginArray(); + for (CodeModel.Removed r : model.removed) { + w.beginObject().name("k").value(r.kind).name("o").value(r.owner).name("s").value(r.signature) + .name("p").value(r.path).name("l").value(r.line).endObject(); + } + w.endArray(); + w.name("natives").beginArray(); + for (CodeModel.NativeFunction n : model.natives) { + if (n.change != null) { + w.beginObject().name("n").value(n.name).name("p").value(n.file.path).name("l").value(n.line) + .name("ch").value(n.change).endObject(); + } + } + w.endArray(); + w.endObject(); + } + + /// Direct calls from unchanged code into changed methods, counted per pair of modules: + /// `{"links": [[callerModule, changedModule, calls], ...]}`, most calls first. + private void impactFlow(Json.Writer w) { + Map counts = new HashMap(); + for (CodeModel.Method m : model.methods) { + if (m.change == null) { + continue; + } + for (CodeModel.Method c : m.callers) { + if (c.change == null) { + String key = c.owner.file.module + "\n" + m.owner.file.module; + Integer n = counts.get(key); + counts.put(key, n == null ? 1 : n + 1); + } + } + } + List> links = new ArrayList>(counts.entrySet()); + Collections.sort(links, (a, b) -> b.getValue().compareTo(a.getValue())); + w.beginObject(); + w.name("links").beginArray(); + for (Map.Entry e : links) { + int nl = e.getKey().indexOf('\n'); + w.beginArray().value(e.getKey().substring(0, nl)).value(e.getKey().substring(nl + 1)) + .value(e.getValue()).endArray(); + } + w.endArray(); + w.endObject(); + } + + private void search(Json.Writer w, String text) { + String needle = asciiLower(text); + w.beginObject(); + w.name("types").beginArray(); + int n = 0; + for (CodeModel.Type t : model.types) { + if (n < SEARCH_LIMIT && asciiLower(t.qualifiedName).contains(needle)) { + typeRef(w, t); + n++; + } + } + w.endArray(); + w.name("methods").beginArray(); + n = 0; + for (CodeModel.Method m : model.methods) { + if (n < SEARCH_LIMIT && asciiLower(m.name).contains(needle)) { + methodRef(w, m); + n++; + } + } + w.endArray(); + w.endObject(); + } + + /// Lower case for identifiers: folded by hand because `String.toLowerCase` depends on + /// the default locale. + static String asciiLower(String s) { + StringBuilder sb = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + sb.append(c >= 'A' && c <= 'Z' ? (char) (c + ('a' - 'A')) : c); + } + return sb.toString(); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/NativeIndexer.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/NativeIndexer.java new file mode 100644 index 00000000000..16430e1a8c2 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/NativeIndexer.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.util.HashMap; +import java.util.Map; + +/// Finds function definitions in C, C++ and Objective-C sources, and links each one +/// whose name is a ParparVM native name to the Java `native` method it implements. +/// +/// ParparVM spells a native `pkg_Class_method__args_R_ret` +/// (`com_codename1_impl_ios_IOSNative_isBiometricsSupported___R_boolean`): the part +/// before the `__` that opens the argument list is the owner's qualified name and the +/// method name joined by `_`. That prefix is all the link needs; checking the rest is +/// `NativeSignatureVerifier`'s job. +/// +/// This is a scanner, not a parser: a definition is a name and a parenthesised list +/// followed by a `{` at file level (or an Objective-C method line), with comments and +/// literals skipped. It finds what a reviewer navigates to and nothing more. +final class NativeIndexer { + private static final int ACC_NATIVE = 0x0100; + + private NativeIndexer() { + } + + static boolean handles(String language) { + return "c".equals(language) || "cpp".equals(language) || "objc".equals(language); + } + + static void add(CodeModel model, CodeModel.SourceFile file, String text) { + int n = text.length(); + int depth = 0; + int line = 1; + // Start of the current top-level declaration, as a candidate header. + StringBuilder header = new StringBuilder(); + int headerLine = 1; + int openLine = 0; + String openName = null; + int i = 0; + while (i < n) { + char c = text.charAt(i); + if (c == '\n') { + line++; + if (depth == 0) { + header.append(' '); + } + i++; + continue; + } + if (c == '/' && i + 1 < n && text.charAt(i + 1) == '/') { + while (i < n && text.charAt(i) != '\n') { + i++; + } + continue; + } + if (c == '/' && i + 1 < n && text.charAt(i + 1) == '*') { + int close = text.indexOf("*/", i + 2); + int stop = close < 0 ? n : close + 2; + for (int k = i; k < stop; k++) { + if (text.charAt(k) == '\n') { + line++; + } + } + i = stop; + continue; + } + if (c == '"' || c == '\'') { + int k = i + 1; + while (k < n && text.charAt(k) != c && text.charAt(k) != '\n') { + k += text.charAt(k) == '\\' ? 2 : 1; + } + i = Math.min(n, k + 1); + continue; + } + if (depth == 0 && (c == '#' || c == '@' && header.toString().trim().length() == 0)) { + // A preprocessor line, or an Objective-C directive line (@implementation, + // @end), is never part of a definition's header. + while (i < n && text.charAt(i) != '\n') { + i++; + } + header.setLength(0); + continue; + } + if (c == '{') { + if (depth == 0) { + openName = definitionName(header.toString()); + openLine = headerLine; + } + depth++; + } else if (c == '}') { + depth = Math.max(0, depth - 1); + if (depth == 0) { + if (openName != null) { + model.natives.add(new CodeModel.NativeFunction(openName, file, openLine, line)); + } + openName = null; + header.setLength(0); + } + } else if (depth == 0) { + if (c == ';') { + header.setLength(0); + } else { + if (header.toString().trim().length() == 0 && !Character.isWhitespace(c)) { + headerLine = line; + header.setLength(0); + } + header.append(c); + } + } + i++; + } + } + + /// The function or method a header such as `static int foo(int a)` or + /// `- (void)viewDidLoad` defines, or null for a struct, enum, block or `@implementation`. + static String definitionName(String header) { + String h = header.trim(); + if (h.length() == 0) { + return null; + } + if (h.startsWith("-") || h.startsWith("+")) { + int close = h.indexOf(')'); + String rest = close < 0 ? h.substring(1) : h.substring(close + 1); + StringBuilder sel = new StringBuilder(); + for (String part : rest.trim().split("\\s+")) { + int colon = part.indexOf(':'); + if (colon >= 0) { + sel.append(part, 0, colon + 1); + } else if (sel.length() == 0) { + sel.append(part); + break; + } + } + return sel.length() == 0 ? null : h.charAt(0) + sel.toString(); + } + int paren = h.indexOf('('); + if (paren <= 0 || h.startsWith("@") || h.contains("=")) { + return null; + } + int end = paren; + while (end > 0 && Character.isWhitespace(h.charAt(end - 1))) { + end--; + } + int start = end; + while (start > 0 && (Character.isLetterOrDigit(h.charAt(start - 1)) || h.charAt(start - 1) == '_' + || h.charAt(start - 1) == ':')) { + start--; + } + if (start == end) { + return null; + } + String name = h.substring(start, end); + if ("if".equals(name) || "while".equals(name) || "for".equals(name) || "switch".equals(name) + || "sizeof".equals(name)) { + return null; + } + return name; + } + + /// Links ParparVM-named natives to their Java methods. + static void linkToJava(CodeModel model) { + Map javaNatives = new HashMap(); + for (CodeModel.Method m : model.methods) { + if ((m.modifiers & ACC_NATIVE) != 0) { + javaNatives.put(m.owner.qualifiedName.replace('.', '_') + "_" + m.name, m); + } + } + if (javaNatives.isEmpty()) { + return; + } + for (CodeModel.NativeFunction f : model.natives) { + int args = f.name.indexOf("__"); + if (args > 0) { + f.javaMethod = javaNatives.get(f.name.substring(0, args)); + } + } + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/OutlineSink.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/OutlineSink.java new file mode 100644 index 00000000000..1b988c087e0 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/OutlineSink.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.util.List; + +/// Receives the outline of one Java source file, declaration by declaration, from +/// the parser bridge (`com.codename1.tools.javac.SourceOutliner`). +/// +/// Calls nest: `beginType`/`endType` bracket the members of a type (a nested type +/// opens inside its outer one), and `beginMethod`/`endMethod` bracket what a body +/// declares and calls. Lines are 1 based. Type names are as written in the source +/// (`List` arrives as `List`, `a.b.C` as `a.b.C`); resolving them is the +/// model's job. +public interface OutlineSink { + /// The file's package, empty for the default package. + void packageName(String name); + + /// One import: `name` is the dotted name without `.*`. + void importDecl(String name, boolean isStatic, boolean onDemand); + + /// Opens a type. `kind` is `class`, `interface`, `enum`, `record` or `annotation`. + void beginType(String name, String kind, int modifiers, int line, int endLine, + String extendsName, List implementsNames); + + /// Closes the innermost open type. + void endType(); + + /// A field of the innermost open type. + void field(String name, String typeName, int modifiers, int line); + + /// Opens a method or constructor (`returnType` is null for a constructor). + void beginMethod(String name, String returnType, List paramTypes, List paramNames, + int modifiers, int line, int endLine); + + /// A local variable, parameter or pattern binding of the open method. + void local(String name, String typeName); + + /// A call made by the open method (or by the initializer of the open type when no + /// method is open). `receiver` is the qualifier as written: null for an + /// unqualified call, `this`, `super`, a name such as `list` or `Display`, or a + /// chain such as `a.b`, `Display.getInstance()`, `new T` or `(T)` that the model + /// types step by step; `?` when the qualifier is an expression it cannot follow. + /// `receiverIsCall` says whether the last step of the chain was itself a call. + void call(String receiver, boolean receiverIsCall, String name, int argCount, int line); + + /// An instance creation (`new T(...)`), which is a call of `T`'s constructor. + void instantiation(String typeName, int argCount, int line); + + /// Closes the open method; `complexity` is its cyclomatic complexity. + void endMethod(int complexity); +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/Progress.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Progress.java new file mode 100644 index 00000000000..dc596b0be0c --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Progress.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +/// Told what indexing is doing, so a user interface can show more than a blank screen. +public interface Progress { + /// The current phase; `total` is 0 when the phase has no count. + void progress(String phase, int done, int total); +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/ProjectScanner.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ProjectScanner.java new file mode 100644 index 00000000000..fa6e798a89b --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ProjectScanner.java @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Finds the source files of a tree and builds a `CodeModel` from them. +/// +/// It recognises two layouts by their marker directories and names each file's +/// module from its path, so a chart can group by it: +/// +/// - **cn1-app**: a Codename One application (`common/src/main/java`, `ios/...`). +/// - **cn1-repo**: the Codename One framework tree (`CodenameOne/src`, `Ports/*`). +/// +/// Anything else is **generic**, and is indexed all the same. +public final class ProjectScanner { + private static final Map LANGUAGES = new HashMap(); + private static final Set SKIPPED_DIRS = new HashSet(Arrays.asList( + "target", "build", "node_modules", ".m2-repo", "dist", "out", "bin", "DerivedData", "Pods", + "cn1-binaries", "__pycache__")); + private static final long MAX_FILE_BYTES = 4L * 1024 * 1024; + + static { + LANGUAGES.put("java", "java"); + LANGUAGES.put("kt", "kotlin"); + LANGUAGES.put("m", "objc"); + LANGUAGES.put("mm", "objc"); + LANGUAGES.put("h", "c"); + LANGUAGES.put("c", "c"); + LANGUAGES.put("cpp", "cpp"); + LANGUAGES.put("cc", "cpp"); + LANGUAGES.put("cxx", "cpp"); + LANGUAGES.put("hpp", "cpp"); + LANGUAGES.put("swift", "swift"); + LANGUAGES.put("cs", "csharp"); + LANGUAGES.put("js", "javascript"); + LANGUAGES.put("py", "python"); + LANGUAGES.put("css", "css"); + } + + private final File root; + private final List excludes = new ArrayList(); + private boolean includeTests = true; + private Progress progress; + + /// A scanner for the tree under `root`. + public ProjectScanner(File root) { + this.root = root.getAbsoluteFile(); + } + + /// Skips every path starting with `prefix` (relative to the root, `/` separated). + public ProjectScanner exclude(String prefix) { + excludes.add(prefix); + return this; + } + + /// Whether test sources are indexed (they are by default, and flagged). + public ProjectScanner includeTests(boolean include) { + this.includeTests = include; + return this; + } + + /// Reports progress while `scan` runs. + public ProjectScanner progress(Progress listener) { + this.progress = listener; + return this; + } + + /// Indexes the tree. + public CodeModel scan() throws IOException { + CodeModel model = new CodeModel(root.getPath()); + model.layout = detectLayout(root); + List found = gitFiles(); + if (found == null) { + found = new ArrayList(); + walk(root, "", found); + } + int done = 0; + for (File f : found) { + if (progress != null && done++ % 50 == 0) { + progress.progress("Reading sources", done, found.size()); + } + String rel = relative(f); + String lang = languageOf(f.getName()); + String text; + try { + text = new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8); + } catch (java.nio.file.NoSuchFileException gone) { + // An untracked file deleted since the listing, such as a regenerated source. + continue; + } + CodeModel.SourceFile sf = model.addFile(rel, lang); + sf.module = moduleOf(rel); + sf.test = isTest(rel); + countLines(sf, text); + if ("java".equals(lang)) { + ModelBuilder.add(model, sf, text); + } else if (NativeIndexer.handles(lang)) { + NativeIndexer.add(model, sf, text); + } + } + if (progress != null) { + progress.progress("Resolving types and calls", found.size(), found.size()); + } + new Resolver(model).resolve(); + NativeIndexer.linkToJava(model); + return model; + } + + /// Inside a git work tree, the files git tracks plus the untracked ones it does not + /// ignore, so generated output under `.gitignore` is never indexed; null outside one. + private List gitFiles() { + List paths; + try { + paths = Git.lines(Git.run(root, "-c", "core.quotePath=false", "ls-files", "-z", "--cached", "--others", "--exclude-standard", + "--", "."), '\0'); + } catch (IOException e) { + return null; + } + List out = new ArrayList(); + Set seen = new HashSet(); + for (String p : paths) { + if (!seen.add(p) || isExcluded(p) || languageOf(p) == null || !includeTests && isTest(p)) { + continue; + } + boolean hidden = false; + for (String seg : p.split("/")) { + if (seg.startsWith(".") || SKIPPED_DIRS.contains(seg)) { + hidden = true; + break; + } + } + File f = new File(root, p); + if (!hidden && f.isFile() && f.length() <= MAX_FILE_BYTES) { + out.add(f); + } + } + java.util.Collections.sort(out); + return out; + } + + static String detectLayout(File root) { + if (new File(root, "CodenameOne/src").isDirectory() && new File(root, "Ports").isDirectory()) { + return "cn1-repo"; + } + if (new File(root, "common/src/main").isDirectory()) { + return "cn1-app"; + } + return "generic"; + } + + private void walk(File dir, String rel, List out) { + File[] children = dir.listFiles(); + if (children == null) { + return; + } + Arrays.sort(children); + for (File c : children) { + String name = c.getName(); + String path = rel.length() == 0 ? name : rel + "/" + name; + if (isExcluded(path)) { + continue; + } + if (c.isDirectory()) { + // A linked directory can point back up the tree; git does not follow them either. + if (name.startsWith(".") || SKIPPED_DIRS.contains(name) || Files.isSymbolicLink(c.toPath())) { + continue; + } + walk(c, path, out); + } else if (languageOf(name) != null && c.length() <= MAX_FILE_BYTES + && (includeTests || !isTest(path))) { + out.add(c); + } + } + } + + private boolean isExcluded(String path) { + for (String e : excludes) { + if (path.startsWith(e)) { + return true; + } + } + return false; + } + + private String relative(File f) { + String r = root.toURI().relativize(f.toURI()).getPath(); + return r.endsWith("/") ? r.substring(0, r.length() - 1) : r; + } + + static String languageOf(String fileName) { + int dot = fileName.lastIndexOf('.'); + return dot < 0 ? null : LANGUAGES.get(fileName.substring(dot + 1)); + } + + /// The path up to its `src` directory (`maven/core`, `Ports/Android`, `common`), + /// else its first directory. + static String moduleOf(String path) { + String[] parts = path.split("/"); + for (int i = 1; i < parts.length - 1; i++) { + if ("src".equals(parts[i])) { + StringBuilder sb = new StringBuilder(parts[0]); + for (int k = 1; k < i; k++) { + sb.append('/').append(parts[k]); + } + return sb.toString(); + } + } + return parts.length > 1 ? parts[0] : ""; + } + + static boolean isTest(String path) { + return path.contains("/src/test/") || path.startsWith("test/") || path.contains("/test/") + || path.contains("/tests/"); + } + + /// Counts lines, and lines that hold code rather than only blanks or comments. + static void countLines(CodeModel.SourceFile sf, String text) { + int lines = 0; + int code = 0; + boolean inBlock = false; + int start = 0; + int n = text.length(); + while (start <= n) { + int end = text.indexOf('\n', start); + if (end < 0) { + end = n; + } + if (end == n && start == n) { + break; + } + lines++; + String line = text.substring(start, end).trim(); + if (inBlock) { + int close = line.indexOf("*/"); + if (close >= 0) { + inBlock = false; + if (line.substring(close + 2).trim().length() > 0) { + code++; + } + } + } else if (line.startsWith("/*")) { + inBlock = line.indexOf("*/", 2) < 0; + } else if (line.length() > 0 && !line.startsWith("//") + && !("python".equals(sf.language) && line.startsWith("#"))) { + code++; + } + start = end + 1; + } + sf.lines = lines; + sf.codeLines = code; + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/Resolver.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Resolver.java new file mode 100644 index 00000000000..87c3c01928e --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/Resolver.java @@ -0,0 +1,454 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/// Resolves the names a `ModelBuilder` recorded as written: supertypes, field types, +/// and every call site to the methods it may reach. +/// +/// The model is built from parse trees, not attributed ones, so this is name +/// resolution as a reader would do it: nested types, single and on-demand imports, +/// the same package, then locals, fields, and the return types of earlier calls in a +/// chain. Precision wins over recall: a name that does not resolve to a type in the +/// tree (a JDK class, a library) produces no edge rather than a guessed one, and an +/// overloaded name links every overload of the matching arity. +final class Resolver { + private static final int MAX_SUPER_DEPTH = 32; + + private final CodeModel model; + + Resolver(CodeModel model) { + this.model = model; + } + + void resolve() { + for (CodeModel.Type t : model.types) { + t.superType = t.extendsName == null ? null : resolveType(t.extendsName, t); + if (t.superType == t) { + t.superType = null; + } + for (String i : t.implementsNames) { + CodeModel.Type it = resolveType(i, t); + if (it != null && it != t) { + // An interface's "extends" list arrives as implementsNames too. + t.interfaces.add(it); + } + } + if ("interface".equals(t.kind) && t.superType != null) { + t.interfaces.add(0, t.superType); + t.superType = null; + } + } + for (CodeModel.Type t : model.types) { + addDependency(t, t.superType); + for (CodeModel.Type i : t.interfaces) { + addDependency(t, i); + } + for (CodeModel.Field f : t.fields) { + f.resolved = f.typeName == null ? null : resolveType(f.typeName, t); + addDependency(t, f.resolved); + } + for (CodeModel.Method m : t.methods) { + if (m.returnType != null) { + addDependency(t, resolveType(m.returnType, t)); + } + for (String p : m.paramTypes) { + if (p != null) { + addDependency(t, resolveType(p, t)); + } + } + } + } + for (CodeModel.Method m : model.methods) { + for (CodeModel.Method s : superMethods(m)) { + m.overrides.add(s); + } + } + for (CodeModel.Method m : model.methods) { + for (CodeModel.Call c : m.rawCalls) { + for (CodeModel.Method target : resolveCall(c, m.owner, m)) { + if (target != m || !c.creation) { + m.calls.add(target); + target.callers.add(m); + if (!m.callLines.containsKey(target)) { + m.callLines.put(target, c.line); + } + } + addDependency(m.owner, target.owner); + } + if (c.creation) { + addDependency(m.owner, resolveType(c.receiver, m.owner)); + } + } + } + for (CodeModel.Type t : model.types) { + for (CodeModel.Call c : t.initCalls) { + for (CodeModel.Method target : resolveCall(c, t, null)) { + addDependency(t, target.owner); + } + if (c.creation) { + addDependency(t, resolveType(c.receiver, t)); + } + } + } + } + + private static void addDependency(CodeModel.Type from, CodeModel.Type to) { + if (to != null && to != from && !isEnclosing(to, from)) { + from.dependencies.add(to); + } + } + + private static boolean isEnclosing(CodeModel.Type outer, CodeModel.Type inner) { + for (CodeModel.Type t = inner.outer; t != null; t = t.outer) { + if (t == outer) { + return true; + } + } + return false; + } + + // ------------------------------------------------------------------ types + + /// The type `written` names when it appears inside `context`, or null when it is not + /// a type of this tree. + CodeModel.Type resolveType(String written, CodeModel.Type context) { + if (written == null) { + return null; + } + String n = written; + while (n.endsWith("[]")) { + n = n.substring(0, n.length() - 2); + } + if (n.length() == 0 || Character.isLowerCase(n.charAt(0)) && n.indexOf('.') < 0) { + // A primitive or a type variable cannot be lower case and dotless and be ours, + // except by an unusual naming convention we do not try to honour. + return null; + } + int dot = n.indexOf('.'); + if (dot > 0) { + CodeModel.Type direct = model.typesByName.get(n); + if (direct != null) { + return direct; + } + CodeModel.Type head = resolveSimple(n.substring(0, dot), context); + if (head == null) { + return null; + } + return model.typesByName.get(head.qualifiedName + n.substring(dot)); + } + return resolveSimple(n, context); + } + + private CodeModel.Type resolveSimple(String name, CodeModel.Type context) { + // Member types of the context, its outers and their supertypes. + for (CodeModel.Type t = context; t != null; t = t.outer) { + if (t.name.equals(name)) { + return t; + } + CodeModel.Type member = memberType(t, name, 0); + if (member != null) { + return member; + } + } + CodeModel.SourceFile f = context.file; + for (String imp : f.imports) { + if (imp.equals(name) || imp.endsWith("." + name)) { + return model.typesByName.get(imp); + } + } + CodeModel.Type samePackage = model.typesByName.get(f.pkg.length() == 0 ? name : f.pkg + "." + name); + if (samePackage != null) { + return samePackage; + } + for (String pkg : f.onDemandImports) { + CodeModel.Type t = model.typesByName.get(pkg + "." + name); + if (t != null) { + return t; + } + } + return null; + } + + private CodeModel.Type memberType(CodeModel.Type t, String name, int depth) { + if (t == null || depth > MAX_SUPER_DEPTH) { + return null; + } + for (CodeModel.Type n : t.nested) { + if (n.name.equals(name)) { + return n; + } + } + CodeModel.Type fromSuper = memberType(t.superType, name, depth + 1); + if (fromSuper != null) { + return fromSuper; + } + for (CodeModel.Type i : t.interfaces) { + CodeModel.Type fromInterface = memberType(i, name, depth + 1); + if (fromInterface != null) { + return fromInterface; + } + } + return null; + } + + // ------------------------------------------------------------------ members + + /// `t` and all its supertypes, nearest first, each once. + private static List hierarchy(CodeModel.Type t) { + List out = new ArrayList(); + Set seen = new HashSet(); + collect(t, out, seen); + return out; + } + + private static void collect(CodeModel.Type t, List out, Set seen) { + if (t == null || !seen.add(t) || out.size() > 256) { + return; + } + out.add(t); + collect(t.superType, out, seen); + for (CodeModel.Type i : t.interfaces) { + collect(i, out, seen); + } + } + + private static List superMethods(CodeModel.Method m) { + List out = new ArrayList(); + if ("".equals(m.name) || m.isStatic()) { + return out; + } + List h = hierarchy(m.owner); + for (int i = 1; i < h.size(); i++) { + for (CodeModel.Method s : h.get(i).methods) { + if (s.name.equals(m.name) && s.paramTypes.size() == m.paramTypes.size() && !s.isStatic()) { + out.add(s); + } + } + } + return out; + } + + /// Methods named `name` with `argc` arguments in `t` or its supertypes; when + /// `argc` matches none, every method of that name (a variable-arity call). + private static List findMethods(CodeModel.Type t, String name, int argc) { + List exact = new ArrayList(); + List any = new ArrayList(); + for (CodeModel.Type h : hierarchy(t)) { + for (CodeModel.Method m : h.methods) { + if (m.name.equals(name)) { + any.add(m); + if (m.paramTypes.size() == argc) { + exact.add(m); + } + } + } + if (!exact.isEmpty()) { + // The nearest declaration wins; an override further up is reached through + // the `overrides` edges, not by linking every level. + return exact; + } + } + return exact.isEmpty() ? any : exact; + } + + private CodeModel.Field findField(CodeModel.Type t, String name) { + for (CodeModel.Type h : hierarchy(t)) { + for (CodeModel.Field f : h.fields) { + if (f.name.equals(name)) { + return f; + } + } + } + return null; + } + + private CodeModel.Type fieldType(CodeModel.Type t, String name) { + CodeModel.Field f = findField(t, name); + if (f == null || f.typeName == null) { + return null; + } + if (f.resolved == null) { + f.resolved = resolveType(f.typeName, ownerOf(t, f)); + } + return f.resolved; + } + + private static CodeModel.Type ownerOf(CodeModel.Type t, CodeModel.Field f) { + for (CodeModel.Type h : hierarchy(t)) { + if (h.fields.contains(f)) { + return h; + } + } + return t; + } + + // ------------------------------------------------------------------ calls + + private List resolveCall(CodeModel.Call c, CodeModel.Type context, CodeModel.Method in) { + if (c.creation) { + CodeModel.Type t = resolveType(c.receiver, context); + if (t == null) { + return new ArrayList(); + } + List ctors = new ArrayList(); + for (CodeModel.Method m : t.methods) { + if ("".equals(m.name) && m.paramTypes.size() == c.argCount) { + ctors.add(m); + } + } + return ctors; + } + if (c.receiver == null) { + for (CodeModel.Type t = context; t != null; t = t.outer) { + List found = findMethods(t, c.name, c.argCount); + if (!found.isEmpty()) { + return found; + } + } + CodeModel.Type staticOwner = staticImportOwner(c.name, context); + return staticOwner == null ? new ArrayList() + : findMethods(staticOwner, c.name, c.argCount); + } + if ("super".equals(c.receiver)) { + return context.superType == null ? new ArrayList() + : findMethods(context.superType, c.name, c.argCount); + } + CodeModel.Type target = typeOfChain(c.receiver, context, in); + return target == null ? new ArrayList() : findMethods(target, c.name, c.argCount); + } + + private CodeModel.Type staticImportOwner(String member, CodeModel.Type context) { + for (String imp : context.file.staticImports) { + int dot = imp.lastIndexOf('.'); + if (dot <= 0) { + continue; + } + String last = imp.substring(dot + 1); + if (last.equals(member) || "*".equals(last)) { + CodeModel.Type owner = model.typesByName.get(imp.substring(0, dot)); + if (owner != null) { + return owner; + } + } + } + return null; + } + + /// The type of a receiver chain such as `this`, `list`, `a.b`, `Display.getInstance()`, + /// `new Foo` or `(Foo)`; null when any step leaves the tree. + private CodeModel.Type typeOfChain(String chain, CodeModel.Type context, CodeModel.Method in) { + if ("?".equals(chain)) { + return null; + } + if (chain.startsWith("new ")) { + return resolveType(chain.substring(4), context); + } + if (chain.startsWith("(") && chain.endsWith(")")) { + return resolveType(chain.substring(1, chain.length() - 1), context); + } + List steps = splitChain(chain); + CodeModel.Type current = null; + int i = 0; + String first = steps.get(0); + if ("this".equals(first)) { + current = context; + i = 1; + } else if (first.endsWith("()")) { + current = returnTypeOf(context, first.substring(0, first.length() - 2), true); + i = 1; + } else { + String local = in == null ? null : in.locals.get(first); + if (local != null) { + current = resolveType(local, context); + i = 1; + } else { + for (CodeModel.Type t = context; t != null && current == null; t = t.outer) { + current = fieldType(t, first); + } + if (current != null) { + i = 1; + } else { + // A type name, possibly qualified: take the longest prefix that is one. + StringBuilder name = new StringBuilder(); + for (int k = 0; k < steps.size() && !steps.get(k).endsWith("()"); k++) { + if (k > 0) { + name.append('.'); + } + name.append(steps.get(k)); + CodeModel.Type t = resolveType(name.toString(), context); + if (t != null) { + current = t; + i = k + 1; + } + } + } + } + if (current == null) { + return null; + } + } + for (; i < steps.size() && current != null; i++) { + String s = steps.get(i); + if (s.endsWith("()")) { + current = returnTypeOf(current, s.substring(0, s.length() - 2), false); + } else { + CodeModel.Type ft = fieldType(current, s); + current = ft != null ? ft : memberType(current, s, 0); + } + } + return current; + } + + private CodeModel.Type returnTypeOf(CodeModel.Type t, String method, boolean searchOuters) { + for (CodeModel.Type c = t; c != null; c = searchOuters ? c.outer : null) { + for (CodeModel.Type h : hierarchy(c)) { + for (CodeModel.Method m : h.methods) { + if (m.name.equals(method) && m.returnType != null) { + return resolveType(m.returnType, h); + } + } + } + } + return null; + } + + /// Splits `a.b().c` into `a`, `b()`, `c`. + private static List splitChain(String chain) { + List out = new ArrayList(); + int start = 0; + for (int i = 0; i <= chain.length(); i++) { + if (i == chain.length() || chain.charAt(i) == '.') { + if (i > start) { + out.add(chain.substring(start, i)); + } + start = i + 1; + } + } + return out; + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/codemodel/ReviewQueries.java b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ReviewQueries.java new file mode 100644 index 00000000000..2cb6c672205 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/codemodel/ReviewQueries.java @@ -0,0 +1,279 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// The reviewer's questions about a branch: what its commits are, what it amounts to, and +/// why a class changed. Every answer honours the commit focused with `commit`. +/// +/// - `commits`: the branch's commits, newest first. +/// - `commit SHA|uncommitted|all`: focuses one commit, or the whole branch again. +/// - `prsummary`: totals, change per module and file, the commits, and the hotspots. +/// - `why QNAME`: the commits that touched a top-level class and the comments they added, +/// per changed method. +final class ReviewQueries { + private static final int HOTSPOTS = 12; + + private final CodeModel model; + private final Commits commits; + + ReviewQueries(CodeModel model) { + this.model = model; + this.commits = model.commits; + } + + String answer(String req) { + StringBuilder sb = new StringBuilder(4096); + Json.Writer w = new Json.Writer(sb); + if ("commits".equals(req)) { + w.beginObject(); + focus(w); + commitList(w); + w.endObject(); + } else if (req.startsWith("commit ")) { + String id = req.substring(7).trim(); + if ("all".equals(id) || "-".equals(id)) { + commits.focus(null); + } else { + String sha = commits.resolve(id); + if (sha == null) { + return ModelQueries.error("no commit " + id + " on this branch"); + } + commits.focus(sha); + } + w.beginObject(); + focus(w); + w.endObject(); + } else if ("prsummary".equals(req)) { + summary(w); + } else { + why(w, req.substring(4).trim()); + } + return sb.toString(); + } + + private void focus(Json.Writer w) { + Commits.Info f = commits.get(commits.focus()); + w.name("focus"); + if (f == null) { + w.value(""); + } else { + ref(w, f); + } + } + + static String shortSha(String sha) { + return Commits.UNCOMMITTED.equals(sha) ? "working tree" : sha.substring(0, Math.min(8, sha.length())); + } + + static void ref(Json.Writer w, Commits.Info c) { + w.beginObject().name("sha").value(c.sha).name("short").value(shortSha(c.sha)).name("s").value(c.subject) + .name("b").value(c.body).name("t").value(c.time).name("au").value(c.author) + .name("a").value(c.added).name("d").value(c.deleted).name("files").value(c.files.size()).endObject(); + } + + private void commitList(Json.Writer w) { + w.name("commits").beginArray(); + for (Commits.Info c : commits.all()) { + ref(w, c); + } + w.endArray(); + } + + // ------------------------------------------------------------------ prsummary + + private void summary(Json.Writer w) { + Commits.Info f = commits.get(commits.focus()); + w.beginObject(); + focus(w); + commitList(w); + if (model.git != null) { + w.name("base").value(model.git.base).name("branch").value(model.git.branch); + } + // file -> {added, deleted}: the commit's own numbers when one is focused. + Map files = new LinkedHashMap(); + for (CodeModel.SourceFile sf : model.files) { + if (f != null) { + int[] ad = f.perFile.get(sf.path); + // change is null for an approved file while approved changes are hidden, + // as the method counts below already respect. + if (ad != null && sf.change != null) { + files.put(sf, ad); + } + } else if (sf.change != null) { + files.put(sf, new int[]{sf.added, sf.deleted}); + } + } + int added = 0; + int deleted = 0; + Map modules = new LinkedHashMap(); + for (Map.Entry e : files.entrySet()) { + added += e.getValue()[0]; + deleted += e.getValue()[1]; + String mod = e.getKey().module.length() == 0 ? "(root)" : e.getKey().module; + int[] m = modules.get(mod); + if (m == null) { + m = new int[3]; + modules.put(mod, m); + } + m[0] += e.getValue()[0]; + m[1] += e.getValue()[1]; + m[2]++; + } + int methodsNew = 0; + int methodsChanged = 0; + int typesNew = 0; + int typesChanged = 0; + List hot = new ArrayList(); + for (CodeModel.Method m : model.methods) { + if (m.change == null) { + continue; + } + if ("A".equals(m.change)) { + methodsNew++; + } else { + methodsChanged++; + } + int own = 0; + for (int i = m.line; i <= m.endLine; i++) { + String sha = commits.at(m.owner.file.path, i); + if (sha != null && (f == null || f.sha.equals(sha))) { + own++; + } + } + hot.add(new Object[]{m, own}); + } + for (CodeModel.Type t : model.types) { + if ("A".equals(t.change)) { + typesNew++; + } else if (t.change != null) { + typesChanged++; + } + } + w.name("totals").beginObject().name("files").value(files.size()).name("added").value(added) + .name("deleted").value(deleted).name("methodsNew").value(methodsNew) + .name("methodsChanged").value(methodsChanged).name("typesNew").value(typesNew) + .name("typesChanged").value(typesChanged).name("commits").value(commits.all().size()).endObject(); + w.name("modules").beginArray(); + for (Map.Entry e : modules.entrySet()) { + w.beginObject().name("n").value(e.getKey()).name("a").value(e.getValue()[0]) + .name("d").value(e.getValue()[1]).name("files").value(e.getValue()[2]).endObject(); + } + w.endArray(); + List> fl = new ArrayList>( + files.entrySet()); + Collections.sort(fl, (a, b) -> (b.getValue()[0] + b.getValue()[1]) - (a.getValue()[0] + a.getValue()[1])); + w.name("files").beginArray(); + for (Map.Entry e : fl) { + CodeModel.SourceFile sf = e.getKey(); + w.beginObject().name("p").value(sf.path).name("mod").value(sf.module).name("pkg").value(sf.pkg) + .name("ch").value(sf.change == null ? "M" : sf.change).name("a").value(e.getValue()[0]) + .name("d").value(e.getValue()[1]).endObject(); + } + w.endArray(); + Collections.sort(hot, (a, b) -> (Integer) b[1] - (Integer) a[1]); + w.name("hotspots").beginArray(); + for (int i = 0; i < hot.size() && i < HOTSPOTS; i++) { + CodeModel.Method m = (CodeModel.Method) hot.get(i)[0]; + w.beginObject().name("id").value(m.id).name("n").value(m.name).name("on").value(m.owner.name) + .name("q").value(ChangeQueries.top(m.owner).qualifiedName).name("p").value(m.owner.file.path) + .name("ch").value(m.change).name("lines").value((Integer) hot.get(i)[1]) + .name("callers").value(m.callers.size()).endObject(); + } + w.endArray(); + w.endObject(); + } + + // ------------------------------------------------------------------ why + + private void why(Json.Writer w, String qname) { + CodeModel.Type type = null; + for (CodeModel.Type t : model.types) { + if (t.qualifiedName.equals(qname)) { + type = t; + } + } + if (type == null) { + w.beginObject().name("error").value("no class " + qname).endObject(); + return; + } + String path = type.file.path; + w.beginObject(); + w.name("q").value(qname).name("p").value(path); + w.name("commits").beginArray(); + for (String sha : commits.in(path, type.line, type.endLine)) { + if (commits.focus() == null || commits.focus().equals(sha)) { + ref(w, commits.get(sha)); + } + } + w.endArray(); + comments(w, path, type.line, type.endLine); + w.name("methods").beginArray(); + List ms = new ArrayList(); + collect(type, ms); + for (CodeModel.Method m : ms) { + if (m.change == null) { + continue; + } + w.beginObject().name("id").value(m.id).name("n").value(m.name).name("on").value(m.owner.name) + .name("ch").value(m.change).name("sig").value(m.signature()) + .name("k").value(Approvals.key(m)) + .name("h").value(model.approvals == null ? "" : model.approvals.fingerprint(m)) + .name("l").value(m.line) + .name("e").value(m.endLine); + w.name("commits").beginArray(); + for (String sha : commits.in(path, m.line, m.endLine)) { + if (commits.focus() == null || commits.focus().equals(sha)) { + w.value(sha); + } + } + w.endArray(); + // The doc comment right above the method, when the branch wrote it. + comments(w, path, commits.docStart(path, m.line), m.endLine); + w.endObject(); + } + w.endArray(); + w.endObject(); + } + + private static void collect(CodeModel.Type t, List out) { + out.addAll(t.methods); + for (CodeModel.Type n : t.nested) { + collect(n, out); + } + } + + private void comments(Json.Writer w, String path, int from, int to) { + w.name("comments").beginArray(); + for (Object[] c : commits.addedComments(path, from, to)) { + w.beginObject().name("l").value((Integer) c[0]).name("text").value((String) c[1]) + .name("c").value((String) c[2]).endObject(); + } + w.endArray(); + } +} diff --git a/maven/code-model/src/main/java/com/codename1/tools/javac/SourceOutliner.java b/maven/code-model/src/main/java/com/codename1/tools/javac/SourceOutliner.java new file mode 100644 index 00000000000..bbc103965d9 --- /dev/null +++ b/maven/code-model/src/main/java/com/codename1/tools/javac/SourceOutliner.java @@ -0,0 +1,586 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.javac; + +import com.codename1.tools.codemodel.FlowNode; +import com.codename1.tools.codemodel.OutlineSink; + +import java.util.ArrayList; +import java.util.List; + +/// The code model's window into the in-tree Java parser, whose trees are package +/// private: it parses one file (parse only, no attribution, so a file whose +/// dependencies are absent still outlines) and reports its declarations and calls to +/// an `OutlineSink`, or builds one method's flow chart. +/// +/// It lives in the parser's package on purpose. A change to the tree classes then +/// fails this module's compile rather than producing an empty model. +public final class SourceOutliner { + private static final int LABEL_MAX = 80; + + private final Source source; + private final Tree.CompilationUnit unit; + + private SourceOutliner(Source source, Tree.CompilationUnit unit) { + this.source = source; + this.unit = unit; + } + + /// Parses `text`. Returns null when the parser gave up on the file entirely; + /// a file with syntax errors otherwise yields what could be recovered. + private static SourceOutliner parse(String fileName, String text) { + Source src = new Source(fileName, text); + try { + Tree.CompilationUnit cu = new JavaSourceParser(src, new Log()).parseCompilationUnit(); + return cu == null ? null : new SourceOutliner(src, cu); + } catch (RuntimeException e) { + return null; + } + } + + /// Outlines `text` into `sink`; false when the file could not be parsed at all. + public static boolean outline(String fileName, String text, OutlineSink sink) { + SourceOutliner o = parse(fileName, text); + if (o == null) { + return false; + } + sink.packageName(o.unit.packageName == null ? "" : o.unit.packageName); + for (Tree.Import imp : o.unit.imports) { + if (!imp.implicit) { + sink.importDecl(imp.name, imp.isStatic, imp.onDemand); + } + } + for (Tree.ClassDecl c : o.unit.types) { + o.type(c, sink); + } + return true; + } + + /// The flow chart of the method or constructor declared on `line` (the line of its + /// name), or null when no method is declared there. + public static FlowNode flow(String fileName, String text, int line) { + SourceOutliner o = parse(fileName, text); + if (o == null) { + return null; + } + for (Tree.ClassDecl c : o.unit.types) { + Tree.MethodDecl m = o.findMethod(c, line); + if (m != null) { + FlowNode root = new FlowNode("method", o.lineText(m.pos), o.line(m.pos)); + if (m.body != null) { + o.flowStatements(m.body.stats, root.addBranch("body")); + } + return root; + } + } + return null; + } + + /// The flow charts of the methods declared on each of `lines`, parsing the file once; + /// an entry is null where no method is declared, and every entry is when the file + /// does not parse. + public static FlowNode[] flows(String fileName, String text, int[] lines) { + FlowNode[] out = new FlowNode[lines.length]; + SourceOutliner o = parse(fileName, text); + if (o == null) { + return out; + } + for (int i = 0; i < lines.length; i++) { + for (Tree.ClassDecl c : o.unit.types) { + Tree.MethodDecl m = o.findMethod(c, lines[i]); + if (m != null) { + FlowNode root = new FlowNode("method", o.lineText(m.pos), o.line(m.pos)); + if (m.body != null) { + o.flowStatements(m.body.stats, root.addBranch("body")); + } + out[i] = root; + break; + } + } + } + return out; + } + + // ------------------------------------------------------------------ outline + + private int line(int pos) { + return source.line(pos); + } + + private void type(Tree.ClassDecl c, OutlineSink sink) { + List impl = new ArrayList(); + for (Tree t : c.implementing) { + String n = typeName(t); + if (n != null) { + impl.add(n); + } + } + int flags = c.mods == null ? 0 : c.mods.flags; + int start = line(c.pos); + sink.beginType(c.name, kindName(c.kind), flags, start, line(blockEnd(c.pos)), + typeName(c.extending), impl); + for (Tree.VarDef rc : c.recordComponents) { + sink.field(rc.name, typeName(rc.vartype), JavaSourceParser.ACC_PRIVATE | JavaSourceParser.ACC_FINAL, + line(rc.pos)); + } + List initializers = new ArrayList(); + for (Tree m : c.members) { + if (m instanceof Tree.ClassDecl) { + type((Tree.ClassDecl) m, sink); + } else if (m instanceof Tree.MethodDecl) { + method((Tree.MethodDecl) m, sink); + } else if (m instanceof Tree.VarDef) { + Tree.VarDef v = (Tree.VarDef) m; + sink.field(v.name, typeName(v.vartype), v.mods == null ? 0 : v.mods.flags, line(v.pos)); + if (v.init != null) { + initializers.add(v.init); + } + } else if (m instanceof Tree.Block) { + initializers.add(m); + } + } + if (!initializers.isEmpty()) { + // Field initializers and initializer blocks: the type's own calls, reported + // outside any method so the model can attribute them to the type. + Calls calls = new Calls(sink); + calls.scan(initializers); + } + sink.endType(); + } + + private void method(Tree.MethodDecl m, OutlineSink sink) { + List types = new ArrayList(); + List names = new ArrayList(); + for (Tree.VarDef p : m.params) { + types.add(typeName(p.vartype)); + names.add(p.name); + } + String name = m.returnType == null ? "" : m.name; + int start = line(m.pos); + int end = m.body == null ? start : line(m.body.endPos); + sink.beginMethod(name, m.returnType == null ? null : typeName(m.returnType), types, names, + m.mods == null ? 0 : m.mods.flags, start, end); + for (int i = 0; i < types.size(); i++) { + sink.local(names.get(i), types.get(i)); + } + Calls calls = new Calls(sink); + if (m.body != null) { + calls.scan(m.body); + } + sink.endMethod(calls.complexity); + } + + private static String kindName(Tree.ClassKind k) { + switch (k) { + case INTERFACE: + return "interface"; + case ENUM: + return "enum"; + case RECORD: + return "record"; + case ANNOTATION: + return "annotation"; + default: + return "class"; + } + } + + /// A type tree as a name: generics and array brackets dropped, a primitive by its + /// keyword, null when there is no type (`var`, an implicit lambda parameter). + static String typeName(Tree t) { + if (t == null) { + return null; + } + if (t instanceof Tree.Ident) { + return ((Tree.Ident) t).name; + } + if (t instanceof Tree.Select) { + Tree.Select s = (Tree.Select) t; + String head = typeName(s.selected); + return head == null ? s.name : head + "." + s.name; + } + if (t instanceof Tree.TypeApply) { + return typeName(((Tree.TypeApply) t).clazz); + } + if (t instanceof Tree.ArrayTypeTree) { + String e = typeName(((Tree.ArrayTypeTree) t).elem); + return e == null ? null : e + "[]"; + } + if (t instanceof Tree.PrimitiveTypeTree) { + Token.Kind k = ((Tree.PrimitiveTypeTree) t).tag; + return k == null ? null : primitiveName(k.name()); + } + return null; + } + + private static String primitiveName(String kind) { + // Token kinds are the keywords in upper case (INT, BOOLEAN, VOID). Folded by + // hand: a keyword is ASCII and String.toLowerCase is locale sensitive. + StringBuilder sb = new StringBuilder(kind.length()); + for (int i = 0; i < kind.length(); i++) { + char c = kind.charAt(i); + sb.append(c >= 'A' && c <= 'Z' ? (char) (c + ('a' - 'A')) : c); + } + return sb.toString(); + } + + /// The offset of the `}` that closes the first block opened after `pos`, skipping + /// comments, strings and character literals; the end of the text when unmatched. + private int blockEnd(int pos) { + String s = source.text; + int n = s.length(); + int depth = 0; + int i = Source.real(pos); + while (i < n) { + char c = s.charAt(i); + if (c == '/' && i + 1 < n && s.charAt(i + 1) == '/') { + while (i < n && s.charAt(i) != '\n') { + i++; + } + continue; + } + if (c == '/' && i + 1 < n && s.charAt(i + 1) == '*') { + int close = s.indexOf("*/", i + 2); + i = close < 0 ? n : close + 2; + continue; + } + if (c == '"' || c == '\'') { + i = skipLiteral(s, i); + continue; + } + if (c == '{') { + depth++; + } else if (c == '}') { + depth--; + if (depth == 0) { + return i; + } + } + i++; + } + return Math.max(0, n - 1); + } + + private static int skipLiteral(String s, int start) { + int n = s.length(); + char q = s.charAt(start); + if (q == '"' && s.startsWith("\"\"\"", start)) { + int close = s.indexOf("\"\"\"", start + 3); + return close < 0 ? n : close + 3; + } + int i = start + 1; + while (i < n) { + char c = s.charAt(i); + if (c == '\\') { + i += 2; + continue; + } + if (c == q || c == '\n') { + return i + 1; + } + i++; + } + return n; + } + + /// Collects a body's calls, locals and decision points. + private final class Calls extends TreeScanner { + private final OutlineSink sink; + int complexity = 1; + + Calls(OutlineSink sink) { + this.sink = sink; + } + + @Override + void scan(Tree t) { + if (t == null) { + return; + } + if (t instanceof Tree.MethodCall) { + Tree.MethodCall c = (Tree.MethodCall) t; + String receiver; + if (c.receiver == null) { + receiver = null; + } else if (c.superCall) { + receiver = "super"; + } else { + receiver = receiverName(c.receiver); + } + sink.call(receiver, receiver != null && receiver.indexOf('(') >= 0, c.name, c.args.size(), + line(c.pos)); + } else if (t instanceof Tree.NewClass) { + Tree.NewClass n = (Tree.NewClass) t; + String tn = typeName(n.clazz); + if (tn != null) { + sink.instantiation(tn, n.args.size(), line(n.pos)); + } + // An anonymous class's methods are this method's behaviour: scan them in place. + } else if (t instanceof Tree.VarDef) { + Tree.VarDef v = (Tree.VarDef) t; + if (v.vartype != null) { + sink.local(v.name, typeName(v.vartype)); + } + } else if (t instanceof Tree.ForEach) { + Tree.ForEach f = (Tree.ForEach) t; + complexity++; + if (f.var != null && f.var.vartype != null) { + sink.local(f.var.name, typeName(f.var.vartype)); + } + } else if (t instanceof Tree.Catch) { + Tree.Catch c = (Tree.Catch) t; + if (c.param != null && c.param.vartype != null) { + sink.local(c.param.name, typeName(c.param.vartype)); + } + } else if (t instanceof Tree.Try) { + complexity += ((Tree.Try) t).catches.size(); + for (Tree.Catch c : ((Tree.Try) t).catches) { + scan(c); + } + } else if (t instanceof Tree.BindingPattern) { + Tree.VarDef v = ((Tree.BindingPattern) t).var; + if (v != null && v.vartype != null) { + sink.local(v.name, typeName(v.vartype)); + } + } else if (t instanceof Tree.If || t instanceof Tree.WhileLoop || t instanceof Tree.DoLoop + || t instanceof Tree.ForLoop || t instanceof Tree.Conditional) { + complexity++; + } else if (t instanceof Tree.Case) { + if (!((Tree.Case) t).isDefault) { + complexity++; + } + } else if (t instanceof Tree.Switch) { + for (Tree.Case c : ((Tree.Switch) t).cases) { + scan(c); + } + } else if (t instanceof Tree.Binary) { + Token.Kind op = ((Tree.Binary) t).op; + if (op == Token.Kind.AMPAMP || op == Token.Kind.BARBAR) { + complexity++; + } + } + super.scan(t); + } + } + + /// A receiver expression as a chain the model can type step by step: `this`, an + /// identifier, a dotted name (`a.b.c`), a call in the chain written `name()` + /// (`Display.getInstance()`), `new T` or a cast `(T)`; `?` for anything else. + private static String receiverName(Tree t) { + if (t == null) { + return "?"; + } + if (t instanceof Tree.Parens) { + return receiverName(((Tree.Parens) t).expr); + } + if (t instanceof Tree.Ident) { + return ((Tree.Ident) t).name; + } + if (t instanceof Tree.Select) { + Tree.Select s = (Tree.Select) t; + String left = receiverName(s.selected); + return "?".equals(left) ? "?" : left + "." + s.name; + } + if (t instanceof Tree.MethodCall) { + Tree.MethodCall c = (Tree.MethodCall) t; + if (c.receiver == null) { + return c.name + "()"; + } + String left = c.superCall ? "super" : receiverName(c.receiver); + return "?".equals(left) ? "?" : left + "." + c.name + "()"; + } + if (t instanceof Tree.NewClass) { + String n = typeName(((Tree.NewClass) t).clazz); + return n == null ? "?" : "new " + n; + } + if (t instanceof Tree.Cast) { + String n = typeName(((Tree.Cast) t).clazz); + return n == null ? "?" : "(" + n + ")"; + } + return "?"; + } + + // ------------------------------------------------------------------ flow + + private Tree.MethodDecl findMethod(Tree.ClassDecl c, int targetLine) { + for (Tree m : c.members) { + if (m instanceof Tree.MethodDecl && line(m.pos) == targetLine) { + return (Tree.MethodDecl) m; + } + if (m instanceof Tree.ClassDecl) { + Tree.MethodDecl inner = findMethod((Tree.ClassDecl) m, targetLine); + if (inner != null) { + return inner; + } + } + } + return null; + } + + private String lineText(int pos) { + String s = source.text; + int p = Math.min(Math.max(0, Source.real(pos)), s.length()); + int start = s.lastIndexOf('\n', p - 1) + 1; + int end = s.indexOf('\n', p); + if (end < 0) { + end = s.length(); + } + String t = s.substring(start, end).trim(); + if (t.endsWith("{")) { + t = t.substring(0, t.length() - 1).trim(); + } + return t.length() > LABEL_MAX ? t.substring(0, LABEL_MAX - 3) + "..." : t; + } + + private void flowStatements(List stats, List out) { + if (stats == null) { + return; + } + for (Tree s : stats) { + flowStatement(s, out); + } + } + + private void flowBody(Tree body, List out) { + if (body instanceof Tree.Block) { + flowStatements(((Tree.Block) body).stats, out); + } else if (body != null) { + flowStatement(body, out); + } + } + + private void flowStatement(Tree s, List out) { + int ln = line(s.pos); + if (s instanceof Tree.Block) { + flowStatements(((Tree.Block) s).stats, out); + } else if (s instanceof Tree.If) { + Tree.If i = (Tree.If) s; + FlowNode n = new FlowNode("if", lineText(s.pos), ln); + flowBody(i.thenPart, n.addBranch("yes")); + List no = n.addBranch("no"); + if (i.elsePart != null) { + flowBody(i.elsePart, no); + } + out.add(n); + } else if (s instanceof Tree.WhileLoop || s instanceof Tree.DoLoop || s instanceof Tree.ForLoop + || s instanceof Tree.ForEach) { + FlowNode n = new FlowNode("loop", lineText(s.pos), ln); + Tree body; + if (s instanceof Tree.WhileLoop) { + body = ((Tree.WhileLoop) s).body; + } else if (s instanceof Tree.DoLoop) { + body = ((Tree.DoLoop) s).body; + } else if (s instanceof Tree.ForLoop) { + body = ((Tree.ForLoop) s).body; + } else { + body = ((Tree.ForEach) s).body; + } + flowBody(body, n.addBranch("body")); + out.add(n); + } else if (s instanceof Tree.Labeled) { + flowStatement(((Tree.Labeled) s).body, out); + } else if (s instanceof Tree.Switch) { + Tree.Switch sw = (Tree.Switch) s; + FlowNode n = new FlowNode("switch", lineText(s.pos), ln); + for (Tree.Case c : sw.cases) { + List b = n.addBranch(c.isDefault ? "default" : lineText(c.pos)); + flowStatements(c.stats, b); + } + out.add(n); + } else if (s instanceof Tree.Try) { + Tree.Try t = (Tree.Try) s; + FlowNode n = new FlowNode("try", lineText(s.pos), ln); + flowBody(t.body, n.addBranch("try")); + for (Tree.Catch c : t.catches) { + flowBody(c.body, n.addBranch(lineText(c.pos))); + } + if (t.finalizer != null) { + flowBody(t.finalizer, n.addBranch("finally")); + } + out.add(n); + } else if (s instanceof Tree.Synchronized) { + FlowNode n = new FlowNode("sync", lineText(s.pos), ln); + flowBody(((Tree.Synchronized) s).body, n.addBranch("body")); + out.add(n); + } else if (s instanceof Tree.Return || s instanceof Tree.Yield) { + out.add(new FlowNode("return", lineText(s.pos), ln)); + } else if (s instanceof Tree.Throw) { + out.add(new FlowNode("throw", lineText(s.pos), ln)); + } else if (s instanceof Tree.Break || s instanceof Tree.Continue) { + out.add(new FlowNode(s instanceof Tree.Break ? "break" : "continue", lineText(s.pos), ln)); + } else if (s instanceof Tree.Empty) { + return; + } else if (s instanceof Tree.ClassDecl) { + out.add(new FlowNode("stmt", lineText(s.pos), ln)); + } else { + boolean call = s instanceof Tree.ExpressionStatement + && ((Tree.ExpressionStatement) s).expr instanceof Tree.MethodCall; + FlowNode prev = out.isEmpty() ? null : out.get(out.size() - 1); + // Consecutive plain statements on one line collapse into one box. + if (prev != null && prev.getLine() == ln && prev.getBranches().isEmpty()) { + return; + } + FlowNode n = new FlowNode(call ? "call" : "stmt", lineText(s.pos), ln); + callbacks(s, n); + out.add(n); + } + } + + /// Adds a branch to `n` for each block lambda and anonymous class method written inside + /// statement `s`: callback-style code keeps its logic there, and a chart that stopped at + /// the statement would show it as a single box. + private void callbacks(Tree s, final FlowNode n) { + new TreeScanner() { + @Override + void scan(Tree t) { + if (t instanceof Tree.Lambda) { + Tree body = ((Tree.Lambda) t).body; + if (body instanceof Tree.Block) { + flowStatements(((Tree.Block) body).stats, n.addBranch(lambdaLabel((Tree.Lambda) t))); + } + } else if (t instanceof Tree.NewClass && ((Tree.NewClass) t).body != null) { + scan(((Tree.NewClass) t).args); + for (Tree m : ((Tree.NewClass) t).body.members) { + if (m instanceof Tree.MethodDecl && ((Tree.MethodDecl) m).body != null) { + flowStatements(((Tree.MethodDecl) m).body.stats, + n.addBranch(((Tree.MethodDecl) m).name + "()")); + } + } + } else { + super.scan(t); + } + } + }.scan(s); + } + + private static String lambdaLabel(Tree.Lambda l) { + StringBuilder sb = new StringBuilder(); + for (Tree.VarDef p : l.params) { + if (sb.length() > 0) { + sb.append(", "); + } + sb.append(p.name); + } + return sb.length() == 0 ? "() ->" : sb.append(" ->").toString(); + } +} diff --git a/maven/code-model/src/test/java/com/codename1/tools/codemodel/CodeModelTest.java b/maven/code-model/src/test/java/com/codename1/tools/codemodel/CodeModelTest.java new file mode 100644 index 00000000000..3f2e793cc78 --- /dev/null +++ b/maven/code-model/src/test/java/com/codename1/tools/codemodel/CodeModelTest.java @@ -0,0 +1,384 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.tools.codemodel; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CodeModelTest { + @TempDir + File tmp; + + private static void write(File root, String path, String text) throws IOException { + File f = new File(root, path); + f.getParentFile().mkdirs(); + Files.write(f.toPath(), text.getBytes(StandardCharsets.UTF_8)); + } + + private static CodeModel.Method method(CodeModel model, String type, String name, int arity) { + CodeModel.Type t = model.typesByName.get(type); + assertNotNull(t, type); + for (CodeModel.Method m : t.methods) { + if (m.name.equals(name) && m.paramTypes.size() == arity) { + return m; + } + } + throw new AssertionError("no " + type + "#" + name + "/" + arity); + } + + private static List calls(CodeModel.Method m) { + List out = new ArrayList(); + for (CodeModel.Method c : m.calls) { + out.add(c.owner.name + "." + c.name + "/" + c.paramTypes.size()); + } + return out; + } + + private File fixture() throws IOException { + File root = new File(tmp, "proj"); + write(root, "src/a/Display.java", "package a;\n" + + "public class Display {\n" + + " static Display instance;\n" + + " public static Display getInstance() { return instance; }\n" + + " public void callSerially(Runnable r) { }\n" + + " public Impl impl() { return null; }\n" + + " public static class Impl {\n" + + " public void flush() { }\n" + + " public native void nativeFlush(int x);\n" + + " }\n" + + "}\n"); + write(root, "src/a/Base.java", "package a;\n" + + "public abstract class Base {\n" + + " public void paint() { }\n" + + " public void paint(int x) { }\n" + + "}\n"); + write(root, "src/b/Util.java", "package b;\n" + + "public final class Util {\n" + + " public static int twice(int v) { return v * 2; }\n" + + "}\n"); + write(root, "src/b/Widget.java", "package b;\n" + + "import a.Base;\n" + + "import a.Display;\n" + + "import static b.Util.twice;\n" + + "public class Widget extends Base {\n" + + " private Display display;\n" + + " @Override public void paint() {\n" + + " Display.getInstance().callSerially(null);\n" + + " display.impl().flush();\n" + + " Display.Impl local = null;\n" + + " local.flush();\n" + + " super.paint(1);\n" + + " int t = twice(3);\n" + + " if (t > 2 && t < 9) { helper(); }\n" + + " new Widget();\n" + + " }\n" + + " void helper() { }\n" + + "}\n"); + write(root, "native/a_Display_Impl.m", "#include \"x.h\"\n" + + "JAVA_VOID a_Display_Impl_nativeFlush___int(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT me, JAVA_INT x) {\n" + + " if (x) { other(); }\n" + + "}\n" + + "@implementation Foo\n" + + "- (void)viewDidLoad:(BOOL)animated {\n" + + "}\n" + + "@end\n"); + return root; + } + + @Test + void approvalFingerprintIgnoresReformattingButNotLiterals() { + String base = "int f() { return g(\"a b\", ' '); }"; + assertEquals(Approvals.hash(base), Approvals.hash("int f()\n{\n return g(\"a b\",' ');\n}")); + assertFalse(Approvals.hash(base).equals(Approvals.hash("int f() { return g(\"ab\", ' '); }"))); + assertFalse(Approvals.hash(base).equals(Approvals.hash("int f() { return g(\"a b\", '\\t'); }"))); + // A string after a line comment still counts its spaces. + assertFalse(Approvals.hash("// note\nlog(\"a b\");\n").equals(Approvals.hash("// note\nlog(\"ab\");\n"))); + // A comment with an apostrophe can be reflowed; a text block's spaces count. + assertEquals(Approvals.hash("// don't do this\nint x;"), Approvals.hash("// don't do this\n int x;")); + assertFalse(Approvals.hash("String s = \"\"\"\n a b\n\"\"\";").equals( + Approvals.hash("String s = \"\"\"\n ab\n\"\"\";"))); + } + + @Test + void resolvesReceiversOverloadsAndStaticImports() throws IOException { + CodeModel model = new ProjectScanner(fixture()).scan(); + CodeModel.Method paint = method(model, "b.Widget", "paint", 0); + List c = calls(paint); + assertTrue(c.contains("Display.getInstance/0"), c.toString()); + assertTrue(c.contains("Display.callSerially/1"), "a chain types through a return type: " + c); + assertTrue(c.contains("Impl.flush/0"), "a field, a method and a nested type: " + c); + assertTrue(c.contains("Base.paint/1"), "super call picks the overload by arity: " + c); + assertFalse(c.contains("Base.paint/0"), c.toString()); + assertTrue(c.contains("Util.twice/1"), "static import: " + c); + assertTrue(c.contains("Widget.helper/0"), c.toString()); + assertTrue(c.contains("Widget./0") || model.typesByName.get("b.Widget").dependencies.size() > 0); + assertEquals(3, paint.complexity, "1, plus one if and one &&"); + assertTrue(paint.overrides.contains(method(model, "a.Base", "paint", 0))); + assertTrue(method(model, "a.Display", "callSerially", 1).callers.contains(paint)); + CodeModel.Type widget = model.typesByName.get("b.Widget"); + assertEquals("a.Base", widget.superType.qualifiedName); + assertEquals(7, paint.line); + assertEquals(16, paint.endLine); + } + + @Test + void linksParparVmNativesAndFindsObjcMethods() throws IOException { + CodeModel model = new ProjectScanner(fixture()).scan(); + CodeModel.NativeFunction nf = null; + boolean objc = false; + for (CodeModel.NativeFunction f : model.natives) { + if (f.name.startsWith("a_Display_Impl_nativeFlush")) { + nf = f; + } + objc |= "-viewDidLoad:".equals(f.name); + } + assertNotNull(nf); + assertEquals(2, nf.line); + assertEquals(4, nf.endLine); + assertEquals("nativeFlush", nf.javaMethod.name); + assertTrue(objc); + } + + @Test + void queriesAnswerAsJson() throws IOException { + ModelQueries q = new ModelQueries(new ProjectScanner(fixture()).scan()); + assertTrue(q.answer("type b.Widget").contains("\"q\":\"a.Base\"")); + assertTrue(q.answer("method b.Widget#paint").contains("\"callees\"")); + assertTrue(q.answer("search twice").contains("\"n\":\"twice\"")); + assertTrue(q.answer("diff").contains("error")); + assertTrue(q.answer("nonsense").contains("error")); + assertTrue(q.answer("packages").contains("[\"b\",\"a\",")); + } + + private static void git(File dir, String... args) throws IOException { + String[] all = new String[args.length + 4]; + all[0] = "-c"; + all[1] = "user.email=test@example.com"; + all[2] = "-c"; + all[3] = "user.name=test"; + System.arraycopy(args, 0, all, 4, args.length); + Git.run(dir, all); + } + + @Test + void marksBranchChangesWithRootInSubdirectory() throws IOException { + File repo = new File(tmp, "repo"); + File app = new File(repo, "app"); + write(app, "src/p/Keep.java", "package p;\npublic class Keep {\n void a() {\n b();\n }\n" + + " void b() {\n }\n void gone() {\n }\n}\n"); + write(app, "src/p/Dead.java", "package p;\npublic class Dead {\n}\n"); + git(repo, "init", "-q", "-b", "main"); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "base"); + git(repo, "checkout", "-q", "-b", "topic"); + write(app, "src/p/Keep.java", "package p;\npublic class Keep {\n void a() {\n b();\n }\n" + + " void b() {\n int x = 1;\n }\n void fresh() {\n }\n}\n"); + new File(app, "src/p/Dead.java").delete(); + write(app, "src/p/Untracked.java", "package p;\nclass Untracked {\n void u() {\n new Keep().b();\n }\n}\n"); + + CodeModel model = new ProjectScanner(app).scan(); + new GitChanges(model).apply("main"); + Impact.compute(model, Impact.DEFAULT_DEPTH); + + assertEquals("M", model.filesByPath.get("src/p/Keep.java").change); + assertEquals("A", model.filesByPath.get("src/p/Untracked.java").change, + "untracked files count when the root is below the git top level"); + assertEquals("M", method(model, "p.Keep", "b", 0).change); + assertNull(method(model, "p.Keep", "a", 0).change); + assertEquals(1, method(model, "p.Keep", "a", 0).impact, "a calls the changed b"); + assertEquals("A", method(model, "p.Keep", "fresh", 0).change); + boolean gone = false; + boolean dead = false; + for (CodeModel.Removed r : model.removed) { + gone |= "gone()".equals(r.signature); + dead |= "p.Dead".equals(r.owner); + } + assertTrue(gone, "a removed method is recorded"); + assertTrue(dead, "a deleted file's types are recorded"); + } + + @Test + void renamedFileUnderAPathWithASpaceDiffsAgainstItsOldName() throws IOException { + File repo = new File(tmp, "spaced"); + File app = new File(repo, "My App"); + StringBuilder body = new StringBuilder("package p;\npublic class Old {\n"); + for (int i = 0; i < 8; i++) { + body.append(" void m").append(i).append("() {\n }\n"); + } + body.append("}\n"); + write(app, "src/p/Old.java", body.toString()); + write(app, "src/p/Edited.java", "package p;\nclass Edited {\n void e() {\n }\n}\n"); + String moved = "package p;\nclass Moved {\n void a() {\n }\n void b() {\n }\n}\n"; + write(app, "src/p/Moved.java", moved); + git(repo, "init", "-q", "-b", "main"); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "base"); + git(repo, "checkout", "-q", "-b", "topic"); + new File(app, "src/p/Old.java").delete(); + write(app, "src/p/New.java", body.toString().replace("class Old", "class New")); + write(app, "src/p/Edited.java", "package p;\nclass Edited {\n void e() {\n int x = 1;\n }\n}\n"); + new File(app, "src/p/Moved.java").delete(); + write(app, "src/p/sub/Moved.java", moved); + git(repo, "add", "-A"); + + CodeModel model = new ProjectScanner(app).scan(); + new GitChanges(model).apply("main"); + + assertEquals("M", model.filesByPath.get("src/p/Edited.java").change, + "git ends a header with a TAB when the path holds a space"); + assertEquals("M", method(model, "p.Edited", "e", 0).change); + assertEquals("M", model.filesByPath.get("src/p/sub/Moved.java").change, + "a rename with no edit has no hunks but is still a change"); + String diff = FileDiff.of(model, "src/p/New.java"); + int added = diff.split("\\[\"\\+\"", -1).length - 1; + assertEquals(1, added, "only the renamed class line is new: " + diff); + } + + @Test + void highlightsRankAReworkedMethodAboveNewBoilerplate() throws IOException { + File repo = new File(tmp, "hl"); + write(repo, "src/p/Router.java", "package p;\npublic class Router {\n int route(int x) {\n" + + " return send(x);\n }\n int send(int x) {\n return x;\n }\n}\n"); + write(repo, "src/p/Caller.java", "package p;\nclass Caller {\n int go() {\n" + + " return new Router().route(1);\n }\n}\n"); + git(repo, "init", "-q", "-b", "main"); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "base"); + write(repo, "src/p/Router.java", "package p;\npublic class Router {\n int route(int x) {\n" + + " if (x < 0) {\n return drop(x);\n }\n for (int i = 0; i < x; i++) {\n" + + " send(i);\n }\n return send(x);\n }\n int send(int x) {\n" + + " return x;\n }\n int drop(int x) {\n return 0;\n }\n" + + " int getX() {\n return 1;\n }\n}\n"); + + CodeModel model = new ProjectScanner(repo).scan(); + new GitChanges(model).apply("main"); + List items = new Highlights(model).rank(); + + assertFalse(items.isEmpty(), "the reworked method is a highlight"); + Highlights.Item top = items.get(0); + assertEquals("route", top.method.name); + assertEquals("flow", top.kind); + assertEquals("change", top.view); + assertEquals(0, top.decisionsBefore); + assertEquals(2, top.decisionsAfter); + assertTrue(top.stepsAdded >= 4, "if, return, loop and call are new steps: " + top.stepsAdded); + assertTrue(top.newCalls.contains("Router.drop"), String.valueOf(top.newCalls)); + assertTrue(top.ripple.contains("Caller.go"), "an untouched caller elsewhere runs the new code"); + for (Highlights.Item it : items) { + assertFalse("getX".equals(it.method.name) || "drop".equals(it.method.name), + "a new method without branches is not a highlight: " + it.method.name); + } + } + + @Test + void aFlowChartGoesInsideCallbacks() { + String text = "package p;\nclass Cb {\n void load() {\n ask(\"x\", r -> {\n" + + " if (r == null) {\n return;\n }\n use(r);\n" + + " });\n }\n void ask(String q, java.util.function.Consumer c) { }\n" + + " void use(String r) { }\n}\n"; + FlowNode flow = com.codename1.tools.javac.SourceOutliner.flow("Cb.java", text, 3); + assertNotNull(flow); + FlowNode call = flow.getBranches().get(0).get(0); + assertEquals("call", call.getKind()); + assertEquals(1, call.getBranches().size(), "the lambda's body is a branch of the call"); + assertEquals("r ->", call.getBranchLabels().get(0)); + List body = call.getBranches().get(0); + assertEquals("if", body.get(0).getKind()); + assertEquals("call", body.get(1).getKind()); + } + + @Test + void anApprovedMethodLeavesEveryAnswerUntilTheBranchChangesItAgain() throws IOException { + File repo = new File(tmp, "ap"); + write(repo, "src/p/A.java", "package p;\npublic class A {\n int one() {\n return 1;\n }\n" + + " int two() {\n return 2;\n }\n}\n"); + git(repo, "init", "-q", "-b", "main"); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "base"); + write(repo, "src/p/A.java", "package p;\npublic class A {\n int one() {\n return 10;\n }\n" + + " int two() {\n return 20;\n }\n}\n"); + CodeModelSession s = CodeModelSession.open(repo.getPath(), "main"); + String diff = s.ask("diff"); + assertTrue(diff.contains("\"k\":\"p.A#one()\""), diff); + CodeModel.Method one = method(modelOf(s), "p.A", "one", 0); + String fp = modelOf(s).approvals.fingerprint(one); + + s.ask("hide p.A#one()=" + fp); + assertNull(method(modelOf(s), "p.A", "one", 0).change, "approved: no longer a change"); + assertEquals("M", method(modelOf(s), "p.A", "two", 0).change); + assertEquals("M", modelOf(s).filesByPath.get("src/p/A.java").change, "two still changes the file"); + + s.ask("hide p.A#one()=" + fp + "|p.A#two()=" + modelOf(s).approvals.fingerprint(method(modelOf(s), "p.A", + "two", 0))); + assertNull(modelOf(s).filesByPath.get("src/p/A.java").change, "every change approved: the file is quiet"); + + s.ask("hide"); + assertEquals("M", method(modelOf(s), "p.A", "one", 0).change, "showing all brings it back"); + + // Review feedback changes one() again: its old approval no longer matches. + write(repo, "src/p/A.java", "package p;\npublic class A {\n int one() {\n return 11;\n }\n" + + " int two() {\n return 20;\n }\n}\n"); + s.ask("reload"); + s.ask("hide p.A#one()=" + fp); + assertEquals("M", method(modelOf(s), "p.A", "one", 0).change, "changed since approval: back for review"); + } + + @Test + void aFlowDiffCarriesTheCommentsAndCommitsThatExplainIt() throws IOException { + File repo = new File(tmp, "fn"); + write(repo, "src/p/A.java", "package p;\npublic class A {\n int f(Object o) {\n" + + " // the old way\n return 1;\n }\n}\n"); + git(repo, "init", "-q", "-b", "main"); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "base"); + git(repo, "checkout", "-q", "-b", "work"); + write(repo, "src/p/A.java", "package p;\npublic class A {\n int f(Object o) {\n" + + " if (o == null) { // nothing to measure\n return 0;\n }\n" + + " return 2;\n }\n}\n"); + git(repo, "commit", "-q", "-am", "Guard null inputs"); + CodeModelSession s = CodeModelSession.open(repo.getPath(), "main"); + String fd = s.ask("flowdiff p.A#f"); + assertTrue(fd.contains("\"comment\":\"nothing to measure\""), fd); + assertTrue(fd.contains("\"subject\":\"Guard null inputs\""), "the commit that wrote the line: " + fd); + assertTrue(fd.contains("\"oldNotes\":[{\"line\":5,\"comment\":\"the old way\"}]"), + "the removed step's comment comes from the base: " + fd); + assertTrue(fd.contains("\"commits\":[{"), fd); + } + + private static CodeModel modelOf(CodeModelSession s) { + return s.model(); + } +} diff --git a/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/ToolSupport.java b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/ToolSupport.java index 1ae8ac20f9c..ede4d25e091 100644 --- a/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/ToolSupport.java +++ b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/ToolSupport.java @@ -90,6 +90,9 @@ static void register(Project project, ProjectLayout layout, SourceSet main, Code register(project, layout, ext, userProperties, roots, javaRoot, encoding, "certificateWizard", DesktopTool.CERTIFICATE_WIZARD, "Opens the iOS Certificate Wizard for this project"); + register(project, layout, ext, userProperties, roots, javaRoot, encoding, "visualize", + DesktopTool.CODE_VISUALIZER, + "Opens the Code Visualizer on this project; -Pcodevisualizer.base= also shows the branch's changes"); } /// The main source set's Java and Kotlin directories as the build resolved @@ -162,6 +165,8 @@ private static void register(Project project, ProjectLayout layout, CodenameOneE t.getDetached().set(project.getProviders().gradleProperty("spawn").map(Boolean::parseBoolean) .orElse(Boolean.TRUE)); t.getInitialForm().set(project.getProviders().gradleProperty("className")); + t.getBase().set(project.getProviders().gradleProperty("codevisualizer.base")); + t.getMcpPort().set(project.getProviders().gradleProperty("codevisualizer.mcp.port")); t.getToken().set(project.getProviders().gradleProperty("token")); t.getUser().set(project.getProviders().gradleProperty("user")); t.getBaseUrl().set(project.getProviders().gradleProperty("baseUrl") @@ -202,6 +207,17 @@ public abstract static class ToolTask extends Cn1Task { @Optional public abstract Property getInitialForm(); + /// The revision the Code Visualizer compares the branch against. + @Input + @Optional + public abstract Property getBase(); + + /// `-Pcodevisualizer.mcp.port`: the port the visualizer's assistant tools are served + /// on; 8766, or a free one, when unset. + @Input + @Optional + public abstract Property getMcpPort(); + /// A Codename One signing API token for the Certificate Wizard. @Input @Optional @@ -260,6 +276,12 @@ public void open() { if (getInitialForm().isPresent()) { extra.add("-Dgamebuilder.scene=" + getInitialForm().get()); } + } else if (tool == DesktopTool.CODE_VISUALIZER) { + binding.set("root", layout.rootDir().getAbsolutePath()); + binding.set("base", getBase().getOrNull()); + if (getMcpPort().isPresent()) { + extra.add("-Dcodevisualizer.mcp.port=" + getMcpPort().get()); + } } else if (tool == DesktopTool.CERTIFICATE_WIZARD) { File certs = new File(layout.projectDir(), "iosCerts"); ensureDir(certs); @@ -300,6 +322,8 @@ private static DesktopTool toolFor(String name) { return DesktopTool.GUI_BUILDER; case "gameBuilder": return DesktopTool.GAME_BUILDER; + case "visualize": + return DesktopTool.CODE_VISUALIZER; default: return DesktopTool.CERTIFICATE_WIZARD; } diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/OpenCodeVisualizerMojo.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/OpenCodeVisualizerMojo.java new file mode 100644 index 00000000000..4555eb2d224 --- /dev/null +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/OpenCodeVisualizerMojo.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.maven; + +import org.apache.commons.io.FileUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.descriptor.PluginDescriptor; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +/// `mvn cn1:visualize [-Dcodevisualizer.base=master] [-Dcodevisualizer.root=DIR] [-Dcodevisualizer.mcp.port=N]`: opens the +/// Code Visualizer on this project -- charts of its size, change and churn, and package, +/// class, UML, call and flow diagrams that drill down to the lines in a code editor. With +/// `codevisualizer.base`, the views also show what the branch changed since its merge base with that +/// revision, and how far the change reaches through callers. +/// +/// The root defaults to the top level project of the invocation, so running it from a +/// generated application's root covers every module. The visualizer always serves its +/// assistant tools over MCP, on `codevisualizer.mcp.port` or else 8766 (a free port when +/// that is taken), and writes the port to `target/cn1-visualizer.port` under the root for +/// the project skill's `Sim.java --visualizer`. +@Mojo(name = "visualize", aggregator = true, requiresProject = false) +public class OpenCodeVisualizerMojo extends AbstractCN1Mojo { + private static final String LAUNCHED_KEY = "com.codename1.maven.OpenCodeVisualizerMojo.launched"; + + /// How the visualizer starts, shared with the Gradle plugin's `visualize` task. + private static final DesktopTool TOOL = DesktopTool.CODE_VISUALIZER; + + @Parameter(defaultValue = "${session}", readonly = true) + private MavenSession guardSession; + + @Parameter(defaultValue = "${plugin}", readonly = true) + private PluginDescriptor guardPlugin; + + /// The revision the branch is compared against; none shows the code alone. + @Parameter(property = "codevisualizer.base", required = false) + private String base; + + /// The directory to index, when not the top level project. + @Parameter(property = "codevisualizer.root", required = false) + private File root; + + /// The loopback port the assistant tools are served on; 8766, or a free one, by default. + @Parameter(property = "codevisualizer.mcp.port", required = false) + private Integer mcpPort; + + @Parameter(property = "codevisualizer.spawn", required = false, defaultValue = "true") + private boolean spawn; + + @Override + protected void executeImpl() throws MojoExecutionException, MojoFailureException { + Map context = guardContext(); + if (context != null && Boolean.TRUE.equals(context.get(LAUNCHED_KEY))) { + return; + } + if (context != null) { + context.put(LAUNCHED_KEY, Boolean.TRUE); + } + File dir = root != null ? root : topLevelDir(); + // The desktop tools' binding format (`ProjectDescriptor.format`): one raw key=value a + // line, no escape sequences, so a Windows path is written as it is. + StringBuilder binding = new StringBuilder("# Codename One Code Visualizer binding\n"); + binding.append("root=").append(dir.getAbsolutePath()).append('\n'); + if (base != null && base.trim().length() > 0) { + binding.append("base=").append(base.trim()).append('\n'); + } + File input = new File(TOOL.runtimeDir(), "codevisualizer-" + java.util.UUID.randomUUID() + ".input"); + try { + FileUtils.write(input, binding.toString(), StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new MojoExecutionException("Failed to write the visualizer binding", ex); + } + List classpath = resolveDesktopTool(TOOL, pluginVersion(), + "To work on the visualizer itself, run it from its module:\n" + + " scripts/code-visualizer.sh --root DIR [--base REF]"); + getLog().info("Launching Codename One Code Visualizer on " + dir + + (base == null ? "" : " against " + base)); + launchDesktopTool(TOOL, classpath, input, dir, spawn, + mcpPort == null ? null : java.util.Collections.singletonList("-Dcodevisualizer.mcp.port=" + mcpPort)); + } + + private File topLevelDir() { + if (guardSession != null && guardSession.getTopLevelProject() != null + && guardSession.getTopLevelProject().getBasedir() != null) { + return guardSession.getTopLevelProject().getBasedir(); + } + return project != null && project.getBasedir() != null ? project.getBasedir() : new File("."); + } + + /// One map per invocation, as `OpenGuiBuilderMojo` keys its guard: the goal is an + /// aggregator, but a reactor that binds it would still reach it once per project. + private Map guardContext() { + if (guardSession == null || guardPlugin == null) { + return getPluginContext(); + } + MavenProject top = guardSession.getTopLevelProject(); + return top == null ? getPluginContext() : guardSession.getPluginContext(guardPlugin, top); + } + + private String pluginVersion() { + if (pluginArtifacts != null) { + for (Artifact a : pluginArtifacts) { + if ("codenameone-maven-plugin".equals(a.getArtifactId()) + && "com.codenameone".equals(a.getGroupId())) { + return a.getVersion(); + } + } + } + return "8.0-SNAPSHOT"; + } +} diff --git a/maven/core-unittests/src/test/java/com/codename1/components/CoachMarksTest.java b/maven/core-unittests/src/test/java/com/codename1/components/CoachMarksTest.java index 5ffbbed1503..830900cd081 100644 --- a/maven/core-unittests/src/test/java/com/codename1/components/CoachMarksTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/components/CoachMarksTest.java @@ -66,6 +66,27 @@ void stepsAdvanceAndFinish() { assertEquals(1, clicked[0], "the form gets touches back once the tour ends"); } + @FormTest + void anAreaStepLightsOnlyThatPartOfTheTarget() { + Form f = new Form(BoxLayout.y()); + Button a = new Button("A wide button with a long label"); + f.add(a); + f.show(); + CoachMarks tour = new CoachMarks(f).add(a, new com.codename1.ui.geom.Rectangle(4, 2, 10, 6), "Part", + "Just this").add(a, new com.codename1.ui.geom.Rectangle(a.getWidth() + 50, 0, 10, 10), null, + "Off the target"); + tour.show(); + int[] whole = new int[]{a.getWidth(), a.getHeight()}; + int[] lit = tour.litArea(); + assertNotNull(lit); + int pad = com.codename1.ui.CN.convertToPixels(1.5f); + assertEquals(10 + pad * 2, lit[2], "the area's width, padded, not the button's " + whole[0]); + assertEquals(6 + pad * 2, lit[3]); + tour.next(); + assertNull(tour.litArea(), "an area outside the target lights nothing"); + tour.dismiss(); + } + @FormTest void showBeforeTheFormIsShownStillPaints() { Form f = new Form(BoxLayout.y()); diff --git a/maven/core-unittests/src/test/java/com/codename1/ui/CodeEditorTest.java b/maven/core-unittests/src/test/java/com/codename1/ui/CodeEditorTest.java index 6b01910646d..46caaba8d12 100644 --- a/maven/core-unittests/src/test/java/com/codename1/ui/CodeEditorTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/ui/CodeEditorTest.java @@ -118,6 +118,40 @@ void testThirdPartyHighlighterUsedByPureEditor() { } } + @FormTest + void testLineHighlightsAndScrollToLineOnNativePeer() { + CodeEditor editor = showNativeEditor(); + cmds().clear(); + editor.setLineHighlights(Arrays.asList(new CodeLineHighlight(3, 5, 0x00ff00), + new CodeLineHighlight(9, 9, 0xff0000, 120))); + editor.scrollToLine(7); + pump(); + String all = String.join("\n", cmds()); + assertTrue(all.contains("setLineHighlights"), all); + assertTrue(all.contains("\"l\":3") && all.contains("\"el\":5") && all.contains("\"a\":120"), all); + assertTrue(all.contains("scrollToLine"), all); + } + + @FormTest + void testScrollToLineMovesPureEditorCaret() { + implementation.setEditorNativePeerSupported(false); + CodeEditor editor = new CodeEditor("java", "a\nbb\nccc\ndddd\n"); + Form f = new Form("code", new BorderLayout()); + f.add(BorderLayout.CENTER, editor); + f.show(); + pump(); + com.codename1.ui.editor.CodeView view = (com.codename1.ui.editor.CodeView) editor.getComponentAt(0); + editor.setLineHighlights(Arrays.asList(new CodeLineHighlight(2, 3, 0x00ff00))); + editor.scrollToLine(3); + pump(); + assertEquals(5, view.getCaretOffset(), "start of line 3"); + editor.scrollToLine(99); + pump(); + assertTrue(view.getCaretOffset() >= 12, "past the end goes to the last line"); + editor.setLineHighlights(null); + pump(); + } + @FormTest void testReadOnlyMapsToEditable() { CodeEditor editor = showNativeEditor(); diff --git a/maven/core-unittests/src/test/java/com/codename1/ui/graph/NodeGraphTest.java b/maven/core-unittests/src/test/java/com/codename1/ui/graph/NodeGraphTest.java index e827bbc9276..b25c3443bb8 100644 --- a/maven/core-unittests/src/test/java/com/codename1/ui/graph/NodeGraphTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/ui/graph/NodeGraphTest.java @@ -183,6 +183,25 @@ public boolean edgeCreating(NodeGraph graph, GraphNode s, GraphPort sp, GraphNod assertTrue(m.getEdges().isEmpty()); } + @FormTest + void aRestingPointerShowsTheTooltipUnderItAndAPressHidesIt() { + DefaultGraphModel m = twoBoxes(); + GraphEdge e = m.addEdge("a", "b"); + e.setTooltip("a calls b"); + m.getNode("a").setTooltip("box a"); + NodeGraph g = show(m); + Component c = g.canvas(); + c.pointerHover(new int[]{c.getAbsoluteX() + 190}, new int[]{c.getAbsoluteY() + 45}); + assertEquals("a calls b", g.getVisibleTooltip(), "the edge under the pointer"); + g.hoverAt(60, 40); + assertEquals("box a", g.getVisibleTooltip(), "a node wins over the background"); + g.hoverAt(310, 40); + assertNull(g.getVisibleTooltip(), "b has no tooltip"); + g.hoverAt(60, 40); + tap(g, 60, 40); + assertNull(g.getVisibleTooltip(), "a press hides it"); + } + @FormTest void tappingAnEdgeSelectsItAndDeleteRemovesIt() { DefaultGraphModel m = twoBoxes(); diff --git a/maven/javase/src/test/java/com/codename1/impl/javase/JavaSEPortEditorBoundsTest.java b/maven/javase/src/test/java/com/codename1/impl/javase/JavaSEPortEditorBoundsTest.java new file mode 100644 index 00000000000..ba9a61f11ba --- /dev/null +++ b/maven/javase/src/test/java/com/codename1/impl/javase/JavaSEPortEditorBoundsTest.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl.javase; + +import java.awt.Font; +import java.awt.Rectangle; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/// The native text editor sits over its field in AWT points. Its bounds are also where +/// AWT delivers mouse events, so bounds left in Codename One pixels made a multi-line +/// editor in a Retina dialog twice its size and it swallowed the clicks meant for the +/// dialog's buttons. +class JavaSEPortEditorBoundsTest { + + @Test + void boundsAreInPointsOfTheCanvas() { + Rectangle r = JavaSEPort.editorBounds(63, 155, 2382, 312, 10, 20, 10, 20, 2.0); + assertEquals(new Rectangle(41, 82, 1171, 146), r); + } + + @Test + void unscaledCanvasKeepsPixels() { + Rectangle r = JavaSEPort.editorBounds(10, 20, 300, 40, 2, 4, 2, 4, 1.0); + assertEquals(new Rectangle(14, 22, 292, 36), r); + } + + @Test + void fontIsInPointsOfTheCanvas() { + Font f = JavaSEPort.editorFont(new Font("Dialog", Font.PLAIN, 28), 2.0); + assertEquals(14f, f.getSize2D(), 0.001f); + } +} diff --git a/maven/pom.xml b/maven/pom.xml index beb4acee4a7..bc516fa4173 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -141,6 +141,7 @@ linux parparvm javac + code-model + com.codenameonecodenameone-core + com.codenameonecodenameone-javase + com.codenameonecodenameone-code-model${cn1.version} + org.junit.jupiterjunit-jupiter-api5.10.2test + org.junit.jupiterjunit-jupiter-engine5.10.2test + + executable-jarjavase + + org.codehaus.mojoproperties-maven-plugin1.0.0initializeread-project-properties${basedir}/../common/codenameone_settings.properties + com.codenameonecodenameone-maven-plugin${cn1.plugin.version}generate-desktop-app-wrappergenerate-sourcesgenerate-desktop-app-wrapper + org.apache.maven.pluginsmaven-dependency-plugincopy-dependenciesprepare-packagecopy-dependencies${project.build.directory}/libsruntime + org.apache.maven.pluginsmaven-jar-plugintruelibs/com.codename1.codevisualizer.CodeVisualizerLauncherCodename One Code VisualizerCodename One Code Visualizer${project.version} + + + diff --git a/scripts/code-visualizer/javase/src/desktop/java/com/codename1/codevisualizer/CodeVisualizerLauncher.java b/scripts/code-visualizer/javase/src/desktop/java/com/codename1/codevisualizer/CodeVisualizerLauncher.java new file mode 100644 index 00000000000..da4f61f6d6d --- /dev/null +++ b/scripts/code-visualizer/javase/src/desktop/java/com/codename1/codevisualizer/CodeVisualizerLauncher.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.codevisualizer; + +/// The executable jar's entry point. +public final class CodeVisualizerLauncher { + private CodeVisualizerLauncher() { + } + + public static void main(String[] args) throws Exception { + CodeVisualizerStub.main(args); + } +} diff --git a/scripts/code-visualizer/javase/src/desktop/java/com/codename1/codevisualizer/CodeVisualizerStub.java b/scripts/code-visualizer/javase/src/desktop/java/com/codename1/codevisualizer/CodeVisualizerStub.java new file mode 100644 index 00000000000..12481828d0b --- /dev/null +++ b/scripts/code-visualizer/javase/src/desktop/java/com/codename1/codevisualizer/CodeVisualizerStub.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.codevisualizer; + +import com.codename1.impl.javase.JavaSEPort; +import com.codename1.ui.Display; + +import java.awt.Toolkit; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +/// Starts the visualizer on the JavaSE port. +/// +/// What to index comes from the binding file `cn1:visualize` writes, named by the +/// `codevisualizer.input` property: raw `key=value` lines, `root` (required) and `base`. +/// Without one, `codevisualizer.root` and `codevisualizer.base` are read, then the +/// current directory. +/// +/// The assistant tools are always served: on `codevisualizer.mcp.port` when it is set, +/// else on 8766, or on a free port when 8766 is taken. The port is written to +/// `target/cn1-visualizer.port` under the indexed root (`build/` in a Gradle project), +/// where the skill's `Sim.java --visualizer` reads it, and removed when the window closes. +public final class CodeVisualizerStub implements Runnable { + static final String APP_DISPLAY_NAME = "Codename One Code Visualizer"; + private static final String APP_STORAGE_NAME = "CodenameOneCodeVisualizer"; + private static JFrame frame; + + /// The port an assistant reaches the visualizer on when none is asked for. + static final int DEFAULT_MCP_PORT = 8766; + + public static void main(String[] args) throws IOException { + String root = System.getProperty("codevisualizer.root"); + String base = System.getProperty("codevisualizer.base"); + String input = System.getProperty("codevisualizer.input"); + if (input != null && input.length() > 0) { + for (String line : Files.readAllLines(new File(input).toPath(), StandardCharsets.UTF_8)) { + int eq = line.indexOf('='); + if (eq <= 0) { + continue; + } + String key = line.substring(0, eq).trim(); + String value = line.substring(eq + 1); + if ("root".equals(key)) { + root = value; + } else if ("base".equals(key)) { + base = value; + } + } + } + if (root == null || root.length() == 0) { + root = new File(".").getAbsolutePath(); + } + CodeVisualizer.setService(new LocalModelService(root, base)); + + System.setProperty("apple.awt.application.name", APP_DISPLAY_NAME); + System.setProperty("com.apple.mrj.application.apple.menu.about.name", APP_DISPLAY_NAME); + System.setProperty("sun.awt.application.name", APP_DISPLAY_NAME); + System.setProperty("sun.awt.X11.XWMClass", APP_STORAGE_NAME); + if (System.getProperty("codename1.arg.desktop.themeMode") == null) { + // The platform's own look (Aqua, Fluent, Adwaita), light and dark. + System.setProperty("codename1.arg.desktop.themeMode", "native"); + } + JavaSEPort.setNativeTheme("/NativeTheme.res"); + JavaSEPort.blockMonitors(); + JavaSEPort.setAppHomeDir("." + APP_STORAGE_NAME); + JavaSEPort.setExposeFilesystem(true); + JavaSEPort.setTablet(true); + JavaSEPort.setUseNativeInput(true); + JavaSEPort.setShowEDTViolationStacks(false); + JavaSEPort.setShowEDTWarnings(false); + JavaSEPort.setDesktopTitleBarMode("native"); + JavaSEPort.setDesktopInteractiveScrollbars(true); + JavaSEPort.setFontFaces(File.separatorChar == '\\' ? "ArialUnicodeMS" : "Arial", "SansSerif", "Monospaced"); + frame = new JFrame(APP_DISPLAY_NAME); + JavaSEPort.setDefaultPixelMilliRatio(Toolkit.getDefaultToolkit().getScreenResolution() / 25.4 + * JavaSEPort.getRetinaScale()); + Display.init(frame.getContentPane()); + Display.getInstance().setProperty("AppName", APP_DISPLAY_NAME); + String asked = System.getProperty("codevisualizer.mcp.port"); + int port = -1; + if (asked != null && asked.trim().length() > 0) { + try { + port = Integer.parseInt(asked.trim()); + } catch (NumberFormatException e) { + System.err.println("codevisualizer.mcp.port is not a number: " + asked + "; choosing one"); + } + } + if (port <= 0) { + port = choosePort(); + } + Display.getInstance().setProperty("codevisualizer.mcp.port", String.valueOf(port)); + publishPort(new File(root), port); + SwingUtilities.invokeLater(new CodeVisualizerStub()); + } + + private static int choosePort() throws IOException { + if (isFree(DEFAULT_MCP_PORT)) { + return DEFAULT_MCP_PORT; + } + try (java.net.ServerSocket s = new java.net.ServerSocket(0, 1, java.net.InetAddress.getLoopbackAddress())) { + return s.getLocalPort(); + } + } + + private static boolean isFree(int port) { + try (java.net.ServerSocket s = new java.net.ServerSocket(port, 1, java.net.InetAddress.getLoopbackAddress())) { + return true; + } catch (IOException taken) { + return false; + } + } + + /// Writes the port where an assistant in the project finds it. A project with a + /// Gradle build and no Maven one keeps its output in `build/`. + private static void publishPort(File root, int port) { + boolean gradle = !new File(root, "pom.xml").isFile() + && (new File(root, "build.gradle").isFile() || new File(root, "build.gradle.kts").isFile()); + final String written = port + "\n"; + final File file = new File(new File(root, gradle ? "build" : "target"), "cn1-visualizer.port"); + try { + Files.createDirectories(file.getParentFile().toPath()); + Files.write(file.toPath(), written.getBytes(StandardCharsets.US_ASCII)); + } catch (IOException e) { + System.err.println("Could not write " + file + ": " + e); + return; + } + Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { + @Override + public void run() { + // A second window on the same root may have written its own port since. + try { + if (written.equals(new String(Files.readAllBytes(file.toPath()), StandardCharsets.US_ASCII))) { + Files.delete(file.toPath()); + } + } catch (IOException gone) { + // Already removed. + } + } + }, "cn1-visualizer-port-file")); + } + + @Override + public void run() { + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setLocationByPlatform(true); + frame.getContentPane().setPreferredSize(new java.awt.Dimension(1440, 900)); + frame.pack(); + frame.setVisible(true); + Display.getInstance().callSerially(new Runnable() { + @Override + public void run() { + CodeVisualizer app = new CodeVisualizer(); + app.init(this); + app.start(); + } + }); + } +} diff --git a/scripts/code-visualizer/javase/src/desktop/java/com/codename1/codevisualizer/LocalModelService.java b/scripts/code-visualizer/javase/src/desktop/java/com/codename1/codevisualizer/LocalModelService.java new file mode 100644 index 00000000000..2e2da0e0a11 --- /dev/null +++ b/scripts/code-visualizer/javase/src/desktop/java/com/codename1/codevisualizer/LocalModelService.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.codevisualizer; + +import com.codename1.tools.codemodel.CodeModelSession; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.concurrent.atomic.AtomicReference; + +/// Answers the visualizer's requests in process, from a `CodeModelSession`. +/// +/// The tree is indexed on the first request, which arrives on a worker thread, so the +/// window is up and saying so while a large tree is parsed. The session is not thread +/// safe and the UI and the MCP tools ask from different threads, so every request is +/// serialised here. +final class LocalModelService implements ModelService { + private final String root; + private final String base; + private CodeModelSession session; + /// Calls followed out from a change when tracing its impact (the CLI default). + private static final int IMPACT_DEPTH = 4; + private String openFailure; + private final AtomicReference phase = new AtomicReference(); + + LocalModelService(String root, String base) throws IOException { + this.root = new File(root).getCanonicalPath(); + this.base = base == null || base.trim().length() == 0 ? null : base.trim(); + } + + @Override + public synchronized String ask(String request) { + if (session == null && openFailure == null) { + try { + session = CodeModelSession.open(root, base, IMPACT_DEPTH, true, new ArrayList(), + (what, done, total) -> phase.set(total > 0 ? what + " (" + done + " of " + total + ")" : what)); + phase.set(null); + } catch (IOException | RuntimeException e) { + openFailure = "Cannot index " + root + ": " + e; + } + } + if (session == null) { + return "{\"error\":" + quote(openFailure) + "}"; + } + return session.ask(request); + } + + @Override + public String read(String path) throws IOException { + File f = new File(root, path).getCanonicalFile(); + // A path from the model is relative to the root; anything that resolves outside it + // (an MCP caller's "../..") is refused rather than read. + String inside = root.endsWith(File.separator) ? root : root + File.separator; + if (!f.getPath().startsWith(inside)) { + throw new IOException("outside the indexed root: " + path); + } + return new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8); + } + + @Override + public String getRoot() { + return root; + } + + @Override + public String progress() { + return phase.get(); + } + + @Override + public String getBase() { + return base; + } + + private static String quote(String s) { + StringBuilder b = new StringBuilder("\""); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '"' || c == '\\') { + b.append('\\').append(c); + } else if (c < 0x20) { + b.append(' '); + } else { + b.append(c); + } + } + return b.append('"').toString(); + } +} diff --git a/scripts/code-visualizer/javase/src/test/java/com/codename1/codevisualizer/RealRepoShots.java b/scripts/code-visualizer/javase/src/test/java/com/codename1/codevisualizer/RealRepoShots.java new file mode 100644 index 00000000000..978b216e015 --- /dev/null +++ b/scripts/code-visualizer/javase/src/test/java/com/codename1/codevisualizer/RealRepoShots.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.codevisualizer; + +import com.codename1.mcp.MCP; +import com.codename1.ui.Display; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import javax.swing.JPanel; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/// Screenshots of a real repository, for a person to look at: run by hand with +/// `-Dtest=RealRepoShots -Dcv.realRepo=/path/to/repo [-Dcv.realBase=master] +/// [-Dcv.realViews=graph;file:PATH;...]`. Skipped otherwise, so the build never +/// depends on a checkout being present. Images land in `target/real-screens`. +class RealRepoShots { + private static int requestId; + + @Test + void shoot() throws Exception { + String repo = System.getProperty("cv.realRepo"); + assumeTrue(repo != null && repo.length() > 0, "set cv.realRepo to run"); + String base = System.getProperty("cv.realBase", "master"); + System.setProperty("codename1.arg.desktop.themeMode", "native"); + com.codename1.impl.javase.JavaSEPort.setNativeTheme("/NativeTheme.res"); + CodeVisualizer.setService(new LocalModelService(repo, base)); + if (!Display.isInitialized()) { + Display.init(new JPanel()); + } + Display.getInstance().callSeriallyAndWait(() -> { + // The first-launch tour would cover every view these tests drive and shoot. + com.codename1.io.Preferences.set("cv.tourShown", true); + app = new CodeVisualizer(); + app.init(null); + app.start(); + }); + waitFor("summary", 600000); + Thread.sleep(1500); + shot("home"); + if (Boolean.getBoolean("cv.dumpGraph")) { + Display.getInstance().callSeriallyAndWait(() -> dump(app().getCurrentCenter())); + } + // The shot resizes the form, which queues a refit; paint again once it has run. + Thread.sleep(500); + shot("home"); + String views = System.getProperty("cv.realViews", ""); + int n = 0; + for (String v : views.split(";")) { + if (v.trim().length() == 0) { + continue; + } + int colon = v.indexOf(':'); + String view = colon < 0 ? v.trim() : v.substring(0, colon).trim(); + String target = colon < 0 ? "" : v.substring(colon + 1).trim(); + String r = callRaw("visualizer_show", "{\"view\":\"" + view + "\",\"target\":\"" + target + "\"}"); + System.out.println("[real] " + v + " -> " + r.substring(0, Math.min(300, r.length()))); + Thread.sleep(1500); + shot((++n) + "-" + view + "-" + target.replaceAll("[^A-Za-z0-9.]+", "_")); + } + int k = 0; + for (String select : System.getProperty("cv.select", "").split(";")) { + if (select.trim().length() == 0) { + continue; + } + if (select.trim().startsWith("commit=")) { + String sha = select.trim().substring(7); + Display.getInstance().callSeriallyAndWait(() -> app().focusOn("all".equals(sha) ? null : sha)); + } else if (select.trim().startsWith("view=")) { + callRaw("visualizer_show", "{\"view\":\"" + select.trim().substring(5) + "\"}"); + } else if (select.trim().startsWith("dark=")) { + boolean dark = Boolean.parseBoolean(select.trim().substring(5)); + Display.getInstance().callSeriallyAndWait(() -> app().setDark(dark)); + } else { + Display.getInstance().callSeriallyAndWait(() -> selectIn(app().getCurrentCenter(), select.trim())); + } + Thread.sleep(Long.getLong("cv.wait", 4000)); + if (k == 0) { + for (String u : new String[]{"VizPanelTitle", "VizCommitSubject", "VizDetailText", "VizCardTitle"}) { + com.codename1.ui.plaf.Style st = com.codename1.ui.plaf.UIManager.getInstance().getComponentStyle(u); + System.out.println("[uiid] " + u + " " + st.getFont().getHeight() + " ttf=" + st.getFont().isTTFNativeFont()); + } + Display.getInstance().callSeriallyAndWait(() -> fonts(app().getCurrentCenter())); + } + shot("selected-" + (++k)); + } + } + + private static CodeVisualizer app; + + private static CodeVisualizer app() { + return app; + } + + private static void selectIn(com.codename1.ui.Component c, String id) { + if (c instanceof com.codename1.ui.graph.NodeGraph) { + com.codename1.ui.graph.NodeGraph g = (com.codename1.ui.graph.NodeGraph) c; + if (id.startsWith("hover:") && edgeById(g, id.substring(6)) != null) { + com.codename1.graph.GraphEdge e = edgeById(g, id.substring(6)); + for (int y = 0; y < g.getHeight(); y += 3) { + for (int x = 0; x < g.getWidth(); x += 3) { + if (g.edgeAt(x, y) == e && g.nodeAt(x, y) == null) { + g.hoverAt(x, y); + return; + } + } + } + } else if (id.indexOf('>') > 0 && edgeById(g, id) != null) { + g.selectEdge(edgeById(g, id)); + } else if (g.getModel().getNode(id) != null) { + g.select(g.getModel().getNode(id)); + } + } else if (c instanceof com.codename1.ui.Container) { + for (int i = 0; i < ((com.codename1.ui.Container) c).getComponentCount(); i++) { + selectIn(((com.codename1.ui.Container) c).getComponentAt(i), id); + } + } + } + + private static void fonts(com.codename1.ui.Component c) { + if (c instanceof com.codename1.ui.Label || c instanceof com.codename1.ui.TextArea) { + System.out.println("[font] " + c.getUIID() + " " + c.getStyle().getFont().getHeight() + " " + + c.getUnselectedStyle().getFont().getHeight()); + } + if (c instanceof com.codename1.ui.Container) { + for (int i = 0; i < ((com.codename1.ui.Container) c).getComponentCount(); i++) { + fonts(((com.codename1.ui.Container) c).getComponentAt(i)); + } + } + } + + private static void dump(com.codename1.ui.Component c) { + if (c instanceof com.codename1.ui.graph.NodeGraph) { + com.codename1.ui.graph.NodeGraph g = (com.codename1.ui.graph.NodeGraph) c; + System.out.println("[graph] size " + g.getWidth() + "x" + g.getHeight() + " zoom " + g.getZoom() + + " view " + g.getViewX()); + for (com.codename1.graph.GraphNode n : g.getModel().getNodes()) { + System.out.println("[graph] " + n.getId() + " " + n.getX() + "," + n.getY()); + } + } else if (c instanceof com.codename1.ui.Container) { + for (int i = 0; i < ((com.codename1.ui.Container) c).getComponentCount(); i++) { + dump(((com.codename1.ui.Container) c).getComponentAt(i)); + } + } + } + + private static void shot(String name) throws Exception { + Path dir = new File("target/real-screens").toPath(); + Files.createDirectories(dir); + final String file = dir.resolve(name + ".png").toString(); + Display.getInstance().callSeriallyAndWait(() -> { + com.codename1.ui.Form f = Display.getInstance().getCurrent(); + f.setSize(new com.codename1.ui.geom.Dimension(1800, 1100)); + f.layoutContainer(); + f.revalidate(); + com.codename1.ui.Image img = com.codename1.ui.Image.createImage(1800, 1100, 0xff000000); + f.paintComponent(img.getGraphics(), true); + try (java.io.OutputStream o = new java.io.FileOutputStream(file)) { + com.codename1.ui.util.ImageIO.getImageIO().save(img, o, com.codename1.ui.util.ImageIO.FORMAT_PNG, 1f); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + } + + private static void waitFor(String view, long ms) throws Exception { + long deadline = System.currentTimeMillis() + ms; + while (System.currentTimeMillis() < deadline) { + Map s = Data.parse(callRaw("visualizer_state", "{}")); + if (view.equals(s.get("view"))) { + return; + } + Thread.sleep(250); + } + } + + private static String callRaw(String tool, String args) { + String response = MCP.getServer().handleMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (++requestId) + + ",\"method\":\"tools/call\",\"params\":{\"name\":\"" + tool + "\",\"arguments\":" + args + "}}"); + Map result = Data.map(Data.parse(response), "result"); + if (result == null) { + return response; + } + return Data.s(Data.maps(result, "content").get(0), "text", "{}"); + } + + private static com.codename1.graph.GraphEdge edgeById(com.codename1.ui.graph.NodeGraph g, String id) { + for (com.codename1.graph.GraphEdge e : g.getModel().getEdges()) { + if (id.equals(e.getId())) { + return e; + } + } + return null; + } +} diff --git a/scripts/code-visualizer/javase/src/test/java/com/codename1/codevisualizer/VisualizerToolsTest.java b/scripts/code-visualizer/javase/src/test/java/com/codename1/codevisualizer/VisualizerToolsTest.java new file mode 100644 index 00000000000..9d60384857f --- /dev/null +++ b/scripts/code-visualizer/javase/src/test/java/com/codename1/codevisualizer/VisualizerToolsTest.java @@ -0,0 +1,703 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.codevisualizer; + +import com.codename1.mcp.MCP; +import com.codename1.ui.Component; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.chart.Chart; +import com.codename1.ui.Display; +import com.codename1.ui.graph.NodeGraph; +import com.codename1.graph.GraphEdge; +import com.codename1.graph.GraphNode; +import com.codename1.graph.GraphShapes; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import javax.swing.JPanel; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// Drives the visualizer the way an assistant does -- JSON-RPC into its MCP tools -- over a +/// small git repository with one change, and checks what each view put on screen. +class VisualizerToolsTest { + private static CodeVisualizer app; + private static int requestId; + + private static Path fixture; + + @AfterAll + static void deleteFixture() throws IOException { + if (fixture != null) { + try (java.util.stream.Stream all = Files.walk(fixture)) { + all.sorted(java.util.Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } + } + } + + @BeforeAll + static void start() throws Exception { + Path root = Files.createTempDirectory("cvtest"); + fixture = root; + Path src = root.resolve("src/p"); + Files.createDirectories(src); + write(src.resolve("Shape.java"), "package p;\npublic interface Shape {\n double area();\n}\n"); + write(src.resolve("Square.java"), "package p;\npublic class Square implements Shape {\n" + + " private double side;\n public double area() {\n return side * side;\n }\n}\n"); + write(src.resolve("Report.java"), "package p;\npublic class Report {\n" + + " public String describe(Shape s) {\n return \"area \" + s.area();\n }\n}\n"); + git(root, "init", "-q"); + git(root, "-c", "user.email=t@t", "-c", "user.name=t", "add", "."); + git(root, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "-m", "one"); + write(src.resolve("Circle.java"), "package p;\n/// A round shape.\npublic class Circle implements Shape {\n" + + " private double r;\n /// The area, pi r squared.\n public double area() {\n" + + " return Math.PI * r * r;\n }\n public double radius() {\n return r;\n }\n}\n"); + git(root, "add", "src/p/Circle.java"); + git(root, "-c", "user.email=t@t", "-c", "user.name=Ada", "commit", "-q", "-m", + "Add Circle, a round shape\n\nThe first shape with a radius."); + // The second change stays uncommitted: the working tree is a commit of its own. + write(src.resolve("Report.java"), "package p;\npublic class Report {\n" + + " public String describe(Shape s) {\n if (s == null) {\n return \"none\";\n" + + " }\n if (s instanceof Circle) {\n" + + " return \"circle \" + ((Circle) s).radius(); // a reader checks the radius\n" + + " }\n return \"area: \" + s.area();\n }\n}\n"); + CodeVisualizer.setService(new LocalModelService(root.toString(), "HEAD~1")); + // The look the desktop app ships with, so the screenshots show what a user sees. + System.setProperty("codename1.arg.desktop.themeMode", "native"); + com.codename1.impl.javase.JavaSEPort.setNativeTheme("/NativeTheme.res"); + if (!Display.isInitialized()) { + Display.init(new JPanel()); + } + Display.getInstance().callSeriallyAndWait(() -> { + // The first-launch tour would cover every view these tests drive and shoot. + com.codename1.io.Preferences.set("cv.tourShown", true); + app = new CodeVisualizer(); + app.init(null); + app.start(); + }); + Map state = waitFor("summary"); + assertEquals("summary", state.get("view"), "the app never finished starting: " + state + " summary " + + callRaw("visualizer_model", "{\"request\":\"summary\"}")); + } + + @Test + void theModelToolAnswersTheBranchsChanges() throws Exception { + Map diff = call("visualizer_model", "{\"request\":\"diff\"}"); + assertEquals(2, Data.maps(diff, "files").size(), String.valueOf(diff)); + for (Map f : Data.maps(diff, "files")) { + assertEquals(Data.s(f, "p", "").endsWith("Circle.java") ? "A" : "M", Data.s(f, "ch"), String.valueOf(f)); + } + } + + @Test + void eachViewShowsWhatItNames() throws Exception { + call("visualizer_show", "{\"view\":\"graph\"}"); + NodeGraph changes = find(center(), NodeGraph.class); + assertNotNull(changes, "the home view is the change graph"); + assertEquals("modified", changes.getModel().getNode("p.Report").getStyleKey(), "Report changed"); + assertEquals("added", changes.getModel().getNode("p.Circle").getStyleKey(), "Circle is new"); + assertEquals("plain", changes.getModel().getNode("p.Shape").getStyleKey(), "Shape is unchanged context"); + Display.getInstance().callSeriallyAndWait(() -> changes.select(changes.getModel().getNode("p.Circle"))); + Label why = null; + for (int i = 0; i < 100 && why == null; i++) { + Thread.sleep(100); + why = findLabelStarting(center(), "Add Circle, a round shape"); + } + assertNotNull(why, "selecting a class shows the commit that wrote it"); + Button diffButton = findButton(center(), "Diff"); + assertNotNull(diffButton, "each changed method has its diff in place"); + press(diffButton); + DiffView inline = null; + for (int i = 0; i < 100 && inline == null; i++) { + Thread.sleep(100); + inline = find(center(), DiffView.class); + } + assertNotNull(inline, "the diff opens beside the graph"); + shot("graph-class"); + GraphEdge reportCircle = edgeById(changes, "p.Report>p.Circle"); + assertNotNull(reportCircle, "the new call is an arrow"); + assertTrue(reportCircle.getTooltip() != null && reportCircle.getTooltip().contains("a reader checks the radius"), + "the arrow's tooltip quotes the comment at the call: " + reportCircle.getTooltip()); + Display.getInstance().callSeriallyAndWait(() -> changes.selectEdge(reportCircle)); + Label callNote = null; + for (int i = 0; i < 100 && callNote == null; i++) { + Thread.sleep(100); + callNote = findLabelStarting(center(), "a reader checks the radius"); + } + assertNotNull(callNote, "selecting an arrow shows the comment at each new call"); + assertNotNull(findLabelStarting(center(), "Uncommitted"), "and the commit that added it"); + shot("graph-edge"); + GraphEdge reportShape = edgeById(changes, "p.Report>p.Shape"); + assertNotNull(reportShape, "Report calls Shape"); + Display.getInstance().callSeriallyAndWait(() -> changes.selectEdge(reportShape)); + Thread.sleep(1500); + assertEquals(changes, find(center(), NodeGraph.class), "the graph stays on screen"); + call("visualizer_show", "{\"view\":\"file\",\"target\":\"src/p/Circle.java\"}"); + Button signature = null; + for (int i = 0; i < 100 && signature == null; i++) { + Thread.sleep(100); + signature = findButton(center(), "double area()"); + } + assertNotNull(signature, "a new file opens on its outline"); + shot("outline"); + + Map queue = call("visualizer_show", "{\"view\":\"queue\"}"); + assertEquals("queue", queue.get("view")); + shot("queue"); + // The toolbar's mode switch really navigates, and the sidebar is gone. + press((Button) findNamed(Display.getInstance().getCurrent(), "Graph")); + assertEquals("graph", waitFor("graph").get("view"), "the Graph mode opens the change graph"); + press((Button) findNamed(Display.getInstance().getCurrent(), "Summary")); + assertEquals("summary", waitFor("summary").get("view"), "the Summary mode opens the summary"); + com.codename1.ui.chart.Chart chart = null; + for (int i = 0; i < 100 && chart == null; i++) { + Thread.sleep(100); + chart = find(center(), com.codename1.ui.chart.Chart.class); + } + shot("summary"); + assertNotNull(chart, "the summary charts the change: " + center()); + for (Button c : buttons(Display.getInstance().getCurrent())) { + assertFalse("Changed files".equals(c.getText()), "no sidebar rows remain"); + } + + Map file = call("visualizer_show", "{\"view\":\"file\",\"target\":\"src/p/Report.java\"," + + "\"note\":\"the null guard\"}"); + assertEquals("file", file.get("view"), String.valueOf(file)); + assertEquals("the null guard", file.get("note")); + DiffView diff = find(center(), DiffView.class); + assertNotNull(diff, "a file opens as a diff"); + assertArrayEquals(new int[]{7, 1, 0}, diff.rowCounts(), "seven lines added, one removed, nothing folded"); + shot("file"); + + Map method = call("visualizer_show", "{\"view\":\"method\",\"target\":\"p.Report#describe\"}"); + assertEquals("method", method.get("view"), String.valueOf(method)); + assertArrayEquals(new int[]{7, 1, 0}, find(center(), DiffView.class).rowCounts()); + + Map flow = call("visualizer_show", "{\"view\":\"flow\",\"target\":\"p.Report#describe\"}"); + assertEquals("flow", flow.get("view"), String.valueOf(flow)); + boolean decision = false; + boolean changed = false; + for (GraphNode n : find(center(), NodeGraph.class).getModel().getNodes()) { + decision |= GraphShapes.DECISION.equals(n.getShape()); + changed |= "added".equals(n.getStyleKey()); + } + assertTrue(decision, "the if is a diamond"); + assertTrue(changed, "the added lines are marked"); + shot("flow"); + + Map change = call("visualizer_show", "{\"view\":\"change\",\"target\":\"p.Report#describe\"}"); + assertEquals("change", change.get("view"), String.valueOf(change)); + List sides = new java.util.ArrayList(); + all(center(), NodeGraph.class, sides); + assertEquals(2, sides.size(), "before and after side by side"); + assertTrue(styled(sides.get(0), "removed"), "the old return is red on the left"); + assertTrue(styled(sides.get(1), "added"), "the new guard is green on the right"); + assertFalse(styled(sides.get(0), "added"), "nothing is added to the old version"); + shot("change"); + + Map calls = call("visualizer_show", "{\"view\":\"calls\",\"target\":\"p.Report#describe\"}"); + assertEquals("calls", calls.get("view")); + NodeGraph cg = find(center(), NodeGraph.class); + assertNotNull(cg.getModel().getNode("self")); + String callees = cg.getModel().getNode("out0").getLabel() + " " + cg.getModel().getNode("out1").getLabel(); + assertTrue(callees.contains("Shape.area") && callees.contains("Circle.radius"), "the callees are on the right: " + + callees); + shot("calls"); + + Map uml = call("visualizer_show", "{\"view\":\"type\",\"target\":\"p.Square\"}"); + assertNull(uml.get("warning"), String.valueOf(uml)); + NodeGraph g = find(center(), NodeGraph.class); + assertTrue(g.getModel().getNode("self") instanceof UmlRenderer.UmlNode); + assertEquals("Shape", g.getModel().getNode("up0").getLabel(), "the interface is above the box"); + shot("type"); + + assertNotNull(findNamed(Display.getInstance().getCurrent(), "Back"), "the toolbar has a Back button"); + Map back = call("visualizer_back", "{}"); + assertEquals("calls", back.get("view")); + List trail = Data.list(back, "trail"); + assertEquals("Report.describe", trail.get(trail.size() - 1), "back returns to the method: " + back); + // The trail is shared by every test in this class, so only its end says anything here. + assertFalse("Report.describe".equals(trail.get(trail.size() - 2)), + "a method's tabs are one step of history: " + back); + + Map members = call("visualizer_show", "{\"view\":\"members\",\"target\":\"src/p/Report.java\"}"); + assertEquals("members", members.get("view"), String.valueOf(members)); + assertTrue(styled(find(center(), NodeGraph.class), "modified"), "describe is the changed member"); + shot("members"); + + Map map = call("visualizer_show", "{\"view\":\"map\"}"); + assertEquals("map", map.get("view")); + assertNotNull(find(center(), Chart.class), "the change map is a chart"); + Thread.sleep(1500); + shot("map"); + + Map light = call("visualizer_settings", "{\"theme\":\"light\",\"fontScale\":1.5}"); + assertEquals("light", light.get("theme"), String.valueOf(light)); + assertEquals(1.5, ((Number) light.get("fontScale")).doubleValue(), 0.001); + call("visualizer_show", "{\"view\":\"file\",\"target\":\"src/p/Report.java\"}"); + shot("file-light-large"); + call("visualizer_settings", "{\"theme\":\"dark\",\"fontScale\":1.25}"); + } + + @Test + void highlightsLeadWithTheMethodWhoseFlowChanged() throws Exception { + Map h = call("visualizer_model", "{\"request\":\"highlights\"}"); + List> items = Data.maps(h, "items"); + assertFalse(items.isEmpty(), String.valueOf(h)); + Map top = items.get(0); + assertEquals("describe", Data.s(top, "n"), "Report.describe gained two decisions: " + h); + assertEquals("flow", Data.s(top, "kind")); + assertEquals("change", Data.s(top, "view")); + assertEquals(2, Data.i(top, "da", 0)); + + Map shown = call("visualizer_show", "{\"view\":\"highlights\"}"); + assertEquals("highlights", shown.get("view"), String.valueOf(shown)); + assertNotNull(findLabelStarting(center(), "HIGHLIGHT 1 OF"), "the strip counts the highlights"); + List graphs = new ArrayList(); + all(center(), NodeGraph.class, graphs); + assertEquals(2, graphs.size(), "a changed flow shows its chart before and after"); + assertTrue(styled(graphs.get(1), "added"), "the new decisions are green on the right"); + // The shot resizes the form, which queues a refit; paint again once it has run. + shot("highlights"); + Thread.sleep(800); + shot("highlights"); + } + + @Test + void approvingAChangeHidesItUntilShownAgain() throws Exception { + Map d = call("visualizer_model", "{\"request\":\"diff\"}"); + Map describe = null; + for (Map m : Data.maps(d, "methods")) { + if ("describe".equals(Data.s(m, "n"))) { + describe = m; + } + } + assertNotNull(describe, String.valueOf(d)); + final String key = Data.s(describe, "k"); + final String fp = Data.s(describe, "h"); + assertEquals("p.Report#describe(Shape)", key); + try { + Display.getInstance().callSeriallyAndWait(() -> { + app.approve(key, fp); + if (!Approvals.isHiding()) { + app.toggleApproved(); + } + }); + Thread.sleep(1500); + Map hidden = call("visualizer_model", "{\"request\":\"highlights\"}"); + assertTrue(Data.maps(hidden, "items").isEmpty(), "the approved method is not a highlight: " + hidden); + Map d2 = call("visualizer_model", "{\"request\":\"diff\"}"); + for (Map m : Data.maps(d2, "methods")) { + assertFalse("describe".equals(Data.s(m, "n")), "approved: out of the diff"); + } + } finally { + Display.getInstance().callSeriallyAndWait(() -> { + app.revoke(key); + if (Approvals.isHiding()) { + app.toggleApproved(); + } + }); + Thread.sleep(1500); + } + Map back = call("visualizer_model", "{\"request\":\"highlights\"}"); + assertFalse(Data.maps(back, "items").isEmpty(), "showing everything brings it back: " + back); + } + + @Test + void anApprovalOfOlderCodeComesBackChanged() throws Exception { + Map d = call("visualizer_model", "{\"request\":\"diff\"}"); + Map describe = null; + for (Map m : Data.maps(d, "methods")) { + if ("describe".equals(Data.s(m, "n"))) { + describe = m; + } + } + assertNotNull(describe, String.valueOf(d)); + final Map item = describe; + final String key = Data.s(describe, "k"); + final String stale = "0" + Data.s(describe, "h"); + final String[] text = new String[1]; + try { + // Approved at a fingerprint the code no longer has: a later commit changed it. + Display.getInstance().callSeriallyAndWait(() -> { + app.approvals().approve(key, stale); + text[0] = Approvals.button(app, item).getText(); + }); + assertTrue(text[0].startsWith("Changed Since Approval"), text[0]); + Display.getInstance().callSeriallyAndWait(() -> { + if (!Approvals.isHiding()) { + app.toggleApproved(); + } + }); + Thread.sleep(1500); + boolean listed = false; + for (Map m : Data.maps(call("visualizer_model", "{\"request\":\"diff\"}"), "methods")) { + listed |= "describe".equals(Data.s(m, "n")); + } + assertTrue(listed, "changed since approval: still listed while approved changes are hidden"); + } finally { + Display.getInstance().callSeriallyAndWait(() -> { + app.revoke(key); + if (Approvals.isHiding()) { + app.toggleApproved(); + } + }); + Thread.sleep(1500); + } + } + + @Test + void anAssistantListensAndExplainsInPlace() throws Exception { + Map none = call("visualizer_listen", "{\"timeoutSeconds\":1}"); + assertEquals("false", String.valueOf(none.get("asked")), String.valueOf(none)); + call("visualizer_show", "{\"view\":\"flow\",\"target\":\"p.Report#describe\"}"); + NodeGraph g = find(center(), NodeGraph.class); + assertNotNull(g); + final String nodeId = g.getModel().getNodes().get(1).getId(); + final String[] id = new String[1]; + Display.getInstance().callSeriallyAndWait(() -> { + Map element = new java.util.LinkedHashMap(); + element.put("type", "node"); + element.put("node", nodeId); + id[0] = app.asker().submit(element, "Why is this check here?"); + }); + Map asked = call("visualizer_listen", "{\"timeoutSeconds\":5}"); + Map q = Data.map(asked, "question"); + assertNotNull(q, String.valueOf(asked)); + assertEquals(id[0], Data.s(q, "id")); + assertEquals("Why is this check here?", Data.s(q, "question")); + assertEquals(nodeId, Data.s(Data.map(q, "element"), "node")); + Thread.sleep(400); + String busy = workingText(); + assertNotNull(busy, "the window shows the question is being worked on"); + assertTrue(busy.contains("working on"), busy); + + Map shown = call("visualizer_explain", "{\"questionId\":\"" + id[0] + "\",\"text\":" + + "\"A null shape has no area.\",\"steps\":[{\"text\":\"First the null check\"}]," + + "\"diagram\":{\"nodes\":[{\"id\":\"a\",\"label\":\"caller\"},{\"id\":\"b\"," + + "\"label\":\"describe\",\"style\":\"modified\"}],\"edges\":[{\"from\":\"a\",\"to\":\"b\"}]}}"); + assertEquals("shown with 1 steps", Data.s(shown, "explained"), String.valueOf(shown)); + final boolean[] open = new boolean[1]; + Display.getInstance().callSeriallyAndWait(() -> open[0] = app.asker().isExplaining()); + assertTrue(open[0], "the callout is on screen"); + assertNull(workingText(), "the answer clears the working indicator"); + Thread.sleep(800); + shot("explain"); + } + + @Test + void anAssistantPointsThingsOutWithCoachMarks() throws Exception { + call("visualizer_show", "{\"view\":\"change\",\"target\":\"p.Report#describe\"}"); + NodeGraph g = find(center(), NodeGraph.class); + assertNotNull(g); + String nodeId = g.getModel().getNodes().get(1).getId(); + Map r = call("visualizer_coach", "{\"steps\":[{\"control\":\"Approved changes\"," + + "\"title\":\"Approvals\",\"text\":\"Hide what you approved\"},{\"node\":\"" + nodeId + + "\",\"text\":\"This decision is new\"},{\"text\":\"The whole view\"}]}"); + assertEquals(3, Data.i(r, "coached", -1), String.valueOf(r)); + final boolean[] up = new boolean[1]; + Display.getInstance().callSeriallyAndWait(() -> up[0] = Tour.isShowing()); + assertTrue(up[0], "the coach marks are on screen"); + Thread.sleep(600); + shot("coach"); + Display.getInstance().callSeriallyAndWait(Tour::dismiss); + } + + @Test + void theTourVisitsTheToolbar() throws Exception { + call("visualizer_show", "{\"view\":\"highlights\",\"target\":\"0\"}"); + final boolean[] up = new boolean[1]; + Display.getInstance().callSeriallyAndWait(() -> { + Tour.show(app); + up[0] = Tour.isShowing(); + }); + assertTrue(up[0]); + Thread.sleep(600); + shot("tour"); + Display.getInstance().callSeriallyAndWait(Tour::dismiss); + } + + @Test + void theFileDiffHoldsBothSides() throws Exception { + Map fd = call("visualizer_model", "{\"request\":\"filediff src/p/Report.java\"}"); + int added = 0; + int removed = 0; + for (Object o : Data.list(fd, "lines")) { + List l = Data.list(o); + if ("+".equals(l.get(0))) { + added++; + } else if ("-".equals(l.get(0))) { + removed++; + assertTrue(String.valueOf(l.get(3)).contains("\"area \""), "the old line is the removed one"); + } + } + assertEquals(7, added, String.valueOf(fd)); + assertEquals(1, removed); + } + + @Test + void sourceOutsideTheRootIsRefused() { + LocalModelService s = (LocalModelService) serviceOf(); + try { + s.read("../../etc/passwd"); + throw new AssertionError("read outside the root"); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains("outside")); + } + } + + private static ModelService serviceOf() { + try { + java.lang.reflect.Field f = CodeVisualizer.class.getDeclaredField("service"); + f.setAccessible(true); + return (ModelService) f.get(null); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + + private static String typeId(String q) throws Exception { + Map t = Data.parse(callRaw("visualizer_model", "{\"request\":\"type " + q + "\"}")); + return String.valueOf(Data.i(t, "id", -1)); + } + + /// The first component of type `type` in `c`, depth first, or null. + private static T find(Component c, Class type) { + if (type.isInstance(c)) { + return type.cast(c); + } + if (c instanceof Container) { + for (Component k : (Container) c) { + T found = find(k, type); + if (found != null) { + return found; + } + } + } + return null; + } + + /// Writes what is on screen to target/screens/NAME.png, for a person to look at. + private static void all(Component c, Class type, List out) { + if (type.isInstance(c)) { + out.add(type.cast(c)); + } + if (c instanceof Container) { + for (Component k : (Container) c) { + all(k, type, out); + } + } + } + + private static boolean styled(NodeGraph g, String style) { + for (GraphNode n : g.getModel().getNodes()) { + if (style.equals(n.getStyleKey())) { + return true; + } + } + return false; + } + + private static void press(final Button b) throws Exception { + Display.getInstance().callSeriallyAndWait(() -> { + b.pressed(); + b.released(); + }); + } + + private static List