-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.nim
322 lines (241 loc) · 9.77 KB
/
main.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import std/[threadpool, strutils, strformat, os]
import imstyle
import openurl
import tinydialogs
import kdl, kdl/prefs
import nimgl/[opengl, glfw]
import nimgl/imgui, nimgl/imgui/[impl_opengl, impl_glfw]
import src/[settingsmodal, utils, types, icons]
when defined(release):
import resources
proc getConfigDir(app: App): string =
getConfigDir() / app.config.name
proc drawAboutModal(app: App) =
igSetNextWindowPos(igGetMainViewport().getCenter(), Always, igVec2(0.5f, 0.5f))
let unusedOpen = true # Passing this parameter creates a close button
if igBeginPopupModal(cstring "About " & app.config.name & "###about", unusedOpen.unsafeAddr, flags = makeFlags(ImGuiWindowFlags.NoResize)):
# Display icon image
var texture: GLuint
var image = app.res(app.config.iconPath).readImageFromMemory()
image.loadTextureFromData(texture)
igImage(cast[ptr ImTextureID](texture), igVec2(64, 64)) # Or igVec2(image.width.float32, image.height.float32)
if igIsItemHovered() and app.config.website.len > 0:
igSetTooltip(cstring app.config.website & " " & FA_ExternalLink)
if igIsMouseClicked(ImGuiMouseButton.Left):
app.config.website.openURL()
igSameLine()
igPushTextWrapPos(250)
igTextWrapped(cstring app.config.comment)
igPopTextWrapPos()
igSpacing()
# To make it not clickable
igPushItemFlag(ImGuiItemFlags.Disabled, true)
igSelectable("Credits", true, makeFlags(ImGuiSelectableFlags.DontClosePopups))
igPopItemFlag()
if igBeginChild("##credits", igVec2(0, 75)):
for (author, url) in app.config.authors:
if igSelectable(cstring author) and url.len > 0:
url.openURL()
if igIsItemHovered() and url.len > 0:
igSetTooltip(cstring url & " " & FA_ExternalLink)
igEndChild()
igSpacing()
igText(cstring app.config.version)
if app.prefs.path.len > 0:
igSameLine()
igSetCursorPosX(igGetCurrentWindow().size.x - igCalcFrameSize("Open prefs file").x - igGetStyle().windowPadding.x)
if igButton("Open prefs file"):
openURL(app.prefs.path)
if igIsItemHovered():
igSetTooltip(cstring app.prefs.path & " " & FA_FileTextO)
igEndPopup()
proc drawMainMenuBar(app: var App) =
var openAbout, openPrefs, openBlockdialog = false
if igBeginMainMenuBar():
if igBeginMenu("File"):
igMenuItem("Settings " & FA_Cog, "Ctrl+P", openPrefs.addr)
if igMenuItem("Quit " & FA_Times, "Ctrl+Q"):
app.win.setWindowShouldClose(true)
igEndMenu()
if igBeginMenu("Edit"):
if igMenuItem("Hello"):
# If a messageBox hasn't been called or if a called messageBox has already been closed
if app.messageBoxResult.isNil or app.messageBoxResult.isReady():
app.messageBoxResult = spawn messageBox(app.config.name, "Hello, earthling. Wanna come with us?", DialogType.YesNo, IconType.Question, Button.Yes)
openBlockdialog = true
igEndMenu()
if igBeginMenu("About"):
if igMenuItem("Website " & FA_ExternalLink, enabled = app.config.website.len > 0):
app.config.website.openurl()
igMenuItem(cstring "About " & app.config.name, shortcut = nil, p_selected = openAbout.addr)
igEndMenu()
igEndMainMenuBar()
# See https://github.com/ocornut/imgui/issues/331#issuecomment-751372071
if openPrefs:
initCache(app.prefs[settings])
igOpenPopup("Settings")
if openAbout:
igOpenPopup("###about")
if openBlockdialog:
igOpenPopup("###blockdialog")
# These modals will only get drawn when igOpenPopup(name) are called, respectly
app.drawAboutModal()
app.drawSettingsmodal()
app.drawBlockDialogModal()
proc drawMain(app: var App) = # Draw the main window
let viewport = igGetMainViewport()
app.drawMainMenuBar()
# Work area is the entire viewport minus main menu bar, task bars, etc.
igSetNextWindowPos(viewport.workPos)
igSetNextWindowSize(viewport.workSize)
if igBegin(cstring app.config.name, flags = makeFlags(ImGuiWindowFlags.NoResize, NoDecoration, NoMove)):
igText(FA_Info & " Application average %.3f ms/frame (%.1f FPS)", 1000f / igGetIO().framerate, igGetIO().framerate)
if igButton("Click me"):
spawn notifyPopup(app.config.name, "Do not do that again", IconType.Warning)
app.fonts[1].igPushFont()
igText("Unicode fonts (NotoSansJP-Regular.otf)")
igText("日本語の言葉 " & FA_SmileO)
igPopFont()
if not app.messageBoxResult.isNil and app.messageBoxResult.isReady:
if ^app.messageBoxResult == Button.Yes:
igText("Glad you said yes!")
else:
igText("Prepare yourself for the consequences...")
igEnd()
proc render(app: var App) = # Called in the main loop
# Poll and handle events (inputs, window resize, etc.)
glfwPollEvents() # Use glfwWaitEvents() to only draw on events (more efficient)
# Start Dear ImGui Frame
igOpenGL3NewFrame()
igGlfwNewFrame()
igNewFrame()
# Draw application
app.drawMain()
# Render
igRender()
var displayW, displayH: int32
let bgColor = igColorConvertU32ToFloat4(uint32 WindowBg)
app.win.getFramebufferSize(displayW.addr, displayH.addr)
glViewport(0, 0, displayW, displayH)
glClearColor(bgColor.x, bgColor.y, bgColor.z, bgColor.w)
glClear(GL_COLOR_BUFFER_BIT)
igOpenGL3RenderDrawData(igGetDrawData())
app.win.makeContextCurrent()
app.win.swapBuffers()
proc initWindow(app: var App) =
glfwWindowHint(GLFWContextVersionMajor, 3)
glfwWindowHint(GLFWContextVersionMinor, 3)
glfwWindowHint(GLFWOpenglForwardCompat, GLFW_TRUE)
glfwWindowHint(GLFWOpenglProfile, GLFW_OPENGL_CORE_PROFILE)
glfwWindowHint(GLFWResizable, GLFW_TRUE)
if app.prefs[maximized]:
glfwWindowHint(GLFWMaximized, GLFW_TRUE)
app.win = glfwCreateWindow(
app.prefs[winsize].w,
app.prefs[winsize].h,
cstring app.config.name,
# glfwGetPrimaryMonitor(), # Show the window on the primary monitor
icon = false # Do not use default icon
)
if app.win == nil:
quit(-1)
# Set the window icon
var icon = initGLFWImage(app.res(app.config.iconPath).readImageFromMemory())
app.win.setWindowIcon(1, icon.addr)
# min width, min height, max widht, max height
app.win.setWindowSizeLimits(app.config.minSize.w, app.config.minSize.h, GLFW_DONT_CARE, GLFW_DONT_CARE)
# If negative pos, center the window in the first monitor
if app.prefs[winpos].x < 0 or app.prefs[winpos].y < 0:
var monitorX, monitorY, count, width, height: int32
let monitor = glfwGetMonitors(count.addr)[0]#glfwGetPrimaryMonitor()
let videoMode = monitor.getVideoMode()
monitor.getMonitorPos(monitorX.addr, monitorY.addr)
app.win.getWindowSize(width.addr, height.addr)
app.win.setWindowPos(
monitorX + int32((videoMode.width - width) / 2),
monitorY + int32((videoMode.height - height) / 2)
)
else:
app.win.setWindowPos(app.prefs[winpos].x, app.prefs[winpos].y)
proc initApp(): App =
when defined(release):
result.resources = readResources()
result.config = Config()
let filename =
when defined(release): "prefs"
else: "prefs_dev"
let path = (result.getConfigDir() / filename).changeFileExt("kdl")
try:
result.prefs = initKPrefs(
path = path,
default = initPrefs()
)
except KdlError:
let m = messageBox(result.config.name, &"Corrupt preferences file {path}.\nYou cannot continue using the app until it is fixed.\nYou may fix it manually or do you want to delete it and reset its content? You cannot undo this action", DialogType.OkCancel, IconType.Error, Button.No)
if m == Button.Yes:
discard tryRemoveFile(path)
result.prefs = initKPrefs(
path = path,
default = initPrefs()
)
else:
raise
result.updatePrefs()
template initFonts(app: var App) =
# Merge ForkAwesome icon font
let config = utils.newImFontConfig(mergeMode = true)
let iconFontGlyphRanges = [uint16 FA_Min, uint16 FA_Max]
for e, font in app.config.fonts:
let glyph_ranges =
case font.glyphRanges
of GlyphRanges.Default: io.fonts.getGlyphRangesDefault()
of ChineseFull: io.fonts.getGlyphRangesChineseFull()
of ChineseSimplified: io.fonts.getGlyphRangesChineseSimplifiedCommon()
of Cyrillic: io.fonts.getGlyphRangesCyrillic()
of Japanese: io.fonts.getGlyphRangesJapanese()
of Korean: io.fonts.getGlyphRangesKorean()
of Thai: io.fonts.getGlyphRangesThai()
of Vietnamese: io.fonts.getGlyphRangesVietnamese()
app.fonts[e] = io.fonts.igAddFontFromMemoryTTF(app.res(font.path), font.size, glyph_ranges = glyph_ranges)
# Here we add the icon font to every font
if app.config.iconFontPath.len > 0:
io.fonts.igAddFontFromMemoryTTF(app.res(app.config.iconFontPath), font.size, config.unsafeAddr, iconFontGlyphRanges[0].unsafeAddr)
proc terminate(app: var App) =
sync() # Wait for spawned threads
var x, y, width, height: int32
app.win.getWindowPos(x.addr, y.addr)
app.win.getWindowSize(width.addr, height.addr)
app.prefs[winpos] = (x, y)
app.prefs[winsize] = (width, height)
app.prefs[maximized] = app.win.getWindowAttrib(GLFWMaximized) == GLFW_TRUE
app.prefs.save()
proc main() =
var app = initApp()
# Setup Window
doAssert glfwInit()
app.initWindow()
app.win.makeContextCurrent()
glfwSwapInterval(1) # Enable vsync
doAssert glInit()
# Setup Dear ImGui context
igCreateContext()
let io = igGetIO()
io.iniFilename = nil # Disable .ini config file
# Setup Dear ImGui style using ImStyle
app.res(app.config.stylePath).parseKdl().loadStyle().setCurrent()
# Setup Platform/Renderer backends
doAssert igGlfwInitForOpenGL(app.win, true)
doAssert igOpenGL3Init()
app.initFonts()
# Main loop
while not app.win.windowShouldClose:
app.render()
# Cleanup
igOpenGL3Shutdown()
igGlfwShutdown()
igDestroyContext()
app.terminate()
app.win.destroyWindow()
glfwTerminate()
when isMainModule:
main()