; Revert "Guard terminal par. in XTerm mouse mode"
[emacs.git] / lisp / mpc.el
blob20e4bc85d85249a2612723827ec453778e87c9cb
1 ;;; mpc.el --- A client for the Music Player Daemon -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2016 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: multimedia
8 ;; This file is part of GNU Emacs.
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.
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.
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/>.
23 ;;; Commentary:
25 ;; This is an Emacs front end to the Music Player Daemon.
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.
34 ;; Bugs:
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.
40 ;; Todo:
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 ;-)
83 ;;; Code:
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
91 ;; UI-commands : mpc-
92 ;; internal : mpc--
94 (eval-when-compile
95 (require 'cl-lib)
96 (require 'subr-x))
98 (defgroup mpc ()
99 "Client for the Music Player Daemon (mpd)."
100 :prefix "mpc-"
101 :group 'multimedia
102 :group 'applications)
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))
110 ;;; Misc utils ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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)))
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)))
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)))
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)))))
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)))
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))))))))
188 (define-obsolete-function-alias 'mpc-string-prefix-p 'string-prefix-p "24.3")
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)
198 ;;; Support for the actual connection and MPD command execution ;;;;;;;;;;;;
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)
209 (defvar mpc-proc nil)
211 (defconst mpc--proc-end-re "^\\(?:OK\\(?: MPD .*\\)?\\|ACK \\(.*\\)\\)\n")
213 (define-error 'mpc-proc-error "MPD error")
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"))))
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.
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)))))))))
255 (defun mpc--proc-connect (host)
256 (let ((port 6600)
257 local
258 pass)
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))
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))))))
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)))
316 (defconst mpc--proc-alist-to-alists-starters '(file directory))
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)))
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)
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))))
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))))
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)))))
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)))))
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"))
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"))
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))))
424 (defun mpc-proc-buf-to-alists (buf)
425 (mpc--proc-alist-to-alists (mpc-proc-buf-to-alist buf)))
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))))
440 (defun mpc-proc-tag-string-to-sym (tag)
441 (intern (capitalize tag)))
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))))
455 ;;; Support for regularly updated current status information ;;;;;;;;;;;;;;;
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.
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.")
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)))))))
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)))))))
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))
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)))
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))))))
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))
562 ;;; A thin layer above the raw protocol commands ;;;;;;;;;;;;;;;;;;;;;;;;;;;
564 ;; (defvar mpc-queue nil)
565 ;; (defvar mpc-queue-back nil)
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))))))
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"))))))
609 (defvar mpc--find-memoize-union-tags nil)
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))))
618 (defun mpc-cmd-special-tag-p (tag)
619 (or (memq tag '(Playlist Search Directory))
620 (string-match "|" (symbol-name tag))))
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))))
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)))
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))
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)))
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"))
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))))
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")))))
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))))))))
791 (defun mpc-cmd-stop (&optional callback)
792 (mpc-proc-cmd "stop" callback))
794 (defun mpc-cmd-clear (&optional callback)
795 (mpc-proc-cmd "clear" callback)
796 ;; (setq mpc-queue-back nil mpc-queue nil)
799 (defun mpc-cmd-consume (&optional arg)
800 "Set consume mode state."
801 (mpc-proc-cmd (list "consume" arg) #'mpc-status-refresh))
803 (defun mpc-cmd-random (&optional arg)
804 "Set random (shuffle) mode state."
805 (mpc-proc-cmd (list "random" arg) #'mpc-status-refresh))
807 (defun mpc-cmd-repeat (&optional arg)
808 "Set repeat mode state."
809 (mpc-proc-cmd (list "repeat" arg) #'mpc-status-refresh))
811 (defun mpc-cmd-single (&optional arg)
812 "Set single mode state."
813 (mpc-proc-cmd (list "single" arg) #'mpc-status-refresh))
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))))
822 (defun mpc-cmd-status ()
823 (mpc-proc-cmd-to-alist "status"))
825 (defun mpc-cmd-play ()
826 (mpc-proc-cmd "play")
827 (mpc-status-refresh))
829 (defun mpc-cmd-seekcur (time)
830 (mpc-proc-cmd (list "seekcur" time) #'mpc-status-refresh))
832 (defun mpc-cmd-add (files &optional playlist)
833 "Add the songs FILES to PLAYLIST.
834 If PLAYLIST is t or nil or missing, use the main playlist."
835 (mpc-proc-cmd (mpc-proc-cmd-list
836 (mapcar (lambda (file)
837 (if (stringp playlist)
838 (list "playlistadd" playlist file)
839 (list "add" file)))
840 files)))
841 (if (stringp playlist)
842 (mpc-cmd-flush 'Playlist playlist)))
844 (defun mpc-cmd-delete (song-poss &optional playlist)
845 "Delete the songs at positions SONG-POSS from PLAYLIST.
846 If PLAYLIST is t or nil or missing, use the main playlist."
847 (mpc-proc-cmd (mpc-proc-cmd-list
848 (mapcar (lambda (song-pos)
849 (if (stringp playlist)
850 (list "playlistdelete" playlist song-pos)
851 (list "delete" song-pos)))
852 ;; Sort them from last to first, so the renumbering
853 ;; caused by the earlier deletions don't affect
854 ;; later ones.
855 (sort song-poss '>))))
856 (if (stringp playlist)
857 (puthash (cons 'Playlist playlist) nil mpc--find-memoize)))
860 (defun mpc-cmd-move (song-poss dest-pos &optional playlist)
861 (let ((i 0))
862 (mpc-proc-cmd
863 (mpc-proc-cmd-list
864 (mapcar (lambda (song-pos)
865 (if (>= song-pos dest-pos)
866 ;; positions past dest-pos have been
867 ;; shifted by i.
868 (setq song-pos (+ song-pos i)))
869 (prog1 (if (stringp playlist)
870 (list "playlistmove" playlist song-pos dest-pos)
871 (list "move" song-pos dest-pos))
872 (if (< song-pos dest-pos)
873 ;; This move has shifted dest-pos by 1.
874 (cl-decf dest-pos))
875 (cl-incf i)))
876 ;; Sort them from last to first, so the renumbering
877 ;; caused by the earlier deletions affect
878 ;; later ones a bit less.
879 (sort song-poss '>))))
880 (if (stringp playlist)
881 (puthash (cons 'Playlist playlist) nil mpc--find-memoize))))
883 (defun mpc-cmd-update (&optional arg callback)
884 (let ((cb callback))
885 (mpc-proc-cmd (if arg (list "update" arg) "update")
886 (lambda () (mpc-status-refresh) (if cb (funcall cb))))
887 (unless callback (mpc-proc-sync))))
889 (defun mpc-cmd-tagtypes ()
890 (mapcar 'cdr (mpc-proc-cmd-to-alist "tagtypes")))
892 ;; This was never integrated into MPD.
893 ;; (defun mpc-cmd-download (file)
894 ;; (with-current-buffer (generate-new-buffer " *mpc download*")
895 ;; (set-buffer-multibyte nil)
896 ;; (let* ((proc (mpc-proc))
897 ;; (stdbuf (process-buffer proc))
898 ;; (markpos (marker-position (process-mark proc)))
899 ;; (stdcoding (process-coding-system proc)))
900 ;; (unwind-protect
901 ;; (progn
902 ;; (set-process-buffer proc (current-buffer))
903 ;; (set-process-coding-system proc 'binary (cdr stdcoding))
904 ;; (set-marker (process-mark proc) (point))
905 ;; (mpc-proc-cmd (list "download" file)))
906 ;; (set-process-buffer proc stdbuf)
907 ;; (set-marker (process-mark proc) markpos stdbuf)
908 ;; (set-process-coding-system proc (car stdcoding) (cdr stdcoding)))
909 ;; ;; The command has completed, let's decode.
910 ;; (goto-char (point-max))
911 ;; (delete-char -1) ;Delete final newline.
912 ;; (while (re-search-backward "^>" nil t)
913 ;; (delete-char 1))
914 ;; (current-buffer))))
916 ;;; Misc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
918 (defcustom mpc-mpd-music-directory nil
919 "Location of MPD's music directory."
920 :type '(choice (const nil) directory))
922 (defcustom mpc-data-directory
923 (locate-user-emacs-file "mpc" ".mpc")
924 "Directory where MPC.el stores auxiliary data."
925 :type 'directory)
927 (defun mpc-data-directory ()
928 (unless (file-directory-p mpc-data-directory)
929 (make-directory mpc-data-directory))
930 mpc-data-directory)
932 (defun mpc-file-local-copy (file)
933 ;; Try to set mpc-mpd-music-directory.
934 (when (and (null mpc-mpd-music-directory)
935 (or (string-match "\\`localhost" mpc-host)
936 (file-name-absolute-p mpc-host)))
937 (let ((files `(,(let ((xdg (getenv "XDG_CONFIG_HOME")))
938 (concat (if (and xdg (file-name-absolute-p xdg))
939 xdg "~/.config")
940 "/mpd/mpd.conf"))
941 "~/.mpdconf" "~/.mpd/mpd.conf" "/etc/mpd.conf"))
942 file)
943 (while (and files (not file))
944 (if (file-exists-p (car files)) (setq file (car files)))
945 (setq files (cdr files)))
946 (with-temp-buffer
947 (ignore-errors (insert-file-contents file))
948 (goto-char (point-min))
949 (if (re-search-forward "^music_directory[ ]+\"\\([^\"]+\\)\"")
950 (setq mpc-mpd-music-directory
951 (match-string 1))))))
952 ;; Use mpc-mpd-music-directory if applicable, or else try to use the
953 ;; `download' command, although it's never been accepted in `mpd' :-(
954 (if (and mpc-mpd-music-directory
955 (file-exists-p (expand-file-name file mpc-mpd-music-directory)))
956 (expand-file-name file mpc-mpd-music-directory)
957 ;; (let ((aux (expand-file-name (replace-regexp-in-string "[/]" "|" file)
958 ;; (mpc-data-directory))))
959 ;; (unless (file-exists-p aux)
960 ;; (condition-case err
961 ;; (with-local-quit
962 ;; (with-current-buffer (mpc-cmd-download file)
963 ;; (write-region (point-min) (point-max) aux)
964 ;; (kill-buffer (current-buffer))))
965 ;; (mpc-proc-error (message "Download error: %s" err) (setq aux nil))))
966 ;; aux)
969 ;;; Formatter ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
971 (defun mpc-secs-to-time (secs)
972 ;; We could use `format-seconds', but it doesn't seem worth the trouble
973 ;; because we'd still need to check (>= secs (* 60 100)) since the special
974 ;; %z only allows us to drop the large units for small values but
975 ;; not to drop the small units for large values.
976 (if (stringp secs) (setq secs (string-to-number secs)))
977 (if (>= secs (* 60 100)) ;More than 100 minutes.
978 (format "%dh%02d" ;"%d:%02d:%02d"
979 (/ secs 3600) (% (/ secs 60) 60)) ;; (% secs 60)
980 (format "%d:%02d" (/ secs 60) (% secs 60))))
982 (defvar mpc-tempfiles nil)
983 (defconst mpc-tempfiles-reftable (make-hash-table :weakness 'key))
985 (defun mpc-tempfiles-clean ()
986 (let ((live ()))
987 (maphash (lambda (_k v) (push v live)) mpc-tempfiles-reftable)
988 (dolist (f mpc-tempfiles)
989 (unless (member f live) (ignore-errors (delete-file f))))
990 (setq mpc-tempfiles live)))
992 (defun mpc-tempfiles-add (key file)
993 (mpc-tempfiles-clean)
994 (puthash key file mpc-tempfiles-reftable)
995 (push file mpc-tempfiles))
997 (defun mpc-format (format-spec info &optional hscroll)
998 "Format the INFO according to FORMAT-SPEC, inserting the result at point."
999 (let* ((pos 0)
1000 (start (point))
1001 (col (if hscroll (- hscroll) 0))
1002 (insert (lambda (str)
1003 (cond
1004 ((>= col 0) (insert str))
1005 (t (insert (substring str (min (length str) (- col))))))))
1006 (pred nil))
1007 (while (string-match "%\\(?:%\\|\\(-\\)?\\([0-9]+\\)?{\\([[:alpha:]][[:alnum:]]*\\)\\(?:-\\([^}]+\\)\\)?}\\)" format-spec pos)
1008 (let ((pre-text (substring format-spec pos (match-beginning 0))))
1009 (funcall insert pre-text)
1010 (setq col (+ col (string-width pre-text))))
1011 (setq pos (match-end 0))
1012 (if (null (match-end 3))
1013 (progn
1014 (funcall insert "%")
1015 (setq col (+ col 1)))
1016 (let* ((size (match-string 2 format-spec))
1017 (tag (intern (match-string 3 format-spec)))
1018 (post (match-string 4 format-spec))
1019 (right-align (match-end 1))
1020 (text
1021 (if (eq info 'self) (symbol-name tag)
1022 (pcase tag
1023 ((or `Time `Duration)
1024 (let ((time (cdr (or (assq 'time info) (assq 'Time info)))))
1025 (setq pred (list nil)) ;Just assume it's never eq.
1026 (when time
1027 (mpc-secs-to-time (if (and (eq tag 'Duration)
1028 (string-match ":" time))
1029 (substring time (match-end 0))
1030 time)))))
1031 (`Cover
1032 (let ((dir (file-name-directory (cdr (assq 'file info)))))
1033 ;; (debug)
1034 (push `(equal ',dir (file-name-directory (cdr (assq 'file info)))) pred)
1035 (if-let ((covers '(".folder.png" "cover.jpg" "folder.jpg"))
1036 (cover (cl-loop for file in (directory-files (mpc-file-local-copy dir))
1037 if (member (downcase file) covers)
1038 return (concat dir file)))
1039 (file (with-demoted-errors "MPC: %s"
1040 (mpc-file-local-copy cover))))
1041 (let (image)
1042 (if (null size) (setq image (create-image file))
1043 (let ((tempfile (make-temp-file "mpc" nil ".jpg")))
1044 (call-process "convert" nil nil nil
1045 "-scale" size file tempfile)
1046 (setq image (create-image tempfile))
1047 (mpc-tempfiles-add image tempfile)))
1048 (setq size nil)
1049 (propertize dir 'display image))
1050 ;; Make sure we return something on which we can
1051 ;; place the `mpc-pred' property, as
1052 ;; a negative-cache. We could also use
1053 ;; a default cover.
1054 (progn (setq size nil) " "))))
1055 (_ (let ((val (cdr (assq tag info))))
1056 ;; For Streaming URLs, there's no other info
1057 ;; than the URL in `file'. Pretend it's in `Title'.
1058 (when (and (null val) (eq tag 'Title))
1059 (setq val (cdr (assq 'file info))))
1060 (push `(equal ',val (cdr (assq ',tag info))) pred)
1061 (cond
1062 ((not (and (eq tag 'Date) (stringp val))) val)
1063 ;; For "date", only keep the year!
1064 ((string-match "[0-9]\\{4\\}" val)
1065 (match-string 0 val))
1066 (t val)))))))
1067 (space (when size
1068 (setq size (string-to-number size))
1069 (propertize " " 'display
1070 (list 'space :align-to (+ col size)))))
1071 (textwidth (if text (string-width text) 0))
1072 (postwidth (if post (string-width post) 0)))
1073 (when text
1074 (let ((display
1075 (if (and size
1076 (> (+ postwidth textwidth) size))
1077 (propertize
1078 (truncate-string-to-width text size nil nil "…")
1079 'help-echo text)
1080 text)))
1081 (when (memq tag '(Artist Album Composer)) ;FIXME: wrong list.
1082 (setq display
1083 (propertize display
1084 'mouse-face 'highlight
1085 'follow-link t
1086 'keymap `(keymap
1087 (mouse-2
1088 . (lambda ()
1089 (interactive)
1090 (mpc-constraints-push 'noerror)
1091 (mpc-constraints-restore
1092 ',(list (list tag text)))))))))
1093 (funcall insert
1094 (concat (when size
1095 (propertize " " 'display
1096 (list 'space :align-to
1097 (+ col
1098 (if (and size right-align)
1099 (- size postwidth textwidth)
1100 0)))))
1101 display post))))
1102 (if (null size) (setq col (+ col textwidth postwidth))
1103 (insert space)
1104 (setq col (+ col size))))))
1105 (put-text-property start (point) 'mpc-pred
1106 `(lambda (info) (and ,@(nreverse pred))))))
1108 ;;; The actual UI code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1110 (defvar mpc-mode-map
1111 (let ((map (make-sparse-keymap)))
1112 ;; (define-key map "\e" 'mpc-stop)
1113 (define-key map "q" 'mpc-quit)
1114 (define-key map "\r" 'mpc-select)
1115 (define-key map [(shift return)] 'mpc-select-toggle)
1116 (define-key map [mouse-2] 'mpc-select)
1117 (define-key map [S-mouse-2] 'mpc-select-extend)
1118 (define-key map [C-mouse-2] 'mpc-select-toggle)
1119 (define-key map [drag-mouse-2] 'mpc-drag-n-drop)
1120 ;; We use `always' because a binding to t is like a binding to nil.
1121 (define-key map [follow-link] :always)
1122 ;; But follow-link doesn't apply blindly to header-line and
1123 ;; mode-line clicks.
1124 (define-key map [header-line follow-link] 'ignore)
1125 (define-key map [mode-line follow-link] 'ignore)
1126 ;; Doesn't work because the first click changes the buffer, so the second
1127 ;; is applied elsewhere :-(
1128 ;; (define-key map [(double mouse-2)] 'mpc-play-at-point)
1129 (define-key map "p" 'mpc-pause)
1130 (define-key map "s" 'mpc-toggle-play)
1131 (define-key map ">" 'mpc-next)
1132 (define-key map "<" 'mpc-prev)
1133 (define-key map "g" 'mpc-seek-current)
1134 map))
1136 (easy-menu-define mpc-mode-menu mpc-mode-map
1137 "Menu for MPC.el."
1138 '("MPC.el"
1139 ["Play/Pause" mpc-toggle-play] ;FIXME: Add one of ⏯/▶/⏸ in there?
1140 ["Next Track" mpc-next] ;FIXME: Add ⇥ there?
1141 ["Previous Track" mpc-prev] ;FIXME: Add ⇤ there?
1142 ["Seek Within Track" mpc-seek-current]
1143 "--"
1144 ["Repeat Playlist" mpc-toggle-repeat :style toggle
1145 :selected (member '(repeat . "1") mpc-status)]
1146 ["Shuffle Playlist" mpc-toggle-shuffle :style toggle
1147 :selected (member '(random . "1") mpc-status)]
1148 ["Repeat Single Track" mpc-toggle-single :style toggle
1149 :selected (member '(single . "1") mpc-status)]
1150 ["Consume Mode" mpc-toggle-consume :style toggle
1151 :selected (member '(consume . "1") mpc-status)]
1152 "--"
1153 ["Add new browser" mpc-tagbrowser]
1154 ["Update DB" mpc-update]
1155 ["Quit" mpc-quit]))
1157 (defvar mpc-tool-bar-map
1158 (let ((map (make-sparse-keymap)))
1159 (tool-bar-local-item "mpc/prev" 'mpc-prev 'prev map
1160 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop"))
1161 :label "Prev" :vert-only t)
1162 ;; FIXME: how can we bind it to the down-event?
1163 (tool-bar-local-item "mpc/rewind" 'mpc-rewind 'rewind map
1164 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop"))
1165 :label "Rew" :vert-only t
1166 :button '(:toggle . (and mpc--faster-toggle-timer
1167 (not mpc--faster-toggle-forward))))
1168 ;; We could use a single toggle command for pause/play, with 2 different
1169 ;; icons depending on whether or not it's selected, but then it'd have
1170 ;; to be a toggle-button, thus displayed depressed in one of the
1171 ;; two states :-(
1172 (tool-bar-local-item "mpc/pause" 'mpc-pause 'pause map
1173 :label "Pause" :vert-only t
1174 :visible '(equal (cdr (assq 'state mpc-status)) "play")
1175 :help "Pause/play")
1176 (tool-bar-local-item "mpc/play" 'mpc-play 'play map
1177 :label "Play" :vert-only t
1178 :visible '(not (equal (cdr (assq 'state mpc-status)) "play"))
1179 :help "Play/pause")
1180 ;; FIXME: how can we bind it to the down-event?
1181 (tool-bar-local-item "mpc/ffwd" 'mpc-ffwd 'ffwd map
1182 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop"))
1183 :label "Ffwd" :vert-only t
1184 :button '(:toggle . (and mpc--faster-toggle-timer
1185 mpc--faster-toggle-forward)))
1186 (tool-bar-local-item "mpc/next" 'mpc-next 'next map
1187 :label "Next" :vert-only t
1188 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop")))
1189 (tool-bar-local-item "mpc/stop" 'mpc-stop 'stop map
1190 :label "Stop" :vert-only t)
1191 (tool-bar-local-item "mpc/add" 'mpc-playlist-add 'add map
1192 :label "Add" :vert-only t
1193 :help "Append to the playlist")
1194 map))
1196 (define-derived-mode mpc-mode special-mode "MPC"
1197 "Major mode for the features common to all buffers of MPC."
1198 (buffer-disable-undo)
1199 (if (boundp 'tool-bar-map) ; not if --without-x
1200 (setq-local tool-bar-map mpc-tool-bar-map))
1201 (setq-local truncate-lines t))
1203 ;;; The mpc-status-mode buffer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1205 (define-derived-mode mpc-status-mode mpc-mode "MPC-Status"
1206 "Major mode to display MPC status info."
1207 (setq-local mode-line-format
1208 '("%e" mode-line-frame-identification
1209 mode-line-buffer-identification))
1210 (setq-local window-area-factor 3)
1211 (setq-local header-line-format '("MPC " mpc-volume)))
1213 (defvar mpc-status-buffer-format
1214 '("%-5{Time} / %{Duration} %2{Disc--}%4{Track}" "%{Title}" "%{Album}" "%{Artist}" "%128{Cover}"))
1216 (defun mpc-status-buffer-refresh ()
1217 (let ((buf (mpc-proc-buffer (mpc-proc) 'status)))
1218 (when (buffer-live-p buf)
1219 (with-current-buffer buf
1220 (save-excursion
1221 (goto-char (point-min))
1222 (when (assq 'file mpc-status)
1223 (let ((inhibit-read-only t))
1224 (dolist (spec mpc-status-buffer-format)
1225 (let ((pred (get-text-property (point) 'mpc-pred)))
1226 (if (and pred (funcall pred mpc-status))
1227 (forward-line)
1228 (delete-region (point) (line-beginning-position 2))
1229 (ignore-errors (mpc-format spec mpc-status))
1230 (insert "\n"))))
1231 (unless (eobp) (delete-region (point) (point-max))))))))))
1233 (defun mpc-status-buffer-show ()
1234 (interactive)
1235 (let* ((proc (mpc-proc))
1236 (buf (mpc-proc-buffer proc 'status))
1237 (songs-buf (mpc-proc-buffer proc 'songs))
1238 (songs-win (if songs-buf (get-buffer-window songs-buf 0))))
1239 (unless (buffer-live-p buf)
1240 (setq buf (get-buffer-create "*MPC-Status*"))
1241 (with-current-buffer buf
1242 (mpc-status-mode))
1243 (mpc-proc-buffer proc 'status buf))
1244 (if (null songs-win) (pop-to-buffer buf)
1245 (let ((_win (split-window songs-win 20 t)))
1246 (set-window-dedicated-p songs-win nil)
1247 (set-window-buffer songs-win buf)
1248 (set-window-dedicated-p songs-win 'soft)))))
1250 ;;; Selection management;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1252 (defvar mpc-separator-ol nil)
1254 (defvar-local mpc-select nil)
1256 (defmacro mpc-select-save (&rest body)
1257 "Execute BODY and restore the selection afterwards."
1258 (declare (indent 0) (debug t))
1259 `(let ((selection (mpc-select-get-selection))
1260 (position (cons (buffer-substring-no-properties
1261 (line-beginning-position) (line-end-position))
1262 (current-column))))
1263 ,@body
1264 (mpc-select-restore selection)
1265 (goto-char (point-min))
1266 (if (re-search-forward
1267 (concat "^" (regexp-quote (car position)) "$")
1268 (if (overlayp mpc-separator-ol)
1269 (overlay-end mpc-separator-ol))
1271 (move-to-column (cdr position)))
1272 (let ((win (get-buffer-window (current-buffer) 0)))
1273 (if win (set-window-point win (point))))))
1275 (defun mpc-select-get-selection ()
1276 (mapcar (lambda (ol)
1277 (buffer-substring-no-properties
1278 (overlay-start ol) (1- (overlay-end ol))))
1279 mpc-select))
1281 (defun mpc-select-restore (selection)
1282 ;; Restore the selection. I.e. move the overlays back to their
1283 ;; corresponding location. Actually which overlay is used for what
1284 ;; doesn't matter.
1285 (mapc 'delete-overlay mpc-select)
1286 (setq mpc-select nil)
1287 (dolist (elem selection)
1288 ;; After an update, some elements may have disappeared.
1289 (goto-char (point-min))
1290 (when (re-search-forward
1291 (concat "^" (regexp-quote elem) "$") nil t)
1292 (mpc-select-make-overlay)))
1293 (when mpc-tag (mpc-tagbrowser-all-select))
1294 (beginning-of-line))
1296 (defun mpc-select-make-overlay ()
1297 (cl-assert (not (get-char-property (point) 'mpc-select)))
1298 (let ((ol (make-overlay
1299 (line-beginning-position) (line-beginning-position 2))))
1300 (overlay-put ol 'mpc-select t)
1301 (overlay-put ol 'face 'highlight)
1302 (overlay-put ol 'evaporate t)
1303 (push ol mpc-select)))
1305 (defun mpc-select (&optional event)
1306 "Select the tag value at point."
1307 (interactive (list last-nonmenu-event))
1308 (mpc-event-set-point event)
1309 (if (and (bolp) (eobp)) (forward-line -1))
1310 (mapc 'delete-overlay mpc-select)
1311 (setq mpc-select nil)
1312 (if (mpc-tagbrowser-all-p)
1314 (mpc-select-make-overlay))
1315 (when mpc-tag
1316 (mpc-tagbrowser-all-select)
1317 (mpc-selection-refresh)))
1319 (defun mpc-select-toggle (&optional event)
1320 "Toggle the selection of the tag value at point."
1321 (interactive (list last-nonmenu-event))
1322 (mpc-event-set-point event)
1323 (save-excursion
1324 (cond
1325 ;; The line is already selected: deselect it.
1326 ((get-char-property (point) 'mpc-select)
1327 (let ((ols nil))
1328 (dolist (ol mpc-select)
1329 (if (and (<= (overlay-start ol) (point))
1330 (> (overlay-end ol) (point)))
1331 (delete-overlay ol)
1332 (push ol ols)))
1333 (cl-assert (= (1+ (length ols)) (length mpc-select)))
1334 (setq mpc-select ols)))
1335 ;; We're trying to select *ALL* additionally to others.
1336 ((mpc-tagbrowser-all-p) nil)
1337 ;; Select the current line.
1338 (t (mpc-select-make-overlay))))
1339 (when mpc-tag
1340 (mpc-tagbrowser-all-select)
1341 (mpc-selection-refresh)))
1343 (defun mpc-select-extend (&optional event)
1344 "Extend the selection up to point."
1345 (interactive (list last-nonmenu-event))
1346 (mpc-event-set-point event)
1347 (if (null mpc-select)
1348 ;; If nothing's selected yet, fallback to selecting the elem at point.
1349 (mpc-select event)
1350 (save-excursion
1351 (cond
1352 ;; The line is already in a selected area; truncate the area.
1353 ((get-char-property (point) 'mpc-select)
1354 (let ((before 0)
1355 (after 0)
1356 (mid (line-beginning-position))
1357 start end)
1358 (while (and (zerop (forward-line 1))
1359 (get-char-property (point) 'mpc-select))
1360 (setq end (1+ (point)))
1361 (cl-incf after))
1362 (goto-char mid)
1363 (while (and (zerop (forward-line -1))
1364 (get-char-property (point) 'mpc-select))
1365 (setq start (point))
1366 (cl-incf before))
1367 (if (and (= after 0) (= before 0))
1368 ;; Shortening an already minimum-size region: do nothing.
1370 (if (> after before)
1371 (setq end mid)
1372 (setq start (1+ mid)))
1373 (let ((ols '()))
1374 (dolist (ol mpc-select)
1375 (if (and (>= (overlay-start ol) start)
1376 (< (overlay-start ol) end))
1377 (delete-overlay ol)
1378 (push ol ols)))
1379 (setq mpc-select (nreverse ols))))))
1380 ;; Extending a prior area. Look for the closest selection.
1382 (when (mpc-tagbrowser-all-p)
1383 (forward-line 1))
1384 (let ((before 0)
1385 (count 0)
1386 (dir 1)
1387 (start (line-beginning-position)))
1388 (while (and (zerop (forward-line 1))
1389 (not (get-char-property (point) 'mpc-select)))
1390 (cl-incf count))
1391 (unless (get-char-property (point) 'mpc-select)
1392 (setq count nil))
1393 (goto-char start)
1394 (while (and (zerop (forward-line -1))
1395 (not (get-char-property (point) 'mpc-select)))
1396 (cl-incf before))
1397 (unless (get-char-property (point) 'mpc-select)
1398 (setq before nil))
1399 (when (and before (or (null count) (< before count)))
1400 (setq count before)
1401 (setq dir -1))
1402 (goto-char start)
1403 (dotimes (_i (1+ (or count 0)))
1404 (mpc-select-make-overlay)
1405 (forward-line dir))))))
1406 (when mpc-tag
1407 (mpc-tagbrowser-all-select)
1408 (mpc-selection-refresh))))
1410 ;;; Constraint sets ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1412 (defvar mpc--song-search nil)
1414 (defun mpc-constraints-get-current (&optional avoid-buf)
1415 "Return currently selected set of constraints.
1416 If AVOID-BUF is non-nil, it specifies a buffer which should be ignored
1417 when constructing the set of constraints."
1418 (let ((constraints (if mpc--song-search `((Search ,mpc--song-search))))
1419 tag select)
1420 (dolist (buf (process-get (mpc-proc) 'buffers))
1421 (setq buf (cdr buf))
1422 (when (and (setq tag (buffer-local-value 'mpc-tag buf))
1423 (not (eq buf avoid-buf))
1424 (setq select
1425 (with-current-buffer buf (mpc-select-get-selection))))
1426 (push (cons tag select) constraints)))
1427 constraints))
1429 (defun mpc-constraints-tag-lookup (buffer-tag constraints)
1430 (let (res)
1431 (dolist (constraint constraints)
1432 (when (or (eq (car constraint) buffer-tag)
1433 (and (string-match "|" (symbol-name buffer-tag))
1434 (member (symbol-name (car constraint))
1435 (split-string (symbol-name buffer-tag) "|"))))
1436 (setq res (cdr constraint))))
1437 res))
1439 (defun mpc-constraints-restore (constraints)
1440 (let ((search (assq 'Search constraints)))
1441 (setq mpc--song-search (cadr search))
1442 (when search (setq constraints (delq search constraints))))
1443 (dolist (buf (process-get (mpc-proc) 'buffers))
1444 (setq buf (cdr buf))
1445 (when (buffer-live-p buf)
1446 (let* ((tag (buffer-local-value 'mpc-tag buf))
1447 (constraint (mpc-constraints-tag-lookup tag constraints)))
1448 (when tag
1449 (with-current-buffer buf
1450 (mpc-select-restore constraint))))))
1451 (mpc-selection-refresh))
1453 ;; I don't get the ring.el code. I think it doesn't do what I need, but
1454 ;; then I don't understand when what it does would be useful.
1455 (defun mpc-ring-make (size) (cons 0 (cons 0 (make-vector size nil))))
1456 (defun mpc-ring-push (ring val)
1457 (aset (cddr ring) (car ring) val)
1458 (setcar (cdr ring) (max (cadr ring) (1+ (car ring))))
1459 (setcar ring (mod (1+ (car ring)) (length (cddr ring)))))
1460 (defun mpc-ring-pop (ring)
1461 (setcar ring (mod (1- (car ring)) (cadr ring)))
1462 (aref (cddr ring) (car ring)))
1464 (defvar mpc-constraints-ring (mpc-ring-make 10))
1466 (defun mpc-constraints-push (&optional noerror)
1467 "Push the current selection on the ring for later."
1468 (interactive)
1469 (let ((constraints (mpc-constraints-get-current)))
1470 (if (null constraints)
1471 (unless noerror (error "No selection to push"))
1472 (mpc-ring-push mpc-constraints-ring constraints))))
1474 (defun mpc-constraints-pop ()
1475 "Recall the most recently pushed selection."
1476 (interactive)
1477 (let ((constraints (mpc-ring-pop mpc-constraints-ring)))
1478 (if (null constraints)
1479 (error "No selection to return to")
1480 (mpc-constraints-restore constraints))))
1482 ;;; The TagBrowser mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1484 (defconst mpc-tagbrowser-all-name (propertize "*ALL*" 'face 'italic))
1485 (defvar-local mpc-tagbrowser-all-ol nil)
1486 (defvar-local mpc-tag-name nil)
1487 (defun mpc-tagbrowser-all-p ()
1488 (and (eq (point-min) (line-beginning-position))
1489 (equal mpc-tagbrowser-all-name
1490 (buffer-substring (point-min) (line-end-position)))))
1492 (define-derived-mode mpc-tagbrowser-mode mpc-mode '("MPC-" mpc-tag-name)
1493 (setq-local mode-line-process '("" mpc-tag-name))
1494 (setq-local mode-line-format nil)
1495 (setq-local header-line-format '("" mpc-tag-name)) ;; "s"
1496 (setq-local buffer-undo-list t)
1499 (defun mpc-tagbrowser-refresh ()
1500 (mpc-select-save
1501 (widen)
1502 (goto-char (point-min))
1503 (cl-assert (looking-at (regexp-quote mpc-tagbrowser-all-name)))
1504 (forward-line 1)
1505 (let ((inhibit-read-only t))
1506 (delete-region (point) (point-max))
1507 (dolist (val (mpc-cmd-list mpc-tag)) (insert val "\n")))
1508 (set-buffer-modified-p nil))
1509 (mpc-reorder))
1511 (defun mpc-updated-db ()
1512 ;; FIXME: This is not asynchronous, but is run from a process filter.
1513 (unless (assq 'updating_db mpc-status)
1514 (clrhash mpc--find-memoize)
1515 (dolist (buf (process-get (mpc-proc) 'buffers))
1516 (setq buf (cdr buf))
1517 (when (buffer-local-value 'mpc-tag buf)
1518 (with-current-buffer buf (with-local-quit (mpc-tagbrowser-refresh)))))
1519 (with-local-quit (mpc-songs-refresh))))
1521 (defun mpc-tagbrowser-tag-name (tag)
1522 (cond
1523 ((string-match "|" (symbol-name tag))
1524 (let ((tag1 (intern (substring (symbol-name tag)
1525 0 (match-beginning 0))))
1526 (tag2 (intern (substring (symbol-name tag)
1527 (match-end 0)))))
1528 (concat (mpc-tagbrowser-tag-name tag1)
1529 " | "
1530 (mpc-tagbrowser-tag-name tag2))))
1531 ((string-match "y\\'" (symbol-name tag))
1532 (concat (substring (symbol-name tag) 0 -1) "ies"))
1533 (t (concat (symbol-name tag) "s"))))
1535 (defun mpc-tagbrowser-buf (tag)
1536 (let ((buf (mpc-proc-buffer (mpc-proc) tag)))
1537 (if (buffer-live-p buf) buf
1538 (setq buf (get-buffer-create (format "*MPC %ss*" tag)))
1539 (mpc-proc-buffer (mpc-proc) tag buf)
1540 (with-current-buffer buf
1541 (let ((inhibit-read-only t))
1542 (erase-buffer)
1543 (if (member tag '(Directory))
1544 (mpc-tagbrowser-dir-mode)
1545 (mpc-tagbrowser-mode))
1546 (insert mpc-tagbrowser-all-name "\n"))
1547 (forward-line -1)
1548 (setq mpc-tag tag)
1549 (setq mpc-tag-name (mpc-tagbrowser-tag-name tag))
1550 (mpc-tagbrowser-all-select)
1551 (mpc-tagbrowser-refresh)
1552 buf))))
1554 (defvar tag-browser-tagtypes
1555 (lazy-completion-table tag-browser-tagtypes
1556 (lambda ()
1557 (append '("Playlist" "Directory")
1558 (mpc-cmd-tagtypes)))))
1560 (defun mpc-tagbrowser (tag)
1561 "Create a new browser for TAG."
1562 (interactive
1563 (list
1564 (let ((completion-ignore-case t))
1565 (intern
1566 (completing-read "Tag: " tag-browser-tagtypes nil 'require-match)))))
1567 (let* ((newbuf (mpc-tagbrowser-buf tag))
1568 (win (get-buffer-window newbuf 0)))
1569 (if win (select-window win)
1570 (if (with-current-buffer (window-buffer)
1571 (derived-mode-p 'mpc-tagbrowser-mode))
1572 (setq win (selected-window))
1573 ;; Find a tagbrowser-mode buffer.
1574 (let ((buffers (process-get (mpc-proc) 'buffers))
1575 buffer)
1576 (while
1577 (and buffers
1578 (not (and (buffer-live-p (setq buffer (cdr (pop buffers))))
1579 (with-current-buffer buffer
1580 (derived-mode-p 'mpc-tagbrowser-mode))
1581 (setq win (get-buffer-window buffer 0))))))))
1582 (if (not win)
1583 (pop-to-buffer newbuf)
1584 (setq win (split-window win nil 'horiz))
1585 (set-window-buffer win newbuf)
1586 (set-window-dedicated-p win 'soft)
1587 (select-window win)
1588 (balance-windows-area)))))
1590 (defun mpc-tagbrowser-all-select ()
1591 "Select the special *ALL* entry if no other is selected."
1592 (if mpc-select
1593 (delete-overlay mpc-tagbrowser-all-ol)
1594 (save-excursion
1595 (goto-char (point-min))
1596 (if mpc-tagbrowser-all-ol
1597 (move-overlay mpc-tagbrowser-all-ol
1598 (point) (line-beginning-position 2))
1599 (let ((ol (make-overlay (point) (line-beginning-position 2))))
1600 (overlay-put ol 'face 'highlight)
1601 (overlay-put ol 'evaporate t)
1602 (setq-local mpc-tagbrowser-all-ol ol))))))
1604 ;; (defvar mpc-constraints nil)
1605 (defun mpc-separator (active)
1606 ;; Place a separator mark.
1607 (unless mpc-separator-ol
1608 (setq-local mpc-separator-ol
1609 (make-overlay (point) (point)))
1610 (overlay-put mpc-separator-ol 'after-string
1611 (propertize "\n"
1612 'face '(:height 0.05 :inverse-video t))))
1613 (goto-char (point-min))
1614 (forward-line 1)
1615 (while
1616 (and (member (buffer-substring-no-properties
1617 (line-beginning-position) (line-end-position))
1618 active)
1619 (zerop (forward-line 1))))
1620 (if (or (eobp) (null active))
1621 (delete-overlay mpc-separator-ol)
1622 (move-overlay mpc-separator-ol (1- (point)) (point))))
1624 (defun mpc-sort (active)
1625 ;; Sort the active elements at the front.
1626 (let ((inhibit-read-only t))
1627 (goto-char (point-min))
1628 (if (mpc-tagbrowser-all-p) (forward-line 1))
1629 (condition-case nil
1630 (sort-subr nil 'forward-line 'end-of-line
1631 nil nil
1632 (lambda (s1 s2)
1633 (setq s1 (buffer-substring-no-properties
1634 (car s1) (cdr s1)))
1635 (setq s2 (buffer-substring-no-properties
1636 (car s2) (cdr s2)))
1637 (cond
1638 ((member s1 active)
1639 (if (member s2 active)
1640 (let ((cmp (mpc-compare-strings s1 s2 t)))
1641 (and (numberp cmp) (< cmp 0)))
1643 ((member s2 active) nil)
1644 (t (let ((cmp (mpc-compare-strings s1 s2 t)))
1645 (and (numberp cmp) (< cmp 0)))))))
1646 ;; The comparison predicate arg is new in Emacs-22.
1647 (wrong-number-of-arguments
1648 (sort-subr nil 'forward-line 'end-of-line
1649 (lambda ()
1650 (let ((name (buffer-substring-no-properties
1651 (point) (line-end-position))))
1652 (cond
1653 ((member name active) (concat "1" name))
1654 (t (concat "2" "name"))))))))))
1656 (defvar mpc--changed-selection)
1658 (defun mpc-reorder (&optional nodeactivate)
1659 "Reorder entries based on the currently active selections.
1660 I.e. split the current browser buffer into a first part containing the
1661 entries included in the selection, then a separator, and then the entries
1662 not included in the selection.
1663 Return non-nil if a selection was deactivated."
1664 (mpc-select-save
1665 (let ((constraints (mpc-constraints-get-current (current-buffer)))
1666 (active 'all))
1667 ;; (unless (equal constraints mpc-constraints)
1668 ;; (setq-local mpc-constraints constraints)
1669 (dolist (cst constraints)
1670 (let ((vals (apply 'mpc-union
1671 (mapcar (lambda (val)
1672 (mpc-cmd-list mpc-tag (car cst) val))
1673 (cdr cst)))))
1674 (setq active
1675 (if (listp active) (mpc-intersection active vals) vals))))
1677 (when (listp active)
1678 ;; Remove the selections if they are all in conflict with
1679 ;; other constraints.
1680 (let ((deactivate t))
1681 (dolist (sel selection)
1682 (when (member sel active) (setq deactivate nil)))
1683 (when deactivate
1684 ;; Variable declared/used by `mpc-select-save'.
1685 (when selection
1686 (setq mpc--changed-selection t))
1687 (unless nodeactivate
1688 (setq selection nil)
1689 (mapc 'delete-overlay mpc-select)
1690 (setq mpc-select nil)
1691 (mpc-tagbrowser-all-select))))
1693 ;; Don't bother splitting the "active" elements to the first part if
1694 ;; they're the same as the selection.
1695 (when (equal (sort (copy-sequence active) #'string-lessp)
1696 (sort (copy-sequence selection) #'string-lessp))
1697 (setq active 'all)))
1699 ;; FIXME: This `mpc-sort' takes a lot of time. Maybe we should
1700 ;; be more clever and presume the buffer is mostly sorted already.
1701 (mpc-sort (if (listp active) active))
1702 (mpc-separator (if (listp active) active)))))
1704 (defun mpc-selection-refresh ()
1705 (let ((mpc--changed-selection t))
1706 (while mpc--changed-selection
1707 (setq mpc--changed-selection nil)
1708 (dolist (buf (process-get (mpc-proc) 'buffers))
1709 (setq buf (cdr buf))
1710 (when (and (buffer-local-value 'mpc-tag buf)
1711 (not (eq buf (current-buffer))))
1712 (with-current-buffer buf (mpc-reorder)))))
1713 ;; FIXME: reorder the current buffer last and prevent deactivation,
1714 ;; since whatever selection we made here is the most recent one
1715 ;; and should hence take precedence.
1716 (when mpc-tag (mpc-reorder 'nodeactivate))
1717 ;; FIXME: comment?
1718 (if (and mpc--song-search mpc--changed-selection)
1719 (progn
1720 (setq mpc--song-search nil)
1721 (mpc-selection-refresh))
1722 (mpc-songs-refresh))))
1724 ;;; Hierarchical tagbrowser ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1725 ;; Todo:
1726 ;; - Add a button on each dir to open/close it (?)
1727 ;; - add the parent dir on the previous line, grayed-out, if it's not
1728 ;; present (because we're in the non-selected part and the parent is
1729 ;; in the selected part).
1731 (defvar mpc-tagbrowser-dir-mode-map
1732 (let ((map (make-sparse-keymap)))
1733 (set-keymap-parent map mpc-tagbrowser-mode-map)
1734 (define-key map [?\M-\C-m] 'mpc-tagbrowser-dir-toggle)
1735 map))
1737 ;; (defvar mpc-tagbrowser-dir-keywords
1738 ;; '(mpc-tagbrowser-dir-hide-prefix))
1740 (define-derived-mode mpc-tagbrowser-dir-mode mpc-tagbrowser-mode '("MPC-" mpc-tag-name)
1741 ;; (setq-local font-lock-defaults
1742 ;; '(mpc-tagbrowser-dir-keywords t))
1745 ;; (defun mpc-tagbrowser-dir-hide-prefix (limit)
1746 ;; (while
1747 ;; (let ((prev (buffer-substring (line-beginning-position 0)
1748 ;; (line-end-position 0))))
1749 ;; (
1751 (defun mpc-tagbrowser-dir-toggle (event)
1752 "Open or close the element at point."
1753 (interactive (list last-nonmenu-event))
1754 (mpc-event-set-point event)
1755 (let ((name (buffer-substring (line-beginning-position)
1756 (line-end-position)))
1757 (prop (intern mpc-tag))
1758 (proc (mpc-proc)))
1759 (if (not (member name (process-get proc prop)))
1760 (process-put proc prop
1761 (cons name (process-get proc prop)))
1762 (let ((new (delete name (process-get proc prop))))
1763 (setq name (concat name "/"))
1764 (process-put proc prop
1765 (delq nil
1766 (mapcar (lambda (x)
1767 (if (string-prefix-p name x)
1768 nil x))
1769 new)))))
1770 (mpc-tagbrowser-refresh)))
1773 ;;; Playlist management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1775 (defvar-local mpc-songs-playlist nil
1776 "Name of the currently selected playlist, if any.
1777 A value of t means the main playlist.")
1779 (defun mpc-playlist-create (name)
1780 "Save current playlist under name NAME."
1781 (interactive "sPlaylist name: ")
1782 (mpc-proc-cmd (list "save" name))
1783 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1784 (when (buffer-live-p buf)
1785 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1787 (defun mpc-playlist-destroy (name)
1788 "Delete playlist named NAME."
1789 (interactive
1790 (list (completing-read "Delete playlist: " (mpc-cmd-list 'Playlist)
1791 nil 'require-match)))
1792 (mpc-proc-cmd (list "rm" name))
1793 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1794 (when (buffer-live-p buf)
1795 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1797 (defun mpc-playlist-rename (oldname newname)
1798 "Rename playlist OLDNAME to NEWNAME."
1799 (interactive
1800 (let* ((oldname (if (and (eq mpc-tag 'Playlist) (null current-prefix-arg))
1801 (buffer-substring (line-beginning-position)
1802 (line-end-position))
1803 (completing-read "Rename playlist: "
1804 (mpc-cmd-list 'Playlist)
1805 nil 'require-match)))
1806 (newname (read-string (format-message "Rename `%s' to: " oldname))))
1807 (if (zerop (length newname))
1808 (error "Aborted")
1809 (list oldname newname))))
1810 (mpc-proc-cmd (list "rename" oldname newname))
1811 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1812 (if (buffer-live-p buf)
1813 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1815 (defun mpc-playlist ()
1816 "Show the current playlist."
1817 (interactive)
1818 (mpc-constraints-push 'noerror)
1819 (mpc-constraints-restore '()))
1821 (defun mpc-playlist-add ()
1822 "Add the selection to the playlist."
1823 (interactive)
1824 (let ((songs (mapcar #'car (mpc-songs-selection))))
1825 (mpc-cmd-add songs)
1826 (message "Appended %d songs" (length songs))
1827 ;; Return the songs added. Used in `mpc-play'.
1828 songs))
1830 (defun mpc-playlist-delete ()
1831 "Remove the selected songs from the playlist."
1832 (interactive)
1833 (unless mpc-songs-playlist
1834 (error "The selected songs aren't part of a playlist"))
1835 (let ((song-poss (mapcar #'cdr (mpc-songs-selection))))
1836 (mpc-cmd-delete song-poss mpc-songs-playlist)
1837 (mpc-songs-refresh)
1838 (message "Deleted %d songs" (length song-poss))))
1840 ;;; Volume management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1842 (defvar mpc-volume-map
1843 (let ((map (make-sparse-keymap)))
1844 ;; Bind the up-events rather than the down-event, so the
1845 ;; `message' isn't canceled by the subsequent up-event binding.
1846 (define-key map [down-mouse-1] 'ignore)
1847 (define-key map [mouse-1] 'mpc-volume-mouse-set)
1848 (define-key map [header-line mouse-1] 'mpc-volume-mouse-set)
1849 (define-key map [header-line down-mouse-1] 'ignore)
1850 (define-key map [mode-line mouse-1] 'mpc-volume-mouse-set)
1851 (define-key map [mode-line down-mouse-1] 'ignore)
1852 map))
1854 (defvar mpc-volume nil) (put 'mpc-volume 'risky-local-variable t)
1856 (defun mpc-volume-refresh ()
1857 ;; Maintain the volume.
1858 (setq mpc-volume
1859 (mpc-volume-widget
1860 (string-to-number (cdr (assq 'volume mpc-status)))))
1861 (let ((status-buf (mpc-proc-buffer (mpc-proc) 'status)))
1862 (when (buffer-live-p status-buf)
1863 (with-current-buffer status-buf (force-mode-line-update)))))
1865 (defvar mpc-volume-step 5)
1867 (defun mpc-volume-mouse-set (&optional event)
1868 "Change volume setting."
1869 (interactive (list last-nonmenu-event))
1870 (let* ((posn (event-start event))
1871 (diff
1872 (if (memq (if (stringp (car-safe (posn-object posn)))
1873 (aref (car (posn-object posn)) (cdr (posn-object posn)))
1874 (with-current-buffer (window-buffer (posn-window posn))
1875 (char-after (posn-point posn))))
1876 '(?◁ ?<))
1877 (- mpc-volume-step) mpc-volume-step))
1878 (curvol (string-to-number (cdr (assq 'volume mpc-status))))
1879 (newvol (max 0 (min 100 (+ curvol diff)))))
1880 (if (= newvol curvol)
1881 (progn
1882 (message "MPD volume already at %s%%" newvol)
1883 (ding))
1884 (mpc-proc-cmd (list "setvol" newvol) 'mpc-status-refresh)
1885 (message "Set MPD volume to %s%%" newvol))))
1887 (defun mpc-volume-widget (vol &optional size)
1888 (unless size (setq size 12.5))
1889 (let ((scaledvol (* (/ vol 100.0) size)))
1890 ;; (message "Volume sizes: %s - %s" (/ vol fact) (/ (- 100 vol) fact))
1891 (list (propertize "<" ;; "◁"
1892 ;; 'face 'default
1893 'keymap mpc-volume-map
1894 'face '(:box (:line-width -2 :style pressed-button))
1895 'mouse-face '(:box (:line-width -2 :style released-button)))
1897 (propertize "a"
1898 'display (list 'space :width scaledvol)
1899 'face '(:inverse-video t
1900 :box (:line-width -2 :style released-button)))
1901 (propertize "a"
1902 'display (list 'space :width (- size scaledvol))
1903 'face '(:box (:line-width -2 :style released-button)))
1905 (propertize ">" ;; "▷"
1906 ;; 'face 'default
1907 'keymap mpc-volume-map
1908 'face '(:box (:line-width -2 :style pressed-button))
1909 'mouse-face '(:box (:line-width -2 :style released-button))))))
1911 ;;; MPC songs mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1913 (defvar mpc-current-song nil) (put 'mpc-current-song 'risky-local-variable t)
1914 (defvar mpc-current-updating nil) (put 'mpc-current-updating 'risky-local-variable t)
1915 (defvar mpc-songs-format-description nil) (put 'mpc-songs-format-description 'risky-local-variable t)
1917 (defvar mpc-previous-window-config nil)
1919 (defvar mpc-songs-mode-map
1920 (let ((map (make-sparse-keymap)))
1921 (define-key map [remap mpc-select] 'mpc-songs-jump-to)
1922 map))
1924 (defvar mpc-songpointer-set-visible nil)
1926 (defvar mpc-songs-hashcons (make-hash-table :test 'equal :weakness t)
1927 "Make song file name objects unique via hash consing.
1928 This is used so that they can be compared with `eq', which is needed for
1929 `text-property-any'.")
1930 (defun mpc-songs-hashcons (name)
1931 (or (gethash name mpc-songs-hashcons) (puthash name name mpc-songs-hashcons)))
1932 (defcustom mpc-songs-format "%2{Disc--}%3{Track} %-5{Time} %25{Title} %20{Album} %20{Artist} %5{Date}"
1933 "Format used to display each song in the list of songs."
1934 :type 'string)
1936 (defvar mpc-songs-totaltime)
1938 (defun mpc-songs-refresh ()
1939 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
1940 (when (buffer-live-p buf)
1941 (with-current-buffer buf
1942 (let ((constraints (mpc-constraints-get-current (current-buffer)))
1943 (dontsort nil)
1944 (inhibit-read-only t)
1945 (totaltime 0)
1946 (curline (cons (count-lines (point-min)
1947 (line-beginning-position))
1948 (buffer-substring (line-beginning-position)
1949 (line-end-position))))
1950 active)
1951 (setq mpc-songs-playlist nil)
1952 (if (null constraints)
1953 ;; When there are no constraints, rather than show the list of
1954 ;; all songs (which could take a while to download and
1955 ;; format), we show the current playlist.
1956 ;; FIXME: it would be good to be able to show the complete
1957 ;; list, but that would probably require us to format it
1958 ;; on-the-fly to make it bearable.
1959 (setq dontsort t
1960 mpc-songs-playlist t
1961 active (mpc-proc-buf-to-alists
1962 (mpc-proc-cmd "playlistinfo")))
1963 (dolist (cst constraints)
1964 (if (and (eq (car cst) 'Playlist)
1965 (= 1 (length (cdr cst))))
1966 (setq mpc-songs-playlist (cadr cst)))
1967 ;; We don't do anything really special here for playlists,
1968 ;; because it's unclear what's a correct "union" of playlists.
1969 (let ((vals (apply 'mpc-union
1970 (mapcar (lambda (val)
1971 (mpc-cmd-find (car cst) val))
1972 (cdr cst)))))
1973 (setq active (cond
1974 ((null active)
1975 (if (eq (car cst) 'Playlist)
1976 (setq dontsort t))
1977 vals)
1978 ((or dontsort
1979 ;; Try to preserve ordering and
1980 ;; repetitions from playlists.
1981 (not (eq (car cst) 'Playlist)))
1982 (mpc-intersection active vals
1983 (lambda (x) (assq 'file x))))
1985 (setq dontsort t)
1986 (mpc-intersection vals active
1987 (lambda (x)
1988 (assq 'file x)))))))))
1989 (mpc-select-save
1990 (erase-buffer)
1991 ;; Sorting songs is surprisingly difficult: when comparing two
1992 ;; songs with the same album name but different artist name, you
1993 ;; have to know whether these are two different albums (with the
1994 ;; same name) or a single album (typically a compilation).
1995 ;; I punt on it and just use file-name sorting, which does the
1996 ;; right thing if your library is properly arranged.
1997 (dolist (song (if dontsort active
1998 (sort (copy-sequence active)
1999 (lambda (song1 song2)
2000 (let ((cmp (mpc-compare-strings
2001 (cdr (assq 'file song1))
2002 (cdr (assq 'file song2)))))
2003 (and (integerp cmp) (< cmp 0)))))))
2004 (cl-incf totaltime (string-to-number (or (cdr (assq 'Time song)) "0")))
2005 (mpc-format mpc-songs-format song)
2006 (delete-char (- (skip-chars-backward " "))) ;Remove trailing space.
2007 (insert "\n")
2008 (put-text-property
2009 (line-beginning-position 0) (line-beginning-position)
2010 'mpc-file (mpc-songs-hashcons (cdr (assq 'file song))))
2011 (let ((pos (assq 'Pos song)))
2012 (if pos
2013 (put-text-property
2014 (line-beginning-position 0) (line-beginning-position)
2015 'mpc-file-pos (string-to-number (cdr pos)))))
2017 (goto-char (point-min))
2018 (forward-line (car curline))
2019 (if (or (search-forward (cdr curline) nil t)
2020 (search-backward (cdr curline) nil t))
2021 (beginning-of-line)
2022 (goto-char (point-min)))
2023 (setq-local mpc-songs-totaltime
2024 (unless (zerop totaltime)
2025 (list " " (mpc-secs-to-time totaltime))))
2026 ))))
2027 (let ((mpc-songpointer-set-visible t))
2028 (mpc-songpointer-refresh)))
2030 (defun mpc-songs-search (string)
2031 "Filter songs to those who include STRING in their metadata."
2032 (interactive "sSearch for: ")
2033 (setq mpc--song-search
2034 (if (zerop (length string)) nil string))
2035 (let ((mpc--changed-selection t))
2036 (while mpc--changed-selection
2037 (setq mpc--changed-selection nil)
2038 (dolist (buf (process-get (mpc-proc) 'buffers))
2039 (setq buf (cdr buf))
2040 (when (buffer-local-value 'mpc-tag buf)
2041 (with-current-buffer buf (mpc-reorder))))
2042 (mpc-songs-refresh))))
2044 (defun mpc-songs-kill-search ()
2045 "Turn off the current search restriction."
2046 (interactive)
2047 (mpc-songs-search nil))
2049 (defun mpc-songs-selection ()
2050 "Return the list of songs currently selected."
2051 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2052 (when (buffer-live-p buf)
2053 (with-current-buffer buf
2054 (save-excursion
2055 (let ((files ()))
2056 (if mpc-select
2057 (dolist (ol mpc-select)
2058 (push (cons
2059 (get-text-property (overlay-start ol) 'mpc-file)
2060 (get-text-property (overlay-start ol) 'mpc-file-pos))
2061 files))
2062 (goto-char (point-min))
2063 (while (not (eobp))
2064 (push (cons
2065 (get-text-property (point) 'mpc-file)
2066 (get-text-property (point) 'mpc-file-pos))
2067 files)
2068 (forward-line 1)))
2069 (nreverse files)))))))
2071 (defun mpc-songs-jump-to (song-file &optional posn)
2072 "Jump to song SONG-FILE; interactively, this is the song at point."
2073 (interactive
2074 (let* ((event last-nonmenu-event)
2075 (posn (event-end event)))
2076 (with-selected-window (posn-window posn)
2077 (goto-char (posn-point posn))
2078 (list (get-text-property (point) 'mpc-file)
2079 posn))))
2080 (let* ((plbuf (mpc-proc-cmd "playlist"))
2081 (re (if song-file
2082 ;; Newer MPCs apparently include "file: " in the buffer.
2083 (concat "^\\([0-9]+\\):\\(?:file: \\)?"
2084 (regexp-quote song-file) "$")))
2085 (sn (with-current-buffer plbuf
2086 (goto-char (point-min))
2087 (when (and re (re-search-forward re nil t))
2088 (match-string 1)))))
2089 (cond
2090 ((null re) (posn-set-point posn))
2091 ((null sn) (user-error "This song is not in the playlist"))
2092 ((null (with-current-buffer plbuf (re-search-forward re nil t)))
2093 ;; song-file only appears once in the playlist: no ambiguity,
2094 ;; we're good to go!
2095 (mpc-proc-cmd (list "play" sn)))
2097 ;; The song appears multiple times in the playlist. If the current
2098 ;; buffer holds not only the destination song but also the current
2099 ;; song, then we will move in the playlist to the same relative
2100 ;; position as in the buffer. Otherwise, we will simply choose the
2101 ;; song occurrence closest to the current song.
2102 (with-selected-window (posn-window posn)
2103 (let* ((cur (and (markerp overlay-arrow-position)
2104 (marker-position overlay-arrow-position)))
2105 (dest (save-excursion
2106 (goto-char (posn-point posn))
2107 (line-beginning-position)))
2108 (lines (when cur (* (if (< cur dest) 1 -1)
2109 (count-lines cur dest)))))
2110 (with-current-buffer plbuf
2111 (goto-char (point-min))
2112 ;; Start the search from the current song.
2113 (forward-line (string-to-number
2114 (or (cdr (assq 'song mpc-status)) "0")))
2115 ;; If the current song is also displayed in the buffer,
2116 ;; then try to move to the same relative position.
2117 (if lines (forward-line lines))
2118 ;; Now search the closest occurrence.
2119 (let* ((next (save-excursion
2120 (when (re-search-forward re nil t)
2121 (cons (point) (match-string 1)))))
2122 (prev (save-excursion
2123 (when (re-search-backward re nil t)
2124 (cons (point) (match-string 1)))))
2125 (sn (cdr (if (and next prev)
2126 (if (< (- (car next) (point))
2127 (- (point) (car prev)))
2128 next prev)
2129 (or next prev)))))
2130 (cl-assert sn)
2131 (mpc-proc-cmd (concat "play " sn))))))))))
2133 (define-derived-mode mpc-songs-mode mpc-mode "MPC-song"
2134 (setq mpc-songs-format-description
2135 (with-temp-buffer (mpc-format mpc-songs-format 'self) (buffer-string)))
2136 (setq-local header-line-format
2137 ;; '("MPC " mpc-volume " " mpc-current-song)
2138 (list (propertize " " 'display '(space :align-to 0))
2139 ;; 'mpc-songs-format-description
2140 '(:eval
2141 (let ((hscroll (window-hscroll)))
2142 (with-temp-buffer
2143 (mpc-format mpc-songs-format 'self hscroll)
2144 ;; That would be simpler than the hscroll handling in
2145 ;; mpc-format, but currently move-to-column does not
2146 ;; recognize :space display properties.
2147 ;; (move-to-column hscroll)
2148 ;; (delete-region (point-min) (point))
2149 (buffer-string))))))
2150 (setq-local
2151 mode-line-format
2152 '("%e" mode-line-frame-identification mode-line-buffer-identification
2153 #(" " 0 3
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 mode-line-position
2156 #(" " 0 2
2157 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2158 mpc-songs-totaltime
2159 mpc-current-updating
2160 #(" " 0 2
2161 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2162 (mpc--song-search
2163 (:propertize
2164 ("Search=\"" mpc--song-search "\"")
2165 help-echo "mouse-2: kill this search"
2166 follow-link t
2167 mouse-face mode-line-highlight
2168 keymap (keymap (mode-line keymap
2169 (mouse-2 . mpc-songs-kill-search))))
2170 (:propertize "NoSearch"
2171 help-echo "mouse-2: set a search restriction"
2172 follow-link t
2173 mouse-face mode-line-highlight
2174 keymap (keymap (mode-line keymap (mouse-2 . mpc-songs-search)))))))
2176 ;; (setq-local mode-line-process
2177 ;; '("" ;; mpc-volume " "
2178 ;; mpc-songs-totaltime
2179 ;; mpc-current-updating))
2182 (defun mpc-songpointer-set (pos)
2183 (let* ((win (get-buffer-window (current-buffer) t))
2184 (visible (when win
2185 (or mpc-songpointer-set-visible
2186 (and (markerp overlay-arrow-position)
2187 (eq (marker-buffer overlay-arrow-position)
2188 (current-buffer))
2189 (<= (window-start win) overlay-arrow-position)
2190 (< overlay-arrow-position (window-end win)))))))
2191 (unless (local-variable-p 'overlay-arrow-position)
2192 (setq-local overlay-arrow-position (make-marker)))
2193 (move-marker overlay-arrow-position pos)
2194 ;; If the arrow was visible, try to keep it that way.
2195 (if (and visible pos
2196 (or (> (window-start win) pos) (>= pos (window-end win t))))
2197 (set-window-point win pos))))
2199 (defun mpc-songpointer-refresh ()
2200 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2201 (when (buffer-live-p buf)
2202 (with-current-buffer buf
2203 (let* ((pos (text-property-any
2204 (point-min) (point-max)
2205 'mpc-file (mpc-songs-hashcons
2206 (cdr (assq 'file mpc-status)))))
2207 (other (when pos
2208 (save-excursion
2209 (goto-char pos)
2210 (text-property-any
2211 (line-beginning-position 2) (point-max)
2212 'mpc-file (mpc-songs-hashcons
2213 (cdr (assq 'file mpc-status))))))))
2214 (if other
2215 ;; The song appears multiple times in the buffer.
2216 ;; We need to be careful to choose the right occurrence.
2217 (mpc-proc-cmd "playlist" 'mpc-songpointer-refresh-hairy)
2218 (mpc-songpointer-set pos)))))))
2220 (defun mpc-songpointer-context (size plbuf)
2221 (with-current-buffer plbuf
2222 (goto-char (point-min))
2223 (forward-line (string-to-number (or (cdr (assq 'song mpc-status)) "0")))
2224 (let ((context-before '())
2225 (context-after '()))
2226 (save-excursion
2227 (dotimes (_i size)
2228 (when (re-search-backward "^[0-9]+:\\(.*\\)" nil t)
2229 (push (mpc-songs-hashcons (match-string 1)) context-before))))
2230 ;; Skip the actual current song.
2231 (forward-line 1)
2232 (dotimes (_i size)
2233 (when (re-search-forward "^[0-9]+:\\(.*\\)" nil t)
2234 (push (mpc-songs-hashcons (match-string 1)) context-after)))
2235 ;; If there isn't `size' context, then return nil.
2236 (unless (and (< (length context-before) size)
2237 (< (length context-after) size))
2238 (cons (nreverse context-before) (nreverse context-after))))))
2240 (defun mpc-songpointer-score (context pos)
2241 (let ((count 0))
2242 (goto-char pos)
2243 (dolist (song (car context))
2244 (and (zerop (forward-line -1))
2245 (eq (get-text-property (point) 'mpc-file) song)
2246 (cl-incf count)))
2247 (goto-char pos)
2248 (dolist (song (cdr context))
2249 (and (zerop (forward-line 1))
2250 (eq (get-text-property (point) 'mpc-file) song)
2251 (cl-incf count)))
2252 count))
2254 (defun mpc-songpointer-refresh-hairy ()
2255 ;; Based on the complete playlist, we should figure out where in the
2256 ;; song buffer is the currently playing song.
2257 (let ((plbuf (current-buffer))
2258 (buf (mpc-proc-buffer (mpc-proc) 'songs)))
2259 (when (buffer-live-p buf)
2260 (with-current-buffer buf
2261 (let* ((context-size 0)
2262 (context '(() . ()))
2263 (pos (text-property-any
2264 (point-min) (point-max)
2265 'mpc-file (mpc-songs-hashcons
2266 (cdr (assq 'file mpc-status)))))
2267 (score 0)
2268 (other pos))
2269 (while
2270 (setq other
2271 (save-excursion
2272 (goto-char other)
2273 (text-property-any
2274 (line-beginning-position 2) (point-max)
2275 'mpc-file (mpc-songs-hashcons
2276 (cdr (assq 'file mpc-status))))))
2277 ;; There is an `other' contestant.
2278 (let ((other-score (mpc-songpointer-score context other)))
2279 (cond
2280 ;; `other' is worse: try the next one.
2281 ((< other-score score) nil)
2282 ;; `other' is better: remember it and then search further.
2283 ((> other-score score)
2284 (setq pos other)
2285 (setq score other-score))
2286 ;; Both are equal and increasing the context size won't help.
2287 ;; Arbitrarily choose one of the two and keep looking
2288 ;; for a better match.
2289 ((< score context-size) nil)
2291 ;; Score is equal and increasing context might help: try it.
2292 (cl-incf context-size)
2293 (let ((new-context
2294 (mpc-songpointer-context context-size plbuf)))
2295 (if (null new-context)
2296 ;; There isn't more context: choose one arbitrarily
2297 ;; and keep looking for a better match elsewhere.
2298 (cl-decf context-size)
2299 (setq context new-context)
2300 (setq score (mpc-songpointer-score context pos))
2301 (save-excursion
2302 (goto-char other)
2303 ;; Go back one line so we find `other' again.
2304 (setq other (line-beginning-position 0)))))))))
2305 (mpc-songpointer-set pos))))))
2307 (defun mpc-current-refresh ()
2308 ;; Maintain the current data.
2309 (mpc-status-buffer-refresh)
2310 (setq mpc-current-updating
2311 (if (assq 'updating_db mpc-status) " Updating-DB"))
2312 (ignore-errors
2313 (setq mpc-current-song
2314 (when (assq 'file mpc-status)
2315 (concat " "
2316 (mpc-secs-to-time (cdr (assq 'time mpc-status)))
2318 (cdr (assq 'Title mpc-status))
2319 " ("
2320 (cdr (assq 'Artist mpc-status))
2321 " / "
2322 (cdr (assq 'Album mpc-status))
2323 ")"))))
2324 (force-mode-line-update t))
2326 (defun mpc-songs-buf ()
2327 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2328 (if (buffer-live-p buf) buf
2329 (with-current-buffer (setq buf (get-buffer-create "*MPC-Songs*"))
2330 (mpc-proc-buffer (mpc-proc) 'songs buf)
2331 (mpc-songs-mode)
2332 buf))))
2334 (defun mpc-update ()
2335 "Tell MPD to refresh its database."
2336 (interactive)
2337 (mpc-cmd-update))
2339 (defun mpc-quit ()
2340 "Quit Music Player Daemon."
2341 (interactive)
2342 (let* ((proc mpc-proc)
2343 (bufs (mapcar 'cdr (if proc (process-get proc 'buffers))))
2344 (wins (mapcar (lambda (buf) (get-buffer-window buf 0)) bufs))
2345 (song-buf (mpc-songs-buf))
2346 frames)
2347 ;; Collect all the frames where MPC buffers appear.
2348 (dolist (win wins)
2349 (when (and win (not (memq (window-frame win) frames)))
2350 (push (window-frame win) frames)))
2351 (if (and frames song-buf
2352 (with-current-buffer song-buf mpc-previous-window-config))
2353 (progn
2354 (select-frame (car frames))
2355 (set-window-configuration
2356 (with-current-buffer song-buf mpc-previous-window-config)))
2357 ;; Now delete the ones that show nothing else than MPC buffers.
2358 (dolist (frame frames)
2359 (let ((delete t))
2360 (dolist (win (window-list frame))
2361 (unless (memq (window-buffer win) bufs) (setq delete nil)))
2362 (if delete (ignore-errors (delete-frame frame))))))
2363 ;; Then kill the buffers.
2364 (mapc 'kill-buffer bufs)
2365 (mpc-status-stop)
2366 (if proc (delete-process proc))))
2368 (defun mpc-toggle-consume ()
2369 "Toggle consume mode: removing played songs from the playlist."
2370 (interactive)
2371 (mpc-cmd-consume
2372 (if (string= "0" (cdr (assq 'consume (mpc-cmd-status)))) "1" "0")))
2374 (defun mpc-toggle-repeat ()
2375 "Toggle repeat mode."
2376 (interactive)
2377 (mpc-cmd-repeat
2378 (if (string= "0" (cdr (assq 'repeat (mpc-cmd-status)))) "1" "0")))
2380 (defun mpc-toggle-single ()
2381 "Toggle single mode."
2382 (interactive)
2383 (mpc-cmd-single
2384 (if (string= "0" (cdr (assq 'single (mpc-cmd-status)))) "1" "0")))
2386 (defun mpc-toggle-shuffle ()
2387 "Toggle shuffling of the playlist (random mode)."
2388 (interactive)
2389 (mpc-cmd-random
2390 (if (string= "0" (cdr (assq 'random (mpc-cmd-status)))) "1" "0")))
2392 (defun mpc-stop ()
2393 "Stop playing the current queue of songs."
2394 (interactive)
2395 (mpc-cmd-stop)
2396 (mpc-cmd-clear)
2397 (mpc-status-refresh))
2399 (defun mpc-pause ()
2400 "Pause playing."
2401 (interactive)
2402 (mpc-cmd-pause "1"))
2404 (defun mpc-resume ()
2405 "Resume playing."
2406 (interactive)
2407 (mpc-cmd-pause "0"))
2409 (defun mpc-seek-current (pos)
2410 "Seek within current track."
2411 (interactive
2412 (list (read-string "Position to go ([+-]seconds): ")))
2413 (mpc-cmd-seekcur pos))
2415 (defun mpc-toggle-play ()
2416 "Toggle between play and pause.
2417 If stopped, start playback."
2418 (interactive)
2419 (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2420 (mpc-cmd-play)
2421 (if (member (cdr (assq 'state (mpc-cmd-status))) '("pause"))
2422 (mpc-resume)
2423 (mpc-pause))))
2425 (defun mpc-play ()
2426 "Start playing whatever is selected."
2427 (interactive)
2428 (if (member (cdr (assq 'state (mpc-cmd-status))) '("pause"))
2429 (mpc-resume)
2430 ;; When playing the playlist ends, the playlist isn't cleared, but the
2431 ;; user probably doesn't want to re-listen to it before getting to
2432 ;; listen to what he just selected.
2433 ;; (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2434 ;; (mpc-cmd-clear))
2435 ;; Actually, we don't use mpc-play to append to the playlist any more,
2436 ;; so we can just always empty the playlist.
2437 (mpc-cmd-clear)
2438 (if (mpc-playlist-add)
2439 (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2440 (mpc-cmd-play))
2441 (user-error "Don't know what to play"))))
2443 (defun mpc-next ()
2444 "Jump to the next song in the queue."
2445 (interactive)
2446 (mpc-proc-cmd "next")
2447 (mpc-status-refresh))
2449 (defun mpc-prev ()
2450 "Jump to the beginning of the current song, or to the previous song."
2451 (interactive)
2452 (let ((time (cdr (assq 'time mpc-status))))
2453 ;; Here we rely on the fact that string-to-number silently ignores
2454 ;; everything after a non-digit char.
2455 (cond
2456 ;; Go back to the beginning of current song.
2457 ((and time (> (string-to-number time) 0))
2458 (mpc-proc-cmd (list "seekid" (cdr (assq 'songid mpc-status)) 0)))
2459 ;; We're at the beginning of the first song of the playlist.
2460 ;; Fetch the previous one from `mpc-queue-back'.
2461 ;; ((and (zerop (string-to-number (cdr (assq 'song mpc-status))))
2462 ;; mpc-queue-back)
2463 ;; ;; Because we use cmd-list rather than cmd-play, the queue is not
2464 ;; ;; automatically updated.
2465 ;; (let ((prev (pop mpc-queue-back)))
2466 ;; (push prev mpc-queue)
2467 ;; (mpc-proc-cmd
2468 ;; (mpc-proc-cmd-list
2469 ;; (list (list "add" prev)
2470 ;; (list "move" (cdr (assq 'playlistlength mpc-status)) "0")
2471 ;; "previous")))))
2472 ;; We're at the beginning of a song, but not the first one.
2473 (t (mpc-proc-cmd "previous")))
2474 (mpc-status-refresh)))
2476 (defvar mpc-last-seek-time '(0 . 0))
2478 (defun mpc--faster (event speedup step)
2479 "Fast forward."
2480 (interactive (list last-nonmenu-event))
2481 (let ((repeat-delay (/ (abs (float step)) speedup)))
2482 (if (not (memq 'down (event-modifiers event)))
2483 (let* ((currenttime (float-time))
2484 (last-time (- currenttime (car mpc-last-seek-time))))
2485 (if (< last-time (* 0.9 repeat-delay))
2486 nil ;; Throttle
2487 (let* ((status (if (< last-time 1.0)
2488 mpc-status (mpc-cmd-status)))
2489 (songid (cdr (assq 'songid status)))
2490 (time (if songid
2491 (if (< last-time 1.0)
2492 (cdr mpc-last-seek-time)
2493 (string-to-number
2494 (cdr (assq 'time status)))))))
2495 (setq mpc-last-seek-time
2496 (cons currenttime (setq time (+ time step))))
2497 (mpc-proc-cmd (list "seekid" songid time)
2498 'mpc-status-refresh))))
2499 (let ((status (mpc-cmd-status)))
2500 (let* ((songid (cdr (assq 'songid status)))
2501 (time (if songid (string-to-number
2502 (cdr (assq 'time status))))))
2503 (let ((timer (run-with-timer
2504 t repeat-delay
2505 (lambda ()
2506 (mpc-proc-cmd (list "seekid" songid
2507 (setq time (+ time step)))
2508 'mpc-status-refresh)))))
2509 (while (mouse-movement-p
2510 (event-basic-type (setq event (read-event)))))
2511 (cancel-timer timer)))))))
2513 (defvar mpc--faster-toggle-timer nil)
2514 (defun mpc--faster-stop ()
2515 (when mpc--faster-toggle-timer
2516 (cancel-timer mpc--faster-toggle-timer)
2517 (setq mpc--faster-toggle-timer nil)))
2519 (defun mpc--faster-toggle-refresh ()
2520 (if (equal (cdr (assq 'state mpc-status)) "stop")
2521 (mpc--faster-stop)))
2523 (defun mpc--songduration ()
2524 (string-to-number
2525 (let ((s (cdr (assq 'time mpc-status))))
2526 (if (not (string-match ":" s))
2527 (error "Unexpected time format %S" s)
2528 (substring s (match-end 0))))))
2530 (defvar mpc--faster-toggle-forward nil)
2531 (defvar mpc--faster-acceleration 0.5)
2532 (defun mpc--faster-toggle (speedup step)
2533 (setq speedup (float speedup))
2534 (if mpc--faster-toggle-timer
2535 (mpc--faster-stop)
2536 (mpc-status-refresh) (mpc-proc-sync)
2537 (let* (songid ;The ID of the currently ffwd/rewinding song.
2538 songduration ;The duration of that song.
2539 songtime ;The time of the song last time we ran.
2540 oldtime ;The time of day last time we ran.
2541 prevsongid) ;The song we're in the process leaving.
2542 (let ((fun
2543 (lambda ()
2544 (let ((newsongid (cdr (assq 'songid mpc-status))))
2546 (if (and (equal prevsongid newsongid)
2547 (not (equal prevsongid songid)))
2548 ;; We left prevsongid and came back to it. Pretend it
2549 ;; didn't happen.
2550 (setq newsongid songid))
2552 (cond
2553 ((null newsongid) (mpc--faster-stop))
2554 ((not (equal songid newsongid))
2555 ;; We jumped to another song: reset.
2556 (setq songid newsongid)
2557 (setq songtime (string-to-number
2558 (cdr (assq 'time mpc-status))))
2559 (setq songduration (mpc--songduration))
2560 (setq oldtime (float-time)))
2561 ((and (>= songtime songduration) mpc--faster-toggle-forward)
2562 ;; Skip to the beginning of the next song.
2563 (if (not (equal (cdr (assq 'state mpc-status)) "play"))
2564 (mpc-proc-cmd "next" 'mpc-status-refresh)
2565 ;; If we're playing, this is done automatically, so we
2566 ;; don't need to do anything, or rather we *shouldn't*
2567 ;; do anything otherwise there's a race condition where
2568 ;; we could skip straight to the next next song.
2569 nil))
2570 ((and (<= songtime 0) (not mpc--faster-toggle-forward))
2571 ;; Skip to the end of the previous song.
2572 (setq prevsongid songid)
2573 (mpc-proc-cmd "previous"
2574 (lambda ()
2575 (mpc-status-refresh
2576 (lambda ()
2577 (setq songid (cdr (assq 'songid mpc-status)))
2578 (setq songtime (setq songduration (mpc--songduration)))
2579 (setq oldtime (float-time))
2580 (mpc-proc-cmd (list "seekid" songid songtime)))))))
2582 (setq speedup (+ speedup mpc--faster-acceleration))
2583 (let ((newstep
2584 (truncate (* speedup (- (float-time) oldtime)))))
2585 (if (<= newstep 1) (setq newstep 1))
2586 (setq oldtime (+ oldtime (/ newstep speedup)))
2587 (if (not mpc--faster-toggle-forward)
2588 (setq newstep (- newstep)))
2589 (setq songtime (min songduration (+ songtime newstep)))
2590 (unless (>= songtime songduration)
2591 (condition-case nil
2592 (mpc-proc-cmd
2593 (list "seekid" songid songtime)
2594 'mpc-status-refresh)
2595 (mpc-proc-error (mpc-status-refresh)))))))))))
2596 (setq mpc--faster-toggle-forward (> step 0))
2597 (funcall fun) ;Initialize values.
2598 (setq mpc--faster-toggle-timer
2599 (run-with-timer t 0.3 fun))))))
2603 (defvar mpc-faster-speedup 8)
2605 (defun mpc-ffwd (_event)
2606 "Fast forward."
2607 (interactive (list last-nonmenu-event))
2608 ;; (mpc--faster event 4.0 1)
2609 (mpc--faster-toggle mpc-faster-speedup 1))
2611 (defun mpc-rewind (_event)
2612 "Fast rewind."
2613 (interactive (list last-nonmenu-event))
2614 ;; (mpc--faster event 4.0 -1)
2615 (mpc--faster-toggle mpc-faster-speedup -1))
2618 (defun mpc-play-at-point (&optional event)
2619 (interactive (list last-nonmenu-event))
2620 (mpc-select event)
2621 (mpc-play))
2623 ;; (defun mpc-play-tagval ()
2624 ;; "Play all the songs of the tag at point."
2625 ;; (interactive)
2626 ;; (let* ((val (buffer-substring (line-beginning-position) (line-end-position)))
2627 ;; (songs (mapcar 'cdar
2628 ;; (mpc-proc-buf-to-alists
2629 ;; (mpc-proc-cmd (list "find" mpc-tag val))))))
2630 ;; (mpc-cmd-add songs)
2631 ;; (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2632 ;; (mpc-cmd-play))))
2634 ;;; Drag'n'drop support ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2635 ;; Todo:
2636 ;; the main thing to do here, is to provide visual feedback during the drag:
2637 ;; - change the mouse-cursor.
2638 ;; - highlight/select the source and the current destination.
2640 (defun mpc-drag-n-drop (event)
2641 "DWIM for a drag EVENT."
2642 (interactive "e")
2643 (let* ((start (event-start event))
2644 (end (event-end event))
2645 (start-buf (window-buffer (posn-window start)))
2646 (end-buf (window-buffer (posn-window end)))
2647 (songs
2648 (with-current-buffer start-buf
2649 (goto-char (posn-point start))
2650 (if (get-text-property (point) 'mpc-select)
2651 ;; FIXME: actually we should only consider the constraints
2652 ;; corresponding to the selection in this particular buffer.
2653 (mpc-songs-selection)
2654 (cond
2655 ((and (derived-mode-p 'mpc-songs-mode)
2656 (get-text-property (point) 'mpc-file))
2657 (list (cons (get-text-property (point) 'mpc-file)
2658 (get-text-property (point) 'mpc-file-pos))))
2659 ((and mpc-tag (not (mpc-tagbrowser-all-p)))
2660 (mapcar (lambda (song)
2661 (list (cdr (assq 'file song))))
2662 (mpc-cmd-find
2663 mpc-tag
2664 (buffer-substring (line-beginning-position)
2665 (line-end-position)))))
2667 (error "Unsupported starting position for drag'n'drop gesture")))))))
2668 (with-current-buffer end-buf
2669 (goto-char (posn-point end))
2670 (cond
2671 ((eq mpc-tag 'Playlist)
2672 ;; Adding elements to a named playlist.
2673 (let ((playlist (if (or (mpc-tagbrowser-all-p)
2674 (and (bolp) (eolp)))
2675 (error "Not a playlist")
2676 (buffer-substring (line-beginning-position)
2677 (line-end-position)))))
2678 (mpc-cmd-add (mapcar 'car songs) playlist)
2679 (message "Added %d songs to %s" (length songs) playlist)
2680 (if (member playlist
2681 (cdr (assq 'Playlist (mpc-constraints-get-current))))
2682 (mpc-songs-refresh))))
2683 ((derived-mode-p 'mpc-songs-mode)
2684 (cond
2685 ((null mpc-songs-playlist)
2686 (error "The songs shown do not belong to a playlist"))
2687 ((eq start-buf end-buf)
2688 ;; Moving songs within the shown playlist.
2689 (let ((dest-pos (get-text-property (point) 'mpc-file-pos)))
2690 (mpc-cmd-move (mapcar 'cdr songs) dest-pos mpc-songs-playlist)
2691 (message "Moved %d songs" (length songs))))
2693 ;; Adding songs to the shown playlist.
2694 (let ((dest-pos (get-text-property (point) 'mpc-file-pos))
2695 (pl (if (stringp mpc-songs-playlist)
2696 (mpc-cmd-find 'Playlist mpc-songs-playlist)
2697 (mpc-proc-cmd-to-alist "playlist"))))
2698 ;; MPD's protocol does not let us add songs at a particular
2699 ;; position in a playlist, so we first have to add them to the
2700 ;; end, and then move them to their final destination.
2701 (mpc-cmd-add (mapcar 'car songs) mpc-songs-playlist)
2702 (mpc-cmd-move (let ((poss '()))
2703 (dotimes (i (length songs))
2704 (push (+ i (length pl)) poss))
2705 (nreverse poss))
2706 dest-pos mpc-songs-playlist)
2707 (message "Added %d songs" (length songs)))))
2708 (mpc-songs-refresh))
2710 (error "Unsupported drag'n'drop gesture"))))))
2712 ;;; Toplevel ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2714 (defcustom mpc-frame-alist '((name . "MPC") (tool-bar-lines . 1)
2715 (font . "Sans"))
2716 "Alist of frame parameters for the MPC frame."
2717 :type 'alist)
2719 ;;;###autoload
2720 (defun mpc ()
2721 "Main entry point for MPC."
2722 (interactive
2723 (progn
2724 (if current-prefix-arg
2725 ;; FIXME: We should provide some completion here, especially for the
2726 ;; case where the user specifies a local socket/file name.
2727 (setq mpc-host (read-string "MPD host and port: " nil nil mpc-host)))
2728 nil))
2729 (let* ((song-buf (mpc-songs-buf))
2730 (song-win (get-buffer-window song-buf 0)))
2731 (if song-win
2732 (select-window song-win)
2733 (if (or (window-dedicated-p) (window-minibuffer-p))
2734 (ignore-errors (select-frame (make-frame mpc-frame-alist)))
2735 (with-current-buffer song-buf
2736 (setq-local mpc-previous-window-config
2737 (current-window-configuration))))
2738 (let* ((win1 (selected-window))
2739 (win2 (split-window))
2740 (tags mpc-browser-tags))
2741 (unless tags (error "Need at least one entry in `mpc-browser-tags'"))
2742 (set-window-buffer win2 song-buf)
2743 (set-window-dedicated-p win2 'soft)
2744 (mpc-status-buffer-show)
2745 (while
2746 (progn
2747 (set-window-buffer win1 (mpc-tagbrowser-buf (pop tags)))
2748 (set-window-dedicated-p win1 'soft)
2749 tags)
2750 (setq win1 (split-window win1 nil 'horiz)))))
2751 (balance-windows-area))
2752 (mpc-songs-refresh)
2753 (mpc-status-refresh))
2755 (provide 'mpc)
2757 ;;; mpc.el ends here