summaryrefslogtreecommitdiff
path: root/src/main.go
blob: 76f5af74fe4b935110073b42a1943d7617e478d2 (plain)
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/gotk3/gotk3/gdk"
	"github.com/gotk3/gotk3/glib"
	"github.com/gotk3/gotk3/gtk"
)

const (
	appTitle   = "kjagave"
	appVersion = "1.0"
)

type SavedColor struct {
	Hex  string `json:"hex"`
	Name string `json:"name"`
}

type App struct {
	window       *gtk.Window
	colorButton  *gtk.ColorButton
	currentColor *gdk.RGBA
	listStore    *gtk.ListStore
	treeView     *gtk.TreeView
	deleteBtn    *gtk.Button
	savedColors  []SavedColor
	configFile   string
	selectedIter *gtk.TreeIter
}

func main() {
	gtk.Init(nil)

	configDir := filepath.Join(os.Getenv("HOME"), ".config")
	os.MkdirAll(configDir, 0755)

	app := &App{
		configFile: filepath.Join(configDir, "kjagave.json"),
	}

	app.loadColors()
	app.createUI()
	app.populateList()

	gtk.Main()
}

func (app *App) createUI() {
	var err error

	// main window
	app.window, err = gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	app.window.SetTitle(appTitle)
	app.window.SetDefaultSize(550, 450)
	app.window.SetResizable(false)
	app.window.Connect("destroy", gtk.MainQuit)

	// vertical box
	mainBox, _ := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)
	mainBox.SetMarginTop(15)
	mainBox.SetMarginBottom(15)
	mainBox.SetMarginStart(15)
	mainBox.SetMarginEnd(15)

	// color selection area
	colorBox, _ := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 10)
	colorBox.SetHAlign(gtk.ALIGN_CENTER)

	label, _ := gtk.LabelNew("Select Color:")
	colorBox.PackStart(label, false, false, 0)

	// initialize color 
	app.currentColor = gdk.NewRGBA()
	app.currentColor.Parse("#69BAA7")

	app.colorButton, err = gtk.ColorButtonNewWithRGBA(app.currentColor)
	if err != nil {
		log.Fatal("Unable to create color button:", err)
	}
	app.colorButton.SetUseAlpha(true)
	app.colorButton.SetTitle("Choose a Color")
	app.colorButton.Connect("color-set", func() {
		app.currentColor = app.colorButton.GetRGBA()
	})

	colorBox.PackStart(app.colorButton, false, false, 0)

	hexEntry, _ := gtk.EntryNew()
	hexEntry.SetEditable(false)
	hexEntry.SetWidthChars(10)
	hexEntry.SetText(rgbaToHex(app.currentColor))
	colorBox.PackStart(hexEntry, false, false, 0)

	// color picker button
	pickerBtn, _ := gtk.ButtonNewWithLabel("Pick from Screen")
	pickerBtn.Connect("clicked", func() {
		if color, err := app.pickColorFromScreen(); err == nil {
			app.colorButton.SetRGBA(color)
			app.currentColor = color
			hexEntry.SetText(rgbaToHex(color))
		}
	})
	colorBox.PackStart(pickerBtn, false, false, 0)

	// bump hex entry when color changes
	app.colorButton.Connect("color-set", func() {
		app.currentColor = app.colorButton.GetRGBA()
		hexEntry.SetText(rgbaToHex(app.currentColor))
	})

	mainBox.PackStart(colorBox, false, false, 0)

	expander, _ := gtk.ExpanderNew("Saved Colors")
	expander.SetExpanded(true)
	expanderBox, _ := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 5)
	expanderBox.SetMarginTop(5)
	expanderBox.SetMarginBottom(5)
	btnBox, _ := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 5)
	btnBox.SetHAlign(gtk.ALIGN_END)
	app.deleteBtn, _ = gtk.ButtonNewWithLabel("Delete")
	app.deleteBtn.SetSensitive(false)
	app.deleteBtn.Connect("clicked", app.onDeleteClicked)
	btnBox.PackStart(app.deleteBtn, false, false, 0)
	saveBtn, _ := gtk.ButtonNewWithLabel("Save...")
	saveBtn.Connect("clicked", app.onSaveClicked)
	btnBox.PackStart(saveBtn, false, false, 0)
	expanderBox.PackStart(btnBox, false, false, 0)

	// treeview
	scrolled, _ := gtk.ScrolledWindowNew(nil, nil)
	scrolled.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
	scrolled.SetSizeRequest(-1, 180)

	app.listStore, _ = gtk.ListStoreNew(gdk.PixbufGetType(), glib.TYPE_STRING, glib.TYPE_STRING)
	app.treeView, _ = gtk.TreeViewNew()
	app.treeView.SetModel(app.listStore)
	app.treeView.SetHeadersVisible(true)

	// color column with swatch
	colorCol, _ := gtk.TreeViewColumnNew()
	colorCol.SetTitle("Color")
	colorCol.SetSortColumnID(1)

	pixbufRenderer, _ := gtk.CellRendererPixbufNew()
	colorCol.PackStart(pixbufRenderer, false)
	colorCol.AddAttribute(pixbufRenderer, "pixbuf", 0)

	textRenderer, _ := gtk.CellRendererTextNew()
	colorCol.PackStart(textRenderer, true)
	colorCol.AddAttribute(textRenderer, "text", 1)

	app.treeView.AppendColumn(colorCol)

	// name column
	nameRenderer, _ := gtk.CellRendererTextNew()
	nameCol, _ := gtk.TreeViewColumnNewWithAttribute("Name", nameRenderer, "text", 2)
	nameCol.SetSortColumnID(2)
	app.treeView.AppendColumn(nameCol)

	selection, _ := app.treeView.GetSelection()
	selection.SetMode(gtk.SELECTION_SINGLE)
	selection.Connect("changed", app.onSelectionChanged)

	scrolled.Add(app.treeView)
	expanderBox.PackStart(scrolled, true, true, 0)
	expander.Add(expanderBox)
	mainBox.PackStart(expander, true, true, 0)

	// bottom button box
	bottomBox, _ := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 5)
	bottomBox.SetHAlign(gtk.ALIGN_END)

	copyBtn, _ := gtk.ButtonNewWithLabel("Copy to Clipboard")
	copyBtn.Connect("clicked", app.onCopyClicked)
	bottomBox.PackStart(copyBtn, false, false, 0)

	aboutBtn, _ := gtk.ButtonNewWithLabel("About")
	aboutBtn.Connect("clicked", app.onAboutClicked)
	bottomBox.PackStart(aboutBtn, false, false, 0)

	mainBox.PackStart(bottomBox, false, false, 0)

	app.window.Add(mainBox)
	app.window.ShowAll()
}

