Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
diamondburned
GitHub Repository: diamondburned/gtkcord4
Path: blob/main/internal/messages/uploading.go
366 views
1
package messages
2
3
import (
4
"context"
5
"errors"
6
"fmt"
7
"io"
8
"strings"
9
10
"github.com/diamondburned/gotk4/pkg/glib/v2"
11
"github.com/diamondburned/gotk4/pkg/gtk/v4"
12
"github.com/diamondburned/gotk4/pkg/pango"
13
"github.com/diamondburned/gotkit/gtkutil/cssutil"
14
"github.com/diamondburned/gotkit/gtkutil/textutil"
15
)
16
17
type uploadingLabel struct {
18
*gtk.Label
19
err []error
20
cur int
21
max int
22
}
23
24
var uploadingLabelCSS = cssutil.Applier("message-uploading-label", `
25
.message-uploading-label {
26
opacity: 0.75;
27
font-size: 0.8em;
28
}
29
`)
30
31
func newUploadingLabel(ctx context.Context, count int) *uploadingLabel {
32
l := uploadingLabel{max: count}
33
l.Label = gtk.NewLabel("")
34
l.Label.SetXAlign(0)
35
l.Label.SetWrap(true)
36
l.Label.SetWrapMode(pango.WrapWordChar)
37
uploadingLabelCSS(l.Label)
38
39
l.invalidate()
40
return &l
41
}
42
43
// Done increments the done counter.
44
func (l *uploadingLabel) Done() {
45
l.cur++
46
l.invalidate()
47
}
48
49
// HasErrored returns true if the label contains any error.
50
func (l *uploadingLabel) HasErrored() bool { return len(l.err) > 0 }
51
52
// AppendError adds an error into the label.
53
func (l *uploadingLabel) AppendError(err error) {
54
l.err = append(l.err, err)
55
l.invalidate()
56
}
57
58
func (l *uploadingLabel) invalidate() {
59
var m string
60
if l.max > 0 {
61
m += fmt.Sprintf("<i>Uploaded %d/%d...</i>", l.cur, l.max)
62
}
63
for _, err := range l.err {
64
m += "\n" + textutil.ErrorMarkup(err.Error())
65
}
66
l.Label.SetMarkup(strings.TrimPrefix(m, "\n"))
67
}
68
69
type wrappedReader struct {
70
r io.Reader
71
l *uploadingLabel
72
}
73
74
func (r wrappedReader) Read(b []byte) (int, error) {
75
n, err := r.r.Read(b)
76
if err != nil {
77
glib.IdleAdd(func() {
78
if errors.Is(err, io.EOF) {
79
r.l.Done()
80
} else {
81
r.l.AppendError(err)
82
}
83
})
84
}
85
return n, err
86
}
87
88