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