GenCode_CSharp.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { FairyEditor, FairyGUI, System } from 'csharp';
  2. import CodeWriter from './CodeWriter';
  3. class GenClassInfo {
  4. name: string
  5. varName: string
  6. type: string
  7. customType: boolean
  8. otherPkgName: string
  9. constructor(member: FairyEditor.PublishHandler.MemberInfo) {
  10. this.name = member.name;
  11. this.varName = member.varName;
  12. this.type = member.type;
  13. this.customType = false
  14. }
  15. }
  16. let exportLangKV = new Map<string, string>()
  17. /**UI的vm类名后缀*/
  18. let vmSuffix = "VM"
  19. function genCodeCS(handler: FairyEditor.PublishHandler) {
  20. let settings = (<FairyEditor.GlobalPublishSettings>handler.project.GetSettings("Publish")).codeGeneration;
  21. let codePkgName = handler.ToFilename(handler.pkg.name); //convert chinese to pinyin, remove special chars etc.
  22. codePkgName = myCapitalize(codePkgName);
  23. //package代码的根目录
  24. let exportCodePath = `${handler.exportCodePath}/${codePkgName}`;
  25. //模板代码根目录
  26. let codeTemplatesPath = handler.project.assetsPath.replace("assets", "plugins/xgame_gen_code/Templates/cs");
  27. console.log(`CodePath:${exportCodePath} codePkgName:${codePkgName}`);
  28. console.log(`codeTemplatesPath:${codeTemplatesPath} getMemberByName:${settings.getMemberByName}`);
  29. //CollectClasses(stripeMemeber, stripeClass, fguiNamespace)
  30. let classes = handler.CollectClasses(settings.ignoreNoname, settings.ignoreNoname, null);
  31. // handler.SetupCodeFolder(exportCodePath, "cs"); //check if target folder exists, and delete old files
  32. //创建Package代码文件夹
  33. if (!System.IO.Directory.Exists(exportCodePath)) {
  34. System.IO.Directory.CreateDirectory(exportCodePath);
  35. }
  36. let classCnt = classes.Count;
  37. let writer = new CodeWriter();
  38. // 一个个导出类导出
  39. for (let i: number = 0; i < classCnt; i++) {
  40. let classInfo = classes.get_Item(i);
  41. if (!checkPackageItemIsGenCode(handler, classInfo.res)) {
  42. // console.warn("不需要导出:" + classInfo.resName)
  43. continue
  44. } else {
  45. console.log("导出:" + classInfo.resName)
  46. }
  47. logClassInfo(classInfo)
  48. let resName = myCapitalize(classInfo.resName);
  49. let uiName = codePkgName + resName;
  50. let uiCodePath = `${exportCodePath}/${resName}`;
  51. //创建UI窗口的代码文件夹
  52. if (!System.IO.Directory.Exists(uiCodePath)) {
  53. System.IO.Directory.CreateDirectory(uiCodePath);
  54. }
  55. if (classInfo.res.exported) {
  56. // 有设置导出属性的才生成View和Ctrl代码
  57. genUIClassOnce(uiCodePath, codeTemplatesPath, codePkgName, resName, uiName, "View");
  58. }
  59. genUIClassOnce(uiCodePath, codeTemplatesPath, codePkgName, resName, uiName, vmSuffix);
  60. // 需要绑定的组件变量
  61. let genClassTypeMap = new Map<string, GenClassInfo>()
  62. // 需要多语言转义的变量
  63. let langTypeMap = new Map<string, GenClassInfo>()
  64. // TODO 该信息后续看是否需要生成脚本
  65. let otherPkgName: Array<string> = new Array<string>()
  66. // 提前先获取一次生成组件变量存在引用的生成代码或者跨包的生成代码类.
  67. for (let index = 0; index < classInfo.members?.Count; index++) {
  68. const element = classInfo.members.get_Item(index);
  69. console.log("element.name:" + element.name + " varName:" + element.varName + " type:" + element.type)
  70. if (element.res) {
  71. let desc = handler.GetItemDesc(element.res) as FairyGUI.Utils.XML
  72. let superClassName = desc?.GetAttribute("extention")
  73. //fgui的组件.xml文件,如果是普通组件,则没有extention属性,否则extention会记录具体的组件类型
  74. // 是一个自定义组件
  75. console.log("element.res name:" + element.res.name + " owner.name:" + element.res.owner.name + " type:" + element.res.type
  76. + " super:" + superClassName)
  77. // 如果是当前的包那么直接发布
  78. // 如果是其他包。那么需要判断这个是否需要生成代码的,否则也是直接当成是component组件引用
  79. if (element.res.owner.name == handler.pkg.name) {
  80. // 判断是否需要导出生成代码类否则直接生成扩展类吧
  81. if (checkPackageItemIsGenCode(handler, element.res)) { //&& element.res.exported
  82. let className = `${codePkgName}${myCapitalize(element.res.name)}${vmSuffix}`;
  83. if (otherPkgName.indexOf(className) == -1) {
  84. otherPkgName.push(className)
  85. }
  86. } else {
  87. // 生成绑定ext类
  88. }
  89. } else {
  90. // 不在同一个包,需要读取目标路径的配置xml判断是否需要生成
  91. if (checkOtherPackageItemIsGenCode(element.res)) {
  92. // console.log("引用其他包的资源可以生成代码:" + element.res.owner.name + "." + element.res.name)
  93. let className = `${myCapitalize(element.res.owner.name)}${myCapitalize(element.res.name)}${vmSuffix}`;
  94. if (otherPkgName.indexOf(className) == -1) {
  95. otherPkgName.push(className)
  96. // writer.writeln('import { %s } from "../%s/%s";', className + "_" + element.res.owner.name, element.res.owner.name, className + "_" + element.res.owner.name)
  97. }
  98. }
  99. }
  100. }
  101. }
  102. // 组件变量
  103. for (let index = 0; index < classInfo.members?.Count; index++) {
  104. const element = classInfo.members.get_Item(index);
  105. if (element.res) {
  106. // 如果是当前的包那么直接发布
  107. // 如果是其他包。那么需要判断这个是否需要生成代码的,否则也是直接当成是component组件引用
  108. if (element.res.owner.name == handler.pkg.name) {
  109. // 判断是否需要导出生成代码类否则直接生成扩展类吧
  110. // 只有当这个组件资源里面勾选了生成代码 + exported才生成代码
  111. if (checkPackageItemIsGenCode(handler, element.res)) { // && element.res.exported
  112. // 有生成代码标记
  113. let gci = new GenClassInfo(element);
  114. gci.type = `${codePkgName}${myCapitalize(element.res.name)}${vmSuffix}`;
  115. gci.customType = true;
  116. genClassTypeMap.set(element.varName, gci)
  117. }
  118. // 通过判断在该组件是否勾选了导出,那么也需要生成一下ext类
  119. else {
  120. let desc = handler.GetItemDesc(element.res) as FairyGUI.Utils.XML
  121. let superClassName = desc?.GetAttribute("extention")
  122. console.log(`GetItemDesc name:${element.res.name} exported:${element.res.exported} ext:${superClassName}`);
  123. if (!superClassName) {
  124. // // null = GComponent
  125. // writer.writeln('public FairyGUI.GComponent %s;', element.varName)
  126. let gci = new GenClassInfo(element);
  127. gci.type = "GComponent";
  128. genClassTypeMap.set(element.varName, gci)
  129. // 如果有title的可以?
  130. if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
  131. gci = new GenClassInfo(element);
  132. gci.type = superClassName;
  133. langTypeMap.set(element.varName, gci)
  134. }
  135. } else {
  136. // writer.writeln('public FairyGUI.G%s %s;',superClassName, element.varName)
  137. let gci = new GenClassInfo(element);
  138. gci.type = "G" + superClassName;
  139. genClassTypeMap.set(element.varName, gci)
  140. if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
  141. langTypeMap.set(element.varName, gci)
  142. }
  143. }
  144. }
  145. } else {
  146. // 不在同一个包,需要读取目标路径的配置xml判断是否需要生成
  147. if (checkOtherPackageItemIsGenCode(element.res)) {
  148. // // console.log("引用其他包的资源可以生成代码:" + element.res.owner.name + "." + element.res.name)
  149. let gci = new GenClassInfo(element);
  150. gci.type = `${myCapitalize(element.res.owner.name)}${myCapitalize(element.res.name)}${vmSuffix}`;
  151. gci.customType = true;
  152. gci.otherPkgName = myCapitalize(element.res.owner.name);
  153. genClassTypeMap.set(element.varName, gci)
  154. } else {
  155. let superClassName = checkOtherPackageItemExtension(element.res)
  156. if (superClassName) {
  157. // writer.writeln('public FairyGUI.G%s %s;',superClassName, element.varName)
  158. let gci = new GenClassInfo(element);
  159. gci.type = "G" + superClassName;
  160. genClassTypeMap.set(element.varName, gci)
  161. if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
  162. langTypeMap.set(element.varName, gci)
  163. }
  164. }
  165. else {
  166. let gci = new GenClassInfo(element);
  167. gci.type = "GComponent";
  168. genClassTypeMap.set(element.varName, gci)
  169. if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
  170. langTypeMap.set(element.varName, gci)
  171. }
  172. }
  173. }
  174. }
  175. } else {
  176. // fgui 默认的组件变量即可
  177. // writer.writeln('public FairyGUI.%s %s;',element.type, element.varName)
  178. genClassTypeMap.set(element.varName, new GenClassInfo(element))
  179. if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
  180. langTypeMap.set(element.varName, new GenClassInfo(element))
  181. }
  182. }
  183. }
  184. if (classInfo.res.exported) {
  185. // 有设置导出属性的才生成Ctrl代码
  186. genUIClassOnce(uiCodePath, codeTemplatesPath, codePkgName, resName, uiName, "Ctrl", genClassTypeMap);
  187. }
  188. genViewModelClass(uiCodePath, codeTemplatesPath, codePkgName, resName, uiName, genClassTypeMap);
  189. }
  190. // 写一个binder类可以直接获取这个package导出的信息
  191. // 如果有些组件需要绑定的也可以绑定这个组件类型
  192. // let binderName = "GenMain_" + codePkgName;
  193. // writer.writeln('export class %s', binderName)
  194. // writer.startBlock()
  195. // writer.writeln()
  196. // writer.writeln('public static PackageName:string = "%s";', handler.pkg.name)
  197. // writer.writeln()
  198. // // 把这个包导出的类记录一下引用的类名
  199. // // bindall扩展类绑定
  200. // writer.writeln('public static bindAll()');
  201. // writer.startBlock();
  202. // // for (let i: number = 0; i < classCnt; i++) {
  203. // // let classInfo = classes.get_Item(i);
  204. // // writer.writeln('UIObjectFactory.SetPackageItemExtension(%s.URL, typeof(%s));', classInfo.className, classInfo.className);
  205. // // }
  206. // writer.endBlock(); //bindall
  207. // writer.endBlock()
  208. // writer.save(exportCodePath + '/' + binderName + '.ts');
  209. writer.reset()
  210. // 把该包多语言的kv保存下来
  211. if (exportLangKV.size > 0) {
  212. exportLangKV.forEach((v, k) => {
  213. writer.writeln("%s %s", k, v)
  214. })
  215. writer.save(exportCodePath + '/' + "lang_" + codePkgName + '.txt');
  216. }
  217. writer.reset()
  218. }
  219. /**
  220. * 创建UI代码,已经存在则跳过
  221. * 不重复创建
  222. * classSuffix 类名后缀:View、ViewCtrl、ViewModel等
  223. */
  224. function genUIClassOnce(uiCodePath: string, codeTemplatesPath: string, pkgName: string, panelName: string, uiName: string, classSuffix: string, genClassTypeMap: Map<string, GenClassInfo> = null) {
  225. let uiClassName = uiName + classSuffix;
  226. let uiClassPath = `${uiCodePath}/${uiClassName}.cs`;
  227. if (System.IO.File.Exists(uiClassPath)) {
  228. console.log(`${uiClassName}已经存在,不重复创建`);
  229. // System.IO.File.Delete(uiClassPath);
  230. return;
  231. }
  232. let uiClassText = System.IO.File.ReadAllText(`${codeTemplatesPath}/Template${classSuffix}.cs`);
  233. uiClassText = uiClassText.replaceAll("<#pkgName>", pkgName);
  234. uiClassText = uiClassText.replaceAll("<#panelName>", panelName);
  235. uiClassText = uiClassText.replaceAll("<#UIName>", uiName);
  236. if (genClassTypeMap != null) {
  237. uiClassText = genButtonEvents(uiClassText, genClassTypeMap);
  238. }
  239. System.IO.File.WriteAllText(uiClassPath, uiClassText);
  240. }
  241. /**生成GButton的onClick注册代码*/
  242. function genButtonEvents(uiClassText: string, genClassTypeMap: Map<string, GenClassInfo>): string {
  243. let uiEventsAdd: string = "";
  244. let uiEventsRemove: string = "";
  245. let uiEventsDefine: string = "";
  246. genClassTypeMap.forEach((v, k) => {
  247. if (v.type == "GButton") {
  248. let btnName = myCapitalize(v.name);
  249. let functionName = `OnClick${btnName}`;
  250. uiEventsAdd += ` VM.${btnName}.onClick.Add(${functionName});\n`;
  251. uiEventsRemove += ` VM.${btnName}.onClick.Remove(${functionName});\n`;
  252. uiEventsDefine += ` private void ${functionName}(EventContext context)
  253. {
  254. }\n`;
  255. }
  256. });
  257. uiClassText = uiClassText.replace("<#UIEventsAddArea>", uiEventsAdd);
  258. uiClassText = uiClassText.replace("<#UIEventsRemoveArea>", uiEventsRemove);
  259. uiClassText = uiClassText.replace("<#UIEventsDefineArea>", uiEventsDefine);
  260. return uiClassText;
  261. }
  262. /**
  263. * 生成ViewModel.Gen代码
  264. * 每次都会重新生成
  265. */
  266. function genViewModelClass(uiCodePath: string, codeTemplatesPath: string, pkgName: string, panelName: string, uiName: string, genClassTypeMap: Map<string, GenClassInfo>) {
  267. let vmClassName = `${uiName}${vmSuffix}.Gen`;
  268. let vmClassPath = `${uiCodePath}/${vmClassName}.cs`;
  269. if (System.IO.File.Exists(vmClassPath)) {
  270. //删除旧文件
  271. System.IO.File.Delete(vmClassPath);
  272. }
  273. let vmClassText = System.IO.File.ReadAllText(`${codeTemplatesPath}/Template${vmSuffix}.Gen.cs`);
  274. vmClassText = vmClassText.replaceAll("<#pkgName>", pkgName);
  275. vmClassText = vmClassText.replaceAll("<#panelName>", panelName);
  276. vmClassText = vmClassText.replaceAll("<#UIName>", uiName);
  277. // 开始绑定组件get
  278. let propertyDefine: string = "";
  279. let propertyAssign: string = "";
  280. genClassTypeMap.forEach((v, k) => {
  281. propertyDefine += ` public ${v.type} ${myCapitalize(v.name)} { get; private set; }\n`;
  282. let eTypeWithoutG = v.type.slice(1,v.type.length); // component组件名字去掉开头的'G'
  283. if (v.customType) {
  284. propertyAssign += ` ${myCapitalize(v.name)} = new ${v.type}(panel.GetChild("${v.name}").asCom);\n`;
  285. // propertyAssign += ` ${myCapitalize(v.name)} = (panel.GetChild("${v.superName}").asCom).GetChild("${v.name}").as${eTypeWithoutG};\n\r`;
  286. } else {
  287. if (v.type == "Controller") {
  288. propertyAssign += ` ${myCapitalize(v.name)} = panel.GetController("${v.name}");\n`;
  289. }
  290. else if (v.type == "Transition") {
  291. propertyAssign += ` ${myCapitalize(v.name)} = panel.GetTransition("${v.name}");\n`;
  292. }
  293. else {
  294. propertyAssign += ` ${myCapitalize(v.name)} = panel.GetChild("${v.name}") as ${v.type};\n`;
  295. }
  296. }
  297. });
  298. vmClassText = vmClassText.replace("<#PropertyDefineArea>", propertyDefine);
  299. vmClassText = vmClassText.replace("<#PropertyAssignArea>", propertyAssign);
  300. System.IO.File.WriteAllText(vmClassPath, vmClassText);
  301. }
  302. function genBindClass(handler: FairyEditor.PublishHandler, pkgItem: FairyEditor.FPackageItem) {
  303. let writer = new CodeWriter();
  304. // if (!checkPackageItemIsGenCode(handler, pkgItem)) {
  305. // return
  306. // } else {
  307. // console.log("导出:" + pkgItem.name)
  308. // }
  309. writer.reset();
  310. writer.writeln('import { FairyGUI } from \'csharp\';');
  311. writer.writeln('import { binder } from \'framework/common/NiceDecorator\';')
  312. writer.writeln('import { BaseUI, UILayer } from "../../../framework/ui/BaseUI";')
  313. writer.writeln();
  314. pkgItem = handler.pkg.GetItem(pkgItem.id)
  315. console.log(pkgItem.name + " - " + pkgItem.file)
  316. console.log(pkgItem.GetURL())
  317. let pkg = pkgItem.GetTrunk()
  318. // 提前先获取一次生成组件变量存在引用的生成代码或者跨包的生成代码类.
  319. for (let index = 0; index < pkg.children.Count; index++) {
  320. const child = pkg.children.get_Item(index);
  321. console.log("child : " + child.name)
  322. }
  323. }
  324. function checkPackageItemIsLang(handler: FairyEditor.PublishHandler, pkgItem: FairyEditor.FPackageItem, refComponentName: string) {
  325. // console.log("found lang = " + refComponentName)
  326. console.log(`checkPackageItemIsLang pkgItem.file:${pkgItem.file}`);
  327. let file = System.IO.File.ReadAllText(pkgItem.file)
  328. let xml = new FairyGUI.Utils.XML(file)
  329. let sd = xml?.GetNode("scriptData")
  330. if (!sd) {
  331. return false
  332. }
  333. let eles = xml?.GetNode("displayList")?.Elements()
  334. for (let index = 0; index < eles?.Count; index++) {
  335. const element = eles.get_Item(index);
  336. if (element.GetAttribute("name") == refComponentName) {
  337. // 获取这个组件id
  338. let id = element.GetAttribute("id")
  339. // 然后跑去找这个配置的lang是否是1
  340. if (sd.GetAttribute("lang" + id) == "1") {
  341. let key = handler.pkg.name + "." + pkgItem.name + "." + refComponentName
  342. // 保存一下这个多语言的key - text
  343. if (element.HasAttribute("text")) {
  344. exportLangKV.set(key, element.GetAttribute("text"))
  345. }
  346. else if (element.HasAttribute("url")) {
  347. exportLangKV.set(key, element.GetAttribute("url"))
  348. }
  349. else if (element.GetNode("Button")?.HasAttribute("title")) {
  350. exportLangKV.set(key, element.GetNode("Button").GetAttribute("title"))
  351. }
  352. else if (element.GetNode("Label")?.HasAttribute("title")) {
  353. exportLangKV.set(key, element.GetNode("Label").GetAttribute("title"))
  354. }
  355. return true
  356. } else {
  357. return false
  358. }
  359. }
  360. }
  361. return false
  362. }
  363. /**
  364. * 判断包内Item是否有生成代码标记
  365. */
  366. function checkPackageItemIsGenCode(handler: FairyEditor.PublishHandler, pkgItem: FairyEditor.FPackageItem) {
  367. let xml = handler.GetScriptData(pkgItem)
  368. let gencode = xml?.GetAttribute("gencode" + pkgItem.id)
  369. if (gencode == "1") {
  370. return true
  371. }
  372. return false
  373. }
  374. // 例如一个组件里面选择了某个丢进来的组件勾选了生成代码,但是这个组件不生成实例化代码就用ext
  375. function checkComponentIsGenCode(handler: FairyEditor.PublishHandler, pkgItem: FairyEditor.FPackageItem, refComponentId: string) {
  376. let xml = handler.GetScriptData(pkgItem)
  377. let gencode = xml?.GetAttribute("gencode" + refComponentId)
  378. if (gencode == "1") {
  379. return true
  380. }
  381. return false
  382. }
  383. /**
  384. * 判断其他包内Item是否有生成代码标记
  385. */
  386. function checkOtherPackageItemIsGenCode(pkgItem: FairyEditor.FPackageItem) {
  387. let file = System.IO.File.ReadAllText(pkgItem.file)
  388. let xml = new FairyGUI.Utils.XML(file)
  389. let gencode = xml?.GetNode("scriptData")?.GetAttribute("gencode" + pkgItem.id)
  390. if (gencode == "1") {
  391. return true
  392. }
  393. return false
  394. }
  395. function checkOtherPackageItemExtension(pkgItem: FairyEditor.FPackageItem) {
  396. let file = System.IO.File.ReadAllText(pkgItem.file)
  397. let xml = new FairyGUI.Utils.XML(file)
  398. return xml?.GetAttribute("extention")
  399. }
  400. function logClassInfo(ci: FairyEditor.PublishHandler.ClassInfo) {
  401. console.log(ci.superClassName + "." + ci.className + " resName=" + ci.resName + " resId=" + ci.resId)
  402. // for (let index = 0; index < ci.members?.Count; index++) {
  403. // const element = ci.members.get_Item(index);
  404. // console.log(" > " + element.name + " -v:" + element.varName + " -t:" + element.type )
  405. // if(element.res) {
  406. // console.log(" : res=" + element.res.name + " 包名:" + element.res.owner.name)
  407. // }
  408. // }
  409. for (let index = 0; index < ci.references?.Count; index++) {
  410. const element = ci.references.get_Item(index);
  411. console.log(" >> ref:" + element)
  412. }
  413. }
  414. /**
  415. * 字符串首字母转大写
  416. */
  417. function myCapitalize(str:string) {
  418. return str[0].toUpperCase() + str.slice(1,str.length)
  419. }
  420. export { genCodeCS };