дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
Порівняти коміти
21
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
c677ccd85d | ||
|
|
8968974f42 | ||
|
|
5f083ae47c | ||
|
|
83b14b4329 | ||
|
|
74eefd6116 | ||
|
|
a96c70f2a7 | ||
|
|
304503b9f1 | ||
|
|
06cf8fb16a | ||
|
|
521e00d075 | ||
|
|
b4cad6ec1b | ||
|
|
62e26fa7e3 | ||
|
|
1119467ab4 | ||
|
|
e1ce850a29 | ||
|
|
3e39368d43 | ||
|
|
b2a5ea1594 | ||
|
|
902d8ca257 | ||
|
|
92b5b5306f | ||
|
|
707cee9b0b | ||
|
|
d64be035c6 | ||
|
|
cb60c742fc | ||
|
|
b245335cc6 |
No files matched your search
Створено
+200
-148
@@ -474,7 +474,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "457d7ed3f888dfd2c7af56d4975cade43c622f74bdcddfed6d4352f57acc6310"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"portable-atomic",
|
||||
"tokio",
|
||||
]
|
||||
@@ -1655,9 +1655,9 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"crossbeam-utils",
|
||||
"hashbrown 0.14.5",
|
||||
"lock_api",
|
||||
"lock_api 0.4.14",
|
||||
"once_cell",
|
||||
"parking_lot_core",
|
||||
"parking_lot_core 0.9.12",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -2154,7 +2154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2210,6 +2210,16 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "faster-hex"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4ede54fe330383a5de28c0a1f06668ff9dbf06c8094e1c5150c39488a5e911d"
|
||||
dependencies = [
|
||||
"defmt 0.3.101",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -2453,8 +2463,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"lock_api",
|
||||
"parking_lot",
|
||||
"lock_api 0.4.14",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2734,9 +2744,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix"
|
||||
version = "0.89.0"
|
||||
version = "0.90.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2156d2e07fc3afa7632a82bf3cb0db91f995645a2852f642105c9ac9b52e1cb2"
|
||||
checksum = "b92b20c1560511a9014b16e29db2f3c6f0580d4fe289b70f41131277b065a3b0"
|
||||
dependencies = [
|
||||
"gix-actor",
|
||||
"gix-attributes",
|
||||
@@ -2788,9 +2798,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-actor"
|
||||
version = "0.44.0"
|
||||
version = "0.44.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2127da41042965ed205568a52443465806944f71c8acd73f48ec94b8cd8e798e"
|
||||
checksum = "78243d3371019288a40a75ba1a58de2815c32591fc87b9f7cb01918bce364ca8"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-date",
|
||||
@@ -2799,9 +2809,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-attributes"
|
||||
version = "0.37.0"
|
||||
version = "0.37.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0feca0b8919aba9f123b75de54062dd61eb37d2a2130f34be520da6ed8b8ef72"
|
||||
checksum = "6b9947d93a94d41ddde66ac655674269121cbebaf6cdee30d8d0e7dbe85edb4c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2816,27 +2826,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-bitmap"
|
||||
version = "0.6.0"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "408cb9e482e0dcc5fc481850556348dda6981ec054a4a8e81a8e1bbf84f85eef"
|
||||
checksum = "9543567ee22142c81fdf75b2811160bec749a5b9f48665e4763f88b1789b8612"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-chunk"
|
||||
version = "0.10.0"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "626335faf30ed235744642c2309aa370683b8bb2757f1c22a807e274dff60074"
|
||||
checksum = "60cd5f0e47ffae98bad241ccbc031693765004fb4c2a419f7fda2963232af1e3"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-command"
|
||||
version = "0.12.0"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac560c05e19455016a4a94b33a77debe59aaed8783da32a73d31c9975947152e"
|
||||
checksum = "2986e78ebad43510ccd7dd18bd9f22e9afd52f2de791e2979b9c715bacb6f0a8"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2847,9 +2857,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-commitgraph"
|
||||
version = "0.41.0"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dfede9936d4b789867c09722576aea4ceb0e3aacf962eef035ebab0686b41a80"
|
||||
checksum = "60b53b700d2a506cf98075099df1fcc0558265cbb47fd86bc6d03c231e4bd72a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-chunk",
|
||||
@@ -2861,9 +2871,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-config"
|
||||
version = "0.62.0"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65a9c000fa9a9154f22ffc8f8d74426e9300d759c2029e8701e2ba39d5d464ea"
|
||||
checksum = "3e11ccf82e9630c4e7befbae07cbe90e79de61dc73a34448c2dec70a13da9ebf"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-config-value",
|
||||
@@ -2881,9 +2891,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-config-value"
|
||||
version = "0.21.0"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab206c2fccfd35e0de7fb1b424997cfd42912062c66dae024e08a06e22d46674"
|
||||
checksum = "d7666081ef0ecc5e1dc54bc6ce16dac9d7b9490780f6c130393ef9e50c909d4a"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -2895,9 +2905,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-date"
|
||||
version = "0.18.0"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f7eeeecc599082f32b5ea6a8c4c734e38be9730e2c09e3fe2851bb4692393e9"
|
||||
checksum = "4c538190012dbb536df54734ec38cc1109270c73f2f76585c011dd5b0c9f087c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2907,9 +2917,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-diff"
|
||||
version = "0.69.0"
|
||||
version = "0.70.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa640963fdcbc6b4718e48593c3917f5ae764b59fb5a96313cb5a757246d041d"
|
||||
checksum = "2c794988335792f85c3ca79c385c950b3a921a71ba3df361cb1f9e5b6bd4a6e4"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-attributes",
|
||||
@@ -2931,9 +2941,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-dir"
|
||||
version = "0.31.0"
|
||||
version = "0.32.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84e916ef77f19161b738ae9913662bc36fed1e48256a943f40277b3a585841da"
|
||||
checksum = "af939f21c65d4f15457c72d08c874d454893185c51a3596e3c2bd3d9c567618d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-discover",
|
||||
@@ -2951,9 +2961,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-discover"
|
||||
version = "0.57.0"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7d0f8fd2c7e4b458eb3081362d49b54bd0131d23ecd49be802085a11f0d3cee"
|
||||
checksum = "4a0875f4e5408713fcf92265973cc38bf9dc5a93384ce218beba0572b7785a03"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"dunce",
|
||||
@@ -2966,18 +2976,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-error"
|
||||
version = "0.5.1"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb3308a948a01b94ef13d9ee7a9b28c1303d8d9a9dc33b401ff40c2184d9e04a"
|
||||
checksum = "50ad6c42fa50280f382026ff838a8afa7ab2ad83e92349cab4392972baae69cd"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-filter"
|
||||
version = "0.36.0"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d8d932ee4043f7d77d15ee58d2be2bc95accea5dd1d77fd145de1b7c504551b"
|
||||
checksum = "f8df8d50fda4684c6ec366f75e4082ab6fc3d437d3deec30ff88462710b68d17"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"encoding_rs",
|
||||
@@ -2996,9 +3006,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-fs"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44a05d043e670c055cd8b53d078562dc0bc1e322bff6b0376b407d37cf72dcc5"
|
||||
checksum = "808f23d897ddfe847d9b7206bda947901885be623bdf96b226a2dccf87f018c7"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3011,9 +3021,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-glob"
|
||||
version = "0.29.0"
|
||||
version = "0.29.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b0d03ab50fa841621031960679caf7fe94940968d9a0736d12a580f2c03e525"
|
||||
checksum = "7a12789fa68a150293ad8834d267b31044240532b5ccf2734d228fe985cba2be"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3025,11 +3035,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-hash"
|
||||
version = "0.28.0"
|
||||
version = "0.28.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40ca156064e378d8c657084365846cedb8dc498c6ea4500965a64d74f12af2be"
|
||||
checksum = "b4802ffb87e051795822bfdaa8ab9075b23e316684f7054e6ce4a246b2b76f4e"
|
||||
dependencies = [
|
||||
"faster-hex",
|
||||
"faster-hex 0.10.1",
|
||||
"gix-error",
|
||||
"gix-utils",
|
||||
"sha1dc",
|
||||
@@ -3044,7 +3054,7 @@ checksum = "916cb6b2ec42ffaca624e7867bb382a4673015cb4ffcd7330b48085d02e4c615"
|
||||
dependencies = [
|
||||
"gix-hash",
|
||||
"hashbrown 0.17.1",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3062,9 +3072,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-imara-diff"
|
||||
version = "0.3.1"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c48eccd894bd15555b0346470e63491ded94aefe76b3fcb1052084b5a393238"
|
||||
checksum = "23347fa4a29a440eebf045d0bc21da465c0dc70434c2a4bcdfcc658f16c9e27e"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -3072,9 +3082,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-index"
|
||||
version = "0.57.0"
|
||||
version = "0.58.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc6db8b20a3dba8836daf90b24199600bb27dcfce3a127ec24ae61e15a7c5b68"
|
||||
checksum = "06bfc736774a623307eda890c918d308ef5acd37402bde2d6768fccb1f6ecb5d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3124,9 +3134,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-note"
|
||||
version = "0.3.0"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd364f8bdceaed9e7f3ae40f324b16e39f20e9c7e6a6a058f7c6ec66c3e6205c"
|
||||
checksum = "8473688f2262f4364f521b39ce2a5dbe94494f327fc19c945318d7aff580952e"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
"gix-hash",
|
||||
@@ -3135,9 +3145,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-object"
|
||||
version = "0.66.0"
|
||||
version = "0.66.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0e38f50177e211642af154f9a7f710b7a3a637e635f9b6adb9d51973b0f9209"
|
||||
checksum = "beaf9086dd00b9d2a177ca3ae83210ce926cee7c0faa112e053851221cd8f94d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-actor",
|
||||
@@ -3156,9 +3166,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-odb"
|
||||
version = "0.86.0"
|
||||
version = "0.87.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca444f33f2140876ed6b5313c2b550b4af699008193c96f3bff5023afa9ef4ea"
|
||||
checksum = "941b5b99fed282a5b05b54ea486c36c76b558afe151e6804c3acdd5c8f3c3459"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"crc32fast",
|
||||
@@ -3175,15 +3185,15 @@ dependencies = [
|
||||
"gix-utils",
|
||||
"gix-zlib",
|
||||
"memmap2",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-pack"
|
||||
version = "0.76.0"
|
||||
version = "0.77.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc5024cc503cd29461a705ae90b9eae772fa8f0e6fafc1c48513877dc374de05"
|
||||
checksum = "e2ef461798b1e6cb652192c69dfc9658dfc1bab457ef812dd1ab85d75104cbef"
|
||||
dependencies = [
|
||||
"clru",
|
||||
"crc32fast",
|
||||
@@ -3204,45 +3214,46 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-packetline"
|
||||
version = "0.24.0"
|
||||
version = "0.24.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "830e51b227f6a925fe9308858ac91170dd00fa2880f5480fc81e8a4594fe2c35"
|
||||
checksum = "6e198121152a397ad1007e3334931b04b393fa17f6af34f17b33e376b15bf5ea"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"faster-hex",
|
||||
"faster-hex 2.0.0",
|
||||
"gix-error",
|
||||
"gix-trace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-parallel"
|
||||
version = "0.50.0"
|
||||
version = "0.50.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e994cf1eec247ba4be7f9e7c0d58cc73f83eecb5fcb9feb595df5ba3d2078546"
|
||||
checksum = "d3a5c86eeec0194a3444611b4762ba05cc5029408a617348b4f6a74a34c222cd"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"gix-trace",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"parking_lot 0.13.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-path"
|
||||
version = "0.14.0"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6d563d4d0c975ed0df4e853f9ec962a2ba46633b1d324e1a5582541fcae0c6b"
|
||||
checksum = "615e3ff75800c67022ec8065b67e0846420a88c5f484e6c4fd81c78472e4c77a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
"gix-trace",
|
||||
"gix-validate",
|
||||
"winreg 0.56.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-pathspec"
|
||||
version = "0.22.0"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e3b7f03e516a8435d18c3cc2d446925940c81d409145ac21edb5a576f0625e4"
|
||||
checksum = "490aa03a11e0cbb998a0a593b75e27ea2e30df4ebd8f84f60e0641b9b72270e8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3255,9 +3266,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-protocol"
|
||||
version = "0.67.0"
|
||||
version = "0.68.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "832b5dc46a3c0a6f6fa8f8e571c11074add4b545c6789799ae6d6c36ae1a294e"
|
||||
checksum = "83677ebae6a1a09dc07f2435b5ebe68470dc51afb74052135e98fd7c11f85ba9"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-date",
|
||||
@@ -3273,9 +3284,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-quote"
|
||||
version = "0.10.0"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7f92bc1b13c09e88388578e8aa1e987ec35f28fca158c13b1baa7ab1a85b124"
|
||||
checksum = "5069a7ec021bb47abe9f12dcc075d292e8cf4a9dff5fffd38595b39c6b419aaa"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3284,9 +3295,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-ref"
|
||||
version = "0.69.0"
|
||||
version = "0.69.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "073bc0928e1f747823b1eaed94918119dacef4c616532bc3d17e5b7457863471"
|
||||
checksum = "68686e4697b9cd15d1b152ef51df870513210ed22938eacc13b3672b76035f13"
|
||||
dependencies = [
|
||||
"gix-actor",
|
||||
"gix-error",
|
||||
@@ -3304,9 +3315,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-refspec"
|
||||
version = "0.47.0"
|
||||
version = "0.47.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccc7010dae0df2900aa77cc67f8aca042cd80e35938ccc179010d863b1d42a0c"
|
||||
checksum = "2569309da6fdc230973cf5b846508154c0e813fda60f2b2da768cc5655ed312c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3317,9 +3328,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-revision"
|
||||
version = "0.51.0"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63210c1943b67fa700806c3c3486fc16a92b3ea871f5cf092340b8eec10a0ca1"
|
||||
checksum = "241465fc73530f41d0a1c18320c5e291365b7c2c2a3dfd07afe2a5d6265085c8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3336,9 +3347,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-revwalk"
|
||||
version = "0.37.0"
|
||||
version = "0.38.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "800479fbbf1e7f94f663e07943a91add5499343e7aac611a81e6a0460fd44af6"
|
||||
checksum = "8b46edeacd25d9d3131941ae6bc91002bf7ba10e130393b7e9bc23d528625447"
|
||||
dependencies = [
|
||||
"gix-commitgraph",
|
||||
"gix-date",
|
||||
@@ -3351,9 +3362,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-sec"
|
||||
version = "0.16.0"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5640f642a1b471616d48230b1def7ca743cb30903441ff84800cafbab3c0fddf"
|
||||
checksum = "9598d1f35baec7038c2d278bfcc18f1d8951f41dcc3f51ab6175661dfe5a6137"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"gix-path",
|
||||
@@ -3363,9 +3374,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-shallow"
|
||||
version = "0.15.0"
|
||||
version = "0.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94bc0720a3d6b10f18e3ac382a7780bcfc4c6bee94a8b5857b8e4ec94c50d754"
|
||||
checksum = "1d805949578724b5164c90ec6d19567832ccaa5ba8a3fe26f7befc52007e2407"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3376,9 +3387,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-status"
|
||||
version = "0.36.0"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42d3174a9f3fb991cf25a7a609ab6c50f19baa7d5f8ce05a48c202f7db4ce3ba"
|
||||
checksum = "31b00c359278210e3cc0803d057db1d61c5d6694c21ed9ad0b8f8f862157247a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"filetime",
|
||||
@@ -3398,14 +3409,13 @@ dependencies = [
|
||||
"gix-worktree",
|
||||
"hashbrown 0.16.1",
|
||||
"portable-atomic",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-submodule"
|
||||
version = "0.36.0"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d945257bd0d624ca844a5a36c79d748df080f355b0ac92d68793875aa529a3f"
|
||||
checksum = "d558a1307b6f3de2a92bd91d0570c53952d4f2329e6860813007508c8ed413dc"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-config",
|
||||
@@ -3425,22 +3435,22 @@ dependencies = [
|
||||
"dashmap",
|
||||
"gix-fs",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-trace"
|
||||
version = "0.3.0"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "133f2de116104d637541831b6acb157898556d5eeec363ab2eb1c583adc6bb56"
|
||||
checksum = "1c96f84d731a96780e6a7ad5ee70b4ecc398499946b62617945fbaeb6ab878f8"
|
||||
|
||||
[[package]]
|
||||
name = "gix-transport"
|
||||
version = "0.61.0"
|
||||
version = "0.62.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e43d6b0097ea9f2f266d5d6c43b8f615ed3da7c686ec8771cd17c1cb33cb0de"
|
||||
checksum = "cdcd9cdfd8745aa38f926a4a380c13d76b200d7338de57fc492982cd5a6652ba"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-command",
|
||||
@@ -3456,9 +3466,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-traverse"
|
||||
version = "0.63.0"
|
||||
version = "0.64.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a668a6e7f7688e5a43eaf161f1471ffc559de1a5fd8471e861c64d59d1699e1e"
|
||||
checksum = "00171e00e91508300d0361072c4eb110ec0f1322d8b95ed36887231702a38ebc"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"gix-commitgraph",
|
||||
@@ -3473,9 +3483,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-url"
|
||||
version = "0.40.0"
|
||||
version = "0.40.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04317dea7a5dd5253bbcab060c230f3de6a57d17cc9600c6cd7030bf4795b414"
|
||||
checksum = "def12e1016b872f1094442882f627905c59bd73480435291a4958cf373a8f28d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3486,9 +3496,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-utils"
|
||||
version = "0.5.1"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8e770b8c34311044d1addc7b18957db0ac27183707e1140dc90e6f674a6354e"
|
||||
checksum = "b5e6d46894c7a4fd9c5e26d233a0fa836002ba0af9a11aef58923d317c486e10"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"bytes",
|
||||
@@ -3501,9 +3511,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-validate"
|
||||
version = "0.13.0"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cbcd59cc52742468bc5c8a0e7123390d154f45e6cbd37461b0dcecdc681f2179"
|
||||
checksum = "5d6f293fd8abd9bd9bc1e0a23541f73607e932b5a2bde2246320da38edde5726"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3511,9 +3521,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-worktree"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a285c0f6b41e504e8bb81ca3f861c4da00cb3d5ced3210a4591112f22da6d38f"
|
||||
checksum = "fe92aec0a25cf073394492a6ee2aa4d27632acde91a653d34de0e4da6afb485d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-attributes",
|
||||
@@ -3530,9 +3540,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-worktree-stream"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d2789610e8179d4e0e8e51170a52a66483c103a8ad3c7db4d075b571856cb6"
|
||||
checksum = "3fe5d65793848ffb596f6c5596fd120b132038736525628227e2388ca454f64d"
|
||||
dependencies = [
|
||||
"gix-attributes",
|
||||
"gix-error",
|
||||
@@ -3545,14 +3555,14 @@ dependencies = [
|
||||
"gix-trace",
|
||||
"gix-traverse",
|
||||
"gix-utils",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-zlib"
|
||||
version = "0.3.0"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c2edb206bf06f3c801f4f6789c696396171558ab9b4c7f1fe3ba4d39b00b0f4"
|
||||
checksum = "81a49a8b263d2a140f1c178ff93375b8d4cc7b1d3252cd87ce1ca88bce62b9b9"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
"zlib-rs",
|
||||
@@ -4156,7 +4166,7 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"rustix",
|
||||
"semver",
|
||||
"serde",
|
||||
@@ -4297,7 +4307,7 @@ dependencies = [
|
||||
"ide-language",
|
||||
"libc",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
@@ -4329,7 +4339,7 @@ dependencies = [
|
||||
"notify",
|
||||
"open",
|
||||
"oracledb",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"rsa",
|
||||
"rustls",
|
||||
@@ -4385,7 +4395,7 @@ dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
"ed25519-dalek",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4403,7 +4413,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
@@ -4510,7 +4520,7 @@ dependencies = [
|
||||
"ide-workspace",
|
||||
"ignore",
|
||||
"jsonschema",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"regex-lite",
|
||||
"regex-syntax",
|
||||
@@ -4540,7 +4550,7 @@ dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"rustls-platform-verifier",
|
||||
@@ -4565,7 +4575,7 @@ dependencies = [
|
||||
"ide-language",
|
||||
"ignore",
|
||||
"nucleo-matcher",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"postcard",
|
||||
"rayon",
|
||||
"redb",
|
||||
@@ -4593,7 +4603,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
@@ -4634,7 +4644,7 @@ dependencies = [
|
||||
"ide-extension",
|
||||
"ide-text",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"regex-lite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4699,7 +4709,7 @@ dependencies = [
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
"lsp-types",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4739,7 +4749,7 @@ dependencies = [
|
||||
"jupyter-protocol",
|
||||
"jupyter-zmq-client",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4759,7 +4769,7 @@ dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"ide-extension",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4798,7 +4808,7 @@ dependencies = [
|
||||
"ide-run",
|
||||
"ide-ssh",
|
||||
"ignore",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4816,8 +4826,9 @@ dependencies = [
|
||||
"ide-build",
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"ide-workspace",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"portable-pty",
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
@@ -4899,7 +4910,7 @@ name = "ide-spell"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4916,7 +4927,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"keyring",
|
||||
"keyring-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"russh",
|
||||
"russh-sftp",
|
||||
"rustls",
|
||||
@@ -4966,7 +4977,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
"specta",
|
||||
@@ -4998,7 +5009,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
@@ -5045,7 +5056,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ignore",
|
||||
"notify",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"rayon",
|
||||
"rustix",
|
||||
"serde",
|
||||
@@ -5086,7 +5097,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -5096,6 +5107,7 @@ dependencies = [
|
||||
"toml_edit 0.25.17+spec-1.1.0",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"winreg 0.56.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
@@ -5239,7 +5251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5277,7 +5289,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5777,6 +5789,15 @@ dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
@@ -6748,7 +6769,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"security-framework",
|
||||
@@ -6938,8 +6959,18 @@ version = "0.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
"lock_api 0.4.14",
|
||||
"parking_lot_core 0.9.12",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226"
|
||||
dependencies = [
|
||||
"lock_api 0.5.0",
|
||||
"parking_lot_core 0.10.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6950,7 +6981,19 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"redox_syscall 0.5.18",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"redox_syscall 0.9.5",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
@@ -7401,7 +7444,7 @@ version = "31.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf52d87428247c5aa3760ac8e7d8b13ec7b3579b955a8c3f311668b6860acba5"
|
||||
dependencies = [
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7597,6 +7640,15 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_users"
|
||||
version = "0.5.3"
|
||||
@@ -7636,7 +7688,7 @@ dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri 0.3.2",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -7970,7 +8022,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8038,7 +8090,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8712,7 +8764,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-quartz-core 0.3.2",
|
||||
"raw-window-handle",
|
||||
"redox_syscall",
|
||||
"redox_syscall 0.5.18",
|
||||
"tracing",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
@@ -8812,7 +8864,7 @@ version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"lock_api 0.4.14",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9086,7 +9138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
|
||||
dependencies = [
|
||||
"new_debug_unreachable",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"phf_shared",
|
||||
"precomputed-hash",
|
||||
]
|
||||
@@ -9274,7 +9326,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-ui-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"raw-window-handle",
|
||||
"tao-macros",
|
||||
@@ -9782,10 +9834,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9965,7 +10017,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
@@ -11622,7 +11674,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -12420,7 +12472,7 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"rand 0.9.5",
|
||||
"regex",
|
||||
"scc",
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
|
||||
jupyter-protocol = "=2.0.3"
|
||||
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
gix = { version = "0.90", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
|
||||
@@ -486,6 +486,15 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
/// JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub quotes: Option<String>,
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
|
||||
@@ -46,6 +46,13 @@ pub enum Capability {
|
||||
/// the manifest does not list; each answer applies to one host. Plain
|
||||
/// HTTP elsewhere always needs `net.http:<host>`.
|
||||
NetAsk,
|
||||
/// The host of the `string` setting `key`, approved when the user applies
|
||||
/// its value in Settings (`net:setting:server`, `net.http:setting:server`).
|
||||
/// HTTPS (and loopback HTTP) unless `http`.
|
||||
NetSetting {
|
||||
http: bool,
|
||||
key: String,
|
||||
},
|
||||
/// Unencrypted HTTP to one host.
|
||||
NetHttp(String),
|
||||
/// A local socket or named pipe on the project machine.
|
||||
@@ -89,6 +96,7 @@ impl Capability {
|
||||
| Self::VcsWrite
|
||||
| Self::Net(_)
|
||||
| Self::NetAsk
|
||||
| Self::NetSetting { .. }
|
||||
| Self::NetHttp(_)
|
||||
| Self::Secrets
|
||||
| Self::InputEvents
|
||||
@@ -139,6 +147,12 @@ impl Capability {
|
||||
"Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones"
|
||||
.into()
|
||||
}
|
||||
Self::NetSetting { http, key } if *http => {
|
||||
format!("Connect to the host set in the `{key}` setting over unencrypted HTTP (from the machine the project is on)")
|
||||
}
|
||||
Self::NetSetting { http: _, key } => {
|
||||
format!("Connect to the host set in the `{key}` setting (from the machine the project is on)")
|
||||
}
|
||||
Self::NetHttp(host) => {
|
||||
format!("Connect to {host} over unencrypted HTTP (from the machine the project is on)")
|
||||
}
|
||||
@@ -184,6 +198,19 @@ pub fn host_matches(pattern: &str, host: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates a manifest-style host (letters, digits and `-` labels, at most 253
|
||||
/// bytes) and returns it lowercased. A `*` is never valid here — only a
|
||||
/// `net:`/`net.http:` grant itself may carry the `*.` subdomain pattern, and a
|
||||
/// host taken from a setting value never does.
|
||||
pub fn manifest_host(host: &str) -> Result<String, String> {
|
||||
let valid = !host.is_empty()
|
||||
&& host.len() <= 253
|
||||
&& host.split('.').all(|label| {
|
||||
!label.is_empty() && label.len() <= 63 && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
});
|
||||
valid.then(|| host.to_ascii_lowercase()).ok_or_else(|| "invalid host".into())
|
||||
}
|
||||
|
||||
/// Validates a socket path; a grant may use `*` in its last segment only.
|
||||
pub fn validate_ipc_name(name: &str, pattern: bool) -> Result<(), String> {
|
||||
let pipe = name.starts_with(r"\\.\pipe\");
|
||||
@@ -273,6 +300,8 @@ impl fmt::Display for Capability {
|
||||
Self::ClipboardRead => f.write_str("clipboard.read"),
|
||||
Self::Net(h) => write!(f, "net:{h}"),
|
||||
Self::NetAsk => f.write_str("net:ask"),
|
||||
Self::NetSetting { http, key } if *http => write!(f, "net.http:setting:{key}"),
|
||||
Self::NetSetting { http: _, key } => write!(f, "net:setting:{key}"),
|
||||
Self::NetHttp(h) => write!(f, "net.http:{h}"),
|
||||
Self::Ipc(p) => write!(f, "ipc:{p}"),
|
||||
Self::Process(b) => write!(f, "process:{b}"),
|
||||
@@ -300,23 +329,27 @@ impl FromStr for Capability {
|
||||
if kind == "net" && arg == "ask" {
|
||||
return Ok(Self::NetAsk);
|
||||
}
|
||||
let host = arg.strip_prefix("*.").unwrap_or(arg);
|
||||
let valid = !host.is_empty()
|
||||
&& host.len() <= 253
|
||||
&& host.split('.').all(|label| {
|
||||
!label.is_empty()
|
||||
&& label.len() <= 63
|
||||
&& label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
});
|
||||
if valid {
|
||||
Ok(if kind == "net" {
|
||||
Self::Net(arg.to_ascii_lowercase())
|
||||
// `net:setting:<key>` names the plugin's `string` setting the
|
||||
// host comes from; the same key rule as a settings schema.
|
||||
if let Some(key) = arg.strip_prefix("setting:") {
|
||||
let valid_key = !key.is_empty()
|
||||
&& key.len() <= 64
|
||||
&& key.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
|
||||
return if valid_key {
|
||||
Ok(Self::NetSetting { http: kind == "net.http", key: key.to_owned() })
|
||||
} else {
|
||||
Self::NetHttp(arg.to_ascii_lowercase())
|
||||
})
|
||||
} else {
|
||||
Err(format!("invalid host in {s:?}"))
|
||||
Err(format!("invalid setting key in {s:?}"))
|
||||
};
|
||||
}
|
||||
manifest_host(arg.strip_prefix("*.").unwrap_or(arg))
|
||||
.map(|_| {
|
||||
if kind == "net" {
|
||||
Self::Net(arg.to_ascii_lowercase())
|
||||
} else {
|
||||
Self::NetHttp(arg.to_ascii_lowercase())
|
||||
}
|
||||
})
|
||||
.map_err(|_| format!("invalid host in {s:?}"))
|
||||
}
|
||||
"ipc" => {
|
||||
validate_ipc_name(arg, true)?;
|
||||
@@ -555,6 +588,77 @@ mod net_ask_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod net_setting_tests {
|
||||
use super::*;
|
||||
|
||||
/// `net:setting:<key>` names a settings key instead of a host: the host
|
||||
/// comes from the setting's value and is approved when the user sets it
|
||||
/// (#3809).
|
||||
#[test]
|
||||
fn setting_derived_grants_parse_and_print() {
|
||||
for s in ["net:setting:server", "net.http:setting:server"] {
|
||||
let cap: Capability = s.parse().unwrap();
|
||||
assert_eq!(cap.to_string(), s, "{s}");
|
||||
assert_eq!(cap.risk(), Risk::Medium, "{s}");
|
||||
}
|
||||
assert_eq!(
|
||||
"net:setting:server".parse::<Capability>().unwrap(),
|
||||
Capability::NetSetting { http: false, key: "server".into() }
|
||||
);
|
||||
assert_eq!(
|
||||
"net.http:setting:server".parse::<Capability>().unwrap(),
|
||||
Capability::NetSetting { http: true, key: "server".into() }
|
||||
);
|
||||
assert!(!"net:setting:server".parse::<Capability>().unwrap().auto_migrates());
|
||||
let derived = "net:setting:server".parse::<Capability>().unwrap();
|
||||
assert!(derived.describe().contains("`server`"));
|
||||
assert!("net.http:setting:server".parse::<Capability>().unwrap().describe().contains("unencrypted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_derived_grants_stay_strict() {
|
||||
for s in ["net:setting:", "net:setting:a b", "net:setting:a:b", "net.http:setting:"] {
|
||||
assert!(s.parse::<Capability>().is_err(), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The derivation covers nothing by itself: a literal-host grant and a
|
||||
/// setting-derived grant are different grants, and the host materializes
|
||||
/// only after the user approves the setting's value.
|
||||
#[test]
|
||||
fn derived_grants_do_not_cover_literal_hosts() {
|
||||
let derived: Capability = "net:setting:server".parse().unwrap();
|
||||
let literal: Capability = "net:gitlab.intranet.example".parse().unwrap();
|
||||
assert!(!derived.covers(&literal));
|
||||
assert!(!literal.covers(&derived));
|
||||
assert!(!derived.covers(&"net.http:gitlab.intranet.example".parse().unwrap()));
|
||||
assert!(!derived.covers(&"net:setting:other".parse().unwrap()));
|
||||
}
|
||||
|
||||
/// The host of a setting value passes the same rules as a manifest host,
|
||||
/// and a `*` is refused (`net:*` stays impossible).
|
||||
#[test]
|
||||
fn value_hosts_follow_the_manifest_host_rules() {
|
||||
assert_eq!(manifest_host("GitLab.Intranet.Example").unwrap(), "gitlab.intranet.example");
|
||||
for bad in
|
||||
["", "*", "*.example.com", "a b", "under_score.example", "gitlab.intranet.example.", &"a".repeat(254)]
|
||||
{
|
||||
assert!(manifest_host(bad).is_err(), "{bad}");
|
||||
}
|
||||
let long = ["a".repeat(61), "b".repeat(61), "c".repeat(61), "d".repeat(61)].join(".");
|
||||
assert_eq!(long.len(), 247);
|
||||
assert!(manifest_host(&long).is_ok());
|
||||
assert!(
|
||||
manifest_host(&["a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(63)].join(".")).is_err(),
|
||||
"over 253 bytes"
|
||||
);
|
||||
assert!(manifest_host(&"a".repeat(64)).is_err(), "over 63 bytes per label");
|
||||
// Pattern grants keep working: only a value (and a bare host) refuses `*`.
|
||||
assert!("net:*.github.com".parse::<Capability>().is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod database_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -58,6 +58,10 @@ pub struct Grant {
|
||||
/// Exact hosts approved through `net:ask`, separate from manifest grants.
|
||||
#[serde(default)]
|
||||
pub net_hosts: BTreeSet<String>,
|
||||
/// Hosts approved for `net:setting:<key>` / `net.http:setting:<key>`
|
||||
/// grants, keyed by the grant: the user approved the value in Settings.
|
||||
#[serde(default)]
|
||||
pub setting_hosts: BTreeMap<String, String>,
|
||||
/// Optional capabilities the user declined (not asked again until re-confirmed).
|
||||
#[serde(default)]
|
||||
pub declined: BTreeSet<String>,
|
||||
@@ -209,6 +213,7 @@ impl Ledger {
|
||||
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
|
||||
grant.net_hosts.clear();
|
||||
}
|
||||
retain_setting_hosts(grant, req);
|
||||
if !grant.confirmed {
|
||||
return Decision::NeedsConfirmation { new: req.required.clone(), first_time: true };
|
||||
}
|
||||
@@ -236,6 +241,7 @@ impl Ledger {
|
||||
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
|
||||
grant.net_hosts.clear();
|
||||
}
|
||||
retain_setting_hosts(grant, req);
|
||||
grant.plugin_id = req.plugin_id.to_owned();
|
||||
grant.version = req.version.to_owned();
|
||||
grant.package_hash = req.package_hash.to_owned();
|
||||
@@ -269,6 +275,9 @@ impl Ledger {
|
||||
if cap == &Capability::NetAsk {
|
||||
grant.net_hosts.clear();
|
||||
}
|
||||
if matches!(cap, Capability::NetSetting { .. }) {
|
||||
grant.setting_hosts.remove(&s);
|
||||
}
|
||||
if let Capability::Process(_) | Capability::JavaAgent = cap {
|
||||
grant.binaries.remove(&s);
|
||||
for binaries in grant.project_binaries.values_mut() {
|
||||
@@ -292,6 +301,21 @@ impl Ledger {
|
||||
self.grants.get_mut(subject).is_some_and(|g| g.net_hosts.remove(host))
|
||||
}
|
||||
|
||||
/// Remembers the host the user approved for a `net:setting:` grant: it
|
||||
/// covers requests only while the setting still holds it.
|
||||
pub fn remember_setting_host(&mut self, subject: &Subject, cap: &Capability, host: &str) -> bool {
|
||||
let Some(grant) = self.grants.get_mut(subject) else { return false };
|
||||
if !grant.confirmed || !grant.has(cap) || host.contains('*') {
|
||||
return false;
|
||||
}
|
||||
grant.setting_hosts.insert(cap.to_string(), host.to_owned());
|
||||
true
|
||||
}
|
||||
|
||||
pub fn forget_setting_host(&mut self, subject: &Subject, cap: &Capability) -> bool {
|
||||
self.grants.get_mut(subject).is_some_and(|g| g.setting_hosts.remove(&cap.to_string()).is_some())
|
||||
}
|
||||
|
||||
/// Records the program approved for a `process:` grant (or the jar of a `java.agent` one).
|
||||
pub fn set_binary(&mut self, subject: &Subject, cap: &Capability, binary: BinaryGrant) {
|
||||
if let Some(grant) = self.grants.get_mut(subject) {
|
||||
@@ -393,6 +417,19 @@ pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec<Capability>)> {
|
||||
groups.into_iter().map(|(r, v)| (r.0, v)).collect()
|
||||
}
|
||||
|
||||
/// Drops setting-derived hosts the manifest no longer asks for, like
|
||||
/// `net_hosts` are dropped when `net:ask` is removed.
|
||||
fn retain_setting_hosts(grant: &mut Grant, req: &Request<'_>) {
|
||||
let declared: Vec<String> = req
|
||||
.required
|
||||
.iter()
|
||||
.chain(&req.optional)
|
||||
.filter(|c| matches!(c, Capability::NetSetting { .. }))
|
||||
.map(|c| c.to_string())
|
||||
.collect();
|
||||
grant.setting_hosts.retain(|cap, _| declared.contains(cap));
|
||||
}
|
||||
|
||||
/// Pins an explicitly selected executable, retaining a multicall shim's filename.
|
||||
pub fn approve_program(path: &Path) -> Result<BinaryGrant, String> {
|
||||
if !path.is_absolute() || !is_executable(path) {
|
||||
@@ -589,6 +626,58 @@ mod tests {
|
||||
assert!(l.get(&r.subject).unwrap().net_hosts.is_empty());
|
||||
}
|
||||
|
||||
/// A setting-derived host is approved per grant, survives re-confirmation,
|
||||
/// is replaced by the next approval, and goes when the grant or the
|
||||
/// manifest declaration goes (#3809).
|
||||
#[test]
|
||||
fn setting_hosts_are_approved_per_grant_and_drop_with_it() {
|
||||
let mut l = Ledger::in_memory();
|
||||
let r = req("1.0.0", "h", &["project.read"], &["net:setting:server", "net.http:setting:server"]);
|
||||
l.confirm(
|
||||
&r,
|
||||
&["net:setting:server".parse().unwrap(), "net.http:setting:server".parse().unwrap()],
|
||||
BTreeMap::new(),
|
||||
);
|
||||
let cap: Capability = "net:setting:server".parse().unwrap();
|
||||
let other: Capability = "net.http:setting:server".parse().unwrap();
|
||||
|
||||
// Not granted (declined optional, or not confirmed): refused.
|
||||
let declined = req("1.0.0", "h", &["project.read"], &["net:setting:server"]);
|
||||
let mut l2 = Ledger::in_memory();
|
||||
l2.confirm(&declined, &[], BTreeMap::new());
|
||||
assert!(!l2.remember_setting_host(&declined.subject, &cap, "jira.corp.example"), "declined optional");
|
||||
let never = req("1.0.0", "h", &["project.read"], &[]);
|
||||
let mut l3 = Ledger::in_memory();
|
||||
assert!(!l3.remember_setting_host(&never.subject, &cap, "jira.corp.example"), "never confirmed");
|
||||
|
||||
assert!(l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example"));
|
||||
assert!(!l.remember_setting_host(&r.subject, &cap, "*"), "a wildcard value is refused");
|
||||
assert_eq!(
|
||||
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("gitlab.intranet.example")
|
||||
);
|
||||
// The other transport is its own record; the derived grant itself covers no host.
|
||||
assert!(l.remember_setting_host(&r.subject, &other, "jira.corp.example"));
|
||||
assert!(!l.get(&r.subject).unwrap().has(&Capability::Net("gitlab.intranet.example".into())));
|
||||
// Re-confirmation keeps the approval; a manifest that drops the grant drops the record.
|
||||
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
|
||||
assert_eq!(
|
||||
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("gitlab.intranet.example")
|
||||
);
|
||||
let without = req("2.0.0", "h2", &["project.read"], &[]);
|
||||
assert!(matches!(l.decide(&without), Decision::Allowed { .. }), "same or fewer needs: silent");
|
||||
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty(), "records follow the manifest");
|
||||
|
||||
// Revoking the capability clears its record.
|
||||
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
|
||||
l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example");
|
||||
assert!(l.set(&r.subject, &cap, false));
|
||||
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty());
|
||||
// Forgetting without a record is an error.
|
||||
assert!(!l.forget_setting_host(&r.subject, &cap));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_grants_low_risk_only() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -26,7 +26,9 @@ mod resolve;
|
||||
mod ui;
|
||||
mod when;
|
||||
|
||||
pub use capability::{Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, validate_ipc_name};
|
||||
pub use capability::{
|
||||
Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, manifest_host, validate_ipc_name,
|
||||
};
|
||||
pub use index::ContributionIndex;
|
||||
pub use manifest::{
|
||||
ActivationEvent, CATEGORIES, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, MAX_CATEGORIES,
|
||||
|
||||
@@ -372,6 +372,9 @@ impl Manifest {
|
||||
if matches!(cap, Capability::Agents) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
if matches!(cap, Capability::NetSetting { .. }) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
if matches!(cap, Capability::JavaAgent) {
|
||||
return Err(
|
||||
"`java.agent` comes from `[[contributes.javaAgents]]`: remove it from [capabilities]".into()
|
||||
@@ -767,6 +770,20 @@ required = [\"lsp:phoxite\"]
|
||||
assert_eq!(m.capabilities.optional, [Capability::ClipboardRead]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_derived_net_capabilities_need_the_current_api_minor() {
|
||||
for cap in ["net:setting:server", "net.http:setting:server"] {
|
||||
let caps = format!("[capabilities]\noptional = [\"{cap}\"]\n");
|
||||
assert!(
|
||||
err(&format!("{}{caps}", BASE.replace("^1.2", "^1.17"))).contains("new in plugin API 1.18"),
|
||||
"{cap}"
|
||||
);
|
||||
let m = Manifest::parse(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).unwrap();
|
||||
assert_eq!(m.capabilities.optional.len(), 1, "{cap}");
|
||||
assert_eq!(m.capabilities.optional[0].to_string(), cap);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_agent_capability_is_not_declared() {
|
||||
for list in ["required", "optional"] {
|
||||
|
||||
@@ -77,6 +77,69 @@ fn biome_formats(file: &Path) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
const PRETTIER_CONFIGS: [&str; 18] = [
|
||||
".prettierrc",
|
||||
".prettierrc.json",
|
||||
".prettierrc.json5",
|
||||
".prettierrc.yaml",
|
||||
".prettierrc.yml",
|
||||
".prettierrc.toml",
|
||||
".prettierrc.js",
|
||||
".prettierrc.cjs",
|
||||
".prettierrc.mjs",
|
||||
".prettierrc.ts",
|
||||
".prettierrc.cts",
|
||||
".prettierrc.mts",
|
||||
"prettier.config.js",
|
||||
"prettier.config.cjs",
|
||||
"prettier.config.mjs",
|
||||
"prettier.config.ts",
|
||||
"prettier.config.cts",
|
||||
"prettier.config.mts",
|
||||
];
|
||||
|
||||
/// A Prettier configuration applies to `file`: a configuration file or a `prettier` key in a
|
||||
/// `package.json` above it.
|
||||
fn prettier_configured(file: &Path) -> bool {
|
||||
PRETTIER_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some())
|
||||
|| file.ancestors().skip(1).any(|dir| {
|
||||
std::fs::read_to_string(dir.join("package.json"))
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
|
||||
.is_some_and(|v| v.get("prettier").is_some())
|
||||
})
|
||||
}
|
||||
|
||||
/// The languages whose server formats in the IDE's code style (`ts_code_style`).
|
||||
const CODE_STYLE_LANGUAGES: [&str; 4] = ["javascript", "javascriptreact", "typescript", "typescriptreact"];
|
||||
|
||||
/// In Automatic mode, the project's own configuration of `tool` wins over the TypeScript server,
|
||||
/// whose output follows the IDE's code style. Not before the tool is installed (`resolves`): a fresh
|
||||
/// clone keeps formatting with the server until `npm install`.
|
||||
fn project_takes_over(tool: ExternalFormatter, language: &str, file: &Path, resolves: impl FnOnce() -> bool) -> bool {
|
||||
CODE_STYLE_LANGUAGES.contains(&language) && project_configured(tool, file) && resolves()
|
||||
}
|
||||
|
||||
/// Format on save runs the external tool: its own setting, or the editor's when the tool takes over
|
||||
/// from the language server (Black, dprint, or a project configuration), so saving keeps formatting.
|
||||
fn runs_on_save(tool: ExternalFormatter, run_on_save: bool, takes_over: bool, format_on_save: bool) -> bool {
|
||||
run_on_save
|
||||
|| ((matches!(tool, ExternalFormatter::Black | ExternalFormatter::Dprint) || takes_over) && format_on_save)
|
||||
}
|
||||
|
||||
/// The project configures `tool`. Every formatter needs an arm. dprint is chosen before this check
|
||||
/// (`dprint_project`), so it never reaches it.
|
||||
fn project_configured(tool: ExternalFormatter, file: &Path) -> bool {
|
||||
match tool {
|
||||
ExternalFormatter::Prettier => prettier_configured(file),
|
||||
ExternalFormatter::Oxfmt => {
|
||||
OXFMT_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some())
|
||||
}
|
||||
ExternalFormatter::Biome => biome_formats(file),
|
||||
ExternalFormatter::Ruff | ExternalFormatter::Black | ExternalFormatter::Dprint => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `pyproject.toml` Black reads for `file`, in the project root Black finds: the nearest folder
|
||||
/// with `.git`, `.hg`, or a `pyproject.toml` that has `[tool.black]` (one without it is skipped).
|
||||
/// `None` when that root has no `pyproject.toml`: Black then reads the user's configuration.
|
||||
@@ -611,18 +674,26 @@ async fn provider_edits(
|
||||
if selected.is_none() {
|
||||
selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
|
||||
}
|
||||
let mut takes_over = false;
|
||||
// Black is selected only when configured or preferred: the Ruff server's formatting doesn't replace it.
|
||||
if let Some(tool) = selected
|
||||
&& options.tool.is_none()
|
||||
&& tool != ExternalFormatter::Dprint
|
||||
&& tool != ExternalFormatter::Black
|
||||
&& !settings.languages.formatter(tool).prefer
|
||||
&& match doc {
|
||||
Some(doc) => project.lsp.can_format(doc).await?,
|
||||
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
|
||||
}
|
||||
{
|
||||
selected = None;
|
||||
takes_over = project_takes_over(tool, snap.language.as_str(), &snap.path, || {
|
||||
let custom = ide_sdk::apply::setting_path(&project.root, &settings.languages.formatter(tool).path);
|
||||
Tools::new(&host.local_data_dir).formatter_command(tool.name(), &snap.path, custom.as_deref()).is_ok()
|
||||
});
|
||||
if !takes_over
|
||||
&& match doc {
|
||||
Some(doc) => project.lsp.can_format(doc).await?,
|
||||
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
|
||||
}
|
||||
{
|
||||
selected = None;
|
||||
}
|
||||
}
|
||||
let Some(selected) = selected else {
|
||||
if options.on_save && !settings.editor.format_on_save {
|
||||
@@ -644,10 +715,8 @@ async fn provider_edits(
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
};
|
||||
let tool_settings = settings.languages.formatter(selected);
|
||||
// Black and dprint take over from the language server in their projects, so Format on save runs them too.
|
||||
let runs_on_save = tool_settings.run_on_save
|
||||
|| (matches!(selected, ExternalFormatter::Black | ExternalFormatter::Dprint) && settings.editor.format_on_save);
|
||||
if options.on_save && !runs_on_save {
|
||||
if options.on_save && !runs_on_save(selected, tool_settings.run_on_save, takes_over, settings.editor.format_on_save)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
host.require_trust(window)?;
|
||||
@@ -814,7 +883,7 @@ pub async fn python_import_edits(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
|
||||
use ExternalFormatter::{Biome, Black, Dprint, Oxfmt, Prettier, Ruff};
|
||||
use ide_core::LanguageId;
|
||||
use ide_language::LanguageRegistry;
|
||||
|
||||
@@ -1182,6 +1251,55 @@ mod tests {
|
||||
assert_eq!(tool(None, "typescript", file, &settings).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_configuration_of_the_formatter_wins_over_the_language_server() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("a/src")).unwrap();
|
||||
std::fs::create_dir_all(root.join("b/src")).unwrap();
|
||||
std::fs::create_dir_all(root.join("c/src")).unwrap();
|
||||
std::fs::write(root.join("a/.prettierrc.json"), "{}").unwrap();
|
||||
std::fs::write(root.join("b/package.json"), r#"{ "prettier": { "semi": false } }"#).unwrap();
|
||||
std::fs::write(root.join("c/package.json"), r#"{ "name": "c" }"#).unwrap();
|
||||
std::fs::write(root.join("c/biome.json"), "{}").unwrap();
|
||||
assert!(project_configured(Prettier, &root.join("a/src/app.ts")));
|
||||
assert!(project_configured(Prettier, &root.join("b/src/app.ts")));
|
||||
assert!(!project_configured(Prettier, &root.join("c/src/app.ts")));
|
||||
assert!(project_configured(Biome, &root.join("c/src/app.ts")));
|
||||
assert!(!project_configured(Oxfmt, &root.join("c/src/app.ts")));
|
||||
std::fs::write(root.join("c/.oxfmtrc.json"), "{}").unwrap();
|
||||
assert!(project_configured(Oxfmt, &root.join("c/src/app.ts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join(".prettierrc"), "{}").unwrap();
|
||||
let file = |name: &str| dir.path().join(name);
|
||||
for language in ["typescript", "typescriptreact", "javascript", "javascriptreact"] {
|
||||
assert!(project_takes_over(Prettier, language, &file("a.ts"), || true), "{language}");
|
||||
}
|
||||
for language in ["json", "css", "html", "yaml", "markdown", "vue"] {
|
||||
assert!(!project_takes_over(Prettier, language, &file("a.json"), || true), "{language}");
|
||||
}
|
||||
// Configured but not installed yet (before `npm install`): the language server formats.
|
||||
assert!(!project_takes_over(Prettier, "typescript", &file("a.ts"), || false));
|
||||
// No configuration: the tool isn't even looked up.
|
||||
assert!(!project_takes_over(Biome, "typescript", &file("a.ts"), || panic!("resolved")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_on_save_keeps_running_when_the_project_formatter_takes_over() {
|
||||
// Format on save formatted with the language server before; the tool that replaces it does too.
|
||||
assert!(runs_on_save(Prettier, false, true, true));
|
||||
assert!(!runs_on_save(Prettier, false, true, false));
|
||||
assert!(runs_on_save(Black, false, false, true));
|
||||
assert!(runs_on_save(Dprint, false, false, true));
|
||||
// Selected by the settings, not taking over: only its own Run on save.
|
||||
assert!(!runs_on_save(Prettier, false, false, true));
|
||||
assert!(runs_on_save(Prettier, true, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_tool_runs_that_formatter_or_reports_why_not() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -27,6 +27,7 @@ mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub mod trust;
|
||||
mod ts_code_style;
|
||||
mod tsc_watch;
|
||||
pub mod web_server;
|
||||
|
||||
|
||||
@@ -380,6 +380,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"Appearance",
|
||||
vec![
|
||||
act("editor.toggleZen", "Enter Distraction Free Mode"),
|
||||
act("view.toggleZenMode", "Enter Zen Mode"),
|
||||
act("window.toggleFullScreen", "Toggle Full Screen"),
|
||||
toggle("view.toggleCompactMode", "Compact Mode"),
|
||||
toggle("view.togglePresentationAssistant", "Presentation Assistant"),
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct ProjectInfo {
|
||||
pub workspace: Option<ide_workspace::workspace::Workspace>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub unity: Option<ide_workspace::unity::UnityProjectInfo>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub unreal: Option<ide_workspace::unreal::UnrealProjectInfo>,
|
||||
}
|
||||
|
||||
pub fn info(project: &Project) -> ProjectInfo {
|
||||
@@ -45,6 +47,7 @@ pub fn info(project: &Project) -> ProjectInfo {
|
||||
root: project.root.clone().into(),
|
||||
workspace,
|
||||
unity: ide_workspace::unity::detect(&project.root),
|
||||
unreal: ide_workspace::unreal::detect(&project.root),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,12 @@ struct LogAccess {
|
||||
cache: PathBuf,
|
||||
}
|
||||
|
||||
fn external_log_of(host: &Host, window: &str, path: &Path) -> Option<std::sync::Arc<Repo>> {
|
||||
host.external_logs.read().get(host.owner_window(window)).and_then(|repos| {
|
||||
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
})
|
||||
}
|
||||
|
||||
/// Immutable Git objects exposed through the editor's ordinary read-only VFS.
|
||||
/// `encoding` re-decodes the blob with it ("Reload with Encoding") instead of
|
||||
/// the project's detection.
|
||||
@@ -81,9 +87,7 @@ async fn revision_text(
|
||||
encoding: Option<&str>,
|
||||
) -> IdeResult<Option<(String, &'static encoding_rs::Encoding, bool)>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
|
||||
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
});
|
||||
let external = external_log_of(host, window, path);
|
||||
let (path, rev, encoding) = (path.to_path_buf(), rev.to_owned(), encoding.map(str::to_owned));
|
||||
blocking(move || {
|
||||
fn with_repo<T>(
|
||||
@@ -622,9 +626,7 @@ pub async fn vcs_staging_line_hunks(
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
|
||||
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
});
|
||||
let external = external_log_of(host, window, &path);
|
||||
blocking(move || {
|
||||
if let Some(project) = project {
|
||||
return project.with_log_backend_of(&path, |r| {
|
||||
@@ -640,14 +642,37 @@ pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<S
|
||||
.await
|
||||
}
|
||||
|
||||
/// An image at the selected Git revision or index stage as a data URL, absent if the path is missing.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_image_at(host: &Host, window: &str, path: PathBuf, rev: String) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = external_log_of(host, window, &path);
|
||||
blocking(move || {
|
||||
let mime = ide_vfs::image_mime(&path)
|
||||
.ok_or_else(|| ide_core::IdeError::invalid(format!("{} is not a supported image", path.display())))?;
|
||||
let read = |repo: &Repo| repo.file_bytes_at_bounded(&path, &rev, ide_vfs::MAX_IMAGE_SIZE as usize);
|
||||
let bytes = if let Some(project) = project {
|
||||
if !ide_vfs::on_local_drive(&path)
|
||||
&& external.is_none()
|
||||
&& !project.repos().all().iter().any(|repo| ide_vfs::same_share(repo.root(), &path))
|
||||
{
|
||||
return Err(ide_core::IdeError::invalid("image is not on a local drive or an opened share"));
|
||||
}
|
||||
project.with_log_repo_of(&path, read)?
|
||||
} else {
|
||||
read(external.as_deref().ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?)?
|
||||
};
|
||||
Ok(bytes.map(|bytes| format!("data:{mime};base64,{}", ide_vfs::base64(&bytes))))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The file's git mode at `rev` (`100644`, `100755`, `120000`…), `"WT"` for the
|
||||
/// worktree; `None` when absent there. Lets the diff viewer report a mode-only change.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_file_mode(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
|
||||
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
});
|
||||
let external = external_log_of(host, window, &path);
|
||||
blocking(move || {
|
||||
if let Some(project) = project {
|
||||
return project.with_log_backend_of(&path, |r| r.file_mode_at(&path, rev.as_deref()));
|
||||
@@ -3200,6 +3225,7 @@ ide_command::domain!(
|
||||
vcs_discard,
|
||||
vcs_edit_remote,
|
||||
vcs_file_at,
|
||||
vcs_image_at,
|
||||
vcs_file_mode,
|
||||
vcs_diff_entries,
|
||||
vcs_git_version,
|
||||
|
||||
@@ -686,6 +686,9 @@ pub(super) struct Shared {
|
||||
net_prompts: Mutex<HashMap<String, Option<Instant>>>,
|
||||
pub net_hosts_session_only: AtomicBool,
|
||||
session_net_hosts: Mutex<HashMap<String, BTreeSet<String>>>,
|
||||
/// Setting-derived approvals kept for the session only (remote hosts),
|
||||
/// plugin → `net:setting:` grant → its approved host.
|
||||
pub(super) session_setting_hosts: Mutex<HashMap<String, BTreeMap<String, String>>>,
|
||||
pub(super) next_prompt: AtomicU64,
|
||||
pub(super) run_configurations: super::run_detectors::DynamicConfigurations,
|
||||
pub(super) run_targets: Mutex<super::run_targets::Targets>,
|
||||
@@ -733,6 +736,29 @@ pub(super) struct Shared {
|
||||
/// A window's log tabs of one plugin: key → what it runs, oldest first.
|
||||
type LogTabs = Vec<(String, ide_plugin::ServiceLog)>;
|
||||
|
||||
/// The settings key a `net:setting:` grant derives its host from.
|
||||
fn setting_key(cap: &Capability) -> String {
|
||||
match cap {
|
||||
Capability::NetSetting { key, .. } => key.clone(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The host a setting value names: a bare host, or a URL the user pasted
|
||||
/// (`https://jira.corp.example/`), checked with the manifest host rules — a `*`
|
||||
/// is refused. `Ok(None)` when the value is empty (the setting is cleared).
|
||||
pub(super) fn setting_host(value: &str) -> Result<Option<String>, String> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let host =
|
||||
if value.contains("://") { ide_plugin::net_host(value)? } else { value.trim_end_matches('.').to_owned() };
|
||||
ide_extension::manifest_host(&host)
|
||||
.map(Some)
|
||||
.map_err(|_| format!("{value:?} is not a host (example.com) or a URL (https://example.com/)"))
|
||||
}
|
||||
|
||||
/// Log tabs a plugin's code may have open in one window; opening more forgets
|
||||
/// the oldest (that tab can no longer start its program).
|
||||
const MAX_LOG_TABS: usize = 32;
|
||||
@@ -771,6 +797,7 @@ impl Shared {
|
||||
net_prompts: Mutex::default(),
|
||||
net_hosts_session_only: AtomicBool::new(false),
|
||||
session_net_hosts: Mutex::default(),
|
||||
session_setting_hosts: Mutex::default(),
|
||||
next_prompt: AtomicU64::new(1),
|
||||
run_configurations: Arc::default(),
|
||||
run_targets: Mutex::default(),
|
||||
@@ -1038,6 +1065,7 @@ impl Shared {
|
||||
self.withdraw_prompts(plugin);
|
||||
self.net_prompts.lock().remove(plugin);
|
||||
self.session_net_hosts.lock().remove(plugin);
|
||||
self.session_setting_hosts.lock().remove(plugin);
|
||||
let removed: Vec<(Option<String>, String)> = {
|
||||
let mut contexts = self.contexts.lock();
|
||||
let keys: Vec<_> = contexts.keys().filter(|(_, p, _)| p == plugin).cloned().collect();
|
||||
@@ -1556,6 +1584,51 @@ fn project_subdirectory(root: &Path, cwd: &str) -> Result<PathBuf, HostError> {
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
impl PluginApi {
|
||||
/// The value of `key` the user set for this plugin, as a plain string
|
||||
/// (`None` when unset or not a string).
|
||||
pub(super) fn setting_value(&self, key: &str) -> Option<String> {
|
||||
let raw = self.setting(None, key)?;
|
||||
serde_json::from_str::<String>(&raw).ok()
|
||||
}
|
||||
|
||||
/// The plugin's `net:setting:` grants with their hosts: the approved host
|
||||
/// while the setting still holds it, and the pending one to approve
|
||||
/// otherwise (`None` when the value is unset or not a host).
|
||||
pub(super) fn net_setting_hosts(&self, subject: &Subject) -> Vec<(Capability, Option<String>, Option<String>)> {
|
||||
let derived: Vec<Capability> = self
|
||||
.pkg
|
||||
.manifest
|
||||
.capabilities
|
||||
.all()
|
||||
.filter(|c| matches!(c, Capability::NetSetting { .. }))
|
||||
.cloned()
|
||||
.collect();
|
||||
if derived.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let ledger = self.shared.ledger.lock();
|
||||
let grant = ledger.get(subject).filter(|g| g.confirmed);
|
||||
let session = self.shared.session_setting_hosts.lock().get(self.id()).cloned().unwrap_or_default();
|
||||
derived
|
||||
.into_iter()
|
||||
.map(|cap| {
|
||||
let current = self.setting_value(&setting_key(&cap)).and_then(|v| setting_host(&v).ok()).flatten();
|
||||
let record = grant.and_then(|g| g.setting_hosts.get(&cap.to_string())).map(String::as_str);
|
||||
let session_host = session.get(&cap.to_string()).map(String::as_str);
|
||||
// An approval covers requests only while the setting still holds it.
|
||||
let approved = [record, session_host]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|host| current.as_deref() == Some(host))
|
||||
.map(str::to_owned);
|
||||
let pending = current.filter(|host| approved.as_deref() != Some(host));
|
||||
(cap, approved, pending)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl HostApi for PluginApi {
|
||||
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
|
||||
let (host, db) = self.database_host(root)?;
|
||||
@@ -2798,6 +2871,16 @@ impl HostApi for PluginApi {
|
||||
return Ok(None);
|
||||
}
|
||||
let host = host.trim_end_matches('.').to_ascii_lowercase();
|
||||
// A host the plugin derives from a setting is approved in Settings,
|
||||
// not asked about here: pending or revoked, it stays denied without a
|
||||
// dialog (#3809).
|
||||
if self.pkg.manifest.capabilities.all().any(|cap| {
|
||||
matches!(cap, Capability::NetSetting { http: false, key: _ })
|
||||
&& self.setting_value(&setting_key(cap)).and_then(|v| setting_host(&v).ok()).flatten().as_deref()
|
||||
== Some(host.as_str())
|
||||
}) {
|
||||
return Ok(None);
|
||||
}
|
||||
{
|
||||
let ledger = self.shared.ledger.lock();
|
||||
if let Some(grant) = ledger.get(subject)
|
||||
|
||||
@@ -1174,6 +1174,92 @@ impl PluginHost {
|
||||
self.info_of(id)
|
||||
}
|
||||
|
||||
/// Approves the host the plugin's `net:setting:<key>` grant derives from
|
||||
/// the setting's value right now: the dialog when the user applies the
|
||||
/// value in Settings, or the pending row's Approve action. `expected` is
|
||||
/// the host the user was shown: when the setting changed since (the plugin
|
||||
/// can write its own settings), nothing is approved. On a remote host the
|
||||
/// approval is kept for the session only, like `net:ask` (#3809).
|
||||
pub fn approve_net_setting(&self, id: &str, setting: &str, http: bool, expected: &str) -> IdeResult<PluginInfo> {
|
||||
let _guard = self.lifecycle.lock();
|
||||
let plugin = self.get(id)?;
|
||||
self.check_not_uninstalling(&plugin)?;
|
||||
let cap = Capability::NetSetting { http, key: setting.to_owned() };
|
||||
if !plugin.manifest().declares(&cap) {
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} does not declare {cap}")));
|
||||
}
|
||||
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
|
||||
let value = api
|
||||
.setting_value(setting)
|
||||
.ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no value")))?;
|
||||
let host = api::setting_host(&value)
|
||||
.map_err(IdeError::invalid)?
|
||||
.ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no host")))?;
|
||||
if host != expected {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"setting {setting:?} now holds {host}, not {expected}: approve the new value instead"
|
||||
)));
|
||||
}
|
||||
let session_only = self.shared.net_hosts_session_only.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if !session_only {
|
||||
let mut ledger = self.ledger.lock();
|
||||
if !ledger.remember_setting_host(&plugin.subject(), &cap, &host) {
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} does not have {cap} granted")));
|
||||
}
|
||||
self.save_ledger(&ledger);
|
||||
}
|
||||
self.stop(&plugin);
|
||||
if session_only {
|
||||
self.shared.session_setting_hosts.lock().entry(id.to_owned()).or_default().insert(cap.to_string(), host);
|
||||
}
|
||||
if !self.state.lock().disabled.contains(id) {
|
||||
self.start(&plugin);
|
||||
}
|
||||
// Plugins that need this one follow it: running again, or blocked while it can't run.
|
||||
self.settle_dependents(id);
|
||||
self.changed();
|
||||
self.info_of(id)
|
||||
}
|
||||
|
||||
/// The host a `net:setting:<key>` grant derives from `value` (a bare host
|
||||
/// or a URL), for the approval dialog; an error refuses the value.
|
||||
pub fn net_setting_host(&self, id: &str, setting: &str, value: &str) -> IdeResult<String> {
|
||||
let plugin = self.get(id)?;
|
||||
let cap = Capability::NetSetting { http: false, key: setting.to_owned() };
|
||||
if !plugin.manifest().declares(&cap)
|
||||
&& !plugin.manifest().declares(&Capability::NetSetting { http: true, key: setting.to_owned() })
|
||||
{
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} does not declare a setting grant for {setting:?}")));
|
||||
}
|
||||
api::setting_host(value)
|
||||
.map_err(IdeError::invalid)?
|
||||
.ok_or_else(|| IdeError::invalid(format!("{value:?} holds no host")))
|
||||
}
|
||||
|
||||
/// Drops the approved host of a `net:setting:<key>` grant (its revoke
|
||||
/// action, or the setting's value being cleared). Nothing recorded: still
|
||||
/// fine, the state is already as asked.
|
||||
pub fn forget_net_setting(&self, id: &str, setting: &str, http: bool) -> IdeResult<PluginInfo> {
|
||||
let _guard = self.lifecycle.lock();
|
||||
let plugin = self.get(id)?;
|
||||
self.check_not_uninstalling(&plugin)?;
|
||||
let cap = Capability::NetSetting { http, key: setting.to_owned() };
|
||||
{
|
||||
let mut ledger = self.ledger.lock();
|
||||
ledger.forget_setting_host(&plugin.subject(), &cap);
|
||||
self.save_ledger(&ledger);
|
||||
}
|
||||
self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string()));
|
||||
self.stop(&plugin);
|
||||
if !self.state.lock().disabled.contains(id) {
|
||||
self.start(&plugin);
|
||||
}
|
||||
// Plugins that need this one follow it: running again, or blocked while it can't run.
|
||||
self.settle_dependents(id);
|
||||
self.changed();
|
||||
self.info_of(id)
|
||||
}
|
||||
|
||||
/// Grants or revokes one declared capability (Settings › Plugins › Permissions).
|
||||
/// Revoking a required one stops the plugin until consent is given again.
|
||||
pub fn set_capability(&self, id: &str, capability: &str, granted: bool) -> IdeResult<PluginInfo> {
|
||||
@@ -1191,6 +1277,10 @@ impl PluginHost {
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} has not been confirmed yet")));
|
||||
}
|
||||
ledger.set(&subject, &cap, granted);
|
||||
if !granted {
|
||||
// A session-only approval of a setting-derived host goes with its grant.
|
||||
self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string()));
|
||||
}
|
||||
if granted
|
||||
&& cap == Capability::JavaAgent
|
||||
&& let Some(jar) = agent_jar_grant(plugin.manifest(), plugin.dir())
|
||||
@@ -2748,6 +2838,7 @@ impl PluginHost {
|
||||
fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> {
|
||||
plugin_icon(pkg)?;
|
||||
let mut set = self.registry.prepare(pkg)?;
|
||||
check_setting_grants(pkg)?;
|
||||
for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() {
|
||||
if !set.files.contains(icon) {
|
||||
set.files.push(icon.clone());
|
||||
@@ -2906,7 +2997,7 @@ impl PluginHost {
|
||||
meta.declared_extra = set.capabilities.clone();
|
||||
meta.error = None;
|
||||
}
|
||||
let (granted, pending) = match decision {
|
||||
let (mut granted, pending) = match decision {
|
||||
Decision::Allowed { granted, pending } => (granted, pending),
|
||||
Decision::NeedsConfirmation { new, .. } => {
|
||||
let mut meta = plugin.meta.lock();
|
||||
@@ -2919,6 +3010,19 @@ impl PluginHost {
|
||||
if let Err(e) = self.registry.commit(set) {
|
||||
return self.set_failed(plugin, e);
|
||||
}
|
||||
// Setting-derived network grants materialize their approved host while
|
||||
// the setting holds it: `net:setting:server` acts as `net:<host>`, so
|
||||
// the request path keeps its rules (`net_capability` / `covers`).
|
||||
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
|
||||
for (cap, approved, _pending) in api.net_setting_hosts(&plugin.subject()) {
|
||||
if let Some(host) = approved {
|
||||
match cap {
|
||||
Capability::NetSetting { http: false, key: _ } => granted.push(Capability::Net(host)),
|
||||
Capability::NetSetting { http: true, key: _ } => granted.push(Capability::NetHttp(host)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut meta = plugin.meta.lock();
|
||||
meta.granted = granted;
|
||||
@@ -3374,6 +3478,21 @@ impl PluginHost {
|
||||
.filter(|g| g.confirmed && g.has(&Capability::NetAsk) && m.declares(&Capability::NetAsk))
|
||||
.map(|g| g.net_hosts.iter().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
// Setting-derived hosts, listed next to the `net:ask` ones: the
|
||||
// approved host, and a pending one the setting now holds.
|
||||
let net_settings = if m.capabilities.all().any(|c| matches!(c, Capability::NetSetting { .. })) {
|
||||
let api = api::PluginApi { pkg: p.pkg.clone(), shared: self.shared.clone() };
|
||||
api.net_setting_hosts(&p.subject())
|
||||
.into_iter()
|
||||
.filter(|(cap, ..)| grant.as_ref().is_some_and(|g| g.confirmed && g.has(cap)))
|
||||
.map(|(cap, approved, pending)| {
|
||||
let Capability::NetSetting { http, key } = cap else { unreachable!() };
|
||||
types::PluginNetSetting { setting: key, http, host: approved, pending }
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
PluginInfo {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
@@ -3414,6 +3533,7 @@ impl PluginHost {
|
||||
has_code: m.wasm.is_some(),
|
||||
capabilities,
|
||||
net_hosts,
|
||||
net_settings,
|
||||
contributions: self.registry.contributions(&m.id),
|
||||
activation: m.activation.iter().map(ToString::to_string).collect(),
|
||||
warnings: meta.warnings.clone(),
|
||||
@@ -3442,6 +3562,37 @@ fn agent_jar_grant(manifest: &Manifest, dir: &Path) -> Option<BinaryGrant> {
|
||||
Some(BinaryGrant { path, hash })
|
||||
}
|
||||
|
||||
/// `net:setting:<key>` grants name a `string` setting of the plugin's own
|
||||
/// settings schema; checked like the other manifest checks, at install and
|
||||
/// start (#3809).
|
||||
fn check_setting_grants(pkg: &Package) -> Result<(), String> {
|
||||
let derived: Vec<&Capability> =
|
||||
pkg.manifest.capabilities.all().filter(|c| matches!(c, Capability::NetSetting { .. })).collect();
|
||||
if derived.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut strings = BTreeSet::new();
|
||||
for decl in pkg.manifest.declarations(ui_points::SETTINGS) {
|
||||
let decl = ui_points::settings(pkg, decl)?;
|
||||
for property in decl.json.get("properties").and_then(|p| p.as_array()).into_iter().flatten() {
|
||||
if property.get("type").and_then(|t| t.as_str()) == Some("string")
|
||||
&& let Some(key) = property.get("key").and_then(|k| k.as_str())
|
||||
{
|
||||
strings.insert(key.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
for cap in derived {
|
||||
let Capability::NetSetting { http: _, key } = cap else { continue };
|
||||
if !strings.contains(key.as_str()) {
|
||||
return Err(format!(
|
||||
"capability `{cap}` needs a `string` setting {key:?} in the plugin's own settings schema"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Consent / Settings: surface exact contributed JVM flags on the `java.agent` permission.
|
||||
fn annotate_java_agent_vm_options(capabilities: &mut [CapabilityInfo], manifest: &Manifest) {
|
||||
let opts = java_agents::declared_vm_options(manifest);
|
||||
|
||||
@@ -76,6 +76,20 @@ pub struct PluginJavaAgent {
|
||||
pub executor: Option<String>,
|
||||
}
|
||||
|
||||
/// A `net:setting:` grant's host for Settings › Plugins: the approved one while the setting holds it, else the pending one.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginNetSetting {
|
||||
/// The setting key the host comes from (`server` of `net:setting:server`).
|
||||
pub setting: String,
|
||||
/// Plain HTTP (`net.http:setting:`) instead of HTTPS (and loopback HTTP).
|
||||
pub http: bool,
|
||||
/// The approved host, while the setting still holds it.
|
||||
pub host: Option<String>,
|
||||
/// The host the setting holds now when it is not the approved one.
|
||||
pub pending: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginInfo {
|
||||
@@ -101,6 +115,8 @@ pub struct PluginInfo {
|
||||
/// HTTPS hosts the user allowed through `net:ask` ("always allow"),
|
||||
/// none of them declared by the manifest; each can be revoked.
|
||||
pub net_hosts: Vec<String>,
|
||||
/// Setting-derived hosts (`net:setting:`), approved in Settings, listed next to the `net:ask` ones.
|
||||
pub net_settings: Vec<PluginNetSetting>,
|
||||
/// What it contributes while live (point + label).
|
||||
pub contributions: Vec<ContributionInfo>,
|
||||
/// `activation` events of the manifest.
|
||||
|
||||
@@ -208,6 +208,7 @@ impl Host {
|
||||
let root = member.as_ref().unwrap_or(window_root);
|
||||
ide_sdk::apply::server_launch_overrides(cfg, &effective);
|
||||
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
|
||||
crate::ts_code_style::configure(cfg, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
let container_python = effective.languages.python.run_target().is_some();
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript
|
||||
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
|
||||
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
|
||||
//! quick fixes, auto-imports, refactorings and organize imports.
|
||||
|
||||
use ide_core::editor_settings::LanguageCodeStyle;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_language::LanguageServerConfig;
|
||||
use ide_workspace::EditorConfig;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
const SERVERS: [&str; 2] = ["vtsls", "typescript-language-server"];
|
||||
|
||||
/// tsserver's space options the Spaces tab sets, with the IntelliJ `.editorconfig` property
|
||||
/// (`ij_<language>_<name>`) that sets the same thing.
|
||||
const SPACES: [(&str, Option<&str>); 14] = [
|
||||
("insertSpaceAfterCommaDelimiter", Some("space_after_comma")),
|
||||
("insertSpaceAfterSemicolonInForStatements", Some("space_after_semicolon")),
|
||||
("insertSpaceBeforeAndAfterBinaryOperators", None),
|
||||
("insertSpaceAfterKeywordsInControlFlowStatements", None),
|
||||
("insertSpaceAfterFunctionKeywordForAnonymousFunctions", Some("space_before_function_left_parenth")),
|
||||
("insertSpaceBeforeFunctionParenthesis", Some("space_before_method_parentheses")),
|
||||
("insertSpaceAfterConstructor", None),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis", None),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", Some("spaces_within_brackets")),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", Some("spaces_within_object_literal_braces")),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces", None),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", Some("spaces_within_interpolation_expressions")),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces", None),
|
||||
("insertSpaceAfterTypeAssertion", None),
|
||||
];
|
||||
|
||||
/// Adds the code style of JavaScript and TypeScript to a TypeScript server's settings. A file's
|
||||
/// `.editorconfig` comes first, as in the editor (resolved for the server root's `index.ts` /
|
||||
/// `index.js`: the servers take one configuration per project); the server's own settings win.
|
||||
pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &Settings) {
|
||||
if !SERVERS.contains(&cfg.name.as_str()) {
|
||||
return;
|
||||
}
|
||||
let code_style = &settings.editor.code_style;
|
||||
let editorconfig = code_style.editorconfig.then(EditorConfig::new);
|
||||
let mut layer = Map::new();
|
||||
for (language, ext) in [("typescript", "ts"), ("javascript", "js")] {
|
||||
let pairs = editorconfig
|
||||
.as_ref()
|
||||
.and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}"))))
|
||||
.unwrap_or_default();
|
||||
let section = section(language, code_style.languages.get(language), &pairs);
|
||||
if !section.is_empty() {
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
}
|
||||
if layer.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut merged = Value::Object(layer);
|
||||
if let Some(own) = cfg.settings.take() {
|
||||
ide_sdk::apply::merge(&mut merged, own);
|
||||
}
|
||||
cfg.settings = Some(merged);
|
||||
}
|
||||
|
||||
/// The `format` and `preferences` of one language's section.
|
||||
fn section(
|
||||
language: &str,
|
||||
style: Option<&LanguageCodeStyle>,
|
||||
editorconfig: &HashMap<String, String>,
|
||||
) -> Map<String, Value> {
|
||||
let get = |key: &str| editorconfig.get(key).map(|v| v.to_ascii_lowercase());
|
||||
let flag = |name: &str| match get(&format!("ij_{language}_{name}")).as_deref() {
|
||||
Some("true") => Some(true),
|
||||
Some("false") => Some(false),
|
||||
_ => None,
|
||||
};
|
||||
let pick = |value: Option<&String>, allowed: &[&str]| value.filter(|v| allowed.contains(&v.as_str())).cloned();
|
||||
|
||||
let mut format = Map::new();
|
||||
for (key, ij) in SPACES {
|
||||
if let Some(on) = ij.and_then(flag).or_else(|| style.and_then(|s| s.spaces.get(key).copied())) {
|
||||
format.insert(key.into(), json!(on));
|
||||
}
|
||||
}
|
||||
let semicolons = flag("use_semicolon_after_statement")
|
||||
.map(|on| if on { "insert" } else { "remove" }.to_owned())
|
||||
.or_else(|| pick(style.and_then(|s| s.semicolons.as_ref()), &["ignore", "insert", "remove"]));
|
||||
if let Some(semicolons) = semicolons {
|
||||
format.insert("semicolons".into(), json!(semicolons));
|
||||
}
|
||||
let quotes = pick(get("quote_type").as_ref(), &["auto", "single", "double"])
|
||||
.or_else(|| flag("use_double_quotes").map(|on| if on { "double" } else { "single" }.to_owned()))
|
||||
.or_else(|| pick(style.and_then(|s| s.quotes.as_ref()), &["auto", "single", "double"]));
|
||||
|
||||
let mut section = Map::new();
|
||||
if !format.is_empty() {
|
||||
section.insert("format".into(), Value::Object(format));
|
||||
}
|
||||
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
|
||||
if let Some(quotes) = quotes {
|
||||
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": quotes }));
|
||||
}
|
||||
section
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn server(name: &str) -> LanguageServerConfig {
|
||||
serde_json::from_value(json!({ "name": name, "command": name })).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_style_reaches_typescript_and_javascript_sections() {
|
||||
let mut settings = Settings::default();
|
||||
let ts = LanguageCodeStyle {
|
||||
semicolons: Some("remove".into()),
|
||||
quotes: Some("single".into()),
|
||||
spaces: [("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces".into(), false)].into(),
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("typescript".into(), ts);
|
||||
let js = LanguageCodeStyle { semicolons: Some("insert".into()), ..Default::default() };
|
||||
settings.editor.code_style.languages.insert("javascript".into(), js);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
cfg.settings = Some(json!({ "typescript": { "preferences": { "quoteStyle": "double" } } }));
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
assert_eq!(
|
||||
cfg.settings.unwrap(),
|
||||
json!({
|
||||
"typescript": {
|
||||
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
|
||||
// The server's own settings win.
|
||||
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
|
||||
},
|
||||
"javascript": { "format": { "semicolons": "insert" } },
|
||||
})
|
||||
);
|
||||
|
||||
let mut eslint = server("eslint");
|
||||
configure(&mut eslint, dir.path(), &settings);
|
||||
assert_eq!(eslint.settings, None);
|
||||
let mut untouched = server("vtsls");
|
||||
configure(&mut untouched, dir.path(), &Settings::default());
|
||||
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_comes_first() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join(".editorconfig"),
|
||||
"root = true\n[*.ts]\nquote_type = double\nij_typescript_use_semicolon_after_statement = false\n\
|
||||
ij_typescript_space_after_comma = false\n[*.js]\nij_javascript_use_double_quotes = false\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut settings = Settings::default();
|
||||
let ts = LanguageCodeStyle {
|
||||
semicolons: Some("insert".into()),
|
||||
quotes: Some("single".into()),
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("typescript".into(), ts);
|
||||
let mut cfg = server("typescript-language-server");
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
let s = cfg.settings.unwrap();
|
||||
assert_eq!(
|
||||
s["typescript"]["format"],
|
||||
json!({ "semicolons": "remove", "insertSpaceAfterCommaDelimiter": false })
|
||||
);
|
||||
assert_eq!(s["typescript"]["preferences"]["quotePreference"], "double");
|
||||
assert_eq!(s["javascript"]["preferences"]["quoteStyle"], "single");
|
||||
|
||||
settings.editor.code_style.editorconfig = false;
|
||||
let mut cfg = server("vtsls");
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
let s = cfg.settings.unwrap();
|
||||
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
|
||||
assert_eq!(s.get("javascript"), None);
|
||||
}
|
||||
}
|
||||
@@ -110,3 +110,49 @@ async fn external_history_is_readable_and_never_becomes_a_write_target() {
|
||||
assert!(!deleted.exists());
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn revision_images_use_the_selected_git_blob_and_window() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("repo");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
git(&root, &["init", "-b", "main"]);
|
||||
let old = root.join("old.PNG");
|
||||
let new = root.join("new.webp");
|
||||
std::fs::write(&old, [0x89, 0x00, 0xff]).unwrap();
|
||||
std::fs::write(root.join("icon.svg"), b"<svg/>").unwrap();
|
||||
std::fs::write(root.join("photo.jpeg"), [0xff, 0xd8]).unwrap();
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-m", "old image"]);
|
||||
let first = git(&root, &["rev-parse", "HEAD"]);
|
||||
git(&root, &["mv", "old.PNG", "new.webp"]);
|
||||
std::fs::write(&new, [0xff, 0xfe]).unwrap();
|
||||
git(&root, &["commit", "-am", "rename and change image"]);
|
||||
std::fs::write(&new, [0x00, 0x80]).unwrap();
|
||||
git(&root, &["add", "new.webp"]);
|
||||
std::fs::write(&new, "working tree only").unwrap();
|
||||
|
||||
let host = Host::new(common::host_config(&base));
|
||||
let read = |window, path: &Path, rev: &str| vcs::vcs_image_at(&host, window, path.to_owned(), rev.to_owned());
|
||||
assert!(read("standalone", &old, &first).await.is_err());
|
||||
vcs::vcs_open_external_log(&host, "standalone", root.clone()).await.unwrap();
|
||||
assert_eq!(read("standalone", &old, &first).await.unwrap().as_deref(), Some("data:image/png;base64,iQD/"));
|
||||
assert!(read("another-window", &old, &first).await.is_err());
|
||||
|
||||
host.trust.decide(&root, false, false).unwrap();
|
||||
host.open_project("project", &root).unwrap();
|
||||
assert_eq!(read("project", &new, "HEAD").await.unwrap().as_deref(), Some("data:image/webp;base64,//4="));
|
||||
assert_eq!(read("project", &new, ":0").await.unwrap().as_deref(), Some("data:image/webp;base64,AIA="));
|
||||
assert_eq!(read("project", &old, "HEAD").await.unwrap(), None);
|
||||
assert_eq!(
|
||||
read("project", &root.join("icon.svg"), "HEAD").await.unwrap().as_deref(),
|
||||
Some("data:image/svg+xml;base64,PHN2Zy8+")
|
||||
);
|
||||
assert_eq!(
|
||||
read("project", &root.join("photo.jpeg"), "HEAD").await.unwrap().as_deref(),
|
||||
Some("data:image/jpeg;base64,/9g=")
|
||||
);
|
||||
assert!(read("project", &base.join("outside.png"), "HEAD").await.is_err());
|
||||
assert!(read("project", &root.join("file.txt"), "HEAD").await.is_err());
|
||||
}
|
||||
@@ -6631,6 +6631,272 @@ fn net_ask_session_hosts_are_ephemeral_and_cleared_with_plugin_grants() {
|
||||
assert_eq!(seen.lock().len(), 9);
|
||||
}
|
||||
|
||||
/// Sets a plugin's global setting value in the test workspace.
|
||||
fn set_setting(f: &Fixture, plugin: &str, value: &str) {
|
||||
let mut map = serde_json::Map::new();
|
||||
map.insert("server".into(), serde_json::Value::String(value.into()));
|
||||
f.workspace.global_settings.lock().insert(plugin.to_owned(), map);
|
||||
}
|
||||
|
||||
fn net_setting_of<'a>(info: &'a PluginInfo, setting: &str) -> Option<&'a PluginNetSetting> {
|
||||
info.net_settings.iter().find(|s| s.setting == setting && !s.http)
|
||||
}
|
||||
|
||||
fn http_setting_of<'a>(info: &'a PluginInfo, setting: &str) -> Option<&'a PluginNetSetting> {
|
||||
info.net_settings.iter().find(|s| s.setting == setting && s.http)
|
||||
}
|
||||
|
||||
/// `net:setting:` grants: the host is approved in Settings, materializes while
|
||||
/// the setting holds it, replaces and clears with it, and never asks at
|
||||
/// request time — a pending host stays denied without a dialog (#3809).
|
||||
#[test]
|
||||
fn net_setting_grants_approve_replace_and_clear_with_the_setting() {
|
||||
use ide_extension::ledger::{Ledger, Subject};
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("net-setting"));
|
||||
let subject = Subject::Installed("netsetting".into());
|
||||
let (port, seen) = http_server("relay ok", |_| Duration::ZERO);
|
||||
let url = format!("http://127.0.0.1:{port}/");
|
||||
|
||||
// Unset: denied exactly as today, unattended and attended, no dialog.
|
||||
let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err();
|
||||
assert!(err.contains("net:127.0.0.1") && err.contains("not granted"), "{err}");
|
||||
let err = f.host.run_command("netsetting", "fetch", Some(&url), Invocation::default()).unwrap_err();
|
||||
assert!(err.message.contains("not granted"), "{err:?}");
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
assert_eq!(seen.lock().len(), 0);
|
||||
|
||||
// Approved when the value is applied in Settings: the host materializes.
|
||||
set_setting(&f, "netsetting", &url);
|
||||
// The host the user was shown must still be the setting's value: a value
|
||||
// the plugin wrote after the dialog opened is not approved in its place.
|
||||
let err = f.host.approve_net_setting("netsetting", "server", false, "jira.corp.example").unwrap_err();
|
||||
assert!(err.message.contains("now holds 127.0.0.1"), "{err:?}");
|
||||
assert_eq!(net_setting_of(&f.host.info_of("netsetting").unwrap(), "server").unwrap().host, None);
|
||||
f.host.approve_net_setting("netsetting", "server", false, "127.0.0.1").unwrap();
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host.as_deref(), Some("127.0.0.1"));
|
||||
assert_eq!(entry.pending, None);
|
||||
assert_eq!(seen.lock().len(), 0);
|
||||
for invocation in [f.inv(), Invocation::default()] {
|
||||
let result = f.host.run_command("netsetting", "fetch", Some(&url), invocation).unwrap();
|
||||
assert_eq!(result.as_deref(), Some("relay ok"));
|
||||
}
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
assert_eq!(
|
||||
Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("127.0.0.1")
|
||||
);
|
||||
|
||||
// A value that changed anywhere else is not approved: pending, and a call
|
||||
// to it is denied without a dialog — unattended and from a window.
|
||||
set_setting(&f, "netsetting", "jira.corp.example");
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host, None);
|
||||
assert_eq!(entry.pending.as_deref(), Some("jira.corp.example"));
|
||||
let err = f.run("netsetting", "fetch", Some("http://jira.corp.example/")).unwrap_err();
|
||||
assert!(err.contains("not granted"), "{err}");
|
||||
let err = f
|
||||
.host
|
||||
.run_command("netsetting", "fetch", Some("http://jira.corp.example/"), Invocation::default())
|
||||
.unwrap_err();
|
||||
assert!(err.message.contains("not granted"), "{err:?}");
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
|
||||
// The old host no longer materializes either: it is not the setting's value.
|
||||
f.host.set_enabled("netsetting", false).unwrap();
|
||||
f.host.set_enabled("netsetting", true).unwrap();
|
||||
let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err();
|
||||
assert!(err.contains("not granted"), "{err}");
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
|
||||
// The Approve action replaces the approval only after the user confirms it.
|
||||
f.host.approve_net_setting("netsetting", "server", false, "jira.corp.example").unwrap();
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host.as_deref(), Some("jira.corp.example"));
|
||||
assert_eq!(entry.pending, None);
|
||||
assert_eq!(
|
||||
Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("jira.corp.example")
|
||||
);
|
||||
// And the old loopback host stays denied now.
|
||||
let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err();
|
||||
assert!(err.contains("not granted"), "{err}");
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
|
||||
// Revoking the manifest grant drops the record; granting it back asks for
|
||||
// a fresh approval.
|
||||
f.host.set_capability("netsetting", "net:setting:server", false).unwrap();
|
||||
assert!(Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.is_empty());
|
||||
f.host.set_capability("netsetting", "net:setting:server", true).unwrap();
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host, None);
|
||||
assert_eq!(entry.pending.as_deref(), Some("jira.corp.example"));
|
||||
|
||||
// Clearing the setting removes the grant.
|
||||
f.host.approve_net_setting("netsetting", "server", false, "jira.corp.example").unwrap();
|
||||
set_setting(&f, "netsetting", "");
|
||||
f.host.forget_net_setting("netsetting", "server", false).unwrap();
|
||||
assert!(Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.is_empty());
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host, None);
|
||||
assert_eq!(entry.pending, None);
|
||||
let err = f
|
||||
.host
|
||||
.run_command("netsetting", "fetch", Some("http://jira.corp.example/"), Invocation::default())
|
||||
.unwrap_err();
|
||||
assert!(err.message.contains("not granted"), "{err:?}");
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
}
|
||||
|
||||
/// `net.http:setting:` reaches plain HTTP on a non-loopback address; its
|
||||
/// record is kept per transport, next to the HTTPS one.
|
||||
#[test]
|
||||
fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("net-setting"));
|
||||
// 127.0.0.2 is this machine's loopback too, but not in the loopback list
|
||||
// of `net_capability`: its plain HTTP needs the `net.http:` grant.
|
||||
// macOS only configures 127.0.0.1 on lo0 by default.
|
||||
let Ok(listener) = std::net::TcpListener::bind("127.0.0.2:0") else {
|
||||
eprintln!("skipped: 127.0.0.2 is not bound to a loopback interface here");
|
||||
return;
|
||||
};
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let url = format!("http://127.0.0.2:{port}/");
|
||||
let seen: Arc<Mutex<Vec<String>>> = Arc::default();
|
||||
{
|
||||
let seen = seen.clone();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut writer = stream;
|
||||
let mut line = String::new();
|
||||
let mut len = 0;
|
||||
loop {
|
||||
let read = reader.read_line(&mut line).unwrap_or(0);
|
||||
if read == 0 || line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
|
||||
len = v.trim().parse().unwrap_or(0);
|
||||
}
|
||||
line.clear();
|
||||
}
|
||||
let mut req = vec![0; len];
|
||||
let _ = reader.read_exact(&mut req);
|
||||
let body = "plain ok";
|
||||
let _ = writer.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
seen.lock().push("served".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Plain HTTP elsewhere stays out of the ask flow entirely, unattended and attended.
|
||||
let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err();
|
||||
assert!(err.contains("net.http:127.0.0.2") && err.contains("not granted"), "{err}");
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
|
||||
// Approved for the `net.http:` transport only: the record is its own.
|
||||
set_setting(&f, "netsetting", &url);
|
||||
f.host.approve_net_setting("netsetting", "server", true, "127.0.0.2").unwrap();
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = http_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host.as_deref(), Some("127.0.0.2"));
|
||||
assert!(entry.http);
|
||||
// The HTTPS transport has no approval of its own: the setting's host is pending there.
|
||||
let https = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(https.host, None);
|
||||
assert_eq!(https.pending.as_deref(), Some("127.0.0.2"));
|
||||
for invocation in [f.inv(), Invocation::default()] {
|
||||
let result = f.host.run_command("netsetting", "fetch", Some(&url), invocation).unwrap();
|
||||
assert_eq!(result.as_deref(), Some("plain ok"));
|
||||
}
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
|
||||
// A `net:` grant for the same host would not cover plain HTTP; without the
|
||||
// `net.http:` approval the request stays denied (redirect rules unchanged).
|
||||
f.host.forget_net_setting("netsetting", "server", true).unwrap();
|
||||
let err = f.host.run_command("netsetting", "fetch", Some(&url), Invocation::default()).unwrap_err();
|
||||
assert!(err.message.contains("net.http:127.0.0.2") && err.message.contains("not granted"), "{err:?}");
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
}
|
||||
|
||||
/// On a remote host, a setting-derived approval is kept for the session only,
|
||||
/// like the `net:ask` answers (#3809).
|
||||
#[test]
|
||||
fn net_setting_approvals_are_session_only_on_remote_hosts() {
|
||||
use ide_extension::ledger::{Ledger, Subject};
|
||||
let f = fixture(Limits::default());
|
||||
f.host.set_net_hosts_session_only();
|
||||
f.install(&sample("net-setting"));
|
||||
let subject = Subject::Installed("netsetting".into());
|
||||
let (port, seen) = http_server("session ok", |_| Duration::ZERO);
|
||||
let url = format!("http://127.0.0.1:{port}/");
|
||||
|
||||
set_setting(&f, "netsetting", &url);
|
||||
f.host.approve_net_setting("netsetting", "server", false, "127.0.0.1").unwrap();
|
||||
for invocation in [f.inv(), Invocation::default()] {
|
||||
let result = f.host.run_command("netsetting", "fetch", Some(&url), invocation).unwrap();
|
||||
assert_eq!(result.as_deref(), Some("session ok"));
|
||||
}
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
assert!(Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.is_empty());
|
||||
|
||||
// Nothing was written: the approval dies with the session (disable/enable).
|
||||
f.host.set_enabled("netsetting", false).unwrap();
|
||||
f.host.set_enabled("netsetting", true).unwrap();
|
||||
let err = f.host.run_command("netsetting", "fetch", Some(&url), Invocation::default()).unwrap_err();
|
||||
assert!(err.message.contains("not granted"), "{err:?}");
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
}
|
||||
|
||||
/// A `net:setting:` grant must name a `string` setting in the plugin's own
|
||||
/// schema; checked at install like the other manifest checks (#3809).
|
||||
#[test]
|
||||
fn a_setting_grant_needs_a_string_setting_in_the_own_schema() {
|
||||
let f = fixture(Limits::default());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pkg = dir.path().join("net-setting-bad");
|
||||
copy_dir(&sample("net-setting"), &pkg);
|
||||
let manifest = pkg.join("plugin.toml");
|
||||
let text = std::fs::read_to_string(&manifest).unwrap();
|
||||
std::fs::write(&manifest, text.replace("net:setting:server", "net:setting:missing")).unwrap();
|
||||
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("`net:setting:missing`") && err.message.contains("string"), "{err:?}");
|
||||
|
||||
let pkg = dir.path().join("net-setting-number");
|
||||
copy_dir(&sample("net-setting"), &pkg);
|
||||
let schema = pkg.join("settings.json");
|
||||
let text = std::fs::read_to_string(&schema).unwrap();
|
||||
std::fs::write(
|
||||
&schema,
|
||||
text.replace(
|
||||
"\"type\":\"string\",\"title\":\"Server\",\"default\":\"\"",
|
||||
"\"type\":\"number\",\"title\":\"Server\",\"default\":0",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("net:setting:server") && err.message.contains("string"), "{err:?}");
|
||||
}
|
||||
|
||||
/// Runs api14's `fetch` in its window; once the `net:ask` question arrives,
|
||||
/// answers it (`None`: dismisses). Returns the command's result and the prompt.
|
||||
fn net_ask_run_and_answer(
|
||||
|
||||
@@ -52,6 +52,7 @@ fn arm(root: &Path, markers: &Path) -> Armed {
|
||||
git(root, &["config", key, value]);
|
||||
}
|
||||
std::fs::write(root.join("src/a.txt"), "one\ntwo\n").unwrap();
|
||||
std::fs::write(root.join("asset.jpg"), [0xff, 0xd8]).unwrap();
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-qm", "first"]);
|
||||
let first = git(root, &["rev-parse", "HEAD"]);
|
||||
@@ -168,6 +169,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
|
||||
call!("vcs_line_hunks", "", vcs::vcs_line_hunks(host, w, file.clone())),
|
||||
call!("vcs_staging_line_hunks", "", vcs::vcs_staging_line_hunks(host, w, file.clone(), None)),
|
||||
call!("vcs_file_at", "", vcs::vcs_file_at(host, w, file.clone(), None)),
|
||||
call!("vcs_image_at", "", vcs::vcs_image_at(host, w, project.root.join("asset.jpg"), ":0".into())),
|
||||
call!(
|
||||
"vcs_diff_entries",
|
||||
"",
|
||||
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "id-arena"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "macro-string"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin-netsetting"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"openidea-plugin",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-metadata"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"indexmap",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"hashbrown",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"wit-bindgen-rust-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-core"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"indexmap",
|
||||
"prettyplease",
|
||||
"syn",
|
||||
"wasm-metadata",
|
||||
"wit-bindgen-core",
|
||||
"wit-component",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust-macro"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"macro-string",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wit-bindgen-core",
|
||||
"wit-bindgen-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-component"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
"indexmap",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"wasm-encoder",
|
||||
"wasm-metadata",
|
||||
"wasmparser",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-parser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"hashbrown",
|
||||
"id-arena",
|
||||
"indexmap",
|
||||
"log",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"unicode-ident",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "openidea-plugin-netsetting"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" }
|
||||
serde_json = "1"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
Бінарний файл не відображається.
@@ -0,0 +1 @@
|
||||
04c8f881e25aae1b7298f554f3c4ab38251eec48e8d88656d73cad019eb1644c
|
||||
@@ -0,0 +1,17 @@
|
||||
id = "netsetting"
|
||||
name = "Setting-derived network grants"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.18"
|
||||
wasm = "dist/plugin.wasm"
|
||||
activation = ["on-command:*"]
|
||||
|
||||
[capabilities]
|
||||
required = ["storage"]
|
||||
optional = ["net:setting:server", "net.http:setting:server"]
|
||||
|
||||
[contributes.settings]
|
||||
schema = "settings.json"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "fetch"
|
||||
title = "fetch"
|
||||
@@ -0,0 +1 @@
|
||||
{"properties":{"server":{"type":"string","title":"Server","default":""}}}
|
||||
@@ -0,0 +1,178 @@
|
||||
use openidea_plugin::{Error, Event, Invocation, Plugin, StatusItem, StatusMenuEntry, host, register_plugin};
|
||||
#[derive(Default)]
|
||||
struct Api14;
|
||||
impl Plugin for Api14 {
|
||||
fn run_command(&mut self, id: &str, ctx: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
|
||||
let arg = arg.unwrap_or_default();
|
||||
match id {
|
||||
"open-editors" => Ok(Some(format!("{:?}", host::open_editors()?))),
|
||||
"open-editor" => {
|
||||
host::open_editor(arg, Some(openidea_plugin::Range::default()))?;
|
||||
Ok(None)
|
||||
}
|
||||
"set-selections" => {
|
||||
ctx.editor().unwrap().set_selections(&[openidea_plugin::Range::default()])?;
|
||||
Ok(None)
|
||||
}
|
||||
"reveal" => {
|
||||
ctx.editor().unwrap().reveal(openidea_plugin::Range::default())?;
|
||||
Ok(None)
|
||||
}
|
||||
"search-text" => {
|
||||
let result = ctx
|
||||
.project()
|
||||
.unwrap()
|
||||
.search_text(&openidea_plugin::TextQuery { pattern: arg.into(), ..Default::default() }, 10)?;
|
||||
Ok(Some(format!("{result:?}")))
|
||||
}
|
||||
"read-bytes" => Ok(Some(format!("{:?}", ctx.project().unwrap().read_bytes(arg)?))),
|
||||
"problems" => Ok(Some(format!("{:?}", host::problems(if arg.is_empty() { None } else { Some(arg) })?))),
|
||||
"decorations" => {
|
||||
host::set_decorations(
|
||||
arg,
|
||||
"test",
|
||||
&[openidea_plugin::Decoration {
|
||||
range: openidea_plugin::Range::default(),
|
||||
style: "highlight".into(),
|
||||
hover: Some("hover".into()),
|
||||
after: Some("after".into()),
|
||||
}],
|
||||
)?;
|
||||
Ok(None)
|
||||
}
|
||||
"clear-decorations" => {
|
||||
host::clear_decorations("test")?;
|
||||
Ok(None)
|
||||
}
|
||||
"file-decoration" => {
|
||||
host::set_file_decoration(
|
||||
arg,
|
||||
"test",
|
||||
&openidea_plugin::FileDecoration { badge: Some("OK".into()), style: "added".into(), tooltip: None },
|
||||
)?;
|
||||
Ok(None)
|
||||
}
|
||||
"clear-file-decorations" => {
|
||||
host::clear_file_decorations("test")?;
|
||||
Ok(None)
|
||||
}
|
||||
"vcs-log" => Ok(Some(format!(
|
||||
"{:?}",
|
||||
ctx.project().unwrap().vcs_log(if arg.is_empty() { None } else { Some(arg) }, 10)?
|
||||
))),
|
||||
"vcs-blame" => Ok(Some(format!("{:?}", ctx.project().unwrap().vcs_blame(arg)?))),
|
||||
"vcs-diff" => ctx.project().unwrap().vcs_diff(if arg.is_empty() { None } else { Some(arg) }, None),
|
||||
"ipc" => {
|
||||
let stream = host::ipc_connect(arg)?;
|
||||
stream.write(b"echo")?;
|
||||
let bytes = stream.read(4, 2000)?;
|
||||
stream.close()?;
|
||||
Ok(Some(String::from_utf8_lossy(&bytes).into()))
|
||||
}
|
||||
"fetch" => {
|
||||
let response = host::fetch(&openidea_plugin::HttpRequest::get(arg))?;
|
||||
Ok(Some(String::from_utf8_lossy(&response.body).into()))
|
||||
}
|
||||
"global-status" | "window-status" => {
|
||||
let item = StatusItem { text: arg.into(), tooltip: None, command: Some("events".into()) };
|
||||
if id == "global-status" {
|
||||
host::set_status_item("state", &item);
|
||||
} else {
|
||||
host::set_window_status_item("state", &item)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
"menu-status" | "bad-menu-status" => {
|
||||
let item = StatusItem { text: arg.into(), tooltip: None, command: None };
|
||||
let command = if id == "menu-status" { "events" } else { "undeclared" };
|
||||
let menu = [
|
||||
StatusMenuEntry::Header("App".into()),
|
||||
StatusMenuEntry::action("Open", command).with_description("https://app.test").with_argument("web"),
|
||||
StatusMenuEntry::Separator,
|
||||
];
|
||||
host::set_status_item_menu("menu", &item, &menu)?;
|
||||
Ok(None)
|
||||
}
|
||||
"remove-window-status" => {
|
||||
host::remove_window_status_item("state")?;
|
||||
Ok(None)
|
||||
}
|
||||
"execute" => host::execute_command(arg, Some("argument")),
|
||||
"oauth" => {
|
||||
let redirect = host::begin_loopback("oauth/callback")?;
|
||||
host::output_append("oauth", &redirect.redirect_uri())?;
|
||||
redirect.wait(2000)
|
||||
}
|
||||
"secret" => {
|
||||
host::secret_set("token", arg)?;
|
||||
Ok(None)
|
||||
}
|
||||
"delete-secret" => {
|
||||
host::secret_delete("token")?;
|
||||
Ok(None)
|
||||
}
|
||||
"undeclared-secret" => {
|
||||
host::secret_set("undeclared", arg)?;
|
||||
Ok(None)
|
||||
}
|
||||
"output" => {
|
||||
host::output_append("test", arg)?;
|
||||
host::output_reveal("test")?;
|
||||
Ok(None)
|
||||
}
|
||||
"process-run" => Ok(Some(host::run_process("api14-tool", &[], None)?.stdout)),
|
||||
"process-run-command" => Ok(Some(host::run_command(&host::Command::new("api14-tool"), None, None)?.stdout)),
|
||||
"process-start" => {
|
||||
let child = host::start(&host::Command::new("api14-tool"), None)?;
|
||||
Ok(Some(child.wait(2000)?.stdout))
|
||||
}
|
||||
"terminal" => {
|
||||
host::open_terminal("API test", "api14-tool", &[])?;
|
||||
Ok(None)
|
||||
}
|
||||
"log" => {
|
||||
host::open_log_tab(
|
||||
"api-test",
|
||||
"API test",
|
||||
&openidea_plugin::details::ProcessLog {
|
||||
program: "api14-tool".into(),
|
||||
args: Vec::new(),
|
||||
toggles: Vec::new(),
|
||||
},
|
||||
)?;
|
||||
Ok(None)
|
||||
}
|
||||
"events" => host::storage::get("events"),
|
||||
_ => Err(Error::NotFound(id.into())),
|
||||
}
|
||||
}
|
||||
fn handle_events(&mut self, events: &[Event], ctx: &Invocation) {
|
||||
let mut received: Vec<serde_json::Value> =
|
||||
host::storage::get("events").unwrap().map(|s| serde_json::from_str(&s).unwrap()).unwrap_or_default();
|
||||
for event in events {
|
||||
if let Event::Other { kind, data } = event {
|
||||
let editor = ctx.editor().map(|e| {
|
||||
(
|
||||
e.path(),
|
||||
e.selections()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|r| [r.start.line, r.start.character, r.end.line, r.end.character])
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
});
|
||||
received.push(serde_json::json!({ "kind": kind, "data": data, "editor": editor }));
|
||||
}
|
||||
}
|
||||
host::storage::set("events", &serde_json::to_string(&received).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
impl openidea_plugin::TestResults for Api14 {
|
||||
fn parse(&mut self, _config: &str, _chunk: &str) -> Vec<openidea_plugin::PluginTestEvent> {
|
||||
vec![]
|
||||
}
|
||||
fn select_tests(&mut self, config: &str, tests: &[Vec<String>]) -> Option<Vec<String>> {
|
||||
(config == "tests").then(|| tests.iter().map(|p| p.join("::")).collect())
|
||||
}
|
||||
}
|
||||
register_plugin!(Api14, test_results);
|
||||
@@ -8,6 +8,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
ide-language.workspace = true
|
||||
ide-workspace.workspace = true
|
||||
dunce.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -84,11 +84,16 @@ pub(crate) fn detect_with_profiles(
|
||||
}
|
||||
}
|
||||
detect_projects(root, &["build.zig"], zig::detect, &mut out);
|
||||
dotnet::detect(root, &mut out);
|
||||
// A UE project's `.sln` lists the engine's own tool projects; expanding it would bury the
|
||||
// run menu under dozens of `.NET Project` entries that cannot run from here.
|
||||
if !ide_workspace::unreal::is_project(root) {
|
||||
dotnet::detect(root, &mut out);
|
||||
}
|
||||
detect_projects(root, &["Makefile", "makefile", "GNUmakefile"], detect_make, &mut out);
|
||||
detect_projects(root, &["justfile", "Justfile", ".justfile"], detect_just, &mut out);
|
||||
detect_godot(root, &mut out);
|
||||
detect_projects(root, &["pubspec.yaml"], detect_flutter, &mut out);
|
||||
detect_unreal(root, &mut out);
|
||||
crate::external::detect(root, &mut out);
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
@@ -1608,6 +1613,49 @@ pub(crate) fn just_recipes(src: &str) -> Vec<String> {
|
||||
|
||||
// ---------------------------------------------------------------- godot
|
||||
|
||||
// ---------------------------------------------------------------- unreal
|
||||
|
||||
/// Unreal Engine projects (`.uproject`) run through the engine's editor executable, which reads
|
||||
/// its start-up mode from the command line: no flag is the editor, `-game` the game and `-server`
|
||||
/// a dedicated server. All three exist for every project, blueprint-only ones included, because
|
||||
/// the mode is decided at start-up rather than built.
|
||||
fn detect_unreal(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
detect_projects_matching(root, |dir| ide_workspace::unreal::project_file(dir).is_some(), detect_one_unreal, out);
|
||||
}
|
||||
|
||||
/// One Unreal project: the editor, the game and a dedicated server, all run by the same
|
||||
/// `UnrealEditor.exe` and differing only in the flag.
|
||||
fn detect_one_unreal(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let Some(info) = ide_workspace::unreal::detect(root) else { return };
|
||||
// Detection already resolved the engine; a project without one offers nothing to run.
|
||||
let Some(found) = info.engine.as_ref() else {
|
||||
tracing::debug!("no Unreal Engine installation for {}", root.display());
|
||||
return;
|
||||
};
|
||||
let engine =
|
||||
ide_workspace::unreal::engine::EngineInstall { id: found.id.clone(), root: PathBuf::from(&found.root) };
|
||||
let Some(project) = ide_workspace::unreal::project_file(root) else { return };
|
||||
let editor = engine.editor().to_string_lossy().into_owned();
|
||||
out.extend(unreal_configs(&project, &editor));
|
||||
}
|
||||
|
||||
/// The editor, the game and a dedicated server: the three start-up modes the engine documents,
|
||||
/// all run by `UnrealEditor.exe` and differing only in the flag.
|
||||
fn unreal_configs(project: &Path, editor: &str) -> Vec<RunConfig> {
|
||||
let project = project.to_string_lossy().into_owned();
|
||||
[
|
||||
("unreal:editor", "Unreal Editor", None),
|
||||
("unreal:game", "Unreal Game", Some("-game")),
|
||||
("unreal:server", "Unreal Server", Some("-server")),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(id, name, flag)| {
|
||||
let args: Vec<&str> = std::iter::once(project.as_str()).chain(flag).collect();
|
||||
config(id.to_owned(), name, "unreal", editor, &args).debug("lldb-dap")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rebar3 / mix
|
||||
|
||||
/// rebar3 (Erlang): the shell with the applications started, the EUnit tests and, with
|
||||
@@ -1690,3 +1738,23 @@ fn detect_just(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_unreal_project_offers_the_editor_the_game_and_a_dedicated_server() {
|
||||
let configs = unreal_configs(Path::new("/p/Game.uproject"), "UE/UnrealEditor.exe");
|
||||
let listed: Vec<(&str, &str)> = configs.iter().map(|c| (c.id.as_str(), c.name.as_str())).collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[("unreal:editor", "Unreal Editor"), ("unreal:game", "Unreal Game"), ("unreal:server", "Unreal Server"),]
|
||||
);
|
||||
assert_eq!(configs[0].args, ["/p/Game.uproject"]);
|
||||
assert_eq!(configs[1].args, ["/p/Game.uproject", "-game"]);
|
||||
assert_eq!(configs[2].args, ["/p/Game.uproject", "-server"]);
|
||||
assert!(configs.iter().all(|c| c.command == "UE/UnrealEditor.exe" && c.cwd.is_none()));
|
||||
assert!(configs.iter().all(|c| c.debug_adapter.as_deref() == Some("lldb-dap") && c.kind == "unreal"));
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,15 @@ pub(crate) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
if !name.starts_with('.')
|
||||
// Case-insensitive: Unreal's generated trees (`Binaries`, `Intermediate`, …) hold
|
||||
// tens of thousands of files and copies of the engine's own tool projects.
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if !lower.starts_with('.')
|
||||
&& !matches!(
|
||||
name.as_str(),
|
||||
lower.as_str(),
|
||||
"bin" | "obj" | "node_modules" | "target" | "build" | "dist" | "vendor" | "packages"
|
||||
)
|
||||
&& !ide_workspace::unreal::GENERATED_DIRS.iter().any(|dir| dir.eq_ignore_ascii_case(&lower))
|
||||
{
|
||||
dirs.push(path);
|
||||
}
|
||||
|
||||
@@ -1417,3 +1417,40 @@ fn sbt_projects() {
|
||||
assert_eq!(cmdline(&detect(dir.path())[1]), "./sbt test");
|
||||
}
|
||||
}
|
||||
|
||||
/// UE writes a `.sln` listing the engine's own tool projects; expanding it buries the run menu.
|
||||
#[test]
|
||||
fn a_solution_in_a_unreal_project_is_not_expanded_into_dotnet_configurations() {
|
||||
let dir = project(&[
|
||||
("Game.uproject", r#"{"FileVersion":3,"EngineAssociation":"5.8"}"#),
|
||||
(
|
||||
"Game.sln",
|
||||
r#"Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Game", "Source\Game\Game.csproj", "{00000000-0000-0000-0000-000000000000}"
|
||||
EndProject
|
||||
"#,
|
||||
),
|
||||
(
|
||||
"Source/Game/Game.csproj",
|
||||
r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType></PropertyGroup></Project>"#,
|
||||
),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
assert!(c.iter().all(|c| !c.kind.starts_with("dotnet")), "{:?}", ids(&c));
|
||||
}
|
||||
|
||||
/// The engine keeps copies of its tool projects under the generated trees, which hold no code
|
||||
/// anyone runs from here — and on a real project they are deep enough to slow detection down.
|
||||
#[test]
|
||||
fn csproj_under_unreal_generated_directories_is_not_detected() {
|
||||
let exe =
|
||||
r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType></PropertyGroup></Project>"#;
|
||||
let dir = project(&[
|
||||
("Intermediate/ProjectFiles/UnrealBuildTool/UnrealBuildTool.csproj", exe),
|
||||
("Binaries/Win64/ShaderCopy/ShaderCopy.csproj", exe),
|
||||
("Saved/Tools/Helper/Helper.csproj", exe),
|
||||
("DerivedDataCache/Worker/Worker.csproj", exe),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
assert!(c.is_empty(), "{:?}", ids(&c));
|
||||
}
|
||||
@@ -905,7 +905,7 @@ pub fn native_tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
const PYTHON_SERVERS: [&str; 8] =
|
||||
["basedpyright", "pyright", "ty", "pyrefly", "pylsp", "jedi-language-server", "ruff", "djlsp"];
|
||||
|
||||
pub(crate) fn merge(base: &mut Value, layer: Value) {
|
||||
pub fn merge(base: &mut Value, layer: Value) {
|
||||
match (base, layer) {
|
||||
(Value::Object(base), Value::Object(layer)) => {
|
||||
for (k, v) in layer {
|
||||
|
||||
@@ -288,6 +288,13 @@ pub(crate) fn outgoing_commits(
|
||||
) -> Option<OutgoingCommits> {
|
||||
let name = source.shorten().to_str_lossy();
|
||||
let remote = repo.find_remote(default_push_remote(repo, remotes, Some(&name))?).ok()?;
|
||||
// As in IDEA, only a destination the branch is set up with: its upstream or a push refspec.
|
||||
// The remote branch of the same name is only what Push proposes for a new branch.
|
||||
if repo.branch_remote_ref_name(source, gix::remote::Direction::Fetch).is_none()
|
||||
&& configured_destination(repo, source, &name, remote.refspecs(gix::remote::Direction::Push)).is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let target = branch_push_target(repo, source, &remote).ok()?.selection;
|
||||
if target.special_ref {
|
||||
return None;
|
||||
|
||||
@@ -162,6 +162,29 @@ impl Repo {
|
||||
blob_at(&repo, &indexed, rev)
|
||||
}
|
||||
|
||||
/// Raw bytes of the selected commit or index entry, bounded before loading its blob.
|
||||
pub fn file_bytes_at_bounded(&self, path: &Path, rev: &str, max: usize) -> IdeResult<Option<Vec<u8>>> {
|
||||
let _scope = self.execution_scope();
|
||||
let repo = self.gix()?;
|
||||
let given = self.given_rel_path(path)?;
|
||||
let indexed = self.index_spelling(given.clone());
|
||||
let Some((mode, id)) = revision_entry(&repo, &given, &indexed, rev)? else { return Ok(None) };
|
||||
if !mode.is_blob_or_symlink() {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(header) = repo.try_find_header(id).map_err(gx)? {
|
||||
if header.size() > max as u64 {
|
||||
return Err(IdeError::invalid(format!("{} is too large to preview", path.display())));
|
||||
}
|
||||
return Ok(Some(repo.find_object(id).map_err(gx)?.detach().data));
|
||||
}
|
||||
// A partial clone may only have the tree. Keep Git's on-demand fetch under
|
||||
// the repository's execution policy and cap the bytes captured from it.
|
||||
let args = ["cat-file", "blob", &id.to_string()];
|
||||
let out = crate::cli::run_bounded(self.root(), &args, &ide_core::CancellationToken::new(), max)?;
|
||||
Ok(Some(out.stdout))
|
||||
}
|
||||
|
||||
pub fn diff_entry_at(&self, path: &Path, rev: &str) -> IdeResult<Option<DiffEntry>> {
|
||||
let _scope = self.execution_scope();
|
||||
let repo = self.gix()?;
|
||||
@@ -183,14 +206,7 @@ impl Repo {
|
||||
.and_then(|child| child.head().ok()?.1);
|
||||
return Ok(Some(DiffEntry { mode: "160000".into(), gitlink }));
|
||||
}
|
||||
let entry = if !rev.starts_with(':') && indexed != given {
|
||||
match entry_at(&repo, &given, rev)? {
|
||||
Some(entry) => Some(entry),
|
||||
None => entry_at(&repo, &indexed, rev)?,
|
||||
}
|
||||
} else {
|
||||
entry_at(&repo, &indexed, rev)?
|
||||
};
|
||||
let entry = revision_entry(&repo, &given, &indexed, rev)?;
|
||||
Ok(entry.map(|(mode, id)| DiffEntry {
|
||||
mode: format!("{:o}", mode.value()),
|
||||
gitlink: mode.is_commit().then(|| id.to_string()),
|
||||
@@ -334,6 +350,22 @@ pub(crate) fn mode_at(repo: &gix::Repository, rel: &str, rev: &str) -> IdeResult
|
||||
Ok(entry_at(repo, rel, rev)?.map(|(mode, _)| format!("{:o}", mode.value())))
|
||||
}
|
||||
|
||||
/// Prefer the spelling in the revision to a later case-only rename in the index.
|
||||
fn revision_entry(
|
||||
repo: &gix::Repository,
|
||||
given: &str,
|
||||
indexed: &str,
|
||||
rev: &str,
|
||||
) -> IdeResult<Option<(gix::objs::tree::EntryMode, gix::ObjectId)>> {
|
||||
if !rev.starts_with(':')
|
||||
&& indexed != given
|
||||
&& let Some(entry) = entry_at(repo, given, rev)?
|
||||
{
|
||||
return Ok(Some(entry));
|
||||
}
|
||||
entry_at(repo, indexed, rev)
|
||||
}
|
||||
|
||||
fn entry_at(
|
||||
repo: &gix::Repository,
|
||||
rel: &str,
|
||||
|
||||
@@ -1808,6 +1808,37 @@ fn outgoing_commits_follow_the_push_target_and_its_fetch_refspec() {
|
||||
assert!(repo.inspect_push(&selection, false, &cancel).unwrap().remote_tip.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_commits_need_an_upstream_or_a_push_refspec() {
|
||||
// A new branch reuses the name of an old one still on the server.
|
||||
let (fx, _) = Fixture::with_origin();
|
||||
fx.git(&["switch", "-q", "-c", "topic"]);
|
||||
fx.write("b.txt", "old topic\n");
|
||||
fx.commit_all("Old topic");
|
||||
fx.git(&["push", "-q", "origin", "topic"]);
|
||||
fx.git(&["switch", "-q", "main"]);
|
||||
fx.git(&["branch", "-q", "-D", "topic"]);
|
||||
fx.write("c.txt", "main\n");
|
||||
fx.commit_all("Main moves on");
|
||||
fx.git(&["push", "-q", "origin", "main"]);
|
||||
fx.git(&["switch", "-q", "--no-track", "-c", "topic", "origin/main"]);
|
||||
let repo = fx.repo();
|
||||
|
||||
let info = repo.branch_info().unwrap();
|
||||
assert!(info.upstream.is_none());
|
||||
assert!(info.outgoing.is_none());
|
||||
assert!(repo.branches().unwrap().iter().find(|b| b.current).unwrap().outgoing.is_none());
|
||||
// Push still proposes the remote branch of the same name.
|
||||
let selection = repo.default_push_target(None).unwrap().unwrap().selection;
|
||||
assert_eq!((&*selection.remote, &*selection.target), ("origin", "topic"));
|
||||
|
||||
fx.git(&["config", "remote.origin.push", "refs/heads/topic:refs/heads/topic"]);
|
||||
assert_eq!(repo.branch_info().unwrap().outgoing.map(|o| o.count), Some(1));
|
||||
fx.git(&["config", "--unset", "remote.origin.push"]);
|
||||
fx.git(&["branch", "-q", "--set-upstream-to=origin/topic"]);
|
||||
assert_eq!(repo.branch_info().unwrap().outgoing.map(|o| o.count), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_up_to_commit_prefers_a_containing_local_branch_and_only_publishes_the_selection() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
|
||||
@@ -963,6 +963,21 @@ fn file_at_revisions_and_index() {
|
||||
assert_eq!(repo.file_at(&p, Some("no-such-rev"), encoding_rs::UTF_8).unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_revision_bytes_check_the_selected_blob_size() {
|
||||
let fx = Fixture::new();
|
||||
let path = fx.path("image.png");
|
||||
std::fs::write(&path, [0xff, 0x00, 0xfe]).unwrap();
|
||||
fx.commit_all("image");
|
||||
std::fs::write(&path, [0x80]).unwrap();
|
||||
fx.git(&["add", "image.png"]);
|
||||
let repo = fx.repo();
|
||||
assert_eq!(repo.file_bytes_at_bounded(&path, "HEAD", 3).unwrap().unwrap(), [0xff, 0x00, 0xfe]);
|
||||
assert_eq!(repo.file_bytes_at_bounded(&path, ":0", 1).unwrap().unwrap(), [0x80]);
|
||||
assert_eq!(repo.file_bytes_at_bounded(&path, "HEAD", 2).unwrap_err().kind, ErrorKind::InvalidInput);
|
||||
assert_eq!(repo.file_bytes_at_bounded(&fx.path("absent.png"), "HEAD", 0).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_at_in_a_blobless_clone() {
|
||||
let fx = Fixture::new();
|
||||
|
||||
@@ -24,8 +24,8 @@ pub use archive::{
|
||||
read_archive_entry, split_archive_path,
|
||||
};
|
||||
pub use bytes::{
|
||||
ByteRange, FileProbe, MAX_RANGE_LEN, base64, content_path_allowed, image_mime, on_local_drive, probe,
|
||||
read_data_url, read_range, same_share,
|
||||
ByteRange, FileProbe, MAX_IMAGE_SIZE, MAX_RANGE_LEN, base64, content_path_allowed, image_mime, on_local_drive,
|
||||
probe, read_data_url, read_range, same_share,
|
||||
};
|
||||
pub use compare::{
|
||||
DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction,
|
||||
|
||||
@@ -25,5 +25,8 @@ uuid.workspace = true
|
||||
zip.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.56"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -260,6 +260,13 @@ impl EditorConfig {
|
||||
|
||||
/// Effective properties for `file` (absolute); `None` when no section applies.
|
||||
pub fn resolve(&self, file: &Path) -> Option<EditorConfigProps> {
|
||||
let props = props_from(&self.resolve_pairs(file)?);
|
||||
(!props.is_empty()).then_some(props)
|
||||
}
|
||||
|
||||
/// Every `key = value` that applies to `file` (keys lower-cased), domain-specific ones
|
||||
/// (`quote_type`, `ij_*`) included; `None` when no section applies.
|
||||
pub fn resolve_pairs(&self, file: &Path) -> Option<HashMap<String, String>> {
|
||||
let mut chain: Vec<(PathBuf, Arc<ParsedFile>)> = Vec::new();
|
||||
for dir in file.ancestors().skip(1) {
|
||||
if let Some(parsed) = self.load(&dir.join(FILE_NAME)) {
|
||||
@@ -286,11 +293,7 @@ impl EditorConfig {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return None;
|
||||
}
|
||||
let props = props_from(&map);
|
||||
(!props.is_empty()).then_some(props)
|
||||
matched.then_some(map)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod roots;
|
||||
pub mod settings;
|
||||
pub mod text_refs;
|
||||
pub mod unity;
|
||||
pub mod unreal;
|
||||
pub mod window_groups;
|
||||
pub mod workspace;
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Unreal Engine project identity, read from the `.uproject` at the root.
|
||||
//!
|
||||
//! Only the root and the engine tree are looked at: everything else in a UE project is
|
||||
//! content, generated output, or engine code, and must never be walked.
|
||||
|
||||
pub mod engine;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Generated directory beside the project root; excluded from the index, the search and the tree.
|
||||
pub const GENERATED_DIRS: &[&str] = &["Binaries", "Intermediate", "Saved", "DerivedDataCache"];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UnrealProjectInfo {
|
||||
/// The engine the project builds against. `None` means none could be located, which is the
|
||||
/// only reason such a project offers no run configuration at all.
|
||||
pub engine: Option<UnrealEngine>,
|
||||
}
|
||||
|
||||
/// A located engine, shown so a project without run configurations says why.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UnrealEngine {
|
||||
/// `5.8` for a launcher install, or the registry key a source build registered under.
|
||||
pub id: String,
|
||||
/// Absolute engine root.
|
||||
pub root: String,
|
||||
}
|
||||
|
||||
/// The `.uproject` directly inside `root`, picked by name order when a folder has several.
|
||||
pub fn project_file(root: &Path) -> Option<PathBuf> {
|
||||
let mut found: Vec<PathBuf> = std::fs::read_dir(root)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("uproject")))
|
||||
.collect();
|
||||
found.sort();
|
||||
found.into_iter().next()
|
||||
}
|
||||
|
||||
pub fn is_project(root: &Path) -> bool {
|
||||
project_file(root).is_some()
|
||||
}
|
||||
|
||||
pub fn detect(root: &Path) -> Option<UnrealProjectInfo> {
|
||||
let file = project_file(root)?;
|
||||
let association = std::fs::read_to_string(&file)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
|
||||
.and_then(|json| json.get("EngineAssociation")?.as_str().map(|v| v.trim().to_owned()))
|
||||
.filter(|v| !v.is_empty());
|
||||
let engine = engine::locate(association.as_deref())
|
||||
.map(|found| UnrealEngine { id: found.id, root: found.root.to_string_lossy().into_owned() });
|
||||
Some(UnrealProjectInfo { engine })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_holding_a_uproject_is_a_project() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
write(&root.join("Arts.uproject"), r#"{"FileVersion":3,"EngineAssociation":"5.8","Plugins":[]}"#);
|
||||
std::fs::create_dir_all(root.join("Content")).unwrap();
|
||||
assert!(is_project(root));
|
||||
assert!(detect(root).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_without_a_uproject_is_not_a_project() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
write(&temp.path().join("Source/Game.Target.cs"), "");
|
||||
assert!(!is_project(temp.path()));
|
||||
assert!(detect(temp.path()).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Locating an installed Unreal Engine.
|
||||
//!
|
||||
//! A launcher install registers its directory per version under `HKLM` and a source build under
|
||||
//! `HKCU`, keyed by whatever the `.uproject`'s `EngineAssociation` names.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A registered engine, keyed by whatever the machine calls it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EngineInstall {
|
||||
/// `5.8` for a launcher install, a GUID-like key for a source build.
|
||||
pub id: String,
|
||||
pub root: PathBuf,
|
||||
}
|
||||
|
||||
impl EngineInstall {
|
||||
/// The editor executable, which runs every start-up mode.
|
||||
pub fn editor(&self) -> PathBuf {
|
||||
self.root.join("Engine").join("Binaries").join("Win64").join("UnrealEditor.exe")
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine `association` names, following Unreal's own lookup: the association is the key a
|
||||
/// registered directory is stored under, so an unknown or empty one locates nothing.
|
||||
pub fn locate(association: Option<&str>) -> Option<EngineInstall> {
|
||||
pick(installed(), association)
|
||||
}
|
||||
|
||||
fn pick(installs: Vec<EngineInstall>, association: Option<&str>) -> Option<EngineInstall> {
|
||||
let id = association?;
|
||||
// A registered directory that is gone is a leftover from an uninstalled engine.
|
||||
installs.into_iter().find(|i| i.id.eq_ignore_ascii_case(id) && i.root.is_dir())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn installed() -> Vec<EngineInstall> {
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
|
||||
|
||||
let mut out = Vec::new();
|
||||
if let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(r"SOFTWARE\EpicGames\Unreal Engine") {
|
||||
for id in key.enum_keys().flatten() {
|
||||
let Ok(sub) = key.open_subkey(&id) else { continue };
|
||||
let Ok(dir) = sub.get_value::<String, _>("InstalledDirectory") else { continue };
|
||||
if !dir.trim().is_empty() {
|
||||
out.push(EngineInstall { id, root: PathBuf::from(dir) });
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(key) = RegKey::predef(HKEY_CURRENT_USER).open_subkey(r"SOFTWARE\Epic Games\Unreal Engine\Builds") {
|
||||
for (id, _) in key.enum_values().flatten() {
|
||||
let Ok(dir) = key.get_value::<String, _>(&id) else { continue };
|
||||
if !dir.trim().is_empty() {
|
||||
out.push(EngineInstall { id, root: PathBuf::from(dir) });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn installed() -> Vec<EngineInstall> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A fake install whose directory exists, so `pick` treats it as usable.
|
||||
fn install(dir: &std::path::Path, id: &str) -> EngineInstall {
|
||||
let root = dir.join(format!("UE_{id}"));
|
||||
std::fs::create_dir_all(root.join("Engine/Binaries/Win64")).unwrap();
|
||||
EngineInstall { id: id.to_owned(), root }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_association_picks_that_install_and_nothing_else() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let installs = vec![install(temp.path(), "5.8"), install(temp.path(), "5.3")];
|
||||
assert_eq!(pick(installs.clone(), Some("5.3")).unwrap().id, "5.3");
|
||||
assert_eq!(pick(installs, Some("4.27")), None);
|
||||
assert_eq!(pick(Vec::new(), None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_registered_engine_that_was_deleted_is_not_picked() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let ghost = EngineInstall { id: "5.8".to_owned(), root: temp.path().join("gone") };
|
||||
assert_eq!(pick(vec![ghost], Some("5.8")), None);
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,8 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
|
||||
|
||||
**Move Caret Forward a Paragraph** / **Backward a Paragraph** jump each caret over a run of non-blank lines to the blank line after or before it (a line of only spaces or tabs counts as blank), or to the end or start of the file; their **with Selection** variants select up to there. They have no default shortcut.
|
||||
|
||||
**Move Caret to Next Word** / **Previous Word in Different "CamelHumps" Mode** (and their **with Selection** variants), **Delete to Word Start** and **Delete to Word End in Different "CamelHumps" Mode** move or delete by word the other way from **Settings › Editor › General › Smart Keys › Use "CamelHumps" words**: by hump (`parse|HTML|Document`) while it is off, by whole word while it is on. They have no default shortcut.
|
||||
|
||||
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
|
||||
|
||||
**Cut up to Line End** cuts from each caret to the end of its line, together with the line break when only whitespace is left (or the caret is already at the line end), so pressing it again on the same caret cuts the next line too; those repeated cuts collect into one clipboard entry. **Delete to Line Start** and **Delete to Line End** delete the same way without copying (to the line start, or the line break before the caret at the line start), or delete the selection. They have no default shortcut except in the Eclipse keymaps (`⇧⌘⌦` / `Ctrl+Shift+Delete` for Delete to Line End).
|
||||
@@ -158,6 +160,7 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
|
||||
- **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**.
|
||||
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
|
||||
- **View › Appearance › Enter Distraction Free Mode** hides tool windows, tabs, the status bar and the gutter and centres the text. Run the same command again to leave.
|
||||
- **View › Appearance › Enter Zen Mode** turns on Distraction Free Mode and full screen together; **Exit Zen Mode** turns both off.
|
||||
- **Show Line Numbers**, **Show Indent Guides**, **Show Sticky Lines** and **Show Whitespaces** turn these on or off in every editor. Run them from Find Action, or right-click the gutter and open **Appearance**.
|
||||
- Line numbers, whitespace, indent guides, caret style and the intention bulb are in **Settings › Editor › General › Appearance**. Breadcrumbs and sticky lines (the enclosing declarations pinned at the top while you scroll) have their own pages under **Settings › Editor › General**.
|
||||
|
||||
|
||||
@@ -83,6 +83,12 @@ The Astro and Angular servers also run from the project's own `node_modules/.bin
|
||||
|
||||
On these pages, **Formatting provider** chooses between **Automatic (language server first)** and the tool itself, **Run on save** formats on save, and **Enabled languages** limits which languages the tool handles.
|
||||
|
||||
With **Automatic**, a JavaScript or TypeScript file below the tool's own configuration (a Prettier configuration file or `prettier` key in `package.json`, an oxfmt configuration, or Biome's) is formatted by that tool rather than by the language server, once the tool is installed (before `npm install`, the language server formats). **Settings › Editor › General › Reformat code on save** then runs the tool too.
|
||||
|
||||
### Code style
|
||||
|
||||
**Settings › Editor › Code Style › JavaScript** and **TypeScript** have **Spaces** (after commas, around operators, within braces and so on) and **Punctuation** (semicolons: keep, use or don't use; quotes: as in the file, single or double). They are saved per project with the other code style settings and sent to the TypeScript server, which applies them to **Reformat Code** and to the code it adds: quick fixes, auto-imports, refactorings and **Optimize Imports**. JSX files follow JavaScript and TSX files TypeScript. When EditorConfig support is on, the project's `.editorconfig` comes first where it sets `quote_type` or the IntelliJ properties `ij_typescript_use_semicolon_after_statement`, `ij_typescript_use_double_quotes`, `ij_typescript_space_after_comma`, `ij_typescript_spaces_within_object_literal_braces` and the like (`ij_javascript_*` for JavaScript). tsserver has no trailing-comma option, so trailing commas stay as written.
|
||||
|
||||
### Biome lint
|
||||
|
||||
In a Biome project, Biome's diagnostics show in the editor and the Problems tool window, and `⌥⏎` / `Alt+Enter` offers its quick fixes and suppressions. Biome's safe fixes (`source.fixAll.biome`) run with **Code › Code Cleanup** and, when **Settings › Tools › Actions on Save › Run code cleanup** is on, on save. When Biome's formatter is enabled, its fix-all formats the file too.
|
||||
|
||||
@@ -55,6 +55,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
**将光标移至下一段落** / **上一段落** 让每个光标越过一段连续的非空行,跳到其后或其前的空行(只含空格或制表符的行也算空行),没有空行时跳到文件末尾或开头;对应的 **并选择** 版本选择到该处。它们默认没有快捷键。
|
||||
|
||||
**以另一种“驼峰”模式将光标移至下一个单词** / **上一个单词**(及其 **并选择** 版本)、**以另一种“驼峰”模式删除到单词开头** 和 **删除到单词结尾** 按与 **设置 › 编辑器 › 常规 › 智能键 › 使用“驼峰”单词** 相反的方式按单词移动或删除:该选项关闭时按驼峰片段(`parse|HTML|Document`),开启时按整个单词。它们默认没有快捷键。
|
||||
|
||||
**剪切到行尾** 从每个光标剪切到所在行的行尾;光标后只剩空白(或光标已在行尾)时连同换行符一起剪切,所以在同一光标处再按一次会剪切下一行,这些连续的剪切合并为剪贴板中的一条内容。**删除到行首** 和 **删除到行尾** 以同样方式删除但不复制(删除到行首时,若光标在行首则删除前面的换行符),有选区时删除选区。除 Eclipse 键位映射(删除到行尾为 `⇧⌘⌦` / `Ctrl+Shift+Delete`)外,它们默认没有快捷键。
|
||||
|
||||
**贪婪退格** 一次删除每个光标前的所有空格、制表符和换行符,直到前一个非空白字符;光标前是其他字符或有选区时,它与 `⌫` / `Backspace` 相同。它默认没有快捷键。
|
||||
@@ -158,6 +160,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
|
||||
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
- **视图 › 外观 › 进入无干扰模式** 隐藏工具窗口、标签页、状态栏和装订区域,并让正文居中。再执行一次即可退出。
|
||||
- **视图 › 外观 › 进入 Zen 模式** 同时开启无干扰模式和全屏;**退出 Zen 模式** 同时关闭两者。
|
||||
- **显示行号**、**显示缩进参考线**、**显示粘滞行** 和 **显示空白** 在所有编辑器中打开或关闭对应显示。可从查找操作运行,或右键单击装订区域并打开 **外观**。
|
||||
- 行号、空白字符、缩进参考线、光标样式和意图灯泡在 **设置 › 编辑器 › 常规 › 外观** 中设置。痕迹导航和粘滞行(滚动时把所在的声明固定在顶部)在 **设置 › 编辑器 › 常规** 下各有单独的页面。
|
||||
|
||||
|
||||
@@ -84,6 +84,12 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
|
||||
|
||||
这些页面上,**格式化工具** 可选 **自动(优先语言服务器)** 或工具本身,**保存时运行** 控制保存时格式化,**启用的语言** 限定工具处理哪些语言。
|
||||
|
||||
选 **自动** 时,位于该工具自身配置之下的 JavaScript、TypeScript 文件(Prettier 配置文件或 `package.json` 里的 `prettier` 键、oxfmt 配置、Biome 配置)由该工具格式化,而不是语言服务器;前提是该工具已安装(`npm install` 之前仍由语言服务器格式化)。这时 **设置 › 编辑器 › 常规 › 保存时重新格式化代码** 也会运行该工具。
|
||||
|
||||
### 代码样式
|
||||
|
||||
**设置 › 编辑器 › 代码样式 › JavaScript** 和 **TypeScript** 有 **空格**(逗号后、运算符两侧、花括号内等)和 **标点**(分号:保持原样、使用或不使用;引号:与文件一致、单引号或双引号)两个标签页。它们和其他代码样式设置一起按项目保存,并发送给 TypeScript 服务器:服务器将其用于 **重新格式化代码**,以及它添加的代码,包括快速修复、自动导入、重构和 **优化导入**。JSX 文件跟随 JavaScript,TSX 文件跟随 TypeScript。启用 EditorConfig 支持时,项目 `.editorconfig` 中设置的 `quote_type` 或 IntelliJ 属性 `ij_typescript_use_semicolon_after_statement`、`ij_typescript_use_double_quotes`、`ij_typescript_space_after_comma`、`ij_typescript_spaces_within_object_literal_braces` 等(JavaScript 用 `ij_javascript_*`)优先。tsserver 没有尾随逗号选项,尾随逗号保持原样。
|
||||
|
||||
### Biome 检查
|
||||
|
||||
在 Biome 项目中,Biome 的诊断显示在编辑器和“问题”工具窗口里,`⌥⏎` / `Alt+Enter` 提供它的快速修复和抑制。Biome 的安全修复(`source.fixAll.biome`)随 **代码 › 代码清理** 运行;开启 **设置 › 工具 › 保存时操作 › 运行代码清理** 后,保存时也会运行。Biome 的格式化器开启时,它的全部修复也会格式化文件。
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Git Branches of a project with several repositories: the current repository is listed first,
|
||||
* and moving the pointer from a repository row toward its open branch list keeps that list open
|
||||
* while it crosses the other repository rows (like a submenu of a menu). Git is stubbed at the
|
||||
* IPC layer.
|
||||
*/
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const ROOTS = ["/dev/acme/app", "/dev/acme/lib", "/dev/acme/tools", "/dev/acme/web"];
|
||||
|
||||
async function openBranches(page: Page) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ roots }) => {
|
||||
const h = window.__ipc.handlers;
|
||||
const branch = (name: string, current = false) => ({
|
||||
name,
|
||||
current,
|
||||
remote: false,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: null,
|
||||
commit: "1111111",
|
||||
});
|
||||
const repoName = (root: string) => root.split("/").pop()!;
|
||||
h.vcs_roots = () =>
|
||||
roots.map((root) => ({ root, operation: null, head: "main", headCommit: "1111111", hasRemotes: false }));
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: "1111111",
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_tags = () => [];
|
||||
h.vcs_branches = (args: { repo?: string | null }) => [
|
||||
branch("main", true),
|
||||
branch(`only-${repoName(args?.repo ?? roots[0]!)}`),
|
||||
];
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs, refreshNow, loadBranches } = await import(/* @vite-ignore */ vcsModule);
|
||||
// The window works on the third repository.
|
||||
useVcs.setState({ available: true, root: roots[0], repo: roots[2], branchesLoaded: false });
|
||||
await refreshNow();
|
||||
await loadBranches();
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.branches");
|
||||
},
|
||||
{ roots: ROOTS },
|
||||
);
|
||||
const list = page.getByRole("listbox", { name: "Repositories and branches" });
|
||||
await expect(list).toBeVisible();
|
||||
return list;
|
||||
}
|
||||
|
||||
const center = async (locator: ReturnType<Page["locator"]>) => {
|
||||
const box = (await locator.boundingBox())!;
|
||||
return { x: box.x + box.width / 2, y: box.y + box.height / 2, box };
|
||||
};
|
||||
|
||||
test("multi-repository Git Branches lists the current repository first and keeps a branch list open on the way to it", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const list = await openBranches(page);
|
||||
const rows = list.getByRole("option").filter({ has: page.locator("[data-row-key^='repo:']") });
|
||||
await expect(rows).toHaveCount(4);
|
||||
await expect(rows.first()).toContainText("tools");
|
||||
|
||||
// Open the first repository's branches, then head diagonally into the list across the rows below.
|
||||
const first = await center(rows.nth(0));
|
||||
await page.mouse.move(first.x, first.y);
|
||||
const branchesOfTools = page.getByRole("dialog", { name: "Branches of tools" });
|
||||
await expect(branchesOfTools).toBeVisible();
|
||||
const target = (await branchesOfTools.boundingBox())!;
|
||||
const last = await center(rows.nth(3));
|
||||
await page.mouse.move(target.x + 12, last.y, { steps: 12 });
|
||||
await expect(branchesOfTools).toBeVisible();
|
||||
await expect(branchesOfTools.getByText("only-tools", { exact: true })).toBeVisible();
|
||||
|
||||
// Moving straight onto another repository row switches to its branches.
|
||||
const second = await center(rows.nth(1));
|
||||
await page.mouse.move(second.x - 40, second.y);
|
||||
await page.mouse.move(second.x - 60, second.y);
|
||||
const branchesOfApp = page.getByRole("dialog", { name: "Branches of app" });
|
||||
await expect(branchesOfApp).toBeVisible();
|
||||
await expect(branchesOfTools).toBeHidden();
|
||||
|
||||
// Stopping on a row while heading for the open list switches only after a short delay.
|
||||
const third = await center(rows.nth(2));
|
||||
const appList = (await branchesOfApp.boundingBox())!;
|
||||
await page.mouse.move(appList.x - 30, second.y);
|
||||
await page.mouse.move(appList.x - 6, third.y);
|
||||
await expect(branchesOfApp).toBeVisible();
|
||||
await expect(page.getByRole("dialog", { name: "Branches of lib" })).toBeVisible();
|
||||
await expect(branchesOfApp).toBeHidden();
|
||||
});
|
||||
@@ -41,3 +41,19 @@ test("Copy Path/Reference keeps its preview and shortcut visible and can be resi
|
||||
await expect(popup).toBeHidden();
|
||||
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(path);
|
||||
});
|
||||
|
||||
test("Copy Path/Reference… in the Project view previews what each row copies", async ({ workbench: page, context }) => {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await page.getByRole("treeitem", { name: "build.gradle.kts" }).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Copy Path/Reference…" }).click();
|
||||
|
||||
const popup = page.getByRole("dialog", { name: "Copy Path/Reference…" });
|
||||
const name = popup.getByRole("option", { name: /^File Name/ });
|
||||
await expect(name.locator('[title="build.gradle.kts"]')).toBeVisible();
|
||||
await expect(popup.getByRole("option", { name: /^Path From Content Root/ })).toBeVisible();
|
||||
await page.keyboard.type("file name");
|
||||
await expect(name).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(popup).toBeHidden();
|
||||
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("build.gradle.kts");
|
||||
});
|
||||
@@ -411,7 +411,8 @@ test("rename owns deletion and Cmd+Enter without editing the previously focused
|
||||
await page.keyboard.press("Meta+a");
|
||||
const query = "SELECT 'keep this query';\nSELECT 2;";
|
||||
await page.keyboard.insertText(query);
|
||||
await page.keyboard.press("Meta+ArrowUp");
|
||||
// Caret on the first line (Cmd+Up is Jump to Navigation Bar, not a caret move).
|
||||
await content.locator(".cm-line").first().click();
|
||||
await expect(content).toHaveText(query.replace("\n", ""));
|
||||
|
||||
await choose(page, "Result 1", "Rename Tab");
|
||||
@@ -439,8 +440,7 @@ test("rename owns deletion and Cmd+Enter without editing the previously focused
|
||||
await expect(content).toHaveText(query.replace("\n", ""));
|
||||
|
||||
// The editor's own Delete Line shortcut still works after the dialog closes.
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+ArrowUp");
|
||||
await content.locator(".cm-line").first().click();
|
||||
await page.keyboard.press("Meta+Backspace");
|
||||
await expect(content.locator(".cm-line").filter({ hasText: /SELECT/ })).toHaveCount(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const ROOT = "/dev/acme-api";
|
||||
|
||||
async function pngVersions(page: Page) {
|
||||
return page.evaluate(() => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 4;
|
||||
canvas.height = 3;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.fillStyle = "teal";
|
||||
ctx.fillRect(0, 0, 4, 3);
|
||||
const head = canvas.toDataURL();
|
||||
ctx.clearRect(2, 1, 1, 1);
|
||||
ctx.fillStyle = "rgba(0, 128, 128, 0.5)";
|
||||
ctx.fillRect(2, 1, 1, 1);
|
||||
const index = canvas.toDataURL();
|
||||
ctx.clearRect(0, 0, 2, 1);
|
||||
return { head, index, local: canvas.toDataURL() };
|
||||
});
|
||||
}
|
||||
|
||||
async function expectCount(page: Page, count: number) {
|
||||
await expect(
|
||||
page.getByRole("status").filter({ hasText: new RegExp(`^${count} changed pixels?$`, "i") }),
|
||||
).toBeVisible();
|
||||
}
|
||||
|
||||
test("Commit Changes renders a PNG and highlights one alpha-only change", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
const { head, index: local } = await pngVersions(page);
|
||||
const file = "status.png";
|
||||
const path = ROOT + "/" + file;
|
||||
await page.evaluate(
|
||||
async ({ root, path, file, head, local }) => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
const branch = { head: "main", headCommit: "1111111", operation: null, upstream: null, ahead: 0, behind: 0 };
|
||||
handlers.vcs_roots = () => [{ root, ...branch }];
|
||||
handlers.vcs_branch_info = () => branch;
|
||||
handlers.vcs_branches = () => [];
|
||||
handlers.vcs_stashes = () => [];
|
||||
handlers.vcs_status = () => [{ path, relPath: file, staged: null, unstaged: "modified", renamedFrom: null }];
|
||||
handlers.vcs_image_at = ({ rev }) => (rev === "HEAD" ? head : null);
|
||||
handlers.fs_read_image = () => local;
|
||||
const store = "/src/features/vcs/store.ts";
|
||||
const { useVcs, refreshNow } = await import(/* @vite-ignore */ store);
|
||||
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
|
||||
await refreshNow();
|
||||
},
|
||||
{ root: ROOT, path, file, head, local },
|
||||
);
|
||||
await page.keyboard.press("Meta+k");
|
||||
await page.getByRole("tree", { name: "Changes" }).getByText(file, { exact: true }).dblclick();
|
||||
const toolbar = page.getByRole("toolbar", { name: "Image diff" });
|
||||
const highlight = toolbar.getByRole("button", { name: "Highlight changed pixels" });
|
||||
await highlight.click();
|
||||
await expectCount(page, 1);
|
||||
const mask = page.getByLabel("Pixel difference mask");
|
||||
await expect(mask).toBeVisible();
|
||||
const pixels = await mask.evaluate((element) => {
|
||||
const canvas = element as HTMLCanvasElement;
|
||||
const data = canvas.getContext("2d")!.getImageData(0, 0, canvas.width, canvas.height).data;
|
||||
return Array.from({ length: canvas.width * canvas.height }, (_, i) => data.slice(4 * i, 4 * i + 4).join(","));
|
||||
});
|
||||
expect(pixels).toHaveLength(12);
|
||||
expect(pixels.filter((pixel) => pixel !== pixels[0])).toEqual([pixels[6]]);
|
||||
expect(pixels[6]).not.toBe(pixels[0]);
|
||||
await highlight.click();
|
||||
await expect(mask).toBeHidden();
|
||||
expect(await ipcCalls(page, "vcs_image_at")).toContainEqual({ path, rev: "HEAD" });
|
||||
expect(await ipcCalls(page, "fs_read_image")).toContainEqual({ path });
|
||||
});
|
||||
|
||||
test("staged and unstaged PNG diffs compare the index with the specified side", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
const images = await pngVersions(page);
|
||||
await page.evaluate(({ head, index, local }) => {
|
||||
window.__ipc.handlers.vcs_image_at = ({ rev }) => (rev === "HEAD" ? head : rev === ":0" ? index : null);
|
||||
window.__ipc.handlers.fs_read_image = () => local;
|
||||
}, images);
|
||||
for (const [side, count] of [
|
||||
["staged", 1],
|
||||
["unstaged", 2],
|
||||
] as const) {
|
||||
await page.evaluate(
|
||||
async ({ side, root }) => {
|
||||
const input = "/src/features/vcs/diffInput.ts";
|
||||
const { openDiff, workingDiffData } = await import(/* @vite-ignore */ input);
|
||||
const path = root + "/status.png";
|
||||
const status = { path, relPath: "status.png", staged: "modified", unstaged: "modified", renamedFrom: null };
|
||||
await openDiff(workingDiffData(path, undefined, side, status));
|
||||
},
|
||||
{ side, root: ROOT },
|
||||
);
|
||||
const highlight = page.getByRole("button", { name: "Highlight changed pixels" });
|
||||
await highlight.click();
|
||||
await expectCount(page, count);
|
||||
await highlight.click();
|
||||
}
|
||||
});
|
||||
|
||||
test("the three-way PNG diff labels each revision and compares all three pairs", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
const images = await pngVersions(page);
|
||||
await page.evaluate(async ({ head, index, local }) => {
|
||||
window.__ipc.handlers.vcs_image_at = ({ rev }) => (rev === "HEAD" ? head : rev === ":0" ? index : null);
|
||||
window.__ipc.handlers.fs_read_image = () => local;
|
||||
const input = "/src/features/vcs/diffInput.ts";
|
||||
const { openDiff, stagingGutterDiffData } = await import(/* @vite-ignore */ input);
|
||||
await openDiff(stagingGutterDiffData("/dev/acme-api/status.png"));
|
||||
}, images);
|
||||
for (const [label, url] of [
|
||||
["HEAD", images.head],
|
||||
["Staged (index)", images.index],
|
||||
["Local Version", images.local],
|
||||
] as const) {
|
||||
await expect(page.getByRole("img", { name: label, exact: true })).toHaveAttribute("src", url);
|
||||
}
|
||||
const toolbar = page.getByRole("toolbar", { name: "Image diff" });
|
||||
await toolbar.getByRole("button", { name: "Highlight changed pixels" }).click();
|
||||
await expectCount(page, 1);
|
||||
for (const [pair, count] of [
|
||||
["Staged (index) ↔ Local Version", 2],
|
||||
["HEAD ↔ Local Version", 3],
|
||||
] as const) {
|
||||
await toolbar.getByRole("button", { name: "Compare revisions" }).click();
|
||||
await page.getByRole("option", { name: pair }).click();
|
||||
await expectCount(page, count);
|
||||
}
|
||||
});
|
||||
|
||||
for (const ext of ["jpg", "jpeg", "webp", "svg"] as const) {
|
||||
test(`renders both historical revisions of a renamed .${ext} without a working file`, async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
const path = `${ROOT}/current.${ext}`;
|
||||
const oldPath = `${ROOT}/original.${ext}`;
|
||||
await page.evaluate(
|
||||
async ({ path, oldPath, ext }) => {
|
||||
const before =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="8" height="6"><rect width="8" height="6"/></svg>';
|
||||
const after = before.replace("<rect ", '<rect id="same-shape" ');
|
||||
const url = (source: string) => "data:image/svg+xml;base64," + btoa(source);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 8;
|
||||
canvas.height = 6;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
const encode = (color: string) => {
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(0, 0, 8, 6);
|
||||
// WebKit can decode WebP even when its canvas encoder would return PNG.
|
||||
if (ext === "webp") {
|
||||
const bytes =
|
||||
color === "white"
|
||||
? "UklGRiIAAABXRUJQVlA4TBYAAAAvB0ABAAfQ//73v/8BgCD8b5uI6H8I"
|
||||
: "UklGRiAAAABXRUJQVlA4TBMAAAAvB0ABAAcQEf0PAAThf9tERP9DAA==";
|
||||
return "data:image/webp;base64," + bytes;
|
||||
}
|
||||
return canvas.toDataURL("image/jpeg");
|
||||
};
|
||||
const left = ext === "svg" ? url(before) : encode("white");
|
||||
const right = ext === "svg" ? url(after) : encode("black");
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.vcs_image_at = (args) => {
|
||||
if (args.path === oldPath && args.rev === "11111111") return left;
|
||||
if (args.path === path && args.rev === "22222222") return right;
|
||||
return null;
|
||||
};
|
||||
handlers.vcs_file_at = (args) => (args.path === oldPath ? before : after);
|
||||
const input = "/src/features/vcs/diffInput.ts";
|
||||
const { openDiff, commitFileDiffData } = await import(/* @vite-ignore */ input);
|
||||
await openDiff(
|
||||
commitFileDiffData(
|
||||
{ id: "22222222", shortId: "22222222", parents: ["11111111"], repo: "/dev/acme-api" },
|
||||
{ path: "current." + ext, oldPath: "original." + ext, kind: "renamed" },
|
||||
),
|
||||
);
|
||||
},
|
||||
{ path, oldPath, ext },
|
||||
);
|
||||
const toolbar = page.getByRole("toolbar", { name: "Image diff" });
|
||||
await toolbar.getByRole("button", { name: "Highlight changed pixels" }).click();
|
||||
await expectCount(page, ext === "svg" ? 0 : 48);
|
||||
expect(await ipcCalls(page, "fs_read_image")).toEqual([]);
|
||||
if (ext === "svg") {
|
||||
await toolbar.getByRole("button", { name: "View source diff" }).click();
|
||||
const xml = page.locator(".cm-content").filter({ hasText: "same-shape" });
|
||||
await expect(xml).toBeVisible();
|
||||
await page.getByRole("button", { name: "Image preview" }).click();
|
||||
await expect(xml).toBeHidden();
|
||||
await expect(page.getByRole("button", { name: "View source diff" })).toBeVisible();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Identical opaque teal RGBA rows encoded with zlib levels 0 and 9. The cropped version removes the rightmost column.
|
||||
const originalPng =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAPklEQVR4AQEzAMz/AACAgP8AgID/AICA/wCAgP8AAICA/wCAgP8AgID/AICA/wAAgID/AICA/wCAgP8AgID/UTEX9btCu2YAAAAASUVORK5CYII=";
|
||||
const recompressedPng =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAEUlEQVR42mNgaGj4j4IJCgAAUTEX9X/prpgAAAAASUVORK5CYII=";
|
||||
const croppedPng =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAAEElEQVR42mNgaGj4D8c4OQBRFBH4p8q4GwAAAABJRU5ErkJggg==";
|
||||
|
||||
for (const [scenario, count] of [
|
||||
["recompressed", 0],
|
||||
["cropped", 3],
|
||||
["added", 12],
|
||||
["deleted", 12],
|
||||
] as const) {
|
||||
test(`shows ${count} changed pixels for historical PNGs (${scenario})`, async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ scenario, before, after }) => {
|
||||
const input = "/src/features/vcs/diffInput.ts";
|
||||
const { openDiff, commitFileDiffData } = await import(/* @vite-ignore */ input);
|
||||
window.__ipc.handlers.vcs_image_at = ({ rev }) =>
|
||||
"data:image/png;base64," + (rev === "11111111" ? before : after);
|
||||
const kind = scenario === "added" || scenario === "deleted" ? scenario : "modified";
|
||||
await openDiff(
|
||||
commitFileDiffData(
|
||||
{ id: "22222222", shortId: "22222222", parents: ["11111111"], repo: "/dev/acme-api" },
|
||||
{ path: "snapshot.png", kind },
|
||||
),
|
||||
);
|
||||
},
|
||||
{ scenario, before: originalPng, after: scenario === "cropped" ? croppedPng : recompressedPng },
|
||||
);
|
||||
if (scenario === "added" || scenario === "deleted") {
|
||||
const missing = scenario === "added" ? "(does not exist)" : "(deleted)";
|
||||
await expect(page.getByRole("region", { name: missing }).getByText("No image on this side")).toBeVisible();
|
||||
const rev = scenario === "added" ? "22222222" : "11111111";
|
||||
await expect(page.getByRole("img", { name: rev })).toBeVisible();
|
||||
const reads = await ipcCalls(page, "vcs_image_at");
|
||||
expect(new Set(reads.map((call) => call.rev))).toEqual(new Set([rev]));
|
||||
}
|
||||
await page.getByRole("button", { name: "Highlight changed pixels" }).click();
|
||||
await expectCount(page, count);
|
||||
if (scenario === "cropped") {
|
||||
const changed = await page.getByLabel("Pixel difference mask").evaluate((element) => {
|
||||
const ctx = (element as HTMLCanvasElement).getContext("2d")!;
|
||||
const rgba = ctx.getImageData(0, 0, 4, 3).data;
|
||||
return Array.from({ length: 12 }, (_, i) => i).filter((i) => rgba[i * 4] !== rgba[i * 4 + 1]);
|
||||
});
|
||||
expect(changed).toEqual([3, 7, 11]);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
id = "json"
|
||||
name = "JSON"
|
||||
formatter = { tool = "prettier", parser = "json", range = true }
|
||||
extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map"]
|
||||
extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map", "uproject", "uplugin"]
|
||||
filenames = [".prettierrc", ".watchmanconfig", "composer.lock", ".arcconfig"]
|
||||
indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "JSON"
|
||||
|
||||
+53
-34
@@ -351,33 +351,35 @@ installing (or when a new version asks for more). Low-risk capabilities are
|
||||
listed; high-risk ones are called out as equivalent to running code on the
|
||||
machine. Users can revoke optional capabilities in Settings › Plugins.
|
||||
|
||||
| Capability | Risk | Unlocks today |
|
||||
| ------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ide.commands` | high | Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing. API 1.4; declared own commands are exempt. |
|
||||
| `database.sources` | medium | API 1.4: manage only the plugin's own project database sources, write their secure credentials and request connection; trusted projects only. |
|
||||
| `project.read` | low | `Project::root`, `read_file`, `read_bytes`, `find_files`, `symbols`, `search_text`, `host::projects`, `publish_diagnostics`, `problems`, editor opening and decorations |
|
||||
| `project.write` | high | `Project::write_file` — creates and replaces text files inside the open projects, the settings and build scripts a trusted project runs included |
|
||||
| `fs.read:<path>` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory |
|
||||
| `fs.write:<path>` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading |
|
||||
| `editor.read` | low | `TextEditor::document`, `selections`, `host::open_editors` |
|
||||
| `editor.write` | medium | `TextEditor::apply_edits` |
|
||||
| `vcs.read` | low | `Project::vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff` (new reads require trust), `host::pending_commit`, before-commit checks |
|
||||
| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` |
|
||||
| `build.read` | low | API 1.10: `Project::build_dependencies`, the Maven / Gradle dependency graph the IDE resolved; trusted projects only |
|
||||
| `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) |
|
||||
| `events` | low | file opened/saved, editor focused, repository changed events |
|
||||
| `events.input` | medium | `action-performed` and `input-mode-changed` events |
|
||||
| `process:<program>` | high | `Project::run_process`, language servers, debug adapters, runs |
|
||||
| `lsp:<server>` | high | API 1.9: `Project::language_server_request` / `language_server_notify` to that running language server (its name in the language definition); trusted projects only |
|
||||
| `java.agent` | high | API 1.10: the `[[contributes.javaAgents]]` jar runs inside the Java applications you start; derived from that declaration, never listed |
|
||||
| `net:<host>` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains |
|
||||
| `net:ask` | medium | Ask the user at the first request to an HTTPS (or loopback) host that is not declared; one answer per host, revocable; API 1.5 |
|
||||
| `net.http:<host>` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` |
|
||||
| `ipc:<path>` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 |
|
||||
| `secrets` | medium | `{{secret:<name>}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` |
|
||||
| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views |
|
||||
| `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran |
|
||||
| `agents` | medium | API 1.18: `host::fork_agent_session`, fork a recorded native agent session into a new task in the project; trusted projects only |
|
||||
| Capability | Risk | Unlocks today |
|
||||
| ------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ide.commands` | high | Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing. API 1.4; declared own commands are exempt. |
|
||||
| `database.sources` | medium | API 1.4: manage only the plugin's own project database sources, write their secure credentials and request connection; trusted projects only. |
|
||||
| `project.read` | low | `Project::root`, `read_file`, `read_bytes`, `find_files`, `symbols`, `search_text`, `host::projects`, `publish_diagnostics`, `problems`, editor opening and decorations |
|
||||
| `project.write` | high | `Project::write_file` — creates and replaces text files inside the open projects, the settings and build scripts a trusted project runs included |
|
||||
| `fs.read:<path>` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory |
|
||||
| `fs.write:<path>` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading |
|
||||
| `editor.read` | low | `TextEditor::document`, `selections`, `host::open_editors` |
|
||||
| `editor.write` | medium | `TextEditor::apply_edits` |
|
||||
| `vcs.read` | low | `Project::vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff` (new reads require trust), `host::pending_commit`, before-commit checks |
|
||||
| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` |
|
||||
| `build.read` | low | API 1.10: `Project::build_dependencies`, the Maven / Gradle dependency graph the IDE resolved; trusted projects only |
|
||||
| `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) |
|
||||
| `events` | low | file opened/saved, editor focused, repository changed events |
|
||||
| `events.input` | medium | `action-performed` and `input-mode-changed` events |
|
||||
| `process:<program>` | high | `Project::run_process`, language servers, debug adapters, runs |
|
||||
| `lsp:<server>` | high | API 1.9: `Project::language_server_request` / `language_server_notify` to that running language server (its name in the language definition); trusted projects only |
|
||||
| `java.agent` | high | API 1.10: the `[[contributes.javaAgents]]` jar runs inside the Java applications you start; derived from that declaration, never listed |
|
||||
| `net:<host>` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains |
|
||||
| `net:ask` | medium | Ask the user at the first request to an HTTPS (or loopback) host that is not declared; one answer per host, revocable; API 1.5 |
|
||||
| `net.http:<host>` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` |
|
||||
| `net:setting:<key>` | medium | API 1.18: the host of the plugin's `string` setting `<key>` over HTTPS (also loopback HTTP), approved when the user applies the value in Settings; bare host or URL |
|
||||
| `net.http:setting:<key>` | medium | API 1.18: the same setting's host over unencrypted HTTP, approved the same way |
|
||||
| `ipc:<path>` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 |
|
||||
| `secrets` | medium | `{{secret:<name>}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` |
|
||||
| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views |
|
||||
| `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran |
|
||||
| `agents` | medium | API 1.18: `host::fork_agent_session`, fork a recorded native agent session into a new task in the project; trusted projects only |
|
||||
|
||||
`process:` capabilities are also derived from what the contributions start: a
|
||||
language's `language-servers` and `debugger` commands and a run detector's
|
||||
@@ -2044,6 +2046,23 @@ so the plugin should tell the user to run the action once interactively. Plain H
|
||||
to other hosts never goes through this flow: declare `net.http:<host>`. A
|
||||
manifest using `net:ask` declares `engines.openidea = "^1.5"`.
|
||||
|
||||
A setting-derived grant, `net:setting:<key>` (API 1.18), names a `string` setting of
|
||||
the plugin's own schema instead of a host; `net.http:setting:<key>` is the same
|
||||
over plain HTTP. The key is checked at install like the other manifest checks, and
|
||||
the manifest declares `engines.openidea = "^1.18"`. When the user applies the
|
||||
setting's value in Settings, a dialog names the plugin, the setting and the host —
|
||||
which may be a bare host or a URL — and states plainly that a `net.http:` connection
|
||||
is unencrypted. **Deny is the default**: only an explicit approval materializes the
|
||||
host, which then behaves exactly like a `net:<host>` (or `net.http:<host>`) grant —
|
||||
all ports, no subdomains, `*` refused, redirects unchanged. A value that reaches the
|
||||
plugin any other way (a hand-edited settings file, a project settings file, a value
|
||||
written by the plugin itself) is not approved: the plugin's permissions show the host
|
||||
as pending with an **Approve** action. Changing the setting replaces the approval only
|
||||
after the user confirms it; clearing the setting removes it. The approved hosts are
|
||||
listed next to the `net:ask` ones and revocable. Unattended calls to a pending or
|
||||
revoked host return `denied` without a dialog, like `net:ask`; on remote hosts the
|
||||
approval is kept for the session only.
|
||||
|
||||
A host answer covers all ports of that host, like `net:<host>`, and never
|
||||
covers subdomains or wildcard patterns. IDNs are shown in ASCII (punycode);
|
||||
IP literals use their canonical form. Redirects are checked against the
|
||||
@@ -2343,8 +2362,8 @@ argument, JSON text:
|
||||
|
||||
`host::start_run` still starts only the plugin's own configurations. To launch
|
||||
the user's configuration with the plugin's Java agent, bind the agent to an
|
||||
executor (_Java agents_): **Run '<name>' with <title>** and **Debug '<name>'
|
||||
with <title>** then appear in this menu for Application, Spring Boot and JAR
|
||||
executor (_Java agents_): **Run '`<name>`' with `<title>`** and **Debug '`<name>`'
|
||||
with `<title>`** then appear in this menu for Application, Spring Boot and JAR
|
||||
Application configurations, and go through the normal launch (build,
|
||||
classpath, JDK, debugger, Stop).
|
||||
|
||||
@@ -2872,11 +2891,11 @@ jdk = "jetbrains" # optional: only those VM options on
|
||||
shortened command line moves only the classpath into its argument file.
|
||||
- **Executors** (API 1.18). With `executor = "<title>"` (1–40 characters) the
|
||||
agent no longer loads into every launch. The plugin gets an executor beside
|
||||
Run and Debug instead, as IDEA's "Run with JRebel" or "Profile": **Run '<name>'
|
||||
with <title>** and **Debug '<name>' with <title>** in the run widget's ⋮ menu,
|
||||
Run and Debug instead, as IDEA's "Run with JRebel" or "Profile": **Run '`<name>`'
|
||||
with `<title>`** and **Debug '`<name>`' with `<title>`** in the run widget's ⋮ menu,
|
||||
the gutter's ▶ menu, the context menus' run entries and the Services context
|
||||
menu of those configurations, plus the actions **Run with <title>** and
|
||||
**Debug with <title>** (Find Action, Keymap). Only launches through them get
|
||||
menu of those configurations, plus the actions **Run with `<title>`** and
|
||||
**Debug with `<title>`** (Find Action, Keymap). Only launches through them get
|
||||
the agent and its `vmOptions`; the grant and jar pin are the same. Without
|
||||
`java.agent` the IDE says so instead of launching, and a configuration on a
|
||||
run target is refused the same way.
|
||||
@@ -3757,7 +3776,7 @@ no generic env-forwarding flags are added. Container env is forwarded only if
|
||||
the wrapper's own conventions allow it.
|
||||
|
||||
Registration never changes a selection. The first registration prompts the
|
||||
project's windows: “Use <name> for running PHP / Node / Composer in this project?”
|
||||
project's windows: “Use `<name>` for running PHP / Node / Composer in this project?”
|
||||
with **Use** / **Not now**. The first answer is remembered on the host per
|
||||
project + plugin + target id. Use sets the project's default run target and its
|
||||
PHP and Node run-target choices; Not now leaves settings alone. Interpreters
|
||||
|
||||
@@ -252,6 +252,52 @@ pub async fn plugin_revoke_net_host(state: State<'_, AppState>, id: String, host
|
||||
blocking(move || plugins.revoke_net_host(&id, &host)).await
|
||||
}
|
||||
|
||||
/// The host a `net:setting:` grant derives from `value` (a bare host or a
|
||||
/// URL), validated with the manifest host rules; an error refuses the value.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn plugin_net_setting_host(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
setting: String,
|
||||
value: String,
|
||||
) -> IdeResult<String> {
|
||||
let plugins = state.plugins.clone();
|
||||
blocking(move || plugins.net_setting_host(&id, &setting, &value)).await
|
||||
}
|
||||
|
||||
/// Approves `host` for the plugin's `net:setting:<key>` grant (applied in
|
||||
/// Settings, or the pending row); refused when the setting no longer holds it.
|
||||
#[desktop_command(trust = outside_restricted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn plugin_approve_net_setting(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
setting: String,
|
||||
http: bool,
|
||||
host: String,
|
||||
) -> IdeResult<PluginInfo> {
|
||||
let plugins = state.plugins.clone();
|
||||
blocking(move || plugins.approve_net_setting(&id, &setting, http, &host)).await
|
||||
}
|
||||
|
||||
/// Drops the approved host of a `net:setting:<key>` grant (revoked, or the
|
||||
/// setting's value cleared).
|
||||
#[desktop_command(trust = outside_restricted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn plugin_forget_net_setting(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
setting: String,
|
||||
http: bool,
|
||||
) -> IdeResult<PluginInfo> {
|
||||
let plugins = state.plugins.clone();
|
||||
blocking(move || plugins.forget_net_setting(&id, &setting, http)).await
|
||||
}
|
||||
|
||||
/// Links a development plugin folder (`openidea-plugin link` does the same from a terminal).
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
@@ -650,8 +696,10 @@ pub fn plugin_set_theme_frame(state: State<'_, AppState>, color: Option<String>)
|
||||
|
||||
ide_command::desktop_domain!(
|
||||
plugin_activation_event,
|
||||
plugin_approve_net_setting,
|
||||
plugin_assets,
|
||||
plugin_catalog,
|
||||
plugin_forget_net_setting,
|
||||
plugin_grant,
|
||||
plugin_install_dir,
|
||||
plugin_installed_intellij_themes,
|
||||
@@ -661,6 +709,7 @@ ide_command::desktop_domain!(
|
||||
plugin_market,
|
||||
plugin_market_download,
|
||||
plugin_market_url,
|
||||
plugin_net_setting_host,
|
||||
plugin_preview_install,
|
||||
plugin_read_intellij_theme,
|
||||
plugin_reload,
|
||||
|
||||
@@ -849,6 +849,7 @@ mod tests {
|
||||
"window.toggleFullScreen",
|
||||
"view.toggleTheme",
|
||||
"editor.toggleZen",
|
||||
"view.toggleZenMode",
|
||||
"view.toggleToolbar",
|
||||
"view.toggleToolWindowBars",
|
||||
"view.toggleStatusBar",
|
||||
|
||||
@@ -1529,6 +1529,7 @@ mod tests {
|
||||
settings: Default::default(),
|
||||
workspace: None,
|
||||
unity: None,
|
||||
unreal: None,
|
||||
})
|
||||
.unwrap())
|
||||
}
|
||||
|
||||
@@ -456,6 +456,7 @@ plugin_answer_command trusted project_host bin
|
||||
plugin_answer_commit trusted project_host bindings sync
|
||||
plugin_answer_prompt trusted project_host bindings sync
|
||||
plugin_answer_run_target trusted project_host bindings async
|
||||
plugin_approve_net_setting outside_restricted desktop bindings async
|
||||
plugin_assets always desktop bindings async
|
||||
plugin_cancel_task trusted project_host bindings sync
|
||||
plugin_catalog always desktop bindings async
|
||||
@@ -470,6 +471,7 @@ plugin_decoration_sets trusted project_host bin
|
||||
plugin_endpoints trusted project_host bindings async
|
||||
plugin_event_kinds trusted project_host bindings async
|
||||
plugin_finish_operation trusted project_host bindings sync
|
||||
plugin_forget_net_setting outside_restricted desktop bindings async
|
||||
plugin_formatters trusted project_host bindings sync
|
||||
plugin_grant outside_restricted desktop bindings async
|
||||
plugin_install_dir outside_restricted desktop bindings async
|
||||
@@ -487,6 +489,7 @@ plugin_navigation_goto trusted project_host bin
|
||||
plugin_navigation_index trusted project_host bindings async
|
||||
plugin_navigation_invalidate trusted project_host bindings sync
|
||||
plugin_navigation_markers trusted project_host bindings async
|
||||
plugin_net_setting_host always desktop bindings async
|
||||
plugin_parse_test_results trusted project_host bindings async
|
||||
plugin_post_events trusted project_host bindings sync
|
||||
plugin_prepare_debug_run trusted project_host bindings async
|
||||
@@ -752,6 +755,7 @@ vcs_has_commit always project_host bin
|
||||
vcs_has_hook always project_host bindings async
|
||||
vcs_ignore_blame_revision trusted project_host bindings async
|
||||
vcs_ignored_files always project_host bindings async
|
||||
vcs_image_at always project_host bindings async
|
||||
vcs_init always project_host bindings async
|
||||
vcs_inspect_push trusted project_host bindings async
|
||||
vcs_invalidate_log_signatures always project_host bindings async
|
||||
|
||||
@@ -1226,6 +1226,11 @@ export const commands = {
|
||||
*/
|
||||
pluginAnswerPrompt: (promptId: string, answer: string[] | null) => __TAURI_INVOKE<boolean>("plugin_answer_prompt", { promptId, answer }),
|
||||
pluginAnswerRunTarget: (id: string, useTarget: boolean) => typedError<Settings_Serialize, IdeError>(__TAURI_INVOKE("plugin_answer_run_target", { id, useTarget })),
|
||||
/**
|
||||
* Approves `host` for the plugin's `net:setting:<key>` grant (applied in
|
||||
* Settings, or the pending row); refused when the setting no longer holds it.
|
||||
*/
|
||||
pluginApproveNetSetting: (id: string, setting: string, http: boolean, host: string) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_approve_net_setting", { id, setting, http, host })),
|
||||
/** Validated assets of a plugin whose id starts with `prefix` (icon theme mapping and SVGs). */
|
||||
pluginAssets: (pluginId: string, prefix: string) => typedError<([string, string])[], IdeError>(__TAURI_INVOKE("plugin_assets", { pluginId, prefix })),
|
||||
/** Cancels a plugin task (`taskStarted` with `cancellable`). */
|
||||
@@ -1258,6 +1263,11 @@ export const commands = {
|
||||
pluginEventKinds: () => __TAURI_INVOKE<EventKind[]>("plugin_event_kinds"),
|
||||
/** Reports exactly one completion from the operation's launching window. */
|
||||
pluginFinishOperation: (id: string, status: number | null, stopped: boolean) => typedError<boolean, IdeError>(__TAURI_INVOKE("plugin_finish_operation", { id, status, stopped })),
|
||||
/**
|
||||
* Drops the approved host of a `net:setting:<key>` grant (revoked, or the
|
||||
* setting's value cleared).
|
||||
*/
|
||||
pluginForgetNetSetting: (id: string, setting: string, http: boolean) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_forget_net_setting", { id, setting, http })),
|
||||
pluginFormatters: () => typedError<FormatterChoice[], IdeError>(__TAURI_INVOKE("plugin_formatters")),
|
||||
/** Confirms a plugin waiting for consent (project plugins, new capabilities). */
|
||||
pluginGrant: (id: string, consent: Consent) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_grant", { id, consent })),
|
||||
@@ -1297,6 +1307,11 @@ export const commands = {
|
||||
pluginNavigationIndex: (paths: string[], request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_navigation_index", { paths, request })),
|
||||
pluginNavigationInvalidate: (paths: string[] | null) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_navigation_invalidate", { paths })),
|
||||
pluginNavigationMarkers: (paths: string[]) => typedError<FileMarkers[], IdeError>(__TAURI_INVOKE("plugin_navigation_markers", { paths })),
|
||||
/**
|
||||
* The host a `net:setting:` grant derives from `value` (a bare host or a
|
||||
* URL), validated with the manifest host rules; an error refuses the value.
|
||||
*/
|
||||
pluginNetSettingHost: (id: string, setting: string, value: string) => typedError<string, IdeError>(__TAURI_INVOKE("plugin_net_setting_host", { id, setting, value })),
|
||||
/** Parses one batch of an owned test configuration's output. */
|
||||
pluginParseTestResults: (config: string, chunk: string) => typedError<PluginTestEvent[] | null, IdeError>(__TAURI_INVOKE("plugin_parse_test_results", { config, chunk })),
|
||||
/** Workbench events from this window (only the kinds of `plugin_event_kinds`). */
|
||||
@@ -1448,6 +1463,7 @@ export const commands = {
|
||||
settings: Settings_Serialize,
|
||||
workspace?: Workspace_Serialize | null,
|
||||
unity?: UnityProjectInfo | null,
|
||||
unreal?: UnrealProjectInfo | null,
|
||||
} | null>("project_current"),
|
||||
/**
|
||||
* File › Rename Project…: the project's display name (title bar, recent
|
||||
@@ -2131,6 +2147,8 @@ export const commands = {
|
||||
vcsHasHook: (repo: string | null, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("vcs_has_hook", { repo, name })),
|
||||
vcsIgnoreBlameRevision: (path: string, commit: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_ignore_blame_revision", { path, commit })),
|
||||
vcsIgnoredFiles: () => typedError<FileStatus[], IdeError>(__TAURI_INVOKE("vcs_ignored_files")),
|
||||
/** An image at the selected Git revision or index stage as a data URL, absent if the path is missing. */
|
||||
vcsImageAt: (path: string, rev: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_image_at", { path, rev })),
|
||||
/**
|
||||
* `git init` in `dir` (VCS › Create Git Repository…): with the git of the window's project when
|
||||
* it is trusted, the default one in a window without a project.
|
||||
@@ -9140,6 +9158,12 @@ export type LanguageCodeStyle_Deserialize = {
|
||||
keywordCase?: string | null,
|
||||
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
|
||||
identifierCase?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
|
||||
semicolons?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
|
||||
quotes?: string | null,
|
||||
/** JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`). */
|
||||
spaces?: { [key in string]: boolean },
|
||||
};
|
||||
|
||||
/** Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit). */
|
||||
@@ -9164,6 +9188,12 @@ export type LanguageCodeStyle_Serialize = {
|
||||
keywordCase?: string | null,
|
||||
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
|
||||
identifierCase?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
|
||||
semicolons?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
|
||||
quotes?: string | null,
|
||||
/** JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`). */
|
||||
spaces?: { [key in string]: boolean },
|
||||
};
|
||||
|
||||
/** Language identifier, e.g. `rust`, `typescript`, `kotlin`. Matches LSP `languageId`. */
|
||||
@@ -11071,6 +11101,8 @@ export type PluginInfo = {
|
||||
* none of them declared by the manifest; each can be revoked.
|
||||
*/
|
||||
netHosts: string[],
|
||||
/** Setting-derived hosts (`net:setting:`), approved in Settings, listed next to the `net:ask` ones. */
|
||||
netSettings: PluginNetSetting[],
|
||||
/** What it contributes while live (point + label). */
|
||||
contributions: ContributionInfo[],
|
||||
/** `activation` events of the manifest. */
|
||||
@@ -11127,6 +11159,18 @@ export type PluginLocation = {
|
||||
range: Range,
|
||||
};
|
||||
|
||||
/** A `net:setting:` grant's host for Settings › Plugins: the approved one while the setting holds it, else the pending one. */
|
||||
export type PluginNetSetting = {
|
||||
/** The setting key the host comes from (`server` of `net:setting:server`). */
|
||||
setting: string,
|
||||
/** Plain HTTP (`net.http:setting:`) instead of HTTPS (and loopback HTTP). */
|
||||
http: boolean,
|
||||
/** The approved host, while the setting still holds it. */
|
||||
host: string | null,
|
||||
/** The host the setting holds now when it is not the approved one. */
|
||||
pending: string | null,
|
||||
};
|
||||
|
||||
/** A line a view's `process` body printed. */
|
||||
export type PluginOutputLine = {
|
||||
stderr: boolean,
|
||||
@@ -11583,6 +11627,7 @@ export type ProjectInfo_Deserialize = {
|
||||
settings: Settings_Deserialize,
|
||||
workspace?: Workspace_Deserialize | null,
|
||||
unity?: UnityProjectInfo | null,
|
||||
unreal?: UnrealProjectInfo | null,
|
||||
};
|
||||
|
||||
export type ProjectInfo_Serialize = {
|
||||
@@ -11594,6 +11639,7 @@ export type ProjectInfo_Serialize = {
|
||||
settings: Settings_Serialize,
|
||||
workspace?: Workspace_Serialize | null,
|
||||
unity?: UnityProjectInfo | null,
|
||||
unreal?: UnrealProjectInfo | null,
|
||||
};
|
||||
|
||||
/** An interpreter another project uses: the project root and the SDK itself. */
|
||||
@@ -14317,6 +14363,22 @@ export type UnityProjectInfo = {
|
||||
projects: string[],
|
||||
};
|
||||
|
||||
/** A located engine, shown so a project without run configurations says why. */
|
||||
export type UnrealEngine = {
|
||||
/** `5.8` for a launcher install, or the registry key a source build registered under. */
|
||||
id: string,
|
||||
/** Absolute engine root. */
|
||||
root: string,
|
||||
};
|
||||
|
||||
export type UnrealProjectInfo = {
|
||||
/**
|
||||
* The engine the project builds against. `None` means none could be located, which is the
|
||||
* only reason such a project offers no run configuration at all.
|
||||
*/
|
||||
engine: UnrealEngine | null,
|
||||
};
|
||||
|
||||
/** A requirement the project's interpreter does not satisfy. */
|
||||
export type UnsatisfiedRequirement = {
|
||||
dependency: ManifestDependency,
|
||||
|
||||
@@ -34,7 +34,7 @@ import type { LanguageDescription } from "@codemirror/language";
|
||||
import type { HunkKind } from "@/bindings";
|
||||
import type { LineEnding } from "@/platform/ipc";
|
||||
import { create } from "zustand";
|
||||
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
|
||||
import { maybeEditorService, type EditorInput, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { rootOfPath } from "@/platform/projectRoots";
|
||||
@@ -254,6 +254,25 @@ export function editorsFor(path: string): TextEditorHandle[] {
|
||||
return [...useEditorRegistry.getState().editors].filter((e) => e.ctx.path === path);
|
||||
}
|
||||
|
||||
/**
|
||||
* While a cell editor of a custom editor (a notebook) has focus, it stands in for the
|
||||
* active editor's view: the notebook publishes the editor context keys for it and
|
||||
* editor actions resolve to it, like a text tab's view. The owner keeps this current
|
||||
* on focus changes (see `_setFocusedCellEditor`); editor/core re-reads it whenever it
|
||||
* republishes contexts, so actions never fall back to the last text tab.
|
||||
*/
|
||||
let focusedCell: EditorView | null = null;
|
||||
|
||||
/** The focused cell editor standing in for the active editor's view, if any. */
|
||||
export function focusedCellEditor(): EditorView | null {
|
||||
return focusedCell;
|
||||
}
|
||||
|
||||
/** Published by the custom editor owning the cell editors (a notebook); `null` once none has focus. */
|
||||
export function _setFocusedCellEditor(view: EditorView | null) {
|
||||
focusedCell = view;
|
||||
}
|
||||
|
||||
// --- called by editor/core only ---------------------------------------------
|
||||
|
||||
export function _setActiveEditor(handle: TextEditorHandle | null) {
|
||||
@@ -998,6 +1017,37 @@ export function _provideCodePreview(provider: typeof codePreviewProvider) {
|
||||
codePreviewProvider = provider;
|
||||
}
|
||||
|
||||
/** A row of the Copy Path/Reference… chooser. */
|
||||
export interface CopyPathRow {
|
||||
/** The action whose shortcut the row shows. */
|
||||
id: string;
|
||||
/** English label, translated by the chooser. */
|
||||
label: string;
|
||||
/** The copied text; a row without one is left out. */
|
||||
preview: string | null;
|
||||
run: () => void;
|
||||
}
|
||||
|
||||
type CopyPathChooser = (
|
||||
anchor: { x: number; y: number } | "center",
|
||||
rows: readonly CopyPathRow[],
|
||||
ctx: MenuGroupContext,
|
||||
) => void;
|
||||
let copyPathChooser: CopyPathChooser | null = null;
|
||||
|
||||
/**
|
||||
* The editor's Copy Path/Reference… chooser for files outside an editor (the Project view's
|
||||
* selection): `rows`, then the rows contributed to the `copyPath` menu for `ctx`, with previews.
|
||||
*/
|
||||
export function openCopyPathChooser(...args: Parameters<CopyPathChooser>): void {
|
||||
copyPathChooser?.(...args);
|
||||
}
|
||||
|
||||
/** @internal editor/core only. */
|
||||
export function _provideCopyPathChooser(open: CopyPathChooser) {
|
||||
copyPathChooser = open;
|
||||
}
|
||||
|
||||
let workspaceHistory: ((id: number, redo: boolean) => Promise<void>) | null = null;
|
||||
|
||||
/** Undo/redo a refactoring through the same history used by editor commands. */
|
||||
|
||||
@@ -7,6 +7,7 @@ import { foldEffect, syntaxTree, toggleFold } from "@codemirror/language";
|
||||
import { acceptCompletion, completionStatus } from "@codemirror/autocomplete";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { focusedCellEditor } from "@/editor/api";
|
||||
import { focusedSoftWrapSurface } from "@/workbench/softWrap";
|
||||
import { resetSurfaceFontZoom, stepFocusedSurfaceFontZoom, stepSurfaceFontZoomIn } from "@/workbench/contributions";
|
||||
import { editorController, useGotoLine, useTabs } from "./controller";
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
deleteLine,
|
||||
duplicateEntireLines,
|
||||
duplicateLineOrSelection,
|
||||
inDifferentHumpsMode,
|
||||
joinLines,
|
||||
moveStatementDown,
|
||||
moveStatementUp,
|
||||
@@ -68,7 +70,8 @@ import { customRegions } from "./cm/regions";
|
||||
import { toggleRenderedViewAtCaret } from "./cm/renderedDocs";
|
||||
import { enclosingHeaders } from "./cm/stickyScroll";
|
||||
import { moveElementLeft, moveElementRight } from "./cm/moveElement";
|
||||
import { caretAnchor, openPopup, updatePopup, useLspPopup, type LspPopup } from "@/editor/lsp/popupStore";
|
||||
import { caretAnchor, openPopup, updatePopup, useLspPopup } from "@/editor/lsp/popupStore";
|
||||
import { copyPathPopup } from "./copyPathChooser";
|
||||
import {
|
||||
cursorCodeBlockEnd,
|
||||
cursorCodeBlockStart,
|
||||
@@ -109,7 +112,7 @@ import {
|
||||
import { useProject } from "@/platform/project";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { menuGroupItems, notifications } from "@/workbench/contributions";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
|
||||
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
|
||||
import { toggleReadOnly } from "./fileAttributes";
|
||||
@@ -165,8 +168,15 @@ function withTextView(run: (view: EditorView) => unknown, editable: boolean) {
|
||||
};
|
||||
}
|
||||
|
||||
function withView(run: (view: EditorView, slot: EditorSlot) => unknown) {
|
||||
function withView(run: (view: EditorView, slot: EditorSlot | null) => unknown) {
|
||||
return () => {
|
||||
// While a notebook cell editor has focus it is the editor the action runs in
|
||||
// (the notebook publishes the editor context keys for it), never the last text tab.
|
||||
const cell = focusedCellEditor();
|
||||
if (cell) {
|
||||
run(cell, null);
|
||||
return;
|
||||
}
|
||||
const slot = activeSlot();
|
||||
if (!slot?.view) return;
|
||||
run(slot.view, slot);
|
||||
@@ -636,24 +646,10 @@ function pathWithLines(state: EditorState, path: string, kind: "relative" | "abs
|
||||
return `${pathToCopy(kind, path)}:${first}${last > first ? `-${last}` : ""}`;
|
||||
}
|
||||
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
|
||||
// The popup's items resolve against the open document; a notebook cell has none.
|
||||
if (!slot) return;
|
||||
const path = slot.model.path;
|
||||
const contributed = menuGroupItems("copyPath", {
|
||||
paths: [path],
|
||||
...selectedLineContext(view.state),
|
||||
}).flatMap((item) =>
|
||||
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
|
||||
? [
|
||||
{
|
||||
id: item.id,
|
||||
label: item.verbatim ? item.label : tx(item.label),
|
||||
preview: item.preview,
|
||||
shortcut: shortcutLabel(item.id),
|
||||
run: item.run,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
const flavours = [
|
||||
{ id: "project.copyAbsolutePath", label: "Absolute Path", value: pathToCopy("absolute", path) },
|
||||
{
|
||||
@@ -670,26 +666,20 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
value: pathWithLines(view.state, path),
|
||||
},
|
||||
];
|
||||
const popup: Extract<LspPopup, { kind: "list" }> = {
|
||||
kind: "list",
|
||||
title: tx("Copy Path/Reference…"),
|
||||
layout: "copyPath",
|
||||
anchor: caretAnchor(view, view.state.selection.main.head),
|
||||
items: [
|
||||
...flavours
|
||||
.filter((f) => f.value !== null)
|
||||
.map((f) => ({
|
||||
id: f.id,
|
||||
label: tx(f.label),
|
||||
preview: f.value!,
|
||||
shortcut: shortcutLabel(f.id),
|
||||
run: () => {
|
||||
const lineNumbered =
|
||||
f.id === "editor.copyPathWithLineNumber" || f.id === "editor.copyAbsolutePathWithLineNumber";
|
||||
void executeAction(f.id, lineNumbered ? f.value : path);
|
||||
},
|
||||
})),
|
||||
...contributed,
|
||||
const popup = copyPathPopup(
|
||||
caretAnchor(view, view.state.selection.main.head),
|
||||
flavours.map((f) => ({
|
||||
id: f.id,
|
||||
label: f.label,
|
||||
preview: f.value,
|
||||
run: () => {
|
||||
const lineNumbered =
|
||||
f.id === "editor.copyPathWithLineNumber" || f.id === "editor.copyAbsolutePathWithLineNumber";
|
||||
void executeAction(f.id, lineNumbered ? f.value : path);
|
||||
},
|
||||
})),
|
||||
{ paths: [path], ...selectedLineContext(view.state) },
|
||||
[
|
||||
{
|
||||
id: "editor.copyReference",
|
||||
label: tx("Reference"),
|
||||
@@ -699,7 +689,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
run: () => {},
|
||||
},
|
||||
],
|
||||
};
|
||||
);
|
||||
openPopup(popup);
|
||||
void resolveReference(view, slot)
|
||||
.then((reference) => {
|
||||
@@ -792,7 +782,7 @@ export function registerEditorActions(): () => void {
|
||||
const text = (
|
||||
id: string,
|
||||
title: string,
|
||||
run: (view: EditorView, slot: EditorSlot) => unknown,
|
||||
run: (view: EditorView, slot: EditorSlot | null) => unknown,
|
||||
extra: Partial<Action> = {},
|
||||
): Action => ({
|
||||
id,
|
||||
@@ -920,6 +910,18 @@ export function registerEditorActions(): () => void {
|
||||
category: "Editor Actions",
|
||||
keyWhen: "editorTextFocus || diffEditorFocus",
|
||||
}),
|
||||
edit(
|
||||
"code.deleteToWordStartInDifferentHumpsMode",
|
||||
'Delete to Word Start in Different "CamelHumps" Mode',
|
||||
(v) => inDifferentHumpsMode("deleteToStart", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions", keyWhen: "editorTextFocus || diffEditorFocus" },
|
||||
),
|
||||
edit(
|
||||
"code.deleteToWordEndInDifferentHumpsMode",
|
||||
'Delete to Word End in Different "CamelHumps" Mode',
|
||||
(v) => inDifferentHumpsMode("deleteToEnd", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions", keyWhen: "editorTextFocus || diffEditorFocus" },
|
||||
),
|
||||
edit("code.moveLineUp", "Move Line Up", (v) => moveLineUp(v)),
|
||||
edit("code.moveLineDown", "Move Line Down", (v) => moveLineDown(v)),
|
||||
edit("code.moveElementLeft", "Move Element Left", (v) => moveElementLeft(v), {
|
||||
@@ -928,24 +930,38 @@ export function registerEditorActions(): () => void {
|
||||
edit("code.moveElementRight", "Move Element Right", (v) => moveElementRight(v), {
|
||||
keywords: ["swap argument", "move parameter"],
|
||||
}),
|
||||
text("code.moveStatementUp", "Move Statement Up", (v, slot) => moveStatement(v, slot, true)),
|
||||
text("code.moveStatementDown", "Move Statement Down", (v, slot) => moveStatement(v, slot, false)),
|
||||
text("code.extendSelection", "Extend Selection", (_v, slot) => void queueSelection(slot, extend), {
|
||||
category: "Edit",
|
||||
}),
|
||||
text("code.shrinkSelection", "Shrink Selection", (_v, slot) => void queueSelection(slot, shrink), {
|
||||
category: "Edit",
|
||||
}),
|
||||
text("code.moveStatementUp", "Move Statement Up", (v, slot) => slot && moveStatement(v, slot, true)),
|
||||
text("code.moveStatementDown", "Move Statement Down", (v, slot) => slot && moveStatement(v, slot, false)),
|
||||
text(
|
||||
"code.extendSelection",
|
||||
"Extend Selection",
|
||||
(_v, slot) => {
|
||||
if (slot) void queueSelection(slot, extend);
|
||||
},
|
||||
{
|
||||
category: "Edit",
|
||||
},
|
||||
),
|
||||
text(
|
||||
"code.shrinkSelection",
|
||||
"Shrink Selection",
|
||||
(_v, slot) => {
|
||||
if (slot) void queueSelection(slot, shrink);
|
||||
},
|
||||
{
|
||||
category: "Edit",
|
||||
},
|
||||
),
|
||||
text("code.fold", "Collapse", (v) => foldAtCaret(v), { category: "Folding", keywords: ["fold"] }),
|
||||
text("code.unfold", "Expand", (v) => unfoldAtCaret(v), { category: "Folding", keywords: ["unfold"] }),
|
||||
text("code.foldToggle", "Toggle Fold", (v) => toggleFold(v), { category: "Folding" }),
|
||||
text("code.cyclicExpandWord", "Cyclic Expand Word", (v, slot) => expandWord(v, slot, "backward"), {
|
||||
text("code.cyclicExpandWord", "Cyclic Expand Word", (v, slot) => slot && expandWord(v, slot, "backward"), {
|
||||
keywords: ["hippie", "complete word", "dabbrev"],
|
||||
}),
|
||||
text(
|
||||
"code.cyclicExpandWordBackward",
|
||||
"Cyclic Expand Word (Backward)",
|
||||
(v, slot) => expandWord(v, slot, "forward"),
|
||||
(v, slot) => slot && expandWord(v, slot, "forward"),
|
||||
{
|
||||
keywords: ["hippie", "complete word", "dabbrev"],
|
||||
},
|
||||
@@ -956,7 +972,7 @@ export function registerEditorActions(): () => void {
|
||||
when: TEXT_WHEN,
|
||||
run: ({ arg }) => {
|
||||
if (typeof arg === "string") copyReference(Promise.resolve(arg));
|
||||
else withView((v, slot) => copyReference(resolveReference(v, slot)))();
|
||||
else withView((v, slot) => slot && copyReference(resolveReference(v, slot)))();
|
||||
},
|
||||
category: "Edit",
|
||||
keywords: ["fully qualified name", "fqn", "copy path"],
|
||||
@@ -983,8 +999,13 @@ export function registerEditorActions(): () => void {
|
||||
icon: "soft-wrap",
|
||||
keywords: ["word wrap", "line wrap"],
|
||||
when: "textEditorActive || softWrapSurfaceFocus",
|
||||
toggled: () => focusedSoftWrapSurface()?.enabled() ?? activeSlot()?.model.softWrapOn() ?? false,
|
||||
// Cell editors wrap always; without the cell the setting is the active text tab's.
|
||||
toggled: () =>
|
||||
focusedSoftWrapSurface()?.enabled() ??
|
||||
(focusedCellEditor() ? true : (activeSlot()?.model.softWrapOn() ?? false)),
|
||||
run: () => {
|
||||
// Don't flip the last text tab's setting while a notebook cell has focus.
|
||||
if (focusedCellEditor()) return;
|
||||
const surface = focusedSoftWrapSurface();
|
||||
if (surface) surface.toggle();
|
||||
else activeSlot()?.model.toggleSoftWrap();
|
||||
@@ -996,8 +1017,12 @@ export function registerEditorActions(): () => void {
|
||||
category: "View",
|
||||
keywords: ["render documentation comments", "javadoc", "rendered doc", "comments"],
|
||||
when: "textEditorActive",
|
||||
toggled: () => activeSlot()?.model.renderedDocsOn() ?? false,
|
||||
run: () => activeSlot()?.model.toggleRenderedDocs(),
|
||||
toggled: () => (focusedCellEditor() ? false : (activeSlot()?.model.renderedDocsOn() ?? false)),
|
||||
run: () => {
|
||||
// Notebook cells have no doc-comment rendering: leave it, don't toggle the last text tab's.
|
||||
if (focusedCellEditor()) return;
|
||||
activeSlot()?.model.toggleRenderedDocs();
|
||||
},
|
||||
},
|
||||
text("editor.toggleRenderedView", "Toggle Rendered View", (v) => toggleRenderedViewAtCaret(v), {
|
||||
category: "View",
|
||||
@@ -1005,11 +1030,11 @@ export function registerEditorActions(): () => void {
|
||||
}),
|
||||
text("code.foldAll", "Collapse All", (v) => collapseAll(v), { category: "Folding", icon: "collapse-all" }),
|
||||
text("code.unfoldAll", "Expand All", (v) => expandAll(v), { category: "Folding", icon: "expand-all" }),
|
||||
text("code.expandDocComments", "Expand Doc Comments", (v, slot) => foldDocComments(v, slot, false), {
|
||||
text("code.expandDocComments", "Expand Doc Comments", (v, slot) => slot && foldDocComments(v, slot, false), {
|
||||
category: "Folding",
|
||||
keywords: ["unfold", "documentation comments", "javadoc"],
|
||||
}),
|
||||
text("code.collapseDocComments", "Collapse Doc Comments", (v, slot) => foldDocComments(v, slot, true), {
|
||||
text("code.collapseDocComments", "Collapse Doc Comments", (v, slot) => slot && foldDocComments(v, slot, true), {
|
||||
category: "Folding",
|
||||
keywords: ["fold", "documentation comments", "javadoc"],
|
||||
}),
|
||||
@@ -1023,7 +1048,11 @@ export function registerEditorActions(): () => void {
|
||||
}),
|
||||
occurrence("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", addNextOccurrence),
|
||||
occurrence("code.selectAllOccurrences", "Select All Occurrences", selectAllOccurrences),
|
||||
text("code.completeStatement", "Complete Current Statement", (v, slot) => completeCurrentStatement(v, slot)),
|
||||
text(
|
||||
"code.completeStatement",
|
||||
"Complete Current Statement",
|
||||
(v, slot) => slot && completeCurrentStatement(v, slot),
|
||||
),
|
||||
edit("code.startNewLine", "Start New Line", (v) => startNewLine(v)),
|
||||
edit("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)),
|
||||
edit("code.splitLine", "Split Line", (v) => splitLine(v)),
|
||||
@@ -1083,6 +1112,30 @@ export function registerEditorActions(): () => void {
|
||||
(v) => selectParagraphBackward(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.nextWordInDifferentHumpsMode",
|
||||
'Move Caret to Next Word in Different "CamelHumps" Mode',
|
||||
(v) => inDifferentHumpsMode("right", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.previousWordInDifferentHumpsMode",
|
||||
'Move Caret to Previous Word in Different "CamelHumps" Mode',
|
||||
(v) => inDifferentHumpsMode("left", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.nextWordInDifferentHumpsModeWithSelection",
|
||||
'Move Caret to Next Word in Different "CamelHumps" Mode with Selection',
|
||||
(v) => inDifferentHumpsMode("selectRight", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.previousWordInDifferentHumpsModeWithSelection",
|
||||
'Move Caret to Previous Word in Different "CamelHumps" Mode with Selection',
|
||||
(v) => inDifferentHumpsMode("selectLeft", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
text("editor.contextInfo", "Context Info", (v) => showContextInfo(v), {
|
||||
category: "View",
|
||||
keywords: ["enclosing method", "enclosing class", "where am I"],
|
||||
@@ -1135,7 +1188,7 @@ export function registerEditorActions(): () => void {
|
||||
category: "Editor Actions",
|
||||
keywords: ["overwrite mode", "overtype"],
|
||||
toggled: () => {
|
||||
const view = activeSlot()?.view;
|
||||
const view = focusedCellEditor() ?? activeSlot()?.view;
|
||||
return view ? isOverwrite(view.state) : false;
|
||||
},
|
||||
}),
|
||||
@@ -1162,7 +1215,7 @@ export function registerEditorActions(): () => void {
|
||||
text(
|
||||
"code.fillParagraph",
|
||||
"Fill Paragraph",
|
||||
(v, slot) => fillParagraph(v, hardWrapAt(slot.model.settings(), slot.model.info)),
|
||||
(v, slot) => slot && fillParagraph(v, hardWrapAt(slot.model.settings(), slot.model.info)),
|
||||
{
|
||||
category: "Edit",
|
||||
keywords: ["wrap", "reflow", "rewrap comment"],
|
||||
@@ -1176,9 +1229,16 @@ export function registerEditorActions(): () => void {
|
||||
category: "Edit",
|
||||
keywords: ["spaces", "indentation"],
|
||||
}),
|
||||
text("code.unwrap", "Unwrap/Remove…", (_v, slot) => void unwrapAtCaret(slot), {
|
||||
keywords: ["unwrap", "remove if"],
|
||||
}),
|
||||
text(
|
||||
"code.unwrap",
|
||||
"Unwrap/Remove…",
|
||||
(_v, slot) => {
|
||||
if (slot) void unwrapAtCaret(slot);
|
||||
},
|
||||
{
|
||||
keywords: ["unwrap", "remove if"],
|
||||
},
|
||||
),
|
||||
text("code.foldSelection", "Fold Selection / Remove Region", (v) => foldSelection(v), { category: "Folding" }),
|
||||
{
|
||||
id: "editor.toggleColumnSelection",
|
||||
@@ -1187,7 +1247,7 @@ export function registerEditorActions(): () => void {
|
||||
keywords: ["block selection", "rectangular selection"],
|
||||
when: "textEditorActive",
|
||||
toggled: () => {
|
||||
const view = activeSlot()?.view;
|
||||
const view = focusedCellEditor() ?? activeSlot()?.view;
|
||||
return view ? isColumnMode(view.state) : false;
|
||||
},
|
||||
run: withView((v) => toggleColumnMode(v)),
|
||||
@@ -1265,7 +1325,8 @@ export function registerEditorActions(): () => void {
|
||||
when: "textEditorActive",
|
||||
run: () => {
|
||||
const slot = activeSlot();
|
||||
if (slot) toggleReadOnly(slot.model);
|
||||
// A notebook has no document model to toggle: leave it rather than the last text tab's file.
|
||||
if (slot && !focusedCellEditor()) toggleReadOnly(slot.model);
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1564,7 +1625,7 @@ export function registerEditorActions(): () => void {
|
||||
when: TEXT_WHEN,
|
||||
run: ({ arg }) => {
|
||||
if (typeof arg === "string") copyEditorPath(arg);
|
||||
else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path)))();
|
||||
else withView((view, slot) => slot && copyEditorPath(pathWithLines(view.state, slot.model.path)))();
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1574,7 +1635,7 @@ export function registerEditorActions(): () => void {
|
||||
when: TEXT_WHEN,
|
||||
run: ({ arg }) => {
|
||||
if (typeof arg === "string") copyEditorPath(arg);
|
||||
else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path, "absolute")))();
|
||||
else withView((view, slot) => slot && copyEditorPath(pathWithLines(view.state, slot.model.path, "absolute")))();
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -24,10 +24,15 @@ import {
|
||||
} from "@codemirror/language";
|
||||
import {
|
||||
copyLineDown,
|
||||
cursorGroupLeft,
|
||||
cursorGroupRight,
|
||||
deleteGroupForward,
|
||||
deleteLine as deleteDocLine,
|
||||
insertNewlineAndIndent,
|
||||
moveLineDown,
|
||||
moveLineUp,
|
||||
selectGroupLeft,
|
||||
selectGroupRight,
|
||||
} from "@codemirror/commands";
|
||||
import { SearchCursor } from "@codemirror/search";
|
||||
import { humpLeft, humpRight, wordStartLeft } from "../model/camelHumps";
|
||||
@@ -90,6 +95,21 @@ export const deleteHumpForward = deleteHump(true);
|
||||
/** ⌥⌫ / Ctrl+Backspace without CamelHumps: the whitespace before the caret and the word (or punctuation run) before it. */
|
||||
export const deleteWordBackward = deleteHump(false, false);
|
||||
|
||||
/** The word moves and deletes the editor keys run in each mode (`caretExtension`): `[without CamelHumps, with CamelHumps]`. */
|
||||
const WORD_COMMANDS = {
|
||||
left: [cursorGroupLeft, cursorHumpLeft],
|
||||
right: [cursorGroupRight, cursorHumpRight],
|
||||
selectLeft: [selectGroupLeft, selectHumpLeft],
|
||||
selectRight: [selectGroupRight, selectHumpRight],
|
||||
deleteToStart: [deleteWordBackward, deleteHumpBackward],
|
||||
deleteToEnd: [deleteGroupForward, deleteHumpForward],
|
||||
} satisfies Record<string, [Command, Command]>;
|
||||
|
||||
/** IDEA's "… in Different "CamelHumps" Mode": the word command of the mode "Use CamelHumps words" is not set to. */
|
||||
export function inDifferentHumpsMode(op: keyof typeof WORD_COMMANDS, camelHumps: boolean): Command {
|
||||
return WORD_COMMANDS[op][camelHumps ? 0 : 1];
|
||||
}
|
||||
|
||||
// --- lines / selections -------------------------------------------------------
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
deleteWordBackward,
|
||||
duplicateEntireLines,
|
||||
duplicateLineOrSelection,
|
||||
inDifferentHumpsMode,
|
||||
moveStatementDown,
|
||||
moveStatementUp,
|
||||
nextOccurrence,
|
||||
@@ -228,6 +229,57 @@ describe("Delete to Word Start", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('in Different "CamelHumps" Mode', () => {
|
||||
function run(text: string, op: Parameters<typeof inDifferentHumpsMode>[0], camelHumps: boolean, times = 1) {
|
||||
const v = make(text);
|
||||
for (let i = 0; i < times; i++) inDifferentHumpsMode(op, camelHumps)(v);
|
||||
return show(v);
|
||||
}
|
||||
|
||||
it("moves by humps while the setting is off", () => {
|
||||
expect(run("|parseHTMLDocument x", "right", false)).toBe("parse|HTMLDocument x");
|
||||
expect(run("|parseHTMLDocument x", "right", false, 2)).toBe("parseHTML|Document x");
|
||||
expect(run("x parseHTMLDocument|", "left", false)).toBe("x parseHTML|Document");
|
||||
expect(run("|snake_case_name", "right", false)).toBe("snake_|case_name");
|
||||
});
|
||||
|
||||
it("moves by whole words while the setting is on", () => {
|
||||
expect(run("|parseHTMLDocument x", "right", true)).toBe("parseHTMLDocument| x");
|
||||
expect(run("x parseHTMLDocument|", "left", true)).toBe("x |parseHTMLDocument");
|
||||
});
|
||||
|
||||
it("extends the selection from its anchor in the with Selection variants", () => {
|
||||
expect(run("|fooBarBaz", "selectRight", false, 2)).toBe("[fooBar]Baz");
|
||||
expect(run("fooBarBaz|", "selectLeft", false)).toBe("fooBar[Baz]");
|
||||
expect(run("|fooBar baz", "selectRight", true)).toBe("[fooBar] baz");
|
||||
});
|
||||
|
||||
it("moves every caret, and leaves a selection at its edge without extending", () => {
|
||||
expect(run("|fooBar\n|bazQux", "right", false)).toBe("foo|Bar\nbaz|Qux");
|
||||
expect(run("[fooBar]Baz", "right", false)).toBe("fooBar|Baz");
|
||||
expect(run("foo[BarBaz]", "left", false)).toBe("foo|BarBaz");
|
||||
});
|
||||
|
||||
it("deletes to the word start or end of the other mode", () => {
|
||||
expect(run("a.fooBar|", "deleteToStart", false)).toBe("a.foo|");
|
||||
expect(run("a.fooBar|", "deleteToStart", true)).toBe("a.|");
|
||||
expect(run("|fooBar.b", "deleteToEnd", false)).toBe("|Bar.b");
|
||||
expect(run("|fooBar.b", "deleteToEnd", true)).toBe("|.b");
|
||||
expect(run("foo [BarBaz] qux", "deleteToEnd", false)).toBe("foo | qux");
|
||||
expect(run("foo [BarBaz] qux", "deleteToEnd", true)).toBe("foo | qux");
|
||||
expect(run("aBc|\nxYz|", "deleteToStart", false)).toBe("a|\nx|");
|
||||
});
|
||||
|
||||
it("does not delete in a read-only editor", () => {
|
||||
for (const camelHumps of [false, true]) {
|
||||
const v = make("foo|Bar", EditorState.readOnly.of(true));
|
||||
expect(inDifferentHumpsMode("deleteToStart", camelHumps)(v)).toBe(false);
|
||||
expect(inDifferentHumpsMode("deleteToEnd", camelHumps)(v)).toBe(false);
|
||||
expect(show(v)).toBe("foo|Bar");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("paste reformatting", () => {
|
||||
/** One unit deeper after a line ending in `{`. */
|
||||
const braceIndent = indentService.of((cx, pos) => {
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
_provideNavigationHistory,
|
||||
_provideOpenEditorPaths,
|
||||
_setActiveEditor,
|
||||
focusedCellEditor,
|
||||
shownLine,
|
||||
type NavigationLocation,
|
||||
} from "@/editor/api";
|
||||
@@ -1116,6 +1117,9 @@ export class EditorController implements SlotHost {
|
||||
const slot = this.activeSlot;
|
||||
const meta = slot?.model.getMeta();
|
||||
const s = useTabs.getState();
|
||||
// A focused notebook cell editor stands in for the active text editor (the notebook
|
||||
// publishes the editor context keys for it): republishing on tab churn keeps them on.
|
||||
const cell = focusedCellEditor();
|
||||
setContext("editorPath", slot?.model.path ?? null);
|
||||
setContext("editorLangId", meta?.language ?? null);
|
||||
setContext("editorReadOnly", !!meta?.readOnly);
|
||||
@@ -1125,8 +1129,8 @@ export class EditorController implements SlotHost {
|
||||
Object.values(s.panes).some((p) => p.tabs.length > 0),
|
||||
);
|
||||
setContext("editorSplit", paneIds(s).length > 1);
|
||||
setContext("editorTextFocus", !!slot?.view?.hasFocus);
|
||||
setContext("textEditorActive", !!slot);
|
||||
setContext("editorTextFocus", cell ? cell.hasFocus : !!slot?.view?.hasFocus);
|
||||
setContext("textEditorActive", !!slot || !!cell);
|
||||
}
|
||||
|
||||
// --- navigation history --------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/** The Copy Path/Reference… chooser: each way to copy, with a preview of the text it copies. */
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { menuGroupItems, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { openPopup, type ListPopupItem, type LspPopup, type PopupPoint } from "@/editor/lsp/popupStore";
|
||||
import type { CopyPathRow } from "@/editor/api";
|
||||
|
||||
/** The chooser's popup: `rows`, then the rows contributed to the `copyPath` menu for `ctx`. */
|
||||
export function copyPathPopup(
|
||||
anchor: PopupPoint | "center",
|
||||
rows: readonly CopyPathRow[],
|
||||
ctx: MenuGroupContext,
|
||||
trailing: readonly ListPopupItem[] = [],
|
||||
): Extract<LspPopup, { kind: "list" }> {
|
||||
const contributed = menuGroupItems("copyPath", ctx).flatMap((item) =>
|
||||
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
|
||||
? [
|
||||
{
|
||||
id: item.id,
|
||||
label: item.verbatim ? item.label : tx(item.label),
|
||||
preview: item.preview,
|
||||
shortcut: shortcutLabel(item.id),
|
||||
run: item.run,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
return {
|
||||
kind: "list",
|
||||
title: tx("Copy Path/Reference…"),
|
||||
layout: "copyPath",
|
||||
anchor,
|
||||
items: [
|
||||
...rows.flatMap((row) =>
|
||||
row.preview === null
|
||||
? []
|
||||
: [{ id: row.id, label: tx(row.label), preview: row.preview, shortcut: shortcutLabel(row.id), run: row.run }],
|
||||
),
|
||||
...contributed,
|
||||
...trailing,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Opens the chooser for files outside an editor (`openCopyPathChooser` of `@/editor/api`). */
|
||||
export function openCopyPathChooser(
|
||||
anchor: PopupPoint | "center",
|
||||
rows: readonly CopyPathRow[],
|
||||
ctx: MenuGroupContext,
|
||||
): void {
|
||||
openPopup(copyPathPopup(anchor, rows, ctx));
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { evaluateWhen, getContext, useContextKeys } from "@/platform/context";
|
||||
import { installKeyboardDispatcher } from "@/platform/keymap";
|
||||
import { _setFocusedCellEditor } from "@/editor/api";
|
||||
import { TEXT_WHEN, registerEditorActions } from "./actions";
|
||||
import { editorController, useEditorStatus, useTabs } from "./controller";
|
||||
import { initialTabsState } from "./model/tabs";
|
||||
import { columnModeField, isColumnMode } from "./cm/columnMode";
|
||||
|
||||
const toggleReadOnlyMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("./fileAttributes", async (original) => ({
|
||||
...(await original<typeof import("./fileAttributes")>()),
|
||||
toggleReadOnly: toggleReadOnlyMock,
|
||||
}));
|
||||
|
||||
const ctrl = editorController();
|
||||
let disposeActions: () => void;
|
||||
beforeAll(() => {
|
||||
disposeActions = registerEditorActions();
|
||||
ctrl.start();
|
||||
});
|
||||
afterAll(() => {
|
||||
ctrl.stop();
|
||||
disposeActions();
|
||||
});
|
||||
afterEach(() => {
|
||||
useTabs.setState(initialTabsState(), true);
|
||||
useEditorStatus.setState({ status: null });
|
||||
useContextKeys.setState({}, true);
|
||||
_setFocusedCellEditor(null);
|
||||
toggleReadOnlyMock.mockClear();
|
||||
});
|
||||
|
||||
/** A bare editor standing in for a focused notebook cell (the fact CellEditor publishes). */
|
||||
function focusedCell(doc = "x = 1\n"): { view: EditorView; clear: () => void } {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
// `columnModeField`: what a cell editor carries through its own extension list.
|
||||
const view = new EditorView({ doc, parent: host, extensions: columnModeField });
|
||||
view.focus();
|
||||
if (!view.hasFocus) throw new Error("the jsdom view did not take focus");
|
||||
_setFocusedCellEditor(view);
|
||||
return { view, clear: () => _setFocusedCellEditor(null) };
|
||||
}
|
||||
|
||||
function disposeView(cell: { view: EditorView }): void {
|
||||
cell.view.destroy();
|
||||
cell.view.dom.remove();
|
||||
}
|
||||
|
||||
describe("editor context keys with a focused notebook cell", () => {
|
||||
it("keeps the keys on while a cell editor has focus, with no text editor open", () => {
|
||||
const cell = focusedCell();
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(true);
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
// Republishing (tab churn, pane focus) must not drop the keys.
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(true);
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
} finally {
|
||||
cell.clear();
|
||||
disposeView(cell);
|
||||
}
|
||||
});
|
||||
|
||||
it("lets a focused cell editor win over the mounted but unfocused text editor", async () => {
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
try {
|
||||
const textView = slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
const cell = focusedCell();
|
||||
ctrl.publishContext();
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
expect(textView.hasFocus).toBe(false);
|
||||
cell.clear();
|
||||
disposeView(cell);
|
||||
} finally {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("drops the keys once no cell editor has focus", () => {
|
||||
const cell = focusedCell();
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(true);
|
||||
cell.clear();
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(false);
|
||||
expect(getContext().editorTextFocus).toBe(false);
|
||||
} finally {
|
||||
disposeView(cell);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a text tab's own keys when no cell editor is focused", async () => {
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
try {
|
||||
const view = slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
view.focus();
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(true);
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
} finally {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("editor actions in a focused notebook cell", () => {
|
||||
it("run in the focused cell editor, not the last text tab", async () => {
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
try {
|
||||
const textView = slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
const cell = focusedCell();
|
||||
ctrl.publishContext();
|
||||
await executeAction("editor.toggleColumnSelection");
|
||||
expect(isColumnMode(cell.view.state)).toBe(true);
|
||||
expect(isColumnMode(textView.state)).toBe(false);
|
||||
cell.clear();
|
||||
disposeView(cell);
|
||||
} finally {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("do not toggle the last text tab's read-only attribute", async () => {
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
try {
|
||||
slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
const cell = focusedCell();
|
||||
await executeAction("file.toggleReadOnly");
|
||||
expect(toggleReadOnlyMock).not.toHaveBeenCalled();
|
||||
// Without a focused cell the text editor is toggled, as before.
|
||||
cell.clear();
|
||||
ctrl.publishContext();
|
||||
await executeAction("file.toggleReadOnly");
|
||||
expect(toggleReadOnlyMock).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("give the keyboard to the cell: ⌥⌘L reaches an editor action there", () => {
|
||||
const cell = focusedCell();
|
||||
ctrl.publishContext();
|
||||
const reformat = vi.fn();
|
||||
const disposeStub = registerActions([
|
||||
{ id: "code.reformat", title: "Reformat Code", category: "Code", when: TEXT_WHEN, run: reformat },
|
||||
]);
|
||||
const uninstall = installKeyboardDispatcher(window);
|
||||
try {
|
||||
const event = new KeyboardEvent("keydown", {
|
||||
key: "l",
|
||||
code: "KeyL",
|
||||
altKey: true,
|
||||
metaKey: true,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
cell.view.contentDOM.dispatchEvent(event);
|
||||
expect(reformat).toHaveBeenCalledOnce();
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
} finally {
|
||||
uninstall();
|
||||
disposeStub();
|
||||
cell.clear();
|
||||
disposeView(cell);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Copy Path with a notebook tab", () => {
|
||||
it("resolves the notebook tab's path while a cell editor has focus", () => {
|
||||
const paneId = useTabs.getState().activePane;
|
||||
useTabs.setState((s) => ({
|
||||
...s,
|
||||
panes: {
|
||||
...s.panes,
|
||||
[paneId]: {
|
||||
...s.panes[paneId]!,
|
||||
tabs: [
|
||||
{
|
||||
id: "nb-1",
|
||||
input: { kind: "notebook", key: "notebook:/p/a.ipynb", path: "/p/a.ipynb" },
|
||||
preview: false,
|
||||
pinned: false,
|
||||
},
|
||||
],
|
||||
active: "nb-1",
|
||||
mru: ["nb-1"],
|
||||
},
|
||||
},
|
||||
}));
|
||||
const cell = focusedCell();
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
expect(ctrl.activePath()).toBe("/p/a.ipynb");
|
||||
expect(evaluateWhen("textEditorActive", getContext())).toBe(true);
|
||||
} finally {
|
||||
cell.clear();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,8 @@ import {
|
||||
registerOverlay,
|
||||
registerStatusItem,
|
||||
} from "@/workbench/contributions";
|
||||
import { _provideCodePreview, _provideDocumentAttacher, editorsFor } from "@/editor/api";
|
||||
import { _provideCodePreview, _provideCopyPathChooser, _provideDocumentAttacher, editorsFor } from "@/editor/api";
|
||||
import { openCopyPathChooser } from "./copyPathChooser";
|
||||
import { isUntitledUri } from "@/platform/virtualDocs";
|
||||
import { formatDocument } from "@/editor/lsp/format";
|
||||
import { chooserTitle, locationItems, pinToFind } from "@/editor/lsp/navigation";
|
||||
@@ -82,6 +83,7 @@ export function activate(): void | (() => void) {
|
||||
},
|
||||
});
|
||||
_provideDocumentAttacher((path, options) => attachDocument(ctrl.manager, path, options));
|
||||
_provideCopyPathChooser(openCopyPathChooser);
|
||||
_provideCodePreview((path, editable) =>
|
||||
previewExtensions(path, ctrl.manager.settings()?.editor, ctrl.manager.backend, editable),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { getContext, setContext, useContextKeys } from "@/platform/context";
|
||||
import { _setFocusedCellEditor } from "@/editor/api";
|
||||
import { registerLspActions } from "./actions";
|
||||
import { registerInlineCompletionActions } from "./inlineCompletion";
|
||||
import { editorController, useEditorStatus, useTabs } from "@/editor/core/controller";
|
||||
import { initialTabsState } from "@/editor/core/model/tabs";
|
||||
|
||||
const { formatDocument, showIntentions, refactorThis, requestInline, showHint } = vi.hoisted(() => ({
|
||||
formatDocument: vi.fn(),
|
||||
showIntentions: vi.fn(),
|
||||
refactorThis: vi.fn(),
|
||||
requestInline: vi.fn(),
|
||||
showHint: vi.fn(),
|
||||
}));
|
||||
vi.mock("./format", async (original) => ({
|
||||
...(await original<typeof import("./format")>()),
|
||||
formatDocument,
|
||||
}));
|
||||
vi.mock("./intentions", async (original) => ({
|
||||
...(await original<typeof import("./intentions")>()),
|
||||
showIntentions,
|
||||
}));
|
||||
vi.mock("@/editor/refactor", async (original) => ({
|
||||
...(await original<typeof import("@/editor/refactor")>()),
|
||||
refactorThis,
|
||||
}));
|
||||
vi.mock("./inlineCompletion", async (original) => ({
|
||||
...(await original<typeof import("./inlineCompletion")>()),
|
||||
requestInline,
|
||||
}));
|
||||
vi.mock("./hint", async (original) => ({
|
||||
...(await original<typeof import("./hint")>()),
|
||||
showHint,
|
||||
}));
|
||||
|
||||
const ctrl = editorController();
|
||||
let dispose: () => void;
|
||||
beforeAll(() => {
|
||||
const lsp = registerLspActions();
|
||||
const inline = registerInlineCompletionActions();
|
||||
dispose = () => {
|
||||
inline();
|
||||
lsp();
|
||||
};
|
||||
ctrl.start();
|
||||
});
|
||||
afterAll(() => {
|
||||
ctrl.stop();
|
||||
dispose();
|
||||
});
|
||||
afterEach(() => {
|
||||
useTabs.setState(initialTabsState(), true);
|
||||
useEditorStatus.setState({ status: null });
|
||||
useContextKeys.setState({}, true);
|
||||
_setFocusedCellEditor(null);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
/** Mounts the text editor of an open tab (a background text tab, as in a split with a notebook). */
|
||||
async function mountTextEditor(path = "/p/a.ts"): Promise<EditorView> {
|
||||
await ctrl.openFile(path, { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const view = slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
return view;
|
||||
}
|
||||
|
||||
/** A bare editor standing in for a focused notebook cell (the fact CellEditor publishes). */
|
||||
function focusedCell(): { view: EditorView; clear: () => void } {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const view = new EditorView({ doc: "x = 1\nprint(x)\n", parent: host });
|
||||
view.focus();
|
||||
if (!view.hasFocus) throw new Error("the jsdom view did not take focus");
|
||||
_setFocusedCellEditor(view);
|
||||
return {
|
||||
view,
|
||||
clear: () => {
|
||||
_setFocusedCellEditor(null);
|
||||
view.destroy();
|
||||
view.dom.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("editor actions with a focused notebook cell", () => {
|
||||
it("run in the focused cell, not the last text tab", async () => {
|
||||
const textView = await mountTextEditor();
|
||||
const cell = focusedCell();
|
||||
setContext("projectOpen", true);
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
await executeAction("code.reformat");
|
||||
await executeAction("code.showIntentions");
|
||||
await executeAction("refactor.thisMenu");
|
||||
expect(formatDocument).toHaveBeenCalledWith(cell.view, { explicit: true });
|
||||
expect(showIntentions).toHaveBeenCalledWith(cell.view);
|
||||
expect(refactorThis).toHaveBeenCalledWith(cell.view, expect.any(Function));
|
||||
expect(showHint).not.toHaveBeenCalled();
|
||||
// The background text editor was not acted on (it is the view `activeEditor()` holds).
|
||||
expect(formatDocument).not.toHaveBeenCalledWith(textView, { explicit: true });
|
||||
expect(showIntentions).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
cell.clear();
|
||||
hostRemove(textView);
|
||||
}
|
||||
});
|
||||
|
||||
it("keep running in the focused text editor when no cell editor is focused", async () => {
|
||||
const view = await mountTextEditor();
|
||||
setContext("projectOpen", true);
|
||||
view.focus();
|
||||
await vi.waitFor(() => expect(getContext().editorTextFocus).toBe(true));
|
||||
await executeAction("code.reformat");
|
||||
expect(formatDocument).toHaveBeenCalledWith(view, { explicit: true });
|
||||
expect(formatDocument).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("target the focused cell for inline completion", async () => {
|
||||
const textView = await mountTextEditor();
|
||||
const cell = focusedCell();
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
await executeAction("editor.inlineCompletion.trigger");
|
||||
await vi.waitFor(() => expect(showHint).toHaveBeenCalled());
|
||||
expect(showHint).toHaveBeenCalledWith(cell.view, expect.any(String));
|
||||
expect(showHint).not.toHaveBeenCalledWith(textView, expect.anything());
|
||||
} finally {
|
||||
cell.clear();
|
||||
hostRemove(textView);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function hostRemove(view: EditorView): void {
|
||||
const host = view.dom.parentElement;
|
||||
view.destroy();
|
||||
host?.remove();
|
||||
}
|
||||
@@ -2,7 +2,14 @@
|
||||
import { generateActionIcon, isGenerateAction } from "./generate";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { activeEditor, editorsFor, registerSaveParticipant, whenSynced, type TextEditorHandle } from "@/editor/api";
|
||||
import {
|
||||
activeEditor,
|
||||
editorsFor,
|
||||
focusedCellEditor,
|
||||
registerSaveParticipant,
|
||||
whenSynced,
|
||||
type TextEditorHandle,
|
||||
} from "@/editor/api";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { maybeEditorService } from "@/workbench/contributions";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -67,6 +74,13 @@ export const GENERATE_KEY_WHEN = GENERATE_LANGUAGES.map((id) => `editorLangId ==
|
||||
|
||||
function withEditor(run: (view: EditorView) => unknown): Action["run"] {
|
||||
return () => {
|
||||
// While a notebook cell editor has focus it is the editor the action runs in
|
||||
// (the notebook publishes the editor context keys for it), never the last text tab.
|
||||
const cell = focusedCellEditor();
|
||||
if (cell) {
|
||||
void run(cell);
|
||||
return;
|
||||
}
|
||||
const ed = activeEditor();
|
||||
if (!ed) return;
|
||||
void run(ed.view);
|
||||
@@ -439,6 +453,9 @@ export function registerLspActions(): () => void {
|
||||
category: "Refactor",
|
||||
when: "projectOpen",
|
||||
run: ({ ctx }) => {
|
||||
// A focused notebook cell is the editor here, like for Show Context Actions.
|
||||
const cell = focusedCellEditor();
|
||||
if (cell && evaluateWhen(EDITOR_WHEN, ctx)) return refactorThis(cell, startRename);
|
||||
const ed = activeEditor();
|
||||
if (ed && evaluateWhen(EDITOR_WHEN, ctx)) return refactorThis(ed.view, startRename);
|
||||
showNothingHere();
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
type RequestId,
|
||||
unavailableText,
|
||||
} from "@/platform/ipc";
|
||||
import { activeEditor } from "@/editor/api";
|
||||
import { activeEditor, focusedCellEditor } from "@/editor/api";
|
||||
import { docOf, isUnavailable, lspRequest } from "./lsp";
|
||||
import { offsetToPos, rangeToOffsets } from "./positions";
|
||||
import { showHint } from "./hint";
|
||||
@@ -288,7 +288,8 @@ const VISIBLE = `editorTextFocus && ${CONTEXT_KEY}`;
|
||||
|
||||
function onView(run: (view: EditorView) => unknown): Action["run"] {
|
||||
return () => {
|
||||
const view = activeEditor()?.view;
|
||||
// A focused notebook cell editor is the editor (the notebook publishes the editor keys).
|
||||
const view = focusedCellEditor() ?? activeEditor()?.view;
|
||||
if (view) void run(view);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,7 +24,9 @@ import { registerKeyClaim } from "@/platform/keymap";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { copySourceOf } from "@/platform/clipboardSource";
|
||||
import {
|
||||
EDITOR_TAB_MIME,
|
||||
getAgentContextSources,
|
||||
maybeEditorService,
|
||||
notifications,
|
||||
OWNS_FILE_DROP,
|
||||
type AgentContextSource,
|
||||
@@ -100,6 +102,18 @@ type Item =
|
||||
|
||||
const isSection = (item: Item) => item.kind === "section";
|
||||
|
||||
/** The file of an editor tab drag payload (`{paneId, tabId}`), null for virtual and non-file tabs. */
|
||||
const tabFilePath = (payload: string): string | null => {
|
||||
try {
|
||||
const p = JSON.parse(payload) as { paneId?: unknown; tabId?: unknown };
|
||||
if (typeof p.paneId !== "string" || typeof p.tabId !== "string") return null;
|
||||
const input = maybeEditorService()?.tabInput?.(p.paneId, p.tabId);
|
||||
return input?.kind === "file" && input.path && !isVirtualUri(input.path) ? input.path : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const SECTION_TITLES: Record<Section, string> = {
|
||||
command: "Commands",
|
||||
skill: "Skills",
|
||||
@@ -941,17 +955,21 @@ export function Composer(props: ComposerProps) {
|
||||
};
|
||||
}, [addPaths, addImages]);
|
||||
|
||||
// Files and folders dragged from the Project view: the same `@` references.
|
||||
// Files and folders dragged from the Project view, and file tabs dragged from the editor:
|
||||
// the same `@` references.
|
||||
useEffect(() => {
|
||||
const el = boxRef.current;
|
||||
if (!el) return;
|
||||
return registerDropTarget(el, {
|
||||
accepts: (type) => type === FILES_DRAG,
|
||||
accepts: (type, data) => type === FILES_DRAG || (type === EDITOR_TAB_MIME && !!tabFilePath(data.payload)),
|
||||
over: () => setFileOver(true),
|
||||
leave: () => setFileOver(false),
|
||||
drop: (data) => {
|
||||
setFileOver(false);
|
||||
addPaths(data.payload.split("\n").filter(Boolean));
|
||||
if (data.type === EDITOR_TAB_MIME) {
|
||||
const path = tabFilePath(data.payload);
|
||||
if (path) addPaths([path]);
|
||||
} else addPaths(data.payload.split("\n").filter(Boolean));
|
||||
},
|
||||
});
|
||||
}, [addPaths]);
|
||||
|
||||
@@ -7,6 +7,7 @@ import userEvent from "@testing-library/user-event";
|
||||
import { caretOf, setCaret, textOf, typeChars, typeIn } from "./composerTesting";
|
||||
import chipStyles from "./ReferenceChip.module.css";
|
||||
import { FILES_DRAG, dragSession } from "@/ui";
|
||||
import { EDITOR_TAB_MIME, provideEditorService, type EditorService } from "@/workbench/contributions";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
const findFiles = vi.fn();
|
||||
@@ -123,6 +124,32 @@ describe("Composer dropped paths", () => {
|
||||
expect(textOf(box)).toBe("@src/a.ts @src/dir/ ");
|
||||
});
|
||||
|
||||
it("references the file of an editor tab dragged onto it and ignores other tabs", () => {
|
||||
provideEditorService({
|
||||
tabInput: (_pane: string, tab: string) =>
|
||||
tab === "file"
|
||||
? { kind: "file", key: "/p/src/a.ts", path: "/p/src/a.ts" }
|
||||
: { kind: "agentSession", key: "agent:one", data: { task: "one" } },
|
||||
} as unknown as EditorService);
|
||||
const box = renderComposer();
|
||||
const restore = document.elementFromPoint;
|
||||
document.elementFromPoint = () => box;
|
||||
try {
|
||||
act(() => {
|
||||
const other = dragSession({
|
||||
type: EDITOR_TAB_MIME,
|
||||
payload: JSON.stringify({ paneId: "p", tabId: "session" }),
|
||||
});
|
||||
expect(other.drop(0, 0)).toBe(false);
|
||||
const file = dragSession({ type: EDITOR_TAB_MIME, payload: JSON.stringify({ paneId: "p", tabId: "file" }) });
|
||||
expect(file.drop(0, 0)).toBe(true);
|
||||
});
|
||||
} finally {
|
||||
document.elementFromPoint = restore;
|
||||
}
|
||||
expect(textOf(box)).toBe("@src/a.ts ");
|
||||
});
|
||||
|
||||
it("deduplicates live references and allows a deleted reference to be dropped again", () => {
|
||||
const box = renderComposer();
|
||||
drop(box, "/p/src/a.ts\n/p/src/a.ts\n/p/src/dir/");
|
||||
|
||||
@@ -232,7 +232,7 @@ export function activate(): () => void {
|
||||
registerStatusItem({ id: "agents.status", align: "right", priority: 3, title: "Agents", component: AgentsStatus }),
|
||||
registerMenuGroup({
|
||||
id: "agents.send",
|
||||
menus: ["editor", "projectView"],
|
||||
menus: ["editor", "editorTab", "projectView"],
|
||||
order: 80,
|
||||
items: (menu, { paths, dirs }) =>
|
||||
paths.length && !paths.some(isVirtualUri) && agentsHere()
|
||||
@@ -240,7 +240,8 @@ export function activate(): () => void {
|
||||
{
|
||||
kind: "action",
|
||||
action: "agents.sendToAgent",
|
||||
arg: menu === "projectView" ? paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)) : undefined,
|
||||
// The editor sends its selection; a tab or the Project view sends the files.
|
||||
arg: menu === "editor" ? undefined : paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
|
||||
@@ -3,6 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
|
||||
import {
|
||||
dropOnEditor,
|
||||
menuGroupItems,
|
||||
useContributions,
|
||||
useEditorTabTitles,
|
||||
type EditorInput,
|
||||
@@ -595,3 +596,20 @@ describe("the diff of an agent change", () => {
|
||||
expect(backend.openInput.mock.lastCall![0].data.chain).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Send to Agent menus", () => {
|
||||
it("sends the selection from the editor and the files from an editor tab or the Project view", () => {
|
||||
const dispose = activate();
|
||||
try {
|
||||
const send = (menu: "editor" | "editorTab" | "projectView", dirs?: boolean[]) =>
|
||||
menuGroupItems(menu, { paths: ["/p/a.ts", "/p/src"].slice(0, dirs ? 2 : 1), dirs }).find(
|
||||
(i) => "action" in i && i.action === "agents.sendToAgent",
|
||||
);
|
||||
expect(send("editor")).toMatchObject({ arg: undefined });
|
||||
expect(send("editorTab")).toMatchObject({ arg: ["/p/a.ts"] });
|
||||
expect(send("projectView", [false, true])).toMatchObject({ arg: ["/p/a.ts", "/p/src/"] });
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import { _resetI18nForTests, setLocale } from "@/platform/i18n";
|
||||
import { useKeymap } from "@/platform/keymap";
|
||||
import * as ipc from "@/platform/ipc";
|
||||
import { resetDistractionFree, setDistractionFree } from "@/workbench/distractionFree";
|
||||
import { useFullscreen } from "@/workbench/zenMode";
|
||||
import { registerStatusItem, registerToolWindow } from "@/workbench/contributions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { _reloadLayouts, saveLayout } from "@/workbench/toolwindows/layouts";
|
||||
@@ -333,6 +334,19 @@ describe("window-scoped menu labels", () => {
|
||||
resetDistractionFree();
|
||||
});
|
||||
|
||||
it("flips Enter / Exit Zen Mode only while Distraction Free Mode and full screen are both on", () => {
|
||||
const label = () => buildMenuConfig("macos").labels["menu.view.toggleZenMode"];
|
||||
expect(label()).toBe("Enter Zen Mode");
|
||||
setDistractionFree(true);
|
||||
expect(label()).toBe("Enter Zen Mode");
|
||||
useFullscreen.setState({ on: true });
|
||||
expect(label()).toBe("Exit Zen Mode");
|
||||
setDistractionFree(false);
|
||||
expect(label()).toBe("Enter Zen Mode");
|
||||
useFullscreen.setState({ on: false });
|
||||
resetDistractionFree();
|
||||
});
|
||||
|
||||
it("formats Recompile with the active local Java filename across locales", async () => {
|
||||
try {
|
||||
expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile");
|
||||
|
||||
@@ -344,6 +344,14 @@ describe("loose files (LightEdit)", () => {
|
||||
expect(fsReadDir).toHaveBeenCalledWith("/x/a.txt");
|
||||
expect(lightEditOpen).toHaveBeenCalledWith("/x/a.txt");
|
||||
});
|
||||
|
||||
it("opens the folder of a dropped .uproject instead of the file", async () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openPaths(["/work/Game/Game.uproject"], async () => false);
|
||||
expect(windowOpenFiles).not.toHaveBeenCalled();
|
||||
expect(lightEditOpen).not.toHaveBeenCalled();
|
||||
expect(openProject).toHaveBeenCalledWith("/work/Game");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Open Containing Folder as Project", () => {
|
||||
|
||||
@@ -23,6 +23,7 @@ import { useProject } from "@/platform/project";
|
||||
import { syncRemoteRecentMenu } from "@/platform/remote";
|
||||
import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions";
|
||||
import { useDistractionFree } from "@/workbench/distractionFree";
|
||||
import { useFullscreen } from "@/workbench/zenMode";
|
||||
import { javaFileNameOf, menuLabelParams } from "@/workbench/menuLabels";
|
||||
import { orderStatusItems } from "@/workbench/StatusBar";
|
||||
import { statusWidgetRows } from "@/workbench/statusBarWidgets";
|
||||
@@ -278,6 +279,10 @@ export function installMenuBridge(): () => void {
|
||||
useDistractionFree.subscribe((s, prev) => {
|
||||
if (s.active !== prev.active) push();
|
||||
}),
|
||||
// View › Appearance › Enter / Exit Zen Mode also follows full screen.
|
||||
useFullscreen.subscribe((s, prev) => {
|
||||
if (s.on !== prev.on && useDistractionFree.getState().active) push();
|
||||
}),
|
||||
// Window › Hide All Tool Windows reads "Restore Tool Windows" while it would restore them.
|
||||
useToolWindowLayout.subscribe((s, prev) => {
|
||||
if (toolWindowsRestorable(s) !== toolWindowsRestorable(prev)) push();
|
||||
|
||||
@@ -128,14 +128,19 @@ export async function openFiles(files: readonly string[]): Promise<void> {
|
||||
|
||||
const pathIsDir = (path: string) => call(commands.fsReadDir(path)).then(() => true);
|
||||
|
||||
/** A file that names the project around it: dropping it opens that folder, as a double-click would. */
|
||||
const projectMarker = /\.uproject$/i;
|
||||
|
||||
/** Opens dropped paths: files as loose files ({@link openFiles}), the first folder as a project. */
|
||||
export async function openPaths(
|
||||
paths: readonly string[],
|
||||
isDir: (path: string) => Promise<boolean> = pathIsDir,
|
||||
): Promise<void> {
|
||||
const kinds = await Promise.all(paths.map((p) => isDir(p).catch(() => false)));
|
||||
const files = paths.filter((_, i) => !kinds[i]);
|
||||
const dir = paths.find((_, i) => kinds[i]);
|
||||
// An Unreal project is dragged in as its `.uproject`, which names the folder to open.
|
||||
const marker = paths.find((p, i) => !kinds[i] && projectMarker.test(p));
|
||||
const files = paths.filter((p, i) => !kinds[i] && p !== marker);
|
||||
const dir = paths.find((_, i) => kinds[i]) ?? (marker ? dirname(marker) : undefined);
|
||||
await openFiles(files);
|
||||
if (dir) await openProjectWithPolicy(dir);
|
||||
}
|
||||
|
||||
@@ -70,6 +70,56 @@ export function ExtractorSelect({ value, onChange }: { value: ExportFormat; onCh
|
||||
export const copyFormatOf = (extractor: ExportFormat): CopyFormat =>
|
||||
extractor === "csv" ? "csv" : extractor === "onerow" ? "onerow" : "tsv";
|
||||
|
||||
/** The toolbar's extractor; `table` is the whole table to export (`null`: nothing, already reported). */
|
||||
export interface ExtractorMenu {
|
||||
value: ExportFormat;
|
||||
onChange: (f: ExportFormat) => void;
|
||||
table: () => ExportData | null | Promise<ExportData | null>;
|
||||
}
|
||||
|
||||
const PANEL_ENTRIES: ReadonlyArray<{ panel: DataPanel; label: string }> = [
|
||||
{ panel: "record", label: "Show Record View" },
|
||||
{ panel: "value", label: "Open in Value Editor" },
|
||||
{ panel: "aggregates", label: "Show Aggregate View" },
|
||||
];
|
||||
|
||||
/**
|
||||
* The view's entries of the grid's context menu (DataGrip's): the side panels, checked while
|
||||
* shown, then the toolbar's extractor and Export Table to Clipboard when the view has them.
|
||||
*/
|
||||
export function viewMenu(
|
||||
panel: DataPanel | null,
|
||||
onPanelChange: (panel: DataPanel | null) => void,
|
||||
extractor?: ExtractorMenu,
|
||||
): MenuItem[] {
|
||||
const items: MenuItem[] = PANEL_ENTRIES.map(({ panel: p, label }) => ({
|
||||
label,
|
||||
checked: panel === p,
|
||||
run: () => onPanelChange(panel === p ? null : p),
|
||||
}));
|
||||
if (!extractor) return items;
|
||||
return [
|
||||
...items,
|
||||
{ kind: "separator" },
|
||||
{
|
||||
label: "Data Extractor",
|
||||
submenu: EXPORT_FORMATS.map((f) => ({
|
||||
label: f.label,
|
||||
checked: f.id === extractor.value,
|
||||
run: () => extractor.onChange(f.id),
|
||||
})),
|
||||
},
|
||||
{
|
||||
label: "Export Table to Clipboard",
|
||||
icon: "copy",
|
||||
run: () =>
|
||||
void Promise.resolve(extractor.table()).then(
|
||||
(data) => data && writeClipboardText(exportData(extractor.value, data)),
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** The Record / Value / Aggregates panel's toggle (IDEA's "Show Value Editor"). */
|
||||
export function PanelToggle({ panel, onChange }: { panel: DataPanel | null; onChange: (p: DataPanel | null) => void }) {
|
||||
return (
|
||||
@@ -117,6 +167,8 @@ export interface DataViewProps extends Pick<
|
||||
onPanelChange: (panel: DataPanel | null) => void;
|
||||
/** Plain ⌘C's copy format (the toolbar's extractor; TSV by default). */
|
||||
copyFormat?: CopyFormat;
|
||||
/** The toolbar's extractor, also offered in the grid's context menu with the whole table to copy. */
|
||||
extractor?: ExtractorMenu;
|
||||
/** The search bar is shown (the toolbar's search button, ⌘F in the grid). */
|
||||
searchOpen?: boolean;
|
||||
onSearchOpenChange?: (open: boolean) => void;
|
||||
@@ -248,7 +300,11 @@ export function DataView(props: DataViewProps) {
|
||||
driver={props.driver}
|
||||
sort={sort}
|
||||
onSort={onSort}
|
||||
rowMenu={props.rowMenu && ((rows) => props.rowMenu!(rows.map(at)))}
|
||||
rowMenu={(rows) => {
|
||||
const own = props.rowMenu?.(rows.map(at)) ?? [];
|
||||
const view = viewMenu(panel, onPanelChange, props.extractor);
|
||||
return own.length ? [...own, { kind: "separator" }, ...view] : view;
|
||||
}}
|
||||
rowNumber={(r) => (props.firstRowNumber ?? 1) + at(r)}
|
||||
copyFormat={props.copyFormat}
|
||||
onSelectionChange={setRange}
|
||||
|
||||
@@ -954,6 +954,23 @@
|
||||
padding: 2px 4px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.modifyFilter {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.modifyGroup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
height: 22px;
|
||||
padding: 0 6px;
|
||||
color: var(--fg-muted);
|
||||
cursor: default;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.modifyGroup:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
.modifyList {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
|
||||
@@ -1013,3 +1013,75 @@ describe("local filter (#6022)", () => {
|
||||
expect(cities()).toEqual(["Shanghai", "Beijing", "Shenzhen", "Hangzhou"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the data view's context menu (DataGrip)", () => {
|
||||
const columns = [
|
||||
{ name: "id", type: "int" },
|
||||
{ name: "city", type: "text" },
|
||||
];
|
||||
const data = [
|
||||
["1", "Shanghai"],
|
||||
["2", "Beijing"],
|
||||
];
|
||||
const value = (r: number, c: number) => data[r]?.[c] ?? null;
|
||||
|
||||
it("toggles the side panels, switches the extractor and exports the whole table to the clipboard", async () => {
|
||||
const writeText = vi.fn(() => Promise.resolve());
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
const onPanelChange = vi.fn();
|
||||
const onExtractor = vi.fn();
|
||||
const table = () => ({ columns, rows: data, table: "cities", driver: "postgres" as const });
|
||||
const { rerender } = render(
|
||||
<>
|
||||
<DataView
|
||||
columns={columns}
|
||||
rowCount={2}
|
||||
value={value}
|
||||
panel="value"
|
||||
onPanelChange={onPanelChange}
|
||||
extractor={{ value: "csv", onChange: onExtractor, table }}
|
||||
/>
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
const open = () => {
|
||||
fireEvent.mouseDown(screen.getAllByRole("gridcell")[0]!, { button: 0 });
|
||||
fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
|
||||
};
|
||||
open();
|
||||
expect(screen.getByRole("menuitemcheckbox", { name: /Open in Value Editor/ })).toHaveAttribute(
|
||||
"aria-checked",
|
||||
"true",
|
||||
);
|
||||
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /Show Record View/ }));
|
||||
expect(onPanelChange).toHaveBeenLastCalledWith("record");
|
||||
open();
|
||||
// The shown panel's entry hides it.
|
||||
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /Open in Value Editor/ }));
|
||||
expect(onPanelChange).toHaveBeenLastCalledWith(null);
|
||||
|
||||
open();
|
||||
await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: /Export Table to Clipboard/ })));
|
||||
expect(writeText).toHaveBeenCalledWith(exportData("csv", table()));
|
||||
|
||||
open();
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: /Data Extractor/ }));
|
||||
expect(screen.getByRole("menuitemcheckbox", { name: /^CSV/ })).toHaveAttribute("aria-checked", "true");
|
||||
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /SQL Inserts/ }));
|
||||
expect(onExtractor).toHaveBeenCalledWith("sql");
|
||||
|
||||
// Without an extractor (a view with no toolbar one) only the panels are offered.
|
||||
rerender(
|
||||
<>
|
||||
<DataView columns={columns} rowCount={2} value={value} panel={null} onPanelChange={onPanelChange} />
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
open();
|
||||
expect(screen.queryByRole("menuitem", { name: /Export Table to Clipboard/ })).toBeNull();
|
||||
expect(screen.getByRole("menuitemcheckbox", { name: /Show Aggregate View/ })).toHaveAttribute(
|
||||
"aria-checked",
|
||||
"false",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,14 @@
|
||||
* Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { call, commands, type DbColumnInfo, type DbDriver, type DbTableGrant } from "@/platform/ipc";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
type DbColumnInfo,
|
||||
type DbDriver,
|
||||
type DbTableDetails,
|
||||
type DbTableGrant,
|
||||
} from "@/platform/ipc";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import {
|
||||
Button,
|
||||
@@ -14,6 +21,7 @@ import {
|
||||
Input,
|
||||
Popup,
|
||||
Icon,
|
||||
SearchField,
|
||||
Select,
|
||||
T,
|
||||
Tabs,
|
||||
@@ -551,7 +559,8 @@ function ModifyTableDialog(props: ModifyProps) {
|
||||
if (table && !details) void loadDetails(id, schema, table);
|
||||
}, [details, id, schema, table]);
|
||||
if (!table) return <ModifyTableForm {...props} initial={null} />;
|
||||
if (details?.status === "ok") return <ModifyTableForm {...props} initial={details.value.columns} />;
|
||||
if (details?.status === "ok")
|
||||
return <ModifyTableForm {...props} initial={details.value.columns} details={details.value} />;
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
@@ -565,6 +574,63 @@ function ModifyTableDialog(props: ModifyProps) {
|
||||
);
|
||||
}
|
||||
|
||||
/** A read-only row of the Modify Table list (a key, foreign key, index or trigger). */
|
||||
interface ObjectRow {
|
||||
key: string;
|
||||
name: string;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The groups after Columns, as DataGrip lists them: the primary key of the columns as edited,
|
||||
* then the foreign keys, indexes and triggers the table has (shown, not edited here).
|
||||
*/
|
||||
function objectGroups(
|
||||
columns: readonly ColumnDraft[],
|
||||
details: DbTableDetails | null | undefined,
|
||||
): Array<{ id: string; label: string; icon: string; rows: ObjectRow[] }> {
|
||||
const pk = columns.filter((c) => c.primaryKey && !c.dropped).map((c) => c.name);
|
||||
const list = (names: readonly string[]) => `(${names.join(", ")})`;
|
||||
return [
|
||||
{
|
||||
id: "keys",
|
||||
label: "Keys",
|
||||
icon: "db-key",
|
||||
rows: pk.length ? [{ key: "primary", name: "PRIMARY KEY", detail: list(pk) }] : [],
|
||||
},
|
||||
{
|
||||
id: "foreignKeys",
|
||||
label: "Foreign Keys",
|
||||
icon: "db-foreign-key",
|
||||
rows: (details?.foreignKeys ?? []).map((fk, i) => ({
|
||||
key: `fk-${i}`,
|
||||
name: list(fk.columns),
|
||||
detail: `→ ${fk.refTable} ${list(fk.refColumns)}`,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "indexes",
|
||||
label: "Indexes",
|
||||
icon: "db-index",
|
||||
rows: (details?.indexes ?? []).map((ix) => ({
|
||||
key: `ix-${ix.name}`,
|
||||
name: ix.name,
|
||||
detail: `${ix.unique ? "UNIQUE " : ""}${list(ix.columns)}`,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "triggers",
|
||||
label: "Triggers",
|
||||
icon: "db-trigger",
|
||||
rows: (details?.triggers ?? []).map((t) => ({
|
||||
key: `tr-${t.name}`,
|
||||
name: t.name,
|
||||
detail: `${t.timing} ${t.events}`.toUpperCase(),
|
||||
})),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function ModifyTableForm({
|
||||
id,
|
||||
schema,
|
||||
@@ -572,7 +638,8 @@ function ModifyTableForm({
|
||||
focusColumn,
|
||||
addColumn,
|
||||
initial,
|
||||
}: ModifyProps & { initial: DbColumnInfo[] | null }) {
|
||||
details,
|
||||
}: ModifyProps & { initial: DbColumnInfo[] | null; details?: DbTableDetails }) {
|
||||
const driver = driverOf(id);
|
||||
const [name, setName] = useState(table ?? "table_name");
|
||||
const [columns, setColumns] = useState<ColumnDraft[]>(() => {
|
||||
@@ -611,6 +678,28 @@ function ModifyTableForm({
|
||||
}
|
||||
};
|
||||
const locked = !!current && !canAlterColumn(driver, current);
|
||||
// The list's filter (names and types) and its collapsed groups.
|
||||
const [filter, setFilter] = useState("");
|
||||
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
|
||||
const query = filter.trim().toLowerCase();
|
||||
const matches = (...texts: string[]) => !query || texts.some((t) => t.toLowerCase().includes(query));
|
||||
const shownColumns = columns.filter((c) => matches(c.name, c.dataType));
|
||||
const groups = objectGroups(columns, details)
|
||||
.map((g) => ({ ...g, rows: g.rows.filter((r) => matches(r.name, r.detail)) }))
|
||||
.filter((g) => g.rows.length);
|
||||
const toggleGroup = (group: string) =>
|
||||
setCollapsed((c) => {
|
||||
const next = new Set(c);
|
||||
if (!next.delete(group)) next.add(group);
|
||||
return next;
|
||||
});
|
||||
const groupHeader = (group: string, label: string, count: number) => (
|
||||
<div className={styles.modifyGroup} onMouseDown={() => toggleGroup(group)}>
|
||||
<Icon name={collapsed.has(group) ? "chevron-right" : "chevron-down"} size={12} />
|
||||
<span>{tx(label)}</span>
|
||||
<span className={styles.treeType}>{count}</span>
|
||||
</div>
|
||||
);
|
||||
const showGrants = !!table && grantsSupported(driver);
|
||||
const [tab, setTab] = useState<"columns" | "grants">("columns");
|
||||
const title = table ? `Modify Table ${table}` : "Create Table";
|
||||
@@ -672,21 +761,52 @@ function ModifyTableForm({
|
||||
disabled={!current}
|
||||
onClick={remove}
|
||||
/>
|
||||
<SearchField
|
||||
variant="bare"
|
||||
className={styles.modifyFilter}
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
placeholder="Filter by name or type"
|
||||
aria-label="Filter columns"
|
||||
/>
|
||||
</div>
|
||||
<div role="listbox" aria-label={tx("Columns")} className={styles.modifyList}>
|
||||
{columns.map((c) => (
|
||||
<div
|
||||
key={c.key}
|
||||
role="option"
|
||||
aria-selected={c.key === selected}
|
||||
tabIndex={-1}
|
||||
className={styles.modifyItem}
|
||||
data-dropped={c.dropped || undefined}
|
||||
onMouseDown={() => setSelected(c.key)}
|
||||
>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} />
|
||||
<span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span>
|
||||
<span className={styles.treeType}>{c.dataType}</span>
|
||||
<div role="group" aria-label={tx("Columns")}>
|
||||
{groupHeader("columns", "Columns", shownColumns.length)}
|
||||
{!collapsed.has("columns") &&
|
||||
shownColumns.map((c) => (
|
||||
<div
|
||||
key={c.key}
|
||||
role="option"
|
||||
aria-selected={c.key === selected}
|
||||
tabIndex={-1}
|
||||
className={styles.modifyItem}
|
||||
data-dropped={c.dropped || undefined}
|
||||
onMouseDown={() => setSelected(c.key)}
|
||||
>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} />
|
||||
<span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span>
|
||||
<span className={styles.treeType}>{c.dataType}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{groups.map((g) => (
|
||||
<div key={g.id} role="group" aria-label={tx(g.label)}>
|
||||
{groupHeader(g.id, g.label, g.rows.length)}
|
||||
{!collapsed.has(g.id) &&
|
||||
g.rows.map((r) => (
|
||||
<div
|
||||
key={r.key}
|
||||
role="option"
|
||||
aria-selected={false}
|
||||
aria-disabled
|
||||
className={styles.modifyItem}
|
||||
>
|
||||
<Icon name={g.icon} size={16} />
|
||||
<span className={styles.nodeLabel}>{r.name}</span>
|
||||
<span className={styles.treeType}>{r.detail}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -453,9 +453,9 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
}
|
||||
};
|
||||
|
||||
const showExport = async (at: { x: number; y: number }) => {
|
||||
if (!r) return;
|
||||
// What is exported or copied is the whole values, not the starts the page carries.
|
||||
/** The result to export or copy: the whole values, not the starts the page carries. */
|
||||
const exportSource = async (): Promise<ExportData | null> => {
|
||||
if (!r) return null;
|
||||
if (hasCutCells(r)) {
|
||||
try {
|
||||
await loadPage(tab);
|
||||
@@ -466,17 +466,14 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
key: "db-whole-value",
|
||||
});
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
showContextMenu(
|
||||
at,
|
||||
exportMenu(
|
||||
{ columns, rows: rowsOf(r), driver, table: queryTable(text, { driver }) },
|
||||
queryTable(text, { driver }),
|
||||
extractor,
|
||||
),
|
||||
);
|
||||
return { columns, rows: rowsOf(r), driver, table: queryTable(text, { driver }) };
|
||||
};
|
||||
const showExport = async (at: { x: number; y: number }) => {
|
||||
const data = await exportSource();
|
||||
if (data) showContextMenu(at, exportMenu(data, queryTable(text, { driver }), extractor));
|
||||
};
|
||||
|
||||
// Submit / Revert / Go to Column (⌘↩ / ⌥⌘Z / ⌘F12) reach the latest state through the handle, as in the table editor.
|
||||
@@ -635,6 +632,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
panel={panel}
|
||||
onPanelChange={setPanel}
|
||||
copyFormat={copyFormatOf(extractor)}
|
||||
extractor={{ value: extractor, onChange: setExtractor, table: exportSource }}
|
||||
searchOpen={searchOpen}
|
||||
onSearchOpenChange={setSearchOpen}
|
||||
firstRowNumber={(tab.page ?? 0) * (tab.pageSize ?? 0) + 1}
|
||||
|
||||
@@ -440,6 +440,16 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
panel={panel}
|
||||
onPanelChange={setPanel}
|
||||
copyFormat={copyFormatOf(extractor)}
|
||||
extractor={{
|
||||
value: extractor,
|
||||
onChange: setExtractor,
|
||||
table: () => ({
|
||||
columns: gridColumns,
|
||||
rows: page.result.rows,
|
||||
table: ref.table,
|
||||
driver: sourceById(ref.id)?.driver ?? "sqlite",
|
||||
}),
|
||||
}}
|
||||
searchOpen={searchOpen}
|
||||
onSearchOpenChange={setSearchOpen}
|
||||
firstRowNumber={offset + 1}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { ObjectDialogs } from "./ObjectDialogs";
|
||||
import { detailsKey, openDialog, useDatabase } from "./store";
|
||||
|
||||
const column = (name: string, dataType: string, primaryKey = false) => ({
|
||||
name,
|
||||
dataType,
|
||||
nullable: !primaryKey,
|
||||
default: null,
|
||||
primaryKey,
|
||||
});
|
||||
|
||||
function open() {
|
||||
useDatabase.setState({
|
||||
details: {
|
||||
[detailsKey("db", "main", "orders")]: {
|
||||
status: "ok",
|
||||
value: {
|
||||
columns: [column("id", "integer", true), column("customer_id", "integer"), column("note", "text")],
|
||||
indexes: [{ name: "orders_customer", unique: false, columns: ["customer_id"] }],
|
||||
foreignKeys: [
|
||||
{
|
||||
schema: "main",
|
||||
table: "orders",
|
||||
columns: ["customer_id"],
|
||||
refSchema: "main",
|
||||
refTable: "customers",
|
||||
refColumns: ["id"],
|
||||
},
|
||||
],
|
||||
triggers: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
} as never);
|
||||
openDialog({ kind: "modifyTable", id: "db", schema: "main", table: "orders" });
|
||||
render(<ObjectDialogs />);
|
||||
}
|
||||
|
||||
const rows = (group: string) =>
|
||||
within(screen.getByRole("group", { name: group }))
|
||||
.queryAllByRole("option")
|
||||
.map((o) => o.textContent);
|
||||
|
||||
afterEach(() => useDatabase.setState({ dialog: null, details: {} } as never));
|
||||
|
||||
describe("Modify Table's list (DataGrip)", () => {
|
||||
it("groups the columns, keys, foreign keys and indexes, and filters them by name or type", () => {
|
||||
open();
|
||||
expect(rows("Columns")).toEqual(["idinteger", "customer_idinteger", "notetext"]);
|
||||
expect(rows("Keys")).toEqual(["PRIMARY KEY(id)"]);
|
||||
expect(rows("Foreign Keys")).toEqual(["(customer_id)→ customers (id)"]);
|
||||
expect(rows("Indexes")).toEqual(["orders_customer(customer_id)"]);
|
||||
// No triggers: no group.
|
||||
expect(screen.queryByRole("group", { name: "Triggers" })).toBeNull();
|
||||
|
||||
// A group collapses from its header.
|
||||
fireEvent.mouseDown(within(screen.getByRole("group", { name: "Indexes" })).getByText("Indexes"));
|
||||
expect(rows("Indexes")).toEqual([]);
|
||||
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Filter columns" }), { target: { value: "TEXT" } });
|
||||
expect(rows("Columns")).toEqual(["notetext"]);
|
||||
expect(screen.queryByRole("group", { name: "Foreign Keys" })).toBeNull();
|
||||
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Filter columns" }), { target: { value: "customer" } });
|
||||
expect(rows("Columns")).toEqual(["customer_idinteger"]);
|
||||
expect(rows("Foreign Keys")).toEqual(["(customer_id)→ customers (id)"]);
|
||||
});
|
||||
|
||||
it("keeps Keys on the primary key as edited in Create Table", () => {
|
||||
openDialog({ kind: "modifyTable", id: "db", schema: "main", table: null });
|
||||
render(<ObjectDialogs />);
|
||||
expect(rows("Keys")).toEqual(["PRIMARY KEY(id)"]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add Column" }));
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Primary key" }));
|
||||
expect(rows("Keys")).toEqual(["PRIMARY KEY(id, column_2)"]);
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,8 @@ import type * as Ipc from "@/platform/ipc";
|
||||
import { render } from "@testing-library/react";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { IdeEvent, NotebookSnapshot } from "@/bindings";
|
||||
import { focusedCellEditor } from "@/editor/api";
|
||||
import { getContext, useContextKeys } from "@/platform/context";
|
||||
import { CellEditor } from "./CellEditor";
|
||||
import { NotebookSession, notebookBackend } from "./session";
|
||||
|
||||
@@ -25,7 +27,10 @@ vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
onmessage = (_event: unknown) => {};
|
||||
},
|
||||
}));
|
||||
afterEach(() => kernelListeners.clear());
|
||||
afterEach(() => {
|
||||
kernelListeners.clear();
|
||||
useContextKeys.setState({}, true);
|
||||
});
|
||||
|
||||
function snapshot(): NotebookSnapshot {
|
||||
return {
|
||||
@@ -88,6 +93,37 @@ describe("cell editor focus", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("cell editor context keys", () => {
|
||||
it("publishes the editor keys and the focused view while the cell editor has focus", async () => {
|
||||
useContextKeys.setState({}, true);
|
||||
const session = makeSession();
|
||||
await session.load();
|
||||
const { container, unmount } = render(
|
||||
<CellEditor session={session} id="cell-a" source="typed text" type="code" frozen={false} />,
|
||||
);
|
||||
const view = EditorView.findFromDOM(container.querySelector(".cm-editor")!)!;
|
||||
expect(focusedCellEditor()).toBeNull();
|
||||
expect(getContext().textEditorActive).toBeFalsy();
|
||||
view.contentDOM.focus();
|
||||
await vi.waitFor(() => {
|
||||
expect(focusedCellEditor()).toBe(view);
|
||||
expect(getContext().textEditorActive).toBe(true);
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
});
|
||||
view.contentDOM.blur();
|
||||
await vi.waitFor(() => {
|
||||
expect(focusedCellEditor()).toBeNull();
|
||||
expect(getContext().textEditorActive).toBe(false);
|
||||
expect(getContext().editorTextFocus).toBe(false);
|
||||
});
|
||||
view.contentDOM.focus();
|
||||
await vi.waitFor(() => expect(focusedCellEditor()).toBe(view));
|
||||
unmount();
|
||||
expect(focusedCellEditor()).toBeNull();
|
||||
await session.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("cell editor theme", () => {
|
||||
const cssRules = () => [...document.styleSheets].reduce((n, sheet) => n + sheet.cssRules.length, 0);
|
||||
|
||||
|
||||
@@ -12,14 +12,23 @@ import {
|
||||
import { defaultKeymap, indentWithTab } from "@codemirror/commands";
|
||||
import { bracketMatching, indentOnInput, syntaxHighlighting } from "@codemirror/language";
|
||||
import type { NotebookCellDoc } from "@/bindings";
|
||||
import { adjacentEditor, cellEditorExtensions, embeddedEditorExtensions, externalHistory } from "@/editor/api";
|
||||
import {
|
||||
_setFocusedCellEditor,
|
||||
adjacentEditor,
|
||||
cellEditorExtensions,
|
||||
embeddedEditorExtensions,
|
||||
externalHistory,
|
||||
focusedCellEditor,
|
||||
} from "@/editor/api";
|
||||
import { openideaTheme } from "@/editor/core/cm/theme";
|
||||
import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
|
||||
import { selectionMarks } from "@/editor/core/cm/selectionMarks";
|
||||
import { seamlessSelection } from "@/editor/core/cm/selectionLayer";
|
||||
import { multiCaretMouse } from "@/editor/core/cm/multiCaret";
|
||||
import { findLanguageDescription, loadSupport } from "@/editor/core/cm/languages";
|
||||
import { tooltipBounds } from "@/editor/core/cm/setup";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { setContext } from "@/platform/context";
|
||||
import type { CellReveal, NotebookSession } from "./session";
|
||||
import styles from "./Notebook.module.css";
|
||||
|
||||
@@ -74,6 +83,7 @@ export function CellEditor({
|
||||
drawSelection(),
|
||||
selectionMarks,
|
||||
seamlessSelection(),
|
||||
multiCaretMouse,
|
||||
highlightActiveLine(),
|
||||
highlightSpecialChars(),
|
||||
bracketMatching(),
|
||||
@@ -123,8 +133,16 @@ export function CellEditor({
|
||||
),
|
||||
EditorView.updateListener.of((update) => {
|
||||
session.editors.set(id, update.state);
|
||||
// The session puts the caret back here after a backend undo/redo (session.ts history).
|
||||
if (update.focusChanged) session.focusedCell = update.view.hasFocus ? id : null;
|
||||
if (update.focusChanged) {
|
||||
// The session puts the caret back here after a backend undo/redo (session.ts history).
|
||||
session.focusedCell = update.view.hasFocus ? id : null;
|
||||
// While the cell editor has focus the notebook publishes the editor context keys a
|
||||
// text tab does, and the cell's view is what editor actions resolve (@/editor/api,
|
||||
// re-read by editor/core's publishContext and the action resolvers).
|
||||
_setFocusedCellEditor(update.view.hasFocus ? update.view : null);
|
||||
setContext("textEditorActive", update.view.hasFocus);
|
||||
setContext("editorTextFocus", update.view.hasFocus);
|
||||
}
|
||||
if (update.docChanged && update.transactions.some((tr) => !tr.annotation(external))) {
|
||||
session.edit({ type: "setSource", cell: id, source: update.state.doc.toString() });
|
||||
}
|
||||
@@ -150,6 +168,7 @@ export function CellEditor({
|
||||
alive = false;
|
||||
session.editors.set(id, editor.state);
|
||||
if (session.focusedCell === id) session.focusedCell = null;
|
||||
if (focusedCellEditor() === editor) _setFocusedCellEditor(null);
|
||||
view.current = null;
|
||||
editor.destroy();
|
||||
};
|
||||
|
||||
@@ -189,7 +189,7 @@
|
||||
min-height: 80px;
|
||||
max-height: 600px;
|
||||
border: 1px solid var(--border);
|
||||
background: white;
|
||||
background: var(--bg-editor, var(--bg-app));
|
||||
resize: vertical;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useLayoutEffect, useMemo, useRef } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import Anser from "anser";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
import { subscribeTheme } from "@/platform/themeWatch";
|
||||
import { editorService, notifications } from "@/workbench/contributions";
|
||||
import { resolveLink } from "@/features/viewers/markdown/render";
|
||||
import {
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
markdownRoot,
|
||||
resolveMarkdownAttachments,
|
||||
staticOutputDocument,
|
||||
type OutputPalette,
|
||||
} from "./security";
|
||||
import { mimeText, object, own } from "./outputs";
|
||||
import styles from "./Notebook.module.css";
|
||||
@@ -43,8 +45,34 @@ function AnsiText({ text, error = false }: { text: string; error?: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** The output frame's colours: the notebook's own background and the theme's text and table colours. */
|
||||
function readPalette(): OutputPalette {
|
||||
const root = document.documentElement;
|
||||
const css = getComputedStyle(root);
|
||||
const token = (name: string) => css.getPropertyValue(name).trim();
|
||||
return {
|
||||
fg: token("--fg"),
|
||||
bg: token("--bg-editor") || token("--bg-app"),
|
||||
border: token("--border-strong"),
|
||||
headerBg: token("--bg-elev"),
|
||||
scheme: root.dataset.theme === "light" ? "light" : "dark",
|
||||
};
|
||||
}
|
||||
|
||||
/** Tracks the active theme so output frames follow it. */
|
||||
function useOutputPalette(): OutputPalette {
|
||||
const [palette, setPalette] = useState(readPalette);
|
||||
useEffect(() => {
|
||||
const update = () => setPalette(readPalette());
|
||||
update();
|
||||
return subscribeTheme(update);
|
||||
}, []);
|
||||
return palette;
|
||||
}
|
||||
|
||||
function StaticHtml({ html, title }: { html: string; title: string }) {
|
||||
const srcDoc = useMemo(() => staticOutputDocument(html), [html]);
|
||||
const palette = useOutputPalette();
|
||||
const srcDoc = useMemo(() => staticOutputDocument(html, palette), [html, palette]);
|
||||
return (
|
||||
<iframe className={styles.outputFrame} sandbox="" referrerPolicy="no-referrer" srcDoc={srcDoc} title={title} />
|
||||
);
|
||||
|
||||
@@ -40,6 +40,18 @@ describe("static notebook output sanitization", () => {
|
||||
expect(document.querySelector("body div")?.hasAttribute("style")).toBe(false);
|
||||
});
|
||||
|
||||
it("themes the output frame from the supplied palette and ignores unsafe colour values", () => {
|
||||
const palette = { fg: "#d1d3d9", bg: "#191a1c", border: "#40434a", headerBg: "#212326", scheme: "dark" as const };
|
||||
const html = staticOutputDocument("<table><tr><th>a</th></tr></table>", palette);
|
||||
expect(html).toContain("background:#191a1c");
|
||||
expect(html).toContain("color-scheme:dark");
|
||||
expect(html).toContain("border:1px solid #40434a");
|
||||
const hostile = staticOutputDocument("<p>x</p>", { ...palette, bg: "red;}</style><script>alert(1)</script>" });
|
||||
expect(hostile).not.toContain("<script>");
|
||||
expect(hostile).toContain("background:white");
|
||||
expect(staticOutputDocument("<p>x</p>")).toContain("background:white");
|
||||
});
|
||||
|
||||
it("retains safe SVG chart paint, local definitions and raster images but removes active/external SVG", () => {
|
||||
const url = sanitizedSvgUrl(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">
|
||||
<script>alert(1)</script><foreignObject><div>host markup</div></foreignObject>
|
||||
|
||||
@@ -217,9 +217,25 @@ function htmlRoot(html: string, markdown = false): HTMLElement {
|
||||
return root;
|
||||
}
|
||||
|
||||
export function staticOutputDocument(html: string): string {
|
||||
export interface OutputPalette {
|
||||
fg: string;
|
||||
bg: string;
|
||||
border: string;
|
||||
headerBg: string;
|
||||
scheme: "light" | "dark";
|
||||
}
|
||||
|
||||
const CSS_COLOR = /^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%/]+\)|[a-z]+)$/i;
|
||||
|
||||
export function staticOutputDocument(html: string, palette?: OutputPalette): string {
|
||||
const root = htmlRoot(html);
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OUTPUT_CSP}"><style>body{margin:8px;font:13px system-ui,sans-serif;color:#222;background:white;overflow-wrap:anywhere}table{border-collapse:collapse;max-width:100%}th,td{padding:4px 8px;border:1px solid #ddd;text-align:left}pre{white-space:pre-wrap}img{max-width:100%;height:auto}</style></head><body>${root.innerHTML}</body></html>`;
|
||||
const safe = (c: string, fallback: string) => (CSS_COLOR.test(c.trim()) ? c.trim() : fallback);
|
||||
const fg = safe(palette?.fg ?? "", "#222");
|
||||
const bg = safe(palette?.bg ?? "", "white");
|
||||
const border = safe(palette?.border ?? "", "#ddd");
|
||||
const headerBg = safe(palette?.headerBg ?? "", "transparent");
|
||||
const scheme = palette?.scheme ?? "light";
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OUTPUT_CSP}"><style>body{margin:8px;font:13px system-ui,sans-serif;color:${fg};background:${bg};color-scheme:${scheme};overflow-wrap:anywhere}table{border-collapse:collapse;max-width:100%}th,td{padding:4px 8px;border:1px solid ${border};text-align:left}th{background:${headerBg}}pre{white-space:pre-wrap}img{max-width:100%;height:auto}</style></head><body>${root.innerHTML}</body></html>`;
|
||||
}
|
||||
|
||||
const markdown = new Marked({ gfm: true }).use(mathExtension());
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
MarketPlugin,
|
||||
PluginIcon as PluginIconData,
|
||||
PluginInfo,
|
||||
PluginNetSetting,
|
||||
PluginStatus,
|
||||
} from "@/bindings";
|
||||
import {
|
||||
@@ -56,6 +57,8 @@ import {
|
||||
setAllInstalledEnabled,
|
||||
setPluginCapability,
|
||||
revokePluginNetHost,
|
||||
approvePluginNetSetting,
|
||||
forgetPluginNetSetting,
|
||||
setPluginEnabled,
|
||||
uninstallPlugin,
|
||||
updateAllPlugins,
|
||||
@@ -567,7 +570,7 @@ function ProgramPermission({ plugin, cap, disabled }: { plugin: PluginInfo; cap:
|
||||
}
|
||||
|
||||
function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean }) {
|
||||
if (plugin.capabilities.length === 0 && plugin.netHosts.length === 0) {
|
||||
if (plugin.capabilities.length === 0 && plugin.netHosts.length === 0 && plugin.netSettings.length === 0) {
|
||||
return (
|
||||
<div className={styles.muted}>
|
||||
<T>No special permissions.</T>
|
||||
@@ -600,10 +603,73 @@ function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean })
|
||||
{plugin.netHosts.map((host) => (
|
||||
<NetHostRow key={host} plugin={plugin} host={host} disabled={busy || !confirmed} />
|
||||
))}
|
||||
{plugin.netSettings.map((entry) => (
|
||||
<NetSettingRow
|
||||
key={`${entry.setting}:${entry.http}`}
|
||||
plugin={plugin}
|
||||
entry={entry}
|
||||
disabled={busy || !confirmed}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
/** A host a `net:setting:<key>` grant approved in Settings, or the pending one to approve. */
|
||||
function NetSettingRow({
|
||||
plugin,
|
||||
entry,
|
||||
disabled,
|
||||
}: {
|
||||
plugin: PluginInfo;
|
||||
entry: PluginNetSetting;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
const label = entry.http ? `net.http:setting:${entry.setting}` : `net:setting:${entry.setting}`;
|
||||
const pending = entry.pending;
|
||||
return (
|
||||
<li className={styles.capabilityItem}>
|
||||
<div className={styles.capabilityHeader}>
|
||||
<span className={styles.mono}>{label}</span>
|
||||
<Badge tone={RISK_LABEL.medium.tone}>{RISK_LABEL.medium.label}</Badge>
|
||||
</div>
|
||||
{pending ? (
|
||||
<>
|
||||
<p className={styles.capabilityDescription}>
|
||||
{entry.http
|
||||
? tx`The “${entry.setting}” setting now holds ${entry.pending}. Approving connects over unencrypted HTTP.`
|
||||
: tx`The “${entry.setting}” setting now holds ${entry.pending}. Approve it to let the plugin connect.`}
|
||||
</p>
|
||||
<div className={styles.programPermission}>
|
||||
<Button
|
||||
disabled={disabled}
|
||||
onClick={() => void approvePluginNetSetting(plugin.id, entry.setting, entry.http, pending)}
|
||||
>
|
||||
{tx("Approve")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
entry.host && (
|
||||
<>
|
||||
<p className={styles.capabilityDescription}>
|
||||
{tx`The host set in the “${entry.setting}” setting, on any port. Remove it to leave it unapproved.`}
|
||||
</p>
|
||||
<div className={styles.programPermission}>
|
||||
<Button
|
||||
disabled={disabled}
|
||||
onClick={() => void forgetPluginNetSetting(plugin.id, entry.setting, entry.http)}
|
||||
>
|
||||
{tx("Remove")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** The agent a `java.agent` grant loads: jar, args, and any contributed JVM options. */
|
||||
function JavaAgentDetail({ plugin, cap, disabled }: { plugin: PluginInfo; cap: CapabilityInfo; disabled: boolean }) {
|
||||
const agent = plugin.javaAgent;
|
||||
|
||||
@@ -80,6 +80,7 @@ function plugin(partial: Partial<PluginInfo> & Pick<PluginInfo, "id">): PluginIn
|
||||
hasCode: true,
|
||||
capabilities: [],
|
||||
netHosts: [],
|
||||
netSettings: [],
|
||||
contributions: [],
|
||||
activation: [],
|
||||
warnings: [],
|
||||
@@ -1784,6 +1785,42 @@ describe("marketplace", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("lists the host of a net:setting grant with revoke and a pending one with approve", async () => {
|
||||
const user = userEvent.setup();
|
||||
const base = createMemoryPluginsBackend([
|
||||
plugin({
|
||||
id: "p",
|
||||
name: "GitLab bridge",
|
||||
netSettings: [
|
||||
{ setting: "server", http: false, host: "jira.corp.example", pending: null },
|
||||
{ setting: "server", http: true, host: null, pending: "intra.example" },
|
||||
],
|
||||
capabilities: [
|
||||
{ id: "net:setting:server", risk: "medium", description: "Connect", optional: true, granted: true },
|
||||
{ id: "net.http:setting:server", risk: "medium", description: "Connect", optional: true, granted: true },
|
||||
],
|
||||
}),
|
||||
]);
|
||||
const approveNetSetting = vi.fn((id: string, setting: string, http: boolean, host: string) =>
|
||||
base.approveNetSetting(id, setting, http, host),
|
||||
);
|
||||
const forgetNetSetting = vi.fn((id: string, setting: string, http: boolean) =>
|
||||
base.forgetNetSetting(id, setting, http),
|
||||
);
|
||||
setPluginsBackend({ ...base, approveNetSetting, forgetNetSetting });
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
|
||||
await screen.findAllByText("net:setting:server");
|
||||
expect(screen.getByText(/The host set in the “server” setting, on any port\./)).toBeInTheDocument();
|
||||
expect(screen.getByText(/The “server” setting now holds intra\.example\./)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Approving connects over unencrypted HTTP\./)).toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "Approve" }));
|
||||
await waitFor(() => expect(approveNetSetting).toHaveBeenCalledWith("p", "server", true, "intra.example"));
|
||||
// Both transports are approved now; the HTTPS row comes first.
|
||||
await user.click((await screen.findAllByRole("button", { name: "Remove" }))[0]!);
|
||||
await waitFor(() => expect(forgetNetSetting).toHaveBeenCalledWith("p", "server", false));
|
||||
});
|
||||
|
||||
it("shows the Java agent next to the java.agent permission", async () => {
|
||||
setPluginsBackend(
|
||||
createMemoryPluginsBackend([
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import type { ComponentType } from "react";
|
||||
import { MessagesHost } from "@/workbench/messages";
|
||||
import { SettingsFormContext, useSettingsPages } from "@/workbench/contributions";
|
||||
import { useSettingsFormFor } from "@/features/settings/components/context";
|
||||
import {
|
||||
applySettings,
|
||||
closeSettings,
|
||||
openSettings,
|
||||
resetPage,
|
||||
@@ -64,6 +67,11 @@ const declaration: SettingsDecl = {
|
||||
{ key: "name", title: "Name", type: "string", default: "" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "server",
|
||||
title: "Server",
|
||||
properties: [{ key: "server", title: "Server", type: "string", default: "" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
let dispose: () => void;
|
||||
@@ -174,6 +182,151 @@ it("does not run a command when applying settings fails", async () => {
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a host value that is not a host when it is staged", async () => {
|
||||
const { usePlugins } = await import("../store");
|
||||
act(() => {
|
||||
usePlugins.setState({
|
||||
plugins: [
|
||||
{
|
||||
id: "example.helper",
|
||||
name: "Helper",
|
||||
capabilities: [
|
||||
{ id: "net:setting:server", risk: "medium", description: "Connect", optional: true, granted: true },
|
||||
],
|
||||
} as never,
|
||||
],
|
||||
});
|
||||
});
|
||||
render(<Harness page="server" />);
|
||||
const field = screen.getByRole("textbox", { name: "Server" });
|
||||
fireEvent.change(field, { target: { value: "not a host!" } });
|
||||
await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent(/Enter a host/));
|
||||
expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toEqual({});
|
||||
fireEvent.change(field, { target: { value: "jira.corp.example" } });
|
||||
await waitFor(() => expect(screen.queryByRole("alert")).toBeNull());
|
||||
expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toMatchObject({
|
||||
"example.helper": { server: "jira.corp.example" },
|
||||
});
|
||||
});
|
||||
|
||||
it("asks about the host when a net:setting value is applied; deny leaves it unapproved", async () => {
|
||||
const user = userEvent.setup();
|
||||
const approveNetSetting = vi.fn(async () => ({}) as never);
|
||||
setPluginsBackend({ ...createMemoryPluginsBackend([]), approveNetSetting });
|
||||
const { usePlugins } = await import("../store");
|
||||
const plugin = {
|
||||
id: "example.helper",
|
||||
name: "Helper",
|
||||
version: "1.0.0",
|
||||
description: "",
|
||||
authors: [],
|
||||
homepage: null,
|
||||
changeNotes: null,
|
||||
icon: null,
|
||||
javaAgent: null,
|
||||
source: "installed",
|
||||
path: "/plugins/helper",
|
||||
enabled: true,
|
||||
status: "active",
|
||||
error: null,
|
||||
hasCode: true,
|
||||
capabilities: [{ id: "net:setting:server", risk: "medium", description: "Connect", optional: true, granted: true }],
|
||||
netHosts: [],
|
||||
netSettings: [],
|
||||
contributions: [],
|
||||
activation: [],
|
||||
warnings: [],
|
||||
stats: {
|
||||
activations: 0,
|
||||
activationMs: 0,
|
||||
calls: 0,
|
||||
errors: 0,
|
||||
maxCallMs: 0,
|
||||
p95CallMs: 0,
|
||||
slowCalls: 0,
|
||||
crashes: 0,
|
||||
reclaims: 0,
|
||||
},
|
||||
publisher: null,
|
||||
previousVersion: null,
|
||||
depends: [],
|
||||
dependents: [],
|
||||
extensionPoints: [],
|
||||
};
|
||||
act(() => {
|
||||
usePlugins.setState({ plugins: [plugin as never] });
|
||||
});
|
||||
render(
|
||||
<>
|
||||
<MessagesHost />
|
||||
<Harness page="server" />
|
||||
</>,
|
||||
);
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Server" }), {
|
||||
target: { value: "https://jira.corp.example/" },
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toMatchObject({
|
||||
"example.helper": { server: "https://jira.corp.example/" },
|
||||
}),
|
||||
);
|
||||
// Applying asks; the answer resolves the apply.
|
||||
const applying = applySettings();
|
||||
await user.click(await screen.findByRole("button", { name: "Deny" }));
|
||||
await act(() => applying);
|
||||
await waitFor(() => expect(approveNetSetting).not.toHaveBeenCalled());
|
||||
// The value itself was saved; only the approval was withheld.
|
||||
expect(useProject.getState().settings).toMatchObject({
|
||||
plugins: { "example.helper": { server: "https://jira.corp.example/" } },
|
||||
});
|
||||
});
|
||||
|
||||
it("records the approval when the applied host is allowed, and forgets it when cleared", async () => {
|
||||
const user = userEvent.setup();
|
||||
const approveNetSetting = vi.fn(async () => ({}) as never);
|
||||
const forgetNetSetting = vi.fn(async () => ({}) as never);
|
||||
setPluginsBackend({ ...createMemoryPluginsBackend([]), approveNetSetting, forgetNetSetting });
|
||||
const { usePlugins } = await import("../store");
|
||||
const plugin = {
|
||||
id: "example.helper",
|
||||
name: "Helper",
|
||||
netSettings: [],
|
||||
capabilities: [{ id: "net:setting:server", risk: "medium", description: "Connect", optional: true, granted: true }],
|
||||
};
|
||||
act(() => {
|
||||
usePlugins.setState({ plugins: [plugin as never] });
|
||||
});
|
||||
render(
|
||||
<>
|
||||
<MessagesHost />
|
||||
<Harness page="server" />
|
||||
</>,
|
||||
);
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Server" }), { target: { value: "jira.corp.example" } });
|
||||
await waitFor(() =>
|
||||
expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toMatchObject({
|
||||
"example.helper": { server: "jira.corp.example" },
|
||||
}),
|
||||
);
|
||||
const applying = applySettings();
|
||||
await user.click(await screen.findByRole("button", { name: "Allow" }));
|
||||
await act(() => applying);
|
||||
await waitFor(() =>
|
||||
expect(approveNetSetting).toHaveBeenCalledWith("example.helper", "server", false, "jira.corp.example"),
|
||||
);
|
||||
|
||||
// Clearing the value forgets the approval without a dialog.
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Server" }), { target: { value: "" } });
|
||||
await waitFor(() =>
|
||||
expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toMatchObject({
|
||||
"example.helper": { server: "" },
|
||||
}),
|
||||
);
|
||||
await act(() => applySettings());
|
||||
await waitFor(() => expect(forgetNetSetting).toHaveBeenCalledWith("example.helper", "server", false));
|
||||
expect(screen.queryByText(/Allow Helper to connect/)).toBeNull();
|
||||
});
|
||||
|
||||
it("lists the plugin's declared secrets on its settings page", async () => {
|
||||
setPluginsBackend({
|
||||
...createMemoryPluginsBackend([]),
|
||||
|
||||
@@ -65,6 +65,12 @@ export interface PluginsBackend {
|
||||
pickProgram(): Promise<string | null>;
|
||||
setCapability(id: string, capability: string, granted: boolean): Promise<PluginInfo>;
|
||||
revokeNetHost(id: string, host: string): Promise<PluginInfo>;
|
||||
/** The host a `net:setting:` grant derives from `value` (a bare host or a URL); an error refuses it. */
|
||||
netSettingHost(id: string, setting: string, value: string): Promise<string>;
|
||||
/** Approves `host` for a `net:setting:` grant; refused when the setting no longer holds it. */
|
||||
approveNetSetting(id: string, setting: string, http: boolean, host: string): Promise<PluginInfo>;
|
||||
/** Drops the approved host of a `net:setting:` grant (revoked, or the setting cleared). */
|
||||
forgetNetSetting(id: string, setting: string, http: boolean): Promise<PluginInfo>;
|
||||
/** Validated assets (icon theme mapping and SVGs) whose id starts with `prefix`. */
|
||||
assets(pluginId: string, prefix: string): Promise<[string, string][]>;
|
||||
/** `language` / `file` / `view` activation events. */
|
||||
@@ -232,6 +238,9 @@ export const tauriPluginsBackend: PluginsBackend = {
|
||||
pickProgram: () => choosePath({ directory: false, title: tx("Choose plugin executable") }),
|
||||
setCapability: (id, capability, granted) => call(commands.pluginSetCapability(id, capability, granted)),
|
||||
revokeNetHost: (id, host) => call(commands.pluginRevokeNetHost(id, host)),
|
||||
netSettingHost: (id, setting, value) => call(commands.pluginNetSettingHost(id, setting, value)),
|
||||
approveNetSetting: (id, setting, http, host) => call(commands.pluginApproveNetSetting(id, setting, http, host)),
|
||||
forgetNetSetting: (id, setting, http) => call(commands.pluginForgetNetSetting(id, setting, http)),
|
||||
assets: (pluginId, prefix) => call(commands.pluginAssets(pluginId, prefix)),
|
||||
activationEvent: async (kind, value) => {
|
||||
await call(commands.pluginActivationEvent(kind, value));
|
||||
@@ -481,6 +490,7 @@ function samplePlugins(): PluginInfo[] {
|
||||
error: null,
|
||||
capabilities: [],
|
||||
netHosts: [],
|
||||
netSettings: [],
|
||||
contributions: [],
|
||||
activation: [],
|
||||
warnings: [],
|
||||
@@ -663,6 +673,38 @@ export function createMemoryPluginsBackend(
|
||||
emit({ type: "commandsChanged" });
|
||||
return { ...p };
|
||||
},
|
||||
netSettingHost: async (_id, _setting, value) => {
|
||||
let host = value.trim();
|
||||
if (host.includes("://"))
|
||||
host = host
|
||||
.replace(/^[a-z][a-z0-9+.-]*:\/\//i, "")
|
||||
.replace(/[/?#].*$/, "")
|
||||
.replace(/.*@/, "");
|
||||
host = host.replace(/:\d+$/, "").replace(/\.$/, "").toLowerCase();
|
||||
if (
|
||||
!host ||
|
||||
host.includes("*") ||
|
||||
!/^[a-z0-9.-]+$/.test(host) ||
|
||||
host.split(".").some((l) => !l || /[^a-z0-9-]/.test(l))
|
||||
)
|
||||
throw new IpcError({ kind: "invalidInput", message: `${value}: not a host (example.com) or a URL` });
|
||||
return host;
|
||||
},
|
||||
approveNetSetting: async (id, setting, http, host) => {
|
||||
const p = find(id);
|
||||
p.netSettings = [
|
||||
...p.netSettings.filter((n) => n.setting !== setting || n.http !== http),
|
||||
{ setting, http, host, pending: null },
|
||||
];
|
||||
emit({ type: "commandsChanged" });
|
||||
return { ...p };
|
||||
},
|
||||
forgetNetSetting: async (id, setting, http) => {
|
||||
const p = find(id);
|
||||
p.netSettings = p.netSettings.filter((n) => n.setting !== setting || n.http !== http);
|
||||
emit({ type: "commandsChanged" });
|
||||
return { ...p };
|
||||
},
|
||||
assets: async () => [],
|
||||
activationEvent: async () => {},
|
||||
catalog: async () => catalog.map((c) => ({ ...c })),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** IDE-rendered plugin settings; every control edits the dialog's staged form. */
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { tx, VerbatimTextContext } from "@/platform/i18n";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { Button, Checkbox, IconButton, Input, Select, T } from "@/ui";
|
||||
import { registerSettingsPages, useSettingsForm } from "@/workbench/contributions";
|
||||
import { pluginsBackend } from "./backend";
|
||||
@@ -236,10 +237,19 @@ function accepts(s: SettingSchema, value: unknown): boolean {
|
||||
|
||||
function SettingControl({ pluginId, s }: { pluginId: string; s: SettingSchema }) {
|
||||
const [invalid, setInvalid] = useState(false);
|
||||
const [hostInvalid, setHostInvalid] = useState(false);
|
||||
const form = useSettingsForm();
|
||||
const all = form.useValue("plugins") as PluginSettings | undefined;
|
||||
const stored = all?.[pluginId]?.[s.key];
|
||||
const value = accepts(s, stored) ? stored : s.default;
|
||||
// A `net:setting:<key>` grant takes its host from this setting: the value is
|
||||
// checked when it is staged, and its host is asked about when it is applied
|
||||
// (#3809). Only granted transports are asked about.
|
||||
const transports = netSettingTransports(pluginId, s.key);
|
||||
const [initialRaw] = useState(() => (typeof stored === "string" ? stored : ""));
|
||||
const applied = form.useExternal(`net-setting:${s.key}`, initialRaw, (raw) =>
|
||||
applyNetSettingValue(pluginId, s.key, transports, raw),
|
||||
);
|
||||
const control = (
|
||||
<ValueControl
|
||||
s={s}
|
||||
@@ -249,7 +259,28 @@ function SettingControl({ pluginId, s }: { pluginId: string; s: SettingSchema })
|
||||
setInvalid(!valid);
|
||||
// Keep the chosen value even when it equals the default: false and ""
|
||||
// are real plugin settings, not "remove the override".
|
||||
if (valid) form.setMapEntry("plugins", [pluginId, s.key], v);
|
||||
if (!valid) return;
|
||||
if (!transports.length || typeof v !== "string") {
|
||||
setHostInvalid(false);
|
||||
form.setMapEntry("plugins", [pluginId, s.key], v);
|
||||
if (transports.length && v === null) applied.set(""); // cleared: forget on apply
|
||||
return;
|
||||
}
|
||||
if (v.trim() === "") {
|
||||
setHostInvalid(false);
|
||||
form.setMapEntry("plugins", [pluginId, s.key], v);
|
||||
applied.set(v); // cleared: forget on apply
|
||||
return;
|
||||
}
|
||||
// A host value is refused before it is staged.
|
||||
void pluginsBackend()
|
||||
.netSettingHost(pluginId, s.key, v.trim())
|
||||
.then(() => {
|
||||
setHostInvalid(false);
|
||||
form.setMapEntry("plugins", [pluginId, s.key], v);
|
||||
applied.set(v);
|
||||
})
|
||||
.catch(() => setHostInvalid(true));
|
||||
}}
|
||||
/>
|
||||
);
|
||||
@@ -276,10 +307,76 @@ function SettingControl({ pluginId, s }: { pluginId: string; s: SettingSchema })
|
||||
<T>The value exceeds this setting’s limits.</T>
|
||||
</p>
|
||||
)}
|
||||
{hostInvalid && (
|
||||
<p role="alert" className={styles.error}>
|
||||
<T>Enter a host (example.com) or a URL (https://example.com/).</T>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The transports (`false`: HTTPS/loopback, `true`: plain HTTP) of the
|
||||
* plugin's granted `net:setting:<key>` grants for this settings key. */
|
||||
function netSettingTransports(pluginId: string, key: string): boolean[] {
|
||||
const plugin = usePlugins.getState().plugins.find((p) => p.id === pluginId);
|
||||
const transports: boolean[] = [];
|
||||
for (const cap of plugin?.capabilities ?? []) {
|
||||
const match = /^(net(?:\.http)?):setting:(.+)$/.exec(cap.id);
|
||||
if (match?.[2] === key && cap.granted) transports.push(match[1] === "net.http");
|
||||
}
|
||||
return transports;
|
||||
}
|
||||
|
||||
/**
|
||||
* The value was applied in Settings: the host it names is approved here or
|
||||
* never — Deny is the default, and a value that arrives any other way stays
|
||||
* pending in the plugin's permissions. Clearing the setting forgets the
|
||||
* approval (#3809).
|
||||
*/
|
||||
async function applyNetSettingValue(
|
||||
pluginId: string,
|
||||
key: string,
|
||||
transports: boolean[],
|
||||
raw: unknown,
|
||||
): Promise<string> {
|
||||
const value = typeof raw === "string" ? raw.trim() : "";
|
||||
const backend = pluginsBackend();
|
||||
if (!value || !transports.length) {
|
||||
for (const http of transports) await backend.forgetNetSetting(pluginId, key, http);
|
||||
return value;
|
||||
}
|
||||
const host = await backend.netSettingHost(pluginId, key, value);
|
||||
const name = usePlugins.getState().plugins.find((p) => p.id === pluginId)?.name ?? pluginId;
|
||||
for (const http of transports) {
|
||||
const entry = usePlugins
|
||||
.getState()
|
||||
.plugins.find((p) => p.id === pluginId)
|
||||
?.netSettings.find((n) => n.setting === key && n.http === http);
|
||||
if (entry?.host === host) continue; // the host is already the approved one
|
||||
const answer = await ask({
|
||||
title: tx`Allow ${name} to connect to ${host}?`,
|
||||
body: [
|
||||
tx`This host comes from the plugin's “${key}” setting.`,
|
||||
" ",
|
||||
http
|
||||
? tx("The connection is unencrypted HTTP: anyone on the network can read it.")
|
||||
: tx("This allows this exact host on any port; subdomains need separate permission."),
|
||||
" ",
|
||||
tx("Deny leaves the host unapproved; you can approve it any time in the plugin's permissions."),
|
||||
],
|
||||
buttons: [
|
||||
{ id: "allow", label: http ? tx("Allow unencrypted HTTP") : tx("Allow") },
|
||||
{ id: "deny", label: tx("Deny"), primary: true },
|
||||
],
|
||||
cancel: false,
|
||||
icon: "question",
|
||||
});
|
||||
if (answer.button === "allow") await backend.approveNetSetting(pluginId, key, http, host);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function PageAction({ pluginId, action }: { pluginId: string; action: SettingsAction }) {
|
||||
const form = useSettingsForm();
|
||||
const lock = useRef(false);
|
||||
|
||||
@@ -211,6 +211,20 @@ export function revokePluginNetHost(id: string, host: string): Promise<boolean>
|
||||
return withBusy(id, tx`Could not revoke ${host} for ${name}`, () => pluginsBackend().revokeNetHost(id, host));
|
||||
}
|
||||
|
||||
export function approvePluginNetSetting(id: string, setting: string, http: boolean, host: string): Promise<boolean> {
|
||||
const name = nameOf(id);
|
||||
return withBusy(id, tx`Could not approve the host of the ${setting} setting for ${name}`, () =>
|
||||
pluginsBackend().approveNetSetting(id, setting, http, host),
|
||||
);
|
||||
}
|
||||
|
||||
export function forgetPluginNetSetting(id: string, setting: string, http: boolean): Promise<boolean> {
|
||||
const name = nameOf(id);
|
||||
return withBusy(id, tx`Could not revoke the host of the ${setting} setting for ${name}`, () =>
|
||||
pluginsBackend().forgetNetSetting(id, setting, http),
|
||||
);
|
||||
}
|
||||
|
||||
export async function refreshCatalog(): Promise<void> {
|
||||
try {
|
||||
usePlugins.setState({ catalog: await pluginsBackend().catalog(), catalogError: null });
|
||||
|
||||
@@ -21,9 +21,12 @@ export function useProjectTitleMenu(): { label: string; items: MenuItem[] } {
|
||||
const mode = useProjectTree((s) => s.mode);
|
||||
const scope = useProjectTree((s) => s.scope);
|
||||
const unity = useProjectTree((s) => s.unity);
|
||||
const unreal = useProjectTree((s) => s.unreal);
|
||||
// The engine panes only exist in a project of that engine.
|
||||
const available = (id: string) => (id !== "unity" || Boolean(unity)) && (id !== "unreal" || Boolean(unreal));
|
||||
// User scopes (Settings › Scopes) follow the built-in panes, as in IDEA.
|
||||
const scopes = userScopes(useProject((s) => (s.settings as { scopes?: unknown } | null)?.scopes));
|
||||
const items: MenuItem[] = VIEW_MODES.filter(([id]) => id !== "unity" || unity).map(([id, label]) => ({
|
||||
const items: MenuItem[] = VIEW_MODES.filter(([id]) => available(id)).map(([id, label]) => ({
|
||||
id,
|
||||
label,
|
||||
checked: id === mode,
|
||||
|
||||
@@ -605,7 +605,7 @@ export function ProjectView() {
|
||||
const rootNode = m.roots[0];
|
||||
if (!rootNode) return;
|
||||
setSelection(new Set([rootNode.key]), rootNode.key);
|
||||
showContextMenu(e, contextMenuItems([rootNode]));
|
||||
showContextMenu(e, contextMenuItems([rootNode], { x: e.clientX, y: e.clientY }));
|
||||
return;
|
||||
}
|
||||
const nodes = [...sel].map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.placeholder);
|
||||
@@ -614,7 +614,7 @@ export function ProjectView() {
|
||||
// Contributed groups may read the file first (bounded wait).
|
||||
const at = { x: e.clientX, y: e.clientY };
|
||||
void prepareMenuGroups("projectView", menuGroupContext(target)).then(() =>
|
||||
showContextMenu(at, contextMenuItems(target)),
|
||||
showContextMenu(at, contextMenuItems(target, at)),
|
||||
);
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -8,6 +8,11 @@ import { registerMenuGroup } from "@/workbench/contributions";
|
||||
import { contextMenuItems, keyLabel, revealLabel } from "./contextMenu";
|
||||
import type { ProjectNode } from "./model";
|
||||
import { useProjectTree } from "./store";
|
||||
import { closePopup, useLspPopup } from "@/editor/lsp/popupStore";
|
||||
import { _provideCopyPathChooser } from "@/editor/api";
|
||||
import { openCopyPathChooser } from "@/editor/core/copyPathChooser";
|
||||
|
||||
_provideCopyPathChooser(openCopyPathChooser);
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/ipc")>()),
|
||||
@@ -79,6 +84,7 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closePopup();
|
||||
disposers.forEach((d) => d());
|
||||
useProject.setState({ project: null, settings: null });
|
||||
useProjectTree.setState({ root: null });
|
||||
@@ -147,38 +153,56 @@ describe("project view context menu", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("lists contributed links in Copy Path/Reference…", () => {
|
||||
/** Runs Copy Path/Reference… and returns the chooser's rows as `label: preview`. */
|
||||
const chooser = (items: MenuItem[]) => {
|
||||
const item = resolveMenuItems(items).find((r) => r.label === "Copy Path/Reference…");
|
||||
expect(item?.submenu).toBeUndefined();
|
||||
item!.run!();
|
||||
const popup = useLspPopup.getState().popup;
|
||||
return popup?.kind === "list" ? popup.items.map((i) => `${i.label}: ${i.preview}`) : undefined;
|
||||
};
|
||||
|
||||
it("previews each way Copy Path/Reference… copies the selection, contributed links included", () => {
|
||||
disposers.push(
|
||||
registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: (_menu, ctx) => [
|
||||
{ label: `Link ${ctx.paths.join()} ${ctx.dirs?.join()}`, verbatim: true, run: () => undefined },
|
||||
{
|
||||
id: "test.link",
|
||||
label: "Link",
|
||||
verbatim: true,
|
||||
preview: `${ctx.paths.join()} ${ctx.dirs?.join()}`,
|
||||
run: () => undefined,
|
||||
},
|
||||
// Without a preview a contribution has nothing to show in the chooser.
|
||||
{ id: "test.bare", label: "Bare", run: () => undefined },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(sub(contextMenuItems([node("/p/src", true)]), "Copy Path/Reference…")).toEqual([
|
||||
"Absolute Path",
|
||||
"File Name",
|
||||
"Path From Content Root",
|
||||
"-",
|
||||
"Link /p/src true",
|
||||
expect(chooser(contextMenuItems([node("/p/src", true), node("/p/src/a.ts")], { x: 10, y: 20 }))).toEqual([
|
||||
"Absolute Path: /p/src\n/p/src/a.ts",
|
||||
"File Name: src\na.ts",
|
||||
"Path From Content Root: src\nsrc/a.ts",
|
||||
"Link: /p/src,/p/src/a.ts true,false",
|
||||
]);
|
||||
expect(useLspPopup.getState().popup).toMatchObject({ layout: "copyPath", anchor: { x: 10, y: 20 } });
|
||||
});
|
||||
|
||||
it("lists contributed links in Copy Path/Reference… of library files too", () => {
|
||||
it("offers no content root paths for library files in Copy Path/Reference…", () => {
|
||||
disposers.push(
|
||||
registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: (_menu, ctx) => [{ label: `Link ${ctx.paths.join()}`, verbatim: true, run: () => undefined }],
|
||||
items: (_menu, ctx) => [
|
||||
{ id: "test.link", label: "Link", verbatim: true, preview: ctx.paths.join(), run: () => undefined },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(sub(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]), "Copy Path/Reference…")).toEqual([
|
||||
"Absolute Path",
|
||||
"File Name",
|
||||
"-",
|
||||
"Link /root/.m2/lib.jar",
|
||||
expect(chooser(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]))).toEqual([
|
||||
"Absolute Path: /root/.m2/lib.jar",
|
||||
"File Name: lib.jar",
|
||||
"Link: /root/.m2/lib.jar",
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/** Context menu and "New" popup of the project view. */
|
||||
import { openCopyPathChooser } from "@/editor/api";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import type { PathKind } from "@/platform/copyPath";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
|
||||
import { formatBinding, hostBinding, isMacHost, shortcutLabel } from "@/platform/keymap";
|
||||
@@ -18,6 +20,7 @@ import {
|
||||
canPaste,
|
||||
copyPaths,
|
||||
copySelection,
|
||||
pathsFor,
|
||||
delegate,
|
||||
deleteSelection,
|
||||
findFileUsages,
|
||||
@@ -151,6 +154,8 @@ function delegated(
|
||||
}
|
||||
|
||||
type Entry = MenuItem | null | false | undefined;
|
||||
/** Where a menu opens; popups its items open appear there. */
|
||||
type MenuPoint = { x: number; y: number } | "center";
|
||||
|
||||
/** A submenu of the present entries, or nothing when none is left (never an empty submenu). */
|
||||
function submenu(id: string, label: string, entries: Entry[], icon?: string): MenuItem | null {
|
||||
@@ -160,8 +165,13 @@ function submenu(id: string, label: string, entries: Entry[], icon?: string): Me
|
||||
}
|
||||
|
||||
/** Project view actions available for the selected files and directories. */
|
||||
export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
if (nodes.some((n) => n.readOnly)) return libraryMenuItems(nodes.filter((n) => !n.group));
|
||||
/** `at`: where the menu opens, for the popups its items open (Copy Path/Reference…). */
|
||||
export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center"): MenuItem[] {
|
||||
if (nodes.some((n) => n.readOnly))
|
||||
return libraryMenuItems(
|
||||
nodes.filter((n) => !n.group),
|
||||
at,
|
||||
);
|
||||
const lead = nodes[0] ?? null;
|
||||
const single = nodes.length === 1 ? lead : null;
|
||||
const nonRoot = nodes.filter((n) => !n.root);
|
||||
@@ -217,22 +227,7 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
disabled: !nonRoot.length,
|
||||
run: () => copySelection(false),
|
||||
},
|
||||
{
|
||||
id: "copyPath",
|
||||
label: "Copy Path/Reference…",
|
||||
submenu: [
|
||||
{
|
||||
id: "abs",
|
||||
label: "Absolute Path",
|
||||
shortcut: keyLabel("project.copyAbsolutePath"),
|
||||
run: () => void copyPaths("absolute", nodes),
|
||||
},
|
||||
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
|
||||
{ id: "rel", label: "Path From Content Root", run: () => void copyPaths("relative", nodes) },
|
||||
{ kind: "separator" },
|
||||
...menuGroupItems("copyPath", menuGroupContext(nodes)),
|
||||
],
|
||||
},
|
||||
copyPathItem(nodes, at, false),
|
||||
{
|
||||
id: "paste",
|
||||
label: "Paste",
|
||||
@@ -464,27 +459,13 @@ function openInRightSplitItem(files: ProjectNode[]): MenuItem {
|
||||
}
|
||||
|
||||
/** Library sources (External Libraries) are read-only: copy, find and reveal only. */
|
||||
function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
function libraryMenuItems(nodes: ProjectNode[], at: MenuPoint): MenuItem[] {
|
||||
if (!nodes.length) return [];
|
||||
const single = nodes.length === 1 ? nodes[0]! : null;
|
||||
const folder = single?.dir ? single.path : null;
|
||||
const items: Entry[] = [
|
||||
{ id: "copy", label: "Copy", icon: "copy", shortcut: keyLabel("project.copy"), run: () => copySelection(false) },
|
||||
{
|
||||
id: "copyPath",
|
||||
label: "Copy Path/Reference…",
|
||||
submenu: [
|
||||
{
|
||||
id: "abs",
|
||||
label: "Absolute Path",
|
||||
shortcut: keyLabel("project.copyAbsolutePath"),
|
||||
run: () => void copyPaths("absolute", nodes),
|
||||
},
|
||||
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
|
||||
{ kind: "separator" },
|
||||
...menuGroupItems("copyPath", menuGroupContext(nodes)),
|
||||
],
|
||||
},
|
||||
copyPathItem(nodes, at, true),
|
||||
{ kind: "separator" },
|
||||
!!folder && delegated("find.inPath", { directory: folder }, "Find in Files…", { icon: "search" }),
|
||||
!!folder && { kind: "separator" },
|
||||
@@ -518,6 +499,43 @@ export function revealLabel() {
|
||||
return fileManagerName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy Path/Reference…: a chooser previewing what each way copies for the selection (several
|
||||
* paths one per line), contributed links and references included. Library files have no
|
||||
* content or source root.
|
||||
*/
|
||||
function copyPathItem(nodes: ProjectNode[], at: MenuPoint, library: boolean): Entry {
|
||||
const row = (kind: PathKind, id: string, label: string) => {
|
||||
const paths = pathsFor(kind, nodes);
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
// A selection only partly under a source root has no source-root path.
|
||||
preview: paths.length && paths.length === nodes.length ? paths.join("\n") : null,
|
||||
run: () => void copyPaths(kind, nodes),
|
||||
};
|
||||
};
|
||||
return {
|
||||
id: "copyPath",
|
||||
label: "Copy Path/Reference…",
|
||||
run: () =>
|
||||
openCopyPathChooser(
|
||||
at,
|
||||
[
|
||||
row("absolute", "project.copyAbsolutePath", "Absolute Path"),
|
||||
row("name", "project.copyFileName", "File Name"),
|
||||
...(library
|
||||
? []
|
||||
: [
|
||||
row("relative", "project.copyRelativePath", "Path From Content Root"),
|
||||
row("source", "project.copySourceRootPath", "Path From Source Root"),
|
||||
]),
|
||||
],
|
||||
menuGroupContext(nodes),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** What contributed menu groups see: the selected (non-placeholder) paths. */
|
||||
export function menuGroupContext(nodes: ProjectNode[]): MenuGroupContext {
|
||||
const real = nodes.filter((n) => !n.placeholder);
|
||||
|
||||
@@ -62,11 +62,19 @@ export function activate(): () => void {
|
||||
const p = useProject.getState().project;
|
||||
const s = useProjectTree.getState();
|
||||
if ((p?.root ?? null) !== s.root || p?.workspace?.projects !== (s.members ?? undefined))
|
||||
initProjectTree(p?.root ?? null, p?.name ?? "", p?.workspace?.projects ?? null, p?.unity ?? null);
|
||||
initProjectTree(
|
||||
p?.root ?? null,
|
||||
p?.name ?? "",
|
||||
p?.workspace?.projects ?? null,
|
||||
p?.unity ?? null,
|
||||
p?.unreal ?? null,
|
||||
);
|
||||
else if (p) {
|
||||
useProjectTree.setState({ name: p.name, unity: p.unity ?? null });
|
||||
useProjectTree.setState({ name: p.name, unity: p.unity ?? null, unreal: p.unreal ?? null });
|
||||
if (p.unity && !s.unity && s.mode === "project") setViewMode("unity");
|
||||
if (!p.unity && s.mode === "unity") setViewMode("project");
|
||||
if (p.unreal && !s.unreal && s.mode === "project") setViewMode("unreal");
|
||||
if (!p.unreal && s.mode === "unreal") setViewMode("project");
|
||||
}
|
||||
};
|
||||
sync();
|
||||
|
||||
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача