将消息的请求和响应分离,便于维护

This commit is contained in:
xu_yanfeng 2024-12-27 19:20:22 +08:00
parent f7937a5c8b
commit 3e9d259b2c
16 changed files with 214 additions and 142 deletions

View File

@ -1,4 +1,5 @@
import { Chunk } from "../scripts/terminal"; import { Chunk } from "../scripts/terminal";
import { FrameDetails, Info, NodeInfoData, ObjectData, ObjectItemRequestData, TreeData } from "../views/devtools/data";
export enum Page { export enum Page {
None = "None", None = "None",
@ -10,21 +11,65 @@ export enum Page {
Options = "Options", Options = "Options",
} }
// #region 定义接受发送的数据声明,方便定位
export interface RequestTreeInfoData {
/**
* 使frameID
*/
frameID: number;
}
export type ResponseTreeInfoData = TreeData;
export interface RequestNodeInfoData {
/**
* UUID
*/
uuid: string;
}
export type ResponseNodeInfoData = NodeInfoData;
export interface RequestSupportData {}
export interface ResponseSupportData {
/**
*
*/
support: boolean;
/**
*
*/
msg: string;
}
export type ResponseUpdateFramesData = FrameDetails[];
export interface RequestUseFrameData {
id: number;
}
export type RequestSetPropertyData = Info;
export type ResponseSetPropertyData = Info;
export type RequestLogData = string[];
export type RequestObjectData = ObjectData;
export type ResponseObjectData = ObjectItemRequestData;
export enum Msg { export enum Msg {
None = "None", None = "None",
/** /**
* *
*/ */
NodeInfo = "node-info", RequestNodeInfo = "request-node-info",
ResponseNodeInfo = "response-node-info",
/** /**
* *
*/ */
TreeInfo = "tree-info", RequstTreeInfo = "request-tree-info",
ResponseTreeInfo = "response-tree-info",
/** /**
* *
*/ */
Support = "game-support",// RequestSupport = "request-support",
MemoryInfo = "memory-info",// ResponseSupport = "response-support",
ResponseMemoryInfo = "response-memory-info",
MemoryInfo = "memory-info",
/** /**
* *
*/ */
@ -36,18 +81,16 @@ export enum Msg {
/** /**
* frame * frame
*/ */
UpdateFrames = "UpdateFrames", ResponseUpdateFrames = "response-update-frames",
UseFrame = "UseFrame", RequestUseFrame = "request-use-frame",
GetObjectItemData = "GetObjectItemData",
LogData = "LogData", RequestObjectItemData = "request-object-item-data",
/** ResponseObjectItemData = "response-object-item-data",
* node属性
*/ RequestLogData = "request-log-data",
SetProperty = "set-property",
/** RequestSetProperty = "request-set-property",
* ResponseSetProperty = "update-property",
*/
UpdateProperty = "update-property",
} }
export class PluginEvent { export class PluginEvent {
@ -92,7 +135,7 @@ export class PluginEvent {
static create(data: any): PluginEvent { static create(data: any): PluginEvent {
let obj = data; let obj = data;
if (typeof data === "string") { if (typeof data === "string") {
obj = JSON.stringify(data) obj = JSON.stringify(data);
} else if (typeof data === "object") { } else if (typeof data === "object") {
obj = data; obj = data;
} else { } else {
@ -130,14 +173,7 @@ export class PluginEvent {
event.source = event.target = null; event.source = event.target = null;
} }
toChunk(): Chunk[] { toChunk(): Chunk[] {
return [ return [new Chunk(new Date().toLocaleString()).color("white").background("black").padding("0 4px"), new Chunk(this.source).color("white").background("red").padding("0 4px").margin("0 0 0 5px"), new Chunk("=>").color("black").background("yellow").bold(), new Chunk(this.target, false).color("white").background("green").padding("0 4px"), new Chunk(this.msg, true).color("white").background("black").margin("0 0 0 5px").padding("0 6px"), new Chunk(JSON.stringify(this.data))];
new Chunk(new Date().toLocaleString()).color("white").background("black").padding('0 4px'),
new Chunk(this.source).color('white').background("red").padding('0 4px').margin('0 0 0 5px'),
new Chunk('=>').color('black').background("yellow").bold(),
new Chunk(this.target, false).color("white").background("green").padding('0 4px'),
new Chunk(this.msg, true).color("white").background("black").margin('0 0 0 5px').padding("0 6px"),
new Chunk(JSON.stringify(this.data))
];
} }
constructor(source: Page, target: Page, msg: Msg, data?: any) { constructor(source: Page, target: Page, msg: Msg, data?: any) {
if (PageInclude(target)) { if (PageInclude(target)) {
@ -146,7 +182,7 @@ export class PluginEvent {
this.msg = msg; this.msg = msg;
this.data = data; this.data = data;
} else { } else {
console.warn(`无效的target: ${target}`) console.warn(`无效的target: ${target}`);
} }
} }
} }
@ -157,7 +193,7 @@ function inEnum(enumValues: any, value: Page | Msg) {
//@ts-ignore //@ts-ignore
let itemEnum = enumValues[key] as string; let itemEnum = enumValues[key] as string;
if (itemEnum === value) { if (itemEnum === value) {
return true return true;
} }
} }
} }
@ -168,7 +204,6 @@ export function PageInclude(page: Page) {
return inEnum(Page, page); return inEnum(Page, page);
} }
export function MsgInclude(msg: Msg) { export function MsgInclude(msg: Msg) {
return inEnum(Msg, msg) return inEnum(Msg, msg);
} }

View File

@ -1 +1 @@
export const title = 'my first plugin' export const title = "CCInspector";

View File

@ -1 +1 @@
export const title = '我的第一个插件' export const title = "CCInspector";

View File

@ -1,5 +1,5 @@
import { ChromeConst } from "cc-plugin/src/chrome/const"; import { ChromeConst } from "cc-plugin/src/chrome/const";
import { Msg, Page, PluginEvent } from "../../core/types"; import { Msg, Page, PluginEvent, RequestSupportData } from "../../core/types";
import { Terminal } from "../terminal"; import { Terminal } from "../terminal";
import { PortMan } from "./portMan"; import { PortMan } from "./portMan";
import { portMgr } from "./portMgr"; import { portMgr } from "./portMgr";
@ -15,12 +15,7 @@ function onTabConnect(tab: chrome.tabs.Tab, port: chrome.runtime.Port) {
debugger; debugger;
return; return;
} }
let portMan = portMgr.findPort(tab.id); const portMan = portMgr.addPort(tab, port);
if (portMan) {
// 一个port发起多次发起链接以最后一次的为数据通讯基准
// portMgr.removePort(portMan);
}
portMan = portMgr.addPort(tab, port);
portMan.init(); portMan.init();
} }
chrome.runtime.onConnect.addListener((port: chrome.runtime.Port) => { chrome.runtime.onConnect.addListener((port: chrome.runtime.Port) => {
@ -60,7 +55,7 @@ chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (id && id > -1) { if (id && id > -1) {
let portMan = portMgr.findPort(id); let portMan = portMgr.findPort(id);
if (portMan) { if (portMan) {
let data = new PluginEvent(Page.Background, Page.Content, Msg.Support); const data = new PluginEvent(Page.Background, Page.Content, Msg.RequestSupport, {} as RequestSupportData);
portMgr.sendContentMsg(data); portMgr.sendContentMsg(data);
} }
} }

View File

@ -1,11 +1,28 @@
import { PluginEvent } from "../../core/types"; import { PluginEvent } from "../../core/types";
import { FrameDetails } from "../../views/devtools/data";
import { PortMan } from "./portMan"; import { PortMan } from "./portMan";
import { portMgr } from "./portMgr"; import { portMgr } from "./portMgr";
export class PortContent extends PortMan { export class PortContent extends PortMan {
protected frameID: number = 0;
constructor(tab: chrome.tabs.Tab, port: chrome.runtime.Port) {
super(tab, port);
this.frameID = port.sender.frameId || 0;
}
getFrameDetais(): FrameDetails {
return {
url: this.url,
frameID: this.frameID,
};
}
init(): void { init(): void {
// content连上来要同时devtools更新 // 使用新连上来的content
portMgr._updateFrames(); const { frameId } = this.port.sender;
if (frameId !== undefined) {
portMgr.useFrame(frameId);
}
// 新的content连上来需要更新devtools
portMgr.updateFrames();
this.onDisconnect = (disPort: chrome.runtime.Port) => { this.onDisconnect = (disPort: chrome.runtime.Port) => {
/** /**
* const index = this.content.findIndex((el) => * const index = this.content.findIndex((el) =>
@ -16,7 +33,7 @@ export class PortContent extends PortMan {
*/ */
// content失去链接需要更新Devtools // content失去链接需要更新Devtools
portMgr.removePort(this); portMgr.removePort(this);
portMgr._updateFrames(); portMgr.updateFrames();
}; };
this.onMessage = (data: PluginEvent) => { this.onMessage = (data: PluginEvent) => {
// content的数据一般都是要同步到devtools // content的数据一般都是要同步到devtools

View File

@ -1,32 +1,36 @@
import { Msg, Page, PluginEvent } from "../../core/types"; import { Msg, Page, PluginEvent, RequestTreeInfoData, RequestUseFrameData } from "../../core/types";
import { PortMan } from "./portMan"; import { PortMan } from "./portMan";
import { portMgr } from "./portMgr"; import { portMgr } from "./portMgr";
export class PortDevtools extends PortMan { export class PortDevtools extends PortMan {
init(): void { init(): void {
// 当devtools链接后主动同步frames数据 // 当devtools链接后主动同步frames数据
portMgr._updateFrames(); portMgr.updateFrames();
this.onDisconnect = () => { this.onDisconnect = () => {
portMgr.removePort(this); portMgr.removePort(this);
}; };
this.onMessage = (data: PluginEvent) => { this.onMessage = (data: PluginEvent) => {
if (data.msg === Msg.UseFrame) { if (data.msg === Msg.RequestUseFrame) {
portMgr.useFrame(data.data); portMgr.useFrame((data.data as RequestUseFrameData).id);
} else { } else {
// 从devtools过来的消息统一派发到Content中 // 从devtools过来的消息统一派发到Content中
if (data.check(Page.Devtools, Page.Background)) { if (data.check(Page.Devtools, Page.Background)) {
if (data.msg === Msg.TreeInfo) { if (data.msg === Msg.RequstTreeInfo) {
if (portMgr.isCurrentFrme(data.data)) { const d = data.data as RequestTreeInfoData;
if (!portMgr.isCurrentFrme(d.frameID)) {
console.log(`frameID[${data.data}]不一致`); console.log(`frameID[${data.data}]不一致`);
debugger;
} }
} }
data.reset(Page.Background, Page.Content); data.reset(Page.Background, Page.Content);
const port = portMgr.getCurrentUseContent(); const port = portMgr.getCurrentUsePort();
if (!port) { if (!port) {
console.warn(`not find andy port`); console.warn(`not find andy port`);
return; return;
} }
port.postMessage(data); port.send(data);
} else {
debugger;
} }
} }
}; };

View File

@ -12,7 +12,7 @@ export abstract class PortMan {
public id: number | null = null; public id: number | null = null;
public title: string = ""; public title: string = "";
public url: string = ""; public url: string = "";
public port: chrome.runtime.Port | null = null; protected port: chrome.runtime.Port | null = null;
public tab: chrome.tabs.Tab | null = null; public tab: chrome.tabs.Tab | null = null;
public onDisconnect: (port: chrome.runtime.Port) => void | null = null; public onDisconnect: (port: chrome.runtime.Port) => void | null = null;
public onMessage: (data: PluginEvent) => void | null = null; public onMessage: (data: PluginEvent) => void | null = null;
@ -24,14 +24,12 @@ export abstract class PortMan {
this.tab = tab; this.tab = tab;
this.name = port.name; this.name = port.name;
this.id = tab.id; this.id = tab.id;
this.url = tab.url; this.url = port.sender.url;
this.title = tab.title; this.title = tab.title;
this.terminal = new Terminal(`Port-${this.name}`); this.terminal = new Terminal(`Port-${this.name}`);
port.onMessage.addListener((data: any, port: chrome.runtime.Port) => { port.onMessage.addListener((data: any, port: chrome.runtime.Port) => {
const event = PluginEvent.create(data); const event = PluginEvent.create(data);
console.log(...this.terminal.chunkMessage(event.toChunk())); console.log(...this.terminal.chunkMessage(event.toChunk()));
// 如果多个页面都监听 onMessage 事件,对于某一次事件只有第一次调用 sendResponse() 能成功发出回应,所有其他回应将被忽略。
// port.postMessage(data);
if (event.valid && this.onMessage) { if (event.valid && this.onMessage) {
this.onMessage(event); this.onMessage(event);
} else { } else {
@ -47,10 +45,27 @@ export abstract class PortMan {
} }
abstract init(): void; abstract init(): void;
isConnectPort() { isContent() {
return this.name === Page.Content; return this.name === Page.Content;
} }
isDevtoolsPort() { isDevtools() {
return this.name === Page.Devtools; return this.name === Page.Devtools;
} }
isUseing(id: number) {
if (!this.port) {
return false;
}
if (!this.port.sender) {
return false;
}
if (this.port.sender.frameId === undefined) {
return false;
}
return this.port.sender.frameId === id;
}
send(data: PluginEvent) {
if (this.port) {
this.port.postMessage(data);
}
}
} }

View File

@ -1,5 +1,5 @@
import { FrameDetails } from "views/devtools/data"; import { Msg, Page, PluginEvent, RequestSupportData, ResponseUpdateFramesData } from "../../core/types";
import { Msg, Page, PluginEvent } from "../../core/types"; import { FrameDetails } from "../../views/devtools/data";
import { Terminal } from "../terminal"; import { Terminal } from "../terminal";
import { PortContent } from "./portContent"; import { PortContent } from "./portContent";
import { PortDevtools } from "./portDevtools"; import { PortDevtools } from "./portDevtools";
@ -22,18 +22,19 @@ export class PortMgr {
public findPort(id: number): PortMan | null { public findPort(id: number): PortMan | null {
return this.portArray.find((el) => el.id === id) || null; return this.portArray.find((el) => el.id === id) || null;
} }
public _updateFrames() { /**
* devtools更新
*/
public updateFrames() {
// 将content类型的port收集起来同步到devtools // 将content类型的port收集起来同步到devtools
const data: FrameDetails[] = []; const data: FrameDetails[] = [];
this.portArray.forEach((item) => { this.portArray.forEach((item) => {
if (item.isConnectPort()) { if (item.isContent()) {
data.push({ const frame = (item as PortContent).getFrameDetais();
url: item.port.sender?.url || "", data.push(frame);
frameID: item.port.sender?.frameId || 0,
});
} }
}); });
const event = new PluginEvent(Page.Background, Page.Devtools, Msg.UpdateFrames, data); const event = new PluginEvent(Page.Background, Page.Devtools, Msg.ResponseUpdateFrames, data as ResponseUpdateFramesData);
this.sendDevtoolMsg(event); this.sendDevtoolMsg(event);
} }
@ -89,38 +90,34 @@ export class PortMgr {
} }
sendContentMsg(data: PluginEvent) { sendContentMsg(data: PluginEvent) {
this.getCurrentUseContent()?.postMessage(data); this.getCurrentUsePort()?.send(data);
} }
sendDevtoolMsg(data: PluginEvent) { sendDevtoolMsg(data: PluginEvent) {
const portManArray = this.portArray.filter((el) => el.isDevtoolsPort()); const portManArray = this.portArray.filter((el) => el.isDevtools());
if (portManArray.length) { if (portManArray.length) {
portManArray.forEach((portMan) => { portManArray.forEach((portMan) => {
portMan.port.postMessage(data); portMan.send(data);
}); });
} else { } else {
console.log("not find devtools port"); console.log("not find devtools port");
} }
} }
getCurrentUseContent(): chrome.runtime.Port | null { getCurrentUsePort(): PortMan | null {
const portMan = this.portArray.find((portMan: PortMan) => { const portMan = this.portArray.find((portMan: PortMan) => {
const el = portMan.port; return portMan.isContent() && portMan.isUseing(this.currentUseContentFrameID);
const b1 = el.sender?.frameId !== undefined;
const b2 = el.sender.frameId === this.currentUseContentFrameID;
return b1 && b2;
}); });
if (portMan) { return portMan || null;
return portMan.port;
} else {
return null;
}
} }
useFrame(id: number) { useFrame(id: number) {
this.currentUseContentFrameID = id; this.currentUseContentFrameID = id;
// 更新这个frame的tree // 更新这个frame的tree
const sendData = new PluginEvent(Page.Background, Page.Content, Msg.Support); const sendData = new PluginEvent(Page.Background, Page.Content, Msg.RequestSupport, {} as RequestSupportData);
this.getCurrentUseContent()?.postMessage(sendData); this.getCurrentUsePort()?.send(sendData);
} }
isCurrentFrme(id: number) { isCurrentFrme(id: number) {
if (typeof id !== "number") {
throw new Error("id must be number");
}
return this.currentUseContentFrameID === id; return this.currentUseContentFrameID === id;
} }
} }

View File

@ -1,7 +1,7 @@
// content.js 和原始界面共享DOM具有操作dom的能力 // content.js 和原始界面共享DOM具有操作dom的能力
// 但是不共享js,要想访问页面js,只能通过注入的方式 // 但是不共享js,要想访问页面js,只能通过注入的方式
import { ChromeConst } from "cc-plugin/src/chrome/const"; import { ChromeConst } from "cc-plugin/src/chrome/const";
import { Msg, Page, PluginEvent } from "../../core/types"; import { Msg, Page, PluginEvent, ResponseSupportData } from "../../core/types";
import { DocumentEvent } from "../const"; import { DocumentEvent } from "../const";
import { Terminal } from "../terminal"; import { Terminal } from "../terminal";
@ -63,10 +63,10 @@ connect.onMessage.addListener((data: PluginEvent, sender: chrome.runtime.Port) =
function checkGame() { function checkGame() {
let gameCanvas = document.querySelector("#GameCanvas"); let gameCanvas = document.querySelector("#GameCanvas");
const sendData = new PluginEvent(Page.Content, Page.Devtools, Msg.Support, { const sendData = new PluginEvent(Page.Content, Page.Devtools, Msg.ResponseSupport, {
support: !!gameCanvas, support: !!gameCanvas,
msg: "未发现GameCanvas,不支持调试游戏!", msg: "未发现GameCanvas,不支持调试游戏!",
}); } as ResponseSupportData);
if (connect) { if (connect) {
connect.postMessage(sendData); connect.postMessage(sendData);
} else { } else {
@ -76,4 +76,4 @@ function checkGame() {
} }
injectScript(ChromeConst.script.inject); injectScript(ChromeConst.script.inject);
checkGame(); // checkGame();

View File

@ -1,6 +1,6 @@
// eval 注入脚本的代码,变量尽量使用var,后来发现在import之后,let会自动变为var // eval 注入脚本的代码,变量尽量使用var,后来发现在import之后,let会自动变为var
import { uniq } from "lodash"; import { uniq } from "lodash";
import { Msg, PluginEvent } from "../../core/types"; import { Msg, PluginEvent, RequestNodeInfoData, RequestLogData, RequestObjectData, RequestSetPropertyData, ResponseNodeInfoData, ResponseObjectData, ResponseSetPropertyData, ResponseSupportData, ResponseTreeInfoData } from "../../core/types";
import { ArrayData, BoolData, ColorData, DataType, EngineData, Group, ImageData, Info, InvalidData, NodeInfoData, NumberData, ObjectData, ObjectItemRequestData, Property, StringData, TreeData, Vec2Data, Vec3Data } from "../../views/devtools/data"; import { ArrayData, BoolData, ColorData, DataType, EngineData, Group, ImageData, Info, InvalidData, NodeInfoData, NumberData, ObjectData, ObjectItemRequestData, Property, StringData, TreeData, Vec2Data, Vec3Data } from "../../views/devtools/data";
import { InjectEvent } from "./event"; import { InjectEvent } from "./event";
import { getValue, trySetValueWithConfig } from "./setValue"; import { getValue, trySetValueWithConfig } from "./setValue";
@ -25,22 +25,22 @@ export class Inspector extends InjectEvent {
} }
onMessage(pluginEvent: PluginEvent): void { onMessage(pluginEvent: PluginEvent): void {
switch (pluginEvent.msg) { switch (pluginEvent.msg) {
case Msg.Support: { case Msg.RequestSupport: {
let isCocosGame = this._isCocosGame(); const isCocosGame = this._isCocosGame();
this.notifySupportGame(isCocosGame); this.notifySupportGame(isCocosGame);
break; break;
} }
case Msg.TreeInfo: { case Msg.RequstTreeInfo: {
this.updateTreeInfo(); this.updateTreeInfo();
break; break;
} }
case Msg.NodeInfo: { case Msg.RequestNodeInfo: {
let nodeUUID = pluginEvent.data; const data = pluginEvent.data as RequestNodeInfoData;
this.getNodeInfo(nodeUUID); this.getNodeInfo(data.uuid);
break; break;
} }
case Msg.SetProperty: { case Msg.RequestSetProperty: {
const data: Info = pluginEvent.data; const data: RequestSetPropertyData = pluginEvent.data;
let value = data.data; let value = data.data;
if (data.type === DataType.Color) { if (data.type === DataType.Color) {
// @ts-ignore // @ts-ignore
@ -48,22 +48,22 @@ export class Inspector extends InjectEvent {
} }
if (this.setValue(data.path, value)) { if (this.setValue(data.path, value)) {
this.sendMsgToContent(Msg.UpdateProperty, data); this.sendMsgToContent(Msg.ResponseSetProperty, data as ResponseSetPropertyData);
} else { } else {
console.warn(`设置失败:${data.path}`); console.warn(`设置失败:${data.path}`);
} }
break; break;
} }
case Msg.LogData: { case Msg.RequestLogData: {
const data: string[] = pluginEvent.data; const data: RequestLogData = pluginEvent.data;
const value = getValue(this.inspectorGameMemoryStorage, data); const value = getValue(this.inspectorGameMemoryStorage, data);
// 直接写console.log会被tree shaking // 直接写console.log会被tree shaking
const logFunction = console.log; const logFunction = console.log;
logFunction(value); logFunction(value);
break; break;
} }
case Msg.GetObjectItemData: { case Msg.RequestObjectItemData: {
const data: ObjectData = pluginEvent.data; const data: RequestObjectData = pluginEvent.data;
let val = getValue(this.inspectorGameMemoryStorage, data.path); let val = getValue(this.inspectorGameMemoryStorage, data.path);
if (val) { if (val) {
let itemData: Property[] = this._buildObjectItemData({ let itemData: Property[] = this._buildObjectItemData({
@ -76,7 +76,7 @@ export class Inspector extends InjectEvent {
id: data.id, id: data.id,
data: itemData, data: itemData,
}; };
this.sendMsgToContent(Msg.GetObjectItemData, result); this.sendMsgToContent(Msg.ResponseObjectItemData, result as ResponseObjectData);
} }
break; break;
} }
@ -88,7 +88,7 @@ export class Inspector extends InjectEvent {
} }
notifySupportGame(b: boolean) { notifySupportGame(b: boolean) {
this.sendMsgToContent(Msg.Support, b); this.sendMsgToContent(Msg.ResponseSupport, { support: b, msg: "" } as ResponseSupportData);
} }
updateTreeInfo() { updateTreeInfo() {
@ -99,7 +99,7 @@ export class Inspector extends InjectEvent {
if (scene) { if (scene) {
let treeData = new TreeData(); let treeData = new TreeData();
this.getNodeChildren(scene, treeData); this.getNodeChildren(scene, treeData);
this.sendMsgToContent(Msg.TreeInfo, treeData); this.sendMsgToContent(Msg.ResponseTreeInfo, treeData as ResponseTreeInfoData);
} else { } else {
console.warn("can't execute api : cc.director.getScene"); console.warn("can't execute api : cc.director.getScene");
this.notifySupportGame(false); this.notifySupportGame(false);
@ -588,7 +588,7 @@ export class Inspector extends InjectEvent {
groupData.push(compGroup); groupData.push(compGroup);
} }
const data: NodeInfoData = new NodeInfoData(uuid, groupData); const data: NodeInfoData = new NodeInfoData(uuid, groupData);
this.sendMsgToContent(Msg.NodeInfo, data); this.sendMsgToContent(Msg.ResponseNodeInfo, data as ResponseNodeInfoData);
} else { } else {
// 未获取到节点数据 // 未获取到节点数据
console.log("未获取到节点数据"); console.log("未获取到节点数据");

View File

@ -105,7 +105,13 @@ export interface ObjectItemRequestData {
} }
export interface FrameDetails { export interface FrameDetails {
/**
* frameID
*/
frameID: number; frameID: number;
/**
* url
*/
url: string; url: string;
} }

View File

@ -45,10 +45,10 @@ import { Option } from "@xuyanfeng/cc-ui/types/cc-select/const";
import { storeToRefs } from "pinia"; import { storeToRefs } from "pinia";
import { defineComponent, nextTick, onMounted, reactive, ref, toRaw, watch } from "vue"; import { defineComponent, nextTick, onMounted, reactive, ref, toRaw, watch } from "vue";
import PluginConfig from "../../../cc-plugin.config"; import PluginConfig from "../../../cc-plugin.config";
import { Msg, PluginEvent } from "../../core/types"; import { Msg, PluginEvent, RequestNodeInfoData, RequestSupportData, RequestTreeInfoData, RequestLogData, RequestObjectData, RequestUseFrameData, ResponseObjectData, ResponseSetPropertyData, ResponseSupportData } from "../../core/types";
import { bridge } from "./bridge"; import { bridge } from "./bridge";
import Bus, { BusMsg } from "./bus"; import Bus, { BusMsg } from "./bus";
import { EngineData, FrameDetails, Info, NodeInfoData, ObjectData, ObjectItemRequestData, TreeData } from "./data"; import { EngineData, FrameDetails, NodeInfoData, ObjectData, TreeData } from "./data";
import { appStore, RefreshType } from "./store"; import { appStore, RefreshType } from "./store";
import Test from "./test/test.vue"; import Test from "./test/test.vue";
import Properties from "./ui/propertys.vue"; import Properties from "./ui/propertys.vue";
@ -174,7 +174,7 @@ export default defineComponent({
const elTree = ref<typeof CCTree>(); const elTree = ref<typeof CCTree>();
function _initChromeRuntimeConnect() { function _initChromeRuntimeConnect() {
const msgFunctionMap: Record<string, Function> = {}; const msgFunctionMap: Record<string, Function> = {};
msgFunctionMap[Msg.TreeInfo] = (data: Array<TreeData>) => { msgFunctionMap[Msg.ResponseTreeInfo] = (data: Array<TreeData>) => {
isShowDebug.value = true; isShowDebug.value = true;
if (!Array.isArray(data)) { if (!Array.isArray(data)) {
data = [data]; data = [data];
@ -189,7 +189,9 @@ export default defineComponent({
}); });
} }
}; };
msgFunctionMap[Msg.Support] = (isCocosGame: boolean) => { msgFunctionMap[Msg.ResponseSupport] = (data: ResponseSupportData) => {
debugger;
const isCocosGame: boolean = data.support;
isShowDebug.value = isCocosGame; isShowDebug.value = isCocosGame;
if (isCocosGame) { if (isCocosGame) {
syncSettings(); syncSettings();
@ -201,9 +203,10 @@ export default defineComponent({
selectedUUID = null; selectedUUID = null;
} }
}; };
msgFunctionMap[Msg.NodeInfo] = (eventData: NodeInfoData) => { msgFunctionMap[Msg.ResponseNodeInfo] = (eventData: NodeInfoData) => {
isShowDebug.value = true; isShowDebug.value = true;
try { try {
// class
const nodeInfo = new NodeInfoData(eventData.uuid, eventData.group).parse(eventData); const nodeInfo = new NodeInfoData(eventData.uuid, eventData.group).parse(eventData);
treeItemData.value = nodeInfo; treeItemData.value = nodeInfo;
} catch (error) { } catch (error) {
@ -214,7 +217,7 @@ export default defineComponent({
msgFunctionMap[Msg.MemoryInfo] = (eventData: any) => { msgFunctionMap[Msg.MemoryInfo] = (eventData: any) => {
memory.value = eventData; memory.value = eventData;
}; };
msgFunctionMap[Msg.UpdateProperty] = (data: Info) => { msgFunctionMap[Msg.ResponseSetProperty] = (data: ResponseSetPropertyData) => {
const uuid = data.path[0]; const uuid = data.path[0];
const key = data.path[1]; const key = data.path[1];
const value = data.data; const value = data.data;
@ -239,7 +242,7 @@ export default defineComponent({
} }
} }
}; };
msgFunctionMap[Msg.UpdateFrames] = (details: FrameDetails[]) => { msgFunctionMap[Msg.ResponseUpdateFrames] = (details: FrameDetails[]) => {
// iframes // iframes
iframes.value = iframes.value.filter((item) => { iframes.value = iframes.value.filter((item) => {
details.find((el) => el.frameID === item.value); details.find((el) => el.frameID === item.value);
@ -263,7 +266,7 @@ export default defineComponent({
onChangeFrame(); onChangeFrame();
} }
}; };
msgFunctionMap[Msg.GetObjectItemData] = (requestData: ObjectItemRequestData) => { msgFunctionMap[Msg.ResponseObjectItemData] = (requestData: ResponseObjectData) => {
if (requestData.id !== null) { if (requestData.id !== null) {
let findIndex = requestList.findIndex((el) => el.id === requestData.id); let findIndex = requestList.findIndex((el) => el.id === requestData.id);
if (findIndex > -1) { if (findIndex > -1) {
@ -277,7 +280,6 @@ export default defineComponent({
if (!data) { if (!data) {
return; return;
} }
debugger;
if (data.isTargetDevtools()) { if (data.isTargetDevtools()) {
PluginEvent.finish(data); PluginEvent.finish(data);
const { msg } = data; const { msg } = data;
@ -303,7 +305,7 @@ export default defineComponent({
false false
); );
Bus.on(BusMsg.ShowPlace, (data: EngineData) => { Bus.on(BusMsg.ShowPlace, (data: EngineData) => {
console.log(data); console.log(toRaw(data));
_expand(data.engineUUID); _expand(data.engineUUID);
}); });
Bus.on(BusMsg.RequestObjectData, (data: ObjectData, cb: Function) => { Bus.on(BusMsg.RequestObjectData, (data: ObjectData, cb: Function) => {
@ -311,13 +313,13 @@ export default defineComponent({
return; return;
} }
requestList.push({ id: data.id, cb }); requestList.push({ id: data.id, cb });
bridge.send(Msg.GetObjectItemData, data); bridge.send(Msg.RequestObjectItemData, data as RequestObjectData);
}); });
Bus.on(BusMsg.UpdateSettings, () => { Bus.on(BusMsg.UpdateSettings, () => {
syncSettings(); syncSettings();
}); });
Bus.on(BusMsg.LogData, (data: string[]) => { Bus.on(BusMsg.LogData, (data: string[]) => {
bridge.send(Msg.LogData, data); bridge.send(Msg.RequestLogData, data as RequestLogData);
}); });
onMounted(() => { onMounted(() => {
syncSettings(); syncSettings();
@ -382,7 +384,7 @@ export default defineComponent({
} }
function updateNodeInfo() { function updateNodeInfo() {
if (selectedUUID) { if (selectedUUID) {
bridge.send(Msg.NodeInfo, selectedUUID); bridge.send(Msg.RequestNodeInfo, { uuid: selectedUUID } as RequestNodeInfoData);
} }
} }
let selectedUUID: string | null = null; let selectedUUID: string | null = null;
@ -391,11 +393,11 @@ export default defineComponent({
} }
function onBtnClickUpdateTree() { function onBtnClickUpdateTree() {
const id = toRaw(frameID.value); const id = toRaw(frameID.value);
bridge.send(Msg.TreeInfo, id); bridge.send(Msg.RequstTreeInfo, { frameID: id } as RequestTreeInfoData);
} }
function onChangeFrame() { function onChangeFrame() {
const id = Number(toRaw(frameID.value)); const id = Number(toRaw(frameID.value));
bridge.send(Msg.UseFrame, id); bridge.send(Msg.RequestUseFrame, { id } as RequestUseFrameData);
} }
const elLeft = ref<HTMLDivElement>(); const elLeft = ref<HTMLDivElement>();
const version = ref(PluginConfig.manifest.version); const version = ref(PluginConfig.manifest.version);
@ -454,7 +456,7 @@ export default defineComponent({
}, },
onBtnClickUpdatePage() { onBtnClickUpdatePage() {
bridge.send(Msg.Support); bridge.send(Msg.RequestSupport, {} as RequestSupportData);
}, },
onMemoryTest() { onMemoryTest() {
bridge.send(Msg.MemoryInfo); bridge.send(Msg.MemoryInfo);

View File

@ -1,5 +1,7 @@
import CCP from "cc-plugin/src/ccp/entry-render"; import CCP from "cc-plugin/src/ccp/entry-render";
import { ChromeConst } from "cc-plugin/src/chrome/const"; import { ChromeConst } from "cc-plugin/src/chrome/const";
import { Msg, RequestSupportData } from "../../core/types";
import { bridge } from "./bridge";
export function init() { export function init() {
if (chrome && chrome.devtools) { if (chrome && chrome.devtools) {
// 对应的是Elements面板的边栏 // 对应的是Elements面板的边栏
@ -17,8 +19,7 @@ export function init() {
console.log("[CC-Inspector] Dev Panel Created!"); console.log("[CC-Inspector] Dev Panel Created!");
panel.onShown.addListener((window) => { panel.onShown.addListener((window) => {
// 面板显示查询是否是cocos游戏 // 面板显示查询是否是cocos游戏
console.log("panel show"); bridge.send(Msg.RequestSupport, {} as RequestSupportData);
// bridge.sendToBackground(Msg.Support, null)
}); });
panel.onHidden.addListener(() => { panel.onHidden.addListener(() => {
// 面板隐藏 // 面板隐藏

View File

@ -1,5 +1,5 @@
import { v4 } from "uuid"; import { v4 } from "uuid";
import { Msg, Page, PluginEvent } from "../../../core/types"; import { Msg, Page, PluginEvent, RequestNodeInfoData, RequestObjectData, ResponseNodeInfoData, ResponseObjectData, ResponseTreeInfoData } from "../../../core/types";
import { ArrayData, BoolData, ColorData, EngineData, EnumData, Group, ImageData, Info, InvalidData, NodeInfoData, NumberData, ObjectData, ObjectItemRequestData, Property, StringData, TextData, TreeData, Vec2Data, Vec3Data, Vec4Data } from "../data"; import { ArrayData, BoolData, ColorData, EngineData, EnumData, Group, ImageData, Info, InvalidData, NodeInfoData, NumberData, ObjectData, ObjectItemRequestData, Property, StringData, TextData, TreeData, Vec2Data, Vec3Data, Vec4Data } from "../data";
export class TestClient { export class TestClient {
recv(event: PluginEvent) {} recv(event: PluginEvent) {}
@ -100,8 +100,8 @@ export class TestServer {
} }
recv(msg: string, data: any) { recv(msg: string, data: any) {
switch (msg) { switch (msg) {
case Msg.NodeInfo: { case Msg.RequestNodeInfo: {
const id: string = data as string; const id: string = (data as RequestNodeInfoData).uuid;
const node: Node = this.testData.findNode(id); const node: Node = this.testData.findNode(id);
let group = []; let group = [];
if (node) { if (node) {
@ -111,37 +111,37 @@ export class TestServer {
group.push(g); group.push(g);
} }
const ret: NodeInfoData = new NodeInfoData(id, group); const ret: NodeInfoData = new NodeInfoData(id, group);
const event = new PluginEvent(Page.Background, Page.Devtools, Msg.NodeInfo, ret); const event = new PluginEvent(Page.Background, Page.Devtools, Msg.ResponseNodeInfo, ret as ResponseNodeInfoData);
this.send(event); this.send(event);
break; break;
} }
case Msg.TreeInfo: { case Msg.RequstTreeInfo: {
const ret: TreeData = new TreeData(); const ret: TreeData = new TreeData();
this.testData.toTreeData(ret); this.testData.toTreeData(ret);
const event = new PluginEvent(Page.Inject, Page.Devtools, Msg.TreeInfo, ret); const event = new PluginEvent(Page.Inject, Page.Devtools, Msg.ResponseTreeInfo, ret as ResponseTreeInfoData);
this.send(event); this.send(event);
break; break;
} }
case Msg.SetProperty: { case Msg.RequestSetProperty: {
console.log(data); console.log(data);
break; break;
} }
case Msg.GetObjectItemData: { case Msg.RequestObjectItemData: {
const objData = data as ObjectData; const objData: RequestObjectData = data as ObjectData;
const info = this.testData.findInfo(objData.id); const info = this.testData.findInfo(objData.id);
if (info && info instanceof ObjectData) { if (info && info instanceof ObjectData) {
const ret: ObjectItemRequestData = { const ret: ObjectItemRequestData = {
id: objData.id, id: objData.id,
data: info.testProperty(), data: info.testProperty(),
}; };
const event = new PluginEvent(Page.Inject, Page.Devtools, Msg.GetObjectItemData, ret); const event = new PluginEvent(Page.Inject, Page.Devtools, Msg.ResponseObjectItemData, ret as ResponseObjectData);
this.send(event); this.send(event);
} else { } else {
console.warn("not found data: ", objData.id); console.warn("not found data: ", objData.id);
} }
break; break;
} }
case Msg.LogData: { case Msg.RequestLogData: {
console.log(data); console.log(data);
break; break;
} }

View File

@ -15,7 +15,7 @@
import ccui from "@xuyanfeng/cc-ui"; import ccui from "@xuyanfeng/cc-ui";
import { storeToRefs } from "pinia"; import { storeToRefs } from "pinia";
import { defineComponent, ref } from "vue"; import { defineComponent, ref } from "vue";
import { Msg, Page, PluginEvent } from "../../../core/types"; import { Msg, Page, PluginEvent, ResponseUpdateFramesData } from "../../../core/types";
import { Terminal } from "../../../scripts/terminal"; import { Terminal } from "../../../scripts/terminal";
import { bridge } from "../bridge"; import { bridge } from "../bridge";
import { FrameDetails, Group, InvalidData, NodeInfoData, TreeData } from "../data"; import { FrameDetails, Group, InvalidData, NodeInfoData, TreeData } from "../data";
@ -31,7 +31,8 @@ export default defineComponent({
}, },
setup(props, { emit }) { setup(props, { emit }) {
const { config } = storeToRefs(appStore()); const { config } = storeToRefs(appStore());
const show = ref(__DEV__); // web
const show = ref(__DEV__ && !(chrome && chrome.runtime));
// //
const testData = { const testData = {
uuid: "d1NHXHs35F1rbFJZKeigkl", uuid: "d1NHXHs35F1rbFJZKeigkl",
@ -74,7 +75,7 @@ export default defineComponent({
}, },
onTerminal() { onTerminal() {
const t = new Terminal("flag"); const t = new Terminal("flag");
const event = new PluginEvent(Page.Background, Page.Background, Msg.NodeInfo, ""); const event = new PluginEvent(Page.Background, Page.Background, Msg.ResponseTreeInfo, "");
console.log(...t.message("1")); console.log(...t.message("1"));
console.log(...t.log("newline", true)); console.log(...t.log("newline", true));
console.log(...t.log("oneline", false)); console.log(...t.log("oneline", false));
@ -92,7 +93,7 @@ export default defineComponent({
active: true, active: true,
children: [], children: [],
}; };
const event = new PluginEvent(Page.Inject, Page.Devtools, Msg.TreeInfo, data); const event = new PluginEvent(Page.Inject, Page.Devtools, Msg.ResponseTreeInfo, data);
bridge.doMessage(event); bridge.doMessage(event);
}, },
onFrames() { onFrames() {
@ -100,16 +101,16 @@ export default defineComponent({
{ url: "url1", frameID: 1 }, { url: "url1", frameID: 1 },
{ url: "url2", frameID: 2 }, { url: "url2", frameID: 2 },
]; ];
const event = new PluginEvent(Page.Background, Page.Devtools, Msg.UpdateFrames, data); const event = new PluginEvent(Page.Background, Page.Devtools, Msg.ResponseUpdateFrames, data as ResponseUpdateFramesData);
testServer.send(event); testServer.send(event);
}, },
onTestNodeInfo() { onTestNodeInfo() {
const event = new PluginEvent(Page.Background, Page.Devtools, Msg.NodeInfo, testData); const event = new PluginEvent(Page.Background, Page.Devtools, Msg.ResponseTreeInfo, testData);
testServer.send(event); testServer.send(event);
}, },
onNull() { onNull() {
const data = new NodeInfoData("", [new Group("", "1").buildProperty("dependAssets", new InvalidData("Null"))]); const data = new NodeInfoData("", [new Group("", "1").buildProperty("dependAssets", new InvalidData("Null"))]);
const event = new PluginEvent(Page.Background, Page.Devtools, Msg.NodeInfo, data); const event = new PluginEvent(Page.Background, Page.Devtools, Msg.ResponseTreeInfo, data);
testServer.send(event); testServer.send(event);
}, },
}; };

View File

@ -32,7 +32,7 @@
import ccui from "@xuyanfeng/cc-ui"; import ccui from "@xuyanfeng/cc-ui";
import { Option } from "@xuyanfeng/cc-ui/types/cc-select/const"; import { Option } from "@xuyanfeng/cc-ui/types/cc-select/const";
import { defineComponent, onMounted, PropType, ref, toRaw, watch } from "vue"; import { defineComponent, onMounted, PropType, ref, toRaw, watch } from "vue";
import { Msg } from "../../../core/types"; import { Msg, RequestSetPropertyData } from "../../../core/types";
import { bridge } from "../bridge"; import { bridge } from "../bridge";
import Bus, { BusMsg } from "../bus"; import Bus, { BusMsg } from "../bus";
import { EngineData, EnumData, ImageData, Info, NumberData, Property, StringData, TextData, Vec2Data, Vec3Data } from "../data"; import { EngineData, EnumData, ImageData, Info, NumberData, Property, StringData, TextData, Vec2Data, Vec3Data } from "../data";
@ -81,7 +81,6 @@ export default defineComponent({
expand, expand,
subData, subData,
formatValue(data: any) { formatValue(data: any) {
console.log(data);
if (data === null) { if (data === null) {
return "null"; return "null";
} else if (data === undefined) { } else if (data === undefined) {
@ -139,7 +138,7 @@ export default defineComponent({
onChangeValue() { onChangeValue() {
if (!props.value.readonly) { if (!props.value.readonly) {
const raw = toRaw(props.value); const raw = toRaw(props.value);
bridge.send(Msg.SetProperty, raw); bridge.send(Msg.RequestSetProperty, raw as RequestSetPropertyData);
} }
}, },
}; };