-
Notifications
You must be signed in to change notification settings - Fork 23
/
volume.go
90 lines (72 loc) · 1.65 KB
/
volume.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
package commands
import (
"fmt"
"github.com/ambientsound/pms/api"
"github.com/ambientsound/pms/input/lexer"
)
var preMuteVolume int
// Volume adjusts MPD's volume.
type Volume struct {
newcommand
api api.API
sign int
volume int
finished bool
mute bool
}
// NewVolume returns Volume.
func NewVolume(api api.API) Command {
return &Volume{
api: api,
}
}
// Parse implements Command.
func (cmd *Volume) Parse() error {
playerStatus := cmd.api.PlayerStatus()
tok, lit := cmd.ScanIgnoreWhitespace()
cmd.setTabComplete(lit, []string{"mute"})
// Check for muted status.
if tok == lexer.TokenIdentifier && lit == "mute" {
cmd.mute = true
cmd.setTabCompleteEmpty()
return cmd.ParseEnd()
}
// If not muted, try to parse a number.
cmd.Unscan()
_, ilit, absolute, err := cmd.ParseInt()
if err != nil {
return err
}
if absolute {
cmd.volume = ilit
} else {
cmd.volume = int(playerStatus.Volume) + ilit
}
cmd.validateVolume()
cmd.setTabCompleteEmpty()
return cmd.ParseEnd()
}
// validateVolume clamps the volume to the allowable range
func (cmd *Volume) validateVolume() {
if cmd.volume > 100 {
cmd.volume = 100
} else if cmd.volume < 0 {
cmd.volume = 0
}
}
// Exec implements Command.
func (cmd *Volume) Exec() error {
mpdClient := cmd.api.MpdClient()
if mpdClient == nil {
return fmt.Errorf("Unable to set volume: cannot communicate with MPD")
}
playerStatus := cmd.api.PlayerStatus()
switch {
case cmd.mute && playerStatus.Volume == 0:
cmd.volume = preMuteVolume
case cmd.mute && playerStatus.Volume > 0:
preMuteVolume = playerStatus.Volume
cmd.volume = 0
}
return mpdClient.SetVolume(cmd.volume)
}