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

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