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