mpc.el 114 KB

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