func (app *App) populateList() {
	app.listStore.Clear()

	for _, color := range app.savedColors {
		pixbuf := app.createColorSwatch(color.Hex)
		iter := app.listStore.Append()
		app.listStore.Set(iter, []int{0, 1, 2}, []interface{}{pixbuf, color.Hex, color.Name})
	}
}

func (app *App) createColorSwatch(hexColor string) *gdk.Pixbuf {
	pixbuf, err := gdk.PixbufNew(gdk.COLORSPACE_RGB, false, 8, 16, 14)
	if err != nil {
		return nil
	}

	rgba := gdk.NewRGBA()
	rgba.Parse(hexColor)

	r := uint32(rgba.GetRed() * 255)
	g := uint32(rgba.GetGreen() * 255)
	b := uint32(rgba.GetBlue() * 255)

	pixels := pixbuf.GetPixels()
	rowstride := pixbuf.GetRowstride()
	nChannels := pixbuf.GetNChannels()

	for y := 0; y < 14; y++ {
		for x := 0; x < 16; x++ {
			offset := y*rowstride + x*nChannels
			pixels[offset] = byte(r)
			pixels[offset+1] = byte(g)
			pixels[offset+2] = byte(b)
		}
	}

	return pixbuf
}

func (app *App) onSelectionChanged(selection *gtk.TreeSelection) {
	model, iter, ok := selection.GetSelected()
	if !ok {
		app.deleteBtn.SetSensitive(false)
		app.selectedIter = nil
		return
	}

	app.selectedIter = iter
	app.deleteBtn.SetSensitive(true)

	value, _ := model.ToTreeModel().GetValue(iter, 1)
	hexColor, _ := value.GetString()

	rgba := gdk.NewRGBA()
	rgba.Parse(hexColor)
	app.colorButton.SetRGBA(rgba)
	app.currentColor = rgba
}

