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
107// !ISSUE: Need to make it skip over non modified elements
108
109func View(data *Window, width, height int32) {
110 debug := false
111 data.Document.Style["width"] = strconv.Itoa(int(width)) + "px"
112 data.Document.Style["height"] = strconv.Itoa(int(height)) + "px"
113
114 wm := window.NewWindowManager()
115 wm.FPS = true
116
117 wm.OpenWindow(width, height)
118 defer wm.CloseWindow()
119
120 evts := map[string]element.EventList{}
121
122 eventStore := &evts
123
124 state := map[string]element.State{}
125
126 shouldStop := false
127
128 // Main game loop
129 for !wm.WindowShouldClose() && !shouldStop {
130 rl.BeginDrawing()
131 if !shouldStop && debug {
132 shouldStop = true
133 }
134 // Check if the window size has changed
135 newWidth := int32(rl.GetScreenWidth())
136 newHeight := int32(rl.GetScreenHeight())
137
138 if newWidth != width || newHeight != height {
139 rl.ClearBackground(rl.RayWhite)
140 // Window has been resized, handle the event
141 width = newWidth
142 height = newHeight
143
144 data.CSS.Width = float32(width)
145 data.CSS.Height = float32(height)
146
147 data.Document.Style["width"] = strconv.Itoa(int(width)) + "px"
148 data.Document.Style["height"] = strconv.Itoa(int(height)) + "px"
149 }
150
151 eventStore = events.GetEvents(&data.Document.Children[0], &state, eventStore)
152 data.CSS.ComputeNodeStyle(&data.Document.Children[0], &state)
153 rd := data.Render(state)
154 wm.LoadTextures(rd)
155 wm.Draw(rd)
156
157 events.RunEvents(eventStore)
158
159 rl.EndDrawing()
160 }
161}
162
163func CreateNode(node *html.Node, parent *element.Node) {
164 if node.Type == html.ElementNode {
165 newNode := parent.CreateElement(node.Data)
166 for _, attr := range node.Attr {
167 if attr.Key == "class" {
168 classes := strings.Split(attr.Val, " ")
169 for _, class := range classes {
170 newNode.ClassList.Add(class)
171 }
172 } else if attr.Key == "id" {
173 newNode.Id = attr.Val
174 } else if attr.Key == "contenteditable" && (attr.Val == "" || attr.Val == "true") {
175 newNode.Properties.Editable = true
176 } else if attr.Key == "href" {
177 newNode.Href = attr.Val
178 } else if attr.Key == "src" {
179 newNode.Src = attr.Val
180 } else if attr.Key == "title" {
181 newNode.Title = attr.Val
182 } else {
183 newNode.SetAttribute(attr.Key, attr.Val)
184 }
185 }
186 newNode.InnerText = strings.TrimSpace(utils.GetInnerText(node))
187 // Recursively traverse child nodes
188 for child := node.FirstChild; child != nil; child = child.NextSibling {
189 if child.Type == html.ElementNode {
190 CreateNode(child, &newNode)
191 }
192 }
193 parent.AppendChild(newNode)
194
195 } else {
196 for child := node.FirstChild; child != nil; child = child.NextSibling {
197 if child.Type == html.ElementNode {
198 CreateNode(child, parent)
199 }
200 }
201 }
202
203}
204
205func parseHTMLFromFile(path string) ([]string, []string, *html.Node) {
206 file, _ := os.Open(path)
207 defer file.Close()
208
209 scanner := bufio.NewScanner(file)
210 var htmlContent string
211
212 for scanner.Scan() {
213 htmlContent += scanner.Text() + "\n"
214 }
215
216 htmlContent = removeHTMLComments(htmlContent)
217
218 doc, _ := html.Parse(strings.NewReader(encapsulateText(removeWhitespaceBetweenTags(htmlContent))))
219
220 // Extract stylesheet link tags and style tags
221 stylesheets := extractStylesheets(doc, filepath.Dir(path))
222 styleTags := extractStyleTags(doc)
223
224 return stylesheets, styleTags, doc
225}
226
227func extractStylesheets(n *html.Node, baseDir string) []string {
228 var stylesheets []string
229
230 var dfs func(*html.Node)
231 dfs = func(node *html.Node) {
232 if node.Type == html.ElementNode && node.Data == "link" {
233 var href string
234 isStylesheet := false
235
236 for _, attr := range node.Attr {
237 if attr.Key == "rel" && attr.Val == "stylesheet" {
238 isStylesheet = true
239 } else if attr.Key == "href" {
240 href = attr.Val
241 }
242 }
243
244 if isStylesheet {
245 resolvedHref := localizePath(baseDir, href)
246 stylesheets = append(stylesheets, resolvedHref)
247 }
248 }
249
250 for c := node.FirstChild; c != nil; c = c.NextSibling {
251 dfs(c)
252 }
253 }
254
255 dfs(n)
256 return stylesheets
257}
258
259func extractStyleTags(n *html.Node) []string {
260 var styleTags []string
261
262 var dfs func(*html.Node)
263 dfs = func(node *html.Node) {
264 if node.Type == html.ElementNode && node.Data == "style" {
265 var styleContent strings.Builder
266 for c := node.FirstChild; c != nil; c = c.NextSibling {
267 if c.Type == html.TextNode {
268 styleContent.WriteString(c.Data)
269 }
270 }
271 styleTags = append(styleTags, styleContent.String())
272 }
273
274 for c := node.FirstChild; c != nil; c = c.NextSibling {
275 dfs(c)
276 }
277 }
278
279 dfs(n)
280 return styleTags
281}
282
283func localizePath(rootPath, filePath string) string {
284 // Check if the file path has a scheme, indicating it's a URL
285 u, err := url.Parse(filePath)
286 if err == nil && u.Scheme != "" {
287 return filePath
288 }
289
290 // Join the root path and the file path to create an absolute path
291 absPath := filepath.Join(rootPath, filePath)
292
293 // If the absolute path is the same as the original path, return it
294 if absPath == filePath {
295 return filePath
296 }
297
298 return "./" + absPath
299}
300
301func encapsulateText(htmlString string) string {
302 openOpen := regexp.MustCompile(`(<\w+[^>]*>)([^<]+)(<\w+[^>]*>)`)
303 closeOpen := regexp.MustCompile(`(</\w+[^>]*>)([^<]+)(<\w+[^>]*>)`)
304 closeClose := regexp.MustCompile(`(<\/\w+[^>]*>)([^<]+)(<\/\w+[^>]*>)`)
305 a := matchFactory(openOpen)
306 t := openOpen.ReplaceAllStringFunc(htmlString, a)
307 // fmt.Println(t)
308 b := matchFactory(closeOpen)
309 u := closeOpen.ReplaceAllStringFunc(t, b)
310 // fmt.Println(u)
311 c := matchFactory(closeClose)
312 v := closeClose.ReplaceAllStringFunc(u, c)
313 // fmt.Println(v)
314 return v
315}
316
317func matchFactory(re *regexp.Regexp) func(string) string {
318 return func(match string) string {
319 submatches := re.FindStringSubmatch(match)
320 if len(submatches) != 4 {
321 return match
322 }
323
324 // Process submatches
325 if len(removeWhitespace(submatches[2])) > 0 {
326 return submatches[1] + "<notaspan>" + submatches[2] + "</notaspan>" + submatches[3]
327 } else {
328 return match
329 }
330 }
331}
332func removeWhitespace(htmlString string) string {
333 // Remove extra white space
334 reSpaces := regexp.MustCompile(`\s+`)
335 htmlString = reSpaces.ReplaceAllString(htmlString, " ")
336
337 // Trim leading and trailing white space
338 htmlString = strings.TrimSpace(htmlString)
339
340 return htmlString
341}
342
343func removeHTMLComments(htmlString string) string {
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}