/[svn]/linuxsampler/trunk/src/network/lscpserver.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/network/lscpserver.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1161 by iliev, Mon Apr 16 15:51:18 2007 UTC revision 1649 by nagata, Fri Jan 25 15:06:02 2008 UTC
# Line 25  Line 25 
25  #include "lscpresultset.h"  #include "lscpresultset.h"
26  #include "lscpevent.h"  #include "lscpevent.h"
27    
28    #if defined(WIN32)
29    #include <windows.h>
30    #else
31  #include <fcntl.h>  #include <fcntl.h>
32    #endif
33    
34  #if ! HAVE_SQLITE3  #if ! HAVE_SQLITE3
35  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
# Line 36  Line 40 
40  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
41  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
42    
43    
44    /**
45     * Returns a copy of the given string where all special characters are
46     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
47     * to escape LSCP response fields in case the respective response field is
48     * actually defined as using escape sequences in the LSCP specs.
49     *
50     * @e Caution: DO NOT use this function for escaping path based responses,
51     * use the Path class (src/common/Path.h) for this instead!
52     */
53    static String _escapeLscpResponse(String txt) {
54        for (int i = 0; i < txt.length(); i++) {
55            const char c = txt.c_str()[i];
56            if (
57                !(c >= '0' && c <= '9') &&
58                !(c >= 'a' && c <= 'z') &&
59                !(c >= 'A' && c <= 'Z') &&
60                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
61                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
62                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
63                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
64                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
65                !(c == '@') && !(c == '[') && !(c == ']') &&
66                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
67                !(c == '|') && !(c == '}') && !(c == '~')
68            ) {
69                // convert the "special" character into a "\xHH" LSCP escape sequence
70                char buf[5];
71                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
72                txt.replace(i, 1, buf);
73                i += 3;
74            }
75        }
76        return txt;
77    }
78    
79  /**  /**
80   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
81   * The big assumption here is that LSCPServer is going to remain a singleton.   * The big assumption here is that LSCPServer is going to remain a singleton.
# Line 52  Line 92 
92  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
93  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
94  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
95    std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
96  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
97  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
98  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();
# Line 84  LSCPServer::LSCPServer(Sampler* pSampler Line 125  LSCPServer::LSCPServer(Sampler* pSampler
125      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
126      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
127      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
128        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
129      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
131      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
132      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
133      hSocket = -1;      hSocket = -1;
134  }  }
135    
136  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
137    #if defined(WIN32)
138        if (hSocket >= 0) closesocket(hSocket);
139    #else
140      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
141    #endif
142  }  }
143    
144  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
# Line 142  void LSCPServer::EventHandler::TotalVoic Line 189  void LSCPServer::EventHandler::TotalVoic
189      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
190  }  }
191    
192    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
193        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
194    }
195    
196  #if HAVE_SQLITE3  #if HAVE_SQLITE3
197  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
198      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, Dir));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
199  }  }
200    
201  void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
202      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, Dir));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
203  }  }
204    
205  void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
206      Dir = "'" + Dir + "'";      Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
207      NewName = "'" + NewName + "'";      NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
208      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
209  }  }
210    
211  void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
212      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, Dir));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
213  }  }
214    
215  void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {  void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
216      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, Instr));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
217  }  }
218    
219  void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {  void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
220      Instr = "'" + Instr + "'";      Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
221      NewName = "'" + NewName + "'";      NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
222      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
223  }  }
224    
225    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
226        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
227    }
228  #endif // HAVE_SQLITE3  #endif // HAVE_SQLITE3
229    
230    
# Line 187  int LSCPServer::WaitUntilInitialized(lon Line 243  int LSCPServer::WaitUntilInitialized(lon
243  }  }
244    
245  int LSCPServer::Main() {  int LSCPServer::Main() {
246            #if defined(WIN32)
247            WSADATA wsaData;
248            int iResult;
249            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
250            if (iResult != 0) {
251                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
252                    exit(EXIT_FAILURE);
253            }
254            #endif
255      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
256      if (hSocket < 0) {      if (hSocket < 0) {
257          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 200  int LSCPServer::Main() { Line 265  int LSCPServer::Main() {
265              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
266                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
267                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
268                        #if defined(WIN32)
269                        closesocket(hSocket);
270                        #else
271                      close(hSocket);                      close(hSocket);
272                        #endif
273                      //return -1;                      //return -1;
274                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
275                  }                  }
# Line 212  int LSCPServer::Main() { Line 281  int LSCPServer::Main() {
281    
282      listen(hSocket, 1);      listen(hSocket, 1);
283      Initialized.Set(true);      Initialized.Set(true);
284        
285      // Registering event listeners      // Registering event listeners
286      pSampler->AddChannelCountListener(&eventHandler);      pSampler->AddChannelCountListener(&eventHandler);
287      pSampler->AddAudioDeviceCountListener(&eventHandler);      pSampler->AddAudioDeviceCountListener(&eventHandler);
# Line 220  int LSCPServer::Main() { Line 289  int LSCPServer::Main() {
289      pSampler->AddVoiceCountListener(&eventHandler);      pSampler->AddVoiceCountListener(&eventHandler);
290      pSampler->AddStreamCountListener(&eventHandler);      pSampler->AddStreamCountListener(&eventHandler);
291      pSampler->AddBufferFillListener(&eventHandler);      pSampler->AddBufferFillListener(&eventHandler);
292        pSampler->AddTotalStreamCountListener(&eventHandler);
293      pSampler->AddTotalVoiceCountListener(&eventHandler);      pSampler->AddTotalVoiceCountListener(&eventHandler);
294      pSampler->AddFxSendCountListener(&eventHandler);      pSampler->AddFxSendCountListener(&eventHandler);
295      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
# Line 239  int LSCPServer::Main() { Line 309  int LSCPServer::Main() {
309      timeval timeout;      timeval timeout;
310    
311      while (true) {      while (true) {
312            #if CONFIG_PTHREAD_TESTCANCEL
313                    TestCancel();
314            #endif
315          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers
316          {          {
317              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 282  int LSCPServer::Main() { Line 355  int LSCPServer::Main() {
355                  continue; //Nothing try again                  continue; //Nothing try again
356          if (retval == -1) {          if (retval == -1) {
357                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
358                    #if defined(WIN32)
359                    closesocket(hSocket);
360                    #else
361                  close(hSocket);                  close(hSocket);
362                    #endif
363                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
364          }          }
365    
# Line 294  int LSCPServer::Main() { Line 371  int LSCPServer::Main() {
371                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
372                  }                  }
373    
374                    #if defined(WIN32)
375                    u_long nonblock_io = 1;
376                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
377                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
378                      exit(EXIT_FAILURE);
379                    }
380            #else
381                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
382                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
383                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
384                  }                  }
385                    #endif
386    
387                  // Parser initialization                  // Parser initialization
388                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 321  int LSCPServer::Main() { Line 406  int LSCPServer::Main() {
406                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
407                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
408                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
409                                    itCurrentSession = iter; // another hack
410                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
411                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
412                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
413                                  }                                  }
414                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
415                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
416                                    itCurrentSession = Sessions.end(); // hack as well
417                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
418                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
419                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 354  void LSCPServer::CloseConnection( std::v Line 441  void LSCPServer::CloseConnection( std::v
441          NotifyMutex.Lock();          NotifyMutex.Lock();
442          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
443          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
444            #if defined(WIN32)
445            closesocket(socket);
446            #else
447          close(socket);          close(socket);
448            #endif
449          NotifyMutex.Unlock();          NotifyMutex.Unlock();
450  }  }
451    
452    void LSCPServer::LockRTNotify() {
453        RTNotifyMutex.Lock();
454    }
455    
456    void LSCPServer::UnlockRTNotify() {
457        RTNotifyMutex.Unlock();
458    }
459    
460  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
461          int subs = 0;          int subs = 0;
462          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 419  extern int GetLSCPCommand( void *buf, in Line 518  extern int GetLSCPCommand( void *buf, in
518          return command.size();          return command.size();
519  }  }
520    
521    extern yyparse_param_t* GetCurrentYaccSession() {
522        return &(*itCurrentSession);
523    }
524    
525  /**  /**
526   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
527   * If command is read, it will return true. Otherwise false is returned.   * If command is read, it will return true. Otherwise false is returned.
# Line 429  bool LSCPServer::GetLSCPCommand( std::ve Line 532  bool LSCPServer::GetLSCPCommand( std::ve
532          char c;          char c;
533          int i = 0;          int i = 0;
534          while (true) {          while (true) {
535                    #if defined(WIN32)
536                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
537                    #else
538                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
539                    #endif
540                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection
541                          CloseConnection(iter);                          CloseConnection(iter);
542                          break;                          break;
# Line 444  bool LSCPServer::GetLSCPCommand( std::ve Line 551  bool LSCPServer::GetLSCPCommand( std::ve
551                          }                          }
552                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
553                  }                  }
554                    #if defined(WIN32)
555                    if (result == SOCKET_ERROR) {
556                        int wsa_lasterror = WSAGetLastError();
557                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
558                                    return false;
559                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
560                            CloseConnection(iter);
561                            break;
562                    }
563                    #else
564                  if (result == -1) {                  if (result == -1) {
565                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
566                                  return false;                                  return false;
# Line 482  bool LSCPServer::GetLSCPCommand( std::ve Line 599  bool LSCPServer::GetLSCPCommand( std::ve
599                          CloseConnection(iter);                          CloseConnection(iter);
600                          break;                          break;
601                  }                  }
602                    #endif
603          }          }
604          return false;          return false;
605  }  }
# Line 606  EngineChannel* LSCPServer::GetEngineChan Line 724  EngineChannel* LSCPServer::GetEngineChan
724      EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();      EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
725      if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");      if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
726    
727      return pEngineChannel;              return pEngineChannel;
728  }  }
729    
730  /**  /**
# Line 755  String LSCPServer::GetEngineInfo(String Line 873  String LSCPServer::GetEngineInfo(String
873      LockRTNotify();      LockRTNotify();
874      try {      try {
875          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
876          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
877          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
878          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
879      }      }
# Line 828  String LSCPServer::GetChannelInfo(uint u Line 946  String LSCPServer::GetChannelInfo(uint u
946          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
947          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
948    
949            // convert the filename into the correct encoding as defined for LSCP
950            // (especially in terms of special characters -> escape sequences)
951            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
952    #if WIN32
953                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
954    #else
955                // assuming POSIX
956                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
957    #endif
958            }
959    
960          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
961          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
962          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
963          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
964          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
965          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 1772  String LSCPServer::GetMidiInstrumentMapp Line 1901  String LSCPServer::GetMidiInstrumentMapp
1901          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);
1902          if (iter == mappings.end()) result.Error("there is no map entry with that index");          if (iter == mappings.end()) result.Error("there is no map entry with that index");
1903          else { // found          else { // found
1904              result.Add("NAME", iter->second.Name);  
1905                // convert the filename into the correct encoding as defined for LSCP
1906                // (especially in terms of special characters -> escape sequences)
1907    #if WIN32
1908                const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
1909    #else
1910                // assuming POSIX
1911                const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
1912    #endif
1913    
1914                result.Add("NAME", _escapeLscpResponse(iter->second.Name));
1915              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
1916              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);              result.Add("INSTRUMENT_FILE", instrumentFileName);
1917              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
1918              String instrumentName;              String instrumentName;
1919              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
# Line 1787  String LSCPServer::GetMidiInstrumentMapp Line 1926  String LSCPServer::GetMidiInstrumentMapp
1926                  }                  }
1927                  EngineFactory::Destroy(pEngine);                  EngineFactory::Destroy(pEngine);
1928              }              }
1929              result.Add("INSTRUMENT_NAME", instrumentName);              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
1930              switch (iter->second.LoadMode) {              switch (iter->second.LoadMode) {
1931                  case MidiInstrumentMapper::ON_DEMAND:                  case MidiInstrumentMapper::ON_DEMAND:
1932                      result.Add("LOAD_MODE", "ON_DEMAND");                      result.Add("LOAD_MODE", "ON_DEMAND");
# Line 1942  String LSCPServer::GetMidiInstrumentMap( Line 2081  String LSCPServer::GetMidiInstrumentMap(
2081      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2082      LSCPResultSet result;      LSCPResultSet result;
2083      try {      try {
2084          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2085          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2086      } catch (Exception e) {      } catch (Exception e) {
2087          result.Error(e);          result.Error(e);
# Line 1993  String LSCPServer::CreateFxSend(uint uiS Line 2132  String LSCPServer::CreateFxSend(uint uiS
2132      LSCPResultSet result;      LSCPResultSet result;
2133      try {      try {
2134          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2135            
2136          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2137          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2138    
# Line 2077  String LSCPServer::GetFxSendInfo(uint ui Line 2216  String LSCPServer::GetFxSendInfo(uint ui
2216      try {      try {
2217          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2218          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2219            
2220          // gather audio routing informations          // gather audio routing informations
2221          String AudioRouting;          String AudioRouting;
2222          for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {          for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
# Line 2086  String LSCPServer::GetFxSendInfo(uint ui Line 2225  String LSCPServer::GetFxSendInfo(uint ui
2225          }          }
2226    
2227          // success          // success
2228          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2229          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2230          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2231          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
# Line 2152  String LSCPServer::SetFxSendLevel(uint u Line 2291  String LSCPServer::SetFxSendLevel(uint u
2291      return result.Produce();      return result.Produce();
2292  }  }
2293    
2294    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2295        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2296        LSCPResultSet result;
2297        try {
2298            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2299            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2300            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2301            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2302            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2303            Engine* pEngine = pEngineChannel->GetEngine();
2304            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2305            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2306            InstrumentManager::instrument_id_t instrumentID;
2307            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2308            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2309            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2310        } catch (Exception e) {
2311            result.Error(e);
2312        }
2313        return result.Produce();
2314    }
2315    
2316  /**  /**
2317   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2318   */   */
# Line 2187  String LSCPServer::ResetSampler() { Line 2348  String LSCPServer::ResetSampler() {
2348   */   */
2349  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2350      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2351        const std::string description =
2352            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2353      LSCPResultSet result;      LSCPResultSet result;
2354      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2355      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2356      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2357  #if HAVE_SQLITE3  #if HAVE_SQLITE3
# Line 2196  String LSCPServer::GetServerInfo() { Line 2359  String LSCPServer::GetServerInfo() {
2359  #else  #else
2360      result.Add("INSTRUMENTS_DB_SUPPORT", "no");      result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2361  #endif  #endif
2362        
2363        return result.Produce();
2364    }
2365    
2366    /**
2367     * Will be called by the parser to return the current number of all active streams.
2368     */
2369    String LSCPServer::GetTotalStreamCount() {
2370        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2371        LSCPResultSet result;
2372        result.Add(pSampler->GetDiskStreamCount());
2373      return result.Produce();      return result.Produce();
2374  }  }
2375    
# Line 2238  String LSCPServer::SetGlobalVolume(doubl Line 2411  String LSCPServer::SetGlobalVolume(doubl
2411      return result.Produce();      return result.Produce();
2412  }  }
2413    
2414    String LSCPServer::GetFileInstruments(String Filename) {
2415        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2416        LSCPResultSet result;
2417        try {
2418            VerifyFile(Filename);
2419        } catch (Exception e) {
2420            result.Error(e);
2421            return result.Produce();
2422        }
2423        // try to find a sampler engine that can handle the file
2424        bool bFound = false;
2425        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2426        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2427            Engine* pEngine = NULL;
2428            try {
2429                pEngine = EngineFactory::Create(engineTypes[i]);
2430                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2431                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2432                if (pManager) {
2433                    std::vector<InstrumentManager::instrument_id_t> IDs =
2434                        pManager->GetInstrumentFileContent(Filename);
2435                    // return the amount of instruments in the file
2436                    result.Add(IDs.size());
2437                    // no more need to ask other engine types
2438                    bFound = true;
2439                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2440            } catch (Exception e) {
2441                // NOOP, as exception is thrown if engine doesn't support file
2442            }
2443            if (pEngine) EngineFactory::Destroy(pEngine);
2444        }
2445    
2446        if (!bFound) result.Error("Unknown file format");
2447        return result.Produce();
2448    }
2449    
2450    String LSCPServer::ListFileInstruments(String Filename) {
2451        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2452        LSCPResultSet result;
2453        try {
2454            VerifyFile(Filename);
2455        } catch (Exception e) {
2456            result.Error(e);
2457            return result.Produce();
2458        }
2459        // try to find a sampler engine that can handle the file
2460        bool bFound = false;
2461        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2462        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2463            Engine* pEngine = NULL;
2464            try {
2465                pEngine = EngineFactory::Create(engineTypes[i]);
2466                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2467                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2468                if (pManager) {
2469                    std::vector<InstrumentManager::instrument_id_t> IDs =
2470                        pManager->GetInstrumentFileContent(Filename);
2471                    // return a list of IDs of the instruments in the file
2472                    String s;
2473                    for (int j = 0; j < IDs.size(); j++) {
2474                        if (s.size()) s += ",";
2475                        s += ToString(IDs[j].Index);
2476                    }
2477                    result.Add(s);
2478                    // no more need to ask other engine types
2479                    bFound = true;
2480                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2481            } catch (Exception e) {
2482                // NOOP, as exception is thrown if engine doesn't support file
2483            }
2484            if (pEngine) EngineFactory::Destroy(pEngine);
2485        }
2486    
2487        if (!bFound) result.Error("Unknown file format");
2488        return result.Produce();
2489    }
2490    
2491    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2492        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2493        LSCPResultSet result;
2494        try {
2495            VerifyFile(Filename);
2496        } catch (Exception e) {
2497            result.Error(e);
2498            return result.Produce();
2499        }
2500        InstrumentManager::instrument_id_t id;
2501        id.FileName = Filename;
2502        id.Index    = InstrumentID;
2503        // try to find a sampler engine that can handle the file
2504        bool bFound = false;
2505        bool bFatalErr = false;
2506        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2507        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2508            Engine* pEngine = NULL;
2509            try {
2510                pEngine = EngineFactory::Create(engineTypes[i]);
2511                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2512                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2513                if (pManager) {
2514                    // check if the instrument index is valid
2515                    // FIXME: this won't work if an engine only supports parts of the instrument file
2516                    std::vector<InstrumentManager::instrument_id_t> IDs =
2517                        pManager->GetInstrumentFileContent(Filename);
2518                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2519                        std::stringstream ss;
2520                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2521                        bFatalErr = true;
2522                        throw Exception(ss.str());
2523                    }
2524                    // get the info of the requested instrument
2525                    InstrumentManager::instrument_info_t info =
2526                        pManager->GetInstrumentInfo(id);
2527                    // return detailed informations about the file
2528                    result.Add("NAME", info.InstrumentName);
2529                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2530                    result.Add("FORMAT_VERSION", info.FormatVersion);
2531                    result.Add("PRODUCT", info.Product);
2532                    result.Add("ARTISTS", info.Artists);
2533                    // no more need to ask other engine types
2534                    bFound = true;
2535                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2536            } catch (Exception e) {
2537                // usually NOOP, as exception is thrown if engine doesn't support file
2538                if (bFatalErr) result.Error(e);
2539            }
2540            if (pEngine) EngineFactory::Destroy(pEngine);
2541        }
2542    
2543        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2544        return result.Produce();
2545    }
2546    
2547    void LSCPServer::VerifyFile(String Filename) {
2548        #if WIN32
2549        WIN32_FIND_DATA win32FileAttributeData;
2550        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2551        if (!res) {
2552            std::stringstream ss;
2553            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2554            throw Exception(ss.str());
2555        }
2556        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2557            throw Exception("Directory is specified");
2558        }
2559        #else
2560        struct stat statBuf;
2561        int res = stat(Filename.c_str(), &statBuf);
2562        if (res) {
2563            std::stringstream ss;
2564            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2565            throw Exception(ss.str());
2566        }
2567    
2568        if (S_ISDIR(statBuf.st_mode)) {
2569            throw Exception("Directory is specified");
2570        }
2571        #endif
2572    }
2573    
2574  /**  /**
2575   * Will be called by the parser to subscribe a client (frontend) on the   * Will be called by the parser to subscribe a client (frontend) on the
2576   * server for receiving event messages.   * server for receiving event messages.
# Line 2294  String LSCPServer::RemoveDbInstrumentDir Line 2627  String LSCPServer::RemoveDbInstrumentDir
2627      return result.Produce();      return result.Produce();
2628  }  }
2629    
2630  String LSCPServer::GetDbInstrumentDirectoryCount(String Dir) {  String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2631      dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s)\n", Dir.c_str()));      dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2632      LSCPResultSet result;      LSCPResultSet result;
2633  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2634      try {      try {
2635          result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir));          result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2636      } catch (Exception e) {      } catch (Exception e) {
2637           result.Error(e);           result.Error(e);
2638      }      }
# Line 2309  String LSCPServer::GetDbInstrumentDirect Line 2642  String LSCPServer::GetDbInstrumentDirect
2642      return result.Produce();      return result.Produce();
2643  }  }
2644    
2645  String LSCPServer::GetDbInstrumentDirectories(String Dir) {  String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2646      dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));      dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2647      LSCPResultSet result;      LSCPResultSet result;
2648  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2649      try {      try {
2650          String list;          String list;
2651          StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir);          StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2652    
2653          for (int i = 0; i < dirs->size(); i++) {          for (int i = 0; i < dirs->size(); i++) {
2654              if (list != "") list += ",";              if (list != "") list += ",";
2655              list += "'" + dirs->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2656          }          }
2657    
2658          result.Add(list);          result.Add(list);
# Line 2339  String LSCPServer::GetDbInstrumentDirect Line 2672  String LSCPServer::GetDbInstrumentDirect
2672      try {      try {
2673          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2674    
2675          result.Add("DESCRIPTION", info.Description);          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2676          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
2677          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
2678      } catch (Exception e) {      } catch (Exception e) {
# Line 2381  String LSCPServer::MoveDbInstrumentDirec Line 2714  String LSCPServer::MoveDbInstrumentDirec
2714      return result.Produce();      return result.Produce();
2715  }  }
2716    
2717  String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {  String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2718      dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));      dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2719      LSCPResultSet result;      LSCPResultSet result;
2720  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2721      try {      try {
2722          InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);          InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2723      } catch (Exception e) {      } catch (Exception e) {
2724           result.Error(e);           result.Error(e);
2725      }      }
# Line 2396  String LSCPServer::SetDbInstrumentDirect Line 2729  String LSCPServer::SetDbInstrumentDirect
2729      return result.Produce();      return result.Produce();
2730  }  }
2731    
2732  String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index) {  String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2733      dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d)\n", DbDir.c_str(), FilePath.c_str(), Index));      dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2734      LSCPResultSet result;      LSCPResultSet result;
2735  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2736      try {      try {
2737          InstrumentsDb::GetInstrumentsDb()->AddInstruments(DbDir, FilePath, Index);          InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2738      } catch (Exception e) {      } catch (Exception e) {
2739           result.Error(e);           result.Error(e);
2740      }      }
# Line 2411  String LSCPServer::AddDbInstruments(Stri Line 2744  String LSCPServer::AddDbInstruments(Stri
2744      return result.Produce();      return result.Produce();
2745  }  }
2746    
2747  String LSCPServer::AddDbInstrumentsFlat(String DbDir, String FsDir) {  String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2748      dmsg(2,("LSCPServer: AddDbInstrumentsFlat(DbDir=%s,FilePath=%s)\n", DbDir.c_str(), FsDir.c_str()));      dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2749      LSCPResultSet result;      LSCPResultSet result;
2750  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2751      try {      try {
2752          InstrumentsDb::GetInstrumentsDb()->AddInstrumentsRecursive(DbDir, FsDir, true);          int id;
2753            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2754            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2755            if (bBackground) result = id;
2756      } catch (Exception e) {      } catch (Exception e) {
2757           result.Error(e);           result.Error(e);
2758      }      }
# Line 2426  String LSCPServer::AddDbInstrumentsFlat( Line 2762  String LSCPServer::AddDbInstrumentsFlat(
2762      return result.Produce();      return result.Produce();
2763  }  }
2764    
2765  String LSCPServer::AddDbInstrumentsNonrecursive(String DbDir, String FsDir) {  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2766      dmsg(2,("LSCPServer: AddDbInstrumentsNonrecursive(DbDir=%s,FilePath=%s)\n", DbDir.c_str(), FsDir.c_str()));      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2767      LSCPResultSet result;      LSCPResultSet result;
2768  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2769      try {      try {
2770          InstrumentsDb::GetInstrumentsDb()->AddInstrumentsNonrecursive(DbDir, FsDir);          int id;
2771            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2772            if (ScanMode.compare("RECURSIVE") == 0) {
2773               id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2774            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2775               id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2776            } else if (ScanMode.compare("FLAT") == 0) {
2777               id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2778            } else {
2779                throw Exception("Unknown scan mode: " + ScanMode);
2780            }
2781    
2782            if (bBackground) result = id;
2783      } catch (Exception e) {      } catch (Exception e) {
2784           result.Error(e);           result.Error(e);
2785      }      }
# Line 2456  String LSCPServer::RemoveDbInstrument(St Line 2804  String LSCPServer::RemoveDbInstrument(St
2804      return result.Produce();      return result.Produce();
2805  }  }
2806    
2807  String LSCPServer::GetDbInstrumentCount(String Dir) {  String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2808      dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s)\n", Dir.c_str()));      dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2809      LSCPResultSet result;      LSCPResultSet result;
2810  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2811      try {      try {
2812          result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir));          result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2813      } catch (Exception e) {      } catch (Exception e) {
2814           result.Error(e);           result.Error(e);
2815      }      }
# Line 2471  String LSCPServer::GetDbInstrumentCount( Line 2819  String LSCPServer::GetDbInstrumentCount(
2819      return result.Produce();      return result.Produce();
2820  }  }
2821    
2822  String LSCPServer::GetDbInstruments(String Dir) {  String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2823      dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s)\n", Dir.c_str()));      dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2824      LSCPResultSet result;      LSCPResultSet result;
2825  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2826      try {      try {
2827          String list;          String list;
2828          StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir);          StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2829    
2830          for (int i = 0; i < instrs->size(); i++) {          for (int i = 0; i < instrs->size(); i++) {
2831              if (list != "") list += ",";              if (list != "") list += ",";
2832              list += "'" + instrs->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2833          }          }
2834    
2835          result.Add(list);          result.Add(list);
# Line 2508  String LSCPServer::GetDbInstrumentInfo(S Line 2856  String LSCPServer::GetDbInstrumentInfo(S
2856          result.Add("SIZE", (int)info.Size);          result.Add("SIZE", (int)info.Size);
2857          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
2858          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
2859          result.Add("DESCRIPTION", FilterEndlines(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2860          result.Add("IS_DRUM", info.IsDrum);          result.Add("IS_DRUM", info.IsDrum);
2861          result.Add("PRODUCT", FilterEndlines(info.Product));          result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2862          result.Add("ARTISTS", FilterEndlines(info.Artists));          result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2863          result.Add("KEYWORDS", FilterEndlines(info.Keywords));          result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2864        } catch (Exception e) {
2865             result.Error(e);
2866        }
2867    #else
2868        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2869    #endif
2870        return result.Produce();
2871    }
2872    
2873    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
2874        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
2875        LSCPResultSet result;
2876    #if HAVE_SQLITE3
2877        try {
2878            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
2879    
2880            result.Add("FILES_TOTAL", job.FilesTotal);
2881            result.Add("FILES_SCANNED", job.FilesScanned);
2882            result.Add("SCANNING", job.Scanning);
2883            result.Add("STATUS", job.Status);
2884      } catch (Exception e) {      } catch (Exception e) {
2885           result.Error(e);           result.Error(e);
2886      }      }
# Line 2552  String LSCPServer::MoveDbInstrument(Stri Line 2920  String LSCPServer::MoveDbInstrument(Stri
2920      return result.Produce();      return result.Produce();
2921  }  }
2922    
2923    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
2924        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2925        LSCPResultSet result;
2926    #if HAVE_SQLITE3
2927        try {
2928            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
2929        } catch (Exception e) {
2930             result.Error(e);
2931        }
2932    #else
2933        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2934    #endif
2935        return result.Produce();
2936    }
2937    
2938  String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {  String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
2939      dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));      dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
2940      LSCPResultSet result;      LSCPResultSet result;
# Line 2567  String LSCPServer::SetDbInstrumentDescri Line 2950  String LSCPServer::SetDbInstrumentDescri
2950      return result.Produce();      return result.Produce();
2951  }  }
2952    
2953    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
2954        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
2955        LSCPResultSet result;
2956    #if HAVE_SQLITE3
2957        try {
2958            SearchQuery Query;
2959            std::map<String,String>::iterator iter;
2960            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
2961                if (iter->first.compare("NAME") == 0) {
2962                    Query.Name = iter->second;
2963                } else if (iter->first.compare("CREATED") == 0) {
2964                    Query.SetCreated(iter->second);
2965                } else if (iter->first.compare("MODIFIED") == 0) {
2966                    Query.SetModified(iter->second);
2967                } else if (iter->first.compare("DESCRIPTION") == 0) {
2968                    Query.Description = iter->second;
2969                } else {
2970                    throw Exception("Unknown search criteria: " + iter->first);
2971                }
2972            }
2973    
2974            String list;
2975            StringListPtr pDirectories =
2976                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
2977    
2978            for (int i = 0; i < pDirectories->size(); i++) {
2979                if (list != "") list += ",";
2980                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
2981            }
2982    
2983            result.Add(list);
2984        } catch (Exception e) {
2985             result.Error(e);
2986        }
2987    #else
2988        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2989    #endif
2990        return result.Produce();
2991    }
2992    
2993    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
2994        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
2995        LSCPResultSet result;
2996    #if HAVE_SQLITE3
2997        try {
2998            SearchQuery Query;
2999            std::map<String,String>::iterator iter;
3000            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3001                if (iter->first.compare("NAME") == 0) {
3002                    Query.Name = iter->second;
3003                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3004                    Query.SetFormatFamilies(iter->second);
3005                } else if (iter->first.compare("SIZE") == 0) {
3006                    Query.SetSize(iter->second);
3007                } else if (iter->first.compare("CREATED") == 0) {
3008                    Query.SetCreated(iter->second);
3009                } else if (iter->first.compare("MODIFIED") == 0) {
3010                    Query.SetModified(iter->second);
3011                } else if (iter->first.compare("DESCRIPTION") == 0) {
3012                    Query.Description = iter->second;
3013                } else if (iter->first.compare("IS_DRUM") == 0) {
3014                    if (!strcasecmp(iter->second.c_str(), "true")) {
3015                        Query.InstrType = SearchQuery::DRUM;
3016                    } else {
3017                        Query.InstrType = SearchQuery::CHROMATIC;
3018                    }
3019                } else if (iter->first.compare("PRODUCT") == 0) {
3020                     Query.Product = iter->second;
3021                } else if (iter->first.compare("ARTISTS") == 0) {
3022                     Query.Artists = iter->second;
3023                } else if (iter->first.compare("KEYWORDS") == 0) {
3024                     Query.Keywords = iter->second;
3025                } else {
3026                    throw Exception("Unknown search criteria: " + iter->first);
3027                }
3028            }
3029    
3030            String list;
3031            StringListPtr pInstruments =
3032                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3033    
3034            for (int i = 0; i < pInstruments->size(); i++) {
3035                if (list != "") list += ",";
3036                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3037            }
3038    
3039            result.Add(list);
3040        } catch (Exception e) {
3041             result.Error(e);
3042        }
3043    #else
3044        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3045    #endif
3046        return result.Produce();
3047    }
3048    
3049    String LSCPServer::FormatInstrumentsDb() {
3050        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3051        LSCPResultSet result;
3052    #if HAVE_SQLITE3
3053        try {
3054            InstrumentsDb::GetInstrumentsDb()->Format();
3055        } catch (Exception e) {
3056             result.Error(e);
3057        }
3058    #else
3059        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3060    #endif
3061        return result.Produce();
3062    }
3063    
3064    
3065  /**  /**
3066   * Will be called by the parser to enable or disable echo mode; if echo   * Will be called by the parser to enable or disable echo mode; if echo
# Line 2586  String LSCPServer::SetEcho(yyparse_param Line 3080  String LSCPServer::SetEcho(yyparse_param
3080      }      }
3081      return result.Produce();      return result.Produce();
3082  }  }
   
 String LSCPServer::FilterEndlines(String s) {  
     String s2 = s;  
     for (int i = 0; i < s2.length(); i++) {  
         if (s2.at(i) == '\r') s2.at(i) = ' ';  
         else if (s2.at(i) == '\n') s2.at(i) = ' ';  
     }  
       
     return s2;  
 }  

Legend:
Removed from v.1161  
changed lines
  Added in v.1649

  ViewVC Help
Powered by ViewVC