func (app *App) onSaveClicked() {
	dialog, _ := gtk.DialogNew()
	dialog.SetTitle("Save Color")
	dialog.SetTransientFor(app.window)
	dialog.SetModal(true)
	dialog.SetDefaultSize(300, -1)

	box, _ := dialog.GetContentArea()
	box.SetSpacing(10)
	box.SetMarginTop(10)
	box.SetMarginBottom(10)
	box.SetMarginStart(10)
	box.SetMarginEnd(10)

	// get current color
	hexColor := rgbaToHex(app.currentColor)

	label, _ := gtk.LabelNew(fmt.Sprintf("Color: %s", hexColor))
	box.PackStart(label, false, false, 0)

	entryLabel, _ := gtk.LabelNew("Color Name:")
	entryLabel.SetHAlign(gtk.ALIGN_START)
	box.PackStart(entryLabel, false, false, 0)

	entry, _ := gtk.EntryNew()
	entry.SetText("Untitled")
	entry.SetActivatesDefault(true)
	box.PackStart(entry, false, false, 0)

	dialog.AddButton("Cancel", gtk.RESPONSE_CANCEL)
	okBtn, _ := dialog.AddButton("OK", gtk.RESPONSE_OK)
	okBtn.SetCanDefault(true)
	okBtn.GrabDefault()

	dialog.ShowAll()

	response := dialog.Run()
	if response == gtk.RESPONSE_OK {
		text, _ := entry.GetText()
		app.savedColors = append([]SavedColor{{Hex: hexColor, Name: text}}, app.savedColors...)
		app.saveColors()
		app.populateList()
	}

	dialog.Destroy()
}

func (app *App) onDeleteClicked() {
	if app.selectedIter == nil {
		return
	}

	model := app.listStore.ToTreeModel()
	value, _ := model.GetValue(app.selectedIter, 1)
	hexColor, _ := value.GetString()

	// remove from saved colors
	for i, color := range app.savedColors {
		if color.Hex == hexColor {
			app.savedColors = append(app.savedColors[:i], app.savedColors[i+1:]...)
			break
		}
	}

	app.saveColors()
	app.populateList()
	app.deleteBtn.SetSensitive(false)
	app.selectedIter = nil
}

func (app *App) onCopyClicked() {
	hexColor := rgbaToHex(app.currentColor)

	clipboard, _ := gtk.ClipboardGet(gdk.SELECTION_CLIPBOARD)
	clipboard.SetText(hexColor)

	dialog := gtk.MessageDialogNew(app.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
		gtk.BUTTONS_OK, fmt.Sprintf("Color %s copied to clipboard!", hexColor))
	dialog.Run()
	dialog.Destroy()
}

func (app *App) onAboutClicked() {
	dialog, _ := gtk.AboutDialogNew()
	dialog.SetTransientFor(app.window)
	dialog.SetProgramName(appTitle)
	dialog.SetVersion(appVersion)
	dialog.SetComments("A color picker with screen color grabbing support")
	dialog.SetAuthors([]string{"kjagave 2025", "Based on gcolor2 by Ned Haughton"})
	dialog.SetLicense("GPL-2.0")
	dialog.Run()
	dialog.Destroy()
}

func (app *App) pickColorFromScreen() (*gdk.RGBA, error) {
	// use xcolor for x11 color picking
	cmd := exec.Command("xcolor", "--format", "hex")
	output, err := cmd.Output()
	if err != nil {
		// fallback to grabc
		cmd = exec.Command("grabc")
		output, err = cmd.Output()
		if err != nil {
			dialog := gtk.MessageDialogNew(app.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,
				gtk.BUTTONS_OK, "Color picker not found. Please install 'xcolor'")
			dialog.Run()
			dialog.Destroy()
			return nil, err
		}
	}

	hexColor := strings.TrimSpace(string(output))
	if !strings.HasPrefix(hexColor, "#") {
		hexColor = "#" + hexColor
	}

	rgba := gdk.NewRGBA()
	if !rgba.Parse(hexColor) {
		return nil, fmt.Errorf("invalid color format: %s", hexColor)
	}

	return rgba, nil
}

func (app *App) loadColors() {
	data, err := os.ReadFile(app.configFile)
	if err != nil {
		app.savedColors = []SavedColor{}
		return
	}

	if err := json.Unmarshal(data, &app.savedColors); err != nil {
		log.Printf("Error loading colors: %v", err)
		app.savedColors = []SavedColor{}
	}
}

func (app *App) saveColors() {
	data, err := json.MarshalIndent(app.savedColors, "", "  ")
	if err != nil {
		log.Printf("Error marshaling colors: %v", err)
		return
	}

	if err := os.WriteFile(app.configFile, data, 0644); err != nil {
		log.Printf("Error saving colors: %v", err)
	}
}

func rgbaToHex(rgba *gdk.RGBA) string {
	r := uint8(rgba.GetRed() * 255)
	g := uint8(rgba.GetGreen() * 255)
	b := uint8(rgba.GetBlue() * 255)
	return fmt.Sprintf("#%02X%02X%02X", r, g, b)
}