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