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