-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
397 lines (322 loc) · 12 KB
/
main.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package main
import (
"fmt"
"os"
"path/filepath"
"unsafe"
"github.com/barasher/go-exiftool"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
"github.com/joho/godotenv"
"github.com/sirupsen/logrus"
)
const BOX_SPACING int = 2
const LABEL_MARGIN = 10
var RAW_SUFFIXES = []string{"360", "3fr", "3g2", "3gp", "3gp2", "3gpp", "7z", "a", "aa", "aae", "aax", "acfm", "acr", "afm", "ai", "aif", "aifc", "aiff", "ait", "amfm", "ape", "apng", "arq", "arw", "asf", "avi", "avif", "azw", "azw3", "bmp", "bpg", "btf", "chm", "ciff", "cos", "cr2", "cr3", "crm", "crw", "cs1", "csv", "cur", "czi", "dc3", "dcm", "dcp", "dcr", "dfont", "dib", "dic", "dicm", "divx", "djv", "djvu", "dll", "dng", "doc", "docm", "docx", "dot", "dotm", "dotx", "dpx", "dr4", "ds2", "dss", "dv", "dvb", "dvr-ms", "dylib", "eip", "eps", "eps2", "eps3", "epsf", "epub", "erf", "exe", "exif", "exr", "exv", "f4a", "f4b", "f4p", "f4v", "fff", "fit", "fits", "fla", "flac", "flif", "flir", "flv", "fpf", "fpx", "gif", "glv", "gpr", "gz", "gzip", "hdp", "hdr", "heic", "heif", "hif", "htm", "html", "ical", "icc", "icm", "ico", "ics", "idml", "iiq", "ind", "indd", "indt", "insp", "insv", "inx", "iso", "itc", "j2c", "j2k", "jng", "jp2", "jpc", "jpe", "jpf", "jpm", "jps", "jpx", "json", "jxl", "jxr", "k25", "kdc", "key", "kth", "la", "lfp", "lfr", "lif", "lnk", "lrv", "m2t", "m2ts", "m2v", "m4a", "m4b", "m4p", "m4v", "macos", "max", "mef", "mie", "mif", "miff", "mka", "mks", "mkv", "mng", "mobi", "modd", "moi", "mos", "mov", "mp3", "mp4", "mpc", "mpeg", "mpg", "mpo", "mqv", "mrc", "mrw", "mts", "mxf", "nef", "newer", "nksc", "nmbtemplate", "nrw", "numbers", "o", "odb", "odc", "odf", "odg", "odi", "odp", "ods", "odt", "ofr", "ogg", "ogv", "onp", "opus", "orf", "ori", "otf", "pac", "pages", "pbm", "pcd", "pct", "pcx", "pdb", "pdf", "pef", "pfa", "pfb", "pfm", "pgf", "pgm", "pict", "plist", "pmp", "pot", "potm", "potx", "ppam", "ppax", "ppm", "pps", "ppsm", "ppsx", "ppt", "pptm", "pptx", "prc", "ps", "ps2", "ps3", "psb", "psd", "psdt", "psp", "pspframe", "pspimage", "pspshape", "psptube", "qif", "qt", "qti", "qtif", "r3d", "ra", "raf", "ram", "rar", "raw", "rif", "riff", "rm", "rmvb", "rpm", "rsrc", "rtf", "rv", "rw2", "rwl", "rwz", "seq", "sketch", "so", "sr2", "srf", "srw", "svg", "swf", "thm", "thmx", "tif", "tiff", "torrent", "ts", "ttc", "ttf", "tub", "txt", "vcard", "vcf", "vnt", "vob", "vrd", "vsd", "wav", "wdp", "webm", "webp", "wma", "wmv", "woff", "woff2", "wpg", "wtv", "wv", "x3f", "xcf", "xhtml", "xla", "xlam", "xls", "xlsb", "xlsm", "xlsx", "xlt", "xltm", "xltx", "xmp", "zip"}
var DISPLAY_SUFFIXES = []string{"jpg", "jpeg", "png"}
const DEFAULT_PATH = "~/Pictures"
var log = logrus.New()
var (
et *exiftool.Exiftool
imageDirectory string
imageRawToDispMap map[string]string
currRAWImagePath string
application *gtk.Application
win *gtk.ApplicationWindow
box *gtk.Box
listView *ListView
infoViewFrame *gtk.Frame
infoView *InfoView
imageView *ImageView
header *gtk.HeaderBar
err error
)
func main() {
imageDirectory = DEFAULT_PATH
err = godotenv.Load(".env")
if err == nil {
newImageDirectory := os.Getenv("START_FOLDER")
if imageDirectory != "" {
imageDirectory = newImageDirectory
}
} else {
log.Info("No .env file found")
}
log.Out = os.Stderr
formatter := new(logrus.TextFormatter)
formatter.FullTimestamp = true
formatter.TimestampFormat = "2006-01-02 15:04:05"
formatter.DisableLevelTruncation = true
formatter.QuoteEmptyFields = true
log.SetFormatter(formatter)
if os.Getenv("DEBUG") == "true" {
log.SetLevel(logrus.DebugLevel)
} else if os.Getenv("INFO") == "true" {
log.SetLevel(logrus.InfoLevel)
} else {
log.SetLevel(logrus.WarnLevel)
}
// log = logging.MustGetLogger("raw-rating")
// format := logging.MustStringFormatter(
// `%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.1s}-%{id:03x} ▶ %{color:reset} %{message}`,
// )
// backend := logging.NewLogBackend(os.Stderr, "", 0)
// backendFormatter := logging.NewBackendFormatter(backend, format)
// backendLeveled := logging.AddModuleLevel(backend)
// backendLeveled.SetLevel(logging.ERROR, "raw-rating")
// // logging.SetLevel(logging.ERROR, "raw-rating")
// logging.SetBackend(backendLeveled, backendFormatter)
const appID = "com.github.jjj120.raw-rating"
application, err = gtk.ApplicationNew(appID, glib.APPLICATION_HANDLES_OPEN)
check_error("Could not create application:", err)
application.Connect("open", handleOpen)
et, err = exiftool.NewExiftool()
if err != nil {
check_error("Error when intializing", err)
return
}
defer et.Close()
application.Connect("activate", func() {
win := setupWindow(application)
aNew := glib.SimpleActionNew("new", nil)
aNew.Connect("activate", func() {
setupWindow(application).ShowAll()
})
application.AddAction(aNew)
aQuit := glib.SimpleActionNew("quit", nil)
aQuit.Connect("activate", func() {
application.Quit()
})
application.AddAction(aQuit)
win.ShowAll()
})
os.Exit(application.Run(os.Args))
}
func handleOpen(app *gtk.Application, filePtrs unsafe.Pointer, count int, hint string) {
// inspired by https://github.com/gotk3/gotk3/issues/787#issue-912938376
ptr := (*unsafe.Pointer)(unsafe.Pointer(uintptr(filePtrs) + unsafe.Sizeof(uintptr(0))*uintptr(0)))
f := &glib.File{
Object: &glib.Object{
GObject: glib.ToGObject(*ptr),
},
}
filePath := f.GetPath()
if filePath == "" {
log.Warn("No file path provided")
app.Activate()
return
}
newImageDirOk := true
newImageDirectory := filePath
newImageDirectory, err := filepath.Abs(newImageDirectory)
if err != nil {
check_error("Failed to get absolute path", err)
newImageDirOk = false
}
if newImageDirOk {
imageDirInfo, err := os.Stat(newImageDirectory)
if err != nil {
check_error("Failed to stat directory", err)
newImageDirOk = false
}
if newImageDirOk && !imageDirInfo.IsDir() {
log.Infof("Provided path is not a directory: %s\n", newImageDirectory)
newImageDirOk = false
}
}
if newImageDirOk {
imageDirectory = newImageDirectory
}
app.Activate()
}
func check_error(message string, err error) {
if err != nil {
log.Panic(message, " - ", err)
}
}
func setupWindow(application *gtk.Application) *gtk.ApplicationWindow {
win, err = gtk.ApplicationWindowNew(application)
check_error("Unable to create window", err)
win.SetTitle("RAW Rating")
infoViewFrame, infoView = setupInfoView()
refreshInfoView()
listView = setupListView()
refreshListView()
imageView = setupImageView()
refreshImageView()
listView.listBox.Connect("row-selected", func(box *gtk.ListBox, row *gtk.ListBoxRow) {
if row != nil {
// Call the function to get the label text from the selected row
text := getLabelTextFromRow(row)
currRAWImagePath = imageDirectory + "/" + text
refreshImageChanged()
} else {
// clear all data of the application
// println("resetup application because of none selection")
// setupWindow(application)
}
})
// Create a horizontal box to hold the left and right elements
box, err = gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 10)
check_error("Unable to create horizontal box:", err)
// Create a vertical box for the left elements
vBox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)
check_error("Unable to create vertical box:", err)
// Add the top-left element
vBox.PackStart(infoViewFrame, false, false, 10)
// Add the bottom-left element
vBox.PackStart(listView.scrolledWindow, true, true, 10)
// Add the vertical box and the right label to the horizontal box
box.PackStart(vBox, false, false, 10)
box.PackStart(imageView.box, true, true, 10)
// Connect to key presses
win.Connect("key-press-event", keyPress)
// Add the horizontal box to the window
win.Add(box)
setupHeaderBar()
win.SetTitlebar(header)
win.SetPosition(gtk.WIN_POS_MOUSE)
win.SetDefaultSize(1200, 800)
return win
}
func setupHeaderBar() {
// Create a header bar
header, err = gtk.HeaderBarNew()
check_error("Could not create header bar", err)
header.SetShowCloseButton(true)
header.SetTitle("RAW Rating")
// header.SetSubtitle("Actions Example")
// Create a new menu button
mbtn, err := gtk.MenuButtonNew()
check_error("Could not create menu button", err)
// Set up the menu model for the button
menu := glib.MenuNew()
if menu == nil {
log.Fatal("Could not create menu (nil)")
}
// Actions with the prefix 'app' reference actions on the application
// Actions with the prefix 'win' reference actions on the current window (specific to ApplicationWindow)
// Other prefixes can be added to widgets via InsertActionGroup
menu.Append("New Window", "app.new")
menu.Append("Open Directory", "custom.open_dir")
menu.Append("Close Window", "win.close")
menu.Append("Quit", "app.quit")
// Create the action "win.close"
aClose := glib.SimpleActionNew("close", nil)
aClose.Connect("activate", func() {
win.Close()
})
win.AddAction(aClose)
// Create and insert custom action group with prefix "custom"
customActionGroup := glib.SimpleActionGroupNew()
win.InsertActionGroup("custom", customActionGroup)
// Create an action in the custom action group
aOpenDir := glib.SimpleActionNew("open_dir", nil)
aOpenDir.Connect("activate", func() {
fileChooser, err := gtk.FileChooserDialogNewWith1Button(
"Choose the image directory",
win,
gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
"Select",
gtk.RESPONSE_ACCEPT,
)
if err != nil {
log.Fatal("Unable to create file chooser dialog:", err)
}
// Run the file chooser dialog and check for the response
response := fileChooser.Run()
if response == gtk.RESPONSE_ACCEPT {
imageDirectory = fileChooser.GetFilename()
log.Debug("Selected image dir: ", imageDirectory)
refreshAll()
}
// Destroy the file chooser dialog after use
fileChooser.Destroy()
})
customActionGroup.AddAction(aOpenDir)
win.AddAction(aOpenDir)
mbtn.SetMenuModel(&menu.MenuModel)
// add the menu button to the header
header.PackStart(mbtn)
}
// filesSelected: callback function for "file-set" signal
func refreshAll() {
refreshImageView()
refreshInfoView()
refreshListView()
win.ShowAll()
}
func refreshImageChanged() {
//refresh views (but not file list)
refreshImageView()
refreshInfoView()
win.ShowAll()
}
func keyPress(win *gtk.ApplicationWindow, event *gdk.Event) {
// button press event handler
keyEvent := gdk.EventKeyNewFromEvent(event)
keyVal := keyEvent.KeyVal()
switch keyVal {
case gdk.KEY_Escape:
win.Close()
case gdk.KEY_q:
win.Close()
case gdk.KEY_0:
changeRating(0)
case gdk.KEY_1:
changeRating(1)
case gdk.KEY_2:
changeRating(2)
case gdk.KEY_3:
changeRating(3)
case gdk.KEY_4:
changeRating(4)
case gdk.KEY_5:
changeRating(5)
case gdk.KEY_Left:
prevImage()
case gdk.KEY_Right:
nextImage()
case gdk.KEY_Up:
prevImage()
case gdk.KEY_Down:
nextImage()
default:
log.Debug("Key pressed: ", keyVal)
}
win.ShowAll()
}
func nextImage() {
// change to the next image
incrementImageBy(1)
}
func prevImage() {
// change to the previous image
incrementImageBy(-1)
}
func incrementImageBy(increment int) {
selectedRow := listView.listBox.GetSelectedRow()
if selectedRow != nil {
selectedIndex := selectedRow.GetIndex()
nextIndex := selectedIndex + increment
if nextIndex >= 0 && nextIndex < int(listView.listBox.GetChildren().Length()) {
listView.listBox.SelectRow(listView.listBox.GetRowAtIndex(nextIndex))
}
} else if listView.listBox.GetChildren().Length() > 0 {
// if there is no selected row, select the first row
firstRow := listView.listBox.GetRowAtIndex(0)
listView.listBox.SelectRow(firstRow)
}
}
func changeRating(rating int) {
// change rating of the current image
log.Debug("Change rating of ", currRAWImagePath, " to ", rating)
rawArgs := et.ExtractMetadata(currRAWImagePath)
rawArgs[0].SetString("Rating", fmt.Sprintf("%d", rating))
et.WriteMetadata(rawArgs)
dispArgs := et.ExtractMetadata(imageRawToDispMap[currRAWImagePath])
dispArgs[0].SetString("Rating", fmt.Sprintf("%d", rating))
et.WriteMetadata(dispArgs)
refreshInfoView()
}