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