fix(xiaoyi): unify client and assistant product copy
This commit is contained in:
parent
dcd0f13f26
commit
6ab902d2e3
@ -35,7 +35,10 @@ import { NativeExtensionUI } from './native-ui.mjs';
|
||||
import { canvasReadParameters, canvasReadQuery, previewTarget, previewParameters } from './canvas-contract.mjs';
|
||||
import { PHOTOCRAFT_NAMESPACE, createPhotoCraftExtensions, photoCraftToolAllowlist, activatePhotoCraftTools } from './photocraft-extension.mjs';
|
||||
|
||||
const PRODUCT_VOICE = "对用户回复、状态汇报和错误说明始终使用「小壹」「画布」「工作台」「制作助手」等产品术语。不得向用户暴露底层技术或开源底座名称;工具及参考资料中的内部名称仅用于执行。";
|
||||
|
||||
const SYSTEM = `你是由壹点详情页的本地协作助手“小壹”。使用中文,能够与用户连贯讨论、回答问题、解释原因、提出并比较方案。可以直接自然语言回答;不需要工具时不要调用工具,不把每次对话都当作执行任务。
|
||||
${PRODUCT_VOICE}
|
||||
需要用户选择、确认或补充关键资料时使用ask_user,以原生选项、确认或输入卡片等待回复,再按回复继续。用户明确要求交互选择时不要仅把选项写在正文里。多选使用multi_select;长文本修改使用editor。用户取消表示未决定,不能擅自代选或把取消当授权。普通卖点候选继续使用copywriting_options供用户多选并编辑,逐格预览和采纳沿用copywriting_fields;需要选择后在同一轮继续创作时使用ask_user等待实际选择。
|
||||
需要商品资料或待确认项时用 context_read 或 workflow_read 查看。用户要求查看画布时可以只读核对;只有明确要求修改时才能写入。讨论、解释、建议不自动改图。实际写工具会向本机申请当前版本的写许可;未授权或用户接手时不再修改。
|
||||
使用 context_read 读取当前店铺、品类和品牌规则,不沿用另一店铺或旧规则;品牌规范不是产品参数的证据。
|
||||
@ -50,7 +53,7 @@ const SYSTEM = `你是由壹点详情页的本地协作助手“小壹”。使
|
||||
workflow_propose的instruction仅用于selling_points的补充表达方向和generate_candidate的本次画面要求;其他意图使用当前已保存配置,不通过建议修改资料、屏数或宽度。canvasFirst=true时,新建资料后已经进入模板画布,不要求用户完成旧卖点/方案阶段。以subject识别当前页、图位、花色和候选;generate_candidate指定slotId、productVariantId,可用candidateId作为父版本,一次追加一张新候选,不填写A/B。adopt_candidate指定明确candidateId,仅采纳这一图位,保留手工文字与布局,可撤销。结果未知的原请求只读核查,不能以新候选规避。旧项目canvasFirst不为true时,generate_candidate仍须给未使用的A/B标签;install_template/slot_copy/apply_copy保留旧兼容能力。review_candidates只供比较,不代替视觉审核。export_psd导出当前成品的分层副本,候选不参与导出;提案或打开对话框不代表导出完成。品牌或品类变化时重新开始回合加载规则,不能混用。
|
||||
实时读取界面草稿不代表已经保存或完成分析。草稿或依据变更后,旧事实分析、卖点和方案的stale状态必须保留,不能当作新资料的有效依据。工作流version只用于上下文一致性,不代表方案已确认,也不授予模型调用或付费许可。
|
||||
memory_set只记录对话记忆,不修改产品资料。用户希望改资料时说明尚待审核,不把记忆成功说成产品资料已经变更。
|
||||
客户端已整体接入PhotoCraft原生命令框架,不限于canvas_edit的三个快捷操作。使用tool_search/CodeMode按需发现photocraft命名空间,通过native_catalog查完整命令、参数说明及实时权限,再用native_call执行;不要为每个功能写独立工具。目录按关键词给摘要,精确id才取完整说明;已查得的命令及参数继续复用,避免反复查同一目录或打印未筛选整页。CodeMode可在一次调用中依次await读取、多个原生操作与最终核验,不必为每个确定的小步骤重新询问模型。每步使用刚读取或上一真实完成回执的revision。原生命令未开放或权限被拒时如实说明,不用脚本绕过宿主。CodeMode脚本的文字输出、提案、打开弹窗和pending不代表画布或交付已完成。
|
||||
画布支持完整的原生命令,不限于canvas_edit的三个快捷操作。使用tool_search/CodeMode按需发现photocraft命名空间,通过native_catalog查完整命令、参数说明及实时权限,再用native_call执行;不要为每个功能写独立工具。目录按关键词给摘要,精确id才取完整说明;已查得的命令及参数继续复用,避免反复查同一目录或打印未筛选整页。CodeMode可在一次调用中依次await读取、多个原生操作与最终核验,不必为每个确定的小步骤重新询问模型。每步使用刚读取或上一真实完成回执的revision。原生命令未开放或权限被拒时如实说明,不用脚本绕过宿主。CodeMode脚本的文字输出、提案、打开弹窗和pending不代表画布或交付已完成。
|
||||
原生或工作流操作结果未知时,通过tool_search查找native_reconcile,只读核查保留的原任务;不能重发。若无任务编号或仍未知,告知用户在原项目人工核查。
|
||||
理解用户是在讨论、查看导航还是要求修改。用户明确要做的本机操作,应通过可用工具完成并核对结果,不只回复做法或重复提议;用户明确“先讨论/不修改”则保持只读。对“刚才那个”先结合本项目历史与实时对象核对,不沿用已不存在的图层。只追问会改变结果的关键缺失信息,可逆的普通实现细节可自行处理。
|
||||
用户明确要求先看修改预览时,使用 canvas_preview 在原生界面生成待用户采纳的预览;预览未修改画布,只有用户点击原生界面采纳才应用。用户明确要求直接编辑时沿用原有原生命令。
|
||||
@ -58,11 +61,12 @@ memory_set只记录对话记忆,不修改产品资料。用户希望改资料
|
||||
references是用户提交时冻结的本轮引用;component为pixelMask或vectorMask时指所属图层对应的蒙版。liveSelected只表示实时界面选择,不能替代本轮引用。没有references时,不要猜测用户明确指向了哪个对象。
|
||||
只确认已执行的修改。工具失败要说明。生图和画布操作结果未确认时,只核查原编号。`;
|
||||
|
||||
const PRODUCTION_SYSTEM = `你是小壹的制作 Agent。先读本项目适用的企业 Skill,并按它及模板在 PhotoCraft 制作和复核。由你决定要做什么、顺序、并行和返工。
|
||||
const PRODUCTION_SYSTEM = `你是小壹的制作助手。先读取本项目适用的企业制作指引,按指引和模板在画布中制作和复核。由你决定要做什么、顺序、并行和返工。
|
||||
${PRODUCT_VOICE}
|
||||
用 plan_production 读取本轮输出和工作画布。尚未绑定时,单独调用 open_production_output 打开所选画布,收到已保存的绑定回执后再查询 native_catalog 或调用画布工具。打开失败时按回执处理,可重新打开或选择另一待制作输出。用户查看的页面和制作画布独立。
|
||||
企业 Skill 中的命令行编修可在当前画布用等价的 PhotoCraft 原生命令完成。用已有产品资料写买家看得懂的文案,检查实际画面的图文对应、品牌元素和旧商品信息。
|
||||
企业 Skill 中的命令行编修可在当前画布用等价的画布命令完成。用已有产品资料写买家看得懂的文案,检查实际画面的图文对应、品牌元素和旧商品信息。
|
||||
读取文案和图位后,在当前输出继续写入、采用和复核。子代理工作期间可并行处理其他图文,收到回执后继续当前输出。保留草稿时说明本轮无法解除的具体阻塞。
|
||||
复核后提交当前修订。PhotoCraft 按实际导出回执交接下一项。生图或画布操作结果未确认时按原编号核查。用简短中文说明实际进展。`;
|
||||
复核后提交当前修订。按工作台的实际导出回执交接下一项。生图或画布操作结果未确认时按原编号核查。用简短中文说明实际进展。`;
|
||||
|
||||
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
|
||||
// Both shapes are native projections of the frozen request, never the live selection.
|
||||
@ -573,7 +577,7 @@ export class DetailPiAgent {
|
||||
const [scopeKind, step] = requestScope.split('/');
|
||||
const workerKind = scopeKind === 'product' ? step : taskTools[0]?.name ?? 'detail';
|
||||
const agent = new Agent({
|
||||
initialState:{model,systemPrompt,tools,thinkingLevel:host.session.thinkingLevel},
|
||||
initialState:{model,systemPrompt:systemPrompt+"\n"+PRODUCT_VOICE,tools,thinkingLevel:host.session.thinkingLevel},
|
||||
sessionId:host.manager.getSessionId()+':'+workerKind,
|
||||
streamFn:apiImpl.streamSimple,
|
||||
});
|
||||
|
||||
@ -158,7 +158,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal) {
|
||||
if (pending.length !== 1) throw Error('待核查请求数量异常,请保留项目和请求号');
|
||||
result = await host.recover(pending[0].id, { executeReadOnly: false });
|
||||
result.text = result.phase === 'unknown' ? `原请求仍待核查(${result.requestId || pending[0].id}),未重发。`
|
||||
: result.internalCompaction ? '已核对旧摘要的请求记录。Pi 会在需要时压缩当前会话。'
|
||||
: result.internalCompaction ? '已核对旧摘要的请求记录。需要时,小壹会整理这段对话。'
|
||||
: result.phase === 'failed' ? '已确认这条请求失败。你可以在原对话发送新消息。'
|
||||
: result.needsToolReview ? '原响应已取回。画布建议尚待核对,未自动执行。' : '原响应已取回,未重新调用模型。';
|
||||
if (result.restoredText) result.text += '\n\n' + result.restoredText;
|
||||
|
||||
@ -134,7 +134,7 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
|
||||
const missing = skillPaths.filter(file => !loadedPaths.has(file));
|
||||
if (!skillPaths.length || missing.length) {
|
||||
const names = missing.map(file => documents.get(file).path);
|
||||
throw Error('Pi 无法载入本次制作的 Skill:' + (names.join('、') || '没有已发布的入口'));
|
||||
throw Error('小壹未能读取本次制作的企业指引:' + (names.join('、') || '没有已发布的入口'));
|
||||
}
|
||||
await store.appendEvent({type:'enterprise_skill_resources_bound', outputId:selection.outputId,
|
||||
...((knowledge.resourceRevision) ? {resourceRevision:knowledge.resourceRevision} : null),
|
||||
|
||||
@ -34,7 +34,7 @@ export function nativeTools(host, make) {
|
||||
return publicResult;
|
||||
};
|
||||
return [
|
||||
{...make('native_catalog', '查询 PhotoCraft 完整原生命令和客户端界面能力。filter支持空格分隔的并列关键词,按相关度返回紧凑摘要(默认10项);id精确取某个命令完整parameterDocs。parameterDocs是原生说明而非完整JSON Schema。原生说明中的 document:index 指目录回执的 documentIndex,省略时使用当前文档。先查相关命令,复用已取得说明;可在同次CodeMode中批量查所需id,不要反复打印未筛选整页。实时enabled/reason保留,不需要逐业务工具迁移。', nativeCatalogParameters,
|
||||
{...make('native_catalog', '查询画布命令和工作台界面能力。filter支持空格分隔的并列关键词,按相关度返回紧凑摘要(默认10项);id精确取某个命令完整parameterDocs。parameterDocs是原生说明而非完整JSON Schema。原生说明中的 document:index 指目录回执的 documentIndex,省略时使用当前文档。先查相关命令,复用已取得说明;可在同次CodeMode中批量查所需id,不要反复打印未筛选整页。实时enabled/reason保留,不需要逐业务工具迁移。', nativeCatalogParameters,
|
||||
catalog), ...nativeToolMetadata('native_catalog')},
|
||||
{...make('native_call', '统一执行已发现的原生命令或界面操作。engine.execute的params为{command,params};ui.set/inspect/menu.list沿用目录中的原生契约。参数要求 document:index 时用目录的 documentIndex,当前文档可省略。revision必须来自实时读取。返回真实原生结果;后台任务等待原job终态。若结果给出 resultRef,用 result.read 只读原结果,params 为 {resultId,pointer?,offset?}。pointer 用 JSON Pointer 选择字段(如 /layers),按 nextOffset 翻页。严格依次await;禁止把提案、pending或脚本文字输出当成执行成功。', nativeCallParameters,
|
||||
async (args, signal) => {
|
||||
|
||||
@ -14,13 +14,13 @@ export const PHOTOCRAFT_NATIVE_TOOL_NAMES = Object.freeze(['native_catalog', 'na
|
||||
export const PHOTOCRAFT_NAMESPACE = Object.freeze({
|
||||
name: 'photocraft',
|
||||
aliases: ['PhotoCraft', 'native'],
|
||||
description: 'PhotoCraft native client command catalog and execution.',
|
||||
description: '查询并执行画布命令。',
|
||||
instructions: 'Discover current native commands and their parameter documentation before calling them. All calls retain the current account, project, document, revision and host permission checks. A denied or proposed operation is not an executed operation.',
|
||||
});
|
||||
|
||||
/** Metadata only: the host owns the real handlers, schemas and authorization. */
|
||||
export function nativeToolMetadata(name) {
|
||||
if (!PHOTOCRAFT_NATIVE_TOOL_NAMES.includes(name)) throw new TypeError(`Unknown PhotoCraft native tool: ${name}`);
|
||||
if (!PHOTOCRAFT_NATIVE_TOOL_NAMES.includes(name)) throw new TypeError(`找不到对应的画布工具:${name}`);
|
||||
return {namespace: PHOTOCRAFT_NAMESPACE, exposure: 'direct',
|
||||
...(name === 'native_catalog' ? {} : {executionMode: 'sequential'})};
|
||||
}
|
||||
@ -30,9 +30,9 @@ export function nativeToolMetadata(name) {
|
||||
*/
|
||||
export async function createPhotoCraftExtensions(host, existing = [], { includeGoal = false, mayContinueGoal } = {}) {
|
||||
const cwd = host?.workingDirectory ?? host?.store?.dir;
|
||||
if (typeof cwd !== 'string' || !cwd) throw new TypeError('PhotoCraft extension loading requires host.store.dir');
|
||||
if (typeof cwd !== 'string' || !cwd) throw new TypeError('工作台未能找到制作工具的工作目录');
|
||||
if (!Array.isArray(existing) || existing.some(extension => !(extension?.handlers instanceof Map) || !(extension?.tools instanceof Map))) {
|
||||
throw new TypeError('Existing PhotoCraft extensions must be compiled SDK Extension objects');
|
||||
throw new TypeError('工作台的制作工具配置无效');
|
||||
}
|
||||
const loader = new DefaultResourceLoader({
|
||||
cwd, agentDir: host.store.dir,
|
||||
@ -51,11 +51,12 @@ export async function createPhotoCraftExtensions(host, existing = [], { includeG
|
||||
await loader.reload();
|
||||
const result = loader.getExtensions();
|
||||
if (result.errors.length) {
|
||||
throw new Error(`PhotoCraft SDK extensions failed to load: ${result.errors.map(error => `${error.path}: ${error.error}`).join('; ')}`);
|
||||
const cause = new Error(result.errors.map(error => `${error.path}: ${error.error}`).join('; '));
|
||||
throw new Error('工作台未能加载制作工具,请重新打开客户端后重试', { cause });
|
||||
}
|
||||
if (includeGoal) {
|
||||
const goal = result.extensions.find(extension => extension.commands.has('goal'));
|
||||
if (!goal) throw Error('客户端缺少 Pi 目标插件');
|
||||
if (!goal) throw Error('当前客户端无法继续制作目标,请更新完整客户端');
|
||||
goal.handlers.set('context', [...goal.handlers.get('context') ?? [], event => ({
|
||||
messages: event.messages.map(message => {
|
||||
const {kind,goal:state}=message.details??{};
|
||||
|
||||
@ -31,7 +31,7 @@ export async function recordProductionExport(dir, goalId) {
|
||||
const saved = JSON.parse(await fs.readFile(path.join(dir, 'session.json'), 'utf8'));
|
||||
const manager = SessionManager.open(path.join(dir, 'sessions', path.basename(saved.file)), dir, dir);
|
||||
const entry = manager.getBranch().findLast(row => row.type === 'custom' && row.customType === 'pi-goal');
|
||||
if (entry?.data?.goal?.id !== goalId) throw Error('导出回执与 Pi 制作目标不一致');
|
||||
if (entry?.data?.goal?.id !== goalId) throw Error('导出回执与当前制作目标不一致');
|
||||
if (entry.data.goal.status !== 'complete') {
|
||||
manager.appendCustomEntry('pi-goal', {...entry.data, goal:{...entry.data.goal, status:'complete', updatedAt:Date.now()}});
|
||||
}
|
||||
|
||||
@ -7,7 +7,7 @@ const stageRules = {
|
||||
review: ['review', 'composition', 'product-visual', 'template-reference', 'brand', 'output'],
|
||||
};
|
||||
|
||||
export const knowledgeReadInstruction = '优先使用 Pi 的 read 读取适用 Skill 及其引用,按 PhotoCraft 路径执行。knowledgeFiles 提供本阶段规则的来源,也可用 read_production_knowledge 按编号读取固定版本。';
|
||||
export const knowledgeReadInstruction = '优先使用 read 读取适用的企业制作指引及其引用,按工作台流程执行。knowledgeFiles 提供本阶段规则的来源,也可用 read_production_knowledge 按编号读取固定版本。';
|
||||
|
||||
export function productionKnowledge(knowledge, stage) {
|
||||
const documents = [...(knowledge?.skills ?? []), ...(knowledge?.rules ?? [])]
|
||||
|
||||
@ -64,7 +64,7 @@ export const productionOperationTools = [
|
||||
['use_product_image','用本款原片或裁切区域创建候选,返回后可继续处理其他图位。',obj({slotId:slotRef,...productImageArgs})],
|
||||
['prepare_image_request','保存完整生图请求。回执含可审阅的正式文本、实际参考顺序和模型参数,以及 requestId、revision 和 requestSpecHash。',obj({slotId:slotRef,...preparationArgs})],
|
||||
['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj(dispatchArgs)],
|
||||
['delegate_image_slots','把图位和可执行要求交给 Pi 子代理并行制作。每个图位单独返回已接收或无法定位的结果。',obj({
|
||||
['delegate_image_slots','把图位和明确要求交给制作助手并行处理。每个图位单独返回已接收或无法定位的结果。',obj({
|
||||
jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
|
||||
})],
|
||||
['await_image_slots','等待指定图位的任一制作或验图返回,并读取已有回执。',obj({slotIds:optional(ids)})],
|
||||
|
||||
@ -2,6 +2,6 @@
|
||||
export function assertPiNodeVersion(version) {
|
||||
const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(version || '');
|
||||
if (!match || Number(match[1]) !== 24 || Number(match[2]) < 22 || (Number(match[2]) === 22 && Number(match[3]) < 1)) {
|
||||
throw Error('Agent运行组件需要Node 24.22.1或更新的24.x安全版本,请更新完整客户端');
|
||||
throw Error('小壹的运行组件版本过旧,请更新完整客户端后重试');
|
||||
}
|
||||
}
|
||||
|
||||
@ -191,7 +191,7 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
|
||||
const transport={info:info(id.scope),stream(_model,context){
|
||||
const instructions=getCurrentSystemPrompt(context.messages);
|
||||
assert.match(instructions,/由你决定要做什么、顺序、并行和返工/);
|
||||
assert.match(instructions,/企业 Skill 中的命令行编修可在当前画布用等价的 PhotoCraft 原生命令完成/);
|
||||
assert.match(instructions,/企业 Skill 中的命令行编修可在当前画布用等价的画布命令完成/);
|
||||
const call=steps.shift();
|
||||
return call?stream([{type:'toolCall',name:call[0],id:'tool-'+(++serial),arguments:call[1]??{}}]):
|
||||
stream([{type:'text',text:'当前进展已记在项目里。'}]);
|
||||
|
||||
@ -4,7 +4,7 @@ import { assertPiNodeVersion } from '../src/runtime-policy.mjs';
|
||||
|
||||
test('client packaging and startup reject unpatched and unverified Node lines', () => {
|
||||
for (const version of ['18.20.8', '22.23.4', '24.16.0', '24.22.0', '25.0.0', '26.12.1', 'v24.22.1-rc.1', 'garbage']) {
|
||||
assert.throws(() => assertPiNodeVersion(version), /24.22.1/);
|
||||
assert.throws(() => assertPiNodeVersion(version), /请更新完整客户端/);
|
||||
}
|
||||
for (const version of ['v24.22.1', '24.22.2', '24.23.0']) assert.doesNotThrow(() => assertPiNodeVersion(version));
|
||||
});
|
||||
|
||||
31
apps/detail-agent-pi/test/whitelabel.test.mjs
Normal file
31
apps/detail-agent-pi/test/whitelabel.test.mjs
Normal file
@ -0,0 +1,31 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const source = file => readFileSync(new URL(`../src/${file}`, import.meta.url), 'utf8');
|
||||
const technicalBrand = /(?<![A-Za-z0-9_])(?:Pi(?: Agent)?|PhotoCraft)(?![A-Za-z0-9_])|\bpcraft:/u;
|
||||
|
||||
test('conversation status, errors and tool guidance use product terminology', () => {
|
||||
for (const file of [
|
||||
'agent.mjs', 'desktop-host.mjs', 'enterprise-skill-resources.mjs', 'native-tools.mjs',
|
||||
'photocraft-extension.mjs', 'production-goal.mjs', 'production-knowledge.mjs',
|
||||
'production-operations.mjs', 'runtime-policy.mjs',
|
||||
]) {
|
||||
for (const [index, line] of source(file).split('\n').entries()) {
|
||||
const copy = line.trim();
|
||||
if (/^(?:\/\/|\/\*|\*)/.test(copy) || copy === "aliases: ['PhotoCraft', 'native'],") continue;
|
||||
assert.doesNotMatch(copy, technicalBrand, `${file}:${index + 1}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('both conversation prompts and delegated production share the product voice rule', () => {
|
||||
const agent = source('agent.mjs');
|
||||
for (const name of ['SYSTEM', 'PRODUCTION_SYSTEM']) {
|
||||
const prompt = agent.match(new RegExp('const ' + name + ' = `([\\s\\S]+?)`;'))?.[1];
|
||||
assert.ok(prompt?.includes('${PRODUCT_VOICE}'), name);
|
||||
}
|
||||
assert.match(agent, /initialState:\{model,systemPrompt:systemPrompt\+"\\n"\+PRODUCT_VOICE/);
|
||||
assert.match(agent, /对用户回复、状态汇报和错误说明始终使用「小壹」「画布」「工作台」「制作助手」/);
|
||||
assert.match(agent, /不得向用户暴露底层技术或开源底座名称/);
|
||||
});
|
||||
@ -255,12 +255,12 @@ pub(super) fn detail_selection(models: &[Value], settings: &Value, authorized: &
|
||||
}
|
||||
|
||||
pub(super) fn load_pi_catalog(root:&Path)->R<Vec<Value>> {
|
||||
let manifest:Value=serde_json::from_slice(&std::fs::read(root.join(".manifest.json")).map_err(|_|"客户端缺少Pi模型资料,请安装完整版本")?).map_err(|_|"Pi模型资料无效")?;
|
||||
let files=manifest["files"].as_object().ok_or("Pi模型资料目录无效")?;
|
||||
let manifest:Value=serde_json::from_slice(&std::fs::read(root.join(".manifest.json")).map_err(|_|"客户端缺少模型资料,请安装完整版本")?).map_err(|_|"模型资料无效")?;
|
||||
let files=manifest["files"].as_object().ok_or("模型资料目录无效")?;
|
||||
let mut models=Vec::new();
|
||||
for name in files.keys() {
|
||||
let catalog:Value=serde_json::from_slice(&std::fs::read(root.join(name)).map_err(|_|"Pi模型资料不可读取")?).map_err(|_|"Pi模型资料无效")?;
|
||||
for entries in catalog.as_object().ok_or("Pi模型资料格式无效")?.values().filter_map(Value::as_object) {
|
||||
let catalog:Value=serde_json::from_slice(&std::fs::read(root.join(name)).map_err(|_|"模型资料不可读取")?).map_err(|_|"模型资料无效")?;
|
||||
for entries in catalog.as_object().ok_or("模型资料格式无效")?.values().filter_map(Value::as_object) {
|
||||
models.extend(entries.values().filter(|entry|entry["type"]=="chat"&&entry["contextWindow"].as_u64().is_some_and(|limit|limit>0)).cloned());
|
||||
}
|
||||
}
|
||||
@ -325,6 +325,13 @@ pub(super) fn apply_pi_capacity(model: &mut Value, catalog: &[Value]) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn missing_model_data_tells_the_user_to_install_the_complete_client() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let error = load_pi_catalog(root.path()).unwrap_err();
|
||||
assert_eq!(error.to_string(), "客户端缺少模型资料,请安装完整版本");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_thinking_preference_uses_the_selected_route_support() {
|
||||
let schema = json!({"reasoning":{"properties":{"effort":{"enum":["low","high"]}}}});
|
||||
|
||||
@ -291,7 +291,7 @@ pub(super) fn runtime() -> R<(PathBuf, PathBuf)> {
|
||||
return Ok((node, script));
|
||||
}
|
||||
}
|
||||
Err("客户端缺少Agent运行组件,请保留项目并安装完整版本".into())
|
||||
Err("客户端缺少小壹的运行组件,请保留项目并安装完整版本".into())
|
||||
}
|
||||
|
||||
pub(super) fn record_product_export(project_dir: &Path, scope: &str, goal: &str) -> R<()> {
|
||||
@ -305,11 +305,11 @@ pub(super) fn record_product_export(project_dir: &Path, scope: &str, goal: &str)
|
||||
let receiver = daemon.begin(&run, &json!({
|
||||
"mode":"record-production-export","sessionDir":session,"goalId":goal,
|
||||
}))?;
|
||||
let result = receiver.recv().map_err(|_| "本机Agent连接中断,文件已交付");
|
||||
let result = receiver.recv().map_err(|_| "小壹的本机连接中断,文件已交付");
|
||||
daemon.end(&run);
|
||||
let reply = result??;
|
||||
if reply["value"]["recorded"] == true && reply["value"]["goalId"] == goal { return Ok(()); }
|
||||
Err(reply["value"]["error"].as_str().unwrap_or("Pi 目标完成回执未写入").to_owned())
|
||||
Err(reply["value"]["error"].as_str().unwrap_or("制作目标的完成回执未写入").to_owned())
|
||||
}
|
||||
|
||||
pub(super) fn enrich_models(models:&mut [Value])->R<()> {
|
||||
@ -318,7 +318,7 @@ pub(super) fn enrich_models(models:&mut [Value])->R<()> {
|
||||
#[cfg(test)]
|
||||
if let Some(root)=std::env::var_os("JIANSUN_PI_MODEL_DATA") {return crate::jiansun_models::load_pi_catalog(Path::new(&root));}
|
||||
let (_,script)=runtime()?;
|
||||
let root=script.parent().and_then(Path::parent).ok_or("Pi模型资料位置不可用")?.join("node_modules/@earendil-works/pi-ai/dist/providers/data");
|
||||
let root=script.parent().and_then(Path::parent).ok_or("小壹的模型资料位置不可用")?.join("node_modules/@earendil-works/pi-ai/dist/providers/data");
|
||||
crate::jiansun_models::load_pi_catalog(&root)
|
||||
}).as_ref().map_err(Clone::clone)?;
|
||||
for model in models {crate::jiansun_models::apply_pi_capacity(model,catalog);}
|
||||
@ -664,7 +664,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
let mut canvas_screen_reads = None;
|
||||
let mut late_workflow_replies = Vec::new();
|
||||
let start_workflow = |children: &mut WorkflowChildren, delegation: &Value, run: Option<&str>| {
|
||||
let start = run.ok_or_else(|| "原Agent回合尚未绑定".to_owned())
|
||||
let start = run.ok_or_else(|| "原对话尚未连接到当前项目".to_owned())
|
||||
.and_then(|run| children.start(b, delegation, (run, &project, doc), events, ctx));
|
||||
if let Err(error) = &start
|
||||
&& let Some(method) = delegation["method"].as_str().filter(|method| matches!(*method, "slot-append" | "slot-adopt-prep"))
|
||||
@ -679,15 +679,15 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
let _ = start_workflow(&mut workflow_children, &delegation, bound_run.as_deref());
|
||||
}
|
||||
let value = if late_workflow_replies.is_empty() {
|
||||
receiver.recv().map_err(|_| BridgeFailure::interrupted("本机Agent连接中断,原请求需核查", true))??
|
||||
receiver.recv().map_err(|_| BridgeFailure::interrupted("小壹的本机连接中断,原请求需核查", true))??
|
||||
} else {
|
||||
match receiver.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(value) => value?,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => return Err(BridgeFailure::interrupted("本机Agent连接中断,原请求需核查", true)),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => return Err(BridgeFailure::interrupted("小壹的本机连接中断,原请求需核查", true)),
|
||||
}
|
||||
};
|
||||
if value["runId"] != daemon_run { return Err("本机Agent回合身份不一致".into()); }
|
||||
if value["runId"] != daemon_run { return Err("小壹未能核对本次对话".into()); }
|
||||
if value["type"] == "presentation" {
|
||||
let action = value["action"].as_str().filter(|action| matches!(*action, "pi-delta" | "pi-activity"))
|
||||
.ok_or("Agent展示动作未授权")?;
|
||||
|
||||
@ -98,7 +98,7 @@ pub(super) fn idle(dir: &Path) -> R<()> {
|
||||
if let (Some(account), Some(id)) = (dir.parent().and_then(Path::parent), dir.file_name())
|
||||
&& !super::pi::unresolved(&account.join("pi-validation").join(id).join("requests"))?.is_empty()
|
||||
{
|
||||
return Err("项目有Pi请求待核查,不能删除或绕过原请求".into());
|
||||
return Err("项目有小壹请求待核查,请先核查原请求再删除项目".into());
|
||||
}
|
||||
for name in ["task.json", "image-task.json", "creation-task.json"] {
|
||||
let path = dir.join(name);
|
||||
|
||||
@ -431,7 +431,7 @@ fn settled_task_identity(dir: &Path, requests: &[Value]) -> R<String> {
|
||||
let bytes = STANDARD.decode(request["data"].as_str().ok_or("原请求内容缺失")?).map_err(|_| "原请求编码无效")?;
|
||||
let task: Value = serde_json::from_slice(&bytes).map_err(|_| "原请求记录无效")?;
|
||||
if !matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "rejected" | "not_dispatched")) {
|
||||
return Err("项目有未结束或结果未知的Pi原请求,未读取云端新版;原请求未重发".into());
|
||||
return Err("小壹的原请求尚未结束或需要核查,暂未读取云端新版。原请求未重发。".into());
|
||||
}
|
||||
}
|
||||
Ok(digest(serde_json::to_string(&identities).map_err(|_| "原任务身份无法核对")?.as_bytes()))
|
||||
@ -1100,7 +1100,7 @@ mod tests {
|
||||
task["phase"] = json!("unknown");
|
||||
fs::write(&request, task.to_string()).unwrap();
|
||||
let (_, unknown) = request_files(&account, &local).unwrap();
|
||||
assert!(settled_task_identity(&project, &unknown).unwrap_err().contains("未知的Pi原请求"));
|
||||
assert!(settled_task_identity(&project, &unknown).unwrap_err().contains("小壹的原请求尚未结束或需要核查"));
|
||||
let pending = super::super::pi::unresolved(request.parent().unwrap()).unwrap();
|
||||
assert_eq!(pending.len(), 1);
|
||||
assert_eq!(pending[0]["phase"], "unknown");
|
||||
|
||||
@ -254,7 +254,9 @@ impl Backend for MacMenu {
|
||||
pub fn install(ctx: &egui::Context, app: &photocraft_ui_egui::PhotocraftApp) -> Option<native_menu::NativeMenu> {
|
||||
let language = &app.session.prefs().interface.language;
|
||||
let lang = photocraft_ui_egui::i18n::Lang::from_pref(language);
|
||||
let bar = native_menu::photocraft_layout(&photocraft_ui_egui::menus::menu_items(app), lang, language).bar;
|
||||
let bar = native_menu::photocraft_layout_for(
|
||||
&photocraft_ui_egui::menus::menu_items(app), lang, language, photocraft_ui_egui::CLIENT_NAME,
|
||||
).bar;
|
||||
// Never crash for a menu: if AppKit refuses, keep the in-window menus.
|
||||
let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let mut menu = MacMenu::new(ctx);
|
||||
|
||||
@ -161,7 +161,7 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
eframe::NativeOptions {
|
||||
viewport: viewport
|
||||
.with_app_id(APP_ID)
|
||||
.with_title("由壹点详情页工作台")
|
||||
.with_title(photocraft_ui_egui::CLIENT_NAME)
|
||||
.with_inner_size([1440.0, 900.0])
|
||||
.with_min_inner_size([1100.0, 720.0])
|
||||
.with_drag_and_drop(true)
|
||||
@ -534,7 +534,7 @@ fn main() -> eframe::Result {
|
||||
let created_in_callback = app_created.clone();
|
||||
let started_sentinel = sentinel.clone();
|
||||
let result = eframe::run_native(
|
||||
"由壹点详情页工作台",
|
||||
photocraft_ui_egui::CLIENT_NAME,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
created_in_callback.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
@ -294,7 +294,7 @@ fn capture(_wayland: bool, _scale: f32, stop: &std::sync::atomic::AtomicBool, pl
|
||||
fn capture(_wayland: bool, _scale: f32, stop: &std::sync::atomic::AtomicBool, placements: &[Placement]) -> Result<Capture, String> {
|
||||
use core_graphics2::{display::get_active_display_list, image::CGImageAlphaInfo as Alpha, window};
|
||||
if !window::preflight_screen_capture_access() && !window::request_screen_capture_access() {
|
||||
return Err("Allow PhotoCraft in System Settings > Privacy & Security > Screen Recording, then reopen PhotoCraft".into());
|
||||
return Err("请在系统设置的「隐私与安全性 → 屏幕录制」中允许小壹录制屏幕,然后重新打开客户端".into());
|
||||
}
|
||||
let displays = get_active_display_list(17).ok_or("Could not enumerate displays")?;
|
||||
if displays.is_empty() || displays.len() > 16 {
|
||||
|
||||
@ -42,7 +42,7 @@ fn open_filter_extensions(extensions: &[&str]) -> Vec<String> {
|
||||
/// picker defaults to another filter.
|
||||
const OPEN_FILTERS: &[(&str, &[&str])] = &[
|
||||
("小壹工程", &["xiaoyi"]),
|
||||
("PhotoCraft", &["pcraft"]),
|
||||
("画布工程文件", &["pcraft"]),
|
||||
("Photoshop", &["psd", "psb", "psdt"]),
|
||||
("Affinity", &["af", "afdesign", "afphoto", "afpub"]),
|
||||
("Krita", &["kra", "krz"]),
|
||||
@ -90,7 +90,7 @@ fn open_filters() -> Vec<(&'static str, Vec<String>)> {
|
||||
const SAVE_FILTERS: &[(&str, &[&str])] = &[
|
||||
("PSD Document", &["psd", "psb"]),
|
||||
("PDF", &["pdf"]),
|
||||
("PhotoCraft", &["pcraft"]),
|
||||
("画布工程文件", &["pcraft"]),
|
||||
("OpenRaster", &["ora"]),
|
||||
("PNG", &["png"]),
|
||||
("JPEG", &["jpg", "jpeg"]),
|
||||
|
||||
@ -4,6 +4,15 @@ use photocraft_format::list_recovery;
|
||||
use photocraft_ui_egui::{PhotocraftApp, prefs_ui};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn native_open_and_save_filters_keep_the_engine_extension_under_the_product_label() {
|
||||
assert!(open_filters().iter().any(|(name, extensions)| *name == "画布工程文件" && *extensions == open_filter_extensions(&["pcraft"])));
|
||||
let filters = save_filters("工程.pcraft");
|
||||
assert_eq!(filters[0], ("画布工程文件".to_owned(), vec!["pcraft".to_owned()]));
|
||||
assert!(open_filters().iter().all(|(name, _)| !name.contains("PhotoCraft")));
|
||||
assert!(filters.iter().all(|(name, _)| !name.contains("PhotoCraft")));
|
||||
}
|
||||
|
||||
/// #6601: a chosen path whose name isn't valid Unicode is reported, never handed on lossily
|
||||
/// (Open would fail with "No such file", Save would write a second, renamed file).
|
||||
#[test]
|
||||
|
||||
@ -38,13 +38,13 @@ fn has_display() -> bool {
|
||||
/// The dialog's text: the error, the renderer that was tried and why it wasn't the preference,
|
||||
/// the version and, when one was opened, the log file.
|
||||
pub fn text(error: &str, renderer: &str, note: Option<&str>, version: &str, log: Option<&Path>) -> String {
|
||||
let mut text = format!("PhotoCraft could not start.\n\n{error}\n\nRenderer: {renderer}");
|
||||
let mut text = format!("小壹未能启动。\n\n{error}\n\n渲染器:{renderer}");
|
||||
if let Some(note) = note {
|
||||
text.push_str(&format!("\nStartup: {note}"));
|
||||
text.push_str(&format!("\n启动说明:{note}"));
|
||||
}
|
||||
text.push_str(&format!("\nVersion: {version}"));
|
||||
text.push_str(&format!("\n版本:{version}"));
|
||||
if let Some(path) = log {
|
||||
text.push_str(&format!("\nLog file: {}", path.display()));
|
||||
text.push_str(&format!("\n日志文件:{}", path.display()));
|
||||
}
|
||||
text
|
||||
}
|
||||
@ -57,7 +57,7 @@ pub fn show(error: &str, renderer: &str, note: Option<&str>, log: Option<&Path>)
|
||||
log::info!("showing the startup-failure dialog");
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_title(photocraft_ui_egui::i18n::t("PhotoCraft could not start"))
|
||||
.set_title("小壹未能启动")
|
||||
.set_description(body)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
@ -80,17 +80,18 @@ mod tests {
|
||||
let log = Path::new("/home/me/.config/photocraft/logs/photocraft.log");
|
||||
let body = text("no adapter for Vulkan", "dx12", None, "0.15.1 (abc1234)", Some(log));
|
||||
for part in [
|
||||
"could not start",
|
||||
"小壹未能启动",
|
||||
"no adapter for Vulkan",
|
||||
"Renderer: dx12",
|
||||
"Version: 0.15.1 (abc1234)",
|
||||
"Log file: /home/me/.config/photocraft/logs/photocraft.log",
|
||||
"渲染器:dx12",
|
||||
"版本:0.15.1 (abc1234)",
|
||||
"日志文件:/home/me/.config/photocraft/logs/photocraft.log",
|
||||
] {
|
||||
assert!(body.contains(part), "{part:?} missing from {body:?}");
|
||||
}
|
||||
assert!(!body.contains("Startup:"), "no fallback to explain: {body:?}");
|
||||
assert!(!body.contains("PhotoCraft"));
|
||||
assert!(!body.contains("启动说明:"), "no fallback to explain: {body:?}");
|
||||
// A start whose log file could not be created says so by leaving the line out.
|
||||
assert!(!text("boom", "cpu", None, "0.15.1", None).contains("Log file:"));
|
||||
assert!(!text("boom", "cpu", None, "0.15.1", None).contains("日志文件:"));
|
||||
}
|
||||
|
||||
/// A crash fallback is the confusing case: the app picks a renderer the user never chose, so
|
||||
@ -99,6 +100,6 @@ mod tests {
|
||||
fn a_fallback_that_was_not_the_preference_is_explained() {
|
||||
let note = "the previous start didn't finish on vulkan; using dx12";
|
||||
let body = text("device lost", "dx12", Some(note), "0.15.1", None);
|
||||
assert!(body.contains(&format!("Renderer: dx12\nStartup: {note}\n")), "{body:?}");
|
||||
assert!(body.contains(&format!("渲染器:dx12\n启动说明:{note}\n")), "{body:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -564,6 +564,7 @@ impl PhotocraftApp {
|
||||
}
|
||||
match written {
|
||||
Err(e) => {
|
||||
let e = if crate::client_brand::active(self) { crate::client_brand::file_diagnostic(&e) } else { e };
|
||||
self.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);
|
||||
self.ui.status_error = true;
|
||||
}
|
||||
|
||||
@ -33,8 +33,9 @@ pub(super) fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(card), |ui| {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let title = ui.painter().layout_no_wrap(tl!("PhotoCraft").into(), crate::theme::semibold(38.0), t.text);
|
||||
let by = ui.painter().layout_no_wrap(tl!("open source").into(), egui::FontId::proportional(13.0), t.text_faint);
|
||||
let title = ui.painter().layout_no_wrap(crate::client_brand::name(app).into(), crate::theme::semibold(38.0), t.text);
|
||||
let subtitle = if crate::client_brand::active(app) { "" } else { tl!("open source") };
|
||||
let by = ui.painter().layout_no_wrap(subtitle.into(), egui::FontId::proportional(13.0), t.text_faint);
|
||||
let total = title.size().x + by.size().x + 10.0;
|
||||
ui.add_space(((card.width() - total) / 2.0).max(0.0));
|
||||
let (r, _) = ui.allocate_exact_size(title.size(), Sense::hover());
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
//! Presentation of the material platform client; upstream notices stay intact.
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
pub const NAME: &str = "由壹点详情页工作台";
|
||||
pub const NAME: &str = "小壹工作台";
|
||||
|
||||
pub fn active(app: &PhotocraftApp) -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@ -28,6 +28,23 @@ pub fn text_for(branded: bool, value: &str) -> String {
|
||||
if branded { value.replace("PhotoCraft", NAME) } else { value.into() }
|
||||
}
|
||||
|
||||
/// Brand stock profile labels while preserving the names of custom profiles.
|
||||
pub(crate) fn profile_label(branded: bool, label: &str) -> String {
|
||||
let builtin = branded && photocraft_cms::Builtin::ALL.iter().any(|profile| profile.description() == label);
|
||||
text_for(builtin, label)
|
||||
}
|
||||
|
||||
/// Translate the engine's format name when presenting a file diagnostic.
|
||||
pub(crate) fn file_diagnostic(value: &str) -> String {
|
||||
if let Some(detail) = value.strip_prefix("pcraft: ") {
|
||||
format!("画布工程文件:{detail}")
|
||||
} else if let Some((context, detail)) = value.split_once(": pcraft: ") {
|
||||
format!("{context}: 画布工程文件:{detail}")
|
||||
} else {
|
||||
value.into()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn licenses(ui: &mut egui::Ui) {
|
||||
ui.label("本客户端基于 PhotoCraft v0.19.0 二次开发。原项目与第三方组件的署名及许可保留如下。");
|
||||
egui::ScrollArea::vertical().id_salt("client-open-source-licenses").max_height(350.0).show(ui, |ui| {
|
||||
@ -75,10 +92,55 @@ mod tests {
|
||||
assert_eq!(crate::dialogs::title(d), format!("关于{NAME}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_copy_stays_white_label() {
|
||||
let has_engine_name = |text: &str| {
|
||||
text.contains("PhotoCraft") || text.contains("pcraft:") ||
|
||||
text.split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-').any(|word| word == "Pi")
|
||||
};
|
||||
let app = client();
|
||||
let menus = crate::menus::menu_items(&app);
|
||||
let native = crate::native_menu::photocraft_layout_for(&menus, crate::i18n::Lang::EN, "auto", name(&app));
|
||||
assert!(native.bar.menus.iter().any(|menu| menu.title == NAME));
|
||||
for menu in &native.bar.menus {
|
||||
assert!(!has_engine_name(&menu.title), "{}", menu.title);
|
||||
}
|
||||
for item in native.bar.items() {
|
||||
assert!(!has_engine_name(&item.label), "{}", item.label);
|
||||
}
|
||||
|
||||
for (file, source) in [
|
||||
("agent panel", include_str!("jiansun/agent_panel.rs")),
|
||||
("copy warnings", include_str!("jiansun/native_copy_warnings.rs")),
|
||||
("workflow export", include_str!("jiansun/workflow_export.rs")),
|
||||
] {
|
||||
let production = source.split_once("mod tests {").map_or(source, |(production, _)| production);
|
||||
for line in production.lines().filter(|line| line.contains('"') && !line.trim_start().starts_with("//")) {
|
||||
assert!(!has_engine_name(line), "{file}: {line}");
|
||||
}
|
||||
}
|
||||
|
||||
for line in include_str!("i18n/zh-hans.tsv").lines().filter(|line| !line.starts_with('#')) {
|
||||
let Some((key, translation)) = line.rsplit_once('\t') else { continue };
|
||||
// The standalone app's identity and upstream help live outside the client.
|
||||
if matches!(key.split('\t').next_back(), Some("PhotoCraft" | "About PhotoCraft" |
|
||||
"PhotoCraft Website" | "PhotoCraft on GitHub" | "PhotoCraft website" |
|
||||
"PhotoCraft — an open-source, native image editor written in Rust." | "Default PhotoCraft Size"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
assert!(!has_engine_name(translation), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presentation_keeps_source_attribution_separate_from_client_copy() {
|
||||
let app = client();
|
||||
assert_eq!(name(&app), NAME);
|
||||
let stock = photocraft_cms::Builtin::DotGain20Compat.description();
|
||||
assert!(!profile_label(true, stock).contains("PhotoCraft"));
|
||||
assert_eq!(profile_label(true, "PhotoCraft Studio CMYK"), "PhotoCraft Studio CMYK");
|
||||
assert_eq!(file_diagnostic("draft.pcraft: missing"), "draft.pcraft: missing");
|
||||
assert_eq!(text(&app, "PhotoCraft Print Settings"), format!("{NAME} Print Settings"));
|
||||
assert!(include_str!("../../../NOTICE").contains("ArtCraft Team and the PhotoCraft contributors"));
|
||||
assert!(include_str!("../../../LICENSE-MIT").contains("Copyright"));
|
||||
|
||||
@ -250,10 +250,12 @@ fn profile_options(
|
||||
space: Option<photocraft_cms::ColorSpace>,
|
||||
working: &str,
|
||||
installed: &[photocraft_engine::installed_profiles::InstalledProfile],
|
||||
branded: bool,
|
||||
) -> Vec<(String, String)> {
|
||||
let mut v = vec![("working".to_string(), crate::i18n::fmt(tl!("Working: {working}"), &[("working", working)]))];
|
||||
let working = crate::client_brand::profile_label(branded, working);
|
||||
let mut v = vec![("working".to_string(), crate::i18n::fmt(tl!("Working: {working}"), &[("working", &working)]))];
|
||||
let Some(space) = space else { return v };
|
||||
v.extend(photocraft_cms::Builtin::ALL.iter().filter(|b| b.profile().color_space == space).map(|b| (b.id().to_string(), b.description().to_string())));
|
||||
v.extend(photocraft_cms::Builtin::ALL.iter().filter(|b| b.profile().color_space == space).map(|b| (b.id().to_string(), crate::client_brand::text_for(branded, b.description()))));
|
||||
v.extend(installed.iter().filter(|i| i.is_destination() && i.color_space == space).map(|i| (i.path.clone(), i.description.clone())));
|
||||
v
|
||||
}
|
||||
@ -770,7 +772,7 @@ pub fn body(app: &mut crate::PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<Strin
|
||||
let space = color_mode_of(&mode).map(photocraft_engine::color_cmds::mode_space);
|
||||
let working = color_mode_of(&mode).map(|m| app.session.color.working(m).description.clone()).unwrap_or_default();
|
||||
let installed = photocraft_engine::installed_profiles::installed();
|
||||
let opts = profile_options(space, &working, &installed);
|
||||
let opts = profile_options(space, &working, &installed, crate::client_brand::active(app));
|
||||
let mut profile = get_s(f, "profile", "working");
|
||||
if !opts.iter().any(|(v, _)| *v == profile) {
|
||||
// Not a profile of this mode (or no longer installed): Create must not send it.
|
||||
|
||||
@ -10,7 +10,7 @@ fn color_profile_menu_lists_the_profiles_of_the_modes_space() {
|
||||
InstalledProfile { path: "panel.icc".into(), description: "Panel".into(), class: ProfileClass::Display, color_space: ColorSpace::Rgb },
|
||||
];
|
||||
let values = |mode: &str| {
|
||||
profile_options(color_mode_of(mode).map(photocraft_engine::color_cmds::mode_space), "sRGB", &installed).into_iter().map(|(v, _)| v).collect::<Vec<_>>()
|
||||
profile_options(color_mode_of(mode).map(photocraft_engine::color_cmds::mode_space), "sRGB", &installed, false).into_iter().map(|(v, _)| v).collect::<Vec<_>>()
|
||||
};
|
||||
let rgb = values("rgb");
|
||||
assert_eq!(rgb[0], "working");
|
||||
@ -18,7 +18,7 @@ fn color_profile_menu_lists_the_profiles_of_the_modes_space() {
|
||||
assert!(!rgb.contains(&Builtin::CoatedCmyk.id().to_string()) && !rgb.contains(&"press.icc".to_string()));
|
||||
let cmyk = values("cmyk");
|
||||
assert!(cmyk.contains(&"press.icc".to_string()) && !cmyk.contains(&Builtin::Srgb.id().to_string()));
|
||||
assert!(profile_options(None, "sRGB", &installed).len() == 1, "an unknown mode offers only the working space");
|
||||
assert!(profile_options(None, "sRGB", &installed, false).len() == 1, "an unknown mode offers only the working space");
|
||||
// Every entry is one `file.new` takes for that mode.
|
||||
for mode in ["rgb", "gray", "cmyk", "lab"] {
|
||||
for v in values(mode).into_iter().filter(|v| !v.ends_with(".icc")) {
|
||||
|
||||
@ -211,10 +211,16 @@ impl PhotocraftApp {
|
||||
|
||||
/// Show "Couldn't open <name>: <error>" as an error (status bar + notice).
|
||||
pub fn open_failed(&mut self, name: &str, err: &str) {
|
||||
self.failed({
|
||||
let template = "Couldn't open {name}: {error}";
|
||||
crate::i18n::fmt(tl!(template), &[("name", name), ("error", err)])
|
||||
});
|
||||
let template = tl!("Couldn't open {name}: {error}");
|
||||
let message = |error: &str| crate::i18n::fmt(template, &[("name", name), ("error", error)]);
|
||||
let raw = message(err);
|
||||
log::warn!("{raw}");
|
||||
let notice = if crate::client_brand::active(self) {
|
||||
message(&crate::client_brand::file_diagnostic(err))
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
notices::error(self, notice);
|
||||
}
|
||||
|
||||
/// Log `msg` and show it as an error (status bar + notice).
|
||||
|
||||
@ -979,7 +979,7 @@
|
||||
All Caps 全部大写
|
||||
All Slices 所有切片
|
||||
All User Slices 所有用户切片
|
||||
All shortcuts reset to PhotoCraft defaults. 所有快捷键已重置为 PhotoCraft 默认值。
|
||||
All shortcuts reset to PhotoCraft defaults. 已恢复默认快捷键。
|
||||
Alt Alt
|
||||
Alt-click to define a source point to clone from 按 Alt 单击以定义仿制源点
|
||||
Always use pressure for opacity 始终用压感控制不透明度
|
||||
@ -1234,8 +1234,8 @@
|
||||
Drop an image or PSD anywhere to open it. 将图像或 PSD 拖放到任意位置即可打开。
|
||||
Native file drag-and-drop is unavailable Wayland 上不支持原生文件拖放
|
||||
Native file drag-and-drop is not supported on Wayland yet. Use File › Open, or copy the image in your file manager and paste it with {paste}. Wayland 尚不支持原生文件拖放。请使用“文件 › 打开”,或在文件管理器中复制图像后使用 {paste} 粘贴。
|
||||
To drop files, start PhotoCraft under XWayland: `{command}` 要拖放文件,请在 XWayland 下启动 PhotoCraft:`{command}`
|
||||
Or set Preferences › Performance › Linux display server to X11: PhotoCraft then always starts under XWayland. 或将 首选项 › 性能 › Linux 显示服务器 设为 X11:PhotoCraft 将始终在 XWayland 下启动。
|
||||
To drop files, start PhotoCraft under XWayland: `{command}` 如需拖放文件,请在 XWayland 下重新打开工作台:`{command}`
|
||||
Or set Preferences › Performance › Linux display server to X11: PhotoCraft then always starts under XWayland. 或将 首选项 › 性能 › Linux 显示服务器 设为 X11:工作台将始终在 XWayland 下启动。
|
||||
Edit › Paste “编辑 › 粘贴”
|
||||
Duplicate Layers… 复制图层…
|
||||
Duplicate style 复制样式
|
||||
@ -1493,7 +1493,7 @@
|
||||
Perspective Warp: draw planes along the image's perspective, then switch to Warp 透视变形:沿图像透视绘制平面,然后切换到变形
|
||||
Photo Filter 照片滤镜
|
||||
PhotoCraft PhotoCraft
|
||||
PhotoCraft Manages Colors 由 PhotoCraft 管理颜色
|
||||
PhotoCraft Manages Colors 由应用管理颜色
|
||||
PhotoCraft — an open-source, native image editor written in Rust. PhotoCraft — 用 Rust 编写的开源原生图像编辑器。
|
||||
Pin Depth: 控制点深度:
|
||||
Pixel Length: 像素长度:
|
||||
@ -1571,11 +1571,11 @@
|
||||
Import Shortcuts… 导入快捷键…
|
||||
Load a keyboard shortcut set saved as .kys 载入保存为 .kys 的键盘快捷键集
|
||||
Imported {n} shortcuts from {file}. Click OK to keep them. 已从 {file} 导入 {n} 个快捷键。点击“确定”保留。
|
||||
{n} commands are not in PhotoCraft. {n} 个命令在 PhotoCraft 中不存在。
|
||||
{n} commands are not in PhotoCraft. 工作台中没有对应的 {n} 个命令。
|
||||
Keyboard shortcuts imported 已导入键盘快捷键
|
||||
Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. 此处正在使用你的键盘快捷键集 {set}:{n} 个快捷键与默认值不同。可在“编辑 › 键盘快捷键”中查看;“全部重置为默认值”可撤销。
|
||||
Import keyboard shortcuts? 导入键盘快捷键?
|
||||
PhotoCraft found your keyboard shortcut set {set} from another image editor on this computer: {n} of its shortcuts differ from PhotoCraft's. Import it? PhotoCraft 在这台电脑上找到了你在其他图像编辑器中的键盘快捷键集 {set}:其中 {n} 个快捷键与 PhotoCraft 不同。要导入吗?
|
||||
PhotoCraft found your keyboard shortcut set {set} from another image editor on this computer: {n} of its shortcuts differ from PhotoCraft's. Import it? 在本机找到其他图像编辑器的快捷键集 {set},其中 {n} 个快捷键与当前设置不同。要导入吗?
|
||||
Edit › Keyboard Shortcuts › Reset All to Defaults undoes an import. “编辑 › 键盘快捷键 › 全部重置为默认值”可撤销导入。
|
||||
Don't Import 不导入
|
||||
The keyboard shortcut set was not imported: {error} 未导入键盘快捷键集:{error}
|
||||
@ -2311,7 +2311,7 @@ cameraRaw Blending 混合
|
||||
System Info 系统信息
|
||||
More panels 更多面板
|
||||
More documents 更多文档
|
||||
These settings aren't available in PhotoCraft yet. PhotoCraft 暂不支持这些设置。
|
||||
These settings aren't available in PhotoCraft yet. 当前版本暂不支持这些设置。
|
||||
Graphics 图形
|
||||
Reset GPU Backend 重置 GPU 后端
|
||||
Applies at next launch. 下次启动时生效。
|
||||
@ -2435,7 +2435,7 @@ cameraRaw Blending 混合
|
||||
Automatic uses GPU acceleration when available and falls back to CPU rendering on errors. 自动模式会在可用时使用 GPU 加速,出错时改用 CPU 渲染。
|
||||
Switched to CPU rendering 已切换到 CPU 渲染
|
||||
GPU acceleration could not continue. Your documents are unchanged. GPU 加速无法继续。您的文档未更改。
|
||||
PhotoCraft is using the CPU image compositor. The window may still use your graphics adapter. PhotoCraft 正在使用 CPU 合成图像。窗口仍可能使用您的显卡。
|
||||
PhotoCraft is using the CPU image compositor. The window may still use your graphics adapter. 正在使用 CPU 合成图像。窗口仍可能由显卡渲染。
|
||||
Retry GPU requires a restart. Save your work first. 重试 GPU 需要重新启动。请先保存您的工作。
|
||||
Retry GPU tries the graphics processor again now. 重试 GPU 会立即再次尝试使用图形处理器。
|
||||
GPU acceleration resumed. 已恢复 GPU 加速。
|
||||
@ -2628,7 +2628,7 @@ fontWeight Italic 斜体
|
||||
Color to Alpha… 颜色转为 Alpha…
|
||||
Transparency Threshold 透明度阈值
|
||||
Opacity Threshold 不透明度阈值
|
||||
PhotoCraft — Screen Color Picker PhotoCraft — 屏幕取色器
|
||||
PhotoCraft — Screen Color Picker 屏幕取色器
|
||||
Rasterize svg groups deeper than 栅格化超过此深度的 SVG 组
|
||||
0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 设为 0 可关闭此阈值;嵌套超过 100 层的 SVG 组始终会被栅格化。
|
||||
Rule of Thirds 三等分
|
||||
@ -2922,7 +2922,7 @@ curves Smooth 平滑
|
||||
{name} (Photoshop) {name}(Photoshop)
|
||||
{message} ({note}) {message}({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} 已从 {file} 载入 {n} 个动作
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} 个步骤在 PhotoCraft 中尚无对应功能
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet 有 {n} 个步骤暂不受支持
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} 已将 {n} 个动作存储到 {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out 已省略 {n} 个没有 Photoshop 对应功能的步骤
|
||||
File Naming 文件命名
|
||||
@ -3017,12 +3017,12 @@ curves Smooth 平滑
|
||||
Bicubic Smoother 双三次(较平滑)
|
||||
Bicubic Sharper 双三次(较锐利)
|
||||
Pasting from other apps is unavailable 无法从其他应用粘贴
|
||||
PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. PhotoCraft 在此会话中无法访问系统剪贴板。在 Wayland 上,Flatpak 沙盒会隐藏读取其他应用图像所用的协议。
|
||||
To paste from other apps, start PhotoCraft under XWayland: `{command}` 要从其他应用粘贴,请在 XWayland 下启动 PhotoCraft:`{command}`
|
||||
Nothing to paste: PhotoCraft can't read the system clipboard here 没有可粘贴的内容:PhotoCraft 在此无法读取系统剪贴板
|
||||
PhotoCraft can't reach the system clipboard in this session. On Wayland, a Flatpak sandbox hides the protocol that images from other apps are read through. 工作台目前无法访问系统剪贴板。在 Wayland 上,Flatpak 沙盒会隐藏读取其他应用图像所用的协议。
|
||||
To paste from other apps, start PhotoCraft under XWayland: `{command}` 如需从其他应用粘贴,请在 XWayland 下重新打开工作台:`{command}`
|
||||
Nothing to paste: PhotoCraft can't read the system clipboard here 无法读取系统剪贴板
|
||||
Delete this set 删除此组
|
||||
New Set… 新建组…
|
||||
PhotoCraft Defaults PhotoCraft 默认值
|
||||
PhotoCraft Defaults 默认快捷键
|
||||
Save a list of these shortcuts as a web page 将这些快捷键的列表存储为网页
|
||||
Save the changes to this set 将更改存储到此组
|
||||
Save these shortcuts as a .kys file 将这些快捷键存储为 .kys 文件
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 63 and column 53.
|
@ -3334,7 +3334,7 @@ impl Workspace {
|
||||
"high" => "高",
|
||||
"xhigh" => "很高",
|
||||
"max" => "最高",
|
||||
_ => "跟随 Pi",
|
||||
_ => "自动",
|
||||
};
|
||||
let current = self.thinking_by_model.get(self.model.as_str()).and_then(Value::as_str).unwrap_or("");
|
||||
let mut selected = current;
|
||||
@ -6099,6 +6099,33 @@ mod tests {
|
||||
assert!(requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thinking_picker_labels_the_automatic_setting_and_keeps_its_empty_value() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
for width in [250.0, 520.0] {
|
||||
let (mut app, requests) = dock_fixture();
|
||||
let mut workspace = app.jiansun.take().unwrap();
|
||||
workspace.reduce_motion = true;
|
||||
workspace.models[0]["reasoning"] = json!(true);
|
||||
workspace.models[0]["reasoningEfforts"] = json!(["high"]);
|
||||
workspace.thinking_by_model[workspace.model.as_str()] = json!("high");
|
||||
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::cjk_fonts::install_system_provider_for_tests)
|
||||
.with_size(vec2(width, 240.0))
|
||||
.build_ui_state(|ui, workspace: &mut Workspace| workspace.thinking_picker(ui), workspace);
|
||||
harness.run_steps(4);
|
||||
harness.get_by_label("高").click();
|
||||
harness.run_steps(4);
|
||||
harness.get_by_label("自动").click();
|
||||
harness.run_steps(4);
|
||||
let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected a local preference action") };
|
||||
assert_eq!(method, "select-model");
|
||||
assert_eq!(input["field"], "thinkingLevel");
|
||||
assert_eq!(input["selection"], "");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
#[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"]
|
||||
@ -6128,7 +6155,7 @@ mod tests {
|
||||
harness.run_steps(6);
|
||||
let trigger = geometry(harness.state().0.jiansun.as_ref().unwrap(), "thinkingLevel");
|
||||
assert!(trigger.left() >= 0.0 && trigger.right() <= width);
|
||||
harness.get_by_label("跟随 Pi").click();
|
||||
harness.get_by_label("自动").click();
|
||||
harness.run_steps(4);
|
||||
harness.render().unwrap().save(directory.join(format!("thinking-picker-{width}.png"))).unwrap();
|
||||
harness.get_by_label("高").click();
|
||||
|
||||
@ -55,7 +55,7 @@ pub(crate) fn record(app: &mut PhotocraftApp, original: Option<&Scope>, result:
|
||||
return;
|
||||
}
|
||||
if let Some(w) = app.jiansun.as_mut() {
|
||||
w.note(format!("保存副本时有导出提示:\n{details}\n请保留完整 .pcraft 工程目录;导出文件不保证保留小壹图位映射。"));
|
||||
w.note(format!("保存副本时有导出提示:\n{details}\n请保留完整的画布工程目录;导出文件不保证保留小壹图位映射。"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -50,7 +50,7 @@ pub(super) fn message(raw:&str)->Message<'_> {
|
||||
fn dimensions(ui:&Ui,raw:&str,available_width:f32)->(f32,f32) {
|
||||
let button=ui.painter().layout_no_wrap("查看详情".into(),FontId::proportional(13.0),egui::Color32::WHITE).size().x+ui.spacing().button_padding.x*2.0;
|
||||
let width=(available_width-14.0-button-ui.spacing().item_spacing.x*2.0).max(1.0);
|
||||
let text=ui.painter().layout(message(raw).title.into(),FontId::proportional(14.0),egui::Color32::WHITE,width);
|
||||
let text=ui.painter().layout(crate::client_brand::file_diagnostic(message(raw).title),FontId::proportional(14.0),egui::Color32::WHITE,width);
|
||||
(width,text.size().y.max(34.0))
|
||||
}
|
||||
|
||||
@ -59,7 +59,7 @@ pub(super) fn inline_height(ui:&Ui,raw:&str,available_width:f32)->f32 {dimension
|
||||
pub(super) fn inline(ui:&mut Ui,raw:&str)->egui::Response {
|
||||
let t=crate::theme::Tokens::get(ui.ctx()).agent();
|
||||
let (width,height)=dimensions(ui,raw,ui.available_width());
|
||||
let label=ui.painter().layout(message(raw).title.into(),FontId::proportional(14.0),t.text,width);
|
||||
let label=ui.painter().layout(crate::client_brand::file_diagnostic(message(raw).title),FontId::proportional(14.0),t.text,width);
|
||||
ui.horizontal_top(|ui| {
|
||||
let color = if raw == "客户端工具配置不匹配,本次未发送模型请求" { t.warning } else { t.danger };
|
||||
ui.add(crate::icons::image("triangle-alert",14.0,color));
|
||||
@ -71,16 +71,18 @@ pub(super) fn inline(ui:&mut Ui,raw:&str)->egui::Response {
|
||||
pub(super) fn details(ui:&mut Ui,id:egui::Id,raw:&str,reduced:bool)->egui::Response {
|
||||
let t=crate::theme::Tokens::get(ui.ctx()).agent();
|
||||
let text=message(raw);
|
||||
ui.add(egui::Label::new(RichText::new(text.title).size(13.0).color(t.text)).wrap());
|
||||
let title=crate::client_brand::file_diagnostic(text.title);
|
||||
let diagnostic=crate::client_brand::file_diagnostic(raw);
|
||||
ui.add(egui::Label::new(RichText::new(&title).size(13.0).color(t.text)).wrap());
|
||||
if let Some(reason)=text.reason {ui.add(egui::Label::new(RichText::new(reason).size(12.0).color(t.text_dim)).wrap());}
|
||||
if let Some(guidance)=text.guidance {ui.add(egui::Label::new(RichText::new(guidance).size(12.0).color(t.text)).wrap());}
|
||||
if text.title!=raw {
|
||||
kit::disclosure(ui,id,"技术详情",false,reduced,|ui| {kit::selectable_text(ui,RichText::new(raw).size(12.0).color(t.text_dim));});
|
||||
kit::disclosure(ui,id,"技术详情",false,reduced,|ui| {kit::selectable_text(ui,RichText::new(&diagnostic).size(12.0).color(t.text_dim));});
|
||||
}
|
||||
let copy=kit::action_button(ui,"复制问题详情",kit::ButtonRole::Quiet,true);
|
||||
if copy.clicked() {
|
||||
let reason=text.reason.unwrap_or("");
|
||||
let body = if text.title == raw { raw.to_owned() } else { format!("{}\n{}\n\n技术详情:\n{raw}",text.title,reason) };
|
||||
let body = if text.title == raw { diagnostic } else { format!("{title}\n{reason}\n\n技术详情:\n{diagnostic}") };
|
||||
ui.ctx().copy_text(body);
|
||||
}
|
||||
copy
|
||||
@ -133,7 +135,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_error_details_requires_a_click_and_keeps_the_exact_diagnostic() {
|
||||
fn copy_error_details_requires_a_click_and_uses_the_product_format_name() {
|
||||
let ctx=egui::Context::default();
|
||||
crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium);
|
||||
let raw="can't read smart source within the preview budget: pcraft: limit exceeded: canvas 1440x35827 exceeds 8192 pixels per side";
|
||||
@ -148,7 +150,7 @@ mod tests {
|
||||
for (time,pressed) in [(0.1,true),(0.2,false)] {
|
||||
let mut out=render(time,vec![egui::Event::PointerMoved(at),egui::Event::PointerButton {pos:at,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE}],&mut rect);
|
||||
out.textures_delta.clear();
|
||||
if !pressed {assert!(out.platform_output.commands.iter().any(|command|matches!(command,egui::OutputCommand::CopyText(text) if text.ends_with(raw)&&text.contains("图片暂时无法读取"))));}
|
||||
if !pressed {assert!(out.platform_output.commands.iter().any(|command|matches!(command,egui::OutputCommand::CopyText(text) if text.contains("画布工程文件:limit exceeded: canvas 1440x35827 exceeds 8192 pixels per side")&&!text.contains("pcraft:")&&text.contains("图片暂时无法读取"))));}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -159,7 +159,7 @@ fn feedback(app: &mut PhotocraftApp, scope: &Scope, result: &Result<Value, Strin
|
||||
// `note` marks the original project's draft dirty. Preserve
|
||||
// the warning summary without copying a destination path.
|
||||
let details = warnings.iter().filter_map(Value::as_str).map(|warning| format!("• {}", native_copy_warnings::safe_warning(warning))).collect::<Vec<_>>().join("\n");
|
||||
format!("{format}副本已导出,导出提示:\n{details}\n请保留完整 .pcraft 工程目录;{format} 不保证保留小壹图位映射。")
|
||||
format!("{format}副本已导出,导出提示:\n{details}\n请保留完整的画布工程目录;{format} 不保证保留小壹图位映射。")
|
||||
} else {
|
||||
format!("已导出分层{format}副本,工程和未保存修改保留")
|
||||
}
|
||||
|
||||
@ -342,6 +342,7 @@ fn finish_save(app: &mut PhotocraftApp, ctx: &egui::Context, save: SaveJob, labe
|
||||
JobOutcome::Failed(err) => {
|
||||
// Don't close the window over the error.
|
||||
app.jobs.close_after_saves = false;
|
||||
let err = if crate::client_brand::active(app) { crate::client_brand::file_diagnostic(&err) } else { err };
|
||||
notices::error(app, crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &err)]));
|
||||
}
|
||||
JobOutcome::Cancelled => {
|
||||
|
||||
@ -31,6 +31,7 @@ mod native_cpu_transition;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod jiansun;
|
||||
pub(crate) mod client_brand;
|
||||
pub use client_brand::NAME as CLIENT_NAME;
|
||||
pub mod control;
|
||||
pub mod dialogs;
|
||||
pub mod dock;
|
||||
|
||||
@ -384,11 +384,15 @@ pub struct Layout {
|
||||
|
||||
/// Turn PhotoCraft's menus (tagged with roles) into a Mac menu bar. See the module docs.
|
||||
pub fn mac_layout(bar: &MenuBar, lang: Lang) -> Layout {
|
||||
mac_layout_for(bar, lang, APP_NAME)
|
||||
}
|
||||
|
||||
fn mac_layout_for(bar: &MenuBar, lang: Lang, app_name: &str) -> Layout {
|
||||
let mut bar = bar.clone();
|
||||
let mut clashes = Vec::new();
|
||||
let bound: HashMap<String, String> = bar.items().iter().filter_map(|it| Some((Chord::parse(it.shortcut.as_deref()?)?.portable(), it.id.clone()))).collect();
|
||||
let taken = |sc: &str, own: Option<&str>| bound.get(sc).filter(|cmd| Some(cmd.as_str()) != own).cloned();
|
||||
let named = |s: &str| crate::i18n::fmt(tr(lang, s), &[("app", APP_NAME)]);
|
||||
let named = |s: &str| crate::i18n::fmt(tr(lang, s), &[("app", app_name)]);
|
||||
|
||||
let about = take(&mut bar, |n| matches!(n, Node::Item(it) if it.role == Some(ItemRole::About)));
|
||||
let settings = take(&mut bar, |n| match n {
|
||||
@ -443,7 +447,7 @@ pub fn mac_layout(bar: &MenuBar, lang: Lang) -> Layout {
|
||||
}
|
||||
menu.push(Node::Item(quit));
|
||||
}
|
||||
bar.menus.insert(0, Menu { title: APP_NAME.into(), role: MenuRole::App, children: menu });
|
||||
bar.menus.insert(0, Menu { title: app_name.into(), role: MenuRole::App, children: menu });
|
||||
|
||||
match taken("Cmd+W", None) {
|
||||
Some(command) => clashes.push(Clash { shortcut: "Cmd+W", system: "Close Window", command, resolution: "no system Close Window item" }),
|
||||
@ -600,6 +604,10 @@ fn translate(bar: &mut MenuBar, lang: Lang) {
|
||||
/// PhotoCraft's menus as a Mac menu bar, in the UI language; `language` is the
|
||||
/// `interface.language` preference (`auto` or a code), checked in the app menu's Language.
|
||||
pub fn photocraft_layout(items: &[MenuItem], lang: Lang, language: &str) -> Layout {
|
||||
photocraft_layout_for(items, lang, language, APP_NAME)
|
||||
}
|
||||
|
||||
pub fn photocraft_layout_for(items: &[MenuItem], lang: Lang, language: &str, app_name: &str) -> Layout {
|
||||
let mut bar = from_items(&crate::menus::TOP_MENUS, items);
|
||||
bar.tag_item("help.about", ItemRole::About);
|
||||
bar.tag_item("file.exit", ItemRole::Quit);
|
||||
@ -608,7 +616,7 @@ pub fn photocraft_layout(items: &[MenuItem], lang: Lang, language: &str) -> Layo
|
||||
bar.tag_item("window.theme.toggle", ItemRole::Appearance);
|
||||
bar.tag_menu("Window", MenuRole::Window);
|
||||
bar.tag_menu("Help", MenuRole::Help);
|
||||
let mut layout = mac_layout(&bar, lang);
|
||||
let mut layout = mac_layout_for(&bar, lang, app_name);
|
||||
// Language goes right after Settings (before Appearance), as in the other Craft apps.
|
||||
if let Some(app_menu) = layout.bar.menus.iter_mut().find(|m| m.role == MenuRole::App) {
|
||||
let settings = |n: &Node| match n {
|
||||
@ -721,7 +729,7 @@ pub fn sync(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
for it in &mut items {
|
||||
it.enabled &= crate::menus::modal_allows(app, &it.id);
|
||||
}
|
||||
let layout = photocraft_layout(&items, lang, &app.session.prefs().interface.language);
|
||||
let layout = photocraft_layout_for(&items, lang, &app.session.prefs().interface.language, crate::client_brand::name(app));
|
||||
let Some(menu) = app.services.native_menu.as_mut() else { return };
|
||||
if !menu.logged {
|
||||
for c in &layout.clashes {
|
||||
|
||||
@ -43,8 +43,15 @@ pub struct Notice {
|
||||
impl Notice {
|
||||
/// `s` (the title or a line) in the current language, with [`Notice::args`] filled in.
|
||||
pub fn text(&self, s: &str) -> String {
|
||||
self.display_text(s, false)
|
||||
}
|
||||
|
||||
fn display_text(&self, s: &str, branded: bool) -> String {
|
||||
let args: Vec<(&str, &str)> = self.args.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||
crate::i18n::fmt(crate::i18n::t(s), &args)
|
||||
let template = crate::i18n::t(s);
|
||||
let client_copy = branded && (self.dismiss_pref.as_deref() == Some(WAYLAND_FILE_DROP_DISMISSED)
|
||||
|| matches!(self.title.as_str(), CLIPBOARD_UNREADABLE | "Some preferences were reset"));
|
||||
crate::i18n::fmt(&crate::client_brand::text_for(client_copy, template), &args)
|
||||
}
|
||||
}
|
||||
|
||||
@ -105,7 +112,7 @@ pub fn wayland_file_drop_guidance(app: &mut PhotocraftApp) {
|
||||
/// fall back to, so the clipboard may hold an image all the same. Say so, and give the command
|
||||
/// that starts this install under XWayland, where the X11 clipboard works, when there is one.
|
||||
pub fn clipboard_unreadable(app: &mut PhotocraftApp) {
|
||||
app.ui.status = tl!("Nothing to paste: PhotoCraft can't read the system clipboard here").into();
|
||||
app.ui.status = crate::client_brand::text(app, tl!("Nothing to paste: PhotoCraft can't read the system clipboard here"));
|
||||
app.ui.status_error = false;
|
||||
if app.ui.notices.iter().any(|notice| notice.title == CLIPBOARD_UNREADABLE) {
|
||||
return;
|
||||
@ -240,6 +247,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
let t = crate::theme::Tokens::get(ctx);
|
||||
let mut dismiss_id = None;
|
||||
let branded = crate::client_brand::active(app);
|
||||
// Clear the status bar (~24 px) and leave the dock's edge some air.
|
||||
let area = egui::Area::new(egui::Id::unique("photocraft-notices"))
|
||||
.order(egui::Order::Foreground)
|
||||
@ -257,7 +265,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(340.0);
|
||||
ui.horizontal(|ui| {
|
||||
let title = egui::RichText::new(n.text(&n.title)).strong().color(if n.error { t.warning } else { t.text });
|
||||
let title = egui::RichText::new(n.display_text(&n.title, branded)).strong().color(if n.error { t.warning } else { t.text });
|
||||
ui.add(egui::Label::new(title).wrap());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
|
||||
if ui.add(egui::Button::new(egui::RichText::new("×").color(t.text_dim)).frame(false)).on_hover_text(tl!("Dismiss")).clicked() {
|
||||
@ -267,7 +275,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
});
|
||||
let show_lines = |ui: &mut egui::Ui| {
|
||||
for line in n.lines.iter().take(if n.keep_open { usize::MAX } else { MAX_LINES }) {
|
||||
let line = n.text(line);
|
||||
let line = n.display_text(line, branded);
|
||||
ui.add(egui::Label::new(egui::RichText::new(format!("• {line}")).color(t.text_dim)).wrap());
|
||||
}
|
||||
};
|
||||
|
||||
@ -386,6 +386,7 @@ pub fn load_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Result<V
|
||||
"{n} step has no PhotoCraft equivalent yet",
|
||||
"{n} steps have no PhotoCraft equivalent yet",
|
||||
);
|
||||
let note = crate::client_brand::text(app, ¬e);
|
||||
let template = "{message} ({note})";
|
||||
crate::i18n::fmt(tl!(template), &[("message", &loaded), ("note", ¬e)])
|
||||
} else {
|
||||
@ -438,7 +439,8 @@ fn save_dialog(app: &mut PhotocraftApp, set: Option<String>) -> Result<Value, St
|
||||
"{n} step with no Photoshop equivalent left out",
|
||||
"{n} steps with no Photoshop equivalent left out",
|
||||
);
|
||||
let template = "{message} ({note})";
|
||||
let note = crate::client_brand::text(app, ¬e);
|
||||
let template = "{message} ({note})";
|
||||
crate::i18n::fmt(tl!(template), &[("message", &saved), ("note", ¬e)])
|
||||
} else {
|
||||
saved
|
||||
|
||||
@ -152,7 +152,7 @@ pub fn status_bar_pro(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
&st.doc,
|
||||
&app.ui.chrome.status_info,
|
||||
tl!(app.ui.tool.label()),
|
||||
&profile_name(&st.doc),
|
||||
&crate::client_brand::profile_label(crate::client_brand::active(app), &profile_name(&st.doc)),
|
||||
&app.session.prefs().units_and_rulers,
|
||||
);
|
||||
let mut pct = app.ui.views[i].zoom * 100.0;
|
||||
|
||||
@ -47,7 +47,7 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let title = app
|
||||
.session
|
||||
.active()
|
||||
.map(|d| format!("{}{}", if show_name { d.doc.name.as_str() } else { "PhotoCraft" }, if d.is_dirty() { " •" } else { "" }))
|
||||
.map(|d| format!("{}{}", if show_name { d.doc.name.as_str() } else { crate::client_brand::name(app) }, if d.is_dirty() { " •" } else { "" }))
|
||||
.unwrap_or_else(|| crate::client_brand::name(app).into());
|
||||
// The menus and the far-end controls are laid out first; the title is centred in
|
||||
// whatever room is left between them (`free`, left to right: menus then controls, or
|
||||
|
||||
@ -254,6 +254,7 @@ fn choose_program(app: &mut PhotocraftApp) -> Result<Value, String> {
|
||||
pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
let file_dialog_open = app.file_dialog_open();
|
||||
let can_pick = app.services.file_dialog.is_some() && !file_dialog_open;
|
||||
let branded = crate::client_brand::active(app);
|
||||
let Some(pending) = app.smart_svg.pending.as_mut() else { return };
|
||||
let mut ok = false;
|
||||
let mut cancel = false;
|
||||
@ -291,7 +292,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
continue;
|
||||
}
|
||||
let available = pending.target.extension == "svg" || choice != Editor::Internal;
|
||||
ui.add_enabled_ui(available, |ui| ui.radio_value(&mut pending.editor, choice, tr(label)));
|
||||
ui.add_enabled_ui(available, |ui| ui.radio_value(&mut pending.editor, choice, crate::client_brand::text_for(branded, tr(label))));
|
||||
}
|
||||
if pending.editor == Editor::Program {
|
||||
if let Some(program) = &pending.program {
|
||||
@ -302,11 +303,11 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.label(
|
||||
egui::RichText::new(tr(if pending.target.extension == "svg" {
|
||||
egui::RichText::new(crate::client_brand::text_for(branded, tr(if pending.target.extension == "svg" {
|
||||
"Save to the opened SVG file. Each saved change becomes one undo step in PhotoCraft."
|
||||
} else {
|
||||
"Save to the opened original-format file. Each saved change becomes one undo step in PhotoCraft."
|
||||
}))
|
||||
})))
|
||||
.small()
|
||||
.color(tokens.text_dim),
|
||||
);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user