/[svn]/linuxsampler/trunk/src/db/InstrumentsDb.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/db/InstrumentsDb.cpp

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

revision 1644 by persson, Sat Jan 19 16:55:03 2008 UTC revision 1911 by senoner, Sat Jun 6 13:50:36 2009 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   Copyright (C) 2007, 2008 Grigor Iliev                                 *   *   Copyright (C) 2007-2009 Grigor Iliev, Benno Senoner                   *
4   *                                                                         *   *                                                                         *
5   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
6   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 20  Line 20 
20    
21  #include "InstrumentsDb.h"  #include "InstrumentsDb.h"
22    
23    #include "../common/File.h"
24    #include "../common/Path.h"
25  #include "../common/global_private.h"  #include "../common/global_private.h"
26    
27  #include <iostream>  #include <iostream>
28  #include <sstream>  #include <sstream>
29  #include <vector>  #include <vector>
 #include <dirent.h>  
30  #include <errno.h>  #include <errno.h>
31    #ifndef WIN32
32  #include <fnmatch.h>  #include <fnmatch.h>
33    #endif
34    
35  #include "../common/Exception.h"  #include "../common/Exception.h"
36    
# Line 35  namespace LinuxSampler { Line 38  namespace LinuxSampler {
38    
39      InstrumentsDb InstrumentsDb::instance;      InstrumentsDb InstrumentsDb::instance;
40    
41      void InstrumentsDb::CreateInstrumentsDb(String File) {      void InstrumentsDb::CreateInstrumentsDb(String FilePath) {
42          struct stat statBuf;          File f = File(FilePath);
43          int res = stat(File.c_str(), &statBuf);          if (f.Exist()) {
44          if (!res) {              throw Exception("File exists: " + FilePath);
             throw Exception("File exists: " + File);  
45          }          }
46                    
47          GetInstrumentsDb()->SetDbFile(File);          GetInstrumentsDb()->SetDbFile(FilePath);
48    
49          String sql =          String sql =
50              "  CREATE TABLE instr_dirs (                                      "              "  CREATE TABLE instr_dirs (                                      "
# Line 87  namespace LinuxSampler { Line 89  namespace LinuxSampler {
89    
90      InstrumentsDb::InstrumentsDb() {      InstrumentsDb::InstrumentsDb() {
91          db = NULL;          db = NULL;
         DbInstrumentsMutex = Mutex();  
92          InTransaction = false;          InTransaction = false;
93      }      }
94    
# Line 120  namespace LinuxSampler { Line 121  namespace LinuxSampler {
121      sqlite3* InstrumentsDb::GetDb() {      sqlite3* InstrumentsDb::GetDb() {
122          if ( db != NULL) return db;          if ( db != NULL) return db;
123    
124          if (DbFile.empty()) DbFile = CONFIG_DEFAULT_INSTRUMENTS_DB_LOCATION;          if (DbFile.empty()) {
125                        #ifndef WIN32
126                        DbFile = CONFIG_DEFAULT_INSTRUMENTS_DB_LOCATION;
127                            #else
128                            char *userprofile = getenv("USERPROFILE");
129                            if(userprofile) {
130                                DbFile = userprofile;
131                                    DbFile += "\\.linuxsampler\\instruments.db";
132                        }
133                            else {
134                                // in case USERPROFILE is not set (which should not occur)
135                                DbFile = "instruments.db";
136                            }
137                            #endif
138                }
139                  #if defined(__APPLE__)  /* 20071224 Toshi Nagata  */                  #if defined(__APPLE__)  /* 20071224 Toshi Nagata  */
140                  if (DbFile.find("~") == 0)                  if (DbFile.find("~") == 0)
141                          DbFile.replace(0, 1, getenv("HOME"));                          DbFile.replace(0, 1, getenv("HOME"));
# Line 131  namespace LinuxSampler { Line 146  namespace LinuxSampler {
146              db = NULL;              db = NULL;
147              throw Exception("Cannot open instruments database: " + DbFile);              throw Exception("Cannot open instruments database: " + DbFile);
148          }          }
149    #ifndef WIN32
150          rc = sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, NULL, Regexp, NULL, NULL);          rc = sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, NULL, Regexp, NULL, NULL);
151          if (rc) { throw Exception("Failed to add user function for handling regular expressions."); }          if (rc) { throw Exception("Failed to add user function for handling regular expressions."); }
152    #endif
153    
154          // TODO: remove this in the next version          // TODO: remove this in the next version
155          try {          try {
# Line 261  namespace LinuxSampler { Line 278  namespace LinuxSampler {
278          return ExecSqlInt(sql.str(), DirName);          return ExecSqlInt(sql.str(), DirName);
279      }      }
280    
281        int InstrumentsDb::GetDirectoryId(int InstrId) {
282            dmsg(2,("InstrumentsDb: GetDirectoryId(InstrId=%d)\n", InstrId));
283            std::stringstream sql;
284            sql << "SELECT dir_id FROM instruments WHERE instr_id=" << InstrId;
285            return ExecSqlInt(sql.str());
286        }
287    
288      String InstrumentsDb::GetDirectoryName(int DirId) {      String InstrumentsDb::GetDirectoryName(int DirId) {
289          String sql = "SELECT dir_name FROM instr_dirs WHERE dir_id=" + ToString(DirId);          String sql = "SELECT dir_name FROM instr_dirs WHERE dir_id=" + ToString(DirId);
290          String name = ExecSqlString(sql);          String name = ExecSqlString(sql);
# Line 285  namespace LinuxSampler { Line 309  namespace LinuxSampler {
309                  path = "/" + path;                  path = "/" + path;
310                  break;                  break;
311              }              }
312              path = GetDirectoryName(DirId) + path;              path = GetDirectoryName(DirId) + "/" + path;
313              DirId = GetParentDirectoryId(DirId);              DirId = GetParentDirectoryId(DirId);
314          }          }
315    
# Line 293  namespace LinuxSampler { Line 317  namespace LinuxSampler {
317    
318          return path;          return path;
319      }      }
320        
321        StringListPtr InstrumentsDb::GetInstrumentsByFile(String File) {
322            dmsg(2,("InstrumentsDb: GetInstrumentsByFile(File=%s)\n", File.c_str()));
323    
324            StringListPtr instrs(new std::vector<String>);
325            
326            BeginTransaction();
327            try {
328                File = toEscapedFsPath(File);
329                IntListPtr ids = ExecSqlIntList("SELECT instr_id FROM instruments WHERE instr_file=?", File);
330                
331                for (int i = 0; i < ids->size(); i++) {
332                    String name = GetInstrumentName(ids->at(i));
333                    String dir = GetDirectoryPath(GetDirectoryId(ids->at(i)));
334                    instrs->push_back(dir + name);
335                }
336            } catch (Exception e) {
337                EndTransaction();
338                throw e;
339            }
340            EndTransaction();
341            
342            return instrs;
343        }
344    
345      void InstrumentsDb::AddDirectory(String Dir) {      void InstrumentsDb::AddDirectory(String Dir) {
346          dmsg(2,("InstrumentsDb: AddDirectory(Dir=%s)\n", Dir.c_str()));          dmsg(2,("InstrumentsDb: AddDirectory(Dir=%s)\n", Dir.c_str()));
# Line 611  namespace LinuxSampler { Line 659  namespace LinuxSampler {
659          FireDirectoryInfoChanged(Dir);          FireDirectoryInfoChanged(Dir);
660      }      }
661    
662      int InstrumentsDb::AddInstruments(ScanMode Mode, String DbDir, String FsDir, bool bBackground) {      int InstrumentsDb::AddInstruments(ScanMode Mode, String DbDir, String FsDir, bool bBackground, bool insDir) {
663          dmsg(2,("InstrumentsDb: AddInstruments(Mode=%d,DbDir=%s,FsDir=%s,bBackground=%d)\n", Mode, DbDir.c_str(), FsDir.c_str(), bBackground));          dmsg(2,("InstrumentsDb: AddInstruments(Mode=%d,DbDir=%s,FsDir=%s,bBackground=%d,insDir=%d)\n", Mode, DbDir.c_str(), FsDir.c_str(), bBackground, insDir));
664          if(!bBackground) {          if(!bBackground) {
665              switch (Mode) {              switch (Mode) {
666                  case NON_RECURSIVE:                  case NON_RECURSIVE:
667                      AddInstrumentsNonrecursive(DbDir, FsDir);                      AddInstrumentsNonrecursive(DbDir, FsDir, insDir);
668                      break;                      break;
669                  case RECURSIVE:                  case RECURSIVE:
670                      AddInstrumentsRecursive(DbDir, FsDir);                      AddInstrumentsRecursive(DbDir, FsDir, false, insDir);
671                      break;                      break;
672                  case FLAT:                  case FLAT:
673                      AddInstrumentsRecursive(DbDir, FsDir, true);                      AddInstrumentsRecursive(DbDir, FsDir, true, insDir);
674                      break;                      break;
675                  default:                  default:
676                      throw Exception("Unknown scan mode");                      throw Exception("Unknown scan mode");
# Line 633  namespace LinuxSampler { Line 681  namespace LinuxSampler {
681    
682          ScanJob job;          ScanJob job;
683          int jobId = Jobs.AddJob(job);          int jobId = Jobs.AddJob(job);
684          InstrumentsDbThread.Execute(new AddInstrumentsJob(jobId, Mode, DbDir, FsDir));          InstrumentsDbThread.Execute(new AddInstrumentsJob(jobId, Mode, DbDir, FsDir, insDir));
685    
686          return jobId;          return jobId;
687      }      }
# Line 641  namespace LinuxSampler { Line 689  namespace LinuxSampler {
689      int InstrumentsDb::AddInstruments(String DbDir, String FilePath, int Index, bool bBackground) {      int InstrumentsDb::AddInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
690          dmsg(2,("InstrumentsDb: AddInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));          dmsg(2,("InstrumentsDb: AddInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
691          if(!bBackground) {          if(!bBackground) {
692              AddInstruments(DbDir, FilePath, Index);              AddInstruments(DbDir, false, FilePath, Index);
693              return -1;              return -1;
694          }          }
695    
696          ScanJob job;          ScanJob job;
697          int jobId = Jobs.AddJob(job);          int jobId = Jobs.AddJob(job);
698          InstrumentsDbThread.Execute(new AddInstrumentsFromFileJob(jobId, DbDir, FilePath, Index));          InstrumentsDbThread.Execute(new AddInstrumentsFromFileJob(jobId, DbDir, FilePath, Index, false));
699    
700          return jobId;          return jobId;
701      }      }
702    
703      void InstrumentsDb::AddInstruments(String DbDir, String FilePath, int Index, ScanProgress* pProgress) {      void InstrumentsDb::AddInstruments(String DbDir, bool insDir, String FilePath, int Index, ScanProgress* pProgress) {
704          dmsg(2,("InstrumentsDb: AddInstruments(DbDir=%s,FilePath=%s,Index=%d)\n", DbDir.c_str(), FilePath.c_str(), Index));          dmsg(2,("InstrumentsDb: AddInstruments(DbDir=%s,insDir=%d,FilePath=%s,Index=%d)\n", DbDir.c_str(), insDir, FilePath.c_str(), Index));
705          if (DbDir.empty() || FilePath.empty()) return;          if (DbDir.empty() || FilePath.empty()) return;
706                    
707          DbInstrumentsMutex.Lock();          DbInstrumentsMutex.Lock();
# Line 661  namespace LinuxSampler { Line 709  namespace LinuxSampler {
709              int dirId = GetDirectoryId(DbDir);              int dirId = GetDirectoryId(DbDir);
710              if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedText(DbDir));              if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedText(DbDir));
711    
712              struct stat statBuf;              File f = File(FilePath);
713              int res = stat(FilePath.c_str(), &statBuf);              if (!f.Exist()) {
             if (res) {  
714                  std::stringstream ss;                  std::stringstream ss;
715                  ss << "Fail to stat `" << FilePath << "`: " << strerror(errno);                  ss << "Fail to stat `" << FilePath << "`: " << f.GetErrorMsg();
716                  throw Exception(ss.str());                  throw Exception(ss.str());
717              }              }
718    
719              if (!S_ISREG(statBuf.st_mode)) {              if (!f.IsFile()) {
720                  std::stringstream ss;                  std::stringstream ss;
721                  ss << "`" << FilePath << "` is not an instrument file";                  ss << "`" << FilePath << "` is not an instrument file";
722                  throw Exception(ss.str());                  throw Exception(ss.str());
723              }              }
724    
725              AddInstrumentsFromFile(DbDir, FilePath, Index, pProgress);              String dir = insDir ? PrepareSubdirectory(DbDir, FilePath) : DbDir;
726                AddInstrumentsFromFile(dir, FilePath, Index, pProgress);
727          } catch (Exception e) {          } catch (Exception e) {
728              DbInstrumentsMutex.Unlock();              DbInstrumentsMutex.Unlock();
729              throw e;              throw e;
# Line 684  namespace LinuxSampler { Line 732  namespace LinuxSampler {
732          DbInstrumentsMutex.Unlock();          DbInstrumentsMutex.Unlock();
733      }      }
734    
735      void InstrumentsDb::AddInstrumentsNonrecursive(String DbDir, String FsDir, ScanProgress* pProgress) {      void InstrumentsDb::AddInstrumentsNonrecursive(String DbDir, String FsDir, bool insDir, ScanProgress* pProgress) {
736          dmsg(2,("InstrumentsDb: AddInstrumentsNonrecursive(DbDir=%s,FsDir=%s)\n", DbDir.c_str(), FsDir.c_str()));          dmsg(2,("InstrumentsDb: AddInstrumentsNonrecursive(DbDir=%s,FsDir=%s,insDir=%d)\n", DbDir.c_str(), FsDir.c_str(), insDir));
737          if (DbDir.empty() || FsDir.empty()) return;          if (DbDir.empty() || FsDir.empty()) return;
738                    
739          DbInstrumentsMutex.Lock();          DbInstrumentsMutex.Lock();
# Line 693  namespace LinuxSampler { Line 741  namespace LinuxSampler {
741              int dirId = GetDirectoryId(DbDir);              int dirId = GetDirectoryId(DbDir);
742              if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedPath(DbDir));              if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedPath(DbDir));
743    
744              struct stat statBuf;              File f = File(FsDir);
745              int res = stat(FsDir.c_str(), &statBuf);              if (!f.Exist()) {
             if (res) {  
746                  std::stringstream ss;                  std::stringstream ss;
747                  ss << "Fail to stat `" << FsDir << "`: " << strerror(errno);                  ss << "Fail to stat `" << FsDir << "`: " << f.GetErrorMsg();
748                  throw Exception(ss.str());                  throw Exception(ss.str());
749              }              }
750    
751              if (!S_ISDIR(statBuf.st_mode)) {              if (!f.IsDirectory()) {
752                  throw Exception("Directory expected");                  throw Exception("Directory expected: " + FsDir);
753              }              }
754                            
755              if (FsDir.at(FsDir.length() - 1) != '/') FsDir.append("/");              if (FsDir.at(FsDir.length() - 1) != File::DirSeparator) {
756                    FsDir.push_back(File::DirSeparator);
             DIR* pDir = opendir(FsDir.c_str());  
             if (pDir == NULL) {  
                 std::stringstream ss;  
                 ss << "The scanning of directory `" << FsDir << "` failed: ";  
                 ss << strerror(errno);  
                 std::cerr << ss.str();  
                 DbInstrumentsMutex.Unlock();  
                 return;  
757              }              }
758                
759              struct dirent* pEnt = readdir(pDir);              try {
760              while (pEnt != NULL) {                  FileListPtr fileList = File::GetFiles(FsDir);
761                  if (pEnt->d_type != DT_REG) {                  for (int i = 0; i < fileList->size(); i++) {
762                      pEnt = readdir(pDir);                      String dir = insDir ? PrepareSubdirectory(DbDir, fileList->at(i)) : DbDir;
763                      continue;                                          AddInstrumentsFromFile(dir, FsDir + fileList->at(i), -1, pProgress);
764                  }                  }
765                } catch(Exception e) {
766                  AddInstrumentsFromFile(DbDir, FsDir + String(pEnt->d_name), -1, pProgress);                  e.PrintMessage();
767                  pEnt = readdir(pDir);                  DbInstrumentsMutex.Unlock();
768              }                  return;
   
             if (closedir(pDir)) {  
                 std::stringstream ss;  
                 ss << "Failed to close directory `" << FsDir << "`: ";  
                 ss << strerror(errno);  
                 std::cerr << ss.str();  
769              }              }
770          } catch (Exception e) {          } catch (Exception e) {
771              DbInstrumentsMutex.Unlock();              DbInstrumentsMutex.Unlock();
# Line 742  namespace LinuxSampler { Line 775  namespace LinuxSampler {
775          DbInstrumentsMutex.Unlock();          DbInstrumentsMutex.Unlock();
776      }      }
777    
778      void InstrumentsDb::AddInstrumentsRecursive(String DbDir, String FsDir, bool Flat, ScanProgress* pProgress) {      void InstrumentsDb::AddInstrumentsRecursive(String DbDir, String FsDir, bool Flat, bool insDir, ScanProgress* pProgress) {
779          dmsg(2,("InstrumentsDb: AddInstrumentsRecursive(DbDir=%s,FsDir=%s,Flat=%d)\n", DbDir.c_str(), FsDir.c_str(), Flat));          dmsg(2,("InstrumentsDb: AddInstrumentsRecursive(DbDir=%s,FsDir=%s,Flat=%d,insDir=%d)\n", DbDir.c_str(), FsDir.c_str(), Flat, insDir));
780          if (pProgress != NULL) {          if (pProgress != NULL) {
781              pProgress->SetTotalFileCount(InstrumentFileCounter::Count(FsDir));              InstrumentFileCounter c;
782                pProgress->SetTotalFileCount(c.Count(FsDir));
783          }          }
784    
785          DirectoryScanner::Scan(DbDir, FsDir, Flat, pProgress);          DirectoryScanner d;
786            d.Scan(DbDir, FsDir, Flat, insDir, pProgress);
787      }      }
788    
789      int InstrumentsDb::GetInstrumentCount(int DirId) {      int InstrumentsDb::GetInstrumentCount(int DirId) {
# Line 1137  namespace LinuxSampler { Line 1172  namespace LinuxSampler {
1172                  }                  }
1173              }              }
1174          } catch(Exception e) {          } catch(Exception e) {
1175              std::cerr << e.Message() << std::endl;              e.PrintMessage();
1176          }          }
1177      }      }
1178    
1179      void InstrumentsDb::AddGigInstruments(String DbDir, String File, int Index, ScanProgress* pProgress) {      void InstrumentsDb::AddGigInstruments(String DbDir, String FilePath, int Index, ScanProgress* pProgress) {
1180          dmsg(2,("InstrumentsDb: AddGigInstruments(DbDir=%s,File=%s,Index=%d)\n", DbDir.c_str(), File.c_str(), Index));          dmsg(2,("InstrumentsDb: AddGigInstruments(DbDir=%s,FilePath=%s,Index=%d)\n", DbDir.c_str(), FilePath.c_str(), Index));
1181          int dirId = GetDirectoryId(DbDir);          int dirId = GetDirectoryId(DbDir);
1182          if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedPath(DbDir));          if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedPath(DbDir));
1183    
1184          struct stat statBuf;          File f = File(FilePath);
1185          int res = stat(File.c_str(), &statBuf);          if (!f.Exist()) {
         if (res) {  
1186              std::stringstream ss;              std::stringstream ss;
1187              ss << "Fail to stat `" << File << "`: " << strerror(errno);              ss << "Fail to stat `" << FilePath << "`: " << f.GetErrorMsg();
1188              throw Exception(ss.str());              throw Exception(ss.str());
1189          }          }
1190    
1191          if (!S_ISREG(statBuf.st_mode)) {          if (!f.IsFile()) {
1192              std::stringstream ss;              std::stringstream ss;
1193              ss << "`" << File << "` is not a regular file";              ss << "`" << FilePath << "` is not a regular file";
1194              throw Exception(ss.str());              throw Exception(ss.str());
1195          }          }
1196    
1197            bool unlocked = false;
1198          RIFF::File* riff = NULL;          RIFF::File* riff = NULL;
1199          gig::File* gig = NULL;          gig::File* gig = NULL;
1200          try {          try {
1201              riff = new RIFF::File(File);              riff = new RIFF::File(FilePath);
1202              gig::File* gig = new gig::File(riff);              gig::File* gig = new gig::File(riff);
1203              gig->SetAutoLoad(false); // avoid time consuming samples scanning              gig->SetAutoLoad(false); // avoid time consuming samples scanning
1204    
# Line 1171  namespace LinuxSampler { Line 1206  namespace LinuxSampler {
1206              sql << "INSERT INTO instruments (dir_id,instr_name,instr_file,";              sql << "INSERT INTO instruments (dir_id,instr_name,instr_file,";
1207              sql << "instr_nr,format_family,format_version,instr_size,";              sql << "instr_nr,format_family,format_version,instr_size,";
1208              sql << "description,is_drum,product,artists,keywords) VALUES (";              sql << "description,is_drum,product,artists,keywords) VALUES (";
1209              sql << dirId << ",?,?,?,'GIG',?," << statBuf.st_size << ",?,?,?,?,?)";              sql << dirId << ",?,?,?,'GIG',?," << f.GetSize() << ",?,?,?,?,?)";
1210    
1211              sqlite3_stmt* pStmt = NULL;              sqlite3_stmt* pStmt = NULL;
1212    
# Line 1180  namespace LinuxSampler { Line 1215  namespace LinuxSampler {
1215                  throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));                  throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1216              }              }
1217    
1218              String s = toEscapedFsPath(File);              String s = FilePath;
1219    
1220                #if WIN32
1221                for (int i = 0; i < s.length(); i++) {
1222                    if (s[i] == '\\') s[i] = '/';
1223                }
1224                #endif
1225    
1226                s = toEscapedFsPath(s);
1227              BindTextParam(pStmt, 2, s);              BindTextParam(pStmt, 2, s);
1228              String ver = "";              String ver = "";
1229              if (gig->pVersion != NULL) ver = ToString(gig->pVersion->major);              if (gig->pVersion != NULL) ver = ToString(gig->pVersion->major);
# Line 1188  namespace LinuxSampler { Line 1231  namespace LinuxSampler {
1231    
1232              if (Index == -1) {              if (Index == -1) {
1233                  int instrIndex = 0;                  int instrIndex = 0;
1234                    // Assume that it's locked and should be unlocked at this point
1235                    // to be able to use the database from another threads
1236                    if (!InTransaction) {
1237                        DbInstrumentsMutex.Unlock();
1238                        unlocked = true;
1239                    } else {
1240                        std::cerr << "Shouldn't be in transaction when adding instruments." << std::endl;
1241                    }
1242    
1243                  if (pProgress != NULL) gig->GetInstrument(0, &(pProgress->GigFileProgress)); // TODO: this workaround should be fixed                  if (pProgress != NULL) gig->GetInstrument(0, &(pProgress->GigFileProgress)); // TODO: this workaround should be fixed
1244                  gig::Instrument* pInstrument = gig->GetFirstInstrument();                  gig::Instrument* pInstrument = gig->GetFirstInstrument();
1245    
1246                    if (!InTransaction) DbInstrumentsMutex.Lock();
1247                  while (pInstrument) {                  while (pInstrument) {
1248                      BindTextParam(pStmt, 7, gig->pInfo->Product);                      BindTextParam(pStmt, 7, gig->pInfo->Product);
1249                      BindTextParam(pStmt, 8, gig->pInfo->Artists);                      BindTextParam(pStmt, 8, gig->pInfo->Artists);
1250                      BindTextParam(pStmt, 9, gig->pInfo->Keywords);                      BindTextParam(pStmt, 9, gig->pInfo->Keywords);
1251                      AddGigInstrument(pStmt, DbDir, dirId, File, pInstrument, instrIndex);                      AddGigInstrument(pStmt, DbDir, dirId, FilePath, pInstrument, instrIndex);
1252    
1253                      instrIndex++;                      instrIndex++;
1254                      pInstrument = gig->GetNextInstrument();                      pInstrument = gig->GetNextInstrument();
# Line 1207  namespace LinuxSampler { Line 1261  namespace LinuxSampler {
1261                      BindTextParam(pStmt, 7, gig->pInfo->Product);                      BindTextParam(pStmt, 7, gig->pInfo->Product);
1262                      BindTextParam(pStmt, 8, gig->pInfo->Artists);                      BindTextParam(pStmt, 8, gig->pInfo->Artists);
1263                      BindTextParam(pStmt, 9, gig->pInfo->Keywords);                      BindTextParam(pStmt, 9, gig->pInfo->Keywords);
1264                      AddGigInstrument(pStmt, DbDir, dirId, File, pInstrument, Index);                      AddGigInstrument(pStmt, DbDir, dirId, FilePath, pInstrument, Index);
1265                  }                  }
1266              }              }
1267    
# Line 1217  namespace LinuxSampler { Line 1271  namespace LinuxSampler {
1271          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
1272              if (gig != NULL) delete gig;              if (gig != NULL) delete gig;
1273              if (riff != NULL) delete riff;              if (riff != NULL) delete riff;
1274                if (unlocked) DbInstrumentsMutex.Lock();
1275              std::stringstream ss;              std::stringstream ss;
1276              ss << "Failed to scan `" << File << "`: " << e.Message;              ss << "Failed to scan `" << FilePath << "`: " << e.Message;
1277                            
1278              throw Exception(ss.str());              throw Exception(ss.str());
1279          } catch (Exception e) {          } catch (Exception e) {
1280              if (gig != NULL) delete gig;              if (gig != NULL) delete gig;
1281              if (riff != NULL) delete riff;              if (riff != NULL) delete riff;
1282                if (unlocked) DbInstrumentsMutex.Lock();
1283              throw e;              throw e;
1284          } catch (...) {          } catch (...) {
1285              if (gig != NULL) delete gig;              if (gig != NULL) delete gig;
1286              if (riff != NULL) delete riff;              if (riff != NULL) delete riff;
1287              throw Exception("Failed to scan `" + File + "`");              if (unlocked) DbInstrumentsMutex.Lock();
1288                throw Exception("Failed to scan `" + FilePath + "`");
1289          }          }
1290      }      }
1291    
1292      void InstrumentsDb::AddGigInstrument(sqlite3_stmt* pStmt, String DbDir, int DirId, String File, gig::Instrument* pInstrument, int Index) {      void InstrumentsDb::AddGigInstrument(sqlite3_stmt* pStmt, String DbDir, int DirId, String File, gig::Instrument* pInstrument, int Index) {
1293            dmsg(2,("InstrumentsDb: AddGigInstrument(DbDir=%s,DirId=%d,File=%s,Index=%d)\n", DbDir.c_str(), DirId, File.c_str(), Index));
1294          String name = pInstrument->pInfo->Name;          String name = pInstrument->pInfo->Name;
1295          if (name == "") return;          if (name == "") return;
1296          name = GetUniqueInstrumentName(DirId, name);          name = GetUniqueName(DirId, name);
1297                    
1298          std::stringstream sql2;          std::stringstream sql2;
1299          sql2 << "SELECT COUNT(*) FROM instruments WHERE instr_file=? AND ";          sql2 << "SELECT COUNT(*) FROM instruments WHERE instr_file=? AND ";
# Line 1331  namespace LinuxSampler { Line 1389  namespace LinuxSampler {
1389    
1390          return instrumentFinder.GetInstruments();          return instrumentFinder.GetInstruments();
1391      }      }
1392        
1393        StringListPtr InstrumentsDb::FindLostInstrumentFiles() {
1394            dmsg(2,("InstrumentsDb: FindLostInstrumentFiles()\n"));
1395    
1396            BeginTransaction();
1397            try {
1398                StringListPtr files = ExecSqlStringList("SELECT DISTINCT instr_file FROM instruments");
1399                StringListPtr result(new std::vector<String>);
1400                for (int i = 0; i < files->size(); i++) {
1401                    File f(toNonEscapedFsPath(files->at(i)));
1402                    if (!f.Exist()) result->push_back(files->at(i));
1403                }
1404                return result;
1405            } catch (Exception e) {
1406                EndTransaction();
1407                throw e;
1408            }
1409            EndTransaction();
1410        }
1411        
1412        void InstrumentsDb::SetInstrumentFilePath(String OldPath, String NewPath) {
1413            if (OldPath == NewPath) return;
1414            StringListPtr instrs;
1415            BeginTransaction();
1416            try {
1417                std::vector<String> params(2);
1418                params[0] = toEscapedFsPath(NewPath);
1419                params[1] = toEscapedFsPath(OldPath);
1420                instrs = GetInstrumentsByFile(OldPath);
1421                ExecSql("UPDATE instruments SET instr_file=? WHERE instr_file=?", params);
1422            } catch (Exception e) {
1423                EndTransaction();
1424                throw e;
1425            }
1426            EndTransaction();
1427            
1428            for (int i = 0; i < instrs->size(); i++) {
1429                FireInstrumentInfoChanged(instrs->at(i));
1430            }
1431        }
1432    
1433      void InstrumentsDb::BeginTransaction() {      void InstrumentsDb::BeginTransaction() {
1434          dmsg(2,("InstrumentsDb: BeginTransaction(InTransaction=%d)\n", InTransaction));          dmsg(2,("InstrumentsDb: BeginTransaction(InTransaction=%d)\n", InTransaction));
# Line 1392  namespace LinuxSampler { Line 1490  namespace LinuxSampler {
1490    
1491      void InstrumentsDb::ExecSql(String Sql) {      void InstrumentsDb::ExecSql(String Sql) {
1492          dmsg(2,("InstrumentsDb: ExecSql(Sql=%s)\n", Sql.c_str()));          dmsg(2,("InstrumentsDb: ExecSql(Sql=%s)\n", Sql.c_str()));
1493          sqlite3_stmt *pStmt = NULL;          std::vector<String> Params;
1494                    ExecSql(Sql, Params);
         int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);  
         if (res != SQLITE_OK) {  
             throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));  
         }  
           
         res = sqlite3_step(pStmt);  
         if(res != SQLITE_DONE) {  
             sqlite3_finalize(pStmt);  
             throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));  
         }  
   
         sqlite3_finalize(pStmt);  
