GUI
GUI is the source package
# Open?(go)
# New?(go)
# View?(go)
# CreateNode?(go)
# extractStylesheets?(go)
# extractStyleTags?(go)
# localizePath?(go)
# encapsulateText?(go)
# matchFactory?(go)
# removeWhitespace?(go)
# removeHTMLComments?(go)
1package gui
2
3import (
4 "bufio"
5 _ "embed"
6 "fmt"
7 "gui/cstyle"
8 "gui/cstyle/plugins/block"
9 "gui/cstyle/plugins/flex"
10 "gui/cstyle/plugins/inline"
11 "gui/window"
12
13 "gui/element"
14 "gui/events"
15 "gui/utils"
16 "net/url"
17 "os"
18 "path/filepath"
19 "regexp"
20 "strconv"
21 "strings"
22
23 rl "github.com/gen2brain/raylib-go/raylib"
24 "golang.org/x/net/html"
25)
26
27// _ "net/http/pprof"
28
29//go:embed master.css
30var mastercss string
31
32type Window struct {
33 CSS cstyle.CSS
34 Document element.Node
35 Adapter func()
36}
37
38func Open(path string) Window {
39 window := New()
40
41 styleSheets, styleTags, htmlNodes := parseHTMLFromFile(path)
42
43 for _, v := range styleSheets {
44 window.CSS.StyleSheet(v)
45 }
46
47 for _, v := range styleTags {
48 window.CSS.StyleTag(v)
49 }
50
51 CreateNode(htmlNodes, &window.Document)
52
53 return window
54}
55
56func New() Window {
57 css := cstyle.CSS{
58 Width: 800,
59 Height: 450,
60 }
61
62 css.StyleTag(mastercss)
63 // This is still apart of computestyle
64 // css.AddPlugin(position.Init())
65 css.AddPlugin(inline.Init())
66 css.AddPlugin(block.Init())
67 css.AddPlugin(flex.Init())
68
69 el := element.Node{}
70 document := el.CreateElement("ROOT")
71 document.Style["width"] = "800px"
72 document.Style["height"] = "450px"
73 document.Properties.Id = "ROOT"
74 return Window{
75 CSS: css,
76 Document: document,
77 }
78}
79
80func (w *Window) Render(state map[string]element.State) []element.State {
81 flatDoc := flatten(w.Document)
82 store := []element.State{}
83
84 for _, v := range flatDoc {
85 // wont work unless state is a pointer to the og
86 // s := state[v.Properties.Id]
87 // s.RenderCount++
88 // state[v.Properties.Id] = s
89 store = append(store, state[v.Properties.Id])
90 }
91 return store
92}
93
94func flatten(n element.Node) []element.Node {
95 var nodes []element.Node
96 nodes = append(nodes, n)
97
98 children := n.Children
99 if len(children) > 0 {
100 for _, ch := range children {
101 chNodes := flatten(ch)
102 nodes = append(nodes, chNodes...)
103 }
104 }
105 return nodes
106}
107
108func View(data *Window, width, height int32) {
109 debug := false
110 data.Document.Style["width"] = strconv.Itoa(int(width)) + "px"
111 data.Document.Style["height"] = strconv.Itoa(int(height)) + "px"
112
113 wm := window.NewWindowManager()
114 wm.FPS = true
115
116 wm.OpenWindow(width, height)
117 defer wm.CloseWindow()
118
119 evts := map[string]element.EventList{}
120
121 eventStore := &evts
122
123 state := map[string]element.State{}
124
125 // Main game loop
126 for !wm.WindowShouldClose() && !debug {
127 rl.BeginDrawing()
128
129 // Check if the window size has changed
130 newWidth := int32(rl.GetScreenWidth())
131 newHeight := int32(rl.GetScreenHeight())
132
133 if newWidth != width || newHeight != height {
134 rl.ClearBackground(rl.RayWhite)
135 // Window has been resized, handle the event
136 width = newWidth
137 height = newHeight
138
139 data.CSS.Width = float32(width)
140 data.CSS.Height = float32(height)
141
142 data.Document.Style["width"] = strconv.Itoa(int(width)) + "px"
143 data.Document.Style["height"] = strconv.Itoa(int(height)) + "px"
144 }
145
146 eventStore = events.GetEvents(&data.Document.Children[0], &state, eventStore)
147 data.CSS.ComputeNodeStyle(&data.Document.Children[0], &state)
148 rd := data.Render(state)
149 wm.LoadTextures(rd)
150 wm.Draw(rd)
151
152 events.RunEvents(eventStore)
153
154 rl.EndDrawing()
155 }
156}
157
158func CreateNode(node *html.Node, parent *element.Node) {
159 if node.Type == html.ElementNode {
160 newNode := parent.CreateElement(node.Data)
161 for _, attr := range node.Attr {
162 if attr.Key == "class" {
163 classes := strings.Split(attr.Val, " ")
164 for _, class := range classes {
165 newNode.ClassList.Add(class)
166 }
167 } else if attr.Key == "id" {
168 newNode.Id = attr.Val
169 } else if attr.Key == "contenteditable" && (attr.Val == "" || attr.Val == "true") {
170 newNode.Properties.Editable = true
171 } else if attr.Key == "href" {
172 newNode.Href = attr.Val
173 } else if attr.Key == "src" {
174 newNode.Src = attr.Val
175 } else if attr.Key == "title" {
176 newNode.Title = attr.Val
177 } else {
178 newNode.SetAttribute(attr.Key, attr.Val)
179 }
180 }
181 newNode.InnerText = strings.TrimSpace(utils.GetInnerText(node))
182 // Recursively traverse child nodes
183 for child := node.FirstChild; child != nil; child = child.NextSibling {
184 if child.Type == html.ElementNode {
185 CreateNode(child, &newNode)
186 }
187 }
188 parent.AppendChild(newNode)
189
190 } else {
191 for child := node.FirstChild; child != nil; child = child.NextSibling {
192 if child.Type == html.ElementNode {
193 CreateNode(child, parent)
194 }
195 }
196 }
197
198}
199
200func parseHTMLFromFile(path string) ([]string, []string, *html.Node) {
201 file, _ := os.Open(path)
202 defer file.Close()
203
204 scanner := bufio.NewScanner(file)
205 var htmlContent string
206
207 for scanner.Scan() {
208 htmlContent += scanner.Text() + "\n"
209 }
210
211 fmt.Println(htmlContent)
212
213 htmlContent = removeHTMLComments(htmlContent)
214
215 doc, _ := html.Parse(strings.NewReader(encapsulateText(removeWhitespaceBetweenTags(htmlContent))))
216
217 // Extract stylesheet link tags and style tags
218 stylesheets := extractStylesheets(doc, filepath.Dir(path))
219 styleTags := extractStyleTags(doc)
220
221 return stylesheets, styleTags, doc
222}
223
224func extractStylesheets(n *html.Node, baseDir string) []string {
225 var stylesheets []string
226
227 var dfs func(*html.Node)
228 dfs = func(node *html.Node) {
229 if node.Type == html.ElementNode && node.Data == "link" {
230 var href string
231 isStylesheet := false
232
233 for _, attr := range node.Attr {
234 if attr.Key == "rel" && attr.Val == "stylesheet" {
235 isStylesheet = true
236 } else if attr.Key == "href" {
237 href = attr.Val
238 }
239 }
240
241 if isStylesheet {
242 resolvedHref := localizePath(baseDir, href)
243 stylesheets = append(stylesheets, resolvedHref)
244 }
245 }
246
247 for c := node.FirstChild; c != nil; c = c.NextSibling {
248 dfs(c)
249 }
250 }
251
252 dfs(n)
253 return stylesheets
254}
255
256func extractStyleTags(n *html.Node) []string {
257 var styleTags []string
258
259 var dfs func(*html.Node)
260 dfs = func(node *html.Node) {
261 if node.Type == html.ElementNode && node.Data == "style" {
262 var styleContent strings.Builder
263 for c := node.FirstChild; c != nil; c = c.NextSibling {
264 if c.Type == html.TextNode {
265 styleContent.WriteString(c.Data)
266 }
267 }
268 styleTags = append(styleTags, styleContent.String())
269 }
270
271 for c := node.FirstChild; c != nil; c = c.NextSibling {
272 dfs(c)
273 }
274 }
275
276 dfs(n)
277 return styleTags
278}
279
280func localizePath(rootPath, filePath string) string {
281 // Check if the file path has a scheme, indicating it's a URL
282 u, err := url.Parse(filePath)
283 if err == nil && u.Scheme != "" {
284 return filePath
285 }
286
287 // Join the root path and the file path to create an absolute path
288 absPath := filepath.Join(rootPath, filePath)
289
290 // If the absolute path is the same as the original path, return it
291 if absPath == filePath {
292 return filePath
293 }
294
295 return "./" + absPath
296}
297
298func encapsulateText(htmlString string) string {
299 // !ISSUE: openOpen not correctly matching string after updating the next issue
300 openOpen := regexp.MustCompile(`(<\w+[^>]*>)([^<]+)(<\w+[^>]*>)`)
301 closeOpen := regexp.MustCompile(`(</\w+[^>]*>)([^<]+)(<\w+[^>]*>)`)
302 closeClose := regexp.MustCompile(`(<\/\w+[^>]*>)([^<]+)(<\/\w+[^>]*>)`)
303 a := matchFactory(openOpen)
304 t := openOpen.ReplaceAllStringFunc(htmlString, a)
305 // fmt.Println(t)
306 b := matchFactory(closeOpen)
307 u := closeOpen.ReplaceAllStringFunc(t, b)
308 // fmt.Println(u)
309 c := matchFactory(closeClose)
310 v := closeClose.ReplaceAllStringFunc(u, c)
311 // fmt.Println(v)
312 return v
313}
314
315func matchFactory(re *regexp.Regexp) func(string) string {
316 return func(match string) string {
317 submatches := re.FindStringSubmatch(match)
318 if len(submatches) != 4 {
319 return match
320 }
321
322 // Process submatches
323 if len(removeWhitespace(submatches[2])) > 0 {
324 return submatches[1] + "<notaspan>" + submatches[2] + "</notaspan>" + submatches[3]
325 } else {
326 return match
327 }
328 }
329}
330func removeWhitespace(htmlString string) string {
331 // Remove extra white space
332 reSpaces := regexp.MustCompile(`\s+`)
333 htmlString = reSpaces.ReplaceAllString(htmlString, " ")
334
335 // Trim leading and trailing white space
336 htmlString = strings.TrimSpace(htmlString)
337
338 return htmlString
339}
340
341func removeHTMLComments(htmlString string) string {
342 // !ISSUE: Updated from <!--(.*?)--> and broke the openOpen matching
343 re := regexp.MustCompile(`<!--[\s\S]*?-->`)
344 return re.ReplaceAllString(htmlString, "")
345}
346
347func removeWhitespaceBetweenTags(html string) string {
348 // Create a regular expression to match spaces between angle brackets
349 re := regexp.MustCompile(`>\s+<`)
350 // Replace all matches of spaces between angle brackets with "><"
351 return re.ReplaceAllString(html, "><")
352}