-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
358 lines (303 loc) · 7.43 KB
/
app.go
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// App struct
type App struct {
ctx context.Context
userDir string
UserLocale string `json:"userLocale"`
jsonFile []byte
jsonFileName string
jsonFilePath string
jsonFileSaved bool
DarkMode bool `json:"darkMode"`
}
// NewApp creates a new App application struct
func NewApp() *App {
a := &App{
jsonFileSaved: true,
UserLocale: "en",
DarkMode: false,
}
var err error
a.userDir, err = os.UserHomeDir()
if err != nil {
panic(err)
}
a.LoadSettings()
args := os.Args[1:]
if len(args) > 0 {
a.jsonFilePath = args[0]
a.jsonFileName = filepath.Base(a.jsonFilePath)
a.jsonFile, _ = os.ReadFile(a.jsonFilePath)
} else {
a.jsonFileName = "untitled file"
}
return a
}
// startup is called at application startup
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
initListeners(a)
runtime.WindowSetTitle(a.ctx, a.jsonFileName)
runtime.OnFileDrop(a.ctx, func(x, y int, paths []string) {
if len(paths) == 0 {
return
}
errs := make([]string, 0)
for _, p := range paths {
d, err := os.ReadFile(p)
if err != nil {
a.Alert(fmt.Sprintf("failed to open file %s", p), "Error")
}
if err = validateJSONFile(p, d); err != nil {
errs = append(errs, err.Error())
continue
}
a.New(d)
return
}
a.Alert(fmt.Sprintf("No json file found errors: %s", strings.Join(errs, "\n")), "ERROR")
})
}
func validateJSONFile(jsonFilePath string, fileData []byte) error {
fi, err := os.Stat(jsonFilePath)
if err != nil {
return err
}
if fi.IsDir() {
return errors.New("file is a directory")
}
if fi.Size() > 30_000_000 {
return fmt.Errorf("file size too big: %d", fi.Size())
}
if json.Valid(fileData) {
return nil
}
parts := strings.Split(jsonFilePath, ".")
if parts[len(parts)-1] == "json" && ((fileData[0] == '{' && fileData[len(fileData)-1] == '}') || (fileData[0] == '[' && fileData[len(fileData)-1] == ']')) {
return nil
}
return errors.New("not a json file")
}
// domReady is called after front-end resources have been loaded
func (a *App) domReady(ctx context.Context) {
runtime.EventsEmit(a.ctx, "change-lang", a.UserLocale)
}
// beforeClose is called when the application is about to quit,
// either by clicking the window close button or calling runtime.Quit.
// Returning true will cause the application to continue, false will continue shutdown as normal.
func (a *App) beforeClose(ctx context.Context) (prevent bool) {
return a.alertBeforeQuit()
}
// shutdown is called at application termination
func (a *App) shutdown(ctx context.Context) {
// Perform your teardown here
}
// alertBeforeQuit opens an alert / confirm dialog before quitting if the editor has unsaved changes.
func (a *App) alertBeforeQuit() bool {
if !a.jsonFileSaved {
res, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Title: "Alert, unsaved changes!",
Message: "You have unsaved changes, save before quit?",
Type: runtime.QuestionDialog,
Buttons: []string{
"Yes",
"No",
"Cancel",
},
})
if err != nil {
panic(err)
}
if res == "No" {
return false
}
if res == "Yes" {
return !a.Save()
}
if res == "Cancel" {
return true
}
}
return false
}
// GetCurrentFile returns the currently opened json file's contents.
func (a *App) GetCurrentFile() string {
return string(a.jsonFile)
}
// New creates an empty editor.
func (a *App) New(data []byte) bool {
res, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Title: "Alert, closing file!",
Message: "Are you sure to close the current file and create a new one?",
Type: runtime.QuestionDialog,
Buttons: []string{
"Yes",
"No",
},
})
if err != nil {
panic(err)
}
if res == "Yes" {
if data == nil {
data = []byte("{}")
}
a.jsonFile = data
a.jsonFileName = ""
a.jsonFilePath = ""
a.jsonFileSaved = true
runtime.WindowSetTitle(a.ctx, a.jsonFileName)
runtime.EventsEmit(a.ctx, "json-saved", a.jsonFileSaved)
runtime.EventsEmit(a.ctx, "json-data", string(a.jsonFile))
return true
}
return false
}
// Open loads a file from disk.
func (a *App) Open() bool {
prevent := a.alertBeforeQuit()
if prevent {
return false
}
var err error
newPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
DefaultDirectory: a.userDir,
Title: "select a json file",
Filters: []runtime.FileFilter{
{
DisplayName: "*.json",
Pattern: "*.json",
},
},
})
if err != nil {
runtime.EventsEmit(a.ctx, "error", err.Error())
}
if newPath != "" {
a.jsonFilePath = newPath
} else {
return false
}
a.jsonFileName = filepath.Base(a.jsonFilePath)
fileData, err := os.ReadFile(a.jsonFilePath)
if err != nil {
runtime.EventsEmit(a.ctx, "error", err.Error())
return false
}
if err = validateJSONFile(a.jsonFilePath, fileData); err != nil {
runtime.EventsEmit(a.ctx, "error", err.Error())
return false
}
a.jsonFile = fileData
a.jsonFileSaved = true
runtime.WindowSetTitle(a.ctx, a.jsonFileName)
runtime.EventsEmit(a.ctx, "json-saved", a.jsonFileSaved)
runtime.EventsEmit(a.ctx, "json-data", string(a.jsonFile))
return true
}
// Save stores the currently opened json file on disk.
func (a *App) Save() bool {
var (
jPath string
err error
)
if a.jsonFilePath == "" {
jPath, err = runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
DefaultDirectory: a.userDir,
Title: "select a json file",
Filters: []runtime.FileFilter{
{
DisplayName: "*.json",
Pattern: "*.json",
},
},
})
if err != nil {
runtime.EventsEmit(a.ctx, "error", err.Error())
}
if jPath == "" {
return false
}
a.jsonFilePath = jPath
}
err = os.WriteFile(a.jsonFilePath, a.jsonFile, 0644)
if err != nil {
runtime.EventsEmit(a.ctx, "error", err.Error())
return false
}
a.jsonFileName = filepath.Base(a.jsonFilePath)
a.jsonFileSaved = true
runtime.EventsEmit(a.ctx, "json-saved", a.jsonFileSaved)
runtime.WindowSetTitle(a.ctx, a.jsonFileName)
return true
}
// Alert shows an alert dialog.
func (a *App) Alert(message string, title string) {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.WarningDialog,
Title: title,
Message: message,
})
}
// LoadSettings loads the app's configs from disk.
func (a *App) LoadSettings() {
fp := path.Join(a.userDir, ".jsoneditor-settings")
if _, err := os.Stat(fp); err != nil {
return
}
d, err := os.ReadFile(fp)
if err != nil {
panic(err)
}
nA := App{
ctx: a.ctx,
userDir: a.userDir,
jsonFile: a.jsonFile,
jsonFileName: a.jsonFileName,
jsonFilePath: a.jsonFilePath,
jsonFileSaved: a.jsonFileSaved,
UserLocale: a.UserLocale,
DarkMode: a.DarkMode,
}
err = json.Unmarshal(d, &nA)
if err != nil {
panic(err)
}
*a = nA
}
// SaveSettings stores the app's settings on disk.
func (a *App) SaveSettings() {
d, err := json.Marshal(a)
if err != nil {
panic(err)
}
f, err := os.Create(path.Join(a.userDir, ".jsoneditor-settings"))
if err != nil {
panic(err)
}
defer f.Close()
_, err = f.Write(d)
if err != nil {
log.Fatal(err)
}
}
// GetLocale returns the app's currently selected locale.
func (a *App) GetLocale() string {
return a.UserLocale
}
// GetDarkMode returns if the app is in dark mode or not.
func (a *App) GetDarkMode() bool {
return a.DarkMode
}