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