1495      }      }
1496    
1497      void InstrumentsDb::ExecSql(String Sql, String Param) {      void InstrumentsDb::ExecSql(String Sql, String Param) {
1498          dmsg(2,("InstrumentsDb: ExecSql(Sql=%s,Param=%s)\n", Sql.c_str(), Param.c_str()));          dmsg(2,("InstrumentsDb: ExecSql(Sql=%s,Param=%s)\n", Sql.c_str(), Param.c_str()));
1499            std::vector<String> Params;
1500            Params.push_back(Param);
1501            ExecSql(Sql, Params);
1502        }
1503    
1504        void InstrumentsDb::ExecSql(String Sql, std::vector<String>& Params) {
1505            dmsg(2,("InstrumentsDb: ExecSql(Sql=%s,Params)\n", Sql.c_str()));
1506          sqlite3_stmt *pStmt = NULL;          sqlite3_stmt *pStmt = NULL;
1507                    
1508          int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);          int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);
# Line 1418  namespace LinuxSampler { Line 1511  namespace LinuxSampler {
1511              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1512          }          }
1513    
1514          BindTextParam(pStmt, 1, Param);          for(int i = 0; i < Params.size(); i++) {
1515                BindTextParam(pStmt, i + 1, Params[i]);
1516            }
1517    
1518          res = sqlite3_step(pStmt);          res = sqlite3_step(pStmt);
1519          if (res != SQLITE_DONE) {          if (res != SQLITE_DONE) {
# Line 1500  namespace LinuxSampler { Line 1595  namespace LinuxSampler {
1595      }      }
1596    
1597      IntListPtr InstrumentsDb::ExecSqlIntList(String Sql) {      IntListPtr InstrumentsDb::ExecSqlIntList(String Sql) {
1598            dmsg(2,("InstrumentsDb: ExecSqlIntList(Sql=%s)\n", Sql.c_str()));
1599            std::vector<String> Params;
1600            return ExecSqlIntList(Sql, Params);
1601        }
1602    
1603        IntListPtr InstrumentsDb::ExecSqlIntList(String Sql, String Param) {
1604            dmsg(2,("InstrumentsDb: ExecSqlIntList(Sql=%s,Param=%s)\n", Sql.c_str(), Param.c_str()));
1605            std::vector<String> Params;
1606            Params.push_back(Param);
1607            return ExecSqlIntList(Sql, Params);
1608        }
1609    
1610        IntListPtr InstrumentsDb::ExecSqlIntList(String Sql, std::vector<String>& Params) {
1611            dmsg(2,("InstrumentsDb: ExecSqlIntList(Sql=%s)\n", Sql.c_str()));
1612          IntListPtr intList(new std::vector<int>);          IntListPtr intList(new std::vector<int>);
1613                    
1614          sqlite3_stmt *pStmt = NULL;          sqlite3_stmt *pStmt = NULL;
# Line 1509  namespace LinuxSampler { Line 1618  namespace LinuxSampler {
1618              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1619          }          }
1620                    
1621            for(int i = 0; i < Params.size(); i++) {
1622                BindTextParam(pStmt, i + 1, Params[i]);
1623            }
1624            
1625          res = sqlite3_step(pStmt);          res = sqlite3_step(pStmt);
1626          while(res == SQLITE_ROW) {          while(res == SQLITE_ROW) {
1627              intList->push_back(sqlite3_column_int(pStmt, 0));              intList->push_back(sqlite3_column_int(pStmt, 0));
# Line 1526  namespace LinuxSampler { Line 1639  namespace LinuxSampler {
1639      }      }
1640            
1641      StringListPtr InstrumentsDb::ExecSqlStringList(String Sql) {      StringListPtr InstrumentsDb::ExecSqlStringList(String Sql) {
1642            dmsg(2,("InstrumentsDb: ExecSqlStringList(Sql=%s)\n", Sql.c_str()));
1643          StringListPtr stringList(new std::vector<String>);          StringListPtr stringList(new std::vector<String>);
1644                    
1645          sqlite3_stmt *pStmt = NULL;          sqlite3_stmt *pStmt = NULL;
# Line 1569  namespace LinuxSampler { Line 1683  namespace LinuxSampler {
1683          }          }
1684      }      }
1685    
1686    #ifndef WIN32
1687      void InstrumentsDb::Regexp(sqlite3_context* pContext, int argc, sqlite3_value** ppValue) {      void InstrumentsDb::Regexp(sqlite3_context* pContext, int argc, sqlite3_value** ppValue) {
1688          if (argc != 2) return;          if (argc != 2) return;
1689    
# Line 1579  namespace LinuxSampler { Line 1694  namespace LinuxSampler {
1694              sqlite3_result_int(pContext, 1);              sqlite3_result_int(pContext, 1);
1695          }          }
1696      }      }
1697    #endif
1698    
1699      String InstrumentsDb::GetDirectoryPath(String File) {      String InstrumentsDb::GetDirectoryPath(String File) {
1700          if (File.empty()) return String("");          if (File.empty()) return String("");
# Line 1653  namespace LinuxSampler { Line 1769  namespace LinuxSampler {
1769          if (File.empty()) throw Exception("Invalid file name: " + File);          if (File.empty()) throw Exception("Invalid file name: " + File);
1770      }      }
1771    
1772      String InstrumentsDb::GetUniqueInstrumentName(int DirId, String Name) {      String InstrumentsDb::GetUniqueName(int DirId, String Name) {
1773          dmsg(2,("InstrumentsDb: GetUniqueInstrumentName(DirId=%d,Name=%s)\n", DirId, Name.c_str()));          dmsg(2,("InstrumentsDb: GetUniqueInstrumentName(DirId=%d,Name=%s)\n", DirId, Name.c_str()));
1774    
1775          if (GetInstrumentId(DirId, Name) == -1 && GetDirectoryId(DirId, Name) == -1) return Name;          if (GetInstrumentId(DirId, Name) == -1 && GetDirectoryId(DirId, Name) == -1) return Name;
# Line 1668  namespace LinuxSampler { Line 1784  namespace LinuxSampler {
1784    
1785          throw Exception("Unable to find an unique name: " + Name);          throw Exception("Unable to find an unique name: " + Name);
1786      }      }
1787        
1788        String InstrumentsDb::PrepareSubdirectory(String DbDir, String FsPath) {
1789            std::string dir = Path::getBaseName(FsPath);
1790            dir = toAbstractName(dir);
1791            if(dir.empty()) dir = "New Directory";
1792            dir = GetUniqueName(GetDirectoryId(DbDir), dir);
1793            dir = AppendNode(DbDir, dir);
1794            AddDirectory(dir);
1795            return dir;
1796        }
1797    
1798        String InstrumentsDb::AppendNode(String DbDir, String Node) {
1799            if(DbDir.length() == 1 && DbDir.at(0) == '/') return DbDir + Node;
1800            if(DbDir.at(DbDir.length() - 1) == '/') return DbDir + Node;
1801            return DbDir + "/" + Node;
1802        }
1803    
1804      String InstrumentsDb::toDbName(String AbstractName) {      String InstrumentsDb::toDbName(String AbstractName) {
1805          for (int i = 0; i < AbstractName.length(); i++) {          for (int i = 0; i < AbstractName.length(); i++) {
# Line 1699  namespace LinuxSampler { Line 1831  namespace LinuxSampler {
1831          return text;          return text;
1832      }      }
1833            
1834        String InstrumentsDb::toNonEscapedText(String text) {
1835            String sb;
1836            for (int i = 0; i < text.length(); i++) {
1837                char c = text.at(i);
1838                            if(c == '\\') {
1839                                    if(i >= text.length()) {
1840                                            std::cerr << "Broken escape sequence!" << std::endl;
1841                                            break;
1842                                    }
1843                                    char c2 = text.at(++i);
1844                                    if(c2 == '\'')      sb.push_back('\'');
1845                                    else if(c2 == '"')  sb.push_back('"');
1846                                    else if(c2 == '\\') sb.push_back('\\');
1847                                    else if(c2 == 'r')  sb.push_back('\r');
1848                                    else if(c2 == 'n')  sb.push_back('\n');
1849                                    else std::cerr << "Unknown escape sequence \\" << c2 << std::endl;
1850                            } else {
1851                                    sb.push_back(c);
1852                            }
1853            }
1854            return sb;
1855        }
1856        
1857      String InstrumentsDb::toEscapedFsPath(String FsPath) {      String InstrumentsDb::toEscapedFsPath(String FsPath) {
1858          return toEscapedText(FsPath);          return toEscapedText(FsPath);
1859      }      }
1860            
1861        String InstrumentsDb::toNonEscapedFsPath(String FsPath) {
1862            return toNonEscapedText(FsPath);
1863        }
1864        
1865      String InstrumentsDb::toAbstractName(String DbName) {      String InstrumentsDb::toAbstractName(String DbName) {
1866          for (int i = 0; i < DbName.length(); i++) {          for (int i = 0; i < DbName.length(); i++) {
1867              if (DbName.at(i) == '/') DbName.at(i) = '\0';              if (DbName.at(i) == '/') DbName.at(i) = '\0';

Legend:
Removed from v.1644  
changed lines
  Added in v.1911

  ViewVC Help
Powered by ViewVC