Compare commits
9 Commits
v0.3.6
...
fix/review
| Author | SHA1 | Date | |
|---|---|---|---|
| b801588c9f | |||
| 597dffe92d | |||
| 30e77664d5 | |||
| 23fabe11ec | |||
| 37f5c504f7 | |||
| 20c94ef9f0 | |||
| dc88269baf | |||
| 9fc81015d7 | |||
| 294d10eb40 |
11
PLUGINS.md
11
PLUGINS.md
@ -75,6 +75,17 @@ host.t(key, params?) // app i18n
|
||||
host.log(...args) // console, tagged with the plugin id
|
||||
```
|
||||
|
||||
## Theme tokens
|
||||
A plugin's DOM inherits the app's CSS variables — use them so the panel follows the
|
||||
active theme. The exact names (a wrong name silently falls back to your hardcoded
|
||||
default, which then breaks on the opposite theme):
|
||||
|
||||
`--accent` `--accent-2` `--accent-deep` · `--bg` `--panel` `--panel-2` `--panel-3`
|
||||
`--elevated` `--border` · `--txt` `--muted` `--faint` · `--add` (success) `--edit`
|
||||
(warning) `--del` (danger) · `--mono` (font)
|
||||
|
||||
There is no `--text`, `--ok`, `--err`, or `--sans`.
|
||||
|
||||
## Contribution points
|
||||
- **Menu items** and **views** appear in the **Actions** menu.
|
||||
- **File context items** appear when you right-click a file in Changes.
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "exbyte-depot",
|
||||
"private": true,
|
||||
"version": "0.3.6",
|
||||
"version": "0.4.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
243
plugins-examples/team-relay/index.js
Normal file
243
plugins-examples/team-relay/index.js
Normal file
@ -0,0 +1,243 @@
|
||||
// Team Relay — presence + coordinator tools over a GENERIC relay.
|
||||
//
|
||||
// The relay (see exbyte-relay/) is a dumb message bus: it routes opaque JSON and
|
||||
// tracks who's online, and knows nothing about Perforce. ALL the logic lives
|
||||
// here and runs through the permission-gated `host.team` bridge:
|
||||
// - every ~4s we announce presence (user, #open files, access level) and drain
|
||||
// our inbox in one /sync round-trip;
|
||||
// - a coordinator (admin/super) can ask a teammate's client to shelve its open
|
||||
// work to the server — the teammate's client does the shelve, nothing is
|
||||
// submitted, and their files stay checked out (shelve is non-destructive).
|
||||
//
|
||||
// Relay URL/token/room are configured in the Team tab and stored per-plugin —
|
||||
// nothing is hardcoded into the app.
|
||||
|
||||
export function activate(host) {
|
||||
const team = host.team;
|
||||
if (!team) { host.log('no team bridge — plugin.json needs the "team" permission'); return; }
|
||||
|
||||
const S = host.storage;
|
||||
if (!S.get("room")) S.set("room", "team");
|
||||
const getCfg = () => ({
|
||||
url: (S.get("relayUrl") || "").trim().replace(/\/+$/, ""),
|
||||
token: (S.get("relayToken") || "").trim(),
|
||||
room: (S.get("room") || "team").trim() || "team",
|
||||
});
|
||||
|
||||
const me = team.whoami() || {};
|
||||
const myId = me.client || me.user || "unknown";
|
||||
let access = "";
|
||||
team.maxAccess().then((a) => { access = String(a || "").toLowerCase(); updateAll(); }).catch(() => {});
|
||||
const isCoordinator = () => access === "super" || access === "admin";
|
||||
|
||||
let members = [];
|
||||
let status = "idle"; // idle | ok | error
|
||||
let statusMsg = "";
|
||||
const updaters = new Set();
|
||||
const updateAll = () => updaters.forEach((fn) => { try { fn(); } catch (_) {} });
|
||||
|
||||
// ---- relay I/O (backend HTTP pipe → no CORS, any http(s) URL) --------------
|
||||
async function post(path, bodyObj) {
|
||||
const c = getCfg();
|
||||
if (!c.url) throw new Error("Relay URL not set");
|
||||
const txt = await team.relay(c.url + path, "POST", JSON.stringify(bodyObj), c.token);
|
||||
return JSON.parse(txt || "{}");
|
||||
}
|
||||
async function send(to, type, payload) {
|
||||
const c = getCfg();
|
||||
await post("/send", { room: c.room, to, from: myId, type, payload: payload || {} });
|
||||
}
|
||||
|
||||
// ---- inbound message handling ---------------------------------------------
|
||||
async function handle(msg) {
|
||||
const from = msg.from || "A teammate";
|
||||
if (msg.type === "shelve-request") {
|
||||
host.flash(from + " is shelving your open work to the server…");
|
||||
host.notify("Team Relay", from + " is shelving your open work to the server…");
|
||||
try {
|
||||
const n = await team.openCount();
|
||||
if (!n) { await send(from, "shelve-result", { ok: true, change: "", files: 0 }); return; }
|
||||
const r = await team.shelveOpen("Remote shelve requested by " + from + " via Team Relay");
|
||||
host.notify("Team Relay", "Your open work was shelved as CL " + r.change + " (" + r.files + " file(s)). Your files stay checked out.");
|
||||
await send(from, "shelve-result", { ok: true, change: r.change, files: r.files });
|
||||
} catch (e) {
|
||||
host.flash("Remote shelve failed: " + e, true);
|
||||
await send(from, "shelve-result", { ok: false, error: String(e) });
|
||||
}
|
||||
} else if (msg.type === "shelve-result") {
|
||||
const p = msg.payload || {};
|
||||
if (p.ok && p.change) host.flash(from + ": shelved " + p.files + " file(s) as CL " + p.change + " — find it under Pending / Shelved.");
|
||||
else if (p.ok) host.flash(from + ": nothing open to shelve.");
|
||||
else host.flash(from + ": shelve failed — " + p.error, true);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- presence loop (one global timer, survives plugin reloads) ------------
|
||||
let busy = false;
|
||||
async function tick() {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
const c = getCfg();
|
||||
if (!c.url) { status = "idle"; statusMsg = "Set the relay URL below."; return; }
|
||||
const openCount = await team.openCount().catch(() => 0);
|
||||
const res = await post("/sync", {
|
||||
room: c.room, id: myId, name: me.user || myId,
|
||||
meta: { client: myId, user: me.user || "", openCount, access },
|
||||
});
|
||||
members = Array.isArray(res.members) ? res.members : [];
|
||||
status = "ok";
|
||||
statusMsg = members.length + (members.length === 1 ? " online" : " online");
|
||||
for (const m of (Array.isArray(res.messages) ? res.messages : [])) await handle(m);
|
||||
} catch (e) {
|
||||
status = "error";
|
||||
statusMsg = String(e).replace(/^Error:\s*/, "");
|
||||
} finally {
|
||||
busy = false;
|
||||
updateAll();
|
||||
}
|
||||
}
|
||||
// Single presence loop even if the plugin is reloaded (blob module re-imported).
|
||||
if (typeof window !== "undefined") {
|
||||
if (window.__exbyteTeamRelayTimer) clearInterval(window.__exbyteTeamRelayTimer);
|
||||
window.__exbyteTeamRelayTimer = setInterval(tick, 4000);
|
||||
}
|
||||
tick();
|
||||
|
||||
// ---- UI helpers ------------------------------------------------------------
|
||||
function styleBtn(b, primary) {
|
||||
b.style.cssText =
|
||||
"padding:4px 10px;border-radius:6px;cursor:pointer;white-space:nowrap;font:12px var(--sans,system-ui,sans-serif);" +
|
||||
(primary
|
||||
? "background:var(--accent,#7c6ef6);color:#fff;border:1px solid var(--accent,#7c6ef6)"
|
||||
: "background:transparent;color:var(--muted,#9a9aa8);border:1px solid var(--border,#33333d)");
|
||||
if (b.disabled) { b.style.opacity = "0.5"; b.style.cursor = "default"; }
|
||||
}
|
||||
|
||||
function buildSettings() {
|
||||
const wrap = document.createElement("div");
|
||||
wrap.style.cssText =
|
||||
"display:flex;flex-direction:column;gap:6px;padding:9px;border:1px solid var(--border,#26262e);border-radius:8px;background:var(--panel,#17171d)";
|
||||
const title = document.createElement("div");
|
||||
title.textContent = "Relay settings";
|
||||
title.style.cssText = "font-weight:600;margin-bottom:2px";
|
||||
const field = (label, key, ph, pw) => {
|
||||
const l = document.createElement("label");
|
||||
l.style.cssText = "display:flex;flex-direction:column;gap:2px;font-size:11px;color:var(--muted,#9a9aa8)";
|
||||
l.appendChild(document.createTextNode(label));
|
||||
const inp = document.createElement("input");
|
||||
inp.type = pw ? "password" : "text";
|
||||
inp.placeholder = ph || "";
|
||||
inp.value = S.get(key) || "";
|
||||
inp.style.cssText =
|
||||
"padding:5px 7px;border:1px solid var(--border,#33333d);border-radius:6px;background:var(--bg,#0e0e12);color:var(--txt,#e8e8ee);font:12px var(--mono,ui-monospace,monospace)";
|
||||
inp.addEventListener("input", () => S.set(key, inp.value));
|
||||
l.appendChild(inp);
|
||||
return l;
|
||||
};
|
||||
const save = document.createElement("button");
|
||||
save.textContent = "Connect";
|
||||
styleBtn(save, true);
|
||||
save.addEventListener("click", () => { host.flash("Relay settings saved."); tick(); });
|
||||
wrap.append(
|
||||
title,
|
||||
field("Relay URL", "relayUrl", "http://26.0.0.1:8787"),
|
||||
field("Token (optional)", "relayToken", "shared secret", true),
|
||||
field("Room", "room", "team"),
|
||||
save,
|
||||
);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function renderMembers(container) {
|
||||
container.textContent = "";
|
||||
if (!getCfg().url) return;
|
||||
if (!members.length) {
|
||||
const empty = document.createElement("div");
|
||||
empty.style.cssText = "color:var(--muted,#9a9aa8);padding:8px 0";
|
||||
empty.textContent = status === "error" ? "Can't reach the relay — check the URL/token." : "No teammates online yet.";
|
||||
container.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
for (const m of members) {
|
||||
const meta = m.meta || {};
|
||||
const oc = Number(meta.openCount || 0);
|
||||
const row = document.createElement("div");
|
||||
row.style.cssText = "display:flex;align-items:center;gap:8px;padding:7px 0;border-top:1px solid var(--border,#26262e)";
|
||||
const infoCol = document.createElement("div");
|
||||
infoCol.style.flex = "1";
|
||||
const name = document.createElement("div");
|
||||
name.style.fontWeight = "600";
|
||||
name.textContent = (m.name || m.id) + (m.id === myId ? " (you)" : "");
|
||||
const sub = document.createElement("div");
|
||||
sub.style.cssText = "color:var(--muted,#9a9aa8);font-size:11px";
|
||||
sub.textContent = m.id + " · " + oc + " open" + (meta.access ? " · " + meta.access : "");
|
||||
infoCol.append(name, sub);
|
||||
row.appendChild(infoCol);
|
||||
|
||||
if (isCoordinator() && m.id !== myId) {
|
||||
const btn = document.createElement("button");
|
||||
const idle = oc > 0 ? "Force shelve" : "Nothing open";
|
||||
btn.textContent = idle;
|
||||
btn.disabled = oc === 0;
|
||||
styleBtn(btn, oc > 0);
|
||||
if (oc > 0) {
|
||||
btn.title = "Ask this teammate's client to shelve their open work to the server (nothing is submitted).";
|
||||
btn.addEventListener("click", async () => {
|
||||
btn.disabled = true; btn.textContent = "Requesting…"; styleBtn(btn, false);
|
||||
try { await send(m.id, "shelve-request", {}); host.flash("Asked " + (m.name || m.id) + " to shelve their open work…"); }
|
||||
catch (e) { host.flash("Couldn't reach the relay: " + e, true); }
|
||||
setTimeout(() => { btn.disabled = false; btn.textContent = idle; styleBtn(btn, true); }, 2500);
|
||||
});
|
||||
}
|
||||
row.appendChild(btn);
|
||||
}
|
||||
container.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- dock panel ("Team") ---------------------------------------------------
|
||||
host.ui.addDockPanel({
|
||||
id: "team",
|
||||
title: "Team",
|
||||
icon: "people",
|
||||
render: (el) => {
|
||||
el.textContent = "";
|
||||
el.style.cssText =
|
||||
"display:flex;flex-direction:column;height:100%;gap:9px;padding:11px 13px;overflow:auto;" +
|
||||
"font:12px/1.5 var(--sans,system-ui,sans-serif);color:var(--txt,#e8e8ee)";
|
||||
|
||||
const head = document.createElement("div");
|
||||
head.style.cssText = "display:flex;align-items:center;gap:8px";
|
||||
const dot = document.createElement("span");
|
||||
dot.style.cssText = "width:8px;height:8px;border-radius:50%;flex:0 0 auto";
|
||||
const statusText = document.createElement("span");
|
||||
statusText.style.cssText = "color:var(--muted,#9a9aa8);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap";
|
||||
const gear = document.createElement("button");
|
||||
gear.textContent = "Settings";
|
||||
styleBtn(gear, false);
|
||||
head.append(dot, statusText, gear);
|
||||
|
||||
const settings = buildSettings();
|
||||
settings.style.display = getCfg().url ? "none" : "flex";
|
||||
gear.addEventListener("click", () => {
|
||||
settings.style.display = settings.style.display === "none" ? "flex" : "none";
|
||||
});
|
||||
|
||||
const membersEl = document.createElement("div");
|
||||
el.append(head, settings, membersEl);
|
||||
|
||||
const refresh = () => {
|
||||
dot.style.background =
|
||||
status === "ok" ? "var(--add,#3ecf8e)" : status === "error" ? "var(--del,#ff6b6b)" : "var(--muted,#9a9aa8)";
|
||||
statusText.textContent = statusMsg || "";
|
||||
renderMembers(membersEl);
|
||||
};
|
||||
updaters.add(refresh);
|
||||
refresh();
|
||||
return () => { updaters.delete(refresh); };
|
||||
},
|
||||
});
|
||||
|
||||
host.log("Team Relay activated (id " + myId + ")");
|
||||
}
|
||||
12
plugins-examples/team-relay/plugin.json
Normal file
12
plugins-examples/team-relay/plugin.json
Normal file
@ -0,0 +1,12 @@
|
||||
{
|
||||
"id": "team-relay",
|
||||
"name": "Team Relay",
|
||||
"version": "1.0.1",
|
||||
"author": "Exbyte Studios",
|
||||
"description": "See who on the team is online and what they have open, over a lightweight relay on your VPN. Coordinators (admin/super) can force-shelve a teammate's open work to the server when they've stepped away — the teammate's client does the shelve; nothing is submitted. Configure the relay URL in the Team tab. Requires the Exbyte relay service.",
|
||||
"entry": "index.js",
|
||||
"minAppVersion": "0.4.0",
|
||||
"permissions": ["team", "notify"],
|
||||
"defaultEnabled": false,
|
||||
"contributes": { "dock": ["team"] }
|
||||
}
|
||||
@ -1,28 +1,32 @@
|
||||
// Unreal Engine Tools — official plugin.
|
||||
// The core app keeps the build engine (UnrealBuildTool / MSBuild), the build
|
||||
// overlay and the log reader; this plugin is just the Unreal-facing surface:
|
||||
// a "Build Solution" action and a live Unreal-log view. Reached through the
|
||||
// permission-gated `host.ue` bridge.
|
||||
// overlay and the log reader; this plugin is just the Unreal-facing surface.
|
||||
// It renders natively: the actions sit in the working-folder right-click menu
|
||||
// with the host's Unreal + hammer icons, and the log is a bottom-dock tab —
|
||||
// exactly where these lived before, just delivered as a plugin. Reached through
|
||||
// the permission-gated `host.ue` bridge.
|
||||
|
||||
export function activate(host) {
|
||||
const ue = host.ue;
|
||||
if (!ue) { host.log("no ue bridge — plugin.json needs the \"ue\" permission"); return; }
|
||||
|
||||
// Build the game target (UnrealBuildTool for the game module, MSBuild for plain C++).
|
||||
host.ui.addMenuItem("🔨 Build Solution (Unreal)", () => {
|
||||
if (!ue.hasProject()) { host.flash("No Unreal project in the current working folder.", true); return; }
|
||||
ue.build(); // triggers the core build flow + overlay
|
||||
});
|
||||
// Right-click the working folder → Launch / Build, shown only on a UE project.
|
||||
// Prefer the native folder-context slot (host ≥ 0.3.7); fall back to the top
|
||||
// menu on older hosts so the actions are always reachable.
|
||||
const addAction = (label, run, icon) => {
|
||||
if (host.ui.addFolderContextItem) host.ui.addFolderContextItem(label, run, { icon, visible: () => ue.hasProject() });
|
||||
else host.ui.addMenuItem(label, () => { if (!ue.hasProject()) { host.flash("No Unreal project in the current working folder.", true); return; } run(); }, { icon });
|
||||
};
|
||||
addAction("Launch Unreal Engine", () => ue.launch(), "ue");
|
||||
addAction("Build Solution (.sln)", () => ue.build(), "hammer");
|
||||
|
||||
// Live Unreal editor log (tails Saved/Logs). Opens from the Actions menu.
|
||||
host.ui.addView({
|
||||
id: "unreal-log",
|
||||
title: "Unreal Log",
|
||||
render: (el) => {
|
||||
el.style.cssText = "display:flex;flex-direction:column;height:100%;min-height:340px";
|
||||
// Bottom-dock "Unreal" tab — tails the editor log (Saved/Logs), refreshing live.
|
||||
// Native dock panel on host ≥ 0.3.7; a modal view as a fallback on older hosts.
|
||||
const mountLog = (el) => {
|
||||
el.style.cssText = "display:flex;flex-direction:column;height:100%";
|
||||
const pre = document.createElement("pre");
|
||||
pre.style.cssText =
|
||||
"flex:1;margin:0;overflow:auto;white-space:pre-wrap;word-break:break-word;" +
|
||||
"flex:1;margin:0;padding:10px 14px;overflow:auto;white-space:pre-wrap;word-break:break-word;" +
|
||||
"font:11.5px/1.6 var(--mono,ui-monospace,monospace);color:var(--muted,#9a9aa8)";
|
||||
el.appendChild(pre);
|
||||
let alive = true;
|
||||
@ -32,15 +36,16 @@ export function activate(host) {
|
||||
if (!ue.hasProject()) { pre.textContent = "No Unreal project in the current working folder."; return; }
|
||||
const atBottom = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 30;
|
||||
const txt = await ue.readLog(200000);
|
||||
pre.textContent = txt || "No Unreal log yet. It appears when the editor writes to Saved/Logs (i.e. while Unreal is running).";
|
||||
pre.textContent = txt || "No Unreal log yet. It shows here when the editor writes to Saved/Logs — i.e. while Unreal is running.";
|
||||
if (atBottom) pre.scrollTop = pre.scrollHeight;
|
||||
} catch (e) { pre.textContent = String(e); }
|
||||
}
|
||||
tick();
|
||||
const id = setInterval(tick, 1500);
|
||||
return () => { alive = false; clearInterval(id); };
|
||||
},
|
||||
});
|
||||
};
|
||||
if (host.ui.addDockPanel) host.ui.addDockPanel({ id: "unreal", title: "Unreal", icon: "ue", render: mountLog });
|
||||
else host.ui.addView({ id: "unreal-log", title: "Unreal Log", render: mountLog });
|
||||
|
||||
host.log("Unreal Engine Tools activated");
|
||||
}
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
{
|
||||
"id": "unreal",
|
||||
"name": "Unreal Engine Tools",
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.0",
|
||||
"author": "Exbyte Studios",
|
||||
"description": "Build the game (.sln / UnrealBuildTool) and tail the Unreal editor log. Enable this on Unreal Engine projects.",
|
||||
"description": "Build the game (.sln / UnrealBuildTool), launch the editor, and tail the Unreal log. Actions live in the working-folder right-click menu; the log is a bottom-dock tab. Enable on Unreal Engine projects.",
|
||||
"entry": "index.js",
|
||||
"minAppVersion": "0.3.6",
|
||||
"permissions": ["ue"],
|
||||
"defaultEnabled": true,
|
||||
"contributes": { "menu": true, "views": ["unreal-log"] }
|
||||
"contributes": { "folderContext": true, "dock": ["unreal"] }
|
||||
}
|
||||
|
||||
211
src-tauri/Cargo.lock
generated
211
src-tauri/Cargo.lock
generated
@ -468,6 +468,23 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||
|
||||
[[package]]
|
||||
name = "chacha20"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.0",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
@ -558,6 +575,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.0"
|
||||
@ -966,9 +992,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "exbyte-depot"
|
||||
version = "0.3.6"
|
||||
version = "0.4.2"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"reqwest 0.12.28",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
@ -1279,8 +1306,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"wasi",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1302,8 +1331,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
"rand_core 0.10.1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1572,6 +1604,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower-service",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -2042,6 +2075,12 @@ version = "0.4.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "lru-slab"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "mac-notification-sys"
|
||||
version = "0.6.15"
|
||||
@ -2784,6 +2823,62 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
"pin-project-lite",
|
||||
"quinn-proto",
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-proto"
|
||||
version = "0.11.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.4.3",
|
||||
"lru-slab",
|
||||
"rand 0.10.2",
|
||||
"rand_pcg",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"slab",
|
||||
"thiserror 2.0.18",
|
||||
"tinyvec",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-udp"
|
||||
version = "0.5.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
|
||||
dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.46"
|
||||
@ -2812,7 +2907,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
|
||||
dependencies = [
|
||||
"chacha20",
|
||||
"getrandom 0.4.3",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -2822,7 +2928,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -2834,6 +2940,21 @@ dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
|
||||
|
||||
[[package]]
|
||||
name = "rand_pcg"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
|
||||
dependencies = [
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raw-window-handle"
|
||||
version = "0.6.2"
|
||||
@ -2909,6 +3030,44 @@ version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.12.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-util",
|
||||
"js-sys",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"quinn",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tower-service",
|
||||
"url",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.13.4"
|
||||
@ -3046,6 +3205,7 @@ version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046"
|
||||
dependencies = [
|
||||
"web-time",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@ -3093,6 +3253,12 @@ version = "1.0.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
@ -3315,6 +3481,18 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_with"
|
||||
version = "3.21.0"
|
||||
@ -3385,7 +3563,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
]
|
||||
|
||||
@ -3709,7 +3887,7 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
"plist",
|
||||
"raw-window-handle",
|
||||
"reqwest",
|
||||
"reqwest 0.13.4",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_repr",
|
||||
@ -3858,7 +4036,7 @@ checksum = "01fc2c5ff41105bd1f7242d8201fdf3efd70749b82fa013a17f2126357d194cc"
|
||||
dependencies = [
|
||||
"log",
|
||||
"notify-rust",
|
||||
"rand",
|
||||
"rand 0.9.4",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_repr",
|
||||
@ -3917,7 +4095,7 @@ dependencies = [
|
||||
"minisign-verify",
|
||||
"osakit",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"reqwest 0.13.4",
|
||||
"rustls",
|
||||
"semver",
|
||||
"serde",
|
||||
@ -4692,6 +4870,16 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-time"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web_atoms"
|
||||
version = "0.2.5"
|
||||
@ -4757,6 +4945,15 @@ dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com"
|
||||
version = "0.38.2"
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "exbyte-depot"
|
||||
version = "0.3.6"
|
||||
version = "0.4.2"
|
||||
description = "Exbyte Depot — native Perforce client by Exbyte Studios"
|
||||
authors = ["Exbyte Studios"]
|
||||
edition = "2021"
|
||||
@ -26,6 +26,8 @@ serde_json = "1"
|
||||
tauri-plugin-dialog = "2.7.1"
|
||||
# decode p4 output on non-UTF8 (ANSI/cp1251) systems — Cyrillic paths
|
||||
encoding_rs = "0.8"
|
||||
# backend-side HTTPS for the plugin registry (webview fetch is blocked by CORS)
|
||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
|
||||
|
||||
# Auto-updater (desktop only — checks Gitea Releases for a signed new version)
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
|
||||
@ -92,6 +92,95 @@ fn ensure_under_root(conn: &Conn, path: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Like `ensure_under_root`, but the root itself is refused: for destructive
|
||||
/// operations, where the workspace folder must never be the target.
|
||||
fn ensure_inside_root(conn: &Conn, path: &str) -> Result<(), String> {
|
||||
ensure_under_root(conn, path)?;
|
||||
let canon_root = std::fs::canonicalize(&conn.root).map_err(|e| e.to_string())?;
|
||||
let canon = std::fs::canonicalize(path).map_err(|e| e.to_string())?;
|
||||
if canon == canon_root {
|
||||
return Err("Refusing to operate on the workspace root".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A build input must be a solution or project file inside the workspace: MSBuild
|
||||
/// runs whatever an arbitrary project file tells it to.
|
||||
fn ensure_build_input(conn: &Conn, path: &str) -> Result<(), String> {
|
||||
let p = std::path::Path::new(path);
|
||||
if path.is_empty() || !p.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");
|
||||
if !["sln", "slnx", "uproject"].iter().any(|x| ext.eq_ignore_ascii_case(x)) {
|
||||
return Err(format!("Not a solution or Unreal project: {path}"));
|
||||
}
|
||||
ensure_under_root(conn, path)
|
||||
}
|
||||
|
||||
/// Upper bound for a blocking p4 call. Streaming transfers (sync/submit) aren't
|
||||
/// subject to it: they run for as long as they keep going and can be cancelled.
|
||||
const P4_TIMEOUT: Duration = Duration::from_secs(900);
|
||||
|
||||
/// Read a child's pipe to the end on its own thread, so a full stderr pipe can't
|
||||
/// block the process while we're reading stdout.
|
||||
fn read_all<R: std::io::Read + Send + 'static>(reader: Option<R>) -> std::thread::JoinHandle<Vec<u8>> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
if let Some(mut r) = reader {
|
||||
let _ = r.read_to_end(&mut buf);
|
||||
}
|
||||
buf
|
||||
})
|
||||
}
|
||||
|
||||
/// Split a child's output into decoded lines. `BufRead::lines` stops at the first
|
||||
/// non-UTF-8 byte, and p4 prints paths in the ANSI codepage.
|
||||
fn byte_lines<R: std::io::Read>(reader: R) -> impl Iterator<Item = String> {
|
||||
BufReader::new(reader)
|
||||
.split(b'\n')
|
||||
.map_while(Result::ok)
|
||||
.map(|l| decode(&l).trim_end_matches('\r').to_string())
|
||||
}
|
||||
|
||||
/// Deliver a child's lines over a channel, so the reader can poll a cancel flag
|
||||
/// while the child prints nothing.
|
||||
fn line_channel<R: std::io::Read + Send + 'static>(reader: R) -> std::sync::mpsc::Receiver<String> {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for line in byte_lines(reader) {
|
||||
if tx.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
/// `Command::output` with a time limit: the child is killed once it runs out.
|
||||
fn run_limited(cmd: &mut Command, timeout: Duration) -> std::io::Result<std::process::Output> {
|
||||
let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
|
||||
let out = read_all(child.stdout.take());
|
||||
let err = read_all(child.stderr.take());
|
||||
let started = Instant::now();
|
||||
let status = loop {
|
||||
if let Some(s) = child.try_wait()? {
|
||||
break s;
|
||||
}
|
||||
if started.elapsed() >= timeout {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "p4 timed out"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(std::process::Output {
|
||||
status,
|
||||
stdout: out.join().unwrap_or_default(),
|
||||
stderr: err.join().unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Build a `p4` command with the connection's global flags applied.
|
||||
/// On Windows we set CREATE_NO_WINDOW so no console flashes on every call.
|
||||
/// stdin defaults to null so a command that unexpectedly prompts (expired
|
||||
@ -122,7 +211,7 @@ fn p4_cmd(conn: &Conn, tagged: bool) -> Command {
|
||||
|
||||
/// Run a tagged (JSON) p4 command and collect the objects it prints.
|
||||
fn run_json(conn: &Conn, args: &[&str]) -> Result<Vec<Value>, String> {
|
||||
let out = match p4_cmd(conn, true).args(args).output() {
|
||||
let out = match run_limited(p4_cmd(conn, true).args(args), P4_TIMEOUT) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
let m = format!("Failed to start p4: {e}");
|
||||
@ -513,7 +602,7 @@ async fn p4_changes(state: State<'_, AppState>) -> Result<Vec<Value>, String> {
|
||||
.map_or(false, |d| d.get("depotFile0").is_some());
|
||||
if shelved {
|
||||
result.push(c);
|
||||
} else {
|
||||
} else if cl_is_stale(&c) {
|
||||
let _ = run_text(&conn, &["change", "-d", &num]);
|
||||
}
|
||||
}
|
||||
@ -521,6 +610,19 @@ async fn p4_changes(state: State<'_, AppState>) -> Result<Vec<Value>, String> {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Empty changelists are cleaned up only once they're a few minutes old, so a poll
|
||||
/// can't delete one that a partial submit has just created.
|
||||
fn cl_is_stale(change: &Value) -> bool {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs());
|
||||
change
|
||||
.get("time")
|
||||
.and_then(|t| t.as_str())
|
||||
.and_then(|t| t.parse::<u64>().ok())
|
||||
.map_or(false, |t| now.saturating_sub(t) > 300)
|
||||
}
|
||||
|
||||
/// Submitted history for a depot path (History tab).
|
||||
#[tauri::command]
|
||||
async fn p4_history(state: State<'_, AppState>, path: String) -> Result<Vec<Value>, String> {
|
||||
@ -537,7 +639,7 @@ async fn p4_disconnect(state: State<'_, AppState>) -> Result<(), String> {
|
||||
|
||||
/// Run a non-tagged p4 command (raw text out). Errors carry stderr.
|
||||
fn run_text(conn: &Conn, args: &[&str]) -> Result<String, String> {
|
||||
let out = match p4_cmd(conn, false).args(args).output() {
|
||||
let out = match run_limited(p4_cmd(conn, false).args(args), P4_TIMEOUT) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
let m = format!("Failed to start p4: {e}");
|
||||
@ -588,13 +690,20 @@ fn run_stream(conn: &Conn, args: &[&str], op: &str, total: i64) -> Result<String
|
||||
let mut count: i64 = 0;
|
||||
let mut last = Instant::now();
|
||||
let mut cancelled = false;
|
||||
let err_reader = read_all(child.stderr.take());
|
||||
if let Some(out) = child.stdout.take() {
|
||||
for line in BufReader::new(out).lines().map_while(Result::ok) {
|
||||
let lines = line_channel(out);
|
||||
loop {
|
||||
if TRANSFER_CANCEL.load(Ordering::SeqCst) {
|
||||
cancelled = true;
|
||||
let _ = child.kill();
|
||||
break;
|
||||
}
|
||||
let line = match lines.recv_timeout(Duration::from_millis(200)) {
|
||||
Ok(l) => l,
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
};
|
||||
count += 1;
|
||||
// throttle to ~25 fps regardless of file count, but always send the first few
|
||||
if count <= 5 || last.elapsed().as_millis() >= 40 {
|
||||
@ -611,15 +720,7 @@ fn run_stream(conn: &Conn, args: &[&str], op: &str, total: i64) -> Result<String
|
||||
}
|
||||
}
|
||||
let status = child.wait().map_err(|e| e.to_string())?;
|
||||
let stderr = child
|
||||
.stderr
|
||||
.take()
|
||||
.map(|mut s| {
|
||||
let mut buf = String::new();
|
||||
let _ = std::io::Read::read_to_string(&mut s, &mut buf);
|
||||
buf.trim().to_string()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let stderr = decode(&err_reader.join().unwrap_or_default()).trim().to_string();
|
||||
|
||||
// tell the UI the transfer is finished
|
||||
if let Some(app) = APP.get() {
|
||||
@ -632,9 +733,14 @@ fn run_stream(conn: &Conn, args: &[&str], op: &str, total: i64) -> Result<String
|
||||
log_p4(args, count, false, Some("cancelled by user"));
|
||||
return Err("Cancelled.".into());
|
||||
}
|
||||
if !status.success() && !stderr.is_empty() {
|
||||
log_p4(args, 0, false, Some(&stderr));
|
||||
return Err(stderr);
|
||||
if !status.success() {
|
||||
let msg = if stderr.is_empty() {
|
||||
format!("p4 {} failed", args.first().unwrap_or(&""))
|
||||
} else {
|
||||
stderr
|
||||
};
|
||||
log_p4(args, 0, false, Some(&msg));
|
||||
return Err(msg);
|
||||
}
|
||||
log_p4(args, count, true, None);
|
||||
Ok(collected.trim().to_string())
|
||||
@ -709,11 +815,7 @@ async fn p4_diff(state: State<'_, AppState>, file: String) -> Result<String, Str
|
||||
#[tauri::command]
|
||||
async fn p4_revert(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> {
|
||||
let conn = current(&state)?;
|
||||
let mut args: Vec<&str> = vec!["revert"];
|
||||
for f in &files {
|
||||
args.push(f.as_str());
|
||||
}
|
||||
run_text(&conn, &args)
|
||||
run_batched(&conn, &["revert"], &files)
|
||||
}
|
||||
|
||||
/// Create an empty numbered changelist with a description; returns its number.
|
||||
@ -850,11 +952,7 @@ async fn p4_reopen_default(state: State<'_, AppState>, files: Vec<String>) -> Re
|
||||
if files.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let mut args: Vec<&str> = vec!["reopen", "-c", "default"];
|
||||
for f in &files {
|
||||
args.push(f.as_str());
|
||||
}
|
||||
run_text(&conn, &args)
|
||||
run_batched(&conn, &["reopen", "-c", "default"], &files)
|
||||
}
|
||||
|
||||
/// Edit the description of a pending changelist, preserving its file list.
|
||||
@ -917,9 +1015,15 @@ async fn p4_submit(
|
||||
return Err("No files selected to submit".into());
|
||||
}
|
||||
let n = files.len() as i64;
|
||||
let opened_total = run_json(&conn, &["opened"])?.len();
|
||||
// all opened files selected → submit the whole default changelist in one go
|
||||
if files.len() >= opened_total {
|
||||
let opened = run_json(&conn, &["opened"])?;
|
||||
let in_default: std::collections::HashSet<&str> = opened
|
||||
.iter()
|
||||
.filter(|v| v.get("change").and_then(|c| c.as_str()) == Some("default"))
|
||||
.filter_map(|v| v.get("depotFile").and_then(|d| d.as_str()))
|
||||
.collect();
|
||||
let selected: std::collections::HashSet<&str> = files.iter().map(|f| f.as_str()).collect();
|
||||
// exactly the default changelist selected → submit it in one go
|
||||
if selected == in_default {
|
||||
return run_stream(&conn, &["submit", "-d", &description], "submit", n);
|
||||
}
|
||||
// partial submit → dedicated numbered changelist (batched reopen for large sets)
|
||||
@ -961,6 +1065,26 @@ fn file_batches(files: &[String], prefix_len: usize) -> Vec<std::ops::Range<usiz
|
||||
ranges
|
||||
}
|
||||
|
||||
/// Run `prefix <files…>` in batches that fit the Windows command line.
|
||||
fn run_batched(conn: &Conn, prefix: &[&str], files: &[String]) -> Result<String, String> {
|
||||
let prefix_len: usize = prefix.iter().map(|p| p.len() + 1).sum();
|
||||
let mut out = String::new();
|
||||
for r in file_batches(files, prefix_len) {
|
||||
let mut args: Vec<&str> = prefix.to_vec();
|
||||
for f in &files[r] {
|
||||
args.push(f.as_str());
|
||||
}
|
||||
let text = run_text(conn, &args)?;
|
||||
if !text.is_empty() {
|
||||
if !out.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&text);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn files_cmd(conn: &Conn, cmd: &str, files: &[String]) -> Result<Vec<Value>, String> {
|
||||
if files.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@ -1045,13 +1169,20 @@ fn run_reconcile_stream(conn: &Conn, spec: &str) -> Result<i64, String> {
|
||||
let mut count: i64 = 0;
|
||||
let mut last = Instant::now();
|
||||
let mut cancelled = false;
|
||||
let err_reader = read_all(child.stderr.take());
|
||||
if let Some(out) = child.stdout.take() {
|
||||
for line in BufReader::new(out).lines().map_while(Result::ok) {
|
||||
let lines = line_channel(out);
|
||||
loop {
|
||||
if SCAN_CANCEL.load(Ordering::SeqCst) {
|
||||
cancelled = true;
|
||||
let _ = child.kill();
|
||||
break;
|
||||
}
|
||||
let line = match lines.recv_timeout(Duration::from_millis(200)) {
|
||||
Ok(l) => l,
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
};
|
||||
// reconcile prints one `//depot/… - opened for add|edit|delete` per file
|
||||
if !line.starts_with("//") {
|
||||
continue;
|
||||
@ -1070,15 +1201,7 @@ fn run_reconcile_stream(conn: &Conn, spec: &str) -> Result<i64, String> {
|
||||
}
|
||||
}
|
||||
let _ = child.wait();
|
||||
let stderr = child
|
||||
.stderr
|
||||
.take()
|
||||
.map(|mut s| {
|
||||
let mut buf = String::new();
|
||||
let _ = std::io::Read::read_to_string(&mut s, &mut buf);
|
||||
buf.trim().to_string()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let stderr = decode(&err_reader.join().unwrap_or_default()).trim().to_string();
|
||||
|
||||
// final event so the UI can clear the counter / show the total
|
||||
if let Some(app) = APP.get() {
|
||||
@ -1158,6 +1281,10 @@ async fn open_in_explorer(state: State<'_, AppState>, target: String) -> Result<
|
||||
} else {
|
||||
target
|
||||
};
|
||||
// touching a network path would send the user's Windows credentials to that host
|
||||
if local.starts_with("\\\\") || local.starts_with("//") {
|
||||
return Err("Network paths can't be opened here".into());
|
||||
}
|
||||
let path = std::path::Path::new(&local);
|
||||
if !path.exists() {
|
||||
return Err(format!("Path not synced to disk yet: {local}"));
|
||||
@ -1324,15 +1451,8 @@ async fn open_in_editor(state: State<'_, AppState>, depot: String, editor: Strin
|
||||
.ok_or_else(|| "No editor available".to_string())?;
|
||||
|
||||
if ed.exe.is_empty() {
|
||||
// system-default association via `start`
|
||||
let mut c = Command::new("cmd");
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
c.creation_flags(0x0800_0000);
|
||||
}
|
||||
c.args(["/C", "start", "", &local])
|
||||
.spawn()
|
||||
// system-default association, no shell: the file name is depot data
|
||||
tauri_plugin_opener::open_path(&local, None::<&str>)
|
||||
.map_err(|e| format!("Could not launch: {e}"))?;
|
||||
} else {
|
||||
let mut c = Command::new(&ed.exe);
|
||||
@ -1362,14 +1482,7 @@ async fn launch_file(state: State<'_, AppState>, path: String) -> Result<(), Str
|
||||
if !std::path::Path::new(&path).exists() {
|
||||
return Err(format!("File not found: {path}"));
|
||||
}
|
||||
let mut c = Command::new("cmd");
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
c.creation_flags(0x0800_0000);
|
||||
}
|
||||
c.args(["/C", "start", "", &path])
|
||||
.spawn()
|
||||
tauri_plugin_opener::open_path(&path, None::<&str>)
|
||||
.map_err(|e| format!("Could not launch: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
@ -1480,7 +1593,10 @@ fn resolve_engine_dir(uproject: &str) -> Option<String> {
|
||||
/// `MSBuild <solution>` does. For a plain C++ solution it falls back to MSBuild.
|
||||
/// Output streams line-by-line as `build-log` events.
|
||||
#[tauri::command]
|
||||
async fn build_sln(path: String, config: String, uproject: String) -> Result<String, String> {
|
||||
async fn build_sln(state: State<'_, AppState>, path: String, config: String, uproject: String) -> Result<String, String> {
|
||||
let conn = current(&state)?;
|
||||
ensure_build_input(&conn, &path)?;
|
||||
ensure_build_input(&conn, &uproject)?;
|
||||
if !std::path::Path::new(&path).exists() && uproject.is_empty() {
|
||||
return Err(format!("Solution not found: {path}"));
|
||||
}
|
||||
@ -1589,8 +1705,9 @@ async fn build_sln(path: String, config: String, uproject: String) -> Result<Str
|
||||
}
|
||||
};
|
||||
|
||||
let err_reader = read_all(child.stderr.take());
|
||||
if let Some(out) = child.stdout.take() {
|
||||
for line in BufReader::new(out).lines().map_while(Result::ok) {
|
||||
for line in byte_lines(out) {
|
||||
if !line.trim().is_empty() {
|
||||
scan(&line);
|
||||
emit(line, false, false);
|
||||
@ -1598,9 +1715,8 @@ async fn build_sln(path: String, config: String, uproject: String) -> Result<Str
|
||||
}
|
||||
}
|
||||
let status = child.wait().map_err(|e| e.to_string())?;
|
||||
if let Some(mut se) = child.stderr.take() {
|
||||
let mut buf = String::new();
|
||||
let _ = std::io::Read::read_to_string(&mut se, &mut buf);
|
||||
{
|
||||
let buf = decode(&err_reader.join().unwrap_or_default());
|
||||
for line in buf.lines() {
|
||||
if !line.trim().is_empty() {
|
||||
scan(line);
|
||||
@ -1723,14 +1839,20 @@ async fn delete_folder(state: State<'_, AppState>, path: String) -> Result<Vec<V
|
||||
let conn = current(&state)?;
|
||||
if !path.starts_with("//") {
|
||||
// local-only folder → remove on disk (confined)
|
||||
ensure_under_root(&conn, &path)?;
|
||||
ensure_inside_root(&conn, &path)?;
|
||||
std::fs::remove_dir_all(&path).map_err(|e| format!("Could not delete folder: {e}"))?;
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let base = path.trim_end_matches(['/', '.']);
|
||||
let spec = format!("{base}/...");
|
||||
// un-open anything already opened under here (adds/edits/deletes) so delete is clean
|
||||
let _ = run_json(&conn, &["revert", &spec]);
|
||||
// open work must not disappear with the folder: it's submitted, shelved or reverted first
|
||||
let open = run_json(&conn, &["opened", &spec]).unwrap_or_default();
|
||||
if !open.is_empty() {
|
||||
return Err(format!(
|
||||
"{} file(s) under this folder are open. Submit, shelve or revert them first.",
|
||||
open.len()
|
||||
));
|
||||
}
|
||||
let deleted = run_json(&conn, &["delete", &spec]).or_else(|e| {
|
||||
let l = e.to_lowercase();
|
||||
if l.contains("no such file") || l.contains("not on client") || l.contains("no file(s)") || l.contains("empty") {
|
||||
@ -1739,11 +1861,14 @@ async fn delete_folder(state: State<'_, AppState>, path: String) -> Result<Vec<V
|
||||
Err(e)
|
||||
}
|
||||
})?;
|
||||
// nothing versioned here → drop the local directory outright
|
||||
// nothing versioned here → remove the directory only if it's already empty,
|
||||
// so unversioned files are never deleted as a side effect
|
||||
if deleted.is_empty() {
|
||||
if let Some(local) = scope_local_dir(&conn, base) {
|
||||
if ensure_under_root(&conn, &local).is_ok() {
|
||||
let _ = std::fs::remove_dir_all(&local);
|
||||
if std::path::Path::new(&local).is_dir() {
|
||||
ensure_inside_root(&conn, &local)?;
|
||||
std::fs::remove_dir(&local)
|
||||
.map_err(|_| "Nothing here is versioned, but the folder still holds local files. Delete it in Explorer.".to_string())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1795,6 +1920,7 @@ async fn read_depot(state: State<'_, AppState>, depot: String) -> Result<tauri::
|
||||
.next()
|
||||
.and_then(|v| v.get("path").and_then(|p| p.as_str()).map(String::from))
|
||||
.ok_or_else(|| "Could not resolve the file path".to_string())?;
|
||||
ensure_under_root(&conn, &local)?;
|
||||
check_local_size(&local)?;
|
||||
std::fs::read(&local)
|
||||
.map(tauri::ipc::Response::new)
|
||||
@ -1836,20 +1962,45 @@ async fn print_depot(state: State<'_, AppState>, spec: String) -> Result<tauri::
|
||||
Ok(tauri::ipc::Response::new(out.stdout))
|
||||
}
|
||||
|
||||
/// Run an arbitrary `p4` command for the built-in terminal and return combined
|
||||
/// stdout+stderr as text. Never errors on a non-zero exit — the terminal shows
|
||||
/// the error text just like a real console would.
|
||||
/// What the built-in terminal refuses: commands that expose the ticket, change the
|
||||
/// client's settings or destroy server history, and global flags, since `-p` alone
|
||||
/// would point the session at another server.
|
||||
fn console_guard(args: &[String]) -> Result<(), String> {
|
||||
const FLAGS: &[&str] = &["-ztag", "-Mj", "-s", "-e"];
|
||||
const BLOCKED: &[&str] = &[
|
||||
"admin", "configure", "login", "logout", "obliterate", "passwd", "set", "tickets", "trust",
|
||||
];
|
||||
let mut rest = args.iter().skip_while(|a| FLAGS.iter().any(|f| *f == a.as_str()));
|
||||
let cmd = rest.next().map_or("", |s| s.as_str());
|
||||
if cmd.is_empty() {
|
||||
return Err("Usage: p4 <command>".into());
|
||||
}
|
||||
if cmd.starts_with('-') {
|
||||
return Err(format!("Global flag {cmd} isn't available in this terminal"));
|
||||
}
|
||||
if BLOCKED.iter().any(|b| cmd.eq_ignore_ascii_case(b)) {
|
||||
return Err(format!("p4 {cmd} isn't available in this terminal"));
|
||||
}
|
||||
if cmd.eq_ignore_ascii_case("print") && rest.any(|a| a.starts_with('-') && a.contains('o')) {
|
||||
return Err("p4 print -o isn't available in this terminal".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run a `p4` command for the built-in terminal and return combined stdout+stderr
|
||||
/// as text. Never errors on a non-zero exit — the terminal shows the error text
|
||||
/// just like a real console would.
|
||||
#[tauri::command]
|
||||
async fn p4_console(state: State<'_, AppState>, args: Vec<String>) -> Result<String, String> {
|
||||
let conn = current(&state)?;
|
||||
if let Err(m) = console_guard(&args) {
|
||||
return Ok(m);
|
||||
}
|
||||
let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
|
||||
// stdin is null (p4_cmd default) so prompting commands fail fast instead of
|
||||
// hanging; a failing P4EDITOR aborts editor-spawning forms (change, submit
|
||||
// without -d, client, …) the same way.
|
||||
let out = p4_cmd(&conn, false)
|
||||
.env("P4EDITOR", "cmd /c exit 1")
|
||||
.args(&refs)
|
||||
.output()
|
||||
let out = run_limited(p4_cmd(&conn, false).env("P4EDITOR", "cmd /c exit 1").args(&refs), P4_TIMEOUT)
|
||||
.map_err(|e| format!("Failed to start p4: {e}"))?;
|
||||
let mut s = decode(&out.stdout);
|
||||
let err = decode(&out.stderr);
|
||||
@ -1911,22 +2062,22 @@ async fn p4_opened_all(state: State<'_, AppState>, scope: String) -> Result<Vec<
|
||||
#[tauri::command]
|
||||
async fn p4_lock(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> {
|
||||
let conn = current(&state)?;
|
||||
let mut args: Vec<&str> = vec!["lock"];
|
||||
for f in &files {
|
||||
args.push(f.as_str());
|
||||
}
|
||||
run_text(&conn, &args)
|
||||
run_batched(&conn, &["lock"], &files)
|
||||
}
|
||||
|
||||
/// Release locks.
|
||||
#[tauri::command]
|
||||
async fn p4_unlock(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> {
|
||||
let conn = current(&state)?;
|
||||
let mut args: Vec<&str> = vec!["unlock"];
|
||||
for f in &files {
|
||||
args.push(f.as_str());
|
||||
}
|
||||
run_text(&conn, &args)
|
||||
run_batched(&conn, &["unlock"], &files)
|
||||
}
|
||||
|
||||
/// Release a lock held by someone else (`p4 unlock -f`). The server allows this
|
||||
/// for admin and above only.
|
||||
#[tauri::command]
|
||||
async fn p4_unlock_force(state: State<'_, AppState>, files: Vec<String>) -> Result<String, String> {
|
||||
let conn = current(&state)?;
|
||||
run_batched(&conn, &["unlock", "-f"], &files)
|
||||
}
|
||||
|
||||
/// Read the server typemap as a list of "TYPE PATTERN" entries.
|
||||
@ -2003,11 +2154,7 @@ async fn p4_reopen_type(state: State<'_, AppState>, files: Vec<String>, filetype
|
||||
if files.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let mut args: Vec<&str> = vec!["reopen", "-t", &filetype];
|
||||
for f in &files {
|
||||
args.push(f.as_str());
|
||||
}
|
||||
run_text(&conn, &args)
|
||||
run_batched(&conn, &["reopen", "-t", &filetype], &files)
|
||||
}
|
||||
|
||||
/// Extract the largest embedded PNG from a byte blob — this is how an uncooked
|
||||
@ -2076,6 +2223,7 @@ async fn uasset_thumbnail(state: State<'_, AppState>, spec: String, historical:
|
||||
.next()
|
||||
.and_then(|v| v.get("path").and_then(|p| p.as_str()).map(String::from))
|
||||
.ok_or_else(|| "Could not resolve the file path".to_string())?;
|
||||
ensure_under_root(&conn, &local)?;
|
||||
if let Ok(m) = std::fs::metadata(&local) {
|
||||
if m.len() > MAX_UASSET {
|
||||
return Err("Asset too large for a thumbnail".into());
|
||||
@ -2312,7 +2460,16 @@ async fn p4_shelve(state: State<'_, AppState>, change: String) -> Result<String,
|
||||
#[tauri::command]
|
||||
async fn p4_unshelve(state: State<'_, AppState>, change: String) -> Result<String, String> {
|
||||
let conn = current(&state)?;
|
||||
run_text(&conn, &["unshelve", "-s", &change, "-f"])
|
||||
run_text(&conn, &["unshelve", "-s", &change])
|
||||
}
|
||||
|
||||
/// The caller's maximum protection level on this server (`p4 protects -m`),
|
||||
/// e.g. "super" / "admin" / "write". Read-only; decides which actions the UI
|
||||
/// offers (the server still enforces the real permission).
|
||||
#[tauri::command]
|
||||
async fn p4_protects_max(state: State<'_, AppState>) -> Result<String, String> {
|
||||
let conn = current(&state)?;
|
||||
run_text(&conn, &["protects", "-m"]).map(|s| s.trim().to_string())
|
||||
}
|
||||
|
||||
/// Delete the shelved files of a changelist.
|
||||
@ -2393,7 +2550,11 @@ async fn p4_annotate(state: State<'_, AppState>, spec: String) -> Result<String,
|
||||
let conn = current(&state)?;
|
||||
let mut s = run_text(&conn, &["annotate", "-c", "-u", "-q", &spec])?;
|
||||
if s.len() > 2_000_000 {
|
||||
s.truncate(2_000_000);
|
||||
let mut cut = 2_000_000;
|
||||
while !s.is_char_boundary(cut) {
|
||||
cut -= 1;
|
||||
}
|
||||
s.truncate(cut);
|
||||
s.push_str("\n… (truncated)");
|
||||
}
|
||||
Ok(s)
|
||||
@ -2426,11 +2587,7 @@ async fn p4_reopen_to(state: State<'_, AppState>, change: String, files: Vec<Str
|
||||
if files.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let mut args: Vec<&str> = vec!["reopen", "-c", &change];
|
||||
for f in &files {
|
||||
args.push(f.as_str());
|
||||
}
|
||||
run_text(&conn, &args)
|
||||
run_batched(&conn, &["reopen", "-c", &change], &files)
|
||||
}
|
||||
|
||||
/// Newest submitted changelist in the scope — cheap poll for "new submit" toasts.
|
||||
@ -2543,18 +2700,23 @@ async fn p4_reconcile_apply(state: State<'_, AppState>, paths: Vec<String>) -> R
|
||||
if clean.is_empty() {
|
||||
return Err("No files selected".into());
|
||||
}
|
||||
let mut applied = Vec::new();
|
||||
for r in file_batches(&clean, "reconcile -e -a -d ".len()) {
|
||||
let mut args: Vec<&str> = vec!["reconcile", "-e", "-a", "-d"];
|
||||
for p in &clean {
|
||||
for p in &clean[r] {
|
||||
args.push(p.as_str());
|
||||
}
|
||||
run_json(&conn, &args).or_else(|e| {
|
||||
match run_json(&conn, &args) {
|
||||
Ok(v) => applied.extend(v),
|
||||
Err(e) => {
|
||||
let l = e.to_lowercase();
|
||||
if l.contains("no file") || l.contains("up-to-date") || l.contains("no differing") {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(e)
|
||||
if !(l.contains("no file") || l.contains("up-to-date") || l.contains("no differing")) {
|
||||
return Err(e);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(applied)
|
||||
}
|
||||
|
||||
/// Toggle the read-only attribute on local working files so they can be edited
|
||||
@ -2837,12 +2999,8 @@ async fn p4_group_member(
|
||||
Ok(decode(&res.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
/// OpenRouter API key baked into the binary at compile time from the
|
||||
/// git-ignored file src-tauri/openrouter.key.
|
||||
const BAKED_AI_KEY: &str = include_str!("../openrouter.key");
|
||||
|
||||
/// Path to the (git-ignored) OpenRouter API key, stored in the app config dir.
|
||||
/// Kept as a fallback/override location for builds without a baked key.
|
||||
/// Path to the user's OpenRouter API key, stored in the app config dir. No key
|
||||
/// ships with the build: anything inside the binary is public.
|
||||
fn ai_key_path() -> Option<std::path::PathBuf> {
|
||||
let app = APP.get()?;
|
||||
let dir = app.path().app_config_dir().ok()?;
|
||||
@ -2850,10 +3008,6 @@ fn ai_key_path() -> Option<std::path::PathBuf> {
|
||||
}
|
||||
#[tauri::command]
|
||||
async fn read_ai_key() -> Result<String, String> {
|
||||
let baked = BAKED_AI_KEY.trim();
|
||||
if !baked.is_empty() {
|
||||
return Ok(baked.to_string());
|
||||
}
|
||||
Ok(ai_key_path()
|
||||
.and_then(|p| std::fs::read_to_string(p).ok())
|
||||
.map(|s| s.trim().to_string())
|
||||
@ -2923,10 +3077,8 @@ async fn plugin_list() -> Result<Vec<Value>, String> {
|
||||
let Ok(m) = serde_json::from_str::<Value>(&txt) else { continue };
|
||||
let id = m.get("id").and_then(|v| v.as_str()).map(String::from)
|
||||
.unwrap_or_else(|| e.file_name().to_string_lossy().to_string());
|
||||
// off by default unless the manifest opts in (defaultEnabled) — official
|
||||
// plugins like Unreal ship on; the user's choice persists in enabled.json
|
||||
let default_on = m.get("defaultEnabled").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let enabled = *en.get(&id).unwrap_or(&default_on);
|
||||
// off until the user turns it on; the choice persists in enabled.json
|
||||
let enabled = *en.get(&id).unwrap_or(&false);
|
||||
out.push(serde_json::json!({
|
||||
"id": id,
|
||||
"name": m.get("name").and_then(|v| v.as_str()).unwrap_or(""),
|
||||
@ -2975,10 +3127,10 @@ async fn plugin_set_enabled(id: String, enabled: bool) -> Result<(), String> {
|
||||
/// this only touches the confined plugins folder (id + name are path-validated).
|
||||
#[tauri::command]
|
||||
async fn plugin_write_file(id: String, name: String, content: String) -> Result<(), String> {
|
||||
if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') || id.contains("..") {
|
||||
if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') || id.contains("..") || id.starts_with('.') {
|
||||
return Err("Invalid plugin id".into());
|
||||
}
|
||||
if name.is_empty() || name.contains('/') || name.contains('\\') || name.contains("..") {
|
||||
if name.is_empty() || name.contains('/') || name.contains('\\') || name.contains(':') || name.contains("..") {
|
||||
return Err("Invalid file name".into());
|
||||
}
|
||||
let dir = plugins_dir().ok_or("No config dir")?.join(&id);
|
||||
@ -2987,6 +3139,86 @@ async fn plugin_write_file(id: String, name: String, content: String) -> Result<
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fetch text from the Exbyte plugin registry over HTTPS on the backend — the
|
||||
/// webview `fetch()` is blocked by CORS (Gitea raw sends no ACAO header), so the
|
||||
/// plugin catalog and installs go through here. Restricted to the trusted host.
|
||||
#[tauri::command]
|
||||
async fn registry_http_get(url: String) -> Result<String, String> {
|
||||
if !url.starts_with("https://gitea.exbytestudios.com/") {
|
||||
return Err("Only the Exbyte registry host is allowed".into());
|
||||
}
|
||||
let client = reqwest::Client::builder()
|
||||
.user_agent("ExbyteDepot")
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let resp = client.get(&url).send().await.map_err(|e| e.to_string())?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("HTTP {}", resp.status().as_u16()));
|
||||
}
|
||||
resp.text().await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The relay pipe only reaches this machine and private (VPN/LAN) addresses, by
|
||||
/// IP, so plugin traffic can't leave for an arbitrary internet host.
|
||||
fn relay_url_allowed(url: &str) -> bool {
|
||||
let Ok(u) = reqwest::Url::parse(url) else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(u.scheme(), "http" | "https") {
|
||||
return false;
|
||||
}
|
||||
match u.host_str() {
|
||||
Some("localhost") => true,
|
||||
Some(host) => host
|
||||
.parse::<std::net::Ipv4Addr>()
|
||||
.map_or(false, |ip| ip.is_private() || ip.is_loopback()),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic HTTP pipe for plugins that talk to a self-hosted service (e.g. the
|
||||
/// team relay on the VPN). The webview can't reach arbitrary hosts — CSP pins
|
||||
/// `connect-src`, and cross-origin `fetch` hits CORS — so the plugin routes its
|
||||
/// requests through here. This is a DUMB pipe: it has no idea what the service
|
||||
/// is, which keeps the relay URL out of the app (the plugin holds it) and lets
|
||||
/// one primitive serve any future relay-backed plugin. Private addresses only; an
|
||||
/// optional bearer token authenticates against the caller's own service.
|
||||
#[tauri::command]
|
||||
async fn relay_http(
|
||||
url: String,
|
||||
method: String,
|
||||
body: Option<String>,
|
||||
token: Option<String>,
|
||||
) -> Result<String, String> {
|
||||
if !relay_url_allowed(&url) {
|
||||
return Err("Relay URL must be http(s) on a private network address".into());
|
||||
}
|
||||
let client = reqwest::Client::builder()
|
||||
.user_agent("ExbyteDepot")
|
||||
.timeout(std::time::Duration::from_secs(20))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut req = match method.to_uppercase().as_str() {
|
||||
"GET" => client.get(&url),
|
||||
"POST" => client.post(&url),
|
||||
other => return Err(format!("Unsupported method {other}")),
|
||||
};
|
||||
if let Some(tok) = token.filter(|t| !t.is_empty()) {
|
||||
req = req.header("authorization", format!("Bearer {tok}"));
|
||||
}
|
||||
if let Some(b) = body {
|
||||
req = req.header("content-type", "application/json").body(b);
|
||||
}
|
||||
let resp = req.send().await.map_err(|e| e.to_string())?;
|
||||
let status = resp.status();
|
||||
let text = resp.text().await.map_err(|e| e.to_string())?;
|
||||
if !status.is_success() {
|
||||
return Err(format!("HTTP {}: {}", status.as_u16(), text.trim()));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
fn copy_dir_recursive(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(to)?;
|
||||
for e in std::fs::read_dir(from)? {
|
||||
@ -3146,6 +3378,9 @@ pub fn run() {
|
||||
plugin_read_entry,
|
||||
plugin_set_enabled,
|
||||
plugin_write_file,
|
||||
registry_http_get,
|
||||
relay_http,
|
||||
p4_protects_max,
|
||||
plugin_install,
|
||||
plugin_remove,
|
||||
plugins_dir_path,
|
||||
@ -3168,6 +3403,7 @@ pub fn run() {
|
||||
p4_opened_all,
|
||||
p4_lock,
|
||||
p4_unlock,
|
||||
p4_unlock_force,
|
||||
p4_typemap_get,
|
||||
p4_typemap_set,
|
||||
p4_reopen_type,
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Exbyte Depot",
|
||||
"mainBinaryName": "Exbyte Depot",
|
||||
"version": "0.3.6",
|
||||
"version": "0.4.2",
|
||||
"identifier": "com.bonchellon.exbyte-depot",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
||||
17
src/App.css
17
src/App.css
@ -374,6 +374,12 @@ body.resizing{cursor:col-resize!important;user-select:none}
|
||||
color:var(--muted);border-radius:7px;padding:3px 10px;cursor:pointer;font-size:11.5px}
|
||||
.stlog:hover{color:var(--txt);border-color:var(--accent)}
|
||||
.stlog svg{width:13px;height:13px}
|
||||
.stlog.icon{padding:3px 7px}
|
||||
.stupd{position:relative}
|
||||
.stupd.has{color:var(--accent);border-color:var(--accent)}
|
||||
.stupd.busy{color:var(--accent-2)}
|
||||
.stupd[disabled]{cursor:default;opacity:.85}
|
||||
.stupd-dot{position:absolute;top:2px;right:2px;width:6px;height:6px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 2px var(--panel)}
|
||||
.logpeek{position:absolute;left:8px;bottom:26px;width:520px;max-width:calc(100vw - 20px);max-height:min(340px,60vh);overflow-y:auto;z-index:250;
|
||||
background:var(--elevated);border:1px solid var(--border);border-radius:11px 11px 0 0;padding:5px;box-shadow:0 -14px 40px -12px rgba(0,0,0,.55)}
|
||||
.logpeek-h{position:sticky;top:0;padding:5px 9px 7px;font-size:10.5px;text-transform:uppercase;letter-spacing:.5px;color:var(--faint);
|
||||
@ -731,7 +737,8 @@ body.resizing-v{cursor:row-resize!important;user-select:none}
|
||||
.th-token input[type=color]::-webkit-color-swatch-wrapper{padding:0}
|
||||
/* plugins manager */
|
||||
.pl-list{flex:1;min-height:0;overflow:auto;padding:14px;display:flex;flex-direction:column;gap:10px}
|
||||
.pl-official-h{font-size:11px;text-transform:uppercase;letter-spacing:.5px;color:var(--faint);font-weight:700;margin:8px 2px 0;padding-top:10px;border-top:1px solid var(--border-soft)}
|
||||
.pl-official-h{font-size:11px;text-transform:uppercase;letter-spacing:.5px;color:var(--faint);font-weight:700;margin:8px 2px 0;padding-top:10px;border-top:1px solid var(--border-soft);display:flex;align-items:baseline;gap:8px}
|
||||
.pl-cat-sub{text-transform:none;letter-spacing:0;font-weight:500;color:var(--faint);opacity:.8}
|
||||
.pl-card{display:flex;gap:12px;align-items:flex-start;border:1px solid var(--border);border-radius:12px;padding:13px 15px;background:var(--panel);transition:.15s}
|
||||
.pl-card.off{opacity:.55}
|
||||
.pl-main{flex:1;min-width:0}
|
||||
@ -940,11 +947,17 @@ body.resizing-v{cursor:row-resize!important;user-select:none}
|
||||
.dropinner svg{width:44px;height:44px}
|
||||
.dropinner span{font-size:15px;font-weight:600;color:var(--txt)}
|
||||
|
||||
/* re-auth: who we're signing back in as */
|
||||
.reauth-who{display:flex;flex-wrap:wrap;gap:6px;margin:2px 0 14px}
|
||||
.reauth-who span{font-family:var(--mono);font-size:11px;color:var(--muted);
|
||||
background:var(--panel-3);border:1px solid var(--border);border-radius:6px;padding:3px 8px}
|
||||
|
||||
/* toast */
|
||||
.toast{position:fixed;bottom:18px;left:50%;transform:translateX(-50%);z-index:200;max-width:72%;
|
||||
background:var(--elevated);border:1px solid var(--border);color:var(--txt);
|
||||
padding:11px 18px;border-radius:12px;font-size:12.5px;box-shadow:0 20px 50px -15px rgba(0,0,0,.6);
|
||||
animation:toastin .25s ease;white-space:pre-wrap;text-align:center}
|
||||
animation:toastin .25s ease;white-space:pre-wrap;text-align:center;
|
||||
max-height:30vh;overflow-y:auto;overflow-wrap:anywhere}
|
||||
.toast.err{border-color:rgba(242,99,126,.4);color:var(--del)}
|
||||
@keyframes toastin{from{opacity:0;transform:translate(-50%,10px)}to{opacity:1;transform:translate(-50%,0)}}
|
||||
|
||||
|
||||
280
src/App.tsx
280
src/App.tsx
@ -4,15 +4,15 @@ import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { getCurrentWebview } from "@tauri-apps/api/webview";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { isPermissionGranted, requestPermission, sendNotification } from "@tauri-apps/plugin-notification";
|
||||
import { open as openDialog } from "@tauri-apps/plugin-dialog";
|
||||
import { open as openDialog, ask as askDialog } from "@tauri-apps/plugin-dialog";
|
||||
import ModelViewer from "./ModelViewer";
|
||||
import CodeView from "./CodeView";
|
||||
import UpdateBanner from "./Updater";
|
||||
import { useUpdater } from "./Updater";
|
||||
import "./App.css";
|
||||
import { p4, statusOf, splitPath, kindOf, isCodeFile, fmtTime, describeFiles, filelogRevs, humanSize, leaf, saveSession, loadSession, clearSession, saveScope, loadScope, recentScopes, pushRecentScope, fileBytes, getEditor, setEditorPref, P4Info, OpenedFile, Client, Change, Session, Describe, Dir, User, Editor, FileRev, FsEntry, PluginInfo } from "./p4";
|
||||
import { p4, statusOf, splitPath, kindOf, isCodeFile, fmtTime, describeFiles, filelogRevs, humanSize, leaf, syncSummary, isAuthError, onAuthLost, saveSession, loadSession, clearSession, saveScope, loadScope, recentScopes, pushRecentScope, fileBytes, getEditor, setEditorPref, P4Info, OpenedFile, Client, Change, Session, Describe, Dir, User, Editor, FileRev, FsEntry, PluginInfo } from "./p4";
|
||||
import { t, LANG, LANGS, setLangGlobal, Lang } from "./i18n";
|
||||
import { Theme, THEME_TOKENS, BUILTIN_THEMES, allThemes, loadCustomThemes, saveCustomThemes, loadActiveId, saveActiveId, resolveTheme, applyTheme, tokenValue, newCustomId, exportTheme, importTheme } from "./themes";
|
||||
import { loadPlugins, getRegistry, subscribeRegistry, runSubmitHooks, PluginView, autoInstallOfficial, fetchRegistry, installFromRegistry, RegistryEntry } from "./plugins";
|
||||
import { loadPlugins, getRegistry, subscribeRegistry, runSubmitHooks, PluginView, PluginDock, fetchRegistry, installFromRegistry, RegistryEntry } from "./plugins";
|
||||
import { aiSummary, aiExplainCode, getExplain, saveExplain, dropExplain, initials, avatarColor, activity } from "./ai";
|
||||
|
||||
// native OS notification (works even when the window is hidden in the tray)
|
||||
@ -82,6 +82,13 @@ const I = {
|
||||
open: <svg viewBox="0 0 24 24" fill="none"><path d="M14 4h6v6M20 4l-8 8M18 13v5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>,
|
||||
};
|
||||
|
||||
// Resolve a plugin-declared icon NAME to a real SVG from the host set, so plugin
|
||||
// contributions render with native icons instead of a generic glyph.
|
||||
function pluginIcon(name?: string): ReactNode {
|
||||
if (name && Object.prototype.hasOwnProperty.call(I, name)) return (I as Record<string, ReactNode>)[name];
|
||||
return I.hex;
|
||||
}
|
||||
|
||||
/* ---------------- theme hook (built-in + custom themes) ---------------- */
|
||||
function useTheme(): [boolean, () => void, string, (id: string) => void] {
|
||||
const [themeId, setThemeId] = useState(() => loadActiveId());
|
||||
@ -144,7 +151,7 @@ export default function App() {
|
||||
onInfo={setInfo} onSession={(s) => { setSession(s); saveSession(s); }}
|
||||
onDisconnect={() => { p4.disconnect(); clearSession(); setInfo(null); setSession(null); setPhase("connect"); }} />;
|
||||
|
||||
return <>{content}<UpdateBanner /></>;
|
||||
return content;
|
||||
}
|
||||
|
||||
/* ---------------- custom styled dropdown (replaces the ugly native <select>) ---------------- */
|
||||
@ -394,12 +401,14 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
const [uproject, setUproject] = useState(""); // local .uproject path when the scope is a UE project
|
||||
const uprojectRef = useRef(""); // live mirror for the plugin ue-bridge closures
|
||||
const [slnPath, setSlnPath] = useState(""); // local .sln path in the scope (for building)
|
||||
const slnPathRef = useRef(""); // live mirror for the plugin ue-bridge closures
|
||||
const [editors, setEditors] = useState<Editor[]>([]); // code editors installed on this machine
|
||||
const [editorId, setEditorId] = useState(getEditor()); // chosen editor id ("" → auto-pick)
|
||||
const [others, setOthers] = useState<Map<string, { user: string; locked: boolean }>>(new Map()); // files opened/locked by OTHER users
|
||||
const [needResolve, setNeedResolve] = useState<OpenedFile[]>([]); // files awaiting conflict resolution
|
||||
const [resolveOpen, setResolveOpen] = useState(false);
|
||||
const [offline, setOffline] = useState(false); // lost connection to the server
|
||||
const [reauth, setReauth] = useState(false); // p4 ticket expired — prompt for the password
|
||||
const [workOffline, setWorkOffline] = useState(() => { try { return localStorage.getItem("exd-workoffline") === "1"; } catch { return false; } }); // explicit offline-work mode
|
||||
const [behind, setBehind] = useState<{ count: number; sample: string[] } | null>(null); // server has newer content than the workspace
|
||||
const lastSubmit = useRef<string>(""); // newest submitted CL seen (new-submit toast)
|
||||
@ -413,9 +422,10 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
const [aiBusy, setAiBusy] = useState(false); // AI commit-summary generation in flight
|
||||
const [ctx, setCtx] = useState<null | { x: number; y: number; items: CtxItem[] }>(null); // right-click menu
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]); // live p4 command log (P4V-style)
|
||||
// bottom dock: a tabbed panel (Log / Terminal / Unreal), opened from Window menu
|
||||
// bottom dock: a tabbed panel (Log / Terminal + any plugin dock panels), opened from Window menu
|
||||
const [dockOpen, setDockOpen] = useState(false);
|
||||
const [dockTab, setDockTab] = useState<"log" | "terminal" | "unreal">("log");
|
||||
const [dockTab, setDockTab] = useState<string>("log");
|
||||
const upd = useUpdater(); // silent update check + state for the status-bar update icon
|
||||
// right-side view panel: tabbed (File Viewer / File Tree). Header hides at one tab.
|
||||
const [viewTabs, setViewTabs] = useState<ViewTab[]>(() => {
|
||||
try { const a = JSON.parse(localStorage.getItem("exd-viewtabs") || ""); if (Array.isArray(a) && a.length && a.every((x: string) => x === "viewer" || x === "tree" || x === "locks")) return a; } catch {}
|
||||
@ -475,8 +485,12 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
document.body.classList.add("resizing-v");
|
||||
}
|
||||
|
||||
// A toast is one line of feedback, never a report: cap it so a raw p4 dump or a
|
||||
// long server error can't grow the bubble over the whole window. Full output
|
||||
// always stays available in the Log dock.
|
||||
function flash(text: string, err = false) {
|
||||
setToast({ text, err });
|
||||
const one = (text || "").trim();
|
||||
setToast({ text: one.length > 220 ? one.slice(0, 220).trimEnd() + "…" : one, err });
|
||||
setTimeout(() => setToast(null), 4500);
|
||||
}
|
||||
function confirm(opts: { title: string; body: string; confirm: string; danger?: boolean }): Promise<boolean> {
|
||||
@ -484,7 +498,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
}
|
||||
|
||||
// open the bottom dock on a given tab (toggle off if already showing it)
|
||||
function openDock(tab: "log" | "terminal" | "unreal") {
|
||||
function openDock(tab: string) {
|
||||
setDockOpen((o) => (o && dockTab === tab ? false : true));
|
||||
setDockTab(tab);
|
||||
}
|
||||
@ -570,8 +584,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
const sameUser = (o.user || "").toLowerCase() === me;
|
||||
const sameClient = (o.client || "").toLowerCase() === myClient;
|
||||
if (sameUser && sameClient) continue; // it's my own checkout
|
||||
// `p4 opened -a` includes an `ourLock` field only when the file is locked
|
||||
const locked = (o as Record<string, unknown>).ourLock !== undefined;
|
||||
const locked = isHeld(o);
|
||||
map.set(dp, { user: o.user || "?", locked });
|
||||
}
|
||||
setOthers(map);
|
||||
@ -629,28 +642,39 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
hasProject: () => !!uprojectRef.current,
|
||||
uproject: () => uprojectRef.current,
|
||||
build: () => { startBuild(); },
|
||||
launch: () => { void launchUE(); },
|
||||
readLog: (tb?: number) => p4.ueLog(uprojectRef.current, tb ?? 200_000),
|
||||
},
|
||||
// Team bridge — presence; plugin owns the logic
|
||||
team: {
|
||||
whoami: () => (info ? { user: info.userName, client: info.clientName, root: info.clientRoot } : null),
|
||||
maxAccess: () => p4.protectsMax().catch(() => ""),
|
||||
openCount: () => p4.opened("").then((a) => a.length).catch(() => 0),
|
||||
submitShelved: (change: string) => p4.submitShelved(change),
|
||||
relay: (url: string, method: string, body?: string, token?: string) => p4.relayHttp(url, method, body, token),
|
||||
},
|
||||
});
|
||||
setPluginVer((v) => v + 1);
|
||||
return res;
|
||||
}
|
||||
useEffect(() => { uprojectRef.current = uproject; }, [uproject]); // keep the ue-bridge mirror live
|
||||
// keep the ue-bridge mirrors live: the bridge closures are built once (plugins
|
||||
// load as soon as we have a workspace) but the paths are detected later, per
|
||||
// working folder — so the bridge must read refs, never captured state.
|
||||
useEffect(() => { uprojectRef.current = uproject; }, [uproject]);
|
||||
useEffect(() => { slnPathRef.current = slnPath; }, [slnPath]);
|
||||
useEffect(() => {
|
||||
if (pluginsLoaded.current || !info?.clientName) return;
|
||||
pluginsLoaded.current = true;
|
||||
(async () => {
|
||||
// auto-install official plugins (e.g. Unreal) on first run so no one loses tooling
|
||||
try {
|
||||
const installed = new Set((await p4.pluginList()).map((p) => p.id));
|
||||
const added = await autoInstallOfficial(installed);
|
||||
if (added.length) console.log("[plugins] auto-installed:", added);
|
||||
} catch { /* offline — skip */ }
|
||||
// No auto-install: only load what the user chose to install. New plugins are
|
||||
// browsed and installed by hand from Settings → Plugins (the registry catalog).
|
||||
const { loaded, errors } = await reloadPlugins();
|
||||
if (errors.length) console.warn("[plugins] load errors:", errors);
|
||||
if (loaded) flash(t("{n} plugin(s) loaded", { n: loaded }));
|
||||
})().catch(() => {});
|
||||
}, [info?.clientName]); // eslint-disable-line
|
||||
// any p4 command that comes back "not logged in" raises the re-auth prompt
|
||||
useEffect(() => { onAuthLost(() => setReauth(true)); return () => onAuthLost(null); }, []);
|
||||
useEffect(() => subscribeRegistry(() => setPluginVer((v) => v + 1)), []);
|
||||
// live Perforce command log — the Rust backend emits one event per p4 call
|
||||
useEffect(() => {
|
||||
@ -773,7 +797,10 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
checkBehind(); // a new submit landed → am I now behind?
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// an expired ticket is not an outage: the server answered, it just
|
||||
// refused us. The re-auth prompt handles it — don't also claim offline.
|
||||
if (isAuthError(e)) return;
|
||||
if (alive && !offline) setOffline(true); // p4 unreachable → show offline banner
|
||||
}
|
||||
};
|
||||
@ -938,7 +965,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
|
||||
async function getLatest() {
|
||||
setBusy(true);
|
||||
try { flash(t("Get Latest: {msg}", { msg: await p4.sync(activePath) })); await refresh(); await loadHistory(); behindRef.current = 0; setBehind(null); } // sync may pull new submitted changelists → refresh History too
|
||||
try { flash(t("Get Latest: {msg}", { msg: syncSummary(await p4.sync(activePath)) })); await refresh(); await loadHistory(); behindRef.current = 0; setBehind(null); } // sync may pull new submitted changelists → refresh History too
|
||||
catch (e) { flash(String(e), true); setBusy(false); }
|
||||
}
|
||||
// check whether the server has newer content than my workspace (files behind)
|
||||
@ -962,7 +989,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
if (!r) return;
|
||||
if (!(await confirm({ title: t("Sync workspace to {rev}?", { rev: r }), body: t("Your synced files change to match {rev}. Un-submitted (opened) work is not touched. You can Get Latest to return to head.", { rev: r }), confirm: t("Sync") }))) return;
|
||||
setBusy(true);
|
||||
try { flash(t("Synced to {rev}: {msg}", { rev: r, msg: await p4.syncTo(activePath, r) })); await refresh(); await loadHistory(); }
|
||||
try { flash(t("Synced to {rev}: {msg}", { rev: r, msg: syncSummary(await p4.syncTo(activePath, r)) })); await refresh(); await loadHistory(); }
|
||||
catch (e) { flash(String(e), true); setBusy(false); }
|
||||
}
|
||||
function promptSyncTo() {
|
||||
@ -1000,12 +1027,20 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
// delete a folder — marks its files for delete (reviewable), removes fresh/local ones
|
||||
async function deleteFolder(path: string) {
|
||||
const name = splitPath(path).name || path;
|
||||
if (!(await confirm({ title: t("Delete folder “{name}”?", { name }), body: t("Every file under this folder is marked for delete. Nothing leaves the server until you Submit; freshly-added files are removed right away."), confirm: t("Delete"), danger: true }))) return;
|
||||
if (!(await confirm({ title: t("Delete folder “{name}”?", { name }), body: t("Every file under this folder is marked for delete. Nothing leaves the server until you Submit. A folder with open files is refused."), confirm: t("Delete"), danger: true }))) return;
|
||||
try { const r = await p4.deleteFolder(path); flash(r.length ? t("Marked {n} file(s) for delete — Submit to remove the folder.", { n: r.length }) : t("Folder removed.")); await refresh(); }
|
||||
catch (e) { flash(String(e), true); }
|
||||
}
|
||||
// right-click on a folder in the File Tree → folder operations
|
||||
function folderMenu(n: FsEntry, e: ReactMouseEvent) {
|
||||
if (!n.isDir) {
|
||||
openCtx(e, [
|
||||
{ label: t("Check out"), icon: I.lock, act: () => checkOut([n.path]) },
|
||||
{ label: t("Open in Explorer"), icon: I.reveal, act: () => reveal(n.path) },
|
||||
{ label: t("Copy path"), icon: I.copy, act: () => copyText(n.path, t("Path")) },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
const isDepot = n.path.startsWith("//");
|
||||
openCtx(e, [
|
||||
{ label: t("New folder / project…"), icon: I.folder, act: () => newFolder(n.path) },
|
||||
@ -1022,25 +1057,29 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
|
||||
function openCtx(e: ReactMouseEvent, items: CtxItem[]) { e.preventDefault(); e.stopPropagation(); setCtx({ x: e.clientX, y: e.clientY, items }); }
|
||||
|
||||
// launch Unreal by opening the detected .uproject (file association starts UE)
|
||||
// launch Unreal by opening the detected .uproject (file association starts UE).
|
||||
// Reads the ref, not the state: the plugin ue-bridge calls this through a
|
||||
// closure captured before the project was detected.
|
||||
async function launchUE() {
|
||||
if (!uproject) return;
|
||||
try { await p4.launchFile(uproject); flash(t("Launching Unreal…")); }
|
||||
const up = uprojectRef.current;
|
||||
if (!up) { flash(t("No Unreal project in the working folder. Choose the project folder first."), true); return; }
|
||||
try { await p4.launchFile(up); flash(t("Launching Unreal…")); }
|
||||
catch (e) { flash(String(e), true); }
|
||||
}
|
||||
|
||||
// open the configuration picker (Development / Shipping / …) before building
|
||||
function startBuild() {
|
||||
if (!slnPath && !uproject) { flash(t("No .sln found in the working folder. Choose the project folder first."), true); return; }
|
||||
if (!slnPathRef.current && !uprojectRef.current) { flash(t("No .sln found in the working folder. Choose the project folder first."), true); return; }
|
||||
setBuildPick(true);
|
||||
}
|
||||
// build with the chosen UE configuration, live output. For a real UE project we
|
||||
// pass the .uproject so the backend builds the game module via UnrealBuildTool.
|
||||
async function buildSln(config: string) {
|
||||
setBuildPick(false);
|
||||
if (!slnPath && !uproject) return;
|
||||
const sln = slnPathRef.current, up = uprojectRef.current;
|
||||
if (!sln && !up) return;
|
||||
setBuildLog([]); setBuildOk(null); setBuilding(true); setBuildOpen(true); setBuildMin(false);
|
||||
try { await p4.buildSln(slnPath, config, uproject); }
|
||||
try { await p4.buildSln(sln, config, up); }
|
||||
catch { /* the overlay already shows the failure line */ }
|
||||
}
|
||||
|
||||
@ -1277,7 +1316,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
const isCode = isCodeFile(splitPath(dp).name);
|
||||
openCtx(e, [
|
||||
{ label: targets.length > 1 ? t("Discard changes · {n} files", { n: targets.length }) : t("Discard changes"), icon: I.trash, danger: true, act: () => discard(targets) },
|
||||
{ label: t("Lock (exclusive)"), icon: I.lock, act: () => lockFiles(dps, true) },
|
||||
{ label: t("Lock against submit"), icon: I.lock, act: () => lockFiles(dps, true) },
|
||||
{ label: t("Unlock"), icon: I.unlock, act: () => lockFiles(dps, false) },
|
||||
{ label: t("Set exclusive-lock type (+l)"), icon: I.lock, act: () => setExclusiveType(dps) },
|
||||
...(workOffline ? [{ label: t("Make writable (offline edit)"), icon: I.unlock, act: () => makeWritable(targets) }] : []),
|
||||
@ -1286,7 +1325,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
...(isCode ? [{ label: t("Blame (annotate)"), icon: I.people, act: () => setModal({ kind: "blame", spec: dp, name: splitPath(dp).name }) }] : []),
|
||||
{ label: t("Open in Explorer"), icon: I.reveal, act: () => reveal(dp) },
|
||||
{ label: t("Copy path"), icon: I.copy, act: () => copyText(dp, t("Path")) },
|
||||
...getRegistry().fileItems.map((fi) => ({ label: fi.label, icon: I.hex, act: () => { void Promise.resolve(fi.run(view[i] as { depotFile?: string })).catch((err) => flash(String(err), true)); } })),
|
||||
...getRegistry().fileItems.map((fi) => ({ label: fi.label, icon: pluginIcon(fi.icon), act: () => { void Promise.resolve(fi.run(view[i] as { depotFile?: string })).catch((err) => flash(String(err), true)); } })),
|
||||
]);
|
||||
}
|
||||
async function lockFiles(dps: string[], lock: boolean) {
|
||||
@ -1294,6 +1333,15 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
try { await (lock ? p4.lock(dps) : p4.unlock(dps)); flash(lock ? t("Locked {n} file(s).", { n: dps.length }) : t("Unlocked {n} file(s).", { n: dps.length })); await refresh(); }
|
||||
catch (e) { flash(String(e), true); }
|
||||
}
|
||||
// `p4 edit`; an exclusive (+l) file held elsewhere comes back without a record
|
||||
async function checkOut(paths: string[]) {
|
||||
try {
|
||||
const r = await p4.edit(paths);
|
||||
const all = r.length >= paths.length;
|
||||
flash(all ? t("{n} file(s) checked out.", { n: r.length }) : t("Checked out {n} of {total}. The rest are held by someone else.", { n: r.length, total: paths.length }), !all);
|
||||
await refresh();
|
||||
} catch (e) { flash(String(e), true); }
|
||||
}
|
||||
// switch opened files to an exclusive-lock file type (+l) so only one person edits them
|
||||
async function setExclusiveType(dps: string[]) {
|
||||
if (!dps.length) return;
|
||||
@ -1356,6 +1404,16 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
const showBlame = (spec: string, name: string) => setModal({ kind: "blame", spec, name });
|
||||
|
||||
async function doResolve(mode: "am" | "ay" | "at", file = "") {
|
||||
if (mode !== "am") {
|
||||
const name = file ? splitPath(file).name : t("{n} files", { n: needResolve.length });
|
||||
const theirs = mode === "at";
|
||||
if (!(await confirm({
|
||||
title: theirs ? t("Accept theirs for {name}?", { name }) : t("Accept yours for {name}?", { name }),
|
||||
body: theirs ? t("Your local changes in these files are replaced by the server version.") : t("Changes made on the server are dropped and your version wins."),
|
||||
confirm: theirs ? t("Accept theirs") : t("Accept yours"),
|
||||
danger: true,
|
||||
}))) return;
|
||||
}
|
||||
try {
|
||||
await p4.resolveFile(file, mode);
|
||||
const rest = await p4.resolveList();
|
||||
@ -1397,6 +1455,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
{ label: (viewTabs.includes("locks") ? "✓ " : "") + t("File Locks"), icon: I.lock, hint: t("Everyone's checked-out / exclusively-locked files, docked into the view panel."), act: () => toggleViewTab("locks") },
|
||||
{ label: (dockOpen && dockTab === "log" ? "✓ " : "") + t("Log"), kb: "Ctrl+L", icon: I.log, hint: t("Show the panel of recently run Perforce commands."), act: () => openDock("log") },
|
||||
{ label: (dockOpen && dockTab === "terminal" ? "✓ " : "") + t("Terminal"), kb: "Ctrl+`", icon: I.terminal, hint: t("Open an embedded terminal for raw p4 commands."), act: () => openDock("terminal") },
|
||||
...getRegistry().docks.map((d) => ({ label: (dockOpen && dockTab === `plugin:${d.id}` ? "✓ " : "") + d.title, icon: pluginIcon(d.icon), hint: t("From plugin: {p}", { p: d.pluginId }), act: () => openDock(`plugin:${d.id}`) })),
|
||||
],
|
||||
Tools: [
|
||||
{ label: t("Search depot…"), icon: I.search, hint: t("Find files anywhere in the depot by name or path."), act: () => setModal({ kind: "search" }) },
|
||||
@ -1407,7 +1466,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
{ label: t("Streams…"), icon: I.branch, hint: t("Switch stream, merge down from the parent, or copy up to it."), act: () => setModal({ kind: "streams" }) },
|
||||
{ label: t("Jobs…"), icon: I.log, hint: t("Perforce's task/bug tracker — create jobs and attach them to changelists."), act: () => setModal({ kind: "jobs" }) },
|
||||
{ label: t("Edit .p4ignore…"), icon: I.gear, hint: t("Edit which files reconcile / add ignore (build output, caches)."), act: () => setModal({ kind: "ignore" }) },
|
||||
...getRegistry().menu.map((m) => ({ label: m.label, icon: I.hex, hint: t("From plugin: {p}", { p: m.pluginId }), act: () => { void Promise.resolve(m.run()).catch((e) => flash(String(e), true)); } })),
|
||||
...getRegistry().menu.map((m) => ({ label: m.label, icon: pluginIcon(m.icon), hint: t("From plugin: {p}", { p: m.pluginId }), act: () => { void Promise.resolve(m.run()).catch((e) => flash(String(e), true)); } })),
|
||||
...getRegistry().views.map((v) => ({ label: v.title, icon: I.hex, hint: t("Plugin view"), act: () => setPluginView(v) })),
|
||||
{ label: t("People & Roles…"), icon: I.people, hint: t("See who works on this depot and their roles."), act: () => setModal({ kind: "users" }) },
|
||||
{ label: t("Settings…"), icon: I.gear, hint: t("App preferences — language, theme, editor, and more."), act: () => setModal({ kind: "settings" }) },
|
||||
@ -1460,7 +1519,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
...(activePath ? [{ label: t("Rename…"), icon: I.pencil, act: () => renameFolder(activePath) }] : []),
|
||||
...(activePath ? [{ label: t("Properties"), icon: I.info, act: () => setModal({ kind: "folderprops", path: activePath, name: splitPath(activePath).name || activePath }) }] : []),
|
||||
{ label: t("Show in File Tree"), icon: I.folder, act: () => showInTree("depot") },
|
||||
...(uproject ? [{ label: t("Launch Unreal Engine"), icon: I.ue, act: launchUE }] : []),
|
||||
...getRegistry().folderItems.filter((f) => !f.visible || f.visible()).map((f) => ({ label: f.label, icon: pluginIcon(f.icon), act: () => { void Promise.resolve(f.run()).catch((e) => flash(String(e), true)); } })),
|
||||
{ label: t("Open in Explorer"), icon: I.reveal, act: () => reveal(activePath || String(info?.clientRoot || "")) },
|
||||
{ label: t("Choose another folder…"), icon: I.folder, act: () => browseTo("") },
|
||||
{ label: t("Copy path"), icon: I.copy, act: () => copyText(activePath || "//…", t("Path")) },
|
||||
@ -1693,7 +1752,7 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
</div>
|
||||
|
||||
{dockOpen && <DockPanel tab={dockTab} setTab={setDockTab} onClose={() => setDockOpen(false)}
|
||||
height={dockH} onResize={startDockResize}
|
||||
height={dockH} onResize={startDockResize} docks={getRegistry().docks}
|
||||
logs={logs} onClearLogs={() => setLogs([])}
|
||||
termLines={termLines} termInput={termInput} setTermInput={setTermInput} termBusy={termBusy}
|
||||
onRun={runConsole} cmdHist={cmdHist} onClearTerm={() => setTermLines([])} />}
|
||||
@ -1704,11 +1763,32 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
<span className="stlast">{logs.length ? `${logs[logs.length - 1].cmd} ${logCount(logs[logs.length - 1])}` : "p4 — ready"}</span>
|
||||
</span>
|
||||
<span className="stspace" />
|
||||
{/* Plugin dock panels get a status-bar button too — a dock tab you can't
|
||||
open from anywhere is just a hidden tab. Listed before the built-ins so
|
||||
Terminal/Log keep their place as plugins come and go. */}
|
||||
{getRegistry().docks.map((d) => (
|
||||
<button key={`${d.pluginId}:${d.id}`} className="stlog"
|
||||
onClick={() => openDock(`plugin:${d.id}`)}
|
||||
title={t("From plugin: {p}", { p: d.pluginId })}>
|
||||
{pluginIcon(d.icon)}<span>{d.title}</span>
|
||||
</button>
|
||||
))}
|
||||
<button className="stlog" onClick={() => openDock("terminal")} title="Ctrl+`">{I.terminal}<span>{t("Terminal")}</span></button>
|
||||
<button className="stlog" onClick={() => openDock("log")} title="Ctrl+L">{I.log}<span>Log</span></button>
|
||||
<button className="stlog" onClick={() => window.dispatchEvent(new Event("exd-check-update"))} title={t("Check for updates")}>
|
||||
<svg viewBox="0 0 24 24" fill="none"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
|
||||
<span>{t("Updates")}</span>
|
||||
<button
|
||||
className={"stlog stupd icon" + (upd.phase === "available" ? " has" : "") + (upd.phase === "downloading" || upd.phase === "checking" ? " busy" : "")}
|
||||
onClick={() => (upd.phase === "available" ? upd.install() : upd.check())}
|
||||
disabled={upd.phase === "downloading"}
|
||||
title={
|
||||
upd.phase === "available" ? t("Update available — click to install")
|
||||
: upd.phase === "downloading" ? t("Downloading… {pct}%", { pct: upd.pct })
|
||||
: upd.phase === "done" ? t("Installed — restarting…")
|
||||
: t("Check for updates")
|
||||
}>
|
||||
{upd.phase === "checking" || upd.phase === "downloading"
|
||||
? <span className="ldr sm" />
|
||||
: <svg viewBox="0 0 24 24" fill="none"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>}
|
||||
{upd.phase === "available" && <span className="stupd-dot" />}
|
||||
</button>
|
||||
{peek && logs.length > 0 && (
|
||||
<div className="logpeek" onMouseEnter={showPeek} onMouseLeave={hidePeek}>
|
||||
@ -1755,6 +1835,10 @@ function Workbench({ info, session, light, toggleTheme, themeId, setThemeId, lan
|
||||
{showXfer && transfer && xferMin && <TransferChip transfer={transfer} onExpand={() => setXferMin(false)} onCancel={cancelTransfer} />}
|
||||
{buildPick && <BuildPicker onPick={buildSln} onClose={() => setBuildPick(false)} />}
|
||||
{buildOpen && !buildMin && <BuildOverlay lines={buildLog} building={building} ok={buildOk} sln={slnPath} onMinimize={() => setBuildMin(true)} onClose={() => setBuildOpen(false)} />}
|
||||
{/* last in the tree so it sits over every other overlay — nothing else
|
||||
can succeed until the session is back */}
|
||||
{reauth && <ReauthModal session={session} onSignOut={onDisconnect}
|
||||
onDone={(i) => { setReauth(false); setOffline(false); onInfo(i); flash(t("Reconnected to the server.")); void refresh(); }} />}
|
||||
{buildOpen && buildMin && <BuildChip building={building} ok={buildOk} onExpand={() => setBuildMin(false)} onClose={() => setBuildOpen(false)} />}
|
||||
{ctx && <ContextMenu x={ctx.x} y={ctx.y} items={ctx.items} onClose={() => setCtx(null)} />}
|
||||
{toast && <div className={"toast" + (toast.err ? " err" : "")}>{toast.text}</div>}
|
||||
@ -2059,18 +2143,20 @@ function LogRow({ l }: { l: LogEntry }) {
|
||||
// common p4 subcommands for the terminal's autocomplete
|
||||
const P4_COMMANDS = ["add","annotate","branch","branches","change","changes","client","clients","counter","counters","delete","depot","depots","describe","diff","dirs","edit","filelog","files","fstat","group","groups","have","info","integrate","labels","login","logout","monitor","move","opened","print","protect","reconcile","reopen","resolve","resolved","revert","reviews","shelve","sizes","status","stream","streams","submit","sync","tag","tickets","unshelve","user","users","where"];
|
||||
|
||||
/* ---------------- bottom dock: tabbed Log / Terminal / Unreal ---------------- */
|
||||
function DockPanel({ tab, setTab, onClose, height, onResize, logs, onClearLogs, termLines, termInput, setTermInput, termBusy, onRun, cmdHist, onClearTerm }: {
|
||||
tab: "log" | "terminal" | "unreal"; setTab: (t: "log" | "terminal" | "unreal") => void; onClose: () => void;
|
||||
height: number; onResize: (e: ReactMouseEvent) => void;
|
||||
/* ---------------- bottom dock: tabbed Log / Terminal + plugin dock panels ---------------- */
|
||||
function DockPanel({ tab, setTab, onClose, height, onResize, docks, logs, onClearLogs, termLines, termInput, setTermInput, termBusy, onRun, cmdHist, onClearTerm }: {
|
||||
tab: string; setTab: (t: string) => void; onClose: () => void;
|
||||
height: number; onResize: (e: ReactMouseEvent) => void; docks: PluginDock[];
|
||||
logs: LogEntry[]; onClearLogs: () => void;
|
||||
termLines: TermLine[]; termInput: string; setTermInput: (s: string) => void; termBusy: boolean;
|
||||
onRun: (cmd: string) => void; cmdHist: string[]; onClearTerm: () => void;
|
||||
}) {
|
||||
const tabs: { key: "log" | "terminal" | "unreal"; label: string; icon: ReactNode }[] = [
|
||||
const tabs: { key: string; label: string; icon: ReactNode }[] = [
|
||||
{ key: "log", label: t("Log"), icon: I.log },
|
||||
{ key: "terminal", label: t("Terminal"), icon: I.terminal },
|
||||
...docks.map((d) => ({ key: `plugin:${d.id}`, label: d.title, icon: pluginIcon(d.icon) })),
|
||||
];
|
||||
const activeDock = tab.startsWith("plugin:") ? docks.find((d) => `plugin:${d.id}` === tab) : undefined;
|
||||
return (
|
||||
<div className="dockpanel" style={{ flexBasis: height, height }}>
|
||||
<div className="dockhandle" onMouseDown={onResize} title={t("Drag to resize")} />
|
||||
@ -2090,11 +2176,26 @@ function DockPanel({ tab, setTab, onClose, height, onResize, logs, onClearLogs,
|
||||
<div className="dockpane" key={tab}>
|
||||
{tab === "log" && <LogTab logs={logs} />}
|
||||
{tab === "terminal" && <TerminalTab lines={termLines} input={termInput} setInput={setTermInput} busy={termBusy} onRun={onRun} cmdHist={cmdHist} />}
|
||||
{activeDock && <PluginDockPanel dock={activeDock} />}
|
||||
{tab.startsWith("plugin:") && !activeDock && <div className="logempty">{t("This panel's plugin is no longer active.")}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Host for a plugin-provided dock panel: mounts the plugin's render() into a div
|
||||
// and runs its cleanup on unmount / tab switch. Same pattern as PluginViewModal.
|
||||
function PluginDockPanel({ dock }: { dock: PluginDock }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const el = ref.current; if (!el) return;
|
||||
let cleanup: void | (() => void);
|
||||
try { cleanup = dock.render(el); } catch (e) { el.textContent = String(e); }
|
||||
return () => { try { (cleanup as (() => void) | undefined)?.(); } catch { /* ignore */ } el.innerHTML = ""; };
|
||||
}, [dock]);
|
||||
return <div className="dockplugin" ref={ref} style={{ height: "100%", overflow: "auto" }} />;
|
||||
}
|
||||
|
||||
function LogTab({ logs }: { logs: LogEntry[] }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => { if (ref.current) ref.current.scrollTop = ref.current.scrollHeight; }, [logs]);
|
||||
@ -2340,6 +2441,65 @@ function TextPrompt({ title, label, value, onSave, onClose }: { title: string; l
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------- re-authenticate (expired ticket) ----------------
|
||||
Perforce expires the login ticket on its own schedule, so a long day
|
||||
outlives it and every command starts failing. The server is still there and
|
||||
the workspace is untouched — only the ticket died — so we ask for the
|
||||
password over the running app instead of dropping back to the Connect
|
||||
screen, which would throw away the scope, selection and open panels.
|
||||
Deliberately not dismissable by clicking away: nothing works until it's
|
||||
resolved one way or the other. */
|
||||
function ReauthModal({ session, onDone, onSignOut }: {
|
||||
session: Session | null; onDone: (i: P4Info) => void; onSignOut: () => void;
|
||||
}) {
|
||||
const [password, setPassword] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
const ref = useRef<HTMLInputElement>(null);
|
||||
useEffect(() => { ref.current?.focus(); }, []);
|
||||
|
||||
async function reconnect() {
|
||||
if (!session || !password || busy) return;
|
||||
setBusy(true); setErr("");
|
||||
try {
|
||||
const i = await p4.login(session.server, session.user, password, session.client);
|
||||
setPassword("");
|
||||
onDone(i);
|
||||
} catch (e) { setErr(String(e)); setBusy(false); }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal-back">
|
||||
<div className="modal-card prompt" onClick={(e) => e.stopPropagation()}>
|
||||
<h3>{t("Session expired")}</h3>
|
||||
<div className="prompt-label">
|
||||
{t("Perforce ended the session. Sign in again to carry on — your workspace and open changes are untouched.")}
|
||||
</div>
|
||||
<div className="reauth-who">
|
||||
<span>{session?.user}</span>
|
||||
<span>{session?.client}</span>
|
||||
<span>{session?.server}</span>
|
||||
</div>
|
||||
<div className="fld"><label>{t("Password")}</label>
|
||||
<div className="inp">
|
||||
<svg viewBox="0 0 24 24" fill="none"><rect x="4" y="10" width="16" height="10" rx="2" stroke="currentColor" strokeWidth="1.6" /><path d="M8 10V7a4 4 0 0 1 8 0v3" stroke="currentColor" strokeWidth="1.6" /></svg>
|
||||
<input ref={ref} type="password" value={password} disabled={busy}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && reconnect()} />
|
||||
</div>
|
||||
</div>
|
||||
{err && <div className="err"><span>⚠</span><span>{err}</span></div>}
|
||||
<div className="modal-actions">
|
||||
<button className="mbtn ghost" onClick={onSignOut} disabled={busy}>{t("Sign out")}</button>
|
||||
<button className="mbtn primary" onClick={reconnect} disabled={busy || !password}>
|
||||
{busy ? t("Connecting…") : t("Reconnect")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------- confirm modal ---------------- */
|
||||
function ConfirmModal({ title, body, confirm, danger, onClose }: { title: string; body: string; confirm: string; danger?: boolean; onClose: (v: boolean) => void }) {
|
||||
const btn = useRef<HTMLButtonElement>(null);
|
||||
@ -2417,6 +2577,12 @@ function SearchModal({ scope, onClose, onOpenEditor, onReveal, onCopy }: { scope
|
||||
}
|
||||
|
||||
/* ---------------- file locks viewer — who has what locked/open across the depot ---------------- */
|
||||
// held by someone: a `p4 lock`, or an open of an exclusive (+l) file type
|
||||
function isHeld(f: OpenedFile): boolean {
|
||||
const r = f as Record<string, unknown>;
|
||||
return r.ourLock !== undefined || /\+\w*l/.test(String(r.type || ""));
|
||||
}
|
||||
|
||||
// the File Locks list (bar + rows), reused by the modal AND the dockable panel
|
||||
function LocksPanel({ me, onReveal, onFlash, onUnlock }: { me: string; onReveal: (dp: string) => void; onFlash: (t: string, e?: boolean) => void; onUnlock: (dp: string) => void }) {
|
||||
const [files, setFiles] = useState<OpenedFile[]>([]);
|
||||
@ -2424,8 +2590,9 @@ function LocksPanel({ me, onReveal, onFlash, onUnlock }: { me: string; onReveal:
|
||||
const [q, setQ] = useState("");
|
||||
const [lockedOnly, setLockedOnly] = useState(true);
|
||||
const load = () => { setBusy(true); p4.openedAll("").then(setFiles).catch((e) => { onFlash(String(e), true); setFiles([]); }).finally(() => setBusy(false)); };
|
||||
useEffect(() => { load(); }, []); // eslint-disable-line
|
||||
const isLocked = (f: OpenedFile) => (f as Record<string, unknown>).ourLock !== undefined;
|
||||
const [admin, setAdmin] = useState(false);
|
||||
useEffect(() => { load(); p4.protectsMax().then((a) => setAdmin(/^(admin|super)$/i.test(a))).catch(() => {}); }, []); // eslint-disable-line
|
||||
const isLocked = isHeld;
|
||||
const s = q.trim().toLowerCase();
|
||||
const rows = files.filter((f) => (!lockedOnly || isLocked(f)) && (!s || (f.depotFile || "").toLowerCase().includes(s) || (f.user || "").toLowerCase().includes(s)));
|
||||
return (
|
||||
@ -2443,12 +2610,14 @@ function LocksPanel({ me, onReveal, onFlash, onUnlock }: { me: string; onReveal:
|
||||
const sp = splitPath(dp);
|
||||
const locked = isLocked(f);
|
||||
const mine = (f.user || "").toLowerCase() === me.toLowerCase();
|
||||
const hasLock = (f as Record<string, unknown>).ourLock !== undefined; // `p4 unlock` can't release a +l open
|
||||
return (
|
||||
<div key={dp + (f.client || "")} className="srch-row">
|
||||
<span className={"held" + (locked ? " locked" : "")} style={{ marginRight: 4 }}>{locked ? I.lock : I.unlock}</span>
|
||||
<span className="srch-body"><span className="n">{sp.name}</span><span className="p">{sp.dir}</span></span>
|
||||
<span className="lk-who">{f.user}{mine ? " · " + t("you") : ""}<span className="lk-client">{f.client}</span></span>
|
||||
{locked && mine && <button className="rslv-act" title={t("Unlock")} onClick={() => { onUnlock(dp); setTimeout(load, 400); }}>{t("Unlock")}</button>}
|
||||
{hasLock && mine && <button className="rslv-act" title={t("Unlock")} onClick={() => { onUnlock(dp); setTimeout(load, 400); }}>{t("Unlock")}</button>}
|
||||
{hasLock && !mine && admin && <button className="rslv-act" title={t("Force unlock")} onClick={() => { p4.unlockForce([dp]).then(load).catch((e) => onFlash(String(e), true)); }}>{t("Force unlock")}</button>}
|
||||
<button className="srch-act" title={t("Open in Explorer")} onClick={() => onReveal(dp)}>{I.folder}</button>
|
||||
</div>
|
||||
);
|
||||
@ -2697,7 +2866,7 @@ function ExpNode({ node, depth, load, max, onReveal, onFlash, onOpen, onMenu }:
|
||||
const childMax = Math.max(1, ...(kids || []).map((k) => k.size));
|
||||
return (
|
||||
<div className="exp-node">
|
||||
<div className={"exp-row" + (node.isDir || onOpen ? " dir" : "")} style={{ paddingLeft: 10 + depth * 15 }} onClick={activate} onContextMenu={(e) => { if (node.isDir && onMenu) { e.preventDefault(); e.stopPropagation(); onMenu(node, e); } }} title={node.path}>
|
||||
<div className={"exp-row" + (node.isDir || onOpen ? " dir" : "")} style={{ paddingLeft: 10 + depth * 15 }} onClick={activate} onContextMenu={(e) => { if (onMenu) { e.preventDefault(); e.stopPropagation(); onMenu(node, e); } }} title={node.path}>
|
||||
<span className="exp-caret">{node.isDir ? (busy ? <span className="ldr sm" /> : <span className={"chevi" + (open ? " open" : "")}>{I.chevron}</span>) : null}</span>
|
||||
<span className="exp-ic">{node.isDir ? I.folder : FILE_GLYPH}</span>
|
||||
<span className="exp-name">{node.name}</span>
|
||||
@ -3249,12 +3418,17 @@ function PluginsModal({ onClose, onReload, onFlash, embedded }: { onClose?: () =
|
||||
const [busy, setBusy] = useState(true);
|
||||
const [dir, setDir] = useState("");
|
||||
const [reg, setReg] = useState<RegistryEntry[]>([]);
|
||||
const [regBusy, setRegBusy] = useState(true);
|
||||
const [regErr, setRegErr] = useState("");
|
||||
const [installing, setInstalling] = useState<string>("");
|
||||
const load = () => { setBusy(true); p4.pluginList().then(setList).catch((e) => onFlash(String(e), true)).finally(() => setBusy(false)); };
|
||||
useEffect(() => { load(); p4.pluginsDirPath().then(setDir).catch(() => {}); fetchRegistry().then(setReg).catch(() => {}); const k = (e: KeyboardEvent) => e.key === "Escape" && onClose?.(); document.addEventListener("keydown", k); return () => document.removeEventListener("keydown", k); }, []); // eslint-disable-line
|
||||
const loadReg = () => { setRegBusy(true); setRegErr(""); fetchRegistry().then(setReg).catch((e) => setRegErr(String(e))).finally(() => setRegBusy(false)); };
|
||||
useEffect(() => { load(); loadReg(); p4.pluginsDirPath().then(setDir).catch(() => {}); const k = (e: KeyboardEvent) => e.key === "Escape" && onClose?.(); document.addEventListener("keydown", k); return () => document.removeEventListener("keydown", k); }, []); // eslint-disable-line
|
||||
async function installReg(entry: RegistryEntry) {
|
||||
const perms = (entry.permissions || []).join(", ") || "—";
|
||||
if (!(await askDialog(t("A plugin runs with full access to this app, including your Perforce session. Declared permissions: {perms}.", { perms }), { title: t("Install plugin “{name}”?", { name: entry.name }), kind: "warning" }))) return;
|
||||
setInstalling(entry.id);
|
||||
try { await installFromRegistry(entry); load(); await onReload(); onFlash(t("Installed plugin “{id}”.", { id: entry.name })); }
|
||||
try { await installFromRegistry(entry); await p4.pluginSetEnabled(entry.id, true); load(); await onReload(); onFlash(t("Installed plugin “{id}”.", { id: entry.name })); }
|
||||
catch (e) { onFlash(String(e), true); }
|
||||
finally { setInstalling(""); }
|
||||
}
|
||||
@ -3274,7 +3448,7 @@ function PluginsModal({ onClose, onReload, onFlash, embedded }: { onClose?: () =
|
||||
} catch (e) { onFlash(String(e), true); }
|
||||
}
|
||||
const body = (<>
|
||||
<div className="tm-hint">{t("Plugins add features on top of the core app. Install a folder with a plugin.json, toggle plugins on/off, then they load automatically. Plugins run in-app — only install ones you trust.")}</div>
|
||||
<div className="tm-hint">{t("Plugins add features on top of the core app. Browse the catalog below and install what you need — nothing is installed automatically. Toggle plugins on/off; enabled ones load on launch. Plugins run in-app — only install ones you trust.")}</div>
|
||||
<div className="pl-list">
|
||||
{busy ? <div className="ur-empty"><span className="ldr" /> {t("Loading…")}</div>
|
||||
: list.length === 0 ? <div className="ur-empty">{I.hex}{t("No plugins installed yet.\nInstall one from a folder, or drop it into the plugins folder below.")}</div>
|
||||
@ -3294,9 +3468,12 @@ function PluginsModal({ onClose, onReload, onFlash, embedded }: { onClose?: () =
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{reg.filter((e) => !list.some((p) => p.id === e.id)).length > 0 && (<>
|
||||
<div className="pl-official-h">{t("Official plugins")}</div>
|
||||
{reg.filter((e) => !list.some((p) => p.id === e.id)).map((e) => (
|
||||
<div className="pl-official-h">{t("Available to install")}<span className="pl-cat-sub">{t("from the Exbyte plugin registry")}</span></div>
|
||||
{regBusy ? <div className="ur-empty"><span className="ldr" /> {t("Loading the plugin catalog…")}</div>
|
||||
: regErr ? <div className="ur-empty">{I.hex}{t("Couldn't reach the plugin registry.")}<button className="mbtn ghost" style={{ flex: "none", padding: "6px 12px", marginTop: 8 }} onClick={loadReg}>{I.sync}{t("Retry")}</button></div>
|
||||
: reg.filter((e) => !list.some((p) => p.id === e.id)).length === 0
|
||||
? <div className="ur-empty">{I.check}{t("Everything from the catalog is already installed.")}</div>
|
||||
: reg.filter((e) => !list.some((p) => p.id === e.id)).map((e) => (
|
||||
<div key={e.id} className="pl-card">
|
||||
<div className="pl-main">
|
||||
<div className="pl-top"><b>{e.name}</b><span className="pl-ver">v{e.version}</span></div>
|
||||
@ -3308,7 +3485,6 @@ function PluginsModal({ onClose, onReload, onFlash, embedded }: { onClose?: () =
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>)}
|
||||
</div>
|
||||
<div className="modal-actions" style={{ padding: "12px 16px", borderTop: "1px solid var(--border-soft)" }}>
|
||||
<button className="mbtn ghost" onClick={() => p4.openPluginsDir().catch(() => {})} title={dir}>{I.reveal}{t("Open plugins folder")}</button>
|
||||
|
||||
118
src/Updater.tsx
118
src/Updater.tsx
@ -1,53 +1,44 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { check, type Update } from "@tauri-apps/plugin-updater";
|
||||
import { relaunch } from "@tauri-apps/plugin-process";
|
||||
import { t } from "./i18n";
|
||||
|
||||
type Phase = "idle" | "checking" | "available" | "uptodate" | "downloading" | "done" | "error";
|
||||
export type UpdPhase = "idle" | "checking" | "available" | "uptodate" | "downloading" | "done" | "error";
|
||||
|
||||
// Update prompt. Quietly checks the Gitea Releases endpoint a few seconds after
|
||||
// launch, and again on demand when the "Updates" button fires `exd-check-update`.
|
||||
// If a newer signed version exists, slides a small card into the bottom-right.
|
||||
export default function UpdateBanner() {
|
||||
export interface UpdaterState {
|
||||
phase: UpdPhase;
|
||||
pct: number;
|
||||
err: string;
|
||||
version?: string;
|
||||
check: () => void; // manual check
|
||||
install: () => void; // download + install the pending update
|
||||
}
|
||||
|
||||
// Update logic as a hook. Silently checks the Gitea Releases endpoint a few
|
||||
// seconds after mount, and again on demand (manual). The UI is just a single
|
||||
// download icon in the status bar (see Workbench) — no floating card.
|
||||
export function useUpdater(): UpdaterState {
|
||||
const [update, setUpdate] = useState<Update | null>(null);
|
||||
const [phase, setPhase] = useState<Phase>("idle");
|
||||
const [phase, setPhase] = useState<UpdPhase>("idle");
|
||||
const [pct, setPct] = useState(0);
|
||||
const [err, setErr] = useState("");
|
||||
const [hidden, setHidden] = useState(false);
|
||||
const busyRef = useRef(false);
|
||||
|
||||
// shared check routine. `manual` shows "checking" / "up to date" feedback.
|
||||
async function runCheck(manual: boolean) {
|
||||
if (busyRef.current || phase === "downloading") return;
|
||||
busyRef.current = true;
|
||||
if (manual) { setHidden(false); setPhase("checking"); }
|
||||
if (manual) setPhase("checking");
|
||||
try {
|
||||
const u = await check();
|
||||
if (u) { setUpdate(u); setPhase("available"); setHidden(false); }
|
||||
else if (manual) { setPhase("uptodate"); setHidden(false); }
|
||||
else setPhase("idle");
|
||||
if (u) { setUpdate(u); setPhase("available"); }
|
||||
else { setPhase(manual ? "uptodate" : "idle"); }
|
||||
} catch (e) {
|
||||
if (manual) { setErr(String(e)); setPhase("error"); setHidden(false); }
|
||||
setErr(String(e));
|
||||
if (manual) setPhase("error");
|
||||
} finally { busyRef.current = false; }
|
||||
}
|
||||
|
||||
// initial silent check + listen for manual "Updates" clicks
|
||||
useEffect(() => {
|
||||
const id = setTimeout(() => runCheck(false), 4000);
|
||||
const onManual = () => runCheck(true);
|
||||
window.addEventListener("exd-check-update", onManual);
|
||||
return () => { clearTimeout(id); window.removeEventListener("exd-check-update", onManual); };
|
||||
}, []); // eslint-disable-line
|
||||
|
||||
// auto-dismiss the transient "up to date" card
|
||||
useEffect(() => {
|
||||
if (phase !== "uptodate") return;
|
||||
const id = setTimeout(() => { setHidden(true); setPhase("idle"); }, 3500);
|
||||
return () => clearTimeout(id);
|
||||
}, [phase]);
|
||||
|
||||
async function install() {
|
||||
if (!update) return;
|
||||
if (!update) { void runCheck(true); return; }
|
||||
setPhase("downloading"); setPct(0);
|
||||
let total = 0, got = 0;
|
||||
try {
|
||||
@ -61,59 +52,20 @@ export default function UpdateBanner() {
|
||||
} catch (e) { setErr(String(e)); setPhase("error"); }
|
||||
}
|
||||
|
||||
if (hidden || phase === "idle") return null;
|
||||
// initial silent check + listen for manual "Updates" clicks (kept for compatibility)
|
||||
useEffect(() => {
|
||||
const id = setTimeout(() => runCheck(false), 4000);
|
||||
const onManual = () => runCheck(true);
|
||||
window.addEventListener("exd-check-update", onManual);
|
||||
return () => { clearTimeout(id); window.removeEventListener("exd-check-update", onManual); };
|
||||
}, []); // eslint-disable-line
|
||||
|
||||
// compact cards for the transient states (no `update` object yet)
|
||||
if (phase === "checking") {
|
||||
return <div className="upd sm"><div className="upd-head"><span className="upd-ic"><span className="ldr sm" /></span><div className="upd-ttl"><b>{t("Checking for updates…")}</b></div></div></div>;
|
||||
}
|
||||
if (phase === "uptodate") {
|
||||
return <div className="upd sm ok" onClick={() => { setHidden(true); setPhase("idle"); }}>
|
||||
<div className="upd-head"><span className="upd-ic ok"><svg viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5 9-11" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" /></svg></span>
|
||||
<div className="upd-ttl"><b>{t("You're on the latest version")}</b></div></div>
|
||||
</div>;
|
||||
}
|
||||
if (phase === "error") {
|
||||
return <div className="upd sm"><div className="upd-head"><span className="upd-ic"><svg viewBox="0 0 24 24" fill="none"><path d="M12 8v5m0 3h.01M10.3 4l-7 12A1.5 1.5 0 0 0 4.6 18h14.8a1.5 1.5 0 0 0 1.3-2L13.7 4a1.5 1.5 0 0 0-3.4 0Z" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg></span>
|
||||
<div className="upd-ttl"><b>{t("Update check failed")}</b><span>{err.slice(0, 80)}</span></div>
|
||||
<button className="upd-x" onClick={() => { setHidden(true); setPhase("idle"); }}><svg viewBox="0 0 24 24" width="13" height="13" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg></button></div>
|
||||
</div>;
|
||||
}
|
||||
if (!update) return null;
|
||||
// let the transient "checked, up to date" / "error" state fade back to idle
|
||||
useEffect(() => {
|
||||
if (phase !== "uptodate" && phase !== "error") return;
|
||||
const id = setTimeout(() => setPhase("idle"), 3500);
|
||||
return () => clearTimeout(id);
|
||||
}, [phase]);
|
||||
|
||||
return (
|
||||
<div className="upd">
|
||||
<div className="upd-head">
|
||||
<span className="upd-ic">
|
||||
<svg viewBox="0 0 24 24" fill="none"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
|
||||
</span>
|
||||
<div className="upd-ttl">
|
||||
<b>{t("Update available")}</b>
|
||||
<span>Exbyte Depot v{update.version}</span>
|
||||
</div>
|
||||
{phase === "available" && (
|
||||
<button className="upd-x" onClick={() => setHidden(true)} title={t("Later")}>
|
||||
<svg viewBox="0 0 24 24" width="13" height="13" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{update.body?.trim() && phase === "available" && <div className="upd-notes">{update.body.trim()}</div>}
|
||||
|
||||
{phase === "downloading" && (
|
||||
<div className="upd-prog">
|
||||
<div className="upd-track"><div className="upd-fill" style={{ width: `${pct}%` }} /></div>
|
||||
<span>{t("Downloading… {pct}%", { pct })}</span>
|
||||
</div>
|
||||
)}
|
||||
{phase === "done" && <div className="upd-notes">{t("Installed — restarting…")}</div>}
|
||||
|
||||
{phase === "available" && (
|
||||
<div className="upd-actions">
|
||||
<button className="upd-later" onClick={() => setHidden(true)}>{t("Later")}</button>
|
||||
<button className="upd-go" onClick={install}>{t("Update now")}</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
return { phase, pct, err, version: update?.version, check: () => runCheck(true), install };
|
||||
}
|
||||
|
||||
@ -9,7 +9,7 @@ function langName(): string { return LANG_NAMES[LANG] || "English"; }
|
||||
// fixed model — no user-facing AI settings
|
||||
export const DEFAULT_MODEL = "openai/gpt-4o-mini";
|
||||
|
||||
// the key is baked into the binary at build time (src-tauri/openrouter.key)
|
||||
// the key lives in the app config dir (openrouter.key); none ships with the build
|
||||
export async function resolveKey(): Promise<string> {
|
||||
try { return (await p4.readAiKey()) || ""; } catch { return ""; }
|
||||
}
|
||||
@ -17,7 +17,7 @@ export async function resolveKey(): Promise<string> {
|
||||
// generate a commit summary + description from the changed files
|
||||
export async function aiSummary(files: OpenedFile[]): Promise<{ summary: string; description: string }> {
|
||||
const key = await resolveKey();
|
||||
if (!key) throw new Error("No OpenRouter API key baked into this build");
|
||||
if (!key) throw new Error("No OpenRouter API key configured");
|
||||
const list = files.slice(0, 200).map((f) => `${statusOf(f.action).ch} ${f.depotFile || ""}`).join("\n");
|
||||
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
|
||||
method: "POST",
|
||||
@ -48,7 +48,7 @@ export async function aiSummary(files: OpenedFile[]): Promise<{ summary: string;
|
||||
// briefly explain what a source file does (2–4 sentences, plain text)
|
||||
export async function aiExplainCode(name: string, code: string): Promise<string> {
|
||||
const key = await resolveKey();
|
||||
if (!key) throw new Error("No OpenRouter API key baked into this build");
|
||||
if (!key) throw new Error("No OpenRouter API key configured");
|
||||
const snippet = code.slice(0, 14000); // cap the payload
|
||||
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
|
||||
method: "POST",
|
||||
|
||||
29
src/i18n.ts
29
src/i18n.ts
@ -73,6 +73,7 @@ const D: Record<string, Tr> = {
|
||||
"Build Solution (.sln)": { ru: "Собрать решение (.sln)", de: "Projektmappe bauen (.sln)", fr: "Compiler la solution (.sln)", es: "Compilar solución (.sln)" },
|
||||
"Build Solution — no .sln": { ru: "Собрать решение — нет .sln", de: "Projektmappe bauen — keine .sln", fr: "Compiler — aucune .sln", es: "Compilar — sin .sln" },
|
||||
"No .sln found in the working folder. Choose the project folder first.": { ru: "В рабочей папке нет .sln. Сначала выбери папку проекта.", de: "Keine .sln im Arbeitsordner. Wähle zuerst den Projektordner.", fr: "Aucune .sln dans le dossier de travail. Choisissez d’abord le dossier du projet.", es: "No hay .sln en la carpeta de trabajo. Elige primero la carpeta del proyecto." },
|
||||
"No Unreal project in the working folder. Choose the project folder first.": { ru: "В рабочей папке нет проекта Unreal. Сначала выбери папку проекта.", de: "Kein Unreal-Projekt im Arbeitsordner. Wähle zuerst den Projektordner.", fr: "Aucun projet Unreal dans le dossier de travail. Choisissez d’abord le dossier du projet.", es: "No hay proyecto Unreal en la carpeta de trabajo. Elige primero la carpeta del proyecto." },
|
||||
"Build": { ru: "Сборка", de: "Build", fr: "Compilation", es: "Compilación" },
|
||||
"AI": { ru: "ИИ", de: "KI", fr: "IA", es: "IA" },
|
||||
"Terminal": { ru: "Терминал", de: "Terminal", fr: "Terminal", es: "Terminal" },
|
||||
@ -180,6 +181,7 @@ const D: Record<string, Tr> = {
|
||||
"Plugins": { ru: "Плагины", de: "Plugins", fr: "Extensions", es: "Plugins" },
|
||||
"General": { ru: "Общие", de: "Allgemein", fr: "Général", es: "General" },
|
||||
"Check for updates": { ru: "Проверить обновления", de: "Nach Updates suchen", fr: "Vérifier les mises à jour", es: "Buscar actualizaciones" },
|
||||
"Update available — click to install": { ru: "Есть обновление — нажми, чтобы установить", de: "Update verfügbar — zum Installieren klicken", fr: "Mise à jour dispo — cliquez pour installer", es: "Actualización disponible — clic para instalar" },
|
||||
"Updates": { ru: "Обновления", de: "Updates", fr: "Mises à jour", es: "Actualizaciones" },
|
||||
"Checking for updates…": { ru: "Проверяю обновления…", de: "Suche nach Updates…", fr: "Recherche de mises à jour…", es: "Buscando actualizaciones…" },
|
||||
"You're on the latest version": { ru: "У тебя последняя версия", de: "Du hast die neueste Version", fr: "Vous avez la dernière version", es: "Tienes la última versión" },
|
||||
@ -187,11 +189,17 @@ const D: Record<string, Tr> = {
|
||||
"Appearance": { ru: "Оформление", de: "Darstellung", fr: "Apparence", es: "Apariencia" },
|
||||
"Base theme": { ru: "Базовая тема", de: "Basis-Theme", fr: "Thème de base", es: "Tema base" },
|
||||
"{n} installed": { ru: "установлено: {n}", de: "{n} installiert", fr: "{n} installés", es: "{n} instalados" },
|
||||
"Plugins add features on top of the core app. Install a folder with a plugin.json, toggle plugins on/off, then they load automatically. Plugins run in-app — only install ones you trust.": { ru: "Плагины добавляют функции поверх ядра. Установи папку с plugin.json, включай/выключай — они грузятся автоматически. Плагины работают внутри приложения — ставь только те, которым доверяешь.", de: "Plugins fügen Funktionen zur Kern-App hinzu. Installiere einen Ordner mit plugin.json, schalte Plugins ein/aus — sie laden automatisch. Plugins laufen in der App — installiere nur vertrauenswürdige.", fr: "Les extensions ajoutent des fonctions au cœur de l’app. Installez un dossier avec plugin.json, activez/désactivez — elles se chargent automatiquement. Elles s’exécutent dans l’app — n’installez que celles de confiance.", es: "Los plugins añaden funciones al núcleo. Instala una carpeta con plugin.json, actívalos/desactívalos y se cargan solos. Se ejecutan en la app — instala solo los de confianza." },
|
||||
"Plugins add features on top of the core app. Browse the catalog below and install what you need — nothing is installed automatically. Toggle plugins on/off; enabled ones load on launch. Plugins run in-app — only install ones you trust.": { ru: "Плагины добавляют функции поверх ядра. Смотри каталог ниже и ставь нужное — ничего не ставится само. Включай/выключай; включённые грузятся при запуске. Плагины работают внутри приложения — ставь только те, которым доверяешь.", de: "Plugins erweitern die Kern-App. Durchsuche den Katalog unten und installiere, was du brauchst — nichts wird automatisch installiert. Plugins ein/aus schalten; aktivierte laden beim Start. Sie laufen in der App — installiere nur vertrauenswürdige.", fr: "Les extensions enrichissent le cœur de l’app. Parcourez le catalogue ci-dessous et installez ce qu’il faut — rien n’est installé automatiquement. Activez/désactivez ; les activées se chargent au démarrage. Elles s’exécutent dans l’app — n’installez que celles de confiance.", es: "Los plugins añaden funciones al núcleo. Explora el catálogo abajo e instala lo que necesites — nada se instala solo. Actívalos/desactívalos; los activos se cargan al iniciar. Se ejecutan en la app — instala solo los de confianza." },
|
||||
"No plugins installed yet.\nInstall one from a folder, or drop it into the plugins folder below.": { ru: "Плагинов пока нет.\nУстанови из папки или положи в папку плагинов ниже.", de: "Noch keine Plugins.\nAus einem Ordner installieren oder in den Plugin-Ordner unten legen.", fr: "Aucune extension.\nInstallez depuis un dossier ou déposez-la dans le dossier ci-dessous.", es: "Aún no hay plugins.\nInstala desde una carpeta o suéltalo en la carpeta de abajo." },
|
||||
"Enable": { ru: "Включить", de: "Aktivieren", fr: "Activer", es: "Activar" },
|
||||
"Disable": { ru: "Выключить", de: "Deaktivieren", fr: "Désactiver", es: "Desactivar" },
|
||||
"Official plugins": { ru: "Официальные плагины", de: "Offizielle Plugins", fr: "Extensions officielles", es: "Plugins oficiales" },
|
||||
"Available to install": { ru: "Доступно для установки", de: "Verfügbar zur Installation", fr: "Disponibles à l’installation", es: "Disponibles para instalar" },
|
||||
"from the Exbyte plugin registry": { ru: "из реестра плагинов Exbyte", de: "aus der Exbyte-Plugin-Registry", fr: "depuis le registre de plugins Exbyte", es: "del registro de plugins de Exbyte" },
|
||||
"Loading the plugin catalog…": { ru: "Загружаю каталог плагинов…", de: "Plugin-Katalog wird geladen…", fr: "Chargement du catalogue…", es: "Cargando el catálogo…" },
|
||||
"Couldn't reach the plugin registry.": { ru: "Не удалось получить реестр плагинов.", de: "Plugin-Registry nicht erreichbar.", fr: "Registre de plugins injoignable.", es: "No se pudo acceder al registro." },
|
||||
"Retry": { ru: "Повторить", de: "Erneut", fr: "Réessayer", es: "Reintentar" },
|
||||
"Everything from the catalog is already installed.": { ru: "Всё из каталога уже установлено.", de: "Alles aus dem Katalog ist bereits installiert.", fr: "Tout le catalogue est déjà installé.", es: "Todo el catálogo ya está instalado." },
|
||||
"Install": { ru: "Установить", de: "Installieren", fr: "Installer", es: "Instalar" },
|
||||
"Open plugins folder": { ru: "Открыть папку плагинов", de: "Plugin-Ordner öffnen", fr: "Ouvrir le dossier des extensions", es: "Abrir carpeta de plugins" },
|
||||
"Reload": { ru: "Перезагрузить", de: "Neu laden", fr: "Recharger", es: "Recargar" },
|
||||
@ -395,6 +403,20 @@ const D: Record<string, Tr> = {
|
||||
// collaboration / advanced perforce
|
||||
"Lock (exclusive)": { ru: "Заблокировать (эксклюзивно)", de: "Sperren (exklusiv)", fr: "Verrouiller (exclusif)", es: "Bloquear (exclusivo)" },
|
||||
"Unlock": { ru: "Разблокировать", de: "Entsperren", fr: "Déverrouiller", es: "Desbloquear" },
|
||||
"Force unlock": { ru: "Снять чужую блокировку", de: "Entsperren erzwingen", fr: "Forcer le déverrouillage", es: "Forzar desbloqueo" },
|
||||
"Lock against submit": { ru: "Запретить submit другим", de: "Submit für andere sperren", fr: "Bloquer le submit des autres", es: "Bloquear el submit de otros" },
|
||||
"Check out": { ru: "Взять в работу", de: "Auschecken", fr: "Extraire", es: "Extraer" },
|
||||
"{n} file(s) checked out.": { ru: "Взято в работу файлов: {n}.", de: "{n} Datei(en) ausgecheckt.", fr: "{n} fichier(s) extrait(s).", es: "{n} archivo(s) extraído(s)." },
|
||||
"Checked out {n} of {total}. The rest are held by someone else.": { ru: "Взято в работу {n} из {total}. Остальные заняты другими.", de: "{n} von {total} ausgecheckt. Der Rest ist von anderen belegt.", fr: "{n} sur {total} extraits. Le reste est tenu par d'autres.", es: "{n} de {total} extraídos. El resto lo tienen otros." },
|
||||
"Accept theirs for {name}?": { ru: "Принять серверную версию: {name}?", de: "Server-Version für {name} übernehmen?", fr: "Accepter la version serveur pour {name} ?", es: "¿Aceptar la versión del servidor para {name}?" },
|
||||
"Accept yours for {name}?": { ru: "Оставить свою версию: {name}?", de: "Eigene Version für {name} behalten?", fr: "Garder votre version pour {name} ?", es: "¿Conservar tu versión para {name}?" },
|
||||
"Your local changes in these files are replaced by the server version.": { ru: "Ваши локальные правки в этих файлах будут заменены серверной версией.", de: "Ihre lokalen Änderungen werden durch die Server-Version ersetzt.", fr: "Vos modifications locales sont remplacées par la version serveur.", es: "Tus cambios locales se sustituyen por la versión del servidor." },
|
||||
"Changes made on the server are dropped and your version wins.": { ru: "Изменения с сервера будут отброшены, останется ваша версия.", de: "Änderungen vom Server werden verworfen, Ihre Version bleibt.", fr: "Les modifications du serveur sont ignorées, votre version l'emporte.", es: "Los cambios del servidor se descartan y prevalece tu versión." },
|
||||
"Accept theirs": { ru: "Принять серверную", de: "Server-Version übernehmen", fr: "Accepter le serveur", es: "Aceptar servidor" },
|
||||
"Accept yours": { ru: "Оставить свою", de: "Eigene behalten", fr: "Garder la vôtre", es: "Conservar la tuya" },
|
||||
"Every file under this folder is marked for delete. Nothing leaves the server until you Submit. A folder with open files is refused.": { ru: "Все файлы в этой папке будут помечены на удаление. С сервера ничего не исчезнет до Submit. Папку с открытыми файлами удалить нельзя.", de: "Alle Dateien im Ordner werden zum Löschen markiert. Vor dem Submit verschwindet nichts vom Server. Ordner mit geöffneten Dateien werden abgelehnt.", fr: "Tous les fichiers du dossier sont marqués pour suppression. Rien ne quitte le serveur avant le Submit. Un dossier avec des fichiers ouverts est refusé.", es: "Todos los archivos de la carpeta se marcan para eliminar. Nada sale del servidor hasta el Submit. Una carpeta con archivos abiertos se rechaza." },
|
||||
"Install plugin “{name}”?": { ru: "Установить плагин «{name}»?", de: "Plugin „{name}“ installieren?", fr: "Installer le plugin « {name} » ?", es: "¿Instalar el plugin «{name}»?" },
|
||||
"A plugin runs with full access to this app, including your Perforce session. Declared permissions: {perms}.": { ru: "Плагин работает с полным доступом к приложению, включая вашу сессию Perforce. Заявленные разрешения: {perms}.", de: "Ein Plugin läuft mit vollem Zugriff auf diese App, auch auf Ihre Perforce-Sitzung. Angegebene Berechtigungen: {perms}.", fr: "Un plugin s'exécute avec un accès complet à l'application, y compris votre session Perforce. Autorisations déclarées : {perms}.", es: "Un plugin se ejecuta con acceso total a la app, incluida tu sesión de Perforce. Permisos declarados: {perms}." },
|
||||
"Locked {n} file(s).": { ru: "Заблокировано файлов: {n}.", de: "{n} Datei(en) gesperrt.", fr: "{n} fichier(s) verrouillé(s).", es: "{n} archivo(s) bloqueado(s)." },
|
||||
"Unlocked {n} file(s).": { ru: "Разблокировано файлов: {n}.", de: "{n} Datei(en) entsperrt.", fr: "{n} fichier(s) déverrouillé(s).", es: "{n} archivo(s) desbloqueado(s)." },
|
||||
"Locked by {u}": { ru: "Заблокировал {u}", de: "Gesperrt von {u}", fr: "Verrouillé par {u}", es: "Bloqueado por {u}" },
|
||||
@ -439,6 +461,11 @@ const D: Record<string, Tr> = {
|
||||
"Not a text file.": { ru: "Не текстовый файл.", de: "Keine Textdatei.", fr: "Pas un fichier texte.", es: "No es un archivo de texto." },
|
||||
"{user} submitted #{n}": { ru: "{user} отправил #{n}", de: "{user} hat #{n} übermittelt", fr: "{user} a soumis #{n}", es: "{user} envió #{n}" },
|
||||
"Reconnected to the server.": { ru: "Соединение с сервером восстановлено.", de: "Wieder mit dem Server verbunden.", fr: "Reconnecté au serveur.", es: "Reconectado al servidor." },
|
||||
// session expired → re-auth prompt
|
||||
"Session expired": { ru: "Сессия истекла", de: "Sitzung abgelaufen", fr: "Session expirée", es: "Sesión expirada" },
|
||||
"Perforce ended the session. Sign in again to carry on — your workspace and open changes are untouched.": { ru: "Perforce завершил сессию. Войдите снова, чтобы продолжить — workspace и открытые правки не тронуты.", de: "Perforce hat die Sitzung beendet. Melde dich erneut an — dein Workspace und offene Änderungen bleiben unberührt.", fr: "Perforce a mis fin à la session. Reconnectez-vous pour continuer — votre workspace et vos modifications ouvertes sont intacts.", es: "Perforce terminó la sesión. Inicia sesión de nuevo para continuar: tu workspace y los cambios abiertos están intactos." },
|
||||
"Reconnect": { ru: "Переподключиться", de: "Neu verbinden", fr: "Se reconnecter", es: "Reconectar" },
|
||||
"Sign out": { ru: "Выйти", de: "Abmelden", fr: "Se déconnecter", es: "Cerrar sesión" },
|
||||
"Connected server": { ru: "Сервер подключения", de: "Verbundener Server", fr: "Serveur connecté", es: "Servidor conectado" },
|
||||
"No embedded thumbnail. Load the 3D model below (needs Unreal Engine installed).": { ru: "Встроенного превью нет. Загрузи 3D-модель ниже (нужен установленный Unreal Engine).", de: "Kein eingebettetes Vorschaubild. Lade unten das 3D-Modell (Unreal Engine muss installiert sein).", fr: "Pas de miniature intégrée. Charge le modèle 3D ci-dessous (Unreal Engine requis).", es: "Sin miniatura incrustada. Carga el modelo 3D abajo (requiere Unreal Engine instalado)." },
|
||||
"Load 3D model": { ru: "Загрузить 3D-модель", de: "3D-Modell laden", fr: "Charger le modèle 3D", es: "Cargar modelo 3D" },
|
||||
|
||||
65
src/p4.ts
65
src/p4.ts
@ -1,5 +1,31 @@
|
||||
// Typed wrappers around the Rust p4 commands.
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { invoke as rawInvoke } from "@tauri-apps/api/core";
|
||||
|
||||
/** True when p4 rejected us for auth reasons — an expired or dropped ticket —
|
||||
* as opposed to the server being unreachable. Perforce expires tickets on its
|
||||
* own schedule (often 12h), so a workday can outlive a login. */
|
||||
export function isAuthError(e: unknown): boolean {
|
||||
return /P4PASSWD|invalid or unset|session has expired|session was logged out|please login again/i
|
||||
.test(String(e));
|
||||
}
|
||||
|
||||
// Set by the app: called when any command comes back with an auth failure, so
|
||||
// the UI can ask for the password again instead of dead-ending on every action.
|
||||
let authLost: (() => void) | null = null;
|
||||
export function onAuthLost(fn: (() => void) | null) { authLost = fn; }
|
||||
|
||||
// Commands that legitimately report bad credentials — the login screen shows
|
||||
// those inline, and firing the re-auth prompt from them would loop.
|
||||
const AUTH_CMDS = new Set(["p4_login", "p4_restore", "p4_clients"]);
|
||||
|
||||
/** Every p4 command funnels through here so a lost ticket is caught in one
|
||||
* place rather than at each of the ~110 call sites. */
|
||||
function invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
|
||||
return rawInvoke<T>(cmd, args).catch((e) => {
|
||||
if (!AUTH_CMDS.has(cmd) && isAuthError(e)) authLost?.();
|
||||
throw e;
|
||||
});
|
||||
}
|
||||
|
||||
export interface P4Info {
|
||||
serverAddress?: string;
|
||||
@ -113,6 +139,13 @@ export const p4 = {
|
||||
pluginReadEntry: (id: string) => invoke<string>("plugin_read_entry", { id }),
|
||||
pluginSetEnabled: (id: string, enabled: boolean) => invoke<void>("plugin_set_enabled", { id, enabled }),
|
||||
pluginWriteFile: (id: string, name: string, content: string) => invoke<void>("plugin_write_file", { id, name, content }),
|
||||
registryHttpGet: (url: string) => invoke<string>("registry_http_get", { url }),
|
||||
// generic HTTP pipe for relay-backed plugins (any http(s) URL, optional bearer)
|
||||
relayHttp: (url: string, method: string, body?: string, token?: string) =>
|
||||
invoke<string>("relay_http", { url, method, body, token }),
|
||||
// shelve everything open in the default changelist → { change, files }
|
||||
// caller's max protection level on the server (super/admin/write/…)
|
||||
protectsMax: () => invoke<string>("p4_protects_max"),
|
||||
pluginInstall: (src: string) => invoke<string>("plugin_install", { src }),
|
||||
pluginRemove: (id: string) => invoke<void>("plugin_remove", { id }),
|
||||
pluginsDirPath: () => invoke<string>("plugins_dir_path"),
|
||||
@ -159,6 +192,7 @@ export const p4 = {
|
||||
openedAll: (scope = "") => invoke<OpenedFile[]>("p4_opened_all", { scope }),
|
||||
lock: (files: string[]) => invoke<string>("p4_lock", { files }),
|
||||
unlock: (files: string[]) => invoke<string>("p4_unlock", { files }),
|
||||
unlockForce: (files: string[]) => invoke<string>("p4_unlock_force", { files }),
|
||||
typemapGet: () => invoke<string[]>("p4_typemap_get"),
|
||||
typemapSet: (entries: string[]) => invoke<string>("p4_typemap_set", { entries }),
|
||||
reopenType: (files: string[], filetype: string) => invoke<string>("p4_reopen_type", { files, filetype }),
|
||||
@ -297,6 +331,35 @@ export function fmtTime(t?: string): string {
|
||||
return d.toLocaleString(undefined, { day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" });
|
||||
}
|
||||
|
||||
/** Condense `p4 sync` stdout into one short line.
|
||||
*
|
||||
* A sync prints one line per file — `//depot/F.uasset#3 - updating d:\ws\F.uasset` —
|
||||
* so a real Get Latest returns thousands of full paths. Dumping that into a toast
|
||||
* buries the screen; the per-file detail already streamed into the transfer dialog.
|
||||
* Short outputs ("File(s) up-to-date.") pass through unchanged. */
|
||||
export function syncSummary(out: string): string {
|
||||
const text = (out || "").trim();
|
||||
if (!text) return "up to date";
|
||||
const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
|
||||
// p4 says its piece in one line when nothing moved ("File(s) up-to-date.") and
|
||||
// so do server errors — keep those verbatim; flash() caps the length.
|
||||
if (lines.length === 1) return lines[0];
|
||||
let added = 0, updated = 0, deleted = 0;
|
||||
for (const l of lines) {
|
||||
if (/ - (added as|refreshing) /.test(l)) added++;
|
||||
else if (/ - (updating|replacing) /.test(l)) updated++;
|
||||
else if (/ - deleted as /.test(l)) deleted++;
|
||||
}
|
||||
const moved = added + updated + deleted;
|
||||
// unrecognised shape (server notices, errors) — report the line count, not the text
|
||||
if (!moved) return `${lines.length.toLocaleString()} lines`;
|
||||
const parts: string[] = [];
|
||||
if (added) parts.push(`+${added.toLocaleString()}`);
|
||||
if (updated) parts.push(`~${updated.toLocaleString()}`);
|
||||
if (deleted) parts.push(`−${deleted.toLocaleString()}`);
|
||||
return `${moved.toLocaleString()} files (${parts.join(" ")})`;
|
||||
}
|
||||
|
||||
// action -> single-char status + css class
|
||||
export function statusOf(action?: string): { ch: string; cls: string } {
|
||||
const a = (action || "").toLowerCase();
|
||||
|
||||
101
src/plugins.ts
101
src/plugins.ts
@ -11,14 +11,18 @@ import { t } from "./i18n";
|
||||
import { resolveTheme, loadActiveId } from "./themes";
|
||||
|
||||
// ---- contribution shapes ----------------------------------------------------
|
||||
export interface PluginMenuItem { pluginId: string; label: string; run: () => void | Promise<void> }
|
||||
export interface PluginFileItem { pluginId: string; label: string; run: (file: { depotFile?: string; [k: string]: unknown }) => void | Promise<void> }
|
||||
// `icon` is a NAME from the host icon set (e.g. "ue", "hammer"); the host renders
|
||||
// the real SVG. Unknown / omitted names fall back to a neutral glyph.
|
||||
export interface PluginMenuItem { pluginId: string; label: string; icon?: string; run: () => void | Promise<void> }
|
||||
export interface PluginFileItem { pluginId: string; label: string; icon?: string; run: (file: { depotFile?: string; [k: string]: unknown }) => void | Promise<void> }
|
||||
export interface PluginFolderItem { pluginId: string; label: string; icon?: string; visible?: () => boolean; run: () => void | Promise<void> }
|
||||
export interface PluginView { pluginId: string; id: string; title: string; render: (container: HTMLElement) => void | (() => void) }
|
||||
export interface PluginDock { pluginId: string; id: string; title: string; icon?: string; render: (container: HTMLElement) => void | (() => void) }
|
||||
export interface PluginSubmitHook { pluginId: string; run: (files: { depotFile?: string }[]) => SubmitVerdict | Promise<SubmitVerdict> }
|
||||
export type SubmitVerdict = { ok: boolean; message?: string };
|
||||
|
||||
interface Registry { menu: PluginMenuItem[]; fileItems: PluginFileItem[]; views: PluginView[]; submitHooks: PluginSubmitHook[] }
|
||||
const registry: Registry = { menu: [], fileItems: [], views: [], submitHooks: [] };
|
||||
interface Registry { menu: PluginMenuItem[]; fileItems: PluginFileItem[]; folderItems: PluginFolderItem[]; views: PluginView[]; docks: PluginDock[]; submitHooks: PluginSubmitHook[] }
|
||||
const registry: Registry = { menu: [], fileItems: [], folderItems: [], views: [], docks: [], submitHooks: [] };
|
||||
let version = 0;
|
||||
const listeners = new Set<() => void>();
|
||||
function bump() { version++; listeners.forEach((l) => l()); }
|
||||
@ -26,7 +30,7 @@ function bump() { version++; listeners.forEach((l) => l()); }
|
||||
export function getRegistry(): Registry { return registry; }
|
||||
export function registryVersion(): number { return version; }
|
||||
export function subscribeRegistry(cb: () => void): () => void { listeners.add(cb); return () => { listeners.delete(cb); }; }
|
||||
function clearRegistry() { registry.menu = []; registry.fileItems = []; registry.views = []; registry.submitHooks = []; }
|
||||
function clearRegistry() { registry.menu = []; registry.fileItems = []; registry.folderItems = []; registry.views = []; registry.docks = []; registry.submitHooks = []; }
|
||||
|
||||
// Unreal Engine bridge — the core keeps the build machinery + overlay + log
|
||||
// reader; the plugin only drives them. Gated by the "ue" permission.
|
||||
@ -34,9 +38,24 @@ export interface UeBridge {
|
||||
hasProject: () => boolean;
|
||||
uproject: () => string;
|
||||
build: () => void;
|
||||
launch: () => void;
|
||||
readLog: (tailBytes?: number) => Promise<string>;
|
||||
}
|
||||
|
||||
// Team bridge — presence + coordinator tools. The plugin drives these; the core
|
||||
// just exposes the p4 primitives + a generic HTTP pipe to the relay. Gated by
|
||||
// the "team" permission. Nothing here touches the Perforce server config: shelve
|
||||
// is an ordinary client-side operation and `relay` talks only to the URL the
|
||||
// plugin was configured with.
|
||||
export interface TeamBridge {
|
||||
whoami: () => { user?: string; client?: string; root?: string } | null;
|
||||
maxAccess: () => Promise<string>; // "super" | "admin" | "write" | …
|
||||
openCount: () => Promise<number>; // files open in this workspace
|
||||
submitShelved: (change: string) => Promise<string>;
|
||||
// dumb HTTP pipe to the configured relay (backend does the request; no CORS)
|
||||
relay: (url: string, method: string, body?: string, token?: string) => Promise<string>;
|
||||
}
|
||||
|
||||
// ---- host context (provided by the app) -------------------------------------
|
||||
export interface HostContext {
|
||||
flash: (text: string, err?: boolean) => void;
|
||||
@ -45,6 +64,7 @@ export interface HostContext {
|
||||
selectedFile: () => { depotFile?: string } | null;
|
||||
refresh: () => void;
|
||||
ue?: UeBridge;
|
||||
team?: TeamBridge;
|
||||
}
|
||||
|
||||
// ---- the Host SDK a plugin receives -----------------------------------------
|
||||
@ -55,9 +75,11 @@ export interface HostApi {
|
||||
has: (perm: string) => boolean;
|
||||
p4: Record<string, (...a: unknown[]) => Promise<unknown>>;
|
||||
ui: {
|
||||
addMenuItem: (label: string, run: () => void | Promise<void>) => void;
|
||||
addFileContextItem: (label: string, run: (file: { depotFile?: string }) => void | Promise<void>) => void;
|
||||
addMenuItem: (label: string, run: () => void | Promise<void>, opts?: { icon?: string }) => void;
|
||||
addFileContextItem: (label: string, run: (file: { depotFile?: string }) => void | Promise<void>, opts?: { icon?: string }) => void;
|
||||
addFolderContextItem: (label: string, run: () => void | Promise<void>, opts?: { icon?: string; visible?: () => boolean }) => void;
|
||||
addView: (view: { id: string; title: string; render: (el: HTMLElement, host: HostApi) => void | (() => void) }) => void;
|
||||
addDockPanel: (dock: { id: string; title: string; icon?: string; render: (el: HTMLElement, host: HostApi) => void | (() => void) }) => void;
|
||||
addSubmitHook: (run: (files: { depotFile?: string }[]) => SubmitVerdict | Promise<SubmitVerdict>) => void;
|
||||
};
|
||||
flash: (text: string, err?: boolean) => void;
|
||||
@ -68,6 +90,7 @@ export interface HostApi {
|
||||
selectedFile: () => { depotFile?: string } | null;
|
||||
refresh: () => void;
|
||||
ue?: UeBridge; // present only with the "ue" permission
|
||||
team?: TeamBridge; // present only with the "team" permission
|
||||
theme: () => Record<string, string>;
|
||||
t: typeof t;
|
||||
log: (...a: unknown[]) => void;
|
||||
@ -95,9 +118,11 @@ function makeHost(info: PluginInfo, ctx: HostContext): HostApi {
|
||||
has,
|
||||
p4: p4host,
|
||||
ui: {
|
||||
addMenuItem: (label, run) => { registry.menu.push({ pluginId: info.id, label, run }); bump(); },
|
||||
addFileContextItem: (label, run) => { registry.fileItems.push({ pluginId: info.id, label, run }); bump(); },
|
||||
addMenuItem: (label, run, opts) => { registry.menu.push({ pluginId: info.id, label, icon: opts?.icon, run }); bump(); },
|
||||
addFileContextItem: (label, run, opts) => { registry.fileItems.push({ pluginId: info.id, label, icon: opts?.icon, run }); bump(); },
|
||||
addFolderContextItem: (label, run, opts) => { registry.folderItems.push({ pluginId: info.id, label, icon: opts?.icon, visible: opts?.visible, run }); bump(); },
|
||||
addView: (view) => { registry.views.push({ pluginId: info.id, id: view.id, title: view.title, render: (el) => view.render(el, host) }); bump(); },
|
||||
addDockPanel: (dock) => { registry.docks.push({ pluginId: info.id, id: dock.id, title: dock.title, icon: dock.icon, render: (el) => dock.render(el, host) }); bump(); },
|
||||
addSubmitHook: (run) => { registry.submitHooks.push({ pluginId: info.id, run }); bump(); },
|
||||
},
|
||||
flash: ctx.flash,
|
||||
@ -116,6 +141,7 @@ function makeHost(info: PluginInfo, ctx: HostContext): HostApi {
|
||||
log: (...a) => console.log(`[plugin:${info.id}]`, ...a),
|
||||
};
|
||||
if (has("ue") && ctx.ue) host.ue = ctx.ue; // Unreal bridge, permission-gated
|
||||
if (has("team") && ctx.team) host.team = ctx.team; // Team bridge, permission-gated
|
||||
return host;
|
||||
}
|
||||
|
||||
@ -164,37 +190,52 @@ export async function runSubmitHooks(files: { depotFile?: string }[]): Promise<S
|
||||
// then hands each file to the backend to write into the plugins folder.
|
||||
export const REGISTRY_URL = "https://gitea.exbytestudios.com/ExbytePublicServices/exbyte-depot-plugins/raw/branch/main/registry.json";
|
||||
|
||||
// Ed25519 key that signs registry.json (published as registry.json.sig). The registry
|
||||
// pins every plugin file by SHA-256, so the branch alone can't change what gets installed.
|
||||
const REGISTRY_PUBKEY = "xFys0cQSGc06fZ8LfwsZAjLgmVYqW4nQxkJhXVmUEoM=";
|
||||
const fromB64 = (s: string) => Uint8Array.from(atob(s.trim()), (c) => c.charCodeAt(0));
|
||||
|
||||
async function verifyRegistry(text: string, signature: string): Promise<void> {
|
||||
const key = await crypto.subtle.importKey("raw", fromB64(REGISTRY_PUBKEY), { name: "Ed25519" }, false, ["verify"]);
|
||||
const ok = await crypto.subtle.verify({ name: "Ed25519" }, key, fromB64(signature), new TextEncoder().encode(text));
|
||||
if (!ok) throw new Error("Plugin registry signature is invalid");
|
||||
}
|
||||
|
||||
async function sha256Hex(text: string): Promise<string> {
|
||||
const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
||||
return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
export interface RegistryEntry {
|
||||
id: string; name: string; version: string; author?: string; description?: string;
|
||||
permissions?: string[]; minAppVersion?: string; official?: boolean; autoInstall?: boolean;
|
||||
files: string[]; baseUrl: string;
|
||||
files: string[]; baseUrl: string; sha256?: Record<string, string>;
|
||||
}
|
||||
|
||||
// All registry HTTP goes through the Rust backend (registryHttpGet): the webview
|
||||
// `fetch()` is blocked by CORS because Gitea's raw endpoint sends no ACAO header.
|
||||
export async function fetchRegistry(): Promise<RegistryEntry[]> {
|
||||
const r = await fetch(REGISTRY_URL, { cache: "no-store" });
|
||||
if (!r.ok) throw new Error(`registry HTTP ${r.status}`);
|
||||
const j = await r.json();
|
||||
const [txt, sig] = await Promise.all([p4.registryHttpGet(REGISTRY_URL), p4.registryHttpGet(REGISTRY_URL + ".sig")]);
|
||||
await verifyRegistry(txt, sig);
|
||||
const j = JSON.parse(txt);
|
||||
return Array.isArray(j.plugins) ? (j.plugins as RegistryEntry[]).filter((p) => p && p.id && Array.isArray(p.files)) : [];
|
||||
}
|
||||
|
||||
/** Download a registry plugin's files over HTTPS and write them into the plugins folder. */
|
||||
/** Download a registry plugin's files (backend HTTPS) and write them into the plugins folder. */
|
||||
export async function installFromRegistry(entry: RegistryEntry): Promise<void> {
|
||||
// nothing is written until every file matches the signed registry
|
||||
const files: [string, string][] = [];
|
||||
for (const f of entry.files) {
|
||||
const res = await fetch(entry.baseUrl + f, { cache: "no-store" });
|
||||
if (!res.ok) throw new Error(`${f}: HTTP ${res.status}`);
|
||||
await p4.pluginWriteFile(entry.id, f, await res.text());
|
||||
const text = await p4.registryHttpGet(entry.baseUrl + f);
|
||||
const pinned = entry.sha256?.[f];
|
||||
if (!pinned || (await sha256Hex(text)) !== pinned) throw new Error(`${f} doesn't match the signed registry`);
|
||||
files.push([f, text]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Install any official plugins marked autoInstall that aren't installed yet. Silent on network failure. */
|
||||
export async function autoInstallOfficial(installedIds: Set<string>): Promise<string[]> {
|
||||
let reg: RegistryEntry[] = [];
|
||||
try { reg = await fetchRegistry(); } catch { return []; }
|
||||
const done: string[] = [];
|
||||
for (const e of reg) {
|
||||
if (e.autoInstall && !installedIds.has(e.id)) {
|
||||
try { await installFromRegistry(e); done.push(e.id); } catch { /* offline / transient — try next launch */ }
|
||||
}
|
||||
}
|
||||
return done;
|
||||
// the catalog shows entry.permissions, so the manifest that takes effect must agree with it
|
||||
const manifest = JSON.parse(files.find(([f]) => f === "plugin.json")?.[1] ?? "{}");
|
||||
const declared = [...(manifest.permissions || [])].sort().join();
|
||||
if (manifest.id !== entry.id || declared !== [...(entry.permissions || [])].sort().join()) {
|
||||
throw new Error("plugin.json doesn't match the registry entry");
|
||||
}
|
||||
for (const [f, text] of files) await p4.pluginWriteFile(entry.id, f, text);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user