13 const messageBuffer = 5
14 const reHighlight = `\b(%s)\b`
16 var ErrUserClosed = errors.New("user closed")
18 // User definition, implemented set Item interface and io.Writer
28 replyTo *User // Set when user gets a /msg, for replying.
33 func NewUser(identity Identifier) *User {
36 Config: *DefaultUserConfig,
38 msg: make(chan Message, messageBuffer),
39 done: make(chan struct{}, 1),
41 u.SetColorIdx(rand.Int())
46 func NewUserScreen(identity Identifier, screen io.WriteCloser) *User {
47 u := NewUser(identity)
53 // Rename the user with a new Identifier.
54 func (u *User) SetId(id string) {
55 u.Identifier.SetId(id)
56 u.SetColorIdx(rand.Int())
59 // ReplyTo returns the last user that messaged this user.
60 func (u *User) ReplyTo() *User {
64 // SetReplyTo sets the last user to message this user.
65 func (u *User) SetReplyTo(user *User) {
69 // ToggleQuietMode will toggle whether or not quiet mode is enabled
70 func (u *User) ToggleQuietMode() {
71 u.Config.Quiet = !u.Config.Quiet
74 // SetColorIdx will set the colorIdx to a specific value, primarily used for
76 func (u *User) SetColorIdx(idx int) {
80 // Block until user is closed
81 func (u *User) Wait() {
85 // Disconnect user, stop accepting messages
86 func (u *User) Close() {
87 u.closeOnce.Do(func() {
99 // Consume message buffer into an io.Writer. Will block, should be called in a
101 // TODO: Not sure if this is a great API.
102 func (u *User) Consume() {
103 for m := range u.msg {
108 // Consume one message and stop, mostly for testing
109 func (u *User) ConsumeOne() Message {
113 // SetHighlight sets the highlighting regular expression to match string.
114 func (u *User) SetHighlight(s string) error {
115 re, err := regexp.Compile(fmt.Sprintf(reHighlight, s))
119 u.Config.Highlight = re
123 func (u *User) render(m Message) string {
124 switch m := m.(type) {
126 return m.RenderFor(u.Config) + Newline
128 u.SetReplyTo(m.From())
129 return m.Render(u.Config.Theme) + Newline
131 return m.Render(u.Config.Theme) + Newline
135 // HandleMsg will render the message to the screen, blocking.
136 func (u *User) HandleMsg(m Message) error {
138 _, err := u.screen.Write([]byte(r))
140 logger.Printf("Write failed to %s, closing: %s", u.Name(), err)
146 // Add message to consume by user
147 func (u *User) Send(m Message) error {
153 logger.Printf("Msg buffer full, closing: %s", u.Name())
160 // Container for per-user configurations.
161 type UserConfig struct {
162 Highlight *regexp.Regexp
168 // Default user configuration to use
169 var DefaultUserConfig *UserConfig
172 DefaultUserConfig = &UserConfig{
177 // TODO: Seed random?