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