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