summaryrefslogtreecommitdiff
path: root/tag.go
blob: 642e8dd52658a971aed4858975b23cf3101fb7c5 (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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package main

import (
	"errors"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
	"log"
	"math"
	"random.chars.jp/git/image-board/store"
	"strings"
	"time"
)

var tagSearchBar *fyne.Container

func init() {
	tagSearchBar = func() *fyne.Container {
		var (
			submit *widget.Button
			entry  = widget.NewEntry()
		)
		entry.PlaceHolder = "Enter tags here"
		doSearch := func(s string) {
			if entry.Text == "" {
				return
			}
			tagSearch(strings.Split(s, " "), makeReturnFunc())
		}
		submit = widget.NewButton("Search", func() {
			submit.Disable()
			defer submit.Enable()

			doSearch(entry.Text)
		})
		entry.OnSubmitted = doSearch
		return container.NewBorder(nil, nil, nil, submit, entry, submit)
	}()
}

var tagMenu = &fyne.MenuItem{
	ChildMenu: &fyne.Menu{
		Label: "Tag",
		Items: []*fyne.MenuItem{
			{
				Label: "Search",
				Action: func() {
					go func() {
						t := tagSelectDialog(nil, true)
						if t != nil {
							tagSearch(t, makeReturnFunc())
						}
					}()
				},
			},
			{
				Label: "Create",
				Action: func() {
					go func() {
						if !privileged() {
							return
						}
						name := widget.NewEntry()
						tType := widget.NewSelect(store.AllowedTagTypes, nil)
						dialog.ShowForm("Create new tag", "Submit", "Cancel",
							[]*widget.FormItem{widget.NewFormItem("Tag Name", name), widget.NewFormItem("Type", tType)}, func(submit bool) {
								if !submit {
									return
								}
								if !store.MatchName(name.Text) {
									go dialog.ShowInformation("Invalid input", "Tag name invalid.", window)
									return
								}
								go func() {
									defer loading("Creating", "Waiting for server...")()
									s := time.Now()
									if err := remote.TagCreate(name.Text); err != nil {
										go dialog.ShowError(err, window)
										return
									} else if tType.Selected != "" {
										if err = remote.TagType(name.Text, tType.Selected); err != nil {
											go dialog.ShowError(err, window)
											return
										}
									} else {
										tType.Selected = store.GenericType
									}
									log.Printf("Created tag %s with type %s in %s.", name.Text, tType.Selected, time.Now().Sub(s))
									tags = append(tags, name.Text)
								}()
							}, window)
					}()
				},
			},
			{
				Label: "Edit/Delete",
				Action: func() {
					go func() {
						if !privileged() {
							return
						}
						ts := tagSelectDialog(nil, true)
						if ts == nil || len(ts) == 0 {
							return
						}
						tType := widget.NewSelect(store.AllowedTagTypes, nil)
						var diag dialog.Dialog
						del := widget.NewFormItem("Delete", widget.NewButton("Delete tags", func() {
							go func() {
								dialog.ShowConfirm("Confirmation", "Are you sure you want to destroy these tags?", func(okay bool) {
									if okay {
										go func() {
											defer loading("Destroying", "Waiting for server...")()
											for _, tag := range ts {
												s := time.Now()
												if err := remote.TagDestroy(tag); err != nil {
													dialog.ShowError(err, window)
													return
												}
												log.Printf("Tag %s destroyed in %s.", tag, time.Now().Sub(s))
											}
										}()
										diag.Hide()
									}
								}, window)
							}()
						}))
						diag = dialog.NewForm("Edit tags", "Submit", "Cancel", []*widget.FormItem{
							widget.NewFormItem("Selected tags", widget.NewLabel(strings.Join(ts, " "))),
							widget.NewFormItem("Tag type", tType),
							del,
						}, func(submit bool) {
							if !submit {
								return
							}
							if tType.Selected == "" {
								tType.Selected = store.GenericType
							}
							go func() {
								defer loading("Setting", "Waiting for server...")()
								for _, tag := range ts {
									s := time.Now()
									if err := remote.TagType(tag, tType.Selected); err != nil {
										go dialog.ShowError(err, window)
										return
									}
									log.Printf("Set type of tag %s to %s in %s.", tag, tType.Selected, time.Now().Sub(s))
								}
							}()
						}, window)
						diag.Show()
					}()
				},
			},
		},
	},
	Label: "Tag",
}

var tags []string
var (
	tagSearchQuery       string
	tagSearchResult      []string
	tagSearchResultImage [][store.PageSize]*store.Image
)

func tagRefresh() (err error) {
	defer loading("Loading", "Fetching tags...")()
	s := time.Now()
	tags, err = remote.Tags()
	log.Printf("Fetched tags in %s.", time.Now().Sub(s))
	return err
}

func tagSelectDialog(selected []string, diag bool) []string {
	t := make(map[string]bool, len(tags))
	for _, tag := range tags {
		t[tag] = false
	}
	for _, sel := range selected {
		t[sel] = true
	}

	var deselected []string
	for tag, sel := range t {
		if !sel {
			deselected = append(deselected, tag)
		}
	}
	deselectedRefresh := func() {
		var a []string
		for _, tag := range deselected {
			if !t[tag] {
				a = append(a, tag)
			}
		}
		deselected = a
	}

	l := widget.NewList(
		func() int {
			return len(selected)
		},
		nil,
		func(id widget.ListItemID, object fyne.CanvasObject) {
			object.(*widget.Button).SetText(selected[id])
		})
	r := widget.NewList(
		func() int {
			return len(deselected)
		},
		nil,
		func(id widget.ListItemID, object fyne.CanvasObject) {
			object.(*widget.Button).SetText(deselected[id])
		})
	l.CreateItem = func() fyne.CanvasObject {
		var b *widget.Button
		b = widget.NewButton("template", func() {
			b.Disable()
			defer b.Enable()

			t[b.Text] = false
			var a int
			for i, tag := range selected {
				if tag == b.Text {
					a = i
					break
				}
			}
			selected = append(selected[:a], selected[a+1:]...)
			deselected = append(deselected, b.Text)
			l.Refresh()
			r.Refresh()
		})
		return b
	}
	r.CreateItem = func() fyne.CanvasObject {
		var b *widget.Button
		b = widget.NewButton("template", func() {
			b.Disable()
			defer b.Enable()

			t[b.Text] = true
			selected = append(selected, b.Text)
			deselectedRefresh()
			l.Refresh()
			r.Refresh()
		})
		return b
	}

	sr := widget.NewEntry()
	sr.OnChanged = func(s string) {
		if s == "" {
			r.UnselectAll()
			l.UnselectAll()
			return
		}

		sel := false
		for i, tag := range deselected {
			if strings.Contains(tag, s) {
				r.Select(i)
				sel = true
				break
			}
		}
		if !sel {
			r.UnselectAll()
		}

		sel = false
		for i, tag := range selected {
			if strings.Contains(tag, s) {
				l.Select(i)
				break
			}
		}
		if !sel {
			l.UnselectAll()
		}
	}

	c := container.NewBorder(sr, nil, nil, nil, container.NewHSplit(
		container.NewBorder(widget.NewLabel("Selected"), nil, nil, nil, l),
		container.NewBorder(widget.NewLabel("Available"), nil, nil, nil, r),
	))
	s := make(chan bool)
	cb := func(submit bool) {
		s <- submit
	}

	size := fyne.Size{
		Width:  512,
		Height: 384,
	}

	if diag {
		d := dialog.NewCustomConfirm("Select Tags", "Confirm", "Cancel", c, cb, window)
		d.Resize(size)
		d.Show()
	} else {
		w := application.NewWindow("Select Tags")
		w.Resize(size)
		confirm := widget.NewButton("Confirm", func() {
			cb(true)
		})
		cancel := widget.NewButton("Cancel", func() {
			w.Close()
		})
		cnf := container.NewBorder(nil, nil, confirm, cancel)
		w.SetContent(container.New(layout.NewBorderLayout(nil, cnf, nil, nil), c, cnf))
		w.Show()
	}

	if !<-s {
		log.Print("Tag selection aborted.")
		return nil
	}
	log.Printf("Tags %s selected.", selected)
	return selected
}

func tagSearch(tags []string, back func()) {
	tagSearchQuery = tags[0]
	for i := 1; i < len(tags); i++ {
		tagSearchQuery += "!" + tags[i]
	}

	defer loading("Searching", "Fetching results...")()
	s := time.Now()
	if flakes, err := remote.ImageSearch(tags); err != nil {
		dialog.ShowError(err, window)
		return
	} else {
		tagSearchResult = flakes
		tagSearchResultImage = make([][store.PageSize]*store.Image,
			int(math.Ceil(float64(len(tagSearchResult))/store.PageSize)))
	}
	log.Printf("Retrieved search result for %s in %s.", tagSearchQuery, time.Now().Sub(s))

	go func() {
		if err := tagSearchPageSet(0, back); err != nil {
			dialog.ShowError(err, window)
		}
	}()
}

func tagSearchPageSet(page int, back func()) error {
	if page >= len(tagSearchResultImage) {
		return errors.New("no results were found")
	}
	if tagSearchResultImage[page][0] == nil {
		if err := func() error {
			done, value := progress("Loading", "Fetching images...")
			defer done()
			s := time.Now()
			for i := page * store.PageSize; i < (page+1)*store.PageSize; i++ {
				if i >= len(tagSearchResult) {
					break
				}
				if img, err := remote.Image(tagSearchResult[i]); err != nil {
					return err
				} else {
					tagSearchResultImage[page][i] = &img
					log.Printf("Fetched image %s.", img.Snowflake)
				}
				var length float64
				if (page+1)*store.PageSize >= len(tagSearchResult) {
					length = float64(len(tagSearchResult) - page*store.PageSize)
				} else {
					length = float64(store.PageSize)
				}
				value(float64(i-(page*store.PageSize)+1) / length)
			}
			log.Printf("Fetched search result page %v for %s in %s.", page, tagSearchQuery, time.Now().Sub(s))
			return nil
		}(); err != nil {
			return err
		}
	}

	var images []store.Image
	for _, image := range tagSearchResultImage[page] {
		if image != nil {
			images = append(images, *image)
		}
	}

	var gallery *fyne.Container
	if g, err := makeGallery(images); err != nil {
		return err
	} else {
		gallery = g
	}

	sc := container.NewVScroll(gallery)
	sc.SetMinSize(fyne.Size{
		Width:  116,
		Height: 200,
	})

	var fwd *widget.Button
	fwd = widget.NewButton("Previous", func() {
		fwd.Disable()
		if err := tagSearchPageSet(page-1, back); err != nil {
			dialog.ShowError(err, window)
		}
	})
	if page == 0 {
		fwd.Disable()
	}

	var aft *widget.Button
	aft = widget.NewButton("Next", func() {
		aft.Disable()
		if err := tagSearchPageSet(page+1, back); err != nil {
			dialog.ShowError(err, window)
		}
	})
	if page == len(tagSearchResultImage)-1 {
		aft.Disable()
	}

	p := container.NewBorder(nil, nil,
		fwd,
		aft,
	)
	var ret *widget.Button
	ret = widget.NewButton("Back", func() {
		ret.Disable()
		back()
	})
	msg := fmt.Sprintf("Displaying search results for query \"%s\"",
		strings.ReplaceAll(tagSearchQuery, "!", " "))
	if !strings.Contains(tagSearchQuery, "!") {
		log.Print("Single tag display, appending tag type.")
		s := time.Now()
		if info, err := remote.TagInfo(tagSearchQuery); err != nil {
			return err
		} else {
			msg += " (" + info.Type + ")"
		}
		log.Printf("Type of tag %s fetched in %s.", tagSearchQuery, time.Now().Sub(s))
	}
	b := container.NewBorder(nil, nil, ret,
		widget.NewLabel(msg+"."))

	setContent(container.New(layout.NewBorderLayout(b, p, nil, nil), b, p, sc))
	return nil
}