Merge from trunk.
[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-restore (constraints)
1353 (let ((search (assq 'Search constraints)))
1354 (setq mpc--song-search (cadr search))
1355 (when search (setq constraints (delq search constraints))))
1356 (dolist (buf (process-get (mpc-proc) 'buffers))
1357 (setq buf (cdr buf))
1358 (when (buffer-live-p buf)
1359 (let* ((tag (buffer-local-value 'mpc-tag buf))
1360 (constraint (assq tag constraints)))
1361 (when tag
1362 (with-current-buffer buf
1363 (mpc-select-restore (cdr constraint)))))))
1364 (mpc-selection-refresh))
1365
1366 ;; I don't get the ring.el code. I think it doesn't do what I need, but
1367 ;; then I don't understand when what it does would be useful.
1368 (defun mpc-ring-make (size) (cons 0 (cons 0 (make-vector size nil))))
1369 (defun mpc-ring-push (ring val)
1370 (aset (cddr ring) (car ring) val)
1371 (setcar (cdr ring) (max (cadr ring) (1+ (car ring))))
1372 (setcar ring (mod (1+ (car ring)) (length (cddr ring)))))
1373 (defun mpc-ring-pop (ring)
1374 (setcar ring (mod (1- (car ring)) (cadr ring)))
1375 (aref (cddr ring) (car ring)))
1376
1377 (defvar mpc-constraints-ring (mpc-ring-make 10))
1378
1379 (defun mpc-constraints-push (&optional noerror)
1380 "Push the current selection on the ring for later."
1381 (interactive)
1382 (let ((constraints (mpc-constraints-get-current)))
1383 (if (null constraints)
1384 (unless noerror (error "No selection to push"))
1385 (mpc-ring-push mpc-constraints-ring constraints))))
1386
1387 (defun mpc-constraints-pop ()
1388 "Recall the most recently pushed selection."
1389 (interactive)
1390 (let ((constraints (mpc-ring-pop mpc-constraints-ring)))
1391 (if (null constraints)
1392 (error "No selection to return to")
1393 (mpc-constraints-restore constraints))))
1394
1395 ;;; The TagBrowser mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1396
1397 (defconst mpc-tagbrowser-all-name (propertize "*ALL*" 'face 'italic))
1398 (defvar mpc-tagbrowser-all-ol nil)
1399 (make-variable-buffer-local 'mpc-tagbrowser-all-ol)
1400 (defvar mpc-tag-name nil) (make-variable-buffer-local 'mpc-tag-name)
1401 (defun mpc-tagbrowser-all-p ()
1402 (and (eq (point-min) (line-beginning-position))
1403 (equal mpc-tagbrowser-all-name
1404 (buffer-substring (point-min) (line-end-position)))))
1405
1406 (define-derived-mode mpc-tagbrowser-mode mpc-mode '("MPC-" mpc-tag-name)
1407 (set (make-local-variable 'mode-line-process) '("" mpc-tag-name))
1408 (set (make-local-variable 'mode-line-format) nil)
1409 (set (make-local-variable 'header-line-format) '("" mpc-tag-name ;; "s"
1410 ))
1411 (set (make-local-variable 'buffer-undo-list) t)
1412 )
1413
1414 (defun mpc-tagbrowser-refresh ()
1415 (mpc-select-save
1416 (widen)
1417 (goto-char (point-min))
1418 (assert (looking-at (regexp-quote mpc-tagbrowser-all-name)))
1419 (forward-line 1)
1420 (let ((inhibit-read-only t))
1421 (delete-region (point) (point-max))
1422 (dolist (val (mpc-cmd-list mpc-tag)) (insert val "\n")))
1423 (set-buffer-modified-p nil))
1424 (mpc-reorder))
1425
1426 (defun mpc-updated-db ()
1427 ;; FIXME: This is not asynchronous, but is run from a process filter.
1428 (unless (assq 'updating_db mpc-status)
1429 (clrhash mpc--find-memoize)
1430 (dolist (buf (process-get (mpc-proc) 'buffers))
1431 (setq buf (cdr buf))
1432 (when (buffer-local-value 'mpc-tag buf)
1433 (with-current-buffer buf (with-local-quit (mpc-tagbrowser-refresh)))))
1434 (with-local-quit (mpc-songs-refresh))))
1435
1436 (defun mpc-tagbrowser-tag-name (tag)
1437 (cond
1438 ((string-match "|" (symbol-name tag))
1439 (let ((tag1 (intern (substring (symbol-name tag)
1440 0 (match-beginning 0))))
1441 (tag2 (intern (substring (symbol-name tag)
1442 (match-end 0)))))
1443 (concat (mpc-tagbrowser-tag-name tag1)
1444 " | "
1445 (mpc-tagbrowser-tag-name tag2))))
1446 ((string-match "y\\'" (symbol-name tag))
1447 (concat (substring (symbol-name tag) 0 -1) "ies"))
1448 (t (concat (symbol-name tag) "s"))))
1449
1450 (defun mpc-tagbrowser-buf (tag)
1451 (let ((buf (mpc-proc-buffer (mpc-proc) tag)))
1452 (if (buffer-live-p buf) buf
1453 (setq buf (get-buffer-create (format "*MPC %ss*" tag)))
1454 (mpc-proc-buffer (mpc-proc) tag buf)
1455 (with-current-buffer buf
1456 (let ((inhibit-read-only t))
1457 (erase-buffer)
1458 (if (member tag '(Directory))
1459 (mpc-tagbrowser-dir-mode)
1460 (mpc-tagbrowser-mode))
1461 (insert mpc-tagbrowser-all-name "\n"))
1462 (forward-line -1)
1463 (setq mpc-tag tag)
1464 (setq mpc-tag-name (mpc-tagbrowser-tag-name tag))
1465 (mpc-tagbrowser-all-select)
1466 (mpc-tagbrowser-refresh)
1467 buf))))
1468
1469 (defvar tag-browser-tagtypes
1470 (lazy-completion-table tag-browser-tagtypes
1471 (lambda ()
1472 (append '("Playlist" "Directory")
1473 (mpc-cmd-tagtypes)))))
1474
1475 (defun mpc-tagbrowser (tag)
1476 "Create a new browser for TAG."
1477 (interactive
1478 (list
1479 (let ((completion-ignore-case t))
1480 (intern
1481 (completing-read "Tag: " tag-browser-tagtypes nil 'require-match)))))
1482 (let* ((newbuf (mpc-tagbrowser-buf tag))
1483 (win (get-buffer-window newbuf 0)))
1484 (if win (select-window win)
1485 (if (with-current-buffer (window-buffer (selected-window))
1486 (derived-mode-p 'mpc-tagbrowser-mode))
1487 (setq win (selected-window))
1488 ;; Find a tagbrowser-mode buffer.
1489 (let ((buffers (process-get (mpc-proc) 'buffers))
1490 buffer)
1491 (while
1492 (and buffers
1493 (not (and (buffer-live-p (setq buffer (cdr (pop buffers))))
1494 (with-current-buffer buffer
1495 (derived-mode-p 'mpc-tagbrowser-mode))
1496 (setq win (get-buffer-window buffer 0))))))))
1497 (if (not win)
1498 (pop-to-buffer newbuf)
1499 (setq win (split-window win nil 'horiz))
1500 (set-window-buffer win newbuf)
1501 (set-window-dedicated-p win 'soft)
1502 (select-window win)
1503 (balance-windows-area)))))
1504
1505 (defun mpc-tagbrowser-all-select ()
1506 "Select the special *ALL* entry if no other is selected."
1507 (if mpc-select
1508 (delete-overlay mpc-tagbrowser-all-ol)
1509 (save-excursion
1510 (goto-char (point-min))
1511 (if mpc-tagbrowser-all-ol
1512 (move-overlay mpc-tagbrowser-all-ol
1513 (point) (line-beginning-position 2))
1514 (let ((ol (make-overlay (point) (line-beginning-position 2))))
1515 (overlay-put ol 'face 'region)
1516 (overlay-put ol 'evaporate t)
1517 (set (make-local-variable 'mpc-tagbrowser-all-ol) ol))))))
1518
1519 ;; (defvar mpc-constraints nil)
1520 (defun mpc-separator (active)
1521 ;; Place a separator mark.
1522 (unless mpc-separator-ol
1523 (set (make-local-variable 'mpc-separator-ol)
1524 (make-overlay (point) (point)))
1525 (overlay-put mpc-separator-ol 'after-string
1526 (propertize "\n"
1527 'face '(:height 0.05 :inverse-video t))))
1528 (goto-char (point-min))
1529 (forward-line 1)
1530 (while
1531 (and (member (buffer-substring-no-properties
1532 (line-beginning-position) (line-end-position))
1533 active)
1534 (zerop (forward-line 1))))
1535 (if (or (eobp) (null active))
1536 (delete-overlay mpc-separator-ol)
1537 (move-overlay mpc-separator-ol (1- (point)) (point))))
1538
1539 (defun mpc-sort (active)
1540 ;; Sort the active elements at the front.
1541 (let ((inhibit-read-only t))
1542 (goto-char (point-min))
1543 (if (mpc-tagbrowser-all-p) (forward-line 1))
1544 (condition-case nil
1545 (sort-subr nil 'forward-line 'end-of-line
1546 nil nil
1547 (lambda (s1 s2)
1548 (setq s1 (buffer-substring-no-properties
1549 (car s1) (cdr s1)))
1550 (setq s2 (buffer-substring-no-properties
1551 (car s2) (cdr s2)))
1552 (cond
1553 ((member s1 active)
1554 (if (member s2 active)
1555 (let ((cmp (mpc-compare-strings s1 s2 t)))
1556 (and (numberp cmp) (< cmp 0)))
1557 t))
1558 ((member s2 active) nil)
1559 (t (let ((cmp (mpc-compare-strings s1 s2 t)))
1560 (and (numberp cmp) (< cmp 0)))))))
1561 ;; The comparison predicate arg is new in Emacs-22.
1562 (wrong-number-of-arguments
1563 (sort-subr nil 'forward-line 'end-of-line
1564 (lambda ()
1565 (let ((name (buffer-substring-no-properties
1566 (point) (line-end-position))))
1567 (cond
1568 ((member name active) (concat "1" name))
1569 (t (concat "2" "name"))))))))))
1570
1571 (defvar mpc--changed-selection)
1572
1573 (defun mpc-reorder (&optional nodeactivate)
1574 "Reorder entries based on thre currently active selections.
1575 I.e. split the current browser buffer into a first part containing the
1576 entries included in the selection, then a separator, and then the entries
1577 not included in the selection.
1578 Return non-nil if a selection was deactivated."
1579 (mpc-select-save
1580 (let ((constraints (mpc-constraints-get-current (current-buffer)))
1581 (active 'all))
1582 ;; (unless (equal constraints mpc-constraints)
1583 ;; (set (make-local-variable 'mpc-constraints) constraints)
1584 (dolist (cst constraints)
1585 (let ((vals (apply 'mpc-union
1586 (mapcar (lambda (val)
1587 (mpc-cmd-list mpc-tag (car cst) val))
1588 (cdr cst)))))
1589 (setq active
1590 (if (listp active) (mpc-intersection active vals) vals))))
1591
1592 (when (and (listp active))
1593 ;; Remove the selections if they are all in conflict with
1594 ;; other constraints.
1595 (let ((deactivate t))
1596 (dolist (sel selection)
1597 (when (member sel active) (setq deactivate nil)))
1598 (when deactivate
1599 ;; Variable declared/used by `mpc-select-save'.
1600 (when selection
1601 (setq mpc--changed-selection t))
1602 (unless nodeactivate
1603 (setq selection nil)
1604 (mapc 'delete-overlay mpc-select)
1605 (setq mpc-select nil)
1606 (mpc-tagbrowser-all-select)))))
1607
1608 ;; FIXME: This `mpc-sort' takes a lot of time. Maybe we should
1609 ;; be more clever and presume the buffer is mostly sorted already.
1610 (mpc-sort (if (listp active) active))
1611 (mpc-separator (if (listp active) active)))))
1612
1613 (defun mpc-selection-refresh ()
1614 (let ((mpc--changed-selection t))
1615 (while mpc--changed-selection
1616 (setq mpc--changed-selection nil)
1617 (dolist (buf (process-get (mpc-proc) 'buffers))
1618 (setq buf (cdr buf))
1619 (when (and (buffer-local-value 'mpc-tag buf)
1620 (not (eq buf (current-buffer))))
1621 (with-current-buffer buf (mpc-reorder)))))
1622 ;; FIXME: reorder the current buffer last and prevent deactivation,
1623 ;; since whatever selection we made here is the most recent one
1624 ;; and should hence take precedence.
1625 (when mpc-tag (mpc-reorder 'nodeactivate))
1626 ;; FIXME: comment?
1627 (if (and mpc--song-search mpc--changed-selection)
1628 (progn
1629 (setq mpc--song-search nil)
1630 (mpc-selection-refresh))
1631 (mpc-songs-refresh))))
1632
1633 ;;; Hierarchical tagbrowser ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1634 ;; Todo:
1635 ;; - Add a button on each dir to open/close it (?)
1636 ;; - add the parent dir on the previous line, greyed-out, if it's not
1637 ;; present (because we're in the non-selected part and the parent is
1638 ;; in the selected part).
1639
1640 (defvar mpc-tagbrowser-dir-mode-map
1641 (let ((map (make-sparse-keymap)))
1642 (set-keymap-parent map mpc-tagbrowser-mode-map)
1643 (define-key map [?\M-\C-m] 'mpc-tagbrowser-dir-toggle)
1644 map))
1645
1646 ;; (defvar mpc-tagbrowser-dir-keywords
1647 ;; '(mpc-tagbrowser-dir-hide-prefix))
1648
1649 (define-derived-mode mpc-tagbrowser-dir-mode mpc-tagbrowser-mode '("MPC-" mpc-tag-name)
1650 ;; (set (make-local-variable 'font-lock-defaults)
1651 ;; '(mpc-tagbrowser-dir-keywords t))
1652 )
1653
1654 ;; (defun mpc-tagbrowser-dir-hide-prefix (limit)
1655 ;; (while
1656 ;; (let ((prev (buffer-substring (line-beginning-position 0)
1657 ;; (line-end-position 0))))
1658 ;; (
1659
1660 (defun mpc-tagbrowser-dir-toggle (event)
1661 "Open or close the element at point."
1662 (interactive (list last-nonmenu-event))
1663 (mpc-event-set-point event)
1664 (let ((name (buffer-substring (line-beginning-position)
1665 (line-end-position)))
1666 (prop (intern mpc-tag)))
1667 (if (not (member name (process-get (mpc-proc) prop)))
1668 (process-put (mpc-proc) prop
1669 (cons name (process-get (mpc-proc) prop)))
1670 (let ((new (delete name (process-get (mpc-proc) prop))))
1671 (setq name (concat name "/"))
1672 (process-put (mpc-proc) prop
1673 (delq nil
1674 (mapcar (lambda (x)
1675 (if (mpc-string-prefix-p name x)
1676 nil x))
1677 new)))))
1678 (mpc-tagbrowser-refresh)))
1679
1680
1681 ;;; Playlist management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1682
1683 (defvar mpc-songs-playlist nil
1684 "Name of the currently selected playlist, if any.
1685 A value of t means the main playlist.")
1686 (make-variable-buffer-local 'mpc-songs-playlist)
1687
1688 (defun mpc-playlist-create (name)
1689 "Save current playlist under name NAME."
1690 (interactive "sPlaylist name: ")
1691 (mpc-proc-cmd (list "save" name))
1692 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1693 (when (buffer-live-p buf)
1694 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1695
1696 (defun mpc-playlist-destroy (name)
1697 "Delete playlist named NAME."
1698 (interactive
1699 (list (completing-read "Delete playlist: " (mpc-cmd-list 'Playlist)
1700 nil 'require-match)))
1701 (mpc-proc-cmd (list "rm" 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-rename (oldname newname)
1707 "Rename playlist OLDNAME to NEWNAME."
1708 (interactive
1709 (let* ((oldname (if (and (eq mpc-tag 'Playlist) (null current-prefix-arg))
1710 (buffer-substring (line-beginning-position)
1711 (line-end-position))
1712 (completing-read "Rename playlist: "
1713 (mpc-cmd-list 'Playlist)
1714 nil 'require-match)))
1715 (newname (read-string (format "Rename '%s' to: " oldname))))
1716 (if (zerop (length newname))
1717 (error "Aborted")
1718 (list oldname newname))))
1719 (mpc-proc-cmd (list "rename" oldname newname))
1720 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1721 (if (buffer-live-p buf)
1722 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1723
1724 (defun mpc-playlist ()
1725 "Show the current playlist."
1726 (interactive)
1727 (mpc-constraints-push 'noerror)
1728 (mpc-constraints-restore '()))
1729
1730 (defun mpc-playlist-add ()
1731 "Add the selection to the playlist."
1732 (interactive)
1733 (let ((songs (mapcar #'car (mpc-songs-selection))))
1734 (mpc-cmd-add songs)
1735 (message "Appended %d songs" (length songs))
1736 ;; Return the songs added. Used in `mpc-play'.
1737 songs))
1738
1739 (defun mpc-playlist-delete ()
1740 "Remove the selected songs from the playlist."
1741 (interactive)
1742 (unless mpc-songs-playlist
1743 (error "The selected songs aren't part of a playlist"))
1744 (let ((song-poss (mapcar #'cdr (mpc-songs-selection))))
1745 (mpc-cmd-delete song-poss mpc-songs-playlist)
1746 (mpc-songs-refresh)
1747 (message "Deleted %d songs" (length song-poss))))
1748
1749 ;;; Volume management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1750
1751 (defvar mpc-volume-map
1752 (let ((map (make-sparse-keymap)))
1753 (define-key map [down-mouse-1] 'mpc-volume-mouse-set)
1754 (define-key map [mouse-1] 'ignore)
1755 (define-key map [header-line down-mouse-1] 'mpc-volume-mouse-set)
1756 (define-key map [header-line mouse-1] 'ignore)
1757 (define-key map [mode-line down-mouse-1] 'mpc-volume-mouse-set)
1758 (define-key map [mode-line mouse-1] 'ignore)
1759 map))
1760
1761 (defvar mpc-volume nil) (put 'mpc-volume 'risky-local-variable t)
1762
1763 (defun mpc-volume-refresh ()
1764 ;; Maintain the volume.
1765 (setq mpc-volume
1766 (mpc-volume-widget
1767 (string-to-number (cdr (assq 'volume mpc-status))))))
1768
1769 (defvar mpc-volume-step 5)
1770
1771 (defun mpc-volume-mouse-set (&optional event)
1772 "Change volume setting."
1773 (interactive (list last-nonmenu-event))
1774 (let* ((posn (event-start event))
1775 (diff
1776 (if (memq (if (stringp (car-safe (posn-object posn)))
1777 (aref (car (posn-object posn)) (cdr (posn-object posn)))
1778 (with-current-buffer (window-buffer (posn-window posn))
1779 (char-after (posn-point posn))))
1780 '(?◁ ?<))
1781 (- mpc-volume-step) mpc-volume-step))
1782 (newvol (+ (string-to-number (cdr (assq 'volume mpc-status))) diff)))
1783 (mpc-proc-cmd (list "setvol" newvol) 'mpc-status-refresh)
1784 (message "Set MPD volume to %s%%" newvol)))
1785
1786 (defun mpc-volume-widget (vol &optional size)
1787 (unless size (setq size 12.5))
1788 (let ((scaledvol (* (/ vol 100.0) size)))
1789 ;; (message "Volume sizes: %s - %s" (/ vol fact) (/ (- 100 vol) fact))
1790 (list (propertize "<" ;; "◁"
1791 ;; 'face 'default
1792 'keymap mpc-volume-map
1793 'face '(:box (:line-width -2 :style pressed-button))
1794 'mouse-face '(:box (:line-width -2 :style released-button)))
1795 " "
1796 (propertize "a"
1797 'display (list 'space :width scaledvol)
1798 'face '(:inverse-video t
1799 :box (:line-width -2 :style released-button)))
1800 (propertize "a"
1801 'display (list 'space :width (- size scaledvol))
1802 'face '(:box (:line-width -2 :style released-button)))
1803 " "
1804 (propertize ">" ;; "▷"
1805 ;; 'face 'default
1806 'keymap mpc-volume-map
1807 'face '(:box (:line-width -2 :style pressed-button))
1808 'mouse-face '(:box (:line-width -2 :style released-button))))))
1809
1810 ;;; MPC songs mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1811
1812 (defvar mpc-current-song nil) (put 'mpc-current-song 'risky-local-variable t)
1813 (defvar mpc-current-updating nil) (put 'mpc-current-updating 'risky-local-variable t)
1814 (defvar mpc-songs-format-description nil) (put 'mpc-songs-format-description 'risky-local-variable t)
1815
1816 (defvar mpc-previous-window-config nil)
1817
1818 (defvar mpc-songs-mode-map
1819 (let ((map (make-sparse-keymap)))
1820 (set-keymap-parent map mpc-mode-map)
1821 (define-key map [remap mpc-select] 'mpc-songs-jump-to)
1822 map))
1823
1824 (defvar mpc-songpointer-set-visible nil)
1825
1826 (defvar mpc-songs-hashcons (make-hash-table :test 'equal :weakness t)
1827 "Make song file name objects unique via hash consing.
1828 This is used so that they can be compared with `eq', which is needed for
1829 `text-property-any'.")
1830 (defun mpc-songs-hashcons (name)
1831 (or (gethash name mpc-songs-hashcons) (puthash name name mpc-songs-hashcons)))
1832 (defcustom mpc-songs-format "%2{Disc--}%3{Track} %-5{Time} %25{Title} %20{Album} %20{Artist} %10{Date}"
1833 "Format used to display each song in the list of songs."
1834 :type 'string)
1835
1836 (defvar mpc-songs-totaltime)
1837
1838 (defun mpc-songs-refresh ()
1839 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
1840 (when (buffer-live-p buf)
1841 (with-current-buffer buf
1842 (let ((constraints (mpc-constraints-get-current (current-buffer)))
1843 (dontsort nil)
1844 (inhibit-read-only t)
1845 (totaltime 0)
1846 (curline (cons (count-lines (point-min)
1847 (line-beginning-position))
1848 (buffer-substring (line-beginning-position)
1849 (line-end-position))))
1850 active)
1851 (setq mpc-songs-playlist nil)
1852 (if (null constraints)
1853 ;; When there are no constraints, rather than show the list of
1854 ;; all songs (which could take a while to download and
1855 ;; format), we show the current playlist.
1856 ;; FIXME: it would be good to be able to show the complete
1857 ;; list, but that would probably require us to format it
1858 ;; on-the-fly to make it bearable.
1859 (setq dontsort t
1860 mpc-songs-playlist t
1861 active (mpc-proc-buf-to-alists
1862 (mpc-proc-cmd "playlistinfo")))
1863 (dolist (cst constraints)
1864 (if (and (eq (car cst) 'Playlist)
1865 (= 1 (length (cdr cst))))
1866 (setq mpc-songs-playlist (cadr cst)))
1867 ;; We don't do anything really special here for playlists,
1868 ;; because it's unclear what's a correct "union" of playlists.
1869 (let ((vals (apply 'mpc-union
1870 (mapcar (lambda (val)
1871 (mpc-cmd-find (car cst) val))
1872 (cdr cst)))))
1873 (setq active (cond
1874 ((null active)
1875 (if (eq (car cst) 'Playlist)
1876 (setq dontsort t))
1877 vals)
1878 ((or dontsort
1879 ;; Try to preserve ordering and
1880 ;; repetitions from playlists.
1881 (not (eq (car cst) 'Playlist)))
1882 (mpc-intersection active vals
1883 (lambda (x) (assq 'file x))))
1884 (t
1885 (setq dontsort t)
1886 (mpc-intersection vals active
1887 (lambda (x)
1888 (assq 'file x)))))))))
1889 (mpc-select-save
1890 (erase-buffer)
1891 ;; Sorting songs is surprisingly difficult: when comparing two
1892 ;; songs with the same album name but different artist name, you
1893 ;; have to know whether these are two different albums (with the
1894 ;; same name) or a single album (typically a compilation).
1895 ;; I punt on it and just use file-name sorting, which does the
1896 ;; right thing if your library is properly arranged.
1897 (dolist (song (if dontsort active
1898 (sort active
1899 (lambda (song1 song2)
1900 (let ((cmp (mpc-compare-strings
1901 (cdr (assq 'file song1))
1902 (cdr (assq 'file song2)))))
1903 (and (integerp cmp) (< cmp 0)))))))
1904 (incf totaltime (string-to-number (or (cdr (assq 'Time song)) "0")))
1905 (mpc-format mpc-songs-format song)
1906 (delete-char (- (skip-chars-backward " "))) ;Remove trailing space.
1907 (insert "\n")
1908 (put-text-property
1909 (line-beginning-position 0) (line-beginning-position)
1910 'mpc-file (mpc-songs-hashcons (cdr (assq 'file song))))
1911 (let ((pos (assq 'Pos song)))
1912 (if pos
1913 (put-text-property
1914 (line-beginning-position 0) (line-beginning-position)
1915 'mpc-file-pos (string-to-number (cdr pos)))))
1916 ))
1917 (goto-char (point-min))
1918 (forward-line (car curline))
1919 (if (or (search-forward (cdr curline) nil t)
1920 (search-backward (cdr curline) nil t))
1921 (beginning-of-line)
1922 (goto-char (point-min)))
1923 (set (make-local-variable 'mpc-songs-totaltime)
1924 (unless (zerop totaltime)
1925 (list " " (mpc-secs-to-time totaltime))))
1926 ))))
1927 (let ((mpc-songpointer-set-visible t))
1928 (mpc-songpointer-refresh)))
1929
1930 (defun mpc-songs-search (string)
1931 "Filter songs to those who include STRING in their metadata."
1932 (interactive "sSearch for: ")
1933 (setq mpc--song-search
1934 (if (zerop (length string)) nil string))
1935 (let ((mpc--changed-selection t))
1936 (while mpc--changed-selection
1937 (setq mpc--changed-selection nil)
1938 (dolist (buf (process-get (mpc-proc) 'buffers))
1939 (setq buf (cdr buf))
1940 (when (buffer-local-value 'mpc-tag buf)
1941 (with-current-buffer buf (mpc-reorder))))
1942 (mpc-songs-refresh))))
1943
1944 (defun mpc-songs-kill-search ()
1945 "Turn off the current search restriction."
1946 (interactive)
1947 (mpc-songs-search nil))
1948
1949 (defun mpc-songs-selection ()
1950 "Return the list of songs currently selected."
1951 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
1952 (when (buffer-live-p buf)
1953 (with-current-buffer buf
1954 (save-excursion
1955 (let ((files ()))
1956 (if mpc-select
1957 (dolist (ol mpc-select)
1958 (push (cons
1959 (get-text-property (overlay-start ol) 'mpc-file)
1960 (get-text-property (overlay-start ol) 'mpc-file-pos))
1961 files))
1962 (goto-char (point-min))
1963 (while (not (eobp))
1964 (push (cons
1965 (get-text-property (point) 'mpc-file)
1966 (get-text-property (point) 'mpc-file-pos))
1967 files)
1968 (forward-line 1)))
1969 (nreverse files)))))))
1970
1971 (defun mpc-songs-jump-to (song-file &optional posn)
1972 "Jump to song SONG-FILE; interactively, this is the song at point."
1973 (interactive
1974 (let* ((event last-nonmenu-event)
1975 (posn (event-end event)))
1976 (with-selected-window (posn-window posn)
1977 (goto-char (posn-point posn))
1978 (list (get-text-property (point) 'mpc-file)
1979 posn))))
1980 (let* ((plbuf (mpc-proc-cmd "playlist"))
1981 (re (concat "^\\([0-9]+\\):" (regexp-quote song-file) "$"))
1982 (sn (with-current-buffer plbuf
1983 (goto-char (point-min))
1984 (when (re-search-forward re nil t)
1985 (match-string 1)))))
1986 (cond
1987 ((null sn) (error "This song is not in the playlist"))
1988 ((null (with-current-buffer plbuf (re-search-forward re nil t)))
1989 ;; song-file only appears once in the playlist: no ambiguity,
1990 ;; we're good to go!
1991 (mpc-proc-cmd (list "play" sn)))
1992 (t
1993 ;; The song appears multiple times in the playlist. If the current
1994 ;; buffer holds not only the destination song but also the current
1995 ;; song, then we will move in the playlist to the same relative
1996 ;; position as in the buffer. Otherwise, we will simply choose the
1997 ;; song occurrence closest to the current song.
1998 (with-selected-window (posn-window posn)
1999 (let* ((cur (and (markerp overlay-arrow-position)
2000 (marker-position overlay-arrow-position)))
2001 (dest (save-excursion
2002 (goto-char (posn-point posn))
2003 (line-beginning-position)))
2004 (lines (when cur (* (if (< cur dest) 1 -1)
2005 (count-lines cur dest)))))
2006 (with-current-buffer plbuf
2007 (goto-char (point-min))
2008 ;; Start the search from the current song.
2009 (forward-line (string-to-number
2010 (or (cdr (assq 'song mpc-status)) "0")))
2011 ;; If the current song is also displayed in the buffer,
2012 ;; then try to move to the same relative position.
2013 (if lines (forward-line lines))
2014 ;; Now search the closest occurrence.
2015 (let* ((next (save-excursion
2016 (when (re-search-forward re nil t)
2017 (cons (point) (match-string 1)))))
2018 (prev (save-excursion
2019 (when (re-search-backward re nil t)
2020 (cons (point) (match-string 1)))))
2021 (sn (cdr (if (and next prev)
2022 (if (< (- (car next) (point))
2023 (- (point) (car prev)))
2024 next prev)
2025 (or next prev)))))
2026 (assert sn)
2027 (mpc-proc-cmd (concat "play " sn))))))))))
2028
2029 (define-derived-mode mpc-songs-mode mpc-mode "MPC-song"
2030 (setq mpc-songs-format-description
2031 (with-temp-buffer (mpc-format mpc-songs-format 'self) (buffer-string)))
2032 (set (make-local-variable 'header-line-format)
2033 ;; '("MPC " mpc-volume " " mpc-current-song)
2034 (list (propertize " " 'display '(space :align-to 0))
2035 ;; 'mpc-songs-format-description
2036 '(:eval
2037 (let ((hscroll (window-hscroll)))
2038 (with-temp-buffer
2039 (mpc-format mpc-songs-format 'self hscroll)
2040 ;; That would be simpler than the hscroll handling in
2041 ;; mpc-format, but currently move-to-column does not
2042 ;; recognize :space display properties.
2043 ;; (move-to-column hscroll)
2044 ;; (delete-region (point-min) (point))
2045 (buffer-string))))))
2046 (set (make-local-variable 'mode-line-format)
2047 '("%e" mode-line-frame-identification mode-line-buffer-identification
2048 #(" " 0 3
2049 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2050 mode-line-position
2051 #(" " 0 2
2052 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2053 mpc-songs-totaltime
2054 mpc-current-updating
2055 #(" " 0 2
2056 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2057 (mpc--song-search
2058 (:propertize
2059 ("Search=\"" mpc--song-search "\"")
2060 help-echo "mouse-2: kill this search"
2061 follow-link t
2062 mouse-face mode-line-highlight
2063 keymap (keymap (mode-line keymap
2064 (mouse-2 . mpc-songs-kill-search))))
2065 (:propertize "NoSearch"
2066 help-echo "mouse-2: set a search restriction"
2067 follow-link t
2068 mouse-face mode-line-highlight
2069 keymap (keymap (mode-line keymap (mouse-2 . mpc-songs-search)))))))
2070
2071 ;; (set (make-local-variable 'mode-line-process)
2072 ;; '("" ;; mpc-volume " "
2073 ;; mpc-songs-totaltime
2074 ;; mpc-current-updating))
2075 )
2076
2077 (defun mpc-songpointer-set (pos)
2078 (let* ((win (get-buffer-window (current-buffer) t))
2079 (visible (when win
2080 (or mpc-songpointer-set-visible
2081 (and (markerp overlay-arrow-position)
2082 (eq (marker-buffer overlay-arrow-position)
2083 (current-buffer))
2084 (<= (window-start win) overlay-arrow-position)
2085 (< overlay-arrow-position (window-end win)))))))
2086 (unless (local-variable-p 'overlay-arrow-position)
2087 (set (make-local-variable 'overlay-arrow-position) (make-marker)))
2088 (move-marker overlay-arrow-position pos)
2089 ;; If the arrow was visible, try to keep it that way.
2090 (if (and visible pos
2091 (or (> (window-start win) pos) (>= pos (window-end win t))))
2092 (set-window-point win pos))))
2093
2094 (defun mpc-songpointer-refresh ()
2095 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2096 (when (buffer-live-p buf)
2097 (with-current-buffer buf
2098 (let* ((pos (text-property-any
2099 (point-min) (point-max)
2100 'mpc-file (mpc-songs-hashcons
2101 (cdr (assq 'file mpc-status)))))
2102 (other (when pos
2103 (save-excursion
2104 (goto-char pos)
2105 (text-property-any
2106 (line-beginning-position 2) (point-max)
2107 'mpc-file (mpc-songs-hashcons
2108 (cdr (assq 'file mpc-status))))))))
2109 (if other
2110 ;; The song appears multiple times in the buffer.
2111 ;; We need to be careful to choose the right occurrence.
2112 (mpc-proc-cmd "playlist" 'mpc-songpointer-refresh-hairy)
2113 (mpc-songpointer-set pos)))))))
2114
2115 (defun mpc-songpointer-context (size plbuf)
2116 (with-current-buffer plbuf
2117 (goto-char (point-min))
2118 (forward-line (string-to-number (or (cdr (assq 'song mpc-status)) "0")))
2119 (let ((context-before '())
2120 (context-after '()))
2121 (save-excursion
2122 (dotimes (_i size)
2123 (when (re-search-backward "^[0-9]+:\\(.*\\)" nil t)
2124 (push (mpc-songs-hashcons (match-string 1)) context-before))))
2125 ;; Skip the actual current song.
2126 (forward-line 1)
2127 (dotimes (_i size)
2128 (when (re-search-forward "^[0-9]+:\\(.*\\)" nil t)
2129 (push (mpc-songs-hashcons (match-string 1)) context-after)))
2130 ;; If there isn't `size' context, then return nil.
2131 (unless (and (< (length context-before) size)
2132 (< (length context-after) size))
2133 (cons (nreverse context-before) (nreverse context-after))))))
2134
2135 (defun mpc-songpointer-score (context pos)
2136 (let ((count 0))
2137 (goto-char pos)
2138 (dolist (song (car context))
2139 (and (zerop (forward-line -1))
2140 (eq (get-text-property (point) 'mpc-file) song)
2141 (incf count)))
2142 (goto-char pos)
2143 (dolist (song (cdr context))
2144 (and (zerop (forward-line 1))
2145 (eq (get-text-property (point) 'mpc-file) song)
2146 (incf count)))
2147 count))
2148
2149 (defun mpc-songpointer-refresh-hairy ()
2150 ;; Based on the complete playlist, we should figure out where in the
2151 ;; song buffer is the currently playing song.
2152 (let ((plbuf (current-buffer))
2153 (buf (mpc-proc-buffer (mpc-proc) 'songs)))
2154 (when (buffer-live-p buf)
2155 (with-current-buffer buf
2156 (let* ((context-size 0)
2157 (context '(() . ()))
2158 (pos (text-property-any
2159 (point-min) (point-max)
2160 'mpc-file (mpc-songs-hashcons
2161 (cdr (assq 'file mpc-status)))))
2162 (score 0)
2163 (other pos))
2164 (while
2165 (setq other
2166 (save-excursion
2167 (goto-char other)
2168 (text-property-any
2169 (line-beginning-position 2) (point-max)
2170 'mpc-file (mpc-songs-hashcons
2171 (cdr (assq 'file mpc-status))))))
2172 ;; There is an `other' contestant.
2173 (let ((other-score (mpc-songpointer-score context other)))
2174 (cond
2175 ;; `other' is worse: try the next one.
2176 ((< other-score score) nil)
2177 ;; `other' is better: remember it and then search further.
2178 ((> other-score score)
2179 (setq pos other)
2180 (setq score other-score))
2181 ;; Both are equal and increasing the context size won't help.
2182 ;; Arbitrarily choose one of the two and keep looking
2183 ;; for a better match.
2184 ((< score context-size) nil)
2185 (t
2186 ;; Score is equal and increasing context might help: try it.
2187 (incf context-size)
2188 (let ((new-context
2189 (mpc-songpointer-context context-size plbuf)))
2190 (if (null new-context)
2191 ;; There isn't more context: choose one arbitrarily
2192 ;; and keep looking for a better match elsewhere.
2193 (decf context-size)
2194 (setq context new-context)
2195 (setq score (mpc-songpointer-score context pos))
2196 (save-excursion
2197 (goto-char other)
2198 ;; Go back one line so we find `other' again.
2199 (setq other (line-beginning-position 0)))))))))
2200 (mpc-songpointer-set pos))))))
2201
2202 (defun mpc-current-refresh ()
2203 ;; Maintain the current data.
2204 (mpc-status-buffer-refresh)
2205 (setq mpc-current-updating
2206 (if (assq 'updating_db mpc-status) " Updating-DB"))
2207 (ignore-errors
2208 (setq mpc-current-song
2209 (when (assq 'file mpc-status)
2210 (concat " "
2211 (mpc-secs-to-time (cdr (assq 'time mpc-status)))
2212 " "
2213 (cdr (assq 'Title mpc-status))
2214 " ("
2215 (cdr (assq 'Artist mpc-status))
2216 " / "
2217 (cdr (assq 'Album mpc-status))
2218 ")"))))
2219 (force-mode-line-update t))
2220
2221 (defun mpc-songs-buf ()
2222 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2223 (if (buffer-live-p buf) buf
2224 (with-current-buffer (setq buf (get-buffer-create "*MPC-Songs*"))
2225 (mpc-proc-buffer (mpc-proc) 'songs buf)
2226 (mpc-songs-mode)
2227 buf))))
2228
2229 (defun mpc-update ()
2230 "Tell MPD to refresh its database."
2231 (interactive)
2232 (mpc-cmd-update))
2233
2234 (defun mpc-quit ()
2235 "Quit Music Player Daemon."
2236 (interactive)
2237 (let* ((proc mpc-proc)
2238 (bufs (mapcar 'cdr (if proc (process-get proc 'buffers))))
2239 (wins (mapcar (lambda (buf) (get-buffer-window buf 0)) bufs))
2240 (song-buf (mpc-songs-buf))
2241 frames)
2242 ;; Collect all the frames where MPC buffers appear.
2243 (dolist (win wins)
2244 (when (and win (not (memq (window-frame win) frames)))
2245 (push (window-frame win) frames)))
2246 (if (and frames song-buf
2247 (with-current-buffer song-buf mpc-previous-window-config))
2248 (progn
2249 (select-frame (car frames))
2250 (set-window-configuration
2251 (with-current-buffer song-buf mpc-previous-window-config)))
2252 ;; Now delete the ones that show nothing else than MPC buffers.
2253 (dolist (frame frames)
2254 (let ((delete t))
2255 (dolist (win (window-list frame))
2256 (unless (memq (window-buffer win) bufs) (setq delete nil)))
2257 (if delete (ignore-errors (delete-frame frame))))))
2258 ;; Then kill the buffers.
2259 (mapc 'kill-buffer bufs)
2260 (mpc-status-stop)
2261 (if proc (delete-process proc))))
2262
2263 (defun mpc-stop ()
2264 "Stop playing the current queue of songs."
2265 (interactive)
2266 (mpc-cmd-stop)
2267 (mpc-cmd-clear)
2268 (mpc-status-refresh))
2269
2270 (defun mpc-pause ()
2271 "Pause playing."
2272 (interactive)
2273 (mpc-cmd-pause "1"))
2274
2275 (defun mpc-resume ()
2276 "Resume playing."
2277 (interactive)
2278 (mpc-cmd-pause "0"))
2279
2280 (defun mpc-play ()
2281 "Start playing whatever is selected."
2282 (interactive)
2283 (if (member (cdr (assq 'state (mpc-cmd-status))) '("pause"))
2284 (mpc-resume)
2285 ;; When playing the playlist ends, the playlist isn't cleared, but the
2286 ;; user probably doesn't want to re-listen to it before getting to
2287 ;; listen to what he just selected.
2288 ;; (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2289 ;; (mpc-cmd-clear))
2290 ;; Actually, we don't use mpc-play to append to the playlist any more,
2291 ;; so we can just always empty the playlist.
2292 (mpc-cmd-clear)
2293 (if (mpc-playlist-add)
2294 (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2295 (mpc-cmd-play))
2296 (error "Don't know what to play"))))
2297
2298 (defun mpc-next ()
2299 "Jump to the next song in the queue."
2300 (interactive)
2301 (mpc-proc-cmd "next")
2302 (mpc-status-refresh))
2303
2304 (defun mpc-prev ()
2305 "Jump to the beginning of the current song, or to the previous song."
2306 (interactive)
2307 (let ((time (cdr (assq 'time mpc-status))))
2308 ;; Here we rely on the fact that string-to-number silently ignores
2309 ;; everything after a non-digit char.
2310 (cond
2311 ;; Go back to the beginning of current song.
2312 ((and time (> (string-to-number time) 0))
2313 (mpc-proc-cmd (list "seekid" (cdr (assq 'songid mpc-status)) 0)))
2314 ;; We're at the beginning of the first song of the playlist.
2315 ;; Fetch the previous one from `mpc-queue-back'.
2316 ;; ((and (zerop (string-to-number (cdr (assq 'song mpc-status))))
2317 ;; mpc-queue-back)
2318 ;; ;; Because we use cmd-list rather than cmd-play, the queue is not
2319 ;; ;; automatically updated.
2320 ;; (let ((prev (pop mpc-queue-back)))
2321 ;; (push prev mpc-queue)
2322 ;; (mpc-proc-cmd
2323 ;; (mpc-proc-cmd-list
2324 ;; (list (list "add" prev)
2325 ;; (list "move" (cdr (assq 'playlistlength mpc-status)) "0")
2326 ;; "previous")))))
2327 ;; We're at the beginning of a song, but not the first one.
2328 (t (mpc-proc-cmd "previous")))
2329 (mpc-status-refresh)))
2330
2331 (defvar mpc-last-seek-time '(0 . 0))
2332
2333 (defun mpc--faster (event speedup step)
2334 "Fast forward."
2335 (interactive (list last-nonmenu-event))
2336 (let ((repeat-delay (/ (abs (float step)) speedup)))
2337 (if (not (memq 'down (event-modifiers event)))
2338 (let* ((currenttime (float-time))
2339 (last-time (- currenttime (car mpc-last-seek-time))))
2340 (if (< last-time (* 0.9 repeat-delay))
2341 nil ;; Trottle
2342 (let* ((status (if (< last-time 1.0)
2343 mpc-status (mpc-cmd-status)))
2344 (songid (cdr (assq 'songid status)))
2345 (time (if songid
2346 (if (< last-time 1.0)
2347 (cdr mpc-last-seek-time)
2348 (string-to-number
2349 (cdr (assq 'time status)))))))
2350 (setq mpc-last-seek-time
2351 (cons currenttime (setq time (+ time step))))
2352 (mpc-proc-cmd (list "seekid" songid time)
2353 'mpc-status-refresh))))
2354 (let ((status (mpc-cmd-status)))
2355 (let* ((songid (cdr (assq 'songid status)))
2356 (time (if songid (string-to-number
2357 (cdr (assq 'time status))))))
2358 (let ((timer (run-with-timer
2359 t repeat-delay
2360 (lambda ()
2361 (mpc-proc-cmd (list "seekid" songid
2362 (setq time (+ time step)))
2363 'mpc-status-refresh)))))
2364 (while (mouse-movement-p
2365 (event-basic-type (setq event (read-event)))))
2366 (cancel-timer timer)))))))
2367
2368 (defvar mpc--faster-toggle-timer nil)
2369 (defun mpc--faster-stop ()
2370 (when mpc--faster-toggle-timer
2371 (cancel-timer mpc--faster-toggle-timer)
2372 (setq mpc--faster-toggle-timer nil)))
2373
2374 (defun mpc--faster-toggle-refresh ()
2375 (if (equal (cdr (assq 'state mpc-status)) "stop")
2376 (mpc--faster-stop)))
2377
2378 (defun mpc--songduration ()
2379 (string-to-number
2380 (let ((s (cdr (assq 'time mpc-status))))
2381 (if (not (string-match ":" s))
2382 (error "Unexpected time format %S" s)
2383 (substring s (match-end 0))))))
2384
2385 (defvar mpc--faster-toggle-forward nil)
2386 (defvar mpc--faster-acceleration 0.5)
2387 (defun mpc--faster-toggle (speedup step)
2388 (setq speedup (float speedup))
2389 (if mpc--faster-toggle-timer
2390 (mpc--faster-stop)
2391 (mpc-status-refresh) (mpc-proc-sync)
2392 (let* (songid ;The ID of the currently ffwd/rewinding song.
2393 songduration ;The duration of that song.
2394 songtime ;The time of the song last time we ran.
2395 oldtime ;The timeoftheday last time we ran.
2396 prevsongid) ;The song we're in the process leaving.
2397 (let ((fun
2398 (lambda ()
2399 (let ((newsongid (cdr (assq 'songid mpc-status))))
2400
2401 (if (and (equal prevsongid newsongid)
2402 (not (equal prevsongid songid)))
2403 ;; We left prevsongid and came back to it. Pretend it
2404 ;; didn't happen.
2405 (setq newsongid songid))
2406
2407 (cond
2408 ((null newsongid) (mpc--faster-stop))
2409 ((not (equal songid newsongid))
2410 ;; We jumped to another song: reset.
2411 (setq songid newsongid)
2412 (setq songtime (string-to-number
2413 (cdr (assq 'time mpc-status))))
2414 (setq songduration (mpc--songduration))
2415 (setq oldtime (float-time)))
2416 ((and (>= songtime songduration) mpc--faster-toggle-forward)
2417 ;; Skip to the beginning of the next song.
2418 (if (not (equal (cdr (assq 'state mpc-status)) "play"))
2419 (mpc-proc-cmd "next" 'mpc-status-refresh)
2420 ;; If we're playing, this is done automatically, so we
2421 ;; don't need to do anything, or rather we *shouldn't*
2422 ;; do anything otherwise there's a race condition where
2423 ;; we could skip straight to the next next song.
2424 nil))
2425 ((and (<= songtime 0) (not mpc--faster-toggle-forward))
2426 ;; Skip to the end of the previous song.
2427 (setq prevsongid songid)
2428 (mpc-proc-cmd "previous"
2429 (lambda ()
2430 (mpc-status-refresh
2431 (lambda ()
2432 (setq songid (cdr (assq 'songid mpc-status)))
2433 (setq songtime (setq songduration (mpc--songduration)))
2434 (setq oldtime (float-time))
2435 (mpc-proc-cmd (list "seekid" songid songtime)))))))
2436 (t
2437 (setq speedup (+ speedup mpc--faster-acceleration))
2438 (let ((newstep
2439 (truncate (* speedup (- (float-time) oldtime)))))
2440 (if (<= newstep 1) (setq newstep 1))
2441 (setq oldtime (+ oldtime (/ newstep speedup)))
2442 (if (not mpc--faster-toggle-forward)
2443 (setq newstep (- newstep)))
2444 (setq songtime (min songduration (+ songtime newstep)))
2445 (unless (>= songtime songduration)
2446 (condition-case nil
2447 (mpc-proc-cmd
2448 (list "seekid" songid songtime)
2449 'mpc-status-refresh)
2450 (mpc-proc-error (mpc-status-refresh)))))))))))
2451 (setq mpc--faster-toggle-forward (> step 0))
2452 (funcall fun) ;Initialize values.
2453 (setq mpc--faster-toggle-timer
2454 (run-with-timer t 0.3 fun))))))
2455
2456
2457
2458 (defvar mpc-faster-speedup 8)
2459
2460 (defun mpc-ffwd (_event)
2461 "Fast forward."
2462 (interactive (list last-nonmenu-event))
2463 ;; (mpc--faster event 4.0 1)
2464 (mpc--faster-toggle mpc-faster-speedup 1))
2465
2466 (defun mpc-rewind (_event)
2467 "Fast rewind."
2468 (interactive (list last-nonmenu-event))
2469 ;; (mpc--faster event 4.0 -1)
2470 (mpc--faster-toggle mpc-faster-speedup -1))
2471
2472
2473 (defun mpc-play-at-point (&optional event)
2474 (interactive (list last-nonmenu-event))
2475 (mpc-select event)
2476 (mpc-play))
2477
2478 ;; (defun mpc-play-tagval ()
2479 ;; "Play all the songs of the tag at point."
2480 ;; (interactive)
2481 ;; (let* ((val (buffer-substring (line-beginning-position) (line-end-position)))
2482 ;; (songs (mapcar 'cdar
2483 ;; (mpc-proc-buf-to-alists
2484 ;; (mpc-proc-cmd (list "find" mpc-tag val))))))
2485 ;; (mpc-cmd-add songs)
2486 ;; (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2487 ;; (mpc-cmd-play))))
2488
2489 ;;; Drag'n'drop support ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2490 ;; Todo:
2491 ;; the main thing to do here, is to provide visual feedback during the drag:
2492 ;; - change the mouse-cursor.
2493 ;; - highlight/select the source and the current destination.
2494
2495 (defun mpc-drag-n-drop (event)
2496 "DWIM for a drag EVENT."
2497 (interactive "e")
2498 (let* ((start (event-start event))
2499 (end (event-end event))
2500 (start-buf (window-buffer (posn-window start)))
2501 (end-buf (window-buffer (posn-window end)))
2502 (songs
2503 (with-current-buffer start-buf
2504 (goto-char (posn-point start))
2505 (if (get-text-property (point) 'mpc-select)
2506 ;; FIXME: actually we should only consider the constraints
2507 ;; corresponding to the selection in this particular buffer.
2508 (mpc-songs-selection)
2509 (cond
2510 ((and (derived-mode-p 'mpc-songs-mode)
2511 (get-text-property (point) 'mpc-file))
2512 (list (cons (get-text-property (point) 'mpc-file)
2513 (get-text-property (point) 'mpc-file-pos))))
2514 ((and mpc-tag (not (mpc-tagbrowser-all-p)))
2515 (mapcar (lambda (song)
2516 (list (cdr (assq 'file song))))
2517 (mpc-cmd-find
2518 mpc-tag
2519 (buffer-substring (line-beginning-position)
2520 (line-end-position)))))
2521 (t
2522 (error "Unsupported starting position for drag'n'drop gesture")))))))
2523 (with-current-buffer end-buf
2524 (goto-char (posn-point end))
2525 (cond
2526 ((eq mpc-tag 'Playlist)
2527 ;; Adding elements to a named playlist.
2528 (let ((playlist (if (or (mpc-tagbrowser-all-p)
2529 (and (bolp) (eolp)))
2530 (error "Not a playlist")
2531 (buffer-substring (line-beginning-position)
2532 (line-end-position)))))
2533 (mpc-cmd-add (mapcar 'car songs) playlist)
2534 (message "Added %d songs to %s" (length songs) playlist)
2535 (if (member playlist
2536 (cdr (assq 'Playlist (mpc-constraints-get-current))))
2537 (mpc-songs-refresh))))
2538 ((derived-mode-p 'mpc-songs-mode)
2539 (cond
2540 ((null mpc-songs-playlist)
2541 (error "The songs shown do not belong to a playlist"))
2542 ((eq start-buf end-buf)
2543 ;; Moving songs within the shown playlist.
2544 (let ((dest-pos (get-text-property (point) 'mpc-file-pos)))
2545 (mpc-cmd-move (mapcar 'cdr songs) dest-pos mpc-songs-playlist)
2546 (message "Moved %d songs" (length songs))))
2547 (t
2548 ;; Adding songs to the shown playlist.
2549 (let ((dest-pos (get-text-property (point) 'mpc-file-pos))
2550 (pl (if (stringp mpc-songs-playlist)
2551 (mpc-cmd-find 'Playlist mpc-songs-playlist)
2552 (mpc-proc-cmd-to-alist "playlist"))))
2553 ;; MPD's protocol does not let us add songs at a particular
2554 ;; position in a playlist, so we first have to add them to the
2555 ;; end, and then move them to their final destination.
2556 (mpc-cmd-add (mapcar 'car songs) mpc-songs-playlist)
2557 (mpc-cmd-move (let ((poss '()))
2558 (dotimes (i (length songs))
2559 (push (+ i (length pl)) poss))
2560 (nreverse poss)) dest-pos mpc-songs-playlist)
2561 (message "Added %d songs" (length songs)))))
2562 (mpc-songs-refresh))
2563 (t
2564 (error "Unsupported drag'n'drop gesture"))))))
2565
2566 ;;; Toplevel ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2567
2568 (defcustom mpc-frame-alist '((name . "MPC") (tool-bar-lines . 1)
2569 (font . "Sans"))
2570 "Alist of frame parameters for the MPC frame."
2571 :type 'alist)
2572
2573 ;;;###autoload
2574 (defun mpc ()
2575 "Main entry point for MPC."
2576 (interactive
2577 (progn
2578 (if current-prefix-arg
2579 (setq mpc-host (read-string "MPD host and port: " nil nil mpc-host)))
2580 nil))
2581 (let* ((song-buf (mpc-songs-buf))
2582 (song-win (get-buffer-window song-buf 0)))
2583 (if song-win
2584 (select-window song-win)
2585 (if (or (window-dedicated-p (selected-window))
2586 (window-minibuffer-p))
2587 (ignore-errors (select-frame (make-frame mpc-frame-alist)))
2588 (with-current-buffer song-buf
2589 (set (make-local-variable 'mpc-previous-window-config)
2590 (current-window-configuration))))
2591 (let* ((win1 (selected-window))
2592 (win2 (split-window))
2593 (tags mpc-browser-tags))
2594 (unless tags (error "Need at least one entry in `mpc-browser-tags'"))
2595 (set-window-buffer win2 song-buf)
2596 (set-window-dedicated-p win2 'soft)
2597 (mpc-status-buffer-show)
2598 (while
2599 (progn
2600 (set-window-buffer win1 (mpc-tagbrowser-buf (pop tags)))
2601 (set-window-dedicated-p win1 'soft)
2602 tags)
2603 (setq win1 (split-window win1 nil 'horiz)))))
2604 (balance-windows-area))
2605 (mpc-songs-refresh)
2606 (mpc-status-refresh))
2607
2608 (provide 'mpc)
2609
2610 ;;; mpc.el ends here