mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
006eb12db8 | ||
|
|
4e65887b90 | ||
|
|
7f10a4258e | ||
|
|
e42950b4be | ||
|
|
f5ef1a94fe | ||
|
|
2f45cf7ff2 | ||
|
|
72a291d808 | ||
|
|
9be207f4c5 | ||
|
|
f02f834097 | ||
|
|
7254c470ef | ||
|
|
881ec0b193 | ||
|
|
3490111b96 | ||
|
|
68e67055d8 | ||
|
|
6b315c3b68 | ||
|
|
96d73a8570 | ||
|
|
0d76ffd66d | ||
|
|
6d669ad734 | ||
|
|
055d543117 | ||
|
|
0998abdaf3 | ||
|
|
0d8c521fbe | ||
|
|
c4bbb7e880 | ||
|
|
d919dfe757 | ||
|
|
7c28a53cd1 | ||
|
|
1b9a492a74 | ||
|
|
40c6c6160b | ||
|
|
e5f40a3316 | ||
|
|
f102801059 | ||
|
|
5be9b1fabc | ||
|
|
6ca25e4ea9 | ||
|
|
52e98ea8a3 | ||
|
|
3a80560a68 | ||
|
|
c4f6a2c9c1 | ||
|
|
7fbe440e73 | ||
|
|
557df6917d | ||
|
|
37bf2ade11 | ||
|
|
39f4ccf8e0 | ||
|
|
5acf50c1ef | ||
|
|
e8f18b0ac0 | ||
|
|
8d3a8c2c11 | ||
|
|
3509f0b035 | ||
|
|
591096a817 | ||
|
|
717defb2bb | ||
|
|
34d0b76333 | ||
|
|
497758c273 | ||
|
|
e366e4d64e | ||
|
|
ca70fd8380 | ||
|
|
9dd715e4e9 | ||
|
|
e39fbb8903 |
No files matched your search
@@ -10,3 +10,6 @@ rustflags = [
|
||||
"link-arg=--max-memory=4294967296",
|
||||
"--cfg=web_sys_unstable_apis",
|
||||
]
|
||||
|
||||
[env]
|
||||
CARGO_WORKSPACE_DIR = { value = "", relative = true }
|
||||
@@ -1,7 +1,11 @@
|
||||
name: Profiling Changes
|
||||
|
||||
on:
|
||||
pull_request: {}
|
||||
pull_request:
|
||||
paths:
|
||||
- 'node-graph/**'
|
||||
- 'Cargo.toml'
|
||||
- 'Cargo.lock'
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
@@ -50,14 +54,23 @@ jobs:
|
||||
id: master-sha
|
||||
run: echo "sha=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Get CPU info
|
||||
id: cpu-info
|
||||
run: |
|
||||
# Get CPU model and create a short hash for cache key
|
||||
CPU_MODEL=$(cat /proc/cpuinfo | grep "model name" | head -1 | cut -d: -f2 | xargs)
|
||||
CPU_HASH=$(echo "$CPU_MODEL" | sha256sum | cut -c1-8)
|
||||
echo "cpu-hash=$CPU_HASH" >> $GITHUB_OUTPUT
|
||||
echo "CPU: $CPU_MODEL (hash: $CPU_HASH)"
|
||||
|
||||
- name: Cache benchmark baselines
|
||||
id: cache-benchmark-baselines
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: target/iai
|
||||
key: ${{ runner.os }}-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-benchmark-baselines-master-
|
||||
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-
|
||||
|
||||
- name: Run baseline benchmarks
|
||||
if: steps.cache-benchmark-baselines.outputs.cache-hit != 'true'
|
||||
@@ -85,6 +98,8 @@ jobs:
|
||||
cargo bench --bench run_cached_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
|
||||
|
||||
- name: Make old comments collapsed by default
|
||||
# Only run if we have write permissions (not a fork)
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
github-token: ${{secrets.GITHUB_TOKEN}}
|
||||
@@ -109,7 +124,67 @@ jobs:
|
||||
});
|
||||
}
|
||||
|
||||
- name: Analyze profiling changes
|
||||
id: analyze
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
|
||||
function isSignificantChange(diffPct, absoluteChange, benchmarkType) {
|
||||
const meetsPercentageThreshold = Math.abs(diffPct) > 5;
|
||||
const meetsAbsoluteThreshold = absoluteChange > 200000;
|
||||
const isCachedExecution = benchmarkType === 'run_cached' ||
|
||||
benchmarkType.includes('Cached Execution');
|
||||
|
||||
return isCachedExecution
|
||||
? (meetsPercentageThreshold && meetsAbsoluteThreshold)
|
||||
: meetsPercentageThreshold;
|
||||
}
|
||||
|
||||
const allOutputs = [
|
||||
JSON.parse(fs.readFileSync('/tmp/compile_output.json', 'utf8')),
|
||||
JSON.parse(fs.readFileSync('/tmp/update_output.json', 'utf8')),
|
||||
JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8')),
|
||||
JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8'))
|
||||
];
|
||||
const outputNames = ['compile', 'update', 'run_once', 'run_cached'];
|
||||
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution'];
|
||||
|
||||
let hasSignificantChanges = false;
|
||||
let regressionDetails = [];
|
||||
|
||||
for (let i = 0; i < allOutputs.length; i++) {
|
||||
const benchmarkOutput = allOutputs[i];
|
||||
const outputName = outputNames[i];
|
||||
const sectionTitle = sectionTitles[i];
|
||||
|
||||
for (const benchmark of benchmarkOutput) {
|
||||
if (benchmark.profiles?.[0]?.summaries?.parts?.[0]?.metrics_summary?.Callgrind?.Ir?.diffs?.diff_pct) {
|
||||
const diffPct = parseFloat(benchmark.profiles[0].summaries.parts[0].metrics_summary.Callgrind.Ir.diffs.diff_pct);
|
||||
const oldValue = benchmark.profiles[0].summaries.parts[0].metrics_summary.Callgrind.Ir.metrics.Both[1].Int;
|
||||
const newValue = benchmark.profiles[0].summaries.parts[0].metrics_summary.Callgrind.Ir.metrics.Both[0].Int;
|
||||
const absoluteChange = Math.abs(newValue - oldValue);
|
||||
|
||||
if (isSignificantChange(diffPct, absoluteChange, outputName)) {
|
||||
hasSignificantChanges = true;
|
||||
regressionDetails.push({
|
||||
module_path: benchmark.module_path,
|
||||
id: benchmark.id,
|
||||
diffPct,
|
||||
absoluteChange,
|
||||
sectionTitle
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
core.setOutput('has-significant-changes', hasSignificantChanges);
|
||||
core.setOutput('regression-details', JSON.stringify(regressionDetails));
|
||||
|
||||
- name: Comment PR
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
github-token: ${{secrets.GITHUB_TOKEN}}
|
||||
@@ -121,7 +196,7 @@ jobs:
|
||||
const runOnceOutput = JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8'));
|
||||
const runCachedOutput = JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8'));
|
||||
|
||||
let significantChanges = false;
|
||||
const hasSignificantChanges = '${{ steps.analyze.outputs.has-significant-changes }}' === 'true';
|
||||
let commentBody = "";
|
||||
|
||||
function formatNumber(num) {
|
||||
@@ -145,6 +220,17 @@ jobs:
|
||||
let sectionBody = "";
|
||||
let hasResults = false;
|
||||
let hasSignificantChanges = false;
|
||||
|
||||
function isSignificantChange(diffPct, absoluteChange, benchmarkType) {
|
||||
const meetsPercentageThreshold = Math.abs(diffPct) > 5;
|
||||
const meetsAbsoluteThreshold = absoluteChange > 200000;
|
||||
const isCachedExecution = benchmarkType === 'run_cached' ||
|
||||
benchmarkType.includes('Cached Execution');
|
||||
|
||||
return isCachedExecution
|
||||
? (meetsPercentageThreshold && meetsAbsoluteThreshold)
|
||||
: meetsPercentageThreshold;
|
||||
}
|
||||
|
||||
for (const benchmark of benchmarkOutput) {
|
||||
if (benchmark.profiles && benchmark.profiles.length > 0) {
|
||||
@@ -181,8 +267,8 @@ jobs:
|
||||
}
|
||||
|
||||
sectionBody += "```\n</details>\n\n";
|
||||
|
||||
if (Math.abs(irDiff.diff_pct) > 5) {
|
||||
|
||||
if (isSignificantChange(irDiff.diff_pct, Math.abs(irDiff.new - irDiff.old), sectionTitle)) {
|
||||
significantChanges = true;
|
||||
hasSignificantChanges = true;
|
||||
}
|
||||
@@ -232,7 +318,7 @@ jobs:
|
||||
if (commentBody.length > 0) {
|
||||
const output = `<details open>\n<summary>Performance Benchmark Results</summary>\n\n${commentBody}\n</details>`;
|
||||
|
||||
if (significantChanges) {
|
||||
if (hasSignificantChanges) {
|
||||
github.rest.issues.createComment({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
@@ -246,3 +332,13 @@ jobs:
|
||||
} else {
|
||||
console.log("No benchmark results to display.");
|
||||
}
|
||||
|
||||
- name: Fail on significant regressions
|
||||
if: steps.analyze.outputs.has-significant-changes == 'true'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const regressionDetails = JSON.parse('${{ steps.analyze.outputs.regression-details }}');
|
||||
const firstRegression = regressionDetails[0];
|
||||
|
||||
core.setFailed(`Significant performance regression detected: ${firstRegression.module_path} ${firstRegression.id} increased by ${firstRegression.absoluteChange.toLocaleString()} instructions (${firstRegression.diffPct.toFixed(2)}%)`);
|
||||
@@ -26,6 +26,14 @@ jobs:
|
||||
- name: 📥 Clone and checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# We can remove this step once `ubuntu-latest` has Node.js 22 or newer for its native TypeScript support. See:
|
||||
# https://github.com/actions/runner-images?tab=readme-ov-file#available-images
|
||||
# https://nodejs.org/en/learn/typescript/run-natively
|
||||
- name: 📦 Install the latest Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "latest"
|
||||
|
||||
- name: 🕸 Install Zola
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
@@ -77,7 +85,8 @@ jobs:
|
||||
MODE: prod
|
||||
run: |
|
||||
cd website
|
||||
npm run install-fonts
|
||||
npm ci
|
||||
npm run lint
|
||||
zola --config config.toml build --minify
|
||||
|
||||
- name: 📤 Publish to Cloudflare Pages
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
target/
|
||||
result/
|
||||
*.spv
|
||||
*.exrc
|
||||
perf.data*
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
{ pkgs }:
|
||||
|
||||
let
|
||||
libcef = pkgs.libcef.overrideAttrs (_: _: {
|
||||
postInstall = ''
|
||||
strip $out/lib/*
|
||||
'';
|
||||
});
|
||||
cefPath = pkgs.runCommand "cef-path" {} ''
|
||||
mkdir -p $out
|
||||
|
||||
ln -s ${libcef}/include $out/include
|
||||
find ${libcef}/lib -type f -name "*" -exec ln -s {} $out/ \;
|
||||
find ${libcef}/libexec -type f -name "*" -exec ln -s {} $out/ \;
|
||||
cp -r ${libcef}/share/cef/* $out/
|
||||
|
||||
echo '${builtins.toJSON {
|
||||
type = "minimal";
|
||||
name = builtins.baseNameOf libcef.src.url;
|
||||
sha1 = "";
|
||||
}}' > $out/archive.json
|
||||
'';
|
||||
in
|
||||
{
|
||||
CEF_PATH = cefPath;
|
||||
}
|
||||
Generated
+6
-6
@@ -34,11 +34,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1754214453,
|
||||
"narHash": "sha256-Q/I2xJn/j1wpkGhWkQnm20nShYnG7TI99foDBpXm1SY=",
|
||||
"lastModified": 1762363567,
|
||||
"narHash": "sha256-YRqMDEtSMbitIMj+JLpheSz0pwEr0Rmy5mC7myl17xs=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "5b09dc45f24cf32316283e62aec81ffee3c3e376",
|
||||
"rev": "ae814fd3904b621d8ab97418f1d0f2eb0d3716f4",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -63,11 +63,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1753238793,
|
||||
"narHash": "sha256-jmQeEpgX+++MEgrcikcwoSiI7vDZWLP0gci7XiWb9uQ=",
|
||||
"lastModified": 1762569282,
|
||||
"narHash": "sha256-vINZAJpXQTZd5cfh06Rcw7hesH7sGSvi+Tn+HUieJn8=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "0ad7ab4ca8e83febf147197e65c006dff60623ab",
|
||||
"rev": "a35a6144b976f70827c2fe2f5c89d16d8f9179d8",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
+98
-105
@@ -12,8 +12,6 @@
|
||||
# - Development shell: `nix develop .nix` from the project root
|
||||
# - Run in dev shell with direnv: add `use flake` to .envrc
|
||||
{
|
||||
description = "Development environment and build configuration";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
||||
rust-overlay = {
|
||||
@@ -30,9 +28,7 @@
|
||||
flake-utils.lib.eachDefaultSystem (system:
|
||||
let
|
||||
overlays = [ (import rust-overlay) ];
|
||||
pkgs = import nixpkgs {
|
||||
inherit system overlays;
|
||||
};
|
||||
pkgs = import nixpkgs { inherit system overlays; };
|
||||
|
||||
rustExtensions = [ "rust-src" "rust-analyzer" "clippy" "cargo" ];
|
||||
rust = pkgs.rust-bin.stable.latest.default.override {
|
||||
@@ -40,127 +36,124 @@
|
||||
extensions = rustExtensions;
|
||||
};
|
||||
|
||||
rustGPUToolchainPkg = pkgs.rust-bin.nightly."2025-06-23".default.override {
|
||||
extensions = rustExtensions ++ [ "rustc-dev" "llvm-tools" ];
|
||||
};
|
||||
rustGPUToolchainRustPlatform = pkgs.makeRustPlatform {
|
||||
cargo = rustGPUToolchainPkg;
|
||||
rustc = rustGPUToolchainPkg;
|
||||
};
|
||||
rustc_codegen_spirv = rustGPUToolchainRustPlatform.buildRustPackage (finalAttrs: {
|
||||
pname = "rustc_codegen_spirv";
|
||||
version = "0-unstable-2025-08-04";
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "Rust-GPU";
|
||||
repo = "rust-gpu";
|
||||
rev = "c12f216121820580731440ee79ebc7403d6ea04f";
|
||||
hash = "sha256-rG1cZvOV0vYb1dETOzzbJ0asYdE039UZImobXZfKIno=";
|
||||
};
|
||||
cargoHash = "sha256-AEigcEc5wiBd3zLqWN/2HSbkfOVFneAqNvg9HsouZf4=";
|
||||
cargoBuildFlags = [ "-p" "rustc_codegen_spirv" "--features=use-compiled-tools" "--no-default-features" ];
|
||||
doCheck = false;
|
||||
});
|
||||
rustGpuCargo = pkgs.writeShellScriptBin "cargo" ''
|
||||
#!${pkgs.lib.getExe pkgs.bash}
|
||||
|
||||
filtered_args=()
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
+nightly|+nightly-*) ;;
|
||||
*) filtered_args+=("$arg") ;;
|
||||
esac
|
||||
done
|
||||
|
||||
exec ${rustGPUToolchainPkg}/bin/cargo ${"\${filtered_args[@]}"}
|
||||
'';
|
||||
rustGpuPathOverride = "${rustGpuCargo}/bin:${rustGPUToolchainPkg}/bin";
|
||||
|
||||
libcef = pkgs.libcef.overrideAttrs (finalAttrs: previousAttrs: {
|
||||
version = "139.0.17";
|
||||
gitRevision = "6c347eb";
|
||||
chromiumVersion = "139.0.7258.31";
|
||||
srcHash = "sha256-kRMO8DP4El1qytDsAZBdHvR9AAHXce90nPdyfJailBg=";
|
||||
|
||||
__intentionallyOverridingVersion = true;
|
||||
|
||||
postInstall = ''
|
||||
strip $out/lib/*
|
||||
'';
|
||||
});
|
||||
libcefPath = pkgs.runCommand "libcef-path" {} ''
|
||||
mkdir -p $out
|
||||
|
||||
ln -s ${libcef}/include $out/include
|
||||
find ${libcef}/lib -type f -name "*" -exec ln -s {} $out/ \;
|
||||
find ${libcef}/libexec -type f -name "*" -exec ln -s {} $out/ \;
|
||||
cp -r ${libcef}/share/cef/* $out/
|
||||
|
||||
echo '${builtins.toJSON {
|
||||
type = "minimal";
|
||||
name = builtins.baseNameOf libcef.src.url;
|
||||
sha1 = "";
|
||||
}}' > $out/archive.json
|
||||
'';
|
||||
|
||||
# Shared build inputs - system libraries that need to be in LD_LIBRARY_PATH
|
||||
buildInputs = with pkgs; [
|
||||
# System libraries
|
||||
wayland
|
||||
openssl
|
||||
vulkan-loader
|
||||
libraw
|
||||
libGL
|
||||
# Shared build inputs; libraries that need to be in LD_LIBRARY_PATH
|
||||
buildInputs = [
|
||||
pkgs.wayland
|
||||
pkgs.openssl
|
||||
pkgs.vulkan-loader
|
||||
pkgs.libraw
|
||||
pkgs.libGL
|
||||
|
||||
# X11 libraries, not needed on wayland! Remove when x11 is finally dead
|
||||
libxkbcommon
|
||||
xorg.libXcursor
|
||||
xorg.libxcb
|
||||
xorg.libX11
|
||||
pkgs.libxkbcommon
|
||||
pkgs.xorg.libXcursor
|
||||
pkgs.xorg.libxcb
|
||||
pkgs.xorg.libX11
|
||||
];
|
||||
|
||||
# Development tools that don't need to be in LD_LIBRARY_PATH
|
||||
buildTools = [
|
||||
# Packages needed to build the package
|
||||
buildTools = [
|
||||
rust
|
||||
pkgs.nodejs
|
||||
pkgs.nodePackages.npm
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli
|
||||
pkgs.wasm-bindgen-cli_0_2_100
|
||||
pkgs.wasm-pack
|
||||
pkgs.pkg-config
|
||||
pkgs.git
|
||||
pkgs.cargo-about
|
||||
];
|
||||
|
||||
# Development tools; not needed to build the package
|
||||
devTools = [
|
||||
pkgs.git
|
||||
|
||||
pkgs.cargo-watch
|
||||
pkgs.cargo-nextest
|
||||
pkgs.cargo-expand
|
||||
|
||||
# Linker
|
||||
pkgs.mold
|
||||
];
|
||||
# Development tools that don't need to be in LD_LIBRARY_PATH
|
||||
devTools = with pkgs; [
|
||||
cargo-watch
|
||||
cargo-nextest
|
||||
cargo-expand
|
||||
|
||||
# Profiling tools
|
||||
gnuplot
|
||||
samply
|
||||
cargo-flamegraph
|
||||
pkgs.gnuplot
|
||||
pkgs.samply
|
||||
pkgs.cargo-flamegraph
|
||||
];
|
||||
in
|
||||
{
|
||||
# Development shell configuration
|
||||
devShells.default = pkgs.mkShell {
|
||||
|
||||
cefEnv = import ./cef.nix { inherit pkgs; };
|
||||
rustGPUEnv = import ./rust-gpu.nix { inherit pkgs; };
|
||||
|
||||
libPath = "${pkgs.lib.makeLibraryPath buildInputs}:${cefEnv.CEF_PATH}";
|
||||
in {
|
||||
devShells.default = pkgs.mkShell ({
|
||||
packages = buildInputs ++ buildTools ++ devTools;
|
||||
|
||||
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath buildInputs}:${libcefPath}";
|
||||
CEF_PATH = libcefPath;
|
||||
XDG_DATA_DIRS="${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
||||
|
||||
RUST_GPU_PATH_OVERRIDE = rustGpuPathOverride;
|
||||
RUSTC_CODEGEN_SPIRV_PATH = "${rustc_codegen_spirv}/lib/librustc_codegen_spirv.so";
|
||||
LD_LIBRARY_PATH = libPath;
|
||||
XDG_DATA_DIRS =
|
||||
"${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
|
||||
|
||||
shellHook = ''
|
||||
alias cargo='mold --run cargo'
|
||||
'';
|
||||
};
|
||||
}
|
||||
);
|
||||
} // cefEnv // rustGPUEnv);
|
||||
|
||||
packages.default = pkgs.rustPlatform.buildRustPackage (finalAttrs: {
|
||||
pname = "graphite-editor";
|
||||
version = "unstable";
|
||||
src = pkgs.lib.cleanSource ./..;
|
||||
|
||||
cargoLock = {
|
||||
lockFile = ../Cargo.lock;
|
||||
allowBuiltinFetchGit = true;
|
||||
};
|
||||
|
||||
# TODO: Remove the need for this hash by using individual package resolutions and hashes from package-lock.json
|
||||
npmDeps = pkgs.fetchNpmDeps {
|
||||
inherit (finalAttrs) pname version;
|
||||
src = "${finalAttrs.src}/frontend";
|
||||
hash = "sha256-UWuJpKNYj2Xn34rpMDZ75pzMYUOLQjPeGuJ/QlPbX9A=";
|
||||
};
|
||||
|
||||
npmRoot = "frontend";
|
||||
npmConfigScript = "setup";
|
||||
makeCacheWritable = true;
|
||||
|
||||
buildInputs = buildInputs;
|
||||
nativeBuildInputs = buildTools ++ [
|
||||
pkgs.rustPlatform.cargoSetupHook
|
||||
pkgs.npmHooks.npmConfigHook
|
||||
pkgs.makeWrapper
|
||||
];
|
||||
|
||||
env = cefEnv // rustGPUEnv;
|
||||
|
||||
buildPhase = ''
|
||||
export HOME="$TMPDIR"
|
||||
|
||||
pushd frontend
|
||||
npm run build-native
|
||||
popd
|
||||
cargo build -r -p graphite-desktop
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin
|
||||
cp target/release/graphite-desktop $out/bin/graphite-editor
|
||||
|
||||
mkdir -p $out/share/applications
|
||||
cp $src/desktop/assets/*.desktop $out/share/applications/
|
||||
|
||||
mkdir -p $out/share/icons/hicolor/scalable/apps
|
||||
cp $src/desktop/assets/graphite-icon-color.svg $out/share/icons/hicolor/scalable/apps/
|
||||
'';
|
||||
|
||||
doCheck = false;
|
||||
|
||||
postFixup = ''
|
||||
wrapProgram "$out/bin/graphite-editor" \
|
||||
--prefix LD_LIBRARY_PATH : "${libPath}" \
|
||||
--set CEF_PATH "${cefEnv.CEF_PATH}"
|
||||
'';
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
{ pkgs }:
|
||||
|
||||
let
|
||||
toolchainPkg = pkgs.rust-bin.nightly."2025-06-23".default.override {
|
||||
extensions =
|
||||
[ "rust-src" "rust-analyzer" "clippy" "cargo" "rustc-dev" "llvm-tools" ];
|
||||
};
|
||||
toolchainRustPlatform = pkgs.makeRustPlatform {
|
||||
cargo = toolchainPkg;
|
||||
rustc = toolchainPkg;
|
||||
};
|
||||
rustc_codegen_spirv = toolchainRustPlatform.buildRustPackage (finalAttrs: {
|
||||
pname = "rustc_codegen_spirv";
|
||||
version = "0-unstable-2025-08-04";
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "Firestar99";
|
||||
repo = "rust-gpu-new";
|
||||
rev = "c12f216121820580731440ee79ebc7403d6ea04f";
|
||||
hash = "sha256-rG1cZvOV0vYb1dETOzzbJ0asYdE039UZImobXZfKIno=";
|
||||
};
|
||||
cargoHash = "sha256-AEigcEc5wiBd3zLqWN/2HSbkfOVFneAqNvg9HsouZf4=";
|
||||
cargoBuildFlags = [
|
||||
"-p"
|
||||
"rustc_codegen_spirv"
|
||||
"--features=use-compiled-tools"
|
||||
"--no-default-features"
|
||||
];
|
||||
doCheck = false;
|
||||
});
|
||||
cargoWrapper = pkgs.writeShellScriptBin "cargo" ''
|
||||
#!${pkgs.lib.getExe pkgs.bash}
|
||||
|
||||
filtered_args=()
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
+nightly|+nightly-*) ;;
|
||||
*) filtered_args+=("$arg") ;;
|
||||
esac
|
||||
done
|
||||
|
||||
exec ${toolchainPkg}/bin/cargo ${"\${filtered_args[@]}"}
|
||||
'';
|
||||
in {
|
||||
RUST_GPU_PATH_OVERRIDE = "${cargoWrapper}/bin:${toolchainPkg}/bin";
|
||||
RUSTC_CODEGEN_SPIRV_PATH =
|
||||
"${rustc_codegen_spirv}/lib/librustc_codegen_spirv.so";
|
||||
}
|
||||
Generated
+368
-169
File diff suppressed because it is too large.
Load diff
+19
-13
@@ -3,6 +3,10 @@ members = [
|
||||
"desktop",
|
||||
"desktop/wrapper",
|
||||
"desktop/embedded-resources",
|
||||
"desktop/bundle",
|
||||
"desktop/platform/linux",
|
||||
"desktop/platform/mac",
|
||||
"desktop/platform/win",
|
||||
"editor",
|
||||
"frontend/wasm",
|
||||
"libraries/dyn-any",
|
||||
@@ -28,8 +32,6 @@ members = [
|
||||
"proc-macros",
|
||||
]
|
||||
default-members = [
|
||||
"desktop",
|
||||
"desktop/wrapper",
|
||||
"editor",
|
||||
"frontend/wasm",
|
||||
"libraries/dyn-any",
|
||||
@@ -104,7 +106,7 @@ quote = "1.0"
|
||||
chrono = "0.4"
|
||||
ron = "0.11"
|
||||
fastnoise-lite = "1.1"
|
||||
wgpu = { version = "25.0", features = [
|
||||
wgpu = { version = "27.0", features = [
|
||||
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
|
||||
"fragile-send-sync-non-atomic-wasm",
|
||||
"spirv",
|
||||
@@ -132,11 +134,12 @@ web-sys = { version = "=0.3.77", features = [
|
||||
"HtmlImageElement",
|
||||
"ImageBitmapRenderingContext",
|
||||
] }
|
||||
winit = { git = "https://github.com/rust-windowing/winit.git", rev = "37221c7192ef1deec022a2278e54429331c01bad" }
|
||||
winit = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
keyboard-types = "0.8"
|
||||
url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt"] }
|
||||
vello = { git = "https://github.com/linebender/vello.git", rev = "87cc5bee6d3a34d15017dbbb58634ddc7f33ff9b" } # TODO switch back to stable when a release is made
|
||||
vello_encoding = { git = "https://github.com/linebender/vello.git", rev = "87cc5bee6d3a34d15017dbbb58634ddc7f33ff9b" } # TODO switch back to stable when a release is made
|
||||
vello = { git = "https://github.com/linebender/vello" }
|
||||
vello_encoding = { git = "https://github.com/linebender/vello" }
|
||||
resvg = "0.45"
|
||||
usvg = "0.45"
|
||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||
@@ -175,7 +178,7 @@ syn = { version = "2.0", default-features = false, features = [
|
||||
"extra-traits",
|
||||
"proc-macro",
|
||||
] }
|
||||
kurbo = { version = "0.11", features = ["serde"] }
|
||||
kurbo = { version = "0.12", features = ["serde"] }
|
||||
lyon_geom = "1.0"
|
||||
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
|
||||
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
|
||||
@@ -185,18 +188,18 @@ iai-callgrind = { version = "0.16" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "=139.0.1"
|
||||
cef-dll-sys = "=139.0.1"
|
||||
cef = { version = "141", features = ["accelerated_osr"] }
|
||||
cef-dll-sys = "141"
|
||||
include_dir = "0.7"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
rfd = "0.15"
|
||||
open = "5.3"
|
||||
poly-cool = "0.3"
|
||||
polycool = "0.4"
|
||||
spin = "0.10"
|
||||
clap = "4.5"
|
||||
spirv-std = { git = "https://github.com/rust-gpu/rust-gpu", rev = "c12f216121820580731440ee79ebc7403d6ea04f", features = ["bytemuck"] }
|
||||
cargo-gpu = { git = "https://github.com/rust-gpu/cargo-gpu", rev = "3952a22d16edbd38689f3a876e417899f21e1fe7", default-features = false }
|
||||
spirv-std = { git = "https://github.com/Firestar99/rust-gpu-new", rev = "c12f216121820580731440ee79ebc7403d6ea04f", features = ["bytemuck"] }
|
||||
cargo-gpu = { git = "https://github.com/Firestar99/cargo-gpu", rev = "3952a22d16edbd38689f3a876e417899f21e1fe7", default-features = false }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
|
||||
@@ -207,7 +210,6 @@ opt-level = 1
|
||||
[profile.dev.package]
|
||||
graphite-editor = { opt-level = 1 }
|
||||
graphene-core-shaders = { opt-level = 1 }
|
||||
graphene-core = { opt-level = 1 }
|
||||
graphene-std = { opt-level = 1 }
|
||||
interpreted-executor = { opt-level = 1 } # This is a mitigation for https://github.com/rustwasm/wasm-pack/issues/981 which is needed because the node_registry function is too large
|
||||
graphite-proc-macros = { opt-level = 1 }
|
||||
@@ -224,3 +226,7 @@ debug = true
|
||||
[profile.profiling]
|
||||
inherits = "release"
|
||||
debug = true
|
||||
|
||||
[patch.crates-io]
|
||||
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
|
||||
dpi = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[4388711862172196665,{"inputs":[],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientStops":[[0.3237704918032787,{"red":1.0,"green":0.0,"blue":1.0,"alpha":0.1}],[0.5655737704918032,{"red":0.8901961,"green":0.8117647,"blue":0.39215687,"alpha":1.0}],[0.8155737704918032,{"red":0.0,"green":1.0,"blue":1.0,"alpha":0.5}]]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7624113397561636853,{"inputs":[{"Value":{"tagged_value":{"Graphic":{"element":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":3606681156406984991,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::graphic::SourceNodeIdNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[4388711862172196665,{"inputs":[],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientStops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[0.3237704918032787,{"red":0.23828125,"green":0.0,"blue":0.08377075,"alpha":1.0}],[0.5655737704918032,{"red":0.92578125,"green":0.8676921,"blue":0.5569153,"alpha":1.0}],[0.8155737704918032,{"red":0.17333984,"green":0.625,"blue":0.625,"alpha":1.0}],[1.0,{"red":0.106292725,"green":0.3359375,"blue":0.3359375,"alpha":1.0}]]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64","alias":null}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2","alias":null}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[7624113397561636853,{"inputs":[{"Value":{"tagged_value":{"Graphic":{"element":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":3606681156406984991,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::graphic::SourceNodeIdNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProLine truncated
|
||||
+6
-7
@@ -18,7 +18,7 @@ gpu = ["graphite-desktop-wrapper/gpu"]
|
||||
accelerated_paint = ["accelerated_paint_dmabuf", "accelerated_paint_d3d11", "accelerated_paint_iosurface"]
|
||||
accelerated_paint_dmabuf = ["libc", "ash"]
|
||||
accelerated_paint_d3d11 = ["windows", "ash"]
|
||||
accelerated_paint_iosurface = ["objc2-io-surface", "objc2-metal", "core-foundation"]
|
||||
accelerated_paint_iosurface = ["metal", "objc", "core-foundation"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
@@ -43,6 +43,7 @@ rfd = { workspace = true }
|
||||
open = { workspace = true }
|
||||
rand = { workspace = true, features = ["thread_rng"] }
|
||||
serde = { workspace = true }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
|
||||
# Hardware acceleration dependencies
|
||||
ash = { version = "0.38", optional = true }
|
||||
@@ -65,13 +66,11 @@ windows = { version = "0.58.0", features = [
|
||||
|
||||
# macOS-specific dependencies
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2-io-surface = { version = "0.3", optional = true }
|
||||
objc2-metal = { version = "0.3", optional = true }
|
||||
core-foundation = { version = "0.9", optional = true }
|
||||
muda = { git = "https://github.com/tauri-apps/muda.git", rev = "3f460b8fbaed59cda6d95ceea6904f000f093f15", default-features = false }
|
||||
metal = { version = "0.31.0", optional = true }
|
||||
objc = { version = "0.2", optional = true }
|
||||
core-foundation = { version = "0.10", optional = true }
|
||||
|
||||
# Linux-specific dependencies
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
libc = { version = "0.2", optional = true }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.build-dependencies]
|
||||
winres = "0.1"
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "graphite-desktop-bundle"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Bundle"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[dependencies]
|
||||
cef-dll-sys = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
serde = { workspace = true }
|
||||
plist = { version = "*" }
|
||||
@@ -0,0 +1,10 @@
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-env-changed=CARGO_PROFILE");
|
||||
println!("cargo:rerun-if-env-changed=PROFILE");
|
||||
let profile = std::env::var("CARGO_PROFILE").or_else(|_| std::env::var("PROFILE")).unwrap();
|
||||
println!("cargo:rustc-env=CARGO_PROFILE={profile}");
|
||||
|
||||
println!("cargo:rerun-if-env-changed=DEP_CEF_DLL_WRAPPER_CEF_DIR");
|
||||
let cef_dir = std::env::var("DEP_CEF_DLL_WRAPPER_CEF_DIR").unwrap();
|
||||
println!("cargo:rustc-env=CEF_PATH={cef_dir}");
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
pub(crate) const APP_NAME: &str = "Graphite";
|
||||
|
||||
fn profile_name() -> &'static str {
|
||||
let mut profile = env!("CARGO_PROFILE");
|
||||
if profile == "debug" {
|
||||
profile = "dev";
|
||||
}
|
||||
profile
|
||||
}
|
||||
|
||||
pub(crate) fn profile_path() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_WORKSPACE_DIR")).join(format!("target/{}", env!("CARGO_PROFILE")))
|
||||
}
|
||||
|
||||
pub(crate) fn cef_path() -> PathBuf {
|
||||
PathBuf::from(env!("CEF_PATH"))
|
||||
}
|
||||
|
||||
pub(crate) fn build_bin(package: &str, bin: Option<&str>) -> Result<PathBuf, Box<dyn Error>> {
|
||||
let profile = &profile_name();
|
||||
let mut args = vec!["build", "--package", package, "--profile", profile];
|
||||
if let Some(bin) = bin {
|
||||
args.push("--bin");
|
||||
args.push(bin);
|
||||
}
|
||||
run_command("cargo", &args)?;
|
||||
let profile_path = profile_path();
|
||||
let mut bin_path = if let Some(bin) = bin { profile_path.join(bin) } else { profile_path.join(package) };
|
||||
if cfg!(target_os = "windows") {
|
||||
bin_path.set_extension("exe");
|
||||
}
|
||||
Ok(bin_path)
|
||||
}
|
||||
|
||||
pub(crate) fn run_command(program: &str, args: &[&str]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let status = Command::new(program).args(args).stdout(Stdio::inherit()).stderr(Stdio::inherit()).status()?;
|
||||
if !status.success() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn clean_dir(dir: &Path) {
|
||||
if dir.exists() {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
pub(crate) fn copy_dir(src: &Path, dst: &Path) {
|
||||
fs::create_dir_all(dst).unwrap();
|
||||
for entry in fs::read_dir(src).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
let dst_path = dst.join(entry.file_name());
|
||||
if entry.file_type().unwrap().is_dir() {
|
||||
copy_dir(&entry.path(), &dst_path);
|
||||
} else {
|
||||
fs::copy(entry.path(), &dst_path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use std::error::Error;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
const PACKAGE: &str = "graphite-desktop-platform-linux";
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn Error>> {
|
||||
let app_bin = build_bin(PACKAGE, None)?;
|
||||
|
||||
// TODO: Implement bundling for linux
|
||||
|
||||
// TODO: Consider adding more useful cli
|
||||
if std::env::args().any(|a| a == "open") {
|
||||
run_command(&app_bin.to_string_lossy(), &[]).expect("failed to open app");
|
||||
} else {
|
||||
println!("Binary built and placed at {}", app_bin.to_string_lossy());
|
||||
eprintln!("Bundling for Linux is not yet implemented.");
|
||||
eprintln!("You can still start the app with the `open` subcommand. `cargo run -p graphite-desktop-bundle -- open`");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
const APP_ID: &str = "rs.graphite.GraphiteEditor";
|
||||
|
||||
const PACKAGE: &str = "graphite-desktop-platform-mac";
|
||||
const HELPER_BIN: &str = "graphite-desktop-platform-mac-helper";
|
||||
|
||||
const EXEC_PATH: &str = "Contents/MacOS";
|
||||
const FRAMEWORKS_PATH: &str = "Contents/Frameworks";
|
||||
const FRAMEWORK: &str = "Chromium Embedded Framework.framework";
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn Error>> {
|
||||
let app_bin = build_bin(PACKAGE, None)?;
|
||||
let helper_bin = build_bin(PACKAGE, Some(HELPER_BIN))?;
|
||||
|
||||
let profile_path = profile_path();
|
||||
let app_dir = bundle(&profile_path, &app_bin, &helper_bin);
|
||||
|
||||
// TODO: Consider adding more useful cli
|
||||
if std::env::args().any(|a| a == "open") {
|
||||
let executable_path = app_dir.join(EXEC_PATH).join(APP_NAME);
|
||||
run_command(&executable_path.to_string_lossy(), &[]).expect("failed to open app");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bundle(out_dir: &Path, app_bin: &Path, helper_bin: &Path) -> PathBuf {
|
||||
let app_dir = out_dir.join(APP_NAME).with_extension("app");
|
||||
|
||||
clean_dir(&app_dir);
|
||||
|
||||
create_app(&app_dir, APP_ID, APP_NAME, app_bin, false);
|
||||
|
||||
for helper_type in [None, Some("GPU"), Some("Renderer"), Some("Plugin"), Some("Alerts")] {
|
||||
let helper_id_suffix = helper_type.map(|t| format!(".{t}")).unwrap_or_default();
|
||||
let helper_id = format!("{APP_ID}.helper{helper_id_suffix}");
|
||||
let helper_name_suffix = helper_type.map(|t| format!(" ({t})")).unwrap_or_default();
|
||||
let helper_name = format!("{APP_NAME} Helper{helper_name_suffix}");
|
||||
let helper_app_dir = app_dir.join(FRAMEWORKS_PATH).join(&helper_name).with_extension("app");
|
||||
create_app(&helper_app_dir, &helper_id, &helper_name, helper_bin, true);
|
||||
}
|
||||
|
||||
copy_dir(&cef_path().join(FRAMEWORK), &app_dir.join(FRAMEWORKS_PATH).join(FRAMEWORK));
|
||||
|
||||
app_dir
|
||||
}
|
||||
|
||||
fn create_app(app_dir: &Path, id: &str, name: &str, bin: &Path, is_helper: bool) {
|
||||
fs::create_dir_all(app_dir.join(EXEC_PATH)).unwrap();
|
||||
|
||||
let app_contents_dir: &Path = &app_dir.join("Contents");
|
||||
create_info_plist(app_contents_dir, id, name, is_helper).unwrap();
|
||||
fs::copy(bin, app_dir.join(EXEC_PATH).join(name)).unwrap();
|
||||
}
|
||||
|
||||
fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let info = InfoPlist {
|
||||
cf_bundle_development_region: "en".to_string(),
|
||||
cf_bundle_display_name: exec_name.to_string(),
|
||||
cf_bundle_executable: exec_name.to_string(),
|
||||
cf_bundle_identifier: id.to_string(),
|
||||
cf_bundle_info_dictionary_version: "6.0".to_string(),
|
||||
cf_bundle_name: exec_name.to_string(),
|
||||
cf_bundle_package_type: "APPL".to_string(),
|
||||
cf_bundle_signature: "????".to_string(),
|
||||
cf_bundle_version: "0.0.0".to_string(),
|
||||
cf_bundle_short_version_string: "0.0".to_string(),
|
||||
ls_environment: [("MallocNanoZone".to_string(), "0".to_string())].iter().cloned().collect(),
|
||||
ls_file_quarantine_enabled: true,
|
||||
ls_minimum_system_version: "11.0".to_string(),
|
||||
ls_ui_element: if is_helper { Some("1".to_string()) } else { None },
|
||||
ns_bluetooth_always_usage_description: exec_name.to_string(),
|
||||
ns_supports_automatic_graphics_switching: true,
|
||||
ns_web_browser_publickey_credential_usage_description: exec_name.to_string(),
|
||||
ns_camera_usage_description: exec_name.to_string(),
|
||||
ns_microphone_usage_description: exec_name.to_string(),
|
||||
};
|
||||
|
||||
let plist_file = dir.join("Info.plist");
|
||||
plist::to_file_xml(plist_file, &info)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct InfoPlist {
|
||||
#[serde(rename = "CFBundleDevelopmentRegion")]
|
||||
cf_bundle_development_region: String,
|
||||
#[serde(rename = "CFBundleDisplayName")]
|
||||
cf_bundle_display_name: String,
|
||||
#[serde(rename = "CFBundleExecutable")]
|
||||
cf_bundle_executable: String,
|
||||
#[serde(rename = "CFBundleIdentifier")]
|
||||
cf_bundle_identifier: String,
|
||||
#[serde(rename = "CFBundleInfoDictionaryVersion")]
|
||||
cf_bundle_info_dictionary_version: String,
|
||||
#[serde(rename = "CFBundleName")]
|
||||
cf_bundle_name: String,
|
||||
#[serde(rename = "CFBundlePackageType")]
|
||||
cf_bundle_package_type: String,
|
||||
#[serde(rename = "CFBundleSignature")]
|
||||
cf_bundle_signature: String,
|
||||
#[serde(rename = "CFBundleVersion")]
|
||||
cf_bundle_version: String,
|
||||
#[serde(rename = "CFBundleShortVersionString")]
|
||||
cf_bundle_short_version_string: String,
|
||||
#[serde(rename = "LSEnvironment")]
|
||||
ls_environment: HashMap<String, String>,
|
||||
#[serde(rename = "LSFileQuarantineEnabled")]
|
||||
ls_file_quarantine_enabled: bool,
|
||||
#[serde(rename = "LSMinimumSystemVersion")]
|
||||
ls_minimum_system_version: String,
|
||||
#[serde(rename = "LSUIElement")]
|
||||
ls_ui_element: Option<String>,
|
||||
#[serde(rename = "NSBluetoothAlwaysUsageDescription")]
|
||||
ns_bluetooth_always_usage_description: String,
|
||||
#[serde(rename = "NSSupportsAutomaticGraphicsSwitching")]
|
||||
ns_supports_automatic_graphics_switching: bool,
|
||||
#[serde(rename = "NSWebBrowserPublicKeyCredentialUsageDescription")]
|
||||
ns_web_browser_publickey_credential_usage_description: String,
|
||||
#[serde(rename = "NSCameraUsageDescription")]
|
||||
ns_camera_usage_description: String,
|
||||
#[serde(rename = "NSMicrophoneUsageDescription")]
|
||||
ns_microphone_usage_description: String,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
mod common;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod win;
|
||||
|
||||
fn main() {
|
||||
#[cfg(target_os = "linux")]
|
||||
linux::main().unwrap();
|
||||
#[cfg(target_os = "macos")]
|
||||
mac::main().unwrap();
|
||||
#[cfg(target_os = "windows")]
|
||||
win::main().unwrap();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
const PACKAGE: &str = "graphite-desktop-platform-win";
|
||||
const EXECUTABLE: &str = "graphite-editor.exe";
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn Error>> {
|
||||
let app_bin = build_bin(PACKAGE, None)?;
|
||||
|
||||
let executable = bundle(&profile_path(), &app_bin);
|
||||
|
||||
// TODO: Consider adding more useful cli
|
||||
if std::env::args().any(|a| a == "open") {
|
||||
let executable_path = executable.to_string_lossy();
|
||||
run_command(&executable_path, &[]).expect("failed to open app")
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bundle(out_dir: &Path, app_bin: &Path) -> PathBuf {
|
||||
let app_dir = out_dir.join(APP_NAME);
|
||||
|
||||
clean_dir(&app_dir);
|
||||
|
||||
copy_dir(&cef_path(), &app_dir);
|
||||
|
||||
let bin_path = app_dir.join(EXECUTABLE);
|
||||
fs::copy(app_bin, &bin_path).unwrap();
|
||||
|
||||
bin_path
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-linux"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Linux"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[dependencies]
|
||||
graphite-desktop = { path = "../.." }
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
graphite_desktop::start();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-mac"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Mac"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[[bin]]
|
||||
name = "graphite-desktop-platform-mac-helper"
|
||||
path = "src/helper.rs"
|
||||
|
||||
[dependencies]
|
||||
graphite-desktop = { path = "../.." }
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
graphite_desktop::start_helper();
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
graphite_desktop::start();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "graphite-desktop-platform-win"
|
||||
version = "0.0.0"
|
||||
description = "Graphite Desktop Platform Windows"
|
||||
authors = ["Graphite Authors <[email protected]>"]
|
||||
license = "Apache-2.0"
|
||||
repository = ""
|
||||
edition = "2024"
|
||||
rust-version = "1.87"
|
||||
|
||||
[dependencies]
|
||||
graphite-desktop = { path = "../.." }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.build-dependencies]
|
||||
winres = "0.1"
|
||||
@@ -2,7 +2,7 @@ fn main() {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let mut res = winres::WindowsResource::new();
|
||||
res.set_icon("assets/graphite-icon-color.ico");
|
||||
res.set_icon("../../assets/graphite-icon-color.ico");
|
||||
res.compile().expect("Failed to compile Windows resources");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
#![windows_subsystem = "windows"]
|
||||
fn main() {
|
||||
graphite_desktop::start();
|
||||
}
|
||||
+79
-43
@@ -1,5 +1,6 @@
|
||||
use rfd::AsyncFileDialog;
|
||||
use std::sync::Arc;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::sync::mpsc::Sender;
|
||||
use std::sync::mpsc::SyncSender;
|
||||
@@ -7,27 +8,27 @@ use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::dpi::PhysicalSize;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
use winit::event_loop::ControlFlow;
|
||||
use winit::window::Window;
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::cef;
|
||||
use crate::consts::CEF_MESSAGE_LOOP_MAX_ITERATIONS;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::native_window;
|
||||
use crate::persist::PersistentData;
|
||||
use crate::render::GraphicsState;
|
||||
use graphite_desktop_wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, Platform};
|
||||
use graphite_desktop_wrapper::{DesktopWrapper, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, Platform};
|
||||
use crate::wrapper::{DesktopWrapper, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
cef_context: Box<dyn cef::CefContext>,
|
||||
window: Option<Arc<dyn Window>>,
|
||||
native_window: native_window::NativeWindowHandle,
|
||||
window: Option<Window>,
|
||||
window_scale: f64,
|
||||
cef_schedule: Option<Instant>,
|
||||
cef_window_size_sender: Sender<cef::WindowSize>,
|
||||
cef_view_info_sender: Sender<cef::ViewInfoUpdate>,
|
||||
graphics_state: Option<GraphicsState>,
|
||||
wgpu_context: WgpuContext,
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
@@ -39,15 +40,17 @@ pub(crate) struct App {
|
||||
web_communication_initialized: bool,
|
||||
web_communication_startup_buffer: Vec<Vec<u8>>,
|
||||
persistent_data: PersistentData,
|
||||
launch_documents: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(crate) fn new(
|
||||
cef_context: Box<dyn cef::CefContext>,
|
||||
window_size_sender: Sender<cef::WindowSize>,
|
||||
cef_view_info_sender: Sender<cef::ViewInfoUpdate>,
|
||||
wgpu_context: WgpuContext,
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
launch_documents: Vec<PathBuf>,
|
||||
) -> Self {
|
||||
let rendering_app_event_scheduler = app_event_scheduler.clone();
|
||||
let (start_render_sender, start_render_receiver) = std::sync::mpsc::sync_channel(1);
|
||||
@@ -65,9 +68,10 @@ impl App {
|
||||
Self {
|
||||
cef_context,
|
||||
window: None,
|
||||
window_scale: 1.0,
|
||||
cef_schedule: Some(Instant::now()),
|
||||
graphics_state: None,
|
||||
cef_window_size_sender: window_size_sender,
|
||||
cef_view_info_sender,
|
||||
wgpu_context,
|
||||
app_event_receiver,
|
||||
app_event_scheduler,
|
||||
@@ -78,7 +82,7 @@ impl App {
|
||||
web_communication_initialized: false,
|
||||
web_communication_startup_buffer: Vec::new(),
|
||||
persistent_data,
|
||||
native_window: Default::default(),
|
||||
launch_documents,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +106,7 @@ impl App {
|
||||
let show_dialog = async move { dialog.pick_file().await.map(|f| f.path().to_path_buf()) };
|
||||
|
||||
if let Some(path) = futures::executor::block_on(show_dialog)
|
||||
&& let Ok(content) = std::fs::read(&path)
|
||||
&& let Ok(content) = fs::read(&path)
|
||||
{
|
||||
let message = DesktopWrapperMessage::OpenFileDialogResult { path, content, context };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
@@ -135,7 +139,7 @@ impl App {
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::WriteFile { path, content } => {
|
||||
if let Err(e) = std::fs::write(&path, content) {
|
||||
if let Err(e) = fs::write(&path, content) {
|
||||
tracing::error!("Failed to write file {}: {}", path.display(), e);
|
||||
}
|
||||
}
|
||||
@@ -146,19 +150,19 @@ impl App {
|
||||
}
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::UpdateViewportBounds { x, y, width, height } => {
|
||||
DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
|
||||
if let Some(graphics_state) = &mut self.graphics_state
|
||||
&& let Some(window) = &self.window
|
||||
{
|
||||
let window_size = window.surface_size();
|
||||
|
||||
let viewport_offset_x = x / window_size.width as f32;
|
||||
let viewport_offset_y = y / window_size.height as f32;
|
||||
graphics_state.set_viewport_offset([viewport_offset_x, viewport_offset_y]);
|
||||
let viewport_offset_x = x / window_size.width as f64;
|
||||
let viewport_offset_y = y / window_size.height as f64;
|
||||
graphics_state.set_viewport_offset([viewport_offset_x as f32, viewport_offset_y as f32]);
|
||||
|
||||
let viewport_scale_x = if width != 0.0 { window_size.width as f32 / width } else { 1.0 };
|
||||
let viewport_scale_y = if height != 0.0 { window_size.height as f32 / height } else { 1.0 };
|
||||
graphics_state.set_viewport_scale([viewport_scale_x, viewport_scale_y]);
|
||||
let viewport_scale_x = if width != 0.0 { window_size.width as f64 / width } else { 1.0 };
|
||||
let viewport_scale_y = if height != 0.0 { window_size.height as f64 / height } else { 1.0 };
|
||||
graphics_state.set_viewport_scale([viewport_scale_x as f32, viewport_scale_y as f32]);
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::UpdateOverlays(scene) => {
|
||||
@@ -168,18 +172,17 @@ impl App {
|
||||
}
|
||||
DesktopFrontendMessage::MinimizeWindow => {
|
||||
if let Some(window) = &self.window {
|
||||
window.set_minimized(true);
|
||||
window.minimize();
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::MaximizeWindow => {
|
||||
if let Some(window) = &self.window {
|
||||
let maximized = !window.is_maximized();
|
||||
window.set_maximized(maximized);
|
||||
window.toggle_maximize();
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::DragWindow => {
|
||||
if let Some(window) = &self.window {
|
||||
let _ = window.drag_window();
|
||||
window.start_drag();
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::CloseWindow => {
|
||||
@@ -197,6 +200,14 @@ impl App {
|
||||
DesktopFrontendMessage::PersistenceUpdateDocumentsList { ids } => {
|
||||
self.persistent_data.set_document_order(ids);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
|
||||
self.persistent_data.write_preferences(preferences);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceLoadPreferences => {
|
||||
let preferences = self.persistent_data.load_preferences();
|
||||
let message = DesktopWrapperMessage::LoadPreferences { preferences };
|
||||
responses.push(message);
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceLoadCurrentDocument => {
|
||||
if let Some((id, document)) = self.persistent_data.current_document() {
|
||||
let message = DesktopWrapperMessage::LoadDocument {
|
||||
@@ -232,13 +243,28 @@ impl App {
|
||||
responses.push(message);
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
|
||||
self.persistent_data.write_preferences(preferences);
|
||||
DesktopFrontendMessage::OpenLaunchDocuments => {
|
||||
if self.launch_documents.is_empty() {
|
||||
return;
|
||||
}
|
||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||
let launch_documents = std::mem::take(&mut self.launch_documents);
|
||||
let _ = thread::spawn(move || {
|
||||
for path in launch_documents {
|
||||
tracing::info!("Opening file from command line: {}", path.display());
|
||||
if let Ok(content) = fs::read(&path) {
|
||||
let message = DesktopWrapperMessage::OpenFile { path, content };
|
||||
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
} else {
|
||||
tracing::error!("Failed to read file: {}", path.display());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceLoadPreferences => {
|
||||
let preferences = self.persistent_data.load_preferences();
|
||||
let message = DesktopWrapperMessage::LoadPreferences { preferences };
|
||||
responses.push(message);
|
||||
DesktopFrontendMessage::UpdateMenu { entries } => {
|
||||
if let Some(window) = &self.window {
|
||||
window.update_menu(entries);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -320,23 +346,25 @@ impl App {
|
||||
tracing::info!("Exiting main event loop");
|
||||
event_loop.exit();
|
||||
}
|
||||
AppEvent::MenuEvent { id } => {
|
||||
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::MenuEvent { id });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ApplicationHandler for App {
|
||||
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||
let window_attributes = self.native_window.build(event_loop);
|
||||
let window = Window::new(event_loop, self.app_event_scheduler.clone());
|
||||
|
||||
let window: Arc<dyn Window> = Arc::from(event_loop.create_window(window_attributes).unwrap());
|
||||
|
||||
self.native_window.setup(window.as_ref());
|
||||
|
||||
let graphics_state = GraphicsState::new(window.clone(), self.wgpu_context.clone());
|
||||
self.window_scale = window.scale_factor();
|
||||
let _ = self.cef_view_info_sender.send(cef::ViewInfoUpdate::Scale(self.window_scale));
|
||||
self.cef_context.notify_view_info_changed();
|
||||
|
||||
self.window = Some(window);
|
||||
self.graphics_state = Some(graphics_state);
|
||||
|
||||
tracing::info!("Winit window created and ready");
|
||||
let graphics_state = GraphicsState::new(self.window.as_ref().unwrap(), self.wgpu_context.clone());
|
||||
|
||||
self.graphics_state = Some(graphics_state);
|
||||
|
||||
self.desktop_wrapper.init(self.wgpu_context.clone());
|
||||
|
||||
@@ -362,19 +390,27 @@ impl ApplicationHandler for App {
|
||||
WindowEvent::CloseRequested => {
|
||||
self.app_event_scheduler.schedule(AppEvent::CloseWindow);
|
||||
}
|
||||
WindowEvent::SurfaceResized(size) => {
|
||||
let _ = self.cef_window_size_sender.send(size.into());
|
||||
self.cef_context.notify_of_resize();
|
||||
WindowEvent::SurfaceResized(PhysicalSize { width, height }) => {
|
||||
let _ = self.cef_view_info_sender.send(cef::ViewInfoUpdate::Size {
|
||||
width: width as usize,
|
||||
height: height as usize,
|
||||
});
|
||||
self.cef_context.notify_view_info_changed();
|
||||
if let Some(window) = &self.window {
|
||||
let maximized = window.is_maximized();
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::UpdateMaximized { maximized }));
|
||||
}
|
||||
}
|
||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||
self.window_scale = scale_factor;
|
||||
let _ = self.cef_view_info_sender.send(cef::ViewInfoUpdate::Scale(self.window_scale));
|
||||
self.cef_context.notify_view_info_changed();
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
let Some(ref mut graphics_state) = self.graphics_state else { return };
|
||||
// Only rerender once we have a new UI texture to display
|
||||
if let Some(window) = &self.window {
|
||||
match graphics_state.render(window.as_ref()) {
|
||||
match graphics_state.render(window) {
|
||||
Ok(_) => {}
|
||||
Err(wgpu::SurfaceError::Lost) => {
|
||||
tracing::warn!("lost surface");
|
||||
@@ -389,7 +425,7 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
WindowEvent::DragDropped { paths, .. } => {
|
||||
for path in paths {
|
||||
match std::fs::read(&path) {
|
||||
match fs::read(&path) {
|
||||
Ok(content) => {
|
||||
let message = DesktopWrapperMessage::OpenFile { path, content };
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
|
||||
+71
-36
@@ -14,7 +14,7 @@
|
||||
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::render::FrameBufferRef;
|
||||
use graphite_desktop_wrapper::{WgpuContext, deserialize_editor_message};
|
||||
use crate::wrapper::{WgpuContext, deserialize_editor_message};
|
||||
use std::fs::File;
|
||||
use std::io::{Cursor, Read};
|
||||
use std::path::PathBuf;
|
||||
@@ -32,14 +32,12 @@ mod platform;
|
||||
mod utility;
|
||||
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
mod texture_import;
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
use texture_import::SharedTextureHandle;
|
||||
use cef::osr_texture_import::SharedTextureHandle;
|
||||
|
||||
pub(crate) use context::{CefContext, CefContextBuilder, InitError};
|
||||
|
||||
pub(crate) trait CefEventHandler: Clone + Send + Sync + 'static {
|
||||
fn window_size(&self) -> WindowSize;
|
||||
pub(crate) trait CefEventHandler: Send + Sync + 'static {
|
||||
fn view_info(&self) -> ViewInfo;
|
||||
fn draw<'a>(&self, frame_buffer: FrameBufferRef<'a>);
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
fn draw_gpu(&self, shared_texture: SharedTextureHandle);
|
||||
@@ -50,24 +48,54 @@ pub(crate) trait CefEventHandler: Clone + Send + Sync + 'static {
|
||||
fn schedule_cef_message_loop_work(&self, scheduled_time: Instant);
|
||||
fn initialized_web_communication(&self);
|
||||
fn receive_web_message(&self, message: &[u8]);
|
||||
fn duplicate(&self) -> Self
|
||||
where
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct WindowSize {
|
||||
pub(crate) width: usize,
|
||||
pub(crate) height: usize,
|
||||
pub(crate) struct ViewInfo {
|
||||
width: usize,
|
||||
height: usize,
|
||||
scale: f64,
|
||||
}
|
||||
impl WindowSize {
|
||||
pub(crate) fn new(width: usize, height: usize) -> Self {
|
||||
Self { width, height }
|
||||
impl ViewInfo {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self { width: 1, height: 1, scale: 1. }
|
||||
}
|
||||
pub(crate) fn apply_update(&mut self, update: ViewInfoUpdate) {
|
||||
match update {
|
||||
ViewInfoUpdate::Size { width, height } if width > 0 && height > 0 => {
|
||||
self.width = width;
|
||||
self.height = height;
|
||||
}
|
||||
ViewInfoUpdate::Scale(scale) if scale > 0. => {
|
||||
self.scale = scale;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
pub(crate) fn zoom(&self) -> f64 {
|
||||
self.scale.ln() / 1.2_f64.ln()
|
||||
}
|
||||
pub(crate) fn width(&self) -> usize {
|
||||
self.width
|
||||
}
|
||||
pub(crate) fn height(&self) -> usize {
|
||||
self.height
|
||||
}
|
||||
}
|
||||
impl From<winit::dpi::PhysicalSize<u32>> for WindowSize {
|
||||
fn from(size: winit::dpi::PhysicalSize<u32>) -> Self {
|
||||
Self::new(size.width as usize, size.height as usize)
|
||||
impl Default for ViewInfo {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum ViewInfoUpdate {
|
||||
Size { width: usize, height: usize },
|
||||
Scale(f64),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Resource {
|
||||
pub(crate) reader: ResourceReader,
|
||||
@@ -89,34 +117,33 @@ impl Read for ResourceReader {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CefHandler {
|
||||
wgpu_context: WgpuContext,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
window_size_receiver: Arc<Mutex<WindowSizeReceiver>>,
|
||||
view_info_receiver: Arc<Mutex<ViewInfoReceiver>>,
|
||||
}
|
||||
|
||||
impl CefHandler {
|
||||
pub(crate) fn new(wgpu_context: WgpuContext, app_event_scheduler: AppEventScheduler, window_size_receiver: Receiver<WindowSize>) -> Self {
|
||||
pub(crate) fn new(wgpu_context: WgpuContext, app_event_scheduler: AppEventScheduler, view_info_receiver: Receiver<ViewInfoUpdate>) -> Self {
|
||||
Self {
|
||||
wgpu_context,
|
||||
app_event_scheduler,
|
||||
window_size_receiver: Arc::new(Mutex::new(WindowSizeReceiver::new(window_size_receiver))),
|
||||
view_info_receiver: Arc::new(Mutex::new(ViewInfoReceiver::new(view_info_receiver))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CefEventHandler for CefHandler {
|
||||
fn window_size(&self) -> WindowSize {
|
||||
let Ok(mut guard) = self.window_size_receiver.lock() else {
|
||||
tracing::error!("Failed to lock window_size_receiver");
|
||||
return WindowSize::new(1, 1);
|
||||
fn view_info(&self) -> ViewInfo {
|
||||
let Ok(mut guard) = self.view_info_receiver.lock() else {
|
||||
tracing::error!("Failed to lock view_info_receiver");
|
||||
return ViewInfo::new();
|
||||
};
|
||||
let WindowSizeReceiver { receiver, window_size } = &mut *guard;
|
||||
for new_window_size in receiver.try_iter() {
|
||||
*window_size = new_window_size;
|
||||
let ViewInfoReceiver { receiver, view_info } = &mut *guard;
|
||||
for update in receiver.try_iter() {
|
||||
view_info.apply_update(update);
|
||||
}
|
||||
*window_size
|
||||
*view_info
|
||||
}
|
||||
fn draw<'a>(&self, frame_buffer: FrameBufferRef<'a>) {
|
||||
let width = frame_buffer.width() as u32;
|
||||
@@ -244,17 +271,25 @@ impl CefEventHandler for CefHandler {
|
||||
};
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(desktop_wrapper_message));
|
||||
}
|
||||
}
|
||||
|
||||
struct WindowSizeReceiver {
|
||||
window_size: WindowSize,
|
||||
receiver: Receiver<WindowSize>,
|
||||
}
|
||||
impl WindowSizeReceiver {
|
||||
fn new(window_size_receiver: Receiver<WindowSize>) -> Self {
|
||||
fn duplicate(&self) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Self {
|
||||
window_size: WindowSize { width: 1, height: 1 },
|
||||
receiver: window_size_receiver,
|
||||
wgpu_context: self.wgpu_context.clone(),
|
||||
app_event_scheduler: self.app_event_scheduler.clone(),
|
||||
view_info_receiver: self.view_info_receiver.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ViewInfoReceiver {
|
||||
view_info: ViewInfo,
|
||||
receiver: Receiver<ViewInfoUpdate>,
|
||||
}
|
||||
impl ViewInfoReceiver {
|
||||
fn new(receiver: Receiver<ViewInfoUpdate>) -> Self {
|
||||
Self { view_info: ViewInfo::new(), receiver }
|
||||
}
|
||||
}
|
||||
@@ -8,5 +8,7 @@ pub(crate) const SCROLL_LINE_WIDTH: usize = 40;
|
||||
pub(crate) const SCROLL_SPEED_X: f32 = 3.0;
|
||||
pub(crate) const SCROLL_SPEED_Y: f32 = 3.0;
|
||||
|
||||
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.0;
|
||||
|
||||
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
|
||||
@@ -1,3 +1,4 @@
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
mod multithreaded;
|
||||
mod singlethreaded;
|
||||
|
||||
@@ -9,7 +10,7 @@ pub(crate) trait CefContext {
|
||||
|
||||
fn handle_window_event(&mut self, event: &winit::event::WindowEvent);
|
||||
|
||||
fn notify_of_resize(&self);
|
||||
fn notify_view_info_changed(&self);
|
||||
|
||||
fn send_web_message(&self, message: Vec<u8>);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use cef::args::Args;
|
||||
use cef::sys::{CEF_API_VERSION_LAST, cef_resultcode_t};
|
||||
use cef::{
|
||||
App, BrowserSettings, CefString, Client, DictionaryValue, ImplCommandLine, ImplRequestContext, RenderHandler, RequestContextSettings, SchemeHandlerFactory, Settings, WindowInfo, api_hash,
|
||||
App, BrowserSettings, CefString, Client, DictionaryValue, ImplCommandLine, ImplRequestContext, RequestContextSettings, SchemeHandlerFactory, Settings, WindowInfo, api_hash,
|
||||
browser_host_create_browser_sync, execute_process,
|
||||
};
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::cef::CefEventHandler;
|
||||
use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
|
||||
use crate::cef::dirs::create_instance_dir;
|
||||
use crate::cef::input::InputState;
|
||||
use crate::cef::internal::{BrowserProcessAppImpl, BrowserProcessClientImpl, RenderHandlerImpl, RenderProcessAppImpl, SchemeHandlerFactoryImpl};
|
||||
use crate::cef::internal::{BrowserProcessAppImpl, BrowserProcessClientImpl, RenderProcessAppImpl, SchemeHandlerFactoryImpl};
|
||||
|
||||
pub(crate) struct CefContextBuilder<H: CefEventHandler> {
|
||||
pub(crate) args: Args,
|
||||
@@ -25,12 +25,23 @@ unsafe impl<H: CefEventHandler> Send for CefContextBuilder<H> {}
|
||||
|
||||
impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::new_inner(false)
|
||||
}
|
||||
|
||||
pub(crate) fn new_helper() -> Self {
|
||||
Self::new_inner(true)
|
||||
}
|
||||
|
||||
fn new_inner(helper: bool) -> Self {
|
||||
#[cfg(target_os = "macos")]
|
||||
let _loader = {
|
||||
let loader = library_loader::LibraryLoader::new(&std::env::current_exe().unwrap(), false);
|
||||
let loader = cef::library_loader::LibraryLoader::new(&std::env::current_exe().unwrap(), helper);
|
||||
assert!(loader.load());
|
||||
loader
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = helper;
|
||||
|
||||
let _ = api_hash(CEF_API_VERSION_LAST, 0);
|
||||
|
||||
let args = Args::new();
|
||||
@@ -62,39 +73,48 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn initialize(self, event_handler: H) -> Result<impl CefContext, InitError> {
|
||||
let instance_dir = create_instance_dir();
|
||||
|
||||
let settings = Settings {
|
||||
fn common_settings(instance_dir: &Path) -> Settings {
|
||||
Settings {
|
||||
windowless_rendering_enabled: 1,
|
||||
multi_threaded_message_loop: 0,
|
||||
external_message_pump: 1,
|
||||
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
|
||||
cache_path: CefString::from(""),
|
||||
disable_signal_handlers: 1,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
let instance_dir = create_instance_dir();
|
||||
|
||||
let exe = std::env::current_exe().expect("cannot get current exe path");
|
||||
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
|
||||
|
||||
let settings = Settings {
|
||||
main_bundle_path: CefString::from(app_root.to_str().unwrap()),
|
||||
multi_threaded_message_loop: 0,
|
||||
external_message_pump: 1,
|
||||
no_sandbox: 1, // GPU helper crashes when running with sandbox
|
||||
..Self::common_settings(&instance_dir)
|
||||
};
|
||||
|
||||
self.initialize_inner(&event_handler, settings)?;
|
||||
|
||||
create_browser(event_handler, instance_dir)
|
||||
create_browser(event_handler, instance_dir, disable_gpu_acceleration)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(crate) fn initialize(self, event_handler: H) -> Result<impl CefContext, InitError> {
|
||||
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
|
||||
let instance_dir = create_instance_dir();
|
||||
|
||||
let settings = Settings {
|
||||
windowless_rendering_enabled: 1,
|
||||
multi_threaded_message_loop: 1,
|
||||
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
|
||||
cache_path: CefString::from(""),
|
||||
..Default::default()
|
||||
..Self::common_settings(&instance_dir)
|
||||
};
|
||||
|
||||
self.initialize_inner(&event_handler, settings)?;
|
||||
|
||||
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir) {
|
||||
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir, disable_gpu_acceleration) {
|
||||
Ok(context) => {
|
||||
super::multithreaded::CONTEXT.with(|b| {
|
||||
*b.borrow_mut() = Some(context);
|
||||
@@ -111,7 +131,7 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
|
||||
fn initialize_inner(self, event_handler: &H, settings: Settings) -> Result<(), InitError> {
|
||||
// Attention! Wrapping this in an extra App is necessary, otherwise the program still compiles but segfaults
|
||||
let mut cef_app = App::new(BrowserProcessAppImpl::new(event_handler.clone()));
|
||||
let mut cef_app = App::new(BrowserProcessAppImpl::new(event_handler.duplicate()));
|
||||
|
||||
let result = cef::initialize(Some(self.args.as_main_args()), Some(&settings), Some(&mut cef_app), std::ptr::null_mut());
|
||||
if result != 1 {
|
||||
@@ -125,14 +145,20 @@ impl<H: CefEventHandler> CefContextBuilder<H> {
|
||||
}
|
||||
}
|
||||
|
||||
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf) -> Result<SingleThreadedCefContext, InitError> {
|
||||
let render_handler = RenderHandler::new(RenderHandlerImpl::new(event_handler.clone()));
|
||||
let mut client = Client::new(BrowserProcessClientImpl::new(render_handler, event_handler.clone()));
|
||||
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, disable_gpu_acceleration: bool) -> Result<SingleThreadedCefContext, InitError> {
|
||||
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
|
||||
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
let use_accelerated_paint = if disable_gpu_acceleration {
|
||||
false
|
||||
} else {
|
||||
crate::cef::platform::should_enable_hardware_acceleration()
|
||||
};
|
||||
|
||||
let window_info = WindowInfo {
|
||||
windowless_rendering_enabled: 1,
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
shared_texture_enabled: if crate::cef::platform::should_enable_hardware_acceleration() { 1 } else { 0 },
|
||||
shared_texture_enabled: use_accelerated_paint as i32,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -153,7 +179,7 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf) -
|
||||
return Err(InitError::RequestContextCreationFailed);
|
||||
};
|
||||
|
||||
let mut scheme_handler_factory = SchemeHandlerFactory::new(SchemeHandlerFactoryImpl::new(event_handler.clone()));
|
||||
let mut scheme_handler_factory = SchemeHandlerFactory::new(SchemeHandlerFactoryImpl::new(event_handler.duplicate()));
|
||||
incognito_request_context.clear_scheme_handler_factories();
|
||||
incognito_request_context.register_scheme_handler_factory(Some(&CefString::from(RESOURCE_SCHEME)), Some(&CefString::from(RESOURCE_DOMAIN)), Some(&mut scheme_handler_factory));
|
||||
|
||||
@@ -170,6 +196,7 @@ fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf) -
|
||||
|
||||
if let Some(browser) = browser {
|
||||
Ok(SingleThreadedCefContext {
|
||||
event_handler: Box::new(event_handler),
|
||||
browser,
|
||||
input_state: InputState::default(),
|
||||
instance_dir,
|
||||
|
||||
@@ -30,11 +30,11 @@ impl CefContext for MultiThreadedCefContextProxy {
|
||||
});
|
||||
}
|
||||
|
||||
fn notify_of_resize(&self) {
|
||||
fn notify_view_info_changed(&self) {
|
||||
run_on_ui_thread(move || {
|
||||
CONTEXT.with(|b| {
|
||||
if let Some(context) = b.borrow_mut().as_mut() {
|
||||
context.notify_of_resize();
|
||||
context.notify_view_info_changed();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
use cef::{Browser, ImplBrowser, ImplBrowserHost};
|
||||
use winit::event::WindowEvent;
|
||||
|
||||
use crate::cef::input;
|
||||
use crate::cef::input::InputState;
|
||||
use crate::cef::ipc::{MessageType, SendMessage};
|
||||
use crate::cef::{CefEventHandler, input};
|
||||
|
||||
use super::CefContext;
|
||||
|
||||
pub(super) struct SingleThreadedCefContext {
|
||||
pub(super) event_handler: Box<dyn CefEventHandler>,
|
||||
pub(super) browser: Browser,
|
||||
pub(super) input_state: InputState,
|
||||
pub(super) instance_dir: std::path::PathBuf,
|
||||
@@ -19,11 +20,14 @@ impl CefContext for SingleThreadedCefContext {
|
||||
}
|
||||
|
||||
fn handle_window_event(&mut self, event: &WindowEvent) {
|
||||
input::handle_window_event(&self.browser, &mut self.input_state, event)
|
||||
input::handle_window_event(&self.browser, &mut self.input_state, event);
|
||||
}
|
||||
|
||||
fn notify_of_resize(&self) {
|
||||
self.browser.host().unwrap().was_resized();
|
||||
fn notify_view_info_changed(&self) {
|
||||
let view_info = self.event_handler.view_info();
|
||||
let host = self.browser.host().unwrap();
|
||||
host.set_zoom_level(view_info.zoom());
|
||||
host.was_resized();
|
||||
}
|
||||
|
||||
fn send_web_message(&self, message: Vec<u8>) {
|
||||
|
||||
@@ -7,19 +7,19 @@ use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, Wi
|
||||
mod keymap;
|
||||
use keymap::{ToNativeKeycode, ToVKBits};
|
||||
|
||||
use super::consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
use super::consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
|
||||
pub(crate) fn handle_window_event(browser: &Browser, input_state: &mut InputState, event: &WindowEvent) {
|
||||
match event {
|
||||
WindowEvent::PointerMoved { position, .. } | WindowEvent::PointerEntered { position, .. } => {
|
||||
input_state.cursor_move(position);
|
||||
input_state.cursor_move(&position);
|
||||
|
||||
let Some(host) = browser.host() else { return };
|
||||
host.send_mouse_move_event(Some(&input_state.into()), 0);
|
||||
}
|
||||
WindowEvent::PointerLeft { position, .. } => {
|
||||
if let Some(position) = position {
|
||||
input_state.cursor_move(position);
|
||||
input_state.cursor_move(&position);
|
||||
}
|
||||
|
||||
let Some(host) = browser.host() else { return };
|
||||
@@ -129,6 +129,20 @@ pub(crate) fn handle_window_event(browser: &Browser, input_state: &mut InputStat
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::PinchGesture { delta, .. } => {
|
||||
if !delta.is_normal() {
|
||||
return;
|
||||
}
|
||||
let Some(host) = browser.host() else { return };
|
||||
|
||||
let mut mouse_event: MouseEvent = input_state.into();
|
||||
mouse_event.modifiers |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN as u32;
|
||||
mouse_event.modifiers |= cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA as u32;
|
||||
|
||||
let delta = (delta * PINCH_ZOOM_SPEED).round() as i32;
|
||||
|
||||
host.send_mouse_wheel_event(Some(&mouse_event), 0, delta);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ mod browser_process_app;
|
||||
mod browser_process_client;
|
||||
mod browser_process_handler;
|
||||
mod browser_process_life_span_handler;
|
||||
mod browser_process_load_handler;
|
||||
|
||||
mod render_process_app;
|
||||
mod render_process_handler;
|
||||
@@ -13,10 +14,11 @@ mod scheme_handler_factory;
|
||||
mod display_handler;
|
||||
|
||||
pub(super) mod render_handler;
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(super) mod task;
|
||||
|
||||
pub(super) use browser_process_app::BrowserProcessAppImpl;
|
||||
pub(super) use browser_process_client::BrowserProcessClientImpl;
|
||||
pub(super) use render_handler::RenderHandlerImpl;
|
||||
pub(super) use render_process_app::RenderProcessAppImpl;
|
||||
pub(super) use scheme_handler_factory::SchemeHandlerFactoryImpl;
|
||||
@@ -13,7 +13,7 @@ pub(crate) struct BrowserProcessAppImpl<H: CefEventHandler> {
|
||||
object: *mut RcImpl<_cef_app_t, Self>,
|
||||
event_handler: H,
|
||||
}
|
||||
impl<H: CefEventHandler + Clone> BrowserProcessAppImpl<H> {
|
||||
impl<H: CefEventHandler> BrowserProcessAppImpl<H> {
|
||||
pub(crate) fn new(event_handler: H) -> Self {
|
||||
Self {
|
||||
object: std::ptr::null_mut(),
|
||||
@@ -22,9 +22,9 @@ impl<H: CefEventHandler + Clone> BrowserProcessAppImpl<H> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<H: CefEventHandler + Clone> ImplApp for BrowserProcessAppImpl<H> {
|
||||
impl<H: CefEventHandler> ImplApp for BrowserProcessAppImpl<H> {
|
||||
fn browser_process_handler(&self) -> Option<BrowserProcessHandler> {
|
||||
Some(BrowserProcessHandler::new(BrowserProcessHandlerImpl::new(self.event_handler.clone())))
|
||||
Some(BrowserProcessHandler::new(BrowserProcessHandlerImpl::new(self.event_handler.duplicate())))
|
||||
}
|
||||
|
||||
fn on_register_custom_schemes(&self, registrar: Option<&mut SchemeRegistrar>) {
|
||||
@@ -66,6 +66,12 @@ impl<H: CefEventHandler + Clone> ImplApp for BrowserProcessAppImpl<H> {
|
||||
cmd.append_switch_with_value(Some(&CefString::from("ozone-platform")), Some(&CefString::from("wayland")));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
// Hide user prompt asking for keychain access
|
||||
cmd.append_switch(Some(&CefString::from("use-mock-keychain")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +80,7 @@ impl<H: CefEventHandler + Clone> ImplApp for BrowserProcessAppImpl<H> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<H: CefEventHandler + Clone> Clone for BrowserProcessAppImpl<H> {
|
||||
impl<H: CefEventHandler> Clone for BrowserProcessAppImpl<H> {
|
||||
fn clone(&self) -> Self {
|
||||
unsafe {
|
||||
let rc_impl = &mut *self.object;
|
||||
@@ -82,7 +88,7 @@ impl<H: CefEventHandler + Clone> Clone for BrowserProcessAppImpl<H> {
|
||||
}
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.clone(),
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,7 +100,7 @@ impl<H: CefEventHandler> Rc for BrowserProcessAppImpl<H> {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<H: CefEventHandler + Clone> WrapApp for BrowserProcessAppImpl<H> {
|
||||
impl<H: CefEventHandler> WrapApp for BrowserProcessAppImpl<H> {
|
||||
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_app_t, Self>) {
|
||||
self.object = object;
|
||||
}
|
||||
|
||||
@@ -1,26 +1,30 @@
|
||||
use cef::rc::{Rc, RcImpl};
|
||||
use cef::sys::{_cef_client_t, cef_base_ref_counted_t};
|
||||
use cef::{DisplayHandler, ImplClient, LifeSpanHandler, RenderHandler, WrapClient};
|
||||
use cef::{DisplayHandler, ImplClient, LifeSpanHandler, LoadHandler, RenderHandler, WrapClient};
|
||||
|
||||
use crate::cef::CefEventHandler;
|
||||
use crate::cef::ipc::{MessageType, UnpackMessage, UnpackedMessage};
|
||||
|
||||
use super::browser_process_life_span_handler::BrowserProcessLifeSpanHandlerImpl;
|
||||
use super::browser_process_load_handler::LoadHandlerImpl;
|
||||
use super::display_handler::DisplayHandlerImpl;
|
||||
use super::render_handler::RenderHandlerImpl;
|
||||
|
||||
pub(crate) struct BrowserProcessClientImpl<H: CefEventHandler> {
|
||||
object: *mut RcImpl<_cef_client_t, Self>,
|
||||
render_handler: RenderHandler,
|
||||
event_handler: H,
|
||||
load_handler: LoadHandler,
|
||||
render_handler: RenderHandler,
|
||||
display_handler: DisplayHandler,
|
||||
}
|
||||
impl<H: CefEventHandler> BrowserProcessClientImpl<H> {
|
||||
pub(crate) fn new(render_handler: RenderHandler, event_handler: H) -> Self {
|
||||
pub(crate) fn new(event_handler: &H) -> Self {
|
||||
Self {
|
||||
object: std::ptr::null_mut(),
|
||||
render_handler,
|
||||
event_handler: event_handler.clone(),
|
||||
display_handler: DisplayHandler::new(DisplayHandlerImpl::new(event_handler)),
|
||||
event_handler: event_handler.duplicate(),
|
||||
load_handler: LoadHandler::new(LoadHandlerImpl::new(event_handler.duplicate())),
|
||||
render_handler: RenderHandler::new(RenderHandlerImpl::new(event_handler.duplicate())),
|
||||
display_handler: DisplayHandler::new(DisplayHandlerImpl::new(event_handler.duplicate())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,6 +56,10 @@ impl<H: CefEventHandler> ImplClient for BrowserProcessClientImpl<H> {
|
||||
1
|
||||
}
|
||||
|
||||
fn load_handler(&self) -> Option<cef::LoadHandler> {
|
||||
Some(self.load_handler.clone())
|
||||
}
|
||||
|
||||
fn render_handler(&self) -> Option<RenderHandler> {
|
||||
Some(self.render_handler.clone())
|
||||
}
|
||||
@@ -77,8 +85,9 @@ impl<H: CefEventHandler> Clone for BrowserProcessClientImpl<H> {
|
||||
}
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
load_handler: self.load_handler.clone(),
|
||||
render_handler: self.render_handler.clone(),
|
||||
event_handler: self.event_handler.clone(),
|
||||
display_handler: self.display_handler.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ impl<H: CefEventHandler> BrowserProcessHandlerImpl<H> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<H: CefEventHandler + Clone> ImplBrowserProcessHandler for BrowserProcessHandlerImpl<H> {
|
||||
impl<H: CefEventHandler> ImplBrowserProcessHandler for BrowserProcessHandlerImpl<H> {
|
||||
fn on_schedule_message_pump_work(&self, delay_ms: i64) {
|
||||
self.event_handler.schedule_cef_message_loop_work(Instant::now() + Duration::from_millis(delay_ms as u64));
|
||||
}
|
||||
@@ -33,7 +33,7 @@ impl<H: CefEventHandler + Clone> ImplBrowserProcessHandler for BrowserProcessHan
|
||||
}
|
||||
}
|
||||
|
||||
impl<H: CefEventHandler + Clone> Clone for BrowserProcessHandlerImpl<H> {
|
||||
impl<H: CefEventHandler> Clone for BrowserProcessHandlerImpl<H> {
|
||||
fn clone(&self) -> Self {
|
||||
unsafe {
|
||||
let rc_impl = &mut *self.object;
|
||||
@@ -41,7 +41,7 @@ impl<H: CefEventHandler + Clone> Clone for BrowserProcessHandlerImpl<H> {
|
||||
}
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.clone(),
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ impl<H: CefEventHandler> Rc for BrowserProcessHandlerImpl<H> {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<H: CefEventHandler + Clone> WrapBrowserProcessHandler for BrowserProcessHandlerImpl<H> {
|
||||
impl<H: CefEventHandler> WrapBrowserProcessHandler for BrowserProcessHandlerImpl<H> {
|
||||
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_browser_process_handler_t, Self>) {
|
||||
self.object = object;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ impl ImplLifeSpanHandler for BrowserProcessLifeSpanHandlerImpl {
|
||||
_user_gesture: ::std::os::raw::c_int,
|
||||
_popup_features: Option<&cef::PopupFeatures>,
|
||||
_window_info: Option<&mut cef::WindowInfo>,
|
||||
_client: Option<&mut Option<impl cef::ImplClient>>,
|
||||
_client: Option<&mut Option<cef::Client>>,
|
||||
_settings: Option<&mut cef::BrowserSettings>,
|
||||
_extra_info: Option<&mut Option<cef::DictionaryValue>>,
|
||||
_no_javascript_access: Option<&mut ::std::os::raw::c_int>,
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
use cef::rc::{Rc, RcImpl};
|
||||
use cef::sys::{_cef_load_handler_t, cef_base_ref_counted_t, cef_load_handler_t};
|
||||
use cef::{ImplBrowser, ImplBrowserHost, ImplLoadHandler, WrapLoadHandler};
|
||||
|
||||
use crate::cef::CefEventHandler;
|
||||
|
||||
pub(crate) struct LoadHandlerImpl<H: CefEventHandler> {
|
||||
object: *mut RcImpl<cef_load_handler_t, Self>,
|
||||
event_handler: H,
|
||||
}
|
||||
impl<H: CefEventHandler> LoadHandlerImpl<H> {
|
||||
pub(crate) fn new(event_handler: H) -> Self {
|
||||
Self {
|
||||
object: std::ptr::null_mut(),
|
||||
event_handler,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<H: CefEventHandler> ImplLoadHandler for LoadHandlerImpl<H> {
|
||||
fn on_loading_state_change(&self, browser: Option<&mut cef::Browser>, is_loading: ::std::os::raw::c_int, _can_go_back: ::std::os::raw::c_int, _can_go_forward: ::std::os::raw::c_int) {
|
||||
let view_info = self.event_handler.view_info();
|
||||
|
||||
if let Some(browser) = browser
|
||||
&& is_loading == 0
|
||||
{
|
||||
browser.host().unwrap().set_zoom_level(view_info.zoom());
|
||||
}
|
||||
}
|
||||
|
||||
fn get_raw(&self) -> *mut _cef_load_handler_t {
|
||||
self.object.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<H: CefEventHandler> Clone for LoadHandlerImpl<H> {
|
||||
fn clone(&self) -> Self {
|
||||
unsafe {
|
||||
let rc_impl = &mut *self.object;
|
||||
rc_impl.interface.add_ref();
|
||||
}
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<H: CefEventHandler> Rc for LoadHandlerImpl<H> {
|
||||
fn as_base(&self) -> &cef_base_ref_counted_t {
|
||||
unsafe {
|
||||
let base = &*self.object;
|
||||
std::mem::transmute(&base.cef_object)
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<H: CefEventHandler> WrapLoadHandler for LoadHandlerImpl<H> {
|
||||
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_load_handler_t, Self>) {
|
||||
self.object = object;
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,13 @@ impl<H: CefEventHandler> DisplayHandlerImpl<H> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
type CefCursorHandle = cef::CursorHandle;
|
||||
#[cfg(target_os = "macos")]
|
||||
type CefCursorHandle = *mut u8;
|
||||
|
||||
impl<H: CefEventHandler> ImplDisplayHandler for DisplayHandlerImpl<H> {
|
||||
fn on_cursor_change(&self, _browser: Option<&mut cef::Browser>, _cursor: cef::CursorHandle, cursor_type: cef::CursorType, _custom_cursor_info: Option<&cef::CursorInfo>) -> ::std::os::raw::c_int {
|
||||
fn on_cursor_change(&self, _browser: Option<&mut cef::Browser>, _cursor: CefCursorHandle, cursor_type: cef::CursorType, _custom_cursor_info: Option<&cef::CursorInfo>) -> ::std::os::raw::c_int {
|
||||
let cursor = match cursor_type.into() {
|
||||
CT_POINTER => CursorIcon::Default,
|
||||
CT_CROSS => CursorIcon::Crosshair,
|
||||
@@ -117,7 +122,7 @@ impl<H: CefEventHandler> Clone for DisplayHandlerImpl<H> {
|
||||
}
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.clone(),
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,12 +21,12 @@ impl<H: CefEventHandler> RenderHandlerImpl<H> {
|
||||
impl<H: CefEventHandler> ImplRenderHandler for RenderHandlerImpl<H> {
|
||||
fn view_rect(&self, _browser: Option<&mut Browser>, rect: Option<&mut Rect>) {
|
||||
if let Some(rect) = rect {
|
||||
let view = self.event_handler.window_size();
|
||||
let view_info = self.event_handler.view_info();
|
||||
*rect = Rect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: view.width as i32,
|
||||
height: view.height as i32,
|
||||
width: view_info.width() as i32,
|
||||
height: view_info.height() as i32,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ impl<H: CefEventHandler> ImplRenderHandler for RenderHandlerImpl<H> {
|
||||
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
fn on_accelerated_paint(&self, _browser: Option<&mut Browser>, type_: PaintElementType, _dirty_rect_count: usize, _dirty_rects: Option<&Rect>, info: Option<&cef::AcceleratedPaintInfo>) {
|
||||
use crate::cef::texture_import::shared_texture_handle::SharedTextureHandle;
|
||||
use cef::osr_texture_import::SharedTextureHandle;
|
||||
|
||||
if type_ != PaintElementType::default() {
|
||||
return;
|
||||
@@ -78,7 +78,7 @@ impl<H: CefEventHandler> Clone for RenderHandlerImpl<H> {
|
||||
}
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.clone(),
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ impl<H: CefEventHandler> Clone for SchemeHandlerFactoryImpl<H> {
|
||||
}
|
||||
Self {
|
||||
object: self.object,
|
||||
event_handler: self.event_handler.clone(),
|
||||
event_handler: self.event_handler.duplicate(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
//! Common utilities and traits for texture import across platforms
|
||||
|
||||
use crate::cef::texture_import::*;
|
||||
use ash::vk;
|
||||
use cef::sys::cef_color_type_t;
|
||||
use wgpu::Device;
|
||||
|
||||
/// Common format conversion utilities
|
||||
pub mod format {
|
||||
use super::*;
|
||||
|
||||
/// Convert CEF color type to wgpu texture format
|
||||
pub fn cef_to_wgpu(format: cef_color_type_t) -> Result<wgpu::TextureFormat, TextureImportError> {
|
||||
match format {
|
||||
cef_color_type_t::CEF_COLOR_TYPE_BGRA_8888 => Ok(wgpu::TextureFormat::Bgra8UnormSrgb),
|
||||
cef_color_type_t::CEF_COLOR_TYPE_RGBA_8888 => Ok(wgpu::TextureFormat::Rgba8UnormSrgb),
|
||||
_ => Err(TextureImportError::UnsupportedFormat { format }),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
/// Convert CEF color type to Vulkan format
|
||||
pub fn cef_to_vulkan(format: cef_color_type_t) -> Result<vk::Format, TextureImportError> {
|
||||
match format {
|
||||
cef_color_type_t::CEF_COLOR_TYPE_BGRA_8888 => Ok(vk::Format::B8G8R8A8_UNORM),
|
||||
cef_color_type_t::CEF_COLOR_TYPE_RGBA_8888 => Ok(vk::Format::R8G8B8A8_UNORM),
|
||||
_ => Err(TextureImportError::UnsupportedFormat { format }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Common texture creation utilities
|
||||
pub mod texture {
|
||||
use super::*;
|
||||
|
||||
/// Create a fallback CPU texture with the given dimensions and format
|
||||
pub fn create_fallback(device: &Device, width: u32, height: u32, format: cef_color_type_t, label: &str) -> TextureImportResult {
|
||||
let wgpu_format = format::cef_to_wgpu(format)?;
|
||||
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu_format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
|
||||
tracing::warn!(
|
||||
"Using fallback CPU texture for CEF rendering ({}x{}, {:?}) - hardware acceleration failed or unavailable. Consider checking GPU driver support.",
|
||||
width,
|
||||
height,
|
||||
format
|
||||
);
|
||||
Ok(texture)
|
||||
}
|
||||
}
|
||||
|
||||
/// Common Vulkan utilities
|
||||
pub mod vulkan {
|
||||
use super::*;
|
||||
|
||||
/// Find a suitable memory type index for Vulkan allocation
|
||||
pub fn find_memory_type_index(type_filter: u32, properties: vk::MemoryPropertyFlags, mem_properties: &vk::PhysicalDeviceMemoryProperties) -> Option<u32> {
|
||||
(0..mem_properties.memory_type_count).find(|&i| (type_filter & (1 << i)) != 0 && mem_properties.memory_types[i as usize].property_flags.contains(properties))
|
||||
}
|
||||
|
||||
/// Check if the wgpu device is using Vulkan backend
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn is_vulkan_backend(device: &Device) -> bool {
|
||||
use wgpu::hal::api;
|
||||
let mut is_vulkan = false;
|
||||
unsafe {
|
||||
device.as_hal::<api::Vulkan, _, _>(|device| {
|
||||
is_vulkan = device.is_some();
|
||||
});
|
||||
}
|
||||
is_vulkan
|
||||
}
|
||||
|
||||
/// Check if the wgpu device is using D3D12 backend
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn is_d3d12_backend(device: &Device) -> bool {
|
||||
use wgpu::hal::api;
|
||||
let mut is_d3d12 = false;
|
||||
unsafe {
|
||||
device.as_hal::<api::Dx12, _, _>(|device| {
|
||||
is_d3d12 = device.is_some();
|
||||
});
|
||||
}
|
||||
is_d3d12
|
||||
}
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
//! Windows D3D11 shared texture import implementation
|
||||
|
||||
use super::common::{format, texture, vulkan};
|
||||
use super::{TextureImportError, TextureImportResult, TextureImporter};
|
||||
use ash::vk;
|
||||
use cef::{AcceleratedPaintInfo, sys::cef_color_type_t};
|
||||
use std::os::raw::c_void;
|
||||
use wgpu::hal::api;
|
||||
|
||||
pub struct D3D11Importer {
|
||||
pub handle: *mut c_void,
|
||||
pub format: cef_color_type_t,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
impl TextureImporter for D3D11Importer {
|
||||
fn new(info: &AcceleratedPaintInfo) -> Self {
|
||||
Self {
|
||||
handle: info.shared_texture_handle,
|
||||
format: *info.format.as_ref(),
|
||||
width: info.extra.coded_size.width as u32,
|
||||
height: info.extra.coded_size.height as u32,
|
||||
}
|
||||
}
|
||||
|
||||
fn import_to_wgpu(&self, device: &wgpu::Device) -> TextureImportResult {
|
||||
// Try hardware acceleration first
|
||||
if self.supports_hardware_acceleration(device) {
|
||||
// Try D3D12 first (most efficient on Windows)
|
||||
if vulkan::is_d3d12_backend(device) {
|
||||
match self.import_via_d3d12(device) {
|
||||
Ok(texture) => {
|
||||
tracing::info!("Successfully imported D3D11 shared texture via D3D12");
|
||||
return Ok(texture);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to import D3D11 via D3D12: {}, trying Vulkan fallback", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try Vulkan as fallback
|
||||
if vulkan::is_vulkan_backend(device) {
|
||||
match self.import_via_vulkan(device) {
|
||||
Ok(texture) => {
|
||||
tracing::info!("Successfully imported D3D11 shared texture via Vulkan");
|
||||
return Ok(texture);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to import D3D11 via Vulkan: {}, falling back to CPU texture", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to CPU texture
|
||||
texture::create_fallback(device, self.width, self.height, self.format, "CEF D3D11 Texture (fallback)")
|
||||
}
|
||||
|
||||
fn supports_hardware_acceleration(&self, device: &wgpu::Device) -> bool {
|
||||
// Check if handle is valid
|
||||
if self.handle.is_null() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if wgpu is using D3D12 or Vulkan backend
|
||||
vulkan::is_d3d12_backend(device) || vulkan::is_vulkan_backend(device)
|
||||
}
|
||||
}
|
||||
|
||||
impl D3D11Importer {
|
||||
fn import_via_d3d12(&self, device: &wgpu::Device) -> TextureImportResult {
|
||||
// Get wgpu's D3D12 device
|
||||
use wgpu::hal::api;
|
||||
let hal_texture = unsafe {
|
||||
device.as_hal::<api::Dx12, _, _>(|device| {
|
||||
let Some(device) = device else {
|
||||
return Err(TextureImportError::HardwareUnavailable {
|
||||
reason: "Device is not using D3D12 backend".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
// Import D3D11 shared handle directly into D3D12 resource
|
||||
let d3d12_resource = self.import_d3d11_handle_to_d3d12(device)?;
|
||||
|
||||
// Wrap D3D12 resource in wgpu-hal texture
|
||||
let hal_texture = <api::Dx12 as wgpu::hal::Api>::Device::texture_from_raw(
|
||||
d3d12_resource,
|
||||
format::cef_to_wgpu(self.format)?,
|
||||
wgpu::TextureDimension::D2,
|
||||
wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
1, // mip_level_count
|
||||
1, // sample_count
|
||||
);
|
||||
|
||||
Ok(hal_texture)
|
||||
})
|
||||
}?;
|
||||
|
||||
// Import hal texture into wgpu
|
||||
let texture = unsafe {
|
||||
device.create_texture_from_hal::<api::Dx12>(
|
||||
hal_texture,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("CEF D3D11→D3D12 Shared Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: format::cef_to_wgpu(self.format)?,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
fn import_via_vulkan(&self, device: &wgpu::Device) -> TextureImportResult {
|
||||
// Get wgpu's Vulkan instance and device
|
||||
use wgpu::{TextureUses, wgc::api::Vulkan};
|
||||
let hal_texture = unsafe {
|
||||
device.as_hal::<api::Vulkan, _, _>(|device| {
|
||||
let Some(device) = device else {
|
||||
return Err(TextureImportError::HardwareUnavailable {
|
||||
reason: "Device is not using Vulkan backend".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
// Import D3D11 shared handle into Vulkan
|
||||
let vk_image = self.import_d3d11_handle_to_vulkan(device)?;
|
||||
|
||||
// Wrap VkImage in wgpu-hal texture
|
||||
let hal_texture = <api::Vulkan as wgpu::hal::Api>::Device::texture_from_raw(
|
||||
vk_image,
|
||||
&wgpu::hal::TextureDescriptor {
|
||||
label: Some("CEF D3D11 Shared Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: format::cef_to_wgpu(self.format)?,
|
||||
usage: TextureUses::COPY_DST | TextureUses::RESOURCE,
|
||||
memory_flags: wgpu::hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
},
|
||||
None, // drop_callback
|
||||
);
|
||||
|
||||
Ok(hal_texture)
|
||||
})
|
||||
}?;
|
||||
|
||||
// Import hal texture into wgpu
|
||||
let texture = unsafe {
|
||||
device.create_texture_from_hal::<Vulkan>(
|
||||
hal_texture,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("CEF D3D11 Shared Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: format::cef_to_wgpu(self.format)?,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
fn import_d3d11_handle_to_vulkan(&self, hal_device: &<api::Vulkan as wgpu::hal::Api>::Device) -> Result<vk::Image, TextureImportError> {
|
||||
// Get raw Vulkan handles
|
||||
let device = hal_device.raw_device();
|
||||
let _instance = hal_device.shared_instance().raw_instance();
|
||||
|
||||
// Validate dimensions
|
||||
if self.width == 0 || self.height == 0 {
|
||||
return Err(TextureImportError::InvalidHandle("Invalid D3D11 texture dimensions".to_string()));
|
||||
}
|
||||
|
||||
// Create external memory image info
|
||||
let mut external_memory_info = vk::ExternalMemoryImageCreateInfo::default().handle_types(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE);
|
||||
|
||||
// Create image create info
|
||||
let image_create_info = vk::ImageCreateInfo::default()
|
||||
.image_type(vk::ImageType::TYPE_2D)
|
||||
.format(format::cef_to_vulkan(self.format)?)
|
||||
.extent(vk::Extent3D {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth: 1,
|
||||
})
|
||||
.mip_levels(1)
|
||||
.array_layers(1)
|
||||
.samples(vk::SampleCountFlags::TYPE_1)
|
||||
.tiling(vk::ImageTiling::OPTIMAL)
|
||||
.usage(vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::COLOR_ATTACHMENT)
|
||||
.sharing_mode(vk::SharingMode::EXCLUSIVE)
|
||||
.push_next(&mut external_memory_info);
|
||||
|
||||
// Create the image
|
||||
let image = unsafe {
|
||||
device.create_image(&image_create_info, None).map_err(|e| TextureImportError::VulkanError {
|
||||
operation: format!("Failed to create Vulkan image: {:?}", e),
|
||||
})?
|
||||
};
|
||||
|
||||
// Get memory requirements
|
||||
let memory_requirements = unsafe { device.get_image_memory_requirements(image) };
|
||||
|
||||
// Import D3D11 handle
|
||||
let mut import_memory_win32 = vk::ImportMemoryWin32HandleInfoKHR::default()
|
||||
.handle_type(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE)
|
||||
.handle(self.handle as isize);
|
||||
|
||||
// Find a suitable memory type
|
||||
let memory_properties = unsafe { hal_device.shared_instance().raw_instance().get_physical_device_memory_properties(hal_device.raw_physical_device()) };
|
||||
|
||||
let memory_type_index =
|
||||
vulkan::find_memory_type_index(memory_requirements.memory_type_bits, vk::MemoryPropertyFlags::empty(), &memory_properties).ok_or_else(|| TextureImportError::VulkanError {
|
||||
operation: "Failed to find suitable memory type for D3D11 texture".to_string(),
|
||||
})?;
|
||||
|
||||
let allocate_info = vk::MemoryAllocateInfo::default()
|
||||
.allocation_size(memory_requirements.size)
|
||||
.memory_type_index(memory_type_index)
|
||||
.push_next(&mut import_memory_win32);
|
||||
|
||||
let device_memory = unsafe {
|
||||
device.allocate_memory(&allocate_info, None).map_err(|e| TextureImportError::VulkanError {
|
||||
operation: format!("Failed to allocate memory for D3D11 texture: {:?}", e),
|
||||
})?
|
||||
};
|
||||
|
||||
// Bind memory to image
|
||||
unsafe {
|
||||
device.bind_image_memory(image, device_memory, 0).map_err(|e| TextureImportError::VulkanError {
|
||||
operation: format!("Failed to bind memory to image: {:?}", e),
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
fn import_d3d11_handle_to_d3d12(&self, hal_device: &<wgpu::hal::api::Dx12 as wgpu::hal::Api>::Device) -> Result<windows::Win32::Graphics::Direct3D12::ID3D12Resource, TextureImportError> {
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
// Get D3D12 device from wgpu-hal
|
||||
let d3d12_device = hal_device.raw_device();
|
||||
|
||||
// Validate dimensions
|
||||
if self.width == 0 || self.height == 0 {
|
||||
return Err(TextureImportError::InvalidHandle("Invalid D3D11 texture dimensions".to_string()));
|
||||
}
|
||||
|
||||
// Open D3D11 shared handle on D3D12 device
|
||||
unsafe {
|
||||
let mut shared_resource: Option<ID3D12Resource> = None;
|
||||
d3d12_device
|
||||
.OpenSharedHandle(windows::Win32::Foundation::HANDLE(self.handle), &mut shared_resource)
|
||||
.map_err(|e| TextureImportError::PlatformError {
|
||||
message: format!("Failed to open D3D11 shared handle on D3D12: {:?}", e),
|
||||
})?;
|
||||
|
||||
shared_resource.ok_or_else(|| TextureImportError::InvalidHandle("Failed to get D3D12 resource from shared handle".to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
//! Linux DMA-BUF texture import implementation
|
||||
|
||||
use super::common::{format, texture, vulkan};
|
||||
use super::{TextureImportError, TextureImportResult, TextureImporter};
|
||||
use ash::vk;
|
||||
use cef::{AcceleratedPaintInfo, sys::cef_color_type_t};
|
||||
use wgpu::hal::api;
|
||||
|
||||
pub(crate) struct DmaBufImporter {
|
||||
fds: Vec<std::os::fd::RawFd>,
|
||||
format: cef_color_type_t,
|
||||
modifier: u64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
strides: Vec<u32>,
|
||||
offsets: Vec<u32>,
|
||||
}
|
||||
|
||||
impl TextureImporter for DmaBufImporter {
|
||||
fn new(info: &AcceleratedPaintInfo) -> Self {
|
||||
Self {
|
||||
fds: extract_fds_from_info(info),
|
||||
format: *info.format.as_ref(),
|
||||
modifier: info.modifier,
|
||||
width: info.extra.coded_size.width as u32,
|
||||
height: info.extra.coded_size.height as u32,
|
||||
strides: extract_strides_from_info(info),
|
||||
offsets: extract_offsets_from_info(info),
|
||||
}
|
||||
}
|
||||
|
||||
fn import_to_wgpu(&self, device: &wgpu::Device) -> TextureImportResult {
|
||||
// Try hardware acceleration first
|
||||
if self.supports_hardware_acceleration(device) {
|
||||
match self.import_via_vulkan(device) {
|
||||
Ok(texture) => {
|
||||
tracing::info!("Successfully imported DMA-BUF texture via Vulkan");
|
||||
return Ok(texture);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to import DMA-BUF via Vulkan: {}, falling back to CPU texture", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to CPU texture
|
||||
texture::create_fallback(device, self.width, self.height, self.format, "CEF DMA-BUF Texture (fallback)")
|
||||
}
|
||||
|
||||
fn supports_hardware_acceleration(&self, device: &wgpu::Device) -> bool {
|
||||
// Check if we have valid file descriptors
|
||||
if self.fds.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
for &fd in &self.fds {
|
||||
if fd < 0 {
|
||||
return false;
|
||||
}
|
||||
// Check if file descriptor is valid
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
|
||||
if flags == -1 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if wgpu is using Vulkan backend
|
||||
vulkan::is_vulkan_backend(device)
|
||||
}
|
||||
}
|
||||
|
||||
impl DmaBufImporter {
|
||||
fn import_via_vulkan(&self, device: &wgpu::Device) -> TextureImportResult {
|
||||
// Get wgpu's Vulkan instance and device
|
||||
use wgpu::{TextureUses, wgc::api::Vulkan};
|
||||
let hal_texture = unsafe {
|
||||
device.as_hal::<api::Vulkan, _, _>(|device| {
|
||||
let Some(device) = device else {
|
||||
return Err(TextureImportError::HardwareUnavailable {
|
||||
reason: "Device is not using Vulkan backend".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
// Create VkImage from DMA-BUF using external memory
|
||||
let vk_image = self.create_vulkan_image_from_dmabuf(device)?;
|
||||
|
||||
// Wrap VkImage in wgpu-hal texture
|
||||
let hal_texture = <api::Vulkan as wgpu::hal::Api>::Device::texture_from_raw(
|
||||
vk_image,
|
||||
&wgpu::hal::TextureDescriptor {
|
||||
label: Some("CEF DMA-BUF Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: format::cef_to_wgpu(self.format)?,
|
||||
usage: TextureUses::COPY_DST | TextureUses::RESOURCE,
|
||||
memory_flags: wgpu::hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
},
|
||||
None, // drop_callback
|
||||
);
|
||||
|
||||
Ok(hal_texture)
|
||||
})
|
||||
}?;
|
||||
|
||||
// Import hal texture into wgpu
|
||||
let texture = unsafe {
|
||||
device.create_texture_from_hal::<Vulkan>(
|
||||
hal_texture,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("CEF DMA-BUF Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: format::cef_to_wgpu(self.format)?,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
fn create_vulkan_image_from_dmabuf(&self, hal_device: &<api::Vulkan as wgpu::hal::Api>::Device) -> Result<vk::Image, TextureImportError> {
|
||||
// Get raw Vulkan handles
|
||||
let device = hal_device.raw_device();
|
||||
let _instance = hal_device.shared_instance().raw_instance();
|
||||
|
||||
// Validate dimensions
|
||||
if self.width == 0 || self.height == 0 {
|
||||
return Err(TextureImportError::InvalidHandle("Invalid DMA-BUF dimensions".to_string()));
|
||||
}
|
||||
|
||||
// Create external memory image
|
||||
let image_create_info = vk::ImageCreateInfo::default()
|
||||
.image_type(vk::ImageType::TYPE_2D)
|
||||
.format(format::cef_to_vulkan(self.format)?)
|
||||
.extent(vk::Extent3D {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth: 1,
|
||||
})
|
||||
.mip_levels(1)
|
||||
.array_layers(1)
|
||||
.samples(vk::SampleCountFlags::TYPE_1)
|
||||
.tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
|
||||
.usage(vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::COLOR_ATTACHMENT)
|
||||
.sharing_mode(vk::SharingMode::EXCLUSIVE);
|
||||
|
||||
// Set up DRM format modifier
|
||||
let plane_layouts = self.create_subresource_layouts()?;
|
||||
let mut drm_format_modifier = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default()
|
||||
.drm_format_modifier(self.modifier)
|
||||
.plane_layouts(&plane_layouts);
|
||||
|
||||
let image_create_info = image_create_info.push_next(&mut drm_format_modifier);
|
||||
|
||||
// Create the image
|
||||
let image = unsafe {
|
||||
device.create_image(&image_create_info, None).map_err(|e| TextureImportError::VulkanError {
|
||||
operation: format!("Failed to create Vulkan image: {e:?}"),
|
||||
})?
|
||||
};
|
||||
|
||||
// Import memory from DMA-BUF
|
||||
let memory_requirements = unsafe { device.get_image_memory_requirements(image) };
|
||||
|
||||
// Duplicate the file descriptor to avoid ownership issues
|
||||
let dup_fd = unsafe { libc::dup(self.fds[0]) };
|
||||
if dup_fd == -1 {
|
||||
return Err(TextureImportError::PlatformError {
|
||||
message: "Failed to duplicate DMA-BUF file descriptor".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut import_memory_fd = vk::ImportMemoryFdInfoKHR::default().handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT).fd(dup_fd);
|
||||
|
||||
// Find a suitable memory type
|
||||
let memory_properties = unsafe { hal_device.shared_instance().raw_instance().get_physical_device_memory_properties(hal_device.raw_physical_device()) };
|
||||
|
||||
let memory_type_index =
|
||||
vulkan::find_memory_type_index(memory_requirements.memory_type_bits, vk::MemoryPropertyFlags::empty(), &memory_properties).ok_or_else(|| TextureImportError::VulkanError {
|
||||
operation: "Failed to find suitable memory type for DMA-BUF".to_string(),
|
||||
})?;
|
||||
|
||||
let allocate_info = vk::MemoryAllocateInfo::default()
|
||||
.allocation_size(memory_requirements.size)
|
||||
.memory_type_index(memory_type_index)
|
||||
.push_next(&mut import_memory_fd);
|
||||
|
||||
let device_memory = unsafe {
|
||||
device.allocate_memory(&allocate_info, None).map_err(|e| TextureImportError::VulkanError {
|
||||
operation: format!("Failed to allocate memory for DMA-BUF: {e:?}"),
|
||||
})?
|
||||
};
|
||||
|
||||
// Bind memory to image
|
||||
unsafe {
|
||||
device.bind_image_memory(image, device_memory, 0).map_err(|e| TextureImportError::VulkanError {
|
||||
operation: format!("Failed to bind memory to image: {e:?}"),
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
fn create_subresource_layouts(&self) -> Result<Vec<vk::SubresourceLayout>, TextureImportError> {
|
||||
let mut layouts = Vec::new();
|
||||
|
||||
for i in 0..self.fds.len() {
|
||||
layouts.push(vk::SubresourceLayout {
|
||||
offset: self.offsets.get(i).copied().unwrap_or(0) as u64,
|
||||
size: 0, // Will be calculated by driver
|
||||
row_pitch: self.strides.get(i).copied().unwrap_or(0) as u64,
|
||||
array_pitch: 0,
|
||||
depth_pitch: 0,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(layouts)
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_fds_from_info(info: &cef::AcceleratedPaintInfo) -> Vec<std::os::fd::RawFd> {
|
||||
let plane_count = info.plane_count as usize;
|
||||
let mut fds = Vec::with_capacity(plane_count);
|
||||
|
||||
for i in 0..plane_count {
|
||||
if let Some(plane) = info.planes.get(i) {
|
||||
fds.push(plane.fd);
|
||||
}
|
||||
}
|
||||
|
||||
fds
|
||||
}
|
||||
|
||||
fn extract_strides_from_info(info: &cef::AcceleratedPaintInfo) -> Vec<u32> {
|
||||
let plane_count = info.plane_count as usize;
|
||||
let mut strides = Vec::with_capacity(plane_count);
|
||||
|
||||
for i in 0..plane_count {
|
||||
if let Some(plane) = info.planes.get(i) {
|
||||
strides.push(plane.stride);
|
||||
}
|
||||
}
|
||||
|
||||
strides
|
||||
}
|
||||
|
||||
fn extract_offsets_from_info(info: &cef::AcceleratedPaintInfo) -> Vec<u32> {
|
||||
let plane_count = info.plane_count as usize;
|
||||
let mut offsets = Vec::with_capacity(plane_count);
|
||||
|
||||
for i in 0..plane_count {
|
||||
if let Some(plane) = info.planes.get(i) {
|
||||
offsets.push(plane.offset as u32);
|
||||
}
|
||||
}
|
||||
|
||||
offsets
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
//! macOS IOSurface texture import implementation
|
||||
|
||||
use super::common::{format, texture};
|
||||
use super::{TextureImportError, TextureImportResult, TextureImporter};
|
||||
use cef::{AcceleratedPaintInfo, sys::cef_color_type_t};
|
||||
use core_foundation::base::{CFType, TCFType};
|
||||
use objc2_io_surface::{IOSurface, IOSurfaceRef};
|
||||
use objc2_metal::{MTLDevice, MTLPixelFormat, MTLTexture, MTLTextureDescriptor, MTLTextureType, MTLTextureUsage};
|
||||
use std::os::raw::c_void;
|
||||
use wgpu::hal::api;
|
||||
|
||||
pub struct IOSurfaceImporter {
|
||||
pub handle: *mut c_void,
|
||||
pub format: cef_color_type_t,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
impl TextureImporter for IOSurfaceImporter {
|
||||
fn new(info: &AcceleratedPaintInfo) -> Self {
|
||||
Self {
|
||||
handle: info.shared_texture_handle,
|
||||
format: *info.format.as_ref(),
|
||||
width: info.extra.coded_size.width as u32,
|
||||
height: info.extra.coded_size.height as u32,
|
||||
}
|
||||
}
|
||||
|
||||
fn import_to_wgpu(&self, device: &wgpu::Device) -> TextureImportResult {
|
||||
// Try hardware acceleration first
|
||||
if self.supports_hardware_acceleration(device) {
|
||||
match self.import_via_metal(device) {
|
||||
Ok(texture) => {
|
||||
tracing::trace!("Successfully imported IOSurface texture via Metal");
|
||||
return Ok(texture);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to import IOSurface via Metal: {}, falling back to CPU texture", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to CPU texture
|
||||
texture::create_fallback(device, self.width, self.height, self.format, "CEF IOSurface Texture (fallback)")
|
||||
}
|
||||
|
||||
fn supports_hardware_acceleration(&self, device: &wgpu::Device) -> bool {
|
||||
// Check if handle is valid
|
||||
if self.handle.is_null() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if wgpu is using Metal backend
|
||||
self.is_metal_backend(device)
|
||||
}
|
||||
}
|
||||
|
||||
impl IOSurfaceImporter {
|
||||
fn import_via_metal(&self, device: &wgpu::Device) -> TextureImportResult {
|
||||
// Get wgpu's Metal device
|
||||
use wgpu::{hal::Api, wgc::api::Metal};
|
||||
let hal_texture = unsafe {
|
||||
device.as_hal::<api::Metal, _, _>(|device| {
|
||||
let Some(device) = device else {
|
||||
return Err(TextureImportError::HardwareUnavailable {
|
||||
reason: "Device is not using Metal backend".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
// Import IOSurface handle into Metal texture
|
||||
let metal_texture = self.import_iosurface_to_metal(device)?;
|
||||
|
||||
// Wrap Metal texture in wgpu-hal texture
|
||||
let hal_texture = <api::Metal as wgpu::hal::Api>::Device::texture_from_raw(
|
||||
metal_texture,
|
||||
&wgpu::hal::TextureDescriptor {
|
||||
label: Some("CEF IOSurface Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: format::cef_to_wgpu(self.format)?,
|
||||
usage: wgpu::hal::TextureUses::RESOURCE,
|
||||
memory_flags: wgpu::hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
},
|
||||
None, // drop_callback
|
||||
);
|
||||
|
||||
Ok(hal_texture)
|
||||
})
|
||||
}?;
|
||||
|
||||
// Import hal texture into wgpu
|
||||
let texture = unsafe {
|
||||
device.create_texture_from_hal::<Metal>(
|
||||
hal_texture,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("CEF IOSurface Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: format::cef_to_wgpu(self.format)?,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
fn import_iosurface_to_metal(&self, hal_device: &<api::Metal as wgpu::hal::Api>::Device) -> Result<<api::Metal as wgpu::hal::Api>::Texture, TextureImportError> {
|
||||
// Validate dimensions
|
||||
if self.width == 0 || self.height == 0 {
|
||||
return Err(TextureImportError::InvalidHandle("Invalid IOSurface texture dimensions".to_string()));
|
||||
}
|
||||
|
||||
// Convert handle to IOSurface
|
||||
let iosurface = unsafe {
|
||||
let cf_type = CFType::wrap_under_get_rule(self.handle as IOSurfaceRef);
|
||||
IOSurface::from(cf_type)
|
||||
};
|
||||
|
||||
// Get the Metal device from wgpu-hal
|
||||
let metal_device = hal_device.raw_device();
|
||||
|
||||
// Convert CEF format to Metal pixel format
|
||||
let metal_format = self.cef_to_metal_format(self.format)?;
|
||||
|
||||
// Create Metal texture descriptor
|
||||
let texture_descriptor = MTLTextureDescriptor::new();
|
||||
texture_descriptor.setTextureType(MTLTextureType::Type2D);
|
||||
texture_descriptor.setPixelFormat(metal_format);
|
||||
texture_descriptor.setWidth(self.width as usize);
|
||||
texture_descriptor.setHeight(self.height as usize);
|
||||
texture_descriptor.setDepth(1);
|
||||
texture_descriptor.setMipmapLevelCount(1);
|
||||
texture_descriptor.setSampleCount(1);
|
||||
texture_descriptor.setUsage(MTLTextureUsage::ShaderRead);
|
||||
|
||||
// Create Metal texture from IOSurface
|
||||
let metal_texture = unsafe { metal_device.newTextureWithDescriptor_iosurface_plane(&texture_descriptor, &iosurface, 0) };
|
||||
|
||||
let Some(metal_texture) = metal_texture else {
|
||||
return Err(TextureImportError::PlatformError {
|
||||
message: "Failed to create Metal texture from IOSurface".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
tracing::trace!("Successfully created Metal texture from IOSurface");
|
||||
Ok(metal_texture)
|
||||
}
|
||||
|
||||
fn cef_to_metal_format(&self, format: cef_color_type_t) -> Result<MTLPixelFormat, TextureImportError> {
|
||||
match format {
|
||||
cef_color_type_t::CEF_COLOR_TYPE_BGRA_8888 => Ok(MTLPixelFormat::BGRA8Unorm_sRGB),
|
||||
cef_color_type_t::CEF_COLOR_TYPE_RGBA_8888 => Ok(MTLPixelFormat::RGBA8Unorm_sRGB),
|
||||
_ => Err(TextureImportError::UnsupportedFormat { format }),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_metal_backend(&self, device: &wgpu::Device) -> bool {
|
||||
use wgpu::hal::api;
|
||||
let mut is_metal = false;
|
||||
unsafe {
|
||||
device.as_hal::<api::Metal, _, _>(|device| {
|
||||
is_metal = device.is_some();
|
||||
});
|
||||
}
|
||||
is_metal
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
//! Unified texture import system for CEF hardware acceleration
|
||||
//!
|
||||
//! This module provides a platform-agnostic interface for importing shared textures
|
||||
//! from CEF into wgpu, with automatic fallback to CPU textures when hardware
|
||||
//! acceleration is not available.
|
||||
//!
|
||||
//! # Supported Platforms
|
||||
//!
|
||||
//! - **Linux**: DMA-BUF via Vulkan external memory
|
||||
//! - **Windows**: D3D11 shared textures via Vulkan interop
|
||||
//! - **macOS**: IOSurface via Metal native API
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! ```no_run
|
||||
//! // Import texture with automatic platform detection
|
||||
//! let texture = shared_handle.import_texture(&device)?;
|
||||
//! ```
|
||||
//!
|
||||
//! # Features
|
||||
//!
|
||||
//! - `accelerated_paint` - Base feature for texture import
|
||||
//! - `accelerated_paint_dmabuf` - Linux DMA-BUF support
|
||||
//! - `accelerated_paint_d3d11` - Windows D3D11 support
|
||||
//! - `accelerated_paint_iosurface` - macOS IOSurface support
|
||||
|
||||
pub(crate) mod common;
|
||||
|
||||
pub(crate) mod shared_texture_handle;
|
||||
pub(crate) use shared_texture_handle::SharedTextureHandle;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) mod dmabuf;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(crate) mod d3d11;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) mod iosurface;
|
||||
|
||||
/// Result type for texture import operations
|
||||
pub type TextureImportResult = Result<wgpu::Texture, TextureImportError>;
|
||||
|
||||
/// Errors that can occur during texture import
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TextureImportError {
|
||||
#[error("Invalid texture handle: {0}")]
|
||||
InvalidHandle(String),
|
||||
|
||||
#[error("Unsupported texture format: {format:?}")]
|
||||
UnsupportedFormat { format: cef::sys::cef_color_type_t },
|
||||
|
||||
#[error("Hardware acceleration not available: {reason}")]
|
||||
HardwareUnavailable { reason: String },
|
||||
|
||||
#[error("Vulkan operation failed: {operation}")]
|
||||
VulkanError { operation: String },
|
||||
|
||||
#[error("Platform-specific error: {message}")]
|
||||
PlatformError { message: String },
|
||||
|
||||
#[error("Unsupported platform for texture import")]
|
||||
UnsupportedPlatform,
|
||||
}
|
||||
|
||||
/// Trait for platform-specific texture importers
|
||||
pub trait TextureImporter {
|
||||
fn new(info: &cef::AcceleratedPaintInfo) -> Self;
|
||||
|
||||
/// Import the texture into wgpu, with automatic fallback to CPU texture
|
||||
fn import_to_wgpu(&self, device: &wgpu::Device) -> TextureImportResult;
|
||||
|
||||
/// Check if hardware acceleration is available for this texture
|
||||
fn supports_hardware_acceleration(&self, device: &wgpu::Device) -> bool;
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
use cef::AcceleratedPaintInfo;
|
||||
|
||||
use super::{TextureImportError, TextureImportResult, TextureImporter};
|
||||
|
||||
pub(crate) enum SharedTextureHandle {
|
||||
#[cfg(target_os = "linux")]
|
||||
DmaBuf(super::dmabuf::DmaBufImporter),
|
||||
#[cfg(target_os = "windows")]
|
||||
D3D11(super::d3d11::D3D11Importer),
|
||||
#[cfg(target_os = "macos")]
|
||||
IOSurface(super::iosurface::IOSurfaceImporter),
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
impl SharedTextureHandle {
|
||||
pub(crate) fn new(info: &AcceleratedPaintInfo) -> Self {
|
||||
// Extract DMA-BUF information
|
||||
#[cfg(target_os = "linux")]
|
||||
return Self::DmaBuf(super::dmabuf::DmaBufImporter::new(info));
|
||||
|
||||
// Extract D3D11 shared handle with texture metadata
|
||||
#[cfg(target_os = "windows")]
|
||||
return Self::D3D11(super::d3d11::D3D11Importer::new(info));
|
||||
|
||||
// Extract IOSurface handle with texture metadata
|
||||
#[cfg(target_os = "macos")]
|
||||
return Self::IOSurface(super::iosurface::IOSurfaceImporter::new(info));
|
||||
|
||||
#[allow(unreachable_code)]
|
||||
Self::Unsupported
|
||||
}
|
||||
|
||||
/// Import a texture using the appropriate platform-specific importer
|
||||
pub(crate) fn import_texture(self, device: &wgpu::Device) -> TextureImportResult {
|
||||
match self {
|
||||
#[cfg(target_os = "linux")]
|
||||
SharedTextureHandle::DmaBuf(importer) => importer.import_to_wgpu(device),
|
||||
#[cfg(target_os = "windows")]
|
||||
SharedTextureHandle::D3D11(importer) => importer.import_to_wgpu(device),
|
||||
#[cfg(target_os = "macos")]
|
||||
SharedTextureHandle::IOSurface(importer) => importer.import_to_wgpu(device),
|
||||
SharedTextureHandle::Unsupported => Err(TextureImportError::UnsupportedPlatform),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#[derive(clap::Parser)]
|
||||
#[clap(name = "graphite-editor", version)]
|
||||
pub struct Cli {
|
||||
#[arg(help = "Files to open on startup")]
|
||||
pub files: Vec<std::path::PathBuf>,
|
||||
|
||||
#[arg(long, action = clap::ArgAction::SetTrue, help = "Disable hardware accelerated UI rendering")]
|
||||
pub disable_ui_acceleration: bool,
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
pub(crate) static APP_NAME: &str = "Graphite";
|
||||
pub(crate) static APP_ID: &str = "rs.graphite.GraphiteEditor";
|
||||
pub(crate) const APP_NAME: &str = "Graphite";
|
||||
pub(crate) const APP_ID: &str = "rs.graphite.GraphiteEditor";
|
||||
|
||||
pub(crate) static APP_DIRECTORY_NAME: &str = "graphite-editor";
|
||||
pub(crate) static APP_STATE_FILE_NAME: &str = "state.ron";
|
||||
pub(crate) static APP_PREFERENCES_FILE_NAME: &str = "preferences.ron";
|
||||
pub(crate) static APP_DOCUMENTS_DIRECTORY_NAME: &str = "documents";
|
||||
pub(crate) const APP_DIRECTORY_NAME: &str = "graphite-editor";
|
||||
pub(crate) const APP_STATE_FILE_NAME: &str = "state.ron";
|
||||
pub(crate) const APP_PREFERENCES_FILE_NAME: &str = "preferences.ron";
|
||||
pub(crate) const APP_DOCUMENTS_DIRECTORY_NAME: &str = "documents";
|
||||
|
||||
// CEF configuration constants
|
||||
pub(crate) const CEF_WINDOWLESS_FRAME_RATE: i32 = 60;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use graphite_desktop_wrapper::NodeGraphExecutionResult;
|
||||
use graphite_desktop_wrapper::messages::DesktopWrapperMessage;
|
||||
use crate::wrapper::NodeGraphExecutionResult;
|
||||
use crate::wrapper::messages::DesktopWrapperMessage;
|
||||
|
||||
pub(crate) enum AppEvent {
|
||||
UiUpdate(wgpu::Texture),
|
||||
@@ -9,6 +9,7 @@ pub(crate) enum AppEvent {
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
CloseWindow,
|
||||
MenuEvent { id: u64 },
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use graphite_desktop_wrapper::{WgpuContext, WgpuContextBuilder, WgpuFeatures};
|
||||
use crate::wrapper::{WgpuContext, WgpuContextBuilder, WgpuFeatures};
|
||||
|
||||
pub(super) async fn create_wgpu_context() -> WgpuContext {
|
||||
let wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::PUSH_CONSTANTS);
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
use clap::Parser;
|
||||
use std::process::exit;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
pub(crate) mod consts;
|
||||
|
||||
mod app;
|
||||
mod cef;
|
||||
mod cli;
|
||||
mod dirs;
|
||||
mod event;
|
||||
mod persist;
|
||||
mod render;
|
||||
mod window;
|
||||
|
||||
mod gpu_context;
|
||||
|
||||
pub(crate) use graphite_desktop_wrapper as wrapper;
|
||||
|
||||
use app::App;
|
||||
use cef::CefHandler;
|
||||
use cli::Cli;
|
||||
use event::CreateAppEventSchedulerEventLoopExt;
|
||||
|
||||
pub fn start() {
|
||||
tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).init();
|
||||
|
||||
let cef_context_builder = cef::CefContextBuilder::<CefHandler>::new();
|
||||
|
||||
if cef_context_builder.is_sub_process() {
|
||||
// We are in a CEF subprocess
|
||||
// This will block until the CEF subprocess quits
|
||||
let error = cef_context_builder.execute_sub_process();
|
||||
tracing::warn!("Cef subprocess failed with error: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
let cli = Cli::parse();
|
||||
|
||||
let wgpu_context = futures::executor::block_on(gpu_context::create_wgpu_context());
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let (app_event_sender, app_event_receiver) = std::sync::mpsc::channel();
|
||||
let app_event_scheduler = event_loop.create_app_event_scheduler(app_event_sender);
|
||||
|
||||
let (cef_view_info_sender, cef_view_info_receiver) = std::sync::mpsc::channel();
|
||||
|
||||
let cef_handler = cef::CefHandler::new(wgpu_context.clone(), app_event_scheduler.clone(), cef_view_info_receiver);
|
||||
let cef_context = match cef_context_builder.initialize(cef_handler, cli.disable_ui_acceleration) {
|
||||
Ok(c) => {
|
||||
tracing::info!("CEF initialized successfully");
|
||||
c
|
||||
}
|
||||
Err(cef::InitError::AlreadyRunning) => {
|
||||
tracing::error!("Another instance is already running, Exiting.");
|
||||
exit(0);
|
||||
}
|
||||
Err(cef::InitError::InitializationFailed(code)) => {
|
||||
tracing::error!("Cef initialization failed with code: {code}");
|
||||
exit(1);
|
||||
}
|
||||
Err(cef::InitError::BrowserCreationFailed) => {
|
||||
tracing::error!("Failed to create CEF browser");
|
||||
exit(1);
|
||||
}
|
||||
Err(cef::InitError::RequestContextCreationFailed) => {
|
||||
tracing::error!("Failed to create CEF request context");
|
||||
exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
let mut app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, cli.files);
|
||||
|
||||
event_loop.run_app(&mut app).unwrap();
|
||||
}
|
||||
|
||||
pub fn start_helper() {
|
||||
let cef_context_builder = cef::CefContextBuilder::<CefHandler>::new_helper();
|
||||
assert!(cef_context_builder.is_sub_process());
|
||||
cef_context_builder.execute_sub_process();
|
||||
}
|
||||
+1
-67
@@ -1,69 +1,3 @@
|
||||
use std::process::exit;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
pub(crate) mod consts;
|
||||
|
||||
mod app;
|
||||
mod cef;
|
||||
mod dirs;
|
||||
mod event;
|
||||
mod native_window;
|
||||
mod persist;
|
||||
mod render;
|
||||
|
||||
mod gpu_context;
|
||||
|
||||
use app::App;
|
||||
use cef::CefHandler;
|
||||
use event::CreateAppEventSchedulerEventLoopExt;
|
||||
|
||||
fn main() {
|
||||
tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).init();
|
||||
|
||||
let cef_context_builder = cef::CefContextBuilder::<CefHandler>::new();
|
||||
|
||||
if cef_context_builder.is_sub_process() {
|
||||
// We are in a CEF subprocess
|
||||
// This will block until the CEF subprocess quits
|
||||
let error = cef_context_builder.execute_sub_process();
|
||||
tracing::warn!("Cef subprocess failed with error: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
let wgpu_context = futures::executor::block_on(gpu_context::create_wgpu_context());
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let (app_event_sender, app_event_receiver) = std::sync::mpsc::channel();
|
||||
let app_event_scheduler = event_loop.create_app_event_scheduler(app_event_sender);
|
||||
|
||||
let (window_size_sender, window_size_receiver) = std::sync::mpsc::channel();
|
||||
|
||||
let cef_handler = cef::CefHandler::new(wgpu_context.clone(), app_event_scheduler.clone(), window_size_receiver);
|
||||
let cef_context = match cef_context_builder.initialize(cef_handler) {
|
||||
Ok(c) => {
|
||||
tracing::info!("CEF initialized successfully");
|
||||
c
|
||||
}
|
||||
Err(cef::InitError::AlreadyRunning) => {
|
||||
tracing::error!("Another instance is already running, Exiting.");
|
||||
exit(0);
|
||||
}
|
||||
Err(cef::InitError::InitializationFailed(code)) => {
|
||||
tracing::error!("Cef initialization failed with code: {code}");
|
||||
exit(1);
|
||||
}
|
||||
Err(cef::InitError::BrowserCreationFailed) => {
|
||||
tracing::error!("Failed to create CEF browser");
|
||||
exit(1);
|
||||
}
|
||||
Err(cef::InitError::RequestContextCreationFailed) => {
|
||||
tracing::error!("Failed to create CEF request context");
|
||||
exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
let mut app = App::new(Box::new(cef_context), window_size_sender, wgpu_context, app_event_receiver, app_event_scheduler);
|
||||
|
||||
event_loop.run_app(&mut app).unwrap();
|
||||
graphite_desktop::start();
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
use winit::window::{Window, WindowAttributes};
|
||||
|
||||
use crate::consts::APP_NAME;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows;
|
||||
|
||||
pub(crate) enum NativeWindowHandle {
|
||||
#[cfg(target_os = "windows")]
|
||||
#[expect(private_interfaces, dead_code)]
|
||||
Windows(windows::WindowsNativeWindowHandle),
|
||||
None,
|
||||
}
|
||||
impl Default for NativeWindowHandle {
|
||||
fn default() -> Self {
|
||||
Self::None
|
||||
}
|
||||
}
|
||||
impl NativeWindowHandle {
|
||||
#[allow(unused_variables)]
|
||||
pub(super) fn build(&mut self, event_loop: &dyn ActiveEventLoop) -> WindowAttributes {
|
||||
let mut window = WindowAttributes::default()
|
||||
.with_title(APP_NAME)
|
||||
.with_min_surface_size(winit::dpi::LogicalSize::new(400, 300))
|
||||
.with_surface_size(winit::dpi::LogicalSize::new(1200, 800))
|
||||
.with_resizable(true)
|
||||
.with_theme(Some(winit::window::Theme::Dark));
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
use crate::consts::{APP_ID, APP_NAME};
|
||||
use winit::platform::wayland::ActiveEventLoopExtWayland;
|
||||
use winit::platform::wayland::WindowAttributesWayland;
|
||||
use winit::platform::x11::WindowAttributesX11;
|
||||
window = if event_loop.is_wayland() {
|
||||
let wayland_window = WindowAttributesWayland::default().with_name(APP_ID, "").with_prefer_csd(true);
|
||||
window.with_platform_attributes(Box::new(wayland_window))
|
||||
} else {
|
||||
let x11_window = WindowAttributesX11::default().with_name(APP_ID, APP_NAME);
|
||||
window.with_platform_attributes(Box::new(x11_window))
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
if let Ok(win_icon) = winit::platform::windows::WinIcon::from_resource(1, None) {
|
||||
let icon = winit::icon::Icon(std::sync::Arc::new(win_icon));
|
||||
window = window.with_window_icon(Some(icon));
|
||||
}
|
||||
}
|
||||
|
||||
window
|
||||
}
|
||||
#[allow(unused_variables)]
|
||||
pub(crate) fn setup(&mut self, window: &dyn Window) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
*self = NativeWindowHandle::Windows(windows::WindowsNativeWindowHandle::new(window));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use graphite_desktop_wrapper::messages::{Document, DocumentId, Preferences};
|
||||
use crate::wrapper::messages::{Document, DocumentId, Preferences};
|
||||
|
||||
#[derive(Default, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct PersistentData {
|
||||
@@ -6,14 +6,13 @@ pub(crate) struct PersistentData {
|
||||
current_document: Option<DocumentId>,
|
||||
#[serde(skip)]
|
||||
document_order: Option<Vec<DocumentId>>,
|
||||
preferences: Option<Preferences>,
|
||||
}
|
||||
|
||||
impl PersistentData {
|
||||
pub(crate) fn write_document(&mut self, id: DocumentId, document: Document) {
|
||||
self.documents.write(id, document);
|
||||
if let Some(order) = &self.document_order {
|
||||
self.documents.force_order(order.clone());
|
||||
self.documents.force_order(order);
|
||||
}
|
||||
self.flush();
|
||||
}
|
||||
@@ -171,10 +170,10 @@ impl DocumentStore {
|
||||
})
|
||||
}
|
||||
|
||||
fn force_order(&mut self, desired_order: Vec<DocumentId>) {
|
||||
fn force_order(&mut self, desired_order: &Vec<DocumentId>) {
|
||||
let mut ordered_prefix_len = 0;
|
||||
for id in desired_order {
|
||||
if let Some(offset) = self.0[ordered_prefix_len..].iter().position(|meta| meta.id == id) {
|
||||
if let Some(offset) = self.0[ordered_prefix_len..].iter().position(|meta| meta.id == *id) {
|
||||
let found_index = ordered_prefix_len + offset;
|
||||
if found_index != ordered_prefix_len {
|
||||
self.0[ordered_prefix_len..=found_index].rotate_right(1);
|
||||
|
||||
@@ -8,15 +8,9 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
|
||||
let pos = array(
|
||||
// 1st triangle
|
||||
vec2f( -1.0, -1.0), // center
|
||||
vec2f( 1.0, -1.0), // right, center
|
||||
vec2f( -1.0, 1.0), // center, top
|
||||
|
||||
// 2nd triangle
|
||||
vec2f( -1.0, 1.0), // center, top
|
||||
vec2f( 1.0, -1.0), // right, center
|
||||
vec2f( 1.0, 1.0), // right, top
|
||||
vec2f( -1.0, -1.0),
|
||||
vec2f( 3.0, -1.0),
|
||||
vec2f( -1.0, 3.0),
|
||||
);
|
||||
let xy = pos[vertex_index];
|
||||
out.clip_position = vec4f(xy , 0.0, 1.0);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::sync::Arc;
|
||||
use winit::window::Window;
|
||||
use crate::window::Window;
|
||||
|
||||
use graphite_desktop_wrapper::{Color, WgpuContext, WgpuExecutor};
|
||||
use crate::wrapper::{Color, WgpuContext, WgpuExecutor};
|
||||
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Debug)]
|
||||
@@ -24,10 +23,9 @@ pub(crate) struct GraphicsState {
|
||||
}
|
||||
|
||||
impl GraphicsState {
|
||||
pub(crate) fn new(window: Arc<dyn Window>, context: WgpuContext) -> Self {
|
||||
pub(crate) fn new(window: &Window, context: WgpuContext) -> Self {
|
||||
let size = window.surface_size();
|
||||
|
||||
let surface = context.instance.create_surface(window).unwrap();
|
||||
let surface = window.create_surface(context.instance.clone());
|
||||
|
||||
let surface_caps = surface.get_capabilities(&context.adapter);
|
||||
let surface_format = surface_caps.formats.iter().find(|f| f.is_srgb()).copied().unwrap_or(surface_caps.formats[0]);
|
||||
@@ -232,7 +230,7 @@ impl GraphicsState {
|
||||
self.bind_overlays_texture(texture);
|
||||
}
|
||||
|
||||
pub(crate) fn render(&mut self, window: &dyn Window) -> Result<(), wgpu::SurfaceError> {
|
||||
pub(crate) fn render(&mut self, window: &Window) -> Result<(), wgpu::SurfaceError> {
|
||||
if let Some(scene) = self.overlays_scene.take() {
|
||||
self.render_overlays(scene);
|
||||
}
|
||||
@@ -252,6 +250,7 @@ impl GraphicsState {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.01, g: 0.01, b: 0.01, a: 1.0 }),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
depth_slice: None,
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
occlusion_query_set: None,
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
use std::sync::Arc;
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
use winit::window::{Window as WinitWindow, WindowAttributes};
|
||||
|
||||
use crate::consts::APP_NAME;
|
||||
use crate::event::AppEventScheduler;
|
||||
use crate::wrapper::messages::MenuItem;
|
||||
|
||||
pub(crate) trait NativeWindow {
|
||||
fn configure(attributes: WindowAttributes, event_loop: &dyn ActiveEventLoop) -> WindowAttributes;
|
||||
fn new(window: &dyn WinitWindow, app_event_scheduler: AppEventScheduler) -> Self;
|
||||
fn update_menu(&self, _entries: Vec<MenuItem>) {}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "linux")]
|
||||
use linux as native;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac;
|
||||
#[cfg(target_os = "macos")]
|
||||
use mac as native;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod win;
|
||||
#[cfg(target_os = "windows")]
|
||||
use win as native;
|
||||
|
||||
pub(crate) struct Window {
|
||||
winit_window: Arc<dyn winit::window::Window>,
|
||||
#[allow(dead_code)]
|
||||
native_handle: native::NativeWindowImpl,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
pub(crate) fn new(event_loop: &dyn ActiveEventLoop, app_event_scheduler: AppEventScheduler) -> Self {
|
||||
let mut attributes = WindowAttributes::default()
|
||||
.with_title(APP_NAME)
|
||||
.with_min_surface_size(winit::dpi::LogicalSize::new(400, 300))
|
||||
.with_surface_size(winit::dpi::LogicalSize::new(1200, 800))
|
||||
.with_resizable(true)
|
||||
.with_theme(Some(winit::window::Theme::Dark));
|
||||
|
||||
attributes = native::NativeWindowImpl::configure(attributes, event_loop);
|
||||
|
||||
let winit_window = event_loop.create_window(attributes).unwrap();
|
||||
let native_handle = native::NativeWindowImpl::new(winit_window.as_ref(), app_event_scheduler);
|
||||
Self {
|
||||
winit_window: winit_window.into(),
|
||||
native_handle,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn request_redraw(&self) {
|
||||
self.winit_window.request_redraw();
|
||||
}
|
||||
|
||||
pub(crate) fn create_surface(&self, instance: Arc<wgpu::Instance>) -> wgpu::Surface<'static> {
|
||||
instance.create_surface(self.winit_window.clone()).unwrap()
|
||||
}
|
||||
|
||||
pub(crate) fn pre_present_notify(&self) {
|
||||
self.winit_window.pre_present_notify();
|
||||
}
|
||||
|
||||
pub(crate) fn surface_size(&self) -> winit::dpi::PhysicalSize<u32> {
|
||||
self.winit_window.surface_size()
|
||||
}
|
||||
|
||||
pub(crate) fn scale_factor(&self) -> f64 {
|
||||
self.winit_window.scale_factor()
|
||||
}
|
||||
|
||||
pub(crate) fn minimize(&self) {
|
||||
self.winit_window.set_minimized(true);
|
||||
}
|
||||
|
||||
pub(crate) fn toggle_maximize(&self) {
|
||||
self.winit_window.set_maximized(!self.winit_window.is_maximized());
|
||||
}
|
||||
|
||||
pub(crate) fn is_maximized(&self) -> bool {
|
||||
self.winit_window.is_maximized()
|
||||
}
|
||||
|
||||
pub(crate) fn start_drag(&self) {
|
||||
let _ = self.winit_window.drag_window();
|
||||
}
|
||||
|
||||
pub(crate) fn set_cursor(&self, cursor: winit::cursor::Cursor) {
|
||||
self.winit_window.set_cursor(cursor);
|
||||
}
|
||||
|
||||
pub(crate) fn update_menu(&self, entries: Vec<MenuItem>) {
|
||||
self.native_handle.update_menu(entries);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
use winit::platform::wayland::ActiveEventLoopExtWayland;
|
||||
use winit::platform::wayland::WindowAttributesWayland;
|
||||
use winit::platform::x11::WindowAttributesX11;
|
||||
use winit::window::{Window, WindowAttributes};
|
||||
|
||||
use crate::consts::{APP_ID, APP_NAME};
|
||||
use crate::event::AppEventScheduler;
|
||||
|
||||
pub(super) struct NativeWindowImpl {}
|
||||
|
||||
impl super::NativeWindow for NativeWindowImpl {
|
||||
fn configure(attributes: WindowAttributes, event_loop: &dyn ActiveEventLoop) -> WindowAttributes {
|
||||
if event_loop.is_wayland() {
|
||||
let wayland_attributes = WindowAttributesWayland::default().with_name(APP_ID, "").with_prefer_csd(true);
|
||||
attributes.with_platform_attributes(Box::new(wayland_attributes))
|
||||
} else {
|
||||
let x11_attributes = WindowAttributesX11::default().with_name(APP_ID, APP_NAME);
|
||||
attributes.with_platform_attributes(Box::new(x11_attributes))
|
||||
}
|
||||
}
|
||||
|
||||
fn new(_window: &dyn Window, _app_event_scheduler: AppEventScheduler) -> Self {
|
||||
NativeWindowImpl {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
use winit::window::{Window, WindowAttributes};
|
||||
|
||||
use crate::consts::APP_NAME;
|
||||
use crate::event::AppEventScheduler;
|
||||
use crate::wrapper::messages::MenuItem;
|
||||
|
||||
pub(super) struct NativeWindowImpl {
|
||||
menu: menu::Menu,
|
||||
}
|
||||
|
||||
impl super::NativeWindow for NativeWindowImpl {
|
||||
fn configure(attributes: WindowAttributes, _event_loop: &dyn ActiveEventLoop) -> WindowAttributes {
|
||||
let mac_window = winit::platform::macos::WindowAttributesMacOS::default()
|
||||
.with_titlebar_transparent(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_title_hidden(true);
|
||||
attributes.with_platform_attributes(Box::new(mac_window))
|
||||
}
|
||||
|
||||
fn new(_window: &dyn Window, app_event_scheduler: AppEventScheduler) -> Self {
|
||||
let menu = menu::Menu::new(app_event_scheduler, APP_NAME);
|
||||
|
||||
NativeWindowImpl { menu }
|
||||
}
|
||||
|
||||
fn update_menu(&self, entries: Vec<MenuItem>) {
|
||||
self.menu.update(entries);
|
||||
}
|
||||
}
|
||||
|
||||
mod menu;
|
||||
@@ -0,0 +1,156 @@
|
||||
use muda::Menu as MudaMenu;
|
||||
use muda::accelerator::Accelerator;
|
||||
use muda::{AboutMetadataBuilder, CheckMenuItem, IsMenuItem, MenuEvent, MenuId, MenuItem, MenuItemKind, PredefinedMenuItem, Result, Submenu};
|
||||
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::wrapper::messages::MenuItem as WrapperMenuItem;
|
||||
|
||||
pub(super) struct Menu {
|
||||
inner: MudaMenu,
|
||||
}
|
||||
|
||||
impl Menu {
|
||||
pub(super) fn new(event_scheduler: AppEventScheduler, app_name: &str) -> Self {
|
||||
let about = PredefinedMenuItem::about(None, Some(AboutMetadataBuilder::new().name(Some(app_name)).build()));
|
||||
let hide = PredefinedMenuItem::hide(None);
|
||||
let hide_others = PredefinedMenuItem::hide_others(None);
|
||||
let show_all = PredefinedMenuItem::show_all(None);
|
||||
let quit = PredefinedMenuItem::quit(None);
|
||||
let app_submenu = Submenu::with_items(
|
||||
"",
|
||||
true,
|
||||
&[&about, &PredefinedMenuItem::separator(), &hide, &hide_others, &show_all, &PredefinedMenuItem::separator(), &quit],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let menu = MudaMenu::new();
|
||||
menu.prepend(&app_submenu).unwrap();
|
||||
|
||||
menu.init_for_nsapp();
|
||||
|
||||
MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
|
||||
if let Some(id) = menu_id_to_u64(event.id()) {
|
||||
event_scheduler.schedule(AppEvent::MenuEvent { id });
|
||||
}
|
||||
}));
|
||||
|
||||
Menu { inner: menu }
|
||||
}
|
||||
|
||||
pub(super) fn update(&self, entries: Vec<WrapperMenuItem>) {
|
||||
let new_entries = menu_items_from_wrapper(entries);
|
||||
let existing_entries = self.inner.items();
|
||||
|
||||
let mut new_entries_iter = new_entries.iter();
|
||||
let mut existing_entries_iter = existing_entries.iter().skip(1); // Skip first menu (app menu)
|
||||
|
||||
let incremental_update_ok = std::iter::from_fn(move || match (existing_entries_iter.next(), new_entries_iter.next()) {
|
||||
(Some(MenuItemKind::Submenu(old)), Some(MenuItemKind::Submenu(new))) if old.text() == new.text() => {
|
||||
replace_children(old, 0, new.items());
|
||||
Some(true)
|
||||
}
|
||||
(None, None) => None,
|
||||
_ => Some(false),
|
||||
})
|
||||
.all(|b| b);
|
||||
|
||||
if !incremental_update_ok {
|
||||
// Fallback to full replace
|
||||
replace_children(&self.inner, 1, new_entries); // Skip first menu (app menu)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn menu_items_from_wrapper(entries: Vec<WrapperMenuItem>) -> Vec<MenuItemKind> {
|
||||
let mut menu_items: Vec<MenuItemKind> = Vec::new();
|
||||
for entry in entries {
|
||||
match entry {
|
||||
WrapperMenuItem::Action { id, text, enabled, shortcut } => {
|
||||
let id = u64_to_menu_id(id);
|
||||
let accelerator = shortcut.map(|s| Accelerator::new(Some(s.modifiers), s.key));
|
||||
let item = MenuItem::with_id(id, text, enabled, accelerator);
|
||||
menu_items.push(MenuItemKind::MenuItem(item));
|
||||
}
|
||||
WrapperMenuItem::Checkbox { id, text, enabled, shortcut, checked } => {
|
||||
let id = u64_to_menu_id(id);
|
||||
let accelerator = shortcut.map(|s| Accelerator::new(Some(s.modifiers), s.key));
|
||||
let check = CheckMenuItem::with_id(id, text, enabled, checked, accelerator);
|
||||
menu_items.push(MenuItemKind::Check(check));
|
||||
}
|
||||
WrapperMenuItem::SubMenu { text: name, items, .. } => {
|
||||
let items = menu_items_from_wrapper(items);
|
||||
let items = items.iter().map(|item| menu_item_kind_to_dyn(item)).collect::<Vec<&dyn IsMenuItem>>();
|
||||
let submenu = Submenu::with_items(name, true, &items).unwrap();
|
||||
menu_items.push(MenuItemKind::Submenu(submenu));
|
||||
}
|
||||
WrapperMenuItem::Separator => {
|
||||
let separator = PredefinedMenuItem::separator();
|
||||
menu_items.push(MenuItemKind::Predefined(separator));
|
||||
}
|
||||
}
|
||||
}
|
||||
menu_items
|
||||
}
|
||||
|
||||
fn menu_item_kind_to_dyn(item: &MenuItemKind) -> &dyn IsMenuItem {
|
||||
match item {
|
||||
MenuItemKind::MenuItem(i) => i,
|
||||
MenuItemKind::Submenu(i) => i,
|
||||
MenuItemKind::Predefined(i) => i,
|
||||
MenuItemKind::Check(i) => i,
|
||||
MenuItemKind::Icon(i) => i,
|
||||
}
|
||||
}
|
||||
|
||||
fn u64_to_menu_id(id: u64) -> String {
|
||||
format!("{id:08x}")
|
||||
}
|
||||
|
||||
fn menu_id_to_u64(id: &MenuId) -> Option<u64> {
|
||||
u64::from_str_radix(&id.0, 16).ok()
|
||||
}
|
||||
|
||||
fn replace_children<'a, T: Into<MenuContainer<'a>>>(menu: T, skip: usize, new_items: Vec<MenuItemKind>) {
|
||||
let menu: MenuContainer = menu.into();
|
||||
let items = menu.items();
|
||||
for item in items.iter().skip(skip) {
|
||||
menu.remove(menu_item_kind_to_dyn(item)).unwrap();
|
||||
}
|
||||
let items = new_items.iter().map(|item| menu_item_kind_to_dyn(item)).collect::<Vec<&dyn IsMenuItem>>();
|
||||
menu.append_items(items.as_ref()).unwrap();
|
||||
}
|
||||
|
||||
enum MenuContainer<'a> {
|
||||
Menu(&'a MudaMenu),
|
||||
Submenu(&'a Submenu),
|
||||
}
|
||||
impl<'a> MenuContainer<'a> {
|
||||
fn items(&self) -> Vec<MenuItemKind> {
|
||||
match self {
|
||||
MenuContainer::Menu(menu) => menu.items(),
|
||||
MenuContainer::Submenu(submenu) => submenu.items(),
|
||||
}
|
||||
}
|
||||
fn remove(&self, item: &dyn IsMenuItem) -> Result<()> {
|
||||
match self {
|
||||
MenuContainer::Menu(menu) => menu.remove(item),
|
||||
MenuContainer::Submenu(submenu) => submenu.remove(item),
|
||||
}
|
||||
}
|
||||
fn append_items(&self, items: &[&dyn IsMenuItem]) -> Result<()> {
|
||||
match self {
|
||||
MenuContainer::Menu(menu) => menu.append_items(items),
|
||||
MenuContainer::Submenu(submenu) => submenu.append_items(items),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'a> From<&'a MudaMenu> for MenuContainer<'a> {
|
||||
fn from(menu: &'a MudaMenu) -> Self {
|
||||
MenuContainer::Menu(menu)
|
||||
}
|
||||
}
|
||||
impl<'a> From<&'a Submenu> for MenuContainer<'a> {
|
||||
fn from(submenu: &'a Submenu) -> Self {
|
||||
MenuContainer::Submenu(submenu)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
use winit::window::{Window, WindowAttributes};
|
||||
|
||||
use crate::event::AppEventScheduler;
|
||||
|
||||
pub(super) struct NativeWindowImpl {
|
||||
native_handle: native_handle::NativeWindowHandle,
|
||||
}
|
||||
|
||||
impl super::NativeWindow for NativeWindowImpl {
|
||||
fn configure(attributes: WindowAttributes, _event_loop: &dyn ActiveEventLoop) -> WindowAttributes {
|
||||
if let Ok(win_icon) = winit::platform::windows::WinIcon::from_resource(1, None) {
|
||||
let icon = winit::icon::Icon(std::sync::Arc::new(win_icon));
|
||||
attributes.with_window_icon(Some(icon))
|
||||
} else {
|
||||
attributes
|
||||
}
|
||||
}
|
||||
|
||||
fn new(window: &dyn Window, _app_event_scheduler: AppEventScheduler) -> Self {
|
||||
let native_handle = native_handle::NativeWindowHandle::new(window);
|
||||
NativeWindowImpl { native_handle }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NativeWindowImpl {
|
||||
fn drop(&mut self) {
|
||||
self.native_handle.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
mod native_handle;
|
||||
@@ -21,29 +21,14 @@ use windows::Win32::UI::WindowsAndMessaging::*;
|
||||
use windows::core::PCWSTR;
|
||||
use winit::window::Window;
|
||||
|
||||
pub(super) struct WindowsNativeWindowHandle {
|
||||
inner: WindowsNativeWindowHandleInner,
|
||||
}
|
||||
impl WindowsNativeWindowHandle {
|
||||
pub(super) fn new(window: &dyn Window) -> Self {
|
||||
let inner = WindowsNativeWindowHandleInner::new(window);
|
||||
WindowsNativeWindowHandle { inner }
|
||||
}
|
||||
}
|
||||
impl Drop for WindowsNativeWindowHandle {
|
||||
fn drop(&mut self) {
|
||||
self.inner.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct WindowsNativeWindowHandleInner {
|
||||
pub(super) struct NativeWindowHandle {
|
||||
main: HWND,
|
||||
helper: HWND,
|
||||
prev_window_message_handler: isize,
|
||||
}
|
||||
impl WindowsNativeWindowHandleInner {
|
||||
fn new(window: &dyn Window) -> WindowsNativeWindowHandleInner {
|
||||
impl NativeWindowHandle {
|
||||
pub(super) fn new(window: &dyn Window) -> NativeWindowHandle {
|
||||
// Extract Win32 HWND from winit.
|
||||
let hwnd = match window.window_handle().expect("No window handle").as_raw() {
|
||||
RawWindowHandle::Win32(h) => HWND(h.hwnd.get() as *mut std::ffi::c_void),
|
||||
@@ -85,7 +70,7 @@ impl WindowsNativeWindowHandleInner {
|
||||
panic!("SetWindowLongPtrW failed");
|
||||
}
|
||||
|
||||
let inner = WindowsNativeWindowHandleInner {
|
||||
let inner = NativeWindowHandle {
|
||||
main: hwnd,
|
||||
helper,
|
||||
prev_window_message_handler,
|
||||
@@ -115,7 +100,7 @@ impl WindowsNativeWindowHandleInner {
|
||||
inner
|
||||
}
|
||||
|
||||
fn destroy(&self) {
|
||||
pub(super) fn destroy(&self) {
|
||||
registry::remove_by_main(self.main);
|
||||
|
||||
// Undo subclassing and destroy the helper window.
|
||||
@@ -130,13 +115,13 @@ mod registry {
|
||||
use std::cell::RefCell;
|
||||
use windows::Win32::Foundation::HWND;
|
||||
|
||||
use crate::native_window::windows::WindowsNativeWindowHandleInner;
|
||||
use super::NativeWindowHandle;
|
||||
|
||||
thread_local! {
|
||||
static STORE: RefCell<Vec<WindowsNativeWindowHandleInner>> = RefCell::new(Vec::new());
|
||||
static STORE: RefCell<Vec<NativeWindowHandle>> = RefCell::new(Vec::new());
|
||||
}
|
||||
|
||||
pub(super) fn find_by_main(main: HWND) -> Option<WindowsNativeWindowHandleInner> {
|
||||
pub(super) fn find_by_main(main: HWND) -> Option<NativeWindowHandle> {
|
||||
STORE.with_borrow(|vec| vec.iter().find(|h| h.main == main).cloned())
|
||||
}
|
||||
pub(super) fn remove_by_main(main: HWND) {
|
||||
@@ -144,7 +129,7 @@ mod registry {
|
||||
vec.retain(|h| h.main != main);
|
||||
});
|
||||
}
|
||||
pub(super) fn insert(handle: &WindowsNativeWindowHandleInner) {
|
||||
pub(super) fn insert(handle: &NativeWindowHandle) {
|
||||
STORE.with_borrow_mut(|vec| {
|
||||
vec.push(handle.clone());
|
||||
});
|
||||
@@ -31,3 +31,5 @@ ron = { workspace = true}
|
||||
vello = { workspace = true }
|
||||
image = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
keyboard-types = { workspace = true }
|
||||
@@ -1,7 +1,9 @@
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
use graphite_editor::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use graphite_editor::messages::prelude::{AppWindowMessage, DocumentMessage, FrontendMessage, PortfolioMessage, PreferencesMessage};
|
||||
use graphite_editor::messages::layout::LayoutMessage;
|
||||
use graphite_editor::messages::prelude::*;
|
||||
use graphite_editor::messages::tool::tool_messages::tool_prelude::{LayoutTarget, WidgetId};
|
||||
|
||||
use crate::messages::Platform;
|
||||
|
||||
@@ -55,7 +57,7 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
document_path: Some(path),
|
||||
document_serialized_content: content,
|
||||
};
|
||||
dispatcher.queue_editor_message(message.into());
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::ImportFile { path, content } => {
|
||||
let extension = path.extension().and_then(|s| s.to_str()).unwrap_or_default().to_lowercase();
|
||||
@@ -80,7 +82,7 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
};
|
||||
dispatcher.queue_editor_message(message.into());
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::ImportImage { path, content } => {
|
||||
let name = path.file_stem().and_then(|s| s.to_str()).map(|s| s.to_string());
|
||||
@@ -106,7 +108,7 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
};
|
||||
dispatcher.queue_editor_message(message.into());
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
|
||||
DesktopWrapperMessage::UpdatePlatform(platform) => {
|
||||
@@ -116,11 +118,11 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
Platform::Linux => AppWindowPlatform::Linux,
|
||||
};
|
||||
let message = AppWindowMessage::AppWindowUpdatePlatform { platform };
|
||||
dispatcher.queue_editor_message(message.into());
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::UpdateMaximized { maximized } => {
|
||||
let message = FrontendMessage::UpdateMaximized { maximized };
|
||||
dispatcher.queue_editor_message(message.into());
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::LoadDocument {
|
||||
id,
|
||||
@@ -138,15 +140,23 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
to_front,
|
||||
select_after_open,
|
||||
};
|
||||
dispatcher.queue_editor_message(message.into());
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::SelectDocument { id } => {
|
||||
let message = PortfolioMessage::SelectDocument { document_id: id };
|
||||
dispatcher.queue_editor_message(message.into());
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::LoadPreferences { preferences } => {
|
||||
let message = PreferencesMessage::Load { preferences };
|
||||
dispatcher.queue_editor_message(message.into());
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
DesktopWrapperMessage::MenuEvent { id } => {
|
||||
let message = LayoutMessage::WidgetValueUpdate {
|
||||
layout_target: LayoutTarget::MenuBar,
|
||||
widget_id: WidgetId(id),
|
||||
value: serde_json::Value::Bool(true),
|
||||
};
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,7 @@
|
||||
use graphite_editor::messages::prelude::InputPreprocessorMessage;
|
||||
|
||||
use super::DesktopWrapperMessageDispatcher;
|
||||
use super::messages::{DesktopFrontendMessage, EditorMessage};
|
||||
use super::messages::EditorMessage;
|
||||
|
||||
pub(super) fn intercept_editor_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: EditorMessage) -> Option<EditorMessage> {
|
||||
match message {
|
||||
EditorMessage::InputPreprocessor(message) => {
|
||||
if let InputPreprocessorMessage::BoundsOfViewports { bounds_of_viewports } = &message {
|
||||
let top_left = bounds_of_viewports[0].top_left;
|
||||
let bottom_right = bounds_of_viewports[0].bottom_right;
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateViewportBounds {
|
||||
x: top_left.x as f32,
|
||||
y: top_left.y as f32,
|
||||
width: (bottom_right.x - top_left.x) as f32,
|
||||
height: (bottom_right.y - top_left.y) as f32,
|
||||
});
|
||||
}
|
||||
Some(EditorMessage::InputPreprocessor(message))
|
||||
}
|
||||
m => Some(m),
|
||||
}
|
||||
pub(super) fn intercept_editor_message(_dispatcher: &mut DesktopWrapperMessageDispatcher, message: EditorMessage) -> Option<EditorMessage> {
|
||||
// TODO: remove it turns out to be unnecessary
|
||||
Some(message)
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, LayoutKey, LayoutKeysGroup};
|
||||
use graphite_editor::messages::input_mapper::utility_types::misc::ActionKeys;
|
||||
use graphite_editor::messages::layout::utility_types::widgets::menu_widgets::MenuBarEntry;
|
||||
use graphite_editor::messages::prelude::FrontendMessage;
|
||||
|
||||
use super::DesktopWrapperMessageDispatcher;
|
||||
use super::messages::{DesktopFrontendMessage, Document, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
|
||||
use super::messages::{DesktopFrontendMessage, Document, FileFilter, KeyCode, MenuItem, Modifiers, OpenFileDialogContext, SaveFileDialogContext, Shortcut};
|
||||
|
||||
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
|
||||
match message {
|
||||
@@ -76,12 +79,15 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerMaximizeWindow => {
|
||||
dispatcher.respond(DesktopFrontendMessage::MaximizeWindow);
|
||||
}
|
||||
FrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height });
|
||||
}
|
||||
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document, details } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
|
||||
id: document_id,
|
||||
document: Document {
|
||||
name: details.name,
|
||||
path: None,
|
||||
path: details.path,
|
||||
content: document,
|
||||
is_saved: details.is_saved,
|
||||
},
|
||||
@@ -110,13 +116,213 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerLoadRestAutoSaveDocuments => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadRemainingDocuments);
|
||||
}
|
||||
FrontendMessage::TriggerOpenLaunchDocuments => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
|
||||
}
|
||||
FrontendMessage::TriggerSavePreferences { preferences } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceWritePreferences { preferences });
|
||||
}
|
||||
FrontendMessage::TriggerLoadPreferences => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadPreferences);
|
||||
}
|
||||
FrontendMessage::UpdateMenuBarLayout { layout_target, layout } => {
|
||||
let entries = convert_menu_bar_entries_to_menu_items(&layout);
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateMenu { entries });
|
||||
|
||||
return Some(FrontendMessage::UpdateMenuBarLayout { layout, layout_target });
|
||||
}
|
||||
m => return Some(m),
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn convert_menu_bar_entries_to_menu_items(layout: &[MenuBarEntry]) -> Vec<MenuItem> {
|
||||
layout.iter().filter_map(convert_menu_bar_entry_to_menu_item).collect()
|
||||
}
|
||||
|
||||
fn convert_menu_bar_entry_to_menu_item(
|
||||
MenuBarEntry {
|
||||
label,
|
||||
icon,
|
||||
shortcut,
|
||||
action,
|
||||
children,
|
||||
disabled,
|
||||
}: &MenuBarEntry,
|
||||
) -> Option<MenuItem> {
|
||||
let id = action.widget_id.0;
|
||||
let text = if label.is_empty() {
|
||||
return None;
|
||||
} else {
|
||||
label.clone()
|
||||
};
|
||||
let enabled = !*disabled;
|
||||
|
||||
if !children.0.is_empty() {
|
||||
let items = convert_menu_bar_entry_children_to_menu_items(&children.0);
|
||||
return Some(MenuItem::SubMenu { id, text, enabled, items });
|
||||
}
|
||||
|
||||
let shortcut = match shortcut {
|
||||
Some(ActionKeys::Keys(LayoutKeysGroup(keys))) => convert_layout_keys_to_shortcut(keys),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// TODO: Find a better way to determine if this is a checkbox
|
||||
match icon.as_deref() {
|
||||
Some("CheckboxChecked") => {
|
||||
return Some(MenuItem::Checkbox {
|
||||
id,
|
||||
text,
|
||||
enabled,
|
||||
shortcut,
|
||||
checked: true,
|
||||
});
|
||||
}
|
||||
Some("CheckboxUnchecked") => {
|
||||
return Some(MenuItem::Checkbox {
|
||||
id,
|
||||
text,
|
||||
enabled,
|
||||
shortcut,
|
||||
checked: false,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Some(MenuItem::Action { id, text, shortcut, enabled })
|
||||
}
|
||||
|
||||
fn convert_menu_bar_entry_children_to_menu_items(children: &[Vec<MenuBarEntry>]) -> Vec<MenuItem> {
|
||||
let mut items = Vec::new();
|
||||
for (i, section) in children.iter().enumerate() {
|
||||
for entry in section.iter() {
|
||||
if let Some(item) = convert_menu_bar_entry_to_menu_item(entry) {
|
||||
items.push(item);
|
||||
}
|
||||
}
|
||||
if i != children.len() - 1 {
|
||||
items.push(MenuItem::Separator);
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
fn convert_layout_keys_to_shortcut(layout_keys: &Vec<LayoutKey>) -> Option<Shortcut> {
|
||||
let mut key: Option<KeyCode> = None;
|
||||
let mut modifiers = Modifiers::default();
|
||||
for layout_key in layout_keys {
|
||||
match layout_key.key {
|
||||
Key::Shift => modifiers |= Modifiers::SHIFT,
|
||||
Key::Control => modifiers |= Modifiers::CONTROL,
|
||||
Key::Alt => modifiers |= Modifiers::ALT,
|
||||
Key::Meta => modifiers |= Modifiers::META,
|
||||
Key::Command => modifiers |= Modifiers::ALT,
|
||||
Key::Accel => modifiers |= Modifiers::META,
|
||||
Key::Digit0 => key = Some(KeyCode::Digit0),
|
||||
Key::Digit1 => key = Some(KeyCode::Digit1),
|
||||
Key::Digit2 => key = Some(KeyCode::Digit2),
|
||||
Key::Digit3 => key = Some(KeyCode::Digit3),
|
||||
Key::Digit4 => key = Some(KeyCode::Digit4),
|
||||
Key::Digit5 => key = Some(KeyCode::Digit5),
|
||||
Key::Digit6 => key = Some(KeyCode::Digit6),
|
||||
Key::Digit7 => key = Some(KeyCode::Digit7),
|
||||
Key::Digit8 => key = Some(KeyCode::Digit8),
|
||||
Key::Digit9 => key = Some(KeyCode::Digit9),
|
||||
Key::KeyA => key = Some(KeyCode::KeyA),
|
||||
Key::KeyB => key = Some(KeyCode::KeyB),
|
||||
Key::KeyC => key = Some(KeyCode::KeyC),
|
||||
Key::KeyD => key = Some(KeyCode::KeyD),
|
||||
Key::KeyE => key = Some(KeyCode::KeyE),
|
||||
Key::KeyF => key = Some(KeyCode::KeyF),
|
||||
Key::KeyG => key = Some(KeyCode::KeyG),
|
||||
Key::KeyH => key = Some(KeyCode::KeyH),
|
||||
Key::KeyI => key = Some(KeyCode::KeyI),
|
||||
Key::KeyJ => key = Some(KeyCode::KeyJ),
|
||||
Key::KeyK => key = Some(KeyCode::KeyK),
|
||||
Key::KeyL => key = Some(KeyCode::KeyL),
|
||||
Key::KeyM => key = Some(KeyCode::KeyM),
|
||||
Key::KeyN => key = Some(KeyCode::KeyN),
|
||||
Key::KeyO => key = Some(KeyCode::KeyO),
|
||||
Key::KeyP => key = Some(KeyCode::KeyP),
|
||||
Key::KeyQ => key = Some(KeyCode::KeyQ),
|
||||
Key::KeyR => key = Some(KeyCode::KeyR),
|
||||
Key::KeyS => key = Some(KeyCode::KeyS),
|
||||
Key::KeyT => key = Some(KeyCode::KeyT),
|
||||
Key::KeyU => key = Some(KeyCode::KeyU),
|
||||
Key::KeyV => key = Some(KeyCode::KeyV),
|
||||
Key::KeyW => key = Some(KeyCode::KeyW),
|
||||
Key::KeyX => key = Some(KeyCode::KeyX),
|
||||
Key::KeyY => key = Some(KeyCode::KeyY),
|
||||
Key::KeyZ => key = Some(KeyCode::KeyZ),
|
||||
Key::Backquote => key = Some(KeyCode::Backquote),
|
||||
Key::Backslash => key = Some(KeyCode::Backslash),
|
||||
Key::BracketLeft => key = Some(KeyCode::BracketLeft),
|
||||
Key::BracketRight => key = Some(KeyCode::BracketRight),
|
||||
Key::Comma => key = Some(KeyCode::Comma),
|
||||
Key::Equal => key = Some(KeyCode::Equal),
|
||||
Key::Minus => key = Some(KeyCode::Minus),
|
||||
Key::Period => key = Some(KeyCode::Period),
|
||||
Key::Quote => key = Some(KeyCode::Quote),
|
||||
Key::Semicolon => key = Some(KeyCode::Semicolon),
|
||||
Key::Slash => key = Some(KeyCode::Slash),
|
||||
Key::Backspace => key = Some(KeyCode::Backspace),
|
||||
Key::CapsLock => key = Some(KeyCode::CapsLock),
|
||||
Key::ContextMenu => key = Some(KeyCode::ContextMenu),
|
||||
Key::Enter => key = Some(KeyCode::Enter),
|
||||
Key::Space => key = Some(KeyCode::Space),
|
||||
Key::Tab => key = Some(KeyCode::Tab),
|
||||
Key::Delete => key = Some(KeyCode::Delete),
|
||||
Key::End => key = Some(KeyCode::End),
|
||||
Key::Help => key = Some(KeyCode::Help),
|
||||
Key::Home => key = Some(KeyCode::Home),
|
||||
Key::Insert => key = Some(KeyCode::Insert),
|
||||
Key::PageDown => key = Some(KeyCode::PageDown),
|
||||
Key::PageUp => key = Some(KeyCode::PageUp),
|
||||
Key::ArrowDown => key = Some(KeyCode::ArrowDown),
|
||||
Key::ArrowLeft => key = Some(KeyCode::ArrowLeft),
|
||||
Key::ArrowRight => key = Some(KeyCode::ArrowRight),
|
||||
Key::ArrowUp => key = Some(KeyCode::ArrowUp),
|
||||
Key::NumLock => key = Some(KeyCode::NumLock),
|
||||
Key::NumpadAdd => key = Some(KeyCode::NumpadAdd),
|
||||
Key::NumpadHash => key = Some(KeyCode::NumpadHash),
|
||||
Key::NumpadMultiply => key = Some(KeyCode::NumpadMultiply),
|
||||
Key::NumpadParenLeft => key = Some(KeyCode::NumpadParenLeft),
|
||||
Key::NumpadParenRight => key = Some(KeyCode::NumpadParenRight),
|
||||
Key::Escape => key = Some(KeyCode::Escape),
|
||||
Key::F1 => key = Some(KeyCode::F1),
|
||||
Key::F2 => key = Some(KeyCode::F2),
|
||||
Key::F3 => key = Some(KeyCode::F3),
|
||||
Key::F4 => key = Some(KeyCode::F4),
|
||||
Key::F5 => key = Some(KeyCode::F5),
|
||||
Key::F6 => key = Some(KeyCode::F6),
|
||||
Key::F7 => key = Some(KeyCode::F7),
|
||||
Key::F8 => key = Some(KeyCode::F8),
|
||||
Key::F9 => key = Some(KeyCode::F9),
|
||||
Key::F10 => key = Some(KeyCode::F10),
|
||||
Key::F11 => key = Some(KeyCode::F11),
|
||||
Key::F12 => key = Some(KeyCode::F12),
|
||||
Key::F13 => key = Some(KeyCode::F13),
|
||||
Key::F14 => key = Some(KeyCode::F14),
|
||||
Key::F15 => key = Some(KeyCode::F15),
|
||||
Key::F16 => key = Some(KeyCode::F16),
|
||||
Key::F17 => key = Some(KeyCode::F17),
|
||||
Key::F18 => key = Some(KeyCode::F18),
|
||||
Key::F19 => key = Some(KeyCode::F19),
|
||||
Key::F20 => key = Some(KeyCode::F20),
|
||||
Key::F21 => key = Some(KeyCode::F21),
|
||||
Key::F22 => key = Some(KeyCode::F22),
|
||||
Key::F23 => key = Some(KeyCode::F23),
|
||||
Key::F24 => key = Some(KeyCode::F24),
|
||||
Key::Fn => key = Some(KeyCode::Fn),
|
||||
Key::FnLock => key = Some(KeyCode::FnLock),
|
||||
Key::PrintScreen => key = Some(KeyCode::PrintScreen),
|
||||
Key::ScrollLock => key = Some(KeyCode::ScrollLock),
|
||||
Key::Pause => key = Some(KeyCode::Pause),
|
||||
Key::Unidentified => key = Some(KeyCode::Unidentified),
|
||||
_ => key = None,
|
||||
}
|
||||
}
|
||||
key.map(|key| Shortcut { key, modifiers })
|
||||
}
|
||||
@@ -32,8 +32,8 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
|
||||
self.desktop_wrapper_message_queue.push_back(message);
|
||||
}
|
||||
|
||||
pub(super) fn queue_editor_message(&mut self, message: EditorMessage) {
|
||||
if let Some(message) = intercept_editor_message(self, message) {
|
||||
pub(super) fn queue_editor_message<T: Into<EditorMessage>>(&mut self, message: T) {
|
||||
if let Some(message) = intercept_editor_message(self, message.into()) {
|
||||
self.editor_message_queue.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
pub use graphite_editor::messages::prelude::DocumentId;
|
||||
use graphite_editor::messages::prelude::FrontendMessage;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
|
||||
|
||||
pub use graphite_editor::messages::prelude::DocumentId;
|
||||
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
|
||||
|
||||
pub enum DesktopFrontendMessage {
|
||||
ToWeb(Vec<FrontendMessage>),
|
||||
OpenLaunchDocuments,
|
||||
OpenFileDialog {
|
||||
title: String,
|
||||
filters: Vec<FileFilter>,
|
||||
@@ -25,11 +25,11 @@ pub enum DesktopFrontendMessage {
|
||||
content: Vec<u8>,
|
||||
},
|
||||
OpenUrl(String),
|
||||
UpdateViewportBounds {
|
||||
x: f32,
|
||||
y: f32,
|
||||
width: f32,
|
||||
height: f32,
|
||||
UpdateViewportPhysicalBounds {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
},
|
||||
UpdateOverlays(vello::Scene),
|
||||
MinimizeWindow,
|
||||
@@ -55,6 +55,9 @@ pub enum DesktopFrontendMessage {
|
||||
preferences: Preferences,
|
||||
},
|
||||
PersistenceLoadPreferences,
|
||||
UpdateMenu {
|
||||
entries: Vec<MenuItem>,
|
||||
},
|
||||
}
|
||||
|
||||
pub enum DesktopWrapperMessage {
|
||||
@@ -105,6 +108,9 @@ pub enum DesktopWrapperMessage {
|
||||
LoadPreferences {
|
||||
preferences: Option<Preferences>,
|
||||
},
|
||||
MenuEvent {
|
||||
id: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
|
||||
@@ -135,3 +141,32 @@ pub enum Platform {
|
||||
Mac,
|
||||
Linux,
|
||||
}
|
||||
|
||||
pub enum MenuItem {
|
||||
Action {
|
||||
id: u64,
|
||||
text: String,
|
||||
enabled: bool,
|
||||
shortcut: Option<Shortcut>,
|
||||
},
|
||||
Checkbox {
|
||||
id: u64,
|
||||
text: String,
|
||||
enabled: bool,
|
||||
shortcut: Option<Shortcut>,
|
||||
checked: bool,
|
||||
},
|
||||
SubMenu {
|
||||
id: u64,
|
||||
text: String,
|
||||
enabled: bool,
|
||||
items: Vec<MenuItem>,
|
||||
},
|
||||
Separator,
|
||||
}
|
||||
|
||||
pub use keyboard_types::{Code as KeyCode, Modifiers};
|
||||
pub struct Shortcut {
|
||||
pub key: KeyCode,
|
||||
pub modifiers: Modifiers,
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use crate::messages::prelude::*;
|
||||
pub struct Dispatcher {
|
||||
message_queues: Vec<VecDeque<Message>>,
|
||||
pub responses: Vec<FrontendMessage>,
|
||||
pub frontend_update_messages: Vec<Message>,
|
||||
pub message_handlers: DispatcherMessageHandlers,
|
||||
}
|
||||
|
||||
@@ -26,6 +27,7 @@ pub struct DispatcherMessageHandlers {
|
||||
pub portfolio_message_handler: PortfolioMessageHandler,
|
||||
preferences_message_handler: PreferencesMessageHandler,
|
||||
tool_message_handler: ToolMessageHandler,
|
||||
viewport_message_handler: ViewportMessageHandler,
|
||||
}
|
||||
|
||||
impl DispatcherMessageHandlers {
|
||||
@@ -41,19 +43,24 @@ impl DispatcherMessageHandlers {
|
||||
/// The last occurrence of the message in the message queue is sufficient to ensure correct behavior.
|
||||
/// In addition, these messages do not change any state in the backend (aside from caches).
|
||||
const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::PropertiesPanel(
|
||||
PropertiesPanelMessageDiscriminant::Refresh,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::DocumentStructureChanged)),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::Overlays(OverlaysMessageDiscriminant::Draw))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::RunDocumentGraph,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitActiveGraphRender),
|
||||
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::TriggerFontLoad),
|
||||
];
|
||||
/// Since we don't need to update the frontend multiple times per frame,
|
||||
/// we have a set of messages which we will buffer until the next frame is requested.
|
||||
const FRONTEND_UPDATE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::PropertiesPanel(
|
||||
PropertiesPanelMessageDiscriminant::Refresh,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::UpdateDocumentWidgets),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::Overlays(OverlaysMessageDiscriminant::Draw))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::RenderRulers)),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::RenderScrollbars)),
|
||||
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateDocumentLayerStructure),
|
||||
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::TriggerFontLoad),
|
||||
];
|
||||
const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
|
||||
MessageDiscriminant::Broadcast(BroadcastMessageDiscriminant::TriggerEvent(EventMessageDiscriminant::AnimationFrame)),
|
||||
@@ -104,6 +111,19 @@ impl Dispatcher {
|
||||
|
||||
while let Some(message) = self.message_queues.last_mut().and_then(VecDeque::pop_front) {
|
||||
// Skip processing of this message if it will be processed later (at the end of the shallowest level queue)
|
||||
if FRONTEND_UPDATE_MESSAGES.contains(&message.to_discriminant()) {
|
||||
let already_in_queue = self.message_queues.first().is_some_and(|queue| queue.contains(&message));
|
||||
if already_in_queue {
|
||||
self.cleanup_queues(false);
|
||||
continue;
|
||||
} else if self.message_queues.len() > 1 {
|
||||
if !self.frontend_update_messages.contains(&message) {
|
||||
self.frontend_update_messages.push(message);
|
||||
}
|
||||
self.cleanup_queues(false);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if SIDE_EFFECT_FREE_MESSAGES.contains(&message.to_discriminant()) {
|
||||
let already_in_queue = self.message_queues.first().filter(|queue| queue.contains(&message)).is_some();
|
||||
if already_in_queue {
|
||||
@@ -127,6 +147,9 @@ impl Dispatcher {
|
||||
// Process the action by forwarding it to the relevant message handler, or saving the FrontendMessage to be sent to the frontend
|
||||
match message {
|
||||
Message::Animation(message) => {
|
||||
if let AnimationMessage::IncrementFrameCounter = &message {
|
||||
self.message_queues[0].extend(self.frontend_update_messages.drain(..));
|
||||
}
|
||||
self.message_handlers.animation_message_handler.process_message(message, &mut queue, ());
|
||||
}
|
||||
Message::AppWindow(message) => {
|
||||
@@ -146,7 +169,6 @@ impl Dispatcher {
|
||||
let context = DialogMessageContext {
|
||||
portfolio: &self.message_handlers.portfolio_message_handler,
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
viewport_bounds: &self.message_handlers.input_preprocessor_message_handler.viewport_bounds,
|
||||
};
|
||||
self.message_handlers.dialog_message_handler.process_message(message, &mut queue, context);
|
||||
}
|
||||
@@ -169,9 +191,14 @@ impl Dispatcher {
|
||||
Message::InputPreprocessor(message) => {
|
||||
let keyboard_platform = GLOBAL_PLATFORM.get().copied().unwrap_or_default().as_keyboard_platform_layout();
|
||||
|
||||
self.message_handlers
|
||||
.input_preprocessor_message_handler
|
||||
.process_message(message, &mut queue, InputPreprocessorMessageContext { keyboard_platform });
|
||||
self.message_handlers.input_preprocessor_message_handler.process_message(
|
||||
message,
|
||||
&mut queue,
|
||||
InputPreprocessorMessageContext {
|
||||
keyboard_platform,
|
||||
viewport: &self.message_handlers.viewport_message_handler,
|
||||
},
|
||||
);
|
||||
}
|
||||
Message::KeyMapping(message) => {
|
||||
let input = &self.message_handlers.input_preprocessor_message_handler;
|
||||
@@ -195,6 +222,7 @@ impl Dispatcher {
|
||||
let reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open;
|
||||
let timing_information = self.message_handlers.animation_message_handler.timing_information();
|
||||
let animation = &self.message_handlers.animation_message_handler;
|
||||
let viewport = &self.message_handlers.viewport_message_handler;
|
||||
|
||||
self.message_handlers.portfolio_message_handler.process_message(
|
||||
message,
|
||||
@@ -207,6 +235,7 @@ impl Dispatcher {
|
||||
reset_node_definitions_on_open,
|
||||
timing_information,
|
||||
animation,
|
||||
viewport,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -230,10 +259,14 @@ impl Dispatcher {
|
||||
persistent_data: &self.message_handlers.portfolio_message_handler.persistent_data,
|
||||
node_graph: &self.message_handlers.portfolio_message_handler.executor,
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
viewport: &self.message_handlers.viewport_message_handler,
|
||||
};
|
||||
|
||||
self.message_handlers.tool_message_handler.process_message(message, &mut queue, context);
|
||||
}
|
||||
Message::Viewport(message) => {
|
||||
self.message_handlers.viewport_message_handler.process_message(message, &mut queue, ());
|
||||
}
|
||||
Message::NoOp => {}
|
||||
Message::Batched { messages } => {
|
||||
messages.into_iter().for_each(|message| self.handle_message(message, false));
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
use super::new_document_dialog::NewDocumentDialogMessageContext;
|
||||
use super::simple_dialogs::{self, AboutGraphiteDialog, ComingSoonDialog, DemoArtworkDialog, LicensesDialog};
|
||||
use crate::messages::dialog::simple_dialogs::LicensesThirdPartyDialog;
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::ViewportBounds;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct DialogMessageContext<'a> {
|
||||
pub portfolio: &'a PortfolioMessageHandler,
|
||||
pub viewport_bounds: &'a ViewportBounds,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
}
|
||||
|
||||
@@ -23,15 +20,11 @@ pub struct DialogMessageHandler {
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHandler {
|
||||
fn process_message(&mut self, message: DialogMessage, responses: &mut VecDeque<Message>, context: DialogMessageContext) {
|
||||
let DialogMessageContext {
|
||||
portfolio,
|
||||
preferences,
|
||||
viewport_bounds,
|
||||
} = context;
|
||||
let DialogMessageContext { portfolio, preferences } = context;
|
||||
|
||||
match message {
|
||||
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
|
||||
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, NewDocumentDialogMessageContext { viewport_bounds }),
|
||||
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
|
||||
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
|
||||
|
||||
DialogMessage::CloseAllDocumentsWithConfirmation => {
|
||||
|
||||
@@ -4,4 +4,4 @@ mod new_document_dialog_message_handler;
|
||||
#[doc(inline)]
|
||||
pub use new_document_dialog_message::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use new_document_dialog_message_handler::{NewDocumentDialogMessageContext, NewDocumentDialogMessageHandler};
|
||||
pub use new_document_dialog_message_handler::NewDocumentDialogMessageHandler;
|
||||
+6
-14
@@ -1,13 +1,8 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::{input_mapper::utility_types::input_mouse::ViewportBounds, layout::utility_types::widget_prelude::*};
|
||||
use glam::{IVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct NewDocumentDialogMessageContext<'a> {
|
||||
pub viewport_bounds: &'a ViewportBounds,
|
||||
}
|
||||
|
||||
/// A dialog to allow users to set some initial options about a new document.
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
pub struct NewDocumentDialogMessageHandler {
|
||||
@@ -17,8 +12,8 @@ pub struct NewDocumentDialogMessageHandler {
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<NewDocumentDialogMessage, NewDocumentDialogMessageContext<'a>> for NewDocumentDialogMessageHandler {
|
||||
fn process_message(&mut self, message: NewDocumentDialogMessage, responses: &mut VecDeque<Message>, context: NewDocumentDialogMessageContext<'a>) {
|
||||
impl<'a> MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHandler {
|
||||
fn process_message(&mut self, message: NewDocumentDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
|
||||
match message {
|
||||
NewDocumentDialogMessage::Name { name } => self.name = name,
|
||||
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
|
||||
@@ -35,12 +30,9 @@ impl<'a> MessageHandler<NewDocumentDialogMessage, NewDocumentDialogMessageContex
|
||||
});
|
||||
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
// If we already have bounds, we won't receive a viewport bounds update so we just fabricate one ourselves
|
||||
if *context.viewport_bounds != ViewportBounds::default() {
|
||||
responses.add(InputPreprocessorMessage::BoundsOfViewports {
|
||||
bounds_of_viewports: vec![context.viewport_bounds.clone()],
|
||||
});
|
||||
}
|
||||
|
||||
responses.add(ViewportMessage::RepropagateUpdate);
|
||||
|
||||
responses.add(DeferMessage::AfterNavigationReady {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into(), DocumentMessage::DeselectAllLayers.into()],
|
||||
});
|
||||
|
||||
@@ -102,6 +102,7 @@ pub enum FrontendMessage {
|
||||
},
|
||||
TriggerLoadFirstAutoSaveDocument,
|
||||
TriggerLoadRestAutoSaveDocuments,
|
||||
TriggerOpenLaunchDocuments,
|
||||
TriggerLoadPreferences,
|
||||
TriggerOpenDocument,
|
||||
TriggerPaste,
|
||||
@@ -349,6 +350,12 @@ pub enum FrontendMessage {
|
||||
UpdateViewportHolePunch {
|
||||
active: bool,
|
||||
},
|
||||
UpdateViewportPhysicalBounds {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
},
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
RenderOverlays {
|
||||
#[serde(skip, default = "OverlayContext::default")]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
@@ -10,6 +12,7 @@ pub struct OpenDocument {
|
||||
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub struct DocumentDetails {
|
||||
pub name: String,
|
||||
pub path: Option<PathBuf>,
|
||||
#[serde(rename = "isSaved")]
|
||||
pub is_saved: bool,
|
||||
#[serde(rename = "isAutoSaved")]
|
||||
|
||||
@@ -304,16 +304,13 @@ impl fmt::Display for Key {
|
||||
|
||||
impl From<Key> for LayoutKey {
|
||||
fn from(key: Key) -> Self {
|
||||
Self {
|
||||
key: format!("{key:?}"),
|
||||
label: key.to_string(),
|
||||
}
|
||||
Self { key, label: key.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
struct LayoutKey {
|
||||
key: String,
|
||||
pub struct LayoutKey {
|
||||
pub key: Key,
|
||||
label: String,
|
||||
}
|
||||
|
||||
@@ -359,7 +356,7 @@ impl From<KeysGroup> for String {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub struct LayoutKeysGroup(Vec<LayoutKey>);
|
||||
pub struct LayoutKeysGroup(pub Vec<LayoutKey>);
|
||||
|
||||
impl From<KeysGroup> for LayoutKeysGroup {
|
||||
fn from(keys_group: KeysGroup) -> Self {
|
||||
|
||||
@@ -3,41 +3,13 @@ use crate::messages::prelude::*;
|
||||
use bitflags::bitflags;
|
||||
use glam::DVec2;
|
||||
use std::collections::VecDeque;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
// Origin is top left
|
||||
pub type DocumentPosition = DVec2;
|
||||
pub type ViewportPosition = DVec2;
|
||||
pub type EditorPosition = DVec2;
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ViewportBounds {
|
||||
pub top_left: DVec2,
|
||||
pub bottom_right: DVec2,
|
||||
}
|
||||
|
||||
impl ViewportBounds {
|
||||
pub fn from_slice(slice: &[f64]) -> Self {
|
||||
Self {
|
||||
top_left: DVec2::from_slice(&slice[0..2]),
|
||||
bottom_right: DVec2::from_slice(&slice[2..4]),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size(&self) -> DVec2 {
|
||||
(self.bottom_right - self.top_left).ceil()
|
||||
}
|
||||
|
||||
pub fn center(&self) -> DVec2 {
|
||||
(self.bottom_right - self.top_left).ceil() / 2.
|
||||
}
|
||||
|
||||
pub fn in_bounds(&self, position: ViewportPosition) -> bool {
|
||||
position.x >= 0. && position.y >= 0. && position.x <= self.bottom_right.x && position.y <= self.bottom_right.y
|
||||
}
|
||||
}
|
||||
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
#[derive(Debug, Copy, Clone, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ScrollDelta {
|
||||
pub x: f64,
|
||||
@@ -113,9 +85,9 @@ impl EditorMouseState {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_mouse_state(&self, active_viewport_bounds: &ViewportBounds) -> MouseState {
|
||||
pub fn to_mouse_state(&self, viewport: &ViewportMessageHandler) -> MouseState {
|
||||
MouseState {
|
||||
position: self.editor_position - active_viewport_bounds.top_left,
|
||||
position: (viewport.logical(self.editor_position) - viewport.offset()).into(),
|
||||
mouse_keys: self.mouse_keys,
|
||||
scroll_delta: self.scroll_delta,
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ViewportBounds};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::EditorMouseState;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, InputPreprocessor)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum InputPreprocessorMessage {
|
||||
BoundsOfViewports { bounds_of_viewports: Vec<ViewportBounds> },
|
||||
DoubleClick { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
KeyDown { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
|
||||
KeyUp { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{MouseButton, MouseKeys, MouseState, ViewportBounds};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{MouseButton, MouseKeys, MouseState};
|
||||
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
|
||||
use crate::messages::portfolio::utility_types::KeyboardPlatformLayout;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::DVec2;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct InputPreprocessorMessageContext {
|
||||
pub struct InputPreprocessorMessageContext<'a> {
|
||||
pub keyboard_platform: KeyboardPlatformLayout,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
@@ -17,38 +17,18 @@ pub struct InputPreprocessorMessageHandler {
|
||||
pub time: u64,
|
||||
pub keyboard: KeyStates,
|
||||
pub mouse: MouseState,
|
||||
pub viewport_bounds: ViewportBounds,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext> for InputPreprocessorMessageHandler {
|
||||
fn process_message(&mut self, message: InputPreprocessorMessage, responses: &mut VecDeque<Message>, context: InputPreprocessorMessageContext) {
|
||||
let InputPreprocessorMessageContext { keyboard_platform } = context;
|
||||
impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext<'a>> for InputPreprocessorMessageHandler {
|
||||
fn process_message(&mut self, message: InputPreprocessorMessage, responses: &mut VecDeque<Message>, context: InputPreprocessorMessageContext<'a>) {
|
||||
let InputPreprocessorMessageContext { keyboard_platform, viewport } = context;
|
||||
|
||||
match message {
|
||||
InputPreprocessorMessage::BoundsOfViewports { bounds_of_viewports } => {
|
||||
assert_eq!(bounds_of_viewports.len(), 1, "Only one viewport is currently supported");
|
||||
|
||||
for bounds in bounds_of_viewports {
|
||||
// TODO: Extend this to multiple viewports instead of setting it to the value of this last loop iteration
|
||||
self.viewport_bounds = bounds;
|
||||
|
||||
responses.add(NavigationMessage::CanvasPan { delta: DVec2::ZERO });
|
||||
responses.add(NodeGraphMessage::SetGridAlignedEdges);
|
||||
}
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![
|
||||
DeferMessage::AfterGraphRun {
|
||||
messages: vec![DeferMessage::TriggerNavigationReady.into()],
|
||||
}
|
||||
.into(),
|
||||
],
|
||||
});
|
||||
}
|
||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(&self.viewport_bounds);
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
for key in mouse_state.mouse_keys {
|
||||
@@ -81,7 +61,7 @@ impl MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext> f
|
||||
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(&self.viewport_bounds);
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
self.translate_mouse_event(mouse_state, true, responses);
|
||||
@@ -89,7 +69,7 @@ impl MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext> f
|
||||
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(&self.viewport_bounds);
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
responses.add(InputMapperMessage::PointerMove);
|
||||
@@ -100,7 +80,7 @@ impl MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext> f
|
||||
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(&self.viewport_bounds);
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
self.translate_mouse_event(mouse_state, false, responses);
|
||||
@@ -108,7 +88,7 @@ impl MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext> f
|
||||
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(&self.viewport_bounds);
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
|
||||
responses.add(InputMapperMessage::PointerShake);
|
||||
@@ -121,7 +101,7 @@ impl MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContext> f
|
||||
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, keyboard_platform, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(&self.viewport_bounds);
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
self.mouse.scroll_delta = mouse_state.scroll_delta;
|
||||
|
||||
@@ -202,11 +182,6 @@ impl InputPreprocessorMessageHandler {
|
||||
responses.add(InputMapperMessage::KeyDown(key));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn document_bounds(&self) -> [DVec2; 2] {
|
||||
// IPP bounds are relative to the entire application
|
||||
[(0., 0.).into(), self.viewport_bounds.bottom_right - self.viewport_bounds.top_left]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -232,6 +207,7 @@ mod test {
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
keyboard_platform: KeyboardPlatformLayout::Standard,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
|
||||
@@ -251,6 +227,7 @@ mod test {
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
keyboard_platform: KeyboardPlatformLayout::Standard,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
|
||||
@@ -270,6 +247,7 @@ mod test {
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
keyboard_platform: KeyboardPlatformLayout::Standard,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
|
||||
@@ -291,6 +269,7 @@ mod test {
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
keyboard_platform: KeyboardPlatformLayout::Standard,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
|
||||
@@ -311,6 +290,7 @@ mod test {
|
||||
|
||||
let context = InputPreprocessorMessageContext {
|
||||
keyboard_platform: KeyboardPlatformLayout::Standard,
|
||||
viewport: &ViewportMessageHandler::default(),
|
||||
};
|
||||
input_preprocessor.process_message(message, &mut responses, context);
|
||||
|
||||
|
||||
@@ -484,13 +484,19 @@ impl LayoutGroup {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub struct WidgetHolder {
|
||||
#[serde(rename = "widgetId")]
|
||||
pub widget_id: WidgetId,
|
||||
pub widget: Widget,
|
||||
}
|
||||
|
||||
impl PartialEq for WidgetHolder {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.widget == other.widget
|
||||
}
|
||||
}
|
||||
|
||||
impl WidgetHolder {
|
||||
#[deprecated(since = "0.0.0", note = "Please use the builder pattern, e.g. TextLabel::new(\"hello\").widget_holder()")]
|
||||
pub fn new(widget: Widget) -> Self {
|
||||
@@ -502,6 +508,25 @@ impl WidgetHolder {
|
||||
|
||||
/// Diffing updates self (where self is old) based on new, updating the list of modifications as it does so.
|
||||
pub fn diff(&mut self, new: Self, widget_path: &mut [usize], widget_diffs: &mut Vec<WidgetDiff>) {
|
||||
if let (Widget::PopoverButton(button1), Widget::PopoverButton(button2)) = (&mut self.widget, &new.widget) {
|
||||
if button1.disabled == button2.disabled
|
||||
&& button1.style == button2.style
|
||||
&& button1.menu_direction == button2.menu_direction
|
||||
&& button1.icon == button2.icon
|
||||
&& button1.tooltip == button2.tooltip
|
||||
&& button1.tooltip_shortcut == button2.tooltip_shortcut
|
||||
&& button1.popover_min_width == button2.popover_min_width
|
||||
{
|
||||
let mut new_widget_path = widget_path.to_vec();
|
||||
for (i, (a, b)) in button1.popover_layout.iter_mut().zip(button2.popover_layout.iter()).enumerate() {
|
||||
new_widget_path.push(i);
|
||||
a.diff(b.clone(), &mut new_widget_path, widget_diffs);
|
||||
new_widget_path.pop();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// If there have been changes to the actual widget (not just the id)
|
||||
if self.widget != new.widget {
|
||||
// We should update to the new widget value as well as a new widget id
|
||||
|
||||
@@ -19,6 +19,7 @@ pub struct CheckboxInput {
|
||||
pub tooltip: String,
|
||||
|
||||
#[serde(rename = "forLabel")]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub for_label: CheckboxId,
|
||||
|
||||
#[serde(skip)]
|
||||
|
||||
@@ -36,7 +36,8 @@ pub enum SeparatorType {
|
||||
Section,
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Debug, PartialEq, Eq, Default, WidgetBuilder, specta::Type)]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Debug, Eq, Default, WidgetBuilder, specta::Type)]
|
||||
#[derivative(PartialEq)]
|
||||
pub struct TextLabel {
|
||||
pub disabled: bool,
|
||||
|
||||
@@ -62,6 +63,7 @@ pub struct TextLabel {
|
||||
pub tooltip: String,
|
||||
|
||||
#[serde(rename = "forCheckbox")]
|
||||
#[derivative(PartialEq = "ignore")]
|
||||
pub for_checkbox: CheckboxId,
|
||||
|
||||
// Body
|
||||
|
||||
@@ -33,6 +33,8 @@ pub enum Message {
|
||||
Preferences(PreferencesMessage),
|
||||
#[child]
|
||||
Tool(ToolMessage),
|
||||
#[child]
|
||||
Viewport(ViewportMessage),
|
||||
|
||||
// Messages
|
||||
Batched {
|
||||
|
||||
@@ -16,3 +16,4 @@ pub mod portfolio;
|
||||
pub mod preferences;
|
||||
pub mod prelude;
|
||||
pub mod tool;
|
||||
pub mod viewport;
|
||||
@@ -165,6 +165,7 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
Table<Raster<GPU>>,
|
||||
Table<Color>,
|
||||
Table<GradientStops>,
|
||||
Vec<String>,
|
||||
f64,
|
||||
u32,
|
||||
u64,
|
||||
@@ -203,12 +204,44 @@ trait TableRowLayout {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: TableRowLayout> TableRowLayout for Vec<T> {
|
||||
fn type_name() -> &'static str {
|
||||
"Vec"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("Vec<{}> ({} element{})", T::type_name(), self.len(), if self.len() == 1 { "" } else { "s" })
|
||||
}
|
||||
fn element_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
if let Some(index) = data.desired_path.get(data.current_depth).copied() {
|
||||
if let Some(row) = self.get(index) {
|
||||
data.current_depth += 1;
|
||||
let result = row.layout_with_breadcrumb(data);
|
||||
data.current_depth -= 1;
|
||||
return result;
|
||||
} else {
|
||||
warn!("Desired path truncated");
|
||||
data.desired_path.truncate(data.current_depth);
|
||||
}
|
||||
}
|
||||
|
||||
let mut rows = self
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, row)| vec![TextLabel::new(format!("{index}")).narrow(true).widget_holder(), row.element_widget(index)])
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
rows.insert(0, column_headings(&["", "element"]));
|
||||
|
||||
vec![LayoutGroup::Table { rows }]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: TableRowLayout> TableRowLayout for Table<T> {
|
||||
fn type_name() -> &'static str {
|
||||
"Table"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("Table<{}> ({} row{})", T::type_name(), self.len(), if self.len() == 1 { "" } else { "s" })
|
||||
format!("Table<{}> ({} element{})", T::type_name(), self.len(), if self.len() == 1 { "" } else { "s" })
|
||||
}
|
||||
fn element_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
if let Some(index) = data.desired_path.get(data.current_depth).copied() {
|
||||
@@ -595,7 +628,13 @@ impl TableRowLayout for String {
|
||||
"String"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"String".to_string()
|
||||
// Show the first line, and if there are more, indicate that with an ellipsis
|
||||
let first_line = self.lines().next().unwrap_or("");
|
||||
if self.lines().count() > 1 {
|
||||
format!("\"{} …\"", first_line)
|
||||
} else {
|
||||
format!("\"{}\"", first_line)
|
||||
}
|
||||
}
|
||||
fn element_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let widgets = vec![TextAreaInput::new(self.to_string()).disabled(true).widget_holder()];
|
||||
|
||||
@@ -52,10 +52,10 @@ pub struct DocumentMessageContext<'a> {
|
||||
pub executor: &'a mut NodeGraphExecutor,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub device_pixel_ratio: f64,
|
||||
pub data_panel_open: bool,
|
||||
pub layers_panel_open: bool,
|
||||
pub properties_panel_open: bool,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ExtractField)]
|
||||
@@ -195,9 +195,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
ipp,
|
||||
persistent_data,
|
||||
executor,
|
||||
viewport,
|
||||
current_tool,
|
||||
preferences,
|
||||
device_pixel_ratio,
|
||||
data_panel_open,
|
||||
layers_panel_open,
|
||||
properties_panel_open,
|
||||
@@ -213,6 +213,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
document_ptz: &mut self.document_ptz,
|
||||
graph_view_overlay_open: self.graph_view_overlay_open,
|
||||
preferences,
|
||||
viewport,
|
||||
};
|
||||
|
||||
self.navigation_handler.process_message(message, responses, context);
|
||||
@@ -221,15 +222,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let visibility_settings = self.overlays_visibility_settings;
|
||||
|
||||
// Send the overlays message to the overlays message handler
|
||||
self.overlays_message_handler.process_message(
|
||||
message,
|
||||
responses,
|
||||
OverlaysMessageContext {
|
||||
visibility_settings,
|
||||
ipp,
|
||||
device_pixel_ratio,
|
||||
},
|
||||
);
|
||||
self.overlays_message_handler
|
||||
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
|
||||
}
|
||||
DocumentMessage::PropertiesPanel(message) => {
|
||||
let context = PropertiesPanelMessageContext {
|
||||
@@ -268,6 +262,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
navigation_handler: &self.navigation_handler,
|
||||
preferences,
|
||||
layers_panel_open,
|
||||
viewport,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -380,8 +375,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
|
||||
self.layer_range_selection_reference = None;
|
||||
}
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(ipp, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(ipp, responses),
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, responses),
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
@@ -496,6 +491,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.node_graph_handler.wire_in_progress_from_connector = None;
|
||||
self.node_graph_handler.wire_in_progress_to_connector = None;
|
||||
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: None });
|
||||
} else if !self.breadcrumb_network_path.is_empty() {
|
||||
// Exit one level up if inside a nested network
|
||||
responses.add(DocumentMessage::ExitNestedNetwork { steps_back: 1 });
|
||||
} else {
|
||||
responses.add(DocumentMessage::GraphViewOverlay { open: false });
|
||||
}
|
||||
@@ -833,7 +831,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let scale = DAffine2::from_scale(enlargement_factor);
|
||||
let pivot = DAffine2::from_translation(pivot);
|
||||
let transformation = pivot * scale * pivot.inverse();
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
|
||||
for layer in self.network_interface.shallowest_unique_layers(&[]).filter(|layer| can_move(*layer)) {
|
||||
let to = document_to_viewport.inverse() * self.metadata().downstream_transform_to_viewport(layer);
|
||||
@@ -858,10 +856,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let image_size = DVec2::new(image.width as f64, image.height as f64);
|
||||
|
||||
// Align the layer with the mouse or center of viewport
|
||||
let viewport_location = mouse.map_or(ipp.viewport_bounds.center() + ipp.viewport_bounds.top_left, |pos| pos.into());
|
||||
let viewport_location = mouse.map_or(viewport.center_in_viewport_space().into_dvec2() + viewport.offset().into_dvec2(), |pos| pos.into());
|
||||
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
let center_in_viewport = DAffine2::from_translation(document_to_viewport.inverse().transform_point2(viewport_location - ipp.viewport_bounds.top_left));
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
let center_in_viewport = DAffine2::from_translation(document_to_viewport.inverse().transform_point2(viewport_location - viewport.offset().into_dvec2()));
|
||||
let center_in_viewport_layerspace = center_in_viewport;
|
||||
|
||||
// Make layer the size of the image
|
||||
@@ -910,9 +908,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
mouse,
|
||||
parent_and_insert_index,
|
||||
} => {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
let viewport_location = mouse.map_or(ipp.viewport_bounds.center() + ipp.viewport_bounds.top_left, |pos| pos.into());
|
||||
let center_in_viewport = DAffine2::from_translation(document_to_viewport.inverse().transform_point2(viewport_location - ipp.viewport_bounds.top_left));
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
let viewport_location = mouse.map_or(viewport.center_in_viewport_space().into_dvec2() + viewport.offset().into_dvec2(), |pos| pos.into());
|
||||
let center_in_viewport = DAffine2::from_translation(document_to_viewport.inverse().transform_point2(viewport_location - viewport.offset().into_dvec2()));
|
||||
|
||||
let layer_node_id = NodeId::new();
|
||||
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
|
||||
@@ -967,7 +965,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
} else {
|
||||
&self.document_ptz
|
||||
};
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), current_ptz);
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), current_ptz);
|
||||
|
||||
let ruler_scale = if !self.graph_view_overlay_open {
|
||||
self.navigation_handler.snapped_zoom(current_ptz.zoom())
|
||||
@@ -1003,12 +1001,12 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
});
|
||||
}
|
||||
DocumentMessage::RenderScrollbars => {
|
||||
let document_transform_scale = self.navigation_handler.snapped_zoom(self.document_ptz.zoom());
|
||||
let document_transform_scale = self.navigation_handler.snapped_zoom(self.document_ptz.zoom()) / viewport.scale();
|
||||
|
||||
let scale = 0.5 + ASYMPTOTIC_EFFECT + document_transform_scale * SCALE_EFFECT;
|
||||
|
||||
let viewport_size = ipp.viewport_bounds.size();
|
||||
let viewport_mid = ipp.viewport_bounds.center();
|
||||
let viewport_size = viewport.size().into_dvec2();
|
||||
let viewport_mid = viewport.center_in_viewport_space().into_dvec2();
|
||||
let [bounds1, bounds2] = if !self.graph_view_overlay_open {
|
||||
self.metadata().document_bounds_viewport_space().unwrap_or([viewport_mid; 2])
|
||||
} else {
|
||||
@@ -1047,6 +1045,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::SavedDocument { path } => {
|
||||
self.path = path;
|
||||
|
||||
responses.add(PortfolioMessage::AutoSaveActiveDocument);
|
||||
|
||||
// Update the name to match the file stem
|
||||
let document_name_from_path = self.path.as_ref().and_then(|path| {
|
||||
if path.extension().is_some_and(|e| e == FILE_EXTENSION) {
|
||||
@@ -1328,7 +1328,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
|
||||
for _ in 0..undo_count {
|
||||
self.undo(ipp, responses);
|
||||
self.undo(viewport, responses);
|
||||
}
|
||||
|
||||
self.network_interface.finish_transaction();
|
||||
@@ -1478,7 +1478,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
DocumentMessage::PTZUpdate => {
|
||||
if !self.graph_view_overlay_open {
|
||||
let transform = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
let transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
self.network_interface.set_document_to_viewport_transform(transform);
|
||||
// Ensure selection box is kept in sync with the pointer when the PTZ changes
|
||||
responses.add(SelectToolMessage::PointerMove {
|
||||
@@ -1497,7 +1497,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
let transform = self
|
||||
.navigation_handler
|
||||
.calculate_offset_transform(ipp.viewport_bounds.center(), &network_metadata.persistent_metadata.navigation_metadata.node_graph_ptz);
|
||||
.calculate_offset_transform(viewport.center_in_viewport_space().into(), &network_metadata.persistent_metadata.navigation_metadata.node_graph_ptz);
|
||||
self.network_interface.set_transform(transform, &self.breadcrumb_network_path);
|
||||
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
@@ -1537,7 +1537,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.default_node_template();
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: new_artboard_node,
|
||||
node_template: Box::new(new_artboard_node),
|
||||
});
|
||||
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x: 15, y: -3 });
|
||||
responses.add(GraphOperationMessage::ResizeArtboard {
|
||||
@@ -1651,29 +1651,30 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
impl DocumentMessageHandler {
|
||||
/// Runs an intersection test with all layers and a viewport space quad
|
||||
pub fn intersect_quad<'a>(&'a self, viewport_quad: graphene_std::renderer::Quad, ipp: &InputPreprocessorMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
pub fn intersect_quad<'a>(&'a self, viewport_quad: graphene_std::renderer::Quad, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
let document_quad = document_to_viewport.inverse() * viewport_quad;
|
||||
|
||||
ClickXRayIter::new(&self.network_interface, XRayTarget::Quad(document_quad))
|
||||
}
|
||||
|
||||
/// Runs an intersection test with all layers and a viewport space quad; ignoring artboards
|
||||
pub fn intersect_quad_no_artboards<'a>(&'a self, viewport_quad: graphene_std::renderer::Quad, ipp: &InputPreprocessorMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.intersect_quad(viewport_quad, ipp).filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
pub fn intersect_quad_no_artboards<'a>(&'a self, viewport_quad: graphene_std::renderer::Quad, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.intersect_quad(viewport_quad, viewport).filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
}
|
||||
|
||||
/// Runs an intersection test with all layers and a viewport space subpath
|
||||
pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: Subpath<PointId>, ipp: &InputPreprocessorMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: Subpath<PointId>, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
viewport_polygon.apply_transform(document_to_viewport.inverse());
|
||||
|
||||
ClickXRayIter::new(&self.network_interface, XRayTarget::Polygon(viewport_polygon))
|
||||
}
|
||||
|
||||
/// Runs an intersection test with all layers and a viewport space subpath; ignoring artboards
|
||||
pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: Subpath<PointId>, ipp: &InputPreprocessorMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.intersect_polygon(viewport_polygon, ipp).filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: Subpath<PointId>, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.intersect_polygon(viewport_polygon, viewport)
|
||||
.filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
}
|
||||
|
||||
pub fn is_layer_fully_inside(&self, layer: &LayerNodeIdentifier, quad: graphene_std::renderer::Quad) -> bool {
|
||||
@@ -1699,8 +1700,8 @@ impl DocumentMessageHandler {
|
||||
layer_left >= quad_left && layer_right <= quad_right && layer_top <= quad_top && layer_bottom >= quad_bottom
|
||||
}
|
||||
|
||||
pub fn is_layer_fully_inside_polygon(&self, layer: &LayerNodeIdentifier, ipp: &InputPreprocessorMessageHandler, mut viewport_polygon: Subpath<PointId>) -> bool {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
pub fn is_layer_fully_inside_polygon(&self, layer: &LayerNodeIdentifier, viewport: &ViewportMessageHandler, mut viewport_polygon: Subpath<PointId>) -> bool {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
viewport_polygon.apply_transform(document_to_viewport.inverse());
|
||||
|
||||
let layer_click_targets = self.network_interface.document_metadata().click_targets(*layer);
|
||||
@@ -1723,8 +1724,8 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// Find all of the layers that were clicked on from a viewport space location
|
||||
pub fn click_xray(&self, ipp: &InputPreprocessorMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'_> {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
pub fn click_xray(&self, ipp: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'_> {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
let point = document_to_viewport.inverse().transform_point2(ipp.mouse.position);
|
||||
ClickXRayIter::new(&self.network_interface, XRayTarget::Point(point))
|
||||
}
|
||||
@@ -1745,8 +1746,8 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// Find layers under the location in viewport space that was clicked, listed by their depth in the layer tree hierarchy.
|
||||
pub fn click_list<'a>(&'a self, ipp: &InputPreprocessorMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.click_xray(ipp)
|
||||
pub fn click_list<'a>(&'a self, ipp: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.click_xray(ipp, viewport)
|
||||
.filter(move |&layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.skip_while(|&layer| layer == LayerNodeIdentifier::ROOT_PARENT)
|
||||
.scan(true, |last_had_children, layer| {
|
||||
@@ -1759,14 +1760,28 @@ impl DocumentMessageHandler {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn click_list_no_parents<'a>(&'a self, ipp: &InputPreprocessorMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.click_xray(ipp)
|
||||
/// Find layers (including artboards) under the location in viewport space that was clicked, listed by their depth in the layer tree hierarchy.
|
||||
pub fn click_list_with_artboards<'a>(&'a self, ipp: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.click_xray(ipp, viewport)
|
||||
.skip_while(|&layer| layer == LayerNodeIdentifier::ROOT_PARENT)
|
||||
.scan(true, |last_had_children, layer| {
|
||||
if *last_had_children {
|
||||
*last_had_children = layer.has_children(self.network_interface.document_metadata());
|
||||
Some(layer)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn click_list_no_parents<'a>(&'a self, ipp: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.click_xray(ipp, viewport)
|
||||
.filter(move |&layer| !self.network_interface.is_artboard(&layer.to_node(), &[]) && !layer.has_children(self.network_interface.document_metadata()))
|
||||
}
|
||||
|
||||
/// Find the deepest layer that has been clicked on from a location in viewport space.
|
||||
pub fn click(&self, ipp: &InputPreprocessorMessageHandler) -> Option<LayerNodeIdentifier> {
|
||||
self.click_list(ipp).last()
|
||||
pub fn click(&self, ipp: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler) -> Option<LayerNodeIdentifier> {
|
||||
self.click_list(ipp, viewport).last()
|
||||
}
|
||||
|
||||
pub fn click_based_on_position(&self, mouse_snapped_positon: DVec2) -> Option<LayerNodeIdentifier> {
|
||||
@@ -1924,8 +1939,8 @@ impl DocumentMessageHandler {
|
||||
structure_section.as_slice().into()
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, ipp: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let Some(previous_network) = self.undo(ipp, responses) else { return };
|
||||
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let Some(previous_network) = self.undo(viewport, responses) else { return };
|
||||
|
||||
self.document_redo_history.push_back(previous_network);
|
||||
if self.document_redo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
@@ -1933,7 +1948,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn undo(&mut self, ipp: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
pub fn undo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
// If there is no history return and don't broadcast SelectionChanged
|
||||
let mut network_interface = self.document_undo_history.pop_back()?;
|
||||
|
||||
@@ -1942,7 +1957,7 @@ impl DocumentMessageHandler {
|
||||
std::mem::swap(&mut network_interface.resolved_types, &mut self.network_interface.resolved_types);
|
||||
|
||||
//Update the metadata transform based on document PTZ
|
||||
let transform = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
let transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
network_interface.set_document_to_viewport_transform(transform);
|
||||
|
||||
// Ensure document structure is loaded so that updating the selected nodes has the correct metadata
|
||||
@@ -1961,9 +1976,9 @@ impl DocumentMessageHandler {
|
||||
|
||||
Some(previous_network)
|
||||
}
|
||||
pub fn redo_with_history(&mut self, ipp: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
// Push the UpdateOpenDocumentsList message to the queue in order to update the save status of the open documents
|
||||
let Some(previous_network) = self.redo(ipp, responses) else { return };
|
||||
let Some(previous_network) = self.redo(viewport, responses) else { return };
|
||||
|
||||
self.document_undo_history.push_back(previous_network);
|
||||
if self.document_undo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
@@ -1971,7 +1986,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, ipp: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
// If there is no history return and don't broadcast SelectionChanged
|
||||
let mut network_interface = self.document_redo_history.pop_back()?;
|
||||
|
||||
@@ -1980,7 +1995,7 @@ impl DocumentMessageHandler {
|
||||
std::mem::swap(&mut network_interface.resolved_types, &mut self.network_interface.resolved_types);
|
||||
|
||||
//Update the metadata transform based on document PTZ
|
||||
let transform = self.navigation_handler.calculate_offset_transform(ipp.viewport_bounds.center(), &self.document_ptz);
|
||||
let transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
network_interface.set_document_to_viewport_transform(transform);
|
||||
|
||||
let previous_network = std::mem::replace(&mut self.network_interface, network_interface);
|
||||
@@ -2026,11 +2041,11 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// Finds the artboard that bounds the point in viewport space and be the container of any newly added layers.
|
||||
pub fn new_layer_bounding_artboard(&self, ipp: &InputPreprocessorMessageHandler) -> LayerNodeIdentifier {
|
||||
pub fn new_layer_bounding_artboard(&self, ipp: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler) -> LayerNodeIdentifier {
|
||||
let container_based_on_selection = self.new_layer_parent(true);
|
||||
|
||||
let container_based_on_clicked_artboard = self
|
||||
.click_xray(ipp)
|
||||
.click_xray(ipp, viewport)
|
||||
.find(|layer| self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.unwrap_or(LayerNodeIdentifier::ROOT_PARENT);
|
||||
|
||||
|
||||
+24
-3
@@ -108,6 +108,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
GraphOperationMessage::NewArtboard { id, artboard } => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
|
||||
let artboard_location = artboard.location;
|
||||
let artboard_layer = modify_inputs.create_artboard(id, artboard);
|
||||
network_interface.move_layer_to_stack(artboard_layer, LayerNodeIdentifier::ROOT_PARENT, 0, &[]);
|
||||
|
||||
@@ -116,13 +117,33 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
log::error!("Artboard not created");
|
||||
return;
|
||||
};
|
||||
let document_metadata = network_interface.document_metadata();
|
||||
|
||||
let primary_input = artboard.inputs.first().expect("Artboard should have a primary input").clone();
|
||||
if let NodeInput::Node { node_id, .. } = &primary_input {
|
||||
if network_interface.is_layer(node_id, &[]) && !network_interface.is_artboard(node_id, &[]) {
|
||||
network_interface.move_layer_to_stack(LayerNodeIdentifier::new(*node_id, network_interface), artboard_layer, 0, &[]);
|
||||
if network_interface.is_artboard(node_id, &[]) {
|
||||
// Nothing to do here: we have a stack full of artboards!
|
||||
} else if network_interface.is_layer(node_id, &[]) {
|
||||
// We have a stack of non-layer artboards.
|
||||
for (insert_index, layer) in LayerNodeIdentifier::ROOT_PARENT.children(document_metadata).filter(|&layer| layer != artboard_layer).enumerate() {
|
||||
// Parent the layer to our new artboard (retaining ordering)
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack {
|
||||
layer,
|
||||
parent: artboard_layer,
|
||||
insert_index,
|
||||
});
|
||||
// Apply a translation to prevent the content from shifting
|
||||
responses.add(GraphOperationMessage::TransformChange {
|
||||
layer,
|
||||
transform: DAffine2::from_translation(-artboard_location.as_dvec2()),
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: true,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
|
||||
network_interface.disconnect_input(&InputConnector::node(artboard_layer.to_node(), 0), &[]);
|
||||
network_interface.set_input(&InputConnector::node(id, 0), primary_input, &[]);
|
||||
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 1), primary_input, &[]);
|
||||
}
|
||||
}
|
||||
responses.add_front(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
|
||||
|
||||
@@ -21,6 +21,7 @@ pub struct NavigationMessageContext<'a> {
|
||||
pub document_ptz: &'a mut PTZ,
|
||||
pub graph_view_overlay_open: bool,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default, ExtractField)]
|
||||
@@ -41,6 +42,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
document_ptz,
|
||||
graph_view_overlay_open,
|
||||
preferences,
|
||||
viewport,
|
||||
} = context;
|
||||
|
||||
fn get_ptz<'a>(document_ptz: &'a PTZ, network_interface: &'a NodeNetworkInterface, graph_view_overlay_open: bool, breadcrumb_network_path: &[NodeId]) -> Option<&'a PTZ> {
|
||||
@@ -135,7 +137,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
log::error!("Could not get PTZ in CanvasPan");
|
||||
return;
|
||||
};
|
||||
let document_to_viewport = self.calculate_offset_transform(ipp.viewport_bounds.center(), ptz);
|
||||
let document_to_viewport = self.calculate_offset_transform(viewport.center_in_viewport_space().into_dvec2(), ptz);
|
||||
let transformed_delta = document_to_viewport.inverse().transform_vector2(delta);
|
||||
|
||||
ptz.pan += transformed_delta;
|
||||
@@ -169,8 +171,8 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
log::error!("Could not get node graph PTZ in CanvasPanByViewportFraction");
|
||||
return;
|
||||
};
|
||||
let document_to_viewport = self.calculate_offset_transform(ipp.viewport_bounds.center(), ptz);
|
||||
let transformed_delta = document_to_viewport.inverse().transform_vector2(delta * ipp.viewport_bounds.size());
|
||||
let document_to_viewport = self.calculate_offset_transform(viewport.center_in_viewport_space().into_dvec2(), ptz);
|
||||
let transformed_delta = document_to_viewport.inverse().transform_vector2(delta * viewport.size().into_dvec2());
|
||||
|
||||
ptz.pan += transformed_delta;
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
@@ -214,7 +216,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
|
||||
let new_scale = *VIEWPORT_ZOOM_LEVELS.iter().rev().find(|scale| **scale < ptz.zoom()).unwrap_or(&ptz.zoom());
|
||||
if center_on_mouse {
|
||||
responses.add(self.center_zoom(ipp.viewport_bounds.size(), new_scale / ptz.zoom(), ipp.mouse.position));
|
||||
responses.add(self.center_zoom(viewport.size().into(), new_scale / ptz.zoom(), ipp.mouse.position));
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: new_scale });
|
||||
}
|
||||
@@ -225,7 +227,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
|
||||
let new_scale = *VIEWPORT_ZOOM_LEVELS.iter().find(|scale| **scale > ptz.zoom()).unwrap_or(&ptz.zoom());
|
||||
if center_on_mouse {
|
||||
responses.add(self.center_zoom(ipp.viewport_bounds.size(), new_scale / ptz.zoom(), ipp.mouse.position));
|
||||
responses.add(self.center_zoom(viewport.size().into(), new_scale / ptz.zoom(), ipp.mouse.position));
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: new_scale });
|
||||
}
|
||||
@@ -245,9 +247,9 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
return;
|
||||
};
|
||||
|
||||
zoom_factor *= Self::clamp_zoom(ptz.zoom() * zoom_factor, document_bounds, old_zoom, ipp);
|
||||
zoom_factor *= Self::clamp_zoom(ptz.zoom() * zoom_factor, document_bounds, old_zoom, viewport);
|
||||
|
||||
responses.add(self.center_zoom(ipp.viewport_bounds.size(), zoom_factor, ipp.mouse.position));
|
||||
responses.add(self.center_zoom(viewport.size().into(), zoom_factor, ipp.mouse.position));
|
||||
responses.add(NavigationMessage::CanvasZoomSet {
|
||||
zoom_factor: ptz.zoom() * zoom_factor,
|
||||
});
|
||||
@@ -264,7 +266,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
return;
|
||||
};
|
||||
let zoom = zoom_factor.clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
|
||||
let zoom = zoom * Self::clamp_zoom(zoom, document_bounds, old_zoom, ipp);
|
||||
let zoom = zoom * Self::clamp_zoom(zoom, document_bounds, old_zoom, viewport);
|
||||
ptz.set_zoom(zoom);
|
||||
if graph_view_overlay_open {
|
||||
responses.add(NodeGraphMessage::UpdateGraphBarRight);
|
||||
@@ -343,7 +345,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
let (pos1, pos2) = (pos1.min(pos2), pos1.max(pos2));
|
||||
let diagonal = pos2 - pos1;
|
||||
|
||||
if diagonal.length() < f64::EPSILON * 1000. || ipp.viewport_bounds.size() == DVec2::ZERO {
|
||||
if diagonal.length() < f64::EPSILON * 1000. || viewport.size().into_dvec2() == DVec2::ZERO {
|
||||
warn!("Cannot center since the viewport size is 0");
|
||||
return;
|
||||
}
|
||||
@@ -352,10 +354,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
log::error!("Could not get node graph PTZ in CanvasPanByViewportFraction");
|
||||
return;
|
||||
};
|
||||
let document_to_viewport = self.calculate_offset_transform(ipp.viewport_bounds.center(), ptz);
|
||||
let document_to_viewport = self.calculate_offset_transform(viewport.center_in_viewport_space().into_dvec2(), ptz);
|
||||
|
||||
let v1 = document_to_viewport.inverse().transform_point2(DVec2::ZERO);
|
||||
let v2 = document_to_viewport.inverse().transform_point2(ipp.viewport_bounds.size());
|
||||
let v2 = document_to_viewport.inverse().transform_point2(viewport.size().into_dvec2());
|
||||
|
||||
let center = ((v2 + v1) - (pos2 + pos1)) / 2.;
|
||||
let size = (v2 - v1) / diagonal;
|
||||
@@ -397,7 +399,8 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
log::error!("Could not get node graph PTZ in FitViewportToSelection");
|
||||
return;
|
||||
};
|
||||
let document_to_viewport = self.calculate_offset_transform(ipp.viewport_bounds.center(), ptz);
|
||||
|
||||
let document_to_viewport = self.calculate_offset_transform(viewport.center_in_viewport_space().into_dvec2(), ptz);
|
||||
responses.add(NavigationMessage::FitViewportToBounds {
|
||||
bounds: [document_to_viewport.inverse().transform_point2(bounds[0]), document_to_viewport.inverse().transform_point2(bounds[1])],
|
||||
prevent_zoom_past_100: false,
|
||||
@@ -419,7 +422,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
let tilt_raw_not_snapped = {
|
||||
// Compute the angle in document space to counter for the canvas being flipped
|
||||
let viewport_to_document = network_interface.document_metadata().document_to_viewport.inverse();
|
||||
let half_viewport = ipp.viewport_bounds.size() / 2.;
|
||||
let half_viewport = viewport.center_in_viewport_space().into_dvec2();
|
||||
let start_offset = viewport_to_document.transform_vector2(self.mouse_position - half_viewport);
|
||||
let end_offset = viewport_to_document.transform_vector2(ipp.mouse.position - half_viewport);
|
||||
let angle = start_offset.angle_to(end_offset);
|
||||
@@ -459,7 +462,7 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
|
||||
};
|
||||
|
||||
updated_zoom * Self::clamp_zoom(updated_zoom, document_bounds, old_zoom, ipp)
|
||||
updated_zoom * Self::clamp_zoom(updated_zoom, document_bounds, old_zoom, viewport)
|
||||
};
|
||||
let Some(ptz) = get_ptz_mut(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
log::error!("Could not get mutable PTZ in Zoom");
|
||||
@@ -563,9 +566,9 @@ impl NavigationMessageHandler {
|
||||
NavigationMessage::CanvasPan { delta }.into()
|
||||
}
|
||||
|
||||
pub fn clamp_zoom(zoom: f64, document_bounds: Option<[DVec2; 2]>, old_zoom: f64, ipp: &InputPreprocessorMessageHandler) -> f64 {
|
||||
pub fn clamp_zoom(zoom: f64, document_bounds: Option<[DVec2; 2]>, old_zoom: f64, viewport: &ViewportMessageHandler) -> f64 {
|
||||
let document_size = (document_bounds.map(|[min, max]| max - min).unwrap_or_default() / old_zoom) * zoom;
|
||||
let scale_factor = (document_size / ipp.viewport_bounds.size()).max_element();
|
||||
let scale_factor = (document_size / viewport.size().into_dvec2()).max_element();
|
||||
|
||||
if scale_factor <= f64::EPSILON * 100. || !scale_factor.is_finite() || scale_factor >= VIEWPORT_ZOOM_MIN_FRACTION_COVER {
|
||||
return 1.;
|
||||
|
||||
@@ -75,7 +75,8 @@ pub enum NodeGraphMessage {
|
||||
},
|
||||
InsertNode {
|
||||
node_id: NodeId,
|
||||
node_template: NodeTemplate,
|
||||
// Boxed to reduce size of enum (1120 bytes to 8 bytes)
|
||||
node_template: Box<NodeTemplate>,
|
||||
},
|
||||
InsertNodeBetween {
|
||||
node_id: NodeId,
|
||||
|
||||
@@ -20,6 +20,7 @@ use crate::messages::tool::common_functionality::graph_modification_utils::{self
|
||||
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
||||
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||
use crate::messages::viewport::{Position, Rect};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::proto::GraphErrors;
|
||||
@@ -43,6 +44,7 @@ pub struct NodeGraphMessageContext<'a> {
|
||||
pub navigation_handler: &'a NavigationMessageHandler,
|
||||
pub preferences: &'a PreferencesMessageHandler,
|
||||
pub layers_panel_open: bool,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, ExtractField)]
|
||||
@@ -113,6 +115,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
navigation_handler,
|
||||
preferences,
|
||||
layers_panel_open,
|
||||
viewport,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
@@ -264,7 +267,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: node_template.clone(),
|
||||
node_template: Box::new(node_template.clone()),
|
||||
});
|
||||
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
||||
// Only auto connect to the dragged wire if the node is being added to the currently opened network
|
||||
@@ -507,7 +510,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(NodeGraphMessage::UpdateImportsExports);
|
||||
}
|
||||
NodeGraphMessage::InsertNode { node_id, node_template } => {
|
||||
network_interface.insert_node(node_id, node_template, selection_network_path);
|
||||
network_interface.insert_node(node_id, *node_template, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::InsertNodeBetween {
|
||||
node_id,
|
||||
@@ -624,7 +627,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id: encapsulating_node_id,
|
||||
node_template: default_node_template,
|
||||
node_template: Box::new(default_node_template),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: encapsulating_node_id,
|
||||
@@ -783,12 +786,12 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
|
||||
// TODO: Create function
|
||||
let node_graph_shift = if matches!(context_menu_data, ContextMenuData::CreateNode { compatible_type: None }) {
|
||||
let appear_right_of_mouse = if click.x > ipp.viewport_bounds.size().x - 180. { -180. } else { 0. };
|
||||
let appear_above_mouse = if click.y > ipp.viewport_bounds.size().y - 200. { -200. } else { 0. };
|
||||
let appear_right_of_mouse = if click.x > viewport.size().x() - 180. { -180. } else { 0. };
|
||||
let appear_above_mouse = if click.y > viewport.size().y() - 200. { -200. } else { 0. };
|
||||
DVec2::new(appear_right_of_mouse, appear_above_mouse) / network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.matrix2.x_axis.x
|
||||
} else {
|
||||
let appear_right_of_mouse = if click.x > ipp.viewport_bounds.size().x - 173. { -173. } else { 0. };
|
||||
let appear_above_mouse = if click.y > ipp.viewport_bounds.size().y - 34. { -34. } else { 0. };
|
||||
let appear_right_of_mouse = if click.x > viewport.size().x() - 173. { -173. } else { 0. };
|
||||
let appear_above_mouse = if click.y > viewport.size().y() - 34. { -34. } else { 0. };
|
||||
DVec2::new(appear_right_of_mouse, appear_above_mouse) / network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.matrix2.x_axis.x
|
||||
};
|
||||
|
||||
@@ -983,7 +986,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
|
||||
// Auto-panning
|
||||
let messages = [NodeGraphMessage::PointerOutsideViewport { shift }.into(), NodeGraphMessage::PointerMove { shift }.into()];
|
||||
self.auto_panning.setup_by_mouse_position(ipp, &messages, responses);
|
||||
self.auto_panning.setup_by_mouse_position(ipp, viewport, &messages, responses);
|
||||
|
||||
let viewport_location = ipp.mouse.position;
|
||||
let point = network_metadata
|
||||
@@ -1218,8 +1221,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
_ => Some(format!("type:{}", output_type.nested_type())),
|
||||
};
|
||||
|
||||
let appear_right_of_mouse = if ipp.mouse.position.x > ipp.viewport_bounds.size().x - 173. { -173. } else { 0. };
|
||||
let appear_above_mouse = if ipp.mouse.position.y > ipp.viewport_bounds.size().y - 34. { -34. } else { 0. };
|
||||
let appear_right_of_mouse = if ipp.mouse.position.x > viewport.size().y() - 173. { -173. } else { 0. };
|
||||
let appear_above_mouse = if ipp.mouse.position.y > viewport.size().y() - 34. { -34. } else { 0. };
|
||||
let node_graph_shift = DVec2::new(appear_right_of_mouse, appear_above_mouse) / network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.matrix2.x_axis.x;
|
||||
|
||||
self.context_menu = Some(ContextMenuInformation {
|
||||
@@ -1403,7 +1406,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
NodeGraphMessage::PointerOutsideViewport { shift } => {
|
||||
if self.drag_start.is_some() || self.box_selection_start.is_some() || (self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none()) {
|
||||
let _ = self.auto_panning.shift_viewport(ipp, responses);
|
||||
let _ = self.auto_panning.shift_viewport(ipp, viewport, responses);
|
||||
} else {
|
||||
// Auto-panning
|
||||
let messages = [NodeGraphMessage::PointerOutsideViewport { shift }.into(), NodeGraphMessage::PointerMove { shift }.into()];
|
||||
@@ -1611,7 +1614,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
return;
|
||||
};
|
||||
|
||||
let viewport_bbox = ipp.document_bounds();
|
||||
let viewport_bounds = viewport.bounds();
|
||||
let viewport_bbox: [DVec2; 2] = viewport_bounds.into();
|
||||
let document_bbox: [DVec2; 2] = viewport_bbox.map(|p| network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(p));
|
||||
|
||||
let mut nodes = Vec::new();
|
||||
@@ -1657,7 +1661,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
NodeGraphMessage::SetGridAlignedEdges => {
|
||||
if graph_view_overlay_open {
|
||||
network_interface.set_grid_aligned_edges(DVec2::new(ipp.viewport_bounds.bottom_right.x - ipp.viewport_bounds.top_left.x, 0.), breadcrumb_network_path);
|
||||
let viewport_bounds = viewport.bounds();
|
||||
network_interface.set_grid_aligned_edges(DVec2::new(viewport_bounds.x() - viewport_bounds.width(), 0.), breadcrumb_network_path);
|
||||
// Send the new edges to the frontend
|
||||
responses.add(NodeGraphMessage::UpdateImportsExports);
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ impl FrontendGraphDataType {
|
||||
TaggedValue::Vector(_) => Self::Vector,
|
||||
TaggedValue::Color(_) => Self::Color,
|
||||
TaggedValue::Gradient(_) | TaggedValue::GradientStops(_) | TaggedValue::GradientTable(_) => Self::Gradient,
|
||||
TaggedValue::String(_) => Self::Typography,
|
||||
TaggedValue::String(_) | TaggedValue::VecString(_) => Self::Typography,
|
||||
_ => Self::General,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,9 +13,11 @@ fn grid_overlay_rectangular(document: &DocumentMessageHandler, overlay_context:
|
||||
let Some(spacing) = GridSnapping::compute_rectangle_spacing(spacing, &document.document_ptz) else {
|
||||
return;
|
||||
};
|
||||
let document_to_viewport = document.navigation_handler.calculate_offset_transform(overlay_context.size / 2., &document.document_ptz);
|
||||
let document_to_viewport = document
|
||||
.navigation_handler
|
||||
.calculate_offset_transform(overlay_context.viewport.center_in_viewport_space().into(), &document.document_ptz);
|
||||
|
||||
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.size]);
|
||||
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.viewport.size().into()]);
|
||||
|
||||
for primary in 0..2 {
|
||||
let secondary = 1 - primary;
|
||||
@@ -52,9 +54,11 @@ fn grid_overlay_rectangular_dot(document: &DocumentMessageHandler, overlay_conte
|
||||
let Some(spacing) = GridSnapping::compute_rectangle_spacing(spacing, &document.document_ptz) else {
|
||||
return;
|
||||
};
|
||||
let document_to_viewport = document.navigation_handler.calculate_offset_transform(overlay_context.size / 2., &document.document_ptz);
|
||||
let document_to_viewport = document
|
||||
.navigation_handler
|
||||
.calculate_offset_transform(overlay_context.viewport.center_in_viewport_space().into(), &document.document_ptz);
|
||||
|
||||
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.size]);
|
||||
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.viewport.size().into()]);
|
||||
|
||||
let min = bounds.0.iter().map(|corner| corner.y).min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
|
||||
let max = bounds.0.iter().map(|corner| corner.y).max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default();
|
||||
@@ -85,9 +89,11 @@ fn grid_overlay_isometric(document: &DocumentMessageHandler, overlay_context: &m
|
||||
let grid_color = "#".to_string() + &document.snapping_state.grid.grid_color.to_rgba_hex_srgb();
|
||||
let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap();
|
||||
let origin = document.snapping_state.grid.origin;
|
||||
let document_to_viewport = document.navigation_handler.calculate_offset_transform(overlay_context.size / 2., &document.document_ptz);
|
||||
let document_to_viewport = document
|
||||
.navigation_handler
|
||||
.calculate_offset_transform(overlay_context.viewport.center_in_viewport_space().into(), &document.document_ptz);
|
||||
|
||||
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.size]);
|
||||
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.viewport.size().into()]);
|
||||
let tan_a = angle_a.to_radians().tan();
|
||||
let tan_b = angle_b.to_radians().tan();
|
||||
let spacing = DVec2::new(y_axis_spacing / (tan_a + tan_b), y_axis_spacing);
|
||||
@@ -128,9 +134,11 @@ fn grid_overlay_isometric_dot(document: &DocumentMessageHandler, overlay_context
|
||||
let grid_color = "#".to_string() + &document.snapping_state.grid.grid_color.to_rgba_hex_srgb();
|
||||
let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap();
|
||||
let origin = document.snapping_state.grid.origin;
|
||||
let document_to_viewport = document.navigation_handler.calculate_offset_transform(overlay_context.size / 2., &document.document_ptz);
|
||||
let document_to_viewport = document
|
||||
.navigation_handler
|
||||
.calculate_offset_transform(overlay_context.viewport.center_in_viewport_space().into(), &document.document_ptz);
|
||||
|
||||
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.size]);
|
||||
let bounds = document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, overlay_context.viewport.size().into()]);
|
||||
let tan_a = angle_a.to_radians().tan();
|
||||
let tan_b = angle_b.to_radians().tan();
|
||||
let spacing = DVec2::new(y_axis_spacing / (tan_a + tan_b), y_axis_spacing);
|
||||
|
||||
@@ -4,8 +4,7 @@ use crate::messages::prelude::*;
|
||||
#[derive(ExtractField)]
|
||||
pub struct OverlaysMessageContext<'a> {
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub device_pixel_ratio: f64,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
@@ -20,19 +19,14 @@ pub struct OverlaysMessageHandler {
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMessageHandler {
|
||||
fn process_message(&mut self, message: OverlaysMessage, responses: &mut VecDeque<Message>, context: OverlaysMessageContext) {
|
||||
let OverlaysMessageContext {
|
||||
visibility_settings,
|
||||
ipp,
|
||||
device_pixel_ratio,
|
||||
..
|
||||
} = context;
|
||||
let OverlaysMessageContext { visibility_settings, viewport, .. } = context;
|
||||
|
||||
match message {
|
||||
#[cfg(target_family = "wasm")]
|
||||
OverlaysMessage::Draw => {
|
||||
use super::utility_functions::overlay_canvas_element;
|
||||
use super::utility_types::OverlayContext;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use crate::messages::viewport::{Position, ToPhysical};
|
||||
use wasm_bindgen::JsCast;
|
||||
|
||||
let canvas = match &self.canvas {
|
||||
@@ -48,28 +42,26 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
canvas_context.dyn_into().expect("Context should be a canvas 2d context")
|
||||
});
|
||||
|
||||
let size = ipp.viewport_bounds.size().as_uvec2();
|
||||
let size_logical = viewport.size();
|
||||
let size_physical = size_logical.to_physical();
|
||||
let width = size_logical.x().max(size_physical.x());
|
||||
let height = size_logical.y().max(size_physical.y());
|
||||
|
||||
let [a, b, c, d, e, f] = DAffine2::from_scale(DVec2::splat(device_pixel_ratio)).to_cols_array();
|
||||
let _ = canvas_context.set_transform(a, b, c, d, e, f);
|
||||
canvas_context.clear_rect(0., 0., ipp.viewport_bounds.size().x, ipp.viewport_bounds.size().y);
|
||||
let _ = canvas_context.reset_transform();
|
||||
canvas_context.clear_rect(0., 0., width, height);
|
||||
|
||||
if visibility_settings.all() {
|
||||
responses.add(DocumentMessage::GridOverlays {
|
||||
context: OverlayContext {
|
||||
render_context: canvas_context.clone(),
|
||||
size: size.as_dvec2(),
|
||||
device_pixel_ratio,
|
||||
visibility_settings: visibility_settings.clone(),
|
||||
viewport: *viewport,
|
||||
},
|
||||
});
|
||||
for provider in &self.overlay_providers {
|
||||
responses.add(provider(OverlayContext {
|
||||
render_context: canvas_context.clone(),
|
||||
size: size.as_dvec2(),
|
||||
device_pixel_ratio,
|
||||
visibility_settings: visibility_settings.clone(),
|
||||
viewport: *viewport,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -78,9 +70,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
OverlaysMessage::Draw => {
|
||||
use super::utility_types::OverlayContext;
|
||||
|
||||
let size = ipp.viewport_bounds.size();
|
||||
|
||||
let overlay_context = OverlayContext::new(size, device_pixel_ratio, visibility_settings);
|
||||
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
|
||||
|
||||
if visibility_settings.all() {
|
||||
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
||||
@@ -93,7 +83,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
}
|
||||
#[cfg(all(not(target_family = "wasm"), test))]
|
||||
OverlaysMessage::Draw => {
|
||||
let _ = (responses, visibility_settings, ipp, device_pixel_ratio);
|
||||
let _ = (responses, visibility_settings, viewport);
|
||||
}
|
||||
OverlaysMessage::AddProvider { provider: message } => {
|
||||
self.overlay_providers.insert(message);
|
||||
|
||||
@@ -207,7 +207,6 @@ pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &
|
||||
let Some(vector) = document.network_interface.compute_modified_vector(layer) else {
|
||||
continue;
|
||||
};
|
||||
//let document_to_viewport = document.navigation_handler.calculate_offset_transform(overlay_context.size / 2., &document.document_ptz);
|
||||
let transform = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface);
|
||||
let selected = shape_editor.selected_shape_state.get(&layer);
|
||||
let is_selected = |selected: Option<&SelectedLayerState>, point: ManipulatorPointId| selected.is_some_and(|selected| selected.is_point_selected(point));
|
||||
|
||||
@@ -2,10 +2,11 @@ use super::utility_functions::overlay_canvas_context;
|
||||
use crate::consts::{
|
||||
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_YELLOW, COLOR_OVERLAY_YELLOW_DULL,
|
||||
COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE,
|
||||
PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, SEGMENT_SELECTED_THICKNESS,
|
||||
PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SEGMENT_SELECTED_THICKNESS, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::Message;
|
||||
use crate::messages::viewport::ViewportMessageHandler;
|
||||
use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
use glam::{DAffine2, DVec2};
|
||||
@@ -141,10 +142,7 @@ pub struct OverlayContext {
|
||||
#[serde(skip, default = "overlay_canvas_context")]
|
||||
#[specta(skip)]
|
||||
pub render_context: web_sys::CanvasRenderingContext2d,
|
||||
pub size: DVec2,
|
||||
// The device pixel ratio is a property provided by the browser window and is the CSS pixel size divided by the physical monitor's pixel size.
|
||||
// It allows better pixel density of visualizations on high-DPI displays where the OS display scaling is not 100%, or where the browser is zoomed.
|
||||
pub device_pixel_ratio: f64,
|
||||
pub viewport: ViewportMessageHandler,
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
// Message hashing isn't used but is required by the message system macros
|
||||
@@ -499,11 +497,25 @@ impl OverlayContext {
|
||||
self.square(position, None, Some(color_fill), Some(COLOR_OVERLAY_BLUE));
|
||||
}
|
||||
|
||||
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
let quad = DAffine2::from_angle_translation(rotation, position) * Quad::from_box([DVec2::splat(-RESIZE_HANDLE_SIZE / 2.), DVec2::splat(RESIZE_HANDLE_SIZE / 2.)]);
|
||||
self.quad(quad, None, Some(COLOR_OVERLAY_WHITE));
|
||||
}
|
||||
|
||||
pub fn skew_handles(&mut self, edge_start: DVec2, edge_end: DVec2) {
|
||||
let edge_dir = (edge_end - edge_start).normalize();
|
||||
let mid = edge_end.midpoint(edge_start);
|
||||
|
||||
for edge in [edge_dir, -edge_dir] {
|
||||
self.draw_triangle(mid + edge * (3. + SKEW_TRIANGLE_OFFSET), edge, SKEW_TRIANGLE_SIZE, None, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Transforms the canvas context to adjust for DPI scaling
|
||||
///
|
||||
/// Overwrites all existing tranforms. This operation can be reversed with [`Self::reset_transform`].
|
||||
fn start_dpi_aware_transform(&self) {
|
||||
let [a, b, c, d, e, f] = DAffine2::from_scale(DVec2::splat(self.device_pixel_ratio)).to_cols_array();
|
||||
let [a, b, c, d, e, f] = DAffine2::from_scale(DVec2::splat(self.viewport.scale())).to_cols_array();
|
||||
self.render_context
|
||||
.set_transform(a, b, c, d, e, f)
|
||||
.expect("transform should be able to be set to be able to account for DPI");
|
||||
@@ -967,7 +979,7 @@ impl OverlayContext {
|
||||
Pivot::End => -padding,
|
||||
};
|
||||
|
||||
let [a, b, c, d, e, f] = (DAffine2::from_scale(DVec2::splat(self.device_pixel_ratio)) * transform * DAffine2::from_translation(DVec2::new(x, y))).to_cols_array();
|
||||
let [a, b, c, d, e, f] = (DAffine2::from_scale(DVec2::splat(self.viewport.scale())) * transform * DAffine2::from_translation(DVec2::new(x, y))).to_cols_array();
|
||||
self.render_context.set_transform(a, b, c, d, e, f).expect("Failed to rotate the render context to the specified angle");
|
||||
|
||||
if let Some(background) = background_color {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use crate::consts::{
|
||||
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_YELLOW, COLOR_OVERLAY_YELLOW_DULL,
|
||||
COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE,
|
||||
PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER,
|
||||
PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::Message;
|
||||
use crate::messages::prelude::ViewportMessageHandler;
|
||||
use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
use glam::{DAffine2, DVec2};
|
||||
@@ -157,24 +158,18 @@ pub struct OverlayContext {
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
internal: Arc<Mutex<OverlayContextInternal>>,
|
||||
pub size: DVec2,
|
||||
// The device pixel ratio is a property provided by the browser window and is the CSS pixel size divided by the physical monitor's pixel size.
|
||||
// It allows better pixel density of visualizations on high-DPI displays where the OS display scaling is not 100%, or where the browser is zoomed.
|
||||
pub device_pixel_ratio: f64,
|
||||
pub viewport: ViewportMessageHandler,
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
impl Clone for OverlayContext {
|
||||
fn clone(&self) -> Self {
|
||||
let internal = self.internal.lock().expect("Failed to lock internal overlay context");
|
||||
let size = internal.size;
|
||||
let device_pixel_ratio = internal.device_pixel_ratio;
|
||||
let visibility_settings = internal.visibility_settings;
|
||||
drop(internal); // Explicitly release the lock before cloning the Arc<Mutex<_>>
|
||||
Self {
|
||||
internal: self.internal.clone(),
|
||||
size,
|
||||
device_pixel_ratio,
|
||||
viewport: self.viewport,
|
||||
visibility_settings,
|
||||
}
|
||||
}
|
||||
@@ -183,7 +178,7 @@ impl Clone for OverlayContext {
|
||||
// Manual implementations since Scene doesn't implement PartialEq or Debug
|
||||
impl PartialEq for OverlayContext {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.size == other.size && self.device_pixel_ratio == other.device_pixel_ratio && self.visibility_settings == other.visibility_settings
|
||||
self.viewport == other.viewport && self.visibility_settings == other.visibility_settings
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,8 +186,7 @@ impl std::fmt::Debug for OverlayContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("OverlayContext")
|
||||
.field("scene", &"Scene { ... }")
|
||||
.field("size", &self.size)
|
||||
.field("device_pixel_ratio", &self.device_pixel_ratio)
|
||||
.field("viewport", &self.viewport)
|
||||
.field("visibility_settings", &self.visibility_settings)
|
||||
.finish()
|
||||
}
|
||||
@@ -203,8 +197,7 @@ impl Default for OverlayContext {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
internal: Mutex::new(OverlayContextInternal::default()).into(),
|
||||
size: DVec2::ZERO,
|
||||
device_pixel_ratio: 1.0,
|
||||
viewport: ViewportMessageHandler::default(),
|
||||
visibility_settings: OverlaysVisibilitySettings::default(),
|
||||
}
|
||||
}
|
||||
@@ -217,11 +210,10 @@ impl core::hash::Hash for OverlayContext {
|
||||
|
||||
impl OverlayContext {
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn new(size: DVec2, device_pixel_ratio: f64, visibility_settings: OverlaysVisibilitySettings) -> Self {
|
||||
pub(super) fn new(viewport: ViewportMessageHandler, visibility_settings: OverlaysVisibilitySettings) -> Self {
|
||||
Self {
|
||||
internal: Arc::new(Mutex::new(OverlayContextInternal::new(size, device_pixel_ratio, visibility_settings))),
|
||||
size,
|
||||
device_pixel_ratio,
|
||||
internal: Arc::new(Mutex::new(OverlayContextInternal::new(viewport, visibility_settings))),
|
||||
viewport,
|
||||
visibility_settings,
|
||||
}
|
||||
}
|
||||
@@ -280,6 +272,14 @@ impl OverlayContext {
|
||||
self.internal().manipulator_anchor(position, selected, color);
|
||||
}
|
||||
|
||||
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
self.internal().resize_handle(position, rotation);
|
||||
}
|
||||
|
||||
pub fn skew_handles(&mut self, edge_start: DVec2, edge_end: DVec2) {
|
||||
self.internal().skew_handles(edge_start, edge_end);
|
||||
}
|
||||
|
||||
pub fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
|
||||
self.internal().square(position, size, color_fill, color_stroke);
|
||||
}
|
||||
@@ -292,6 +292,7 @@ impl OverlayContext {
|
||||
self.internal().circle(position, radius, color_fill, color_stroke);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn dashed_ellipse(
|
||||
&mut self,
|
||||
center: DVec2,
|
||||
@@ -421,23 +422,21 @@ pub enum DrawHandles {
|
||||
|
||||
pub(super) struct OverlayContextInternal {
|
||||
scene: Scene,
|
||||
size: DVec2,
|
||||
device_pixel_ratio: f64,
|
||||
viewport: ViewportMessageHandler,
|
||||
visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
impl Default for OverlayContextInternal {
|
||||
fn default() -> Self {
|
||||
Self::new(DVec2::new(100., 100.), 1., OverlaysVisibilitySettings::default())
|
||||
Self::new(ViewportMessageHandler::default(), OverlaysVisibilitySettings::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl OverlayContextInternal {
|
||||
pub(super) fn new(size: DVec2, device_pixel_ratio: f64, visibility_settings: OverlaysVisibilitySettings) -> Self {
|
||||
pub(super) fn new(viewport: ViewportMessageHandler, visibility_settings: OverlaysVisibilitySettings) -> Self {
|
||||
Self {
|
||||
scene: Scene::new(),
|
||||
size,
|
||||
device_pixel_ratio,
|
||||
viewport,
|
||||
visibility_settings,
|
||||
}
|
||||
}
|
||||
@@ -473,7 +472,7 @@ impl OverlayContextInternal {
|
||||
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &path);
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), transform, Self::parse_color(color_stroke), None, &path);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color_stroke), None, &path);
|
||||
}
|
||||
|
||||
fn dashed_quad(&mut self, quad: Quad, stroke_color: Option<&str>, color_fill: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
@@ -506,7 +505,7 @@ impl OverlayContextInternal {
|
||||
}
|
||||
|
||||
let stroke_color = stroke_color.unwrap_or(COLOR_OVERLAY_BLUE);
|
||||
let mut stroke = kurbo::Stroke::new(1.0);
|
||||
let mut stroke = kurbo::Stroke::new(1.);
|
||||
|
||||
if let Some(dash_width) = dash_width {
|
||||
let dash_gap = dash_gap_width.unwrap_or(1.);
|
||||
@@ -551,7 +550,7 @@ impl OverlayContextInternal {
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
|
||||
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(1.0), transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &circle);
|
||||
.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &circle);
|
||||
}
|
||||
|
||||
fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
|
||||
@@ -563,13 +562,13 @@ impl OverlayContextInternal {
|
||||
|
||||
let fill = COLOR_OVERLAY_BLUE_50;
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), transform, Self::parse_color(COLOR_OVERLAY_BLUE_50), None, &circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(COLOR_OVERLAY_BLUE_50), None, &circle);
|
||||
|
||||
let inner_circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
|
||||
|
||||
let color_fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &inner_circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &inner_circle);
|
||||
}
|
||||
|
||||
fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
@@ -584,8 +583,22 @@ impl OverlayContextInternal {
|
||||
self.square(position, None, Some(color_fill), Some(COLOR_OVERLAY_BLUE));
|
||||
}
|
||||
|
||||
fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
let quad = DAffine2::from_angle_translation(rotation, position) * Quad::from_box([DVec2::splat(-RESIZE_HANDLE_SIZE / 2.), DVec2::splat(RESIZE_HANDLE_SIZE / 2.)]);
|
||||
self.quad(quad, None, Some(COLOR_OVERLAY_WHITE));
|
||||
}
|
||||
|
||||
fn skew_handles(&mut self, edge_start: DVec2, edge_end: DVec2) {
|
||||
let edge_dir = (edge_end - edge_start).normalize();
|
||||
let mid = edge_end.midpoint(edge_start);
|
||||
|
||||
for edge in [edge_dir, -edge_dir] {
|
||||
self.draw_triangle(mid + edge * 3. + SKEW_TRIANGLE_OFFSET, edge, SKEW_TRIANGLE_SIZE, None, None);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_transform(&self) -> kurbo::Affine {
|
||||
kurbo::Affine::scale(self.device_pixel_ratio)
|
||||
kurbo::Affine::scale(self.viewport.scale())
|
||||
}
|
||||
|
||||
fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
|
||||
@@ -601,7 +614,7 @@ impl OverlayContextInternal {
|
||||
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &rect);
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), transform, Self::parse_color(color_stroke), None, &rect);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color_stroke), None, &rect);
|
||||
}
|
||||
|
||||
fn pixel(&mut self, position: DVec2, color: Option<&str>) {
|
||||
@@ -627,9 +640,10 @@ impl OverlayContextInternal {
|
||||
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &circle);
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), transform, Self::parse_color(color_stroke), None, &circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color_stroke), None, &circle);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn dashed_ellipse(
|
||||
&mut self,
|
||||
_center: DVec2,
|
||||
@@ -678,7 +692,7 @@ impl OverlayContextInternal {
|
||||
);
|
||||
}
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), self.get_transform(), Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), self.get_transform(), Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
|
||||
}
|
||||
|
||||
fn draw_arc_gizmo_angle(&mut self, pivot: DVec2, bold_radius: f64, arc_radius: f64, offset_angle: f64, angle: f64) {
|
||||
@@ -700,7 +714,7 @@ impl OverlayContextInternal {
|
||||
let mut fill_color = Color::from_rgb_str(COLOR_OVERLAY_WHITE.strip_prefix('#').unwrap()).unwrap().with_alpha(0.05).to_rgba_hex_srgb();
|
||||
fill_color.insert(0, '#');
|
||||
let fill_color = Some(fill_color.as_str());
|
||||
self.line(start + DVec2::X * radius * sign, start + DVec2::X * (radius * scale), None, None);
|
||||
self.line(start + DVec2::X * radius * sign, start + DVec2::X * radius * scale.abs(), None, None);
|
||||
self.circle(start, radius, fill_color, None);
|
||||
self.circle(start, radius * scale.abs(), fill_color, None);
|
||||
self.text(
|
||||
@@ -714,14 +728,14 @@ impl OverlayContextInternal {
|
||||
}
|
||||
|
||||
fn compass_rose(&mut self, compass_center: DVec2, angle: f64, show_compass_with_hover_ring: Option<bool>) {
|
||||
const HOVER_RING_OUTER_RADIUS: f64 = COMPASS_ROSE_HOVER_RING_DIAMETER / 2.;
|
||||
const MAIN_RING_OUTER_RADIUS: f64 = COMPASS_ROSE_MAIN_RING_DIAMETER / 2.;
|
||||
const MAIN_RING_INNER_RADIUS: f64 = COMPASS_ROSE_RING_INNER_DIAMETER / 2.;
|
||||
const ARROW_RADIUS: f64 = COMPASS_ROSE_ARROW_SIZE / 2.;
|
||||
const HOVER_RING_STROKE_WIDTH: f64 = HOVER_RING_OUTER_RADIUS - MAIN_RING_INNER_RADIUS;
|
||||
const HOVER_RING_CENTERLINE_RADIUS: f64 = (HOVER_RING_OUTER_RADIUS + MAIN_RING_INNER_RADIUS) / 2.;
|
||||
const MAIN_RING_STROKE_WIDTH: f64 = MAIN_RING_OUTER_RADIUS - MAIN_RING_INNER_RADIUS;
|
||||
const MAIN_RING_CENTERLINE_RADIUS: f64 = (MAIN_RING_OUTER_RADIUS + MAIN_RING_INNER_RADIUS) / 2.;
|
||||
let hover_ring_outer_radius: f64 = COMPASS_ROSE_HOVER_RING_DIAMETER / 2.;
|
||||
let main_ring_outer_radius: f64 = COMPASS_ROSE_MAIN_RING_DIAMETER / 2.;
|
||||
let main_ring_inner_radius: f64 = COMPASS_ROSE_RING_INNER_DIAMETER / 2.;
|
||||
let arrow_radius: f64 = COMPASS_ROSE_ARROW_SIZE / 2.;
|
||||
let hover_ring_stroke_width: f64 = hover_ring_outer_radius - main_ring_inner_radius;
|
||||
let hover_ring_centerline_radius: f64 = (hover_ring_outer_radius + main_ring_inner_radius) / 2.;
|
||||
let main_ring_stroke_width: f64 = main_ring_outer_radius - main_ring_inner_radius;
|
||||
let main_ring_centerline_radius: f64 = (main_ring_outer_radius + main_ring_inner_radius) / 2.;
|
||||
|
||||
let Some(show_hover_ring) = show_compass_with_hover_ring else { return };
|
||||
|
||||
@@ -733,9 +747,9 @@ impl OverlayContextInternal {
|
||||
let mut fill_color = Color::from_rgb_str(COLOR_OVERLAY_BLUE.strip_prefix('#').unwrap()).unwrap().with_alpha(0.5).to_rgba_hex_srgb();
|
||||
fill_color.insert(0, '#');
|
||||
|
||||
let circle = kurbo::Circle::new((center.x, center.y), HOVER_RING_CENTERLINE_RADIUS);
|
||||
let circle = kurbo::Circle::new((center.x, center.y), hover_ring_centerline_radius);
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(HOVER_RING_STROKE_WIDTH), transform, Self::parse_color(&fill_color), None, &circle);
|
||||
.stroke(&kurbo::Stroke::new(hover_ring_stroke_width), transform, Self::parse_color(&fill_color), None, &circle);
|
||||
}
|
||||
|
||||
// Arrows
|
||||
@@ -743,11 +757,11 @@ impl OverlayContextInternal {
|
||||
let direction = DVec2::from_angle(i as f64 * FRAC_PI_2 + angle);
|
||||
let color = if i % 2 == 0 { COLOR_OVERLAY_RED } else { COLOR_OVERLAY_GREEN };
|
||||
|
||||
let tip = center + direction * HOVER_RING_OUTER_RADIUS;
|
||||
let base = center + direction * (MAIN_RING_INNER_RADIUS + MAIN_RING_OUTER_RADIUS) / 2.;
|
||||
let tip = center + direction * hover_ring_outer_radius;
|
||||
let base = center + direction * (main_ring_inner_radius + main_ring_outer_radius) / 2.;
|
||||
|
||||
let r = (ARROW_RADIUS.powi(2) + MAIN_RING_INNER_RADIUS.powi(2)).sqrt();
|
||||
let (cos, sin) = (MAIN_RING_INNER_RADIUS / r, ARROW_RADIUS / r);
|
||||
let r = (arrow_radius.powi(2) + main_ring_inner_radius.powi(2)).sqrt();
|
||||
let (cos, sin) = (main_ring_inner_radius / r, arrow_radius / r);
|
||||
let side1 = center + r * DVec2::new(cos * direction.x - sin * direction.y, sin * direction.x + direction.y * cos);
|
||||
let side2 = center + r * DVec2::new(cos * direction.x + sin * direction.y, -sin * direction.x + direction.y * cos);
|
||||
|
||||
@@ -764,9 +778,9 @@ impl OverlayContextInternal {
|
||||
}
|
||||
|
||||
// Main ring
|
||||
let circle = kurbo::Circle::new((center.x, center.y), MAIN_RING_CENTERLINE_RADIUS);
|
||||
let circle = kurbo::Circle::new((center.x, center.y), main_ring_centerline_radius);
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(MAIN_RING_STROKE_WIDTH), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &circle);
|
||||
.stroke(&kurbo::Stroke::new(main_ring_stroke_width), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &circle);
|
||||
}
|
||||
|
||||
fn pivot(&mut self, position: DVec2, angle: f64) {
|
||||
@@ -780,22 +794,22 @@ impl OverlayContextInternal {
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(COLOR_OVERLAY_YELLOW), None, &circle);
|
||||
|
||||
// Crosshair
|
||||
const CROSSHAIR_RADIUS: f64 = (PIVOT_CROSSHAIR_LENGTH - PIVOT_CROSSHAIR_THICKNESS) / 2.;
|
||||
let crosshair_radius: f64 = (PIVOT_CROSSHAIR_LENGTH - PIVOT_CROSSHAIR_THICKNESS) / 2.;
|
||||
|
||||
let mut stroke = kurbo::Stroke::new(PIVOT_CROSSHAIR_THICKNESS);
|
||||
stroke = stroke.with_caps(kurbo::Cap::Round);
|
||||
|
||||
// Horizontal line
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(kurbo::Point::new(x + CROSSHAIR_RADIUS * uv.x, y + CROSSHAIR_RADIUS * uv.y));
|
||||
path.line_to(kurbo::Point::new(x - CROSSHAIR_RADIUS * uv.x, y - CROSSHAIR_RADIUS * uv.y));
|
||||
path.move_to(kurbo::Point::new(x + crosshair_radius * uv.x, y + crosshair_radius * uv.y));
|
||||
path.line_to(kurbo::Point::new(x - crosshair_radius * uv.x, y - crosshair_radius * uv.y));
|
||||
|
||||
self.scene.stroke(&stroke, transform, Self::parse_color(COLOR_OVERLAY_YELLOW), None, &path);
|
||||
|
||||
// Vertical line
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(kurbo::Point::new(x - CROSSHAIR_RADIUS * uv.y, y + CROSSHAIR_RADIUS * uv.x));
|
||||
path.line_to(kurbo::Point::new(x + CROSSHAIR_RADIUS * uv.y, y - CROSSHAIR_RADIUS * uv.x));
|
||||
path.move_to(kurbo::Point::new(x - crosshair_radius * uv.y, y + crosshair_radius * uv.x));
|
||||
path.line_to(kurbo::Point::new(x + crosshair_radius * uv.y, y - crosshair_radius * uv.x));
|
||||
|
||||
self.scene.stroke(&stroke, transform, Self::parse_color(COLOR_OVERLAY_YELLOW), None, &path);
|
||||
}
|
||||
@@ -809,15 +823,15 @@ impl OverlayContextInternal {
|
||||
// Draw the background circle with a white fill and colored outline
|
||||
let circle = kurbo::Circle::new((x, y), DOWEL_PIN_RADIUS);
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), transform, Self::parse_color(color), None, &circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color), None, &circle);
|
||||
|
||||
// Draw the two filled sectors using paths
|
||||
let mut path = BezPath::new();
|
||||
|
||||
// Top-left sector
|
||||
path.move_to(kurbo::Point::new(x, y));
|
||||
let end_x = x + DOWEL_PIN_RADIUS * (FRAC_PI_2 + angle).cos();
|
||||
let end_y = y + DOWEL_PIN_RADIUS * (FRAC_PI_2 + angle).sin();
|
||||
let end_x = x + DOWEL_PIN_RADIUS * (FRAC_PI_2 + angle.cos());
|
||||
let end_y = y + DOWEL_PIN_RADIUS * (FRAC_PI_2 + angle.sin());
|
||||
path.line_to(kurbo::Point::new(end_x, end_y));
|
||||
// Draw arc manually
|
||||
let arc = kurbo::Arc::new((x, y), (DOWEL_PIN_RADIUS, DOWEL_PIN_RADIUS), FRAC_PI_2 + angle, FRAC_PI_2, 0.0);
|
||||
@@ -828,8 +842,8 @@ impl OverlayContextInternal {
|
||||
|
||||
// Bottom-right sector
|
||||
path.move_to(kurbo::Point::new(x, y));
|
||||
let end_x = x + DOWEL_PIN_RADIUS * (PI + FRAC_PI_2 + angle).cos();
|
||||
let end_y = y + DOWEL_PIN_RADIUS * (PI + FRAC_PI_2 + angle).sin();
|
||||
let end_x = x + DOWEL_PIN_RADIUS * (PI + FRAC_PI_2 + angle.cos());
|
||||
let end_y = y + DOWEL_PIN_RADIUS * (PI + FRAC_PI_2 + angle.sin());
|
||||
path.line_to(kurbo::Point::new(end_x, end_y));
|
||||
// Draw arc manually
|
||||
let arc = kurbo::Arc::new((x, y), (DOWEL_PIN_RADIUS, DOWEL_PIN_RADIUS), PI + FRAC_PI_2 + angle, FRAC_PI_2, 0.0);
|
||||
@@ -861,7 +875,7 @@ impl OverlayContextInternal {
|
||||
self.bezier_to_path(bezier, transform, move_to, &mut path);
|
||||
}
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), vello_transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), vello_transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
|
||||
}
|
||||
|
||||
/// Used by the Pen tool in order to show how the bezier curve would look like.
|
||||
@@ -870,7 +884,7 @@ impl OverlayContextInternal {
|
||||
let mut path = BezPath::new();
|
||||
self.bezier_to_path(bezier, transform, true, &mut path);
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), vello_transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), vello_transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
|
||||
}
|
||||
|
||||
/// Used by the path tool segment mode in order to show the selected segments.
|
||||
@@ -963,7 +977,7 @@ impl OverlayContextInternal {
|
||||
let path = self.push_path(subpaths.iter(), transform);
|
||||
let color = color.unwrap_or(COLOR_OVERLAY_BLUE);
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.0), self.get_transform(), Self::parse_color(color), None, &path);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), self.get_transform(), Self::parse_color(color), None, &path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,15 +1012,20 @@ impl OverlayContextInternal {
|
||||
data[index..index + 4].copy_from_slice(&rgba);
|
||||
}
|
||||
|
||||
let image = peniko::Image {
|
||||
data: data.into(),
|
||||
format: peniko::ImageFormat::Rgba8,
|
||||
width: PATTERN_WIDTH,
|
||||
height: PATTERN_HEIGHT,
|
||||
x_extend: peniko::Extend::Repeat,
|
||||
y_extend: peniko::Extend::Repeat,
|
||||
alpha: 1.0,
|
||||
quality: peniko::ImageQuality::default(),
|
||||
let image = peniko::ImageBrush {
|
||||
image: peniko::ImageData {
|
||||
data: data.into(),
|
||||
format: peniko::ImageFormat::Rgba8,
|
||||
width: PATTERN_WIDTH,
|
||||
height: PATTERN_HEIGHT,
|
||||
alpha_type: peniko::ImageAlphaType::Alpha,
|
||||
},
|
||||
sampler: peniko::ImageSampler {
|
||||
x_extend: peniko::Extend::Repeat,
|
||||
y_extend: peniko::Extend::Repeat,
|
||||
quality: peniko::ImageQuality::default(),
|
||||
alpha: 1.,
|
||||
},
|
||||
};
|
||||
|
||||
let path = self.push_path(subpaths, transform);
|
||||
|
||||
@@ -154,10 +154,7 @@ impl DocumentMetadata {
|
||||
pub fn bounding_box_with_transform(&self, layer: LayerNodeIdentifier, transform: DAffine2) -> Option<[DVec2; 2]> {
|
||||
self.click_targets(layer)?
|
||||
.iter()
|
||||
.filter_map(|click_target| match click_target.target_type() {
|
||||
ClickTargetType::Subpath(subpath) => subpath.bounding_box_with_transform(transform),
|
||||
ClickTargetType::FreePoint(_) => click_target.bounding_box_with_transform(transform),
|
||||
})
|
||||
.filter_map(|click_target| click_target.bounding_box_with_transform(transform))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 221 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user