图形应用框架,包含组件库示例和应用示例
This commit is contained in:
commit
fbc3a70cda
|
@ -0,0 +1,9 @@
|
|||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
|
@ -0,0 +1,7 @@
|
|||
/dist
|
||||
/src-capacitor
|
||||
/src-cordova
|
||||
/.quasar
|
||||
/node_modules
|
||||
.eslintrc.js
|
||||
/src-ssr
|
|
@ -0,0 +1,89 @@
|
|||
module.exports = {
|
||||
// https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy
|
||||
// This option interrupts the configuration hierarchy at this file
|
||||
// Remove this if you have an higher level ESLint config file (it usually happens into a monorepos)
|
||||
root: true,
|
||||
|
||||
// https://eslint.vuejs.org/user-guide/#how-to-use-a-custom-parser
|
||||
// Must use parserOptions instead of "parser" to allow vue-eslint-parser to keep working
|
||||
// `parser: 'vue-eslint-parser'` is already included with any 'plugin:vue/**' config and should be omitted
|
||||
parserOptions: {
|
||||
parser: require.resolve('@typescript-eslint/parser'),
|
||||
extraFileExtensions: ['.vue'],
|
||||
},
|
||||
|
||||
env: {
|
||||
browser: true,
|
||||
es2021: true,
|
||||
node: true,
|
||||
'vue/setup-compiler-macros': true,
|
||||
},
|
||||
|
||||
// Rules order is important, please avoid shuffling them
|
||||
extends: [
|
||||
// Base ESLint recommended rules
|
||||
// 'eslint:recommended',
|
||||
|
||||
// https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#usage
|
||||
// ESLint typescript rules
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
|
||||
// Uncomment any of the lines below to choose desired strictness,
|
||||
// but leave only one uncommented!
|
||||
// See https://eslint.vuejs.org/rules/#available-rules
|
||||
'plugin:vue/vue3-essential', // Priority A: Essential (Error Prevention)
|
||||
// 'plugin:vue/vue3-strongly-recommended', // Priority B: Strongly Recommended (Improving Readability)
|
||||
// 'plugin:vue/vue3-recommended', // Priority C: Recommended (Minimizing Arbitrary Choices and Cognitive Overhead)
|
||||
|
||||
// https://github.com/prettier/eslint-config-prettier#installation
|
||||
// usage with Prettier, provided by 'eslint-config-prettier'.
|
||||
'prettier',
|
||||
],
|
||||
|
||||
plugins: [
|
||||
// required to apply rules which need type information
|
||||
'@typescript-eslint',
|
||||
|
||||
// https://eslint.vuejs.org/user-guide/#why-doesn-t-it-work-on-vue-files
|
||||
// required to lint *.vue files
|
||||
'vue',
|
||||
|
||||
// https://github.com/typescript-eslint/typescript-eslint/issues/389#issuecomment-509292674
|
||||
// Prettier has not been included as plugin to avoid performance impact
|
||||
// add it as an extension for your IDE
|
||||
],
|
||||
|
||||
globals: {
|
||||
ga: 'readonly', // Google Analytics
|
||||
cordova: 'readonly',
|
||||
__statics: 'readonly',
|
||||
__QUASAR_SSR__: 'readonly',
|
||||
__QUASAR_SSR_SERVER__: 'readonly',
|
||||
__QUASAR_SSR_CLIENT__: 'readonly',
|
||||
__QUASAR_SSR_PWA__: 'readonly',
|
||||
process: 'readonly',
|
||||
Capacitor: 'readonly',
|
||||
chrome: 'readonly',
|
||||
},
|
||||
|
||||
// add your custom rules here
|
||||
rules: {
|
||||
'prefer-promise-reject-errors': 'off',
|
||||
|
||||
quotes: ['warn', 'single', { avoidEscape: true }],
|
||||
|
||||
// this rule, if on, would require explicit return type on the `render` function
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
|
||||
// in plain CommonJS modules, you can't use `import foo = require('foo')` to pass this rule, so it has to be disabled
|
||||
'@typescript-eslint/no-var-requires': 'off',
|
||||
'@typescript-eslint/no-namespace': 'off',
|
||||
|
||||
// The core 'no-unused-vars' rules (in the eslint:recommended ruleset)
|
||||
// does not work with type definitions
|
||||
'no-unused-vars': 'off',
|
||||
|
||||
// allow debugger during development only
|
||||
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
|
||||
},
|
||||
};
|
|
@ -0,0 +1,33 @@
|
|||
.DS_Store
|
||||
.thumbs.db
|
||||
node_modules
|
||||
|
||||
# Quasar core related directories
|
||||
.quasar
|
||||
/dist
|
||||
|
||||
# Cordova related directories and files
|
||||
/src-cordova/node_modules
|
||||
/src-cordova/platforms
|
||||
/src-cordova/plugins
|
||||
/src-cordova/www
|
||||
|
||||
# Capacitor related directories and files
|
||||
/src-capacitor/www
|
||||
/src-capacitor/node_modules
|
||||
|
||||
# BEX related directories and files
|
||||
/src-bex/www
|
||||
/src-bex/js/core
|
||||
|
||||
# Log files
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
|
@ -0,0 +1,3 @@
|
|||
# pnpm-related options
|
||||
shamefully-hoist=true
|
||||
strict-peer-dependencies=false
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"singleQuote": true,
|
||||
"semi": true
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"recommendations": [
|
||||
"dbaeumer.vscode-eslint",
|
||||
"esbenp.prettier-vscode",
|
||||
"editorconfig.editorconfig",
|
||||
"vue.volar",
|
||||
"wayou.vscode-todo-highlight"
|
||||
],
|
||||
"unwantedRecommendations": [
|
||||
"octref.vetur",
|
||||
"hookyqr.beautify",
|
||||
"dbaeumer.jshint",
|
||||
"ms-vscode.vscode-typescript-tslint-plugin"
|
||||
]
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"editor.bracketPairColorization.enabled": true,
|
||||
"editor.guides.bracketPairs": true,
|
||||
"editor.formatOnSave": true,
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
"editor.codeActionsOnSave": [
|
||||
"source.fixAll.eslint"
|
||||
],
|
||||
"eslint.validate": [
|
||||
"javascript",
|
||||
"javascriptreact",
|
||||
"typescript",
|
||||
"vue"
|
||||
],
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
# 项目说明
|
||||
|
||||
图形应用基础框架,基于 pixi.js([官网](https://pixijs.com/), [API Docs](https://pixijs.download/release/docs/index.html))
|
||||
viewport 使用的 github 开源的 pixi-viewport[pixi-viewport](https://github.com/davidfig/pixi-viewport)
|
||||
|
||||
# 路线图
|
||||
|
||||
- 图形的位置、旋转属性使用 pixijs 的 transform 变换(完成)
|
||||
- 图形对象的拖拽使用原始的 transform(图形的变换使用原始的变换)(完成)
|
||||
- 图形交互抽象(完成)
|
||||
- 图形子元素变换处理和存储(完成)
|
||||
- 图形复制功能(完成)
|
||||
- 绘制应用图形外包围框及旋转缩放功能(完成)
|
||||
- 绘制增加吸附功能(移动到特定位置附近吸附)(完成)
|
||||
- 菜单事件及处理
|
||||
- 打包
|
||||
- 添加拖拽轨迹限制功能
|
||||
- 添加图形对象 可编辑属性 定义功能
|
||||
|
||||
# pixijs 一些概念
|
||||
|
||||
- 如果图形对象本身有碰撞检测区域,子图形的碰撞检测范围在父级的碰撞检测区域内
|
||||
- v7.2 中 eventMode 属性值的意义:
|
||||
|
||||
> - "none":忽略所有交互事件,且忽略其子级的交互事件。
|
||||
|
||||
> - "passive":不发出(emit)事件,并忽略对自身和非交互式子对象的所有命中测试。交互式子项仍将发出(emit)事件。
|
||||
|
||||
> - "auto":不发出(emit)事件,但如果父级是交互式的,则会进行命中测试。与 v7 中的 interactive=false 相同
|
||||
|
||||
> - "static":发出(emit)事件并进行命中测试。与 v7 中的 interactive=true 相同
|
||||
|
||||
> - "dynamic":发出(emit)事件并进行命中测试,但也会接收模拟的交互事件,以便在鼠标不移动时进行交互
|
||||
|
||||
## Install the dependencies
|
||||
|
||||
```bash
|
||||
yarn
|
||||
# or
|
||||
npm install
|
||||
```
|
||||
|
||||
### Start the app in development mode (hot-code reloading, error reporting, etc.)
|
||||
|
||||
```bash
|
||||
quasar dev
|
||||
```
|
||||
|
||||
### Lint the files
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
# or
|
||||
npm run lint
|
||||
```
|
||||
|
||||
### Format the files
|
||||
|
||||
```bash
|
||||
yarn format
|
||||
# or
|
||||
npm run format
|
||||
```
|
||||
|
||||
### Build the app for production
|
||||
|
||||
```bash
|
||||
quasar build
|
||||
```
|
||||
|
||||
### Customize the configuration
|
||||
|
||||
See [Configuring quasar.config.js](https://v2.quasar.dev/quasar-cli-vite/quasar-config-js).
|
|
@ -0,0 +1,21 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title><%= productName %></title>
|
||||
|
||||
<meta charset="utf-8">
|
||||
<meta name="description" content="<%= productDescription %>">
|
||||
<meta name="format-detection" content="telephone=no">
|
||||
<meta name="msapplication-tap-highlight" content="no">
|
||||
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width<% if (ctx.mode.cordova || ctx.mode.capacitor) { %>, viewport-fit=cover<% } %>">
|
||||
|
||||
<link rel="icon" type="image/png" sizes="128x128" href="icons/favicon-128x128.png">
|
||||
<link rel="icon" type="image/png" sizes="96x96" href="icons/favicon-96x96.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="icons/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="icons/favicon-16x16.png">
|
||||
<link rel="icon" type="image/ico" href="favicon.ico">
|
||||
</head>
|
||||
<body>
|
||||
<!-- quasar:entry-point -->
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"name": "graphic-pixi",
|
||||
"version": "0.0.1",
|
||||
"description": "基于pixijs的图形应用、绘制应用框架",
|
||||
"productName": "Graphic-pixi",
|
||||
"author": "walker <shengxuqiang@joylink.club>",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"lint": "eslint --ext .js,.ts,.vue ./",
|
||||
"format": "prettier --write \"**/*.{js,ts,vue,scss,html,md,json}\" --ignore-path .gitignore",
|
||||
"test": "echo \"No test specified\" && exit 0",
|
||||
"dev": "quasar dev",
|
||||
"proto": "node scripts/proto.cjs",
|
||||
"build": "quasar build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@quasar/extras": "^1.0.0",
|
||||
"@stomp/stompjs": "^7.0.0",
|
||||
"google-protobuf": "^3.21.2",
|
||||
"js-base64": "^3.7.5",
|
||||
"pinia": "^2.0.11",
|
||||
"pixi-viewport": "^5.0.1",
|
||||
"pixi.js": "^7.2.4",
|
||||
"quasar": "^2.6.0",
|
||||
"vue": "^3.0.0",
|
||||
"vue-router": "^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@quasar/app-vite": "^1.0.0",
|
||||
"@types/google-protobuf": "^3.15.6",
|
||||
"@types/node": "^12.20.21",
|
||||
"@typescript-eslint/eslint-plugin": "^5.10.0",
|
||||
"@typescript-eslint/parser": "^5.10.0",
|
||||
"autoprefixer": "^10.4.2",
|
||||
"eslint": "^8.10.0",
|
||||
"eslint-config-prettier": "^8.1.0",
|
||||
"eslint-plugin-vue": "^9.0.0",
|
||||
"prettier": "^2.5.1",
|
||||
"typescript": "^4.5.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18 || ^16 || ^14.19",
|
||||
"npm": ">= 6.13.4",
|
||||
"yarn": ">= 1.21.1"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
/* eslint-disable */
|
||||
// https://github.com/michael-ciniawsky/postcss-load-config
|
||||
|
||||
module.exports = {
|
||||
plugins: [
|
||||
// https://github.com/postcss/autoprefixer
|
||||
require('autoprefixer')({
|
||||
overrideBrowserslist: [
|
||||
'last 4 Chrome versions',
|
||||
'last 4 Firefox versions',
|
||||
'last 4 Edge versions',
|
||||
'last 4 Safari versions',
|
||||
'last 4 Android versions',
|
||||
'last 4 ChromeAndroid versions',
|
||||
'last 4 FirefoxAndroid versions',
|
||||
'last 4 iOS versions'
|
||||
]
|
||||
})
|
||||
|
||||
// https://github.com/elchininet/postcss-rtlcss
|
||||
// If you want to support RTL css, then
|
||||
// 1. yarn/npm install postcss-rtlcss
|
||||
// 2. optionally set quasar.config.js > framework > lang to an RTL language
|
||||
// 3. uncomment the following line:
|
||||
// require('postcss-rtlcss')
|
||||
]
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 63 KiB |
Binary file not shown.
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
After Width: | Height: | Size: 859 B |
Binary file not shown.
After Width: | Height: | Size: 2.0 KiB |
Binary file not shown.
After Width: | Height: | Size: 9.4 KiB |
|
@ -0,0 +1,208 @@
|
|||
/* eslint-env node */
|
||||
|
||||
/*
|
||||
* This file runs in a Node context (it's NOT transpiled by Babel), so use only
|
||||
* the ES6 features that are supported by your Node version. https://node.green/
|
||||
*/
|
||||
|
||||
// Configuration for your app
|
||||
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js
|
||||
|
||||
const { configure } = require('quasar/wrappers');
|
||||
|
||||
module.exports = configure(function (/* ctx */) {
|
||||
return {
|
||||
eslint: {
|
||||
// fix: true,
|
||||
// include: [],
|
||||
// exclude: [],
|
||||
// rawOptions: {},
|
||||
warnings: true,
|
||||
errors: true,
|
||||
exclude: ['src/examples/app/protos/*'],
|
||||
},
|
||||
|
||||
// https://v2.quasar.dev/quasar-cli-vite/prefetch-feature
|
||||
// preFetch: true,
|
||||
|
||||
// app boot file (/src/boot)
|
||||
// --> boot files are part of "main.js"
|
||||
// https://v2.quasar.dev/quasar-cli-vite/boot-files
|
||||
boot: [],
|
||||
|
||||
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#css
|
||||
css: ['app.scss'],
|
||||
|
||||
// https://github.com/quasarframework/quasar/tree/dev/extras
|
||||
extras: [
|
||||
// 'ionicons-v4',
|
||||
// 'mdi-v5',
|
||||
// 'fontawesome-v6',
|
||||
// 'eva-icons',
|
||||
// 'themify',
|
||||
// 'line-awesome',
|
||||
// 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both!
|
||||
|
||||
'roboto-font', // optional, you are not bound to it
|
||||
'material-icons', // optional, you are not bound to it
|
||||
],
|
||||
|
||||
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#build
|
||||
build: {
|
||||
target: {
|
||||
browser: ['es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1'],
|
||||
node: 'node16',
|
||||
},
|
||||
|
||||
vueRouterMode: 'history', // available values: 'hash', 'history'
|
||||
// vueRouterBase,
|
||||
// vueDevtools,
|
||||
// vueOptionsAPI: false,
|
||||
|
||||
// rebuildCache: true, // rebuilds Vite/linter/etc cache on startup
|
||||
|
||||
// publicPath: '/',
|
||||
// analyze: true,
|
||||
// env: {},
|
||||
// rawDefine: {}
|
||||
// ignorePublicFolder: true,
|
||||
// minify: false,
|
||||
// polyfillModulePreload: true,
|
||||
// distDir
|
||||
|
||||
// extendViteConf (viteConf) {},
|
||||
// viteVuePluginOptions: {},
|
||||
|
||||
// vitePlugins: [
|
||||
// [ 'package-name', { ..options.. } ]
|
||||
// ]
|
||||
},
|
||||
|
||||
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#devServer
|
||||
devServer: {
|
||||
// https: true
|
||||
port: 9999,
|
||||
open: false, // opens browser window automatically
|
||||
},
|
||||
|
||||
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#framework
|
||||
framework: {
|
||||
config: {
|
||||
notify: {
|
||||
position: 'top',
|
||||
timeout: 2000,
|
||||
progress: true,
|
||||
},
|
||||
},
|
||||
|
||||
// iconSet: 'material-icons', // Quasar icon set
|
||||
lang: 'zh-CN', // Quasar language pack
|
||||
|
||||
// For special cases outside of where the auto-import strategy can have an impact
|
||||
// (like functional components as one of the examples),
|
||||
// you can manually specify Quasar components/directives to be available everywhere:
|
||||
//
|
||||
// components: [],
|
||||
// directives: [],
|
||||
|
||||
// Quasar plugins
|
||||
plugins: ['Notify', 'Dialog', 'Dark', 'AppFullscreen'],
|
||||
},
|
||||
|
||||
// animations: 'all', // --- includes all animations
|
||||
// https://v2.quasar.dev/options/animations
|
||||
animations: [],
|
||||
|
||||
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#sourcefiles
|
||||
// sourceFiles: {
|
||||
// rootComponent: 'src/App.vue',
|
||||
// router: 'src/router/index',
|
||||
// store: 'src/store/index',
|
||||
// registerServiceWorker: 'src-pwa/register-service-worker',
|
||||
// serviceWorker: 'src-pwa/custom-service-worker',
|
||||
// pwaManifestFile: 'src-pwa/manifest.json',
|
||||
// electronMain: 'src-electron/electron-main',
|
||||
// electronPreload: 'src-electron/electron-preload'
|
||||
// },
|
||||
|
||||
// https://v2.quasar.dev/quasar-cli-vite/developing-ssr/configuring-ssr
|
||||
ssr: {
|
||||
// ssrPwaHtmlFilename: 'offline.html', // do NOT use index.html as name!
|
||||
// will mess up SSR
|
||||
|
||||
// extendSSRWebserverConf (esbuildConf) {},
|
||||
// extendPackageJson (json) {},
|
||||
|
||||
pwa: false,
|
||||
|
||||
// manualStoreHydration: true,
|
||||
// manualPostHydrationTrigger: true,
|
||||
|
||||
prodPort: 3000, // The default port that the production server should use
|
||||
// (gets superseded if process.env.PORT is specified at runtime)
|
||||
|
||||
middlewares: [
|
||||
'render', // keep this as last one
|
||||
],
|
||||
},
|
||||
|
||||
// https://v2.quasar.dev/quasar-cli-vite/developing-pwa/configuring-pwa
|
||||
pwa: {
|
||||
workboxMode: 'generateSW', // or 'injectManifest'
|
||||
injectPwaMetaTags: true,
|
||||
swFilename: 'sw.js',
|
||||
manifestFilename: 'manifest.json',
|
||||
useCredentialsForManifestTag: false,
|
||||
// useFilenameHashes: true,
|
||||
// extendGenerateSWOptions (cfg) {}
|
||||
// extendInjectManifestOptions (cfg) {},
|
||||
// extendManifestJson (json) {}
|
||||
// extendPWACustomSWConf (esbuildConf) {}
|
||||
},
|
||||
|
||||
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-cordova-apps/configuring-cordova
|
||||
cordova: {
|
||||
// noIosLegacyBuildFlag: true, // uncomment only if you know what you are doing
|
||||
},
|
||||
|
||||
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-capacitor-apps/configuring-capacitor
|
||||
capacitor: {
|
||||
hideSplashscreen: true,
|
||||
},
|
||||
|
||||
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-electron-apps/configuring-electron
|
||||
electron: {
|
||||
// extendElectronMainConf (esbuildConf)
|
||||
// extendElectronPreloadConf (esbuildConf)
|
||||
|
||||
inspectPort: 5858,
|
||||
|
||||
bundler: 'packager', // 'packager' or 'builder'
|
||||
|
||||
packager: {
|
||||
// https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options
|
||||
// OS X / Mac App Store
|
||||
// appBundleId: '',
|
||||
// appCategoryType: '',
|
||||
// osxSign: '',
|
||||
// protocol: 'myapp://path',
|
||||
// Windows only
|
||||
// win32metadata: { ... }
|
||||
},
|
||||
|
||||
builder: {
|
||||
// https://www.electron.build/configuration/configuration
|
||||
|
||||
appId: 'graphic-pixi',
|
||||
},
|
||||
},
|
||||
|
||||
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-browser-extensions/configuring-bex
|
||||
bex: {
|
||||
contentScripts: ['my-content-script'],
|
||||
|
||||
// extendBexScriptsConf (esbuildConf) {}
|
||||
// extendBexManifestJson (json) {}
|
||||
},
|
||||
};
|
||||
});
|
|
@ -0,0 +1,95 @@
|
|||
/**
|
||||
* 将proto文件编译到 src/proto/
|
||||
*/
|
||||
const { readdirSync } = require('fs');
|
||||
const { resolve } = require('path');
|
||||
const os = require('os');
|
||||
|
||||
const { exec } = require('child_process');
|
||||
|
||||
const protocDir = resolve(
|
||||
__dirname,
|
||||
'../src/examples/app/app_message/protoc-22.2'
|
||||
);
|
||||
const protoFileDir = resolve(
|
||||
__dirname,
|
||||
'../src/examples/app/app_message/protos'
|
||||
);
|
||||
const destDir = resolve(__dirname, '../src/examples/app/protos');
|
||||
|
||||
/**
|
||||
* 递归处理所有proto文件生成
|
||||
* @param {*} file 文件
|
||||
* @param {*} path 目录
|
||||
*/
|
||||
function recursiveGenerate(file, path = [], cmds = []) {
|
||||
if (file.isFile()) {
|
||||
// 文件,生成
|
||||
if (file.name.endsWith('.proto')) {
|
||||
cmds.push(buildGenerateCmd(file.name, path));
|
||||
} else {
|
||||
console.warn('不是proto文件', file.name);
|
||||
}
|
||||
} else if (file.isDirectory()) {
|
||||
// 文件夹,递归
|
||||
readdirSync(resolve(protoFileDir, ...path, file.name), {
|
||||
withFileTypes: true,
|
||||
}).forEach((f) => {
|
||||
const subPath = [...path, file.name];
|
||||
recursiveGenerate(f, subPath, cmds);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const isLinux = os.type().toLowerCase().includes('linux');
|
||||
|
||||
function buildGenerateCmd(name, path = []) {
|
||||
const protoPath = resolve(protoFileDir, ...path);
|
||||
const tsPath = resolve(destDir, ...path);
|
||||
|
||||
let cmd = ['protoc', `-I=${protoPath}`, `--ts_out=${tsPath}`, `${name}`];
|
||||
let cmdStr = cmd.join(' ');
|
||||
return cmdStr;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const protocBin = resolve(
|
||||
protocDir,
|
||||
`bin/${isLinux ? 'linux-x86_64' : 'win64'}`
|
||||
);
|
||||
const prepareCmds = [];
|
||||
const setPathCmd = isLinux
|
||||
? ['export', `PATH=${protocBin}:${protocDir}:"$PATH"`].join(' ')
|
||||
: ['set', `PATH=${protocBin};${protocDir};%PATH%`].join(' ');
|
||||
const protocVersionCmd = ['protoc', '--version'].join(' ');
|
||||
prepareCmds.push(setPathCmd);
|
||||
prepareCmds.push(protocVersionCmd);
|
||||
|
||||
readdirSync(protoFileDir, {
|
||||
withFileTypes: true,
|
||||
}).forEach((f) => {
|
||||
recursiveGenerate(f, [], prepareCmds);
|
||||
});
|
||||
|
||||
console.log(prepareCmds);
|
||||
|
||||
exec(
|
||||
prepareCmds.join(' && '),
|
||||
{
|
||||
maxBuffer: 1024 * 2000,
|
||||
},
|
||||
(err, stdout, stderr) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
throw err;
|
||||
} else if (stderr.length > 0) {
|
||||
console.error(stderr.toString());
|
||||
throw new Error(stderr.toString());
|
||||
} else {
|
||||
console.log(stdout);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
main();
|
|
@ -0,0 +1,7 @@
|
|||
<template>
|
||||
<router-view />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
|
||||
</script>
|
|
@ -0,0 +1,15 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 356 360">
|
||||
<path
|
||||
d="M43.4 303.4c0 3.8-2.3 6.3-7.1 6.3h-15v-22h14.4c4.3 0 6.2 2.2 6.2 5.2 0 2.6-1.5 4.4-3.4 5 2.8.4 4.9 2.5 4.9 5.5zm-8-13H24.1v6.9H35c2.1 0 4-1.3 4-3.8 0-2.2-1.3-3.1-3.7-3.1zm5.1 12.6c0-2.3-1.8-3.7-4-3.7H24.2v7.7h11.7c3.4 0 4.6-1.8 4.6-4zm36.3 4v2.7H56v-22h20.6v2.7H58.9v6.8h14.6v2.3H58.9v7.5h17.9zm23-5.8v8.5H97v-8.5l-11-13.4h3.4l8.9 11 8.8-11h3.4l-10.8 13.4zm19.1-1.8V298c0-7.9 5.2-10.7 12.7-10.7 7.5 0 13 2.8 13 10.7v1.4c0 7.9-5.5 10.8-13 10.8s-12.7-3-12.7-10.8zm22.7 0V298c0-5.7-3.9-8-10-8-6 0-9.8 2.3-9.8 8v1.4c0 5.8 3.8 8.1 9.8 8.1 6 0 10-2.3 10-8.1zm37.2-11.6v21.9h-2.9l-15.8-17.9v17.9h-2.8v-22h3l15.6 18v-18h2.9zm37.9 10.2v1.3c0 7.8-5.2 10.4-12.4 10.4H193v-22h11.2c7.2 0 12.4 2.8 12.4 10.3zm-3 0c0-5.3-3.3-7.6-9.4-7.6h-8.4V307h8.4c6 0 9.5-2 9.5-7.7V298zm50.8-7.6h-9.7v19.3h-3v-19.3h-9.7v-2.6h22.4v2.6zm34.4-2.6v21.9h-3v-10.1h-16.8v10h-2.8v-21.8h2.8v9.2H296v-9.2h2.9zm34.9 19.2v2.7h-20.7v-22h20.6v2.7H316v6.8h14.5v2.3H316v7.5h17.8zM24 340.2v7.3h13.9v2.4h-14v9.6H21v-22h20v2.7H24zm41.5 11.4h-9.8v7.9H53v-22h13.3c5.1 0 8 1.9 8 6.8 0 3.7-2 6.3-5.6 7l6 8.2h-3.3l-5.8-8zm-9.8-2.6H66c3.1 0 5.3-1.5 5.3-4.7 0-3.3-2.2-4.1-5.3-4.1H55.7v8.8zm47.9 6.2H89l-2 4.3h-3.2l10.7-22.2H98l10.7 22.2h-3.2l-2-4.3zm-1-2.3l-6.3-13-6 13h12.2zm46.3-15.3v21.9H146v-17.2L135.7 358h-2.1l-10.2-15.6v17h-2.8v-21.8h3l11 16.9 11.3-17h3zm35 19.3v2.6h-20.7v-22h20.6v2.7H166v6.8h14.5v2.3H166v7.6h17.8zm47-19.3l-8.3 22h-3l-7.1-18.6-7 18.6h-3l-8.2-22h3.3L204 356l6.8-18.5h3.4L221 356l6.6-18.5h3.3zm10 11.6v-1.4c0-7.8 5.2-10.7 12.7-10.7 7.6 0 13 2.9 13 10.7v1.4c0 7.9-5.4 10.8-13 10.8-7.5 0-12.7-3-12.7-10.8zm22.8 0v-1.4c0-5.7-4-8-10-8s-9.9 2.3-9.9 8v1.4c0 5.8 3.8 8.2 9.8 8.2 6.1 0 10-2.4 10-8.2zm28.3 2.4h-9.8v7.9h-2.8v-22h13.2c5.2 0 8 1.9 8 6.8 0 3.7-2 6.3-5.6 7l6 8.2h-3.3l-5.8-8zm-9.8-2.6h10.2c3 0 5.2-1.5 5.2-4.7 0-3.3-2.1-4.1-5.2-4.1h-10.2v8.8zm40.3-1.5l-6.8 5.6v6.4h-2.9v-22h2.9v12.3l15.2-12.2h3.7l-9.9 8.1 10.3 13.8h-3.6l-8.9-12z" />
|
||||
<path fill="#050A14"
|
||||
d="M188.4 71.7a10.4 10.4 0 01-20.8 0 10.4 10.4 0 1120.8 0zM224.2 45c-2.2-3.9-5-7.5-8.2-10.7l-12 7c-3.7-3.2-8-5.7-12.6-7.3a49.4 49.4 0 00-9.7 13.9 59 59 0 0140.1 14l7.6-4.4a57 57 0 00-5.2-12.5zM178 125.1c4.5 0 9-.6 13.4-1.7v-14a40 40 0 0012.5-7.2 47.7 47.7 0 00-7.1-15.3 59 59 0 01-32.2 27.7v8.7c4.4 1.2 8.9 1.8 13.4 1.8zM131.8 45c-2.3 4-4 8.1-5.2 12.5l12 7a40 40 0 000 14.4c5.7 1.5 11.3 2 16.9 1.5a59 59 0 01-8-41.7l-7.5-4.3c-3.2 3.2-6 6.7-8.2 10.6z" />
|
||||
<path fill="#00B4FF"
|
||||
d="M224.2 98.4c2.3-3.9 4-8 5.2-12.4l-12-7a40 40 0 000-14.5c-5.7-1.5-11.3-2-16.9-1.5a59 59 0 018 41.7l7.5 4.4c3.2-3.2 6-6.8 8.2-10.7zm-92.4 0c2.2 4 5 7.5 8.2 10.7l12-7a40 40 0 0012.6 7.3c4-4.1 7.3-8.8 9.7-13.8a59 59 0 01-40-14l-7.7 4.4c1.2 4.3 3 8.5 5.2 12.4zm46.2-80c-4.5 0-9 .5-13.4 1.7V34a40 40 0 00-12.5 7.2c1.5 5.7 4 10.8 7.1 15.4a59 59 0 0132.2-27.7V20a53.3 53.3 0 00-13.4-1.8z" />
|
||||
<path fill="#00B4FF"
|
||||
d="M178 9.2a62.6 62.6 0 11-.1 125.2A62.6 62.6 0 01178 9.2m0-9.2a71.7 71.7 0 100 143.5A71.7 71.7 0 00178 0z" />
|
||||
<path fill="#050A14"
|
||||
d="M96.6 212v4.3c-9.2-.8-15.4-5.8-15.4-17.8V180h4.6v18.4c0 8.6 4 12.6 10.8 13.5zm16-31.9v18.4c0 8.9-4.3 12.8-10.9 13.5v4.4c9.2-.7 15.5-5.6 15.5-18v-18.3h-4.7zM62.2 199v-2.2c0-12.7-8.8-17.4-21-17.4-12.1 0-20.7 4.7-20.7 17.4v2.2c0 12.8 8.6 17.6 20.7 17.6 1.5 0 3-.1 4.4-.3l11.8 6.2 2-3.3-8.2-4-6.4-3.1a32 32 0 01-3.6.2c-9.8 0-16-3.9-16-13.3v-2.2c0-9.3 6.2-13.1 16-13.1 9.9 0 16.3 3.8 16.3 13.1v2.2c0 5.3-2.1 8.7-5.6 10.8l4.8 2.4c3.4-2.8 5.5-7 5.5-13.2zM168 215.6h5.1L156 179.7h-4.8l17 36zM143 205l7.4-15.7-2.4-5-15.1 31.4h5.1l3.3-7h18.3l-1.8-3.7H143zm133.7 10.7h5.2l-17.3-35.9h-4.8l17 36zm-25-10.7l7.4-15.7-2.4-5-15.1 31.4h5.1l3.3-7h18.3l-1.7-3.7h-14.8zm73.8-2.5c6-1.2 9-5.4 9-11.4 0-8-4.5-10.9-12.9-10.9h-21.4v35.5h4.6v-31.3h16.5c5 0 8.5 1.4 8.5 6.7 0 5.2-3.5 7.7-8.5 7.7h-11.4v4.1h10.7l9.3 12.8h5.5l-9.9-13.2zm-117.4 9.9c-9.7 0-14.7-2.5-18.6-6.3l-2.2 3.8c5.1 5 11 6.7 21 6.7 1.6 0 3.1-.1 4.6-.3l-1.9-4h-3zm18.4-7c0-6.4-4.7-8.6-13.8-9.4l-10.1-1c-6.7-.7-9.3-2.2-9.3-5.6 0-2.5 1.4-4 4.6-5l-1.8-3.8c-4.7 1.4-7.5 4.2-7.5 8.9 0 5.2 3.4 8.7 13 9.6l11.3 1.2c6.4.6 8.9 2 8.9 5.4 0 2.7-2.1 4.7-6 5.8l1.8 3.9c5.3-1.6 8.9-4.7 8.9-10zm-20.3-21.9c7.9 0 13.3 1.8 18.1 5.7l1.8-3.9a30 30 0 00-19.6-5.9c-2 0-4 .1-5.7.3l1.9 4 3.5-.2z" />
|
||||
<path fill="#00B4FF"
|
||||
d="M.5 251.9c29.6-.5 59.2-.8 88.8-1l88.7-.3 88.7.3 44.4.4 44.4.6-44.4.6-44.4.4-88.7.3-88.7-.3a7981 7981 0 01-88.8-1z" />
|
||||
<path fill="none" d="M-565.2 324H-252v15.8h-313.2z" />
|
||||
</svg>
|
After Width: | Height: | Size: 4.4 KiB |
|
@ -0,0 +1,34 @@
|
|||
<template>
|
||||
<q-item
|
||||
clickable
|
||||
tag="a"
|
||||
target="_blank"
|
||||
:href="link"
|
||||
>
|
||||
<q-item-section
|
||||
v-if="icon"
|
||||
avatar
|
||||
>
|
||||
<q-icon :name="icon" />
|
||||
</q-item-section>
|
||||
|
||||
<q-item-section>
|
||||
<q-item-label>{{ title }}</q-item-label>
|
||||
<q-item-label caption>{{ caption }}</q-item-label>
|
||||
</q-item-section>
|
||||
</q-item>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
export interface EssentialLinkProps {
|
||||
title: string;
|
||||
caption?: string;
|
||||
link?: string;
|
||||
icon?: string;
|
||||
}
|
||||
withDefaults(defineProps<EssentialLinkProps>(), {
|
||||
caption: '',
|
||||
link: '#',
|
||||
icon: '',
|
||||
});
|
||||
</script>
|
|
@ -0,0 +1,37 @@
|
|||
<template>
|
||||
<div>
|
||||
<p>{{ title }}</p>
|
||||
<ul>
|
||||
<li v-for="todo in todos" :key="todo.id" @click="increment">
|
||||
{{ todo.id }} - {{ todo.content }}
|
||||
</li>
|
||||
</ul>
|
||||
<p>Count: {{ todoCount }} / {{ meta.totalCount }}</p>
|
||||
<p>Active: {{ active ? 'yes' : 'no' }}</p>
|
||||
<p>Clicks on todos: {{ clickCount }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { Todo, Meta } from './models';
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
todos?: Todo[];
|
||||
meta: Meta;
|
||||
active: boolean;
|
||||
}
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
todos: () => [],
|
||||
});
|
||||
|
||||
const clickCount = ref(0);
|
||||
function increment() {
|
||||
clickCount.value += 1;
|
||||
return clickCount.value;
|
||||
}
|
||||
|
||||
const todoCount = computed(() => props.todos.length);
|
||||
|
||||
</script>
|
|
@ -0,0 +1,8 @@
|
|||
export interface Todo {
|
||||
id: number;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface Meta {
|
||||
totalCount: number;
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
// app global css in SCSS form
|
|
@ -0,0 +1,25 @@
|
|||
// Quasar SCSS (& Sass) Variables
|
||||
// --------------------------------------------------
|
||||
// To customize the look and feel of this app, you can override
|
||||
// the Sass/SCSS variables found in Quasar's source Sass/SCSS files.
|
||||
|
||||
// Check documentation for full list of Quasar variables
|
||||
|
||||
// Your own variables (that are declared here) and Quasar's own
|
||||
// ones will be available out of the box in your .vue/.scss/.sass files
|
||||
|
||||
// It's highly recommended to change the default colors
|
||||
// to match your app's branding.
|
||||
// Tip: Use the "Theme Builder" on Quasar's documentation website.
|
||||
|
||||
$primary : #1976D2;
|
||||
$secondary : #26A69A;
|
||||
$accent : #9C27B0;
|
||||
|
||||
$dark : #1D1D1D;
|
||||
$dark-page : #121212;
|
||||
|
||||
$positive : #21BA45;
|
||||
$negative : #C10015;
|
||||
$info : #31CCEC;
|
||||
$warning : #F2C037;
|
|
@ -0,0 +1,9 @@
|
|||
/* eslint-disable */
|
||||
|
||||
declare namespace NodeJS {
|
||||
interface ProcessEnv {
|
||||
NODE_ENV: string;
|
||||
VUE_ROUTER_MODE: 'hash' | 'history' | 'abstract' | undefined;
|
||||
VUE_ROUTER_BASE: string | undefined;
|
||||
}
|
||||
}
|
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,161 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
option go_package = "google.golang.org/protobuf/types/known/anypb";
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "AnyProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
|
||||
// `Any` contains an arbitrary serialized protocol buffer message along with a
|
||||
// URL that describes the type of the serialized message.
|
||||
//
|
||||
// Protobuf library provides support to pack/unpack Any values in the form
|
||||
// of utility functions or additional generated methods of the Any type.
|
||||
//
|
||||
// Example 1: Pack and unpack a message in C++.
|
||||
//
|
||||
// Foo foo = ...;
|
||||
// Any any;
|
||||
// any.PackFrom(foo);
|
||||
// ...
|
||||
// if (any.UnpackTo(&foo)) {
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
// Example 2: Pack and unpack a message in Java.
|
||||
//
|
||||
// Foo foo = ...;
|
||||
// Any any = Any.pack(foo);
|
||||
// ...
|
||||
// if (any.is(Foo.class)) {
|
||||
// foo = any.unpack(Foo.class);
|
||||
// }
|
||||
// // or ...
|
||||
// if (any.isSameTypeAs(Foo.getDefaultInstance())) {
|
||||
// foo = any.unpack(Foo.getDefaultInstance());
|
||||
// }
|
||||
//
|
||||
// Example 3: Pack and unpack a message in Python.
|
||||
//
|
||||
// foo = Foo(...)
|
||||
// any = Any()
|
||||
// any.Pack(foo)
|
||||
// ...
|
||||
// if any.Is(Foo.DESCRIPTOR):
|
||||
// any.Unpack(foo)
|
||||
// ...
|
||||
//
|
||||
// Example 4: Pack and unpack a message in Go
|
||||
//
|
||||
// foo := &pb.Foo{...}
|
||||
// any, err := anypb.New(foo)
|
||||
// if err != nil {
|
||||
// ...
|
||||
// }
|
||||
// ...
|
||||
// foo := &pb.Foo{}
|
||||
// if err := any.UnmarshalTo(foo); err != nil {
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
// The pack methods provided by protobuf library will by default use
|
||||
// 'type.googleapis.com/full.type.name' as the type URL and the unpack
|
||||
// methods only use the fully qualified type name after the last '/'
|
||||
// in the type URL, for example "foo.bar.com/x/y.z" will yield type
|
||||
// name "y.z".
|
||||
//
|
||||
// JSON
|
||||
//
|
||||
// The JSON representation of an `Any` value uses the regular
|
||||
// representation of the deserialized, embedded message, with an
|
||||
// additional field `@type` which contains the type URL. Example:
|
||||
//
|
||||
// package google.profile;
|
||||
// message Person {
|
||||
// string first_name = 1;
|
||||
// string last_name = 2;
|
||||
// }
|
||||
//
|
||||
// {
|
||||
// "@type": "type.googleapis.com/google.profile.Person",
|
||||
// "firstName": <string>,
|
||||
// "lastName": <string>
|
||||
// }
|
||||
//
|
||||
// If the embedded message type is well-known and has a custom JSON
|
||||
// representation, that representation will be embedded adding a field
|
||||
// `value` which holds the custom JSON in addition to the `@type`
|
||||
// field. Example (for message [google.protobuf.Duration][]):
|
||||
//
|
||||
// {
|
||||
// "@type": "type.googleapis.com/google.protobuf.Duration",
|
||||
// "value": "1.212s"
|
||||
// }
|
||||
//
|
||||
message Any {
|
||||
// A URL/resource name that uniquely identifies the type of the serialized
|
||||
// protocol buffer message. This string must contain at least
|
||||
// one "/" character. The last segment of the URL's path must represent
|
||||
// the fully qualified name of the type (as in
|
||||
// `path/google.protobuf.Duration`). The name should be in a canonical form
|
||||
// (e.g., leading "." is not accepted).
|
||||
//
|
||||
// In practice, teams usually precompile into the binary all types that they
|
||||
// expect it to use in the context of Any. However, for URLs which use the
|
||||
// scheme `http`, `https`, or no scheme, one can optionally set up a type
|
||||
// server that maps type URLs to message definitions as follows:
|
||||
//
|
||||
// * If no scheme is provided, `https` is assumed.
|
||||
// * An HTTP GET on the URL must yield a [google.protobuf.Type][]
|
||||
// value in binary format, or produce an error.
|
||||
// * Applications are allowed to cache lookup results based on the
|
||||
// URL, or have them precompiled into a binary to avoid any
|
||||
// lookup. Therefore, binary compatibility needs to be preserved
|
||||
// on changes to types. (Use versioned type names to manage
|
||||
// breaking changes.)
|
||||
//
|
||||
// Note: this functionality is not currently available in the official
|
||||
// protobuf release, and it is not used for type URLs beginning with
|
||||
// type.googleapis.com.
|
||||
//
|
||||
// Schemes other than `http`, `https` (or the empty scheme) might be
|
||||
// used with implementation specific semantics.
|
||||
//
|
||||
string type_url = 1;
|
||||
|
||||
// Must be a valid serialized protocol buffer of the above specified type.
|
||||
bytes value = 2;
|
||||
}
|
|
@ -0,0 +1,207 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
import "google/protobuf/source_context.proto";
|
||||
import "google/protobuf/type.proto";
|
||||
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "ApiProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
option go_package = "google.golang.org/protobuf/types/known/apipb";
|
||||
|
||||
// Api is a light-weight descriptor for an API Interface.
|
||||
//
|
||||
// Interfaces are also described as "protocol buffer services" in some contexts,
|
||||
// such as by the "service" keyword in a .proto file, but they are different
|
||||
// from API Services, which represent a concrete implementation of an interface
|
||||
// as opposed to simply a description of methods and bindings. They are also
|
||||
// sometimes simply referred to as "APIs" in other contexts, such as the name of
|
||||
// this message itself. See https://cloud.google.com/apis/design/glossary for
|
||||
// detailed terminology.
|
||||
message Api {
|
||||
// The fully qualified name of this interface, including package name
|
||||
// followed by the interface's simple name.
|
||||
string name = 1;
|
||||
|
||||
// The methods of this interface, in unspecified order.
|
||||
repeated Method methods = 2;
|
||||
|
||||
// Any metadata attached to the interface.
|
||||
repeated Option options = 3;
|
||||
|
||||
// A version string for this interface. If specified, must have the form
|
||||
// `major-version.minor-version`, as in `1.10`. If the minor version is
|
||||
// omitted, it defaults to zero. If the entire version field is empty, the
|
||||
// major version is derived from the package name, as outlined below. If the
|
||||
// field is not empty, the version in the package name will be verified to be
|
||||
// consistent with what is provided here.
|
||||
//
|
||||
// The versioning schema uses [semantic
|
||||
// versioning](http://semver.org) where the major version number
|
||||
// indicates a breaking change and the minor version an additive,
|
||||
// non-breaking change. Both version numbers are signals to users
|
||||
// what to expect from different versions, and should be carefully
|
||||
// chosen based on the product plan.
|
||||
//
|
||||
// The major version is also reflected in the package name of the
|
||||
// interface, which must end in `v<major-version>`, as in
|
||||
// `google.feature.v1`. For major versions 0 and 1, the suffix can
|
||||
// be omitted. Zero major versions must only be used for
|
||||
// experimental, non-GA interfaces.
|
||||
//
|
||||
string version = 4;
|
||||
|
||||
// Source context for the protocol buffer service represented by this
|
||||
// message.
|
||||
SourceContext source_context = 5;
|
||||
|
||||
// Included interfaces. See [Mixin][].
|
||||
repeated Mixin mixins = 6;
|
||||
|
||||
// The source syntax of the service.
|
||||
Syntax syntax = 7;
|
||||
}
|
||||
|
||||
// Method represents a method of an API interface.
|
||||
message Method {
|
||||
// The simple name of this method.
|
||||
string name = 1;
|
||||
|
||||
// A URL of the input message type.
|
||||
string request_type_url = 2;
|
||||
|
||||
// If true, the request is streamed.
|
||||
bool request_streaming = 3;
|
||||
|
||||
// The URL of the output message type.
|
||||
string response_type_url = 4;
|
||||
|
||||
// If true, the response is streamed.
|
||||
bool response_streaming = 5;
|
||||
|
||||
// Any metadata attached to the method.
|
||||
repeated Option options = 6;
|
||||
|
||||
// The source syntax of this method.
|
||||
Syntax syntax = 7;
|
||||
}
|
||||
|
||||
// Declares an API Interface to be included in this interface. The including
|
||||
// interface must redeclare all the methods from the included interface, but
|
||||
// documentation and options are inherited as follows:
|
||||
//
|
||||
// - If after comment and whitespace stripping, the documentation
|
||||
// string of the redeclared method is empty, it will be inherited
|
||||
// from the original method.
|
||||
//
|
||||
// - Each annotation belonging to the service config (http,
|
||||
// visibility) which is not set in the redeclared method will be
|
||||
// inherited.
|
||||
//
|
||||
// - If an http annotation is inherited, the path pattern will be
|
||||
// modified as follows. Any version prefix will be replaced by the
|
||||
// version of the including interface plus the [root][] path if
|
||||
// specified.
|
||||
//
|
||||
// Example of a simple mixin:
|
||||
//
|
||||
// package google.acl.v1;
|
||||
// service AccessControl {
|
||||
// // Get the underlying ACL object.
|
||||
// rpc GetAcl(GetAclRequest) returns (Acl) {
|
||||
// option (google.api.http).get = "/v1/{resource=**}:getAcl";
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// package google.storage.v2;
|
||||
// service Storage {
|
||||
// rpc GetAcl(GetAclRequest) returns (Acl);
|
||||
//
|
||||
// // Get a data record.
|
||||
// rpc GetData(GetDataRequest) returns (Data) {
|
||||
// option (google.api.http).get = "/v2/{resource=**}";
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// Example of a mixin configuration:
|
||||
//
|
||||
// apis:
|
||||
// - name: google.storage.v2.Storage
|
||||
// mixins:
|
||||
// - name: google.acl.v1.AccessControl
|
||||
//
|
||||
// The mixin construct implies that all methods in `AccessControl` are
|
||||
// also declared with same name and request/response types in
|
||||
// `Storage`. A documentation generator or annotation processor will
|
||||
// see the effective `Storage.GetAcl` method after inheriting
|
||||
// documentation and annotations as follows:
|
||||
//
|
||||
// service Storage {
|
||||
// // Get the underlying ACL object.
|
||||
// rpc GetAcl(GetAclRequest) returns (Acl) {
|
||||
// option (google.api.http).get = "/v2/{resource=**}:getAcl";
|
||||
// }
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
// Note how the version in the path pattern changed from `v1` to `v2`.
|
||||
//
|
||||
// If the `root` field in the mixin is specified, it should be a
|
||||
// relative path under which inherited HTTP paths are placed. Example:
|
||||
//
|
||||
// apis:
|
||||
// - name: google.storage.v2.Storage
|
||||
// mixins:
|
||||
// - name: google.acl.v1.AccessControl
|
||||
// root: acls
|
||||
//
|
||||
// This implies the following inherited HTTP annotation:
|
||||
//
|
||||
// service Storage {
|
||||
// // Get the underlying ACL object.
|
||||
// rpc GetAcl(GetAclRequest) returns (Acl) {
|
||||
// option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
|
||||
// }
|
||||
// ...
|
||||
// }
|
||||
message Mixin {
|
||||
// The fully qualified name of the interface which is included.
|
||||
string name = 1;
|
||||
|
||||
// If non-empty specifies a path under which inherited HTTP paths
|
||||
// are rooted.
|
||||
string root = 2;
|
||||
}
|
|
@ -0,0 +1,180 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// Author: kenton@google.com (Kenton Varda)
|
||||
//
|
||||
// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
|
||||
// just a program that reads a CodeGeneratorRequest from stdin and writes a
|
||||
// CodeGeneratorResponse to stdout.
|
||||
//
|
||||
// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
|
||||
// of dealing with the raw protocol defined here.
|
||||
//
|
||||
// A plugin executable needs only to be placed somewhere in the path. The
|
||||
// plugin should be named "protoc-gen-$NAME", and will then be used when the
|
||||
// flag "--${NAME}_out" is passed to protoc.
|
||||
|
||||
syntax = "proto2";
|
||||
|
||||
package google.protobuf.compiler;
|
||||
option java_package = "com.google.protobuf.compiler";
|
||||
option java_outer_classname = "PluginProtos";
|
||||
|
||||
option csharp_namespace = "Google.Protobuf.Compiler";
|
||||
option go_package = "google.golang.org/protobuf/types/pluginpb";
|
||||
|
||||
import "google/protobuf/descriptor.proto";
|
||||
|
||||
// The version number of protocol compiler.
|
||||
message Version {
|
||||
optional int32 major = 1;
|
||||
optional int32 minor = 2;
|
||||
optional int32 patch = 3;
|
||||
// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
|
||||
// be empty for mainline stable releases.
|
||||
optional string suffix = 4;
|
||||
}
|
||||
|
||||
// An encoded CodeGeneratorRequest is written to the plugin's stdin.
|
||||
message CodeGeneratorRequest {
|
||||
// The .proto files that were explicitly listed on the command-line. The
|
||||
// code generator should generate code only for these files. Each file's
|
||||
// descriptor will be included in proto_file, below.
|
||||
repeated string file_to_generate = 1;
|
||||
|
||||
// The generator parameter passed on the command-line.
|
||||
optional string parameter = 2;
|
||||
|
||||
// FileDescriptorProtos for all files in files_to_generate and everything
|
||||
// they import. The files will appear in topological order, so each file
|
||||
// appears before any file that imports it.
|
||||
//
|
||||
// protoc guarantees that all proto_files will be written after
|
||||
// the fields above, even though this is not technically guaranteed by the
|
||||
// protobuf wire format. This theoretically could allow a plugin to stream
|
||||
// in the FileDescriptorProtos and handle them one by one rather than read
|
||||
// the entire set into memory at once. However, as of this writing, this
|
||||
// is not similarly optimized on protoc's end -- it will store all fields in
|
||||
// memory at once before sending them to the plugin.
|
||||
//
|
||||
// Type names of fields and extensions in the FileDescriptorProto are always
|
||||
// fully qualified.
|
||||
repeated FileDescriptorProto proto_file = 15;
|
||||
|
||||
// The version number of protocol compiler.
|
||||
optional Version compiler_version = 3;
|
||||
}
|
||||
|
||||
// The plugin writes an encoded CodeGeneratorResponse to stdout.
|
||||
message CodeGeneratorResponse {
|
||||
// Error message. If non-empty, code generation failed. The plugin process
|
||||
// should exit with status code zero even if it reports an error in this way.
|
||||
//
|
||||
// This should be used to indicate errors in .proto files which prevent the
|
||||
// code generator from generating correct code. Errors which indicate a
|
||||
// problem in protoc itself -- such as the input CodeGeneratorRequest being
|
||||
// unparseable -- should be reported by writing a message to stderr and
|
||||
// exiting with a non-zero status code.
|
||||
optional string error = 1;
|
||||
|
||||
// A bitmask of supported features that the code generator supports.
|
||||
// This is a bitwise "or" of values from the Feature enum.
|
||||
optional uint64 supported_features = 2;
|
||||
|
||||
// Sync with code_generator.h.
|
||||
enum Feature {
|
||||
FEATURE_NONE = 0;
|
||||
FEATURE_PROTO3_OPTIONAL = 1;
|
||||
}
|
||||
|
||||
// Represents a single generated file.
|
||||
message File {
|
||||
// The file name, relative to the output directory. The name must not
|
||||
// contain "." or ".." components and must be relative, not be absolute (so,
|
||||
// the file cannot lie outside the output directory). "/" must be used as
|
||||
// the path separator, not "\".
|
||||
//
|
||||
// If the name is omitted, the content will be appended to the previous
|
||||
// file. This allows the generator to break large files into small chunks,
|
||||
// and allows the generated text to be streamed back to protoc so that large
|
||||
// files need not reside completely in memory at one time. Note that as of
|
||||
// this writing protoc does not optimize for this -- it will read the entire
|
||||
// CodeGeneratorResponse before writing files to disk.
|
||||
optional string name = 1;
|
||||
|
||||
// If non-empty, indicates that the named file should already exist, and the
|
||||
// content here is to be inserted into that file at a defined insertion
|
||||
// point. This feature allows a code generator to extend the output
|
||||
// produced by another code generator. The original generator may provide
|
||||
// insertion points by placing special annotations in the file that look
|
||||
// like:
|
||||
// @@protoc_insertion_point(NAME)
|
||||
// The annotation can have arbitrary text before and after it on the line,
|
||||
// which allows it to be placed in a comment. NAME should be replaced with
|
||||
// an identifier naming the point -- this is what other generators will use
|
||||
// as the insertion_point. Code inserted at this point will be placed
|
||||
// immediately above the line containing the insertion point (thus multiple
|
||||
// insertions to the same point will come out in the order they were added).
|
||||
// The double-@ is intended to make it unlikely that the generated code
|
||||
// could contain things that look like insertion points by accident.
|
||||
//
|
||||
// For example, the C++ code generator places the following line in the
|
||||
// .pb.h files that it generates:
|
||||
// // @@protoc_insertion_point(namespace_scope)
|
||||
// This line appears within the scope of the file's package namespace, but
|
||||
// outside of any particular class. Another plugin can then specify the
|
||||
// insertion_point "namespace_scope" to generate additional classes or
|
||||
// other declarations that should be placed in this scope.
|
||||
//
|
||||
// Note that if the line containing the insertion point begins with
|
||||
// whitespace, the same whitespace will be added to every line of the
|
||||
// inserted text. This is useful for languages like Python, where
|
||||
// indentation matters. In these languages, the insertion point comment
|
||||
// should be indented the same amount as any inserted code will need to be
|
||||
// in order to work correctly in that context.
|
||||
//
|
||||
// The code generator that generates the initial file and the one which
|
||||
// inserts into it must both run as part of a single invocation of protoc.
|
||||
// Code generators are executed in the order in which they appear on the
|
||||
// command line.
|
||||
//
|
||||
// If |insertion_point| is present, |name| must also be present.
|
||||
optional string insertion_point = 2;
|
||||
|
||||
// The file contents.
|
||||
optional string content = 15;
|
||||
|
||||
// Information describing the file content being inserted. If an insertion
|
||||
// point is used, this information will be appropriately offset and inserted
|
||||
// into the code generation metadata for the generated files.
|
||||
optional GeneratedCodeInfo generated_code_info = 16;
|
||||
}
|
||||
repeated File file = 15;
|
||||
}
|
|
@ -0,0 +1,975 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// Author: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// The messages in this file describe the definitions found in .proto files.
|
||||
// A valid .proto file can be translated directly to a FileDescriptorProto
|
||||
// without any other information (e.g. without reading its imports).
|
||||
|
||||
syntax = "proto2";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
option go_package = "google.golang.org/protobuf/types/descriptorpb";
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "DescriptorProtos";
|
||||
option csharp_namespace = "Google.Protobuf.Reflection";
|
||||
option objc_class_prefix = "GPB";
|
||||
option cc_enable_arenas = true;
|
||||
|
||||
// descriptor.proto must be optimized for speed because reflection-based
|
||||
// algorithms don't work during bootstrapping.
|
||||
option optimize_for = SPEED;
|
||||
|
||||
// The protocol compiler can output a FileDescriptorSet containing the .proto
|
||||
// files it parses.
|
||||
message FileDescriptorSet {
|
||||
repeated FileDescriptorProto file = 1;
|
||||
}
|
||||
|
||||
// Describes a complete .proto file.
|
||||
message FileDescriptorProto {
|
||||
optional string name = 1; // file name, relative to root of source tree
|
||||
optional string package = 2; // e.g. "foo", "foo.bar", etc.
|
||||
|
||||
// Names of files imported by this file.
|
||||
repeated string dependency = 3;
|
||||
// Indexes of the public imported files in the dependency list above.
|
||||
repeated int32 public_dependency = 10;
|
||||
// Indexes of the weak imported files in the dependency list.
|
||||
// For Google-internal migration only. Do not use.
|
||||
repeated int32 weak_dependency = 11;
|
||||
|
||||
// All top-level definitions in this file.
|
||||
repeated DescriptorProto message_type = 4;
|
||||
repeated EnumDescriptorProto enum_type = 5;
|
||||
repeated ServiceDescriptorProto service = 6;
|
||||
repeated FieldDescriptorProto extension = 7;
|
||||
|
||||
optional FileOptions options = 8;
|
||||
|
||||
// This field contains optional information about the original source code.
|
||||
// You may safely remove this entire field without harming runtime
|
||||
// functionality of the descriptors -- the information is needed only by
|
||||
// development tools.
|
||||
optional SourceCodeInfo source_code_info = 9;
|
||||
|
||||
// The syntax of the proto file.
|
||||
// The supported values are "proto2", "proto3", and "editions".
|
||||
//
|
||||
// If `edition` is present, this value must be "editions".
|
||||
optional string syntax = 12;
|
||||
|
||||
// The edition of the proto file, which is an opaque string.
|
||||
optional string edition = 13;
|
||||
}
|
||||
|
||||
// Describes a message type.
|
||||
message DescriptorProto {
|
||||
optional string name = 1;
|
||||
|
||||
repeated FieldDescriptorProto field = 2;
|
||||
repeated FieldDescriptorProto extension = 6;
|
||||
|
||||
repeated DescriptorProto nested_type = 3;
|
||||
repeated EnumDescriptorProto enum_type = 4;
|
||||
|
||||
message ExtensionRange {
|
||||
optional int32 start = 1; // Inclusive.
|
||||
optional int32 end = 2; // Exclusive.
|
||||
|
||||
optional ExtensionRangeOptions options = 3;
|
||||
}
|
||||
repeated ExtensionRange extension_range = 5;
|
||||
|
||||
repeated OneofDescriptorProto oneof_decl = 8;
|
||||
|
||||
optional MessageOptions options = 7;
|
||||
|
||||
// Range of reserved tag numbers. Reserved tag numbers may not be used by
|
||||
// fields or extension ranges in the same message. Reserved ranges may
|
||||
// not overlap.
|
||||
message ReservedRange {
|
||||
optional int32 start = 1; // Inclusive.
|
||||
optional int32 end = 2; // Exclusive.
|
||||
}
|
||||
repeated ReservedRange reserved_range = 9;
|
||||
// Reserved field names, which may not be used by fields in the same message.
|
||||
// A given name may only be reserved once.
|
||||
repeated string reserved_name = 10;
|
||||
}
|
||||
|
||||
message ExtensionRangeOptions {
|
||||
// The parser stores options it doesn't recognize here. See above.
|
||||
repeated UninterpretedOption uninterpreted_option = 999;
|
||||
|
||||
// Clients can define custom options in extensions of this message. See above.
|
||||
extensions 1000 to max;
|
||||
}
|
||||
|
||||
// Describes a field within a message.
|
||||
message FieldDescriptorProto {
|
||||
enum Type {
|
||||
// 0 is reserved for errors.
|
||||
// Order is weird for historical reasons.
|
||||
TYPE_DOUBLE = 1;
|
||||
TYPE_FLOAT = 2;
|
||||
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
|
||||
// negative values are likely.
|
||||
TYPE_INT64 = 3;
|
||||
TYPE_UINT64 = 4;
|
||||
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
|
||||
// negative values are likely.
|
||||
TYPE_INT32 = 5;
|
||||
TYPE_FIXED64 = 6;
|
||||
TYPE_FIXED32 = 7;
|
||||
TYPE_BOOL = 8;
|
||||
TYPE_STRING = 9;
|
||||
// Tag-delimited aggregate.
|
||||
// Group type is deprecated and not supported in proto3. However, Proto3
|
||||
// implementations should still be able to parse the group wire format and
|
||||
// treat group fields as unknown fields.
|
||||
TYPE_GROUP = 10;
|
||||
TYPE_MESSAGE = 11; // Length-delimited aggregate.
|
||||
|
||||
// New in version 2.
|
||||
TYPE_BYTES = 12;
|
||||
TYPE_UINT32 = 13;
|
||||
TYPE_ENUM = 14;
|
||||
TYPE_SFIXED32 = 15;
|
||||
TYPE_SFIXED64 = 16;
|
||||
TYPE_SINT32 = 17; // Uses ZigZag encoding.
|
||||
TYPE_SINT64 = 18; // Uses ZigZag encoding.
|
||||
}
|
||||
|
||||
enum Label {
|
||||
// 0 is reserved for errors
|
||||
LABEL_OPTIONAL = 1;
|
||||
LABEL_REQUIRED = 2;
|
||||
LABEL_REPEATED = 3;
|
||||
}
|
||||
|
||||
optional string name = 1;
|
||||
optional int32 number = 3;
|
||||
optional Label label = 4;
|
||||
|
||||
// If type_name is set, this need not be set. If both this and type_name
|
||||
// are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
|
||||
optional Type type = 5;
|
||||
|
||||
// For message and enum types, this is the name of the type. If the name
|
||||
// starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
|
||||
// rules are used to find the type (i.e. first the nested types within this
|
||||
// message are searched, then within the parent, on up to the root
|
||||
// namespace).
|
||||
optional string type_name = 6;
|
||||
|
||||
// For extensions, this is the name of the type being extended. It is
|
||||
// resolved in the same manner as type_name.
|
||||
optional string extendee = 2;
|
||||
|
||||
// For numeric types, contains the original text representation of the value.
|
||||
// For booleans, "true" or "false".
|
||||
// For strings, contains the default text contents (not escaped in any way).
|
||||
// For bytes, contains the C escaped value. All bytes >= 128 are escaped.
|
||||
optional string default_value = 7;
|
||||
|
||||
// If set, gives the index of a oneof in the containing type's oneof_decl
|
||||
// list. This field is a member of that oneof.
|
||||
optional int32 oneof_index = 9;
|
||||
|
||||
// JSON name of this field. The value is set by protocol compiler. If the
|
||||
// user has set a "json_name" option on this field, that option's value
|
||||
// will be used. Otherwise, it's deduced from the field's name by converting
|
||||
// it to camelCase.
|
||||
optional string json_name = 10;
|
||||
|
||||
optional FieldOptions options = 8;
|
||||
|
||||
// If true, this is a proto3 "optional". When a proto3 field is optional, it
|
||||
// tracks presence regardless of field type.
|
||||
//
|
||||
// When proto3_optional is true, this field must be belong to a oneof to
|
||||
// signal to old proto3 clients that presence is tracked for this field. This
|
||||
// oneof is known as a "synthetic" oneof, and this field must be its sole
|
||||
// member (each proto3 optional field gets its own synthetic oneof). Synthetic
|
||||
// oneofs exist in the descriptor only, and do not generate any API. Synthetic
|
||||
// oneofs must be ordered after all "real" oneofs.
|
||||
//
|
||||
// For message fields, proto3_optional doesn't create any semantic change,
|
||||
// since non-repeated message fields always track presence. However it still
|
||||
// indicates the semantic detail of whether the user wrote "optional" or not.
|
||||
// This can be useful for round-tripping the .proto file. For consistency we
|
||||
// give message fields a synthetic oneof also, even though it is not required
|
||||
// to track presence. This is especially important because the parser can't
|
||||
// tell if a field is a message or an enum, so it must always create a
|
||||
// synthetic oneof.
|
||||
//
|
||||
// Proto2 optional fields do not set this flag, because they already indicate
|
||||
// optional with `LABEL_OPTIONAL`.
|
||||
optional bool proto3_optional = 17;
|
||||
}
|
||||
|
||||
// Describes a oneof.
|
||||
message OneofDescriptorProto {
|
||||
optional string name = 1;
|
||||
optional OneofOptions options = 2;
|
||||
}
|
||||
|
||||
// Describes an enum type.
|
||||
message EnumDescriptorProto {
|
||||
optional string name = 1;
|
||||
|
||||
repeated EnumValueDescriptorProto value = 2;
|
||||
|
||||
optional EnumOptions options = 3;
|
||||
|
||||
// Range of reserved numeric values. Reserved values may not be used by
|
||||
// entries in the same enum. Reserved ranges may not overlap.
|
||||
//
|
||||
// Note that this is distinct from DescriptorProto.ReservedRange in that it
|
||||
// is inclusive such that it can appropriately represent the entire int32
|
||||
// domain.
|
||||
message EnumReservedRange {
|
||||
optional int32 start = 1; // Inclusive.
|
||||
optional int32 end = 2; // Inclusive.
|
||||
}
|
||||
|
||||
// Range of reserved numeric values. Reserved numeric values may not be used
|
||||
// by enum values in the same enum declaration. Reserved ranges may not
|
||||
// overlap.
|
||||
repeated EnumReservedRange reserved_range = 4;
|
||||
|
||||
// Reserved enum value names, which may not be reused. A given name may only
|
||||
// be reserved once.
|
||||
repeated string reserved_name = 5;
|
||||
}
|
||||
|
||||
// Describes a value within an enum.
|
||||
message EnumValueDescriptorProto {
|
||||
optional string name = 1;
|
||||
optional int32 number = 2;
|
||||
|
||||
optional EnumValueOptions options = 3;
|
||||
}
|
||||
|
||||
// Describes a service.
|
||||
message ServiceDescriptorProto {
|
||||
optional string name = 1;
|
||||
repeated MethodDescriptorProto method = 2;
|
||||
|
||||
optional ServiceOptions options = 3;
|
||||
}
|
||||
|
||||
// Describes a method of a service.
|
||||
message MethodDescriptorProto {
|
||||
optional string name = 1;
|
||||
|
||||
// Input and output type names. These are resolved in the same way as
|
||||
// FieldDescriptorProto.type_name, but must refer to a message type.
|
||||
optional string input_type = 2;
|
||||
optional string output_type = 3;
|
||||
|
||||
optional MethodOptions options = 4;
|
||||
|
||||
// Identifies if client streams multiple client messages
|
||||
optional bool client_streaming = 5 [default = false];
|
||||
// Identifies if server streams multiple server messages
|
||||
optional bool server_streaming = 6 [default = false];
|
||||
}
|
||||
|
||||
// ===================================================================
|
||||
// Options
|
||||
|
||||
// Each of the definitions above may have "options" attached. These are
|
||||
// just annotations which may cause code to be generated slightly differently
|
||||
// or may contain hints for code that manipulates protocol messages.
|
||||
//
|
||||
// Clients may define custom options as extensions of the *Options messages.
|
||||
// These extensions may not yet be known at parsing time, so the parser cannot
|
||||
// store the values in them. Instead it stores them in a field in the *Options
|
||||
// message called uninterpreted_option. This field must have the same name
|
||||
// across all *Options messages. We then use this field to populate the
|
||||
// extensions when we build a descriptor, at which point all protos have been
|
||||
// parsed and so all extensions are known.
|
||||
//
|
||||
// Extension numbers for custom options may be chosen as follows:
|
||||
// * For options which will only be used within a single application or
|
||||
// organization, or for experimental options, use field numbers 50000
|
||||
// through 99999. It is up to you to ensure that you do not use the
|
||||
// same number for multiple options.
|
||||
// * For options which will be published and used publicly by multiple
|
||||
// independent entities, e-mail protobuf-global-extension-registry@google.com
|
||||
// to reserve extension numbers. Simply provide your project name (e.g.
|
||||
// Objective-C plugin) and your project website (if available) -- there's no
|
||||
// need to explain how you intend to use them. Usually you only need one
|
||||
// extension number. You can declare multiple options with only one extension
|
||||
// number by putting them in a sub-message. See the Custom Options section of
|
||||
// the docs for examples:
|
||||
// https://developers.google.com/protocol-buffers/docs/proto#options
|
||||
// If this turns out to be popular, a web service will be set up
|
||||
// to automatically assign option numbers.
|
||||
|
||||
message FileOptions {
|
||||
|
||||
// Sets the Java package where classes generated from this .proto will be
|
||||
// placed. By default, the proto package is used, but this is often
|
||||
// inappropriate because proto packages do not normally start with backwards
|
||||
// domain names.
|
||||
optional string java_package = 1;
|
||||
|
||||
// Controls the name of the wrapper Java class generated for the .proto file.
|
||||
// That class will always contain the .proto file's getDescriptor() method as
|
||||
// well as any top-level extensions defined in the .proto file.
|
||||
// If java_multiple_files is disabled, then all the other classes from the
|
||||
// .proto file will be nested inside the single wrapper outer class.
|
||||
optional string java_outer_classname = 8;
|
||||
|
||||
// If enabled, then the Java code generator will generate a separate .java
|
||||
// file for each top-level message, enum, and service defined in the .proto
|
||||
// file. Thus, these types will *not* be nested inside the wrapper class
|
||||
// named by java_outer_classname. However, the wrapper class will still be
|
||||
// generated to contain the file's getDescriptor() method as well as any
|
||||
// top-level extensions defined in the file.
|
||||
optional bool java_multiple_files = 10 [default = false];
|
||||
|
||||
// This option does nothing.
|
||||
optional bool java_generate_equals_and_hash = 20 [deprecated=true];
|
||||
|
||||
// If set true, then the Java2 code generator will generate code that
|
||||
// throws an exception whenever an attempt is made to assign a non-UTF-8
|
||||
// byte sequence to a string field.
|
||||
// Message reflection will do the same.
|
||||
// However, an extension field still accepts non-UTF-8 byte sequences.
|
||||
// This option has no effect on when used with the lite runtime.
|
||||
optional bool java_string_check_utf8 = 27 [default = false];
|
||||
|
||||
// Generated classes can be optimized for speed or code size.
|
||||
enum OptimizeMode {
|
||||
SPEED = 1; // Generate complete code for parsing, serialization,
|
||||
// etc.
|
||||
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
|
||||
LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
|
||||
}
|
||||
optional OptimizeMode optimize_for = 9 [default = SPEED];
|
||||
|
||||
// Sets the Go package where structs generated from this .proto will be
|
||||
// placed. If omitted, the Go package will be derived from the following:
|
||||
// - The basename of the package import path, if provided.
|
||||
// - Otherwise, the package statement in the .proto file, if present.
|
||||
// - Otherwise, the basename of the .proto file, without extension.
|
||||
optional string go_package = 11;
|
||||
|
||||
// Should generic services be generated in each language? "Generic" services
|
||||
// are not specific to any particular RPC system. They are generated by the
|
||||
// main code generators in each language (without additional plugins).
|
||||
// Generic services were the only kind of service generation supported by
|
||||
// early versions of google.protobuf.
|
||||
//
|
||||
// Generic services are now considered deprecated in favor of using plugins
|
||||
// that generate code specific to your particular RPC system. Therefore,
|
||||
// these default to false. Old code which depends on generic services should
|
||||
// explicitly set them to true.
|
||||
optional bool cc_generic_services = 16 [default = false];
|
||||
optional bool java_generic_services = 17 [default = false];
|
||||
optional bool py_generic_services = 18 [default = false];
|
||||
optional bool php_generic_services = 42 [default = false];
|
||||
|
||||
// Is this file deprecated?
|
||||
// Depending on the target platform, this can emit Deprecated annotations
|
||||
// for everything in the file, or it will be completely ignored; in the very
|
||||
// least, this is a formalization for deprecating files.
|
||||
optional bool deprecated = 23 [default = false];
|
||||
|
||||
// Enables the use of arenas for the proto messages in this file. This applies
|
||||
// only to generated classes for C++.
|
||||
optional bool cc_enable_arenas = 31 [default = true];
|
||||
|
||||
// Sets the objective c class prefix which is prepended to all objective c
|
||||
// generated classes from this .proto. There is no default.
|
||||
optional string objc_class_prefix = 36;
|
||||
|
||||
// Namespace for generated classes; defaults to the package.
|
||||
optional string csharp_namespace = 37;
|
||||
|
||||
// By default Swift generators will take the proto package and CamelCase it
|
||||
// replacing '.' with underscore and use that to prefix the types/symbols
|
||||
// defined. When this options is provided, they will use this value instead
|
||||
// to prefix the types/symbols defined.
|
||||
optional string swift_prefix = 39;
|
||||
|
||||
// Sets the php class prefix which is prepended to all php generated classes
|
||||
// from this .proto. Default is empty.
|
||||
optional string php_class_prefix = 40;
|
||||
|
||||
// Use this option to change the namespace of php generated classes. Default
|
||||
// is empty. When this option is empty, the package name will be used for
|
||||
// determining the namespace.
|
||||
optional string php_namespace = 41;
|
||||
|
||||
// Use this option to change the namespace of php generated metadata classes.
|
||||
// Default is empty. When this option is empty, the proto file name will be
|
||||
// used for determining the namespace.
|
||||
optional string php_metadata_namespace = 44;
|
||||
|
||||
// Use this option to change the package of ruby generated classes. Default
|
||||
// is empty. When this option is not set, the package name will be used for
|
||||
// determining the ruby package.
|
||||
optional string ruby_package = 45;
|
||||
|
||||
// The parser stores options it doesn't recognize here.
|
||||
// See the documentation for the "Options" section above.
|
||||
repeated UninterpretedOption uninterpreted_option = 999;
|
||||
|
||||
// Clients can define custom options in extensions of this message.
|
||||
// See the documentation for the "Options" section above.
|
||||
extensions 1000 to max;
|
||||
|
||||
reserved 38;
|
||||
}
|
||||
|
||||
message MessageOptions {
|
||||
// Set true to use the old proto1 MessageSet wire format for extensions.
|
||||
// This is provided for backwards-compatibility with the MessageSet wire
|
||||
// format. You should not use this for any other reason: It's less
|
||||
// efficient, has fewer features, and is more complicated.
|
||||
//
|
||||
// The message must be defined exactly as follows:
|
||||
// message Foo {
|
||||
// option message_set_wire_format = true;
|
||||
// extensions 4 to max;
|
||||
// }
|
||||
// Note that the message cannot have any defined fields; MessageSets only
|
||||
// have extensions.
|
||||
//
|
||||
// All extensions of your type must be singular messages; e.g. they cannot
|
||||
// be int32s, enums, or repeated messages.
|
||||
//
|
||||
// Because this is an option, the above two restrictions are not enforced by
|
||||
// the protocol compiler.
|
||||
optional bool message_set_wire_format = 1 [default = false];
|
||||
|
||||
// Disables the generation of the standard "descriptor()" accessor, which can
|
||||
// conflict with a field of the same name. This is meant to make migration
|
||||
// from proto1 easier; new code should avoid fields named "descriptor".
|
||||
optional bool no_standard_descriptor_accessor = 2 [default = false];
|
||||
|
||||
// Is this message deprecated?
|
||||
// Depending on the target platform, this can emit Deprecated annotations
|
||||
// for the message, or it will be completely ignored; in the very least,
|
||||
// this is a formalization for deprecating messages.
|
||||
optional bool deprecated = 3 [default = false];
|
||||
|
||||
reserved 4, 5, 6;
|
||||
|
||||
// NOTE: Do not set the option in .proto files. Always use the maps syntax
|
||||
// instead. The option should only be implicitly set by the proto compiler
|
||||
// parser.
|
||||
//
|
||||
// Whether the message is an automatically generated map entry type for the
|
||||
// maps field.
|
||||
//
|
||||
// For maps fields:
|
||||
// map<KeyType, ValueType> map_field = 1;
|
||||
// The parsed descriptor looks like:
|
||||
// message MapFieldEntry {
|
||||
// option map_entry = true;
|
||||
// optional KeyType key = 1;
|
||||
// optional ValueType value = 2;
|
||||
// }
|
||||
// repeated MapFieldEntry map_field = 1;
|
||||
//
|
||||
// Implementations may choose not to generate the map_entry=true message, but
|
||||
// use a native map in the target language to hold the keys and values.
|
||||
// The reflection APIs in such implementations still need to work as
|
||||
// if the field is a repeated message field.
|
||||
optional bool map_entry = 7;
|
||||
|
||||
reserved 8; // javalite_serializable
|
||||
reserved 9; // javanano_as_lite
|
||||
|
||||
// Enable the legacy handling of JSON field name conflicts. This lowercases
|
||||
// and strips underscored from the fields before comparison in proto3 only.
|
||||
// The new behavior takes `json_name` into account and applies to proto2 as
|
||||
// well.
|
||||
//
|
||||
// This should only be used as a temporary measure against broken builds due
|
||||
// to the change in behavior for JSON field name conflicts.
|
||||
//
|
||||
// TODO(b/261750190) This is legacy behavior we plan to remove once downstream
|
||||
// teams have had time to migrate.
|
||||
optional bool deprecated_legacy_json_field_conflicts = 11 [deprecated = true];
|
||||
|
||||
// The parser stores options it doesn't recognize here. See above.
|
||||
repeated UninterpretedOption uninterpreted_option = 999;
|
||||
|
||||
// Clients can define custom options in extensions of this message. See above.
|
||||
extensions 1000 to max;
|
||||
}
|
||||
|
||||
message FieldOptions {
|
||||
// The ctype option instructs the C++ code generator to use a different
|
||||
// representation of the field than it normally would. See the specific
|
||||
// options below. This option is not yet implemented in the open source
|
||||
// release -- sorry, we'll try to include it in a future version!
|
||||
optional CType ctype = 1 [default = STRING];
|
||||
enum CType {
|
||||
// Default mode.
|
||||
STRING = 0;
|
||||
|
||||
CORD = 1;
|
||||
|
||||
STRING_PIECE = 2;
|
||||
}
|
||||
// The packed option can be enabled for repeated primitive fields to enable
|
||||
// a more efficient representation on the wire. Rather than repeatedly
|
||||
// writing the tag and type for each element, the entire array is encoded as
|
||||
// a single length-delimited blob. In proto3, only explicit setting it to
|
||||
// false will avoid using packed encoding.
|
||||
optional bool packed = 2;
|
||||
|
||||
// The jstype option determines the JavaScript type used for values of the
|
||||
// field. The option is permitted only for 64 bit integral and fixed types
|
||||
// (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
|
||||
// is represented as JavaScript string, which avoids loss of precision that
|
||||
// can happen when a large value is converted to a floating point JavaScript.
|
||||
// Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
|
||||
// use the JavaScript "number" type. The behavior of the default option
|
||||
// JS_NORMAL is implementation dependent.
|
||||
//
|
||||
// This option is an enum to permit additional types to be added, e.g.
|
||||
// goog.math.Integer.
|
||||
optional JSType jstype = 6 [default = JS_NORMAL];
|
||||
enum JSType {
|
||||
// Use the default type.
|
||||
JS_NORMAL = 0;
|
||||
|
||||
// Use JavaScript strings.
|
||||
JS_STRING = 1;
|
||||
|
||||
// Use JavaScript numbers.
|
||||
JS_NUMBER = 2;
|
||||
}
|
||||
|
||||
// Should this field be parsed lazily? Lazy applies only to message-type
|
||||
// fields. It means that when the outer message is initially parsed, the
|
||||
// inner message's contents will not be parsed but instead stored in encoded
|
||||
// form. The inner message will actually be parsed when it is first accessed.
|
||||
//
|
||||
// This is only a hint. Implementations are free to choose whether to use
|
||||
// eager or lazy parsing regardless of the value of this option. However,
|
||||
// setting this option true suggests that the protocol author believes that
|
||||
// using lazy parsing on this field is worth the additional bookkeeping
|
||||
// overhead typically needed to implement it.
|
||||
//
|
||||
// This option does not affect the public interface of any generated code;
|
||||
// all method signatures remain the same. Furthermore, thread-safety of the
|
||||
// interface is not affected by this option; const methods remain safe to
|
||||
// call from multiple threads concurrently, while non-const methods continue
|
||||
// to require exclusive access.
|
||||
//
|
||||
// Note that implementations may choose not to check required fields within
|
||||
// a lazy sub-message. That is, calling IsInitialized() on the outer message
|
||||
// may return true even if the inner message has missing required fields.
|
||||
// This is necessary because otherwise the inner message would have to be
|
||||
// parsed in order to perform the check, defeating the purpose of lazy
|
||||
// parsing. An implementation which chooses not to check required fields
|
||||
// must be consistent about it. That is, for any particular sub-message, the
|
||||
// implementation must either *always* check its required fields, or *never*
|
||||
// check its required fields, regardless of whether or not the message has
|
||||
// been parsed.
|
||||
//
|
||||
// As of May 2022, lazy verifies the contents of the byte stream during
|
||||
// parsing. An invalid byte stream will cause the overall parsing to fail.
|
||||
optional bool lazy = 5 [default = false];
|
||||
|
||||
// unverified_lazy does no correctness checks on the byte stream. This should
|
||||
// only be used where lazy with verification is prohibitive for performance
|
||||
// reasons.
|
||||
optional bool unverified_lazy = 15 [default = false];
|
||||
|
||||
// Is this field deprecated?
|
||||
// Depending on the target platform, this can emit Deprecated annotations
|
||||
// for accessors, or it will be completely ignored; in the very least, this
|
||||
// is a formalization for deprecating fields.
|
||||
optional bool deprecated = 3 [default = false];
|
||||
|
||||
// For Google-internal migration only. Do not use.
|
||||
optional bool weak = 10 [default = false];
|
||||
|
||||
// Indicate that the field value should not be printed out when using debug
|
||||
// formats, e.g. when the field contains sensitive credentials.
|
||||
optional bool debug_redact = 16 [default = false];
|
||||
|
||||
// If set to RETENTION_SOURCE, the option will be omitted from the binary.
|
||||
// Note: as of January 2023, support for this is in progress and does not yet
|
||||
// have an effect (b/264593489).
|
||||
enum OptionRetention {
|
||||
RETENTION_UNKNOWN = 0;
|
||||
RETENTION_RUNTIME = 1;
|
||||
RETENTION_SOURCE = 2;
|
||||
}
|
||||
|
||||
optional OptionRetention retention = 17;
|
||||
|
||||
// This indicates the types of entities that the field may apply to when used
|
||||
// as an option. If it is unset, then the field may be freely used as an
|
||||
// option on any kind of entity. Note: as of January 2023, support for this is
|
||||
// in progress and does not yet have an effect (b/264593489).
|
||||
enum OptionTargetType {
|
||||
TARGET_TYPE_UNKNOWN = 0;
|
||||
TARGET_TYPE_FILE = 1;
|
||||
TARGET_TYPE_EXTENSION_RANGE = 2;
|
||||
TARGET_TYPE_MESSAGE = 3;
|
||||
TARGET_TYPE_FIELD = 4;
|
||||
TARGET_TYPE_ONEOF = 5;
|
||||
TARGET_TYPE_ENUM = 6;
|
||||
TARGET_TYPE_ENUM_ENTRY = 7;
|
||||
TARGET_TYPE_SERVICE = 8;
|
||||
TARGET_TYPE_METHOD = 9;
|
||||
}
|
||||
|
||||
optional OptionTargetType target = 18;
|
||||
|
||||
// The parser stores options it doesn't recognize here. See above.
|
||||
repeated UninterpretedOption uninterpreted_option = 999;
|
||||
|
||||
// Clients can define custom options in extensions of this message. See above.
|
||||
extensions 1000 to max;
|
||||
|
||||
reserved 4; // removed jtype
|
||||
}
|
||||
|
||||
message OneofOptions {
|
||||
// The parser stores options it doesn't recognize here. See above.
|
||||
repeated UninterpretedOption uninterpreted_option = 999;
|
||||
|
||||
// Clients can define custom options in extensions of this message. See above.
|
||||
extensions 1000 to max;
|
||||
}
|
||||
|
||||
message EnumOptions {
|
||||
|
||||
// Set this option to true to allow mapping different tag names to the same
|
||||
// value.
|
||||
optional bool allow_alias = 2;
|
||||
|
||||
// Is this enum deprecated?
|
||||
// Depending on the target platform, this can emit Deprecated annotations
|
||||
// for the enum, or it will be completely ignored; in the very least, this
|
||||
// is a formalization for deprecating enums.
|
||||
optional bool deprecated = 3 [default = false];
|
||||
|
||||
reserved 5; // javanano_as_lite
|
||||
|
||||
// Enable the legacy handling of JSON field name conflicts. This lowercases
|
||||
// and strips underscored from the fields before comparison in proto3 only.
|
||||
// The new behavior takes `json_name` into account and applies to proto2 as
|
||||
// well.
|
||||
// TODO(b/261750190) Remove this legacy behavior once downstream teams have
|
||||
// had time to migrate.
|
||||
optional bool deprecated_legacy_json_field_conflicts = 6 [deprecated = true];
|
||||
|
||||
// The parser stores options it doesn't recognize here. See above.
|
||||
repeated UninterpretedOption uninterpreted_option = 999;
|
||||
|
||||
// Clients can define custom options in extensions of this message. See above.
|
||||
extensions 1000 to max;
|
||||
}
|
||||
|
||||
message EnumValueOptions {
|
||||
// Is this enum value deprecated?
|
||||
// Depending on the target platform, this can emit Deprecated annotations
|
||||
// for the enum value, or it will be completely ignored; in the very least,
|
||||
// this is a formalization for deprecating enum values.
|
||||
optional bool deprecated = 1 [default = false];
|
||||
|
||||
// The parser stores options it doesn't recognize here. See above.
|
||||
repeated UninterpretedOption uninterpreted_option = 999;
|
||||
|
||||
// Clients can define custom options in extensions of this message. See above.
|
||||
extensions 1000 to max;
|
||||
}
|
||||
|
||||
message ServiceOptions {
|
||||
|
||||
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
|
||||
// framework. We apologize for hoarding these numbers to ourselves, but
|
||||
// we were already using them long before we decided to release Protocol
|
||||
// Buffers.
|
||||
|
||||
// Is this service deprecated?
|
||||
// Depending on the target platform, this can emit Deprecated annotations
|
||||
// for the service, or it will be completely ignored; in the very least,
|
||||
// this is a formalization for deprecating services.
|
||||
optional bool deprecated = 33 [default = false];
|
||||
|
||||
// The parser stores options it doesn't recognize here. See above.
|
||||
repeated UninterpretedOption uninterpreted_option = 999;
|
||||
|
||||
// Clients can define custom options in extensions of this message. See above.
|
||||
extensions 1000 to max;
|
||||
}
|
||||
|
||||
message MethodOptions {
|
||||
|
||||
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
|
||||
// framework. We apologize for hoarding these numbers to ourselves, but
|
||||
// we were already using them long before we decided to release Protocol
|
||||
// Buffers.
|
||||
|
||||
// Is this method deprecated?
|
||||
// Depending on the target platform, this can emit Deprecated annotations
|
||||
// for the method, or it will be completely ignored; in the very least,
|
||||
// this is a formalization for deprecating methods.
|
||||
optional bool deprecated = 33 [default = false];
|
||||
|
||||
// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
|
||||
// or neither? HTTP based RPC implementation may choose GET verb for safe
|
||||
// methods, and PUT verb for idempotent methods instead of the default POST.
|
||||
enum IdempotencyLevel {
|
||||
IDEMPOTENCY_UNKNOWN = 0;
|
||||
NO_SIDE_EFFECTS = 1; // implies idempotent
|
||||
IDEMPOTENT = 2; // idempotent, but may have side effects
|
||||
}
|
||||
optional IdempotencyLevel idempotency_level = 34
|
||||
[default = IDEMPOTENCY_UNKNOWN];
|
||||
|
||||
// The parser stores options it doesn't recognize here. See above.
|
||||
repeated UninterpretedOption uninterpreted_option = 999;
|
||||
|
||||
// Clients can define custom options in extensions of this message. See above.
|
||||
extensions 1000 to max;
|
||||
}
|
||||
|
||||
// A message representing a option the parser does not recognize. This only
|
||||
// appears in options protos created by the compiler::Parser class.
|
||||
// DescriptorPool resolves these when building Descriptor objects. Therefore,
|
||||
// options protos in descriptor objects (e.g. returned by Descriptor::options(),
|
||||
// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
|
||||
// in them.
|
||||
message UninterpretedOption {
|
||||
// The name of the uninterpreted option. Each string represents a segment in
|
||||
// a dot-separated name. is_extension is true iff a segment represents an
|
||||
// extension (denoted with parentheses in options specs in .proto files).
|
||||
// E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents
|
||||
// "foo.(bar.baz).moo".
|
||||
message NamePart {
|
||||
required string name_part = 1;
|
||||
required bool is_extension = 2;
|
||||
}
|
||||
repeated NamePart name = 2;
|
||||
|
||||
// The value of the uninterpreted option, in whatever type the tokenizer
|
||||
// identified it as during parsing. Exactly one of these should be set.
|
||||
optional string identifier_value = 3;
|
||||
optional uint64 positive_int_value = 4;
|
||||
optional int64 negative_int_value = 5;
|
||||
optional double double_value = 6;
|
||||
optional bytes string_value = 7;
|
||||
optional string aggregate_value = 8;
|
||||
}
|
||||
|
||||
// ===================================================================
|
||||
// Optional source code info
|
||||
|
||||
// Encapsulates information about the original source file from which a
|
||||
// FileDescriptorProto was generated.
|
||||
message SourceCodeInfo {
|
||||
// A Location identifies a piece of source code in a .proto file which
|
||||
// corresponds to a particular definition. This information is intended
|
||||
// to be useful to IDEs, code indexers, documentation generators, and similar
|
||||
// tools.
|
||||
//
|
||||
// For example, say we have a file like:
|
||||
// message Foo {
|
||||
// optional string foo = 1;
|
||||
// }
|
||||
// Let's look at just the field definition:
|
||||
// optional string foo = 1;
|
||||
// ^ ^^ ^^ ^ ^^^
|
||||
// a bc de f ghi
|
||||
// We have the following locations:
|
||||
// span path represents
|
||||
// [a,i) [ 4, 0, 2, 0 ] The whole field definition.
|
||||
// [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
|
||||
// [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
|
||||
// [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
|
||||
// [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
|
||||
//
|
||||
// Notes:
|
||||
// - A location may refer to a repeated field itself (i.e. not to any
|
||||
// particular index within it). This is used whenever a set of elements are
|
||||
// logically enclosed in a single code segment. For example, an entire
|
||||
// extend block (possibly containing multiple extension definitions) will
|
||||
// have an outer location whose path refers to the "extensions" repeated
|
||||
// field without an index.
|
||||
// - Multiple locations may have the same path. This happens when a single
|
||||
// logical declaration is spread out across multiple places. The most
|
||||
// obvious example is the "extend" block again -- there may be multiple
|
||||
// extend blocks in the same scope, each of which will have the same path.
|
||||
// - A location's span is not always a subset of its parent's span. For
|
||||
// example, the "extendee" of an extension declaration appears at the
|
||||
// beginning of the "extend" block and is shared by all extensions within
|
||||
// the block.
|
||||
// - Just because a location's span is a subset of some other location's span
|
||||
// does not mean that it is a descendant. For example, a "group" defines
|
||||
// both a type and a field in a single declaration. Thus, the locations
|
||||
// corresponding to the type and field and their components will overlap.
|
||||
// - Code which tries to interpret locations should probably be designed to
|
||||
// ignore those that it doesn't understand, as more types of locations could
|
||||
// be recorded in the future.
|
||||
repeated Location location = 1;
|
||||
message Location {
|
||||
// Identifies which part of the FileDescriptorProto was defined at this
|
||||
// location.
|
||||
//
|
||||
// Each element is a field number or an index. They form a path from
|
||||
// the root FileDescriptorProto to the place where the definition occurs.
|
||||
// For example, this path:
|
||||
// [ 4, 3, 2, 7, 1 ]
|
||||
// refers to:
|
||||
// file.message_type(3) // 4, 3
|
||||
// .field(7) // 2, 7
|
||||
// .name() // 1
|
||||
// This is because FileDescriptorProto.message_type has field number 4:
|
||||
// repeated DescriptorProto message_type = 4;
|
||||
// and DescriptorProto.field has field number 2:
|
||||
// repeated FieldDescriptorProto field = 2;
|
||||
// and FieldDescriptorProto.name has field number 1:
|
||||
// optional string name = 1;
|
||||
//
|
||||
// Thus, the above path gives the location of a field name. If we removed
|
||||
// the last element:
|
||||
// [ 4, 3, 2, 7 ]
|
||||
// this path refers to the whole field declaration (from the beginning
|
||||
// of the label to the terminating semicolon).
|
||||
repeated int32 path = 1 [packed = true];
|
||||
|
||||
// Always has exactly three or four elements: start line, start column,
|
||||
// end line (optional, otherwise assumed same as start line), end column.
|
||||
// These are packed into a single field for efficiency. Note that line
|
||||
// and column numbers are zero-based -- typically you will want to add
|
||||
// 1 to each before displaying to a user.
|
||||
repeated int32 span = 2 [packed = true];
|
||||
|
||||
// If this SourceCodeInfo represents a complete declaration, these are any
|
||||
// comments appearing before and after the declaration which appear to be
|
||||
// attached to the declaration.
|
||||
//
|
||||
// A series of line comments appearing on consecutive lines, with no other
|
||||
// tokens appearing on those lines, will be treated as a single comment.
|
||||
//
|
||||
// leading_detached_comments will keep paragraphs of comments that appear
|
||||
// before (but not connected to) the current element. Each paragraph,
|
||||
// separated by empty lines, will be one comment element in the repeated
|
||||
// field.
|
||||
//
|
||||
// Only the comment content is provided; comment markers (e.g. //) are
|
||||
// stripped out. For block comments, leading whitespace and an asterisk
|
||||
// will be stripped from the beginning of each line other than the first.
|
||||
// Newlines are included in the output.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// optional int32 foo = 1; // Comment attached to foo.
|
||||
// // Comment attached to bar.
|
||||
// optional int32 bar = 2;
|
||||
//
|
||||
// optional string baz = 3;
|
||||
// // Comment attached to baz.
|
||||
// // Another line attached to baz.
|
||||
//
|
||||
// // Comment attached to moo.
|
||||
// //
|
||||
// // Another line attached to moo.
|
||||
// optional double moo = 4;
|
||||
//
|
||||
// // Detached comment for corge. This is not leading or trailing comments
|
||||
// // to moo or corge because there are blank lines separating it from
|
||||
// // both.
|
||||
//
|
||||
// // Detached comment for corge paragraph 2.
|
||||
//
|
||||
// optional string corge = 5;
|
||||
// /* Block comment attached
|
||||
// * to corge. Leading asterisks
|
||||
// * will be removed. */
|
||||
// /* Block comment attached to
|
||||
// * grault. */
|
||||
// optional int32 grault = 6;
|
||||
//
|
||||
// // ignored detached comments.
|
||||
optional string leading_comments = 3;
|
||||
optional string trailing_comments = 4;
|
||||
repeated string leading_detached_comments = 6;
|
||||
}
|
||||
}
|
||||
|
||||
// Describes the relationship between generated code and its original source
|
||||
// file. A GeneratedCodeInfo message is associated with only one generated
|
||||
// source file, but may contain references to different source .proto files.
|
||||
message GeneratedCodeInfo {
|
||||
// An Annotation connects some span of text in generated code to an element
|
||||
// of its generating .proto file.
|
||||
repeated Annotation annotation = 1;
|
||||
message Annotation {
|
||||
// Identifies the element in the original source .proto file. This field
|
||||
// is formatted the same as SourceCodeInfo.Location.path.
|
||||
repeated int32 path = 1 [packed = true];
|
||||
|
||||
// Identifies the filesystem path to the original source .proto.
|
||||
optional string source_file = 2;
|
||||
|
||||
// Identifies the starting offset in bytes in the generated code
|
||||
// that relates to the identified object.
|
||||
optional int32 begin = 3;
|
||||
|
||||
// Identifies the ending offset in bytes in the generated code that
|
||||
// relates to the identified object. The end offset should be one past
|
||||
// the last relevant byte (so the length of the text = end - begin).
|
||||
optional int32 end = 4;
|
||||
|
||||
// Represents the identified object's effect on the element in the original
|
||||
// .proto file.
|
||||
enum Semantic {
|
||||
// There is no effect or the effect is indescribable.
|
||||
NONE = 0;
|
||||
// The element is set or otherwise mutated.
|
||||
SET = 1;
|
||||
// An alias to the element is returned.
|
||||
ALIAS = 2;
|
||||
}
|
||||
optional Semantic semantic = 5;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
option cc_enable_arenas = true;
|
||||
option go_package = "google.golang.org/protobuf/types/known/durationpb";
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "DurationProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
|
||||
// A Duration represents a signed, fixed-length span of time represented
|
||||
// as a count of seconds and fractions of seconds at nanosecond
|
||||
// resolution. It is independent of any calendar and concepts like "day"
|
||||
// or "month". It is related to Timestamp in that the difference between
|
||||
// two Timestamp values is a Duration and it can be added or subtracted
|
||||
// from a Timestamp. Range is approximately +-10,000 years.
|
||||
//
|
||||
// # Examples
|
||||
//
|
||||
// Example 1: Compute Duration from two Timestamps in pseudo code.
|
||||
//
|
||||
// Timestamp start = ...;
|
||||
// Timestamp end = ...;
|
||||
// Duration duration = ...;
|
||||
//
|
||||
// duration.seconds = end.seconds - start.seconds;
|
||||
// duration.nanos = end.nanos - start.nanos;
|
||||
//
|
||||
// if (duration.seconds < 0 && duration.nanos > 0) {
|
||||
// duration.seconds += 1;
|
||||
// duration.nanos -= 1000000000;
|
||||
// } else if (duration.seconds > 0 && duration.nanos < 0) {
|
||||
// duration.seconds -= 1;
|
||||
// duration.nanos += 1000000000;
|
||||
// }
|
||||
//
|
||||
// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
|
||||
//
|
||||
// Timestamp start = ...;
|
||||
// Duration duration = ...;
|
||||
// Timestamp end = ...;
|
||||
//
|
||||
// end.seconds = start.seconds + duration.seconds;
|
||||
// end.nanos = start.nanos + duration.nanos;
|
||||
//
|
||||
// if (end.nanos < 0) {
|
||||
// end.seconds -= 1;
|
||||
// end.nanos += 1000000000;
|
||||
// } else if (end.nanos >= 1000000000) {
|
||||
// end.seconds += 1;
|
||||
// end.nanos -= 1000000000;
|
||||
// }
|
||||
//
|
||||
// Example 3: Compute Duration from datetime.timedelta in Python.
|
||||
//
|
||||
// td = datetime.timedelta(days=3, minutes=10)
|
||||
// duration = Duration()
|
||||
// duration.FromTimedelta(td)
|
||||
//
|
||||
// # JSON Mapping
|
||||
//
|
||||
// In JSON format, the Duration type is encoded as a string rather than an
|
||||
// object, where the string ends in the suffix "s" (indicating seconds) and
|
||||
// is preceded by the number of seconds, with nanoseconds expressed as
|
||||
// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
|
||||
// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
|
||||
// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
|
||||
// microsecond should be expressed in JSON format as "3.000001s".
|
||||
//
|
||||
message Duration {
|
||||
// Signed seconds of the span of time. Must be from -315,576,000,000
|
||||
// to +315,576,000,000 inclusive. Note: these bounds are computed from:
|
||||
// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
|
||||
int64 seconds = 1;
|
||||
|
||||
// Signed fractions of a second at nanosecond resolution of the span
|
||||
// of time. Durations less than one second are represented with a 0
|
||||
// `seconds` field and a positive or negative `nanos` field. For durations
|
||||
// of one second or more, a non-zero value for the `nanos` field must be
|
||||
// of the same sign as the `seconds` field. Must be from -999,999,999
|
||||
// to +999,999,999 inclusive.
|
||||
int32 nanos = 2;
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
option go_package = "google.golang.org/protobuf/types/known/emptypb";
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "EmptyProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
option cc_enable_arenas = true;
|
||||
|
||||
// A generic empty message that you can re-use to avoid defining duplicated
|
||||
// empty messages in your APIs. A typical example is to use it as the request
|
||||
// or the response type of an API method. For instance:
|
||||
//
|
||||
// service Foo {
|
||||
// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
|
||||
// }
|
||||
//
|
||||
message Empty {}
|
|
@ -0,0 +1,245 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "FieldMaskProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
option go_package = "google.golang.org/protobuf/types/known/fieldmaskpb";
|
||||
option cc_enable_arenas = true;
|
||||
|
||||
// `FieldMask` represents a set of symbolic field paths, for example:
|
||||
//
|
||||
// paths: "f.a"
|
||||
// paths: "f.b.d"
|
||||
//
|
||||
// Here `f` represents a field in some root message, `a` and `b`
|
||||
// fields in the message found in `f`, and `d` a field found in the
|
||||
// message in `f.b`.
|
||||
//
|
||||
// Field masks are used to specify a subset of fields that should be
|
||||
// returned by a get operation or modified by an update operation.
|
||||
// Field masks also have a custom JSON encoding (see below).
|
||||
//
|
||||
// # Field Masks in Projections
|
||||
//
|
||||
// When used in the context of a projection, a response message or
|
||||
// sub-message is filtered by the API to only contain those fields as
|
||||
// specified in the mask. For example, if the mask in the previous
|
||||
// example is applied to a response message as follows:
|
||||
//
|
||||
// f {
|
||||
// a : 22
|
||||
// b {
|
||||
// d : 1
|
||||
// x : 2
|
||||
// }
|
||||
// y : 13
|
||||
// }
|
||||
// z: 8
|
||||
//
|
||||
// The result will not contain specific values for fields x,y and z
|
||||
// (their value will be set to the default, and omitted in proto text
|
||||
// output):
|
||||
//
|
||||
//
|
||||
// f {
|
||||
// a : 22
|
||||
// b {
|
||||
// d : 1
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// A repeated field is not allowed except at the last position of a
|
||||
// paths string.
|
||||
//
|
||||
// If a FieldMask object is not present in a get operation, the
|
||||
// operation applies to all fields (as if a FieldMask of all fields
|
||||
// had been specified).
|
||||
//
|
||||
// Note that a field mask does not necessarily apply to the
|
||||
// top-level response message. In case of a REST get operation, the
|
||||
// field mask applies directly to the response, but in case of a REST
|
||||
// list operation, the mask instead applies to each individual message
|
||||
// in the returned resource list. In case of a REST custom method,
|
||||
// other definitions may be used. Where the mask applies will be
|
||||
// clearly documented together with its declaration in the API. In
|
||||
// any case, the effect on the returned resource/resources is required
|
||||
// behavior for APIs.
|
||||
//
|
||||
// # Field Masks in Update Operations
|
||||
//
|
||||
// A field mask in update operations specifies which fields of the
|
||||
// targeted resource are going to be updated. The API is required
|
||||
// to only change the values of the fields as specified in the mask
|
||||
// and leave the others untouched. If a resource is passed in to
|
||||
// describe the updated values, the API ignores the values of all
|
||||
// fields not covered by the mask.
|
||||
//
|
||||
// If a repeated field is specified for an update operation, new values will
|
||||
// be appended to the existing repeated field in the target resource. Note that
|
||||
// a repeated field is only allowed in the last position of a `paths` string.
|
||||
//
|
||||
// If a sub-message is specified in the last position of the field mask for an
|
||||
// update operation, then new value will be merged into the existing sub-message
|
||||
// in the target resource.
|
||||
//
|
||||
// For example, given the target message:
|
||||
//
|
||||
// f {
|
||||
// b {
|
||||
// d: 1
|
||||
// x: 2
|
||||
// }
|
||||
// c: [1]
|
||||
// }
|
||||
//
|
||||
// And an update message:
|
||||
//
|
||||
// f {
|
||||
// b {
|
||||
// d: 10
|
||||
// }
|
||||
// c: [2]
|
||||
// }
|
||||
//
|
||||
// then if the field mask is:
|
||||
//
|
||||
// paths: ["f.b", "f.c"]
|
||||
//
|
||||
// then the result will be:
|
||||
//
|
||||
// f {
|
||||
// b {
|
||||
// d: 10
|
||||
// x: 2
|
||||
// }
|
||||
// c: [1, 2]
|
||||
// }
|
||||
//
|
||||
// An implementation may provide options to override this default behavior for
|
||||
// repeated and message fields.
|
||||
//
|
||||
// In order to reset a field's value to the default, the field must
|
||||
// be in the mask and set to the default value in the provided resource.
|
||||
// Hence, in order to reset all fields of a resource, provide a default
|
||||
// instance of the resource and set all fields in the mask, or do
|
||||
// not provide a mask as described below.
|
||||
//
|
||||
// If a field mask is not present on update, the operation applies to
|
||||
// all fields (as if a field mask of all fields has been specified).
|
||||
// Note that in the presence of schema evolution, this may mean that
|
||||
// fields the client does not know and has therefore not filled into
|
||||
// the request will be reset to their default. If this is unwanted
|
||||
// behavior, a specific service may require a client to always specify
|
||||
// a field mask, producing an error if not.
|
||||
//
|
||||
// As with get operations, the location of the resource which
|
||||
// describes the updated values in the request message depends on the
|
||||
// operation kind. In any case, the effect of the field mask is
|
||||
// required to be honored by the API.
|
||||
//
|
||||
// ## Considerations for HTTP REST
|
||||
//
|
||||
// The HTTP kind of an update operation which uses a field mask must
|
||||
// be set to PATCH instead of PUT in order to satisfy HTTP semantics
|
||||
// (PUT must only be used for full updates).
|
||||
//
|
||||
// # JSON Encoding of Field Masks
|
||||
//
|
||||
// In JSON, a field mask is encoded as a single string where paths are
|
||||
// separated by a comma. Fields name in each path are converted
|
||||
// to/from lower-camel naming conventions.
|
||||
//
|
||||
// As an example, consider the following message declarations:
|
||||
//
|
||||
// message Profile {
|
||||
// User user = 1;
|
||||
// Photo photo = 2;
|
||||
// }
|
||||
// message User {
|
||||
// string display_name = 1;
|
||||
// string address = 2;
|
||||
// }
|
||||
//
|
||||
// In proto a field mask for `Profile` may look as such:
|
||||
//
|
||||
// mask {
|
||||
// paths: "user.display_name"
|
||||
// paths: "photo"
|
||||
// }
|
||||
//
|
||||
// In JSON, the same mask is represented as below:
|
||||
//
|
||||
// {
|
||||
// mask: "user.displayName,photo"
|
||||
// }
|
||||
//
|
||||
// # Field Masks and Oneof Fields
|
||||
//
|
||||
// Field masks treat fields in oneofs just as regular fields. Consider the
|
||||
// following message:
|
||||
//
|
||||
// message SampleMessage {
|
||||
// oneof test_oneof {
|
||||
// string name = 4;
|
||||
// SubMessage sub_message = 9;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// The field mask can be:
|
||||
//
|
||||
// mask {
|
||||
// paths: "name"
|
||||
// }
|
||||
//
|
||||
// Or:
|
||||
//
|
||||
// mask {
|
||||
// paths: "sub_message"
|
||||
// }
|
||||
//
|
||||
// Note that oneof type names ("test_oneof" in this case) cannot be used in
|
||||
// paths.
|
||||
//
|
||||
// ## Field Mask Verification
|
||||
//
|
||||
// The implementation of any API method which has a FieldMask type field in the
|
||||
// request should verify the included field paths, and return an
|
||||
// `INVALID_ARGUMENT` error if any path is unmappable.
|
||||
message FieldMask {
|
||||
// The set of field mask paths.
|
||||
repeated string paths = 1;
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "SourceContextProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
option go_package = "google.golang.org/protobuf/types/known/sourcecontextpb";
|
||||
|
||||
// `SourceContext` represents information about the source of a
|
||||
// protobuf element, like the file in which it is defined.
|
||||
message SourceContext {
|
||||
// The path-qualified name of the .proto file that contained the associated
|
||||
// protobuf element. For example: `"google/protobuf/source_context.proto"`.
|
||||
string file_name = 1;
|
||||
}
|
|
@ -0,0 +1,95 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
option cc_enable_arenas = true;
|
||||
option go_package = "google.golang.org/protobuf/types/known/structpb";
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "StructProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
|
||||
// `Struct` represents a structured data value, consisting of fields
|
||||
// which map to dynamically typed values. In some languages, `Struct`
|
||||
// might be supported by a native representation. For example, in
|
||||
// scripting languages like JS a struct is represented as an
|
||||
// object. The details of that representation are described together
|
||||
// with the proto support for the language.
|
||||
//
|
||||
// The JSON representation for `Struct` is JSON object.
|
||||
message Struct {
|
||||
// Unordered map of dynamically typed values.
|
||||
map<string, Value> fields = 1;
|
||||
}
|
||||
|
||||
// `Value` represents a dynamically typed value which can be either
|
||||
// null, a number, a string, a boolean, a recursive struct value, or a
|
||||
// list of values. A producer of value is expected to set one of these
|
||||
// variants. Absence of any variant indicates an error.
|
||||
//
|
||||
// The JSON representation for `Value` is JSON value.
|
||||
message Value {
|
||||
// The kind of value.
|
||||
oneof kind {
|
||||
// Represents a null value.
|
||||
NullValue null_value = 1;
|
||||
// Represents a double value.
|
||||
double number_value = 2;
|
||||
// Represents a string value.
|
||||
string string_value = 3;
|
||||
// Represents a boolean value.
|
||||
bool bool_value = 4;
|
||||
// Represents a structured value.
|
||||
Struct struct_value = 5;
|
||||
// Represents a repeated `Value`.
|
||||
ListValue list_value = 6;
|
||||
}
|
||||
}
|
||||
|
||||
// `NullValue` is a singleton enumeration to represent the null value for the
|
||||
// `Value` type union.
|
||||
//
|
||||
// The JSON representation for `NullValue` is JSON `null`.
|
||||
enum NullValue {
|
||||
// Null value.
|
||||
NULL_VALUE = 0;
|
||||
}
|
||||
|
||||
// `ListValue` is a wrapper around a repeated field of values.
|
||||
//
|
||||
// The JSON representation for `ListValue` is JSON array.
|
||||
message ListValue {
|
||||
// Repeated field of dynamically typed values.
|
||||
repeated Value values = 1;
|
||||
}
|
|
@ -0,0 +1,144 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
option cc_enable_arenas = true;
|
||||
option go_package = "google.golang.org/protobuf/types/known/timestamppb";
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "TimestampProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
|
||||
// A Timestamp represents a point in time independent of any time zone or local
|
||||
// calendar, encoded as a count of seconds and fractions of seconds at
|
||||
// nanosecond resolution. The count is relative to an epoch at UTC midnight on
|
||||
// January 1, 1970, in the proleptic Gregorian calendar which extends the
|
||||
// Gregorian calendar backwards to year one.
|
||||
//
|
||||
// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
|
||||
// second table is needed for interpretation, using a [24-hour linear
|
||||
// smear](https://developers.google.com/time/smear).
|
||||
//
|
||||
// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
|
||||
// restricting to that range, we ensure that we can convert to and from [RFC
|
||||
// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
|
||||
//
|
||||
// # Examples
|
||||
//
|
||||
// Example 1: Compute Timestamp from POSIX `time()`.
|
||||
//
|
||||
// Timestamp timestamp;
|
||||
// timestamp.set_seconds(time(NULL));
|
||||
// timestamp.set_nanos(0);
|
||||
//
|
||||
// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
|
||||
//
|
||||
// struct timeval tv;
|
||||
// gettimeofday(&tv, NULL);
|
||||
//
|
||||
// Timestamp timestamp;
|
||||
// timestamp.set_seconds(tv.tv_sec);
|
||||
// timestamp.set_nanos(tv.tv_usec * 1000);
|
||||
//
|
||||
// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
|
||||
//
|
||||
// FILETIME ft;
|
||||
// GetSystemTimeAsFileTime(&ft);
|
||||
// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
|
||||
//
|
||||
// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
|
||||
// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
|
||||
// Timestamp timestamp;
|
||||
// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
|
||||
// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
|
||||
//
|
||||
// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
|
||||
//
|
||||
// long millis = System.currentTimeMillis();
|
||||
//
|
||||
// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
|
||||
// .setNanos((int) ((millis % 1000) * 1000000)).build();
|
||||
//
|
||||
// Example 5: Compute Timestamp from Java `Instant.now()`.
|
||||
//
|
||||
// Instant now = Instant.now();
|
||||
//
|
||||
// Timestamp timestamp =
|
||||
// Timestamp.newBuilder().setSeconds(now.getEpochSecond())
|
||||
// .setNanos(now.getNano()).build();
|
||||
//
|
||||
// Example 6: Compute Timestamp from current time in Python.
|
||||
//
|
||||
// timestamp = Timestamp()
|
||||
// timestamp.GetCurrentTime()
|
||||
//
|
||||
// # JSON Mapping
|
||||
//
|
||||
// In JSON format, the Timestamp type is encoded as a string in the
|
||||
// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
|
||||
// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
|
||||
// where {year} is always expressed using four digits while {month}, {day},
|
||||
// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
|
||||
// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
|
||||
// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
|
||||
// is required. A proto3 JSON serializer should always use UTC (as indicated by
|
||||
// "Z") when printing the Timestamp type and a proto3 JSON parser should be
|
||||
// able to accept both UTC and other timezones (as indicated by an offset).
|
||||
//
|
||||
// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
|
||||
// 01:30 UTC on January 15, 2017.
|
||||
//
|
||||
// In JavaScript, one can convert a Date object to this format using the
|
||||
// standard
|
||||
// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
|
||||
// method. In Python, a standard `datetime.datetime` object can be converted
|
||||
// to this format using
|
||||
// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
|
||||
// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
|
||||
// the Joda Time's [`ISODateTimeFormat.dateTime()`](
|
||||
// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
|
||||
// ) to obtain a formatter capable of generating timestamps in this format.
|
||||
//
|
||||
message Timestamp {
|
||||
// Represents seconds of UTC time since Unix epoch
|
||||
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
|
||||
// 9999-12-31T23:59:59Z inclusive.
|
||||
int64 seconds = 1;
|
||||
|
||||
// Non-negative fractions of a second at nanosecond resolution. Negative
|
||||
// second values with fractions must still have non-negative nanos values
|
||||
// that count forward in time. Must be from 0 to 999,999,999
|
||||
// inclusive.
|
||||
int32 nanos = 2;
|
||||
}
|
|
@ -0,0 +1,187 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
import "google/protobuf/any.proto";
|
||||
import "google/protobuf/source_context.proto";
|
||||
|
||||
option cc_enable_arenas = true;
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "TypeProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
option go_package = "google.golang.org/protobuf/types/known/typepb";
|
||||
|
||||
// A protocol buffer message type.
|
||||
message Type {
|
||||
// The fully qualified message name.
|
||||
string name = 1;
|
||||
// The list of fields.
|
||||
repeated Field fields = 2;
|
||||
// The list of types appearing in `oneof` definitions in this type.
|
||||
repeated string oneofs = 3;
|
||||
// The protocol buffer options.
|
||||
repeated Option options = 4;
|
||||
// The source context.
|
||||
SourceContext source_context = 5;
|
||||
// The source syntax.
|
||||
Syntax syntax = 6;
|
||||
}
|
||||
|
||||
// A single field of a message type.
|
||||
message Field {
|
||||
// Basic field types.
|
||||
enum Kind {
|
||||
// Field type unknown.
|
||||
TYPE_UNKNOWN = 0;
|
||||
// Field type double.
|
||||
TYPE_DOUBLE = 1;
|
||||
// Field type float.
|
||||
TYPE_FLOAT = 2;
|
||||
// Field type int64.
|
||||
TYPE_INT64 = 3;
|
||||
// Field type uint64.
|
||||
TYPE_UINT64 = 4;
|
||||
// Field type int32.
|
||||
TYPE_INT32 = 5;
|
||||
// Field type fixed64.
|
||||
TYPE_FIXED64 = 6;
|
||||
// Field type fixed32.
|
||||
TYPE_FIXED32 = 7;
|
||||
// Field type bool.
|
||||
TYPE_BOOL = 8;
|
||||
// Field type string.
|
||||
TYPE_STRING = 9;
|
||||
// Field type group. Proto2 syntax only, and deprecated.
|
||||
TYPE_GROUP = 10;
|
||||
// Field type message.
|
||||
TYPE_MESSAGE = 11;
|
||||
// Field type bytes.
|
||||
TYPE_BYTES = 12;
|
||||
// Field type uint32.
|
||||
TYPE_UINT32 = 13;
|
||||
// Field type enum.
|
||||
TYPE_ENUM = 14;
|
||||
// Field type sfixed32.
|
||||
TYPE_SFIXED32 = 15;
|
||||
// Field type sfixed64.
|
||||
TYPE_SFIXED64 = 16;
|
||||
// Field type sint32.
|
||||
TYPE_SINT32 = 17;
|
||||
// Field type sint64.
|
||||
TYPE_SINT64 = 18;
|
||||
}
|
||||
|
||||
// Whether a field is optional, required, or repeated.
|
||||
enum Cardinality {
|
||||
// For fields with unknown cardinality.
|
||||
CARDINALITY_UNKNOWN = 0;
|
||||
// For optional fields.
|
||||
CARDINALITY_OPTIONAL = 1;
|
||||
// For required fields. Proto2 syntax only.
|
||||
CARDINALITY_REQUIRED = 2;
|
||||
// For repeated fields.
|
||||
CARDINALITY_REPEATED = 3;
|
||||
}
|
||||
|
||||
// The field type.
|
||||
Kind kind = 1;
|
||||
// The field cardinality.
|
||||
Cardinality cardinality = 2;
|
||||
// The field number.
|
||||
int32 number = 3;
|
||||
// The field name.
|
||||
string name = 4;
|
||||
// The field type URL, without the scheme, for message or enumeration
|
||||
// types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
|
||||
string type_url = 6;
|
||||
// The index of the field type in `Type.oneofs`, for message or enumeration
|
||||
// types. The first type has index 1; zero means the type is not in the list.
|
||||
int32 oneof_index = 7;
|
||||
// Whether to use alternative packed wire representation.
|
||||
bool packed = 8;
|
||||
// The protocol buffer options.
|
||||
repeated Option options = 9;
|
||||
// The field JSON name.
|
||||
string json_name = 10;
|
||||
// The string value of the default value of this field. Proto2 syntax only.
|
||||
string default_value = 11;
|
||||
}
|
||||
|
||||
// Enum type definition.
|
||||
message Enum {
|
||||
// Enum type name.
|
||||
string name = 1;
|
||||
// Enum value definitions.
|
||||
repeated EnumValue enumvalue = 2;
|
||||
// Protocol buffer options.
|
||||
repeated Option options = 3;
|
||||
// The source context.
|
||||
SourceContext source_context = 4;
|
||||
// The source syntax.
|
||||
Syntax syntax = 5;
|
||||
}
|
||||
|
||||
// Enum value definition.
|
||||
message EnumValue {
|
||||
// Enum value name.
|
||||
string name = 1;
|
||||
// Enum value number.
|
||||
int32 number = 2;
|
||||
// Protocol buffer options.
|
||||
repeated Option options = 3;
|
||||
}
|
||||
|
||||
// A protocol buffer option, which can be attached to a message, field,
|
||||
// enumeration, etc.
|
||||
message Option {
|
||||
// The option's name. For protobuf built-in options (options defined in
|
||||
// descriptor.proto), this is the short name. For example, `"map_entry"`.
|
||||
// For custom options, it should be the fully-qualified name. For example,
|
||||
// `"google.api.http"`.
|
||||
string name = 1;
|
||||
// The option's value packed in an Any message. If the value is a primitive,
|
||||
// the corresponding wrapper type defined in google/protobuf/wrappers.proto
|
||||
// should be used. If the value is an enum, it should be stored as an int32
|
||||
// value using the google.protobuf.Int32Value type.
|
||||
Any value = 2;
|
||||
}
|
||||
|
||||
// The syntax in which a protocol buffer element is defined.
|
||||
enum Syntax {
|
||||
// Syntax `proto2`.
|
||||
SYNTAX_PROTO2 = 0;
|
||||
// Syntax `proto3`.
|
||||
SYNTAX_PROTO3 = 1;
|
||||
}
|
|
@ -0,0 +1,123 @@
|
|||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// Wrappers for primitive (non-message) types. These types are useful
|
||||
// for embedding primitives in the `google.protobuf.Any` type and for places
|
||||
// where we need to distinguish between the absence of a primitive
|
||||
// typed field and its default value.
|
||||
//
|
||||
// These wrappers have no meaningful use within repeated fields as they lack
|
||||
// the ability to detect presence on individual elements.
|
||||
// These wrappers have no meaningful use within a map or a oneof since
|
||||
// individual entries of a map or fields of a oneof can already detect presence.
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package google.protobuf;
|
||||
|
||||
option cc_enable_arenas = true;
|
||||
option go_package = "google.golang.org/protobuf/types/known/wrapperspb";
|
||||
option java_package = "com.google.protobuf";
|
||||
option java_outer_classname = "WrappersProto";
|
||||
option java_multiple_files = true;
|
||||
option objc_class_prefix = "GPB";
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||
|
||||
// Wrapper message for `double`.
|
||||
//
|
||||
// The JSON representation for `DoubleValue` is JSON number.
|
||||
message DoubleValue {
|
||||
// The double value.
|
||||
double value = 1;
|
||||
}
|
||||
|
||||
// Wrapper message for `float`.
|
||||
//
|
||||
// The JSON representation for `FloatValue` is JSON number.
|
||||
message FloatValue {
|
||||
// The float value.
|
||||
float value = 1;
|
||||
}
|
||||
|
||||
// Wrapper message for `int64`.
|
||||
//
|
||||
// The JSON representation for `Int64Value` is JSON string.
|
||||
message Int64Value {
|
||||
// The int64 value.
|
||||
int64 value = 1;
|
||||
}
|
||||
|
||||
// Wrapper message for `uint64`.
|
||||
//
|
||||
// The JSON representation for `UInt64Value` is JSON string.
|
||||
message UInt64Value {
|
||||
// The uint64 value.
|
||||
uint64 value = 1;
|
||||
}
|
||||
|
||||
// Wrapper message for `int32`.
|
||||
//
|
||||
// The JSON representation for `Int32Value` is JSON number.
|
||||
message Int32Value {
|
||||
// The int32 value.
|
||||
int32 value = 1;
|
||||
}
|
||||
|
||||
// Wrapper message for `uint32`.
|
||||
//
|
||||
// The JSON representation for `UInt32Value` is JSON number.
|
||||
message UInt32Value {
|
||||
// The uint32 value.
|
||||
uint32 value = 1;
|
||||
}
|
||||
|
||||
// Wrapper message for `bool`.
|
||||
//
|
||||
// The JSON representation for `BoolValue` is JSON `true` and `false`.
|
||||
message BoolValue {
|
||||
// The bool value.
|
||||
bool value = 1;
|
||||
}
|
||||
|
||||
// Wrapper message for `string`.
|
||||
//
|
||||
// The JSON representation for `StringValue` is JSON string.
|
||||
message StringValue {
|
||||
// The string value.
|
||||
string value = 1;
|
||||
}
|
||||
|
||||
// Wrapper message for `bytes`.
|
||||
//
|
||||
// The JSON representation for `BytesValue` is JSON string.
|
||||
message BytesValue {
|
||||
// The bytes value.
|
||||
bytes value = 1;
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
Protocol Buffers - Google's data interchange format
|
||||
Copyright 2008 Google Inc.
|
||||
https://developers.google.com/protocol-buffers/
|
||||
This package contains a precompiled binary version of the protocol buffer
|
||||
compiler (protoc). This binary is intended for users who want to use Protocol
|
||||
Buffers in languages other than C++ but do not want to compile protoc
|
||||
themselves. To install, simply place this binary somewhere in your PATH.
|
||||
If you intend to use the included well known types then don't forget to
|
||||
copy the contents of the 'include' directory somewhere as well, for example
|
||||
into '/usr/local/include/'.
|
||||
Please refer to our official github site for more installation instructions:
|
||||
https://github.com/protocolbuffers/protobuf
|
|
@ -0,0 +1,63 @@
|
|||
syntax = "proto3";
|
||||
|
||||
package graphicData;
|
||||
|
||||
message RtssGraphicStorage {
|
||||
Canvas canvas = 1;
|
||||
repeated Link links = 2;
|
||||
}
|
||||
|
||||
message Canvas {
|
||||
// 画布宽
|
||||
int32 width = 1;
|
||||
// 画布高
|
||||
int32 height = 2;
|
||||
// 背景色
|
||||
string backgroundColor = 3;
|
||||
// 视口变换
|
||||
Transform viewportTransform = 4;
|
||||
}
|
||||
|
||||
message Point {
|
||||
// x坐标
|
||||
float x = 1;
|
||||
// y坐标
|
||||
float y = 2;
|
||||
}
|
||||
|
||||
//变换
|
||||
message Transform {
|
||||
// 位移
|
||||
Point position = 1;
|
||||
// 缩放
|
||||
Point scale = 2;
|
||||
// 旋转弧度
|
||||
float rotation = 3;
|
||||
// 歪斜
|
||||
Point skew = 4;
|
||||
}
|
||||
|
||||
//子元素变换
|
||||
message ChildTransform {
|
||||
// 子元素名称
|
||||
string name = 1;
|
||||
// 子元素变换
|
||||
Transform transform = 2;
|
||||
}
|
||||
// 公共属性
|
||||
message CommonInfo {
|
||||
string id = 1;
|
||||
string graphicType = 2;
|
||||
Transform transform = 3;
|
||||
repeated ChildTransform childTransforms = 4;
|
||||
}
|
||||
|
||||
message Link {
|
||||
CommonInfo common = 1;
|
||||
string code = 2;
|
||||
bool curve = 3; // 是否曲线
|
||||
int32 segmentsCount = 4; // 曲线分段数
|
||||
int32 lineWidth = 5; // 线宽
|
||||
string lineColor = 6; // 线色
|
||||
repeated Point points = 7; // 点坐标列表
|
||||
}
|
|
@ -0,0 +1,109 @@
|
|||
import * as pb_1 from 'google-protobuf';
|
||||
import { IPointData } from 'pixi.js';
|
||||
import { ILinkData } from 'src/graphics/link/Link';
|
||||
import { ChildTransform, GraphicTransform } from 'src/jlgraphic';
|
||||
import { toStorageTransform } from '..';
|
||||
import { graphicData } from '../protos/draw_data_storage';
|
||||
|
||||
export class LinkData implements ILinkData {
|
||||
data: graphicData.Link;
|
||||
constructor(data?: graphicData.Link) {
|
||||
if (data) {
|
||||
this.data = data;
|
||||
} else {
|
||||
this.data = new graphicData.Link({
|
||||
common: new graphicData.CommonInfo(),
|
||||
});
|
||||
}
|
||||
}
|
||||
get code(): string {
|
||||
return this.data.code;
|
||||
}
|
||||
set code(v: string) {
|
||||
this.data.code = v;
|
||||
}
|
||||
get curve(): boolean {
|
||||
return this.data.curve;
|
||||
}
|
||||
set curve(v: boolean) {
|
||||
this.data.curve = v;
|
||||
}
|
||||
get segmentsCount(): number {
|
||||
return this.data.segmentsCount;
|
||||
}
|
||||
set segmentsCount(v: number) {
|
||||
this.data.segmentsCount = v;
|
||||
}
|
||||
get points(): IPointData[] {
|
||||
return this.data.points;
|
||||
}
|
||||
set points(points: IPointData[]) {
|
||||
this.data.points = points.map(
|
||||
(p) => new graphicData.Point({ x: p.x, y: p.y })
|
||||
);
|
||||
}
|
||||
get lineWidth(): number {
|
||||
return this.data.lineWidth;
|
||||
}
|
||||
set lineWidth(v: number) {
|
||||
this.data.lineWidth = v;
|
||||
}
|
||||
get lineColor(): string {
|
||||
return this.data.lineColor;
|
||||
}
|
||||
set lineColor(v: string) {
|
||||
this.data.lineColor = v;
|
||||
}
|
||||
clone(): LinkData {
|
||||
return new LinkData(this.data.cloneMessage());
|
||||
}
|
||||
copyFrom(data: LinkData): void {
|
||||
pb_1.Message.copyInto(data.data, this.data);
|
||||
}
|
||||
eq(other: LinkData): boolean {
|
||||
return pb_1.Message.equals(this.data, other.data);
|
||||
}
|
||||
get id(): string {
|
||||
return this.data.common.id;
|
||||
}
|
||||
set id(v: string) {
|
||||
this.data.common.id = v;
|
||||
}
|
||||
get graphicType(): string {
|
||||
return this.data.common.graphicType;
|
||||
}
|
||||
set graphicType(v: string) {
|
||||
this.data.common.graphicType = v;
|
||||
}
|
||||
get transform(): GraphicTransform {
|
||||
return GraphicTransform.from(this.data.common.transform);
|
||||
}
|
||||
set transform(v: GraphicTransform) {
|
||||
this.data.common.transform = toStorageTransform(v);
|
||||
}
|
||||
get childTransforms(): ChildTransform[] | undefined {
|
||||
const cts: ChildTransform[] = [];
|
||||
if (this.data.common.childTransforms) {
|
||||
this.data.common.childTransforms.forEach((ct) => {
|
||||
cts.push(ChildTransform.from(ct));
|
||||
});
|
||||
}
|
||||
return cts;
|
||||
}
|
||||
set childTransforms(v: ChildTransform[] | undefined) {
|
||||
if (v) {
|
||||
const cts: graphicData.ChildTransform[] = [];
|
||||
v.forEach((ct) =>
|
||||
cts.push(
|
||||
new graphicData.ChildTransform({
|
||||
...ct,
|
||||
transform: toStorageTransform(ct.transform),
|
||||
})
|
||||
)
|
||||
);
|
||||
this.data.common.childTransforms = cts;
|
||||
} else {
|
||||
this.data.common.childTransforms = [];
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
import { fromUint8Array, toUint8Array } from 'js-base64';
|
||||
import { IPointData, Point } from 'pixi.js';
|
||||
import { Link } from 'src/graphics/link/Link';
|
||||
import { LinkDraw } from 'src/graphics/link/LinkDrawAssistant';
|
||||
import {
|
||||
CombinationKey,
|
||||
GraphicApp,
|
||||
GraphicData,
|
||||
GraphicTransform,
|
||||
JlDrawApp,
|
||||
KeyListener,
|
||||
} from 'src/jlgraphic';
|
||||
import { LinkData } from './graphics/LinkInteraction';
|
||||
import { graphicData } from './protos/draw_data_storage';
|
||||
|
||||
export function fromStoragePoint(p: graphicData.Point): Point {
|
||||
return new Point(p.x, p.y);
|
||||
}
|
||||
|
||||
export function toStoragePoint(p: IPointData): graphicData.Point {
|
||||
return new graphicData.Point({ x: p.x, y: p.y });
|
||||
}
|
||||
|
||||
export function fromStorageTransfrom(
|
||||
transfrom: graphicData.Transform
|
||||
): GraphicTransform {
|
||||
return new GraphicTransform(
|
||||
fromStoragePoint(transfrom.position),
|
||||
fromStoragePoint(transfrom.scale),
|
||||
transfrom.rotation,
|
||||
fromStoragePoint(transfrom.skew)
|
||||
);
|
||||
}
|
||||
|
||||
export function toStorageTransform(
|
||||
transform: GraphicTransform
|
||||
): graphicData.Transform {
|
||||
return new graphicData.Transform({
|
||||
position: toStoragePoint(transform.position),
|
||||
scale: toStoragePoint(transform.scale),
|
||||
rotation: transform.rotation,
|
||||
skew: toStoragePoint(transform.skew),
|
||||
});
|
||||
}
|
||||
|
||||
export function initDrawApp(app: JlDrawApp) {
|
||||
app.setOptions({
|
||||
drawAssistants: [
|
||||
new LinkDraw(app, {
|
||||
newData: () => {
|
||||
return new LinkData();
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
app.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'KeyL',
|
||||
onPress: () => {
|
||||
app.interactionPlugin(Link.Type).resume();
|
||||
},
|
||||
})
|
||||
);
|
||||
app.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'KeyS',
|
||||
global: true,
|
||||
combinations: [CombinationKey.Ctrl],
|
||||
onPress: () => {
|
||||
saveDrawDatas(app);
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const StorageKey = 'graphic-storage';
|
||||
export function saveDrawDatas(app: JlDrawApp) {
|
||||
const storage = new graphicData.RtssGraphicStorage();
|
||||
const canvasData = app.canvas.saveData();
|
||||
storage.canvas = new graphicData.Canvas({
|
||||
...canvasData,
|
||||
viewportTransform: toStorageTransform(canvasData.viewportTransform),
|
||||
});
|
||||
const graphics = app.queryStore.getAllGraphics();
|
||||
graphics.forEach((g) => {
|
||||
if (Link.Type === g.type) {
|
||||
const linkData = (g as Link).saveData();
|
||||
storage.links.push((linkData as LinkData).data);
|
||||
}
|
||||
});
|
||||
const base64 = fromUint8Array(storage.serialize());
|
||||
console.log('保存数据', storage);
|
||||
localStorage.setItem(StorageKey, base64);
|
||||
}
|
||||
|
||||
export function loadDrawDatas(app: GraphicApp) {
|
||||
// localStorage.removeItem(StorageKey);
|
||||
const base64 = localStorage.getItem(StorageKey);
|
||||
if (base64) {
|
||||
const storage = graphicData.RtssGraphicStorage.deserialize(
|
||||
toUint8Array(base64)
|
||||
);
|
||||
console.log('加载数据', storage);
|
||||
app.updateCanvas(storage.canvas);
|
||||
const datas: GraphicData[] = [];
|
||||
storage.links.forEach((link) => {
|
||||
datas.push(new LinkData(link));
|
||||
});
|
||||
app.loadGraphic(datas);
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,93 @@
|
|||
import { Color, Graphics, IPointData } from 'pixi.js';
|
||||
import {
|
||||
GraphicData,
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
convertToBezierPoints,
|
||||
} from 'src/jlgraphic';
|
||||
|
||||
export interface ILinkData extends GraphicData {
|
||||
get code(): string; // 编号
|
||||
set code(v: string);
|
||||
get curve(): boolean; // 是否曲线
|
||||
set curve(v: boolean);
|
||||
get segmentsCount(): number; // 曲线分段数
|
||||
set segmentsCount(v: number);
|
||||
get points(): IPointData[]; // 线坐标点
|
||||
set points(points: IPointData[]);
|
||||
get lineWidth(): number; // 线宽
|
||||
set lineWidth(v: number);
|
||||
get lineColor(): string; // 线色
|
||||
set lineColor(v: string);
|
||||
clone(): ILinkData;
|
||||
copyFrom(data: ILinkData): void;
|
||||
eq(other: ILinkData): boolean;
|
||||
}
|
||||
|
||||
export class Link extends JlGraphic {
|
||||
static Type = 'Link';
|
||||
lineGraphic: Graphics;
|
||||
constructor() {
|
||||
super(Link.Type);
|
||||
this.lineGraphic = new Graphics();
|
||||
this.addChild(this.lineGraphic);
|
||||
}
|
||||
get datas(): ILinkData {
|
||||
return this.getDatas<ILinkData>();
|
||||
}
|
||||
doRepaint(): void {
|
||||
if (this.datas.points.length < 2) {
|
||||
throw new Error('Link坐标数据异常');
|
||||
}
|
||||
this.lineGraphic.clear();
|
||||
this.lineGraphic.lineStyle(
|
||||
this.datas.lineWidth,
|
||||
new Color(this.datas.lineColor)
|
||||
);
|
||||
if (this.datas.curve) {
|
||||
// 曲线
|
||||
const bps = convertToBezierPoints(this.datas.points);
|
||||
bps.forEach((bp) => {
|
||||
this.lineGraphic.drawBezierCurve(
|
||||
bp.p1,
|
||||
bp.p2,
|
||||
bp.cp1,
|
||||
bp.cp2,
|
||||
this.datas.segmentsCount
|
||||
);
|
||||
});
|
||||
} else {
|
||||
// 直线
|
||||
const start = this.getStartPoint();
|
||||
this.lineGraphic.moveTo(start.x, start.y);
|
||||
for (let i = 0; i < this.datas.points.length; i++) {
|
||||
const p = this.datas.points[i];
|
||||
this.lineGraphic.lineTo(p.x, p.y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getStartPoint(): IPointData {
|
||||
return this.datas.points[0];
|
||||
}
|
||||
getEndPoint(): IPointData {
|
||||
return this.datas.points[this.datas.points.length - 1];
|
||||
}
|
||||
}
|
||||
|
||||
export class LinkTemplate extends JlGraphicTemplate<Link> {
|
||||
curve: boolean;
|
||||
lineWidth: number;
|
||||
lineColor: string;
|
||||
segmentsCount: number;
|
||||
constructor() {
|
||||
super(Link.Type);
|
||||
this.lineWidth = 2;
|
||||
this.lineColor = '#000000';
|
||||
this.curve = false;
|
||||
this.segmentsCount = 10;
|
||||
}
|
||||
new(): Link {
|
||||
return new Link();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,343 @@
|
|||
import {
|
||||
Color,
|
||||
DisplayObject,
|
||||
FederatedMouseEvent,
|
||||
FederatedPointerEvent,
|
||||
Graphics,
|
||||
IHitArea,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import {
|
||||
AbsorbablePosition,
|
||||
DraggablePoint,
|
||||
GraphicApp,
|
||||
GraphicDrawAssistant,
|
||||
GraphicInteractionPlugin,
|
||||
JlDrawApp,
|
||||
JlGraphic,
|
||||
KeyListener,
|
||||
calculateMirrorPoint,
|
||||
convertToBezierPoints,
|
||||
linePoint,
|
||||
pointPolygon,
|
||||
} from 'src/jlgraphic';
|
||||
import AbsorbablePoint, {
|
||||
AbsorbableCircle,
|
||||
} from 'src/jlgraphic/graphic/AbsorbablePosition';
|
||||
import {
|
||||
BezierCurveEditPlugin,
|
||||
PolylineEditPlugin,
|
||||
} from 'src/jlgraphic/plugins/GraphicEditPlugin';
|
||||
import { ILinkData, Link, LinkTemplate } from './Link';
|
||||
|
||||
export interface ILinkDrawOptions {
|
||||
newData: () => ILinkData;
|
||||
}
|
||||
|
||||
export class LinkDraw extends GraphicDrawAssistant<LinkTemplate> {
|
||||
_options: ILinkDrawOptions;
|
||||
points: Point[] = [];
|
||||
graphic: Graphics = new Graphics();
|
||||
|
||||
// 快捷切曲线绘制
|
||||
keyqListener: KeyListener = new KeyListener({
|
||||
value: 'KeyQ',
|
||||
global: true,
|
||||
onPress: () => {
|
||||
if (this.points.length == 0) {
|
||||
this.graphicTemplate.curve = true;
|
||||
}
|
||||
},
|
||||
});
|
||||
// 快捷切直线绘制
|
||||
keyzListener: KeyListener = new KeyListener({
|
||||
value: 'KeyZ',
|
||||
global: true,
|
||||
onPress: () => {
|
||||
if (this.points.length == 0) {
|
||||
this.graphicTemplate.curve = false;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
constructor(app: JlDrawApp, options: ILinkDrawOptions) {
|
||||
super(app, new LinkTemplate(), Link.Type, '轨道Link');
|
||||
this.container.addChild(this.graphic);
|
||||
this._options = options;
|
||||
this.graphicTemplate.curve = true;
|
||||
|
||||
new LinkPointsEditPlugin(app);
|
||||
}
|
||||
|
||||
newLinkData(): ILinkData {
|
||||
return this._options.newData();
|
||||
}
|
||||
bind(): void {
|
||||
super.bind();
|
||||
this.app.addKeyboardListener(this.keyqListener, this.keyzListener);
|
||||
}
|
||||
unbind(): void {
|
||||
super.unbind();
|
||||
this.app.removeKeyboardListener(this.keyqListener, this.keyzListener);
|
||||
}
|
||||
|
||||
clearCache(): void {
|
||||
this.points = [];
|
||||
this.graphic.clear();
|
||||
}
|
||||
onRightUp(): void {
|
||||
this.createAndStore(true);
|
||||
}
|
||||
onLeftDown(e: FederatedPointerEvent): void {
|
||||
const { x, y } = this.toCanvasCoordinates(e.global);
|
||||
const p = new Point(x, y);
|
||||
if (this.graphicTemplate.curve) {
|
||||
if (this.points.length == 0) {
|
||||
this.points.push(p);
|
||||
} else {
|
||||
this.points.push(p, p.clone());
|
||||
}
|
||||
} else {
|
||||
this.points.push(p);
|
||||
}
|
||||
}
|
||||
onLeftUp(e: FederatedMouseEvent): void {
|
||||
const template = this.graphicTemplate;
|
||||
if (template.curve) {
|
||||
const mp = this.toCanvasCoordinates(e.global);
|
||||
if (this.points.length == 1) {
|
||||
this.points.push(new Point(mp.x, mp.y));
|
||||
} else if (this.points.length > 1) {
|
||||
const cp2 = this.points[this.points.length - 2];
|
||||
const p = this.points[this.points.length - 1];
|
||||
cp2.copyFrom(calculateMirrorPoint(p, mp));
|
||||
this.points.push(mp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
redraw(p: Point): void {
|
||||
if (this.points.length < 1) return;
|
||||
this.graphic.clear();
|
||||
const template = this.graphicTemplate;
|
||||
this.graphic.lineStyle(template.lineWidth, new Color(template.lineColor));
|
||||
const ps = [...this.points];
|
||||
if (template.curve) {
|
||||
// 曲线
|
||||
if (ps.length == 1) {
|
||||
this.graphic.moveTo(ps[0].x, ps[0].y);
|
||||
this.graphic.lineTo(p.x, p.y);
|
||||
} else {
|
||||
if ((ps.length + 1) % 3 == 0) {
|
||||
ps.push(p.clone(), p.clone());
|
||||
} else {
|
||||
const cp = ps[ps.length - 2];
|
||||
const p1 = ps[ps.length - 1];
|
||||
const mp = calculateMirrorPoint(p1, p);
|
||||
cp.copyFrom(mp);
|
||||
}
|
||||
|
||||
const bps = convertToBezierPoints(ps);
|
||||
bps.forEach((bp) =>
|
||||
this.graphic.drawBezierCurve(
|
||||
bp.p1,
|
||||
bp.p2,
|
||||
bp.cp1,
|
||||
bp.cp2,
|
||||
template.segmentsCount
|
||||
)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
ps.push(p);
|
||||
// 直线
|
||||
this.graphic.moveTo(ps[0].x, ps[0].y);
|
||||
for (let i = 1; i < ps.length; i++) {
|
||||
const p = ps[i];
|
||||
this.graphic.lineTo(p.x, p.y);
|
||||
}
|
||||
}
|
||||
}
|
||||
prepareData(): ILinkData | null {
|
||||
const template = this.graphicTemplate;
|
||||
if (
|
||||
(!template.curve && this.points.length < 2) ||
|
||||
(template.curve && this.points.length < 4)
|
||||
) {
|
||||
console.log('Link绘制因点不够取消绘制');
|
||||
return null;
|
||||
}
|
||||
if (template.curve) {
|
||||
this.points.pop();
|
||||
}
|
||||
const data = this.newLinkData();
|
||||
data.id = this.nextId();
|
||||
data.graphicType = Link.Type;
|
||||
data.curve = template.curve;
|
||||
data.segmentsCount = template.segmentsCount;
|
||||
data.points = this.points;
|
||||
data.lineWidth = template.lineWidth;
|
||||
data.lineColor = template.lineColor;
|
||||
data.segmentsCount = template.segmentsCount;
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
export class LinkGraphicHitArea implements IHitArea {
|
||||
link: Link;
|
||||
constructor(link: Link) {
|
||||
this.link = link;
|
||||
}
|
||||
contains(x: number, y: number): boolean {
|
||||
const p = new Point(x, y);
|
||||
if (this.link.datas.curve) {
|
||||
// 曲线
|
||||
const bps = convertToBezierPoints(this.link.datas.points);
|
||||
for (let i = 0; i < bps.length; i++) {
|
||||
const bp = bps[i];
|
||||
if (
|
||||
pointPolygon(
|
||||
p,
|
||||
[bp.p1, bp.cp1, bp.cp2, bp.p2],
|
||||
this.link.datas.lineWidth
|
||||
)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 直线
|
||||
for (let i = 1; i < this.link.datas.points.length; i++) {
|
||||
const p1 = this.link.datas.points[i - 1];
|
||||
const p2 = this.link.datas.points[i];
|
||||
if (linePoint(p1, p2, p, this.link.datas.lineWidth)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建吸附位置
|
||||
* @param link
|
||||
* @returns
|
||||
*/
|
||||
function buildAbsorbablePositions(link: Link): AbsorbablePosition[] {
|
||||
const aps: AbsorbablePosition[] = [];
|
||||
const links = link.queryStore.queryByType<Link>(Link.Type);
|
||||
links.forEach((other) => {
|
||||
if (other.id == link.id) {
|
||||
return;
|
||||
}
|
||||
const apa = new AbsorbablePoint(
|
||||
other.localToCanvasPoint(other.getStartPoint())
|
||||
);
|
||||
const apb = new AbsorbablePoint(
|
||||
other.localToCanvasPoint(other.getEndPoint())
|
||||
);
|
||||
aps.push(apa, apb);
|
||||
});
|
||||
|
||||
aps.push(new AbsorbableCircle(new Point(450, 410), 30));
|
||||
|
||||
return aps;
|
||||
}
|
||||
|
||||
/**
|
||||
* 端点拖拽添加吸附位置
|
||||
* @param g
|
||||
* @param dp
|
||||
* @param index
|
||||
*/
|
||||
function onEditPointCreate(
|
||||
g: JlGraphic,
|
||||
dp: DraggablePoint,
|
||||
index: number
|
||||
): void {
|
||||
const link = g as Link;
|
||||
if (index === 0 || index == link.datas.points.length - 1) {
|
||||
// 端点
|
||||
dp.on('dragstart', () => {
|
||||
link.getGraphicApp().setOptions({
|
||||
absorbablePositions: buildAbsorbablePositions(link),
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* link路径编辑
|
||||
*/
|
||||
export class LinkPointsEditPlugin extends GraphicInteractionPlugin<Link> {
|
||||
static Name = 'LinkPointsDrag';
|
||||
constructor(app: GraphicApp) {
|
||||
super(LinkPointsEditPlugin.Name, app);
|
||||
}
|
||||
filter(...grahpics: JlGraphic[]): Link[] | undefined {
|
||||
return grahpics.filter((g) => g.type == Link.Type) as Link[];
|
||||
}
|
||||
bind(g: Link): void {
|
||||
g.lineGraphic.eventMode = 'static';
|
||||
g.lineGraphic.cursor = 'pointer';
|
||||
g.lineGraphic.hitArea = new LinkGraphicHitArea(g);
|
||||
g.on('selected', this.onSelected, this);
|
||||
g.on('unselected', this.onUnselected, this);
|
||||
}
|
||||
unbind(g: Link): void {
|
||||
g.off('selected', this.onSelected, this);
|
||||
g.off('unselected', this.onUnselected, this);
|
||||
}
|
||||
|
||||
onSelected(g: DisplayObject): void {
|
||||
const link = g as Link;
|
||||
let lep;
|
||||
if (link.datas.curve) {
|
||||
// 曲线
|
||||
lep = link.getAssistantAppend<BezierCurveEditPlugin>(
|
||||
BezierCurveEditPlugin.Name
|
||||
);
|
||||
if (!lep) {
|
||||
lep = new BezierCurveEditPlugin(
|
||||
link,
|
||||
link.datas.points,
|
||||
onEditPointCreate
|
||||
);
|
||||
link.addAssistantAppend(lep);
|
||||
}
|
||||
} else {
|
||||
// 直线
|
||||
lep = link.getAssistantAppend<PolylineEditPlugin>(
|
||||
PolylineEditPlugin.Name
|
||||
);
|
||||
if (!lep) {
|
||||
lep = new PolylineEditPlugin(
|
||||
link,
|
||||
link.datas.points,
|
||||
onEditPointCreate
|
||||
);
|
||||
link.addAssistantAppend(lep);
|
||||
}
|
||||
}
|
||||
lep.showAll();
|
||||
}
|
||||
onUnselected(g: DisplayObject): void {
|
||||
const link = g as Link;
|
||||
let lep;
|
||||
if (link.datas.curve) {
|
||||
// 曲线
|
||||
lep = link.getAssistantAppend<BezierCurveEditPlugin>(
|
||||
BezierCurveEditPlugin.Name
|
||||
);
|
||||
} else {
|
||||
// 直线
|
||||
lep = link.getAssistantAppend<PolylineEditPlugin>(
|
||||
PolylineEditPlugin.Name
|
||||
);
|
||||
}
|
||||
if (lep) {
|
||||
lep.hideAll();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
import { GraphicData, JlGraphic } from 'src/jlgraphic';
|
||||
|
||||
export type ITrunoutData = GraphicData;
|
||||
|
||||
export class Turnout extends JlGraphic {
|
||||
doRepaint(): void {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
}
|
|
@ -0,0 +1,739 @@
|
|||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
/* eslint-disable @typescript-eslint/no-empty-function */
|
||||
import {
|
||||
BitmapFont,
|
||||
BitmapText,
|
||||
Container,
|
||||
DisplayObject,
|
||||
FederatedMouseEvent,
|
||||
IPointData,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import { GraphicIdGenerator } from '../core/IdGenerator';
|
||||
import { JlGraphic, GraphicData, GraphicTemplate } from '../core/JlGraphic';
|
||||
import { BoundsGraphic, TransformPoints } from '../graphic';
|
||||
import { JlOperation } from '../operation/JlOperation';
|
||||
import {
|
||||
AppInteractionPlugin,
|
||||
CombinationKey,
|
||||
InteractionPlugin,
|
||||
KeyListener,
|
||||
ViewportMovePlugin,
|
||||
} from '../plugins';
|
||||
import { CommonMouseTool } from '../plugins/CommonMousePlugin';
|
||||
import { DOWN, LEFT, RIGHT, UP, recursiveChildren } from '../utils';
|
||||
import {
|
||||
CanvasData,
|
||||
CanvasEvent,
|
||||
GraphicApp,
|
||||
GraphicAppOptions,
|
||||
ICanvasProperties,
|
||||
JlCanvas,
|
||||
} from './JlGraphicApp';
|
||||
|
||||
/**
|
||||
* 图形绘制助手
|
||||
*/
|
||||
export abstract class GraphicDrawAssistant<
|
||||
GT extends GraphicTemplate
|
||||
> extends AppInteractionPlugin {
|
||||
_isDrawAssistant = true;
|
||||
app: JlDrawApp;
|
||||
type: string; // 图形对象类型
|
||||
description?: string; // 描述
|
||||
icon: string; // 界面显示的图标
|
||||
container: Container = new Container();
|
||||
graphicTemplate: GT;
|
||||
|
||||
escListener: KeyListener = new KeyListener({
|
||||
value: 'Escape',
|
||||
onPress: () => {
|
||||
this.createAndStore(true);
|
||||
},
|
||||
});
|
||||
|
||||
constructor(
|
||||
graphicApp: JlDrawApp,
|
||||
graphicTemplate: GT,
|
||||
icon: string,
|
||||
description?: string
|
||||
) {
|
||||
super(graphicTemplate.type, graphicApp);
|
||||
this.app = graphicApp;
|
||||
this.graphicTemplate = graphicTemplate;
|
||||
this.type = graphicTemplate.type;
|
||||
this.icon = icon;
|
||||
this.description = description;
|
||||
this.app.registerGraphicTemplates(this.graphicTemplate);
|
||||
}
|
||||
|
||||
public get canvas(): JlCanvas {
|
||||
return this.app.canvas;
|
||||
}
|
||||
|
||||
bind(): void {
|
||||
const canvas = this.canvas;
|
||||
canvas.addChild(this.container);
|
||||
canvas.on('mousedown', this.onLeftDown, this);
|
||||
canvas.on('mousemove', this.onMouseMove, this);
|
||||
canvas.on('mouseup', this.onLeftUp, this);
|
||||
canvas.on('rightdown', this.onRightDown, this);
|
||||
canvas.on('rightup', this.onRightUp, this);
|
||||
this.app.viewport.wheel({
|
||||
percent: 0.01,
|
||||
});
|
||||
this.app.addKeyboardListener(this.escListener);
|
||||
|
||||
this.app
|
||||
.interactionPlugin<ViewportMovePlugin>(ViewportMovePlugin.Name)
|
||||
.resume();
|
||||
}
|
||||
unbind(): void {
|
||||
this.clearCache();
|
||||
const canvas = this.canvas;
|
||||
canvas.removeChild(this.container);
|
||||
canvas.off('mousedown', this.onLeftDown, this);
|
||||
canvas.off('mousemove', this.onMouseMove, this);
|
||||
canvas.off('mouseup', this.onLeftUp, this);
|
||||
canvas.off('rightdown', this.onRightDown, this);
|
||||
canvas.off('rightup', this.onRightUp, this);
|
||||
|
||||
this.app.viewport.plugins.remove('wheel');
|
||||
|
||||
this.app.removeKeyboardListener(this.escListener);
|
||||
|
||||
this.app
|
||||
.interactionPlugin<ViewportMovePlugin>(ViewportMovePlugin.Name)
|
||||
.pause();
|
||||
}
|
||||
|
||||
onLeftDown(e: FederatedMouseEvent) {}
|
||||
|
||||
onMouseMove(e: FederatedMouseEvent) {
|
||||
this.redraw(this.toCanvasCoordinates(e.global));
|
||||
}
|
||||
|
||||
onLeftUp(e: FederatedMouseEvent) {}
|
||||
onRightDown(e: FederatedMouseEvent) {}
|
||||
onRightUp(e: FederatedMouseEvent) {}
|
||||
/**
|
||||
* 获取下一个id
|
||||
*/
|
||||
nextId(): string {
|
||||
return GraphicIdGenerator.next();
|
||||
}
|
||||
|
||||
clearCache(): void {}
|
||||
|
||||
/**
|
||||
* 重绘
|
||||
* @param cp 鼠标所在画布坐标
|
||||
*/
|
||||
abstract redraw(cp: Point): void;
|
||||
|
||||
abstract prepareData(): GraphicData | null;
|
||||
|
||||
toCanvasCoordinates(p: Point): Point {
|
||||
return this.app.toCanvasCoordinates(p);
|
||||
}
|
||||
/**
|
||||
* 保存创建的图形对象
|
||||
*/
|
||||
storeGraphic(...graphics: JlGraphic[]): void {
|
||||
this.app.addGraphics(...graphics);
|
||||
// 创建图形对象操作记录
|
||||
this.app.opRecord.record(new GraphicCreateOperation(this.app, graphics));
|
||||
}
|
||||
/**
|
||||
* 创建并添加到图形App
|
||||
*/
|
||||
createAndStore(finish: boolean): JlGraphic | null {
|
||||
const data = this.prepareData();
|
||||
if (!data) {
|
||||
if (finish) {
|
||||
this.finish();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const template = this.graphicTemplate;
|
||||
const g = template.new();
|
||||
g.loadData(data);
|
||||
g.id = this.nextId();
|
||||
this.storeGraphic(g);
|
||||
if (finish) {
|
||||
this.finish(g);
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制完成
|
||||
*/
|
||||
finish(...graphics: JlGraphic[]): void {
|
||||
this.clearCache();
|
||||
this.app.interactionPlugin(CommonMouseTool.Name).resume();
|
||||
this.app.updateSelected(...graphics);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形App事件
|
||||
*/
|
||||
export enum DrawAppEvent {
|
||||
propertiesupdate = 'propertiesupdate', // 图形对象数据变更
|
||||
}
|
||||
|
||||
export interface IDrawAppOptions {
|
||||
/**
|
||||
* 绘制辅助交互插件
|
||||
*/
|
||||
drawAssistants: GraphicDrawAssistant<GraphicTemplate>[];
|
||||
}
|
||||
|
||||
export type DrawAppOptions = GraphicAppOptions & IDrawAppOptions;
|
||||
|
||||
/**
|
||||
* 绘制应用
|
||||
*/
|
||||
export class JlDrawApp extends GraphicApp {
|
||||
font: BitmapFont = BitmapFont.from(
|
||||
'coordinates',
|
||||
{
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 16,
|
||||
fill: '#ff2700',
|
||||
},
|
||||
{ chars: ['画布坐标:() 屏幕坐标:() 缩放:.,', ['0', '9']] }
|
||||
);
|
||||
coordinates: BitmapText = new BitmapText('画布坐标: (0, 0) 屏幕坐标:(0, 0)', {
|
||||
fontName: 'coordinates',
|
||||
});
|
||||
scaleText: BitmapText = new BitmapText('缩放: 1', {
|
||||
fontName: 'coordinates',
|
||||
});
|
||||
|
||||
drawAssistants: GraphicDrawAssistant<GraphicTemplate>[] = [];
|
||||
|
||||
selectedData: GraphicData | ICanvasProperties | null;
|
||||
|
||||
constructor(dom: HTMLElement) {
|
||||
super(dom);
|
||||
|
||||
this.appendDrawStatesDisplay();
|
||||
|
||||
// 数据更新表单缓存处理
|
||||
this.selectedData = null;
|
||||
this.initSelectedDataUpdateListen();
|
||||
// 拖拽操作记录
|
||||
this.appDragRecord();
|
||||
// 绑定通用键盘操作
|
||||
this.bindKeyboardOperation();
|
||||
}
|
||||
|
||||
setOptions(options: DrawAppOptions): void {
|
||||
super.setOptions(options);
|
||||
// this.registerInteractionPlugin(...options.drawAssistants);
|
||||
}
|
||||
|
||||
registerInteractionPlugin(...plugins: InteractionPlugin[]): void {
|
||||
plugins.forEach((plugin) => {
|
||||
if (plugin instanceof GraphicDrawAssistant) {
|
||||
this.drawAssistants.push(plugin);
|
||||
}
|
||||
super.registerInteractionPlugin(plugin);
|
||||
});
|
||||
}
|
||||
|
||||
getDrawAssistant(graphicType: string): GraphicDrawAssistant<GraphicTemplate> {
|
||||
const sda = this.drawAssistants
|
||||
.filter((da) => da.type === graphicType)
|
||||
.pop();
|
||||
if (!sda) {
|
||||
throw new Error(`未找到图形绘制助手: ${graphicType}`);
|
||||
}
|
||||
return sda;
|
||||
}
|
||||
|
||||
private appDragRecord() {
|
||||
let dragStartDatas: GraphicData[] = [];
|
||||
this.on('dragstart', () => {
|
||||
// 图形拖拽,记录初始数据
|
||||
// console.log('app图形拖拽开始,记录图形数据');
|
||||
dragStartDatas = this.selectedGraphics.map((g) => g.saveData());
|
||||
});
|
||||
// 图形拖拽操作监听
|
||||
this.on('dragend', () => {
|
||||
// 图形拖拽,记录操作
|
||||
// console.log('app图形拖拽结束,记录操作');
|
||||
const newData = this.selectedGraphics.map((g) => g.saveData());
|
||||
this.opRecord.record(
|
||||
new DragOperation(this, this.selectedGraphics, dragStartDatas, newData)
|
||||
);
|
||||
dragStartDatas = [];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 因图形数据更新和表单数据更新存在Vue代理及记录需求,额外处理数据的缓存
|
||||
*/
|
||||
private initSelectedDataUpdateListen() {
|
||||
// 画布数据更新
|
||||
this.selectedData = new CanvasData(this.canvas.properties);
|
||||
this.canvas.on(CanvasEvent.propertiesupdate, () => {
|
||||
if (this.selectedGraphics.length === 0) {
|
||||
this.selectedData = this.canvas.saveData();
|
||||
this.emit('propertiesupdate', this.selectedData);
|
||||
}
|
||||
});
|
||||
this.viewport.on('moved-end', () => {
|
||||
if (this.selectedGraphics.length === 0) {
|
||||
this.selectedData = this.canvas.saveData();
|
||||
this.emit('propertiesupdate', this.selectedData);
|
||||
}
|
||||
});
|
||||
// 图形对象数据更新
|
||||
const graphicPropertiesUpdate = (g: DisplayObject) => {
|
||||
if (this.selectedGraphics.length === 1) {
|
||||
this.selectedData = (g as JlGraphic).saveData();
|
||||
this.emit(DrawAppEvent.propertiesupdate, this.selectedData);
|
||||
}
|
||||
};
|
||||
this.on('graphicselectedchange', (g: DisplayObject, selected) => {
|
||||
let br = g.getAssistantAppend<BoundsGraphic>(BoundsGraphic.Name);
|
||||
if (!br) {
|
||||
// 绘制辅助包围框
|
||||
br = new BoundsGraphic(g);
|
||||
}
|
||||
|
||||
if (selected) {
|
||||
g.on('repaint', graphicPropertiesUpdate, this);
|
||||
if (br) {
|
||||
br.redraw();
|
||||
br.visible = true;
|
||||
}
|
||||
} else {
|
||||
g.off('repaint', graphicPropertiesUpdate, this);
|
||||
if (br) {
|
||||
br.visible = false;
|
||||
}
|
||||
}
|
||||
if (g.scalable) {
|
||||
// 缩放点
|
||||
let sp = g.getAssistantAppend<TransformPoints>(TransformPoints.Name);
|
||||
if (!sp) {
|
||||
sp = new TransformPoints(g);
|
||||
}
|
||||
if (selected) {
|
||||
sp.update();
|
||||
sp.visible = true;
|
||||
} else {
|
||||
sp.visible = false;
|
||||
}
|
||||
}
|
||||
if (this.selectedGraphics.length === 0) {
|
||||
this.selectedData = this.canvas.properties.clone();
|
||||
} else if (this.selectedGraphics.length === 1) {
|
||||
const g = this.selectedGraphics[0];
|
||||
this.selectedData = g.saveData();
|
||||
} else {
|
||||
this.selectedData = null;
|
||||
}
|
||||
this.emit(DrawAppEvent.propertiesupdate, this.selectedData);
|
||||
});
|
||||
this.on('graphicchildselectedchange', (_g, child, selected) => {
|
||||
let br = child.getAssistantAppend<BoundsGraphic>(BoundsGraphic.Name);
|
||||
if (!br) {
|
||||
// 绘制辅助包围框
|
||||
br = new BoundsGraphic(child);
|
||||
}
|
||||
if (selected) {
|
||||
br.redraw();
|
||||
br.visible = true;
|
||||
} else {
|
||||
br.visible = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制状态信息显示
|
||||
*/
|
||||
private appendDrawStatesDisplay(): void {
|
||||
this.app.stage.addChild(this.coordinates);
|
||||
this.app.stage.addChild(this.scaleText);
|
||||
const bound = this.coordinates.getLocalBounds();
|
||||
this.scaleText.position.set(bound.width + 10, 0);
|
||||
this.canvas.interactive = true;
|
||||
this.canvas.on('mousemove', (e) => {
|
||||
if (e.target) {
|
||||
const { x, y } = this.toCanvasCoordinates(e.global);
|
||||
const cpTxt = `(${x}, ${y})`;
|
||||
const tp = e.global;
|
||||
const tpTxt = `(${tp.x}, ${tp.y})`;
|
||||
this.coordinates.text = `画布坐标:${cpTxt} 屏幕坐标:${tpTxt}`;
|
||||
const bound = this.coordinates.getLocalBounds();
|
||||
this.scaleText.position.set(bound.width + 10, 0);
|
||||
}
|
||||
});
|
||||
this.viewport.on('zoomed-end', () => {
|
||||
this.scaleText.text = `缩放: ${this.viewport.scaled}`;
|
||||
});
|
||||
}
|
||||
|
||||
bindKeyboardOperation(): void {
|
||||
this.addKeyboardListener(
|
||||
// Ctrl + A
|
||||
new KeyListener({
|
||||
value: 'KeyA',
|
||||
combinations: [CombinationKey.Ctrl],
|
||||
onPress: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
if (e.ctrlKey) {
|
||||
(app as JlDrawApp).selectAllGraphics();
|
||||
}
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
// 复制功能
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'KeyD',
|
||||
combinations: [CombinationKey.Shift],
|
||||
onPress: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
app.graphicCopyPlugin.init();
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
// Ctrl + Z
|
||||
value: 'KeyZ',
|
||||
global: true,
|
||||
combinations: [CombinationKey.Ctrl],
|
||||
onPress: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
app.opRecord.undo();
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
// Ctrl + Shift + Z
|
||||
value: 'KeyZ',
|
||||
global: true,
|
||||
combinations: [CombinationKey.Ctrl, CombinationKey.Shift],
|
||||
onPress: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
app.opRecord.redo();
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'Delete',
|
||||
onPress: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
(app as JlDrawApp).deleteSelectedGraphics();
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'ArrowUp',
|
||||
pressTriggerEveryTime: true,
|
||||
onPress: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
updateGraphicPositionOnKeyboardEvent(app, UP);
|
||||
},
|
||||
onRelease: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
recordGraphicMoveOperation(app);
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'ArrowDown',
|
||||
pressTriggerEveryTime: true,
|
||||
onPress: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
updateGraphicPositionOnKeyboardEvent(app, DOWN);
|
||||
},
|
||||
onRelease: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
recordGraphicMoveOperation(app);
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'ArrowLeft',
|
||||
pressTriggerEveryTime: true,
|
||||
onPress: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
updateGraphicPositionOnKeyboardEvent(app, LEFT);
|
||||
},
|
||||
onRelease: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
recordGraphicMoveOperation(app);
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'ArrowRight',
|
||||
pressTriggerEveryTime: true,
|
||||
onPress: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
updateGraphicPositionOnKeyboardEvent(app, RIGHT);
|
||||
},
|
||||
onRelease: (e: KeyboardEvent, app: GraphicApp) => {
|
||||
recordGraphicMoveOperation(app);
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 全选
|
||||
*/
|
||||
selectAllGraphics() {
|
||||
this.updateSelected(...this.queryStore.getAllGraphics());
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形对象存储处理,默认添加图形交互
|
||||
* @param graphic
|
||||
*/
|
||||
beforeGraphicStore(graphic: JlGraphic): void {
|
||||
graphic.eventMode = 'static';
|
||||
graphic.selectable = true;
|
||||
graphic.draggable = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除选中图形对象
|
||||
*/
|
||||
deleteSelectedGraphics() {
|
||||
const deletes = this.selectedGraphics.slice(
|
||||
0,
|
||||
this.selectedGraphics.length
|
||||
);
|
||||
this.deleteGraphics(...this.selectedGraphics);
|
||||
// 删除图形对象操作记录
|
||||
this.opRecord.record(new GraphicDeleteOperation(this, deletes));
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
if (this.selectedData == null) return;
|
||||
if (this.selectedGraphics.length === 0) {
|
||||
const cp = this.selectedData as ICanvasProperties;
|
||||
this.opRecord.record(
|
||||
new UpdateCanvasOperation(
|
||||
this,
|
||||
this.canvas,
|
||||
cp,
|
||||
this.canvas.properties.clone()
|
||||
)
|
||||
);
|
||||
this.canvas.update(this.selectedData as ICanvasProperties);
|
||||
} else if (this.selectedGraphics.length === 1) {
|
||||
const g = this.selectedGraphics[0];
|
||||
if (this.selectedData != null) {
|
||||
const data = g.saveData();
|
||||
g.updateData(this.selectedData as GraphicData);
|
||||
this.opRecord.record(
|
||||
new UpdateDataOperation(
|
||||
this,
|
||||
g,
|
||||
data,
|
||||
this.selectedData as GraphicData
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let dragStartDatas: GraphicData[] = [];
|
||||
function updateGraphicPositionOnKeyboardEvent(app: GraphicApp, dp: IPointData) {
|
||||
let dragStart = false;
|
||||
if (dragStartDatas.length === 0) {
|
||||
dragStartDatas = app.selectedGraphics.map((g) => g.saveData());
|
||||
dragStart = true;
|
||||
}
|
||||
if (
|
||||
app.selectedGraphics.length === 1 &&
|
||||
app.selectedGraphics[0].hasSelectedChilds()
|
||||
) {
|
||||
recursiveChildren(app.selectedGraphics[0], (child) => {
|
||||
if (child.selected && child.draggable) {
|
||||
child.emit('transformstart', child);
|
||||
child.position.x += dp.x;
|
||||
child.position.y += dp.y;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
app.selectedGraphics.forEach((g) => {
|
||||
g.emit('transformstart', g);
|
||||
g.position.x += dp.x;
|
||||
g.position.y += dp.y;
|
||||
});
|
||||
}
|
||||
}
|
||||
function recordGraphicMoveOperation(app: GraphicApp) {
|
||||
if (
|
||||
dragStartDatas.length > 0 &&
|
||||
dragStartDatas.length === app.selectedGraphics.length
|
||||
) {
|
||||
const newData = app.selectedGraphics.map((g) => g.saveData());
|
||||
app.opRecord.record(
|
||||
new DragOperation(app, app.selectedGraphics, dragStartDatas, newData)
|
||||
);
|
||||
if (
|
||||
app.selectedGraphics.length === 1 &&
|
||||
app.selectedGraphics[0].hasSelectedChilds()
|
||||
) {
|
||||
recursiveChildren(app.selectedGraphics[0], (child) => {
|
||||
if (child.selected && child.draggable) {
|
||||
child.emit('transformend', child);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
app.selectedGraphics.forEach((g) => {
|
||||
g.emit('transformend', g);
|
||||
});
|
||||
}
|
||||
}
|
||||
dragStartDatas = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新画布操作
|
||||
*/
|
||||
export class UpdateCanvasOperation extends JlOperation {
|
||||
obj: JlCanvas;
|
||||
old: ICanvasProperties;
|
||||
data: ICanvasProperties;
|
||||
description = '';
|
||||
|
||||
constructor(
|
||||
app: GraphicApp,
|
||||
obj: JlCanvas,
|
||||
old: ICanvasProperties,
|
||||
data: ICanvasProperties
|
||||
) {
|
||||
super(app, 'update-canvas');
|
||||
this.app = app;
|
||||
this.obj = obj;
|
||||
this.old = old;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
undo(): JlGraphic[] {
|
||||
this.obj.update(this.old);
|
||||
return [];
|
||||
}
|
||||
redo(): JlGraphic[] {
|
||||
this.obj.update(this.data);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 创建图形操作
|
||||
*/
|
||||
export class GraphicCreateOperation extends JlOperation {
|
||||
obj: JlGraphic[];
|
||||
description = '';
|
||||
|
||||
constructor(app: GraphicApp, obj: JlGraphic[]) {
|
||||
super(app, 'graphic-create');
|
||||
this.app = app;
|
||||
this.obj = obj;
|
||||
}
|
||||
|
||||
undo(): JlGraphic[] | void {
|
||||
this.app.deleteGraphics(...this.obj);
|
||||
}
|
||||
redo(): JlGraphic[] {
|
||||
this.app.addGraphics(...this.obj);
|
||||
return this.obj;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 删除图形操作
|
||||
*/
|
||||
export class GraphicDeleteOperation extends JlOperation {
|
||||
obj: JlGraphic[];
|
||||
|
||||
constructor(app: GraphicApp, obj: JlGraphic[]) {
|
||||
super(app, 'graphic-delete');
|
||||
this.app = app;
|
||||
this.obj = obj;
|
||||
}
|
||||
|
||||
undo(): JlGraphic[] {
|
||||
this.app.addGraphics(...this.obj);
|
||||
return this.obj;
|
||||
}
|
||||
redo(): void {
|
||||
this.app.deleteGraphics(...this.obj);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新数据操作
|
||||
*/
|
||||
export class UpdateDataOperation extends JlOperation {
|
||||
obj: JlGraphic;
|
||||
data: GraphicData; // 更新为data的protobuf数据
|
||||
old: GraphicData; // 更新前data的protobuf数据
|
||||
description = '';
|
||||
|
||||
constructor(
|
||||
app: GraphicApp,
|
||||
obj: JlGraphic,
|
||||
old: GraphicData,
|
||||
data: GraphicData
|
||||
) {
|
||||
super(app, 'update-payload');
|
||||
this.app = app;
|
||||
this.obj = obj;
|
||||
this.old = old;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
undo(): JlGraphic[] {
|
||||
this.obj.updateData(this.old);
|
||||
return [this.obj];
|
||||
}
|
||||
redo(): JlGraphic[] {
|
||||
this.obj.updateData(this.data);
|
||||
return [this.obj];
|
||||
}
|
||||
}
|
||||
|
||||
export class DragOperation extends JlOperation {
|
||||
obj: JlGraphic[];
|
||||
oldData: GraphicData[];
|
||||
newData: GraphicData[];
|
||||
constructor(
|
||||
app: GraphicApp,
|
||||
obj: JlGraphic[],
|
||||
oldData: GraphicData[],
|
||||
newData: GraphicData[]
|
||||
) {
|
||||
super(app, 'graphic-drag');
|
||||
this.obj = [...obj];
|
||||
this.oldData = oldData;
|
||||
this.newData = newData;
|
||||
}
|
||||
|
||||
undo(): void | JlGraphic[] {
|
||||
for (let i = 0; i < this.obj.length; i++) {
|
||||
const g = this.obj[i];
|
||||
g.exitChildEdit();
|
||||
g.updateData(this.oldData[i]);
|
||||
}
|
||||
return this.obj;
|
||||
}
|
||||
redo(): void | JlGraphic[] {
|
||||
for (let i = 0; i < this.obj.length; i++) {
|
||||
const g = this.obj[i];
|
||||
g.exitChildEdit();
|
||||
g.updateData(this.newData[i]);
|
||||
}
|
||||
return this.obj;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,880 @@
|
|||
import EventEmitter from 'eventemitter3';
|
||||
import { Viewport } from 'pixi-viewport';
|
||||
import {
|
||||
Application,
|
||||
Color,
|
||||
Container,
|
||||
DisplayObject,
|
||||
Graphics,
|
||||
Point,
|
||||
Rectangle,
|
||||
} from 'pixi.js';
|
||||
import { GraphicQueryStore, GraphicStore } from '../core/GraphicStore';
|
||||
import { GraphicIdGenerator } from '../core/IdGenerator';
|
||||
import {
|
||||
JlGraphic,
|
||||
GraphicData,
|
||||
GraphicState,
|
||||
GraphicTemplate,
|
||||
GraphicTransform,
|
||||
} from '../core/JlGraphic';
|
||||
import { AbsorbablePosition } from '../graphic';
|
||||
import {
|
||||
AppWsMsgBroker,
|
||||
StompCli,
|
||||
type AppStateSubscription,
|
||||
type StompCliOption,
|
||||
} from '../message/WsMsgBroker';
|
||||
import { OperationRecord } from '../operation/JlOperation';
|
||||
import {
|
||||
CommonMouseTool,
|
||||
GraphicDragEvent,
|
||||
IMouseToolOptions,
|
||||
} from '../plugins';
|
||||
import { GraphicCopyPlugin } from '../plugins/CopyPlugin';
|
||||
import {
|
||||
InteractionPlugin,
|
||||
InteractionPluginType,
|
||||
ViewportMovePlugin,
|
||||
} from '../plugins/InteractionPlugin';
|
||||
import {
|
||||
JlGraphicAppKeyboardPlugin,
|
||||
KeyListener,
|
||||
} from '../plugins/KeyboardPlugin';
|
||||
import { ContextMenuPlugin } from '../ui/ContextMenu';
|
||||
import { getRectangleCenter, recursiveChildren } from '../utils/GraphicUtils';
|
||||
|
||||
export const AppConsts = {
|
||||
viewportname: '__viewport',
|
||||
canvasname: '__jlcanvas',
|
||||
AssistantAppendsName: '__assistantAppends',
|
||||
};
|
||||
|
||||
/**
|
||||
* 画布属性
|
||||
*/
|
||||
export interface ICanvasProperties {
|
||||
width: number;
|
||||
height: number;
|
||||
backgroundColor: string;
|
||||
viewportTransform: GraphicTransform;
|
||||
}
|
||||
|
||||
export class CanvasData implements ICanvasProperties {
|
||||
width: number;
|
||||
height: number;
|
||||
backgroundColor: string;
|
||||
viewportTransform: GraphicTransform;
|
||||
constructor(
|
||||
properties: ICanvasProperties = {
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
backgroundColor: '#ffffff',
|
||||
viewportTransform: GraphicTransform.default(),
|
||||
}
|
||||
) {
|
||||
this.width = properties.width;
|
||||
this.height = properties.height;
|
||||
this.backgroundColor = properties.backgroundColor;
|
||||
this.viewportTransform = properties.viewportTransform;
|
||||
}
|
||||
|
||||
copyFrom(properties: ICanvasProperties): void {
|
||||
this.width = properties.width;
|
||||
this.height = properties.height;
|
||||
this.backgroundColor = properties.backgroundColor;
|
||||
this.viewportTransform = properties.viewportTransform;
|
||||
}
|
||||
|
||||
clone(): CanvasData {
|
||||
const cp = new CanvasData(this);
|
||||
return cp;
|
||||
}
|
||||
}
|
||||
|
||||
export enum CanvasEvent {
|
||||
canvassizechange = 'canvassizechange',
|
||||
propertiesupdate = 'propertiesupdate',
|
||||
enterAbsorbableArea = 'enter-absorbable-area',
|
||||
outAbsorbableArea = 'out-absorbable-area',
|
||||
}
|
||||
|
||||
export class JlCanvas extends Container {
|
||||
__JlCanvas = true;
|
||||
type = 'Canvas';
|
||||
app: GraphicApp;
|
||||
_properties: CanvasData;
|
||||
bg: Graphics = new Graphics(); // 背景
|
||||
nonInteractiveContainer: Container; // 无交互对象容器
|
||||
assistantAppendContainer: Container; // 辅助附加容器
|
||||
|
||||
constructor(app: GraphicApp, properties: CanvasData = new CanvasData()) {
|
||||
super();
|
||||
this.app = app;
|
||||
this._properties = properties;
|
||||
this.eventMode = 'static';
|
||||
this.nonInteractiveContainer = new Container();
|
||||
this.nonInteractiveContainer.name = 'non-interactives';
|
||||
this.nonInteractiveContainer.eventMode = 'none';
|
||||
this.addChild(this.bg);
|
||||
this.addChild(this.nonInteractiveContainer);
|
||||
|
||||
this.sortableChildren = true;
|
||||
this.assistantAppendContainer = new Container();
|
||||
this.assistantAppendContainer.eventMode = 'static';
|
||||
this.assistantAppendContainer.name = AppConsts.AssistantAppendsName;
|
||||
this.assistantAppendContainer.zIndex = 999;
|
||||
this.assistantAppendContainer.sortableChildren = true;
|
||||
this.addChild(this.assistantAppendContainer);
|
||||
|
||||
this.repaint();
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形重绘(数据/状态变化时触发)
|
||||
*/
|
||||
repaint(): void {
|
||||
this.doRepaint();
|
||||
}
|
||||
|
||||
public get width(): number {
|
||||
return this._properties.width;
|
||||
}
|
||||
|
||||
public get height(): number {
|
||||
return this._properties.height;
|
||||
}
|
||||
|
||||
public get backgroundColor(): string {
|
||||
return this._properties.backgroundColor;
|
||||
}
|
||||
|
||||
doRepaint() {
|
||||
this.bg.clear();
|
||||
this.bg
|
||||
.beginFill(new Color(this.backgroundColor))
|
||||
.drawRect(0, 0, this._properties.width, this._properties.height)
|
||||
.endFill();
|
||||
}
|
||||
|
||||
public get properties(): CanvasData {
|
||||
return this._properties;
|
||||
}
|
||||
|
||||
saveData(): CanvasData {
|
||||
const vp = this.getViewport();
|
||||
this.properties.viewportTransform = vp.saveTransform();
|
||||
return this.properties.clone();
|
||||
}
|
||||
|
||||
update(properties: ICanvasProperties) {
|
||||
// 更新画布
|
||||
if (
|
||||
this.properties.width !== properties.width ||
|
||||
this.properties.height !== properties.height
|
||||
) {
|
||||
this._properties.copyFrom(properties);
|
||||
this.emit(CanvasEvent.canvassizechange, this);
|
||||
} else {
|
||||
this._properties.copyFrom(properties);
|
||||
}
|
||||
this.repaint();
|
||||
const vp = this.getViewport();
|
||||
vp.loadTransform(properties.viewportTransform);
|
||||
this.emit(CanvasEvent.propertiesupdate, this);
|
||||
}
|
||||
|
||||
addChild<U extends DisplayObject[]>(...children: U): U[0] {
|
||||
const rt = super.addChild(...children);
|
||||
children.forEach((g) => {
|
||||
recursiveChildren(g as Container, (child) => child.onAddToCanvas());
|
||||
});
|
||||
return rt;
|
||||
}
|
||||
removeChild<U extends DisplayObject[]>(...children: U): U[0] {
|
||||
children.forEach((g) => {
|
||||
recursiveChildren(g as Container, (child) => child.onRemoveFromCanvas());
|
||||
});
|
||||
return super.removeChild(...children);
|
||||
}
|
||||
/**
|
||||
* 添加无交互Child
|
||||
*/
|
||||
addNonInteractiveChild(...obj: DisplayObject[]): void {
|
||||
this.nonInteractiveContainer.addChild(...obj);
|
||||
obj.forEach((g) => {
|
||||
recursiveChildren(g as Container, (child) => child.onAddToCanvas());
|
||||
});
|
||||
}
|
||||
|
||||
removeGraphic(...obj: DisplayObject[]): void {
|
||||
obj.forEach((g) => {
|
||||
recursiveChildren(g as Container, (child) => child.onRemoveFromCanvas());
|
||||
});
|
||||
this.removeChild(...obj);
|
||||
this.nonInteractiveContainer.removeChild(...obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除无交互Child
|
||||
*/
|
||||
removeNonInteractiveChild(...obj: DisplayObject[]): void {
|
||||
obj.forEach((g) => {
|
||||
recursiveChildren(g as Container, (child) => child.onRemoveFromCanvas());
|
||||
});
|
||||
this.nonInteractiveContainer.removeChild(...obj);
|
||||
}
|
||||
|
||||
addAssistantAppends(...appends: DisplayObject[]): void {
|
||||
this.assistantAppendContainer.addChild(...appends);
|
||||
appends.forEach((g) => {
|
||||
recursiveChildren(g as Container, (child) => child.onAddToCanvas());
|
||||
});
|
||||
}
|
||||
removeAssistantAppends(...appends: DisplayObject[]): void {
|
||||
appends.forEach((g) => {
|
||||
recursiveChildren(g as Container, (child) => child.onAddToCanvas());
|
||||
});
|
||||
this.assistantAppendContainer.removeChild(...appends);
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂停所有可交互对象
|
||||
*/
|
||||
pauseInteractiveChildren() {
|
||||
this.interactiveChildren = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复所有可交互对象
|
||||
*/
|
||||
resumeInteractiveChildren() {
|
||||
this.interactiveChildren = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 选中改变事件
|
||||
*/
|
||||
export class SelectedChangeEvent {
|
||||
graphic: JlGraphic;
|
||||
select: boolean;
|
||||
|
||||
constructor(graphic: JlGraphic, select: boolean) {
|
||||
this.graphic = graphic;
|
||||
this.select = select;
|
||||
}
|
||||
}
|
||||
|
||||
export interface GraphicAppEvents extends GlobalMixins.GraphicAppEvents {
|
||||
graphicstored: [graphic: JlGraphic];
|
||||
graphicdeleted: [graphic: JlGraphic];
|
||||
loadfinish: [];
|
||||
'interaction-plugin-resume': [activeTool: InteractionPlugin]; // 交互插件启用
|
||||
'interaction-plugin-pause': [activeTool: InteractionPlugin]; // 交互插件停止
|
||||
'options-update': [options: GraphicAppOptions]; // 配置更新
|
||||
graphicselectedchange: [graphic: JlGraphic, selected: boolean];
|
||||
graphicchildselectedchange: [
|
||||
graphic: JlGraphic,
|
||||
child: DisplayObject,
|
||||
selected: boolean
|
||||
];
|
||||
scaleend: [obj: DisplayObject];
|
||||
dragstart: [event: GraphicDragEvent];
|
||||
dragmove: [event: GraphicDragEvent];
|
||||
dragend: [event: GraphicDragEvent];
|
||||
destroy: [app: GraphicApp];
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形App构造参数
|
||||
*/
|
||||
export interface IGraphicAppConfig {
|
||||
/**
|
||||
* 交互类型配置
|
||||
*/
|
||||
interactiveTypeOptions?: IInteractiveGraphicOptions;
|
||||
/**
|
||||
* 最大保存的操作记录数,默认100,越大越占用内存资源
|
||||
*/
|
||||
maxOperationRecords?: number;
|
||||
/**
|
||||
* 通用鼠标工具选项
|
||||
*/
|
||||
mouseToolOptions?: IMouseToolOptions;
|
||||
/**
|
||||
* 可吸附位置列表
|
||||
*/
|
||||
absorbablePositions?: AbsorbablePosition[];
|
||||
/**
|
||||
* 超出屏幕显示范围是否剪裁,默认true
|
||||
*/
|
||||
cullable?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形添加到容器选项
|
||||
*/
|
||||
export interface IInteractiveGraphicOptions {
|
||||
/**
|
||||
* 包含添加到可交互容器的图形类型,和Excludes同时只能存在一个
|
||||
*/
|
||||
interactiveGraphicTypeIncludes?: string[];
|
||||
/**
|
||||
* 不包含添加到可交互容器的图形类型,和Includes同时只能存在一个
|
||||
*/
|
||||
interactiveGraphicTypeExcludes?: string[];
|
||||
}
|
||||
|
||||
export type GraphicAppOptions = IGraphicAppConfig;
|
||||
|
||||
/**
|
||||
* 图形app基类
|
||||
*/
|
||||
export class GraphicApp extends EventEmitter<GraphicAppEvents> {
|
||||
private graphicStore: GraphicStore;
|
||||
_options?: GraphicAppOptions;
|
||||
dom: HTMLElement;
|
||||
app: Application; // Pixi 渲染器
|
||||
viewport: Viewport; // 视口
|
||||
canvas: JlCanvas; // 画布
|
||||
interactiveTypeOptions: IInteractiveGraphicOptions;
|
||||
|
||||
graphicTemplateMap: Map<string, GraphicTemplate> = new Map<
|
||||
string,
|
||||
GraphicTemplate
|
||||
>(); // 图形对象模板
|
||||
|
||||
opRecord: OperationRecord; // 操作记录
|
||||
|
||||
keyboardPlugin: JlGraphicAppKeyboardPlugin; // 键盘操作处理插件
|
||||
graphicCopyPlugin: GraphicCopyPlugin; // 图形复制操作插件
|
||||
menuPlugin: ContextMenuPlugin; // 菜单插件
|
||||
|
||||
interactionPluginMap: Map<string, InteractionPlugin> = new Map<
|
||||
string,
|
||||
InteractionPlugin
|
||||
>(); // 交互插件
|
||||
|
||||
wsMsgBroker?: AppWsMsgBroker;
|
||||
|
||||
constructor(dom: HTMLElement) {
|
||||
super();
|
||||
document.body.style.overflow = 'hidden';
|
||||
// console.log('创建图形App')
|
||||
this.dom = dom;
|
||||
this.graphicStore = new GraphicStore(this);
|
||||
/**
|
||||
* 默认都添加为非交互
|
||||
*/
|
||||
this.interactiveTypeOptions = { interactiveGraphicTypeIncludes: [] };
|
||||
// 创建pixi渲染app
|
||||
this.app = new Application({
|
||||
width: dom.clientWidth,
|
||||
height: dom.clientHeight,
|
||||
antialias: true,
|
||||
resizeTo: window,
|
||||
});
|
||||
dom.appendChild(this.app.view as unknown as Node);
|
||||
|
||||
// 创建画布
|
||||
this.canvas = new JlCanvas(this);
|
||||
this.canvas.name = AppConsts.canvasname;
|
||||
// 创建相机
|
||||
this.viewport = new Viewport({
|
||||
screenWidth: window.innerWidth,
|
||||
screenHeight: window.innerHeight,
|
||||
worldWidth: this.canvas._properties.width,
|
||||
worldHeight: this.canvas._properties.height,
|
||||
// divWheel: dom,
|
||||
passiveWheel: true,
|
||||
events: this.app.renderer.events,
|
||||
disableOnContextMenu: true,
|
||||
});
|
||||
// 设置视口操作方式
|
||||
this.viewport
|
||||
.wheel({
|
||||
percent: 1,
|
||||
})
|
||||
.pinch()
|
||||
.clampZoom({
|
||||
minScale: 0.1,
|
||||
maxScale: 8,
|
||||
})
|
||||
.clamp({
|
||||
direction: 'all',
|
||||
});
|
||||
this.viewport.name = AppConsts.viewportname;
|
||||
this.viewport.interactiveChildren = true;
|
||||
// 添加视口到渲染器舞台
|
||||
this.app.stage.addChild(this.viewport);
|
||||
// 将画布置于视口
|
||||
this.viewport.addChild(this.canvas);
|
||||
|
||||
// 监听并通知缩放变化事件
|
||||
this.viewport.on('zoomed-end', () => {
|
||||
this.emit('scaleend', this.viewport);
|
||||
});
|
||||
|
||||
this.canvas.on(CanvasEvent.canvassizechange, () => {
|
||||
this.updateViewport();
|
||||
});
|
||||
|
||||
this.opRecord = new OperationRecord();
|
||||
|
||||
// 绑定键盘监听
|
||||
this.keyboardPlugin = new JlGraphicAppKeyboardPlugin(this);
|
||||
this.graphicCopyPlugin = new GraphicCopyPlugin(this);
|
||||
this.menuPlugin = new ContextMenuPlugin(this);
|
||||
|
||||
// 添加通用交互插件
|
||||
const tool = new CommonMouseTool(this);
|
||||
tool.resume();
|
||||
// 视口移动插件
|
||||
ViewportMovePlugin.new(this);
|
||||
}
|
||||
|
||||
setOptions(options: GraphicAppOptions) {
|
||||
// console.log('更新选项', options);
|
||||
if (this._options) {
|
||||
this._options = Object.assign(this._options, options);
|
||||
} else {
|
||||
this._options = options;
|
||||
}
|
||||
if (options.interactiveTypeOptions) {
|
||||
// 更新交互类型配置
|
||||
this.interactiveTypeOptions = options.interactiveTypeOptions;
|
||||
}
|
||||
if (options.maxOperationRecords && options.maxOperationRecords > 0) {
|
||||
this.opRecord.setMaxLen(options.maxOperationRecords);
|
||||
}
|
||||
this.emit('options-update', options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册图形对象模板
|
||||
* @param graphicTemplates
|
||||
*/
|
||||
registerGraphicTemplates(...graphicTemplates: GraphicTemplate[]) {
|
||||
graphicTemplates.forEach((graphicTemplate) => {
|
||||
this.graphicTemplateMap.set(graphicTemplate.type, graphicTemplate);
|
||||
// 加载资源
|
||||
graphicTemplate.loadAsserts();
|
||||
});
|
||||
}
|
||||
|
||||
getGraphicTemplatesByType<GT extends GraphicTemplate>(type: string): GT {
|
||||
const template = this.graphicTemplateMap.get(type);
|
||||
if (!template) {
|
||||
throw new Error(`不存在type=${type}的图形对象模板`);
|
||||
}
|
||||
return template as GT;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使能websocket Stomp通信
|
||||
*/
|
||||
enableWsStomp(options: StompCliOption) {
|
||||
StompCli.new(options);
|
||||
this.wsMsgBroker = new AppWsMsgBroker(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅websocket消息
|
||||
*/
|
||||
subscribe(sub: AppStateSubscription) {
|
||||
if (this.wsMsgBroker) {
|
||||
// console.log('APP订阅', sub)
|
||||
this.wsMsgBroker.subscribe(sub);
|
||||
} else {
|
||||
throw new Error('请先打开StompClient, 执行app.enableWebsocket()');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 取消websocket订阅
|
||||
*/
|
||||
unsubscribe(destination: string) {
|
||||
if (this.wsMsgBroker) {
|
||||
this.wsMsgBroker.unsbuscribe(destination);
|
||||
} else {
|
||||
throw new Error('请先执行enableWebsocket');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理websocket状态
|
||||
* @param graphicStates
|
||||
*/
|
||||
handleGraphicStates(graphicStates: GraphicState[]) {
|
||||
graphicStates.forEach((state) => {
|
||||
const list = this.queryStore.queryByIdOrCode(state.code);
|
||||
if (list.length == 0) {
|
||||
const template = this.getGraphicTemplatesByType(state.graphicType);
|
||||
const g = template.new();
|
||||
g.loadState(state);
|
||||
this.addGraphics(g);
|
||||
} else {
|
||||
list.forEach((g) => {
|
||||
g.updateStates(state);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加键盘监听器,如果是相同的按键,新注册的会覆盖旧的,当移除新的时,旧的自动生效
|
||||
* @param keyListeners
|
||||
*/
|
||||
addKeyboardListener(...keyListeners: KeyListener[]) {
|
||||
keyListeners.forEach((keyListener) =>
|
||||
this.keyboardPlugin.addKeyListener(keyListener)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除键盘监听器
|
||||
* @param keyListeners
|
||||
*/
|
||||
removeKeyboardListener(...keyListeners: KeyListener[]) {
|
||||
keyListeners.forEach((keyListener) =>
|
||||
this.keyboardPlugin.removeKeyListener(keyListener)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* dom尺寸变更处理
|
||||
* @param width canvas容器的宽
|
||||
* @param height canvas容器的高
|
||||
*/
|
||||
onDomResize(width: number, height: number) {
|
||||
this.updateViewport(width, height);
|
||||
}
|
||||
|
||||
public get queryStore(): GraphicQueryStore {
|
||||
return this.graphicStore;
|
||||
}
|
||||
|
||||
public get selectedGraphics(): JlGraphic[] {
|
||||
return this.queryStore.getAllGraphics().filter((g) => g.selected);
|
||||
}
|
||||
|
||||
fireSelectedChange(graphic: JlGraphic) {
|
||||
// console.log('通知选中变化', this.selecteds)
|
||||
const select = graphic.selected;
|
||||
this.emit('graphicselectedchange', graphic, select);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新选中
|
||||
*/
|
||||
updateSelected(...graphics: JlGraphic[]) {
|
||||
this.selectedGraphics.forEach((graphic) => {
|
||||
if (graphics.findIndex((g) => g.id === graphic.id) >= 0) {
|
||||
return;
|
||||
}
|
||||
if (graphic.selected) {
|
||||
graphic.updateSelected(false);
|
||||
this.fireSelectedChange(graphic);
|
||||
}
|
||||
});
|
||||
graphics.forEach((graphic) => {
|
||||
if (graphic.updateSelected(true)) {
|
||||
this.fireSelectedChange(graphic);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新画布
|
||||
* @param param
|
||||
*/
|
||||
updateCanvas(param: ICanvasProperties) {
|
||||
this.canvas.update(param);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载图形,GraphicApp默认添加到无交互容器,DrawApp默认添加到交互容器,如需定制,提供选项配置
|
||||
* @param protos
|
||||
* @param options 添加到可交互/不可交互容器选项配置
|
||||
*/
|
||||
loadGraphic(protos: GraphicData[]) {
|
||||
// console.log('开始加载proto数据', protos);
|
||||
// 加载数据到图形存储
|
||||
protos.forEach((proto) => {
|
||||
const template = this.getGraphicTemplatesByType(proto.graphicType);
|
||||
const g = template.new();
|
||||
g.loadData(proto);
|
||||
this.addGraphics(g);
|
||||
});
|
||||
// 加载数据关系
|
||||
this.graphicStore.getAllGraphics().forEach((g) => g.loadRealtions());
|
||||
// 更新id生成器
|
||||
const max =
|
||||
this.graphicStore
|
||||
.getAllGraphics()
|
||||
.filter((g) => !isNaN(parseInt(g.id)))
|
||||
.map((g) => parseInt(g.id))
|
||||
.sort((a, b) => a - b)
|
||||
.pop() ?? 0;
|
||||
// console.log('最大值', max)
|
||||
GraphicIdGenerator.initSerial(max);
|
||||
// 加载完成通知
|
||||
this.emit('loadfinish');
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加图形前处理
|
||||
* @param graphic
|
||||
*/
|
||||
beforeGraphicStore(graphic: JlGraphic): void {
|
||||
const options = this.interactiveTypeOptions;
|
||||
// 默认无交互
|
||||
graphic.eventMode = 'auto';
|
||||
if (options) {
|
||||
if (
|
||||
options.interactiveGraphicTypeIncludes &&
|
||||
options.interactiveGraphicTypeIncludes.findIndex(
|
||||
(type) => type === graphic.type
|
||||
) >= 0
|
||||
) {
|
||||
graphic.eventMode = 'static';
|
||||
} else if (
|
||||
options.interactiveGraphicTypeExcludes &&
|
||||
options.interactiveGraphicTypeExcludes.findIndex(
|
||||
(type) => type === graphic.type
|
||||
) < 0
|
||||
) {
|
||||
graphic.eventMode = 'static';
|
||||
}
|
||||
}
|
||||
}
|
||||
private doAddGraphics(graphic: JlGraphic): void {
|
||||
this.beforeGraphicStore(graphic);
|
||||
if (this.graphicStore.storeGraphics(graphic)) {
|
||||
// cullable,默认设置剪裁,如果图形包围框不在屏幕内,则不渲染,增加效率用
|
||||
if (!this._options || this._options.cullable !== false) {
|
||||
graphic.cullable = true;
|
||||
}
|
||||
if (graphic.eventMode == 'static' || graphic.eventMode == 'dynamic') {
|
||||
// 添加为可交互
|
||||
// console.log(`type=${graphic.type}的图形添加到交互容器`);
|
||||
this.canvas.addChild(graphic);
|
||||
} else {
|
||||
// 添加到不可交互容器
|
||||
// console.log(`type=${graphic.type}的图形添加到无交互容器`);
|
||||
this.canvas.addNonInteractiveChild(graphic);
|
||||
}
|
||||
graphic.repaint();
|
||||
this.emit('graphicstored', graphic);
|
||||
graphic.on('childselected', (child) => {
|
||||
this.emit('graphicchildselectedchange', graphic, child, true);
|
||||
});
|
||||
graphic.on('childunselected', (child) => {
|
||||
this.emit('graphicchildselectedchange', graphic, child, false);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private doDeleteGraphics(graphic: JlGraphic): void {
|
||||
// graphic可能是vue的Proxy对象,会导致canvas删除时因不是同一个对象而无法从画布移除
|
||||
const g = this.graphicStore.deleteGraphics(graphic);
|
||||
if (g) {
|
||||
// 从画布移除
|
||||
this.canvas.removeGraphic(g);
|
||||
// 清除选中
|
||||
if (g.updateSelected(false)) {
|
||||
this.fireSelectedChange(g);
|
||||
}
|
||||
// 对象删除处理
|
||||
g.onDelete();
|
||||
this.emit('graphicdeleted', g);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 存储图形
|
||||
* @param graphics 图形对象
|
||||
*/
|
||||
addGraphics(...graphics: JlGraphic[]) {
|
||||
graphics.forEach((g) => this.doAddGraphics(g));
|
||||
}
|
||||
/**
|
||||
* 删除图形
|
||||
* @param graphics 图形对象
|
||||
*/
|
||||
deleteGraphics(...graphics: JlGraphic[]) {
|
||||
graphics.forEach((g) => this.doDeleteGraphics(g));
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测并构建关系
|
||||
*/
|
||||
detectRelations(): void {
|
||||
this.graphicStore.getAllGraphics().forEach((g) => g.buildRelation());
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换操作坐标点为画布坐标点
|
||||
* @param e 事件
|
||||
* @returns 画布坐标点
|
||||
*/
|
||||
toCanvasCoordinates(p: Point): Point {
|
||||
return this.viewport.toWorld(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前缩放倍率
|
||||
*/
|
||||
getViewportScaled(): number {
|
||||
return this.viewport.scaled;
|
||||
}
|
||||
/**
|
||||
* 视口中心坐标
|
||||
* @returns
|
||||
*/
|
||||
getViewportCenter(): Point {
|
||||
return this.viewport.center;
|
||||
}
|
||||
/**
|
||||
* 获取视口角落坐标
|
||||
* @returns
|
||||
*/
|
||||
getViewportCorner(): Point {
|
||||
return this.viewport.corner;
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册交互插件,会替换旧的
|
||||
*/
|
||||
registerInteractionPlugin(...plugins: InteractionPlugin[]): void {
|
||||
plugins.forEach((plugin) => {
|
||||
const old = this.interactionPluginMap.get(plugin.name);
|
||||
if (old) {
|
||||
console.warn(`已经存在name=${plugin.name}的交互插件,忽略此插件注册!`);
|
||||
return;
|
||||
}
|
||||
this.interactionPluginMap.set(plugin.name, plugin);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据名称获取交互插件
|
||||
* @param name
|
||||
* @returns
|
||||
*/
|
||||
interactionPlugin<P = InteractionPlugin>(name: string): P {
|
||||
const plugin = this.interactionPluginMap.get(name);
|
||||
if (!plugin) {
|
||||
throw new Error(`未找到name=${name}的交互插件`);
|
||||
}
|
||||
return plugin as P;
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止应用交互插件
|
||||
*/
|
||||
pauseAppInteractionPlugins(): void {
|
||||
this.interactionPluginMap.forEach((plugin) => {
|
||||
if (plugin.isActive() && plugin._type === InteractionPluginType.App) {
|
||||
this.doPauseInteractionPlugin(plugin);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private doPauseInteractionPlugin(plugin?: InteractionPlugin): void {
|
||||
if (plugin && plugin.isActive()) {
|
||||
plugin.pause();
|
||||
this.emit('interaction-plugin-pause', plugin);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除交互插件
|
||||
*/
|
||||
removeInteractionPlugin(plugin: InteractionPlugin) {
|
||||
this.interactionPluginMap.delete(plugin.name);
|
||||
}
|
||||
|
||||
private updateViewport(domWidth?: number, domHeight?: number): void {
|
||||
let screenWidth = this.viewport.screenWidth;
|
||||
let screenHeight = this.viewport.screenHeight;
|
||||
if (domWidth) {
|
||||
screenWidth = domWidth;
|
||||
}
|
||||
if (domHeight) {
|
||||
screenHeight = domHeight;
|
||||
}
|
||||
const worldWidth = this.canvas._properties.width;
|
||||
const worldHeight = this.canvas._properties.height;
|
||||
this.viewport.resize(screenWidth, screenHeight, worldWidth, worldHeight);
|
||||
if (this.viewport.OOB().right) {
|
||||
this.viewport.right = this.viewport.right + 1;
|
||||
} else if (this.viewport.OOB().left) {
|
||||
this.viewport.left = this.viewport.left - 1;
|
||||
} else if (this.viewport.OOB().top) {
|
||||
this.viewport.top = this.viewport.top - 1;
|
||||
} else if (this.viewport.OOB().bottom) {
|
||||
this.viewport.bottom = this.viewport.bottom + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使图形居中显示(所有图形的外包围盒)
|
||||
*/
|
||||
makeGraphicCenterShow(...group: JlGraphic[]): void {
|
||||
if (group.length > 0) {
|
||||
const bounds0 = group[0].getBounds();
|
||||
let lx = bounds0.x;
|
||||
let ly = bounds0.y;
|
||||
let rx = bounds0.x + bounds0.width;
|
||||
let ry = bounds0.y + bounds0.height;
|
||||
if (group.length > 1) {
|
||||
for (let i = 1; i < group.length; i++) {
|
||||
const g = group[i];
|
||||
const bound = g.getBounds();
|
||||
if (bound.x < lx) {
|
||||
lx = bound.x;
|
||||
}
|
||||
if (bound.y < ly) {
|
||||
ly = bound.y;
|
||||
}
|
||||
const brx = bound.x + bound.width;
|
||||
if (brx > rx) {
|
||||
rx = brx;
|
||||
}
|
||||
const bry = bound.y + bound.height;
|
||||
if (bry > ry) {
|
||||
ry = bry;
|
||||
}
|
||||
}
|
||||
}
|
||||
const { x, y } = getRectangleCenter(
|
||||
new Rectangle(lx, ly, rx - lx, ry - ly)
|
||||
);
|
||||
const p = this.viewport.toWorld(x, y);
|
||||
this.viewport.moveCenter(p.x, p.y);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 销毁
|
||||
*/
|
||||
destroy(): void {
|
||||
console.log('销毁图形 APP');
|
||||
this.emit('destroy', this);
|
||||
if (this.wsMsgBroker) {
|
||||
this.wsMsgBroker.close();
|
||||
if (!StompCli.hasAppMsgBroker()) {
|
||||
// 如果没有其他消息代理,关闭websocket Stomp客户端
|
||||
StompCli.close();
|
||||
}
|
||||
}
|
||||
this.interactionPluginMap.forEach((plugin) => {
|
||||
plugin.destroy();
|
||||
});
|
||||
this.canvas.destroy(true);
|
||||
this.viewport.destroy();
|
||||
this.app.destroy(true, true);
|
||||
document.body.style.overflow = 'auto';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
export * from './JlGraphicApp';
|
||||
export * from './JlDrawApp';
|
|
@ -0,0 +1,185 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { GraphicApp } from '../app/JlGraphicApp';
|
||||
import { JlGraphic } from './JlGraphic';
|
||||
|
||||
/**
|
||||
* 图形关系数据
|
||||
*/
|
||||
export class GraphicRelationParam {
|
||||
g: JlGraphic;
|
||||
param: any;
|
||||
constructor(g: JlGraphic, param: any = null) {
|
||||
this.g = g;
|
||||
this.param = param;
|
||||
}
|
||||
isTheGraphic(g: JlGraphic): boolean {
|
||||
return this.g.id === g.id;
|
||||
}
|
||||
getGraphic<G extends JlGraphic>(): G {
|
||||
return this.g as G;
|
||||
}
|
||||
getParam<P>(): P {
|
||||
return this.param as P;
|
||||
}
|
||||
equals(other: GraphicRelationParam): boolean {
|
||||
return this.isTheGraphic(other.g) && this.param === other.param;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 图形关系
|
||||
*/
|
||||
export class GraphicRelation {
|
||||
rp1: GraphicRelationParam;
|
||||
rp2: GraphicRelationParam;
|
||||
constructor(rp1: GraphicRelationParam, rp2: GraphicRelationParam) {
|
||||
this.rp1 = rp1;
|
||||
this.rp2 = rp2;
|
||||
}
|
||||
|
||||
contains(g: JlGraphic): boolean {
|
||||
return this.rp1.isTheGraphic(g) || this.rp2.isTheGraphic(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取给定图形的关系参数
|
||||
* @param g
|
||||
* @returns
|
||||
*/
|
||||
getRelationParam(g: JlGraphic): GraphicRelationParam {
|
||||
if (!this.contains(g)) {
|
||||
throw new Error(
|
||||
`图形关系${this.rp1.g.id}-${this.rp2.g.id}中不包含给定图形${g.id}`
|
||||
);
|
||||
}
|
||||
if (this.rp1.isTheGraphic(g)) {
|
||||
return this.rp1;
|
||||
} else {
|
||||
return this.rp2;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取关联的另一个图形的关系参数
|
||||
* @param g
|
||||
* @returns
|
||||
*/
|
||||
getOtherRelationParam(g: JlGraphic): GraphicRelationParam {
|
||||
if (!this.contains(g)) {
|
||||
throw new Error(
|
||||
`图形关系${this.rp1.g.id}-${this.rp2.g.id}中不包含给定图形${g.id}`
|
||||
);
|
||||
}
|
||||
if (this.rp1.isTheGraphic(g)) {
|
||||
return this.rp2;
|
||||
} else {
|
||||
return this.rp1;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取关联的另一个图形对象
|
||||
* @param g
|
||||
* @returns graphic
|
||||
*/
|
||||
getOtherGraphic<G extends JlGraphic>(g: JlGraphic): G {
|
||||
return this.getOtherRelationParam(g).g as G;
|
||||
}
|
||||
|
||||
equals(orp1: GraphicRelationParam, orp2: GraphicRelationParam): boolean {
|
||||
if (this.rp1.isTheGraphic(orp1.g)) {
|
||||
return this.rp1.equals(orp1) && this.rp2.equals(orp2);
|
||||
} else if (this.rp1.isTheGraphic(orp2.g)) {
|
||||
return this.rp1.equals(orp2) && this.rp2.equals(orp1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
isEqualOther(other: GraphicRelation): boolean {
|
||||
return this.equals(other.rp1, other.rp2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形关系管理
|
||||
*/
|
||||
export class RelationManage {
|
||||
app: GraphicApp;
|
||||
relations: GraphicRelation[] = [];
|
||||
constructor(app: GraphicApp) {
|
||||
this.app = app;
|
||||
}
|
||||
|
||||
isContainsRelation(
|
||||
rp1: GraphicRelationParam,
|
||||
rp2: GraphicRelationParam
|
||||
): boolean {
|
||||
const relation = this.relations.find((relation) =>
|
||||
relation.equals(rp1, rp2)
|
||||
);
|
||||
return !!relation;
|
||||
}
|
||||
addRelation(
|
||||
rp1: GraphicRelationParam | JlGraphic,
|
||||
rp2: GraphicRelationParam | JlGraphic
|
||||
): void {
|
||||
if (!(rp1 instanceof GraphicRelationParam)) {
|
||||
rp1 = new GraphicRelationParam(rp1);
|
||||
}
|
||||
if (!(rp2 instanceof GraphicRelationParam)) {
|
||||
rp2 = new GraphicRelationParam(rp2);
|
||||
}
|
||||
if (!this.isContainsRelation(rp1, rp2)) {
|
||||
const relation = new GraphicRelation(rp1, rp2);
|
||||
this.relations.push(relation);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图形的所有关系
|
||||
* @param g
|
||||
* @returns
|
||||
*/
|
||||
getRelationsOfGraphic(g: JlGraphic): GraphicRelation[] {
|
||||
return this.relations.filter((rl) => rl.contains(g));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定图形的指定关系图形类型的所有关系
|
||||
* @param g 指定图形
|
||||
* @param type 关联图形的类型
|
||||
* @returns
|
||||
*/
|
||||
getRelationsOfGraphicAndOtherType(
|
||||
g: JlGraphic,
|
||||
type: string
|
||||
): GraphicRelation[] {
|
||||
return this.relations.filter(
|
||||
(rl) => rl.contains(g) && rl.getOtherGraphic(g).type === type
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除关系
|
||||
* @param relation
|
||||
*/
|
||||
private deleteRelation(relation: GraphicRelation): void {
|
||||
const index = this.relations.findIndex((rl) => rl.isEqualOther(relation));
|
||||
if (index >= 0) {
|
||||
this.relations.splice(index, 1);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 删除指定图形的所有关系
|
||||
* @param g
|
||||
*/
|
||||
deleteRelationOfGraphic(g: JlGraphic): void {
|
||||
const relations = this.getRelationsOfGraphic(g);
|
||||
relations.forEach((rl) => this.deleteRelation(rl));
|
||||
}
|
||||
/**
|
||||
* 删除指定图形的所有关系
|
||||
* @param g
|
||||
*/
|
||||
deleteRelationOfGraphicAndOtherType(g: JlGraphic, type: string): void {
|
||||
const relations = this.getRelationsOfGraphicAndOtherType(g, type);
|
||||
relations.forEach((rl) => this.deleteRelation(rl));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,185 @@
|
|||
import { GraphicApp } from '../app/JlGraphicApp';
|
||||
import { RelationManage } from './GraphicRelation';
|
||||
import { JlGraphic } from './JlGraphic';
|
||||
|
||||
export interface GraphicQueryStore {
|
||||
/**
|
||||
* 获取所有图形对象
|
||||
*/
|
||||
getAllGraphics(): JlGraphic[];
|
||||
/**
|
||||
* 根据id获取图形
|
||||
*/
|
||||
queryById<T extends JlGraphic>(id: string): T;
|
||||
/**
|
||||
* 根据id模糊查询图形
|
||||
* @param id
|
||||
*/
|
||||
queryByIdAmbiguous(id: string): JlGraphic[];
|
||||
|
||||
/**
|
||||
* 根据类型获取图形列表
|
||||
*/
|
||||
queryByType<T extends JlGraphic>(type: string): T[];
|
||||
/**
|
||||
* 根据code查询
|
||||
* @param code
|
||||
*/
|
||||
queryByCode(code: string): JlGraphic[] | undefined;
|
||||
/**
|
||||
* 根据code模糊查询图形
|
||||
* @param code
|
||||
* @param type
|
||||
*/
|
||||
queryByCodeAmbiguous(code: string): JlGraphic[];
|
||||
/**
|
||||
* 根据id或code查询图形
|
||||
* @param v
|
||||
*/
|
||||
queryByIdOrCode(v: string): JlGraphic[];
|
||||
/**
|
||||
* 根据code和类型获取图形
|
||||
* @param code
|
||||
* @param type
|
||||
*/
|
||||
queryByCodeAndType<T extends JlGraphic>(
|
||||
code: string,
|
||||
type: string
|
||||
): T | undefined;
|
||||
/**
|
||||
* 根据code和类型模糊查询图形
|
||||
* @param code
|
||||
* @param type
|
||||
*/
|
||||
queryByCodeAndTypeAmbiguous<T extends JlGraphic>(
|
||||
code: string,
|
||||
type: string
|
||||
): T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形存储
|
||||
*/
|
||||
export class GraphicStore implements GraphicQueryStore {
|
||||
app: GraphicApp;
|
||||
store: Map<string, JlGraphic>;
|
||||
relationManage: RelationManage;
|
||||
constructor(app: GraphicApp) {
|
||||
this.app = app;
|
||||
this.store = new Map<string, JlGraphic>();
|
||||
this.relationManage = new RelationManage(app);
|
||||
}
|
||||
/**
|
||||
* 获取所有图形对象
|
||||
*/
|
||||
getAllGraphics(): JlGraphic[] {
|
||||
return [...this.store.values()];
|
||||
}
|
||||
queryById<T extends JlGraphic>(id: string): T {
|
||||
const graphic = this.store.get(id) as T;
|
||||
if (!graphic) throw Error(`未找到id为 [${id}] 的图形.`);
|
||||
return this.store.get(id) as T;
|
||||
}
|
||||
queryByIdAmbiguous(id: string): JlGraphic[] {
|
||||
const list: JlGraphic[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.id.search(id) >= 0) {
|
||||
list.push(g);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByType<T extends JlGraphic>(type: string): T[] {
|
||||
const list: T[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.type === type) {
|
||||
list.push(g as T);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByCode(code: string): JlGraphic[] | undefined {
|
||||
const list: JlGraphic[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.code === code) {
|
||||
list.push(g);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByCodeAmbiguous(code: string): JlGraphic[] {
|
||||
const list: JlGraphic[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.code.search(code) >= 0) {
|
||||
list.push(g);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByIdOrCode(s: string): JlGraphic[] {
|
||||
const list: JlGraphic[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.isIdOrCode(s)) {
|
||||
list.push(g);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByCodeAndType<T extends JlGraphic>(
|
||||
code: string,
|
||||
type: string
|
||||
): T | undefined {
|
||||
for (const item of this.store.values()) {
|
||||
if (item.code === code && item.type === type) {
|
||||
return item as T;
|
||||
}
|
||||
}
|
||||
}
|
||||
queryByCodeAndTypeAmbiguous<T extends JlGraphic>(
|
||||
code: string,
|
||||
type: string
|
||||
): T[] {
|
||||
const list: T[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.type === type && g.code.search(code) >= 0) {
|
||||
list.push(g as T);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 存储图形对象
|
||||
* @param graphics 要存储的图形
|
||||
*/
|
||||
storeGraphics(graphic: JlGraphic): boolean {
|
||||
if (!graphic.id || graphic.id.trim() === '') {
|
||||
throw new Error(`存储图形对象异常: id为空, ${graphic}`);
|
||||
}
|
||||
if (this.store.has(graphic.id)) {
|
||||
// 已经存在
|
||||
const exist = this.store.get(graphic.id);
|
||||
console.error(`已经存在id=${graphic.id}的设备${exist}`);
|
||||
return false;
|
||||
} else {
|
||||
this.store.set(graphic.id, graphic);
|
||||
graphic.queryStore = this;
|
||||
graphic.relationManage = this.relationManage;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 删除图形
|
||||
* @param graph 要删除的图形
|
||||
*/
|
||||
deleteGraphics(graphic: JlGraphic): JlGraphic | undefined {
|
||||
const id = graphic.id;
|
||||
const remove = this.store.get(id);
|
||||
if (remove) {
|
||||
this.store.delete(id);
|
||||
// 删除图形关系
|
||||
this.relationManage.deleteRelationOfGraphic(remove);
|
||||
}
|
||||
return remove;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
/**
|
||||
* ID生成器
|
||||
*/
|
||||
export class IdGenerator {
|
||||
serial = 0;
|
||||
type: string;
|
||||
|
||||
constructor(type: string) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
next(): string {
|
||||
++this.serial;
|
||||
// console.log(this.getType() + this.serial)
|
||||
return this.getType() + this.serial;
|
||||
}
|
||||
|
||||
getType(): string {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
initSerial(serial: number): void {
|
||||
// console.log(serial)
|
||||
this.serial = serial;
|
||||
}
|
||||
}
|
||||
|
||||
export const GraphicIdGenerator: IdGenerator = new IdGenerator('');
|
|
@ -0,0 +1,865 @@
|
|||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
/* eslint-disable @typescript-eslint/no-empty-function */
|
||||
import { Viewport } from 'pixi-viewport';
|
||||
import {
|
||||
Container,
|
||||
DisplayObject,
|
||||
Graphics,
|
||||
IPointData,
|
||||
Point,
|
||||
Rectangle,
|
||||
} from 'pixi.js';
|
||||
import { AppConsts, JlCanvas } from '../app';
|
||||
import {
|
||||
convertRectangleToPolygonPoints,
|
||||
recursiveChildren,
|
||||
recursiveFindChild,
|
||||
recursiveFindParent,
|
||||
recursiveParents,
|
||||
} from '../utils';
|
||||
import { GraphicRelation, RelationManage } from './GraphicRelation';
|
||||
import { GraphicQueryStore } from './GraphicStore';
|
||||
import { GraphicIdGenerator } from './IdGenerator';
|
||||
|
||||
//基础图形对象扩展
|
||||
DisplayObject.prototype._selectable = false; //是否可选中
|
||||
DisplayObject.prototype._selected = false;
|
||||
DisplayObject.prototype._childEdit = false;
|
||||
DisplayObject.prototype._transformSave = false;
|
||||
DisplayObject.prototype._assistantAppendMap = null;
|
||||
DisplayObject.prototype._draggable = false;
|
||||
DisplayObject.prototype._dragStartPoint = null;
|
||||
DisplayObject.prototype._scalable = false;
|
||||
DisplayObject.prototype._keepAspectRatio = true;
|
||||
DisplayObject.prototype._rotatable = false;
|
||||
Object.defineProperties(DisplayObject.prototype, {
|
||||
assistantAppendMap: {
|
||||
get() {
|
||||
if (this._assistantAppendMap == null) {
|
||||
this._assistantAppendMap = new Map<string, DisplayObject>();
|
||||
}
|
||||
return this._assistantAppendMap;
|
||||
},
|
||||
},
|
||||
selectable: {
|
||||
get(): boolean {
|
||||
return this._selectable;
|
||||
},
|
||||
set(value: boolean): void {
|
||||
this._selectable = value;
|
||||
},
|
||||
},
|
||||
selected: {
|
||||
get(): boolean {
|
||||
return this._selected;
|
||||
},
|
||||
set(v) {
|
||||
this._selected = v;
|
||||
},
|
||||
},
|
||||
childEdit: {
|
||||
get() {
|
||||
return this._childEdit;
|
||||
},
|
||||
set(v) {
|
||||
this._childEdit = v;
|
||||
},
|
||||
},
|
||||
transformSave: {
|
||||
get() {
|
||||
return this._transformSave;
|
||||
},
|
||||
set(v) {
|
||||
this._transformSave = v;
|
||||
},
|
||||
},
|
||||
draggable: {
|
||||
get(): boolean {
|
||||
return this._draggable;
|
||||
},
|
||||
set(v) {
|
||||
this._draggable = v;
|
||||
},
|
||||
},
|
||||
dragStartPoint: {
|
||||
get() {
|
||||
return this._dragStartPoint;
|
||||
},
|
||||
set(v) {
|
||||
this._dragStartPoint = v;
|
||||
},
|
||||
},
|
||||
scalable: {
|
||||
get() {
|
||||
return this._scalable;
|
||||
},
|
||||
set(v) {
|
||||
this._scalable = v;
|
||||
},
|
||||
},
|
||||
keepAspectRatio: {
|
||||
get(): boolean {
|
||||
return this._keepAspectRatio;
|
||||
},
|
||||
set(v) {
|
||||
this._keepAspectRatio = v;
|
||||
},
|
||||
},
|
||||
rotatable: {
|
||||
get() {
|
||||
return this._rotatable;
|
||||
},
|
||||
set(v) {
|
||||
this._rotatable = v;
|
||||
},
|
||||
},
|
||||
worldAngle: {
|
||||
get() {
|
||||
let angle = this.angle;
|
||||
let parent = this.parent;
|
||||
while (parent != undefined && parent != null) {
|
||||
angle += parent.angle;
|
||||
parent = parent.parent;
|
||||
}
|
||||
angle = angle % 360;
|
||||
if (angle > 180) {
|
||||
angle = angle - 360;
|
||||
}
|
||||
return angle;
|
||||
},
|
||||
},
|
||||
});
|
||||
DisplayObject.prototype.getAllParentScaled =
|
||||
function getAllParentScaled(): Point {
|
||||
const scaled = new Point(1, 1);
|
||||
recursiveParents(this, (parent) => {
|
||||
scaled.x *= parent.scale.x;
|
||||
scaled.y *= parent.scale.y;
|
||||
});
|
||||
return scaled;
|
||||
};
|
||||
DisplayObject.prototype.saveTransform = function saveTransform() {
|
||||
return GraphicTransform.fromObject(this);
|
||||
};
|
||||
DisplayObject.prototype.loadTransform = function loadTransform(
|
||||
transfrom: GraphicTransform
|
||||
) {
|
||||
this.position.copyFrom(transfrom.position);
|
||||
this.scale.copyFrom(transfrom.scale);
|
||||
this.rotation = transfrom.rotation;
|
||||
this.skew.copyFrom(transfrom.skew);
|
||||
};
|
||||
DisplayObject.prototype.isChild = function isChild(
|
||||
obj: DisplayObject
|
||||
): boolean {
|
||||
return recursiveFindChild(this as Container, (child) => child == obj) != null;
|
||||
};
|
||||
DisplayObject.prototype.isParent = function isParent(
|
||||
obj: DisplayObject
|
||||
): boolean {
|
||||
return recursiveFindParent(this, (parent) => parent == obj) != null;
|
||||
};
|
||||
DisplayObject.prototype.isAssistantAppend =
|
||||
function isAssistantAppend(): boolean {
|
||||
return (
|
||||
recursiveFindParent(this, (parent) => {
|
||||
return parent.name === AppConsts.AssistantAppendsName;
|
||||
}) != null
|
||||
);
|
||||
};
|
||||
DisplayObject.prototype.addAssistantAppend = function addAssistantAppend<
|
||||
D extends DisplayObject
|
||||
>(...appends: D[]): void {
|
||||
appends.forEach((append) => {
|
||||
if (append.name == null || append.name.trim() == '') {
|
||||
throw new Error('辅助附加name不能为空');
|
||||
}
|
||||
this.assistantAppendMap.set(append.name, append);
|
||||
this.getCanvas().addAssistantAppends(append);
|
||||
});
|
||||
};
|
||||
DisplayObject.prototype.getAssistantAppend = function getAssistantAppend<
|
||||
D extends DisplayObject
|
||||
>(name: string): D | undefined {
|
||||
return this.assistantAppendMap.get(name) as D;
|
||||
};
|
||||
DisplayObject.prototype.removeAssistantAppend = function removeAssistantAppend(
|
||||
...appends: DisplayObject[]
|
||||
): void {
|
||||
appends.forEach((append) => {
|
||||
if (append.name) {
|
||||
this.removeAssistantAppendByName(append.name);
|
||||
}
|
||||
});
|
||||
};
|
||||
DisplayObject.prototype.removeAssistantAppendByName =
|
||||
function removeAssistantAppendByName(...names: string[]): void {
|
||||
names.forEach((name) => {
|
||||
const append = this.getAssistantAppend(name);
|
||||
if (append) {
|
||||
this.getCanvas().removeAssistantAppends(append);
|
||||
this.assistantAppendMap.delete(name);
|
||||
append.destroy();
|
||||
}
|
||||
});
|
||||
};
|
||||
DisplayObject.prototype.removeAllAssistantAppend =
|
||||
function removeAllAssistantAppend(): void {
|
||||
if (this._assistantAppendMap != null) {
|
||||
this.assistantAppendMap.forEach((append) => {
|
||||
append.getCanvas().removeAssistantAppends(append);
|
||||
});
|
||||
this.assistantAppendMap.clear();
|
||||
}
|
||||
};
|
||||
|
||||
DisplayObject.prototype.isGraphic = function isGraphic() {
|
||||
return Object.hasOwn(this, '__JlGraphic');
|
||||
};
|
||||
DisplayObject.prototype.getGraphic = function getGraphic<
|
||||
G extends JlGraphic
|
||||
>(): G | null {
|
||||
let graphic = this as DisplayObject;
|
||||
while (graphic && !Object.hasOwn(graphic, '__JlGraphic')) {
|
||||
graphic = graphic.parent;
|
||||
}
|
||||
if (graphic) {
|
||||
return graphic as G;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
DisplayObject.prototype.isGraphicChild = function isGraphicChild() {
|
||||
const g = this.getGraphic();
|
||||
return g != null && !this.isAssistantAppend() && g.isChild(this);
|
||||
};
|
||||
DisplayObject.prototype.onAddToCanvas = function onAddToCanvas() {};
|
||||
DisplayObject.prototype.onRemoveFromCanvas = function onRemoveFromCanvas() {};
|
||||
DisplayObject.prototype.isInCanvas = function isInCanvas(): boolean {
|
||||
let graphic = this as DisplayObject;
|
||||
while (graphic && !Object.hasOwn(graphic, '__JlCanvas')) {
|
||||
graphic = graphic.parent;
|
||||
}
|
||||
if (graphic) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
DisplayObject.prototype.getCanvas = function getCanvas() {
|
||||
let graphic = this as DisplayObject;
|
||||
while (graphic && !Object.hasOwn(graphic, '__JlCanvas')) {
|
||||
graphic = graphic.parent;
|
||||
}
|
||||
if (graphic) {
|
||||
return graphic as JlCanvas;
|
||||
}
|
||||
throw new Error(`图形${this.name}不在画布中`);
|
||||
};
|
||||
DisplayObject.prototype.getViewport = function getViewport() {
|
||||
const canvas = this.getCanvas();
|
||||
return canvas.parent as Viewport;
|
||||
};
|
||||
DisplayObject.prototype.getGraphicApp = function getGraphicApp() {
|
||||
const canvas = this.getCanvas();
|
||||
return canvas.app;
|
||||
};
|
||||
DisplayObject.prototype.localToCanvasPoint = function localToCanvasPoint(
|
||||
p: IPointData
|
||||
): Point {
|
||||
return this.getViewport().toWorld(this.toGlobal(p));
|
||||
};
|
||||
DisplayObject.prototype.localToCanvasPoints = function localToCanvasPoints(
|
||||
...points: IPointData[]
|
||||
): Point[] {
|
||||
return points.map((p) => this.localToCanvasPoint(p));
|
||||
};
|
||||
DisplayObject.prototype.canvasToLocalPoint = function canvasToLocalPoint(
|
||||
p: IPointData
|
||||
): Point {
|
||||
return this.toLocal(this.getViewport().toScreen(p));
|
||||
};
|
||||
DisplayObject.prototype.canvasToLocalPoints = function canvasToLocalPoints(
|
||||
...points: IPointData[]
|
||||
): Point[] {
|
||||
return points.map((p) => this.canvasToLocalPoint(p));
|
||||
};
|
||||
DisplayObject.prototype.localToScreenPoint = function localToScreenPoint(
|
||||
p: IPointData
|
||||
): Point {
|
||||
return this.toGlobal(p);
|
||||
};
|
||||
DisplayObject.prototype.localToScreenPoints = function localToScreenPoints(
|
||||
...points: IPointData[]
|
||||
): Point[] {
|
||||
return points.map((p) => this.toGlobal(p));
|
||||
};
|
||||
|
||||
DisplayObject.prototype.localBoundsToCanvasPoints =
|
||||
function localBoundsToCanvasPoints() {
|
||||
const rect = this.getLocalBounds();
|
||||
const pps = convertRectangleToPolygonPoints(rect);
|
||||
return this.localToCanvasPoints(...pps);
|
||||
};
|
||||
|
||||
// 扩展pixijs图形对象,添加自定义绘制贝塞尔曲线,可自定义分段数
|
||||
Graphics.prototype.drawBezierCurve = function drawBezierCurve(
|
||||
p1: IPointData,
|
||||
p2: IPointData,
|
||||
cp1: IPointData,
|
||||
cp2: IPointData,
|
||||
segmentsCount: number
|
||||
): Graphics {
|
||||
const fromX = p1.x;
|
||||
const fromY = p1.y;
|
||||
const n = segmentsCount;
|
||||
let dt = 0;
|
||||
let dt2 = 0;
|
||||
let dt3 = 0;
|
||||
let t2 = 0;
|
||||
let t3 = 0;
|
||||
const cpX = cp1.x;
|
||||
const cpY = cp1.y;
|
||||
const cpX2 = cp2.x;
|
||||
const cpY2 = cp2.y;
|
||||
const toX = p2.x;
|
||||
const toY = p2.y;
|
||||
this.moveTo(p1.x, p1.y);
|
||||
for (let i = 1, j = 0; i <= n; ++i) {
|
||||
j = i / n;
|
||||
dt = 1 - j;
|
||||
dt2 = dt * dt;
|
||||
dt3 = dt2 * dt;
|
||||
t2 = j * j;
|
||||
t3 = t2 * j;
|
||||
const px = dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX;
|
||||
const py = dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY;
|
||||
this.lineTo(px, py);
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
export interface IGraphicTransform {
|
||||
position: IPointData;
|
||||
scale: IPointData;
|
||||
rotation: number;
|
||||
skew: IPointData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形变换数据
|
||||
*/
|
||||
export class GraphicTransform {
|
||||
position: IPointData;
|
||||
scale: IPointData;
|
||||
rotation: number;
|
||||
skew: IPointData;
|
||||
|
||||
constructor(
|
||||
position: IPointData,
|
||||
scale: IPointData,
|
||||
rotation: number,
|
||||
skew: IPointData
|
||||
) {
|
||||
this.position = position;
|
||||
this.scale = scale;
|
||||
this.rotation = rotation;
|
||||
this.skew = skew;
|
||||
}
|
||||
static default(): GraphicTransform {
|
||||
return new GraphicTransform(
|
||||
new Point(0, 0),
|
||||
new Point(1, 1),
|
||||
0,
|
||||
new Point(0, 0)
|
||||
);
|
||||
}
|
||||
static fromObject(obj: DisplayObject): GraphicTransform {
|
||||
return new GraphicTransform(
|
||||
obj.position.clone(),
|
||||
obj.scale.clone(),
|
||||
obj.rotation,
|
||||
obj.skew.clone()
|
||||
);
|
||||
}
|
||||
static from(transform: IGraphicTransform | undefined): GraphicTransform {
|
||||
if (transform) {
|
||||
return new GraphicTransform(
|
||||
new Point(transform.position.x, transform.position.y),
|
||||
new Point(transform.scale.x, transform.scale.y),
|
||||
transform.rotation,
|
||||
new Point(transform.skew.x, transform.skew.y)
|
||||
);
|
||||
}
|
||||
return GraphicTransform.default();
|
||||
}
|
||||
}
|
||||
|
||||
export interface IChildTransform {
|
||||
name: string;
|
||||
transform: IGraphicTransform;
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形子元素变换
|
||||
*/
|
||||
export class ChildTransform {
|
||||
name: string;
|
||||
transform: GraphicTransform;
|
||||
constructor(name: string, transform: GraphicTransform) {
|
||||
this.name = name;
|
||||
this.transform = transform;
|
||||
}
|
||||
static fromChild(child: DisplayObject): ChildTransform {
|
||||
if (
|
||||
child.name == null ||
|
||||
child.name == undefined ||
|
||||
child.name.trim() == ''
|
||||
) {
|
||||
throw new Error(
|
||||
`图形type=${
|
||||
child.getGraphic()?.type
|
||||
}的子元素${child}name为空,但设置为需要保存变换数据`
|
||||
);
|
||||
}
|
||||
return new ChildTransform(child.name, GraphicTransform.fromObject(child));
|
||||
}
|
||||
static from(ct: IChildTransform): ChildTransform {
|
||||
return new ChildTransform(ct.name, GraphicTransform.from(ct.transform));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形数据
|
||||
*/
|
||||
export interface GraphicData {
|
||||
get id(): string; // 图形id
|
||||
set id(v: string);
|
||||
get graphicType(): string; // 图形类型
|
||||
set graphicType(v: string);
|
||||
get transform(): GraphicTransform; //
|
||||
set transform(v: GraphicTransform);
|
||||
get childTransforms(): ChildTransform[] | undefined; //
|
||||
set childTransforms(v: ChildTransform[] | undefined);
|
||||
|
||||
/**
|
||||
* 克隆消息
|
||||
*/
|
||||
clone(): GraphicData;
|
||||
/**
|
||||
* 从给定数据拷贝
|
||||
* @param data
|
||||
*/
|
||||
copyFrom(data: GraphicData): void;
|
||||
/**
|
||||
* 是否相等
|
||||
* @param data
|
||||
*/
|
||||
eq(data: GraphicData): boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形状态
|
||||
*/
|
||||
export interface GraphicState {
|
||||
get code(): string; // 业务标识
|
||||
get graphicType(): string; // 图形类型
|
||||
/**
|
||||
* 克隆消息
|
||||
*/
|
||||
clone(): GraphicState;
|
||||
/**
|
||||
* 从给定数据拷贝
|
||||
* @param data
|
||||
*/
|
||||
copyFrom(data: GraphicState): void;
|
||||
/**
|
||||
* 是否相等
|
||||
* @param data
|
||||
*/
|
||||
eq(data: GraphicState): boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形对象基类
|
||||
*/
|
||||
export abstract class JlGraphic extends Container {
|
||||
readonly __JlGraphic = true as const;
|
||||
readonly type: string; // 图形类型
|
||||
private _id = ''; // 图形的唯一标识,不具有业务意义,唯一,不可重复,可用做图形数据关联。
|
||||
private _code = ''; // 业务编号/名称,用于标识图形对象,具有业务意义
|
||||
_datas?: GraphicData; // 图形数据
|
||||
_states?: GraphicState; // 图形状态数据
|
||||
private _relationManage?: RelationManage; // 图形关系管理
|
||||
private _queryStore?: GraphicQueryStore; // 图形对象查询仓库
|
||||
|
||||
constructor(type: string) {
|
||||
super();
|
||||
this.type = type;
|
||||
this.draggable = false;
|
||||
this.filters;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新选中状态
|
||||
* @param selected
|
||||
* @returns 是否更新
|
||||
*/
|
||||
updateSelected(selected: boolean): boolean {
|
||||
if (this.selected !== selected) {
|
||||
this.selected = selected;
|
||||
this.fireSelected();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
invertSelected() {
|
||||
this.selected = !this.selected;
|
||||
this.fireSelected();
|
||||
}
|
||||
|
||||
fireSelected() {
|
||||
if (this.selected) {
|
||||
this.emit('selected', this);
|
||||
} else {
|
||||
this.exitChildEdit();
|
||||
this.removeAllChildSelected();
|
||||
this.emit('unselected', this);
|
||||
}
|
||||
}
|
||||
|
||||
hasSelectedChilds(): boolean {
|
||||
return (
|
||||
recursiveFindChild(this, (child) => {
|
||||
if (child.selected) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}) != null
|
||||
);
|
||||
}
|
||||
setChildSelected(child: DisplayObject): boolean {
|
||||
if (child.isGraphicChild() && child.selectable) {
|
||||
this.removeAllChildSelected();
|
||||
child.selected = true;
|
||||
this.fireChildSelected(child);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
invertChildSelected(child: DisplayObject): boolean {
|
||||
if (child.isGraphicChild() && child.selectable) {
|
||||
child.selected = !child.selected;
|
||||
this.fireChildSelected(child);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
removeAllChildSelected() {
|
||||
recursiveChildren(this, (child) => {
|
||||
if (child.selected) {
|
||||
child.selected = false;
|
||||
this.fireChildSelected(child);
|
||||
}
|
||||
});
|
||||
}
|
||||
fireChildSelected(child: DisplayObject) {
|
||||
if (child.selected) {
|
||||
this.emit('childselected', child);
|
||||
} else {
|
||||
this.emit('childunselected', child);
|
||||
}
|
||||
}
|
||||
exitChildEdit() {
|
||||
this.childEdit = false;
|
||||
this.removeAllChildSelected();
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否此对象id/code
|
||||
*/
|
||||
isIdOrCode(s: string): boolean {
|
||||
return this.id === s || this.code === s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图形id,如果图形数据对象存在,则返回图形数据对象id
|
||||
*/
|
||||
public get id(): string {
|
||||
if (this._datas) {
|
||||
return this._datas.id;
|
||||
}
|
||||
return this._id;
|
||||
}
|
||||
/**
|
||||
* 设置图形id,如果图形数据存在,则同时设置图形数据id
|
||||
*/
|
||||
public set id(v: string) {
|
||||
this._id = v;
|
||||
if (this._datas) {
|
||||
this._datas.id = v;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取图形业务code,如果业务code在图形数据或图形状态中,则需要重写此方法
|
||||
*/
|
||||
public get code(): string {
|
||||
return this._code;
|
||||
}
|
||||
/**
|
||||
* 设置图形业务code,如果业务code在图形数据或图形状态中,则需要重写此方法
|
||||
*/
|
||||
public set code(v: string) {
|
||||
this._code = v;
|
||||
}
|
||||
|
||||
getDatas<D extends GraphicData>(): D {
|
||||
if (this._datas) {
|
||||
return this._datas as D;
|
||||
}
|
||||
throw new Error(`id=${this.id},type=${this.type}的图形没有数据`);
|
||||
}
|
||||
|
||||
getStates<S extends GraphicState>(): S {
|
||||
if (this._states) {
|
||||
return this._states as S;
|
||||
}
|
||||
throw new Error(`id=${this.id},type=${this.type}的的图形没有状态`);
|
||||
}
|
||||
|
||||
public get queryStore(): GraphicQueryStore {
|
||||
if (this._queryStore) {
|
||||
return this._queryStore;
|
||||
}
|
||||
throw new Error(`type=${this.type}的图形没有QueryStore`);
|
||||
}
|
||||
|
||||
public set queryStore(v: GraphicQueryStore) {
|
||||
this._queryStore = v;
|
||||
}
|
||||
|
||||
public get relationManage(): RelationManage {
|
||||
if (this._relationManage) {
|
||||
return this._relationManage;
|
||||
}
|
||||
throw new Error(`type=${this.type}的图形没有关系管理`);
|
||||
}
|
||||
|
||||
public set relationManage(v: RelationManage) {
|
||||
this._relationManage = v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建图形关系
|
||||
* @param g
|
||||
*/
|
||||
buildRelation() {}
|
||||
|
||||
/**
|
||||
* 从数据加载恢复图形关系
|
||||
*/
|
||||
loadRealtions() {}
|
||||
|
||||
/**
|
||||
* 获取当前图形的所有图形关系
|
||||
* @returns
|
||||
*/
|
||||
getAllRelations(): GraphicRelation[] {
|
||||
return this.relationManage.getRelationsOfGraphic(this);
|
||||
}
|
||||
/**
|
||||
* 获取当前图形的所有指定类型图形关系
|
||||
* @param type
|
||||
* @returns
|
||||
*/
|
||||
queryRelationByType(type: string): GraphicRelation[] {
|
||||
return this.relationManage.getRelationsOfGraphicAndOtherType(this, type);
|
||||
}
|
||||
/**
|
||||
* 删除当前图形关联的指定类型的关系
|
||||
* @param type
|
||||
*/
|
||||
deleteRelationByType(type: string): void {
|
||||
this.relationManage.deleteRelationOfGraphicAndOtherType(this, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建并保存关系数据到datas中
|
||||
*/
|
||||
saveRelations(): void {}
|
||||
/**
|
||||
* 保存数据,复制,非原始数据
|
||||
* @returns
|
||||
*/
|
||||
saveData<D extends GraphicData>(): D {
|
||||
this.getDatas().graphicType = this.type;
|
||||
this.getDatas().transform = GraphicTransform.fromObject(this);
|
||||
this.getDatas().childTransforms = this.buildChildTransforms();
|
||||
this.saveRelations();
|
||||
return this.getDatas().clone() as D;
|
||||
}
|
||||
/**
|
||||
* 构建子元素变换列表
|
||||
* @returns
|
||||
*/
|
||||
private buildChildTransforms(): ChildTransform[] {
|
||||
const childTransforms: ChildTransform[] = [];
|
||||
recursiveChildren(this, (child) => {
|
||||
if (child.transformSave) {
|
||||
childTransforms.push(ChildTransform.fromChild(child));
|
||||
}
|
||||
});
|
||||
return childTransforms;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载数据
|
||||
* @param data
|
||||
*/
|
||||
loadData(data: GraphicData) {
|
||||
if (data.graphicType !== this.type) {
|
||||
throw new Error(
|
||||
`不同的图形类型,请检查数据是否正常: data.graphicType="${data.graphicType}, type="${this.type}`
|
||||
);
|
||||
}
|
||||
this._datas = data;
|
||||
this.loadTransformFrom(data);
|
||||
}
|
||||
|
||||
private loadTransformFrom(data: GraphicData) {
|
||||
if (data.transform) {
|
||||
this.loadTransform(data.transform);
|
||||
}
|
||||
if (data.childTransforms) {
|
||||
data.childTransforms.forEach((ct) => {
|
||||
const child = this.getChildByName(ct.name, true);
|
||||
if (child) {
|
||||
child.loadTransform(ct.transform);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 更新图形数据
|
||||
* @param data
|
||||
* @returns
|
||||
*/
|
||||
updateData(data: GraphicData): boolean {
|
||||
let update = false;
|
||||
if (!this.getDatas().eq(data)) {
|
||||
update = true;
|
||||
const old = this.getDatas().clone();
|
||||
this.getDatas().copyFrom(data);
|
||||
this.onDataChange(data, old);
|
||||
this.loadTransformFrom(data);
|
||||
this.emit('dataupdate', this, data, old);
|
||||
this.repaint();
|
||||
}
|
||||
return update;
|
||||
}
|
||||
/**
|
||||
* 图形数据更新
|
||||
*/
|
||||
onDataChange(newVal: GraphicData, old?: GraphicData): void {}
|
||||
|
||||
/**
|
||||
* 加载状态
|
||||
* @param state
|
||||
*/
|
||||
loadState(state: GraphicState) {
|
||||
if (state.graphicType !== this.type) {
|
||||
throw new Error(
|
||||
`不同的图形类型,请检查数据是否正常: state.graphicType="${state.graphicType}, type="${this.type}`
|
||||
);
|
||||
}
|
||||
this._states = state;
|
||||
}
|
||||
/**
|
||||
* 更新状态
|
||||
* @param state
|
||||
* @returns
|
||||
*/
|
||||
updateStates(state: GraphicState): boolean {
|
||||
let stateChange = false;
|
||||
if (!this.getStates().eq(state)) {
|
||||
// 判断并更新状态,默认状态
|
||||
const old = this.getStates().clone();
|
||||
this.getStates().copyFrom(state);
|
||||
this.onStateChange(state, old);
|
||||
stateChange = true;
|
||||
this.emit('stateupdate', this, state, old);
|
||||
this.repaint();
|
||||
}
|
||||
return stateChange;
|
||||
}
|
||||
/**
|
||||
* 图形状态更新处理
|
||||
*/
|
||||
onStateChange(newVal: GraphicState, old?: GraphicState): void {}
|
||||
|
||||
repaint(): void {
|
||||
this.doRepaint();
|
||||
this.emit('repaint', this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理重绘逻辑
|
||||
*/
|
||||
abstract doRepaint(): void;
|
||||
/**
|
||||
* 处理删除逻辑
|
||||
*/
|
||||
onDelete(): void {
|
||||
this.removeAllAssistantAppend();
|
||||
this.removeAllListeners();
|
||||
recursiveChildren(this, (child) => child.removeAllAssistantAppend());
|
||||
}
|
||||
|
||||
/**
|
||||
* 框选检测,默认取图形包围盒判定,若需要精细判定-子类重写此方法
|
||||
* @param box
|
||||
* @returns
|
||||
*/
|
||||
boxIntersectCheck(box: Rectangle): boolean {
|
||||
return box.intersects(this.getLocalBounds(), this.localTransform);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形对象模板
|
||||
*/
|
||||
export abstract class JlGraphicTemplate<G extends JlGraphic> {
|
||||
readonly type: string;
|
||||
|
||||
constructor(type: string) {
|
||||
this.type = type;
|
||||
}
|
||||
/**
|
||||
* 初始化一个新的图形对象
|
||||
*/
|
||||
abstract new(): G;
|
||||
/**
|
||||
* 加载图形对象需要用到的资源
|
||||
*/
|
||||
loadAsserts(): void {}
|
||||
|
||||
/**
|
||||
* 克隆图形对象
|
||||
* @param graphic
|
||||
* @returns
|
||||
*/
|
||||
clone(graphic: G): G {
|
||||
const g = this.new();
|
||||
if (graphic._datas) {
|
||||
// 数据克隆
|
||||
const datas = graphic.saveData();
|
||||
g.updateData(datas);
|
||||
}
|
||||
if (graphic._states) {
|
||||
// 状态克隆
|
||||
const state = graphic.getStates().clone();
|
||||
g.updateStates(state);
|
||||
}
|
||||
g.id = GraphicIdGenerator.next();
|
||||
return g;
|
||||
}
|
||||
}
|
||||
|
||||
export type GraphicTemplate = JlGraphicTemplate<JlGraphic>;
|
|
@ -0,0 +1,4 @@
|
|||
export * from './JlGraphic';
|
||||
export * from './IdGenerator';
|
||||
export * from './GraphicRelation';
|
||||
export * from './GraphicStore';
|
|
@ -0,0 +1,113 @@
|
|||
declare namespace GlobalMixins {
|
||||
type JlCanvasType = import('./app').JlCanvas;
|
||||
type CanvasProperties = import('./app').ICanvasProperties;
|
||||
type GraphicApp = import('./app').GraphicApp;
|
||||
type JlGraphicType = import('./core').JlGraphic;
|
||||
type GraphicData = import('./core').GraphicData;
|
||||
type GraphicState = import('./core').GraphicState;
|
||||
type GraphicTransform = import('./core').GraphicTransform;
|
||||
type AppDragEventType = import('./plugins').GraphicDragEvent;
|
||||
type BoundsGraphic = import('./graphic').BoundsGraphic;
|
||||
type IPointDataType = import('pixi.js').IPointData;
|
||||
type PointType = import('pixi.js').Point;
|
||||
type DisplayObjectType = import('pixi.js').DisplayObject;
|
||||
type ContainerType = import('pixi.js').Container;
|
||||
interface DisplayObjectEvents {
|
||||
canvassizechange: [JlCanvasType];
|
||||
'enter-absorbable-area': [number | undefined, number | undefined];
|
||||
'out-absorbable-area': [number | undefined, number | undefined];
|
||||
transforming: [JlCanvasType];
|
||||
dataupdate: [JlGraphicType, GraphicData, GraphicData | undefined];
|
||||
pointupdate: [obj: DisplayObjectType, points: IPointDataType[]];
|
||||
stateupdate: [JlGraphicType, GraphicState, GraphicState | undefined];
|
||||
repaint: [DisplayObjectType];
|
||||
propertiesupdate: [JlGraphicType | JlCanvasType];
|
||||
dragstart: [AppDragEventType];
|
||||
dragmove: [AppDragEventType];
|
||||
dragend: [AppDragEventType];
|
||||
scalestart: [DisplayObjectType];
|
||||
scalemove: [DisplayObjectType];
|
||||
scaleend: [DisplayObjectType];
|
||||
rotatestart: [DisplayObjectType];
|
||||
rotatemove: [DisplayObjectType];
|
||||
rotateend: [DisplayObjectType];
|
||||
transformstart: [DisplayObjectType];
|
||||
transformend: [DisplayObjectType];
|
||||
selected: [DisplayObjectType];
|
||||
unselected: [DisplayObjectType];
|
||||
childselected: [DisplayObjectType];
|
||||
childunselected: [DisplayObjectType];
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
||||
interface GraphicAppEvents {
|
||||
propertiesupdate: [selectedData: GraphicData | CanvasProperties | null];
|
||||
}
|
||||
|
||||
interface DisplayObject {
|
||||
_selectable: boolean;
|
||||
_selected: boolean;
|
||||
selectable: boolean; //是否可选中
|
||||
selected: boolean; // 是否选中
|
||||
_childEdit: boolean; // 子元素编辑模式
|
||||
childEdit: boolean;
|
||||
_transformSave: boolean; // 变换是否保存
|
||||
transformSave: boolean; //
|
||||
_assistantAppendMap: Map<string, DisplayObjectType> | null; // 辅助附加图形map
|
||||
assistantAppendMap: Map<string, DisplayObjectType>;
|
||||
_draggable: boolean; // 是否可拖拽
|
||||
draggable: boolean;
|
||||
_dragStartPoint: PointType | null; // 拖拽起始坐标
|
||||
dragStartPoint: PointType | null;
|
||||
_scalable: boolean; // 是否可缩放
|
||||
scalable: boolean;
|
||||
_keepAspectRatio: boolean; // 缩放是否保持纵横比,默认保持
|
||||
keepAspectRatio: boolean;
|
||||
_rotatable: boolean; // 是否可旋转
|
||||
rotatable: boolean;
|
||||
worldAngle: number; // 世界角度,(-180, 180]
|
||||
getAllParentScaled(): PointType;
|
||||
saveTransform(): GraphicTransform; // 保存变换
|
||||
loadTransform(transform: GraphicTransform): void; // 加载变换
|
||||
isChild(obj: DisplayObject): boolean; // 是否子元素
|
||||
isParent(obj: DisplayObject): boolean; // 是否父元素
|
||||
isAssistantAppend(): boolean; // 是否辅助附加图形
|
||||
addAssistantAppend<D extends DisplayObjectType>(...appends: D[]): void;
|
||||
removeAssistantAppend(...appends: DisplayObjectType[]): void;
|
||||
removeAssistantAppendByName(...names: string[]): void;
|
||||
removeAllAssistantAppend(): void;
|
||||
getAssistantAppend<D extends DisplayObjectType>(
|
||||
name: string
|
||||
): D | undefined; // 获取辅助附加图形对象
|
||||
isGraphic(): boolean; // 是否业务图形对象
|
||||
getGraphic<G extends JlGraphicType>(): G | null; // 获取所属的图形对象
|
||||
isGraphicChild(): boolean; // 是否图形子元素
|
||||
onAddToCanvas(): void; // 添加到画布处理
|
||||
onRemoveFromCanvas(): void; //从画布移除处理
|
||||
isInCanvas(): boolean; // 是否添加到画布中
|
||||
getCanvas(): JlCanvasType; // 获取所在画布
|
||||
getViewport(): Viewport; // 获取视口
|
||||
getGraphicApp(): GraphicApp; // 获取图形app
|
||||
localToCanvasPoint(p: IPointData): PointType; // 图形本地坐标转为画布坐标
|
||||
localToCanvasPoints(...points: IPointData[]): PointType[]; // 批量转换
|
||||
canvasToLocalPoint(p: IPointData): PointType; // 画布坐标转为图形本地坐标
|
||||
canvasToLocalPoints(...points: IPointData[]): PointType[]; // 批量转换
|
||||
|
||||
localToScreenPoint(p: IPointData): PointType; // 本地坐标转为屏幕坐标
|
||||
localToScreenPoints(...points: IPointData[]): PointType[]; // 批量
|
||||
screenToLocalPoint(p: IPointData): PointType; // 屏幕坐标转为本地坐标
|
||||
screenToLocalPoints(...points: IPointData[]): PointType[]; // 批量
|
||||
|
||||
localBoundsToCanvasPoints(): PointType[]; // 本地包围框转为多边形点坐标
|
||||
}
|
||||
|
||||
interface Graphics {
|
||||
drawBezierCurve(
|
||||
p1: IPointData,
|
||||
p2: IPointData,
|
||||
cp1: IPointData,
|
||||
cp2: IPointData,
|
||||
segmentsCount: number
|
||||
): Graphics;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,173 @@
|
|||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import {
|
||||
Color,
|
||||
Container,
|
||||
DisplayObject,
|
||||
Graphics,
|
||||
IPointData,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import {
|
||||
calculateFootPointFromPointToLine,
|
||||
calculateIntersectionPointOfCircleAndPoint,
|
||||
distance,
|
||||
linePoint,
|
||||
} from '../utils';
|
||||
import { VectorGraphic, VectorGraphicUtil } from './VectorGraphic';
|
||||
|
||||
/**
|
||||
* 抽象可吸附位置
|
||||
*/
|
||||
export interface AbsorbablePosition extends Container {
|
||||
/**
|
||||
* 尝试吸附图形对象
|
||||
* @param objs 图形对象列表
|
||||
* @returns 如果吸附成功,返回true,否则false
|
||||
*/
|
||||
tryAbsorb(...objs: DisplayObject[]): boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 可吸附点图形参数
|
||||
*/
|
||||
export const AbsorbablePointParam = {
|
||||
lineWidth: 1,
|
||||
lineColor: '#000000',
|
||||
fillColor: '#E77E0E',
|
||||
radius: 5, // 半径
|
||||
};
|
||||
|
||||
const AbsorbablePointGraphic = new Graphics();
|
||||
// AbsorbablePointGraphic.lineStyle(
|
||||
// AbsorbablePointParam.lineWidth,
|
||||
// AbsorbablePointParam.lineColor
|
||||
// );
|
||||
AbsorbablePointGraphic.beginFill(AbsorbablePointParam.fillColor);
|
||||
AbsorbablePointGraphic.drawCircle(0, 0, AbsorbablePointParam.radius);
|
||||
AbsorbablePointGraphic.endFill();
|
||||
|
||||
/**
|
||||
* 可吸附点
|
||||
*/
|
||||
export default class AbsorbablePoint
|
||||
extends Graphics
|
||||
implements AbsorbablePosition, VectorGraphic
|
||||
{
|
||||
_point: Point;
|
||||
absorbRange: number;
|
||||
scaledListenerOn = false;
|
||||
|
||||
constructor(point: IPointData, absorbRange = 10) {
|
||||
super(AbsorbablePointGraphic.geometry);
|
||||
this._point = new Point(point.x, point.y);
|
||||
this.absorbRange = absorbRange;
|
||||
this.position.copyFrom(this._point);
|
||||
this.interactive;
|
||||
VectorGraphicUtil.handle(this);
|
||||
}
|
||||
tryAbsorb(...objs: DisplayObject[]): boolean {
|
||||
for (let i = 0; i < objs.length; i++) {
|
||||
const obj = objs[i];
|
||||
if (
|
||||
distance(this._point.x, this._point.y, obj.position.x, obj.position.y) <
|
||||
this.absorbRange
|
||||
) {
|
||||
obj.position.copyFrom(this._point);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
updateOnScaled() {
|
||||
const scaled = this.getAllParentScaled();
|
||||
const scale = Math.max(scaled.x, scaled.y);
|
||||
this.scale.set(1 / scale, 1 / scale);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 可吸附线
|
||||
*/
|
||||
export class AbsorbableLine extends Graphics implements AbsorbablePosition {
|
||||
p1: Point;
|
||||
p2: Point;
|
||||
absorbRange: number;
|
||||
_color = '#E77E0E';
|
||||
|
||||
constructor(p1: IPointData, p2: IPointData, absorbRange = 20) {
|
||||
super();
|
||||
this.p1 = new Point(p1.x, p1.y);
|
||||
this.p2 = new Point(p2.x, p2.y);
|
||||
this.absorbRange = absorbRange;
|
||||
this.redraw();
|
||||
}
|
||||
redraw() {
|
||||
this.clear();
|
||||
this.lineStyle(1, new Color(this._color));
|
||||
this.moveTo(this.p1.x, this.p1.y);
|
||||
this.lineTo(this.p2.x, this.p2.y);
|
||||
}
|
||||
|
||||
tryAbsorb(...objs: DisplayObject[]): boolean {
|
||||
for (let i = 0; i < objs.length; i++) {
|
||||
const obj = objs[i];
|
||||
const p = obj.position.clone();
|
||||
if (linePoint(this.p1, this.p2, p, this.absorbRange, true)) {
|
||||
const fp = calculateFootPointFromPointToLine(this.p1, this.p2, p);
|
||||
obj.position.copyFrom(fp);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 可吸附圆
|
||||
*/
|
||||
export class AbsorbableCircle extends Graphics implements AbsorbablePosition {
|
||||
absorbRange: number;
|
||||
p0: Point;
|
||||
radius: number;
|
||||
_color = '#E77E0E';
|
||||
|
||||
constructor(p: IPointData, radius: number, absorbRange = 10) {
|
||||
super();
|
||||
this.p0 = new Point(p.x, p.y);
|
||||
this.radius = radius;
|
||||
this.absorbRange = absorbRange;
|
||||
this.redraw();
|
||||
}
|
||||
|
||||
redraw() {
|
||||
this.clear();
|
||||
this.lineStyle(1, new Color(this._color));
|
||||
this.drawCircle(this.p0.x, this.p0.y, this.radius);
|
||||
}
|
||||
|
||||
tryAbsorb(...objs: DisplayObject[]): boolean {
|
||||
for (let i = 0; i < objs.length; i++) {
|
||||
const obj = objs[i];
|
||||
const len = distance(
|
||||
this.p0.x,
|
||||
this.p0.y,
|
||||
obj.position.x,
|
||||
obj.position.y
|
||||
);
|
||||
if (
|
||||
len > this.radius - this.absorbRange &&
|
||||
len < this.radius + this.absorbRange
|
||||
) {
|
||||
// 吸附,计算直线与圆交点,更新对象坐标
|
||||
const p = calculateIntersectionPointOfCircleAndPoint(
|
||||
this.p0,
|
||||
this.radius,
|
||||
obj.position
|
||||
);
|
||||
obj.position.copyFrom(p);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
import { Container, Graphics, IPointData, Point } from 'pixi.js';
|
||||
import { angleToAxisx } from '../utils';
|
||||
|
||||
export interface IDashedLineOptions {
|
||||
/**
|
||||
* 每小段长度,默认4
|
||||
*/
|
||||
length?: number;
|
||||
/**
|
||||
* 起始间隔,默认0
|
||||
*/
|
||||
startSpace?: number;
|
||||
/**
|
||||
* 间隔长度,默认4
|
||||
*/
|
||||
space?: number;
|
||||
/**
|
||||
* 线宽,默认1
|
||||
*/
|
||||
lineWidth?: number;
|
||||
/**
|
||||
* 线色,默认黑
|
||||
*/
|
||||
color?: string;
|
||||
}
|
||||
|
||||
interface ICompleteDashedLineOptions extends IDashedLineOptions {
|
||||
length: number;
|
||||
startSpace: number;
|
||||
space: number;
|
||||
lineWidth: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
const DefaultDashedLineOptions: ICompleteDashedLineOptions = {
|
||||
length: 4,
|
||||
startSpace: 0,
|
||||
space: 4,
|
||||
lineWidth: 1,
|
||||
color: '#0000ff',
|
||||
};
|
||||
|
||||
export class DashedLine extends Container {
|
||||
p1: Point;
|
||||
p2: Point;
|
||||
_options: ICompleteDashedLineOptions;
|
||||
constructor(p1: IPointData, p2: IPointData, options?: IDashedLineOptions) {
|
||||
super();
|
||||
const config = Object.assign({}, DefaultDashedLineOptions, options);
|
||||
this._options = config;
|
||||
this.p1 = new Point(p1.x, p1.y);
|
||||
this.p2 = new Point(p2.x, p2.y);
|
||||
this.redraw();
|
||||
}
|
||||
|
||||
setOptions(options: IDashedLineOptions) {
|
||||
if (options.startSpace != undefined) {
|
||||
this._options.startSpace = options.startSpace;
|
||||
}
|
||||
if (options.length != undefined) {
|
||||
this._options.length = options.length;
|
||||
}
|
||||
if (options.space != undefined) {
|
||||
this._options.space = options.space;
|
||||
}
|
||||
if (options.lineWidth != undefined) {
|
||||
this._options.lineWidth = options.lineWidth;
|
||||
}
|
||||
if (options.color != undefined) {
|
||||
this._options.color = options.color;
|
||||
}
|
||||
this.redraw();
|
||||
}
|
||||
|
||||
redraw() {
|
||||
this.removeChildren();
|
||||
const p1 = this.p1;
|
||||
const p2 = this.p2;
|
||||
const option = this._options;
|
||||
const total = Math.pow(
|
||||
Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2),
|
||||
0.5
|
||||
);
|
||||
let len = option.startSpace;
|
||||
while (len < total) {
|
||||
let dashedLen = option.length;
|
||||
if (len + option.length > total) {
|
||||
dashedLen = total - len;
|
||||
}
|
||||
const line = new Graphics();
|
||||
line.lineStyle(option.lineWidth, option.color);
|
||||
line.moveTo(len, 0);
|
||||
line.lineTo(len + dashedLen, 0);
|
||||
this.addChild(line);
|
||||
len = len + dashedLen + option.space;
|
||||
}
|
||||
|
||||
this.pivot.set(0, option.lineWidth / 2);
|
||||
this.position.set(p1.x, p1.y);
|
||||
this.angle = angleToAxisx(p1, p2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
import { Graphics, IPointData } from 'pixi.js';
|
||||
import { VectorGraphic, VectorGraphicUtil } from './VectorGraphic';
|
||||
|
||||
/**
|
||||
* 拖拽点参数
|
||||
*/
|
||||
export const DraggablePointParam = {
|
||||
lineWidth: 1,
|
||||
lineColor: 0x000000,
|
||||
fillColor: 0xffffff,
|
||||
radius: 5, // 半径
|
||||
};
|
||||
|
||||
const DraggablePointGraphic = new Graphics();
|
||||
DraggablePointGraphic.lineStyle(
|
||||
DraggablePointParam.lineWidth,
|
||||
DraggablePointParam.lineColor
|
||||
);
|
||||
DraggablePointGraphic.beginFill(DraggablePointParam.fillColor);
|
||||
DraggablePointGraphic.drawCircle(0, 0, DraggablePointParam.radius);
|
||||
DraggablePointGraphic.endFill();
|
||||
|
||||
/**
|
||||
* 拖拽点,用于更新图形属性
|
||||
*/
|
||||
export class DraggablePoint extends Graphics implements VectorGraphic {
|
||||
scaledListenerOn = false;
|
||||
/**
|
||||
*
|
||||
* @param point 画布坐标点
|
||||
*/
|
||||
constructor(point: IPointData) {
|
||||
super(DraggablePointGraphic.geometry);
|
||||
this.position.copyFrom(point);
|
||||
this.interactive = true;
|
||||
this.draggable = true;
|
||||
this.cursor = 'crosshair';
|
||||
VectorGraphicUtil.handle(this);
|
||||
}
|
||||
updateOnScaled() {
|
||||
const scaled = this.getAllParentScaled();
|
||||
const scale = Math.max(scaled.x, scaled.y);
|
||||
this.scale.set(1 / scale, 1 / scale);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,475 @@
|
|||
import {
|
||||
Container,
|
||||
DisplayObject,
|
||||
Graphics,
|
||||
IDestroyOptions,
|
||||
Point,
|
||||
Polygon,
|
||||
} from 'pixi.js';
|
||||
import { GraphicDragEvent, KeyListener } from '../plugins';
|
||||
import {
|
||||
angleToAxisx,
|
||||
convertRectangleToPolygonPoints,
|
||||
distance,
|
||||
calculateLineMidpoint,
|
||||
} from '../utils';
|
||||
import { DraggablePoint } from './DraggablePoint';
|
||||
|
||||
const BoundsLineStyle = {
|
||||
width: 1,
|
||||
color: 0x29b6f2,
|
||||
alpha: 1,
|
||||
};
|
||||
|
||||
/**
|
||||
* 缩放、旋转辅助
|
||||
*/
|
||||
export class TransformPoints extends Container {
|
||||
static Name = 'transformPoints';
|
||||
static MinLength = 40;
|
||||
static LeftTopName = 'lt-scale-point';
|
||||
static TopName = 't-scale-point';
|
||||
static RightTopName = 'rt-scale-point';
|
||||
static RightName = 'r-scale-point';
|
||||
static RightBottomName = 'rb-scale-point';
|
||||
static BottomName = 'b-scale-point';
|
||||
static LeftBottomName = 'lb-scale-point';
|
||||
static LeftName = 'l-scale-point';
|
||||
|
||||
static RotateName = 'rotate-point';
|
||||
obj: DisplayObject;
|
||||
|
||||
ltScalePoint: DraggablePoint;
|
||||
ltLocal: Point = new Point();
|
||||
tScalePoint: DraggablePoint;
|
||||
tLocal: Point = new Point();
|
||||
tCanvas: Point = new Point();
|
||||
rtScalePoint: DraggablePoint;
|
||||
rtLocal: Point = new Point();
|
||||
rScalePoint: DraggablePoint;
|
||||
rLocal: Point = new Point();
|
||||
rbScalePoint: DraggablePoint;
|
||||
rbLocal: Point = new Point();
|
||||
bScalePoint: DraggablePoint;
|
||||
bLocal: Point = new Point();
|
||||
lbScalePoint: DraggablePoint;
|
||||
lbLocal: Point = new Point();
|
||||
lScalePoint: DraggablePoint;
|
||||
lLocal: Point = new Point();
|
||||
originScale: Point = new Point();
|
||||
scalePivot: Point = new Point();
|
||||
|
||||
/**
|
||||
* 旋转拖拽点
|
||||
*/
|
||||
rotatePoint: DraggablePoint;
|
||||
/**
|
||||
* 旋转中心坐标
|
||||
*/
|
||||
rotatePivot: Point;
|
||||
/**
|
||||
* 起始旋转坐标
|
||||
*/
|
||||
rotateLastPoint: Point;
|
||||
/**
|
||||
* 起始图形角度
|
||||
*/
|
||||
startAngle = 0;
|
||||
/**
|
||||
* 旋转角度步长
|
||||
*/
|
||||
angleStep = 1;
|
||||
/**
|
||||
* 修改旋转步长键盘监听
|
||||
*/
|
||||
rotateAngleStepKeyListeners: KeyListener[] = [];
|
||||
|
||||
constructor(obj: DisplayObject) {
|
||||
super();
|
||||
this.obj = obj;
|
||||
this.name = TransformPoints.Name;
|
||||
|
||||
// 创建缩放拖拽点
|
||||
this.ltScalePoint = new DraggablePoint(new Point());
|
||||
this.ltScalePoint.name = TransformPoints.LeftTopName;
|
||||
this.addChild(this.ltScalePoint);
|
||||
this.tScalePoint = new DraggablePoint(new Point());
|
||||
this.tScalePoint.name = TransformPoints.TopName;
|
||||
this.addChild(this.tScalePoint);
|
||||
this.rtScalePoint = new DraggablePoint(new Point());
|
||||
this.rtScalePoint.name = TransformPoints.RightTopName;
|
||||
this.addChild(this.rtScalePoint);
|
||||
this.rScalePoint = new DraggablePoint(new Point());
|
||||
this.rScalePoint.name = TransformPoints.RightName;
|
||||
this.addChild(this.rScalePoint);
|
||||
this.rbScalePoint = new DraggablePoint(new Point());
|
||||
this.rbScalePoint.name = TransformPoints.RightBottomName;
|
||||
this.addChild(this.rbScalePoint);
|
||||
this.bScalePoint = new DraggablePoint(new Point());
|
||||
this.bScalePoint.name = TransformPoints.BottomName;
|
||||
this.addChild(this.bScalePoint);
|
||||
this.lbScalePoint = new DraggablePoint(new Point());
|
||||
this.lbScalePoint.name = TransformPoints.LeftBottomName;
|
||||
this.addChild(this.lbScalePoint);
|
||||
this.lScalePoint = new DraggablePoint(new Point());
|
||||
this.lScalePoint.name = TransformPoints.LeftName;
|
||||
this.addChild(this.lScalePoint);
|
||||
this.obj.on('transformstart', this.onObjTransformStart, this);
|
||||
this.obj.on('transformend', this.onObjTransformEnd, this);
|
||||
this.obj.on('repaint', this.onGraphicRepaint, this);
|
||||
this.children.forEach((dp) => {
|
||||
dp.on('dragstart', this.onScaleDragStart, this);
|
||||
dp.on('dragmove', this.onScaleDragMove, this);
|
||||
dp.on('dragend', this.onScaleDragEnd, this);
|
||||
});
|
||||
|
||||
// 创建旋转拖拽点
|
||||
this.rotatePoint = new DraggablePoint(new Point());
|
||||
this.addChild(this.rotatePoint);
|
||||
this.rotatePoint.on('dragstart', this.onRotateStart, this);
|
||||
this.rotatePoint.on('dragmove', this.onRotateMove, this);
|
||||
this.rotatePoint.on('dragend', this.onRotateEnd, this);
|
||||
this.rotatePivot = new Point();
|
||||
this.rotateLastPoint = new Point();
|
||||
// 初始化旋转角度修改键盘监听器
|
||||
for (let i = 1; i < 10; i++) {
|
||||
this.rotateAngleStepKeyListeners.push(
|
||||
KeyListener.create({
|
||||
value: '' + i,
|
||||
onPress: () => {
|
||||
// console.log('修改角度step');
|
||||
this.angleStep = i;
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
this.obj.addAssistantAppend(this);
|
||||
}
|
||||
|
||||
onObjTransformStart() {
|
||||
this.visible = false;
|
||||
}
|
||||
onObjTransformEnd() {
|
||||
this.update();
|
||||
this.visible = true;
|
||||
}
|
||||
onGraphicRepaint() {
|
||||
if (this.visible) {
|
||||
this.update();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 旋转开始
|
||||
* @param de
|
||||
*/
|
||||
onRotateStart(de: GraphicDragEvent) {
|
||||
this.hideAll();
|
||||
const assistantPoint = this.obj.localToCanvasPoint(this.obj.pivot);
|
||||
this.rotatePivot.copyFrom(assistantPoint);
|
||||
this.rotateLastPoint.copyFrom(de.target.position);
|
||||
this.startAngle = this.obj.angle;
|
||||
this.rotateAngleStepKeyListeners.forEach((listener) =>
|
||||
this.obj.getGraphicApp().addKeyboardListener(listener)
|
||||
);
|
||||
this.obj.emit('rotatestart', this.obj);
|
||||
this.obj.emit('transformstart', this.obj);
|
||||
}
|
||||
/**
|
||||
* 旋转移动
|
||||
* @param de
|
||||
*/
|
||||
onRotateMove(de: GraphicDragEvent) {
|
||||
// 旋转角度计算逻辑:取锚点y负方向一点作为旋转点,求旋转点和锚点所形成的直线与x轴角度,此角度+90°即为最终旋转角度,再将旋转角度限制到(-180,180]之间
|
||||
let angle = angleToAxisx(this.rotatePivot, de.target.position);
|
||||
angle = Math.floor(angle / this.angleStep) * this.angleStep;
|
||||
angle = (angle + 90) % 360;
|
||||
if (angle > 180) {
|
||||
angle = angle - 360;
|
||||
}
|
||||
this.obj.angle = angle;
|
||||
this.obj.emit('rotatemove', this.obj);
|
||||
}
|
||||
/**
|
||||
* 旋转结束
|
||||
* @param de
|
||||
*/
|
||||
onRotateEnd() {
|
||||
this.showAll();
|
||||
this.rotateAngleStepKeyListeners.forEach((listener) =>
|
||||
this.obj.getGraphicApp().removeKeyboardListener(listener)
|
||||
);
|
||||
this.obj.emit('rotateend', this.obj);
|
||||
this.obj.emit('transformend', this.obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* 缩放开始
|
||||
*/
|
||||
onScaleDragStart() {
|
||||
this.hideAll();
|
||||
const points = convertRectangleToPolygonPoints(this.obj.getLocalBounds());
|
||||
const p0 = points[0];
|
||||
const p1 = points[1];
|
||||
const p2 = points[2];
|
||||
const p3 = points[3];
|
||||
this.scalePivot = this.obj.pivot.clone();
|
||||
this.ltLocal.copyFrom(p0);
|
||||
this.tCanvas.copyFrom(
|
||||
this.obj.localToCanvasPoint(calculateLineMidpoint(p0, p1))
|
||||
);
|
||||
this.tLocal.copyFrom(calculateLineMidpoint(p0, p1));
|
||||
this.rtLocal.copyFrom(p1);
|
||||
this.rLocal.copyFrom(calculateLineMidpoint(p1, p2));
|
||||
this.rbLocal.copyFrom(p2);
|
||||
this.bLocal.copyFrom(calculateLineMidpoint(p2, p3));
|
||||
this.lbLocal.copyFrom(p3);
|
||||
this.lLocal.copyFrom(calculateLineMidpoint(p0, p3));
|
||||
this.originScale = this.obj.scale.clone();
|
||||
this.obj.emit('scalestart', this.obj);
|
||||
this.obj.emit('transformstart', this.obj);
|
||||
}
|
||||
|
||||
onScaleDragMove(de: GraphicDragEvent) {
|
||||
// 缩放计算逻辑:共8个方向缩放点,根据所拖拽的方向:
|
||||
// 1,计算缩放为1时的此点在拖拽开始时的位置到锚点x、y距离,
|
||||
// 2,计算拖拽点的当前位置到锚点的x、y方向距离,
|
||||
// PS:以上两个计算都是在local(也就是图形对象本地)坐标系,
|
||||
// 用当前距离除以原始距离即为缩放比例
|
||||
const defaultScale = new Point(1, 1);
|
||||
let originWidth = 0;
|
||||
let originHeight = 0;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
this.obj.scale.copyFrom(defaultScale);
|
||||
const point = this.obj.toLocal(de.event.global);
|
||||
if (de.target === this.ltScalePoint) {
|
||||
// 左上角
|
||||
originWidth = Math.abs(this.ltLocal.x - this.scalePivot.x);
|
||||
originHeight = Math.abs(this.ltLocal.y - this.scalePivot.y);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (de.target == this.tScalePoint) {
|
||||
// 上
|
||||
originHeight = Math.abs(this.tLocal.y - this.scalePivot.y);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (de.target == this.rtScalePoint) {
|
||||
// 右上
|
||||
originWidth = Math.abs(this.rtLocal.x - this.scalePivot.x);
|
||||
originHeight = Math.abs(this.rtLocal.y - this.scalePivot.y);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (de.target == this.rScalePoint) {
|
||||
// 右
|
||||
originWidth = Math.abs(this.rLocal.x - this.scalePivot.x);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
} else if (de.target == this.rbScalePoint) {
|
||||
// 右下
|
||||
originWidth = Math.abs(this.rbLocal.x - this.scalePivot.x);
|
||||
originHeight = Math.abs(this.rbLocal.y - this.scalePivot.y);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (de.target == this.bScalePoint) {
|
||||
// 下
|
||||
originHeight = Math.abs(this.bLocal.y - this.scalePivot.y);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (de.target == this.lbScalePoint) {
|
||||
// 左下
|
||||
originWidth = Math.abs(this.lbLocal.x - this.scalePivot.x);
|
||||
originHeight = Math.abs(this.lbLocal.y - this.scalePivot.y);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else {
|
||||
// 左
|
||||
originWidth = Math.abs(this.lLocal.x - this.scalePivot.x);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
}
|
||||
// 计算缩放比例,并根据是否保持纵横比两种情况进行缩放处理
|
||||
const sx = originWidth == 0 ? this.originScale.x : width / originWidth;
|
||||
const sy = originHeight == 0 ? this.originScale.y : height / originHeight;
|
||||
// console.log(originWidth, originHeight, width, height, sx, sy);
|
||||
if (this.obj.keepAspectRatio) {
|
||||
let max = Math.max(sx, sy);
|
||||
if (originWidth == 0) {
|
||||
max = sy;
|
||||
} else if (originHeight == 0) {
|
||||
max = sx;
|
||||
}
|
||||
this.obj.scale.set(max, max);
|
||||
} else {
|
||||
this.obj.scale.x = sx;
|
||||
this.obj.scale.y = sy;
|
||||
}
|
||||
}
|
||||
|
||||
onScaleDragEnd() {
|
||||
this.showAll();
|
||||
this.obj.emit('scaleend', this.obj);
|
||||
this.obj.emit('transformend', this.obj);
|
||||
this.obj.getGraphicApp().emit('scaleend', this.obj);
|
||||
}
|
||||
|
||||
hideOthers(dg: DisplayObject) {
|
||||
this.children.forEach((child) => {
|
||||
if (child.name !== dg.name) {
|
||||
child.visible = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
hideAll() {
|
||||
this.children.forEach((child) => (child.visible = false));
|
||||
}
|
||||
|
||||
showAll() {
|
||||
this.update();
|
||||
this.children.forEach((child) => (child.visible = true));
|
||||
}
|
||||
|
||||
getObjBounds(): { width: number; height: number } {
|
||||
const points = this.obj.localBoundsToCanvasPoints();
|
||||
const p0 = points[0];
|
||||
const p1 = points[1];
|
||||
const p3 = points[3];
|
||||
const width = distance(p0.x, p0.y, p1.x, p1.y);
|
||||
const height = distance(p0.x, p0.y, p3.x, p3.y);
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新位置和cursor
|
||||
* @returns
|
||||
*/
|
||||
update() {
|
||||
if (this.obj.scalable) {
|
||||
this.updateScalePoints();
|
||||
}
|
||||
if (this.obj.rotatable) {
|
||||
this.updateRotatePoint();
|
||||
}
|
||||
}
|
||||
|
||||
updateRotatePoint() {
|
||||
const rect = this.obj.getLocalBounds();
|
||||
const lp = this.obj.pivot.clone();
|
||||
const dy = 10 / this.obj.scale.y;
|
||||
lp.y = rect.y - dy;
|
||||
const p = this.obj.localToCanvasPoint(lp);
|
||||
this.rotatePoint.position.copyFrom(p);
|
||||
}
|
||||
|
||||
updateScalePoints() {
|
||||
const points = this.obj.localBoundsToCanvasPoints();
|
||||
this.ltScalePoint.position.copyFrom(points[0]);
|
||||
this.tScalePoint.position.copyFrom(
|
||||
calculateLineMidpoint(points[0], points[1])
|
||||
);
|
||||
this.rtScalePoint.position.copyFrom(points[1]);
|
||||
this.rScalePoint.position.copyFrom(
|
||||
calculateLineMidpoint(points[1], points[2])
|
||||
);
|
||||
this.rbScalePoint.position.copyFrom(points[2]);
|
||||
this.bScalePoint.position.copyFrom(
|
||||
calculateLineMidpoint(points[2], points[3])
|
||||
);
|
||||
this.lbScalePoint.position.copyFrom(points[3]);
|
||||
this.lScalePoint.position.copyFrom(
|
||||
calculateLineMidpoint(points[3], points[0])
|
||||
);
|
||||
const angle = this.obj.worldAngle;
|
||||
const angle360 = (360 + angle) % 360;
|
||||
if (
|
||||
(angle >= -22.5 && angle <= 22.5) ||
|
||||
(angle360 >= 180 - 22.5 && angle360 <= 180 + 22.5)
|
||||
) {
|
||||
this.ltScalePoint.cursor = 'nw-resize';
|
||||
this.tScalePoint.cursor = 'n-resize';
|
||||
this.rtScalePoint.cursor = 'ne-resize';
|
||||
this.rScalePoint.cursor = 'e-resize';
|
||||
this.rbScalePoint.cursor = 'se-resize';
|
||||
this.bScalePoint.cursor = 's-resize';
|
||||
this.lbScalePoint.cursor = 'sw-resize';
|
||||
this.lScalePoint.cursor = 'w-resize';
|
||||
} else if (
|
||||
(angle >= 22.5 && angle <= 67.5) ||
|
||||
(angle360 >= 180 + 22.5 && angle360 <= 180 + 67.5)
|
||||
) {
|
||||
this.ltScalePoint.cursor = 'n-resize';
|
||||
this.tScalePoint.cursor = 'ne-resize';
|
||||
this.rtScalePoint.cursor = 'e-resize';
|
||||
this.rScalePoint.cursor = 'se-resize';
|
||||
this.rbScalePoint.cursor = 's-resize';
|
||||
this.bScalePoint.cursor = 'sw-resize';
|
||||
this.lbScalePoint.cursor = 'w-resize';
|
||||
this.lScalePoint.cursor = 'nw-resize';
|
||||
} else if (
|
||||
(angle >= 67.5 && angle < 112.5) ||
|
||||
(angle360 >= 180 + 67.5 && angle360 <= 180 + 112.5)
|
||||
) {
|
||||
this.ltScalePoint.cursor = 'ne-resize';
|
||||
this.tScalePoint.cursor = 'e-resize';
|
||||
this.rtScalePoint.cursor = 'se-resize';
|
||||
this.rScalePoint.cursor = 's-resize';
|
||||
this.rbScalePoint.cursor = 'sw-resize';
|
||||
this.bScalePoint.cursor = 'w-resize';
|
||||
this.lbScalePoint.cursor = 'nw-resize';
|
||||
this.lScalePoint.cursor = 'n-resize';
|
||||
} else {
|
||||
this.ltScalePoint.cursor = 'e-resize';
|
||||
this.tScalePoint.cursor = 'se-resize';
|
||||
this.rtScalePoint.cursor = 's-resize';
|
||||
this.rScalePoint.cursor = 'sw-resize';
|
||||
this.rbScalePoint.cursor = 'w-resize';
|
||||
this.bScalePoint.cursor = 'nw-resize';
|
||||
this.lbScalePoint.cursor = 'n-resize';
|
||||
this.lScalePoint.cursor = 'ne-resize';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 包围盒矩形图形,现使用外边框转画布多边形实现
|
||||
*/
|
||||
export class BoundsGraphic extends Graphics {
|
||||
static Name = '_BoundsRect';
|
||||
obj: DisplayObject;
|
||||
constructor(graphic: DisplayObject) {
|
||||
super();
|
||||
this.obj = graphic;
|
||||
this.name = BoundsGraphic.Name;
|
||||
this.visible = false;
|
||||
this.obj.on('transformstart', this.onObjTransformStart, this);
|
||||
this.obj.on('transformend', this.onObjTransformEnd, this);
|
||||
this.obj.on('repaint', this.onGraphicRepaint, this);
|
||||
graphic.addAssistantAppend(this);
|
||||
}
|
||||
|
||||
onObjTransformStart(): void {
|
||||
this.visible = false;
|
||||
}
|
||||
onObjTransformEnd(): void {
|
||||
this.redraw();
|
||||
this.visible = true;
|
||||
}
|
||||
|
||||
onGraphicRepaint(): void {
|
||||
if (this.visible) {
|
||||
this.redraw();
|
||||
this.visible = true;
|
||||
}
|
||||
}
|
||||
|
||||
destroy(options?: boolean | IDestroyOptions | undefined): void {
|
||||
if (this.obj.isGraphic()) {
|
||||
this.obj.off('repaint', this.onGraphicRepaint, this);
|
||||
}
|
||||
super.destroy(options);
|
||||
}
|
||||
|
||||
redraw() {
|
||||
this.visible = false; // 屏蔽包围框本身
|
||||
const bounds = new Polygon(this.obj.localBoundsToCanvasPoints());
|
||||
this.clear().lineStyle(BoundsLineStyle).drawShape(bounds);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
import { DisplayObject } from 'pixi.js';
|
||||
|
||||
export interface VectorGraphic extends DisplayObject {
|
||||
scaledListenerOn: boolean;
|
||||
updateOnScaled(): void;
|
||||
}
|
||||
|
||||
export class VectorGraphicUtil {
|
||||
static handle(obj: VectorGraphic): void {
|
||||
const vg = obj;
|
||||
const onScaleChange = function (obj: DisplayObject) {
|
||||
if (vg.isParent(obj)) {
|
||||
vg.updateOnScaled();
|
||||
}
|
||||
};
|
||||
const registerScaleChange = function registerScaleChange(
|
||||
obj: VectorGraphic
|
||||
): void {
|
||||
if (!obj.scaledListenerOn) {
|
||||
obj.scaledListenerOn = true;
|
||||
obj.getGraphicApp().on('scaleend', onScaleChange);
|
||||
}
|
||||
};
|
||||
const unregisterScaleChange = function unregisterScaleChange(
|
||||
obj: VectorGraphic
|
||||
): void {
|
||||
obj.scaledListenerOn = false;
|
||||
obj.getGraphicApp().off('scaleend', onScaleChange);
|
||||
};
|
||||
obj.onAddToCanvas = function onAddToCanvas() {
|
||||
obj.updateOnScaled();
|
||||
registerScaleChange(obj);
|
||||
};
|
||||
obj.onRemoveFromCanvas = function onRemoveFromCanvas() {
|
||||
unregisterScaleChange(obj);
|
||||
};
|
||||
|
||||
obj.on('added', (container) => {
|
||||
if (container.isInCanvas()) {
|
||||
obj.onAddToCanvas();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
import { ICanvas, ITextStyle, Text, TextStyle } from 'pixi.js';
|
||||
import { VectorGraphic, VectorGraphicUtil } from '.';
|
||||
|
||||
/**
|
||||
* 矢量文字.实现原理:在缩放发生变化时,更新fontSize
|
||||
*/
|
||||
export class VectorText extends Text implements VectorGraphic {
|
||||
vectorFontSize = 8;
|
||||
scaled = 1;
|
||||
scaledListenerOn = false;
|
||||
|
||||
constructor(
|
||||
text?: string | number,
|
||||
style?: Partial<ITextStyle> | TextStyle,
|
||||
canvas?: ICanvas
|
||||
) {
|
||||
super(text, style, canvas);
|
||||
VectorGraphicUtil.handle(this);
|
||||
}
|
||||
|
||||
updateOnScaled() {
|
||||
const scaled = this.getAllParentScaled();
|
||||
const scale = Math.max(scaled.x, scaled.y);
|
||||
this.style.fontSize = this.vectorFontSize * scale;
|
||||
this.scale.set(1 / scale, 1 / scale);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置矢量文字的字体大小
|
||||
*/
|
||||
setVectorFontSize(fontSize: number) {
|
||||
this.vectorFontSize = fontSize;
|
||||
this.style.fontSize = fontSize;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
export * from './VectorGraphic';
|
||||
export * from './VectorText';
|
||||
export * from './DraggablePoint';
|
||||
export * from './AbsorbablePosition';
|
||||
export * from './GraphicTransformGraphics';
|
|
@ -0,0 +1,7 @@
|
|||
export * from './core';
|
||||
export * from './graphic';
|
||||
export * from './app';
|
||||
export * from './operation';
|
||||
export * from './utils';
|
||||
export * from './plugins';
|
||||
export * from './message';
|
|
@ -0,0 +1,26 @@
|
|||
/**
|
||||
* 浮点数相等判断误差值
|
||||
*/
|
||||
export const epsilon = 0.00001;
|
||||
|
||||
/**
|
||||
* 判断浮点数是不是0
|
||||
* @param v
|
||||
* @returns
|
||||
*/
|
||||
export function isZero(v: number) {
|
||||
if (Math.abs(v) < epsilon) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 两浮点数是否相等
|
||||
* @param f1
|
||||
* @param f2
|
||||
* @returns
|
||||
*/
|
||||
export function floatEquals(f1: number, f2: number): boolean {
|
||||
return isZero(f1 - f2);
|
||||
}
|
|
@ -0,0 +1,360 @@
|
|||
/* eslint-disable @typescript-eslint/no-this-alias */
|
||||
|
||||
import { epsilon } from './Constants';
|
||||
|
||||
export default class Vector2 {
|
||||
constructor(values?: [number, number]) {
|
||||
if (values !== undefined) {
|
||||
this.xy = values;
|
||||
}
|
||||
}
|
||||
|
||||
static from(p: { x: number; y: number }): Vector2 {
|
||||
return new Vector2([p.x, p.y]);
|
||||
}
|
||||
|
||||
private values = new Float32Array(2);
|
||||
|
||||
static readonly zero = new Vector2([0, 0]);
|
||||
static readonly one = new Vector2([1, 1]);
|
||||
|
||||
get x(): number {
|
||||
return this.values[0];
|
||||
}
|
||||
|
||||
set x(value: number) {
|
||||
this.values[0] = value;
|
||||
}
|
||||
get y(): number {
|
||||
return this.values[1];
|
||||
}
|
||||
set y(value: number) {
|
||||
this.values[1] = value;
|
||||
}
|
||||
|
||||
get xy(): [number, number] {
|
||||
return [this.values[0], this.values[1]];
|
||||
}
|
||||
|
||||
set xy(values: [number, number]) {
|
||||
this.values[0] = values[0];
|
||||
this.values[1] = values[1];
|
||||
}
|
||||
|
||||
at(index: number): number {
|
||||
return this.values[index];
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.x = 0;
|
||||
this.y = 0;
|
||||
}
|
||||
|
||||
copy(dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = this.x;
|
||||
dest.y = this.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
negate(dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = this;
|
||||
}
|
||||
|
||||
dest.x = -this.x;
|
||||
dest.y = -this.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
equals(vector: Vector2, threshold = epsilon): boolean {
|
||||
if (Math.abs(this.x - vector.x) > threshold) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Math.abs(this.y - vector.y) > threshold) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
length(): number {
|
||||
return Math.sqrt(this.squaredLength());
|
||||
}
|
||||
|
||||
squaredLength(): number {
|
||||
const x = this.x;
|
||||
const y = this.y;
|
||||
|
||||
return x * x + y * y;
|
||||
}
|
||||
|
||||
add(vector: Vector2): Vector2 {
|
||||
this.x += vector.x;
|
||||
this.y += vector.y;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
subtract(vector: Vector2): Vector2 {
|
||||
this.x -= vector.x;
|
||||
this.y -= vector.y;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
multiply(vector: Vector2): Vector2 {
|
||||
this.x *= vector.x;
|
||||
this.y *= vector.y;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
divide(vector: Vector2): Vector2 {
|
||||
this.x /= vector.x;
|
||||
this.y /= vector.y;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
scale(value: number, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = this;
|
||||
}
|
||||
|
||||
dest.x *= value;
|
||||
dest.y *= value;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
normalize(dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = this;
|
||||
}
|
||||
|
||||
let length = this.length();
|
||||
|
||||
if (length === 1) {
|
||||
return this;
|
||||
}
|
||||
|
||||
if (length === 0) {
|
||||
dest.x = 0;
|
||||
dest.y = 0;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
length = 1.0 / length;
|
||||
|
||||
dest.x *= length;
|
||||
dest.y *= length;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
// multiplyMat2(matrix: mat2, dest?: Vector2): Vector2 {
|
||||
// if (!dest) {
|
||||
// dest = this;
|
||||
// }
|
||||
|
||||
// return matrix.multiplyVec2(this, dest);
|
||||
// }
|
||||
|
||||
// multiplyMat3(matrix: mat3, dest?: Vector2): Vector2 {
|
||||
// if (!dest) {
|
||||
// dest = this;
|
||||
// }
|
||||
|
||||
// return matrix.multiplyVec2(this, dest);
|
||||
// }
|
||||
|
||||
// static cross(vector: Vector2, vector2: Vector2, dest?: vec3): vec3 {
|
||||
// if (!dest) {
|
||||
// dest = new vec3();
|
||||
// }
|
||||
|
||||
// const x = vector.x;
|
||||
// const y = vector.y;
|
||||
|
||||
// const x2 = vector2.x;
|
||||
// const y2 = vector2.y;
|
||||
|
||||
// const z = x * y2 - y * x2;
|
||||
|
||||
// dest.x = 0;
|
||||
// dest.y = 0;
|
||||
// dest.z = z;
|
||||
|
||||
// return dest;
|
||||
// }
|
||||
|
||||
/**
|
||||
* 向量点乘
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @returns
|
||||
*/
|
||||
static dot(vector: Vector2, vector2: Vector2): number {
|
||||
return vector.x * vector2.x + vector.y * vector2.y;
|
||||
}
|
||||
/**
|
||||
* 向量长度
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @returns
|
||||
*/
|
||||
static distance(vector: Vector2, vector2: Vector2): number {
|
||||
return Math.sqrt(this.squaredDistance(vector, vector2));
|
||||
}
|
||||
|
||||
/**
|
||||
* 向量长度平方
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @returns
|
||||
*/
|
||||
static squaredDistance(vector: Vector2, vector2: Vector2): number {
|
||||
const x = vector2.x - vector.x;
|
||||
const y = vector2.y - vector.y;
|
||||
|
||||
return x * x + y * y;
|
||||
}
|
||||
|
||||
/**
|
||||
* v2->v1的方向的单位向量
|
||||
* @param v1
|
||||
* @param v2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static direction(v1: Vector2, v2: Vector2, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
const x = v1.x - v2.x;
|
||||
const y = v1.y - v2.y;
|
||||
|
||||
let length = Math.sqrt(x * x + y * y);
|
||||
|
||||
if (length === 0) {
|
||||
dest.x = 0;
|
||||
dest.y = 0;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
length = 1 / length;
|
||||
|
||||
dest.x = x * length;
|
||||
dest.y = y * length;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
static mix(
|
||||
vector: Vector2,
|
||||
vector2: Vector2,
|
||||
time: number,
|
||||
dest?: Vector2
|
||||
): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
const x = vector.x;
|
||||
const y = vector.y;
|
||||
|
||||
const x2 = vector2.x;
|
||||
const y2 = vector2.y;
|
||||
|
||||
dest.x = x + time * (x2 - x);
|
||||
dest.y = y + time * (y2 - y);
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 向量加法
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static sum(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = vector.x + vector2.x;
|
||||
dest.y = vector.y + vector2.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 向量减法
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static difference(
|
||||
vector: Vector2,
|
||||
vector2: Vector2,
|
||||
dest?: Vector2
|
||||
): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = vector.x - vector2.x;
|
||||
dest.y = vector.y - vector2.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 向量乘法
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static product(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = vector.x * vector2.x;
|
||||
dest.y = vector.y * vector2.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 向量除法
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static quotient(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = vector.x / vector2.x;
|
||||
dest.y = vector.y / vector2.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
/// 向量和矩阵代码源自开源代码:https://github.com/matthiasferch/tsm
|
||||
|
||||
export * from './Constants';
|
||||
export * from './Vector2';
|
|
@ -0,0 +1,215 @@
|
|||
import {
|
||||
Client as StompClient,
|
||||
StompSubscription,
|
||||
type Frame,
|
||||
type Message,
|
||||
type messageCallbackType,
|
||||
} from '@stomp/stompjs';
|
||||
import type { GraphicApp } from '../app/JlGraphicApp';
|
||||
import { GraphicState } from '../core/JlGraphic';
|
||||
|
||||
export interface StompCliOption {
|
||||
wsUrl: string; // websocket url
|
||||
token: string; // 认证token
|
||||
reconnectDelay?: number; // 重连延时,默认3秒
|
||||
heartbeatIncoming?: number; // 服务端过来的心跳间隔,默认30秒
|
||||
heartbeatOutgoing?: number; // 到服务端的心跳间隔,默认30秒
|
||||
}
|
||||
|
||||
const DefaultStompOption: StompCliOption = {
|
||||
wsUrl: '',
|
||||
token: '',
|
||||
reconnectDelay: 3000,
|
||||
heartbeatIncoming: 30000,
|
||||
heartbeatOutgoing: 30000,
|
||||
};
|
||||
|
||||
export class StompCli {
|
||||
private static enabled = false;
|
||||
private static options: StompCliOption;
|
||||
private static client: StompClient;
|
||||
private static appMsgBroker: AppWsMsgBroker[] = [];
|
||||
private static connected = false;
|
||||
static new(options: StompCliOption) {
|
||||
if (StompCli.enabled) {
|
||||
// 以及启用
|
||||
return;
|
||||
// throw new Error('websocket 已连接,若确实需要重新连接,请先断开StompCli.close再重新StompCli.new')
|
||||
}
|
||||
StompCli.enabled = true;
|
||||
StompCli.options = Object.assign({}, DefaultStompOption, options);
|
||||
StompCli.client = new StompClient({
|
||||
brokerURL: StompCli.options.wsUrl,
|
||||
connectHeaders: {
|
||||
Authorization: StompCli.options.token,
|
||||
// Authorization: ''
|
||||
},
|
||||
// debug: (str) => {
|
||||
// console.log(str)
|
||||
// }
|
||||
reconnectDelay: StompCli.options.reconnectDelay,
|
||||
heartbeatIncoming: StompCli.options.heartbeatIncoming,
|
||||
heartbeatOutgoing: StompCli.options.heartbeatOutgoing,
|
||||
});
|
||||
|
||||
StompCli.client.onConnect = () => {
|
||||
// console.log('websocket连接(重连),重新订阅', StompCli.appMsgBroker.length)
|
||||
StompCli.connected = true;
|
||||
StompCli.appMsgBroker.forEach((broker) => {
|
||||
broker.resubscribe();
|
||||
});
|
||||
};
|
||||
|
||||
StompCli.client.onStompError = (frame: Frame) => {
|
||||
console.error(
|
||||
'Stomp收到error消息,可能是认证失败(暂时没有判断具体错误类型,后需添加判断),关闭Stomp客户端',
|
||||
frame
|
||||
);
|
||||
StompCli.close();
|
||||
};
|
||||
|
||||
StompCli.client.onDisconnect = (frame: Frame) => {
|
||||
console.log('Stomp 断开连接', frame);
|
||||
StompCli.connected = false;
|
||||
// StompCli.appMsgBroker.forEach(broker => {
|
||||
// broker.close();
|
||||
// });
|
||||
};
|
||||
StompCli.client.onWebSocketClose = (evt: CloseEvent) => {
|
||||
console.log('websocket 关闭', evt);
|
||||
StompCli.connected = false;
|
||||
};
|
||||
// websocket错误处理
|
||||
StompCli.client.onWebSocketError = (err: Event) => {
|
||||
console.log('websocket错误', err);
|
||||
// StompCli.appMsgBroker.forEach(broker => {
|
||||
// broker.unsbuscribeAll();
|
||||
// });
|
||||
};
|
||||
|
||||
StompCli.client.activate();
|
||||
}
|
||||
|
||||
static isEnabled(): boolean {
|
||||
return StompCli.enabled;
|
||||
}
|
||||
|
||||
static isConnected(): boolean {
|
||||
return StompCli.client && StompCli.client.connected;
|
||||
}
|
||||
|
||||
static trySubscribe(
|
||||
destination: string,
|
||||
handler: messageCallbackType
|
||||
): StompSubscription | undefined {
|
||||
if (StompCli.isConnected()) {
|
||||
return StompCli.client.subscribe(destination, handler, {
|
||||
id: destination,
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
static registerAppMsgBroker(broker: AppWsMsgBroker) {
|
||||
StompCli.appMsgBroker.push(broker);
|
||||
}
|
||||
|
||||
static removeAppMsgBroker(broker: AppWsMsgBroker) {
|
||||
const index = StompCli.appMsgBroker.findIndex((mb) => mb == broker);
|
||||
if (index >= 0) {
|
||||
StompCli.appMsgBroker.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
static hasAppMsgBroker(): boolean {
|
||||
return StompCli.appMsgBroker.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭websocket连接
|
||||
*/
|
||||
static close() {
|
||||
StompCli.enabled = false;
|
||||
StompCli.connected = false;
|
||||
if (StompCli.client) {
|
||||
StompCli.client.deactivate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 状态订阅消息转换器
|
||||
export type MessageConverter = (message: Uint8Array) => GraphicState[];
|
||||
// 图形app状态订阅
|
||||
export class AppStateSubscription {
|
||||
destination: string;
|
||||
messageConverter: MessageConverter;
|
||||
subscription?: StompSubscription; // 订阅成功对象,用于取消订阅
|
||||
constructor(
|
||||
destination: string,
|
||||
messageConverter: MessageConverter,
|
||||
subscription?: StompSubscription
|
||||
) {
|
||||
this.destination = destination;
|
||||
this.messageConverter = messageConverter;
|
||||
this.subscription = subscription;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形APP的websocket消息代理
|
||||
*/
|
||||
export class AppWsMsgBroker {
|
||||
app: GraphicApp;
|
||||
subscriptions: Map<string, AppStateSubscription> = new Map<
|
||||
string,
|
||||
AppStateSubscription
|
||||
>();
|
||||
|
||||
constructor(app: GraphicApp) {
|
||||
this.app = app;
|
||||
StompCli.registerAppMsgBroker(this);
|
||||
}
|
||||
|
||||
subscribe(sub: AppStateSubscription) {
|
||||
this.unsbuscribe(sub.destination); // 先尝试取消之前订阅
|
||||
sub.subscription = StompCli.trySubscribe(
|
||||
sub.destination,
|
||||
(message: Message) => {
|
||||
const graphicStates = sub.messageConverter(message.binaryBody);
|
||||
this.app.handleGraphicStates(graphicStates);
|
||||
}
|
||||
);
|
||||
// console.log('代理订阅结果', sub.subscription)
|
||||
this.subscriptions.set(sub.destination, sub);
|
||||
}
|
||||
|
||||
resubscribe() {
|
||||
this.subscriptions.forEach((record) => {
|
||||
this.subscribe(record);
|
||||
});
|
||||
}
|
||||
|
||||
unsbuscribe(destination: string) {
|
||||
const oldSub = this.subscriptions.get(destination);
|
||||
if (oldSub) {
|
||||
if (oldSub.subscription && StompCli.isConnected()) {
|
||||
oldSub.subscription.unsubscribe();
|
||||
}
|
||||
oldSub.subscription = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
unsbuscribeAll() {
|
||||
this.subscriptions.forEach((record) => {
|
||||
this.unsbuscribe(record.destination);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消所有订阅,从通用Stomp客户端移除此消息代理
|
||||
*/
|
||||
close() {
|
||||
StompCli.removeAppMsgBroker(this);
|
||||
this.unsbuscribeAll();
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
export * from './WsMsgBroker';
|
|
@ -0,0 +1,91 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { GraphicApp } from '../app/JlGraphicApp';
|
||||
import { JlGraphic } from '../core/JlGraphic';
|
||||
|
||||
/**
|
||||
* 操作
|
||||
*/
|
||||
export abstract class JlOperation {
|
||||
type: string; // 操作类型/名称
|
||||
app: GraphicApp;
|
||||
obj?: any; // 操作对象
|
||||
data?: any; // 操作数据
|
||||
description?: string = ''; // 操作描述
|
||||
|
||||
constructor(app: GraphicApp, type: string) {
|
||||
this.app = app;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
undo1(): void {
|
||||
const updates = this.undo();
|
||||
if (updates) {
|
||||
this.app.updateSelected(...updates);
|
||||
}
|
||||
}
|
||||
redo1(): void {
|
||||
const updates = this.redo();
|
||||
if (updates) {
|
||||
this.app.updateSelected(...updates);
|
||||
}
|
||||
}
|
||||
|
||||
abstract undo(): JlGraphic[] | void;
|
||||
abstract redo(): JlGraphic[] | void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 操作记录
|
||||
*/
|
||||
export class OperationRecord {
|
||||
undoStack: JlOperation[] = [];
|
||||
redoStack: JlOperation[] = [];
|
||||
private maxLen: number;
|
||||
|
||||
constructor(maxLen = 100) {
|
||||
this.maxLen = maxLen;
|
||||
}
|
||||
|
||||
setMaxLen(v: number) {
|
||||
this.maxLen = v;
|
||||
const len = this.undoStack.length;
|
||||
if (len > v) {
|
||||
const removeCount = len - v;
|
||||
this.undoStack.splice(0, removeCount);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 记录
|
||||
* @param op
|
||||
*/
|
||||
record(op: JlOperation) {
|
||||
if (this.undoStack.length >= this.maxLen) {
|
||||
this.undoStack.shift();
|
||||
}
|
||||
// console.log('operation record', op)
|
||||
this.undoStack.push(op);
|
||||
this.redoStack.splice(0, this.redoStack.length);
|
||||
}
|
||||
/**
|
||||
* 撤销
|
||||
*/
|
||||
undo() {
|
||||
const op = this.undoStack.pop();
|
||||
// console.log('撤销', op);
|
||||
if (op) {
|
||||
op.undo1();
|
||||
this.redoStack.push(op);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 重做
|
||||
*/
|
||||
redo() {
|
||||
const op = this.redoStack.pop();
|
||||
// console.log('重做', op);
|
||||
if (op) {
|
||||
op.redo1();
|
||||
this.undoStack.push(op);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
export * from './JlOperation';
|
|
@ -0,0 +1,574 @@
|
|||
import {
|
||||
Container,
|
||||
DisplayObject,
|
||||
FederatedMouseEvent,
|
||||
Graphics,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import { GraphicApp, JlCanvas } from '../app';
|
||||
import { JlGraphic } from '../core';
|
||||
import { AppInteractionPlugin } from './InteractionPlugin';
|
||||
import { AbsorbablePosition } from '../graphic';
|
||||
import { recursiveChildren } from '../utils';
|
||||
|
||||
export class GraphicDragEvent {
|
||||
/**
|
||||
* 原始事件
|
||||
*/
|
||||
event: FederatedMouseEvent;
|
||||
app: GraphicApp;
|
||||
target: DisplayObject;
|
||||
start: Point;
|
||||
point: Point;
|
||||
dx = 0; // 距上一个move点的x移动距离
|
||||
dy = 0; // 距上一个move点的y移动距离
|
||||
constructor(
|
||||
app: GraphicApp,
|
||||
event: FederatedMouseEvent,
|
||||
target: DisplayObject,
|
||||
start: Point,
|
||||
point: Point,
|
||||
dx?: number,
|
||||
dy?: number
|
||||
) {
|
||||
this.app = app;
|
||||
this.event = event;
|
||||
this.target = target;
|
||||
this.start = start;
|
||||
this.point = point;
|
||||
if (dx) {
|
||||
this.dx = dx;
|
||||
}
|
||||
if (dy) {
|
||||
this.dy = dy;
|
||||
}
|
||||
}
|
||||
// static buildJlGraphicDragEvent(
|
||||
// graphic: JlGraphic,
|
||||
// source: GraphicDragEvent
|
||||
// ): GraphicDragEvent {
|
||||
// const e = new GraphicDragEvent(
|
||||
// source.app,
|
||||
// source.event,
|
||||
// source.target,
|
||||
// source.start,
|
||||
// source.point,
|
||||
// source.dx,
|
||||
// source.dy
|
||||
// );
|
||||
// return e;
|
||||
// }
|
||||
|
||||
/**
|
||||
* 距拖拽起始点的x方向距离
|
||||
*/
|
||||
public get dsx(): number {
|
||||
return this.point.x - this.start.x;
|
||||
}
|
||||
/**
|
||||
* 距拖拽起始点的y方向距离
|
||||
*/
|
||||
public get dsy(): number {
|
||||
return this.point.y - this.start.y;
|
||||
}
|
||||
}
|
||||
|
||||
type GraphicSelectFilter = (graphic: JlGraphic) => boolean;
|
||||
|
||||
export interface IMouseToolOptions {
|
||||
/**
|
||||
* 是否启用框选,默认启用
|
||||
*/
|
||||
boxSelect?: boolean;
|
||||
/**
|
||||
* 是否启用视口拖拽(默认右键),默认启用
|
||||
*/
|
||||
viewportDrag?: boolean;
|
||||
/**
|
||||
* 是否启用鼠标滚轮缩放,默认启用
|
||||
*/
|
||||
wheelZoom?: boolean;
|
||||
/**
|
||||
* boxSelect 移动多少像素触发, 默认3
|
||||
*/
|
||||
threshold?: number;
|
||||
/**
|
||||
* 可选择图形过滤器
|
||||
*/
|
||||
selectFilter?: GraphicSelectFilter;
|
||||
}
|
||||
|
||||
class CompleteMouseToolOptions implements IMouseToolOptions {
|
||||
boxSelect: boolean;
|
||||
viewportDrag: boolean;
|
||||
wheelZoom: boolean;
|
||||
threshold: number;
|
||||
selectFilter?: GraphicSelectFilter | undefined;
|
||||
constructor() {
|
||||
this.boxSelect = true;
|
||||
this.viewportDrag = true;
|
||||
this.wheelZoom = true;
|
||||
this.threshold = 3;
|
||||
}
|
||||
update(options: IMouseToolOptions) {
|
||||
if (options.boxSelect != undefined) {
|
||||
this.boxSelect = options.boxSelect;
|
||||
}
|
||||
if (options.viewportDrag != undefined) {
|
||||
this.viewportDrag = options.viewportDrag;
|
||||
}
|
||||
if (options.wheelZoom != undefined) {
|
||||
this.wheelZoom = options.wheelZoom;
|
||||
}
|
||||
if (options.threshold != undefined) {
|
||||
this.threshold = options.threshold;
|
||||
}
|
||||
this.selectFilter = options.selectFilter;
|
||||
}
|
||||
}
|
||||
|
||||
const DefaultSelectToolOptions: CompleteMouseToolOptions =
|
||||
new CompleteMouseToolOptions();
|
||||
|
||||
/**
|
||||
* 通用交互工具
|
||||
*/
|
||||
export class CommonMouseTool extends AppInteractionPlugin {
|
||||
static Name = 'mouse-tool';
|
||||
options: CompleteMouseToolOptions;
|
||||
box: Graphics = new Graphics();
|
||||
leftDownTarget: DisplayObject | null = null;
|
||||
start: Point | null = null;
|
||||
last: Point | null = null;
|
||||
drag = false;
|
||||
graphicSelect = false;
|
||||
|
||||
/**
|
||||
* 可吸附位置列表
|
||||
*/
|
||||
absorbablePositions?: AbsorbablePosition[];
|
||||
apContainer: Container;
|
||||
static AbsorbablePosisiontsName = '__AbsorbablePosisionts';
|
||||
|
||||
constructor(graphicApp: GraphicApp) {
|
||||
super(CommonMouseTool.Name, graphicApp);
|
||||
this.options = DefaultSelectToolOptions;
|
||||
this.apContainer = new Container();
|
||||
this.apContainer.name = CommonMouseTool.AbsorbablePosisiontsName;
|
||||
this.app.canvas.addAssistantAppend(this.apContainer);
|
||||
graphicApp.on('options-update', (options) => {
|
||||
if (options.mouseToolOptions) {
|
||||
this.options.update(options.mouseToolOptions);
|
||||
if (this.isActive()) {
|
||||
this.pause();
|
||||
this.resume();
|
||||
}
|
||||
}
|
||||
if (options.absorbablePositions) {
|
||||
this.absorbablePositions = options.absorbablePositions;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
bind(): void {
|
||||
const canvas = this.app.canvas;
|
||||
canvas.interactive = true;
|
||||
canvas.on('mousedown', this.onMouseDown, this);
|
||||
canvas.on('mouseup', this.onMouseUp, this);
|
||||
if (this.options.viewportDrag) {
|
||||
this.app.viewport.drag({
|
||||
mouseButtons: 'right',
|
||||
});
|
||||
canvas.on('rightdown', this.setCursor, this);
|
||||
canvas.on('rightup', this.resumeCursor, this);
|
||||
canvas.on('rightupoutside', this.resumeCursor, this);
|
||||
}
|
||||
if (this.options.wheelZoom) {
|
||||
this.app.viewport.wheel({
|
||||
percent: 0.01,
|
||||
});
|
||||
}
|
||||
}
|
||||
unbind(): void {
|
||||
const canvas = this.app.canvas;
|
||||
// 确保所有事件取消监听
|
||||
canvas.off('mousedown', this.onMouseDown, this);
|
||||
canvas.off('mouseup', this.onMouseUp, this);
|
||||
canvas.off('mousemove', this.onDrag, this);
|
||||
canvas.off('mouseup', this.onDragEnd, this);
|
||||
canvas.off('mouseupoutside', this.onDragEnd, this);
|
||||
this.app.viewport.plugins.remove('drag');
|
||||
canvas.off('rightdown', this.setCursor, this);
|
||||
canvas.off('rightup', this.resumeCursor, this);
|
||||
canvas.off('rightupoutside', this.resumeCursor, this);
|
||||
|
||||
this.app.viewport.plugins.remove('wheel');
|
||||
this.clearCache();
|
||||
}
|
||||
|
||||
setCursor() {
|
||||
if (this.app.app.view.style) {
|
||||
this.app.app.view.style.cursor = 'grab';
|
||||
}
|
||||
}
|
||||
|
||||
resumeCursor() {
|
||||
if (this.app.app.view.style) {
|
||||
this.app.app.view.style.cursor = 'inherit';
|
||||
}
|
||||
}
|
||||
|
||||
onMouseDown(e: FederatedMouseEvent) {
|
||||
this.leftDownTarget = e.target as DisplayObject;
|
||||
const canvas = this.app.canvas;
|
||||
let enableDrag = false;
|
||||
|
||||
this.graphicSelect = false;
|
||||
if (e.target instanceof JlCanvas) {
|
||||
// 画布
|
||||
if (this.options.boxSelect) {
|
||||
// 框选
|
||||
enableDrag = true;
|
||||
}
|
||||
} else {
|
||||
// 图形
|
||||
const graphic = (e.target as DisplayObject).getGraphic();
|
||||
if (graphic) {
|
||||
const app = this.app;
|
||||
// 图形选中
|
||||
if (!e.ctrlKey && !graphic.selected && graphic.selectable) {
|
||||
app.updateSelected(graphic);
|
||||
graphic.childEdit = false;
|
||||
this.graphicSelect = true;
|
||||
} else if (
|
||||
!e.ctrlKey &&
|
||||
graphic.selected &&
|
||||
graphic.childEdit &&
|
||||
this.leftDownTarget.isGraphicChild()
|
||||
) {
|
||||
if (this.leftDownTarget.selectable) {
|
||||
graphic.setChildSelected(this.leftDownTarget);
|
||||
} else {
|
||||
graphic.exitChildEdit();
|
||||
}
|
||||
}
|
||||
// 判断是否开启拖拽
|
||||
if (
|
||||
!this.leftDownTarget.isAssistantAppend() &&
|
||||
!graphic.draggable &&
|
||||
!this.leftDownTarget.draggable
|
||||
) {
|
||||
console.debug(
|
||||
'图形未开启拖拽,若需开启,设置draggable = true',
|
||||
graphic,
|
||||
this.leftDownTarget
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
enableDrag = true;
|
||||
}
|
||||
|
||||
if (enableDrag) {
|
||||
// 初始化拖拽监听
|
||||
// console.log('drag 开始');
|
||||
this.start = this.app.toCanvasCoordinates(e.global);
|
||||
canvas.on('mousemove', this.onDrag, this);
|
||||
canvas.on('mouseupoutside', this.onDragEnd, this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 选中处理
|
||||
* @param e
|
||||
*/
|
||||
onMouseUp(e: FederatedMouseEvent) {
|
||||
const app = this.app;
|
||||
if (this.drag) {
|
||||
this.onDragEnd(e);
|
||||
} else {
|
||||
const target = e.target as DisplayObject;
|
||||
const graphic = (e.target as DisplayObject).getGraphic();
|
||||
if (
|
||||
graphic &&
|
||||
graphic.selected &&
|
||||
!this.graphicSelect &&
|
||||
app.selectedGraphics.length == 1 &&
|
||||
target === this.leftDownTarget &&
|
||||
target.isGraphicChild() &&
|
||||
target.selectable
|
||||
) {
|
||||
graphic.childEdit = true;
|
||||
}
|
||||
if (e.ctrlKey) {
|
||||
// 多选
|
||||
if (graphic) {
|
||||
if (graphic.childEdit && target === this.leftDownTarget) {
|
||||
graphic.invertChildSelected(target);
|
||||
} else {
|
||||
graphic.invertSelected();
|
||||
app.fireSelectedChange(graphic);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 非多选
|
||||
if (e.target instanceof JlCanvas) {
|
||||
this.app.updateSelected();
|
||||
} else {
|
||||
if (
|
||||
graphic &&
|
||||
graphic.childEdit &&
|
||||
app.selectedGraphics.length === 1 &&
|
||||
target === this.leftDownTarget
|
||||
) {
|
||||
graphic.setChildSelected(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 多个图形选中,退出子元素编辑模式
|
||||
const selecteds = this.app.selectedGraphics;
|
||||
if (selecteds.length > 1) {
|
||||
selecteds.forEach((g) => g.exitChildEdit());
|
||||
}
|
||||
}
|
||||
this.clearCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理缓存
|
||||
*/
|
||||
clearCache() {
|
||||
this.start = null;
|
||||
this.last = null;
|
||||
this.drag = false;
|
||||
this.leftDownTarget = null;
|
||||
this.box.clear();
|
||||
this.app.canvas.removeChild(this.box);
|
||||
}
|
||||
|
||||
public get boxSelect(): boolean | undefined {
|
||||
return this.options.boxSelect;
|
||||
}
|
||||
|
||||
public get selectFilter(): GraphicSelectFilter | undefined {
|
||||
return this.options.selectFilter;
|
||||
}
|
||||
|
||||
public get threshold(): number {
|
||||
return this.options.threshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* 框选图形绘制并检查
|
||||
*/
|
||||
boxSelectDraw(start: Point, end: Point): void {
|
||||
if (!this.drag) return;
|
||||
// 绘制框选矩形框
|
||||
this.box.clear();
|
||||
this.box.lineStyle({ width: 1, color: 0x000000 });
|
||||
const dsx = end.x - start.x;
|
||||
const dsy = end.y - start.y;
|
||||
let { x, y } = start;
|
||||
if (dsx < 0) {
|
||||
x += dsx;
|
||||
}
|
||||
if (dsy < 0) {
|
||||
y += dsy;
|
||||
}
|
||||
const width = Math.abs(dsx);
|
||||
const height = Math.abs(dsy);
|
||||
this.box.drawRect(x, y, width, height);
|
||||
}
|
||||
|
||||
/**
|
||||
* 框选图形判断
|
||||
* @returns
|
||||
*/
|
||||
boxSelectGraphicCheck(): void {
|
||||
if (!this.drag) return;
|
||||
// 遍历筛选
|
||||
const boxRect = this.box.getLocalBounds();
|
||||
const app = this.app;
|
||||
const selects: JlGraphic[] = [];
|
||||
app.queryStore.getAllGraphics().forEach((g) => {
|
||||
if (!this.selectFilter || this.selectFilter(g)) {
|
||||
// 选择过滤器
|
||||
if (g.boxIntersectCheck(boxRect)) {
|
||||
selects.push(g);
|
||||
}
|
||||
}
|
||||
});
|
||||
app.updateSelected(...selects);
|
||||
}
|
||||
|
||||
onDrag(e: FederatedMouseEvent) {
|
||||
if (this.start) {
|
||||
const current = this.app.toCanvasCoordinates(e.global);
|
||||
const dragStart =
|
||||
Math.abs(current.x - this.start.x) > this.threshold ||
|
||||
Math.abs(current.y - this.start.y) > this.threshold;
|
||||
if (this.leftDownTarget instanceof JlCanvas) {
|
||||
// 画布drag
|
||||
if (!this.drag && dragStart) {
|
||||
this.drag = true;
|
||||
this.app.canvas.addChild(this.box);
|
||||
}
|
||||
if (this.drag) {
|
||||
this.boxSelectDraw(this.start, current);
|
||||
// this.boxSelectGraphicCheck();
|
||||
}
|
||||
} else {
|
||||
// 图形drag
|
||||
if (this.start && !this.drag && dragStart) {
|
||||
// 启动拖拽
|
||||
if (this.leftDownTarget) {
|
||||
const s = this.start;
|
||||
const dragEvent = new GraphicDragEvent(
|
||||
this.app,
|
||||
e,
|
||||
this.leftDownTarget,
|
||||
s,
|
||||
s
|
||||
);
|
||||
this.handleDragEvent(dragEvent, 'dragstart');
|
||||
}
|
||||
this.last = this.start.clone();
|
||||
this.drag = true;
|
||||
}
|
||||
|
||||
// drag移动处理
|
||||
if (this.drag && this.last && this.start) {
|
||||
const current = this.app.toCanvasCoordinates(e.global);
|
||||
const dx = current.x - this.last.x;
|
||||
const dy = current.y - this.last.y;
|
||||
if (this.leftDownTarget) {
|
||||
const dragEvent = new GraphicDragEvent(
|
||||
this.app,
|
||||
e,
|
||||
this.leftDownTarget,
|
||||
this.start,
|
||||
current,
|
||||
dx,
|
||||
dy
|
||||
);
|
||||
this.handleDragEvent(dragEvent, 'dragmove');
|
||||
}
|
||||
this.last = current;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* drag操作结束处理
|
||||
* @param e
|
||||
*/
|
||||
onDragEnd(e: FederatedMouseEvent) {
|
||||
if (this.leftDownTarget instanceof JlCanvas) {
|
||||
this.boxSelectGraphicCheck();
|
||||
} else {
|
||||
if (this.drag) {
|
||||
const end = this.app.toCanvasCoordinates(e.global);
|
||||
if (this.start && this.leftDownTarget) {
|
||||
const dragEvent = new GraphicDragEvent(
|
||||
this.app,
|
||||
e,
|
||||
this.leftDownTarget,
|
||||
this.start,
|
||||
end
|
||||
);
|
||||
this.handleDragEvent(dragEvent, 'dragend');
|
||||
}
|
||||
}
|
||||
}
|
||||
const canvas = this.app.canvas;
|
||||
canvas.off('mousemove', this.onDrag, this);
|
||||
canvas.off('mouseup', this.onDragEnd, this);
|
||||
canvas.off('mouseupoutside', this.onDragEnd, this);
|
||||
this.clearCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理拖拽事件(执行、发布)
|
||||
* @param dragEvent
|
||||
* @param type
|
||||
*/
|
||||
handleDragEvent(
|
||||
dragEvent: GraphicDragEvent,
|
||||
type: 'dragstart' | 'dragmove' | 'dragend'
|
||||
): void {
|
||||
const graphic = dragEvent.target.getGraphic();
|
||||
const targets: DisplayObject[] = [];
|
||||
if (!graphic) {
|
||||
targets.push(dragEvent.target);
|
||||
} else {
|
||||
if (
|
||||
dragEvent.target.isGraphicChild() &&
|
||||
dragEvent.target.selected &&
|
||||
dragEvent.target.draggable
|
||||
) {
|
||||
// 图形子元素
|
||||
recursiveChildren(graphic, (child) => {
|
||||
if (child.selected && child.draggable) {
|
||||
targets.push(child);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// 图形对象
|
||||
targets.push(...this.app.selectedGraphics);
|
||||
}
|
||||
}
|
||||
if (type === 'dragstart') {
|
||||
targets.forEach((target) => {
|
||||
target.dragStartPoint = target.position.clone();
|
||||
target.emit(type, dragEvent);
|
||||
if (!target.isAssistantAppend()) {
|
||||
target.emit('transformstart', target);
|
||||
}
|
||||
});
|
||||
// 显示吸附图形
|
||||
if (this.absorbablePositions && this.absorbablePositions.length > 0) {
|
||||
this.apContainer.removeChildren();
|
||||
this.apContainer.addChild(...this.absorbablePositions);
|
||||
}
|
||||
} else {
|
||||
// 处理位移
|
||||
targets.forEach((target) => {
|
||||
if (target.dragStartPoint) {
|
||||
target.position.set(
|
||||
target.dragStartPoint.x + dragEvent.dsx,
|
||||
target.dragStartPoint.y + dragEvent.dsy
|
||||
);
|
||||
}
|
||||
});
|
||||
// 处理吸附
|
||||
if (this.absorbablePositions) {
|
||||
for (let i = 0; i < this.absorbablePositions.length; i++) {
|
||||
const ap = this.absorbablePositions[i];
|
||||
if (ap.tryAbsorb(...targets)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 事件发布
|
||||
targets.forEach((target) => {
|
||||
target.emit(type, dragEvent);
|
||||
if (type === 'dragend' && !target.isAssistantAppend()) {
|
||||
target.emit('transformend', target);
|
||||
}
|
||||
});
|
||||
|
||||
if (type === 'dragend') {
|
||||
if (this.app.selectedGraphics.length == 1) {
|
||||
this.app.selectedGraphics[0].repaint();
|
||||
}
|
||||
targets.forEach((target) => {
|
||||
target.dragStartPoint = null;
|
||||
});
|
||||
// 移除吸附图形
|
||||
this.absorbablePositions = [];
|
||||
this.apContainer.removeChildren();
|
||||
}
|
||||
}
|
||||
this.app.emit(type, dragEvent);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
import { Container, FederatedPointerEvent, Point } from 'pixi.js';
|
||||
import { GraphicApp, GraphicCreateOperation } from '../app';
|
||||
import { JlGraphic } from '../core';
|
||||
import { KeyListener } from './KeyboardPlugin';
|
||||
|
||||
export class GraphicCopyPlugin {
|
||||
container: Container;
|
||||
app: GraphicApp;
|
||||
keyListeners: KeyListener[];
|
||||
copys: JlGraphic[];
|
||||
start?: Point;
|
||||
running = false;
|
||||
moveLimit?: 'x' | 'y';
|
||||
constructor(app: GraphicApp) {
|
||||
this.app = app;
|
||||
this.container = new Container();
|
||||
this.copys = [];
|
||||
this.keyListeners = [];
|
||||
this.keyListeners.push(
|
||||
new KeyListener({
|
||||
// ESC 用于取消复制操作
|
||||
value: 'Escape',
|
||||
global: true,
|
||||
// combinations: [CombinationKey.Ctrl],
|
||||
onPress: () => {
|
||||
this.cancle();
|
||||
},
|
||||
}),
|
||||
new KeyListener({
|
||||
// X 限制只能在x轴移动
|
||||
value: 'KeyX',
|
||||
global: true,
|
||||
// combinations: [CombinationKey.Ctrl],
|
||||
onPress: () => {
|
||||
this.updateMoveLimit('x');
|
||||
},
|
||||
}),
|
||||
new KeyListener({
|
||||
// Y 限制只能在y轴移动
|
||||
value: 'KeyY',
|
||||
global: true,
|
||||
// combinations: [CombinationKey.Ctrl],
|
||||
onPress: () => {
|
||||
this.updateMoveLimit('y');
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateMoveLimit(limit?: 'x' | 'y'): void {
|
||||
if (this.moveLimit === limit) {
|
||||
this.moveLimit = undefined;
|
||||
} else {
|
||||
this.moveLimit = limit;
|
||||
}
|
||||
}
|
||||
|
||||
init(): void {
|
||||
if (this.running) return;
|
||||
if (this.app.selectedGraphics.length === 0) {
|
||||
throw new Error('没有选中图形,复制取消');
|
||||
}
|
||||
this.running = true;
|
||||
this.copys = [];
|
||||
this.container.alpha = 0.5;
|
||||
this.app.canvas.addChild(this.container);
|
||||
const app = this.app;
|
||||
this.app.selectedGraphics.forEach((g) => {
|
||||
const template = app.getGraphicTemplatesByType(g.type);
|
||||
const clone = template.clone(g);
|
||||
this.copys.push(clone);
|
||||
this.container.addChild(clone);
|
||||
});
|
||||
this.app.canvas.on('mousemove', this.onPointerMove, this);
|
||||
this.app.canvas.on('pointertap', this.onFinish, this);
|
||||
this.keyListeners.forEach((kl) => {
|
||||
this.app.addKeyboardListener(kl);
|
||||
});
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.running = false;
|
||||
this.start = undefined;
|
||||
this.moveLimit = undefined;
|
||||
this.copys = [];
|
||||
this.container.removeChildren();
|
||||
this.app.canvas.removeChild(this.container);
|
||||
this.app.canvas.off('mousemove', this.onPointerMove, this);
|
||||
this.app.canvas.off('pointertap', this.onFinish, this);
|
||||
this.keyListeners.forEach((kl) => {
|
||||
this.app.removeKeyboardListener(kl);
|
||||
});
|
||||
}
|
||||
|
||||
onPointerMove(e: FederatedPointerEvent): void {
|
||||
const cp = this.app.toCanvasCoordinates(e.global);
|
||||
if (!this.start) {
|
||||
this.start = cp;
|
||||
} else {
|
||||
if (this.moveLimit === 'x') {
|
||||
const dx = cp.x - this.start.x;
|
||||
this.container.position.x = dx;
|
||||
this.container.position.y = 0;
|
||||
} else if (this.moveLimit === 'y') {
|
||||
const dy = cp.y - this.start.y;
|
||||
this.container.position.x = 0;
|
||||
this.container.position.y = dy;
|
||||
} else {
|
||||
const dx = cp.x - this.start.x;
|
||||
const dy = cp.y - this.start.y;
|
||||
this.container.position.x = dx;
|
||||
this.container.position.y = dy;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onFinish(): void {
|
||||
console.log('复制确认');
|
||||
// 将图形添加到app
|
||||
this.copys.forEach((g) => {
|
||||
g.position.x += this.container.position.x;
|
||||
g.position.y += this.container.position.y;
|
||||
});
|
||||
this.app.addGraphics(...this.copys);
|
||||
// 创建图形对象操作记录
|
||||
this.app.opRecord.record(new GraphicCreateOperation(this.app, this.copys));
|
||||
this.app.detectRelations();
|
||||
this.app.updateSelected(...this.copys);
|
||||
this.clear();
|
||||
}
|
||||
|
||||
cancle(): void {
|
||||
console.log('复制操作取消');
|
||||
this.app.canvas.removeChild(this.container);
|
||||
this.clear();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,232 @@
|
|||
import {
|
||||
Color,
|
||||
Container,
|
||||
DisplayObject,
|
||||
Graphics,
|
||||
IDestroyOptions,
|
||||
IPointData,
|
||||
} from 'pixi.js';
|
||||
import { JlGraphic } from '../core';
|
||||
import { DraggablePoint } from '../graphic';
|
||||
import { calculateMirrorPoint, distance2 } from '../utils';
|
||||
import { GraphicDragEvent } from './CommonMousePlugin';
|
||||
|
||||
export abstract class GraphicEditPlugin extends Container {
|
||||
graphic: JlGraphic;
|
||||
constructor(g: JlGraphic) {
|
||||
super();
|
||||
this.graphic = g;
|
||||
this.zIndex = 2;
|
||||
this.graphic.on('transformstart', this.hideAll, this);
|
||||
this.graphic.on('transformend', this.showAll, this);
|
||||
this.graphic.on('repaint', this.showAll, this);
|
||||
}
|
||||
|
||||
destroy(options?: boolean | IDestroyOptions | undefined): void {
|
||||
this.graphic.off('transformstart', this.hideAll, this);
|
||||
this.graphic.off('transformend', this.showAll, this);
|
||||
this.graphic.off('repaint', this.showAll, this);
|
||||
super.destroy(options);
|
||||
}
|
||||
|
||||
abstract updateEditedPointsPosition(): void;
|
||||
|
||||
hideAll() {
|
||||
this.visible = false;
|
||||
}
|
||||
showAll() {
|
||||
this.updateEditedPointsPosition();
|
||||
this.visible = true;
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class LineEditPlugin extends GraphicEditPlugin {
|
||||
linePoints: IPointData[];
|
||||
editedPoints: DraggablePoint[] = [];
|
||||
onEditPointCreate?: onEditPointCreate;
|
||||
constructor(
|
||||
g: JlGraphic,
|
||||
linePoints: IPointData[],
|
||||
onEditPointCreate?: onEditPointCreate
|
||||
) {
|
||||
super(g);
|
||||
this.linePoints = linePoints;
|
||||
this.onEditPointCreate = onEditPointCreate;
|
||||
this.graphic.on('pointupdate', this.reset, this);
|
||||
}
|
||||
|
||||
destroy(options?: boolean | IDestroyOptions | undefined): void {
|
||||
this.graphic.off('pointupdate', this.reset, this);
|
||||
super.destroy(options);
|
||||
}
|
||||
|
||||
reset(_obj: DisplayObject, points: IPointData[]): void {
|
||||
this.linePoints = points;
|
||||
this.removeChildren();
|
||||
this.editedPoints.splice(0, this.editedPoints.length);
|
||||
this.initEditPoints();
|
||||
}
|
||||
|
||||
abstract initEditPoints(): void;
|
||||
}
|
||||
|
||||
export type onEditPointCreate = (
|
||||
g: JlGraphic,
|
||||
dp: DraggablePoint,
|
||||
index: number
|
||||
) => void;
|
||||
/**
|
||||
* 折线编辑(兼容线段)
|
||||
*/
|
||||
export class PolylineEditPlugin extends LineEditPlugin {
|
||||
static Name = 'line_points_edit';
|
||||
constructor(
|
||||
g: JlGraphic,
|
||||
linePoints: IPointData[],
|
||||
onEditPointCreate?: onEditPointCreate
|
||||
) {
|
||||
super(g, linePoints, onEditPointCreate);
|
||||
this.name = PolylineEditPlugin.Name;
|
||||
this.initEditPoints();
|
||||
}
|
||||
|
||||
initEditPoints() {
|
||||
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
|
||||
for (let i = 0; i < cps.length; i++) {
|
||||
const p = cps[i];
|
||||
const dp = new DraggablePoint(p);
|
||||
dp.on('dragmove', () => {
|
||||
const tlp = this.graphic.canvasToLocalPoint(dp.position);
|
||||
const cp = this.linePoints[i];
|
||||
cp.x = tlp.x;
|
||||
cp.y = tlp.y;
|
||||
this.graphic.repaint();
|
||||
});
|
||||
if (this.onEditPointCreate) {
|
||||
this.onEditPointCreate(this.graphic, dp, i);
|
||||
}
|
||||
this.editedPoints.push(dp);
|
||||
}
|
||||
this.addChild(...this.editedPoints);
|
||||
}
|
||||
updateEditedPointsPosition() {
|
||||
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
|
||||
if (cps.length === this.editedPoints.length) {
|
||||
for (let i = 0; i < cps.length; i++) {
|
||||
const cp = cps[i];
|
||||
this.editedPoints[i].position.copyFrom(cp);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 贝塞尔曲线编辑
|
||||
*/
|
||||
export class BezierCurveEditPlugin extends LineEditPlugin {
|
||||
static Name = 'bezier_curve_points_edit';
|
||||
// 曲线控制点辅助线
|
||||
auxiliaryLines: Graphics[] = [];
|
||||
constructor(
|
||||
g: JlGraphic,
|
||||
linePoints: IPointData[],
|
||||
onEditPointCreate?: onEditPointCreate
|
||||
) {
|
||||
super(g, linePoints, onEditPointCreate);
|
||||
this.name = BezierCurveEditPlugin.Name;
|
||||
this.initEditPoints();
|
||||
}
|
||||
|
||||
reset(_obj: DisplayObject, points: IPointData[]): void {
|
||||
this.auxiliaryLines.splice(0, this.auxiliaryLines.length);
|
||||
super.reset(_obj, points);
|
||||
}
|
||||
|
||||
initEditPoints() {
|
||||
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
|
||||
for (let i = 0; i < cps.length; i++) {
|
||||
const p = cps[i];
|
||||
const dp = new DraggablePoint(p);
|
||||
const startOrEnd = i == 0 || i == cps.length - 1;
|
||||
const c = i % 3;
|
||||
if (c === 1) {
|
||||
const fp = cps[i - 1];
|
||||
const line = new Graphics();
|
||||
this.drawAuxiliaryLine(line, fp, p);
|
||||
this.auxiliaryLines.push(line);
|
||||
} else if (c === 2) {
|
||||
const np = cps[i + 1];
|
||||
const line = new Graphics();
|
||||
this.drawAuxiliaryLine(line, p, np);
|
||||
this.auxiliaryLines.push(line);
|
||||
}
|
||||
dp.on('dragmove', (de: GraphicDragEvent) => {
|
||||
const tlp = this.graphic.canvasToLocalPoint(dp.position);
|
||||
const cp = this.linePoints[i];
|
||||
cp.x = tlp.x;
|
||||
cp.y = tlp.y;
|
||||
if (c === 0 && !startOrEnd) {
|
||||
const fp = this.linePoints[i - 1];
|
||||
const np = this.linePoints[i + 1];
|
||||
fp.x = fp.x + de.dx;
|
||||
fp.y = fp.y + de.dy;
|
||||
np.x = np.x + de.dx;
|
||||
np.y = np.y + de.dy;
|
||||
} else if (c === 1 && i !== 1) {
|
||||
const bp = this.linePoints[i - 1];
|
||||
const fp2 = this.linePoints[i - 2];
|
||||
const distance = distance2(bp, fp2);
|
||||
const mp = calculateMirrorPoint(bp, cp, distance);
|
||||
fp2.x = mp.x;
|
||||
fp2.y = mp.y;
|
||||
} else if (c === 2 && i !== cps.length - 2) {
|
||||
const bp = this.linePoints[i + 1];
|
||||
const np2 = this.linePoints[i + 2];
|
||||
const distance = distance2(bp, np2);
|
||||
const mp = calculateMirrorPoint(bp, cp, distance);
|
||||
np2.x = mp.x;
|
||||
np2.y = mp.y;
|
||||
}
|
||||
this.graphic.repaint();
|
||||
});
|
||||
if (this.onEditPointCreate) {
|
||||
this.onEditPointCreate(this.graphic, dp, i);
|
||||
}
|
||||
this.editedPoints.push(dp);
|
||||
if (this.auxiliaryLines.length > 0) {
|
||||
this.addChild(...this.auxiliaryLines);
|
||||
}
|
||||
}
|
||||
this.addChild(...this.editedPoints);
|
||||
}
|
||||
|
||||
drawAuxiliaryLine(line: Graphics, p1: IPointData, p2: IPointData) {
|
||||
line.clear();
|
||||
line.lineStyle(1, new Color('blue'));
|
||||
line.moveTo(p1.x, p1.y);
|
||||
line.lineTo(p2.x, p2.y);
|
||||
}
|
||||
|
||||
updateEditedPointsPosition() {
|
||||
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
|
||||
if (cps.length === this.editedPoints.length) {
|
||||
for (let i = 0; i < cps.length; i++) {
|
||||
const cp = cps[i];
|
||||
this.editedPoints[i].position.copyFrom(cp);
|
||||
const c = i % 3;
|
||||
const d = Math.floor(i / 3);
|
||||
if (c === 1 || c === 2) {
|
||||
const li = d * 2 + c - 1;
|
||||
const line = this.auxiliaryLines[li];
|
||||
if (c === 1) {
|
||||
const fp = cps[i - 1];
|
||||
this.drawAuxiliaryLine(line, fp, cp);
|
||||
} else {
|
||||
const np = cps[i + 1];
|
||||
this.drawAuxiliaryLine(line, cp, np);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,243 @@
|
|||
import { FederatedMouseEvent } from 'pixi.js';
|
||||
import { GraphicApp } from '../app/JlGraphicApp';
|
||||
import { JlGraphic } from '../core/JlGraphic';
|
||||
|
||||
export enum InteractionPluginType {
|
||||
App = 'app',
|
||||
Graphic = 'graphic',
|
||||
Other = 'other',
|
||||
}
|
||||
|
||||
/**
|
||||
* 交互插件
|
||||
*/
|
||||
export interface InteractionPlugin {
|
||||
readonly _type: string;
|
||||
name: string; // 唯一标识
|
||||
app: GraphicApp;
|
||||
|
||||
/**
|
||||
* 停止
|
||||
*/
|
||||
pause(): void;
|
||||
/**
|
||||
* 恢复
|
||||
*/
|
||||
resume(): void;
|
||||
/**
|
||||
* 是否生效
|
||||
*/
|
||||
isActive(): boolean;
|
||||
/**
|
||||
* 关闭绑定的交互事件,清理插件相关数据(如需要),从app中移除
|
||||
*/
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
export class ViewportMovePlugin implements InteractionPlugin {
|
||||
static Name = '__viewport-move';
|
||||
readonly _type = InteractionPluginType.Other;
|
||||
name = ViewportMovePlugin.Name; // 唯一标识
|
||||
app: GraphicApp;
|
||||
|
||||
moveHandler: NodeJS.Timeout | null = null;
|
||||
moveSpeedx = 0;
|
||||
moveSpeedy = 0;
|
||||
|
||||
_pause: boolean;
|
||||
|
||||
constructor(app: GraphicApp) {
|
||||
this.app = app;
|
||||
this._pause = true;
|
||||
app.registerInteractionPlugin(this);
|
||||
}
|
||||
|
||||
static new(app: GraphicApp): ViewportMovePlugin {
|
||||
return new ViewportMovePlugin(app);
|
||||
}
|
||||
|
||||
resume(): void {
|
||||
this.app.canvas.on('pointermove', this.viewportMove, this);
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
this.app.canvas.off('pointermove', this.viewportMove, this);
|
||||
}
|
||||
|
||||
isActive(): boolean {
|
||||
return !this._pause;
|
||||
}
|
||||
destroy(): void {
|
||||
this.pause();
|
||||
this.app.removeInteractionPlugin(this);
|
||||
}
|
||||
|
||||
startMove(moveSpeedx: number, moveSpeedy: number) {
|
||||
this.moveSpeedx = moveSpeedx;
|
||||
this.moveSpeedy = moveSpeedy;
|
||||
if (this.moveHandler == null) {
|
||||
const viewport = this.app.viewport;
|
||||
this.moveHandler = setInterval(() => {
|
||||
viewport.moveCorner(
|
||||
viewport.corner.x + this.moveSpeedx,
|
||||
viewport.corner.y + this.moveSpeedy
|
||||
);
|
||||
}, 50);
|
||||
}
|
||||
}
|
||||
|
||||
stopMove() {
|
||||
if (this.moveHandler != null) {
|
||||
clearInterval(this.moveHandler);
|
||||
this.moveHandler = null;
|
||||
}
|
||||
}
|
||||
|
||||
viewportMove(e: FederatedMouseEvent) {
|
||||
const sp = e.global;
|
||||
const viewport = this.app.viewport;
|
||||
const range = 50; // 触发范围和移动速度范围
|
||||
let moveSpeedx = 0;
|
||||
let moveSpeedy = 0;
|
||||
const ds = 3; // 移动速度减小比例控制
|
||||
if (sp.x < range) {
|
||||
moveSpeedx = sp.x - range;
|
||||
} else if (sp.x > viewport.screenWidth - range) {
|
||||
moveSpeedx = sp.x + range - viewport.screenWidth;
|
||||
} else {
|
||||
moveSpeedx = 0;
|
||||
}
|
||||
if (sp.y < range) {
|
||||
moveSpeedy = sp.y - range;
|
||||
} else if (sp.y > viewport.screenHeight - range) {
|
||||
moveSpeedy = sp.y + range - viewport.screenHeight;
|
||||
} else {
|
||||
moveSpeedy = 0;
|
||||
}
|
||||
if (moveSpeedx == 0 && moveSpeedy == 0) {
|
||||
this.app.canvas.cursor = 'auto';
|
||||
this.stopMove();
|
||||
} else {
|
||||
this.app.canvas.cursor = 'grab';
|
||||
this.startMove(moveSpeedx / ds, moveSpeedy / ds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用交互插件,同时只能生效一个
|
||||
*/
|
||||
export abstract class AppInteractionPlugin implements InteractionPlugin {
|
||||
readonly _type = InteractionPluginType.App;
|
||||
name: string; // 唯一标识
|
||||
app: GraphicApp;
|
||||
_pause: boolean;
|
||||
constructor(name: string, app: GraphicApp) {
|
||||
this.name = name;
|
||||
this.app = app;
|
||||
this._pause = true;
|
||||
app.registerInteractionPlugin(this);
|
||||
}
|
||||
isActive(): boolean {
|
||||
return !this._pause;
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
this.unbind();
|
||||
this._pause = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复,app交互插件同时只能生效一个
|
||||
*/
|
||||
resume(): void {
|
||||
this.app.pauseAppInteractionPlugins();
|
||||
this.bind();
|
||||
this._pause = false;
|
||||
}
|
||||
|
||||
abstract bind(): void;
|
||||
abstract unbind(): void;
|
||||
|
||||
destroy(): void {
|
||||
this.pause();
|
||||
this.app.removeInteractionPlugin(this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形交互插件,可同时生效
|
||||
*/
|
||||
export abstract class GraphicInteractionPlugin<G extends JlGraphic>
|
||||
implements InteractionPlugin
|
||||
{
|
||||
readonly _type = InteractionPluginType.Graphic;
|
||||
app: GraphicApp;
|
||||
name: string; // 唯一标识
|
||||
_pause: boolean;
|
||||
constructor(name: string, app: GraphicApp) {
|
||||
this.app = app;
|
||||
this.name = name;
|
||||
this._pause = true;
|
||||
app.registerInteractionPlugin(this);
|
||||
this.resume();
|
||||
// 新增的图形对象绑定
|
||||
this.app.on('graphicstored', (g) => {
|
||||
if (this.isActive()) {
|
||||
this.binds(this.filter(g));
|
||||
}
|
||||
});
|
||||
this.app.on('graphicdeleted', (g) => {
|
||||
if (this.isActive()) {
|
||||
this.unbinds(this.filter(g));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
isActive(): boolean {
|
||||
return !this._pause;
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
const list = this.filter(...this.app.queryStore.getAllGraphics());
|
||||
this.unbinds(list);
|
||||
this._pause = true;
|
||||
}
|
||||
|
||||
resume(): void {
|
||||
const list = this.filter(...this.app.queryStore.getAllGraphics());
|
||||
this.binds(list);
|
||||
this._pause = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤需要的图形对象
|
||||
*/
|
||||
abstract filter(...grahpics: JlGraphic[]): G[] | undefined;
|
||||
|
||||
binds(list?: G[]): void {
|
||||
if (list) {
|
||||
list.forEach((g) => this.bind(g));
|
||||
}
|
||||
}
|
||||
unbinds(list?: G[]): void {
|
||||
if (list) {
|
||||
list.forEach((g) => this.unbind(g));
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 绑定图形对象的交互处理
|
||||
* @param g 图形对象
|
||||
*/
|
||||
abstract bind(g: G): void;
|
||||
/**
|
||||
* 取消图形对象的交互处理
|
||||
* @param g 图形对象
|
||||
*/
|
||||
abstract unbind(g: G): void;
|
||||
|
||||
destroy(): void {
|
||||
this.pause();
|
||||
this.app.removeInteractionPlugin(this);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,346 @@
|
|||
import { GraphicApp } from '../app/JlGraphicApp';
|
||||
|
||||
let target: Node | undefined;
|
||||
|
||||
export class GlobalKeyboardHelper {
|
||||
appKeyboardPluginMap: JlGraphicAppKeyboardPlugin[] = [];
|
||||
|
||||
constructor() {
|
||||
window.onkeydown = (e: KeyboardEvent) => {
|
||||
this.appKeyboardPluginMap.forEach((plugin) => {
|
||||
const listenerMap = plugin.getKeyListener(e);
|
||||
listenerMap?.forEach((listener) => {
|
||||
if (listener.global) {
|
||||
listener.press(e, plugin.app);
|
||||
}
|
||||
});
|
||||
});
|
||||
if (e.ctrlKey) {
|
||||
if (e.code == 'KeyS') {
|
||||
// 屏蔽全局Ctrl+S保存操作
|
||||
// console.log('屏蔽全局Ctrl+S')
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (target && target.nodeName == 'CANVAS') {
|
||||
// 事件的目标是画布时,屏蔽总的键盘操作操作
|
||||
if (e.ctrlKey) {
|
||||
if (e.code == 'KeyA' || e.code == 'KeyS') {
|
||||
// 屏蔽Canvas上的Ctrl+A、Ctrl+S操作
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
window.onkeyup = (e: KeyboardEvent) => {
|
||||
this.appKeyboardPluginMap.forEach((plugin) => {
|
||||
const listenerMap = plugin.getKeyListener(e);
|
||||
listenerMap?.forEach((listener) => {
|
||||
if (listener.global) {
|
||||
listener.release(e, plugin.app);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
registerGAKPlugin(plugin: JlGraphicAppKeyboardPlugin) {
|
||||
if (!this.appKeyboardPluginMap.find((pg) => pg == plugin)) {
|
||||
this.appKeyboardPluginMap.push(plugin);
|
||||
}
|
||||
}
|
||||
|
||||
removeGAKPlugin(plugin: JlGraphicAppKeyboardPlugin) {
|
||||
const index = this.appKeyboardPluginMap.findIndex((pg) => pg == plugin);
|
||||
if (index >= 0) {
|
||||
this.appKeyboardPluginMap.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const GlobalKeyboardPlugin = new GlobalKeyboardHelper();
|
||||
|
||||
export class JlGraphicAppKeyboardPlugin {
|
||||
app: GraphicApp;
|
||||
/**
|
||||
* 结构为Map<key.code|key.key|key.keyCode, Map<KeyListener.identifier, KeyListener>>
|
||||
*/
|
||||
keyListenerMap: Map<number | string, Map<string, KeyListener>> = new Map<
|
||||
number | string,
|
||||
Map<string, KeyListener>
|
||||
>(); // 键值监听map
|
||||
keyListenerStackMap: Map<string, KeyListener[]> = new Map<
|
||||
string,
|
||||
KeyListener[]
|
||||
>(); // 键值监听栈(多次注册相同的监听会把之前注册的监听器入栈,移除最新的监听会从栈中弹出一个作为指定事件监听处理器)
|
||||
|
||||
constructor(app: GraphicApp) {
|
||||
this.app = app;
|
||||
GlobalKeyboardPlugin.registerGAKPlugin(this);
|
||||
const onMouseUpdateTarget = (e: MouseEvent) => {
|
||||
const node = e.target as Node;
|
||||
target = node;
|
||||
// console.log('Mousedown Event', node.nodeName, node.nodeType, node.nodeValue)
|
||||
};
|
||||
const keydownHandle = (e: KeyboardEvent) => {
|
||||
// console.log(e.key, e.code, e.keyCode);
|
||||
if (target && target == this.app.dom.getElementsByTagName('canvas')[0]) {
|
||||
const listenerMap = this.getKeyListener(e);
|
||||
listenerMap?.forEach((listener) => {
|
||||
if (!listener.global) {
|
||||
listener.press(e, this.app);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
const keyupHandle = (e: KeyboardEvent) => {
|
||||
if (target && target == this.app.dom.getElementsByTagName('canvas')[0]) {
|
||||
const listenerMap = this.getKeyListener(e);
|
||||
listenerMap?.forEach((listener) => {
|
||||
if (!listener.global) {
|
||||
listener.release(e, this.app);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', onMouseUpdateTarget, false);
|
||||
document.addEventListener('keydown', keydownHandle, false);
|
||||
document.addEventListener('keyup', keyupHandle, false);
|
||||
this.app.on('destroy', () => {
|
||||
document.removeEventListener('mousedown', onMouseUpdateTarget, false);
|
||||
document.removeEventListener('keydown', keydownHandle, false);
|
||||
document.removeEventListener('keyup', keyupHandle, false);
|
||||
});
|
||||
}
|
||||
|
||||
private getOrInit(key: string | number): Map<string, KeyListener> {
|
||||
let map = this.keyListenerMap.get(key);
|
||||
if (map === undefined) {
|
||||
map = new Map<string, KeyListener>();
|
||||
this.keyListenerMap.set(key, map);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private getOrInitStack(key: string): KeyListener[] {
|
||||
let stack = this.keyListenerStackMap.get(key);
|
||||
if (stack === undefined) {
|
||||
stack = [];
|
||||
this.keyListenerStackMap.set(key, stack);
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册按键监听,若有旧的,旧的入栈
|
||||
* @param keyListener
|
||||
*/
|
||||
addKeyListener(keyListener: KeyListener) {
|
||||
const map = this.getOrInit(keyListener.value);
|
||||
// 查询是否有旧的监听,若有入栈
|
||||
const old = map.get(keyListener.identifier);
|
||||
if (old) {
|
||||
const stack = this.getOrInitStack(keyListener.identifier);
|
||||
stack.push(old);
|
||||
}
|
||||
map.set(keyListener.identifier, keyListener);
|
||||
// console.log(this.getAllListenedKeys());
|
||||
}
|
||||
/**
|
||||
* 移除按键监听,若是当前注册的监听,尝试从栈中取出作为按键监听器,若是旧的,则同时移除栈中的监听
|
||||
* @param keyListener
|
||||
*/
|
||||
removeKeyListener(keyListener: KeyListener) {
|
||||
const map = this.getOrInit(keyListener.value);
|
||||
const old = map.get(keyListener.identifier);
|
||||
map.delete(keyListener.identifier);
|
||||
const stack = this.getOrInitStack(keyListener.identifier);
|
||||
if (old && old === keyListener) {
|
||||
// 是旧的监听
|
||||
const listener = stack.pop();
|
||||
if (listener) {
|
||||
map.set(keyListener.identifier, listener);
|
||||
}
|
||||
} else {
|
||||
// 移除栈中的
|
||||
const index = stack.findIndex((ls) => ls === keyListener);
|
||||
if (index >= 0) {
|
||||
stack.splice(index, 1);
|
||||
}
|
||||
}
|
||||
// console.log(this);
|
||||
}
|
||||
|
||||
getKeyListenerBy(key: string | number): Map<string, KeyListener> | undefined {
|
||||
return this.keyListenerMap.get(key);
|
||||
}
|
||||
|
||||
getKeyListener(e: KeyboardEvent): Map<string, KeyListener> | undefined {
|
||||
return (
|
||||
this.getKeyListenerBy(e.key) ||
|
||||
this.getKeyListenerBy(e.code) ||
|
||||
this.getKeyListenerBy(e.keyCode)
|
||||
);
|
||||
}
|
||||
|
||||
isKeyListened(key: string | number): boolean {
|
||||
return this.getOrInit(key).size > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有注册监听的键值(组合键)
|
||||
*/
|
||||
getAllListenedKeys(): string[] {
|
||||
const keys: string[] = [];
|
||||
this.keyListenerMap.forEach((v) =>
|
||||
v.forEach((_listener, ck) => keys.push(ck))
|
||||
);
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
|
||||
type KeyboardKeyHandler = (e: KeyboardEvent, app: GraphicApp) => void;
|
||||
|
||||
export enum CombinationKey {
|
||||
Ctrl = 'Ctrl',
|
||||
Alt = 'Alt',
|
||||
Shift = 'Shift',
|
||||
}
|
||||
export interface KeyListenerOptions {
|
||||
// 具体的键值,可以是key/code/keycode(keycode已经弃用,建议优先使用key或code),例如:KeyA/(a/A)分别表示键盘A建,其中KeyA为键盘事件的code字段,a/A为键盘事件的key字段
|
||||
value: string | number;
|
||||
// 组合键
|
||||
combinations?: CombinationKey[];
|
||||
// 是否监听全局,为false则只在画布为焦点时才处理
|
||||
global?: boolean;
|
||||
// 按下操作处理
|
||||
onPress?: KeyboardKeyHandler;
|
||||
// 按下操作是否每次触发,默认一次
|
||||
pressTriggerEveryTime?: boolean;
|
||||
// 释放/抬起操作处理
|
||||
onRelease?: KeyboardKeyHandler;
|
||||
}
|
||||
|
||||
export interface ICompleteKeyListenerOptions {
|
||||
// 具体的键值,可以是key/code/keycode(keycode已经弃用,建议优先使用key或code),例如:KeyA/(a/A)分别表示键盘A建,其中KeyA为键盘事件的code字段,a/A为键盘事件的key字段
|
||||
value: string | number;
|
||||
// 组合键
|
||||
combinations: CombinationKey[];
|
||||
// 是否监听全局,为false则只在画布为焦点时才处理
|
||||
global: boolean;
|
||||
// 按下操作处理
|
||||
onPress?: KeyboardKeyHandler;
|
||||
pressTriggerEveryTime: boolean;
|
||||
// 释放/抬起操作处理
|
||||
onRelease?: KeyboardKeyHandler;
|
||||
}
|
||||
|
||||
const DefaultKeyListenerOptions: ICompleteKeyListenerOptions = {
|
||||
value: '',
|
||||
combinations: [],
|
||||
global: false,
|
||||
onPress: undefined,
|
||||
pressTriggerEveryTime: false,
|
||||
onRelease: undefined,
|
||||
};
|
||||
|
||||
export class KeyListener {
|
||||
// value 支持keyCode,key,code三种值
|
||||
readonly options: ICompleteKeyListenerOptions;
|
||||
private isPress = false;
|
||||
|
||||
constructor(options: KeyListenerOptions) {
|
||||
this.options = Object.assign({}, DefaultKeyListenerOptions, options);
|
||||
}
|
||||
|
||||
static create(options: KeyListenerOptions): KeyListener {
|
||||
return new KeyListener(options);
|
||||
}
|
||||
|
||||
public get value(): string | number {
|
||||
return this.options.value;
|
||||
}
|
||||
|
||||
public get combinations(): string[] {
|
||||
return this.options.combinations;
|
||||
}
|
||||
|
||||
public get identifier(): string {
|
||||
return this.options.combinations.join('+') + '+' + this.options.value;
|
||||
}
|
||||
|
||||
public get global(): boolean | undefined {
|
||||
return this.options.global;
|
||||
}
|
||||
|
||||
public get onPress(): KeyboardKeyHandler | undefined {
|
||||
return this.options.onPress;
|
||||
}
|
||||
|
||||
public set onPress(v: KeyboardKeyHandler | undefined) {
|
||||
this.options.onPress = v;
|
||||
}
|
||||
|
||||
public get onRelease(): KeyboardKeyHandler | undefined {
|
||||
return this.options.onRelease;
|
||||
}
|
||||
|
||||
public set onRelease(v: KeyboardKeyHandler | undefined) {
|
||||
this.options.onRelease = v;
|
||||
}
|
||||
|
||||
public get pressTriggerEveryTime(): boolean {
|
||||
return this.options.pressTriggerEveryTime;
|
||||
}
|
||||
|
||||
public set pressTriggerEveryTime(v: boolean) {
|
||||
this.options.pressTriggerEveryTime = v;
|
||||
}
|
||||
|
||||
press(e: KeyboardEvent, app: GraphicApp): void {
|
||||
if (!this.checkCombinations(e)) {
|
||||
console.debug('组合键不匹配, 不执行press', e, this);
|
||||
return;
|
||||
}
|
||||
if (this.pressTriggerEveryTime || !this.isPress) {
|
||||
// console.log('Keydown: ', e, this.onPress);
|
||||
this.isPress = true;
|
||||
if (this.onPress) {
|
||||
this.onPress(e, app);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 检查组合键是否匹配
|
||||
*/
|
||||
checkCombinations(e: KeyboardEvent): boolean {
|
||||
const cbs = this.combinations;
|
||||
if (cbs.length > 0) {
|
||||
if (
|
||||
((e.altKey && cbs.includes(CombinationKey.Alt)) ||
|
||||
(!e.altKey && !cbs.includes(CombinationKey.Alt))) &&
|
||||
((e.ctrlKey && cbs.includes(CombinationKey.Ctrl)) ||
|
||||
(!e.ctrlKey && !cbs.includes(CombinationKey.Ctrl))) &&
|
||||
((e.shiftKey && cbs.includes(CombinationKey.Shift)) ||
|
||||
(!e.shiftKey && !cbs.includes(CombinationKey.Shift)))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
return !e.altKey && !e.ctrlKey && !e.shiftKey;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
release(e: KeyboardEvent, app: GraphicApp): void {
|
||||
if (this.isPress) {
|
||||
// console.log('Keyup : ', e.key, e);
|
||||
this.isPress = false;
|
||||
if (this.onRelease) {
|
||||
this.onRelease(e, app);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
export * from './InteractionPlugin';
|
||||
export * from './CommonMousePlugin';
|
||||
export * from './KeyboardPlugin';
|
||||
export * from './CopyPlugin';
|
|
@ -0,0 +1,668 @@
|
|||
import { Container, Graphics, Point, Rectangle, Text, utils } from 'pixi.js';
|
||||
import { GraphicApp } from '../app';
|
||||
import { OutOfBound } from '../utils';
|
||||
import {
|
||||
DefaultWhiteMenuOptions,
|
||||
MenuCompletionItemStyle,
|
||||
MenuCompletionOptions,
|
||||
MenuCompletionStyleOptions,
|
||||
MenuGroupOptions,
|
||||
MenuItemOptions,
|
||||
MenuOptions,
|
||||
} from './Menu';
|
||||
|
||||
export class ContextMenuPlugin {
|
||||
app: GraphicApp;
|
||||
contextMenuMap: Map<string, ContextMenu> = new Map<string, ContextMenu>();
|
||||
|
||||
constructor(app: GraphicApp) {
|
||||
this.app = app;
|
||||
}
|
||||
/**
|
||||
* 添加菜单
|
||||
*/
|
||||
addContextMenu(menu: ContextMenu) {
|
||||
if (this.contextMenuMap.has(menu.menuName)) {
|
||||
console.log(`已经存在name=${menu.menuName}的菜单`);
|
||||
}
|
||||
this.contextMenuMap.set(menu.menuName, menu);
|
||||
menu.plugin = this;
|
||||
}
|
||||
/**
|
||||
* 通过菜单名称打开菜单到指定坐标
|
||||
* @param menuName
|
||||
* @param global
|
||||
*/
|
||||
openMenu(menuName: string, global: Point) {
|
||||
const menu = this.contextMenuMap.get(menuName);
|
||||
if (menu) {
|
||||
this.open(menu, global);
|
||||
} else {
|
||||
console.warn(`不存在name=${menuName}的菜单`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 通过菜单名称关闭菜单
|
||||
* @param menuName
|
||||
*/
|
||||
closeMenu(menuName: string) {
|
||||
const menu = this.contextMenuMap.get(menuName);
|
||||
if (menu) {
|
||||
this.close(menu);
|
||||
} else {
|
||||
console.warn(`不存在name=${menuName}的菜单`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取视口屏幕宽度
|
||||
*/
|
||||
public get screenWidth(): number {
|
||||
return this.app.viewport.screenWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取视口屏幕高度
|
||||
*/
|
||||
public get screenHeight(): number {
|
||||
return this.app.viewport.screenHeight;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开菜单
|
||||
* @param menu
|
||||
* @param global
|
||||
*/
|
||||
open(menu: ContextMenu, global: Point) {
|
||||
if (!menu.opened) {
|
||||
menu.opened = true;
|
||||
this.app.app.stage.addChild(menu);
|
||||
}
|
||||
// 处理超出显示范围
|
||||
const screenHeight = this.screenHeight;
|
||||
const bottomY = global.y + menu.height;
|
||||
|
||||
let oob = this.oob(menu, global);
|
||||
const pos = global.clone();
|
||||
if (oob.right) {
|
||||
pos.x = global.x - menu.width;
|
||||
}
|
||||
if (oob.bottom) {
|
||||
const py = global.y - menu.height;
|
||||
if (py > 0) {
|
||||
pos.y = py;
|
||||
} else {
|
||||
pos.y = global.y - (bottomY - screenHeight);
|
||||
}
|
||||
}
|
||||
// 移动后是否左上超出
|
||||
oob = this.oob(menu, pos);
|
||||
if (oob.left) {
|
||||
pos.x = 0;
|
||||
}
|
||||
if (oob.top) {
|
||||
pos.y = 0;
|
||||
}
|
||||
menu.position.copyFrom(pos);
|
||||
}
|
||||
/**
|
||||
* 关闭菜单
|
||||
* @param menu
|
||||
*/
|
||||
close(menu: ContextMenu) {
|
||||
if (menu.opened) {
|
||||
menu.opened = false;
|
||||
this.app.app.stage.removeChild(menu);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 越界检查
|
||||
* @param menu
|
||||
* @param global
|
||||
* @returns
|
||||
*/
|
||||
oob(menu: ContextMenu, global: Point): OutOfBound {
|
||||
const screenWidth = this.screenWidth;
|
||||
const screenHeight = this.screenHeight;
|
||||
const bound = new Rectangle(0, 0, screenWidth, screenHeight);
|
||||
const menuRect = new Rectangle(global.x, global.y, menu.width, menu.height);
|
||||
return OutOfBound.check(menuRect, bound);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上下文菜单
|
||||
*/
|
||||
export class ContextMenu extends Container {
|
||||
parentMenuItem?: ContextMenuItem;
|
||||
openedSubMenu?: ContextMenu;
|
||||
menuOptions: MenuCompletionOptions;
|
||||
_plugin?: ContextMenuPlugin;
|
||||
opened = false;
|
||||
bg: Graphics;
|
||||
title?: Text;
|
||||
groups: MenuGroup[];
|
||||
private padding = 5;
|
||||
_active = false; // 激活状态
|
||||
timeoutCloseHandle?: NodeJS.Timeout;
|
||||
|
||||
constructor(menuOptions: MenuOptions, parentMenuItem?: ContextMenuItem) {
|
||||
super();
|
||||
this.menuOptions = Object.assign({}, DefaultWhiteMenuOptions, menuOptions);
|
||||
this.bg = new Graphics();
|
||||
this.groups = [];
|
||||
this.init();
|
||||
this.parentMenuItem = parentMenuItem;
|
||||
}
|
||||
|
||||
public get style(): MenuCompletionStyleOptions {
|
||||
return this.menuOptions.style;
|
||||
}
|
||||
|
||||
public get parentMenu(): ContextMenu | undefined {
|
||||
return this.parentMenuItem?.menu;
|
||||
}
|
||||
|
||||
public get rootMenu(): ContextMenu {
|
||||
if (this.parentMenu) {
|
||||
return this.parentMenu.rootMenu;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否存在激活的菜单项
|
||||
* @returns
|
||||
*/
|
||||
hasActiveItem(): boolean {
|
||||
for (let i = 0; i < this.groups.length; i++) {
|
||||
const group = this.groups[i];
|
||||
if (group.hasActiveItem()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public get active(): boolean {
|
||||
return (
|
||||
this._active ||
|
||||
this.hasActiveItem() ||
|
||||
(this.parentMenuItem != undefined && this.parentMenuItem._active)
|
||||
);
|
||||
}
|
||||
|
||||
public set active(v: boolean) {
|
||||
this._active = v;
|
||||
this.onActiveChanged();
|
||||
}
|
||||
|
||||
onActiveChanged() {
|
||||
if (this.parentMenuItem) {
|
||||
this.parentMenuItem.onActiveChanged();
|
||||
if (!this.active) {
|
||||
this.timeoutCloseHandle = setTimeout(() => {
|
||||
this.close();
|
||||
}, 500);
|
||||
} else {
|
||||
if (this.timeoutCloseHandle) {
|
||||
clearTimeout(this.timeoutCloseHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setOptions(menuOptions: MenuOptions) {
|
||||
this.menuOptions = Object.assign({}, DefaultWhiteMenuOptions, menuOptions);
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化
|
||||
*/
|
||||
init() {
|
||||
// this.initTitle();
|
||||
this.groups = [];
|
||||
const options = this.menuOptions;
|
||||
let maxItemWidth = 0;
|
||||
let borderHeight = 0;
|
||||
options.groups.forEach(group => {
|
||||
const menuGroup = new MenuGroup(this, group);
|
||||
this.groups.push(menuGroup);
|
||||
borderHeight += menuGroup.totalHeight;
|
||||
if (menuGroup.maxWidth > maxItemWidth) {
|
||||
maxItemWidth = menuGroup.maxWidth;
|
||||
}
|
||||
});
|
||||
|
||||
const splitLineWidth = 1;
|
||||
|
||||
const bgWidth = maxItemWidth + this.padding * 2;
|
||||
const bgHeight =
|
||||
borderHeight +
|
||||
this.groups.length * this.padding * 2 +
|
||||
(this.groups.length - 1) * splitLineWidth;
|
||||
|
||||
if (options.style.border) {
|
||||
this.bg.lineStyle(
|
||||
options.style.borderWidth,
|
||||
utils.string2hex(options.style.borderColor)
|
||||
);
|
||||
}
|
||||
this.bg.beginFill(utils.string2hex(options.style.backgroundColor));
|
||||
if (options.style.borderRoundRadius > 0) {
|
||||
this.bg.drawRoundedRect(
|
||||
0,
|
||||
0,
|
||||
bgWidth,
|
||||
bgHeight,
|
||||
options.style.borderRoundRadius
|
||||
);
|
||||
} else {
|
||||
this.bg.drawRect(0, 0, bgWidth, bgHeight);
|
||||
}
|
||||
this.bg.endFill();
|
||||
let groupHeight = 0;
|
||||
this.bg.lineStyle(
|
||||
splitLineWidth,
|
||||
utils.string2hex(options.style.borderColor)
|
||||
);
|
||||
for (let i = 0; i < this.groups.length; i++) {
|
||||
const group = this.groups[i];
|
||||
group.updateItemBox(maxItemWidth);
|
||||
group.position.set(this.padding, groupHeight + this.padding);
|
||||
if (i === this.groups.length - 1) {
|
||||
// 最后一个
|
||||
break;
|
||||
}
|
||||
const splitLineY = groupHeight + group.height + this.padding * 2;
|
||||
this.bg.moveTo(0, splitLineY);
|
||||
this.bg.lineTo(bgWidth, splitLineY);
|
||||
groupHeight = splitLineY + splitLineWidth;
|
||||
}
|
||||
|
||||
this.addChild(this.bg);
|
||||
this.addChild(...this.groups);
|
||||
|
||||
this.interactive = true;
|
||||
this.on('pointerover', () => {
|
||||
this.active = true;
|
||||
});
|
||||
this.on('pointerout', () => {
|
||||
this.active = false;
|
||||
});
|
||||
}
|
||||
|
||||
initTitle() {
|
||||
if (this.menuOptions.title) {
|
||||
this.title = new Text(this.menuOptions.title, { align: 'left' });
|
||||
}
|
||||
}
|
||||
|
||||
public get menuName(): string {
|
||||
return this.menuOptions.name;
|
||||
}
|
||||
|
||||
public get plugin(): ContextMenuPlugin {
|
||||
if (this.parentMenu) {
|
||||
return this.parentMenu.plugin;
|
||||
}
|
||||
if (this._plugin) {
|
||||
return this._plugin;
|
||||
}
|
||||
throw new Error(`上下文菜单name=${this.menuOptions.name}没有添加到插件中`);
|
||||
}
|
||||
|
||||
public set plugin(v: ContextMenuPlugin) {
|
||||
this._plugin = v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示菜单
|
||||
*/
|
||||
open(global: Point): void {
|
||||
if (this.parentMenu) {
|
||||
this.parentMenu.openSub(this, global);
|
||||
} else {
|
||||
this.plugin.open(this, global);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭菜单
|
||||
*/
|
||||
close(): void {
|
||||
if (this.openedSubMenu) {
|
||||
this.openedSubMenu.close();
|
||||
this.openedSubMenu = undefined;
|
||||
}
|
||||
this.plugin.close(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开子菜单
|
||||
* @param subMenu
|
||||
* @param global
|
||||
*/
|
||||
private openSub(subMenu: ContextMenu, global: Point) {
|
||||
if (this.openedSubMenu) {
|
||||
this.openedSubMenu.close();
|
||||
}
|
||||
const pos = global.clone();
|
||||
const oob = this.plugin.oob(subMenu, global);
|
||||
if (oob.right) {
|
||||
pos.x = this.position.x - subMenu.width + this.padding;
|
||||
}
|
||||
if (oob.bottom) {
|
||||
pos.y = this.plugin.screenHeight - subMenu.height - this.padding;
|
||||
}
|
||||
this.plugin.open(subMenu, pos);
|
||||
this.openedSubMenu = subMenu;
|
||||
}
|
||||
}
|
||||
|
||||
class MenuGroup extends Container {
|
||||
private gutter = 3; // 名称、快捷键、箭头文本间隙
|
||||
config: MenuGroupOptions;
|
||||
menu: ContextMenu;
|
||||
items: ContextMenuItem[] = [];
|
||||
constructor(menu: ContextMenu, config: MenuGroupOptions) {
|
||||
super();
|
||||
this.config = config;
|
||||
this.menu = menu;
|
||||
config.items.forEach(item => {
|
||||
this.items.push(new ContextMenuItem(menu, item));
|
||||
});
|
||||
for (let i = 0; i < this.items.length; i++) {
|
||||
const item = this.items[i];
|
||||
item.position.y = i * item.totalHeight;
|
||||
}
|
||||
this.addChild(...this.items);
|
||||
}
|
||||
|
||||
hasActiveItem(): boolean {
|
||||
for (let i = 0; i < this.items.length; i++) {
|
||||
const item = this.items[i];
|
||||
if (item.active) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public get maxWidth(): number {
|
||||
const maxNameWidth = this.items
|
||||
.map(item => item.nameBounds.width)
|
||||
.sort()
|
||||
.reverse()[0];
|
||||
const maxShortcutWidth = this.items
|
||||
.map(item => item.shortcutKeyBounds.width)
|
||||
.sort()
|
||||
.reverse()[0];
|
||||
const maxWidth =
|
||||
maxNameWidth +
|
||||
this.gutter +
|
||||
maxShortcutWidth +
|
||||
this.items[0].paddingLeft +
|
||||
this.items[0].paddingRight;
|
||||
return maxWidth;
|
||||
}
|
||||
|
||||
public get totalHeight(): number {
|
||||
let total = 0;
|
||||
this.items.forEach(item => (total += item.totalHeight));
|
||||
return total;
|
||||
}
|
||||
|
||||
updateItemBox(maxItemWidth: number) {
|
||||
this.items.forEach(item => item.updateBox(maxItemWidth, item.totalHeight));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 菜单项
|
||||
*/
|
||||
class ContextMenuItem extends Container {
|
||||
menu: ContextMenu;
|
||||
config: MenuItemOptions;
|
||||
/**
|
||||
* 名称文本
|
||||
*/
|
||||
nameText?: Text;
|
||||
/**
|
||||
* 快捷键文本
|
||||
*/
|
||||
shortcutKeyText?: Text;
|
||||
private gutter = 3; // 名称、快捷键、箭头文本间隙
|
||||
arrowText?: Text;
|
||||
box: Graphics;
|
||||
subMenu?: ContextMenu;
|
||||
_active = false; // 激活状态
|
||||
|
||||
constructor(menu: ContextMenu, config: MenuItemOptions) {
|
||||
super();
|
||||
this.menu = menu;
|
||||
this.config = config;
|
||||
this.box = new Graphics();
|
||||
this.addChild(this.box);
|
||||
|
||||
this.initNameText();
|
||||
this.initShortcutKeyText();
|
||||
this.initSubMenu();
|
||||
}
|
||||
|
||||
public get active(): boolean {
|
||||
return this._active || (this.subMenu != undefined && this.subMenu.active);
|
||||
}
|
||||
|
||||
public set active(v: boolean) {
|
||||
this._active = v;
|
||||
if (this.subMenu) {
|
||||
this.subMenu.onActiveChanged();
|
||||
}
|
||||
this.onActiveChanged();
|
||||
}
|
||||
|
||||
onActiveChanged() {
|
||||
if (this.active) {
|
||||
this.box.alpha = 1;
|
||||
} else {
|
||||
this.box.alpha = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public get textWidth(): number {
|
||||
return this.nameBounds.width + this.shortcutKeyBounds.width + this.gutter;
|
||||
}
|
||||
|
||||
public get nameGraphic(): Text {
|
||||
if (this.nameText) {
|
||||
return this.nameText;
|
||||
}
|
||||
throw new Error(`菜单项name=${this.config.name}没有初始化名称图形对象`);
|
||||
}
|
||||
|
||||
public get totalHeight(): number {
|
||||
return this.paddingTop + this.paddingBottom + this.nameGraphic.height;
|
||||
}
|
||||
|
||||
public get nameBounds(): Rectangle {
|
||||
return this.nameGraphic.getLocalBounds();
|
||||
}
|
||||
|
||||
public get shortcutKeyBounds(): Rectangle {
|
||||
if (this.shortcutKeyText) {
|
||||
return this.shortcutKeyText.getLocalBounds();
|
||||
} else {
|
||||
return new Rectangle(0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public get style(): MenuCompletionItemStyle {
|
||||
return this.menu.style.itemStyle;
|
||||
}
|
||||
|
||||
private checkPadding(padding: number | number[]) {
|
||||
if (Array.isArray(padding)) {
|
||||
if (padding.length !== 2 && padding.length !== 4) {
|
||||
throw new Error('错误的padding数据');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private toWholePadding(padding: number | number[]): number[] {
|
||||
this.checkPadding(padding);
|
||||
if (Array.isArray(padding)) {
|
||||
if (padding.length == 2) {
|
||||
return [padding[0], padding[1], padding[0], padding[1]];
|
||||
} else {
|
||||
return padding;
|
||||
}
|
||||
} else {
|
||||
return [padding, padding, padding, padding];
|
||||
}
|
||||
}
|
||||
|
||||
public get paddingTop(): number {
|
||||
return this.toWholePadding(this.menu.style.itemStyle.padding)[0];
|
||||
}
|
||||
public get paddingBottom(): number {
|
||||
return this.toWholePadding(this.menu.style.itemStyle.padding)[2];
|
||||
}
|
||||
public get paddingLeft(): number {
|
||||
return this.toWholePadding(this.menu.style.itemStyle.padding)[3];
|
||||
}
|
||||
public get paddingRight(): number {
|
||||
return this.toWholePadding(this.menu.style.itemStyle.padding)[1];
|
||||
}
|
||||
|
||||
public get hoverColor(): string {
|
||||
return this.style.hoverColor;
|
||||
}
|
||||
|
||||
public get fontSize(): number {
|
||||
return this.style.fontSize;
|
||||
}
|
||||
|
||||
public get fontColor(): string {
|
||||
if (this.config.disabled) {
|
||||
return this.style.disabledFontColor;
|
||||
} else if (this.config.fontColor) {
|
||||
return this.config.fontColor;
|
||||
}
|
||||
return this.style.fontColor;
|
||||
}
|
||||
|
||||
initNameText(): Text {
|
||||
this.nameText = new Text(this.config.name, {
|
||||
fontSize: this.fontSize,
|
||||
fill: this.fontColor,
|
||||
});
|
||||
this.addChild(this.nameText);
|
||||
return this.nameText;
|
||||
}
|
||||
|
||||
initShortcutKeyText(): Text | undefined {
|
||||
if (this.config.shortcutKeys && this.config.shortcutKeys.length > 0) {
|
||||
this.shortcutKeyText = new Text(this.config.shortcutKeys.join('+'), {
|
||||
fontSize: this.fontSize,
|
||||
fill: this.fontColor,
|
||||
});
|
||||
this.addChild(this.shortcutKeyText);
|
||||
return this.shortcutKeyText;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
initSubMenu() {
|
||||
if (this.config.subMenu && this.config.subMenu.length > 0) {
|
||||
this.arrowText = new Text('>', {
|
||||
fontSize: this.fontSize,
|
||||
fill: this.fontColor,
|
||||
});
|
||||
this.addChild(this.arrowText);
|
||||
this.subMenu = new ContextMenu(
|
||||
{
|
||||
name: `${this.config.name}子菜单`,
|
||||
groups: this.config.subMenu,
|
||||
style: this.menu.style,
|
||||
},
|
||||
this
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
updateBackground(width: number, height: number) {
|
||||
this.box.clear();
|
||||
const box = this.box;
|
||||
const style = this.menu.style;
|
||||
if (!style.itemStyle.hoverColor) {
|
||||
throw new Error('未设置菜单项的hoverColor');
|
||||
}
|
||||
let hoverColor = style.itemStyle.hoverColor;
|
||||
if (this.style && this.style.hoverColor) {
|
||||
hoverColor = this.style.hoverColor;
|
||||
}
|
||||
box.beginFill(utils.string2hex(hoverColor));
|
||||
if (style.borderRoundRadius > 0) {
|
||||
box.drawRoundedRect(0, 0, width, height, style.borderRoundRadius);
|
||||
} else {
|
||||
box.drawRect(0, 0, width, height);
|
||||
}
|
||||
box.endFill();
|
||||
box.alpha = 0;
|
||||
}
|
||||
|
||||
updateBox(width: number, height: number) {
|
||||
this.removeAllListeners();
|
||||
this.updateBackground(width, height);
|
||||
this.nameText?.position.set(this.paddingLeft, this.paddingTop);
|
||||
if (this.shortcutKeyText) {
|
||||
const skTextWidth = this.shortcutKeyBounds.width;
|
||||
this.shortcutKeyText.position.set(
|
||||
width - skTextWidth - this.paddingRight,
|
||||
this.paddingTop
|
||||
);
|
||||
}
|
||||
if (this.arrowText) {
|
||||
this.arrowText.position.set(
|
||||
width - this.paddingRight - this.gutter,
|
||||
this.paddingTop
|
||||
);
|
||||
}
|
||||
|
||||
// 事件监听
|
||||
this.interactive = true;
|
||||
this.hitArea = new Rectangle(0, 0, width, height);
|
||||
this.cursor = 'pointer';
|
||||
this.on('pointerover', () => {
|
||||
this.active = true;
|
||||
if (this.config.disabled) {
|
||||
this.cursor = 'not-allowed';
|
||||
} else {
|
||||
this.cursor = 'pointer';
|
||||
}
|
||||
if (this.subMenu) {
|
||||
const p = this.toGlobal(new Point(this.width));
|
||||
this.subMenu.open(p);
|
||||
}
|
||||
});
|
||||
this.on('pointerout', () => {
|
||||
this.active = false;
|
||||
});
|
||||
this.on('pointertap', () => {
|
||||
if (this.config.disabled) {
|
||||
// 禁用,不处理
|
||||
return;
|
||||
}
|
||||
if (this.config.onClick) {
|
||||
this.config.onClick();
|
||||
}
|
||||
if (!this.config.subMenu || this.config.subMenu.length === 0) {
|
||||
this.active = false;
|
||||
this.menu.active = false;
|
||||
this.menu.rootMenu.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,173 @@
|
|||
/**
|
||||
* 菜单配置项
|
||||
*/
|
||||
export interface MenuOptions {
|
||||
/**
|
||||
* 菜单名称,需唯一
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 菜单标题
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* 菜单分组
|
||||
*/
|
||||
groups: MenuGroupOptions[];
|
||||
/**
|
||||
* 菜单样式
|
||||
*/
|
||||
style?: MenuStyleOptions;
|
||||
}
|
||||
/**
|
||||
* 菜单分组
|
||||
*/
|
||||
export interface MenuGroupOptions {
|
||||
/**
|
||||
* 菜单项
|
||||
*/
|
||||
items: MenuItemOptions[];
|
||||
}
|
||||
|
||||
export interface MenuCompletionOptions extends MenuOptions {
|
||||
style: MenuCompletionStyleOptions;
|
||||
}
|
||||
/**
|
||||
* 菜单样式配置项
|
||||
*/
|
||||
export interface MenuStyleOptions {
|
||||
/**
|
||||
* 菜单标题样式
|
||||
*/
|
||||
titleStyle?: MenuItemStyle;
|
||||
/**
|
||||
* 菜单背景色
|
||||
*/
|
||||
backgroundColor?: string;
|
||||
/**
|
||||
* 菜单边框线宽度,默认1,0为无线框
|
||||
*/
|
||||
borderWidth?: number;
|
||||
/**
|
||||
* 菜单边框颜色
|
||||
*/
|
||||
borderColor?: string;
|
||||
/**
|
||||
* 包围框是否圆角,小于等于0为直角,圆角的半径
|
||||
*/
|
||||
borderRoundRadius?: number;
|
||||
/**
|
||||
* 菜单项样式
|
||||
*/
|
||||
itemStyle?: MenuItemStyle;
|
||||
}
|
||||
|
||||
export interface MenuCompletionStyleOptions extends MenuStyleOptions {
|
||||
titleStyle: MenuItemStyle;
|
||||
backgroundColor: string;
|
||||
border: boolean;
|
||||
borderWidth: number;
|
||||
borderColor: string;
|
||||
borderRoundRadius: number;
|
||||
itemStyle: MenuCompletionItemStyle;
|
||||
}
|
||||
|
||||
export interface MenuItemOptions {
|
||||
/**
|
||||
* 名称
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 是否禁用,默认不禁用
|
||||
*/
|
||||
disabled?: boolean;
|
||||
/**
|
||||
* 快捷键
|
||||
*/
|
||||
shortcutKeys?: string[];
|
||||
/**
|
||||
* 点击处理
|
||||
*/
|
||||
onClick?: () => void;
|
||||
// /**
|
||||
// * 菜单项字体样式,覆盖MenuOptions中的通用样式
|
||||
// */
|
||||
// style?: MenuItemStyle;
|
||||
fontColor?: string;
|
||||
/**
|
||||
* 子菜单
|
||||
*/
|
||||
subMenu?: MenuGroupOptions[];
|
||||
}
|
||||
|
||||
export interface MenuItemStyle {
|
||||
/**
|
||||
* 字体大小
|
||||
*/
|
||||
fontSize: number;
|
||||
/**
|
||||
* 字体颜色
|
||||
*/
|
||||
fontColor?: string;
|
||||
// /**
|
||||
// * 字体对齐
|
||||
// */
|
||||
// align?: TextStyleAlign;
|
||||
/**
|
||||
* hover颜色
|
||||
*/
|
||||
hoverColor?: string;
|
||||
/**
|
||||
* 禁用下字体颜色
|
||||
*/
|
||||
disabledFontColor?: string;
|
||||
/**
|
||||
* 内边距
|
||||
*/
|
||||
padding: number[] | number; // 内边距
|
||||
}
|
||||
export interface MenuCompletionItemStyle extends MenuItemStyle {
|
||||
fontColor: string;
|
||||
// align: TextStyleAlign;
|
||||
hoverColor: string;
|
||||
/**
|
||||
* 禁用下字体颜色
|
||||
*/
|
||||
disabledFontColor: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认的白色样式
|
||||
*/
|
||||
export const DefaultWhiteStyleOptions: MenuCompletionStyleOptions = {
|
||||
titleStyle: {
|
||||
fontSize: 16,
|
||||
fontColor: '#000000',
|
||||
padding: [5, 15],
|
||||
},
|
||||
backgroundColor: '#ffffff',
|
||||
border: true,
|
||||
borderWidth: 1,
|
||||
borderColor: '#4C4C4C',
|
||||
/**
|
||||
* 默认直角
|
||||
*/
|
||||
borderRoundRadius: 5,
|
||||
itemStyle: {
|
||||
fontSize: 16,
|
||||
fontColor: '#000000',
|
||||
padding: [5, 25],
|
||||
// align: 'left',
|
||||
hoverColor: '#1E78DB',
|
||||
disabledFontColor: '#9D9D9D',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 默认的白色菜单配置
|
||||
*/
|
||||
export const DefaultWhiteMenuOptions: MenuCompletionOptions = {
|
||||
name: '',
|
||||
style: DefaultWhiteStyleOptions,
|
||||
groups: [],
|
||||
};
|
|
@ -0,0 +1,475 @@
|
|||
import {
|
||||
Container,
|
||||
DisplayObject,
|
||||
IPointData,
|
||||
Matrix,
|
||||
Point,
|
||||
Rectangle,
|
||||
} from 'pixi.js';
|
||||
import Vector2 from '../math/Vector2';
|
||||
import { floatEquals, isZero } from '../math';
|
||||
|
||||
/**
|
||||
* 递归父节点执行逻辑
|
||||
* @param obj
|
||||
* @param handler
|
||||
*/
|
||||
export function recursiveParents(
|
||||
obj: DisplayObject,
|
||||
handler: (parent: Container) => void
|
||||
): void {
|
||||
if (obj.parent) {
|
||||
handler(obj.parent);
|
||||
recursiveParents(obj.parent, handler);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归父节点查询父节点对象
|
||||
* @param obj
|
||||
* @param finder
|
||||
* @returns
|
||||
*/
|
||||
export function recursiveFindParent(
|
||||
obj: DisplayObject,
|
||||
finder: (parent: Container) => boolean
|
||||
): Container | null {
|
||||
if (obj.parent) {
|
||||
if (finder(obj.parent)) {
|
||||
return obj.parent;
|
||||
} else {
|
||||
return recursiveFindParent(obj.parent, finder);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归子节点执行逻辑
|
||||
* @param container
|
||||
* @param handler
|
||||
*/
|
||||
export function recursiveChildren(
|
||||
container: Container,
|
||||
handler: (child: DisplayObject) => void
|
||||
): void {
|
||||
container.children.forEach((child) => {
|
||||
handler(child);
|
||||
if (child.children) {
|
||||
recursiveChildren(child as Container, handler);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归子节点查询子节点对象
|
||||
*/
|
||||
export function recursiveFindChild(
|
||||
container: Container,
|
||||
finder: (child: DisplayObject) => boolean
|
||||
): DisplayObject | null {
|
||||
for (let i = 0; i < container.children.length; i++) {
|
||||
const child = container.children[i];
|
||||
if (finder(child)) {
|
||||
return child;
|
||||
} else if (child.children) {
|
||||
return recursiveFindChild(child as Container, finder);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface BezierPoints {
|
||||
p1: IPointData;
|
||||
p2: IPointData;
|
||||
cp1: IPointData;
|
||||
cp2: IPointData;
|
||||
}
|
||||
|
||||
export function convertToBezierPoints(points: IPointData[]): BezierPoints[] {
|
||||
if (points.length < 4 && points.length % 3 !== 1) {
|
||||
throw new Error(`bezierCurve 数据错误: ${points}`);
|
||||
}
|
||||
const bps: BezierPoints[] = [];
|
||||
for (let i = 0; i < points.length - 3; i += 3) {
|
||||
const p1 = new Point(points[i].x, points[i].y);
|
||||
const p2 = new Point(points[i + 3].x, points[i + 3].y);
|
||||
const cp1 = new Point(points[i + 1].x, points[i + 1].y);
|
||||
const cp2 = new Point(points[i + 2].x, points[i + 2].y);
|
||||
bps.push({
|
||||
p1,
|
||||
p2,
|
||||
cp1,
|
||||
cp2,
|
||||
});
|
||||
}
|
||||
return bps;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算矩形中点
|
||||
*/
|
||||
export function getRectangleCenter(rectangle: Rectangle): Point {
|
||||
return new Point(
|
||||
rectangle.x + rectangle.width / 2,
|
||||
rectangle.y + rectangle.height / 2
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算两个矩形中心对齐的坐标, PS: 计算的是较大包围框的中心
|
||||
* @param rect1
|
||||
* @param rect2
|
||||
* @returns
|
||||
*/
|
||||
export function getCenterOfTwoRectangle(
|
||||
rect1: Rectangle,
|
||||
rect2: Rectangle
|
||||
): Point {
|
||||
const x = Math.abs(rect1.width - rect2.width) / 2;
|
||||
const y = Math.abs(rect1.height - rect2.height) / 2;
|
||||
return new Point(x, y);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增量更新点坐标
|
||||
* @param p
|
||||
* @param dx
|
||||
* @param dy
|
||||
*/
|
||||
export function updatePoint<P extends IPointData>(
|
||||
p: P,
|
||||
dx: number,
|
||||
dy: number
|
||||
): P {
|
||||
p.x += dx;
|
||||
p.y += dy;
|
||||
return p;
|
||||
}
|
||||
/**
|
||||
* 序列化图形变换
|
||||
* @param obj
|
||||
* @returns
|
||||
*/
|
||||
export function serializeTransform(obj: DisplayObject): number[] {
|
||||
const position = obj.position;
|
||||
const scale = obj.scale;
|
||||
const angle = obj.angle;
|
||||
const skew = obj.skew;
|
||||
return [position.x, position.y, scale.x, scale.y, angle, skew.x, skew.y];
|
||||
}
|
||||
/**
|
||||
* 反序列化变换数据到图形对象
|
||||
* @param obj
|
||||
* @param transform
|
||||
*/
|
||||
export function deserializeTransformInto(
|
||||
obj: DisplayObject,
|
||||
transform: number[]
|
||||
): void {
|
||||
if (transform.length === 7) {
|
||||
obj.position.set(transform[0], transform[1]);
|
||||
obj.scale.set(transform[2], transform[3]);
|
||||
obj.angle = transform[4];
|
||||
obj.skew.set(transform[5], transform[6]);
|
||||
} else if (transform.length > 0) {
|
||||
console.warn('错误的变换数据', transform);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算变换后的点坐标
|
||||
* @param point 坐标点
|
||||
* @param transform 变换矩阵
|
||||
* @returns
|
||||
*/
|
||||
export function calculateTransformedPoint(
|
||||
point: IPointData,
|
||||
transform: Matrix
|
||||
): Point {
|
||||
const { a, b, c, d, tx, ty } = transform;
|
||||
const x = a * point.x + c * point.y + tx;
|
||||
const y = b * point.x + d * point.y + ty;
|
||||
return new Point(x, y);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将直线转换为多边形
|
||||
* @param p1
|
||||
* @param p2
|
||||
* @param thick
|
||||
* @returns
|
||||
*/
|
||||
export function convertLineToPolygonPoints(
|
||||
p1: IPointData,
|
||||
p2: IPointData,
|
||||
thick: number
|
||||
): IPointData[] {
|
||||
const angle = Math.atan2(p2.y - p1.y, p2.x - p1.x) - Math.PI / 2;
|
||||
const half = thick / 2;
|
||||
const cos = Math.cos(angle) * half;
|
||||
const sin = Math.sin(angle) * half;
|
||||
return [
|
||||
new Point(p1.x - cos, p1.y - sin),
|
||||
new Point(p2.x - cos, p2.y - sin),
|
||||
new Point(p2.x + cos, p2.y + sin),
|
||||
new Point(p1.x + cos, p1.y + sin),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换矩形为多边形点坐标
|
||||
* @param rect 矩形
|
||||
* @returns
|
||||
*/
|
||||
export function convertRectangleToPolygonPoints(rect: Rectangle): IPointData[] {
|
||||
return [
|
||||
new Point(rect.x, rect.y),
|
||||
new Point(rect.x + rect.width, rect.y),
|
||||
new Point(rect.x + rect.width, rect.y + rect.height),
|
||||
new Point(rect.x, rect.y + rect.height),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算线段中点坐标
|
||||
* @param p1
|
||||
* @param p2
|
||||
* @returns
|
||||
*/
|
||||
export function calculateLineMidpoint(p1: IPointData, p2: IPointData): Point {
|
||||
const x = (p1.x + p2.x) / 2;
|
||||
const y = (p1.y + p2.y) / 2;
|
||||
return new Point(x, y);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算点到直线距离
|
||||
* @param p1
|
||||
* @param p2
|
||||
* @param p
|
||||
*/
|
||||
export function calculateDistanceFromPointToLine(
|
||||
p1: IPointData,
|
||||
p2: IPointData,
|
||||
p: IPointData
|
||||
): number {
|
||||
// 求直线的一般方程参数ABC,直线的一般式方程AX+BY+C=0
|
||||
const A = p1.y - p2.y;
|
||||
const B = p2.x - p1.x;
|
||||
const C = p1.x * p2.y - p1.y * p2.x;
|
||||
// 计算点到直线垂直距离: d = |Ax+By+C|/sqrt(A*A+B*B),其中x,y为点坐标
|
||||
const dl = Math.abs(A * p.x + B * p.y + C) / Math.sqrt(A * A + B * B);
|
||||
return dl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算点到直线的垂足坐标
|
||||
* @param p
|
||||
* @param p1
|
||||
* @param p2
|
||||
*/
|
||||
export function calculateFootPointFromPointToLine(
|
||||
p1: IPointData,
|
||||
p2: IPointData,
|
||||
p: IPointData
|
||||
): Point {
|
||||
if (p1.x == p2.x && p1.y == p2.y) {
|
||||
throw new Error(`直线两坐标点相等:${p1}`);
|
||||
}
|
||||
const k = -(
|
||||
((p1.x - p.x) * (p2.x - p1.x) + (p1.y - p.y) * (p2.y - p1.y)) /
|
||||
(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2))
|
||||
);
|
||||
if (isZero(k)) {
|
||||
return new Point(p.x, p.y);
|
||||
}
|
||||
const xf = k * (p2.x - p1.x) + p1.x;
|
||||
const yf = k * (p2.y - p1.y) + p1.y;
|
||||
return new Point(xf, yf);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算直线与圆的交点
|
||||
* 1用直线到圆心的距离和半径相比,判断是否和圆有交点;
|
||||
* 2求出圆心在直线上面的垂点;
|
||||
* 3算出直线的单位向量e;
|
||||
* 4求出一侧交点(Intersection)到projectPoint的长度(sideLength);
|
||||
* 5求出sideLength和这侧端点到projectPoint距离的比例(ratio);
|
||||
* 6projectPoint +/- ratio * e = 两侧交点;
|
||||
* @param p0 圆心坐标
|
||||
* @param radius 圆半径
|
||||
* @param p1 直线坐标1
|
||||
* @param p2 直线坐标2
|
||||
* @returns 交点坐标,可能2/1/0个
|
||||
*/
|
||||
export function calculateIntersectionPointOfCircleAndLine(
|
||||
p0: IPointData,
|
||||
radius: number,
|
||||
p1: IPointData,
|
||||
p2: IPointData
|
||||
): Point[] {
|
||||
const distance = calculateDistanceFromPointToLine(p1, p2, p0);
|
||||
if (distance <= radius) {
|
||||
// 有交点
|
||||
// 计算垂点
|
||||
const pr = calculateFootPointFromPointToLine(p1, p2, p0);
|
||||
if (floatEquals(distance, radius)) {
|
||||
// 切线
|
||||
return [pr];
|
||||
}
|
||||
const vpr = new Vector2([pr.x, pr.y]);
|
||||
const vc = new Vector2([p0.x, p0.y]);
|
||||
// 计算直线单位向量
|
||||
const v1 = new Vector2([p1.x, p1.y]);
|
||||
const v2 = new Vector2([p2.x, p2.y]);
|
||||
const ve = Vector2.direction(v2, v1);
|
||||
const base = Math.sqrt(
|
||||
Math.abs(radius * radius - Vector2.difference(vpr, vc).squaredLength())
|
||||
);
|
||||
const vl = ve.scale(base);
|
||||
const ip1 = Vector2.sum(vpr, vl);
|
||||
const ip2 = Vector2.difference(vpr, vl);
|
||||
return [new Point(ip1.x, ip1.y), new Point(ip2.x, ip2.y)];
|
||||
} else {
|
||||
// 无交点
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算圆心与圆心外一点与圆的交点(取圆心到点的向量与圆的交点)
|
||||
* @param p0 圆心坐标
|
||||
* @param radius 圆半径
|
||||
* @param p 点坐标
|
||||
* @returns
|
||||
*/
|
||||
export function calculateIntersectionPointOfCircleAndPoint(
|
||||
p0: IPointData,
|
||||
radius: number,
|
||||
p: IPointData
|
||||
): Point {
|
||||
const points = calculateIntersectionPointOfCircleAndLine(p0, radius, p0, p);
|
||||
const vc = new Vector2([p0.x, p0.y]);
|
||||
const vp = new Vector2([p.x, p.y]);
|
||||
const vecp = Vector2.direction(vp, vc);
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
const ip = points[i];
|
||||
const ve = Vector2.direction(new Vector2([ip.x, ip.y]), vc);
|
||||
if (ve.equals(vecp)) {
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
throw new Error('计算圆心与圆心外一点与圆的交点逻辑错误');
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算点基于点的镜像点坐标
|
||||
* @param bp 基准点
|
||||
* @param p 待镜像的点坐标
|
||||
* @param distance 镜像点到基准点的距离,默认为p到基准点的距离
|
||||
* @returns
|
||||
*/
|
||||
export function calculateMirrorPoint(
|
||||
bp: IPointData,
|
||||
p: IPointData,
|
||||
distance?: number
|
||||
): Point {
|
||||
const vbp = Vector2.from(bp);
|
||||
const vp = Vector2.from(p);
|
||||
const direction = Vector2.direction(vbp, vp);
|
||||
if (distance == undefined) {
|
||||
distance = Vector2.distance(vbp, vp);
|
||||
}
|
||||
const vmp = Vector2.sum(vbp, direction.scale(distance));
|
||||
return new Point(vmp.x, vmp.y);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算基于给定轴的给定点的镜像点坐标
|
||||
* @param pa 给定轴线的坐标
|
||||
* @param pb 给定轴线的坐标
|
||||
* @param p 待镜像点坐标
|
||||
* @param distance
|
||||
* @returns
|
||||
*/
|
||||
export function calculateMirrorPointBasedOnAxis(
|
||||
pa: IPointData,
|
||||
pb: IPointData,
|
||||
p: IPointData,
|
||||
distance?: number
|
||||
): Point {
|
||||
const fp = calculateFootPointFromPointToLine(pa, pb, p);
|
||||
if (fp.equals(p)) {
|
||||
return fp;
|
||||
} else {
|
||||
return calculateMirrorPoint(fp, p, distance);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算直线与水平夹角,角度按顺时针,从0开始
|
||||
* @param p1
|
||||
* @param p2
|
||||
* @returns 角度,范围[0, 360)
|
||||
*/
|
||||
export function angleToAxisx(p1: IPointData, p2: IPointData): number {
|
||||
if (p1.x == p2.x && p1.y == p2.y) {
|
||||
throw new Error('一个点无法计算角度');
|
||||
}
|
||||
const dx = Math.abs(p1.x - p2.x);
|
||||
const dy = Math.abs(p1.y - p2.y);
|
||||
|
||||
if (p2.x == p1.x) {
|
||||
if (p2.y > p1.y) {
|
||||
return 90;
|
||||
} else {
|
||||
return 270;
|
||||
}
|
||||
}
|
||||
if (p2.y == p1.y) {
|
||||
if (p2.x > p1.x) {
|
||||
return 0;
|
||||
} else {
|
||||
return 180;
|
||||
}
|
||||
}
|
||||
const angle = (Math.atan2(dy, dx) * 180) / Math.PI;
|
||||
if (p2.x > p1.x) {
|
||||
if (p2.y > p1.y) {
|
||||
return angle;
|
||||
} else if (p2.y < p1.y) {
|
||||
return 360 - angle;
|
||||
}
|
||||
} else if (p2.x < p1.x) {
|
||||
if (p2.y > p1.y) {
|
||||
return 180 - angle;
|
||||
} else {
|
||||
return 180 + angle;
|
||||
}
|
||||
}
|
||||
return angle;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算两线夹角,pc与pa,pb的夹角,顺时针为正,逆时针为负
|
||||
* @param pa 交点
|
||||
* @param pb 锚定
|
||||
* @param pc
|
||||
* @returns 夹角, [-180, 180]
|
||||
*/
|
||||
export function angleOfIncludedAngle(
|
||||
pa: IPointData,
|
||||
pb: IPointData,
|
||||
pc: IPointData
|
||||
): number {
|
||||
const abAngle = angleToAxisx(pa, pb);
|
||||
const acAngle = angleToAxisx(pa, pc);
|
||||
let angle = acAngle - abAngle;
|
||||
if (angle < -180) {
|
||||
angle = 360 + angle;
|
||||
} else if (angle > 180) {
|
||||
angle = -(360 - angle);
|
||||
}
|
||||
return angle;
|
||||
}
|
|
@ -0,0 +1,362 @@
|
|||
import { IPointData, Point, Rectangle } from 'pixi.js';
|
||||
// /**
|
||||
// * 点线碰撞检测
|
||||
// * @param pa 线段a端坐标
|
||||
// * @param pb 线段b端坐标
|
||||
// * @param p 点坐标
|
||||
// * @param tolerance 容忍度,越大检测范围越大
|
||||
// * @returns
|
||||
// */
|
||||
// export function linePoint(pa: Point, pb: Point, p: Point, tolerance: number): boolean {
|
||||
// return (Math.abs(distanceSquared(pa.x, pa.y, pb.x, pb.y) - (distanceSquared(pa.x, pa.y, p.x, p.y) + distanceSquared(pb.x, pb.y, p.x, p.y))) <= tolerance)
|
||||
// }
|
||||
|
||||
/**
|
||||
* 根据点到直线的垂直距离计算碰撞
|
||||
* @param pa 线段a端坐标
|
||||
* @param pb 线段b端坐标
|
||||
* @param p 点坐标
|
||||
* @param lineWidth 线宽
|
||||
* @param exact 是否精确(使用给定线宽,否则线宽会设置为8)
|
||||
* @returns
|
||||
*/
|
||||
export function linePoint(
|
||||
pa: IPointData,
|
||||
pb: IPointData,
|
||||
p: IPointData,
|
||||
lineWidth: number,
|
||||
exact = false
|
||||
): boolean {
|
||||
if (!exact && lineWidth < 6) {
|
||||
lineWidth = 6;
|
||||
}
|
||||
// 求直线的一般方程参数ABC,直线的一般式方程AX+BY+C=0
|
||||
const A = pa.y - pb.y;
|
||||
const B = pb.x - pa.x;
|
||||
const C = pa.x * pb.y - pa.y * pb.x;
|
||||
// 计算点到直线垂直距离: d = |Ax+By+C|/sqrt(A*A+B*B),其中x,y为点坐标
|
||||
const dl = Math.abs(A * p.x + B * p.y + C) / Math.sqrt(A * A + B * B);
|
||||
const intersect = dl <= lineWidth / 2;
|
||||
if (intersect) {
|
||||
// 距离在线宽范围内,再判断点是否超过线段两端点范围外(两端点外会有一点误差,两端点线宽一半半径的圆范围内)
|
||||
const da = distance(pa.x, pa.y, p.x, p.y);
|
||||
const db = distance(pb.x, pb.y, p.x, p.y);
|
||||
const dab = distance(pa.x, pa.y, pb.x, pb.y);
|
||||
return da <= dl + dab && db <= dl + dab;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 折线与点碰撞
|
||||
* @param points 折线端点列表
|
||||
* @param p 点座标
|
||||
* @param lineWidth 线宽
|
||||
*/
|
||||
export function polylinePoint(
|
||||
points: IPointData[],
|
||||
p: IPointData,
|
||||
lineWidth: number
|
||||
) {
|
||||
const len = points.length;
|
||||
for (let i = 0; i < len - 1; i++) {
|
||||
if (linePoint(points[i], points[i + 1], p, lineWidth)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 线线碰撞检测
|
||||
* @param pa 线段1a端坐标
|
||||
* @param pb 线段1b端坐标
|
||||
* @param p1 线段2a端坐标
|
||||
* @param p2 线段2b端坐标
|
||||
* @returns
|
||||
*/
|
||||
export function lineLine(
|
||||
pa: IPointData,
|
||||
pb: IPointData,
|
||||
p1: IPointData,
|
||||
p2: IPointData
|
||||
): boolean {
|
||||
const x1 = pa.x;
|
||||
const y1 = pa.y;
|
||||
const x2 = pb.x;
|
||||
const y2 = pb.y;
|
||||
const x3 = p1.x;
|
||||
const y3 = p1.y;
|
||||
const x4 = p2.x;
|
||||
const y4 = p2.y;
|
||||
const s1_x = x2 - x1;
|
||||
const s1_y = y2 - y1;
|
||||
const s2_x = x4 - x3;
|
||||
const s2_y = y4 - y3;
|
||||
const s =
|
||||
(-s1_y * (x1 - x3) + s1_x * (y1 - y3)) / (-s2_x * s1_y + s1_x * s2_y);
|
||||
const t =
|
||||
(s2_x * (y1 - y3) - s2_y * (x1 - x3)) / (-s2_x * s1_y + s1_x * s2_y);
|
||||
return s >= 0 && s <= 1 && t >= 0 && t <= 1;
|
||||
}
|
||||
/**
|
||||
* 点和矩形碰撞检测
|
||||
* @param p 点作弊
|
||||
* @param rect 矩形
|
||||
* @returns
|
||||
*/
|
||||
export function pointBox(p: IPointData, rect: Rectangle): boolean {
|
||||
const { x, y, width, height } = rect;
|
||||
const x2 = p.x;
|
||||
const y2 = p.y;
|
||||
return x2 >= x && x2 <= x + width && y2 >= y && y2 <= y + height;
|
||||
}
|
||||
/**
|
||||
* 线和矩形碰撞检测
|
||||
* @param pa 线段a端坐标
|
||||
* @param pb 线段b端坐标
|
||||
* @param rect 矩形
|
||||
* @returns
|
||||
*/
|
||||
export function lineBox(
|
||||
pa: IPointData,
|
||||
pb: IPointData,
|
||||
rect: Rectangle
|
||||
): boolean {
|
||||
if (pointBox(pa, rect) || pointBox(pb, rect)) {
|
||||
return true;
|
||||
}
|
||||
const { x, y, width, height } = rect;
|
||||
const rp1 = new Point(x, y);
|
||||
const rp2 = new Point(x + width, y);
|
||||
const rp3 = new Point(x + width, y + height);
|
||||
const rp4 = new Point(x, y + height);
|
||||
return (
|
||||
lineLine(pa, pb, rp1, rp2) ||
|
||||
lineLine(pa, pb, rp2, rp3) ||
|
||||
lineLine(pa, pb, rp3, rp4) ||
|
||||
lineLine(pa, pb, rp1, rp4)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 多线段和矩形碰撞检测
|
||||
* @param points
|
||||
* @param rect
|
||||
* @returns false / 碰撞的线段序号
|
||||
*/
|
||||
export function polylineBox(points: IPointData[], rect: Rectangle): boolean {
|
||||
if (points.length < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < points.length - 1; i++) {
|
||||
const p1 = points[i];
|
||||
const p2 = points[i + 1];
|
||||
|
||||
if (lineBox(p1, p2, rect)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 两点碰撞检测
|
||||
* @param p1
|
||||
* @param p2
|
||||
* @param tolerance
|
||||
* @returns
|
||||
*/
|
||||
export function pointPoint2(
|
||||
p1: IPointData,
|
||||
p2: IPointData,
|
||||
tolerance: number
|
||||
): boolean {
|
||||
return pointPoint(p1.x, p1.y, p2.x, p2.y, tolerance);
|
||||
}
|
||||
|
||||
/**
|
||||
* 两点碰撞检测
|
||||
* @param x1
|
||||
* @param y1
|
||||
* @param x2
|
||||
* @param y2
|
||||
* @param tolerance 容忍度/两点半径和
|
||||
* @returns
|
||||
*/
|
||||
export function pointPoint(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
tolerance: number
|
||||
): boolean {
|
||||
return distance(x1, y1, x2, y2) <= tolerance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 两点距离
|
||||
* @param x1
|
||||
* @param y1
|
||||
* @param x2
|
||||
* @param y2
|
||||
* @returns
|
||||
*/
|
||||
export function distance(x1: number, y1: number, x2: number, y2: number) {
|
||||
return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* 两点距离
|
||||
* @param p1
|
||||
* @param p2
|
||||
* @returns
|
||||
*/
|
||||
export function distance2(p1: IPointData, p2: IPointData): number {
|
||||
return distance(p1.x, p1.y, p2.x, p2.y);
|
||||
}
|
||||
|
||||
/**
|
||||
* 圆和点的碰撞检测
|
||||
* @param x1 圆心x
|
||||
* @param y1 圆心y
|
||||
* @param r1 圆半径
|
||||
* @param x2 点x
|
||||
* @param y2 点y
|
||||
* @returns
|
||||
*/
|
||||
export function circlePoint(
|
||||
x1: number,
|
||||
y1: number,
|
||||
r1: number,
|
||||
x2: number,
|
||||
y2: number
|
||||
) {
|
||||
const x = x2 - x1;
|
||||
const y = y2 - y1;
|
||||
return x * x + y * y <= r1 * r1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 圆和点的碰撞检测--不包括圆内部
|
||||
*/
|
||||
export function circlePoint2(
|
||||
x1: number,
|
||||
y1: number,
|
||||
r1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
tolerance: number
|
||||
) {
|
||||
const x = x2 - x1;
|
||||
const y = y2 - y1;
|
||||
return (
|
||||
x * x + y * y <= (r1 + tolerance) * (r1 + tolerance) &&
|
||||
x * x + y * y >= (r1 - tolerance) * (r1 - tolerance)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 点和多边形碰撞检测
|
||||
*/
|
||||
export function pointPolygon(
|
||||
p: IPointData,
|
||||
points: IPointData[],
|
||||
lineWidth: number
|
||||
): boolean {
|
||||
const { x, y } = p;
|
||||
const length = points.length;
|
||||
let c = false;
|
||||
let i, j;
|
||||
for (i = 0, j = length - 1; i < length; i++) {
|
||||
if (
|
||||
points[i].y > y !== points[j].y > y &&
|
||||
x <
|
||||
((points[j].x - points[i].x) * (y - points[i].y)) /
|
||||
(points[j].y - points[i].y) +
|
||||
points[i].x
|
||||
) {
|
||||
c = !c;
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
if (c) {
|
||||
return true;
|
||||
}
|
||||
for (i = 0; i < length - 1; i++) {
|
||||
let p1, p2;
|
||||
if (i === length - 1) {
|
||||
p1 = points[i];
|
||||
p2 = points[0];
|
||||
} else {
|
||||
p1 = points[i];
|
||||
p2 = points[i + 1];
|
||||
}
|
||||
if (linePoint(p1, p2, p, lineWidth)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 线和多边形碰撞检测
|
||||
* @param p1
|
||||
* @param p2
|
||||
* @param points
|
||||
* @param tolerance 多边形包围线宽
|
||||
* @returns
|
||||
*/
|
||||
export function linePolygon(
|
||||
p1: IPointData,
|
||||
p2: IPointData,
|
||||
points: IPointData[],
|
||||
lineWidth: number,
|
||||
polygonWidth: number
|
||||
): boolean {
|
||||
if (pointPolygon(p1, points, polygonWidth)) {
|
||||
return true;
|
||||
}
|
||||
const length = points.length;
|
||||
for (let i = 0; i < length; i++) {
|
||||
let pa, pb;
|
||||
if (i === length - 1) {
|
||||
pa = points[i];
|
||||
pb = points[0];
|
||||
} else {
|
||||
pa = points[i];
|
||||
pb = points[i + 1];
|
||||
}
|
||||
// TODO:此处后续需考虑有线宽的情况
|
||||
if (lineLine(pa, pb, p1, p2)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 多边线与多边形碰撞检测
|
||||
* @param polylinePoints 多边线所有点坐标
|
||||
* @param polygonPoints 多边形所有点坐标
|
||||
* @param polylineWidth 多边线的线宽
|
||||
* @param polygonWidth 多边形线宽
|
||||
* @returns
|
||||
*/
|
||||
export function polylinePolygon(
|
||||
polylinePoints: IPointData[],
|
||||
polygonPoints: IPointData[],
|
||||
polylineWidth: number,
|
||||
polygonWidth: number
|
||||
): boolean {
|
||||
const length = polylinePoints.length;
|
||||
for (let i = 0; i < length - 1; i++) {
|
||||
const p1 = polylinePoints[i];
|
||||
const p2 = polylinePoints[i + 1];
|
||||
if (linePolygon(p1, p2, polygonPoints, polylineWidth, polygonWidth)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
/**
|
||||
* 判定是否代理对象
|
||||
* @param obj
|
||||
* @returns
|
||||
*/
|
||||
export function isProxy(obj: any): boolean {
|
||||
return !!(obj && obj['__Proxy']);
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
import { Point, Rectangle } from 'pixi.js';
|
||||
|
||||
export * from './GraphicUtils';
|
||||
export * from './IntersectUtils';
|
||||
export * from './ObjectUtils';
|
||||
|
||||
export const UP: Point = new Point(0, -1);
|
||||
export const DOWN: Point = new Point(0, 1);
|
||||
export const LEFT: Point = new Point(-1, 0);
|
||||
export const RIGHT: Point = new Point(1, 0);
|
||||
|
||||
/**
|
||||
* 越界结果
|
||||
*/
|
||||
export class OutOfBound {
|
||||
left: boolean;
|
||||
top: boolean;
|
||||
right: boolean;
|
||||
bottom: boolean;
|
||||
constructor(left: boolean, top: boolean, right: boolean, bottom: boolean) {
|
||||
this.left = left;
|
||||
this.top = top;
|
||||
this.right = right;
|
||||
this.bottom = bottom;
|
||||
}
|
||||
static check(rect: Rectangle, bound: Rectangle): OutOfBound {
|
||||
const left = rect.left < bound.left;
|
||||
const top = rect.top < bound.top;
|
||||
const right = rect.right > bound.right;
|
||||
const bottom = rect.bottom > bound.bottom;
|
||||
return new OutOfBound(left, top, right, bottom);
|
||||
}
|
||||
static none(): OutOfBound {
|
||||
return new OutOfBound(false, false, false, false);
|
||||
}
|
||||
static leftOut(): OutOfBound {
|
||||
return new OutOfBound(true, false, false, false);
|
||||
}
|
||||
static topOut(): OutOfBound {
|
||||
return new OutOfBound(false, true, false, false);
|
||||
}
|
||||
static rightOut(): OutOfBound {
|
||||
return new OutOfBound(false, false, true, false);
|
||||
}
|
||||
static bottomOut(): OutOfBound {
|
||||
return new OutOfBound(false, false, false, true);
|
||||
}
|
||||
static leftTopOut(): OutOfBound {
|
||||
return new OutOfBound(true, true, false, false);
|
||||
}
|
||||
static rightBottomOut(): OutOfBound {
|
||||
return new OutOfBound(false, false, true, true);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
<template>
|
||||
<q-layout view="lHh Lpr lFf">
|
||||
<q-page-container>
|
||||
<div id="draw-app-container"></div>
|
||||
</q-page-container>
|
||||
</q-layout>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Point } from 'pixi.js';
|
||||
import { initDrawApp, loadDrawDatas } from 'src/examples/app';
|
||||
import { Link } from 'src/graphics/link/Link';
|
||||
import { GraphicIdGenerator, JlDrawApp } from 'src/jlgraphic';
|
||||
import { onMounted, onUnmounted, ref } from 'vue';
|
||||
|
||||
const leftDrawerOpen = ref(false);
|
||||
function toggleLeftDrawer() {
|
||||
leftDrawerOpen.value = !leftDrawerOpen.value;
|
||||
}
|
||||
|
||||
let drawApp: JlDrawApp | null = null;
|
||||
onMounted(() => {
|
||||
const dom = document.getElementById('draw-app-container');
|
||||
if (dom) {
|
||||
drawApp = new JlDrawApp(dom);
|
||||
initDrawApp(drawApp);
|
||||
loadDrawDatas(drawApp);
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
if (drawApp) {
|
||||
drawApp.destroy();
|
||||
}
|
||||
document.body.style.overflow = 'auto';
|
||||
});
|
||||
</script>
|
|
@ -0,0 +1,27 @@
|
|||
<template>
|
||||
<div class="fullscreen bg-blue text-white text-center q-pa-md flex flex-center">
|
||||
<div>
|
||||
<div style="font-size: 30vh">
|
||||
404
|
||||
</div>
|
||||
|
||||
<div class="text-h2" style="opacity:.4">
|
||||
Oops. Nothing here...
|
||||
</div>
|
||||
|
||||
<q-btn
|
||||
class="q-mt-xl"
|
||||
color="white"
|
||||
text-color="blue"
|
||||
unelevated
|
||||
to="/"
|
||||
label="Go Home"
|
||||
no-caps
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
|
||||
</script>
|
|
@ -0,0 +1,42 @@
|
|||
<template>
|
||||
<q-page class="row items-center justify-evenly">
|
||||
<example-component
|
||||
title="Example component"
|
||||
active
|
||||
:todos="todos"
|
||||
:meta="meta"
|
||||
></example-component>
|
||||
</q-page>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Todo, Meta } from 'components/models';
|
||||
import ExampleComponent from 'components/ExampleComponent.vue';
|
||||
import { ref } from 'vue';
|
||||
|
||||
const todos = ref<Todo[]>([
|
||||
{
|
||||
id: 1,
|
||||
content: 'ct1'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
content: 'ct2'
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
content: 'ct3'
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
content: 'ct4'
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
content: 'ct5'
|
||||
}
|
||||
]);
|
||||
const meta = ref<Meta>({
|
||||
totalCount: 1200
|
||||
});
|
||||
</script>
|
|
@ -0,0 +1,9 @@
|
|||
/* eslint-disable */
|
||||
|
||||
// Forces TS to apply `@quasar/app-vite` augmentations of `quasar` package
|
||||
// Removing this would break `quasar/wrappers` imports as those typings are declared
|
||||
// into `@quasar/app-vite`
|
||||
// As a side effect, since `@quasar/app-vite` reference `quasar` to augment it,
|
||||
// this declaration also apply `quasar` own
|
||||
// augmentations (eg. adds `$q` into Vue component context)
|
||||
/// <reference types="@quasar/app-vite" />
|
|
@ -0,0 +1,36 @@
|
|||
import { route } from 'quasar/wrappers';
|
||||
import {
|
||||
createMemoryHistory,
|
||||
createRouter,
|
||||
createWebHashHistory,
|
||||
createWebHistory,
|
||||
} from 'vue-router';
|
||||
|
||||
import routes from './routes';
|
||||
|
||||
/*
|
||||
* If not building with SSR mode, you can
|
||||
* directly export the Router instantiation;
|
||||
*
|
||||
* The function below can be async too; either use
|
||||
* async/await or return a Promise which resolves
|
||||
* with the Router instance.
|
||||
*/
|
||||
|
||||
export default route(function (/* { store, ssrContext } */) {
|
||||
const createHistory = process.env.SERVER
|
||||
? createMemoryHistory
|
||||
: (process.env.VUE_ROUTER_MODE === 'history' ? createWebHistory : createWebHashHistory);
|
||||
|
||||
const Router = createRouter({
|
||||
scrollBehavior: () => ({ left: 0, top: 0 }),
|
||||
routes,
|
||||
|
||||
// Leave this as is and make changes in quasar.conf.js instead!
|
||||
// quasar.conf.js -> build -> vueRouterMode
|
||||
// quasar.conf.js -> build -> publicPath
|
||||
history: createHistory(process.env.VUE_ROUTER_BASE),
|
||||
});
|
||||
|
||||
return Router;
|
||||
});
|
|
@ -0,0 +1,17 @@
|
|||
import { RouteRecordRaw } from 'vue-router';
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/',
|
||||
component: () => import('layouts/DrawLayout.vue'),
|
||||
},
|
||||
|
||||
// Always leave this as last one,
|
||||
// but you can also remove it
|
||||
{
|
||||
path: '/:catchAll(.*)*',
|
||||
component: () => import('pages/ErrorNotFound.vue'),
|
||||
},
|
||||
];
|
||||
|
||||
export default routes;
|
|
@ -0,0 +1,10 @@
|
|||
/* eslint-disable */
|
||||
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
// Mocks all files ending in `.vue` showing them as plain Vue instances
|
||||
declare module '*.vue' {
|
||||
import type { DefineComponent } from 'vue';
|
||||
const component: DefineComponent<{}, {}, any>;
|
||||
export default component;
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
import { defineStore } from 'pinia';
|
||||
|
||||
export const useCounterStore = defineStore('counter', {
|
||||
state: () => ({
|
||||
counter: 0,
|
||||
}),
|
||||
getters: {
|
||||
doubleCount: (state) => state.counter * 2,
|
||||
},
|
||||
actions: {
|
||||
increment() {
|
||||
this.counter++;
|
||||
},
|
||||
},
|
||||
});
|
|
@ -0,0 +1,32 @@
|
|||
import { store } from 'quasar/wrappers'
|
||||
import { createPinia } from 'pinia'
|
||||
import { Router } from 'vue-router';
|
||||
|
||||
/*
|
||||
* When adding new properties to stores, you should also
|
||||
* extend the `PiniaCustomProperties` interface.
|
||||
* @see https://pinia.vuejs.org/core-concepts/plugins.html#typing-new-store-properties
|
||||
*/
|
||||
declare module 'pinia' {
|
||||
export interface PiniaCustomProperties {
|
||||
readonly router: Router;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* If not building with SSR mode, you can
|
||||
* directly export the Store instantiation;
|
||||
*
|
||||
* The function below can be async too; either use
|
||||
* async/await or return a Promise which resolves
|
||||
* with the Store instance.
|
||||
*/
|
||||
|
||||
export default store((/* { ssrContext } */) => {
|
||||
const pinia = createPinia()
|
||||
|
||||
// You can add Pinia plugins here
|
||||
// pinia.use(SomePiniaPlugin)
|
||||
|
||||
return pinia
|
||||
})
|
|
@ -0,0 +1,10 @@
|
|||
/* eslint-disable */
|
||||
// THIS FEATURE-FLAG FILE IS AUTOGENERATED,
|
||||
// REMOVAL OR CHANGES WILL CAUSE RELATED TYPES TO STOP WORKING
|
||||
import "quasar/dist/types/feature-flag";
|
||||
|
||||
declare module "quasar/dist/types/feature-flag" {
|
||||
interface QuasarFeatureFlags {
|
||||
store: true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"extends": "@quasar/app-vite/tsconfig-preset",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "."
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue