diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/Makefile.am | 78 | ||||
-rw-r--r-- | src/command.c | 6 | ||||
-rw-r--r-- | src/command.h | 1 | ||||
-rw-r--r-- | src/conf.c | 18 | ||||
-rw-r--r-- | src/libmpdclient.c | 929 | ||||
-rw-r--r-- | src/libmpdclient.h | 150 | ||||
-rw-r--r-- | src/main.c | 19 | ||||
-rw-r--r-- | src/ncmpc.h | 5 | ||||
-rw-r--r-- | src/options.c | 2 | ||||
-rw-r--r-- | src/options.h | 4 | ||||
-rw-r--r-- | src/screen.c | 22 | ||||
-rw-r--r-- | src/screen.h | 6 | ||||
-rw-r--r-- | src/screen_help.c | 9 | ||||
-rw-r--r-- | src/screen_lyrics.c | 542 |
14 files changed, 1321 insertions, 470 deletions
diff --git a/src/Makefile.am b/src/Makefile.am index f68653731..3d3fd6ed6 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,27 +1,59 @@ -# +AM_CPPFLAGS = \ + $(GLIB_CFLAGS)\ + $(GTHREAD_CFLAGS)\ + $(libcurl_CFLAGS)\ + -DLOCALE_DIR=\""$(datadir)/locale"\"\ + -DSYSCONFDIR=\""$(sysconfdir)"\" + +ncmpc_headers = \ + libmpdclient.h\ + mpdclient.h\ + easy_download.h\ + options.h\ + conf.h\ + command.h\ + screen.h\ + screen_utils.h\ + list_window.h\ + colors.h\ + support.h\ + wreadln.h\ + strfsong.h\ + utils.h\ + ncmpc.h\ + screen_browse.h + # $Id$ -# bin_PROGRAMS = ncmpc -ncmpc_LDADD = $(GLIB_LIBS) - -AM_CPPFLAGS = $(GLIB_CFLAGS) -DLOCALE_DIR=\""$(datadir)/locale"\" -DSYSCONFDIR=\""$(sysconfdir)"\" - - -ncmpc_headers = libmpdclient.h mpdclient.h options.h conf.h command.h \ - screen.h screen_utils.h list_window.h colors.h support.h \ - wreadln.h strfsong.h utils.h ncmpc.h screen_browse.h - -ncmpc_SOURCES = libmpdclient.c main.c mpdclient.c options.c conf.c command.c \ - screen.c screen_utils.c screen_play.c screen_file.c \ - screen_artist.c screen_search.c screen_help.c \ - screen_keydef.c screen_clock.c \ - list_window.c colors.c support.c wreadln.c strfsong.c utils.c \ - $(ncmpc_headers) - - - - - - +ncmpc_SOURCES = \ + libmpdclient.c\ + main.c\ + mpdclient.c\ + options.c\ + conf.c\ + command.c\ + easy_download.c\ + screen.c\ + screen_utils.c\ + screen_play.c\ + screen_file.c\ + screen_artist.c\ + screen_search.c\ + screen_help.c\ + screen_lyrics.c\ + screen_keydef.c\ + screen_clock.c\ + list_window.c\ + colors.c\ + support.c\ + wreadln.c\ + strfsong.c\ + utils.c\ + $(ncmpc_headers) + +ncmpc_LDADD = \ + $(GLIB_LIBS)\ + $(GTHREAD_LIBS)\ + $(libcurl_LIBS) diff --git a/src/command.c b/src/command.c index f94481ccc..6766e2ac3 100644 --- a/src/command.c +++ b/src/command.c @@ -61,6 +61,7 @@ extern void screen_resize(void); #define F4 KEY_F(4) #define F5 KEY_F(5) #define F6 KEY_F(6) +#define F7 KEY_F(7) static command_definition_t cmds[] = @@ -187,6 +188,11 @@ static command_definition_t cmds[] = { {'6', F6, 0 }, 0, CMD_SCREEN_CLOCK, "screen-clock", N_("Clock screen") }, #endif +#ifdef ENABLE_LYRICS_SCREEN + { {'7', F7, 0 }, 0, CMD_SCREEN_LYRICS, "screen-lyrics", + N_("Lyrics screen") }, +#endif + { { -1, -1, -1 }, 0, CMD_NONE, NULL, NULL } }; diff --git a/src/command.h b/src/command.h index 9a8030284..6da0025c2 100644 --- a/src/command.h +++ b/src/command.h @@ -52,6 +52,7 @@ typedef enum CMD_SCREEN_KEYDEF, CMD_SCREEN_CLOCK, CMD_SCREEN_HELP, + CMD_SCREEN_LYRICS, CMD_QUIT } command_t; diff --git a/src/conf.c b/src/conf.c index f2c21ea05..2074a2638 100644 --- a/src/conf.c +++ b/src/conf.c @@ -65,6 +65,9 @@ #define CONF_SEEK_TIME "seek-time" #define CONF_SCREEN_LIST "screen-list" #define CONF_TIMEDISPLAY_TYPE "timedisplay-type" +#define CONF_HOST "host" +#define CONF_PORT "port" +#define CONF_LYRICS_TIMEOUT "lyrics-timeout" typedef enum { KEY_PARSER_UNKNOWN, @@ -559,6 +562,18 @@ read_rc_file(char *filename, options_t *options) D("\n"); #endif } + else if( !strcasecmp(CONF_HOST, name)) + { + options->host = get_format(value); + } + else if( !strcasecmp(CONF_PORT, name)) + { + options->port = atoi(get_format(value)); + } + else if( !strcasecmp(CONF_LYRICS_TIMEOUT, name)) + { + options->lyrics_timeout = atoi(get_format(value)); + } else { match_found = 0; @@ -681,6 +696,3 @@ read_configuration(options_t *options) return 0; } - - - diff --git a/src/libmpdclient.c b/src/libmpdclient.c index 3bbef181d..27bd9ad52 100644 --- a/src/libmpdclient.c +++ b/src/libmpdclient.c @@ -1,22 +1,22 @@ /* libmpdclient - (c)2003-2004 by Warren Dukes (shank@mercury.chem.pitt.edu) + (c)2003-2006 by Warren Dukes (warren.dukes@gmail.com) This project's homepage is: http://www.musicpd.org - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + - Neither the name of the Music Player Daemon nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR @@ -28,35 +28,210 @@ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - #include "libmpdclient.h" #include <errno.h> #include <sys/types.h> -#include <sys/socket.h> -#include <netdb.h> #include <stdio.h> #include <sys/param.h> - - #include <string.h> -#include <strings.h> -#include <netinet/in.h> -#include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> -#include <stdarg.h> + +#ifdef WIN32 +# include <ws2tcpip.h> +# include <winsock.h> +#else +# include <netinet/in.h> +# include <arpa/inet.h> +# include <sys/socket.h> +# include <netdb.h> +#endif #ifndef MSG_DONTWAIT -#define MSG_DONTWAIT 0 +# define MSG_DONTWAIT 0 +#endif + +#ifndef MPD_NO_GAI +# ifdef AI_ADDRCONFIG +# define MPD_HAVE_GAI +# endif +#endif + +#define COMMAND_LIST 1 +#define COMMAND_LIST_OK 2 + +#ifdef WIN32 +# define SELECT_ERRNO_IGNORE (errno == WSAEINTR || errno == WSAEINPROGRESS) +# define SENDRECV_ERRNO_IGNORE SELECT_ERRNO_IGNORE +#else +# define SELECT_ERRNO_IGNORE (errno == EINTR) +# define SENDRECV_ERRNO_IGNORE (errno == EINTR || errno == EAGAIN) +# define winsock_dll_error(c) 0 +# define closesocket(s) close(s) +# define WSACleanup() do { /* nothing */ } while (0) #endif -#define COMMAND_LIST 1 -#define COMMAND_LIST_OK 2 +#ifdef WIN32 +static int winsock_dll_error(mpd_Connection *connection) +{ + WSADATA wsaData; + if ((WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0 || + LOBYTE(wsaData.wVersion) != 2 || + HIBYTE(wsaData.wVersion) != 2 ) { + snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, + "Could not find usable WinSock DLL."); + connection->error = MPD_ERROR_SYSTEM; + return 1; + } + return 0; +} + +static int do_connect_fail(mpd_Connection *connection, + const struct sockaddr *serv_addr, int addrlen) +{ + int iMode = 1; /* 0 = blocking, else non-blocking */ + ioctlsocket(connection->sock, FIONBIO, (u_long FAR*) &iMode); + return (connect(connection->sock,serv_addr,addrlen) == SOCKET_ERROR + && WSAGetLastError() != WSAEWOULDBLOCK); +} +#else /* !WIN32 (sane operating systems) */ +static int do_connect_fail(mpd_Connection *connection, + const struct sockaddr *serv_addr, int addrlen) +{ + int flags = fcntl(connection->sock, F_GETFL, 0); + fcntl(connection->sock, F_SETFL, flags | O_NONBLOCK); + return (connect(connection->sock,serv_addr,addrlen)<0 && + errno!=EINPROGRESS); +} +#endif /* !WIN32 */ + +#ifdef MPD_HAVE_GAI +static int mpd_connect(mpd_Connection * connection, const char * host, int port, + float timeout) +{ + int error; + char service[20]; + struct addrinfo hints; + struct addrinfo *res = NULL; + struct addrinfo *addrinfo = NULL; + + /** + * Setup hints + */ + hints.ai_flags = AI_ADDRCONFIG; + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + hints.ai_addrlen = 0; + hints.ai_addr = NULL; + hints.ai_canonname = NULL; + hints.ai_next = NULL; + + snprintf(service, sizeof(service), "%d", port); + + error = getaddrinfo(host, service, &hints, &addrinfo); + + if (error) { + snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, + "host \"%s\" not found: %s",host, gai_strerror(error)); + connection->error = MPD_ERROR_UNKHOST; + return -1; + } + + for (res = addrinfo; res; res = res->ai_next) { + /* create socket */ + connection->sock = socket(res->ai_family, SOCK_STREAM, res->ai_protocol); + if (connection->sock < 0) { + snprintf(connection->errorStr, MPD_BUFFER_MAX_LENGTH, + "problems creating socket: %s", + strerror(errno)); + connection->error = MPD_ERROR_SYSTEM; + freeaddrinfo(addrinfo); + return -1; + } + + mpd_setConnectionTimeout(connection,timeout); + + /* connect stuff */ + if (do_connect_fail(connection, res->ai_addr, res->ai_addrlen)) { + /* try the next address family */ + closesocket(connection->sock); + connection->sock = -1; + continue; + } + } + freeaddrinfo(addrinfo); + + if (connection->sock < 0) { + snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, + "problems connecting to \"%s\" on port" + " %i: %s",host,port, strerror(errno)); + connection->error = MPD_ERROR_CONNPORT; + + return -1; + } + + return 0; +} +#else /* !MPD_HAVE_GAI */ +static int mpd_connect(mpd_Connection * connection, const char * host, int port, + float timeout) +{ + struct hostent * he; + struct sockaddr * dest; + int destlen; + struct sockaddr_in sin; + + if(!(he=gethostbyname(host))) { + snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, + "host \"%s\" not found",host); + connection->error = MPD_ERROR_UNKHOST; + return -1; + } + + memset(&sin,0,sizeof(struct sockaddr_in)); + /*dest.sin_family = he->h_addrtype;*/ + sin.sin_family = AF_INET; + sin.sin_port = htons(port); + + switch(he->h_addrtype) { + case AF_INET: + memcpy((char *)&sin.sin_addr.s_addr,(char *)he->h_addr, + he->h_length); + dest = (struct sockaddr *)&sin; + destlen = sizeof(struct sockaddr_in); + break; + default: + strcpy(connection->errorStr,"address type is not IPv4\n"); + connection->error = MPD_ERROR_SYSTEM; + return -1; + break; + } + + if((connection->sock = socket(dest->sa_family,SOCK_STREAM,0))<0) { + strcpy(connection->errorStr,"problems creating socket"); + connection->error = MPD_ERROR_SYSTEM; + return -1; + } + + mpd_setConnectionTimeout(connection,timeout); + + /* connect stuff */ + if (do_connect_fail(connection, dest, destlen)) { + snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, + "problems connecting to \"%s\" on port" + " %i",host,port); + connection->error = MPD_ERROR_CONNPORT; + return -1; + } + + return 0; +} +#endif /* !MPD_HAVE_GAI */ char * mpdTagItemKeys[MPD_TAG_NUM_OF_ITEM_TYPES] = { @@ -70,26 +245,16 @@ char * mpdTagItemKeys[MPD_TAG_NUM_OF_ITEM_TYPES] = "Composer", "Performer", "Comment", + "Disc", "filename" }; - static char * mpd_sanitizeArg(const char * arg) { size_t i; char * ret; register const char *c; register char *rc; - - /* - unsigned int count = 0; - - c = arg; - for(i = strlen(arg); i != 0; --i) { - if(*c=='"' || *c=='\\') count++; - c++; - } - ret = malloc(strlen(arg)+count+1); - */ + /* instead of counting in that loop above, just * use a bit more memory and half running time */ @@ -106,38 +271,69 @@ static char * mpd_sanitizeArg(const char * arg) { return ret; } -mpd_ReturnElement * mpd_newReturnElement(const char * name, const char * value) +static mpd_ReturnElement * mpd_newReturnElement(const char * name, const char * value) { mpd_ReturnElement * ret = malloc(sizeof(mpd_ReturnElement)); - ret->name = (char *)strdup(name); - ret->value = (char *)strdup(value); + ret->name = strdup(name); + ret->value = strdup(value); return ret; } -void mpd_freeReturnElement(mpd_ReturnElement * re) { +static void mpd_freeReturnElement(mpd_ReturnElement * re) { free(re->name); free(re->value); free(re); } void mpd_setConnectionTimeout(mpd_Connection * connection, float timeout) { - connection->timeout.tv_sec = (int)timeout; - connection->timeout.tv_usec = (int)(timeout*1e6 - - connection->timeout.tv_sec*1000000+0.5); + connection->timeout.tv_sec = (int)timeout; + connection->timeout.tv_usec = (int)(timeout*1e6 - + connection->timeout.tv_sec*1000000 + + 0.5); +} + +static int mpd_parseWelcome(mpd_Connection * connection, const char * host, int port, + char * rt, char * output) { + char * tmp; + char * test; + int i; + + if(strncmp(output,MPD_WELCOME_MESSAGE,strlen(MPD_WELCOME_MESSAGE))) { + snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, + "mpd not running on port %i on host \"%s\"", + port,host); + connection->error = MPD_ERROR_NOTMPD; + return 1; + } + + tmp = &output[strlen(MPD_WELCOME_MESSAGE)]; + + for(i=0;i<3;i++) { + if(tmp) connection->version[i] = strtol(tmp,&test,10); + + if (!tmp || (test[0] != '.' && test[0] != '\0')) { + snprintf(connection->errorStr, + MPD_BUFFER_MAX_LENGTH, + "error parsing version number at " + "\"%s\"", + &output[strlen(MPD_WELCOME_MESSAGE)]); + connection->error = MPD_ERROR_NOTMPD; + return 1; + } + tmp = ++test; + } + + return 0; } mpd_Connection * mpd_newConnection(const char * host, int port, float timeout) { int err; - int error; char * rt; - char * output; - char service[20]; + char * output = NULL; mpd_Connection * connection = malloc(sizeof(mpd_Connection)); struct timeval tv; - struct addrinfo hints, *res; - struct addrinfo *addrinfo = NULL; fd_set fds; strcpy(connection->buffer,""); connection->buflen = 0; @@ -149,67 +345,13 @@ mpd_Connection * mpd_newConnection(const char * host, int port, float timeout) { connection->listOks = 0; connection->doneListOk = 0; connection->returnElement = NULL; + connection->request = NULL; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = PF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - - snprintf(service, sizeof(service), "%d", port); - - error = getaddrinfo(host, service, &hints, &addrinfo); - - if (error) { - snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, - "host \"%s\" not found: %s",host, gai_strerror(error)); - connection->error = MPD_ERROR_UNKHOST; + if (winsock_dll_error(connection)) return connection; - } - - for (res = addrinfo; res; res = res->ai_next) { - /* create socket */ - - if((connection->sock = socket(res->ai_family,SOCK_STREAM,res->ai_protocol))<0) { - strcpy(connection->errorStr,"problems creating socket"); - connection->error = MPD_ERROR_SYSTEM; - freeaddrinfo(addrinfo); - return connection; - } - - mpd_setConnectionTimeout(connection,timeout); - - /* connect stuff */ - { -#ifdef WIN32 - int iMode = 1; // 0 = blocking, else non-blocking - ioctlsocket(connection->sock, FIONBIO, (u_long FAR*) &iMode); - if(connect(connection->sock,res->ai_addr,res->ai_addrlen) == SOCKET_ERROR - && WSAGetLastError() != WSAEWOULDBLOCK) -#else - int flags = fcntl(connection->sock, F_GETFL, 0); - fcntl(connection->sock, F_SETFL, flags | O_NONBLOCK); - - if(connect(connection->sock,res->ai_addr,res->ai_addrlen)<0 && - errno!=EINPROGRESS) -#endif - { - /* try the next address family */ - close(connection->sock); - connection->sock = 0; - continue; - } - } - } - - freeaddrinfo(addrinfo); - - if (connection->sock == 0) { - snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, - "problems connecting to \"%s\" on port" - " %i: %s",host,port, strerror(errno)); - connection->error = MPD_ERROR_CONNPORT; + if (mpd_connect(connection, host, port, timeout) < 0) return connection; - } while(!(rt = strstr(connection->buffer,"\n"))) { tv.tv_sec = connection->timeout.tv_sec; @@ -219,38 +361,33 @@ mpd_Connection * mpd_newConnection(const char * host, int port, float timeout) { if((err = select(connection->sock+1,&fds,NULL,NULL,&tv)) == 1) { int readed; readed = recv(connection->sock, - &(connection->buffer[connection->buflen]), - MPD_BUFFER_MAX_LENGTH-connection->buflen,0); + &(connection->buffer[connection->buflen]), + MPD_BUFFER_MAX_LENGTH-connection->buflen,0); if(readed<=0) { snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, - "problems getting a response from" - " \"%s\" on port %i : %s",host, - port, strerror(errno)); + "problems getting a response from" + " \"%s\" on port %i : %s",host, + port, strerror(errno)); connection->error = MPD_ERROR_NORESPONSE; return connection; } connection->buflen+=readed; connection->buffer[connection->buflen] = '\0'; - tv.tv_sec = connection->timeout.tv_sec; - tv.tv_usec = connection->timeout.tv_usec; } else if(err<0) { - switch(errno) { - case EINTR: + if (SELECT_ERRNO_IGNORE) continue; - default: - snprintf(connection->errorStr, + snprintf(connection->errorStr, MPD_BUFFER_MAX_LENGTH, "problems connecting to \"%s\" on port" - " %i",host,port); - connection->error = MPD_ERROR_CONNPORT; - return connection; - } + " %i",host,port); + connection->error = MPD_ERROR_CONNPORT; + return connection; } else { snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, - "timeout in attempting to get a response from" - " \"%s\" on port %i",host,port); + "timeout in attempting to get a response from" + " \"%s\" on port %i",host,port); connection->error = MPD_ERROR_NORESPONSE; return connection; } @@ -261,55 +398,10 @@ mpd_Connection * mpd_newConnection(const char * host, int port, float timeout) { strcpy(connection->buffer,rt+1); connection->buflen = strlen(connection->buffer); - if(strncmp(output,MPD_WELCOME_MESSAGE,strlen(MPD_WELCOME_MESSAGE))) { - free(output); - snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, - "mpd not running on port %i on host \"%s\"", - port,host); - connection->error = MPD_ERROR_NOTMPD; - return connection; - } - - { - char * test; - char * version[3]; - char * tmp = &output[strlen(MPD_WELCOME_MESSAGE)]; - char * search = "."; - int i; - - for(i=0;i<3;i++) { - char * tok; - if(i==3) search = " "; - version[i] = strtok_r(tmp,search,&tok); - if(!version[i]) { - free(output); - snprintf(connection->errorStr, - MPD_BUFFER_MAX_LENGTH, - "error parsing version number at " - "\"%s\"", - &output[strlen(MPD_WELCOME_MESSAGE)]); - connection->error = MPD_ERROR_NOTMPD; - return connection; - } - connection->version[i] = strtol(version[i],&test,10); - if(version[i]==test || *test!='\0') { - free(output); - snprintf(connection->errorStr, - MPD_BUFFER_MAX_LENGTH, - "error parsing version number at " - "\"%s\"", - &output[strlen(MPD_WELCOME_MESSAGE)]); - connection->error = MPD_ERROR_NOTMPD; - return connection; - } - tmp = NULL; - } - } + if(mpd_parseWelcome(connection,host,port,rt,output) == 0) connection->doneProcessing = 1; free(output); - connection->doneProcessing = 1; - return connection; } @@ -319,12 +411,14 @@ void mpd_clearError(mpd_Connection * connection) { } void mpd_closeConnection(mpd_Connection * connection) { - close(connection->sock); + closesocket(connection->sock); if(connection->returnElement) free(connection->returnElement); + if(connection->request) free(connection->request); free(connection); + WSACleanup(); } -void mpd_executeCommand(mpd_Connection * connection, char * command) { +static void mpd_executeCommand(mpd_Connection * connection, char * command) { int ret; struct timeval tv; fd_set fds; @@ -344,20 +438,14 @@ void mpd_executeCommand(mpd_Connection * connection, char * command) { tv.tv_sec = connection->timeout.tv_sec; tv.tv_usec = connection->timeout.tv_usec; - while((ret = select(connection->sock+1,NULL,&fds,NULL,&tv)==1) || - (ret==-1 && errno==EINTR)) { - ret = send(connection->sock,commandPtr,commandLen, -#ifdef WIN32 - ioctlsocket(connection->sock, commandLen, commandPtr)); -#endif -#ifndef WIN32 - MSG_DONTWAIT); -#endif + while((ret = select(connection->sock+1,NULL,&fds,NULL,&tv)==1) || + (ret==-1 && SELECT_ERRNO_IGNORE)) { + ret = send(connection->sock,commandPtr,commandLen,MSG_DONTWAIT); if(ret<=0) { - if(ret==EAGAIN || ret==EINTR) continue; + if (SENDRECV_ERRNO_IGNORE) continue; snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, - "problems giving command \"%s\"",command); + "problems giving command \"%s\"",command); connection->error = MPD_ERROR_SENDING; return; } @@ -372,7 +460,7 @@ void mpd_executeCommand(mpd_Connection * connection, char * command) { if(commandLen>0) { perror(""); snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, - "timeout sending command \"%s\"",command); + "timeout sending command \"%s\"",command); connection->error = MPD_ERROR_TIMEOUT; return; } @@ -383,7 +471,7 @@ void mpd_executeCommand(mpd_Connection * connection, char * command) { } } -void mpd_getNextReturnElement(mpd_Connection * connection) { +static void mpd_getNextReturnElement(mpd_Connection * connection) { char * output = NULL; char * rt = NULL; char * name = NULL; @@ -394,12 +482,13 @@ void mpd_getNextReturnElement(mpd_Connection * connection) { int readed; char * bufferCheck = NULL; int err; + int pos; if(connection->returnElement) mpd_freeReturnElement(connection->returnElement); connection->returnElement = NULL; if(connection->doneProcessing || (connection->listOks && - connection->doneListOk)) + connection->doneListOk)) { strcpy(connection->errorStr,"already done processing current command"); connection->error = 1; @@ -407,7 +496,7 @@ void mpd_getNextReturnElement(mpd_Connection * connection) { } bufferCheck = connection->buffer+connection->bufstart; - while(connection->bufstart>=connection->buflen || + while(connection->bufstart>=connection->buflen || !(rt = strchr(bufferCheck,'\n'))) { if(connection->buflen>=MPD_BUFFER_MAX_LENGTH) { memmove(connection->buffer, @@ -432,22 +521,15 @@ void mpd_getNextReturnElement(mpd_Connection * connection) { FD_SET(connection->sock,&fds); if((err = select(connection->sock+1,&fds,NULL,NULL,&tv) == 1)) { readed = recv(connection->sock, - connection->buffer+connection->buflen, - MPD_BUFFER_MAX_LENGTH-connection->buflen, -#ifdef WIN32 - ioctlsocket(connection->sock, - commandLen, - commandPtr)); -#endif -#ifndef WIN32 - MSG_DONTWAIT); -#endif - if(readed<0 && (errno==EAGAIN || errno==EINTR)) { + connection->buffer+connection->buflen, + MPD_BUFFER_MAX_LENGTH-connection->buflen, + MSG_DONTWAIT); + if(readed<0 && SENDRECV_ERRNO_IGNORE) { continue; } if(readed<=0) { strcpy(connection->errorStr,"connection" - " closed"); + " closed"); connection->error = MPD_ERROR_CONNCLOSED; connection->doneProcessing = 1; connection->doneListOk = 0; @@ -456,7 +538,7 @@ void mpd_getNextReturnElement(mpd_Connection * connection) { connection->buflen+=readed; connection->buffer[connection->buflen] = '\0'; } - else if(err<0 && errno==EINTR) continue; + else if(err<0 && SELECT_ERRNO_IGNORE) continue; else { strcpy(connection->errorStr,"connection timeout"); connection->error = MPD_ERROR_TIMEOUT; @@ -483,7 +565,7 @@ void mpd_getNextReturnElement(mpd_Connection * connection) { if(strcmp(output, "list_OK") == 0) { if(!connection->listOks) { - strcpy(connection->errorStr, + strcpy(connection->errorStr, "got an unexpected list_OK"); connection->error = 1; } @@ -498,7 +580,7 @@ void mpd_getNextReturnElement(mpd_Connection * connection) { char * test; char * needle; int val; - + strcpy(connection->errorStr, output); connection->error = MPD_ERROR_ACK; connection->errorCode = MPD_ACK_ERROR_UNK; @@ -517,19 +599,19 @@ void mpd_getNextReturnElement(mpd_Connection * connection) { return; } - name = strtok_r(output,":",&tok); - if(name && (value = strtok_r(NULL,"",&tok)) && value[0]==' ') { + tok = strchr(output, ':'); + if (!tok) return; + pos = tok - output; + value = ++tok; + name = output; + name[pos] = '\0'; + + if(value[0]==' ') { connection->returnElement = mpd_newReturnElement(name,&(value[1])); } else { - if(!name || !value) { - snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, - "error parsing: %s",output); - } - else { - snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, + snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, "error parsing: %s:%s",name,value); - } connection->errorStr[MPD_BUFFER_MAX_LENGTH] = '\0'; connection->error = 1; } @@ -542,9 +624,9 @@ void mpd_finishCommand(mpd_Connection * connection) { } } -void mpd_finishListOkCommand(mpd_Connection * connection) { - while(!connection->doneProcessing && connection->listOks && - !connection->doneListOk ) +static void mpd_finishListOkCommand(mpd_Connection * connection) { + while(!connection->doneProcessing && connection->listOks && + !connection->doneListOk) { mpd_getNextReturnElement(connection); } @@ -565,11 +647,11 @@ mpd_Status * mpd_getStatus(mpd_Connection * connection) { mpd_Status * status; /*mpd_executeCommand(connection,"status\n"); - + if(connection->error) return NULL;*/ - if(connection->doneProcessing || (connection->listOks && - connection->doneListOk)) + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) { return NULL; } @@ -584,6 +666,7 @@ mpd_Status * mpd_getStatus(mpd_Connection * connection) { status->playlistLength = -1; status->state = -1; status->song = 0; + status->songid = 0; status->elapsedTime = 0; status->totalTime = 0; status->bitRate = 0; @@ -639,17 +722,13 @@ mpd_Status * mpd_getStatus(mpd_Connection * connection) { status->songid = atoi(re->value); } else if(strcmp(re->name,"time")==0) { - char * tok; - char * copy; - char * temp; - copy = strdup(re->value); - temp = strtok_r(copy,":",&tok); - if(temp) { - status->elapsedTime = atoi(temp); - temp = strtok_r(NULL,"",&tok); - if(temp) status->totalTime = atoi(temp); + char * tok = strchr(re->value,':'); + /* the second strchr below is a safety check */ + if (tok && (strchr(tok,0) > (tok+1))) { + /* atoi stops at the first non-[0-9] char: */ + status->elapsedTime = atoi(re->value); + status->totalTime = atoi(tok+1); } - free(copy); } else if(strcmp(re->name,"error")==0) { status->error = strdup(re->value); @@ -661,21 +740,14 @@ mpd_Status * mpd_getStatus(mpd_Connection * connection) { status->updatingDb = atoi(re->value); } else if(strcmp(re->name,"audio")==0) { - char * tok; - char * copy; - char * temp; - copy = strdup(re->value); - temp = strtok_r(copy,":",&tok); - if(temp) { - status->sampleRate = atoi(temp); - temp = strtok_r(NULL,":",&tok); - if(temp) { - status->bits = atoi(temp); - temp = strtok_r(NULL,"",&tok); - if(temp) status->channels = atoi(temp); - } + char * tok = strchr(re->value,':'); + if (tok && (strchr(tok,0) > (tok+1))) { + status->sampleRate = atoi(re->value); + status->bits = atoi(++tok); + tok = strchr(tok,':'); + if (tok && (strchr(tok,0) > (tok+1))) + status->channels = atoi(tok+1); } - free(copy); } mpd_getNextReturnElement(connection); @@ -712,11 +784,11 @@ mpd_Stats * mpd_getStats(mpd_Connection * connection) { mpd_Stats * stats; /*mpd_executeCommand(connection,"stats\n"); - + if(connection->error) return NULL;*/ - if(connection->doneProcessing || (connection->listOks && - connection->doneListOk)) + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) { return NULL; } @@ -779,7 +851,7 @@ void mpd_freeStats(mpd_Stats * stats) { free(stats); } -void mpd_initSong(mpd_Song * song) { +static void mpd_initSong(mpd_Song * song) { song->file = NULL; song->artist = NULL; song->album = NULL; @@ -790,13 +862,15 @@ void mpd_initSong(mpd_Song * song) { /* added by Qball */ song->genre = NULL; song->composer = NULL; + song->disc = NULL; + song->comment = NULL; song->time = MPD_SONG_NO_TIME; song->pos = MPD_SONG_NO_NUM; song->id = MPD_SONG_NO_ID; } -void mpd_finishSong(mpd_Song * song) { +static void mpd_finishSong(mpd_Song * song) { if(song->file) free(song->file); if(song->artist) free(song->artist); if(song->album) free(song->album); @@ -806,9 +880,11 @@ void mpd_finishSong(mpd_Song * song) { if(song->date) free(song->date); if(song->genre) free(song->genre); if(song->composer) free(song->composer); + if(song->disc) free(song->disc); + if(song->comment) free(song->comment); } -mpd_Song * mpd_newSong() { +mpd_Song * mpd_newSong(void) { mpd_Song * ret = malloc(sizeof(mpd_Song)); mpd_initSong(ret); @@ -833,6 +909,8 @@ mpd_Song * mpd_songDup(mpd_Song * song) { if(song->date) ret->date = strdup(song->date); if(song->genre) ret->genre= strdup(song->genre); if(song->composer) ret->composer= strdup(song->composer); + if(song->disc) ret->disc = strdup(song->disc); + if(song->comment) ret->comment = strdup(song->comment); ret->time = song->time; ret->pos = song->pos; ret->id = song->id; @@ -840,19 +918,19 @@ mpd_Song * mpd_songDup(mpd_Song * song) { return ret; } -void mpd_initDirectory(mpd_Directory * directory) { +static void mpd_initDirectory(mpd_Directory * directory) { directory->path = NULL; } -void mpd_finishDirectory(mpd_Directory * directory) { +static void mpd_finishDirectory(mpd_Directory * directory) { if(directory->path) free(directory->path); } -mpd_Directory * mpd_newDirectory () { +mpd_Directory * mpd_newDirectory(void) { mpd_Directory * directory = malloc(sizeof(mpd_Directory));; mpd_initDirectory(directory); - + return directory; } @@ -870,15 +948,15 @@ mpd_Directory * mpd_directoryDup(mpd_Directory * directory) { return ret; } -void mpd_initPlaylistFile(mpd_PlaylistFile * playlist) { +static void mpd_initPlaylistFile(mpd_PlaylistFile * playlist) { playlist->path = NULL; } -void mpd_finishPlaylistFile(mpd_PlaylistFile * playlist) { +static void mpd_finishPlaylistFile(mpd_PlaylistFile * playlist) { if(playlist->path) free(playlist->path); } -mpd_PlaylistFile * mpd_newPlaylistFile() { +mpd_PlaylistFile * mpd_newPlaylistFile(void) { mpd_PlaylistFile * playlist = malloc(sizeof(mpd_PlaylistFile)); mpd_initPlaylistFile(playlist); @@ -899,11 +977,11 @@ mpd_PlaylistFile * mpd_playlistFileDup(mpd_PlaylistFile * playlist) { return ret; } -void mpd_initInfoEntity(mpd_InfoEntity * entity) { +static void mpd_initInfoEntity(mpd_InfoEntity * entity) { entity->info.directory = NULL; -} +} -void mpd_finishInfoEntity(mpd_InfoEntity * entity) { +static void mpd_finishInfoEntity(mpd_InfoEntity * entity) { if(entity->info.directory) { if(entity->type == MPD_INFO_ENTITY_TYPE_DIRECTORY) { mpd_freeDirectory(entity->info.directory); @@ -917,9 +995,9 @@ void mpd_finishInfoEntity(mpd_InfoEntity * entity) { } } -mpd_InfoEntity * mpd_newInfoEntity() { +mpd_InfoEntity * mpd_newInfoEntity(void) { mpd_InfoEntity * entity = malloc(sizeof(mpd_InfoEntity)); - + mpd_initInfoEntity(entity); return entity; @@ -930,27 +1008,27 @@ void mpd_freeInfoEntity(mpd_InfoEntity * entity) { free(entity); } -void mpd_sendInfoCommand(mpd_Connection * connection, char * command) { +static void mpd_sendInfoCommand(mpd_Connection * connection, char * command) { mpd_executeCommand(connection,command); } mpd_InfoEntity * mpd_getNextInfoEntity(mpd_Connection * connection) { mpd_InfoEntity * entity = NULL; - if(connection->doneProcessing || (connection->listOks && - connection->doneListOk)) + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) { return NULL; } if(!connection->returnElement) mpd_getNextReturnElement(connection); - if(connection->returnElement) { + if(connection->returnElement) { if(strcmp(connection->returnElement->name,"file")==0) { entity = mpd_newInfoEntity(); entity->type = MPD_INFO_ENTITY_TYPE_SONG; entity->info.song = mpd_newSong(); - entity->info.song->file = + entity->info.song->file = strdup(connection->returnElement->value); } else if(strcmp(connection->returnElement->name, @@ -958,16 +1036,22 @@ mpd_InfoEntity * mpd_getNextInfoEntity(mpd_Connection * connection) { entity = mpd_newInfoEntity(); entity->type = MPD_INFO_ENTITY_TYPE_DIRECTORY; entity->info.directory = mpd_newDirectory(); - entity->info.directory->path = + entity->info.directory->path = strdup(connection->returnElement->value); } else if(strcmp(connection->returnElement->name,"playlist")==0) { entity = mpd_newInfoEntity(); entity->type = MPD_INFO_ENTITY_TYPE_PLAYLISTFILE; entity->info.playlistFile = mpd_newPlaylistFile(); - entity->info.playlistFile->path = + entity->info.playlistFile->path = strdup(connection->returnElement->value); } + else if(strcmp(connection->returnElement->name, "cpos") == 0){ + entity = mpd_newInfoEntity(); + entity->type = MPD_INFO_ENTITY_TYPE_SONG; + entity->info.song = mpd_newSong(); + entity->info.song->pos = atoi(connection->returnElement->value); + } else { connection->error = 1; strcpy(connection->errorStr,"problem parsing song info"); @@ -983,8 +1067,9 @@ mpd_InfoEntity * mpd_getNextInfoEntity(mpd_Connection * connection) { if(strcmp(re->name,"file")==0) return entity; else if(strcmp(re->name,"directory")==0) return entity; else if(strcmp(re->name,"playlist")==0) return entity; + else if(strcmp(re->name,"cpos")==0) return entity; - if(entity->type == MPD_INFO_ENTITY_TYPE_SONG && + if(entity->type == MPD_INFO_ENTITY_TYPE_SONG && strlen(re->value)) { if(!entity->info.song->artist && strcmp(re->name,"Artist")==0) { @@ -1029,8 +1114,15 @@ mpd_InfoEntity * mpd_getNextInfoEntity(mpd_Connection * connection) { else if(!entity->info.song->composer && strcmp(re->name, "Composer") == 0) { entity->info.song->composer = strdup(re->value); - } - + } + else if(!entity->info.song->disc && + strcmp(re->name, "Disc") == 0) { + entity->info.song->disc = strdup(re->value); + } + else if(!entity->info.song->comment && + strcmp(re->name, "Comment") == 0) { + entity->info.song->comment = strdup(re->value); + } } else if(entity->type == MPD_INFO_ENTITY_TYPE_DIRECTORY) { } @@ -1043,11 +1135,11 @@ mpd_InfoEntity * mpd_getNextInfoEntity(mpd_Connection * connection) { return entity; } -char * mpd_getNextReturnElementNamed(mpd_Connection * connection, - const char * name) +static char * mpd_getNextReturnElementNamed(mpd_Connection * connection, + const char * name) { - if(connection->doneProcessing || (connection->listOks && - connection->doneListOk)) + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) { return NULL; } @@ -1070,6 +1162,7 @@ char * mpd_getNextTag(mpd_Connection * connection,int table) { } return NULL; } + char * mpd_getNextArtist(mpd_Connection * connection) { return mpd_getNextReturnElementNamed(connection,"Artist"); } @@ -1099,6 +1192,13 @@ void mpd_sendPlChangesCommand(mpd_Connection * connection, long long playlist) { free(string); } +void mpd_sendPlChangesPosIdCommand(mpd_Connection * connection, long long playlist) { + char * string = malloc(strlen("plchangesposid")+25); + sprintf(string,"plchangesposid \"%lld\"\n",playlist); + mpd_sendInfoCommand(connection,string); + free(string); +} + void mpd_sendListallCommand(mpd_Connection * connection, const char * dir) { char * sDir = mpd_sanitizeArg(dir); char * string = malloc(strlen("listall")+strlen(sDir)+5); @@ -1130,8 +1230,8 @@ void mpd_sendCurrentSongCommand(mpd_Connection * connection) { mpd_executeCommand(connection,"currentsong\n"); } -void mpd_sendSearchCommand(mpd_Connection * connection, int table, - const char * str) +void mpd_sendSearchCommand(mpd_Connection * connection, int table, + const char * str) { char st[10]; char * string; @@ -1151,92 +1251,9 @@ void mpd_sendSearchCommand(mpd_Connection * connection, int table, free(string); free(sanitStr); } -void mpd_sendSearchTagCommand(mpd_Connection *connection, ...) -{ - va_list arglist; - va_start(arglist, connection); - mpd_sendVSearchTagCommand(connection, arglist); - va_end(arglist); -} - -void mpd_sendVSearchTagCommand(mpd_Connection * connection, va_list arglist) -{ - char *st, *str; - char * string=NULL; - int table; - char * sanitStr; - string = realloc(string,strlen("search")+1); - strcpy(string, "search"); - while((table = va_arg(arglist, int)) != -1) - { - if(table >= 0 && table < MPD_TAG_NUM_OF_ITEM_TYPES) - { - st = mpdTagItemKeys[table]; - str = va_arg(arglist,char *); - sanitStr = mpd_sanitizeArg(str); - string = realloc(string, strlen(string)+strlen(st)+strlen(sanitStr)+6); - sprintf(string, "%s %s \"%s\"",string,st,sanitStr); - free(sanitStr); - } - else { - connection->error = 1; - sprintf(connection->errorStr,"unknown table for search %i",table); - va_end(arglist); - return; - } - } - /* set the last to '\n', should be sufficient space in the string for this */ - sprintf(string, "%s\n", string); - mpd_sendInfoCommand(connection,string); - free(string); -} - -void mpd_sendFindTagCommand(mpd_Connection *connection, ...) -{ - va_list arglist; - va_start(arglist, connection); - mpd_sendVFindTagCommand(connection, arglist); - va_end(arglist); -} - - - - -void mpd_sendVFindTagCommand(mpd_Connection * connection, va_list arglist) -{ - char *st, *str; - char * string=NULL; - int table; - char * sanitStr; - string = realloc(string,strlen("find")+1); - strcpy(string, "find"); - while((table = va_arg(arglist, int)) != -1) - { - if(table >= 0 && table < MPD_TAG_NUM_OF_ITEM_TYPES) - { - st = mpdTagItemKeys[table]; - str = va_arg(arglist,char *); - sanitStr = mpd_sanitizeArg(str); - string = realloc(string, strlen(string)+strlen(st)+strlen(sanitStr)+6); - sprintf(string, "%s %s \"%s\"",string,st,sanitStr); - free(sanitStr); - } - else { - connection->error = 1; - sprintf(connection->errorStr,"unknown table for find %i",table); - va_end(arglist); - return; - } - } - /* set the last to '\n', should be sufficient space in the string for this */ - sprintf(string, "%s\n", string); - mpd_sendInfoCommand(connection,string); - free(string); -} - -void mpd_sendFindCommand(mpd_Connection * connection, int table, - const char * str) +void mpd_sendFindCommand(mpd_Connection * connection, int table, + const char * str) { char st[10]; char * string; @@ -1256,8 +1273,8 @@ void mpd_sendFindCommand(mpd_Connection * connection, int table, free(sanitStr); } -void mpd_sendListCommand(mpd_Connection * connection, int table, - const char * arg1) +void mpd_sendListCommand(mpd_Connection * connection, int table, + const char * arg1) { char st[10]; char * string; @@ -1282,53 +1299,6 @@ void mpd_sendListCommand(mpd_Connection * connection, int table, free(string); } -void mpd_sendListTagCommand(mpd_Connection *connection, int ret_table, ...) -{ - va_list arglist; - va_start(arglist, ret_table); - mpd_sendVListTagCommand(connection, ret_table, arglist); - va_end(arglist); -} -void mpd_sendVListTagCommand(mpd_Connection * connection,int ret_table, va_list arglist) -{ - char *st, *str; - char * string=NULL; - int table; - char * sanitStr; - if(ret_table < 0 && ret_table >= MPD_TAG_NUM_OF_ITEM_TYPES) - { - connection->error = 1; - sprintf(connection->errorStr,"unknown ret_table for search %i",ret_table); - return; - } - - string = realloc(string,strlen("list")+3+strlen(mpdTagItemKeys[ret_table])); - sprintf(string, "list %s",mpdTagItemKeys[ret_table]); - while((table = va_arg(arglist, int)) != -1) - { - if(table >= 0 && table < MPD_TAG_NUM_OF_ITEM_TYPES) - { - st = mpdTagItemKeys[table]; - str = va_arg(arglist,char *); - sanitStr = mpd_sanitizeArg(str); - string = realloc(string, strlen(string)+strlen(st)+strlen(sanitStr)+7); - sprintf(string, "%s %s \"%s\"",string,st,sanitStr); - free(sanitStr); - } - else { - connection->error = 1; - sprintf(connection->errorStr,"unknown table for search %i",table); - va_end(arglist); - return; - } - } - /* set the last to '\n', should be sufficient space in the string for this */ - sprintf(string,"%s\n", string); - mpd_sendInfoCommand(connection,string); - free(string); -} - - void mpd_sendAddCommand(mpd_Connection * connection, const char * file) { char * sFile = mpd_sanitizeArg(file); char * string = malloc(strlen("add")+strlen(sFile)+5); @@ -1623,3 +1593,158 @@ void mpd_freeOutputElement(mpd_OutputEntity * output) { free(output->name); free(output); } + +/** + * mpd_sendNotCommandsCommand + * odd naming, but it gets the not allowed commands + */ + +void mpd_sendNotCommandsCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"notcommands\n"); +} + +/** + * mpd_sendCommandsCommand + * odd naming, but it gets the allowed commands + */ + +void mpd_sendCommandsCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"commands\n"); +} +/** + * Get the next returned command + */ +char * mpd_getNextCommand(mpd_Connection * connection) { + return mpd_getNextReturnElementNamed(connection,"command"); +} + +void mpd_startSearch(mpd_Connection * connection,int exact) { + if(connection->request) { + /* search/find allready in progress */ + /* TODO: set error here? */ + return; + } + if(exact){ + connection->request = strdup("find"); + } + else{ + connection->request = strdup("search"); + } +} + + +void mpd_startFieldSearch(mpd_Connection * connection,int field) { + if(connection->request) { + /* search/find allready in progress */ + /* TODO: set error here? */ + return; + } + if(field < 0 || field >= MPD_TAG_NUM_OF_ITEM_TYPES) { + /* set error here */ + return; + } + + connection->request = malloc(sizeof(char)*( + /* length of the field name */ + strlen(mpdTagItemKeys[field])+ + /* "list"+space+\0 */ + 6 + )); + sprintf(connection->request, "list %s", mpdTagItemKeys[field]); +} + + + +void mpd_addConstraintSearch(mpd_Connection *connection, + int field, + char *name) +{ + char *arg = NULL; + if(!connection->request){ + return; + } + if(name == NULL) { + return; + } + if(field < 0 || field >= MPD_TAG_NUM_OF_ITEM_TYPES) { + return; + } + /* clean up the query */ + arg = mpd_sanitizeArg(name); + /* create space for the query */ + connection->request = realloc(connection->request, ( + /* length of the old string */ + strlen(connection->request)+ + /* space between */ + 1+ + /* length of the field name */ + strlen(mpdTagItemKeys[field])+ + /* space plus starting " */ + 2+ + /* length of search term */ + strlen(arg)+ + /* closign " +\0 that is added sprintf */ + 2 + )*sizeof(char)); + /* and form the query */ + sprintf(connection->request, "%s %s \"%s\"", + connection->request, + mpdTagItemKeys[field], + arg); + free(arg); +} + + +void mpd_commitSearch(mpd_Connection *connection) +{ + if(connection->request) + { + int length = strlen(connection->request); + /* fixing up the string for mpd to like */ + connection->request = realloc(connection->request, + (length+ /* old length */ + 2 /* closing \n and \0 */ + )*sizeof(char)); + connection->request[length] = '\n'; + connection->request[length+1] = '\0'; + /* and off we go */ + mpd_sendInfoCommand(connection, connection->request); + /* clean up a bit */ + free(connection->request); + connection->request = NULL; + } +} + +/** + * @param connection a MpdConnection + * @param path the path to the playlist. + * + * List the content, with full metadata, of a stored playlist. + * + */ +void mpd_sendListPlaylistInfoCommand(mpd_Connection *connection, char *path) +{ + char *arg = mpd_sanitizeArg(path); + char *query = malloc(strlen("listplaylistinfo")+strlen(arg)+5); + sprintf(query, "listplaylistinfo \"%s\"\n",arg); + mpd_sendInfoCommand(connection, query); + free(arg); + free(query); +} + +/** + * @param connection a MpdConnection + * @param path the path to the playlist. + * + * List the content of a stored playlist. + * + */ +void mpd_sendListPlaylistCommand(mpd_Connection *connection, char *path) +{ + char *arg = mpd_sanitizeArg(path); + char *query = malloc(strlen("listplaylist")+strlen(arg)+5); + sprintf(query, "listplaylist \"%s\"\n",arg); + mpd_sendInfoCommand(connection, query); + free(arg); + free(query); +} diff --git a/src/libmpdclient.h b/src/libmpdclient.h index dbbd1019e..437951b31 100644 --- a/src/libmpdclient.h +++ b/src/libmpdclient.h @@ -1,22 +1,22 @@ /* libmpdclient - (c)2003-2004 by Warren Dukes (shank@mercury.chem.pitt.edu) + (c)2003-2006 by Warren Dukes (warren.dukes@gmail.com) This project's homepage is: http://www.musicpd.org - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + - Neither the name of the Music Player Daemon nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR @@ -28,12 +28,15 @@ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ #ifndef LIBMPDCLIENT_H #define LIBMPDCLIENT_H +#ifdef WIN32 +# define __W32API_USE_DLLIMPORT__ 1 +#endif + #include <sys/time.h> #include <stdarg.h> #define MPD_BUFFER_MAX_LENGTH 50000 @@ -71,8 +74,7 @@ extern "C" { #endif - -enum +typedef enum mpd_TagItems { MPD_TAG_ITEM_ARTIST, MPD_TAG_ITEM_ALBUM, @@ -84,11 +86,11 @@ enum MPD_TAG_ITEM_COMPOSER, MPD_TAG_ITEM_PERFORMER, MPD_TAG_ITEM_COMMENT, + MPD_TAG_ITEM_DISC, MPD_TAG_ITEM_FILENAME, MPD_TAG_NUM_OF_ITEM_TYPES }mpd_TagItems; - extern char * mpdTagItemKeys[MPD_TAG_NUM_OF_ITEM_TYPES]; /* internal stuff don't touch this struct */ @@ -111,7 +113,7 @@ typedef struct _mpd_Connection { /* this will be set to MPD_ERROR_* if there is an error, 0 if not */ int error; /* DON'T TOUCH any of the rest of this stuff */ - int sock; + int sock; char buffer[MPD_BUFFER_MAX_LENGTH+1]; int buflen; int bufstart; @@ -121,6 +123,7 @@ typedef struct _mpd_Connection { int commandList; mpd_ReturnElement * returnElement; struct timeval timeout; + char *request; } mpd_Connection; /* mpd_newConnection @@ -255,12 +258,18 @@ typedef struct _mpd_Song { char *date; /* added by qball */ + /* Genre */ char *genre; + /* Composer */ char *composer; + /* Disc */ + char *disc; + /* Comment */ + char *comment; /* length of song in seconds, check that it is not MPD_SONG_NO_TIME */ int time; - /* if plchanges/playlistinfo/playlistid used, is the position of the + /* if plchanges/playlistinfo/playlistid used, is the position of the * song in the playlist */ int pos; /* song id for a song in the playlist */ @@ -275,7 +284,7 @@ typedef struct _mpd_Song { * use mpd_freeSong to free the memory for the mpd_Song, it will also * free memory for file, artist, etc, so don't do it yourself */ -mpd_Song * mpd_newSong(); +mpd_Song * mpd_newSong(void); /* mpd_freeSong * use to free memory allocated by mpd_newSong @@ -301,7 +310,7 @@ typedef struct _mpd_Directory { * allocates memory for a new directory * use mpd_freeDirectory to free this memory */ -mpd_Directory * mpd_newDirectory (); +mpd_Directory * mpd_newDirectory(void); /* mpd_freeDirectory * used to free memory allocated with mpd_newDirectory, and it frees @@ -327,7 +336,7 @@ typedef struct _mpd_PlaylistFile { * allocates memory for new mpd_PlaylistFile, path is set to NULL * free this memory with mpd_freePlaylistFile */ -mpd_PlaylistFile * mpd_newPlaylistFile(); +mpd_PlaylistFile * mpd_newPlaylistFile(void); /* mpd_freePlaylist * free memory allocated for freePlaylistFile, will also free @@ -365,7 +374,7 @@ typedef struct mpd_InfoEntity { } info; } mpd_InfoEntity; -mpd_InfoEntity * mpd_newInfoEntity(); +mpd_InfoEntity * mpd_newInfoEntity(void); void mpd_freeInfoEntity(mpd_InfoEntity * entity); @@ -387,7 +396,15 @@ void mpd_sendPlaylistIdCommand(mpd_Connection * connection, int songId); /* use this to get the changes in the playlist since version _playlist_ */ void mpd_sendPlChangesCommand(mpd_Connection * connection, long long playlist); -/* recursivel fetches all songs/dir/playlists in "dir* (no metadata is +/** + * @param connection: A valid and connected mpd_Connection. + * @param playlist: The playlist version you want the diff with. + * A more bandwidth efficient version of the mpd_sendPlChangesCommand. + * It only returns the pos+id of the changes song. + */ +void mpd_sendPlChangesPosIdCommand(mpd_Connection * connection, long long playlist); + +/* recursivel fetches all songs/dir/playlists in "dir* (no metadata is * returned) */ void mpd_sendListallCommand(mpd_Connection * connection, const char * dir); @@ -402,23 +419,17 @@ void mpd_sendLsInfoCommand(mpd_Connection * connection, const char * dir); #define MPD_TABLE_TITLE 2 #define MPD_TABLE_FILENAME 3 -void mpd_sendSearchCommand(mpd_Connection * connection, int table, +void mpd_sendSearchCommand(mpd_Connection * connection, int table, const char * str); -void mpd_sendFindCommand(mpd_Connection * connection, int table, +void mpd_sendFindCommand(mpd_Connection * connection, int table, const char * str); - -void mpd_sendSearchTagCommand(mpd_Connection *connection, ...); -void mpd_sendFindTagCommand(mpd_Connection *connection, ...); -void mpd_sendVSearchTagCommand(mpd_Connection *connection, va_list arglist); -void mpd_sendVFindTagCommand(mpd_Connection *connection, va_list arglist); /* LIST TAG COMMANDS */ -/* use this function fetch next artist entry, be sure to free the returned +/* use this function fetch next artist entry, be sure to free the returned * string. NULL means there are no more. Best used with sendListArtists */ - char * mpd_getNextArtist(mpd_Connection * connection); char * mpd_getNextAlbum(mpd_Connection * connection); @@ -428,12 +439,9 @@ char * mpd_getNextTag(mpd_Connection *connection, int table); /* list artist or albums by artist, arg1 should be set to the artist if * listing albums by a artist, otherwise NULL for listing all artists or albums */ -void mpd_sendListCommand(mpd_Connection * connection, int table, +void mpd_sendListCommand(mpd_Connection * connection, int table, const char * arg1); -void mpd_sendListTagCommand(mpd_Connection * connection, int table,...); -void mpd_sendVListTagCommand(mpd_Connection * connection,int ret_table, va_list arglist); - /* SIMPLE COMMANDS */ void mpd_sendAddCommand(mpd_Connection * connection, const char * file); @@ -509,7 +517,7 @@ void mpd_sendCommandListOkBegin(mpd_Connection * connection); void mpd_sendCommandListEnd(mpd_Connection * connection); -/* advance to the next listOk +/* advance to the next listOk * returns 0 if advanced to the next list_OK, * returns -1 if it advanced to an OK or ACK */ int mpd_nextListOkCommand(mpd_Connection * connection); @@ -530,6 +538,86 @@ void mpd_sendDisableOutputCommand(mpd_Connection * connection, int outputId); void mpd_freeOutputElement(mpd_OutputEntity * output); +/** + * @param connection a #mpd_Connection + * + * Queries mpd for the allowed commands + */ +void mpd_sendCommandsCommand(mpd_Connection * connection); +/** + * @param connection a #mpd_Connection + * + * Queries mpd for the not allowed commands + */ +void mpd_sendNotCommandsCommand(mpd_Connection * connection); + +/** + * @param connection a #mpd_Connection + * + * returns the next supported command. + * + * @returns a string, needs to be free'ed + */ +char *mpd_getNextCommand(mpd_Connection *connection); + +/** + * @param connection a MpdConnection + * @param path the path to the playlist. + * + * List the content, with full metadata, of a stored playlist. + * + */ +void mpd_sendListPlaylistInfoCommand(mpd_Connection *connection, char *path); +/** + * @param connection a MpdConnection + * @param path the path to the playlist. + * + * List the content of a stored playlist. + * + */ +void mpd_sendListPlaylistCommand(mpd_Connection *connection, char *path); + +/** + * @param connection a #mpd_Connection + * @param exact if to match exact + * + * starts a search, use mpd_addConstraintSearch to add + * a constraint to the search, and mpd_commitSearch to do the actual search + */ +void mpd_startSearch(mpd_Connection * connection,int exact); +/** + * @param connection a #mpd_Connection + * @param field + * @param name + * + */ +void mpd_addConstraintSearch(mpd_Connection *connection, int field, char *name); +/** + * @param connection a #mpd_Connection + * + */ +void mpd_commitSearch(mpd_Connection *connection); + +/** + * @param connection a #mpd_Connection + * @param field The field to search + * + * starts a search for fields... f.e. get a list of artists would be: + * mpd_startFieldSearch(connection, MPD_TAG_ITEM_ARTIST); + * mpd_commitSearch(connection); + * + * or get a list of artist in genre "jazz" would be: + * @code + * mpd_startFieldSearch(connection, MPD_TAG_ITEM_ARTIST); + * mpd_addConstraintSearch(connection, MPD_TAG_ITEM_GENRE, "jazz") + * mpd_commitSearch(connection); + * @endcode + * + * mpd_startSearch will return a list of songs (and you need mpd_getNextInfoEntity) + * this one will return a list of only one field (the field specified with field) and you need + * mpd_getNextTag to get the results + */ +void mpd_startFieldSearch(mpd_Connection * connection,int field); #ifdef __cplusplus } #endif diff --git a/src/main.c b/src/main.c index 3dd7b6b94..c00b7ad68 100644 --- a/src/main.c +++ b/src/main.c @@ -135,6 +135,13 @@ catch_sigint( int sig ) } void +catch_sighup( int sig) +{ + printf("\n%s\n", _("Exiting...")); + exit(EXIT_SUCCESS); +} + +void catch_sigcont( int sig ) { D("catch_sigcont()\n"); @@ -239,7 +246,17 @@ main(int argc, const char *argv[]) perror("sigaction(SIGCONT)"); exit(EXIT_FAILURE); } - + + /* setup signal behaviour - SIGHUP*/ + sigemptyset( &act.sa_mask ); + act.sa_flags = 0; + act.sa_handler = catch_sigint; + if( sigaction(SIGHUP, &act, NULL)<0 ) + { + perror("sigaction(SIGHUP)"); + exit(EXIT_FAILURE); + } + /* install exit function */ atexit(exit_and_cleanup); diff --git a/src/ncmpc.h b/src/ncmpc.h index 4d3b840a5..7bc99a1d6 100644 --- a/src/ncmpc.h +++ b/src/ncmpc.h @@ -17,6 +17,9 @@ #ifndef DISABLE_CLOCK_SCREEN #define ENABLE_CLOCK_SCREEN 1 #endif +#ifndef DISABLE_LYRICS_SCREEN +#define ENABLE_LYRICS_SCREEN 1 +#endif #ifdef DEBUG void D(char *format, ...); @@ -73,5 +76,7 @@ void D(char *format, ...); #define DEFAULT_STATUS_FORMAT "[%artist% - ]%title%|%shortfile%" #define STATUS_FORMAT (options.status_format ? options.status_format : \ DEFAULT_STATUS_FORMAT) + +#define DEFAULT_LYRICS_TIMEOUT 100 #endif /* NCMPC_H */ diff --git a/src/options.c b/src/options.c index 0f281bc16..89a62366b 100644 --- a/src/options.c +++ b/src/options.c @@ -369,7 +369,7 @@ options_init( void ) options.seek_time = 1; options.screen_list = g_strsplit_set(DEFAULT_SCREEN_LIST, " ", 0); options.timedisplay_type = DEFAULT_TIMEDISPLAY_TYPE; + options.lyrics_timeout = DEFAULT_LYRICS_TIMEOUT; return &options; } - diff --git a/src/options.h b/src/options.h index df6ac6146..1bfb350a3 100644 --- a/src/options.h +++ b/src/options.h @@ -19,6 +19,7 @@ typedef struct int search_mode; int hide_cursor; int seek_time; + int lyrics_timeout; gboolean reconnect; gboolean debug; gboolean find_wrap; @@ -38,6 +39,3 @@ extern options_t options; options_t *options_init(void); options_t *options_parse(int argc, const char **argv); - - - diff --git a/src/screen.c b/src/screen.c index 73092073e..d30573917 100644 --- a/src/screen.c +++ b/src/screen.c @@ -40,7 +40,6 @@ #include "screen.h" #include "screen_utils.h" -#define MAX_SONGNAME_LENGTH 512 #define SCREEN_PLAYLIST_ID 0 #define SCREEN_BROWSE_ID 1 @@ -49,6 +48,7 @@ #define SCREEN_KEYDEF_ID 101 #define SCREEN_CLOCK_ID 102 #define SCREEN_SEARCH_ID 103 +#define SCREEN_LYRICS_ID 104 @@ -60,6 +60,7 @@ extern screen_functions_t *get_screen_search(void); extern screen_functions_t *get_screen_artist(void); extern screen_functions_t *get_screen_keydef(void); extern screen_functions_t *get_screen_clock(void); +extern screen_functions_t *get_screen_lyrics(void); typedef screen_functions_t * (*screen_get_mode_functions_fn_t) (void); @@ -87,6 +88,9 @@ static screen_mode_info_t screens[] = { #ifdef ENABLE_CLOCK_SCREEN { SCREEN_CLOCK_ID, "clock", get_screen_clock }, #endif + #ifdef ENABLE_LYRICS_SCREEN + { SCREEN_LYRICS_ID, "lyrics", get_screen_lyrics }, +#endif { G_MAXINT, NULL, NULL } }; @@ -124,6 +128,10 @@ lookup_mode(gint id) return -1; } +gint get_cur_mode_id() +{ + return screens[screen->mode].id; +} static void switch_screen_mode(gint id, mpdclient_t *c) { @@ -234,6 +242,12 @@ paint_top_window(char *header, mpdclient_t *c, int clear) colors_use(w, COLOR_TITLE); waddstr(w, _(":Search ")); #endif +#ifdef ENABLE_LYRICS_SCREEN + colors_use(w, COLOR_TITLE_BOLD); + waddstr(w, get_key_names(CMD_SCREEN_LYRICS, FALSE)); + colors_use(w, COLOR_TITLE); + waddstr(w, _(":Lyrics ")); +#endif } if( c->status->volume==MPD_STATUS_NO_VOLUME ) { @@ -965,12 +979,12 @@ screen_cmd(mpdclient_t *c, command_t cmd) case CMD_SCREEN_CLOCK: switch_screen_mode(SCREEN_CLOCK_ID, c); break; + case CMD_SCREEN_LYRICS: + switch_screen_mode(SCREEN_LYRICS_ID, c); + break; case CMD_QUIT: exit(EXIT_SUCCESS); default: break; } } - - - diff --git a/src/screen.h b/src/screen.h index fe6b394a3..71489f211 100644 --- a/src/screen.h +++ b/src/screen.h @@ -7,11 +7,13 @@ #define IS_PAUSED(s) (s==MPD_STATUS_STATE_PAUSE) #define IS_STOPPED(s) (!(IS_PLAYING(s) | IS_PAUSED(s))) +#define MAX_SONGNAME_LENGTH 512 + typedef struct { WINDOW *w; int rows, cols; - + int cur_action_id; } window_t; @@ -81,6 +83,8 @@ void screen_update(mpdclient_t *c); void screen_idle(mpdclient_t *c); void screen_cmd(mpdclient_t *c, command_t cmd); + +gint get_cur_mode_id(); int screen_get_mouse_event(mpdclient_t *c, list_window_t *lw, int lw_length, unsigned long *bstate, int *row); diff --git a/src/screen_help.c b/src/screen_help.c index d56e744c8..c90c8692d 100644 --- a/src/screen_help.c +++ b/src/screen_help.c @@ -125,7 +125,14 @@ static help_text_row_t help_text[] = { 0, CMD_SELECT, NULL }, { 0, CMD_SEARCH_MODE, NULL }, #endif - +#ifdef ENABLE_LYRICS_SCREEN + { 0, CMD_NONE, NULL }, + { 0, CMD_NONE, NULL }, + { 1, CMD_NONE, N_("Keys - Lyrics screen") }, + { 2, CMD_NONE, NULL }, + { 0, CMD_SCREEN_LYRICS, N_("View Lyrics") }, + { 0, CMD_SELECT, N_("(Re)load lyrics") }, +#endif { 0, CMD_NONE, NULL }, {-1, CMD_NONE, NULL } }; diff --git a/src/screen_lyrics.c b/src/screen_lyrics.c new file mode 100644 index 000000000..6df0e5d9a --- /dev/null +++ b/src/screen_lyrics.c @@ -0,0 +1,542 @@ +/* + * $Id: screen_lyrics.c 3355 2006-09-1 17:44:04Z tradiaz $ + * + * (c) 2006 by Kalle Wallin <kaw@linux.se> + * Tue Aug 1 23:17:38 2006 + * lyrics enhancement written by Andreas Obergrusberger <tradiaz@yahoo.de> + * using www.leoslyrics.com XML API + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include <stdlib.h> +#include <string.h> +#include <glib.h> +#include <ncurses.h> +#include <expat.h> +#include <unistd.h> + +#include "config.h" +#ifndef DISABLE_LYRICS_SCREEN +#include "ncmpc.h" +#include "options.h" +#include "mpdclient.h" +#include "command.h" +#include "screen.h" +#include "screen_utils.h" +#include "easy_download.h" + +#define LEOSLYRICS_SEARCH_URL "http://api.leoslyrics.com/api_search.php?auth=QuodLibet&artist=%s&songtitle=%s" + +#define LEOSLYRICS_CONTENT_URL "http://api.leoslyrics.com/api_lyrics.php?auth=QuodLibet&hid=%s" + +#define CREDITS "Lyrics provided by www.LeosLyrics.com" +typedef struct _formed_text +{ + GString *text; + GArray *lines; + int val; +} formed_text; + + +XML_Parser parser, contentp; +static int lyrics_text_rows = -1; +static list_window_t *lw = NULL; +guint8 result; +char *hid; +GTimer *dltime; +short int lock; +//GString *lyr_text; +//char *lyr_text; +//GArray *textline; +formed_text lyr_text; +/* result is a bitset in which the succes when searching 4 lyrics is logged +countend by position - backwards +0: lyrics in database +1: proper access to the lyrics provider +2: lyrics found +3: exact match +4: lyrics downloaded +5: lyrics saved +wasting 3 bits doesn't mean being a fat memory hog like kde.... does it? +*/ +static void lyrics_paint(screen_t *screen, mpdclient_t *c); + +void get_text_line(formed_text *text, int num, char *dest, int len) +{ + memset(dest, '\0', len*sizeof(char)); + if(num >= text->lines->len-1) return; + int linelen; + if(num == 0) + { + linelen = g_array_index(text->lines, int, num); + memcpy(dest, text->text->str, linelen*sizeof(char)); + } + else if(num == 1) + { //dont ask me why, but this is needed.... + linelen = g_array_index(text->lines, int, num) + - g_array_index(text->lines, int, num-1); + memcpy(dest, &text->text->str[g_array_index(text->lines, int, num-1)], + linelen*sizeof(char)); + } + else + { + linelen = g_array_index(text->lines, int, num+1) + - g_array_index(text->lines, int, num); + memcpy(dest, &text->text->str[g_array_index(text->lines, int, num)], + linelen*sizeof(char)); + } + dest[linelen] = '\n'; + dest[linelen+1] = '\0'; +} + +void add_text_line(formed_text *dest, const char *src, int len) +{ + // need this because g_array_append_val doesnt work with literals + // and expat sends "\n" as an extra line everytime + if(len == 0) + { + dest->val = strlen(src); + if(dest->lines->len > 0) dest->val += g_array_index(dest->lines, int, + dest->lines->len-1); + g_string_append(dest->text, src); + g_array_append_val(dest->lines, dest->val); + return; + } + if(len > 1 || dest->val == 0) + { + dest->val = len; + if(dest->lines->len > 0) dest->val += g_array_index(dest->lines, int, + dest->lines->len-1); + } + else if (len == 1 && dest->val != 0) dest->val = 0; + + if(dest->val > 0) + { + g_string_append_len(dest->text, src, len); + g_array_append_val(dest->lines, dest->val); + } +} + +void formed_text_init(formed_text *text) +{ + if(text->text != NULL) g_string_free(text->text, TRUE); + text->text = g_string_new(""); + + if(text->lines != NULL) g_array_free(text->lines, TRUE); + text->lines = g_array_new(FALSE, TRUE, 4); + + text->val = 0; +} +/* +char *check_lyr_hd(char *artist, char *title, int how) +{ //checking whether for lyrics file existence and proper access + static char path[1024]; + snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", + getenv("HOME"), artist, title); + + if(g_access(path, how) != 0) return NULL; + return path; +} + +int get_lyr_hd(char *artist, char *title) +{ + char *path = check_lyr_hd(artist, title, R_OK); + if(path == NULL) return -1; + + FILE *lyr_file; + lyr_file = fopen(path, "r"); + if(lyr_file == NULL) return -1; + + char *buf = NULL; + char **line = &buf; + size_t n = 0; + + while(1) + { + n = getline(line, &n, lyr_file); + if( n < 1 || *line == NULL || feof(lyr_file) != 0 ) return 0; + add_text_line(&lyr_text, *line, n+1); + free(*line); + *line = NULL; n = 0; + } + + return 0; +} + +int store_lyr_hd() +{ + char artist[512]; + char title[512]; + static char path[1024]; + FILE *lyr_file; + + get_text_line(&lyr_text, 0, artist, 512); + get_text_line(&lyr_text, 1, title, 512); + artist[strlen(artist)-2] = '\0'; + title[strlen(title)-2] = '\0'; + + snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", + getenv("HOME"), artist, title); + + if (check_lyr_hd(artist, title, F_OK) == 0) lyr_file = fopen(path, "w"); + else lyr_file = fopen(path, "xw"); + if(lyr_file == NULL) return -1; + + int i; + char line_buf[1024]; + + for(i = 2; i <= lyr_text.text->len; i++) + { + get_text_line(&lyr_text, i, line_buf, 0); + fputs(line_buf, lyr_file); + } + fclose(lyr_file); + return 0; +} + +*/ +void check_repaint() +{ + if(screen_get_id("lyrics") == get_cur_mode_id())lyrics_paint(NULL, NULL); +} + +int check_dl_progress(void *clientp, double dltotal, double dlnow, + double ultotal, double ulnow) +{ + if(g_timer_elapsed(dltime, NULL) >= options.lyrics_timeout) + { + formed_text_init(&lyr_text); + return -1; + } + return 0; +} + + + +static void check_content(void *data, const char *name, const char **atts) +{ + if(strstr(name, "text") != NULL) + { + + result |= 16; + } +} + + +static void check_search_response(void *data, const char *name, + const char **atts) +{ + if(strstr(name, "response") != NULL) + { + result |=2; + return; + } + + if(result & 4) + { + if(strstr(name, "result") != NULL) + { + if(strstr(atts[2], "hid") != NULL) + { + hid = atts[3]; + } + + if(strstr(atts[2], "exactMatch") != NULL) + { + result |= 8; + } + } + } + +} + +static void end_tag(void *data, const char *name) +{ + //hmmmmmm +} + + static void check_search_success(void *userData, const XML_Char *s, int len) + { + if(result & 2) //lets first check whether we're right + { //we don't really want to search in the wrong string + if(strstr((char*) s, "SUCCESS")) + { + result |=4; + } + } + } + +static void fetch_text(void *userData, const XML_Char *s, int len) +{ + if(result & 16) + { + add_text_line(&lyr_text, s, len); + } +} + +gpointer get_lyr(void *c) +{ + mpd_Status *status = ((mpdclient_t*)c)->status; + mpd_Song *cur = ((mpdclient_t*)c)->song; + mpdclient_update((mpdclient_t*)c); + + if(!(IS_PAUSED(status->state)||IS_PLAYING(status->state))) + { + formed_text_init(&lyr_text); + return NULL; + } + + char url_avail[256]; + char url_hid[256]; + char artist[MAX_SONGNAME_LENGTH]; + char title[MAX_SONGNAME_LENGTH]; + lock = 2; + result = 0; + + if(dltime == NULL) dltime = g_timer_new(); + + strfsong(artist, MAX_SONGNAME_LENGTH, "%artist%", cur); + strfsong(title, MAX_SONGNAME_LENGTH, "%title%", cur); + + formed_text_init(&lyr_text); + add_text_line(&lyr_text, artist, 0); + add_text_line(&lyr_text, title, 0); + + //if(get_lyr_hd(artist, title) == 0) return &lyr_text; + + //this replacess the whitespaces with '+' + g_strdelimit(artist, " ", '+'); + g_strdelimit(title, " ", '+'); + + //we insert the artist and the title into the url + snprintf(url_avail, 512, LEOSLYRICS_SEARCH_URL, artist, title); + + //download that xml! + easy_download_struct lyr_avail = {NULL, 0,-1}; + + g_timer_start(dltime); + if(!easy_download(url_avail, &lyr_avail, check_dl_progress)) return NULL; + g_timer_stop(dltime); + + //we gotta parse that stuff with expat + parser = XML_ParserCreate(NULL); + XML_SetUserData(parser, NULL); + + int state; + + XML_SetElementHandler(parser, check_search_response, end_tag); + XML_SetCharacterDataHandler(parser, check_search_success); + XML_Parse(parser, lyr_avail.data, strlen(lyr_avail.data), state); + XML_ParserFree(parser); + + if(!(result & 4)) return NULL; //check whether lyrics found + easy_download_struct lyr_content = {NULL, 0,-1}; + snprintf(url_hid, 512, LEOSLYRICS_CONTENT_URL, hid); + + g_timer_continue(dltime); + if(!(easy_download(url_hid, &lyr_content, check_dl_progress))) return NULL; + g_timer_stop(dltime); + + contentp = XML_ParserCreate(NULL); + XML_SetUserData(contentp, NULL); + XML_SetElementHandler(contentp, check_content, end_tag); + XML_SetCharacterDataHandler(contentp, fetch_text); + XML_Parse(contentp, lyr_content.data, strlen(lyr_content.data), state); + XML_ParserFree(contentp); + + lw->start = 0; + check_repaint(); + + lock = 1; + return &lyr_text; +} + +static char * +list_callback(int index, int *highlight, void *data) +{ + static char buf[512]; + int linelen; + + //i think i'ts fine to write it into the 1st line... + if((index == lyr_text.lines->len && lyr_text.lines->len != 2)|| + ((lyr_text.lines->len == 0 + ||lyr_text.lines->len == 2) && index == 0)) + { + *highlight=3; + return CREDITS; + } + + if(index < 2 && lyr_text.lines->len > 2) *highlight=3; + else if(index >= lyr_text.lines->len || index == 2) + { + return ""; + } + if(index >1) index--; + get_text_line(&lyr_text, index, buf, 512); + return buf; +} + + +static void +lyrics_init(WINDOW *w, int cols, int rows) +{ + lw = list_window_init(w, cols, rows); + lw->flags = LW_HIDE_CURSOR; + //lyr_text.lines = g_array_new(FALSE, TRUE, 4); + formed_text_init(&lyr_text); + if (!g_thread_supported()) g_thread_init(NULL); + +} + +static void +lyrics_resize(int cols, int rows) +{ + lw->cols = cols; + lw->rows = rows; +} + +static void +lyrics_exit(void) +{ + list_window_free(lw); +} + + +static char * +lyrics_title(char *str, size_t size) +{ + if(lyr_text.lines->len == 2){ + if(lock == 1 && !(result & 2)) return _("Lyrics [No connection]"); + if(lock == 1 && !(result & 4)) return _("Lyrics [Not found]"); + if(lock == 2) return _("Lyrics [retrieving]"); + } + /*if(lyr_text.lines->len > 2) + { + static char buf[512]; + char artist[512]; + char title[512]; + get_text_line(&lyr_text, 0, artist, 512); + get_text_line(&lyr_text, 1, artist, 512); + snprintf(buf, 512, "Lyrics %s - %s", artist, title); + return buf; + }*/ + return "Lyrics"; +} + +static void +lyrics_paint(screen_t *screen, mpdclient_t *c) +{ + lw->clear = 1; + list_window_paint(lw, list_callback, NULL); + wrefresh(lw->w); +} + +static void +lyrics_update(screen_t *screen, mpdclient_t *c) +{ + if( lw->repaint ) + { + list_window_paint(lw, list_callback, NULL); + wrefresh(lw->w); + lw->repaint = 0; + } +} + + +static int +lyrics_cmd(screen_t *screen, mpdclient_t *c, command_t cmd) +{ + lw->repaint=1; + switch(cmd) + { + case CMD_LIST_NEXT: + if( lw->start+lw->rows < lyr_text.lines->len+1 ) + lw->start++; + return 1; + case CMD_LIST_PREVIOUS: + if( lw->start >0 ) + lw->start--; + return 1; + case CMD_LIST_FIRST: + lw->start = 0; + return 1; + case CMD_LIST_LAST: + lw->start = lyrics_text_rows-lw->rows; + if( lw->start<0 ) + lw->start = 0; + return 1; + case CMD_LIST_NEXT_PAGE: + lw->start = lw->start + lw->rows-1; + if( lw->start+lw->rows >= lyr_text.lines->len+1 ) + lw->start = lyr_text.lines->len-lw->rows+1; + if( lw->start<0 ) + lw->start = 0; + return 1; + case CMD_LIST_PREVIOUS_PAGE: + lw->start = lw->start - lw->rows; + if( lw->start<0 ) + lw->start = 0; + return 1; + case CMD_SELECT: + g_thread_create(get_lyr, c, FALSE, NULL); + return 1; + default: + break; + } + + lw->selected = lw->start+lw->rows; + if( screen_find(screen, c, + lw, lyrics_text_rows, + cmd, list_callback, NULL) ) + { + /* center the row */ + lw->start = lw->selected-(lw->rows/2); + if( lw->start+lw->rows > lyrics_text_rows ) + lw->start = lyrics_text_rows-lw->rows; + if( lw->start<0 ) + lw->start=0; + return 1; + } + + return 0; +} + +static list_window_t * +lyrics_lw(void) +{ + return lw; +} + +screen_functions_t * +get_screen_lyrics(void) +{ + static screen_functions_t functions; + + memset(&functions, 0, sizeof(screen_functions_t)); + functions.init = lyrics_init; + functions.exit = lyrics_exit; + functions.open = NULL; + functions.close = NULL; + functions.resize = lyrics_resize; + functions.paint = lyrics_paint; + functions.update = lyrics_update; + functions.cmd = lyrics_cmd; + functions.get_lw = lyrics_lw; + functions.get_title = lyrics_title; + + return &functions; +} +#endif /* ENABLE_LYRICS_SCREEN */ |