MPD client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

nncmpp.c 108KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978
  1. /*
  2. * nncmpp -- the MPD client you never knew you needed
  3. *
  4. * Copyright (c) 2016 - 2018, Přemysl Janouch <p@janouch.name>
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any
  7. * purpose with or without fee is hereby granted.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  12. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  14. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  15. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. *
  17. */
  18. #include "config.h"
  19. // We "need" to have an enum for attributes before including liberty.
  20. // Avoiding colours in the defaults here in order to support dumb terminals.
  21. #define ATTRIBUTE_TABLE(XX) \
  22. XX( NORMAL, "normal", -1, -1, 0 ) \
  23. XX( HIGHLIGHT, "highlight", -1, -1, A_BOLD ) \
  24. /* Gauge */ \
  25. XX( ELAPSED, "elapsed", -1, -1, A_REVERSE ) \
  26. XX( REMAINS, "remains", -1, -1, A_UNDERLINE ) \
  27. /* Tab bar */ \
  28. XX( TAB_BAR, "tab_bar", -1, -1, A_REVERSE ) \
  29. XX( TAB_ACTIVE, "tab_active", -1, -1, A_UNDERLINE ) \
  30. /* Listview */ \
  31. XX( HEADER, "header", -1, -1, A_UNDERLINE ) \
  32. XX( EVEN, "even", -1, -1, 0 ) \
  33. XX( ODD, "odd", -1, -1, 0 ) \
  34. XX( DIRECTORY, "directory", -1, -1, 0 ) \
  35. XX( SELECTION, "selection", -1, -1, A_REVERSE ) \
  36. /* Cyan is good with both black and white.
  37. * Can't use A_REVERSE because bold'd be bright.
  38. * Unfortunately ran out of B&W attributes. */ \
  39. XX( MULTISELECT, "multiselect",-1, 6, 0 ) \
  40. XX( SCROLLBAR, "scrollbar", -1, -1, 0 ) \
  41. /* These are for debugging only */ \
  42. XX( WARNING, "warning", 3, -1, 0 ) \
  43. XX( ERROR, "error", 1, -1, 0 ) \
  44. XX( INCOMING, "incoming", 2, -1, 0 ) \
  45. XX( OUTGOING, "outgoing", 4, -1, 0 )
  46. enum
  47. {
  48. #define XX(name, config, fg_, bg_, attrs_) ATTRIBUTE_ ## name,
  49. ATTRIBUTE_TABLE (XX)
  50. #undef XX
  51. ATTRIBUTE_COUNT
  52. };
  53. // My battle-tested C framework acting as a GLib replacement. Its one big
  54. // disadvantage is missing support for i18n but that can eventually be added
  55. // as an optional feature. Localised applications look super awkward, though.
  56. // User data for logger functions to enable formatted logging
  57. #define print_fatal_data ((void *) ATTRIBUTE_ERROR)
  58. #define print_error_data ((void *) ATTRIBUTE_ERROR)
  59. #define print_warning_data ((void *) ATTRIBUTE_WARNING)
  60. #define LIBERTY_WANT_POLLER
  61. #define LIBERTY_WANT_ASYNC
  62. #define LIBERTY_WANT_PROTO_HTTP
  63. #define LIBERTY_WANT_PROTO_MPD
  64. #include "liberty/liberty.c"
  65. #include "liberty/liberty-tui.c"
  66. #define HAVE_LIBERTY
  67. #include "line-editor.c"
  68. #include <math.h>
  69. #include <locale.h>
  70. #include <termios.h>
  71. #ifndef TIOCGWINSZ
  72. #include <sys/ioctl.h>
  73. #endif // ! TIOCGWINSZ
  74. // ncurses is notoriously retarded for input handling, we need something
  75. // different if only to receive mouse events reliably.
  76. #include "termo.h"
  77. // We need cURL to extract links from Internet stream playlists. It'd be way
  78. // too much code to do this all by ourselves, and there's nothing better around.
  79. #include <curl/curl.h>
  80. #define APP_TITLE PROGRAM_NAME ///< Left top corner
  81. // --- Utilities ---------------------------------------------------------------
  82. // The standard endwin/refresh sequence makes the terminal flicker
  83. static void
  84. update_curses_terminal_size (void)
  85. {
  86. #if defined (HAVE_RESIZETERM) && defined (TIOCGWINSZ)
  87. struct winsize size;
  88. if (!ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &size))
  89. {
  90. char *row = getenv ("LINES");
  91. char *col = getenv ("COLUMNS");
  92. unsigned long tmp;
  93. resizeterm (
  94. (row && xstrtoul (&tmp, row, 10)) ? tmp : size.ws_row,
  95. (col && xstrtoul (&tmp, col, 10)) ? tmp : size.ws_col);
  96. }
  97. #else // HAVE_RESIZETERM && TIOCGWINSZ
  98. endwin ();
  99. refresh ();
  100. #endif // HAVE_RESIZETERM && TIOCGWINSZ
  101. }
  102. static int64_t
  103. clock_msec (clockid_t clock)
  104. {
  105. struct timespec tp;
  106. hard_assert (clock_gettime (clock, &tp) != -1);
  107. return (int64_t) tp.tv_sec * 1000 + (int64_t) tp.tv_nsec / 1000000;
  108. }
  109. static bool
  110. xstrtoul_map (const struct str_map *map, const char *key, unsigned long *out)
  111. {
  112. const char *field = str_map_find (map, key);
  113. return field && xstrtoul (out, field, 10);
  114. }
  115. static const char *
  116. xbasename (const char *path)
  117. {
  118. const char *last_slash = strrchr (path, '/');
  119. return last_slash ? last_slash + 1 : path;
  120. }
  121. static char *
  122. latin1_to_utf8 (const char *latin1)
  123. {
  124. struct str converted = str_make ();
  125. while (*latin1)
  126. {
  127. uint8_t c = *latin1++;
  128. if (c < 0x80)
  129. str_append_c (&converted, c);
  130. else
  131. {
  132. str_append_c (&converted, 0xC0 | (c >> 6));
  133. str_append_c (&converted, 0x80 | (c & 0x3F));
  134. }
  135. }
  136. return str_steal (&converted);
  137. }
  138. static void
  139. cstr_uncapitalize (char *s)
  140. {
  141. if (isupper (s[0]) && islower (s[1]))
  142. s[0] = tolower_ascii (s[0]);
  143. }
  144. static int
  145. print_curl_debug (CURL *easy, curl_infotype type, char *data, size_t len,
  146. void *ud)
  147. {
  148. (void) easy;
  149. (void) ud;
  150. (void) type;
  151. char copy[len + 1];
  152. for (size_t i = 0; i < len; i++)
  153. {
  154. uint8_t c = data[i];
  155. copy[i] = c >= 32 || c == '\n' ? c : '.';
  156. }
  157. copy[len] = '\0';
  158. char *next;
  159. for (char *p = copy; p; p = next)
  160. {
  161. if ((next = strchr (p, '\n')))
  162. *next++ = '\0';
  163. if (!*p)
  164. continue;
  165. if (!utf8_validate (p, strlen (p)))
  166. {
  167. char *fixed = latin1_to_utf8 (p);
  168. print_debug ("cURL: %s", fixed);
  169. free (fixed);
  170. }
  171. else
  172. print_debug ("cURL: %s", p);
  173. }
  174. return 0;
  175. }
  176. static char *
  177. mpd_parse_kv (char *line, char **value)
  178. {
  179. char *key = mpd_client_parse_kv (line, value);
  180. if (!key) print_debug ("%s: %s", "erroneous MPD output", line);
  181. return key;
  182. }
  183. // --- cURL async wrapper ------------------------------------------------------
  184. // You are meant to subclass this structure, no user_data pointers needed
  185. struct poller_curl_task;
  186. /// Receives notification for finished transfers
  187. typedef void (*poller_curl_done_fn)
  188. (CURLMsg *msg, struct poller_curl_task *task);
  189. struct poller_curl_task
  190. {
  191. CURL *easy; ///< cURL easy interface handle
  192. char curl_error[CURL_ERROR_SIZE]; ///< cURL error info buffer
  193. poller_curl_done_fn on_done; ///< Done callback
  194. };
  195. struct poller_curl_fd
  196. {
  197. LIST_HEADER (struct poller_curl_fd)
  198. struct poller_fd fd; ///< Poller FD
  199. };
  200. struct poller_curl
  201. {
  202. struct poller *poller; ///< Parent poller
  203. struct poller_timer timer; ///< cURL timer
  204. CURLM *multi; ///< cURL multi interface handle
  205. struct poller_curl_fd *fds; ///< List of all FDs
  206. };
  207. static void
  208. poller_curl_collect (struct poller_curl *self, curl_socket_t s, int ev_bitmask)
  209. {
  210. int running = 0;
  211. CURLMcode res;
  212. // XXX: ignoring errors, in particular CURLM_CALL_MULTI_PERFORM
  213. if ((res = curl_multi_socket_action (self->multi, s, ev_bitmask, &running)))
  214. print_debug ("cURL: %s", curl_multi_strerror (res));
  215. CURLMsg *msg;
  216. while ((msg = curl_multi_info_read (self->multi, &running)))
  217. if (msg->msg == CURLMSG_DONE)
  218. {
  219. struct poller_curl_task *task = NULL;
  220. hard_assert (!curl_easy_getinfo
  221. (msg->easy_handle, CURLINFO_PRIVATE, &task));
  222. task->on_done (msg, task);
  223. }
  224. }
  225. static void
  226. poller_curl_on_socket (const struct pollfd *pfd, void *user_data)
  227. {
  228. int mask = 0;
  229. if (pfd->revents & POLLIN) mask |= CURL_CSELECT_IN;
  230. if (pfd->revents & POLLOUT) mask |= CURL_CSELECT_OUT;
  231. if (pfd->revents & POLLERR) mask |= CURL_CSELECT_ERR;
  232. poller_curl_collect (user_data, pfd->fd, mask);
  233. }
  234. static int
  235. poller_curl_on_socket_action (CURL *easy, curl_socket_t s, int what,
  236. void *user_data, void *socket_data)
  237. {
  238. (void) easy;
  239. struct poller_curl *self = user_data;
  240. struct poller_curl_fd *fd;
  241. if (!(fd = socket_data))
  242. {
  243. fd = xmalloc (sizeof *fd);
  244. LIST_PREPEND (self->fds, fd);
  245. fd->fd = poller_fd_make (self->poller, s);
  246. fd->fd.dispatcher = poller_curl_on_socket;
  247. fd->fd.user_data = self;
  248. curl_multi_assign (self->multi, s, fd);
  249. }
  250. if (what == CURL_POLL_REMOVE)
  251. {
  252. poller_fd_reset (&fd->fd);
  253. LIST_UNLINK (self->fds, fd);
  254. free (fd);
  255. }
  256. else
  257. {
  258. short events = 0;
  259. if (what == CURL_POLL_IN) events = POLLIN;
  260. if (what == CURL_POLL_OUT) events = POLLOUT;
  261. if (what == CURL_POLL_INOUT) events = POLLIN | POLLOUT;
  262. poller_fd_set (&fd->fd, events);
  263. }
  264. return 0;
  265. }
  266. static void
  267. poller_curl_on_timer (void *user_data)
  268. {
  269. poller_curl_collect (user_data, CURL_SOCKET_TIMEOUT, 0);
  270. }
  271. static int
  272. poller_curl_on_timer_change (CURLM *multi, long timeout_ms, void *user_data)
  273. {
  274. (void) multi;
  275. struct poller_curl *self = user_data;
  276. if (timeout_ms < 0)
  277. poller_timer_reset (&self->timer);
  278. else
  279. poller_timer_set (&self->timer, timeout_ms);
  280. return 0;
  281. }
  282. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  283. static bool
  284. poller_curl_init (struct poller_curl *self, struct poller *poller,
  285. struct error **e)
  286. {
  287. memset (self, 0, sizeof *self);
  288. if (!(self->multi = curl_multi_init ()))
  289. return error_set (e, "cURL setup failed");
  290. CURLMcode mres;
  291. if ((mres = curl_multi_setopt (self->multi,
  292. CURLMOPT_SOCKETFUNCTION, poller_curl_on_socket_action))
  293. || (mres = curl_multi_setopt (self->multi,
  294. CURLMOPT_TIMERFUNCTION, poller_curl_on_timer_change))
  295. || (mres = curl_multi_setopt (self->multi, CURLMOPT_SOCKETDATA, self))
  296. || (mres = curl_multi_setopt (self->multi, CURLMOPT_TIMERDATA, self)))
  297. {
  298. curl_multi_cleanup (self->multi);
  299. return error_set (e, "%s: %s",
  300. "cURL setup failed", curl_multi_strerror (mres));
  301. }
  302. self->timer = poller_timer_make ((self->poller = poller));
  303. self->timer.dispatcher = poller_curl_on_timer;
  304. self->timer.user_data = self;
  305. return true;
  306. }
  307. static void
  308. poller_curl_free (struct poller_curl *self)
  309. {
  310. curl_multi_cleanup (self->multi);
  311. poller_timer_reset (&self->timer);
  312. LIST_FOR_EACH (struct poller_curl_fd, iter, self->fds)
  313. {
  314. poller_fd_reset (&iter->fd);
  315. free (iter);
  316. }
  317. }
  318. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  319. /// Initialize a task with a new easy instance that can be used with the poller
  320. static bool
  321. poller_curl_spawn (struct poller_curl_task *task, struct error **e)
  322. {
  323. CURL *easy;
  324. if (!(easy = curl_easy_init ()))
  325. return error_set (e, "cURL setup failed");
  326. // We already take care of SIGPIPE, and native DNS timeouts are only
  327. // a problem for people without the AsynchDNS feature.
  328. //
  329. // Unfortunately, cURL doesn't allow custom callbacks for DNS.
  330. // The most we could try is parse out the hostname and provide an address
  331. // override for it using CURLOPT_RESOLVE. Or be our own SOCKS4A/5 proxy.
  332. CURLcode res;
  333. if ((res = curl_easy_setopt (easy, CURLOPT_NOSIGNAL, 1L))
  334. || (res = curl_easy_setopt (easy, CURLOPT_ERRORBUFFER, task->curl_error))
  335. || (res = curl_easy_setopt (easy, CURLOPT_PRIVATE, task)))
  336. {
  337. curl_easy_cleanup (easy);
  338. return error_set (e, "%s", curl_easy_strerror (res));
  339. }
  340. task->easy = easy;
  341. return true;
  342. }
  343. static bool
  344. poller_curl_add (struct poller_curl *self, CURL *easy, struct error **e)
  345. {
  346. CURLMcode mres;
  347. // "CURLMOPT_TIMERFUNCTION [...] will be called from within this function"
  348. if ((mres = curl_multi_add_handle (self->multi, easy)))
  349. return error_set (e, "%s", curl_multi_strerror (mres));
  350. return true;
  351. }
  352. static bool
  353. poller_curl_remove (struct poller_curl *self, CURL *easy, struct error **e)
  354. {
  355. CURLMcode mres;
  356. if ((mres = curl_multi_remove_handle (self->multi, easy)))
  357. return error_set (e, "%s", curl_multi_strerror (mres));
  358. return true;
  359. }
  360. // --- Compact map -------------------------------------------------------------
  361. // MPD provides us with a hefty amount of little key-value maps. The overhead
  362. // of str_map for such constant (string -> string) maps is too high and it's
  363. // much better to serialize them (mainly cache locality and memory efficiency).
  364. //
  365. // This isn't intended to be reusable and has case insensitivity built-in.
  366. typedef uint8_t *compact_map_t; ///< Compacted (string -> string) map
  367. static compact_map_t
  368. compact_map (struct str_map *map)
  369. {
  370. struct str s = str_make ();
  371. struct str_map_iter iter = str_map_iter_make (map);
  372. char *value;
  373. static const size_t zero = 0, alignment = sizeof zero;
  374. while ((value = str_map_iter_next (&iter)))
  375. {
  376. size_t entry_len = iter.link->key_length + 1 + strlen (value) + 1;
  377. size_t padding_len = (alignment - entry_len % alignment) % alignment;
  378. entry_len += padding_len;
  379. str_append_data (&s, &entry_len, sizeof entry_len);
  380. str_append_printf (&s, "%s%c%s%c", iter.link->key, 0, value, 0);
  381. str_append_data (&s, &zero, padding_len);
  382. }
  383. str_append_data (&s, &zero, sizeof zero);
  384. return (compact_map_t) str_steal (&s);
  385. }
  386. static char *
  387. compact_map_find (compact_map_t data, const char *needle)
  388. {
  389. size_t entry_len;
  390. while ((entry_len = *(size_t *) data))
  391. {
  392. data += sizeof entry_len;
  393. if (!strcasecmp_ascii (needle, (const char *) data))
  394. return (char *) data + strlen (needle) + 1;
  395. data += entry_len;
  396. }
  397. return NULL;
  398. }
  399. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  400. struct item_list
  401. {
  402. compact_map_t *items; ///< Compacted (string -> string) maps
  403. size_t len; ///< Length
  404. size_t alloc; ///< Allocated items
  405. };
  406. static struct item_list
  407. item_list_make (void)
  408. {
  409. struct item_list self = {};
  410. self.items = xcalloc (sizeof *self.items, (self.alloc = 16));
  411. return self;
  412. }
  413. static void
  414. item_list_free (struct item_list *self)
  415. {
  416. for (size_t i = 0; i < self->len; i++)
  417. free (self->items[i]);
  418. free (self->items);
  419. }
  420. static bool
  421. item_list_set (struct item_list *self, int i, struct str_map *item)
  422. {
  423. if (i < 0 || (size_t) i >= self->len)
  424. return false;
  425. free (self->items[i]);
  426. self->items[i] = compact_map (item);
  427. return true;
  428. }
  429. static compact_map_t
  430. item_list_get (struct item_list *self, int i)
  431. {
  432. if (i < 0 || (size_t) i >= self->len || !self->items[i])
  433. return NULL;
  434. return self->items[i];
  435. }
  436. static void
  437. item_list_resize (struct item_list *self, size_t len)
  438. {
  439. // Make the allocated array big enough but not too large
  440. size_t new_alloc = self->alloc;
  441. while (new_alloc < len)
  442. new_alloc <<= 1;
  443. while ((new_alloc >> 1) >= len
  444. && (new_alloc - len) >= 1024)
  445. new_alloc >>= 1;
  446. for (size_t i = len; i < self->len; i++)
  447. free (self->items[i]);
  448. if (new_alloc != self->alloc)
  449. self->items = xreallocarray (self->items,
  450. sizeof *self->items, (self->alloc = new_alloc));
  451. for (size_t i = self->len; i < len; i++)
  452. self->items[i] = NULL;
  453. self->len = len;
  454. }
  455. // --- Application -------------------------------------------------------------
  456. // Function names are prefixed mostly because of curses which clutters the
  457. // global namespace and makes it harder to distinguish what functions relate to.
  458. // The user interface is focused on conceptual simplicity. That is important
  459. // since we're not using any TUI framework (which are mostly a lost cause to me
  460. // in the post-Unicode era and not worth pursuing), and the code would get
  461. // bloated and incomprehensible fast. We mostly rely on "row_buffer" to write
  462. // text from left to right row after row while keeping track of cells.
  463. //
  464. // There is an independent top pane displaying general status information,
  465. // followed by a tab bar and a listview served by a per-tab event handler.
  466. //
  467. // For simplicity, the listview can only work with items that are one row high.
  468. struct tab;
  469. enum action;
  470. /// Try to handle an action in the tab
  471. typedef bool (*tab_action_fn) (enum action action);
  472. /// Draw an item to the screen using the row buffer API
  473. typedef void (*tab_item_draw_fn)
  474. (size_t item_index, struct row_buffer *buffer, int width);
  475. struct tab
  476. {
  477. LIST_HEADER (struct tab)
  478. char *name; ///< Visible identifier
  479. size_t name_width; ///< Visible width of the name
  480. char *header; ///< The header, should there be any
  481. // Implementation:
  482. tab_action_fn on_action; ///< User action handler callback
  483. tab_item_draw_fn on_item_draw; ///< Item draw callback
  484. // Provided by tab owner:
  485. bool can_multiselect; ///< Multiple items can be selected
  486. size_t item_count; ///< Total item count
  487. // Managed by the common handler:
  488. int item_top; ///< Index of the topmost item
  489. int item_selected; ///< Index of the selected item
  490. int item_mark; ///< Multiselect second point index
  491. };
  492. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  493. enum player_state { PLAYER_STOPPED, PLAYER_PLAYING, PLAYER_PAUSED };
  494. // Basically a container for most of the globals; no big sense in handing
  495. // around a pointer to this, hence it is a simple global variable as well.
  496. // There is enough global state as it is.
  497. static struct app_context
  498. {
  499. // Event loop:
  500. struct poller poller; ///< Poller
  501. bool quitting; ///< Quit signal for the event loop
  502. bool polling; ///< The event loop is running
  503. struct poller_fd tty_event; ///< Terminal input event
  504. struct poller_fd signal_event; ///< Signal FD event
  505. struct poller_timer message_timer; ///< Message timeout
  506. char *message; ///< Message to show in the statusbar
  507. // Connection:
  508. struct mpd_client client; ///< MPD client interface
  509. struct poller_timer connect_event; ///< MPD reconnect timer
  510. enum player_state state; ///< Player state
  511. struct str_map playback_info; ///< Current song info
  512. struct poller_timer elapsed_event; ///< Seconds elapsed event
  513. int64_t elapsed_since; ///< Time of the next tick
  514. // TODO: initialize these to -1
  515. int song; ///< Current song index
  516. int song_elapsed; ///< Song elapsed in seconds
  517. int song_duration; ///< Song duration in seconds
  518. int volume; ///< Current volume
  519. struct item_list playlist; ///< Current playlist
  520. uint32_t playlist_version; ///< Playlist version
  521. int playlist_time; ///< Play time in seconds
  522. // Data:
  523. struct config config; ///< Program configuration
  524. struct strv streams; ///< List of "name NUL URI NUL"
  525. struct tab *help_tab; ///< Special help tab
  526. struct tab *tabs; ///< All other tabs
  527. struct tab *active_tab; ///< Active tab
  528. struct tab *last_tab; ///< Previous tab
  529. // Emulated widgets:
  530. int header_height; ///< Height of the header
  531. int tabs_offset; ///< Offset to tabs or -1
  532. int controls_offset; ///< Offset to player controls or -1
  533. int gauge_offset; ///< Offset to the gauge or -1
  534. int gauge_width; ///< Width of the gauge, if present
  535. struct line_editor editor; ///< Line editor
  536. struct poller_idle refresh_event; ///< Refresh the screen
  537. // Terminal:
  538. termo_t *tk; ///< termo handle
  539. struct poller_timer tk_timer; ///< termo timeout timer
  540. bool locale_is_utf8; ///< The locale is Unicode
  541. bool use_partial_boxes; ///< Use Unicode box drawing chars
  542. struct attrs attrs[ATTRIBUTE_COUNT];
  543. }
  544. g;
  545. /// Shortcut to retrieve named terminal attributes
  546. #define APP_ATTR(name) g.attrs[ATTRIBUTE_ ## name].attrs
  547. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  548. static void
  549. tab_init (struct tab *self, const char *name)
  550. {
  551. memset (self, 0, sizeof *self);
  552. // Add some padding for decorative purposes
  553. self->name = xstrdup_printf (" %s ", name);
  554. // Assuming tab names are pure ASCII, otherwise this would be inaccurate
  555. // and we'd need to filter it first to replace invalid chars with '?'
  556. self->name_width = u8_strwidth ((uint8_t *) self->name, locale_charset ());
  557. self->item_selected = 0;
  558. self->item_mark = -1;
  559. }
  560. static void
  561. tab_free (struct tab *self)
  562. {
  563. free (self->name);
  564. }
  565. static struct tab_range { int from, upto; }
  566. tab_selection_range (struct tab *self)
  567. {
  568. if (self->item_selected < 0 || !self->item_count)
  569. return (struct tab_range) { -1, -1 };
  570. if (self->item_mark < 0)
  571. return (struct tab_range) { self->item_selected, self->item_selected };
  572. return (struct tab_range) { MIN (self->item_selected, self->item_mark),
  573. MAX (self->item_selected, self->item_mark) };
  574. }
  575. // --- Configuration -----------------------------------------------------------
  576. static struct config_schema g_config_settings[] =
  577. {
  578. { .name = "address",
  579. .comment = "Address to connect to the MPD server",
  580. .type = CONFIG_ITEM_STRING,
  581. .default_ = "\"localhost\"" },
  582. { .name = "password",
  583. .comment = "Password to use for MPD authentication",
  584. .type = CONFIG_ITEM_STRING },
  585. { .name = "root",
  586. .comment = "Where all the files MPD is playing are located",
  587. .type = CONFIG_ITEM_STRING },
  588. {}
  589. };
  590. static struct config_schema g_config_colors[] =
  591. {
  592. #define XX(name_, config, fg_, bg_, attrs_) \
  593. { .name = config, .type = CONFIG_ITEM_STRING },
  594. ATTRIBUTE_TABLE (XX)
  595. #undef XX
  596. {}
  597. };
  598. static const char *
  599. get_config_string (struct config_item *root, const char *key)
  600. {
  601. struct config_item *item = config_item_get (root, key, NULL);
  602. hard_assert (item);
  603. if (item->type == CONFIG_ITEM_NULL)
  604. return NULL;
  605. hard_assert (config_item_type_is_string (item->type));
  606. return item->value.string.str;
  607. }
  608. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  609. static void
  610. load_config_settings (struct config_item *subtree, void *user_data)
  611. {
  612. config_schema_apply_to_object (g_config_settings, subtree, user_data);
  613. }
  614. static void
  615. load_config_colors (struct config_item *subtree, void *user_data)
  616. {
  617. config_schema_apply_to_object (g_config_colors, subtree, user_data);
  618. // The attributes cannot be changed dynamically right now, so it doesn't
  619. // make much sense to make use of "on_change" callbacks either.
  620. // For simplicity, we should reload the entire table on each change anyway.
  621. const char *value;
  622. #define XX(name, config, fg_, bg_, attrs_) \
  623. if ((value = get_config_string (subtree, config))) \
  624. g.attrs[ATTRIBUTE_ ## name] = attrs_decode (value);
  625. ATTRIBUTE_TABLE (XX)
  626. #undef XX
  627. }
  628. static int
  629. app_casecmp (const uint8_t *a, const uint8_t *b)
  630. {
  631. int res;
  632. // XXX: this seems to produce some strange results
  633. if (u8_casecmp (a, strlen ((const char *) a), b, strlen ((const char *) b),
  634. NULL, NULL, &res))
  635. res = u8_strcmp (a, b);
  636. return res;
  637. }
  638. static int
  639. strv_sort_utf8_cb (const void *a, const void *b)
  640. {
  641. return app_casecmp (*(const uint8_t **) a, *(const uint8_t **) b);
  642. }
  643. static void
  644. load_config_streams (struct config_item *subtree, void *user_data)
  645. {
  646. (void) user_data;
  647. // XXX: we can't use the tab in load_config_streams() because it hasn't
  648. // been initialized yet, and we cannot initialize it before the
  649. // configuration has been loaded. Thus we load it into the app_context.
  650. struct str_map_iter iter = str_map_iter_make (&subtree->value.object);
  651. struct config_item *item;
  652. while ((item = str_map_iter_next (&iter)))
  653. if (!config_item_type_is_string (item->type))
  654. print_warning ("`%s': stream URIs must be strings", iter.link->key);
  655. else
  656. {
  657. strv_append_owned (&g.streams, xstrdup_printf ("%s%c%s",
  658. iter.link->key, 0, item->value.string.str));
  659. }
  660. qsort (g.streams.vector, g.streams.len,
  661. sizeof *g.streams.vector, strv_sort_utf8_cb);
  662. }
  663. static void
  664. app_load_configuration (void)
  665. {
  666. struct config *config = &g.config;
  667. config_register_module (config, "settings", load_config_settings, NULL);
  668. config_register_module (config, "colors", load_config_colors, NULL);
  669. config_register_module (config, "streams", load_config_streams, NULL);
  670. // Bootstrap configuration, so that we can access schema items at all
  671. config_load (config, config_item_object ());
  672. char *filename = resolve_filename
  673. (PROGRAM_NAME ".conf", resolve_relative_config_filename);
  674. if (!filename)
  675. return;
  676. struct error *e = NULL;
  677. struct config_item *root = config_read_from_file (filename, &e);
  678. free (filename);
  679. if (e)
  680. {
  681. print_error ("error loading configuration: %s", e->message);
  682. error_free (e);
  683. exit (EXIT_FAILURE);
  684. }
  685. if (root)
  686. {
  687. config_load (&g.config, root);
  688. config_schema_call_changed (g.config.root);
  689. }
  690. }
  691. // --- Application -------------------------------------------------------------
  692. static void
  693. app_init_attributes (void)
  694. {
  695. #define XX(name, config, fg_, bg_, attrs_) \
  696. g.attrs[ATTRIBUTE_ ## name].fg = fg_; \
  697. g.attrs[ATTRIBUTE_ ## name].bg = bg_; \
  698. g.attrs[ATTRIBUTE_ ## name].attrs = attrs_;
  699. ATTRIBUTE_TABLE (XX)
  700. #undef XX
  701. }
  702. static void
  703. app_init_context (void)
  704. {
  705. poller_init (&g.poller);
  706. g.client = mpd_client_make (&g.poller);
  707. g.config = config_make ();
  708. g.streams = strv_make ();
  709. g.playlist = item_list_make ();
  710. g.playback_info = str_map_make (free);
  711. g.playback_info.key_xfrm = tolower_ascii_strxfrm;
  712. // This is also approximately what libunistring does internally,
  713. // since the locale name is canonicalized by locale_charset().
  714. // Note that non-Unicode locales are handled pretty inefficiently.
  715. g.locale_is_utf8 = !strcasecmp_ascii (locale_charset (), "UTF-8");
  716. // It doesn't work 100% (e.g. incompatible with undelining in urxvt)
  717. // TODO: make this configurable
  718. g.use_partial_boxes = g.locale_is_utf8;
  719. app_init_attributes ();
  720. }
  721. static void
  722. app_init_terminal (void)
  723. {
  724. TERMO_CHECK_VERSION;
  725. if (!(g.tk = termo_new (STDIN_FILENO, NULL, 0)))
  726. abort ();
  727. if (!initscr () || nonl () == ERR)
  728. abort ();
  729. // By default we don't use any colors so they're not required...
  730. if (start_color () == ERR
  731. || use_default_colors () == ERR
  732. || COLOR_PAIRS <= ATTRIBUTE_COUNT)
  733. return;
  734. for (int a = 0; a < ATTRIBUTE_COUNT; a++)
  735. {
  736. // ...thus we can reset back to defaults even after initializing some
  737. if (g.attrs[a].fg >= COLORS || g.attrs[a].fg < -1
  738. || g.attrs[a].bg >= COLORS || g.attrs[a].bg < -1)
  739. {
  740. app_init_attributes ();
  741. return;
  742. }
  743. init_pair (a + 1, g.attrs[a].fg, g.attrs[a].bg);
  744. g.attrs[a].attrs |= COLOR_PAIR (a + 1);
  745. }
  746. }
  747. static void
  748. app_free_context (void)
  749. {
  750. mpd_client_free (&g.client);
  751. str_map_free (&g.playback_info);
  752. strv_free (&g.streams);
  753. item_list_free (&g.playlist);
  754. line_editor_free (&g.editor);
  755. config_free (&g.config);
  756. poller_free (&g.poller);
  757. free (g.message);
  758. if (g.tk)
  759. termo_destroy (g.tk);
  760. }
  761. static void
  762. app_quit (void)
  763. {
  764. g.quitting = true;
  765. // So far there's nothing for us to wait on, so let's just stop looping;
  766. // otherwise we might want to e.g. cleanly bring down the MPD interface
  767. g.polling = false;
  768. }
  769. static bool
  770. app_is_character_in_locale (ucs4_t ch)
  771. {
  772. // Avoid the overhead joined with calling iconv() for all characters.
  773. if (g.locale_is_utf8)
  774. return true;
  775. // The library really creates a new conversion object every single time
  776. // and doesn't provide any smarter APIs. Luckily, most users use UTF-8.
  777. size_t len;
  778. char *tmp = u32_conv_to_encoding (locale_charset (), iconveh_error,
  779. &ch, 1, NULL, NULL, &len);
  780. if (!tmp)
  781. return false;
  782. free (tmp);
  783. return true;
  784. }
  785. // --- Rendering ---------------------------------------------------------------
  786. static void
  787. app_invalidate (void)
  788. {
  789. poller_idle_set (&g.refresh_event);
  790. }
  791. static void
  792. app_flush_buffer (struct row_buffer *buf, int width, chtype attrs)
  793. {
  794. row_buffer_align (buf, width, attrs);
  795. row_buffer_flush (buf);
  796. row_buffer_free (buf);
  797. }
  798. /// Write the given UTF-8 string padded with spaces.
  799. /// @param[in] attrs Text attributes for the text, including padding.
  800. static void
  801. app_write_line (const char *str, chtype attrs)
  802. {
  803. struct row_buffer buf = row_buffer_make ();
  804. row_buffer_append (&buf, str, attrs);
  805. app_flush_buffer (&buf, COLS, attrs);
  806. }
  807. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  808. static void
  809. app_flush_header (struct row_buffer *buf, chtype attrs)
  810. {
  811. move (g.header_height++, 0);
  812. app_flush_buffer (buf, COLS, attrs);
  813. }
  814. static void
  815. app_draw_song_info (void)
  816. {
  817. compact_map_t map;
  818. if (!(map = item_list_get (&g.playlist, g.song)))
  819. return;
  820. chtype attr_normal = APP_ATTR (NORMAL);
  821. chtype attr_highlight = APP_ATTR (HIGHLIGHT);
  822. char *title;
  823. if ((title = compact_map_find (map, "title"))
  824. || (title = compact_map_find (map, "name"))
  825. || (title = compact_map_find (map, "file")))
  826. {
  827. struct row_buffer buf = row_buffer_make ();
  828. row_buffer_append (&buf, title, attr_highlight);
  829. app_flush_header (&buf, attr_normal);
  830. }
  831. char *artist = compact_map_find (map, "artist");
  832. char *album = compact_map_find (map, "album");
  833. if (!artist && !album)
  834. return;
  835. struct row_buffer buf = row_buffer_make ();
  836. if (artist)
  837. row_buffer_append_args (&buf, " by " + !buf.total_width, attr_normal,
  838. artist, attr_highlight, NULL);
  839. if (album)
  840. row_buffer_append_args (&buf, " from " + !buf.total_width, attr_normal,
  841. album, attr_highlight, NULL);
  842. app_flush_header (&buf, attr_normal);
  843. }
  844. static char *
  845. app_time_string (int seconds)
  846. {
  847. int minutes = seconds / 60; seconds %= 60;
  848. int hours = minutes / 60; minutes %= 60;
  849. struct str s = str_make ();
  850. if (hours)
  851. str_append_printf (&s, "%d:%02d:", hours, minutes);
  852. else
  853. str_append_printf (&s, "%d:", minutes);
  854. str_append_printf (&s, "%02d", seconds);
  855. return str_steal (&s);
  856. }
  857. static void
  858. app_write_time (struct row_buffer *buf, int seconds, chtype attrs)
  859. {
  860. char *s = app_time_string (seconds);
  861. row_buffer_append (buf, s, attrs);
  862. free (s);
  863. }
  864. static void
  865. app_write_gauge (struct row_buffer *buf, float ratio, int width)
  866. {
  867. if (ratio < 0) ratio = 0;
  868. if (ratio > 1) ratio = 1;
  869. // Always compute it in exactly eight times the resolution,
  870. // because sometimes Unicode is even useful
  871. int len_left = ratio * width * 8 + 0.5;
  872. static const char *partials[] = { " ", "▏", "▎", "▍", "▌", "▋", "▊", "▉" };
  873. int remainder = len_left % 8;
  874. len_left /= 8;
  875. const char *partial = NULL;
  876. if (g.use_partial_boxes)
  877. partial = partials[remainder];
  878. else
  879. len_left += remainder >= (int) 4;
  880. int len_right = width - len_left;
  881. row_buffer_space (buf, len_left, APP_ATTR (ELAPSED));
  882. if (partial && len_right-- > 0)
  883. row_buffer_append (buf, partial, APP_ATTR (REMAINS));
  884. row_buffer_space (buf, len_right, APP_ATTR (REMAINS));
  885. }
  886. static void
  887. app_draw_status (void)
  888. {
  889. if (g.state != PLAYER_STOPPED)
  890. app_draw_song_info ();
  891. chtype attr_normal = APP_ATTR (NORMAL);
  892. chtype attr_highlight = APP_ATTR (HIGHLIGHT);
  893. struct row_buffer buf = row_buffer_make ();
  894. bool stopped = g.state == PLAYER_STOPPED;
  895. chtype attr_song_action = stopped ? attr_normal : attr_highlight;
  896. const char *toggle = g.state == PLAYER_PLAYING ? "||" : "|>";
  897. row_buffer_append_args (&buf,
  898. "<<", attr_song_action, " ", attr_normal,
  899. toggle, attr_highlight, " ", attr_normal,
  900. "[]", attr_song_action, " ", attr_normal,
  901. ">>", attr_song_action, " ", attr_normal,
  902. NULL);
  903. if (stopped)
  904. row_buffer_append (&buf, "Stopped", attr_normal);
  905. else
  906. {
  907. if (g.song_elapsed >= 0)
  908. {
  909. app_write_time (&buf, g.song_elapsed, attr_normal);
  910. row_buffer_append (&buf, " ", attr_normal);
  911. }
  912. if (g.song_duration >= 1)
  913. {
  914. row_buffer_append (&buf, "/ ", attr_normal);
  915. app_write_time (&buf, g.song_duration, attr_normal);
  916. row_buffer_append (&buf, " ", attr_normal);
  917. }
  918. row_buffer_append (&buf, " ", attr_normal);
  919. }
  920. // It gets a bit complicated due to the only right-aligned item on the row
  921. char *volume = NULL;
  922. int remaining = COLS - buf.total_width;
  923. if (g.volume >= 0)
  924. {
  925. volume = xstrdup_printf (" %3d%%", g.volume);
  926. remaining -= strlen (volume);
  927. }
  928. if (!stopped && g.song_elapsed >= 0 && g.song_duration >= 1
  929. && remaining > 0)
  930. {
  931. g.gauge_offset = buf.total_width;
  932. g.gauge_width = remaining;
  933. app_write_gauge (&buf,
  934. (float) g.song_elapsed / g.song_duration, remaining);
  935. }
  936. else
  937. row_buffer_space (&buf, remaining, attr_normal);
  938. if (volume)
  939. {
  940. row_buffer_append (&buf, volume, attr_normal);
  941. free (volume);
  942. }
  943. g.controls_offset = g.header_height;
  944. app_flush_header (&buf, attr_normal);
  945. }
  946. static void
  947. app_draw_header (void)
  948. {
  949. g.header_height = 0;
  950. g.tabs_offset = -1;
  951. g.controls_offset = -1;
  952. g.gauge_offset = -1;
  953. g.gauge_width = 0;
  954. switch (g.client.state)
  955. {
  956. case MPD_CONNECTED:
  957. app_draw_status ();
  958. break;
  959. case MPD_CONNECTING:
  960. move (g.header_height++, 0);
  961. app_write_line ("Connecting to MPD...", APP_ATTR (NORMAL));
  962. break;
  963. case MPD_DISCONNECTED:
  964. move (g.header_height++, 0);
  965. app_write_line ("Disconnected", APP_ATTR (NORMAL));
  966. }
  967. chtype attrs[2] = { APP_ATTR (TAB_BAR), APP_ATTR (TAB_ACTIVE) };
  968. // The help tab is disguised so that it's not too intruding
  969. struct row_buffer buf = row_buffer_make ();
  970. row_buffer_append (&buf, APP_TITLE, attrs[g.active_tab == g.help_tab]);
  971. row_buffer_append (&buf, " ", attrs[false]);
  972. g.tabs_offset = g.header_height;
  973. LIST_FOR_EACH (struct tab, iter, g.tabs)
  974. row_buffer_append (&buf, iter->name, attrs[iter == g.active_tab]);
  975. app_flush_header (&buf, attrs[false]);
  976. const char *header = g.active_tab->header;
  977. if (header)
  978. {
  979. buf = row_buffer_make ();
  980. row_buffer_append (&buf, header, APP_ATTR (HEADER));
  981. app_flush_header (&buf, APP_ATTR (HEADER));
  982. }
  983. }
  984. static int
  985. app_fitting_items (void)
  986. {
  987. // The raw number of items that would have fit on the terminal
  988. return LINES - g.header_height - 1 /* status bar */;
  989. }
  990. static int
  991. app_visible_items (void)
  992. {
  993. return MAX (0, app_fitting_items ());
  994. }
  995. /// Figure out scrollbar appearance. @a s is the minimal slider length as well
  996. /// as the scrollbar resolution per @a visible item.
  997. struct scrollbar { long length, start; }
  998. app_compute_scrollbar (struct tab *tab, long visible, long s)
  999. {
  1000. long top = tab->item_top, total = tab->item_count;
  1001. if (total < visible)
  1002. return (struct scrollbar) { 0, 0 };
  1003. if (visible == 1)
  1004. return (struct scrollbar) { s, 0 };
  1005. if (visible == 2)
  1006. return (struct scrollbar) { s, top >= total / 2 ? s : 0 };
  1007. // Only be at the top or bottom when the top or bottom item can be seen.
  1008. // The algorithm isn't optimal but it's a bitch to get right.
  1009. double available_length = s * visible - 2 - s + 1;
  1010. double lenf = s + available_length * visible / total, length = 0.;
  1011. long offset = 1 + available_length * top / total + modf (lenf, &length);
  1012. if (top == 0)
  1013. return (struct scrollbar) { length, 0 };
  1014. if (top + visible >= total)
  1015. return (struct scrollbar) { length, s * visible - length };
  1016. return (struct scrollbar) { length, offset };
  1017. }
  1018. static void
  1019. app_draw_scrollbar (void)
  1020. {
  1021. // This assumes that we can write to the one-before-last column,
  1022. // i.e. that it's not covered by any double-wide character (and that
  1023. // ncurses comes to the right results when counting characters).
  1024. //
  1025. // We could also precompute the scrollbar and append it to each row
  1026. // as we render them, plus all the unoccupied rows.
  1027. struct tab *tab = g.active_tab;
  1028. int visible_items = app_visible_items ();
  1029. hard_assert (tab->item_count != 0);
  1030. if (!g.use_partial_boxes)
  1031. {
  1032. struct scrollbar bar = app_compute_scrollbar (tab, visible_items, 1);
  1033. for (int row = 0; row < visible_items; row++)
  1034. {
  1035. move (g.header_height + row, COLS - 1);
  1036. if (row < bar.start || row >= bar.start + bar.length)
  1037. addch (' ' | APP_ATTR (SCROLLBAR));
  1038. else
  1039. addch (' ' | APP_ATTR (SCROLLBAR) | A_REVERSE);
  1040. }
  1041. return;
  1042. }
  1043. struct scrollbar bar = app_compute_scrollbar (tab, visible_items, 8);
  1044. bar.length += bar.start;
  1045. int start_part = bar.start % 8; bar.start /= 8;
  1046. int end_part = bar.length % 8; bar.length /= 8;
  1047. // Even with this, the solid part must be at least one character high
  1048. static const char *partials[] = { "█", "▇", "▆", "▅", "▄", "▃", "▂", "▁" };
  1049. for (int row = 0; row < visible_items; row++)
  1050. {
  1051. chtype attrs = APP_ATTR (SCROLLBAR);
  1052. if (row > bar.start && row <= bar.length)
  1053. attrs ^= A_REVERSE;
  1054. const char *c = " ";
  1055. if (row == bar.start) c = partials[start_part];
  1056. if (row == bar.length) c = partials[end_part];
  1057. move (g.header_height + row, COLS - 1);
  1058. struct row_buffer buf = row_buffer_make ();
  1059. row_buffer_append (&buf, c, attrs);
  1060. row_buffer_flush (&buf);
  1061. row_buffer_free (&buf);
  1062. }
  1063. }
  1064. static void
  1065. app_draw_view (void)
  1066. {
  1067. move (g.header_height, 0);
  1068. clrtobot ();
  1069. struct tab *tab = g.active_tab;
  1070. bool want_scrollbar = (int) tab->item_count > app_visible_items ();
  1071. int view_width = COLS - want_scrollbar;
  1072. int to_show =
  1073. MIN (app_fitting_items (), (int) tab->item_count - tab->item_top);
  1074. for (int row = 0; row < to_show; row++)
  1075. {
  1076. int item_index = tab->item_top + row;
  1077. int row_attrs = (item_index & 1) ? APP_ATTR (ODD) : APP_ATTR (EVEN);
  1078. bool override_colors = true;
  1079. if (item_index == tab->item_selected)
  1080. row_attrs = APP_ATTR (SELECTION);
  1081. else if (tab->item_mark > -1 &&
  1082. ((item_index >= tab->item_mark && item_index <= tab->item_selected)
  1083. || (item_index >= tab->item_selected && item_index <= tab->item_mark)))
  1084. row_attrs = APP_ATTR (MULTISELECT);
  1085. else
  1086. override_colors = false;
  1087. struct row_buffer buf = row_buffer_make ();
  1088. tab->on_item_draw (item_index, &buf, view_width);
  1089. // Combine attributes used by the handler with the defaults.
  1090. // Avoiding attrset() because of row_buffer_flush().
  1091. for (size_t i = 0; i < buf.chars_len; i++)
  1092. {
  1093. chtype *attrs = &buf.chars[i].attrs;
  1094. if (override_colors)
  1095. *attrs = (*attrs & ~(A_COLOR | A_REVERSE)) | row_attrs;
  1096. else if ((*attrs & A_COLOR) && (row_attrs & A_COLOR))
  1097. *attrs |= (row_attrs & ~A_COLOR);
  1098. else
  1099. *attrs |= row_attrs;
  1100. }
  1101. move (g.header_height + row, 0);
  1102. app_flush_buffer (&buf, view_width, row_attrs);
  1103. }
  1104. if (want_scrollbar)
  1105. app_draw_scrollbar ();
  1106. }
  1107. static void
  1108. app_write_mpd_status_playlist (struct row_buffer *buf)
  1109. {
  1110. struct str stats = str_make ();
  1111. if (g.playlist.len == 1)
  1112. str_append_printf (&stats, "1 song ");
  1113. else
  1114. str_append_printf (&stats, "%zu songs ", g.playlist.len);
  1115. int hours = g.playlist_time / 3600;
  1116. int minutes = g.playlist_time % 3600 / 60;
  1117. if (hours || minutes)
  1118. {
  1119. str_append_c (&stats, ' ');
  1120. if (hours == 1)
  1121. str_append_printf (&stats, " 1 hour");
  1122. else if (hours)
  1123. str_append_printf (&stats, " %d hours", hours);
  1124. if (minutes == 1)
  1125. str_append_printf (&stats, " 1 minute");
  1126. else if (minutes)
  1127. str_append_printf (&stats, " %d minutes", minutes);
  1128. }
  1129. row_buffer_append (buf, stats.str, APP_ATTR (NORMAL));
  1130. str_free (&stats);
  1131. }
  1132. static void
  1133. app_write_mpd_status (struct row_buffer *buf)
  1134. {
  1135. struct str_map *map = &g.playback_info;
  1136. if (g.active_tab->item_mark > -1)
  1137. {
  1138. struct tab_range r = tab_selection_range (g.active_tab);
  1139. char *msg = xstrdup_printf (r.from == r.upto
  1140. ? "Selected %d item" : "Selected %d items", r.upto - r.from + 1);
  1141. row_buffer_append (buf, msg, APP_ATTR (HIGHLIGHT));
  1142. free (msg);
  1143. }
  1144. else if (str_map_find (map, "updating_db"))
  1145. row_buffer_append (buf, "Updating database...", APP_ATTR (NORMAL));
  1146. else
  1147. app_write_mpd_status_playlist (buf);
  1148. const char *s;
  1149. bool repeat = (s = str_map_find (map, "repeat")) && strcmp (s, "0");
  1150. bool random = (s = str_map_find (map, "random")) && strcmp (s, "0");
  1151. bool single = (s = str_map_find (map, "single")) && strcmp (s, "0");
  1152. bool consume = (s = str_map_find (map, "consume")) && strcmp (s, "0");
  1153. struct row_buffer right = row_buffer_make ();
  1154. chtype a[2] = { APP_ATTR (NORMAL), APP_ATTR (HIGHLIGHT) };
  1155. if (repeat) row_buffer_append_args (&right,
  1156. " ", APP_ATTR (NORMAL), "repeat", a[repeat], NULL);
  1157. if (random) row_buffer_append_args (&right,
  1158. " ", APP_ATTR (NORMAL), "random", a[random], NULL);
  1159. if (single) row_buffer_append_args (&right,
  1160. " ", APP_ATTR (NORMAL), "single", a[single], NULL);
  1161. if (consume) row_buffer_append_args (&right,
  1162. " ", APP_ATTR (NORMAL), "consume", a[consume], NULL);
  1163. row_buffer_space (buf,
  1164. MAX (0, COLS - buf->total_width - right.total_width),
  1165. APP_ATTR (NORMAL));
  1166. row_buffer_append_buffer (buf, &right);
  1167. row_buffer_free (&right);
  1168. }
  1169. static void
  1170. app_draw_statusbar (void)
  1171. {
  1172. int caret = -1;
  1173. struct row_buffer buf = row_buffer_make ();
  1174. if (g.message)
  1175. row_buffer_append (&buf, g.message, APP_ATTR (HIGHLIGHT));
  1176. else if (g.editor.line)
  1177. caret = line_editor_write (&g.editor, &buf, COLS, APP_ATTR (HIGHLIGHT));
  1178. else if (g.client.state == MPD_CONNECTED)
  1179. app_write_mpd_status (&buf);
  1180. move (LINES - 1, 0);
  1181. app_flush_buffer (&buf, COLS, APP_ATTR (NORMAL));
  1182. curs_set (0);
  1183. if (caret != -1)
  1184. {
  1185. move (LINES - 1, caret);
  1186. curs_set (1);
  1187. }
  1188. }
  1189. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1190. /// Checks what items are visible and returns if the range was alright
  1191. static bool
  1192. app_fix_view_range (void)
  1193. {
  1194. struct tab *tab = g.active_tab;
  1195. if (tab->item_top < 0)
  1196. {
  1197. tab->item_top = 0;
  1198. return false;
  1199. }
  1200. // If the contents are at least as long as the screen, always fill it
  1201. int max_item_top = (int) tab->item_count - app_visible_items ();
  1202. // But don't let that suggest a negative offset
  1203. max_item_top = MAX (max_item_top, 0);
  1204. if (tab->item_top > max_item_top)
  1205. {
  1206. tab->item_top = max_item_top;
  1207. return false;
  1208. }
  1209. return true;
  1210. }
  1211. static void
  1212. app_on_refresh (void *user_data)
  1213. {
  1214. (void) user_data;
  1215. poller_idle_reset (&g.refresh_event);
  1216. app_draw_header ();
  1217. app_fix_view_range();
  1218. app_draw_view ();
  1219. app_draw_statusbar ();
  1220. refresh ();
  1221. }
  1222. // --- Actions -----------------------------------------------------------------
  1223. /// Scroll down (positive) or up (negative) @a n items
  1224. static bool
  1225. app_scroll (int n)
  1226. {
  1227. g.active_tab->item_top += n;
  1228. app_invalidate ();
  1229. return app_fix_view_range ();
  1230. }
  1231. static void
  1232. app_ensure_selection_visible (void)
  1233. {
  1234. struct tab *tab = g.active_tab;
  1235. if (tab->item_selected < 0 || !tab->item_count)
  1236. return;
  1237. int too_high = tab->item_top - tab->item_selected;
  1238. if (too_high > 0)
  1239. app_scroll (-too_high);
  1240. int too_low = tab->item_selected
  1241. - (tab->item_top + app_visible_items () - 1);
  1242. if (too_low > 0)
  1243. app_scroll (too_low);
  1244. }
  1245. static bool
  1246. app_move_selection (int diff)
  1247. {
  1248. struct tab *tab = g.active_tab;
  1249. int fixed = tab->item_selected + diff;
  1250. fixed = MIN (fixed, (int) tab->item_count - 1);
  1251. fixed = MAX (fixed, 0);
  1252. bool result = !diff || tab->item_selected != fixed;
  1253. tab->item_selected = fixed;
  1254. app_invalidate ();
  1255. app_ensure_selection_visible ();
  1256. return result;
  1257. }
  1258. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1259. static void
  1260. app_prepend_tab (struct tab *tab)
  1261. {
  1262. LIST_PREPEND (g.tabs, tab);
  1263. app_invalidate ();
  1264. }
  1265. static void
  1266. app_switch_tab (struct tab *tab)
  1267. {
  1268. if (tab == g.active_tab)
  1269. return;
  1270. g.last_tab = g.active_tab;
  1271. g.active_tab = tab;
  1272. app_invalidate ();
  1273. }
  1274. static bool
  1275. app_goto_tab (int tab_index)
  1276. {
  1277. int i = 0;
  1278. LIST_FOR_EACH (struct tab, iter, g.tabs)
  1279. if (i++ == tab_index)
  1280. {
  1281. app_switch_tab (iter);
  1282. return true;
  1283. }
  1284. return false;
  1285. }
  1286. // --- Actions -----------------------------------------------------------------
  1287. #define ACTIONS(XX) \
  1288. XX( NONE, "Do nothing" ) \
  1289. \
  1290. XX( QUIT, "Quit" ) \
  1291. XX( REDRAW, "Redraw screen" ) \
  1292. XX( HELP_TAB, "Switch to help tab" ) \
  1293. XX( LAST_TAB, "Switch to previous tab" ) \
  1294. \
  1295. XX( MPD_TOGGLE, "Toggle play/pause" ) \
  1296. XX( MPD_STOP, "Stop playback" ) \
  1297. XX( MPD_PREVIOUS, "Previous song" ) \
  1298. XX( MPD_NEXT, "Next song" ) \
  1299. XX( MPD_BACKWARD, "Seek backwards" ) \
  1300. XX( MPD_FORWARD, "Seek forwards" ) \
  1301. XX( MPD_VOLUME_UP, "Increase volume" ) \
  1302. XX( MPD_VOLUME_DOWN, "Decrease volume" ) \
  1303. \
  1304. XX( MPD_SEARCH, "Global search" ) \
  1305. XX( MPD_ADD, "Add selection to playlist" ) \
  1306. XX( MPD_REPLACE, "Replace playlist" ) \
  1307. XX( MPD_REPEAT, "Toggle repeat" ) \
  1308. XX( MPD_RANDOM, "Toggle random playback" ) \
  1309. XX( MPD_SINGLE, "Toggle single song playback" ) \
  1310. XX( MPD_CONSUME, "Toggle consume" ) \
  1311. XX( MPD_UPDATE_DB, "Update MPD database" ) \
  1312. XX( MPD_COMMAND, "Send raw command to MPD" ) \
  1313. \
  1314. XX( CHOOSE, "Choose item" ) \
  1315. XX( DELETE, "Delete item" ) \
  1316. XX( UP, "Go up a level" ) \
  1317. XX( MULTISELECT, "Toggle multiselect" ) \
  1318. \
  1319. XX( SCROLL_UP, "Scroll up" ) \
  1320. XX( SCROLL_DOWN, "Scroll down" ) \
  1321. XX( MOVE_UP, "Move selection up" ) \
  1322. XX( MOVE_DOWN, "Move selection down" ) \
  1323. \
  1324. XX( GOTO_TOP, "Go to top" ) \
  1325. XX( GOTO_BOTTOM, "Go to bottom" ) \
  1326. XX( GOTO_ITEM_PREVIOUS, "Go to previous item" ) \
  1327. XX( GOTO_ITEM_NEXT, "Go to next item" ) \
  1328. XX( GOTO_PAGE_PREVIOUS, "Go to previous page" ) \
  1329. XX( GOTO_PAGE_NEXT, "Go to next page" ) \
  1330. \
  1331. XX( GOTO_VIEW_TOP, "Select top item" ) \
  1332. XX( GOTO_VIEW_CENTER, "Select center item" ) \
  1333. XX( GOTO_VIEW_BOTTOM, "Select bottom item" ) \
  1334. \
  1335. XX( EDITOR_CONFIRM, "Confirm input" ) \
  1336. \
  1337. XX( EDITOR_B_CHAR, "Go back a character" ) \
  1338. XX( EDITOR_F_CHAR, "Go forward a character" ) \
  1339. XX( EDITOR_B_WORD, "Go back a word" ) \
  1340. XX( EDITOR_F_WORD, "Go forward a word" ) \
  1341. XX( EDITOR_HOME, "Go to start of line" ) \
  1342. XX( EDITOR_END, "Go to end of line" ) \
  1343. \
  1344. XX( EDITOR_B_DELETE, "Delete last character" ) \
  1345. XX( EDITOR_F_DELETE, "Delete next character" ) \
  1346. XX( EDITOR_B_KILL_WORD, "Delete last word" ) \
  1347. XX( EDITOR_B_KILL_LINE, "Delete everything up to BOL" ) \
  1348. XX( EDITOR_F_KILL_LINE, "Delete everything up to EOL" )
  1349. enum action
  1350. {
  1351. #define XX(name, description) ACTION_ ## name,
  1352. ACTIONS (XX)
  1353. #undef XX
  1354. ACTION_COUNT
  1355. };
  1356. static struct action_info
  1357. {
  1358. const char *name; ///< Name for user bindings
  1359. const char *description; ///< Human-readable description
  1360. }
  1361. g_actions[] =
  1362. {
  1363. #define XX(name, description) { #name, description },
  1364. ACTIONS (XX)
  1365. #undef XX
  1366. };
  1367. /// Accept a more human format of action-name instead of ACTION_NAME
  1368. static int action_toupper (int c) { return c == '-' ? '_' : toupper_ascii (c); }
  1369. static int
  1370. action_resolve (const char *name)
  1371. {
  1372. const unsigned char *s = (const unsigned char *) name;
  1373. for (int i = 0; i < ACTION_COUNT; i++)
  1374. {
  1375. const char *target = g_actions[i].name;
  1376. for (size_t k = 0; action_toupper (s[k]) == target[k]; k++)
  1377. if (!s[k] && !target[k])
  1378. return i;
  1379. }
  1380. return -1;
  1381. }
  1382. // --- User input handling -----------------------------------------------------
  1383. static void
  1384. mpd_client_vsend_command (struct mpd_client *self, va_list ap)
  1385. {
  1386. struct strv v = strv_make ();
  1387. const char *command;
  1388. while ((command = va_arg (ap, const char *)))
  1389. strv_append (&v, command);
  1390. mpd_client_send_commandv (self, v.vector);
  1391. strv_free (&v);
  1392. }
  1393. /// Send a command to MPD without caring about the response
  1394. static bool mpd_client_send_simple (struct mpd_client *self, ...)
  1395. ATTRIBUTE_SENTINEL;
  1396. static void
  1397. mpd_on_simple_response (const struct mpd_response *response,
  1398. const struct strv *data, void *user_data)
  1399. {
  1400. (void) data;
  1401. (void) user_data;
  1402. if (!response->success)
  1403. print_error ("%s: %s", "command failed", response->message_text);
  1404. }
  1405. static bool
  1406. mpd_client_send_simple (struct mpd_client *self, ...)
  1407. {
  1408. if (self->state != MPD_CONNECTED)
  1409. return false;
  1410. va_list ap;
  1411. va_start (ap, self);
  1412. mpd_client_vsend_command (self, ap);
  1413. va_end (ap);
  1414. mpd_client_add_task (self, mpd_on_simple_response, NULL);
  1415. mpd_client_idle (self, 0);
  1416. return true;
  1417. }
  1418. #define MPD_SIMPLE(...) \
  1419. mpd_client_send_simple (&g.client, __VA_ARGS__, NULL)
  1420. static bool
  1421. app_setvol (int value)
  1422. {
  1423. char *volume = xstrdup_printf ("%d", MAX (0, MIN (100, value)));
  1424. bool result = g.volume >= 0 && MPD_SIMPLE ("setvol", volume);
  1425. free (volume);
  1426. return result;
  1427. }
  1428. static void
  1429. app_on_editor_end (bool confirmed)
  1430. {
  1431. struct mpd_client *c = &g.client;
  1432. if (!confirmed)
  1433. return;
  1434. size_t len;
  1435. char *u8 = (char *) u32_to_u8 (g.editor.line, g.editor.len + 1, NULL, &len);
  1436. mpd_client_send_command_raw (c, u8);
  1437. free (u8);
  1438. mpd_client_add_task (c, mpd_on_simple_response, NULL);
  1439. mpd_client_idle (c, 0);
  1440. }
  1441. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1442. static bool
  1443. app_mpd_toggle (const char *name)
  1444. {
  1445. const char *s = str_map_find (&g.playback_info, name);
  1446. bool value = s && strcmp (s, "0");
  1447. return MPD_SIMPLE (name, value ? "0" : "1");
  1448. }
  1449. static bool
  1450. app_process_action (enum action action)
  1451. {
  1452. // First let the tab try to handle this
  1453. struct tab *tab = g.active_tab;
  1454. if (tab->on_action && tab->on_action (action))
  1455. {
  1456. app_invalidate ();
  1457. return true;
  1458. }
  1459. switch (action)
  1460. {
  1461. case ACTION_NONE:
  1462. return true;
  1463. case ACTION_QUIT:
  1464. // It is a pseudomode, avoid surprising the user
  1465. if (tab->item_mark > -1)
  1466. {
  1467. tab->item_mark = -1;
  1468. app_invalidate ();
  1469. return true;
  1470. }
  1471. app_quit ();
  1472. return true;
  1473. case ACTION_REDRAW:
  1474. clear ();
  1475. app_invalidate ();
  1476. return true;
  1477. case ACTION_MPD_COMMAND:
  1478. line_editor_start (&g.editor, ':');
  1479. g.editor.on_end = app_on_editor_end;
  1480. app_invalidate ();
  1481. return true;
  1482. default:
  1483. return false;
  1484. case ACTION_MULTISELECT:
  1485. if (!tab->can_multiselect
  1486. || !tab->item_count || tab->item_selected < 0)
  1487. return false;
  1488. app_invalidate ();
  1489. if (tab->item_mark > -1)
  1490. tab->item_mark = -1;
  1491. else
  1492. tab->item_mark = tab->item_selected;
  1493. return true;
  1494. case ACTION_LAST_TAB:
  1495. if (!g.last_tab)
  1496. return false;
  1497. app_switch_tab (g.last_tab);
  1498. return true;
  1499. case ACTION_HELP_TAB:
  1500. app_switch_tab (g.help_tab);
  1501. return true;
  1502. case ACTION_MPD_TOGGLE:
  1503. if (g.state == PLAYER_PLAYING) return MPD_SIMPLE ("pause", "1");
  1504. if (g.state == PLAYER_PAUSED) return MPD_SIMPLE ("pause", "0");
  1505. return MPD_SIMPLE ("play");
  1506. case ACTION_MPD_STOP: return MPD_SIMPLE ("stop");
  1507. case ACTION_MPD_PREVIOUS: return MPD_SIMPLE ("previous");
  1508. case ACTION_MPD_NEXT: return MPD_SIMPLE ("next");
  1509. case ACTION_MPD_FORWARD: return MPD_SIMPLE ("seekcur", "+10");
  1510. case ACTION_MPD_BACKWARD: return MPD_SIMPLE ("seekcur", "-10");
  1511. case ACTION_MPD_REPEAT: return app_mpd_toggle ("repeat");
  1512. case ACTION_MPD_RANDOM: return app_mpd_toggle ("random");
  1513. case ACTION_MPD_SINGLE: return app_mpd_toggle ("single");
  1514. case ACTION_MPD_CONSUME: return app_mpd_toggle ("consume");
  1515. case ACTION_MPD_UPDATE_DB: return MPD_SIMPLE ("update");
  1516. case ACTION_MPD_VOLUME_UP: return app_setvol (g.volume + 10);
  1517. case ACTION_MPD_VOLUME_DOWN: return app_setvol (g.volume - 10);
  1518. // XXX: these should rather be parametrized
  1519. case ACTION_SCROLL_UP: return app_scroll (-3);
  1520. case ACTION_SCROLL_DOWN: return app_scroll (3);
  1521. case ACTION_GOTO_TOP:
  1522. if (tab->item_count)
  1523. {
  1524. g.active_tab->item_selected = 0;
  1525. app_ensure_selection_visible ();
  1526. app_invalidate ();
  1527. }
  1528. return true;
  1529. case ACTION_GOTO_BOTTOM:
  1530. if (tab->item_count)
  1531. {
  1532. g.active_tab->item_selected =
  1533. MAX (0, (int) g.active_tab->item_count - 1);
  1534. app_ensure_selection_visible ();
  1535. app_invalidate ();
  1536. }
  1537. return true;
  1538. case ACTION_GOTO_ITEM_PREVIOUS: return app_move_selection (-1);
  1539. case ACTION_GOTO_ITEM_NEXT: return app_move_selection (1);
  1540. case ACTION_GOTO_PAGE_PREVIOUS:
  1541. app_scroll (-app_visible_items ());
  1542. return app_move_selection (-app_visible_items ());
  1543. case ACTION_GOTO_PAGE_NEXT:
  1544. app_scroll (app_visible_items ());
  1545. return app_move_selection (app_visible_items ());
  1546. case ACTION_GOTO_VIEW_TOP:
  1547. g.active_tab->item_selected = g.active_tab->item_top;
  1548. return app_move_selection (0);
  1549. case ACTION_GOTO_VIEW_CENTER:
  1550. g.active_tab->item_selected = g.active_tab->item_top;
  1551. return app_move_selection (MAX (0, app_visible_items () / 2 - 1));
  1552. case ACTION_GOTO_VIEW_BOTTOM:
  1553. g.active_tab->item_selected = g.active_tab->item_top;
  1554. return app_move_selection (MAX (0, app_visible_items () - 1));
  1555. }
  1556. return false;
  1557. }
  1558. static bool
  1559. app_editor_process_action (enum action action)
  1560. {
  1561. app_invalidate ();
  1562. switch (action)
  1563. {
  1564. case ACTION_QUIT:
  1565. line_editor_abort (&g.editor, false);
  1566. g.editor.on_end = NULL;
  1567. return true;
  1568. case ACTION_EDITOR_CONFIRM:
  1569. line_editor_abort (&g.editor, true);
  1570. g.editor.on_end = NULL;
  1571. return true;
  1572. default:
  1573. return false;
  1574. case ACTION_EDITOR_B_CHAR:
  1575. return line_editor_action (&g.editor, LINE_EDITOR_B_CHAR);
  1576. case ACTION_EDITOR_F_CHAR:
  1577. return line_editor_action (&g.editor, LINE_EDITOR_F_CHAR);
  1578. case ACTION_EDITOR_B_WORD:
  1579. return line_editor_action (&g.editor, LINE_EDITOR_B_WORD);
  1580. case ACTION_EDITOR_F_WORD:
  1581. return line_editor_action (&g.editor, LINE_EDITOR_F_WORD);
  1582. case ACTION_EDITOR_HOME:
  1583. return line_editor_action (&g.editor, LINE_EDITOR_HOME);
  1584. case ACTION_EDITOR_END:
  1585. return line_editor_action (&g.editor, LINE_EDITOR_END);
  1586. case ACTION_EDITOR_B_DELETE:
  1587. return line_editor_action (&g.editor, LINE_EDITOR_B_DELETE);
  1588. case ACTION_EDITOR_F_DELETE:
  1589. return line_editor_action (&g.editor, LINE_EDITOR_F_DELETE);
  1590. case ACTION_EDITOR_B_KILL_WORD:
  1591. return line_editor_action (&g.editor, LINE_EDITOR_B_KILL_WORD);
  1592. case ACTION_EDITOR_B_KILL_LINE:
  1593. return line_editor_action (&g.editor, LINE_EDITOR_B_KILL_LINE);
  1594. case ACTION_EDITOR_F_KILL_LINE:
  1595. return line_editor_action (&g.editor, LINE_EDITOR_F_KILL_LINE);
  1596. }
  1597. }
  1598. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1599. static bool
  1600. app_process_left_mouse_click (int line, int column, bool double_click)
  1601. {
  1602. if (line == g.controls_offset)
  1603. {
  1604. // XXX: there could be a push_widget(buf, text, attrs, handler)
  1605. // function to help with this but it might not be worth it
  1606. enum action action = ACTION_NONE;
  1607. if (column >= 0 && column <= 1) action = ACTION_MPD_PREVIOUS;
  1608. if (column >= 3 && column <= 4) action = ACTION_MPD_TOGGLE;
  1609. if (column >= 6 && column <= 7) action = ACTION_MPD_STOP;
  1610. if (column >= 9 && column <= 10) action = ACTION_MPD_NEXT;
  1611. if (action)
  1612. return app_process_action (action);
  1613. int gauge_offset = column - g.gauge_offset;
  1614. if (g.gauge_offset < 0
  1615. || gauge_offset < 0 || gauge_offset >= g.gauge_width)
  1616. return false;
  1617. float position = (float) gauge_offset / g.gauge_width;
  1618. if (g.song_duration >= 1)
  1619. {
  1620. char *where = xstrdup_printf ("%f", position * g.song_duration);
  1621. MPD_SIMPLE ("seekcur", where);
  1622. free (where);
  1623. }
  1624. }
  1625. else if (line == g.tabs_offset)
  1626. {
  1627. struct tab *winner = NULL;
  1628. int indent = strlen (APP_TITLE);
  1629. if (column < indent)
  1630. {
  1631. app_switch_tab (g.help_tab);
  1632. return true;
  1633. }
  1634. for (struct tab *iter = g.tabs; !winner && iter; iter = iter->next)
  1635. {
  1636. if (column < (indent += iter->name_width))
  1637. winner = iter;
  1638. }
  1639. if (!winner)
  1640. return false;
  1641. app_switch_tab (winner);
  1642. }
  1643. else if (line >= g.header_height)
  1644. {
  1645. struct tab *tab = g.active_tab;
  1646. int row_index = line - g.header_height;
  1647. if (row_index < 0
  1648. || row_index >= (int) tab->item_count - tab->item_top)
  1649. return false;
  1650. // TODO: handle the scrollbar a bit better than this
  1651. int visible_items = app_visible_items ();
  1652. if ((int) tab->item_count > visible_items && column == COLS - 1)
  1653. tab->item_top = (float) row_index / visible_items
  1654. * (int) tab->item_count - visible_items / 2;
  1655. else
  1656. tab->item_selected = row_index + tab->item_top;
  1657. app_invalidate ();
  1658. if (double_click)
  1659. app_process_action (ACTION_CHOOSE);
  1660. }
  1661. return true;
  1662. }
  1663. static bool
  1664. app_process_mouse (termo_mouse_event_t type, int line, int column, int button,
  1665. bool double_click)
  1666. {
  1667. if (type != TERMO_MOUSE_PRESS)
  1668. return true;
  1669. if (g.editor.line)
  1670. line_editor_abort (&g.editor, false);
  1671. if (button == 1)
  1672. return app_process_left_mouse_click (line, column, double_click);
  1673. else if (button == 4)
  1674. return app_process_action (ACTION_SCROLL_UP);
  1675. else if (button == 5)
  1676. return app_process_action (ACTION_SCROLL_DOWN);
  1677. return false;
  1678. }
  1679. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1680. static struct binding
  1681. {
  1682. termo_key_t decoded; ///< Decoded key definition
  1683. enum action action; ///< Action to take
  1684. int order; ///< Order for stable sorting
  1685. }
  1686. *g_normal_keys, *g_editor_keys;
  1687. static size_t g_normal_keys_len, g_editor_keys_len;
  1688. static struct binding_default
  1689. {
  1690. const char *key; ///< Key definition
  1691. enum action action; ///< Action to take
  1692. }
  1693. g_normal_defaults[] =
  1694. {
  1695. { "Escape", ACTION_QUIT },
  1696. { "q", ACTION_QUIT },
  1697. { "C-l", ACTION_REDRAW },
  1698. { "M-Tab", ACTION_LAST_TAB },
  1699. { "F1", ACTION_HELP_TAB },
  1700. { "Home", ACTION_GOTO_TOP },
  1701. { "End", ACTION_GOTO_BOTTOM },
  1702. { "M-<", ACTION_GOTO_TOP },
  1703. { "M->", ACTION_GOTO_BOTTOM },
  1704. { "g", ACTION_GOTO_TOP },
  1705. { "G", ACTION_GOTO_BOTTOM },
  1706. { "S-Up", ACTION_MOVE_UP },
  1707. { "S-Down", ACTION_MOVE_DOWN },
  1708. { "Up", ACTION_GOTO_ITEM_PREVIOUS },
  1709. { "Down", ACTION_GOTO_ITEM_NEXT },
  1710. { "k", ACTION_GOTO_ITEM_PREVIOUS },
  1711. { "j", ACTION_GOTO_ITEM_NEXT },
  1712. { "PageUp", ACTION_GOTO_PAGE_PREVIOUS },
  1713. { "PageDown", ACTION_GOTO_PAGE_NEXT },
  1714. { "C-p", ACTION_GOTO_ITEM_PREVIOUS },
  1715. { "C-n", ACTION_GOTO_ITEM_NEXT },
  1716. { "C-b", ACTION_GOTO_PAGE_PREVIOUS },
  1717. { "C-f", ACTION_GOTO_PAGE_NEXT },
  1718. { "H", ACTION_GOTO_VIEW_TOP },
  1719. { "M", ACTION_GOTO_VIEW_CENTER },
  1720. { "L", ACTION_GOTO_VIEW_BOTTOM },
  1721. // Not sure how to set these up, they're pretty arbitrary so far
  1722. { "Enter", ACTION_CHOOSE },
  1723. { "Delete", ACTION_DELETE },
  1724. { "d", ACTION_DELETE },
  1725. { "Backspace", ACTION_UP },
  1726. { "v", ACTION_MULTISELECT },
  1727. { "/", ACTION_MPD_SEARCH },
  1728. { "a", ACTION_MPD_ADD },
  1729. { "r", ACTION_MPD_REPLACE },
  1730. { ":", ACTION_MPD_COMMAND },
  1731. { "<", ACTION_MPD_PREVIOUS },
  1732. { ">", ACTION_MPD_NEXT },
  1733. { "Left", ACTION_MPD_PREVIOUS },
  1734. { "Right", ACTION_MPD_NEXT },
  1735. { "M-Left", ACTION_MPD_BACKWARD },
  1736. { "M-Right", ACTION_MPD_FORWARD },
  1737. { "h", ACTION_MPD_PREVIOUS },
  1738. { "l", ACTION_MPD_NEXT },
  1739. { "Space", ACTION_MPD_TOGGLE },
  1740. { "C-Space", ACTION_MPD_STOP },
  1741. { "u", ACTION_MPD_UPDATE_DB },
  1742. { "M-PageUp", ACTION_MPD_VOLUME_UP },
  1743. { "M-PageDown", ACTION_MPD_VOLUME_DOWN },
  1744. },
  1745. g_editor_defaults[] =
  1746. {
  1747. { "Left", ACTION_EDITOR_B_CHAR },
  1748. { "Right", ACTION_EDITOR_F_CHAR },
  1749. { "C-b", ACTION_EDITOR_B_CHAR },
  1750. { "C-f", ACTION_EDITOR_F_CHAR },
  1751. { "M-b", ACTION_EDITOR_B_WORD },
  1752. { "M-f", ACTION_EDITOR_F_WORD },
  1753. { "Home", ACTION_EDITOR_HOME },
  1754. { "End", ACTION_EDITOR_END },
  1755. { "C-a", ACTION_EDITOR_HOME },
  1756. { "C-e", ACTION_EDITOR_END },
  1757. { "C-h", ACTION_EDITOR_B_DELETE },
  1758. { "DEL", ACTION_EDITOR_B_DELETE },
  1759. { "Backspace", ACTION_EDITOR_B_DELETE },
  1760. { "C-d", ACTION_EDITOR_F_DELETE },
  1761. { "Delete", ACTION_EDITOR_F_DELETE },
  1762. { "C-u", ACTION_EDITOR_B_KILL_LINE },
  1763. { "C-k", ACTION_EDITOR_F_KILL_LINE },
  1764. { "C-w", ACTION_EDITOR_B_KILL_WORD },
  1765. { "C-g", ACTION_QUIT },
  1766. { "Escape", ACTION_QUIT },
  1767. { "Enter", ACTION_EDITOR_CONFIRM },
  1768. };
  1769. static int
  1770. app_binding_cmp (const void *a, const void *b)
  1771. {
  1772. const struct binding *aa = a, *bb = b;
  1773. int cmp = termo_keycmp (g.tk, &aa->decoded, &bb->decoded);
  1774. return cmp ? cmp : bb->order - aa->order;
  1775. }
  1776. static bool
  1777. app_next_binding (struct str_map_iter *iter, termo_key_t *key, int *action)
  1778. {
  1779. struct config_item *v;
  1780. while ((v = str_map_iter_next (iter)))
  1781. {
  1782. *action = ACTION_NONE;
  1783. if (*termo_strpkey_utf8 (g.tk,
  1784. iter->link->key, key, TERMO_FORMAT_ALTISMETA))
  1785. print_error ("%s: invalid binding", iter->link->key);
  1786. else if (v->type == CONFIG_ITEM_NULL)
  1787. return true;
  1788. else if (v->type != CONFIG_ITEM_STRING)
  1789. print_error ("%s: bindings must be strings", iter->link->key);
  1790. else if ((*action = action_resolve (v->value.string.str)) >= 0)
  1791. return true;
  1792. else
  1793. print_error ("%s: unknown action: %s",
  1794. iter->link->key, v->value.string.str);
  1795. }
  1796. return false;
  1797. }
  1798. static struct binding *
  1799. app_init_bindings (const char *keymap,
  1800. struct binding_default *defaults, size_t defaults_len, size_t *result_len)
  1801. {
  1802. ARRAY (struct binding, a)
  1803. ARRAY_INIT_SIZED (a, defaults_len);
  1804. // Order for stable sorting
  1805. size_t order = 0;
  1806. termo_key_t decoded;
  1807. for (size_t i = 0; i < defaults_len; i++)
  1808. {
  1809. hard_assert (!*termo_strpkey_utf8 (g.tk,
  1810. defaults[i].key, &decoded, TERMO_FORMAT_ALTISMETA));
  1811. a[a_len++] = (struct binding) { decoded, defaults[i].action, order++ };
  1812. }
  1813. struct config_item *root = config_item_get (g.config.root, keymap, NULL);
  1814. if (root && root->type == CONFIG_ITEM_OBJECT)
  1815. {
  1816. struct str_map_iter iter = str_map_iter_make (&root->value.object);
  1817. ARRAY_RESERVE (a, iter.map->len);
  1818. int action;
  1819. while (app_next_binding (&iter, &decoded, &action))
  1820. a[a_len++] = (struct binding) { decoded, action, order++ };
  1821. }
  1822. // Use the helper field to use the last mappings of identical bindings
  1823. size_t out = 0;
  1824. qsort (a, a_len, sizeof *a, app_binding_cmp);
  1825. for (size_t in = 0; in < a_len; in++)
  1826. {
  1827. a[in].order = 0;
  1828. if (!out || termo_keycmp (g.tk, &a[in].decoded, &a[out - 1].decoded))
  1829. a[out++] = a[in];
  1830. }
  1831. *result_len = out;
  1832. return a;
  1833. }
  1834. static bool
  1835. app_process_termo_event (termo_key_t *event)
  1836. {
  1837. struct binding dummy = { *event, 0, 0 }, *binding;
  1838. if (g.editor.line)
  1839. {
  1840. if ((binding = bsearch (&dummy, g_editor_keys, g_editor_keys_len,
  1841. sizeof *binding, app_binding_cmp)))
  1842. return app_editor_process_action (binding->action);
  1843. if (event->type != TERMO_TYPE_KEY || event->modifiers != 0)
  1844. return false;
  1845. line_editor_insert (&g.editor, event->code.codepoint);
  1846. app_invalidate ();
  1847. return true;
  1848. }
  1849. if ((binding = bsearch (&dummy, g_normal_keys, g_normal_keys_len,
  1850. sizeof *binding, app_binding_cmp)))
  1851. return app_process_action (binding->action);
  1852. // TODO: parametrize actions, put this among other bindings
  1853. if (!(event->modifiers & ~TERMO_KEYMOD_ALT)
  1854. && event->code.codepoint >= '0'
  1855. && event->code.codepoint <= '9')
  1856. {
  1857. int n = event->code.codepoint - '0';
  1858. if (app_goto_tab ((n == 0 ? 10 : n) - 1))
  1859. return true;
  1860. }
  1861. return false;
  1862. }
  1863. // --- Current tab -------------------------------------------------------------
  1864. static struct tab g_current_tab;
  1865. static void
  1866. current_tab_on_item_draw (size_t item_index, struct row_buffer *buffer,
  1867. int width)
  1868. {
  1869. // TODO: configurable output, maybe dynamically sized columns
  1870. int length_len = 1 /*separator */ + 2 /* h */ + 3 /* m */+ 3 /* s */;
  1871. compact_map_t map = item_list_get (&g.playlist, item_index);
  1872. const char *artist = compact_map_find (map, "artist");
  1873. const char *title = compact_map_find (map, "title");
  1874. chtype attrs = (int) item_index == g.song ? A_BOLD : 0;
  1875. if (artist && title)
  1876. row_buffer_append_args (buffer,
  1877. artist, attrs, " - ", attrs, title, attrs, NULL);
  1878. else
  1879. row_buffer_append (buffer, compact_map_find (map, "file"), attrs);
  1880. row_buffer_align (buffer, width - length_len, attrs);
  1881. char *s = NULL;
  1882. unsigned long n;
  1883. const char *time = compact_map_find (map, "time");
  1884. if (!time || !xstrtoul (&n, time, 10) || !(s = app_time_string (n)))
  1885. s = xstrdup ("?");
  1886. char *right_aligned = xstrdup_printf ("%*s", length_len, s);
  1887. row_buffer_append (buffer, right_aligned, attrs);
  1888. free (right_aligned);
  1889. free (s);
  1890. }
  1891. static void
  1892. mpd_on_move_response (const struct mpd_response *response,
  1893. const struct strv *data, void *user_data)
  1894. {
  1895. (void) data;
  1896. *(bool *) user_data = false;
  1897. if (!response->success)
  1898. print_error ("%s: %s", "command failed", response->message_text);
  1899. }
  1900. static void
  1901. current_tab_move (int from, int to)
  1902. {
  1903. compact_map_t map;
  1904. const char *id;
  1905. if (!(map = item_list_get (&g.playlist, from))
  1906. || !(id = compact_map_find (map, "id")))
  1907. return;
  1908. char *target_str = xstrdup_printf ("%d", to);
  1909. mpd_client_send_command (&g.client, "moveid", id, target_str, NULL);
  1910. free (target_str);
  1911. }
  1912. static bool
  1913. current_tab_move_selection (int diff)
  1914. {
  1915. static bool already_moving;
  1916. if (already_moving || diff == 0)
  1917. return true;
  1918. struct mpd_client *c = &g.client;
  1919. if (c->state != MPD_CONNECTED)
  1920. return false;
  1921. struct tab *tab = &g_current_tab;
  1922. struct tab_range range = tab_selection_range (tab);
  1923. if (range.from + diff < 0
  1924. || range.upto + diff >= (int) tab->item_count)
  1925. return false;
  1926. mpd_client_list_begin (c);
  1927. if (diff < 0)
  1928. for (int i = range.from; i <= range.upto; i++)
  1929. current_tab_move (i, i + diff);
  1930. else
  1931. for (int i = range.upto; i >= range.from; i--)
  1932. current_tab_move (i, i + diff);
  1933. mpd_client_list_end (c);
  1934. mpd_client_add_task (c, mpd_on_move_response, &already_moving);
  1935. mpd_client_idle (c, 0);
  1936. return already_moving = true;
  1937. }
  1938. static bool
  1939. current_tab_on_action (enum action action)
  1940. {
  1941. struct tab *tab = &g_current_tab;
  1942. compact_map_t map = item_list_get (&g.playlist, tab->item_selected);
  1943. switch (action)
  1944. {
  1945. const char *id;
  1946. case ACTION_MOVE_UP:
  1947. return current_tab_move_selection (-1);
  1948. case ACTION_MOVE_DOWN:
  1949. return current_tab_move_selection (+1);
  1950. case ACTION_CHOOSE:
  1951. tab->item_mark = -1;
  1952. return map && (id = compact_map_find (map, "id"))
  1953. && MPD_SIMPLE ("playid", id);
  1954. case ACTION_DELETE:
  1955. {
  1956. struct mpd_client *c = &g.client;
  1957. struct tab_range range = tab_selection_range (tab);
  1958. if (range.from < 0 || c->state != MPD_CONNECTED)
  1959. return false;
  1960. mpd_client_list_begin (c);
  1961. for (int i = range.from; i <= range.upto; i++)
  1962. {
  1963. if ((map = item_list_get (&g.playlist, i))
  1964. && (id = compact_map_find (map, "id")))
  1965. mpd_client_send_command (c, "deleteid", id, NULL);
  1966. }
  1967. mpd_client_list_end (c);
  1968. mpd_client_add_task (c, mpd_on_simple_response, NULL);
  1969. mpd_client_idle (c, 0);
  1970. return true;
  1971. }
  1972. default:
  1973. return false;
  1974. }
  1975. }
  1976. static void
  1977. current_tab_update (void)
  1978. {
  1979. g_current_tab.item_count = g.playlist.len;
  1980. g_current_tab.item_mark =
  1981. MIN ((int) g.playlist.len - 1, g_current_tab.item_mark);
  1982. app_invalidate ();
  1983. }
  1984. static struct tab *
  1985. current_tab_init (void)
  1986. {
  1987. struct tab *super = &g_current_tab;
  1988. tab_init (super, "Current");
  1989. super->can_multiselect = true;
  1990. super->on_action = current_tab_on_action;
  1991. super->on_item_draw = current_tab_on_item_draw;
  1992. return super;
  1993. }
  1994. // --- Library tab -------------------------------------------------------------
  1995. struct library_level
  1996. {
  1997. LIST_HEADER (struct library_level)
  1998. int item_top; ///< Stored state
  1999. int item_selected; ///< Stored state
  2000. char path[]; ///< Path of the level
  2001. };
  2002. static struct
  2003. {
  2004. struct tab super; ///< Parent class
  2005. struct str path; ///< Current path
  2006. struct strv items; ///< Current items (type, name, path)
  2007. struct library_level *above; ///< Upper levels
  2008. bool searching; ///< Search mode is active
  2009. }
  2010. g_library_tab;
  2011. enum
  2012. {
  2013. // This list is also ordered by ASCII and important for sorting
  2014. LIBRARY_ROOT = '/', ///< Root entry
  2015. LIBRARY_UP = '^', ///< Upper directory
  2016. LIBRARY_DIR = 'd', ///< Directory
  2017. LIBRARY_FILE = 'f' ///< File
  2018. };
  2019. struct library_tab_item
  2020. {
  2021. int type; ///< Type of the item
  2022. const char *name; ///< Visible name
  2023. const char *path; ///< MPD path
  2024. };
  2025. static void
  2026. library_tab_add (int type, const char *name, const char *path)
  2027. {
  2028. strv_append_owned (&g_library_tab.items,
  2029. xstrdup_printf ("%c%s%c%s", type, name, 0, path));
  2030. }
  2031. static struct library_tab_item
  2032. library_tab_resolve (const char *raw)
  2033. {
  2034. struct library_tab_item item;
  2035. item.type = *raw++;
  2036. item.name = raw;
  2037. item.path = strchr (raw, '\0') + 1;
  2038. return item;
  2039. }
  2040. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  2041. static void
  2042. library_tab_on_item_draw (size_t item_index, struct row_buffer *buffer,
  2043. int width)
  2044. {
  2045. (void) width;
  2046. hard_assert (item_index < g_library_tab.items.len);
  2047. struct library_tab_item x =
  2048. library_tab_resolve (g_library_tab.items.vector[item_index]);
  2049. const char *prefix, *name;
  2050. switch (x.type)
  2051. {
  2052. case LIBRARY_ROOT: prefix = "/"; name = ""; break;
  2053. case LIBRARY_UP: prefix = "/"; name = ".."; break;
  2054. case LIBRARY_DIR: prefix = "/"; name = x.name; break;
  2055. case LIBRARY_FILE: prefix = " "; name = x.name; break;
  2056. default: hard_assert (!"invalid item type");
  2057. }
  2058. chtype attrs = x.type != LIBRARY_FILE ? APP_ATTR (DIRECTORY) : 0;
  2059. row_buffer_append_args (buffer, prefix, attrs, name, attrs, NULL);
  2060. }
  2061. static char
  2062. library_tab_header_type (const char *key)
  2063. {
  2064. if (!strcasecmp_ascii (key, "file")) return LIBRARY_FILE;
  2065. if (!strcasecmp_ascii (key, "directory")) return LIBRARY_DIR;
  2066. return 0;
  2067. }
  2068. static void
  2069. library_tab_chunk (char type, const char *path, struct str_map *map)
  2070. {
  2071. const char *artist = str_map_find (map, "artist");
  2072. const char *title = str_map_find (map, "title");
  2073. char *name = (artist && title)
  2074. ? xstrdup_printf ("%s - %s", artist, title)
  2075. : xstrdup (xbasename (path));
  2076. library_tab_add (type, name, path);
  2077. free (name);
  2078. }
  2079. static int
  2080. library_tab_compare (char **a, char **b)
  2081. {
  2082. struct library_tab_item xa = library_tab_resolve (*a);
  2083. struct library_tab_item xb = library_tab_resolve (*b);
  2084. if (xa.type != xb.type)
  2085. return xa.type - xb.type;
  2086. return app_casecmp ((uint8_t *) xa.path, (uint8_t *) xb.path);
  2087. }
  2088. static char *
  2089. library_tab_parent (void)
  2090. {
  2091. struct str *path = &g_library_tab.path;
  2092. if (!path->len)
  2093. return NULL;
  2094. char *last_slash;
  2095. if ((last_slash = strrchr (path->str, '/')))
  2096. return xstrndup (path->str, last_slash - path->str);
  2097. return xstrdup ("");
  2098. }
  2099. static bool
  2100. library_tab_is_above (const char *above, const char *subdir)
  2101. {
  2102. size_t above_len = strlen (above);
  2103. if (strncmp (above, subdir, above_len))
  2104. return false;
  2105. // The root is an empty string and is above anything other than itself
  2106. return subdir[above_len] == '/' || (*subdir && !*above);
  2107. }
  2108. static void
  2109. library_tab_change_level (const char *new_path)
  2110. {
  2111. struct str *path = &g_library_tab.path;
  2112. if (!strcmp (path->str, new_path))
  2113. return;
  2114. struct library_level *above;
  2115. if (library_tab_is_above (path->str, new_path))
  2116. {
  2117. above = xcalloc (1, sizeof *above + path->len + 1);
  2118. above->item_top = g_library_tab.super.item_top;
  2119. above->item_selected = g_library_tab.super.item_selected;
  2120. memcpy (above->path, path->str, path->len);
  2121. LIST_PREPEND (g_library_tab.above, above);
  2122. // Select the ".." entry to reflect Norton Commander
  2123. g_library_tab.super.item_top = 0;
  2124. g_library_tab.super.item_selected = 1;
  2125. }
  2126. else while ((above = g_library_tab.above)
  2127. && !library_tab_is_above (above->path, new_path))
  2128. {
  2129. if (!strcmp (above->path, new_path))
  2130. {
  2131. g_library_tab.super.item_top = above->item_top;
  2132. g_library_tab.super.item_selected = above->item_selected;
  2133. }
  2134. g_library_tab.above = above->next;
  2135. free (above);
  2136. }
  2137. str_reset (path);
  2138. str_append (path, new_path);
  2139. free (g_library_tab.super.header);
  2140. g_library_tab.super.header = NULL;
  2141. g_library_tab.super.item_mark = -1;
  2142. if (path->len)
  2143. g_library_tab.super.header = xstrdup_printf ("/%s", path->str);
  2144. }
  2145. static void
  2146. library_tab_load_data (const struct strv *data)
  2147. {
  2148. strv_reset (&g_library_tab.items);
  2149. char *parent = library_tab_parent ();
  2150. if (parent)
  2151. {
  2152. library_tab_add (LIBRARY_ROOT, "", "");
  2153. library_tab_add (LIBRARY_UP, "", parent);
  2154. free (parent);
  2155. }
  2156. struct str_map map = str_map_make (NULL);
  2157. map.key_xfrm = tolower_ascii_strxfrm;
  2158. char *key, *value, type;
  2159. for (size_t i = data->len; i--; )
  2160. if (!(key = mpd_parse_kv (data->vector[i], &value)))
  2161. continue;
  2162. else if (!(type = library_tab_header_type (key)))
  2163. str_map_set (&map, key, value);
  2164. else
  2165. {
  2166. library_tab_chunk (type, value, &map);
  2167. str_map_clear (&map);
  2168. }
  2169. str_map_free (&map);
  2170. struct strv *items = &g_library_tab.items;
  2171. qsort (items->vector, items->len, sizeof *items->vector,
  2172. (int (*) (const void *, const void *)) library_tab_compare);
  2173. g_library_tab.super.item_count = items->len;
  2174. // XXX: this unmarks even if just the database updates
  2175. g_library_tab.super.item_mark = -1;
  2176. // Don't force the selection visible when there's no need to touch it
  2177. if (g_library_tab.super.item_selected >= (int) items->len)
  2178. app_move_selection (0);
  2179. app_invalidate ();
  2180. }
  2181. static void
  2182. library_tab_on_data (const struct mpd_response *response,
  2183. const struct strv *data, void *user_data)
  2184. {
  2185. char *new_path = user_data;
  2186. if (!response->success)
  2187. {
  2188. print_error ("cannot read directory: %s", response->message_text);
  2189. free (new_path);
  2190. return;
  2191. }
  2192. g_library_tab.searching = false;
  2193. library_tab_change_level (new_path);
  2194. free (new_path);
  2195. library_tab_load_data (data);
  2196. }
  2197. static void
  2198. library_tab_reload (const char *new_path)
  2199. {
  2200. if (!new_path && g_library_tab.searching)
  2201. return; // TODO: perhaps we should call search_on_changed()
  2202. char *path = new_path
  2203. ? xstrdup (new_path)
  2204. : xstrdup (g_library_tab.path.str);
  2205. struct mpd_client *c = &g.client;
  2206. mpd_client_send_command (c, "lsinfo", *path ? path : "/", NULL);
  2207. mpd_client_add_task (c, library_tab_on_data, path);
  2208. mpd_client_idle (c, 0);
  2209. }
  2210. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  2211. static void
  2212. library_tab_on_search_data (const struct mpd_response *response,
  2213. const struct strv *data, void *user_data)
  2214. {
  2215. (void) user_data;
  2216. if (!g_library_tab.searching)
  2217. return;
  2218. if (!response->success)
  2219. {
  2220. print_error ("cannot search: %s", response->message_text);
  2221. return;
  2222. }
  2223. library_tab_load_data (data);
  2224. }
  2225. static void
  2226. search_on_changed (void)
  2227. {
  2228. struct mpd_client *c = &g.client;
  2229. size_t len;
  2230. char *u8 = (char *) u32_to_u8 (g.editor.line, g.editor.len + 1, NULL, &len);
  2231. mpd_client_send_command (c, "search", "any", u8, NULL);
  2232. free (u8);
  2233. mpd_client_add_task (c, library_tab_on_search_data, NULL);
  2234. mpd_client_idle (c, 0);
  2235. }
  2236. static void
  2237. search_on_end (bool confirmed)
  2238. {
  2239. if (!confirmed)
  2240. library_tab_reload (g_library_tab.above->path);
  2241. }
  2242. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  2243. static bool
  2244. library_tab_is_range_playable (struct tab_range range)
  2245. {
  2246. for (int i = range.from; i <= range.upto; i++)
  2247. {
  2248. struct library_tab_item x =
  2249. library_tab_resolve (g_library_tab.items.vector[i]);
  2250. if (x.type == LIBRARY_DIR || x.type == LIBRARY_FILE)
  2251. return true;
  2252. }
  2253. return false;
  2254. }
  2255. static bool
  2256. library_tab_on_action (enum action action)
  2257. {
  2258. struct mpd_client *c = &g.client;
  2259. if (c->state != MPD_CONNECTED)
  2260. return false;
  2261. struct tab *tab = &g_library_tab.super;
  2262. struct tab_range range = tab_selection_range (tab);
  2263. if (range.from < 0)
  2264. return false;
  2265. struct library_tab_item x =
  2266. library_tab_resolve (g_library_tab.items.vector[range.from]);
  2267. switch (action)
  2268. {
  2269. case ACTION_CHOOSE:
  2270. // I can't think of a reasonable way of handling that
  2271. if (range.from != range.upto)
  2272. break;
  2273. switch (x.type)
  2274. {
  2275. case LIBRARY_ROOT:
  2276. case LIBRARY_UP:
  2277. case LIBRARY_DIR: library_tab_reload (x.path); break;
  2278. case LIBRARY_FILE: MPD_SIMPLE ("add", x.path); break;
  2279. default: hard_assert (!"invalid item type");
  2280. }
  2281. tab->item_mark = -1;
  2282. return true;
  2283. case ACTION_UP:
  2284. {
  2285. char *parent = library_tab_parent ();
  2286. if (parent)
  2287. {
  2288. library_tab_reload (parent);
  2289. free (parent);
  2290. }
  2291. return parent != NULL;
  2292. }
  2293. case ACTION_MPD_SEARCH:
  2294. {
  2295. line_editor_start (&g.editor, '/');
  2296. g.editor.on_changed = search_on_changed;
  2297. g.editor.on_end = search_on_end;
  2298. // We just need to be deeper but not match anything real,
  2299. // in order to keep the rest of the codebase functional as-is
  2300. if (!g_library_tab.searching)
  2301. {
  2302. char *fake_subdir = xstrdup_printf ("%s/", g_library_tab.path.str);
  2303. library_tab_change_level (fake_subdir);
  2304. free (fake_subdir);
  2305. }
  2306. free (tab->header);
  2307. tab->header = xstrdup_printf ("Global search");
  2308. g_library_tab.searching = true;
  2309. // Since we've already changed the header, empty the list,
  2310. // although to be consistent we should also ask to search for "",
  2311. // which dumps the database
  2312. struct strv empty = strv_make ();
  2313. library_tab_load_data (&empty);
  2314. strv_free (&empty);
  2315. app_invalidate ();
  2316. return true;
  2317. }
  2318. case ACTION_MPD_ADD:
  2319. if (!library_tab_is_range_playable (range))
  2320. break;
  2321. for (int i = range.from; i <= range.upto; i++)
  2322. {
  2323. struct library_tab_item x =
  2324. library_tab_resolve (g_library_tab.items.vector[i]);
  2325. if (x.type == LIBRARY_DIR || x.type == LIBRARY_FILE)
  2326. MPD_SIMPLE ("add", x.path);
  2327. }
  2328. tab->item_mark = -1;
  2329. return true;
  2330. case ACTION_MPD_REPLACE:
  2331. if (!library_tab_is_range_playable (range))
  2332. break;
  2333. // Clears the playlist (which stops playback), add what user wanted
  2334. // to replace it with, and eventually restore playback;
  2335. // I can't think of a reliable alternative that omits the "play"
  2336. mpd_client_list_begin (c);
  2337. mpd_client_send_command (c, "clear", NULL);
  2338. for (int i = range.from; i <= range.upto; i++)
  2339. {
  2340. struct library_tab_item x =
  2341. library_tab_resolve (g_library_tab.items.vector[i]);
  2342. if (x.type == LIBRARY_DIR || x.type == LIBRARY_FILE)
  2343. mpd_client_send_command (c, "add", x.path, NULL);
  2344. }
  2345. if (g.state == PLAYER_PLAYING)
  2346. mpd_client_send_command (c, "play", NULL);
  2347. mpd_client_list_end (c);
  2348. mpd_client_add_task (c, mpd_on_simple_response, NULL);
  2349. mpd_client_idle (c, 0);
  2350. tab->item_mark = -1;
  2351. return true;
  2352. default:
  2353. break;
  2354. }
  2355. return false;
  2356. }
  2357. static struct tab *
  2358. library_tab_init (void)
  2359. {
  2360. g_library_tab.path = str_make ();
  2361. g_library_tab.items = strv_make ();
  2362. struct tab *super = &g_library_tab.super;
  2363. tab_init (super, "Library");
  2364. super->can_multiselect = true;
  2365. super->on_action = library_tab_on_action;
  2366. super->on_item_draw = library_tab_on_item_draw;
  2367. return super;
  2368. }
  2369. // --- Streams -----------------------------------------------------------------
  2370. // MPD can only parse m3u8 playlists, and only when it feels like doing so
  2371. struct stream_tab_task
  2372. {
  2373. struct poller_curl_task curl; ///< Superclass
  2374. struct str data; ///< Downloaded data
  2375. bool polling; ///< Still downloading
  2376. bool replace; ///< Should playlist be replaced?
  2377. };
  2378. static bool
  2379. is_content_type (const char *content_type,
  2380. const char *expected_type, const char *expected_subtype)
  2381. {
  2382. char *type = NULL, *subtype = NULL;
  2383. bool result = http_parse_media_type (content_type, &type, &subtype, NULL)
  2384. && !strcasecmp_ascii (type, expected_type)
  2385. && !strcasecmp_ascii (subtype, expected_subtype);
  2386. free (type);
  2387. free (subtype);
  2388. return result;
  2389. }
  2390. static void
  2391. streams_tab_filter (char *line, regex_t *re, struct strv *out)
  2392. {
  2393. regmatch_t groups[2];
  2394. if (regexec (re, line, 2, groups, 0) == REG_NOMATCH)
  2395. return;
  2396. // It may happen that playlist files contain useless, invalid quotes,
  2397. // let's be liberal in what we accept
  2398. regoff_t start = groups[1].rm_so, end = groups[1].rm_eo;
  2399. while (end > start + 1 && line[start] == '"' && line[end - 1] == '"')
  2400. {
  2401. start++;
  2402. end--;
  2403. }
  2404. char *target = xstrndup (line + start, end - start);
  2405. if (utf8_validate (target, end - start))
  2406. strv_append_owned (out, target);
  2407. else
  2408. {
  2409. strv_append_owned (out, latin1_to_utf8 (target));
  2410. free (target);
  2411. }
  2412. }
  2413. static void
  2414. streams_tab_parse_playlist (const char *playlist, const char *content_type,
  2415. struct strv *out)
  2416. {
  2417. // We accept a lot of very broken stuff because this is the real world
  2418. struct strv lines = strv_make ();
  2419. cstr_split (playlist, "\r\n", true, &lines);
  2420. // Since this excludes '"', it should even work for XMLs (w/o entities)
  2421. const char *extract_re =
  2422. "(https?://([][a-z0-9._~:/?#@!$&'()*+,;=-]|%[a-f0-9]{2})+)";
  2423. if ((lines.len && !strcasecmp_ascii (lines.vector[0], "[playlist]"))
  2424. || (content_type && is_content_type (content_type, "audio", "x-scpls")))
  2425. extract_re = "^File[^=]*=(.+)";
  2426. else if ((lines.len && !strcasecmp_ascii (lines.vector[0], "#EXTM3U"))
  2427. || (content_type && is_content_type (content_type, "audio", "x-mpegurl")))
  2428. extract_re = "^([^#].*)";
  2429. regex_t *re = regex_compile (extract_re, REG_EXTENDED, NULL);
  2430. hard_assert (re != NULL);
  2431. for (size_t i = 0; i < lines.len; i++)
  2432. streams_tab_filter (lines.vector[i], re, out);
  2433. regex_free (re);
  2434. strv_free (&lines);
  2435. }
  2436. static bool
  2437. streams_tab_extract_links (struct str *data, const char *content_type,
  2438. struct strv *out)
  2439. {
  2440. // Since playlists are also "audio/*", this seems like a sane thing to do
  2441. for (size_t i = 0; i < data->len; i++)
  2442. {
  2443. uint8_t c = data->str[i];
  2444. if ((c < 32) & (c != '\t') & (c != '\r') & (c != '\n'))
  2445. return false;
  2446. }
  2447. streams_tab_parse_playlist (data->str, content_type, out);
  2448. return true;
  2449. }
  2450. static void
  2451. streams_tab_on_downloaded (CURLMsg *msg, struct poller_curl_task *task)
  2452. {
  2453. struct stream_tab_task *self =
  2454. CONTAINER_OF (task, struct stream_tab_task, curl);
  2455. self->polling = false;
  2456. if (msg->data.result
  2457. && msg->data.result != CURLE_WRITE_ERROR)
  2458. {
  2459. cstr_uncapitalize (self->curl.curl_error);
  2460. print_error ("%s", self->curl.curl_error);
  2461. return;
  2462. }
  2463. struct mpd_client *c = &g.client;
  2464. if (c->state != MPD_CONNECTED)
  2465. return;
  2466. CURL *easy = msg->easy_handle;
  2467. CURLcode res;
  2468. long code;
  2469. char *type, *uri;
  2470. if ((res = curl_easy_getinfo (easy, CURLINFO_RESPONSE_CODE, &code))
  2471. || (res = curl_easy_getinfo (easy, CURLINFO_CONTENT_TYPE, &type))
  2472. || (res = curl_easy_getinfo (easy, CURLINFO_EFFECTIVE_URL, &uri)))
  2473. {
  2474. print_error ("%s: %s",
  2475. "cURL info retrieval failed", curl_easy_strerror (res));
  2476. return;
  2477. }
  2478. // cURL is not willing to parse the ICY header, the code is zero then
  2479. if (code && code != 200)
  2480. {
  2481. print_error ("%s: %ld", "unexpected HTTP response", code);
  2482. return;
  2483. }
  2484. mpd_client_list_begin (c);
  2485. if (self->replace)
  2486. mpd_client_send_command (c, "clear", NULL);
  2487. struct strv links = strv_make ();
  2488. if (!streams_tab_extract_links (&self->data, type, &links))
  2489. strv_append (&links, uri);
  2490. for (size_t i = 0; i < links.len; i++)
  2491. mpd_client_send_command (c, "add", links.vector[i], NULL);
  2492. if (self->replace && g.state == PLAYER_PLAYING)
  2493. mpd_client_send_command (c, "play", NULL);
  2494. strv_free (&links);
  2495. mpd_client_list_end (c);
  2496. mpd_client_add_task (c, mpd_on_simple_response, NULL);
  2497. mpd_client_idle (c, 0);
  2498. }
  2499. static size_t
  2500. write_callback (char *ptr, size_t size, size_t nmemb, void *user_data)
  2501. {
  2502. struct str *buf = user_data;
  2503. str_append_data (buf, ptr, size * nmemb);
  2504. // Invoke CURLE_WRITE_ERROR when we've received enough data for a playlist
  2505. if (buf->len >= (1 << 16))
  2506. return 0;
  2507. return size * nmemb;
  2508. }
  2509. static bool
  2510. streams_tab_process (const char *uri, bool replace, struct error **e)
  2511. {
  2512. struct poller poller;
  2513. poller_init (&poller);
  2514. struct poller_curl pc;
  2515. hard_assert (poller_curl_init (&pc, &poller, NULL));
  2516. struct stream_tab_task task;
  2517. hard_assert (poller_curl_spawn (&task.curl, NULL));
  2518. CURL *easy = task.curl.easy;
  2519. task.data = str_make ();
  2520. task.replace = replace;
  2521. bool result = false;
  2522. CURLcode res;
  2523. if ((res = curl_easy_setopt (easy, CURLOPT_FOLLOWLOCATION, 1L))
  2524. || (res = curl_easy_setopt (easy, CURLOPT_NOPROGRESS, 1L))
  2525. // TODO: make the timeout a bit larger once we're asynchronous
  2526. || (res = curl_easy_setopt (easy, CURLOPT_TIMEOUT, 5L))
  2527. // Not checking anything, we just want some data, any data
  2528. || (res = curl_easy_setopt (easy, CURLOPT_SSL_VERIFYPEER, 0L))
  2529. || (res = curl_easy_setopt (easy, CURLOPT_SSL_VERIFYHOST, 0L))
  2530. || (res = curl_easy_setopt (easy, CURLOPT_URL, uri))
  2531. || (res = curl_easy_setopt (easy, CURLOPT_VERBOSE, (long) g_debug_mode))
  2532. || (res = curl_easy_setopt (easy, CURLOPT_DEBUGFUNCTION, print_curl_debug))
  2533. || (res = curl_easy_setopt (easy, CURLOPT_WRITEDATA, &task.data))
  2534. || (res = curl_easy_setopt (easy, CURLOPT_WRITEFUNCTION, write_callback)))
  2535. {
  2536. error_set (e, "%s: %s", "cURL setup failed", curl_easy_strerror (res));
  2537. goto error;
  2538. }
  2539. task.curl.on_done = streams_tab_on_downloaded;
  2540. hard_assert (poller_curl_add (&pc, task.curl.easy, NULL));
  2541. // TODO: don't run a subloop, run the task fully asynchronously
  2542. task.polling = true;
  2543. while (task.polling)
  2544. poller_run (&poller);
  2545. hard_assert (poller_curl_remove (&pc, task.curl.easy, NULL));
  2546. result = true;
  2547. error:
  2548. curl_easy_cleanup (task.curl.easy);
  2549. str_free (&task.data);
  2550. poller_curl_free (&pc);
  2551. poller_free (&poller);
  2552. return result;
  2553. }
  2554. static bool
  2555. streams_tab_on_action (enum action action)
  2556. {
  2557. struct tab *tab = g.active_tab;
  2558. if (tab->item_selected < 0 || !tab->item_count)
  2559. return false;
  2560. // For simplicity the URL is the string following the stream name
  2561. const char *uri = 1 + strchr (g.streams.vector[tab->item_selected], 0);
  2562. struct error *e = NULL;
  2563. switch (action)
  2564. {
  2565. case ACTION_MPD_REPLACE:
  2566. streams_tab_process (uri, true, &e);
  2567. break;
  2568. case ACTION_CHOOSE:
  2569. case ACTION_MPD_ADD:
  2570. streams_tab_process (uri, false, &e);
  2571. break;
  2572. default:
  2573. return false;
  2574. }
  2575. if (e)
  2576. {
  2577. print_error ("%s", e->message);
  2578. error_free (e);
  2579. }
  2580. return true;
  2581. }
  2582. static void
  2583. streams_tab_on_item_draw (size_t item_index, struct row_buffer *buffer,
  2584. int width)
  2585. {
  2586. (void) width;
  2587. row_buffer_append (buffer, g.streams.vector[item_index], 0);
  2588. }
  2589. static struct tab *
  2590. streams_tab_init (void)
  2591. {
  2592. static struct tab super;
  2593. tab_init (&super, "Streams");
  2594. super.on_action = streams_tab_on_action;
  2595. super.on_item_draw = streams_tab_on_item_draw;
  2596. super.item_count = g.streams.len;
  2597. return &super;
  2598. }
  2599. // --- Info tab ----------------------------------------------------------------
  2600. static struct
  2601. {
  2602. struct tab super; ///< Parent class
  2603. struct strv keys; ///< Data keys
  2604. struct strv values; ///< Data values
  2605. }
  2606. g_info_tab;
  2607. static void
  2608. info_tab_on_item_draw (size_t item_index, struct row_buffer *buffer, int width)
  2609. {
  2610. (void) width;
  2611. // It looks like we could do with a generic list structure that just
  2612. // stores formatted row_buffers. Let's see for other tabs:
  2613. // - Current -- unusable, has dynamic column alignment
  2614. // - Library -- could work for the "icons"
  2615. // - Streams -- useless
  2616. // - Debug -- it'd take up considerably more space
  2617. // However so far we're only showing show key-value pairs.
  2618. row_buffer_append_args (buffer,
  2619. g_info_tab.keys.vector[item_index], A_BOLD, ":", A_BOLD, NULL);
  2620. row_buffer_space (buffer, 8 - buffer->total_width, 0);
  2621. row_buffer_append (buffer, g_info_tab.values.vector[item_index], 0);
  2622. }
  2623. static void
  2624. info_tab_add (compact_map_t data, const char *field)
  2625. {
  2626. const char *value = compact_map_find (data, field);
  2627. if (!value) value = "";
  2628. strv_append (&g_info_tab.keys, field);
  2629. strv_append (&g_info_tab.values, value);
  2630. g_info_tab.super.item_count++;
  2631. }
  2632. static void
  2633. info_tab_update (void)
  2634. {
  2635. strv_reset (&g_info_tab.keys);
  2636. strv_reset (&g_info_tab.values);
  2637. g_info_tab.super.item_count = 0;
  2638. compact_map_t map;
  2639. if ((map = item_list_get (&g.playlist, g.song)))
  2640. {
  2641. info_tab_add (map, "Title");
  2642. info_tab_add (map, "Artist");
  2643. info_tab_add (map, "Album");
  2644. info_tab_add (map, "Track");
  2645. info_tab_add (map, "Genre");
  2646. // Yes, it is "file", but this is also for display
  2647. info_tab_add (map, "File");
  2648. }
  2649. }
  2650. static struct tab *
  2651. info_tab_init (void)
  2652. {
  2653. g_info_tab.keys = strv_make ();
  2654. g_info_tab.values = strv_make ();
  2655. struct tab *super = &g_info_tab.super;
  2656. tab_init (super, "Info");
  2657. super->on_item_draw = info_tab_on_item_draw;
  2658. return super;
  2659. }
  2660. // --- Help tab ----------------------------------------------------------------
  2661. static struct
  2662. {
  2663. struct tab super; ///< Parent class
  2664. ARRAY (enum action, actions) ///< Actions for content
  2665. struct strv lines; ///< Visible content
  2666. }
  2667. g_help_tab;
  2668. static bool
  2669. help_tab_on_action (enum action action)
  2670. {
  2671. struct tab *tab = &g_help_tab.super;
  2672. if (tab->item_selected < 0
  2673. || tab->item_selected >= (int) g_help_tab.actions_len
  2674. || action != ACTION_CHOOSE)
  2675. return false;
  2676. action = g_help_tab.actions[tab->item_selected];
  2677. return action != ACTION_NONE
  2678. && action != ACTION_CHOOSE // avoid recursion
  2679. && app_process_action (action);
  2680. }
  2681. static void
  2682. help_tab_strfkey (const termo_key_t *key, struct strv *out)
  2683. {
  2684. // For display purposes, this is highly desirable
  2685. int flags = termo_get_flags (g.tk);
  2686. termo_set_flags (g.tk, flags | TERMO_FLAG_SPACESYMBOL);
  2687. termo_key_t fixed = *key;
  2688. termo_canonicalise (g.tk, &fixed);
  2689. termo_set_flags (g.tk, flags);
  2690. char buf[16];
  2691. termo_strfkey_utf8 (g.tk, buf, sizeof buf, &fixed, TERMO_FORMAT_ALTISMETA);
  2692. strv_append (out, buf);
  2693. }
  2694. static void
  2695. help_tab_assign_action (enum action action)
  2696. {
  2697. hard_assert (g_help_tab.lines.len > g_help_tab.actions_len);
  2698. size_t to_push = g_help_tab.lines.len - g_help_tab.actions_len;
  2699. ARRAY_RESERVE (g_help_tab.actions, to_push);
  2700. for (size_t i = 1; i < to_push; i++)
  2701. g_help_tab.actions[g_help_tab.actions_len++] = ACTION_NONE;
  2702. g_help_tab.actions[g_help_tab.actions_len++] = action;
  2703. }
  2704. static void
  2705. help_tab_group (struct binding *keys, size_t len, struct strv *out,
  2706. bool bound[ACTION_COUNT])
  2707. {
  2708. for (enum action i = 0; i < ACTION_COUNT; i++)
  2709. {
  2710. struct strv ass = strv_make ();
  2711. for (size_t k = 0; k < len; k++)
  2712. if (keys[k].action == i)
  2713. help_tab_strfkey (&keys[k].decoded, &ass);
  2714. if (ass.len)
  2715. {
  2716. char *joined = strv_join (&ass, ", ");
  2717. strv_append_owned (out, xstrdup_printf
  2718. (" %-30s %s", g_actions[i].description, joined));
  2719. free (joined);
  2720. bound[i] = true;
  2721. help_tab_assign_action (i);
  2722. }
  2723. strv_free (&ass);
  2724. }
  2725. }
  2726. static void
  2727. help_tab_unbound (struct strv *out, bool bound[ACTION_COUNT])
  2728. {
  2729. for (enum action i = 0; i < ACTION_COUNT; i++)
  2730. if (!bound[i])
  2731. {
  2732. strv_append_owned (out,
  2733. xstrdup_printf (" %-30s", g_actions[i].description));
  2734. help_tab_assign_action (i);
  2735. }
  2736. }
  2737. static void
  2738. help_tab_on_item_draw (size_t item_index, struct row_buffer *buffer, int width)
  2739. {
  2740. (void) width;
  2741. hard_assert (item_index < g_help_tab.lines.len);
  2742. const char *line = g_help_tab.lines.vector[item_index];
  2743. row_buffer_append (buffer, line, *line == ' ' ? 0 : A_BOLD);
  2744. }
  2745. static struct tab *
  2746. help_tab_init (void)
  2747. {
  2748. ARRAY_INIT (g_help_tab.actions);
  2749. struct strv *lines = &g_help_tab.lines;
  2750. *lines = strv_make ();
  2751. bool bound[ACTION_COUNT] = { [ACTION_NONE] = true };
  2752. strv_append (lines, "Normal mode actions");
  2753. help_tab_group (g_normal_keys, g_normal_keys_len, lines, bound);
  2754. strv_append (lines, "");
  2755. strv_append (lines, "Editor mode actions");
  2756. help_tab_group (g_editor_keys, g_editor_keys_len, lines, bound);
  2757. strv_append (lines, "");
  2758. bool have_unbound = false;
  2759. for (enum action i = 0; i < ACTION_COUNT; i++)
  2760. if (!bound[i])
  2761. have_unbound = true;
  2762. if (have_unbound)
  2763. {
  2764. strv_append (lines, "Unbound actions");
  2765. help_tab_unbound (lines, bound);
  2766. strv_append (lines, "");
  2767. }
  2768. struct tab *super = &g_help_tab.super;
  2769. tab_init (super, "Help");
  2770. super->on_action = help_tab_on_action;
  2771. super->on_item_draw = help_tab_on_item_draw;
  2772. super->item_count = lines->len;
  2773. return super;
  2774. }
  2775. // --- Debug tab ---------------------------------------------------------------
  2776. struct debug_item
  2777. {
  2778. char *text; ///< Logged line
  2779. int64_t timestamp; ///< Timestamp
  2780. chtype attrs; ///< Line attributes
  2781. };
  2782. static struct
  2783. {
  2784. struct tab super; ///< Parent class
  2785. ARRAY (struct debug_item, items) ///< Items
  2786. bool active; ///< The tab is present
  2787. }
  2788. g_debug_tab;
  2789. static void
  2790. debug_tab_on_item_draw (size_t item_index, struct row_buffer *buffer, int width)
  2791. {
  2792. hard_assert (item_index < g_debug_tab.items_len);
  2793. struct debug_item *item = &g_debug_tab.items[item_index];
  2794. char buf[16];
  2795. struct tm tm;
  2796. time_t when = item->timestamp / 1000;
  2797. strftime (buf, sizeof buf, "%T", localtime_r (&when, &tm));
  2798. char *prefix = xstrdup_printf
  2799. ("%s.%03d", buf, (int) (item->timestamp % 1000));
  2800. row_buffer_append (buffer, prefix, 0);
  2801. free (prefix);
  2802. row_buffer_append (buffer, " ", item->attrs);
  2803. row_buffer_append (buffer, item->text, item->attrs);
  2804. // We override the formatting including colors -- do it for the whole line
  2805. row_buffer_align (buffer, width, item->attrs);
  2806. }
  2807. static void
  2808. debug_tab_push (char *message, chtype attrs)
  2809. {
  2810. ARRAY_RESERVE (g_debug_tab.items, 1);
  2811. struct debug_item *item = &g_debug_tab.items[g_debug_tab.items_len++];
  2812. g_debug_tab.super.item_count = g_debug_tab.items_len;
  2813. item->text = message;
  2814. item->attrs = attrs;
  2815. item->timestamp = clock_msec (CLOCK_REALTIME);
  2816. app_invalidate ();
  2817. }
  2818. static struct tab *
  2819. debug_tab_init (void)
  2820. {
  2821. ARRAY_INIT (g_debug_tab.items);
  2822. g_debug_tab.active = true;
  2823. struct tab *super = &g_debug_tab.super;
  2824. tab_init (super, "Debug");
  2825. super->on_item_draw = debug_tab_on_item_draw;
  2826. return super;
  2827. }
  2828. // --- MPD interface -----------------------------------------------------------
  2829. static void
  2830. mpd_read_time (const char *value, int *sec, int *optional_msec)
  2831. {
  2832. if (!value)
  2833. return;
  2834. char *end, *period = strchr (value, '.');
  2835. if (optional_msec && period)
  2836. {
  2837. unsigned long n = strtoul (period + 1, &end, 10);
  2838. if (*end)
  2839. return;
  2840. *optional_msec = MIN (INT_MAX, n);
  2841. }
  2842. unsigned long n = strtoul (value, &end, 10);
  2843. if (end == period || !*end)
  2844. *sec = MIN (INT_MAX, n);
  2845. }
  2846. static void
  2847. mpd_update_playlist_time (void)
  2848. {
  2849. g.playlist_time = 0;
  2850. // It would also be possible to retrieve this from "stats" -> "playtime"
  2851. unsigned long n;
  2852. for (size_t i = 0; i < g.playlist.len; i++)
  2853. {
  2854. compact_map_t map = item_list_get (&g.playlist, i);
  2855. const char *time = compact_map_find (map, "time");
  2856. if (time && xstrtoul (&n, time, 10))
  2857. g.playlist_time += n;
  2858. }
  2859. }
  2860. static void
  2861. mpd_update_playback_state (void)
  2862. {
  2863. struct str_map *map = &g.playback_info;
  2864. g.song_elapsed = g.song_duration = g.volume = g.song = -1;
  2865. uint32_t last_playlist_version = g.playlist_version;
  2866. g.playlist_version = 0;
  2867. const char *state;
  2868. g.state = PLAYER_STOPPED;
  2869. if ((state = str_map_find (map, "state")))
  2870. {
  2871. if (!strcmp (state, "play")) g.state = PLAYER_PLAYING;
  2872. if (!strcmp (state, "pause")) g.state = PLAYER_PAUSED;
  2873. }
  2874. // Values in "time" are always rounded. "elapsed", introduced in MPD 0.16,
  2875. // is in millisecond precision and "duration" as well, starting with 0.20.
  2876. // Prefer the more precise values but use what we have.
  2877. const char *time = str_map_find (map, "time");
  2878. const char *elapsed = str_map_find (map, "elapsed");
  2879. const char *duration = str_map_find (map, "duration");
  2880. struct strv fields = strv_make ();
  2881. if (time)
  2882. {
  2883. cstr_split (time, ":", false, &fields);
  2884. if (fields.len >= 1 && !elapsed) elapsed = fields.vector[0];
  2885. if (fields.len >= 2 && !duration) duration = fields.vector[1];
  2886. }
  2887. int msec_past_second = 0;
  2888. mpd_read_time (elapsed, &g.song_elapsed, &msec_past_second);
  2889. mpd_read_time (duration, &g.song_duration, NULL);
  2890. strv_free (&fields);
  2891. // We could also just poll the server each half a second but let's not
  2892. poller_timer_reset (&g.elapsed_event);
  2893. if (g.state == PLAYER_PLAYING)
  2894. {
  2895. poller_timer_set (&g.elapsed_event, 1000 - msec_past_second);
  2896. g.elapsed_since = clock_msec (CLOCK_BEST) - msec_past_second;
  2897. }
  2898. // The server sends -1 when nothing is being played right now
  2899. unsigned long n;
  2900. if (xstrtoul_map (map, "volume", &n)) g.volume = n;
  2901. if (xstrtoul_map (map, "playlist", &n)) g.playlist_version = n;
  2902. if (xstrtoul_map (map, "song", &n)) g.song = n;
  2903. if (g.playlist_version != last_playlist_version)
  2904. mpd_update_playlist_time ();
  2905. app_invalidate ();
  2906. }
  2907. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  2908. static void
  2909. mpd_process_info_data (const struct strv *data)
  2910. {
  2911. struct str_map *map = &g.playback_info;
  2912. // First there's the status, followed by playlist items chunked by "file"
  2913. unsigned long n; char *key, *value;
  2914. for (size_t i = 0; i < data->len - 1 && data->vector[i]; i++)
  2915. {
  2916. if (!(key = mpd_parse_kv (data->vector[i], &value)))
  2917. continue;
  2918. if (!strcasecmp_ascii (key, "playlistlength")
  2919. && xstrtoul (&n, value, 10))
  2920. item_list_resize (&g.playlist, n);
  2921. str_map_set (map, key, xstrdup (value));
  2922. }
  2923. // It's much better to process the playlist from the back
  2924. struct str_map item = str_map_make (NULL);
  2925. item.key_xfrm = tolower_ascii_strxfrm;
  2926. for (size_t i = data->len - 1; i-- && data->vector[i]; )
  2927. {
  2928. if (!(key = mpd_parse_kv (data->vector[i], &value)))
  2929. continue;
  2930. str_map_set (&item, key, value);
  2931. if (!strcasecmp_ascii (key, "file"))
  2932. {
  2933. if (xstrtoul_map (&item, "pos", &n))
  2934. item_list_set (&g.playlist, n, &item);
  2935. str_map_clear (&item);
  2936. }
  2937. }
  2938. str_map_free (&item);
  2939. }
  2940. /// Find a song by its id in the current playlist. Expensive, rarely called.
  2941. static ssize_t
  2942. mpd_find_pos_of_id (const char *desired_id)
  2943. {
  2944. compact_map_t map;
  2945. const char *id;
  2946. for (size_t i = 0; i < g.playlist.len; i++)
  2947. {
  2948. if ((map = item_list_get (&g.playlist, i))
  2949. && (id = compact_map_find (map, "id"))
  2950. && !strcmp (id, desired_id))
  2951. return i;
  2952. }
  2953. return -1;
  2954. }
  2955. static char *
  2956. mpd_id_of_pos (int pos)
  2957. {
  2958. compact_map_t map = item_list_get (&g.playlist, pos);
  2959. return map ? compact_map_find (map, "id") : NULL;
  2960. }
  2961. static void
  2962. mpd_process_info (const struct strv *data)
  2963. {
  2964. int *selected = &g_current_tab.item_selected;
  2965. int *marked = &g_current_tab.item_mark;
  2966. char *prev_sel_id = mpd_id_of_pos (*selected);
  2967. char *prev_mark_id = mpd_id_of_pos (*marked);
  2968. if (prev_sel_id) prev_sel_id = xstrdup (prev_sel_id);
  2969. if (prev_mark_id) prev_mark_id = xstrdup (prev_mark_id);
  2970. mpd_process_info_data (data);
  2971. const char *sel_id = mpd_id_of_pos (*selected);
  2972. const char *mark_id = mpd_id_of_pos (*marked);
  2973. if (prev_mark_id && (!mark_id || strcmp (prev_mark_id, mark_id)))
  2974. *marked = mpd_find_pos_of_id (prev_mark_id);
  2975. if (prev_sel_id && (!sel_id || strcmp (prev_sel_id, sel_id)))
  2976. {
  2977. if ((*selected = mpd_find_pos_of_id (prev_sel_id)) < 0)
  2978. *marked = -1;
  2979. app_move_selection (0);
  2980. }
  2981. free (prev_sel_id);
  2982. free (prev_mark_id);
  2983. }
  2984. static void
  2985. mpd_on_info_response (const struct mpd_response *response,
  2986. const struct strv *data, void *user_data)
  2987. {
  2988. (void) user_data;
  2989. // TODO: preset an error player state?
  2990. str_map_clear (&g.playback_info);
  2991. if (!response->success)
  2992. print_error ("%s: %s",
  2993. "MPD status retrieval failed", response->message_text);
  2994. else if (!data->len)
  2995. print_debug ("empty MPD status response");
  2996. else
  2997. mpd_process_info (data);
  2998. mpd_update_playback_state ();
  2999. current_tab_update ();
  3000. info_tab_update ();
  3001. }
  3002. static void
  3003. mpd_on_tick (void *user_data)
  3004. {
  3005. (void) user_data;
  3006. int64_t diff_msec = clock_msec (CLOCK_BEST) - g.elapsed_since;
  3007. int elapsed_sec = diff_msec / 1000;
  3008. int elapsed_msec = diff_msec % 1000;
  3009. g.song_elapsed += elapsed_sec;
  3010. g.elapsed_since += elapsed_sec * 1000;
  3011. poller_timer_set (&g.elapsed_event, 1000 - elapsed_msec);
  3012. app_invalidate ();
  3013. }
  3014. static void
  3015. mpd_request_info (void)
  3016. {
  3017. struct mpd_client *c = &g.client;
  3018. mpd_client_list_ok_begin (c);
  3019. mpd_client_send_command (c, "status", NULL);
  3020. char *last_version = xstrdup_printf ("%" PRIu32, g.playlist_version);
  3021. mpd_client_send_command (c, "plchanges", last_version, NULL);
  3022. free (last_version);
  3023. mpd_client_list_end (c);
  3024. mpd_client_add_task (c, mpd_on_info_response, NULL);
  3025. mpd_client_idle (c, 0);
  3026. }
  3027. static void
  3028. mpd_on_events (unsigned subsystems, void *user_data)
  3029. {
  3030. (void) user_data;
  3031. struct mpd_client *c = &g.client;
  3032. if (subsystems & MPD_SUBSYSTEM_DATABASE)
  3033. library_tab_reload (NULL);
  3034. if (subsystems & (MPD_SUBSYSTEM_PLAYER | MPD_SUBSYSTEM_OPTIONS
  3035. | MPD_SUBSYSTEM_PLAYLIST | MPD_SUBSYSTEM_MIXER | MPD_SUBSYSTEM_UPDATE))
  3036. mpd_request_info ();
  3037. else
  3038. mpd_client_idle (c, 0);
  3039. }
  3040. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  3041. static void
  3042. mpd_queue_reconnect (void)
  3043. {
  3044. poller_timer_set (&g.connect_event, 5 * 1000);
  3045. }
  3046. static void
  3047. mpd_on_password_response (const struct mpd_response *response,
  3048. const struct strv *data, void *user_data)
  3049. {
  3050. (void) data;
  3051. (void) user_data;
  3052. struct mpd_client *c = &g.client;
  3053. if (response->success)
  3054. {
  3055. mpd_request_info ();
  3056. library_tab_reload (NULL);
  3057. }
  3058. else
  3059. {
  3060. print_error ("%s: %s",
  3061. "MPD authentication failed", response->message_text);
  3062. mpd_client_send_command (c, "close", NULL);
  3063. }
  3064. }
  3065. static void
  3066. mpd_on_connected (void *user_data)
  3067. {
  3068. (void) user_data;
  3069. struct mpd_client *c = &g.client;
  3070. const char *password =
  3071. get_config_string (g.config.root, "settings.password");
  3072. if (password)
  3073. {
  3074. mpd_client_send_command (c, "password", password, NULL);
  3075. mpd_client_add_task (c, mpd_on_password_response, NULL);
  3076. }
  3077. else
  3078. {
  3079. mpd_request_info ();
  3080. library_tab_reload (NULL);
  3081. }
  3082. }
  3083. static void
  3084. mpd_on_failure (void *user_data)
  3085. {
  3086. (void) user_data;
  3087. // This is also triggered both by a failed connect and a clean disconnect
  3088. print_debug ("connection to MPD failed");
  3089. mpd_queue_reconnect ();
  3090. str_map_clear (&g.playback_info);
  3091. item_list_resize (&g.playlist, 0);
  3092. mpd_update_playback_state ();
  3093. current_tab_update ();
  3094. info_tab_update ();
  3095. }
  3096. static void
  3097. mpd_on_io_hook (void *user_data, bool outgoing, const char *line)
  3098. {
  3099. (void) user_data;
  3100. if (outgoing)
  3101. debug_tab_push (xstrdup_printf ("<< %s", line), APP_ATTR (OUTGOING));
  3102. else
  3103. debug_tab_push (xstrdup_printf (">> %s", line), APP_ATTR (INCOMING));
  3104. }
  3105. static void
  3106. app_on_reconnect (void *user_data)
  3107. {
  3108. (void) user_data;
  3109. struct mpd_client *c = &g.client;
  3110. c->on_failure = mpd_on_failure;
  3111. c->on_connected = mpd_on_connected;
  3112. c->on_event = mpd_on_events;
  3113. if (g_debug_mode)
  3114. c->on_io_hook = mpd_on_io_hook;
  3115. // We accept hostname/IPv4/IPv6 in pseudo-URL format, as well as sockets
  3116. char *address = xstrdup (get_config_string (g.config.root,
  3117. "settings.address")), *p = address, *host = address, *port = "6600";
  3118. // Unwrap IPv6 addresses in format_host_port_pair() format
  3119. char *right_bracket = strchr (p, ']');
  3120. if (p[0] == '[' && right_bracket)
  3121. {
  3122. *right_bracket = '\0';
  3123. host = p + 1;
  3124. p = right_bracket + 1;
  3125. }
  3126. char *colon = strchr (p, ':');
  3127. if (colon)
  3128. {
  3129. *colon = '\0';
  3130. port = colon + 1;
  3131. }
  3132. struct error *e = NULL;
  3133. if (!mpd_client_connect (c, host, port, &e))
  3134. {
  3135. print_error ("%s: %s", "cannot connect to MPD", e->message);
  3136. error_free (e);
  3137. mpd_queue_reconnect ();
  3138. }
  3139. free (address);
  3140. }
  3141. // --- Signals -----------------------------------------------------------------
  3142. static int g_signal_pipe[2]; ///< A pipe used to signal... signals
  3143. /// Program termination has been requested by a signal
  3144. static volatile sig_atomic_t g_termination_requested;
  3145. /// The window has changed in size
  3146. static volatile sig_atomic_t g_winch_received;
  3147. static void
  3148. signals_postpone_handling (char id)
  3149. {
  3150. int original_errno = errno;
  3151. if (write (g_signal_pipe[1], &id, 1) == -1)
  3152. soft_assert (errno == EAGAIN);
  3153. errno = original_errno;
  3154. }
  3155. static void
  3156. signals_superhandler (int signum)
  3157. {
  3158. switch (signum)
  3159. {
  3160. case SIGWINCH:
  3161. g_winch_received = true;
  3162. signals_postpone_handling ('w');
  3163. break;
  3164. case SIGINT:
  3165. case SIGTERM:
  3166. g_termination_requested = true;
  3167. signals_postpone_handling ('t');
  3168. break;
  3169. default:
  3170. hard_assert (!"unhandled signal");
  3171. }
  3172. }
  3173. static void
  3174. signals_setup_handlers (void)
  3175. {
  3176. if (pipe (g_signal_pipe) == -1)
  3177. exit_fatal ("%s: %s", "pipe", strerror (errno));
  3178. set_cloexec (g_signal_pipe[0]);
  3179. set_cloexec (g_signal_pipe[1]);
  3180. // So that the pipe cannot overflow; it would make write() block within
  3181. // the signal handler, which is something we really don't want to happen.
  3182. // The same holds true for read().
  3183. set_blocking (g_signal_pipe[0], false);
  3184. set_blocking (g_signal_pipe[1], false);
  3185. signal (SIGPIPE, SIG_IGN);
  3186. struct sigaction sa;
  3187. sa.sa_flags = SA_RESTART;
  3188. sa.sa_handler = signals_superhandler;
  3189. sigemptyset (&sa.sa_mask);
  3190. if (sigaction (SIGWINCH, &sa, NULL) == -1
  3191. || sigaction (SIGINT, &sa, NULL) == -1
  3192. || sigaction (SIGTERM, &sa, NULL) == -1)
  3193. exit_fatal ("sigaction: %s", strerror (errno));
  3194. }
  3195. // --- Initialisation, event handling ------------------------------------------
  3196. static void
  3197. app_on_tty_event (termo_key_t *event, int64_t event_ts)
  3198. {
  3199. // Simple double click detection via release--press delay, only a bit
  3200. // complicated by the fact that we don't know what's being released
  3201. static termo_key_t last_event;
  3202. static int64_t last_event_ts;
  3203. static int last_button;
  3204. int y, x, button, y_last, x_last;
  3205. termo_mouse_event_t type, type_last;
  3206. if (termo_interpret_mouse (g.tk, event, &type, &button, &y, &x))
  3207. {
  3208. bool double_click = termo_interpret_mouse
  3209. (g.tk, &last_event, &type_last, NULL, &y_last, &x_last)
  3210. && event_ts - last_event_ts < 500
  3211. && type_last == TERMO_MOUSE_RELEASE && type == TERMO_MOUSE_PRESS
  3212. && y_last == y && x_last == x && last_button == button;
  3213. if (!app_process_mouse (type, y, x, button, double_click))
  3214. beep ();
  3215. // Prevent interpreting triple clicks as two double clicks
  3216. if (double_click)
  3217. last_button = 0;
  3218. else if (type == TERMO_MOUSE_PRESS)
  3219. last_button = button;
  3220. }
  3221. else if (!app_process_termo_event (event))
  3222. beep ();
  3223. last_event = *event;
  3224. last_event_ts = event_ts;
  3225. }
  3226. static void
  3227. app_on_tty_readable (const struct pollfd *fd, void *user_data)
  3228. {
  3229. (void) user_data;
  3230. if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
  3231. print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);
  3232. poller_timer_reset (&g.tk_timer);
  3233. termo_advisereadable (g.tk);
  3234. termo_key_t event;
  3235. int64_t event_ts = clock_msec (CLOCK_BEST);
  3236. termo_result_t res;
  3237. while ((res = termo_getkey (g.tk, &event)) == TERMO_RES_KEY)
  3238. app_on_tty_event (&event, event_ts);
  3239. if (res == TERMO_RES_AGAIN)
  3240. poller_timer_set (&g.tk_timer, termo_get_waittime (g.tk));
  3241. else if (res == TERMO_RES_ERROR || res == TERMO_RES_EOF)
  3242. app_quit ();
  3243. }
  3244. static void
  3245. app_on_key_timer (void *user_data)
  3246. {
  3247. (void) user_data;
  3248. termo_key_t event;
  3249. if (termo_getkey_force (g.tk, &event) == TERMO_RES_KEY)
  3250. if (!app_process_termo_event (&event))
  3251. beep ();
  3252. }
  3253. static void
  3254. app_on_signal_pipe_readable (const struct pollfd *fd, void *user_data)
  3255. {
  3256. (void) user_data;
  3257. char id = 0;
  3258. (void) read (fd->fd, &id, 1);
  3259. if (g_termination_requested && !g.quitting)
  3260. app_quit ();
  3261. if (g_winch_received)
  3262. {
  3263. g_winch_received = false;
  3264. update_curses_terminal_size ();
  3265. app_invalidate ();
  3266. }
  3267. }
  3268. static void
  3269. app_on_message_timer (void *user_data)
  3270. {
  3271. (void) user_data;
  3272. free (g.message);
  3273. g.message = NULL;
  3274. app_invalidate ();
  3275. }
  3276. static void
  3277. app_log_handler (void *user_data, const char *quote, const char *fmt,
  3278. va_list ap)
  3279. {
  3280. // We certainly don't want to end up in a possibly infinite recursion
  3281. static bool in_processing;
  3282. if (in_processing)
  3283. return;
  3284. in_processing = true;
  3285. struct str message = str_make ();
  3286. str_append (&message, quote);
  3287. str_append_vprintf (&message, fmt, ap);
  3288. // If the standard error output isn't redirected, try our best at showing
  3289. // the message to the user
  3290. if (!isatty (STDERR_FILENO))
  3291. fprintf (stderr, "%s\n", message.str);
  3292. else if (g_debug_tab.active)
  3293. debug_tab_push (str_steal (&message),
  3294. user_data == NULL ? 0 : g.attrs[(intptr_t) user_data].attrs);
  3295. else
  3296. {
  3297. free (g.message);
  3298. g.message = xstrdup (message.str);
  3299. app_invalidate ();
  3300. poller_timer_set (&g.message_timer, 5000);
  3301. }
  3302. str_free (&message);
  3303. in_processing = false;
  3304. }
  3305. static void
  3306. app_init_poller_events (void)
  3307. {
  3308. g.signal_event = poller_fd_make (&g.poller, g_signal_pipe[0]);
  3309. g.signal_event.dispatcher = app_on_signal_pipe_readable;
  3310. poller_fd_set (&g.signal_event, POLLIN);
  3311. g.tty_event = poller_fd_make (&g.poller, STDIN_FILENO);
  3312. g.tty_event.dispatcher = app_on_tty_readable;
  3313. poller_fd_set (&g.tty_event, POLLIN);
  3314. g.message_timer = poller_timer_make (&g.poller);
  3315. g.message_timer.dispatcher = app_on_message_timer;
  3316. g.tk_timer = poller_timer_make (&g.poller);
  3317. g.tk_timer.dispatcher = app_on_key_timer;
  3318. g.connect_event = poller_timer_make (&g.poller);
  3319. g.connect_event.dispatcher = app_on_reconnect;
  3320. poller_timer_set (&g.connect_event, 0);
  3321. g.elapsed_event = poller_timer_make (&g.poller);
  3322. g.elapsed_event.dispatcher = mpd_on_tick;
  3323. g.refresh_event = poller_idle_make (&g.poller);
  3324. g.refresh_event.dispatcher = app_on_refresh;
  3325. }
  3326. int
  3327. main (int argc, char *argv[])
  3328. {
  3329. static const struct opt opts[] =
  3330. {
  3331. { 'd', "debug", NULL, 0, "run in debug mode" },
  3332. { 'h', "help", NULL, 0, "display this help and exit" },
  3333. { 'V', "version", NULL, 0, "output version information and exit" },
  3334. { 0, NULL, NULL, 0, NULL }
  3335. };
  3336. struct opt_handler oh =
  3337. opt_handler_make (argc, argv, opts, NULL, "MPD client.");
  3338. int c;
  3339. while ((c = opt_handler_get (&oh)) != -1)
  3340. switch (c)
  3341. {
  3342. case 'd':
  3343. g_debug_mode = true;
  3344. break;
  3345. case 'h':
  3346. opt_handler_usage (&oh, stdout);
  3347. exit (EXIT_SUCCESS);
  3348. case 'V':
  3349. printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
  3350. exit (EXIT_SUCCESS);
  3351. default:
  3352. print_error ("wrong options");
  3353. opt_handler_usage (&oh, stderr);
  3354. exit (EXIT_FAILURE);
  3355. }
  3356. argc -= optind;
  3357. argv += optind;
  3358. if (argc)
  3359. {
  3360. opt_handler_usage (&oh, stderr);
  3361. exit (EXIT_FAILURE);
  3362. }
  3363. opt_handler_free (&oh);
  3364. // We only need to convert to and from the terminal encoding
  3365. if (!setlocale (LC_CTYPE, ""))
  3366. print_warning ("failed to set the locale");
  3367. app_init_context ();
  3368. app_load_configuration ();
  3369. app_init_terminal ();
  3370. signals_setup_handlers ();
  3371. app_init_poller_events ();
  3372. g_normal_keys = app_init_bindings ("normal",
  3373. g_normal_defaults, N_ELEMENTS (g_normal_defaults), &g_normal_keys_len);
  3374. g_editor_keys = app_init_bindings ("editor",
  3375. g_editor_defaults, N_ELEMENTS (g_editor_defaults), &g_editor_keys_len);
  3376. if (g_debug_mode)
  3377. app_prepend_tab (debug_tab_init ());
  3378. // Redirect all messages from liberty to a special tab so they're not lost
  3379. g_log_message_real = app_log_handler;
  3380. app_prepend_tab (info_tab_init ());
  3381. if (g.streams.len)
  3382. app_prepend_tab (streams_tab_init ());
  3383. app_prepend_tab (library_tab_init ());
  3384. app_prepend_tab (current_tab_init ());
  3385. app_switch_tab ((g.help_tab = help_tab_init ()));
  3386. g.polling = true;
  3387. while (g.polling)
  3388. poller_run (&g.poller);
  3389. endwin ();
  3390. g_log_message_real = log_message_stdio;
  3391. app_free_context ();
  3392. return 0;
  3393. }