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