fixed code generation and added asset generation

This commit is contained in:
paul
2024-09-28 11:29:37 +05:30
parent 15bed19d57
commit 1c9938398a
11 changed files with 220 additions and 166 deletions

View File

@@ -7,39 +7,46 @@ import TopLevel from "../widgets/toplevel"
// FIXME: if the toplevel comes first, before the MainWindow in widgetlist the root may become null
// Recursive function to generate the code list, imports, requirements, and track mainVariable
function generateTkinterCodeList(widgetList = [], widgetRefs = [], parentVariable = null, mainVariable = "") {
let variableNames = [] // {widgetId: "", name: "", count: 1}
function generateTkinterCodeList(widgetList = [], widgetRefs = [], parentVariable = null, mainVariable = "", usedVariableNames = new Set()) {
let variableMapping = new Map() // Map widget to variable { widgetId: variableName }
let imports = new Set([])
let requirements = new Set([])
let code = []
for (let widget of widgetList) {
// console.log("Key: ", widget)
const widgetRef = widgetRefs[widget.id].current
let varName = widgetRef.getVariableName()
imports.add(widgetRef.getImports())
requirements.add(widgetRef.getRequirements())
// Add imports and requirements to sets
widgetRef.getImports().forEach(importItem => imports.add(importItem));
widgetRef.getRequirements().forEach(requirementItem => requirements.add(requirementItem));
// Set main variable if the widget is MainWindow
if (widget.widgetType === MainWindow) {
mainVariable = varName
}
if (!variableNames.find((val) => val.variable === varName)) {
variableNames.push({ widgetId: widgetRef.id, name: varName, count: 1 })
} else {
// Avoid duplicate names
const existingVariable = variableNames.find((val) => val.variable === varName)
const existingCount = existingVariable.count
existingVariable.count += 1
varName = `${existingVariable.name}${existingCount}`
variableNames.push({ widgetId: widgetRef.id, name: varName, count: 1 })
// Ensure unique variable names across recursion
let originalVarName = varName
let count = 1;
// Check for uniqueness and update varName
while (usedVariableNames.has(varName)) {
varName = `${originalVarName}${count}`
count++
}
const currentParentVariable = variableNames.find(val => val.widgetId === widget.id)?.name || parentVariable
usedVariableNames.add(varName)
variableMapping.set(widget.id, varName) // Store the variable name by widget ID
// Determine the current parent variable from variableNames or fallback to parentVariable
let currentParentVariable = parentVariable || (variableMapping.get(widget.id) || null)
if (widget.widgetType === TopLevel){
// for top level set it to the main variable
// TODO: the toplevels parent should be determined other ways, suppose the top level has another toplevel
currentParentVariable = mainVariable
}
let widgetCode = widgetRef.generateCode(varName, currentParentVariable)
@@ -53,32 +60,32 @@ function generateTkinterCodeList(widgetList = [], widgetRefs = [], parentVariabl
code.push(...widgetCode)
code.push("\n\n")
// Recursively handle child widgets, which are full widget objects
// Recursively handle child widgets
if (widget.children && widget.children.length > 0) {
const childResult = generateTkinterCodeList(widget.children, widgetRefs, varName, mainVariable)
// Pass down the unique names for children to prevent duplication
const childResult = generateTkinterCodeList(widget.children, widgetRefs, varName, mainVariable, usedVariableNames)
// Merge child imports, requirements, and code
imports = new Set([...imports, ...childResult.imports])
requirements = new Set([...requirements, ...childResult.requirements])
code.push(...childResult.code)
// Track the main variable returned by the child
mainVariable = childResult.mainVariable || mainVariable
mainVariable = childResult.mainVariable || mainVariable // the main variable is the main window variable
}
}
return {
imports: Array.from(imports), // Convert Set to Array
imports: Array.from(imports),
code: code,
requirements: Array.from(requirements), // Convert Set to Array
requirements: Array.from(requirements),
mainVariable
}
}
async function generateTkinterCode(projectName, widgetList=[], widgetRefs=[]){
async function generateTkinterCode(projectName, widgetList=[], widgetRefs=[], assetFiles){
console.log("widgetList and refs", projectName, widgetList, widgetRefs)
console.log("widgetList and refs", projectName, widgetList, widgetRefs, assetFiles)
let mainWindowCount = 0
@@ -102,38 +109,37 @@ async function generateTkinterCode(projectName, widgetList=[], widgetRefs=[]){
return
}
// let code = [`# This code is generated by PyUIbuilder: https://github.com/paulledemon \n`]
// code.push("\n", "import tkinter as tk", "\n\n")
// widget - {id, widgetType: widgetComponentType, children: [], parent: "", initialData: {}}
const generatedObject = generateTkinterCodeList(filteredWidgetList, widgetRefs, "", "")
const {code: codeLines, imports, requirements, mainVariable} = generatedObject
// TODO: avoid adding \n inside the list instead rewrite using code.join("\n")
const code = [
"# This code is generated by PyUIbuilder: https://github.com/paulledemon",
"\n\n",
...imports,
...imports.flatMap((item, index) => index < imports.length - 1 ? [item, "\n"] : [item]), //add \n to every line
"\n\n",
...codeLines,
"\n",
`${mainVariable}.mainloop()`,
]
// TODO: create requirements.txt file
console.log("Code: ", code.join(""))
console.log("Code: ", code.join(""), "\n", requirements.join("\n"))
message.info("starting zipping files, download will start in a few seconds")
const createFileList = [
{
fileData: code.join(""),
fileData: code.join("\n"),
fileName: "main.py",
folder: ""
}
]
// TODO: Zip asset files
if (requirements.length > 0){
createFileList.push({
fileData: requirements.join("\n"),
@@ -142,6 +148,36 @@ async function generateTkinterCode(projectName, widgetList=[], widgetRefs=[]){
})
}
for (let asset of assetFiles){
if (asset.fileType === "image"){
createFileList.push({
fileData: asset.originFileObj,
fileName: asset.name,
folder: "assets/images"
})
}else if (asset.fileType === "video"){
createFileList.push({
fileData: asset.originFileObj,
fileName: asset.name,
folder: "assets/videos"
})
}else if (asset.fileType === "audio"){
createFileList.push({
fileData: asset.originFileObj,
fileName: asset.name,
folder: "assets/audio"
})
}else{
createFileList.push({
fileData: asset.originFileObj,
fileName: asset.name,
folder: "assets/media"
})
}
}
// createFilesAndDownload(createFileList, projectName).then(() => {
// message.success("Download complete")
// }).catch(() => {