]> code.delx.au - gnu-emacs/blob - lisp/mpc.el
Add commands for controlling MPD modes
[gnu-emacs] / lisp / mpc.el
1 ;;; mpc.el --- A client for the Music Player Daemon -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2006-2015 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: multimedia
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This is an Emacs front end to the Music Player Daemon.
26
27 ;; It mostly provides a browser inspired from Rhythmbox for your music
28 ;; collection and also allows you to play the music you select. The basic
29 ;; interface is somewhat unusual in that it does not focus on the
30 ;; playlist as much as on the browser.
31 ;; I play albums rather than songs and thus don't have much need for
32 ;; playlists, and it shows. Playlist support exists, but is still limited.
33
34 ;; Bugs:
35
36 ;; - when reaching end/start of song while ffwd/rewind, it may get wedged,
37 ;; signal an error, ... or when mpc-next/prev is called while ffwd/rewind.
38 ;; - MPD errors are not reported to the user.
39
40 ;; Todo:
41
42 ;; - add bindings/buttons/menuentries for the various commands.
43 ;; - mpc-undo
44 ;; - visual feedback for drag'n'drop
45 ;; - display/set `repeat' and `random' state (and maybe also `crossfade').
46 ;; - allow multiple *mpc* sessions in the same Emacs to control different mpds.
47 ;; - fetch album covers and lyrics from the web?
48 ;; - improve MPC-Status: better volume control, add a way to show/hide the
49 ;; rest, plus add the buttons currently in the toolbar.
50 ;; - improve mpc-songs-mode's header-line column-headings so they can be
51 ;; dragged to resize.
52 ;; - allow selecting several entries by drag-mouse.
53 ;; - poll less often
54 ;; - use the `idle' command
55 ;; - do the time-ticking locally (and sync every once in a while)
56 ;; - look at the end of play time to make sure we notice the end
57 ;; as soon as possible
58 ;; - better volume widget.
59 ;; - add synthesized tags.
60 ;; e.g. pseudo-artist = artist + composer + performer.
61 ;; e.g. pseudo-performer = performer or artist
62 ;; e.g. rewrite artist "Foo bar & baz" to "Foo bar".
63 ;; e.g. filename regexp -> compilation flag
64 ;; - window/buffer management.
65 ;; - menubar, tooltips, ...
66 ;; - add mpc-describe-song, mpc-describe-album, ...
67 ;; - add import/export commands (especially export to an MP3 player).
68 ;; - add a real notion of album (as opposed to just album-name):
69 ;; if all songs with same album-name have same artist -> it's an album
70 ;; else it's either several albums or a compilation album (or both),
71 ;; in which case we could use heuristics or user provided info:
72 ;; - if the user followed the 1-album = 1-dir idea, then we can group songs
73 ;; by their directory to create albums.
74 ;; - if a `compilation' flag is available, and if <=1 of the songs have it
75 ;; set, then we can group songs by their artist to create albums.
76 ;; - if two songs have the same track-nb and disk-nb, they're not in the
77 ;; same album. So from the set of songs with identical album names, we
78 ;; can get a lower bound on the number of albums involved, and then see
79 ;; which of those may be non-compilations, etc...
80 ;; - use a special directory name for compilations.
81 ;; - ask the web ;-)
82
83 ;;; Code:
84
85 ;; Prefixes used in this code:
86 ;; mpc-proc : management of connection (in/out formatting, ...)
87 ;; mpc-status : auto-updated status info
88 ;; mpc-volume : stuff handling the volume widget
89 ;; mpc-cmd : mpdlib abstraction
90
91 ;; UI-commands : mpc-
92 ;; internal : mpc--
93
94 (eval-when-compile
95 (require 'cl-lib)
96 (require 'subr-x))
97
98 (defgroup mpc ()
99 "Client for the Music Player Daemon (mpd)."
100 :prefix "mpc-"
101 :group 'multimedia
102 :group 'applications)
103
104 (defcustom mpc-browser-tags '(Genre Artist|Composer|Performer
105 Album|Playlist)
106 "Tags for which a browser buffer should be created by default."
107 ;; FIXME: provide a list of tags, for completion.
108 :type '(repeat symbol))
109
110 ;;; Misc utils ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
111
112 (defun mpc-assq-all (key alist)
113 (let ((res ()) val)
114 (dolist (elem alist)
115 (if (and (eq (car elem) key)
116 (not (member (setq val (cdr elem)) res)))
117 (push val res)))
118 (nreverse res)))
119
120 (defun mpc-union (&rest lists)
121 (let ((res (nreverse (pop lists))))
122 (dolist (list lists)
123 (let ((seen res)) ;Don't remove duplicates within each list.
124 (dolist (elem list)
125 (unless (member elem seen) (push elem res)))))
126 (nreverse res)))
127
128 (defun mpc-intersection (l1 l2 &optional selectfun)
129 "Return L1 after removing all elements not found in L2.
130 If SELECTFUN is non-nil, elements aren't compared directly, but instead
131 they are passed through SELECTFUN before comparison."
132 (let ((res ()))
133 (if selectfun (setq l2 (mapcar selectfun l2)))
134 (dolist (elem l1)
135 (when (member (if selectfun (funcall selectfun elem) elem) l2)
136 (push elem res)))
137 (nreverse res)))
138
139 (defun mpc-event-set-point (event)
140 (condition-case nil (posn-set-point (event-end event))
141 (error (condition-case nil (mouse-set-point event)
142 (error nil)))))
143
144 (defun mpc-compare-strings (str1 str2 &optional ignore-case)
145 "Compare strings STR1 and STR2.
146 Contrary to `compare-strings', this tries to get numbers sorted
147 numerically rather than lexicographically."
148 (let ((res (compare-strings str1 nil nil str2 nil nil ignore-case)))
149 (if (not (integerp res)) res
150 (let ((index (1- (abs res))))
151 (if (or (>= index (length str1)) (>= index (length str2)))
152 res
153 (let ((digit1 (memq (aref str1 index)
154 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9)))
155 (digit2 (memq (aref str2 index)
156 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9))))
157 (if digit1
158 (if digit2
159 (let ((num1 (progn (string-match "[0-9]+" str1 index)
160 (match-string 0 str1)))
161 (num2 (progn (string-match "[0-9]+" str2 index)
162 (match-string 0 str2))))
163 (cond
164 ;; Here we presume that leading zeroes are only used
165 ;; for same-length numbers. So we'll incorrectly
166 ;; consider that "000" comes after "01", but I don't
167 ;; think it matters.
168 ((< (length num1) (length num2)) (- (abs res)))
169 ((> (length num1) (length num2)) (abs res))
170 ((< (string-to-number num1) (string-to-number num2))
171 (- (abs res)))
172 (t (abs res))))
173 ;; "1a" comes before "10", but "0" comes before "a".
174 (if (and (not (zerop index))
175 (memq (aref str1 (1- index))
176 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9)))
177 (abs res)
178 (- (abs res))))
179 (if digit2
180 ;; "1a" comes before "10", but "0" comes before "a".
181 (if (and (not (zerop index))
182 (memq (aref str1 (1- index))
183 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9)))
184 (- (abs res))
185 (abs res))
186 res))))))))
187
188 (define-obsolete-function-alias 'mpc-string-prefix-p 'string-prefix-p "24.3")
189
190 ;; This can speed up mpc--song-search significantly. The table may grow
191 ;; very large, tho. It's only bounded by the fact that it gets flushed
192 ;; whenever the connection is established; which seems to work OK thanks
193 ;; to the fact that MPD tends to disconnect fairly often, although our
194 ;; constant polling often prevents disconnection.
195 (defvar mpc--find-memoize (make-hash-table :test 'equal)) ;; :weakness t
196 (defvar-local mpc-tag nil)
197
198 ;;; Support for the actual connection and MPD command execution ;;;;;;;;;;;;
199
200 (defcustom mpc-host
201 (concat (or (getenv "MPD_HOST") "localhost")
202 (if (getenv "MPD_PORT") (concat ":" (getenv "MPD_PORT"))))
203 "Host (and port) where the Music Player Daemon is running. The
204 format is \"HOST\", \"HOST:PORT\", \"PASSWORD@HOST\" or
205 \"PASSWORD@HOST:PORT\" where PASSWORD defaults to no password, PORT
206 defaults to 6600 and HOST defaults to localhost."
207 :type 'string)
208
209 (defvar mpc-proc nil)
210
211 (defconst mpc--proc-end-re "^\\(?:OK\\(?: MPD .*\\)?\\|ACK \\(.*\\)\\)\n")
212
213 (define-error 'mpc-proc-error "MPD error")
214
215 (defun mpc--debug (format &rest args)
216 (if (get-buffer "*MPC-debug*")
217 (with-current-buffer "*MPC-debug*"
218 (goto-char (point-max))
219 (insert-before-markers ;So it scrolls.
220 (replace-regexp-in-string "\n" "\n "
221 (apply #'format-message format args))
222 "\n"))))
223
224 (defun mpc--proc-filter (proc string)
225 (mpc--debug "Receive \"%s\"" string)
226 (with-current-buffer (process-buffer proc)
227 (if (process-get proc 'ready)
228 (if nil ;; (string-match "\\`\\(OK\n\\)+\\'" string)
229 ;; I haven't figured out yet why I get those extraneous OKs,
230 ;; so I'll just ignore them for now.
231 nil
232 (delete-process proc)
233 (set-process-buffer proc nil)
234 (pop-to-buffer (clone-buffer))
235 (error "MPD output while idle!?"))
236 (save-excursion
237 (let ((start (or (marker-position (process-mark proc)) (point-min))))
238 (goto-char start)
239 (insert string)
240 (move-marker (process-mark proc) (point))
241 (beginning-of-line)
242 (when (and (< start (point))
243 (re-search-backward mpc--proc-end-re start t))
244 (process-put proc 'ready t)
245 (unless (eq (match-end 0) (point-max))
246 (error "Unexpected trailing text"))
247 (let ((error-text (match-string 1)))
248 (delete-region (point) (point-max))
249 (let ((callback (process-get proc 'callback)))
250 (process-put proc 'callback nil)
251 (if error-text
252 (process-put proc 'mpc-proc-error error-text))
253 (funcall callback)))))))))
254
255 (defun mpc--proc-connect (host)
256 (let ((port 6600)
257 local
258 pass)
259
260 (when (string-match "\\`\\(?:\\(.*\\)@\\)?\\(.*?\\)\\(?::\\(.*\\)\\)?\\'"
261 host)
262 (let ((v (match-string 1 host)))
263 (when (and (stringp v) (not (string= "" v)))
264 (setq pass v)))
265 (let ((v (match-string 3 host)))
266 (setq host (match-string 2 host))
267 (when (and (stringp v) (not (string= "" v)))
268 (setq port
269 (if (string-match "[^[:digit:]]" v)
270 (string-to-number v)
271 v)))))
272 (when (file-name-absolute-p host)
273 ;; Expand file name because `file-name-absolute-p'
274 ;; considers paths beginning with "~" as absolute
275 (setq host (expand-file-name host))
276 (setq local t))
277
278 (mpc--debug "Connecting to %s:%s..." host port)
279 (with-current-buffer (get-buffer-create (format " *mpc-%s:%s*" host port))
280 ;; (pop-to-buffer (current-buffer))
281 (let (proc)
282 (while (and (setq proc (get-buffer-process (current-buffer)))
283 (progn ;; (debug)
284 (delete-process proc)))))
285 (erase-buffer)
286 (let* ((coding-system-for-read 'utf-8-unix)
287 (coding-system-for-write 'utf-8-unix)
288 (proc (condition-case err
289 (make-network-process :name "MPC" :buffer (current-buffer)
290 :host (unless local host)
291 :service (if local host port)
292 :family (if local 'local))
293 (error (user-error (error-message-string err))))))
294 (when (processp mpc-proc)
295 ;; Inherit the properties of the previous connection.
296 (let ((plist (process-plist mpc-proc)))
297 (while plist (process-put proc (pop plist) (pop plist)))))
298 (mpc-proc-buffer proc 'mpd-commands (current-buffer))
299 (process-put proc 'callback 'ignore)
300 (process-put proc 'ready nil)
301 (clrhash mpc--find-memoize)
302 (set-process-filter proc 'mpc--proc-filter)
303 (set-process-sentinel proc 'ignore)
304 (set-process-query-on-exit-flag proc nil)
305 ;; This may be called within a process filter ;-(
306 (with-local-quit (mpc-proc-sync proc))
307 (setq mpc-proc proc)
308 (when pass
309 (mpc-proc-cmd (list "password" pass) nil))))))
310
311 (defun mpc--proc-quote-string (s)
312 (if (numberp s) (number-to-string s)
313 (setq s (replace-regexp-in-string "[\"\\]" "\\\\\\&" s))
314 (if (string-match " " s) (concat "\"" s "\"") s)))
315
316 (defconst mpc--proc-alist-to-alists-starters '(file directory))
317
318 (defun mpc--proc-alist-to-alists (alist)
319 (cl-assert (or (null alist)
320 (memq (caar alist) mpc--proc-alist-to-alists-starters)))
321 (let ((starter (caar alist))
322 (alists ())
323 tmp)
324 (dolist (pair alist)
325 (when (eq (car pair) starter)
326 (if tmp (push (nreverse tmp) alists))
327 (setq tmp ()))
328 (push pair tmp))
329 (if tmp (push (nreverse tmp) alists))
330 (nreverse alists)))
331
332 (defun mpc-proc (&optional restart)
333 (unless (and mpc-proc
334 (buffer-live-p (process-buffer mpc-proc))
335 (not (and restart
336 (memq (process-status mpc-proc) '(closed)))))
337 (mpc--proc-connect mpc-host))
338 mpc-proc)
339
340 (defun mpc-proc-check (proc)
341 (let ((error-text (process-get proc 'mpc-proc-error)))
342 (when error-text
343 (process-put proc 'mpc-proc-error nil)
344 (signal 'mpc-proc-error error-text))))
345
346 (defun mpc-proc-sync (&optional proc)
347 "Wait for MPC process until it is idle again.
348 Return the buffer in which the process is/was running."
349 (unless proc (setq proc (mpc-proc)))
350 (unwind-protect
351 (progn
352 (while (and (not (process-get proc 'ready))
353 (accept-process-output proc)))
354 (mpc-proc-check proc)
355 (if (process-get proc 'ready) (process-buffer proc)
356 (error "No response from MPD")))
357 (unless (process-get proc 'ready)
358 ;; (debug)
359 (message "Killing hung process")
360 (delete-process proc))))
361
362 (defun mpc-proc-cmd (cmd &optional callback)
363 "Send command CMD to the MPD server.
364 If CALLBACK is nil, wait for the command to finish before returning,
365 otherwise return immediately and call CALLBACK with no argument
366 when the command terminates.
367 CMD can be a string which is passed as-is to MPD or a list of strings
368 which will be concatenated with proper quoting before passing them to MPD."
369 (let ((proc (mpc-proc 'restart)))
370 (if (and callback (not (process-get proc 'ready)))
371 (let ((old (process-get proc 'callback)))
372 (process-put proc 'callback
373 (lambda ()
374 (funcall old)
375 (mpc-proc-cmd cmd callback))))
376 ;; Wait for any pending async command to terminate.
377 (mpc-proc-sync proc)
378 (process-put proc 'ready nil)
379 (with-current-buffer (process-buffer proc)
380 (erase-buffer)
381 (mpc--debug "Send \"%s\"" cmd)
382 (process-send-string
383 proc (concat (if (stringp cmd) cmd
384 (mapconcat 'mpc--proc-quote-string cmd " "))
385 "\n")))
386 (if callback
387 ;; (let ((buf (current-buffer)))
388 (process-put proc 'callback
389 callback
390 ;; (lambda ()
391 ;; (funcall callback
392 ;; (prog1 (current-buffer)
393 ;; (set-buffer buf)))))
394 )
395 ;; If `callback' is nil, we're executing synchronously.
396 (process-put proc 'callback 'ignore)
397 ;; This returns the process's buffer.
398 (mpc-proc-sync proc)))))
399
400 ;; This function doesn't exist in Emacs-21.
401 ;; (put 'mpc-proc-cmd-list 'byte-optimizer 'byte-optimize-pure-func)
402 (defun mpc-proc-cmd-list (cmds)
403 (concat "command_list_begin\n"
404 (mapconcat (lambda (cmd)
405 (if (stringp cmd) cmd
406 (mapconcat 'mpc--proc-quote-string cmd " ")))
407 cmds
408 "\n")
409 "\ncommand_list_end"))
410
411 (defun mpc-proc-cmd-list-ok ()
412 ;; To implement this, we'll need to tweak the process filter since we'd
413 ;; then sometimes get "trailing" text after "OK\n".
414 (error "Not implemented yet"))
415
416 (defun mpc-proc-buf-to-alist (&optional buf)
417 (with-current-buffer (or buf (current-buffer))
418 (let ((res ()))
419 (goto-char (point-min))
420 (while (re-search-forward "^\\([^:]+\\): \\(.*\\)\n" nil t)
421 (push (cons (intern (match-string 1)) (match-string 2)) res))
422 (nreverse res))))
423
424 (defun mpc-proc-buf-to-alists (buf)
425 (mpc--proc-alist-to-alists (mpc-proc-buf-to-alist buf)))
426
427 (defun mpc-proc-cmd-to-alist (cmd &optional callback)
428 (if callback
429 (let ((buf (current-buffer)))
430 (mpc-proc-cmd cmd (lambda ()
431 (funcall callback (prog1 (mpc-proc-buf-to-alist
432 (current-buffer))
433 (set-buffer buf))))))
434 ;; (let ((res nil))
435 ;; (mpc-proc-cmd-to-alist cmd (lambda (alist) (setq res alist)))
436 ;; (mpc-proc-sync)
437 ;; res)
438 (mpc-proc-buf-to-alist (mpc-proc-cmd cmd))))
439
440 (defun mpc-proc-tag-string-to-sym (tag)
441 (intern (capitalize tag)))
442
443 (defun mpc-proc-buffer (proc use &optional buffer)
444 (let* ((bufs (process-get proc 'buffers))
445 (buf (cdr (assoc use bufs))))
446 (cond
447 ((and buffer (buffer-live-p buf) (not (eq buffer buf)))
448 (error "Duplicate MPC buffer for %s" use))
449 (buffer
450 (if buf
451 (setcdr (assoc use bufs) buffer)
452 (process-put proc 'buffers (cons (cons use buffer) bufs))))
453 (t buf))))
454
455 ;;; Support for regularly updated current status information ;;;;;;;;;;;;;;;
456
457 ;; Exported elements:
458 ;; `mpc-status' holds the uptodate data.
459 ;; `mpc-status-callbacks' holds the registered callback functions.
460 ;; `mpc-status-refresh' forces a refresh of the data.
461 ;; `mpc-status-stop' stops the automatic updating.
462
463 (defvar mpc-status nil)
464 (defvar mpc-status-callbacks
465 '((state . mpc--status-timers-refresh)
466 ;; (song . mpc--queue-refresh)
467 ;; (state . mpc--queue-refresh) ;To detect the end of the last song.
468 (state . mpc--faster-toggle-refresh) ;Only ffwd/rewind while play/pause.
469 (volume . mpc-volume-refresh)
470 (file . mpc-songpointer-refresh)
471 ;; The song pointer may need updating even if the file doesn't change,
472 ;; if the same song appears multiple times in a row.
473 (song . mpc-songpointer-refresh)
474 (updating_db . mpc-updated-db)
475 (updating_db . mpc--status-timers-refresh)
476 (t . mpc-current-refresh))
477 "Alist associating properties to the functions that care about them.
478 Each entry has the form (PROP . FUN) where PROP can be t to mean
479 to call FUN for any change whatsoever.")
480
481 (defun mpc--status-callback ()
482 (let ((old-status mpc-status))
483 ;; Update the alist.
484 (setq mpc-status (mpc-proc-buf-to-alist))
485 (cl-assert mpc-status)
486 (unless (equal old-status mpc-status)
487 ;; Run the relevant refresher functions.
488 (dolist (pair mpc-status-callbacks)
489 (when (or (eq t (car pair))
490 (not (equal (cdr (assq (car pair) old-status))
491 (cdr (assq (car pair) mpc-status)))))
492 (funcall (cdr pair)))))))
493
494 (defvar mpc--status-timer nil)
495 (defun mpc--status-timer-start ()
496 (add-hook 'pre-command-hook 'mpc--status-timer-stop)
497 (unless mpc--status-timer
498 (setq mpc--status-timer (run-with-timer 1 1 'mpc--status-timer-run))))
499 (defun mpc--status-timer-stop ()
500 (when mpc--status-timer
501 (cancel-timer mpc--status-timer)
502 (setq mpc--status-timer nil)))
503 (defun mpc--status-timer-run ()
504 (with-demoted-errors "MPC: %S"
505 (when (process-get (mpc-proc) 'ready)
506 (let* ((buf (mpc-proc-buffer (mpc-proc) 'status))
507 (win (get-buffer-window buf t)))
508 (if (not win)
509 (mpc--status-timer-stop)
510 (with-local-quit (mpc-status-refresh)))))))
511
512 (defvar mpc--status-idle-timer nil)
513 (defun mpc--status-idle-timer-start ()
514 (when mpc--status-idle-timer
515 ;; Turn it off even if we'll start it again, in case it changes the delay.
516 (cancel-timer mpc--status-idle-timer))
517 (setq mpc--status-idle-timer
518 (run-with-idle-timer 1 t 'mpc--status-idle-timer-run))
519 ;; Typically, the idle timer is started from the mpc--status-callback,
520 ;; which is run asynchronously while we're already idle (we typically
521 ;; just started idling), so the timer itself will only be run the next
522 ;; time we idle :-(
523 ;; To work around that, we immediately start the repeat timer.
524 (mpc--status-timer-start))
525 (defun mpc--status-idle-timer-stop (&optional really)
526 (when mpc--status-idle-timer
527 ;; Turn it off even if we'll start it again, in case it changes the delay.
528 (cancel-timer mpc--status-idle-timer))
529 (setq mpc--status-idle-timer
530 (unless really
531 ;; We don't completely stop the timer, so that if some other MPD
532 ;; client starts playback, we may get a chance to notice it.
533 (run-with-idle-timer 10 t 'mpc--status-idle-timer-run))))
534 (defun mpc--status-idle-timer-run ()
535 (mpc--status-timer-start)
536 (mpc--status-timer-run))
537
538 (defun mpc--status-timers-refresh ()
539 "Start/stop the timers according to whether a song is playing."
540 (if (or (member (cdr (assq 'state mpc-status)) '("play"))
541 (cdr (assq 'updating_db mpc-status)))
542 (mpc--status-idle-timer-start)
543 (mpc--status-idle-timer-stop)
544 (mpc--status-timer-stop)))
545
546 (defun mpc-status-refresh (&optional callback)
547 "Refresh `mpc-status'."
548 (let ((cb callback))
549 (mpc-proc-cmd (mpc-proc-cmd-list '("status" "currentsong"))
550 (lambda ()
551 (mpc--status-callback)
552 (if cb (funcall cb))))))
553
554 (defun mpc-status-stop ()
555 "Stop the autorefresh of `mpc-status'.
556 This is normally used only when quitting MPC.
557 Any call to `mpc-status-refresh' may cause it to be restarted."
558 (setq mpc-status nil)
559 (mpc--status-idle-timer-stop 'really)
560 (mpc--status-timer-stop))
561
562 ;;; A thin layer above the raw protocol commands ;;;;;;;;;;;;;;;;;;;;;;;;;;;
563
564 ;; (defvar mpc-queue nil)
565 ;; (defvar mpc-queue-back nil)
566
567 ;; (defun mpc--queue-head ()
568 ;; (if (stringp (car mpc-queue)) (car mpc-queue) (cadar mpc-queue)))
569 ;; (defun mpc--queue-pop ()
570 ;; (when mpc-queue ;Can be nil if out of sync.
571 ;; (let ((song (car mpc-queue)))
572 ;; (cl-assert song)
573 ;; (push (if (and (consp song) (cddr song))
574 ;; ;; The queue's first element is itself a list of
575 ;; ;; songs, where the first element isn't itself a song
576 ;; ;; but a description of the list.
577 ;; (prog1 (cadr song) (setcdr song (cddr song)))
578 ;; (prog1 (if (consp song) (cadr song) song)
579 ;; (setq mpc-queue (cdr mpc-queue))))
580 ;; mpc-queue-back)
581 ;; (cl-assert (stringp (car mpc-queue-back))))))
582
583 ;; (defun mpc--queue-refresh ()
584 ;; ;; Maintain the queue.
585 ;; (mpc--debug "mpc--queue-refresh")
586 ;; (let ((pos (cdr (or (assq 'Pos mpc-status) (assq 'song mpc-status)))))
587 ;; (cond
588 ;; ((null pos)
589 ;; (mpc-cmd-clear 'ignore))
590 ;; ((or (not (member pos '("0" nil)))
591 ;; ;; There's only one song in the playlist and we've stopped.
592 ;; ;; Maybe it's because of some external client that set the
593 ;; ;; playlist like that and/or manually stopped the playback, but
594 ;; ;; it's more likely that we've simply reached the end of
595 ;; ;; the song. So remove it.
596 ;; (and (equal (assq 'state mpc-status) "stop")
597 ;; (equal (assq 'playlistlength mpc-status) "1")
598 ;; (setq pos "1")))
599 ;; ;; We're not playing the first song in the queue/playlist any
600 ;; ;; more, so update the queue.
601 ;; (dotimes (i (string-to-number pos)) (mpc--queue-pop))
602 ;; (mpc-proc-cmd (mpc-proc-cmd-list
603 ;; (make-list (string-to-number pos) "delete 0"))
604 ;; 'ignore)
605 ;; (if (not (equal (cdr (assq 'file mpc-status))
606 ;; (mpc--queue-head)))
607 ;; (message "MPC's queue is out of sync"))))))
608
609 (defvar mpc--find-memoize-union-tags nil)
610
611 (defun mpc-cmd-flush (tag value)
612 (puthash (cons tag value) nil mpc--find-memoize)
613 (dolist (uniontag mpc--find-memoize-union-tags)
614 (if (member (symbol-name tag) (split-string (symbol-name uniontag) "|"))
615 (puthash (cons uniontag value) nil mpc--find-memoize))))
616
617
618 (defun mpc-cmd-special-tag-p (tag)
619 (or (memq tag '(Playlist Search Directory))
620 (string-match "|" (symbol-name tag))))
621
622 (defun mpc-cmd-find (tag value)
623 "Return a list of all songs whose tag TAG has value VALUE.
624 The songs are returned as alists."
625 (or (gethash (cons tag value) mpc--find-memoize)
626 (puthash (cons tag value)
627 (cond
628 ((eq tag 'Playlist)
629 ;; Special case for pseudo-tag playlist.
630 (let ((l (condition-case nil
631 (mpc-proc-buf-to-alists
632 (mpc-proc-cmd (list "listplaylistinfo" value)))
633 (mpc-proc-error
634 ;; "[50@0] {listplaylistinfo} No such playlist"
635 nil)))
636 (i 0))
637 (mapcar (lambda (s)
638 (prog1 (cons (cons 'Pos (number-to-string i)) s)
639 (cl-incf i)))
640 l)))
641 ((eq tag 'Search)
642 (mpc-proc-buf-to-alists
643 (mpc-proc-cmd (list "search" "any" value))))
644 ((eq tag 'Directory)
645 (let ((pairs
646 (mpc-proc-buf-to-alist
647 (mpc-proc-cmd (list "listallinfo" value)))))
648 (mpc--proc-alist-to-alists
649 ;; Strip away the `directory' entries.
650 (delq nil (mapcar (lambda (pair)
651 (if (eq (car pair) 'directory)
652 nil pair))
653 pairs)))))
654 ((string-match "|" (symbol-name tag))
655 (add-to-list 'mpc--find-memoize-union-tags tag)
656 (let ((tag1 (intern (substring (symbol-name tag)
657 0 (match-beginning 0))))
658 (tag2 (intern (substring (symbol-name tag)
659 (match-end 0)))))
660 (mpc-union (mpc-cmd-find tag1 value)
661 (mpc-cmd-find tag2 value))))
662 (t
663 (condition-case nil
664 (mpc-proc-buf-to-alists
665 (mpc-proc-cmd (list "find" (symbol-name tag) value)))
666 (mpc-proc-error
667 ;; If `tag' is not one of the expected tags, MPD burps
668 ;; about not having the relevant table. FIXME: check
669 ;; the kind of error.
670 (error "Unknown tag %s" tag)
671 (let ((res ()))
672 (setq value (cons tag value))
673 (dolist (song (mpc-proc-buf-to-alists
674 (mpc-proc-cmd "listallinfo")))
675 (if (member value song) (push song res)))
676 res)))))
677 mpc--find-memoize)))
678
679 (defun mpc-cmd-list (tag &optional other-tag value)
680 ;; FIXME: we could also provide a `mpc-cmd-list' alternative which
681 ;; doesn't take an "other-tag value" constraint but a "song-list" instead.
682 ;; That might be more efficient in some cases.
683 (cond
684 ((eq tag 'Playlist)
685 (let ((pls (mpc-assq-all 'playlist (mpc-proc-cmd-to-alist "lsinfo"))))
686 (when other-tag
687 (dolist (pl (prog1 pls (setq pls nil)))
688 (let ((plsongs (mpc-cmd-find 'Playlist pl)))
689 (if (not (mpc-cmd-special-tag-p other-tag))
690 (when (member (cons other-tag value)
691 (apply 'append plsongs))
692 (push pl pls))
693 ;; Problem N°2: we compute the intersection whereas all
694 ;; we care about is whether it's empty. So we could
695 ;; speed this up significantly.
696 ;; We only compare file names, because the full song-entries
697 ;; are slightly different (the ones in plsongs include
698 ;; position and id info specific to the playlist), and it's
699 ;; good enough because this is only used with "search", which
700 ;; doesn't pay attention to playlists and URLs anyway.
701 (let* ((osongs (mpc-cmd-find other-tag value))
702 (ofiles (mpc-assq-all 'file (apply 'append osongs)))
703 (plfiles (mpc-assq-all 'file (apply 'append plsongs))))
704 (when (mpc-intersection plfiles ofiles)
705 (push pl pls)))))))
706 pls))
707
708 ((eq tag 'Directory)
709 (if (null other-tag)
710 (apply 'nconc
711 (mpc-assq-all 'directory
712 (mpc-proc-buf-to-alist
713 (mpc-proc-cmd "lsinfo")))
714 (mapcar (lambda (dir)
715 (let ((shortdir
716 (if (get-text-property 0 'display dir)
717 (concat " "
718 (get-text-property 0 'display dir))
719 " ↪ "))
720 (subdirs
721 (mpc-assq-all 'directory
722 (mpc-proc-buf-to-alist
723 (mpc-proc-cmd (list "lsinfo" dir))))))
724 (dolist (subdir subdirs)
725 (put-text-property 0 (1+ (length dir))
726 'display shortdir
727 subdir))
728 subdirs))
729 (process-get (mpc-proc) 'Directory)))
730 ;; If there's an other-tag, then just extract the dir info from the
731 ;; list of other-tag's songs.
732 (let* ((other-songs (mpc-cmd-find other-tag value))
733 (files (mpc-assq-all 'file (apply 'append other-songs)))
734 (dirs '()))
735 (dolist (file files)
736 (let ((dir (file-name-directory file)))
737 (if (and dir (setq dir (directory-file-name dir))
738 (not (equal dir (car dirs))))
739 (push dir dirs))))
740 ;; Dirs might have duplicates still.
741 (setq dirs (delete-dups dirs))
742 (let ((newdirs dirs))
743 (while newdirs
744 (let ((dir (file-name-directory (pop newdirs))))
745 (when (and dir (setq dir (directory-file-name dir))
746 (not (member dir dirs)))
747 (push dir newdirs)
748 (push dir dirs)))))
749 dirs)))
750
751 ;; The UI should not provide access to such a thing anyway currently.
752 ;; But I could imagine adding in the future a browser for the "search"
753 ;; tag, which would provide things like previous searches. Not sure how
754 ;; useful that would be tho.
755 ((eq tag 'Search) (error "Not supported"))
756
757 ((string-match "|" (symbol-name tag))
758 (let ((tag1 (intern (substring (symbol-name tag)
759 0 (match-beginning 0))))
760 (tag2 (intern (substring (symbol-name tag)
761 (match-end 0)))))
762 (mpc-union (mpc-cmd-list tag1 other-tag value)
763 (mpc-cmd-list tag2 other-tag value))))
764
765 ((null other-tag)
766 (condition-case nil
767 (mapcar 'cdr (mpc-proc-cmd-to-alist (list "list" (symbol-name tag))))
768 (mpc-proc-error
769 ;; If `tag' is not one of the expected tags, MPD burps about not
770 ;; having the relevant table.
771 ;; FIXME: check the kind of error.
772 (error "MPD does not know this tag %s" tag)
773 (mpc-assq-all tag (mpc-proc-cmd-to-alist "listallinfo")))))
774 (t
775 (condition-case nil
776 (if (mpc-cmd-special-tag-p other-tag)
777 (signal 'mpc-proc-error "Not implemented")
778 (mapcar 'cdr
779 (mpc-proc-cmd-to-alist
780 (list "list" (symbol-name tag)
781 (symbol-name other-tag) value))))
782 (mpc-proc-error
783 ;; DAMN!! the 3-arg form of `list' is new in 0.12 !!
784 ;; FIXME: check the kind of error.
785 (let ((other-songs (mpc-cmd-find other-tag value)))
786 (mpc-assq-all tag
787 ;; Don't use `nconc' now that mpc-cmd-find may
788 ;; return a memoized result.
789 (apply 'append other-songs))))))))
790
791 (defun mpc-cmd-stop (&optional callback)
792 (mpc-proc-cmd "stop" callback))
793
794 (defun mpc-cmd-clear (&optional callback)
795 (mpc-proc-cmd "clear" callback)
796 ;; (setq mpc-queue-back nil mpc-queue nil)
797 )
798
799 (defun mpc-cmd-consume (&optional arg)
800 "Set consume mode state."
801 (mpc-proc-cmd (list "consume" arg) #'mpc-status-refresh))
802
803 (defun mpc-cmd-random (&optional arg)
804 "Set random (shuffle) mode state."
805 (mpc-proc-cmd (list "random" arg) #'mpc-status-refresh))
806
807 (defun mpc-cmd-repeat (&optional arg)
808 "Set repeat mode state."
809 (mpc-proc-cmd (list "repeat" arg) #'mpc-status-refresh))
810
811 (defun mpc-cmd-single (&optional arg)
812 "Set single mode state."
813 (mpc-proc-cmd (list "single" arg) #'mpc-status-refresh))
814
815 (defun mpc-cmd-pause (&optional arg callback)
816 "Pause or resume playback of the queue of songs."
817 (let ((cb callback))
818 (mpc-proc-cmd (list "pause" arg)
819 (lambda () (mpc-status-refresh) (if cb (funcall cb))))
820 (unless callback (mpc-proc-sync))))
821
822 (defun mpc-cmd-status ()
823 (mpc-proc-cmd-to-alist "status"))
824
825 (defun mpc-cmd-play ()
826 (mpc-proc-cmd "play")
827 (mpc-status-refresh))
828
829 (defun mpc-cmd-add (files &optional playlist)
830 "Add the songs FILES to PLAYLIST.
831 If PLAYLIST is t or nil or missing, use the main playlist."
832 (mpc-proc-cmd (mpc-proc-cmd-list
833 (mapcar (lambda (file)
834 (if (stringp playlist)
835 (list "playlistadd" playlist file)
836 (list "add" file)))
837 files)))
838 (if (stringp playlist)
839 (mpc-cmd-flush 'Playlist playlist)))
840
841 (defun mpc-cmd-delete (song-poss &optional playlist)
842 "Delete the songs at positions SONG-POSS from PLAYLIST.
843 If PLAYLIST is t or nil or missing, use the main playlist."
844 (mpc-proc-cmd (mpc-proc-cmd-list
845 (mapcar (lambda (song-pos)
846 (if (stringp playlist)
847 (list "playlistdelete" playlist song-pos)
848 (list "delete" song-pos)))
849 ;; Sort them from last to first, so the renumbering
850 ;; caused by the earlier deletions don't affect
851 ;; later ones.
852 (sort song-poss '>))))
853 (if (stringp playlist)
854 (puthash (cons 'Playlist playlist) nil mpc--find-memoize)))
855
856
857 (defun mpc-cmd-move (song-poss dest-pos &optional playlist)
858 (let ((i 0))
859 (mpc-proc-cmd
860 (mpc-proc-cmd-list
861 (mapcar (lambda (song-pos)
862 (if (>= song-pos dest-pos)
863 ;; positions past dest-pos have been
864 ;; shifted by i.
865 (setq song-pos (+ song-pos i)))
866 (prog1 (if (stringp playlist)
867 (list "playlistmove" playlist song-pos dest-pos)
868 (list "move" song-pos dest-pos))
869 (if (< song-pos dest-pos)
870 ;; This move has shifted dest-pos by 1.
871 (cl-decf dest-pos))
872 (cl-incf i)))
873 ;; Sort them from last to first, so the renumbering
874 ;; caused by the earlier deletions affect
875 ;; later ones a bit less.
876 (sort song-poss '>))))
877 (if (stringp playlist)
878 (puthash (cons 'Playlist playlist) nil mpc--find-memoize))))
879
880 (defun mpc-cmd-update (&optional arg callback)
881 (let ((cb callback))
882 (mpc-proc-cmd (if arg (list "update" arg) "update")
883 (lambda () (mpc-status-refresh) (if cb (funcall cb))))
884 (unless callback (mpc-proc-sync))))
885
886 (defun mpc-cmd-tagtypes ()
887 (mapcar 'cdr (mpc-proc-cmd-to-alist "tagtypes")))
888
889 ;; This was never integrated into MPD.
890 ;; (defun mpc-cmd-download (file)
891 ;; (with-current-buffer (generate-new-buffer " *mpc download*")
892 ;; (set-buffer-multibyte nil)
893 ;; (let* ((proc (mpc-proc))
894 ;; (stdbuf (process-buffer proc))
895 ;; (markpos (marker-position (process-mark proc)))
896 ;; (stdcoding (process-coding-system proc)))
897 ;; (unwind-protect
898 ;; (progn
899 ;; (set-process-buffer proc (current-buffer))
900 ;; (set-process-coding-system proc 'binary (cdr stdcoding))
901 ;; (set-marker (process-mark proc) (point))
902 ;; (mpc-proc-cmd (list "download" file)))
903 ;; (set-process-buffer proc stdbuf)
904 ;; (set-marker (process-mark proc) markpos stdbuf)
905 ;; (set-process-coding-system proc (car stdcoding) (cdr stdcoding)))
906 ;; ;; The command has completed, let's decode.
907 ;; (goto-char (point-max))
908 ;; (delete-char -1) ;Delete final newline.
909 ;; (while (re-search-backward "^>" nil t)
910 ;; (delete-char 1))
911 ;; (current-buffer))))
912
913 ;;; Misc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
914
915 (defcustom mpc-mpd-music-directory nil
916 "Location of MPD's music directory."
917 :type '(choice (const nil) directory))
918
919 (defcustom mpc-data-directory
920 (locate-user-emacs-file "mpc" ".mpc")
921 "Directory where MPC.el stores auxiliary data."
922 :type 'directory)
923
924 (defun mpc-data-directory ()
925 (unless (file-directory-p mpc-data-directory)
926 (make-directory mpc-data-directory))
927 mpc-data-directory)
928
929 (defun mpc-file-local-copy (file)
930 ;; Try to set mpc-mpd-music-directory.
931 (when (and (null mpc-mpd-music-directory)
932 (or (string-match "\\`localhost" mpc-host)
933 (file-name-absolute-p mpc-host)))
934 (let ((files `(,(let ((xdg (getenv "XDG_CONFIG_HOME")))
935 (concat (if (and xdg (file-name-absolute-p xdg))
936 xdg "~/.config")
937 "/mpd/mpd.conf"))
938 "~/.mpdconf" "~/.mpd/mpd.conf" "/etc/mpd.conf"))
939 file)
940 (while (and files (not file))
941 (if (file-exists-p (car files)) (setq file (car files)))
942 (setq files (cdr files)))
943 (with-temp-buffer
944 (ignore-errors (insert-file-contents file))
945 (goto-char (point-min))
946 (if (re-search-forward "^music_directory[ ]+\"\\([^\"]+\\)\"")
947 (setq mpc-mpd-music-directory
948 (match-string 1))))))
949 ;; Use mpc-mpd-music-directory if applicable, or else try to use the
950 ;; `download' command, although it's never been accepted in `mpd' :-(
951 (if (and mpc-mpd-music-directory
952 (file-exists-p (expand-file-name file mpc-mpd-music-directory)))
953 (expand-file-name file mpc-mpd-music-directory)
954 ;; (let ((aux (expand-file-name (replace-regexp-in-string "[/]" "|" file)
955 ;; (mpc-data-directory))))
956 ;; (unless (file-exists-p aux)
957 ;; (condition-case err
958 ;; (with-local-quit
959 ;; (with-current-buffer (mpc-cmd-download file)
960 ;; (write-region (point-min) (point-max) aux)
961 ;; (kill-buffer (current-buffer))))
962 ;; (mpc-proc-error (message "Download error: %s" err) (setq aux nil))))
963 ;; aux)
964 ))
965
966 ;;; Formatter ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
967
968 (defun mpc-secs-to-time (secs)
969 ;; We could use `format-seconds', but it doesn't seem worth the trouble
970 ;; because we'd still need to check (>= secs (* 60 100)) since the special
971 ;; %z only allows us to drop the large units for small values but
972 ;; not to drop the small units for large values.
973 (if (stringp secs) (setq secs (string-to-number secs)))
974 (if (>= secs (* 60 100)) ;More than 100 minutes.
975 (format "%dh%02d" ;"%d:%02d:%02d"
976 (/ secs 3600) (% (/ secs 60) 60)) ;; (% secs 60)
977 (format "%d:%02d" (/ secs 60) (% secs 60))))
978
979 (defvar mpc-tempfiles nil)
980 (defconst mpc-tempfiles-reftable (make-hash-table :weakness 'key))
981
982 (defun mpc-tempfiles-clean ()
983 (let ((live ()))
984 (maphash (lambda (_k v) (push v live)) mpc-tempfiles-reftable)
985 (dolist (f mpc-tempfiles)
986 (unless (member f live) (ignore-errors (delete-file f))))
987 (setq mpc-tempfiles live)))
988
989 (defun mpc-tempfiles-add (key file)
990 (mpc-tempfiles-clean)
991 (puthash key file mpc-tempfiles-reftable)
992 (push file mpc-tempfiles))
993
994 (defun mpc-format (format-spec info &optional hscroll)
995 "Format the INFO according to FORMAT-SPEC, inserting the result at point."
996 (let* ((pos 0)
997 (start (point))
998 (col (if hscroll (- hscroll) 0))
999 (insert (lambda (str)
1000 (cond
1001 ((>= col 0) (insert str))
1002 (t (insert (substring str (min (length str) (- col))))))))
1003 (pred nil))
1004 (while (string-match "%\\(?:%\\|\\(-\\)?\\([0-9]+\\)?{\\([[:alpha:]][[:alnum:]]*\\)\\(?:-\\([^}]+\\)\\)?}\\)" format-spec pos)
1005 (let ((pre-text (substring format-spec pos (match-beginning 0))))
1006 (funcall insert pre-text)
1007 (setq col (+ col (string-width pre-text))))
1008 (setq pos (match-end 0))
1009 (if (null (match-end 3))
1010 (progn
1011 (funcall insert "%")
1012 (setq col (+ col 1)))
1013 (let* ((size (match-string 2 format-spec))
1014 (tag (intern (match-string 3 format-spec)))
1015 (post (match-string 4 format-spec))
1016 (right-align (match-end 1))
1017 (text
1018 (if (eq info 'self) (symbol-name tag)
1019 (pcase tag
1020 ((or `Time `Duration)
1021 (let ((time (cdr (or (assq 'time info) (assq 'Time info)))))
1022 (setq pred (list nil)) ;Just assume it's never eq.
1023 (when time
1024 (mpc-secs-to-time (if (and (eq tag 'Duration)
1025 (string-match ":" time))
1026 (substring time (match-end 0))
1027 time)))))
1028 (`Cover
1029 (let ((dir (file-name-directory
1030 (mpc-file-local-copy (cdr (assq 'file info))))))
1031 ;; (debug)
1032 (push `(equal ',dir (file-name-directory (cdr (assq 'file info)))) pred)
1033 (if-let ((covers '(".folder.png" "cover.jpg" "folder.jpg"))
1034 (cover (cl-loop for file in (directory-files dir)
1035 if (member (downcase file) covers)
1036 return (concat dir file)))
1037 (file (with-demoted-errors "MPC: %s"
1038 (mpc-file-local-copy cover))))
1039 (let (image)
1040 (if (null size) (setq image (create-image file))
1041 (let ((tempfile (make-temp-file "mpc" nil ".jpg")))
1042 (call-process "convert" nil nil nil
1043 "-scale" size file tempfile)
1044 (setq image (create-image tempfile))
1045 (mpc-tempfiles-add image tempfile)))
1046 (setq size nil)
1047 (propertize dir 'display image))
1048 ;; Make sure we return something on which we can
1049 ;; place the `mpc-pred' property, as
1050 ;; a negative-cache. We could also use
1051 ;; a default cover.
1052 (progn (setq size nil) " "))))
1053 (_ (let ((val (cdr (assq tag info))))
1054 ;; For Streaming URLs, there's no other info
1055 ;; than the URL in `file'. Pretend it's in `Title'.
1056 (when (and (null val) (eq tag 'Title))
1057 (setq val (cdr (assq 'file info))))
1058 (push `(equal ',val (cdr (assq ',tag info))) pred)
1059 (cond
1060 ((not (and (eq tag 'Date) (stringp val))) val)
1061 ;; For "date", only keep the year!
1062 ((string-match "[0-9]\\{4\\}" val)
1063 (match-string 0 val))
1064 (t val)))))))
1065 (space (when size
1066 (setq size (string-to-number size))
1067 (propertize " " 'display
1068 (list 'space :align-to (+ col size)))))
1069 (textwidth (if text (string-width text) 0))
1070 (postwidth (if post (string-width post) 0)))
1071 (when text
1072 (let ((display
1073 (if (and size
1074 (> (+ postwidth textwidth) size))
1075 (propertize
1076 (truncate-string-to-width text size nil nil "…")
1077 'help-echo text)
1078 text)))
1079 (when (memq tag '(Artist Album Composer)) ;FIXME: wrong list.
1080 (setq display
1081 (propertize display
1082 'mouse-face 'highlight
1083 'follow-link t
1084 'keymap `(keymap
1085 (mouse-2
1086 . (lambda ()
1087 (interactive)
1088 (mpc-constraints-push 'noerror)
1089 (mpc-constraints-restore
1090 ',(list (list tag text)))))))))
1091 (funcall insert
1092 (concat (when size
1093 (propertize " " 'display
1094 (list 'space :align-to
1095 (+ col
1096 (if (and size right-align)
1097 (- size postwidth textwidth)
1098 0)))))
1099 display post))))
1100 (if (null size) (setq col (+ col textwidth postwidth))
1101 (insert space)
1102 (setq col (+ col size))))))
1103 (put-text-property start (point) 'mpc-pred
1104 `(lambda (info) (and ,@(nreverse pred))))))
1105
1106 ;;; The actual UI code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1107
1108 (defvar mpc-mode-map
1109 (let ((map (make-sparse-keymap)))
1110 ;; (define-key map "\e" 'mpc-stop)
1111 (define-key map "q" 'mpc-quit)
1112 (define-key map "\r" 'mpc-select)
1113 (define-key map [(shift return)] 'mpc-select-toggle)
1114 (define-key map [mouse-2] 'mpc-select)
1115 (define-key map [S-mouse-2] 'mpc-select-extend)
1116 (define-key map [C-mouse-2] 'mpc-select-toggle)
1117 (define-key map [drag-mouse-2] 'mpc-drag-n-drop)
1118 ;; We use `always' because a binding to t is like a binding to nil.
1119 (define-key map [follow-link] :always)
1120 ;; But follow-link doesn't apply blindly to header-line and
1121 ;; mode-line clicks.
1122 (define-key map [header-line follow-link] 'ignore)
1123 (define-key map [mode-line follow-link] 'ignore)
1124 ;; Doesn't work because the first click changes the buffer, so the second
1125 ;; is applied elsewhere :-(
1126 ;; (define-key map [(double mouse-2)] 'mpc-play-at-point)
1127 (define-key map "p" 'mpc-pause)
1128 (define-key map "s" 'mpc-toggle-play)
1129 (define-key map ">" 'mpc-next)
1130 (define-key map "<" 'mpc-prev)
1131 (define-key map "g" nil)
1132 map))
1133
1134 (easy-menu-define mpc-mode-menu mpc-mode-map
1135 "Menu for MPC.el."
1136 '("MPC.el"
1137 ["Play/Pause" mpc-toggle-play]
1138 ["Next Track" mpc-next]
1139 ["Previous Track" mpc-prev]
1140 "--"
1141 ["Repeat Playlist" mpc-repeat :style toggle
1142 :selected (member '(repeat . "1") mpc-status)]
1143 ["Shuffle Playlist" mpc-shuffle :style toggle
1144 :selected (member '(random . "1") mpc-status)]
1145 ["Repeat Single Track" mpc-single :style toggle
1146 :selected (member '(single . "1") mpc-status)]
1147 ["Consume Mode" mpc-consume :style toggle
1148 :selected (member '(consume . "1") mpc-status)]
1149 "--"
1150 ["Add new browser" mpc-tagbrowser]
1151 ["Update DB" mpc-update]
1152 ["Quit" mpc-quit]))
1153
1154 (defvar mpc-tool-bar-map
1155 (let ((map (make-sparse-keymap)))
1156 (tool-bar-local-item "mpc/prev" 'mpc-prev 'prev map
1157 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop"))
1158 :label "Prev" :vert-only t)
1159 ;; FIXME: how can we bind it to the down-event?
1160 (tool-bar-local-item "mpc/rewind" 'mpc-rewind 'rewind map
1161 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop"))
1162 :label "Rew" :vert-only t
1163 :button '(:toggle . (and mpc--faster-toggle-timer
1164 (not mpc--faster-toggle-forward))))
1165 ;; We could use a single toggle command for pause/play, with 2 different
1166 ;; icons depending on whether or not it's selected, but then it'd have
1167 ;; to be a toggle-button, thus displayed depressed in one of the
1168 ;; two states :-(
1169 (tool-bar-local-item "mpc/pause" 'mpc-pause 'pause map
1170 :label "Pause" :vert-only t
1171 :visible '(equal (cdr (assq 'state mpc-status)) "play")
1172 :help "Pause/play")
1173 (tool-bar-local-item "mpc/play" 'mpc-play 'play map
1174 :label "Play" :vert-only t
1175 :visible '(not (equal (cdr (assq 'state mpc-status)) "play"))
1176 :help "Play/pause")
1177 ;; FIXME: how can we bind it to the down-event?
1178 (tool-bar-local-item "mpc/ffwd" 'mpc-ffwd 'ffwd map
1179 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop"))
1180 :label "Ffwd" :vert-only t
1181 :button '(:toggle . (and mpc--faster-toggle-timer
1182 mpc--faster-toggle-forward)))
1183 (tool-bar-local-item "mpc/next" 'mpc-next 'next map
1184 :label "Next" :vert-only t
1185 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop")))
1186 (tool-bar-local-item "mpc/stop" 'mpc-stop 'stop map
1187 :label "Stop" :vert-only t)
1188 (tool-bar-local-item "mpc/add" 'mpc-playlist-add 'add map
1189 :label "Add" :vert-only t
1190 :help "Append to the playlist")
1191 map))
1192
1193 (define-derived-mode mpc-mode special-mode "MPC"
1194 "Major mode for the features common to all buffers of MPC."
1195 (buffer-disable-undo)
1196 (if (boundp 'tool-bar-map) ; not if --without-x
1197 (setq-local tool-bar-map mpc-tool-bar-map))
1198 (setq-local truncate-lines t))
1199
1200 ;;; The mpc-status-mode buffer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1201
1202 (define-derived-mode mpc-status-mode mpc-mode "MPC-Status"
1203 "Major mode to display MPC status info."
1204 (setq-local mode-line-format
1205 '("%e" mode-line-frame-identification
1206 mode-line-buffer-identification))
1207 (setq-local window-area-factor 3)
1208 (setq-local header-line-format '("MPC " mpc-volume)))
1209
1210 (defvar mpc-status-buffer-format
1211 '("%-5{Time} / %{Duration} %2{Disc--}%4{Track}" "%{Title}" "%{Album}" "%{Artist}" "%128{Cover}"))
1212
1213 (defun mpc-status-buffer-refresh ()
1214 (let ((buf (mpc-proc-buffer (mpc-proc) 'status)))
1215 (when (buffer-live-p buf)
1216 (with-current-buffer buf
1217 (save-excursion
1218 (goto-char (point-min))
1219 (when (assq 'file mpc-status)
1220 (let ((inhibit-read-only t))
1221 (dolist (spec mpc-status-buffer-format)
1222 (let ((pred (get-text-property (point) 'mpc-pred)))
1223 (if (and pred (funcall pred mpc-status))
1224 (forward-line)
1225 (delete-region (point) (line-beginning-position 2))
1226 (ignore-errors (mpc-format spec mpc-status))
1227 (insert "\n"))))
1228 (unless (eobp) (delete-region (point) (point-max))))))))))
1229
1230 (defun mpc-status-buffer-show ()
1231 (interactive)
1232 (let* ((proc (mpc-proc))
1233 (buf (mpc-proc-buffer proc 'status))
1234 (songs-buf (mpc-proc-buffer proc 'songs))
1235 (songs-win (if songs-buf (get-buffer-window songs-buf 0))))
1236 (unless (buffer-live-p buf)
1237 (setq buf (get-buffer-create "*MPC-Status*"))
1238 (with-current-buffer buf
1239 (mpc-status-mode))
1240 (mpc-proc-buffer proc 'status buf))
1241 (if (null songs-win) (pop-to-buffer buf)
1242 (let ((_win (split-window songs-win 20 t)))
1243 (set-window-dedicated-p songs-win nil)
1244 (set-window-buffer songs-win buf)
1245 (set-window-dedicated-p songs-win 'soft)))))
1246
1247 ;;; Selection management;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1248
1249 (defvar mpc-separator-ol nil)
1250
1251 (defvar-local mpc-select nil)
1252
1253 (defmacro mpc-select-save (&rest body)
1254 "Execute BODY and restore the selection afterwards."
1255 (declare (indent 0) (debug t))
1256 `(let ((selection (mpc-select-get-selection))
1257 (position (cons (buffer-substring-no-properties
1258 (line-beginning-position) (line-end-position))
1259 (current-column))))
1260 ,@body
1261 (mpc-select-restore selection)
1262 (goto-char (point-min))
1263 (if (re-search-forward
1264 (concat "^" (regexp-quote (car position)) "$")
1265 (if (overlayp mpc-separator-ol)
1266 (overlay-end mpc-separator-ol))
1267 t)
1268 (move-to-column (cdr position)))
1269 (let ((win (get-buffer-window (current-buffer) 0)))
1270 (if win (set-window-point win (point))))))
1271
1272 (defun mpc-select-get-selection ()
1273 (mapcar (lambda (ol)
1274 (buffer-substring-no-properties
1275 (overlay-start ol) (1- (overlay-end ol))))
1276 mpc-select))
1277
1278 (defun mpc-select-restore (selection)
1279 ;; Restore the selection. I.e. move the overlays back to their
1280 ;; corresponding location. Actually which overlay is used for what
1281 ;; doesn't matter.
1282 (mapc 'delete-overlay mpc-select)
1283 (setq mpc-select nil)
1284 (dolist (elem selection)
1285 ;; After an update, some elements may have disappeared.
1286 (goto-char (point-min))
1287 (when (re-search-forward
1288 (concat "^" (regexp-quote elem) "$") nil t)
1289 (mpc-select-make-overlay)))
1290 (when mpc-tag (mpc-tagbrowser-all-select))
1291 (beginning-of-line))
1292
1293 (defun mpc-select-make-overlay ()
1294 (cl-assert (not (get-char-property (point) 'mpc-select)))
1295 (let ((ol (make-overlay
1296 (line-beginning-position) (line-beginning-position 2))))
1297 (overlay-put ol 'mpc-select t)
1298 (overlay-put ol 'face 'highlight)
1299 (overlay-put ol 'evaporate t)
1300 (push ol mpc-select)))
1301
1302 (defun mpc-select (&optional event)
1303 "Select the tag value at point."
1304 (interactive (list last-nonmenu-event))
1305 (mpc-event-set-point event)
1306 (if (and (bolp) (eobp)) (forward-line -1))
1307 (mapc 'delete-overlay mpc-select)
1308 (setq mpc-select nil)
1309 (if (mpc-tagbrowser-all-p)
1310 nil
1311 (mpc-select-make-overlay))
1312 (when mpc-tag
1313 (mpc-tagbrowser-all-select)
1314 (mpc-selection-refresh)))
1315
1316 (defun mpc-select-toggle (&optional event)
1317 "Toggle the selection of the tag value at point."
1318 (interactive (list last-nonmenu-event))
1319 (mpc-event-set-point event)
1320 (save-excursion
1321 (cond
1322 ;; The line is already selected: deselect it.
1323 ((get-char-property (point) 'mpc-select)
1324 (let ((ols nil))
1325 (dolist (ol mpc-select)
1326 (if (and (<= (overlay-start ol) (point))
1327 (> (overlay-end ol) (point)))
1328 (delete-overlay ol)
1329 (push ol ols)))
1330 (cl-assert (= (1+ (length ols)) (length mpc-select)))
1331 (setq mpc-select ols)))
1332 ;; We're trying to select *ALL* additionally to others.
1333 ((mpc-tagbrowser-all-p) nil)
1334 ;; Select the current line.
1335 (t (mpc-select-make-overlay))))
1336 (when mpc-tag
1337 (mpc-tagbrowser-all-select)
1338 (mpc-selection-refresh)))
1339
1340 (defun mpc-select-extend (&optional event)
1341 "Extend the selection up to point."
1342 (interactive (list last-nonmenu-event))
1343 (mpc-event-set-point event)
1344 (if (null mpc-select)
1345 ;; If nothing's selected yet, fallback to selecting the elem at point.
1346 (mpc-select event)
1347 (save-excursion
1348 (cond
1349 ;; The line is already in a selected area; truncate the area.
1350 ((get-char-property (point) 'mpc-select)
1351 (let ((before 0)
1352 (after 0)
1353 (mid (line-beginning-position))
1354 start end)
1355 (while (and (zerop (forward-line 1))
1356 (get-char-property (point) 'mpc-select))
1357 (setq end (1+ (point)))
1358 (cl-incf after))
1359 (goto-char mid)
1360 (while (and (zerop (forward-line -1))
1361 (get-char-property (point) 'mpc-select))
1362 (setq start (point))
1363 (cl-incf before))
1364 (if (and (= after 0) (= before 0))
1365 ;; Shortening an already minimum-size region: do nothing.
1366 nil
1367 (if (> after before)
1368 (setq end mid)
1369 (setq start (1+ mid)))
1370 (let ((ols '()))
1371 (dolist (ol mpc-select)
1372 (if (and (>= (overlay-start ol) start)
1373 (< (overlay-start ol) end))
1374 (delete-overlay ol)
1375 (push ol ols)))
1376 (setq mpc-select (nreverse ols))))))
1377 ;; Extending a prior area. Look for the closest selection.
1378 (t
1379 (when (mpc-tagbrowser-all-p)
1380 (forward-line 1))
1381 (let ((before 0)
1382 (count 0)
1383 (dir 1)
1384 (start (line-beginning-position)))
1385 (while (and (zerop (forward-line 1))
1386 (not (get-char-property (point) 'mpc-select)))
1387 (cl-incf count))
1388 (unless (get-char-property (point) 'mpc-select)
1389 (setq count nil))
1390 (goto-char start)
1391 (while (and (zerop (forward-line -1))
1392 (not (get-char-property (point) 'mpc-select)))
1393 (cl-incf before))
1394 (unless (get-char-property (point) 'mpc-select)
1395 (setq before nil))
1396 (when (and before (or (null count) (< before count)))
1397 (setq count before)
1398 (setq dir -1))
1399 (goto-char start)
1400 (dotimes (_i (1+ (or count 0)))
1401 (mpc-select-make-overlay)
1402 (forward-line dir))))))
1403 (when mpc-tag
1404 (mpc-tagbrowser-all-select)
1405 (mpc-selection-refresh))))
1406
1407 ;;; Constraint sets ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1408
1409 (defvar mpc--song-search nil)
1410
1411 (defun mpc-constraints-get-current (&optional avoid-buf)
1412 "Return currently selected set of constraints.
1413 If AVOID-BUF is non-nil, it specifies a buffer which should be ignored
1414 when constructing the set of constraints."
1415 (let ((constraints (if mpc--song-search `((Search ,mpc--song-search))))
1416 tag select)
1417 (dolist (buf (process-get (mpc-proc) 'buffers))
1418 (setq buf (cdr buf))
1419 (when (and (setq tag (buffer-local-value 'mpc-tag buf))
1420 (not (eq buf avoid-buf))
1421 (setq select
1422 (with-current-buffer buf (mpc-select-get-selection))))
1423 (push (cons tag select) constraints)))
1424 constraints))
1425
1426 (defun mpc-constraints-tag-lookup (buffer-tag constraints)
1427 (let (res)
1428 (dolist (constraint constraints)
1429 (when (or (eq (car constraint) buffer-tag)
1430 (and (string-match "|" (symbol-name buffer-tag))
1431 (member (symbol-name (car constraint))
1432 (split-string (symbol-name buffer-tag) "|"))))
1433 (setq res (cdr constraint))))
1434 res))
1435
1436 (defun mpc-constraints-restore (constraints)
1437 (let ((search (assq 'Search constraints)))
1438 (setq mpc--song-search (cadr search))
1439 (when search (setq constraints (delq search constraints))))
1440 (dolist (buf (process-get (mpc-proc) 'buffers))
1441 (setq buf (cdr buf))
1442 (when (buffer-live-p buf)
1443 (let* ((tag (buffer-local-value 'mpc-tag buf))
1444 (constraint (mpc-constraints-tag-lookup tag constraints)))
1445 (when tag
1446 (with-current-buffer buf
1447 (mpc-select-restore constraint))))))
1448 (mpc-selection-refresh))
1449
1450 ;; I don't get the ring.el code. I think it doesn't do what I need, but
1451 ;; then I don't understand when what it does would be useful.
1452 (defun mpc-ring-make (size) (cons 0 (cons 0 (make-vector size nil))))
1453 (defun mpc-ring-push (ring val)
1454 (aset (cddr ring) (car ring) val)
1455 (setcar (cdr ring) (max (cadr ring) (1+ (car ring))))
1456 (setcar ring (mod (1+ (car ring)) (length (cddr ring)))))
1457 (defun mpc-ring-pop (ring)
1458 (setcar ring (mod (1- (car ring)) (cadr ring)))
1459 (aref (cddr ring) (car ring)))
1460
1461 (defvar mpc-constraints-ring (mpc-ring-make 10))
1462
1463 (defun mpc-constraints-push (&optional noerror)
1464 "Push the current selection on the ring for later."
1465 (interactive)
1466 (let ((constraints (mpc-constraints-get-current)))
1467 (if (null constraints)
1468 (unless noerror (error "No selection to push"))
1469 (mpc-ring-push mpc-constraints-ring constraints))))
1470
1471 (defun mpc-constraints-pop ()
1472 "Recall the most recently pushed selection."
1473 (interactive)
1474 (let ((constraints (mpc-ring-pop mpc-constraints-ring)))
1475 (if (null constraints)
1476 (error "No selection to return to")
1477 (mpc-constraints-restore constraints))))
1478
1479 ;;; The TagBrowser mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1480
1481 (defconst mpc-tagbrowser-all-name (propertize "*ALL*" 'face 'italic))
1482 (defvar-local mpc-tagbrowser-all-ol nil)
1483 (defvar-local mpc-tag-name nil)
1484 (defun mpc-tagbrowser-all-p ()
1485 (and (eq (point-min) (line-beginning-position))
1486 (equal mpc-tagbrowser-all-name
1487 (buffer-substring (point-min) (line-end-position)))))
1488
1489 (define-derived-mode mpc-tagbrowser-mode mpc-mode '("MPC-" mpc-tag-name)
1490 (setq-local mode-line-process '("" mpc-tag-name))
1491 (setq-local mode-line-format nil)
1492 (setq-local header-line-format '("" mpc-tag-name)) ;; "s"
1493 (setq-local buffer-undo-list t)
1494 )
1495
1496 (defun mpc-tagbrowser-refresh ()
1497 (mpc-select-save
1498 (widen)
1499 (goto-char (point-min))
1500 (cl-assert (looking-at (regexp-quote mpc-tagbrowser-all-name)))
1501 (forward-line 1)
1502 (let ((inhibit-read-only t))
1503 (delete-region (point) (point-max))
1504 (dolist (val (mpc-cmd-list mpc-tag)) (insert val "\n")))
1505 (set-buffer-modified-p nil))
1506 (mpc-reorder))
1507
1508 (defun mpc-updated-db ()
1509 ;; FIXME: This is not asynchronous, but is run from a process filter.
1510 (unless (assq 'updating_db mpc-status)
1511 (clrhash mpc--find-memoize)
1512 (dolist (buf (process-get (mpc-proc) 'buffers))
1513 (setq buf (cdr buf))
1514 (when (buffer-local-value 'mpc-tag buf)
1515 (with-current-buffer buf (with-local-quit (mpc-tagbrowser-refresh)))))
1516 (with-local-quit (mpc-songs-refresh))))
1517
1518 (defun mpc-tagbrowser-tag-name (tag)
1519 (cond
1520 ((string-match "|" (symbol-name tag))
1521 (let ((tag1 (intern (substring (symbol-name tag)
1522 0 (match-beginning 0))))
1523 (tag2 (intern (substring (symbol-name tag)
1524 (match-end 0)))))
1525 (concat (mpc-tagbrowser-tag-name tag1)
1526 " | "
1527 (mpc-tagbrowser-tag-name tag2))))
1528 ((string-match "y\\'" (symbol-name tag))
1529 (concat (substring (symbol-name tag) 0 -1) "ies"))
1530 (t (concat (symbol-name tag) "s"))))
1531
1532 (defun mpc-tagbrowser-buf (tag)
1533 (let ((buf (mpc-proc-buffer (mpc-proc) tag)))
1534 (if (buffer-live-p buf) buf
1535 (setq buf (get-buffer-create (format "*MPC %ss*" tag)))
1536 (mpc-proc-buffer (mpc-proc) tag buf)
1537 (with-current-buffer buf
1538 (let ((inhibit-read-only t))
1539 (erase-buffer)
1540 (if (member tag '(Directory))
1541 (mpc-tagbrowser-dir-mode)
1542 (mpc-tagbrowser-mode))
1543 (insert mpc-tagbrowser-all-name "\n"))
1544 (forward-line -1)
1545 (setq mpc-tag tag)
1546 (setq mpc-tag-name (mpc-tagbrowser-tag-name tag))
1547 (mpc-tagbrowser-all-select)
1548 (mpc-tagbrowser-refresh)
1549 buf))))
1550
1551 (defvar tag-browser-tagtypes
1552 (lazy-completion-table tag-browser-tagtypes
1553 (lambda ()
1554 (append '("Playlist" "Directory")
1555 (mpc-cmd-tagtypes)))))
1556
1557 (defun mpc-tagbrowser (tag)
1558 "Create a new browser for TAG."
1559 (interactive
1560 (list
1561 (let ((completion-ignore-case t))
1562 (intern
1563 (completing-read "Tag: " tag-browser-tagtypes nil 'require-match)))))
1564 (let* ((newbuf (mpc-tagbrowser-buf tag))
1565 (win (get-buffer-window newbuf 0)))
1566 (if win (select-window win)
1567 (if (with-current-buffer (window-buffer)
1568 (derived-mode-p 'mpc-tagbrowser-mode))
1569 (setq win (selected-window))
1570 ;; Find a tagbrowser-mode buffer.
1571 (let ((buffers (process-get (mpc-proc) 'buffers))
1572 buffer)
1573 (while
1574 (and buffers
1575 (not (and (buffer-live-p (setq buffer (cdr (pop buffers))))
1576 (with-current-buffer buffer
1577 (derived-mode-p 'mpc-tagbrowser-mode))
1578 (setq win (get-buffer-window buffer 0))))))))
1579 (if (not win)
1580 (pop-to-buffer newbuf)
1581 (setq win (split-window win nil 'horiz))
1582 (set-window-buffer win newbuf)
1583 (set-window-dedicated-p win 'soft)
1584 (select-window win)
1585 (balance-windows-area)))))
1586
1587 (defun mpc-tagbrowser-all-select ()
1588 "Select the special *ALL* entry if no other is selected."
1589 (if mpc-select
1590 (delete-overlay mpc-tagbrowser-all-ol)
1591 (save-excursion
1592 (goto-char (point-min))
1593 (if mpc-tagbrowser-all-ol
1594 (move-overlay mpc-tagbrowser-all-ol
1595 (point) (line-beginning-position 2))
1596 (let ((ol (make-overlay (point) (line-beginning-position 2))))
1597 (overlay-put ol 'face 'highlight)
1598 (overlay-put ol 'evaporate t)
1599 (setq-local mpc-tagbrowser-all-ol ol))))))
1600
1601 ;; (defvar mpc-constraints nil)
1602 (defun mpc-separator (active)
1603 ;; Place a separator mark.
1604 (unless mpc-separator-ol
1605 (setq-local mpc-separator-ol
1606 (make-overlay (point) (point)))
1607 (overlay-put mpc-separator-ol 'after-string
1608 (propertize "\n"
1609 'face '(:height 0.05 :inverse-video t))))
1610 (goto-char (point-min))
1611 (forward-line 1)
1612 (while
1613 (and (member (buffer-substring-no-properties
1614 (line-beginning-position) (line-end-position))
1615 active)
1616 (zerop (forward-line 1))))
1617 (if (or (eobp) (null active))
1618 (delete-overlay mpc-separator-ol)
1619 (move-overlay mpc-separator-ol (1- (point)) (point))))
1620
1621 (defun mpc-sort (active)
1622 ;; Sort the active elements at the front.
1623 (let ((inhibit-read-only t))
1624 (goto-char (point-min))
1625 (if (mpc-tagbrowser-all-p) (forward-line 1))
1626 (condition-case nil
1627 (sort-subr nil 'forward-line 'end-of-line
1628 nil nil
1629 (lambda (s1 s2)
1630 (setq s1 (buffer-substring-no-properties
1631 (car s1) (cdr s1)))
1632 (setq s2 (buffer-substring-no-properties
1633 (car s2) (cdr s2)))
1634 (cond
1635 ((member s1 active)
1636 (if (member s2 active)
1637 (let ((cmp (mpc-compare-strings s1 s2 t)))
1638 (and (numberp cmp) (< cmp 0)))
1639 t))
1640 ((member s2 active) nil)
1641 (t (let ((cmp (mpc-compare-strings s1 s2 t)))
1642 (and (numberp cmp) (< cmp 0)))))))
1643 ;; The comparison predicate arg is new in Emacs-22.
1644 (wrong-number-of-arguments
1645 (sort-subr nil 'forward-line 'end-of-line
1646 (lambda ()
1647 (let ((name (buffer-substring-no-properties
1648 (point) (line-end-position))))
1649 (cond
1650 ((member name active) (concat "1" name))
1651 (t (concat "2" "name"))))))))))
1652
1653 (defvar mpc--changed-selection)
1654
1655 (defun mpc-reorder (&optional nodeactivate)
1656 "Reorder entries based on the currently active selections.
1657 I.e. split the current browser buffer into a first part containing the
1658 entries included in the selection, then a separator, and then the entries
1659 not included in the selection.
1660 Return non-nil if a selection was deactivated."
1661 (mpc-select-save
1662 (let ((constraints (mpc-constraints-get-current (current-buffer)))
1663 (active 'all))
1664 ;; (unless (equal constraints mpc-constraints)
1665 ;; (setq-local mpc-constraints constraints)
1666 (dolist (cst constraints)
1667 (let ((vals (apply 'mpc-union
1668 (mapcar (lambda (val)
1669 (mpc-cmd-list mpc-tag (car cst) val))
1670 (cdr cst)))))
1671 (setq active
1672 (if (listp active) (mpc-intersection active vals) vals))))
1673
1674 (when (listp active)
1675 ;; Remove the selections if they are all in conflict with
1676 ;; other constraints.
1677 (let ((deactivate t))
1678 (dolist (sel selection)
1679 (when (member sel active) (setq deactivate nil)))
1680 (when deactivate
1681 ;; Variable declared/used by `mpc-select-save'.
1682 (when selection
1683 (setq mpc--changed-selection t))
1684 (unless nodeactivate
1685 (setq selection nil)
1686 (mapc 'delete-overlay mpc-select)
1687 (setq mpc-select nil)
1688 (mpc-tagbrowser-all-select))))
1689
1690 ;; Don't bother splitting the "active" elements to the first part if
1691 ;; they're the same as the selection.
1692 (when (equal (sort (copy-sequence active) #'string-lessp)
1693 (sort (copy-sequence selection) #'string-lessp))
1694 (setq active 'all)))
1695
1696 ;; FIXME: This `mpc-sort' takes a lot of time. Maybe we should
1697 ;; be more clever and presume the buffer is mostly sorted already.
1698 (mpc-sort (if (listp active) active))
1699 (mpc-separator (if (listp active) active)))))
1700
1701 (defun mpc-selection-refresh ()
1702 (let ((mpc--changed-selection t))
1703 (while mpc--changed-selection
1704 (setq mpc--changed-selection nil)
1705 (dolist (buf (process-get (mpc-proc) 'buffers))
1706 (setq buf (cdr buf))
1707 (when (and (buffer-local-value 'mpc-tag buf)
1708 (not (eq buf (current-buffer))))
1709 (with-current-buffer buf (mpc-reorder)))))
1710 ;; FIXME: reorder the current buffer last and prevent deactivation,
1711 ;; since whatever selection we made here is the most recent one
1712 ;; and should hence take precedence.
1713 (when mpc-tag (mpc-reorder 'nodeactivate))
1714 ;; FIXME: comment?
1715 (if (and mpc--song-search mpc--changed-selection)
1716 (progn
1717 (setq mpc--song-search nil)
1718 (mpc-selection-refresh))
1719 (mpc-songs-refresh))))
1720
1721 ;;; Hierarchical tagbrowser ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1722 ;; Todo:
1723 ;; - Add a button on each dir to open/close it (?)
1724 ;; - add the parent dir on the previous line, grayed-out, if it's not
1725 ;; present (because we're in the non-selected part and the parent is
1726 ;; in the selected part).
1727
1728 (defvar mpc-tagbrowser-dir-mode-map
1729 (let ((map (make-sparse-keymap)))
1730 (set-keymap-parent map mpc-tagbrowser-mode-map)
1731 (define-key map [?\M-\C-m] 'mpc-tagbrowser-dir-toggle)
1732 map))
1733
1734 ;; (defvar mpc-tagbrowser-dir-keywords
1735 ;; '(mpc-tagbrowser-dir-hide-prefix))
1736
1737 (define-derived-mode mpc-tagbrowser-dir-mode mpc-tagbrowser-mode '("MPC-" mpc-tag-name)
1738 ;; (setq-local font-lock-defaults
1739 ;; '(mpc-tagbrowser-dir-keywords t))
1740 )
1741
1742 ;; (defun mpc-tagbrowser-dir-hide-prefix (limit)
1743 ;; (while
1744 ;; (let ((prev (buffer-substring (line-beginning-position 0)
1745 ;; (line-end-position 0))))
1746 ;; (
1747
1748 (defun mpc-tagbrowser-dir-toggle (event)
1749 "Open or close the element at point."
1750 (interactive (list last-nonmenu-event))
1751 (mpc-event-set-point event)
1752 (let ((name (buffer-substring (line-beginning-position)
1753 (line-end-position)))
1754 (prop (intern mpc-tag))
1755 (proc (mpc-proc)))
1756 (if (not (member name (process-get proc prop)))
1757 (process-put proc prop
1758 (cons name (process-get proc prop)))
1759 (let ((new (delete name (process-get proc prop))))
1760 (setq name (concat name "/"))
1761 (process-put proc prop
1762 (delq nil
1763 (mapcar (lambda (x)
1764 (if (string-prefix-p name x)
1765 nil x))
1766 new)))))
1767 (mpc-tagbrowser-refresh)))
1768
1769
1770 ;;; Playlist management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1771
1772 (defvar-local mpc-songs-playlist nil
1773 "Name of the currently selected playlist, if any.
1774 A value of t means the main playlist.")
1775
1776 (defun mpc-playlist-create (name)
1777 "Save current playlist under name NAME."
1778 (interactive "sPlaylist name: ")
1779 (mpc-proc-cmd (list "save" name))
1780 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1781 (when (buffer-live-p buf)
1782 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1783
1784 (defun mpc-playlist-destroy (name)
1785 "Delete playlist named NAME."
1786 (interactive
1787 (list (completing-read "Delete playlist: " (mpc-cmd-list 'Playlist)
1788 nil 'require-match)))
1789 (mpc-proc-cmd (list "rm" name))
1790 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1791 (when (buffer-live-p buf)
1792 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1793
1794 (defun mpc-playlist-rename (oldname newname)
1795 "Rename playlist OLDNAME to NEWNAME."
1796 (interactive
1797 (let* ((oldname (if (and (eq mpc-tag 'Playlist) (null current-prefix-arg))
1798 (buffer-substring (line-beginning-position)
1799 (line-end-position))
1800 (completing-read "Rename playlist: "
1801 (mpc-cmd-list 'Playlist)
1802 nil 'require-match)))
1803 (newname (read-string (format-message "Rename `%s' to: " oldname))))
1804 (if (zerop (length newname))
1805 (error "Aborted")
1806 (list oldname newname))))
1807 (mpc-proc-cmd (list "rename" oldname newname))
1808 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1809 (if (buffer-live-p buf)
1810 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1811
1812 (defun mpc-playlist ()
1813 "Show the current playlist."
1814 (interactive)
1815 (mpc-constraints-push 'noerror)
1816 (mpc-constraints-restore '()))
1817
1818 (defun mpc-playlist-add ()
1819 "Add the selection to the playlist."
1820 (interactive)
1821 (let ((songs (mapcar #'car (mpc-songs-selection))))
1822 (mpc-cmd-add songs)
1823 (message "Appended %d songs" (length songs))
1824 ;; Return the songs added. Used in `mpc-play'.
1825 songs))
1826
1827 (defun mpc-playlist-delete ()
1828 "Remove the selected songs from the playlist."
1829 (interactive)
1830 (unless mpc-songs-playlist
1831 (error "The selected songs aren't part of a playlist"))
1832 (let ((song-poss (mapcar #'cdr (mpc-songs-selection))))
1833 (mpc-cmd-delete song-poss mpc-songs-playlist)
1834 (mpc-songs-refresh)
1835 (message "Deleted %d songs" (length song-poss))))
1836
1837 ;;; Volume management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1838
1839 (defvar mpc-volume-map
1840 (let ((map (make-sparse-keymap)))
1841 ;; Bind the up-events rather than the down-event, so the
1842 ;; `message' isn't canceled by the subsequent up-event binding.
1843 (define-key map [down-mouse-1] 'ignore)
1844 (define-key map [mouse-1] 'mpc-volume-mouse-set)
1845 (define-key map [header-line mouse-1] 'mpc-volume-mouse-set)
1846 (define-key map [header-line down-mouse-1] 'ignore)
1847 (define-key map [mode-line mouse-1] 'mpc-volume-mouse-set)
1848 (define-key map [mode-line down-mouse-1] 'ignore)
1849 map))
1850
1851 (defvar mpc-volume nil) (put 'mpc-volume 'risky-local-variable t)
1852
1853 (defun mpc-volume-refresh ()
1854 ;; Maintain the volume.
1855 (setq mpc-volume
1856 (mpc-volume-widget
1857 (string-to-number (cdr (assq 'volume mpc-status)))))
1858 (let ((status-buf (mpc-proc-buffer (mpc-proc) 'status)))
1859 (when (buffer-live-p status-buf)
1860 (with-current-buffer status-buf (force-mode-line-update)))))
1861
1862 (defvar mpc-volume-step 5)
1863
1864 (defun mpc-volume-mouse-set (&optional event)
1865 "Change volume setting."
1866 (interactive (list last-nonmenu-event))
1867 (let* ((posn (event-start event))
1868 (diff
1869 (if (memq (if (stringp (car-safe (posn-object posn)))
1870 (aref (car (posn-object posn)) (cdr (posn-object posn)))
1871 (with-current-buffer (window-buffer (posn-window posn))
1872 (char-after (posn-point posn))))
1873 '(?◁ ?<))
1874 (- mpc-volume-step) mpc-volume-step))
1875 (curvol (string-to-number (cdr (assq 'volume mpc-status))))
1876 (newvol (max 0 (min 100 (+ curvol diff)))))
1877 (if (= newvol curvol)
1878 (progn
1879 (message "MPD volume already at %s%%" newvol)
1880 (ding))
1881 (mpc-proc-cmd (list "setvol" newvol) 'mpc-status-refresh)
1882 (message "Set MPD volume to %s%%" newvol))))
1883
1884 (defun mpc-volume-widget (vol &optional size)
1885 (unless size (setq size 12.5))
1886 (let ((scaledvol (* (/ vol 100.0) size)))
1887 ;; (message "Volume sizes: %s - %s" (/ vol fact) (/ (- 100 vol) fact))
1888 (list (propertize "<" ;; "◁"
1889 ;; 'face 'default
1890 'keymap mpc-volume-map
1891 'face '(:box (:line-width -2 :style pressed-button))
1892 'mouse-face '(:box (:line-width -2 :style released-button)))
1893 " "
1894 (propertize "a"
1895 'display (list 'space :width scaledvol)
1896 'face '(:inverse-video t
1897 :box (:line-width -2 :style released-button)))
1898 (propertize "a"
1899 'display (list 'space :width (- size scaledvol))
1900 'face '(:box (:line-width -2 :style released-button)))
1901 " "
1902 (propertize ">" ;; "▷"
1903 ;; 'face 'default
1904 'keymap mpc-volume-map
1905 'face '(:box (:line-width -2 :style pressed-button))
1906 'mouse-face '(:box (:line-width -2 :style released-button))))))
1907
1908 ;;; MPC songs mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1909
1910 (defvar mpc-current-song nil) (put 'mpc-current-song 'risky-local-variable t)
1911 (defvar mpc-current-updating nil) (put 'mpc-current-updating 'risky-local-variable t)
1912 (defvar mpc-songs-format-description nil) (put 'mpc-songs-format-description 'risky-local-variable t)
1913
1914 (defvar mpc-previous-window-config nil)
1915
1916 (defvar mpc-songs-mode-map
1917 (let ((map (make-sparse-keymap)))
1918 (define-key map [remap mpc-select] 'mpc-songs-jump-to)
1919 map))
1920
1921 (defvar mpc-songpointer-set-visible nil)
1922
1923 (defvar mpc-songs-hashcons (make-hash-table :test 'equal :weakness t)
1924 "Make song file name objects unique via hash consing.
1925 This is used so that they can be compared with `eq', which is needed for
1926 `text-property-any'.")
1927 (defun mpc-songs-hashcons (name)
1928 (or (gethash name mpc-songs-hashcons) (puthash name name mpc-songs-hashcons)))
1929 (defcustom mpc-songs-format "%2{Disc--}%3{Track} %-5{Time} %25{Title} %20{Album} %20{Artist} %5{Date}"
1930 "Format used to display each song in the list of songs."
1931 :type 'string)
1932
1933 (defvar mpc-songs-totaltime)
1934
1935 (defun mpc-songs-refresh ()
1936 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
1937 (when (buffer-live-p buf)
1938 (with-current-buffer buf
1939 (let ((constraints (mpc-constraints-get-current (current-buffer)))
1940 (dontsort nil)
1941 (inhibit-read-only t)
1942 (totaltime 0)
1943 (curline (cons (count-lines (point-min)
1944 (line-beginning-position))
1945 (buffer-substring (line-beginning-position)
1946 (line-end-position))))
1947 active)
1948 (setq mpc-songs-playlist nil)
1949 (if (null constraints)
1950 ;; When there are no constraints, rather than show the list of
1951 ;; all songs (which could take a while to download and
1952 ;; format), we show the current playlist.
1953 ;; FIXME: it would be good to be able to show the complete
1954 ;; list, but that would probably require us to format it
1955 ;; on-the-fly to make it bearable.
1956 (setq dontsort t
1957 mpc-songs-playlist t
1958 active (mpc-proc-buf-to-alists
1959 (mpc-proc-cmd "playlistinfo")))
1960 (dolist (cst constraints)
1961 (if (and (eq (car cst) 'Playlist)
1962 (= 1 (length (cdr cst))))
1963 (setq mpc-songs-playlist (cadr cst)))
1964 ;; We don't do anything really special here for playlists,
1965 ;; because it's unclear what's a correct "union" of playlists.
1966 (let ((vals (apply 'mpc-union
1967 (mapcar (lambda (val)
1968 (mpc-cmd-find (car cst) val))
1969 (cdr cst)))))
1970 (setq active (cond
1971 ((null active)
1972 (if (eq (car cst) 'Playlist)
1973 (setq dontsort t))
1974 vals)
1975 ((or dontsort
1976 ;; Try to preserve ordering and
1977 ;; repetitions from playlists.
1978 (not (eq (car cst) 'Playlist)))
1979 (mpc-intersection active vals
1980 (lambda (x) (assq 'file x))))
1981 (t
1982 (setq dontsort t)
1983 (mpc-intersection vals active
1984 (lambda (x)
1985 (assq 'file x)))))))))
1986 (mpc-select-save
1987 (erase-buffer)
1988 ;; Sorting songs is surprisingly difficult: when comparing two
1989 ;; songs with the same album name but different artist name, you
1990 ;; have to know whether these are two different albums (with the
1991 ;; same name) or a single album (typically a compilation).
1992 ;; I punt on it and just use file-name sorting, which does the
1993 ;; right thing if your library is properly arranged.
1994 (dolist (song (if dontsort active
1995 (sort (copy-sequence active)
1996 (lambda (song1 song2)
1997 (let ((cmp (mpc-compare-strings
1998 (cdr (assq 'file song1))
1999 (cdr (assq 'file song2)))))
2000 (and (integerp cmp) (< cmp 0)))))))
2001 (cl-incf totaltime (string-to-number (or (cdr (assq 'Time song)) "0")))
2002 (mpc-format mpc-songs-format song)
2003 (delete-char (- (skip-chars-backward " "))) ;Remove trailing space.
2004 (insert "\n")
2005 (put-text-property
2006 (line-beginning-position 0) (line-beginning-position)
2007 'mpc-file (mpc-songs-hashcons (cdr (assq 'file song))))
2008 (let ((pos (assq 'Pos song)))
2009 (if pos
2010 (put-text-property
2011 (line-beginning-position 0) (line-beginning-position)
2012 'mpc-file-pos (string-to-number (cdr pos)))))
2013 ))
2014 (goto-char (point-min))
2015 (forward-line (car curline))
2016 (if (or (search-forward (cdr curline) nil t)
2017 (search-backward (cdr curline) nil t))
2018 (beginning-of-line)
2019 (goto-char (point-min)))
2020 (setq-local mpc-songs-totaltime
2021 (unless (zerop totaltime)
2022 (list " " (mpc-secs-to-time totaltime))))
2023 ))))
2024 (let ((mpc-songpointer-set-visible t))
2025 (mpc-songpointer-refresh)))
2026
2027 (defun mpc-songs-search (string)
2028 "Filter songs to those who include STRING in their metadata."
2029 (interactive "sSearch for: ")
2030 (setq mpc--song-search
2031 (if (zerop (length string)) nil string))
2032 (let ((mpc--changed-selection t))
2033 (while mpc--changed-selection
2034 (setq mpc--changed-selection nil)
2035 (dolist (buf (process-get (mpc-proc) 'buffers))
2036 (setq buf (cdr buf))
2037 (when (buffer-local-value 'mpc-tag buf)
2038 (with-current-buffer buf (mpc-reorder))))
2039 (mpc-songs-refresh))))
2040
2041 (defun mpc-songs-kill-search ()
2042 "Turn off the current search restriction."
2043 (interactive)
2044 (mpc-songs-search nil))
2045
2046 (defun mpc-songs-selection ()
2047 "Return the list of songs currently selected."
2048 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2049 (when (buffer-live-p buf)
2050 (with-current-buffer buf
2051 (save-excursion
2052 (let ((files ()))
2053 (if mpc-select
2054 (dolist (ol mpc-select)
2055 (push (cons
2056 (get-text-property (overlay-start ol) 'mpc-file)
2057 (get-text-property (overlay-start ol) 'mpc-file-pos))
2058 files))
2059 (goto-char (point-min))
2060 (while (not (eobp))
2061 (push (cons
2062 (get-text-property (point) 'mpc-file)
2063 (get-text-property (point) 'mpc-file-pos))
2064 files)
2065 (forward-line 1)))
2066 (nreverse files)))))))
2067
2068 (defun mpc-songs-jump-to (song-file &optional posn)
2069 "Jump to song SONG-FILE; interactively, this is the song at point."
2070 (interactive
2071 (let* ((event last-nonmenu-event)
2072 (posn (event-end event)))
2073 (with-selected-window (posn-window posn)
2074 (goto-char (posn-point posn))
2075 (list (get-text-property (point) 'mpc-file)
2076 posn))))
2077 (let* ((plbuf (mpc-proc-cmd "playlist"))
2078 (re (if song-file
2079 ;; Newer MPCs apparently include "file: " in the buffer.
2080 (concat "^\\([0-9]+\\):\\(?:file: \\)?"
2081 (regexp-quote song-file) "$")))
2082 (sn (with-current-buffer plbuf
2083 (goto-char (point-min))
2084 (when (and re (re-search-forward re nil t))
2085 (match-string 1)))))
2086 (cond
2087 ((null re) (posn-set-point posn))
2088 ((null sn) (user-error "This song is not in the playlist"))
2089 ((null (with-current-buffer plbuf (re-search-forward re nil t)))
2090 ;; song-file only appears once in the playlist: no ambiguity,
2091 ;; we're good to go!
2092 (mpc-proc-cmd (list "play" sn)))
2093 (t
2094 ;; The song appears multiple times in the playlist. If the current
2095 ;; buffer holds not only the destination song but also the current
2096 ;; song, then we will move in the playlist to the same relative
2097 ;; position as in the buffer. Otherwise, we will simply choose the
2098 ;; song occurrence closest to the current song.
2099 (with-selected-window (posn-window posn)
2100 (let* ((cur (and (markerp overlay-arrow-position)
2101 (marker-position overlay-arrow-position)))
2102 (dest (save-excursion
2103 (goto-char (posn-point posn))
2104 (line-beginning-position)))
2105 (lines (when cur (* (if (< cur dest) 1 -1)
2106 (count-lines cur dest)))))
2107 (with-current-buffer plbuf
2108 (goto-char (point-min))
2109 ;; Start the search from the current song.
2110 (forward-line (string-to-number
2111 (or (cdr (assq 'song mpc-status)) "0")))
2112 ;; If the current song is also displayed in the buffer,
2113 ;; then try to move to the same relative position.
2114 (if lines (forward-line lines))
2115 ;; Now search the closest occurrence.
2116 (let* ((next (save-excursion
2117 (when (re-search-forward re nil t)
2118 (cons (point) (match-string 1)))))
2119 (prev (save-excursion
2120 (when (re-search-backward re nil t)
2121 (cons (point) (match-string 1)))))
2122 (sn (cdr (if (and next prev)
2123 (if (< (- (car next) (point))
2124 (- (point) (car prev)))
2125 next prev)
2126 (or next prev)))))
2127 (cl-assert sn)
2128 (mpc-proc-cmd (concat "play " sn))))))))))
2129
2130 (define-derived-mode mpc-songs-mode mpc-mode "MPC-song"
2131 (setq mpc-songs-format-description
2132 (with-temp-buffer (mpc-format mpc-songs-format 'self) (buffer-string)))
2133 (setq-local header-line-format
2134 ;; '("MPC " mpc-volume " " mpc-current-song)
2135 (list (propertize " " 'display '(space :align-to 0))
2136 ;; 'mpc-songs-format-description
2137 '(:eval
2138 (let ((hscroll (window-hscroll)))
2139 (with-temp-buffer
2140 (mpc-format mpc-songs-format 'self hscroll)
2141 ;; That would be simpler than the hscroll handling in
2142 ;; mpc-format, but currently move-to-column does not
2143 ;; recognize :space display properties.
2144 ;; (move-to-column hscroll)
2145 ;; (delete-region (point-min) (point))
2146 (buffer-string))))))
2147 (setq-local
2148 mode-line-format
2149 '("%e" mode-line-frame-identification mode-line-buffer-identification
2150 #(" " 0 3
2151 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2152 mode-line-position
2153 #(" " 0 2
2154 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2155 mpc-songs-totaltime
2156 mpc-current-updating
2157 #(" " 0 2
2158 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2159 (mpc--song-search
2160 (:propertize
2161 ("Search=\"" mpc--song-search "\"")
2162 help-echo "mouse-2: kill this search"
2163 follow-link t
2164 mouse-face mode-line-highlight
2165 keymap (keymap (mode-line keymap
2166 (mouse-2 . mpc-songs-kill-search))))
2167 (:propertize "NoSearch"
2168 help-echo "mouse-2: set a search restriction"
2169 follow-link t
2170 mouse-face mode-line-highlight
2171 keymap (keymap (mode-line keymap (mouse-2 . mpc-songs-search)))))))
2172
2173 ;; (setq-local mode-line-process
2174 ;; '("" ;; mpc-volume " "
2175 ;; mpc-songs-totaltime
2176 ;; mpc-current-updating))
2177 )
2178
2179 (defun mpc-songpointer-set (pos)
2180 (let* ((win (get-buffer-window (current-buffer) t))
2181 (visible (when win
2182 (or mpc-songpointer-set-visible
2183 (and (markerp overlay-arrow-position)
2184 (eq (marker-buffer overlay-arrow-position)
2185 (current-buffer))
2186 (<= (window-start win) overlay-arrow-position)
2187 (< overlay-arrow-position (window-end win)))))))
2188 (unless (local-variable-p 'overlay-arrow-position)
2189 (setq-local overlay-arrow-position (make-marker)))
2190 (move-marker overlay-arrow-position pos)
2191 ;; If the arrow was visible, try to keep it that way.
2192 (if (and visible pos
2193 (or (> (window-start win) pos) (>= pos (window-end win t))))
2194 (set-window-point win pos))))
2195
2196 (defun mpc-songpointer-refresh ()
2197 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2198 (when (buffer-live-p buf)
2199 (with-current-buffer buf
2200 (let* ((pos (text-property-any
2201 (point-min) (point-max)
2202 'mpc-file (mpc-songs-hashcons
2203 (cdr (assq 'file mpc-status)))))
2204 (other (when pos
2205 (save-excursion
2206 (goto-char pos)
2207 (text-property-any
2208 (line-beginning-position 2) (point-max)
2209 'mpc-file (mpc-songs-hashcons
2210 (cdr (assq 'file mpc-status))))))))
2211 (if other
2212 ;; The song appears multiple times in the buffer.
2213 ;; We need to be careful to choose the right occurrence.
2214 (mpc-proc-cmd "playlist" 'mpc-songpointer-refresh-hairy)
2215 (mpc-songpointer-set pos)))))))
2216
2217 (defun mpc-songpointer-context (size plbuf)
2218 (with-current-buffer plbuf
2219 (goto-char (point-min))
2220 (forward-line (string-to-number (or (cdr (assq 'song mpc-status)) "0")))
2221 (let ((context-before '())
2222 (context-after '()))
2223 (save-excursion
2224 (dotimes (_i size)
2225 (when (re-search-backward "^[0-9]+:\\(.*\\)" nil t)
2226 (push (mpc-songs-hashcons (match-string 1)) context-before))))
2227 ;; Skip the actual current song.
2228 (forward-line 1)
2229 (dotimes (_i size)
2230 (when (re-search-forward "^[0-9]+:\\(.*\\)" nil t)
2231 (push (mpc-songs-hashcons (match-string 1)) context-after)))
2232 ;; If there isn't `size' context, then return nil.
2233 (unless (and (< (length context-before) size)
2234 (< (length context-after) size))
2235 (cons (nreverse context-before) (nreverse context-after))))))
2236
2237 (defun mpc-songpointer-score (context pos)
2238 (let ((count 0))
2239 (goto-char pos)
2240 (dolist (song (car context))
2241 (and (zerop (forward-line -1))
2242 (eq (get-text-property (point) 'mpc-file) song)
2243 (cl-incf count)))
2244 (goto-char pos)
2245 (dolist (song (cdr context))
2246 (and (zerop (forward-line 1))
2247 (eq (get-text-property (point) 'mpc-file) song)
2248 (cl-incf count)))
2249 count))
2250
2251 (defun mpc-songpointer-refresh-hairy ()
2252 ;; Based on the complete playlist, we should figure out where in the
2253 ;; song buffer is the currently playing song.
2254 (let ((plbuf (current-buffer))
2255 (buf (mpc-proc-buffer (mpc-proc) 'songs)))
2256 (when (buffer-live-p buf)
2257 (with-current-buffer buf
2258 (let* ((context-size 0)
2259 (context '(() . ()))
2260 (pos (text-property-any
2261 (point-min) (point-max)
2262 'mpc-file (mpc-songs-hashcons
2263 (cdr (assq 'file mpc-status)))))
2264 (score 0)
2265 (other pos))
2266 (while
2267 (setq other
2268 (save-excursion
2269 (goto-char other)
2270 (text-property-any
2271 (line-beginning-position 2) (point-max)
2272 'mpc-file (mpc-songs-hashcons
2273 (cdr (assq 'file mpc-status))))))
2274 ;; There is an `other' contestant.
2275 (let ((other-score (mpc-songpointer-score context other)))
2276 (cond
2277 ;; `other' is worse: try the next one.
2278 ((< other-score score) nil)
2279 ;; `other' is better: remember it and then search further.
2280 ((> other-score score)
2281 (setq pos other)
2282 (setq score other-score))
2283 ;; Both are equal and increasing the context size won't help.
2284 ;; Arbitrarily choose one of the two and keep looking
2285 ;; for a better match.
2286 ((< score context-size) nil)
2287 (t
2288 ;; Score is equal and increasing context might help: try it.
2289 (cl-incf context-size)
2290 (let ((new-context
2291 (mpc-songpointer-context context-size plbuf)))
2292 (if (null new-context)
2293 ;; There isn't more context: choose one arbitrarily
2294 ;; and keep looking for a better match elsewhere.
2295 (cl-decf context-size)
2296 (setq context new-context)
2297 (setq score (mpc-songpointer-score context pos))
2298 (save-excursion
2299 (goto-char other)
2300 ;; Go back one line so we find `other' again.
2301 (setq other (line-beginning-position 0)))))))))
2302 (mpc-songpointer-set pos))))))
2303
2304 (defun mpc-current-refresh ()
2305 ;; Maintain the current data.
2306 (mpc-status-buffer-refresh)
2307 (setq mpc-current-updating
2308 (if (assq 'updating_db mpc-status) " Updating-DB"))
2309 (ignore-errors
2310 (setq mpc-current-song
2311 (when (assq 'file mpc-status)
2312 (concat " "
2313 (mpc-secs-to-time (cdr (assq 'time mpc-status)))
2314 " "
2315 (cdr (assq 'Title mpc-status))
2316 " ("
2317 (cdr (assq 'Artist mpc-status))
2318 " / "
2319 (cdr (assq 'Album mpc-status))
2320 ")"))))
2321 (force-mode-line-update t))
2322
2323 (defun mpc-songs-buf ()
2324 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2325 (if (buffer-live-p buf) buf
2326 (with-current-buffer (setq buf (get-buffer-create "*MPC-Songs*"))
2327 (mpc-proc-buffer (mpc-proc) 'songs buf)
2328 (mpc-songs-mode)
2329 buf))))
2330
2331 (defun mpc-update ()
2332 "Tell MPD to refresh its database."
2333 (interactive)
2334 (mpc-cmd-update))
2335
2336 (defun mpc-quit ()
2337 "Quit Music Player Daemon."
2338 (interactive)
2339 (let* ((proc mpc-proc)
2340 (bufs (mapcar 'cdr (if proc (process-get proc 'buffers))))
2341 (wins (mapcar (lambda (buf) (get-buffer-window buf 0)) bufs))
2342 (song-buf (mpc-songs-buf))
2343 frames)
2344 ;; Collect all the frames where MPC buffers appear.
2345 (dolist (win wins)
2346 (when (and win (not (memq (window-frame win) frames)))
2347 (push (window-frame win) frames)))
2348 (if (and frames song-buf
2349 (with-current-buffer song-buf mpc-previous-window-config))
2350 (progn
2351 (select-frame (car frames))
2352 (set-window-configuration
2353 (with-current-buffer song-buf mpc-previous-window-config)))
2354 ;; Now delete the ones that show nothing else than MPC buffers.
2355 (dolist (frame frames)
2356 (let ((delete t))
2357 (dolist (win (window-list frame))
2358 (unless (memq (window-buffer win) bufs) (setq delete nil)))
2359 (if delete (ignore-errors (delete-frame frame))))))
2360 ;; Then kill the buffers.
2361 (mapc 'kill-buffer bufs)
2362 (mpc-status-stop)
2363 (if proc (delete-process proc))))
2364
2365 (defun mpc-consume ()
2366 "Toggle consume mode: removing played songs from the playlist."
2367 (interactive)
2368 (mpc-cmd-consume
2369 (if (string= "0" (cdr (assq 'consume (mpc-cmd-status)))) "1" "0")))
2370
2371 (defun mpc-repeat ()
2372 "Toggle repeat mode."
2373 (interactive)
2374 (mpc-cmd-repeat
2375 (if (string= "0" (cdr (assq 'repeat (mpc-cmd-status)))) "1" "0")))
2376
2377 (defun mpc-single ()
2378 "Toggle single mode."
2379 (interactive)
2380 (mpc-cmd-single
2381 (if (string= "0" (cdr (assq 'single (mpc-cmd-status)))) "1" "0")))
2382
2383 (defun mpc-shuffle ()
2384 "Toggle shuffling of the playlist (random mode)."
2385 (interactive)
2386 (mpc-cmd-random
2387 (if (string= "0" (cdr (assq 'random (mpc-cmd-status)))) "1" "0")))
2388
2389 (defun mpc-stop ()
2390 "Stop playing the current queue of songs."
2391 (interactive)
2392 (mpc-cmd-stop)
2393 (mpc-cmd-clear)
2394 (mpc-status-refresh))
2395
2396 (defun mpc-pause ()
2397 "Pause playing."
2398 (interactive)
2399 (mpc-cmd-pause "1"))
2400
2401 (defun mpc-resume ()
2402 "Resume playing."
2403 (interactive)
2404 (mpc-cmd-pause "0"))
2405
2406 (defun mpc-toggle-play ()
2407 "Toggle between play and pause.
2408 If stopped, start playback."
2409 (interactive)
2410 (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2411 (mpc-cmd-play)
2412 (if (member (cdr (assq 'state (mpc-cmd-status))) '("pause"))
2413 (mpc-resume)
2414 (mpc-pause))))
2415
2416 (defun mpc-play ()
2417 "Start playing whatever is selected."
2418 (interactive)
2419 (if (member (cdr (assq 'state (mpc-cmd-status))) '("pause"))
2420 (mpc-resume)
2421 ;; When playing the playlist ends, the playlist isn't cleared, but the
2422 ;; user probably doesn't want to re-listen to it before getting to
2423 ;; listen to what he just selected.
2424 ;; (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2425 ;; (mpc-cmd-clear))
2426 ;; Actually, we don't use mpc-play to append to the playlist any more,
2427 ;; so we can just always empty the playlist.
2428 (mpc-cmd-clear)
2429 (if (mpc-playlist-add)
2430 (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2431 (mpc-cmd-play))
2432 (user-error "Don't know what to play"))))
2433
2434 (defun mpc-next ()
2435 "Jump to the next song in the queue."
2436 (interactive)
2437 (mpc-proc-cmd "next")
2438 (mpc-status-refresh))
2439
2440 (defun mpc-prev ()
2441 "Jump to the beginning of the current song, or to the previous song."
2442 (interactive)
2443 (let ((time (cdr (assq 'time mpc-status))))
2444 ;; Here we rely on the fact that string-to-number silently ignores
2445 ;; everything after a non-digit char.
2446 (cond
2447 ;; Go back to the beginning of current song.
2448 ((and time (> (string-to-number time) 0))
2449 (mpc-proc-cmd (list "seekid" (cdr (assq 'songid mpc-status)) 0)))
2450 ;; We're at the beginning of the first song of the playlist.
2451 ;; Fetch the previous one from `mpc-queue-back'.
2452 ;; ((and (zerop (string-to-number (cdr (assq 'song mpc-status))))
2453 ;; mpc-queue-back)
2454 ;; ;; Because we use cmd-list rather than cmd-play, the queue is not
2455 ;; ;; automatically updated.
2456 ;; (let ((prev (pop mpc-queue-back)))
2457 ;; (push prev mpc-queue)
2458 ;; (mpc-proc-cmd
2459 ;; (mpc-proc-cmd-list
2460 ;; (list (list "add" prev)
2461 ;; (list "move" (cdr (assq 'playlistlength mpc-status)) "0")
2462 ;; "previous")))))
2463 ;; We're at the beginning of a song, but not the first one.
2464 (t (mpc-proc-cmd "previous")))
2465 (mpc-status-refresh)))
2466
2467 (defvar mpc-last-seek-time '(0 . 0))
2468
2469 (defun mpc--faster (event speedup step)
2470 "Fast forward."
2471 (interactive (list last-nonmenu-event))
2472 (let ((repeat-delay (/ (abs (float step)) speedup)))
2473 (if (not (memq 'down (event-modifiers event)))
2474 (let* ((currenttime (float-time))
2475 (last-time (- currenttime (car mpc-last-seek-time))))
2476 (if (< last-time (* 0.9 repeat-delay))
2477 nil ;; Throttle
2478 (let* ((status (if (< last-time 1.0)
2479 mpc-status (mpc-cmd-status)))
2480 (songid (cdr (assq 'songid status)))
2481 (time (if songid
2482 (if (< last-time 1.0)
2483 (cdr mpc-last-seek-time)
2484 (string-to-number
2485 (cdr (assq 'time status)))))))
2486 (setq mpc-last-seek-time
2487 (cons currenttime (setq time (+ time step))))
2488 (mpc-proc-cmd (list "seekid" songid time)
2489 'mpc-status-refresh))))
2490 (let ((status (mpc-cmd-status)))
2491 (let* ((songid (cdr (assq 'songid status)))
2492 (time (if songid (string-to-number
2493 (cdr (assq 'time status))))))
2494 (let ((timer (run-with-timer
2495 t repeat-delay
2496 (lambda ()
2497 (mpc-proc-cmd (list "seekid" songid
2498 (setq time (+ time step)))
2499 'mpc-status-refresh)))))
2500 (while (mouse-movement-p
2501 (event-basic-type (setq event (read-event)))))
2502 (cancel-timer timer)))))))
2503
2504 (defvar mpc--faster-toggle-timer nil)
2505 (defun mpc--faster-stop ()
2506 (when mpc--faster-toggle-timer
2507 (cancel-timer mpc--faster-toggle-timer)
2508 (setq mpc--faster-toggle-timer nil)))
2509
2510 (defun mpc--faster-toggle-refresh ()
2511 (if (equal (cdr (assq 'state mpc-status)) "stop")
2512 (mpc--faster-stop)))
2513
2514 (defun mpc--songduration ()
2515 (string-to-number
2516 (let ((s (cdr (assq 'time mpc-status))))
2517 (if (not (string-match ":" s))
2518 (error "Unexpected time format %S" s)
2519 (substring s (match-end 0))))))
2520
2521 (defvar mpc--faster-toggle-forward nil)
2522 (defvar mpc--faster-acceleration 0.5)
2523 (defun mpc--faster-toggle (speedup step)
2524 (setq speedup (float speedup))
2525 (if mpc--faster-toggle-timer
2526 (mpc--faster-stop)
2527 (mpc-status-refresh) (mpc-proc-sync)
2528 (let* (songid ;The ID of the currently ffwd/rewinding song.
2529 songduration ;The duration of that song.
2530 songtime ;The time of the song last time we ran.
2531 oldtime ;The time of day last time we ran.
2532 prevsongid) ;The song we're in the process leaving.
2533 (let ((fun
2534 (lambda ()
2535 (let ((newsongid (cdr (assq 'songid mpc-status))))
2536
2537 (if (and (equal prevsongid newsongid)
2538 (not (equal prevsongid songid)))
2539 ;; We left prevsongid and came back to it. Pretend it
2540 ;; didn't happen.
2541 (setq newsongid songid))
2542
2543 (cond
2544 ((null newsongid) (mpc--faster-stop))
2545 ((not (equal songid newsongid))
2546 ;; We jumped to another song: reset.
2547 (setq songid newsongid)
2548 (setq songtime (string-to-number
2549 (cdr (assq 'time mpc-status))))
2550 (setq songduration (mpc--songduration))
2551 (setq oldtime (float-time)))
2552 ((and (>= songtime songduration) mpc--faster-toggle-forward)
2553 ;; Skip to the beginning of the next song.
2554 (if (not (equal (cdr (assq 'state mpc-status)) "play"))
2555 (mpc-proc-cmd "next" 'mpc-status-refresh)
2556 ;; If we're playing, this is done automatically, so we
2557 ;; don't need to do anything, or rather we *shouldn't*
2558 ;; do anything otherwise there's a race condition where
2559 ;; we could skip straight to the next next song.
2560 nil))
2561 ((and (<= songtime 0) (not mpc--faster-toggle-forward))
2562 ;; Skip to the end of the previous song.
2563 (setq prevsongid songid)
2564 (mpc-proc-cmd "previous"
2565 (lambda ()
2566 (mpc-status-refresh
2567 (lambda ()
2568 (setq songid (cdr (assq 'songid mpc-status)))
2569 (setq songtime (setq songduration (mpc--songduration)))
2570 (setq oldtime (float-time))
2571 (mpc-proc-cmd (list "seekid" songid songtime)))))))
2572 (t
2573 (setq speedup (+ speedup mpc--faster-acceleration))
2574 (let ((newstep
2575 (truncate (* speedup (- (float-time) oldtime)))))
2576 (if (<= newstep 1) (setq newstep 1))
2577 (setq oldtime (+ oldtime (/ newstep speedup)))
2578 (if (not mpc--faster-toggle-forward)
2579 (setq newstep (- newstep)))
2580 (setq songtime (min songduration (+ songtime newstep)))
2581 (unless (>= songtime songduration)
2582 (condition-case nil
2583 (mpc-proc-cmd
2584 (list "seekid" songid songtime)
2585 'mpc-status-refresh)
2586 (mpc-proc-error (mpc-status-refresh)))))))))))
2587 (setq mpc--faster-toggle-forward (> step 0))
2588 (funcall fun) ;Initialize values.
2589 (setq mpc--faster-toggle-timer
2590 (run-with-timer t 0.3 fun))))))
2591
2592
2593
2594 (defvar mpc-faster-speedup 8)
2595
2596 (defun mpc-ffwd (_event)
2597 "Fast forward."
2598 (interactive (list last-nonmenu-event))
2599 ;; (mpc--faster event 4.0 1)
2600 (mpc--faster-toggle mpc-faster-speedup 1))
2601
2602 (defun mpc-rewind (_event)
2603 "Fast rewind."
2604 (interactive (list last-nonmenu-event))
2605 ;; (mpc--faster event 4.0 -1)
2606 (mpc--faster-toggle mpc-faster-speedup -1))
2607
2608
2609 (defun mpc-play-at-point (&optional event)
2610 (interactive (list last-nonmenu-event))
2611 (mpc-select event)
2612 (mpc-play))
2613
2614 ;; (defun mpc-play-tagval ()
2615 ;; "Play all the songs of the tag at point."
2616 ;; (interactive)
2617 ;; (let* ((val (buffer-substring (line-beginning-position) (line-end-position)))
2618 ;; (songs (mapcar 'cdar
2619 ;; (mpc-proc-buf-to-alists
2620 ;; (mpc-proc-cmd (list "find" mpc-tag val))))))
2621 ;; (mpc-cmd-add songs)
2622 ;; (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2623 ;; (mpc-cmd-play))))
2624
2625 ;;; Drag'n'drop support ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2626 ;; Todo:
2627 ;; the main thing to do here, is to provide visual feedback during the drag:
2628 ;; - change the mouse-cursor.
2629 ;; - highlight/select the source and the current destination.
2630
2631 (defun mpc-drag-n-drop (event)
2632 "DWIM for a drag EVENT."
2633 (interactive "e")
2634 (let* ((start (event-start event))
2635 (end (event-end event))
2636 (start-buf (window-buffer (posn-window start)))
2637 (end-buf (window-buffer (posn-window end)))
2638 (songs
2639 (with-current-buffer start-buf
2640 (goto-char (posn-point start))
2641 (if (get-text-property (point) 'mpc-select)
2642 ;; FIXME: actually we should only consider the constraints
2643 ;; corresponding to the selection in this particular buffer.
2644 (mpc-songs-selection)
2645 (cond
2646 ((and (derived-mode-p 'mpc-songs-mode)
2647 (get-text-property (point) 'mpc-file))
2648 (list (cons (get-text-property (point) 'mpc-file)
2649 (get-text-property (point) 'mpc-file-pos))))
2650 ((and mpc-tag (not (mpc-tagbrowser-all-p)))
2651 (mapcar (lambda (song)
2652 (list (cdr (assq 'file song))))
2653 (mpc-cmd-find
2654 mpc-tag
2655 (buffer-substring (line-beginning-position)
2656 (line-end-position)))))
2657 (t
2658 (error "Unsupported starting position for drag'n'drop gesture")))))))
2659 (with-current-buffer end-buf
2660 (goto-char (posn-point end))
2661 (cond
2662 ((eq mpc-tag 'Playlist)
2663 ;; Adding elements to a named playlist.
2664 (let ((playlist (if (or (mpc-tagbrowser-all-p)
2665 (and (bolp) (eolp)))
2666 (error "Not a playlist")
2667 (buffer-substring (line-beginning-position)
2668 (line-end-position)))))
2669 (mpc-cmd-add (mapcar 'car songs) playlist)
2670 (message "Added %d songs to %s" (length songs) playlist)
2671 (if (member playlist
2672 (cdr (assq 'Playlist (mpc-constraints-get-current))))
2673 (mpc-songs-refresh))))
2674 ((derived-mode-p 'mpc-songs-mode)
2675 (cond
2676 ((null mpc-songs-playlist)
2677 (error "The songs shown do not belong to a playlist"))
2678 ((eq start-buf end-buf)
2679 ;; Moving songs within the shown playlist.
2680 (let ((dest-pos (get-text-property (point) 'mpc-file-pos)))
2681 (mpc-cmd-move (mapcar 'cdr songs) dest-pos mpc-songs-playlist)
2682 (message "Moved %d songs" (length songs))))
2683 (t
2684 ;; Adding songs to the shown playlist.
2685 (let ((dest-pos (get-text-property (point) 'mpc-file-pos))
2686 (pl (if (stringp mpc-songs-playlist)
2687 (mpc-cmd-find 'Playlist mpc-songs-playlist)
2688 (mpc-proc-cmd-to-alist "playlist"))))
2689 ;; MPD's protocol does not let us add songs at a particular
2690 ;; position in a playlist, so we first have to add them to the
2691 ;; end, and then move them to their final destination.
2692 (mpc-cmd-add (mapcar 'car songs) mpc-songs-playlist)
2693 (mpc-cmd-move (let ((poss '()))
2694 (dotimes (i (length songs))
2695 (push (+ i (length pl)) poss))
2696 (nreverse poss))
2697 dest-pos mpc-songs-playlist)
2698 (message "Added %d songs" (length songs)))))
2699 (mpc-songs-refresh))
2700 (t
2701 (error "Unsupported drag'n'drop gesture"))))))
2702
2703 ;;; Toplevel ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2704
2705 (defcustom mpc-frame-alist '((name . "MPC") (tool-bar-lines . 1)
2706 (font . "Sans"))
2707 "Alist of frame parameters for the MPC frame."
2708 :type 'alist)
2709
2710 ;;;###autoload
2711 (defun mpc ()
2712 "Main entry point for MPC."
2713 (interactive
2714 (progn
2715 (if current-prefix-arg
2716 ;; FIXME: We should provide some completion here, especially for the
2717 ;; case where the user specifies a local socket/file name.
2718 (setq mpc-host (read-string "MPD host and port: " nil nil mpc-host)))
2719 nil))
2720 (let* ((song-buf (mpc-songs-buf))
2721 (song-win (get-buffer-window song-buf 0)))
2722 (if song-win
2723 (select-window song-win)
2724 (if (or (window-dedicated-p) (window-minibuffer-p))
2725 (ignore-errors (select-frame (make-frame mpc-frame-alist)))
2726 (with-current-buffer song-buf
2727 (setq-local mpc-previous-window-config
2728 (current-window-configuration))))
2729 (let* ((win1 (selected-window))
2730 (win2 (split-window))
2731 (tags mpc-browser-tags))
2732 (unless tags (error "Need at least one entry in `mpc-browser-tags'"))
2733 (set-window-buffer win2 song-buf)
2734 (set-window-dedicated-p win2 'soft)
2735 (mpc-status-buffer-show)
2736 (while
2737 (progn
2738 (set-window-buffer win1 (mpc-tagbrowser-buf (pop tags)))
2739 (set-window-dedicated-p win1 'soft)
2740 tags)
2741 (setq win1 (split-window win1 nil 'horiz)))))
2742 (balance-windows-area))
2743 (mpc-songs-refresh)
2744 (mpc-status-refresh))
2745
2746 (provide 'mpc)
2747
2748 ;;; mpc.el ends here