/[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 1187 by iliev, Wed May 16 14:22:26 2007 UTC revision 1944 by persson, Tue Jul 14 18:54:08 2009 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   Copyright (C) 2007 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  #if HAVE_SQLITE3  #include "../common/File.h"
24    #include "../common/Path.h"
25    #include "../common/global_private.h"
26    
27  #include <iostream>  #include <iostream>
28  #include <sstream>  #include <sstream>
29  #include <dirent.h>  #include <vector>
30    #include <algorithm>
31  #include <errno.h>  #include <errno.h>
32    #ifndef WIN32
33  #include <fnmatch.h>  #include <fnmatch.h>
34  #include <ftw.h>  #else
35    #include <direct.h>
36    #endif
37  #include "../common/Exception.h"  #include "../common/Exception.h"
38    
39  namespace LinuxSampler {  namespace LinuxSampler {
40    
41      void DbInstrument::Copy(const DbInstrument& Instr) {      InstrumentsDb InstrumentsDb::instance;
         if (this == &Instr) return;  
42    
43          InstrFile = Instr.InstrFile;      void InstrumentsDb::CreateInstrumentsDb(String FilePath) {
44          InstrNr = Instr.InstrNr;          File f = File(FilePath);
45          FormatFamily = Instr.FormatFamily;          if (f.Exist()) {
46          FormatVersion = Instr.FormatVersion;              throw Exception("File exists: " + FilePath);
         Size = Instr.Size;  
         Created = Instr.Created;  
         Modified = Instr.Modified;  
         Description = Instr.Description;  
         IsDrum = Instr.IsDrum;  
         Product = Instr.Product;  
         Artists = Instr.Artists;  
         Keywords = Instr.Keywords;  
     }  
   
   
     void DbDirectory::Copy(const DbDirectory& Dir) {  
         if (this == &Dir) return;  
   
         Created = Dir.Created;  
         Modified = Dir.Modified;  
         Description = Dir.Description;  
     }  
   
     SearchQuery::SearchQuery() {  
         MinSize = -1;  
         MaxSize = -1;  
         InstrType = BOTH;  
     }  
   
     void SearchQuery::SetFormatFamilies(String s) {  
         if (s.length() == 0) return;  
         int i = 0;  
         int j = s.find(',', 0);  
           
         while (j != std::string::npos) {  
             FormatFamilies.push_back(s.substr(i, j - i));  
             i = j + 1;  
             j = s.find(',', i);  
         }  
           
         if (i < s.length()) FormatFamilies.push_back(s.substr(i));  
     }  
   
     void SearchQuery::SetSize(String s) {  
         String s2 = GetMin(s);  
         if (s2.length() > 0) MinSize = atoll(s2.c_str());  
         else MinSize = -1;  
           
         s2 = GetMax(s);  
         if (s2.length() > 0) MaxSize = atoll(s2.c_str());  
         else MaxSize = -1;  
     }  
   
     void SearchQuery::SetCreated(String s) {  
         CreatedAfter = GetMin(s);  
         CreatedBefore = GetMax(s);  
     }  
   
     void SearchQuery::SetModified(String s) {  
         ModifiedAfter = GetMin(s);  
         ModifiedBefore = GetMax(s);  
     }  
   
     String SearchQuery::GetMin(String s) {  
         if (s.length() < 3) return "";  
         if (s.at(0) == '.' && s.at(1) == '.') return "";  
         int i = s.find("..");  
         if (i == std::string::npos) return "";  
         return s.substr(0, i);  
     }  
   
     String SearchQuery::GetMax(String s) {  
         if (s.length() < 3) return "";  
         if (s.find("..", s.length() - 2) != std::string::npos) return "";  
         int i = s.find("..");  
         if (i == std::string::npos) return "";  
         return s.substr(i + 2);  
     }  
       
     bool InstrumentsDb::AbstractFinder::IsRegex(String Pattern) {  
         if(Pattern.find('?') != String::npos) return true;  
         if(Pattern.find('*') != String::npos) return true;  
         return false;  
     }  
   
     void InstrumentsDb::AbstractFinder::AddSql(String Col, String Pattern, std::stringstream& Sql) {  
         if (Pattern.length() == 0) return;  
   
         if (IsRegex(Pattern)) {  
             Sql << " AND " << Col << " regexp ?";  
             Params.push_back(Pattern);  
             return;  
         }  
   
         String buf;  
         std::vector<String> tokens;  
         std::vector<String> tokens2;  
         std::stringstream ss(Pattern);  
         while (ss >> buf) tokens.push_back(buf);  
   
         if (tokens.size() == 0) {  
             Sql << " AND " << Col << " LIKE ?";  
             Params.push_back("%" + Pattern + "%");  
             return;  
         }  
   
         bool b = false;  
         for (int i = 0; i < tokens.size(); i++) {  
             Sql << (i == 0 ? " AND (" : "");  
   
             for (int j = 0; j < tokens.at(i).length(); j++) {  
                 if (tokens.at(i).at(j) == '+') tokens.at(i).at(j) = ' ';  
             }  
   
             ss.clear();  
             ss.str("");  
             ss << tokens.at(i);  
   
             tokens2.clear();  
             while (ss >> buf) tokens2.push_back(buf);  
   
             if (b && tokens2.size() > 0) Sql << " OR ";  
             if (tokens2.size() > 1) Sql << "(";  
             for (int j = 0; j < tokens2.size(); j++) {  
                 if (j != 0) Sql << " AND ";  
                 Sql << Col << " LIKE ?";  
                 Params.push_back("%" + tokens2.at(j) + "%");  
                 b = true;  
             }  
             if (tokens2.size() > 1) Sql << ")";  
         }  
         if (!b) Sql << "0)";  
         else Sql << ")";  
     }  
   
     InstrumentsDb::DirectoryFinder::DirectoryFinder(SearchQuery* pQuery) : pDirectories(new std::vector<String>) {  
         pStmt = NULL;  
         this->pQuery = pQuery;  
         std::stringstream sql;  
         sql << "SELECT dir_name from instr_dirs WHERE parent_dir_id=?";  
   
         if (pQuery->CreatedAfter.length() != 0) {  
             sql << " AND created > ?";  
             Params.push_back(pQuery->CreatedAfter);  
         }  
         if (pQuery->CreatedBefore.length() != 0) {  
             sql << " AND created < ?";  
             Params.push_back(pQuery->CreatedBefore);  
         }  
         if (pQuery->ModifiedAfter.length() != 0) {  
             sql << " AND modified > ?";  
             Params.push_back(pQuery->ModifiedAfter);  
         }  
         if (pQuery->ModifiedBefore.length() != 0) {  
             sql << " AND modified < ?";  
             Params.push_back(pQuery->ModifiedBefore);  
         }  
   
         AddSql("dir_name", pQuery->Name, sql);  
         AddSql("description", pQuery->Description, sql);  
         SqlQuery = sql.str();  
   
         InstrumentsDb* idb = InstrumentsDb::GetInstrumentsDb();  
   
         int res = sqlite3_prepare(idb->GetDb(), SqlQuery.c_str(), -1, &pStmt, NULL);  
         if (res != SQLITE_OK) {  
             throw Exception("DB error: " + ToString(sqlite3_errmsg(idb->GetDb())));  
         }  
   
         for(int i = 0; i < Params.size(); i++) {  
             idb->BindTextParam(pStmt, i + 2, Params.at(i));  
         }  
     }  
       
     InstrumentsDb::DirectoryFinder::~DirectoryFinder() {  
         if (pStmt != NULL) sqlite3_finalize(pStmt);  
     }  
   
     StringListPtr InstrumentsDb::DirectoryFinder::GetDirectories() {  
         return pDirectories;  
     }  
       
     void InstrumentsDb::DirectoryFinder::ProcessDirectory(String Path, int DirId) {  
         InstrumentsDb* idb = InstrumentsDb::GetInstrumentsDb();  
         idb->BindIntParam(pStmt, 1, DirId);  
   
         String s = Path;  
         if(Path.compare("/") != 0) s += "/";  
         int res = sqlite3_step(pStmt);  
         while(res == SQLITE_ROW) {  
             pDirectories->push_back(s + ToString(sqlite3_column_text(pStmt, 0)));  
             res = sqlite3_step(pStmt);  
         }  
           
         if (res != SQLITE_DONE) {  
             sqlite3_finalize(pStmt);  
             throw Exception("DB error: " + ToString(sqlite3_errmsg(idb->GetDb())));  
         }  
   
         res = sqlite3_reset(pStmt);  
         if (res != SQLITE_OK) {  
             sqlite3_finalize(pStmt);  
             throw Exception("DB error: " + ToString(sqlite3_errmsg(idb->GetDb())));  
         }  
     }  
   
     InstrumentsDb::InstrumentFinder::InstrumentFinder(SearchQuery* pQuery) : pInstruments(new std::vector<String>) {  
         pStmt = NULL;  
         this->pQuery = pQuery;  
         std::stringstream sql;  
         sql << "SELECT instr_name from instruments WHERE dir_id=?";  
   
         if (pQuery->CreatedAfter.length() != 0) {  
             sql << " AND created > ?";  
             Params.push_back(pQuery->CreatedAfter);  
         }  
         if (pQuery->CreatedBefore.length() != 0) {  
             sql << " AND created < ?";  
             Params.push_back(pQuery->CreatedBefore);  
         }  
         if (pQuery->ModifiedAfter.length() != 0) {  
             sql << " AND modified > ?";  
             Params.push_back(pQuery->ModifiedAfter);  
         }  
         if (pQuery->ModifiedBefore.length() != 0) {  
             sql << " AND modified < ?";  
             Params.push_back(pQuery->ModifiedBefore);  
         }  
         if (pQuery->MinSize != -1) sql << " AND instr_size > " << pQuery->MinSize;  
         if (pQuery->MaxSize != -1) sql << " AND instr_size < " << pQuery->MaxSize;  
   
         if (pQuery->InstrType == SearchQuery::CHROMATIC) sql << " AND is_drum = 0";  
         else if (pQuery->InstrType == SearchQuery::DRUM) sql << " AND is_drum != 0";  
   
         if (pQuery->FormatFamilies.size() > 0) {  
             sql << " AND (format_family=?";  
             Params.push_back(pQuery->FormatFamilies.at(0));  
             for (int i = 1; i < pQuery->FormatFamilies.size(); i++) {  
                 sql << "OR format_family=?";  
                 Params.push_back(pQuery->FormatFamilies.at(i));  
             }  
             sql << ")";  
         }  
   
         AddSql("instr_name", pQuery->Name, sql);  
         AddSql("description", pQuery->Description, sql);  
         AddSql("product", pQuery->Product, sql);  
         AddSql("artists", pQuery->Artists, sql);  
         AddSql("keywords", pQuery->Keywords, sql);  
         SqlQuery = sql.str();  
   
         InstrumentsDb* idb = InstrumentsDb::GetInstrumentsDb();  
   
         int res = sqlite3_prepare(idb->GetDb(), SqlQuery.c_str(), -1, &pStmt, NULL);  
         if (res != SQLITE_OK) {  
             throw Exception("DB error: " + ToString(sqlite3_errmsg(idb->GetDb())));  
         }  
   
         for(int i = 0; i < Params.size(); i++) {  
             idb->BindTextParam(pStmt, i + 2, Params.at(i));  
         }  
     }  
       
     InstrumentsDb::InstrumentFinder::~InstrumentFinder() {  
         if (pStmt != NULL) sqlite3_finalize(pStmt);  
     }  
       
     void InstrumentsDb::InstrumentFinder::ProcessDirectory(String Path, int DirId) {  
         InstrumentsDb* idb = InstrumentsDb::GetInstrumentsDb();  
         idb->BindIntParam(pStmt, 1, DirId);  
   
         String s = Path;  
         if(Path.compare("/") != 0) s += "/";  
         int res = sqlite3_step(pStmt);  
         while(res == SQLITE_ROW) {  
             pInstruments->push_back(s + ToString(sqlite3_column_text(pStmt, 0)));  
             res = sqlite3_step(pStmt);  
         }  
           
         if (res != SQLITE_DONE) {  
             sqlite3_finalize(pStmt);  
             throw Exception("DB error: " + ToString(sqlite3_errmsg(idb->GetDb())));  
         }  
   
         res = sqlite3_reset(pStmt);  
         if (res != SQLITE_OK) {  
             sqlite3_finalize(pStmt);  
             throw Exception("DB error: " + ToString(sqlite3_errmsg(idb->GetDb())));  
         }  
     }  
   
     StringListPtr InstrumentsDb::InstrumentFinder::GetInstruments() {  
         return pInstruments;  
     }  
   
     void InstrumentsDb::DirectoryCounter::ProcessDirectory(String Path, int DirId) {  
         count += InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(DirId);  
     }  
   
     void InstrumentsDb::InstrumentCounter::ProcessDirectory(String Path, int DirId) {  
         count += InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(DirId);  
     }  
   
     InstrumentsDb::DirectoryCopier::DirectoryCopier(String SrcParentDir, String DestDir) {  
         this->SrcParentDir = SrcParentDir;  
         this->DestDir = DestDir;  
   
         if (DestDir.at(DestDir.length() - 1) != '/') {  
             this->DestDir.append("/");  
         }  
         if (SrcParentDir.at(SrcParentDir.length() - 1) != '/') {  
             this->SrcParentDir.append("/");  
         }  
     }  
   
     void InstrumentsDb::DirectoryCopier::ProcessDirectory(String Path, int DirId) {  
         InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();  
   
         String dir = DestDir;  
         String subdir = Path;  
         if(subdir.length() > SrcParentDir.length()) {  
             subdir = subdir.substr(SrcParentDir.length());  
             dir += subdir;  
             db->AddDirectory(dir);  
         }  
   
         int dstDirId = db->GetDirectoryId(dir);  
         if(dstDirId == -1) throw Exception("Unkown DB directory: " + dir);  
         IntListPtr ids = db->GetInstrumentIDs(DirId);  
         for (int i = 0; i < ids->size(); i++) {  
             String name = db->GetInstrumentName(ids->at(i));  
             db->CopyInstrument(ids->at(i), name, dstDirId, dir);  
         }  
     }  
   
     InstrumentsDb* InstrumentsDb::pInstrumentsDb = new InstrumentsDb;  
   
     void InstrumentsDb::CreateInstrumentsDb(String File) {  
         struct stat statBuf;  
         int res = stat(File.c_str(), &statBuf);  
         if (!res) {  
             throw Exception("File exists: " + File);  
47          }          }
48                    
49          GetInstrumentsDb()->SetDbFile(File);          GetInstrumentsDb()->SetDbFile(FilePath);
50    
51          String sql =          String sql =
52              "  CREATE TABLE instr_dirs (                                      "              "  CREATE TABLE instr_dirs (                                      "
# Line 395  namespace LinuxSampler { Line 62  namespace LinuxSampler {
62                    
63          GetInstrumentsDb()->ExecSql(sql);          GetInstrumentsDb()->ExecSql(sql);
64    
65          sql = "INSERT INTO instr_dirs (dir_id, parent_dir_id, dir_name) VALUES (0, 0, '/');";          sql = "INSERT INTO instr_dirs (dir_id, parent_dir_id, dir_name) VALUES (0, -2, '/');";
66          GetInstrumentsDb()->ExecSql(sql);          GetInstrumentsDb()->ExecSql(sql);
67    
68          sql =          sql =
# Line 424  namespace LinuxSampler { Line 91  namespace LinuxSampler {
91    
92      InstrumentsDb::InstrumentsDb() {      InstrumentsDb::InstrumentsDb() {
93          db = NULL;          db = NULL;
         DbInstrumentsMutex = Mutex();  
94          InTransaction = false;          InTransaction = false;
95      }      }
96    
# Line 432  namespace LinuxSampler { Line 98  namespace LinuxSampler {
98          if (db != NULL) sqlite3_close(db);          if (db != NULL) sqlite3_close(db);
99      }      }
100            
     void InstrumentsDb::Destroy() {  
         if (pInstrumentsDb != NULL) {  
             delete pInstrumentsDb;  
             pInstrumentsDb = NULL;  
         }  
     }  
   
101      void InstrumentsDb::AddInstrumentsDbListener(InstrumentsDb::Listener* l) {      void InstrumentsDb::AddInstrumentsDbListener(InstrumentsDb::Listener* l) {
102          llInstrumentsDbListeners.AddListener(l);          llInstrumentsDbListeners.AddListener(l);
103      }      }
# Line 448  namespace LinuxSampler { Line 107  namespace LinuxSampler {
107      }      }
108            
109      InstrumentsDb* InstrumentsDb::GetInstrumentsDb() {      InstrumentsDb* InstrumentsDb::GetInstrumentsDb() {
110          return pInstrumentsDb;          return &instance;
111      }      }
112            
113      void InstrumentsDb::SetDbFile(String File) {      void InstrumentsDb::SetDbFile(String File) {
# Line 464  namespace LinuxSampler { Line 123  namespace LinuxSampler {
123      sqlite3* InstrumentsDb::GetDb() {      sqlite3* InstrumentsDb::GetDb() {
124          if ( db != NULL) return db;          if ( db != NULL) return db;
125    
126          if (DbFile.empty()) DbFile = "/var/lib/linuxsampler/instruments.db";          if (DbFile.empty()) {
127                        #ifndef WIN32
128                        DbFile = CONFIG_DEFAULT_INSTRUMENTS_DB_LOCATION;
129                            #else
130                            char *userprofile = getenv("USERPROFILE");
131                            if(userprofile) {
132                                String DbPath = userprofile;
133                                    DbPath += "\\.linuxsampler";
134                                DbFile = DbPath + "\\instruments.db";
135                                    File InstrumentsDbFile(DbFile);
136                                    // if no DB exists create the subdir and then the DB
137                                    if( !InstrumentsDbFile.Exist() ) {
138                                        _mkdir( DbPath.c_str() );
139                                            // formats the DB, which creates a new instruments.db file
140                                            Format();
141                                    }
142                        }
143                            else {
144                                // in case USERPROFILE is not set (which should not occur)
145                                DbFile = "instruments.db";
146                            }
147                            #endif
148                }
149                    #if defined(__APPLE__)  /* 20071224 Toshi Nagata  */
150                    if (DbFile.find("~") == 0)
151                            DbFile.replace(0, 1, getenv("HOME"));
152                    #endif
153          int rc = sqlite3_open(DbFile.c_str(), &db);          int rc = sqlite3_open(DbFile.c_str(), &db);
154          if (rc) {          if (rc) {
155              sqlite3_close(db);              sqlite3_close(db);
156              db = NULL;              db = NULL;
157              throw Exception("Cannot open instruments database: " + DbFile);              throw Exception("Cannot open instruments database: " + DbFile);
158          }          }
159    #ifndef WIN32
160          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);
161          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."); }
162    #endif
163    
164            // TODO: remove this in the next version
165            try {
166                int i = ExecSqlInt("SELECT parent_dir_id FROM instr_dirs WHERE dir_id=0");
167                // The parent ID of the root directory should be -2 now.
168                if(i != -2) ExecSql("UPDATE instr_dirs SET parent_dir_id=-2 WHERE dir_id=0");
169            } catch(Exception e) { }
170            ////////////////////////////////////////
171                    
172          return db;          return db;
173      }      }
# Line 486  namespace LinuxSampler { Line 181  namespace LinuxSampler {
181                    
182          int count = ExecSqlInt(sql.str());          int count = ExecSqlInt(sql.str());
183    
         // While the root dir has ID 0 and parent ID 0, the directory  
         // count for the root dir will be incorrect, so we should fix it.  
         if (count != -1 && DirId == 0) count--;  
184          return count;          return count;
185      }      }
186    
# Line 510  namespace LinuxSampler { Line 202  namespace LinuxSampler {
202              throw e;              throw e;
203          }          }
204          EndTransaction();          EndTransaction();
205          if (i == -1) throw Exception("Unkown DB directory: " + Dir);          if (i == -1) throw Exception("Unkown DB directory: " + toEscapedPath(Dir));
206                    
207          return i;          return i;
208      }      }
# Line 529  namespace LinuxSampler { Line 221  namespace LinuxSampler {
221          BeginTransaction();          BeginTransaction();
222          try {          try {
223              int dirId = GetDirectoryId(Dir);              int dirId = GetDirectoryId(Dir);
224              if(dirId == -1) throw Exception("Unknown DB directory: " + Dir);              if(dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
225    
226              StringListPtr pDirs;              StringListPtr pDirs;
227              if (Recursive) {              if (Recursive) {
# Line 552  namespace LinuxSampler { Line 244  namespace LinuxSampler {
244          std::stringstream sql;          std::stringstream sql;
245          sql << "SELECT dir_name FROM instr_dirs ";          sql << "SELECT dir_name FROM instr_dirs ";
246          sql << "WHERE parent_dir_id=" << DirId << " AND dir_id!=0";          sql << "WHERE parent_dir_id=" << DirId << " AND dir_id!=0";
247          return ExecSqlStringList(sql.str());          StringListPtr dirs = ExecSqlStringList(sql.str());
248    
249            for (int i = 0; i < dirs->size(); i++) {
250                for (int j = 0; j < dirs->at(i).length(); j++) {
251                    if (dirs->at(i).at(j) == '/') dirs->at(i).at(j) = '\0';
252                }
253            }
254    
255            return dirs;
256      }      }
257    
258      int InstrumentsDb::GetDirectoryId(String Dir) {      int InstrumentsDb::GetDirectoryId(String Dir) {
# Line 581  namespace LinuxSampler { Line 281  namespace LinuxSampler {
281    
282      int InstrumentsDb::GetDirectoryId(int ParentDirId, String DirName) {      int InstrumentsDb::GetDirectoryId(int ParentDirId, String DirName) {
283          dmsg(2,("InstrumentsDb: GetDirectoryId(ParentDirId=%d, DirName=%s)\n", ParentDirId, DirName.c_str()));          dmsg(2,("InstrumentsDb: GetDirectoryId(ParentDirId=%d, DirName=%s)\n", ParentDirId, DirName.c_str()));
284            DirName = toDbName(DirName);
285          std::stringstream sql;          std::stringstream sql;
286          sql << "SELECT dir_id FROM instr_dirs WHERE parent_dir_id=";          sql << "SELECT dir_id FROM instr_dirs WHERE parent_dir_id=";
287          sql << ParentDirId << " AND dir_name=?";          sql << ParentDirId << " AND dir_name=?";
288          return ExecSqlInt(sql.str(), DirName);          return ExecSqlInt(sql.str(), DirName);
289      }      }
290    
291        int InstrumentsDb::GetDirectoryId(int InstrId) {
292            dmsg(2,("InstrumentsDb: GetDirectoryId(InstrId=%d)\n", InstrId));
293            std::stringstream sql;
294            sql << "SELECT dir_id FROM instruments WHERE instr_id=" << InstrId;
295            return ExecSqlInt(sql.str());
296        }
297    
298      String InstrumentsDb::GetDirectoryName(int DirId) {      String InstrumentsDb::GetDirectoryName(int DirId) {
299          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);
300          String name = ExecSqlString(sql);          String name = ExecSqlString(sql);
# Line 611  namespace LinuxSampler { Line 319  namespace LinuxSampler {
319                  path = "/" + path;                  path = "/" + path;
320                  break;                  break;
321              }              }
322              path = GetDirectoryName(DirId) + path;              path = GetDirectoryName(DirId) + "/" + path;
323              DirId = GetParentDirectoryId(DirId);              DirId = GetParentDirectoryId(DirId);
324          }          }
325    
# Line 619  namespace LinuxSampler { Line 327  namespace LinuxSampler {
327    
328          return path;          return path;
329      }      }
330        
331        StringListPtr InstrumentsDb::GetInstrumentsByFile(String File) {
332            dmsg(2,("InstrumentsDb: GetInstrumentsByFile(File=%s)\n", File.c_str()));
333    
334            StringListPtr instrs(new std::vector<String>);
335            
336            BeginTransaction();
337            try {
338                File = toEscapedFsPath(File);
339                IntListPtr ids = ExecSqlIntList("SELECT instr_id FROM instruments WHERE instr_file=?", File);
340                
341                for (int i = 0; i < ids->size(); i++) {
342                    String name = GetInstrumentName(ids->at(i));
343                    String dir = GetDirectoryPath(GetDirectoryId(ids->at(i)));
344                    instrs->push_back(dir + name);
345                }
346            } catch (Exception e) {
347                EndTransaction();
348                throw e;
349            }
350            EndTransaction();
351            
352            return instrs;
353        }
354    
355      void InstrumentsDb::AddDirectory(String Dir) {      void InstrumentsDb::AddDirectory(String Dir) {
356          dmsg(2,("InstrumentsDb: AddDirectory(Dir=%s)\n", Dir.c_str()));          dmsg(2,("InstrumentsDb: AddDirectory(Dir=%s)\n", Dir.c_str()));
# Line 633  namespace LinuxSampler { Line 365  namespace LinuxSampler {
365    
366              String dirName = GetFileName(Dir);              String dirName = GetFileName(Dir);
367              if(ParentDir.empty() || dirName.empty()) {              if(ParentDir.empty() || dirName.empty()) {
368                  throw Exception("Failed to add DB directory: " + Dir);                  throw Exception("Failed to add DB directory: " + toEscapedPath(Dir));
369              }              }
370    
371              int id = GetDirectoryId(ParentDir);              int id = GetDirectoryId(ParentDir);
372              if (id == -1) throw Exception("DB directory doesn't exist: " + ParentDir);              if (id == -1) throw Exception("DB directory doesn't exist: " + toEscapedPath(ParentDir));
373              int id2 = GetDirectoryId(id, dirName);              int id2 = GetDirectoryId(id, dirName);
374              if (id2 != -1) throw Exception("DB directory already exist: " + Dir);              if (id2 != -1) throw Exception("DB directory already exist: " + toEscapedPath(Dir));
375              id2 = GetInstrumentId(id, dirName);              id2 = GetInstrumentId(id, dirName);
376              if (id2 != -1) throw Exception("Instrument with that name exist: " + Dir);              if (id2 != -1) throw Exception("Instrument with that name exist: " + toEscapedPath(Dir));
377    
378              std::stringstream sql;              std::stringstream sql;
379              sql << "INSERT INTO instr_dirs (parent_dir_id, dir_name) VALUES (";              sql << "INSERT INTO instr_dirs (parent_dir_id, dir_name) VALUES (";
380              sql << id << ", ?)";              sql << id << ", ?)";
381    
382              ExecSql(sql.str(), dirName);              ExecSql(sql.str(), toDbName(dirName));
383          } catch (Exception e) {          } catch (Exception e) {
384              EndTransaction();              EndTransaction();
385              throw e;              throw e;
# Line 666  namespace LinuxSampler { Line 398  namespace LinuxSampler {
398          BeginTransaction();          BeginTransaction();
399          try {          try {
400              int dirId = GetDirectoryId(Dir);              int dirId = GetDirectoryId(Dir);
401              if (dirId == -1) throw Exception("Unknown DB directory: " + Dir);              if (dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
402              if (dirId == 0) throw Exception("Cannot delete the root directory: " + Dir);              if (dirId == 0) throw Exception("Cannot delete the root directory: " + Dir);
403              if(ParentDir.empty()) throw Exception("Unknown parent directory");              if(ParentDir.empty()) throw Exception("Unknown parent directory");
404              if (Force) RemoveDirectoryContent(dirId);              if (Force) RemoveDirectoryContent(dirId);
# Line 753  namespace LinuxSampler { Line 485  namespace LinuxSampler {
485    
486          try {          try {
487              int id = GetDirectoryId(Dir);              int id = GetDirectoryId(Dir);
488              if(id == -1) throw Exception("Unknown DB directory: " + Dir);              if(id == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
489    
490              sqlite3_stmt *pStmt = NULL;              sqlite3_stmt *pStmt = NULL;
491              std::stringstream sql;              std::stringstream sql;
# Line 776  namespace LinuxSampler { Line 508  namespace LinuxSampler {
508                  if (res != SQLITE_DONE) {                  if (res != SQLITE_DONE) {
509                      throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));                      throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
510                  } else {                  } else {
511                      throw Exception("Unknown DB directory: " + Dir);                      throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
512                  }                  }
513              }              }
514                            
# Line 793  namespace LinuxSampler { Line 525  namespace LinuxSampler {
525      void InstrumentsDb::RenameDirectory(String Dir, String Name) {      void InstrumentsDb::RenameDirectory(String Dir, String Name) {
526          dmsg(2,("InstrumentsDb: RenameDirectory(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));          dmsg(2,("InstrumentsDb: RenameDirectory(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
527          CheckFileName(Name);          CheckFileName(Name);
528            String dbName = toDbName(Name);
529    
530          BeginTransaction();          BeginTransaction();
531          try {          try {
532              int dirId = GetDirectoryId(Dir);              int dirId = GetDirectoryId(Dir);
533              if (dirId == -1) throw Exception("Unknown DB directory: " + Dir);              if (dirId == -1) throw Exception("Unknown DB directory: " + toEscapedText(Dir));
534    
535              std::stringstream sql;              std::stringstream sql;
536              sql << "SELECT parent_dir_id FROM instr_dirs WHERE dir_id=" <<  dirId;              sql << "SELECT parent_dir_id FROM instr_dirs WHERE dir_id=" <<  dirId;
537    
538              int parent = ExecSqlInt(sql.str());              int parent = ExecSqlInt(sql.str());
539              if (parent == -1) throw Exception("Unknown parent directory: " + Dir);              if (parent == -1) throw Exception("Unknown parent directory: " + toEscapedPath(Dir));
540              if (GetDirectoryId(parent, Name) != -1) {  
541                  throw Exception("Cannot rename. Directory with that name already exists: " + Name);              if (GetDirectoryId(parent, dbName) != -1) {
542                    String s = toEscapedPath(Name);
543                    throw Exception("Cannot rename. Directory with that name already exists: " + s);
544              }              }
545    
546              if (GetInstrumentId(parent, Name) != -1) {              if (GetInstrumentId(parent, dbName) != -1) {
547                  throw Exception("Cannot rename. Instrument with that name exist: " + Dir);                  throw Exception("Cannot rename. Instrument with that name exist: " + toEscapedPath(Dir));
548              }              }
549    
550              sql.str("");              sql.str("");
551              sql << "UPDATE instr_dirs SET dir_name=? WHERE dir_id=" << dirId;              sql << "UPDATE instr_dirs SET dir_name=? WHERE dir_id=" << dirId;
552              ExecSql(sql.str(), Name);              ExecSql(sql.str(), dbName);
553          } catch (Exception e) {          } catch (Exception e) {
554              EndTransaction();              EndTransaction();
555              throw e;              throw e;
556          }          }
557    
558          EndTransaction();          EndTransaction();
559          FireDirectoryNameChanged(Dir, Name);          FireDirectoryNameChanged(Dir, toAbstractName(Name));
560      }      }
561    
562      void InstrumentsDb::MoveDirectory(String Dir, String Dst) {      void InstrumentsDb::MoveDirectory(String Dir, String Dst) {
# Line 834  namespace LinuxSampler { Line 569  namespace LinuxSampler {
569          BeginTransaction();          BeginTransaction();
570          try {          try {
571              int dirId = GetDirectoryId(Dir);              int dirId = GetDirectoryId(Dir);
572              if (dirId == -1) throw Exception("Unknown DB directory: " + Dir);              if (dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
573              int dstId = GetDirectoryId(Dst);              int dstId = GetDirectoryId(Dst);
574              if (dstId == -1) throw Exception("Unknown DB directory: " + Dst);              if (dstId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dst));
575              if (dirId == dstId) {              if (dirId == dstId) {
576                  throw Exception("Cannot move directory to itself");                  throw Exception("Cannot move directory to itself");
577              }              }
# Line 852  namespace LinuxSampler { Line 587  namespace LinuxSampler {
587              String dirName = GetFileName(Dir);              String dirName = GetFileName(Dir);
588    
589              int id2 = GetDirectoryId(dstId, dirName);              int id2 = GetDirectoryId(dstId, dirName);
590              if (id2 != -1) throw Exception("DB directory already exist: " + dirName);              if (id2 != -1) throw Exception("DB directory already exist: " + toEscapedPath(dirName));
591              id2 = GetInstrumentId(dstId, dirName);              id2 = GetInstrumentId(dstId, dirName);
592              if (id2 != -1) throw Exception("Instrument with that name exist: " + dirName);              if (id2 != -1) throw Exception("Instrument with that name exist: " + toEscapedPath(dirName));
593    
594              std::stringstream sql;              std::stringstream sql;
595              sql << "UPDATE instr_dirs SET parent_dir_id=" << dstId;              sql << "UPDATE instr_dirs SET parent_dir_id=" << dstId;
# Line 880  namespace LinuxSampler { Line 615  namespace LinuxSampler {
615          BeginTransaction();          BeginTransaction();
616          try {          try {
617              int dirId = GetDirectoryId(Dir);              int dirId = GetDirectoryId(Dir);
618              if (dirId == -1) throw Exception("Unknown DB directory: " + Dir);              if (dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
619              int dstId = GetDirectoryId(Dst);              int dstId = GetDirectoryId(Dst);
620              if (dstId == -1) throw Exception("Unknown DB directory: " + Dst);              if (dstId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dst));
621              if (dirId == dstId) {              if (dirId == dstId) {
622                  throw Exception("Cannot copy directory to itself");                  throw Exception("Cannot copy directory to itself");
623              }              }
# Line 898  namespace LinuxSampler { Line 633  namespace LinuxSampler {
633              String dirName = GetFileName(Dir);              String dirName = GetFileName(Dir);
634    
635              int id2 = GetDirectoryId(dstId, dirName);              int id2 = GetDirectoryId(dstId, dirName);
636              if (id2 != -1) throw Exception("DB directory already exist: " + dirName);              if (id2 != -1) throw Exception("DB directory already exist: " + toEscapedPath(dirName));
637              id2 = GetInstrumentId(dstId, dirName);              id2 = GetInstrumentId(dstId, dirName);
638              if (id2 != -1) throw Exception("Instrument with that name exist: " + dirName);              if (id2 != -1) throw Exception("Instrument with that name exist: " + toEscapedPath(dirName));
639    
640              DirectoryCopier directoryCopier(ParentDir, Dst);              DirectoryCopier directoryCopier(ParentDir, Dst);
641              DirectoryTreeWalk(Dir, &directoryCopier);              DirectoryTreeWalk(Dir, &directoryCopier);
# Line 918  namespace LinuxSampler { Line 653  namespace LinuxSampler {
653          BeginTransaction();          BeginTransaction();
654          try {          try {
655              int id = GetDirectoryId(Dir);              int id = GetDirectoryId(Dir);
656              if(id == -1) throw Exception("Unknown DB directory: " + Dir);              if(id == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
657    
658              std::stringstream sql;              std::stringstream sql;
659              sql << "UPDATE instr_dirs SET description=?,modified=CURRENT_TIMESTAMP ";              sql << "UPDATE instr_dirs SET description=?,modified=CURRENT_TIMESTAMP ";
# Line 934  namespace LinuxSampler { Line 669  namespace LinuxSampler {
669          FireDirectoryInfoChanged(Dir);          FireDirectoryInfoChanged(Dir);
670      }      }
671    
672      void InstrumentsDb::AddInstruments(String DbDir, String FilePath, int Index) {      int InstrumentsDb::AddInstruments(ScanMode Mode, String DbDir, String FsDir, bool bBackground, bool insDir) {
673          dmsg(2,("InstrumentsDb: AddInstruments(DbDir=%s,FilePath=%s,Index=%d)\n", DbDir.c_str(), FilePath.c_str(), Index));          dmsg(2,("InstrumentsDb: AddInstruments(Mode=%d,DbDir=%s,FsDir=%s,bBackground=%d,insDir=%d)\n", Mode, DbDir.c_str(), FsDir.c_str(), bBackground, insDir));
674            if(!bBackground) {
675                switch (Mode) {
676                    case NON_RECURSIVE:
677                        AddInstrumentsNonrecursive(DbDir, FsDir, insDir);
678                        break;
679                    case RECURSIVE:
680                        AddInstrumentsRecursive(DbDir, FsDir, false, insDir);
681                        break;
682                    case FLAT:
683                        AddInstrumentsRecursive(DbDir, FsDir, true, insDir);
684                        break;
685                    default:
686                        throw Exception("Unknown scan mode");
687                }
688    
689                return -1;
690            }
691    
692            ScanJob job;
693            int jobId = Jobs.AddJob(job);
694            InstrumentsDbThread.Execute(new AddInstrumentsJob(jobId, Mode, DbDir, FsDir, insDir));
695    
696            return jobId;
697        }
698        
699        int InstrumentsDb::AddInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
700            dmsg(2,("InstrumentsDb: AddInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
701            if(!bBackground) {
702                AddInstruments(DbDir, false, FilePath, Index);
703                return -1;
704            }
705    
706            ScanJob job;
707            int jobId = Jobs.AddJob(job);
708            InstrumentsDbThread.Execute(new AddInstrumentsFromFileJob(jobId, DbDir, FilePath, Index, false));
709    
710            return jobId;
711        }
712    
713        void InstrumentsDb::AddInstruments(String DbDir, bool insDir, String FilePath, int Index, ScanProgress* pProgress) {
714            dmsg(2,("InstrumentsDb: AddInstruments(DbDir=%s,insDir=%d,FilePath=%s,Index=%d)\n", DbDir.c_str(), insDir, FilePath.c_str(), Index));
715          if (DbDir.empty() || FilePath.empty()) return;          if (DbDir.empty() || FilePath.empty()) return;
716                    
717          DbInstrumentsMutex.Lock();          DbInstrumentsMutex.Lock();
718          try {          try {
719              int dirId = GetDirectoryId(DbDir);              int dirId = GetDirectoryId(DbDir);
720              if (dirId == -1) throw Exception("Invalid DB directory: " + DbDir);              if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedText(DbDir));
721    
722              struct stat statBuf;              File f = File(FilePath);
723              int res = stat(FilePath.c_str(), &statBuf);              if (!f.Exist()) {
             if (res) {  
724                  std::stringstream ss;                  std::stringstream ss;
725                  ss << "Fail to stat `" << FilePath << "`: " << strerror(errno);                  ss << "Fail to stat `" << FilePath << "`: " << f.GetErrorMsg();
726                  throw Exception(ss.str());                  throw Exception(ss.str());
727              }              }
728    
729              if (S_ISREG(statBuf.st_mode)) {              if (!f.IsFile()) {
                 AddInstrumentsFromFile(DbDir, FilePath, Index);  
                 DbInstrumentsMutex.Unlock();  
                 return;  
             }  
   
             if (!S_ISDIR(statBuf.st_mode)) {  
                 DbInstrumentsMutex.Unlock();  
                 return;  
             }  
               
             if (Index != -1) {  
730                  std::stringstream ss;                  std::stringstream ss;
731                  ss << "`" << FilePath << "` is directory, not an instrument file";                  ss << "`" << FilePath << "` is not an instrument file";
732                  throw Exception(ss.str());                  throw Exception(ss.str());
733              }              }
734            
735              AddInstrumentsRecursive(DbDir, FilePath, false);              String dir = insDir ? PrepareSubdirectory(DbDir, FilePath) : DbDir;
736                AddInstrumentsFromFile(dir, FilePath, Index, pProgress);
737          } catch (Exception e) {          } catch (Exception e) {
738              DbInstrumentsMutex.Unlock();              DbInstrumentsMutex.Unlock();
739              throw e;              throw e;
# Line 977  namespace LinuxSampler { Line 742  namespace LinuxSampler {
742          DbInstrumentsMutex.Unlock();          DbInstrumentsMutex.Unlock();
743      }      }
744    
745      void InstrumentsDb::AddInstrumentsNonrecursive(String DbDir, String FsDir) {      void InstrumentsDb::AddInstrumentsNonrecursive(String DbDir, String FsDir, bool insDir, ScanProgress* pProgress) {
746          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));
747          if (DbDir.empty() || FsDir.empty()) return;          if (DbDir.empty() || FsDir.empty()) return;
748                    
749          DbInstrumentsMutex.Lock();          DbInstrumentsMutex.Lock();
750          try {          try {
751              int dirId = GetDirectoryId(DbDir);              int dirId = GetDirectoryId(DbDir);
752              if (dirId == -1) throw Exception("Invalid DB directory: " + DbDir);              if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedPath(DbDir));
753    
754              struct stat statBuf;              File f = File(FsDir);
755              int res = stat(FsDir.c_str(), &statBuf);              if (!f.Exist()) {
             if (res) {  
756                  std::stringstream ss;                  std::stringstream ss;
757                  ss << "Fail to stat `" << FsDir << "`: " << strerror(errno);                  ss << "Fail to stat `" << FsDir << "`: " << f.GetErrorMsg();
758                  throw Exception(ss.str());                  throw Exception(ss.str());
759              }              }
760    
761              if (!S_ISDIR(statBuf.st_mode)) {              if (!f.IsDirectory()) {
762                  throw Exception("Directory expected");                  throw Exception("Directory expected: " + FsDir);
763              }              }
764                            
765              if (FsDir.at(FsDir.length() - 1) != '/') FsDir.append("/");              if (FsDir.at(FsDir.length() - 1) != File::DirSeparator) {
766                    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;  
767              }              }
768                
769              struct dirent* pEnt = readdir(pDir);              try {
770              while (pEnt != NULL) {                  FileListPtr fileList = File::GetFiles(FsDir);
771                  if (pEnt->d_type != DT_REG) {                  for (int i = 0; i < fileList->size(); i++) {
772                      pEnt = readdir(pDir);                      String dir = insDir ? PrepareSubdirectory(DbDir, fileList->at(i)) : DbDir;
773                      continue;                                          AddInstrumentsFromFile(dir, FsDir + fileList->at(i), -1, pProgress);
774                  }                  }
775                } catch(Exception e) {
776                  AddInstrumentsFromFile(DbDir, FsDir + String(pEnt->d_name));                  e.PrintMessage();
777                  pEnt = readdir(pDir);                  DbInstrumentsMutex.Unlock();
778              }                  return;
   
             if (closedir(pDir)) {  
                 std::stringstream ss;  
                 ss << "Failed to close directory `" << FsDir << "`: ";  
                 ss << strerror(errno);  
                 std::cerr << ss.str();  
779              }              }
780          } catch (Exception e) {          } catch (Exception e) {
781              DbInstrumentsMutex.Unlock();              DbInstrumentsMutex.Unlock();
# Line 1035  namespace LinuxSampler { Line 785  namespace LinuxSampler {
785          DbInstrumentsMutex.Unlock();          DbInstrumentsMutex.Unlock();
786      }      }
787    
788      void InstrumentsDb::AddInstrumentsRecursive(String DbDir, String FsDir, bool Flat) {      void InstrumentsDb::AddInstrumentsRecursive(String DbDir, String FsDir, bool Flat, bool insDir, ScanProgress* pProgress) {
789          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));
790          DirectoryScanner::Scan(DbDir, FsDir, Flat);          if (pProgress != NULL) {
791                InstrumentFileCounter c;
792                pProgress->SetTotalFileCount(c.Count(FsDir));
793            }
794    
795            DirectoryScanner d;
796            d.Scan(DbDir, FsDir, Flat, insDir, pProgress);
797      }      }
798    
799      int InstrumentsDb::GetInstrumentCount(int DirId) {      int InstrumentsDb::GetInstrumentCount(int DirId) {
# Line 1069  namespace LinuxSampler { Line 825  namespace LinuxSampler {
825          }          }
826          EndTransaction();          EndTransaction();
827    
828          if (i == -1) throw Exception("Unknown Db directory: " + Dir);          if (i == -1) throw Exception("Unknown Db directory: " + toEscapedPath(Dir));
829          return i;          return i;
830      }      }
831    
# Line 1085  namespace LinuxSampler { Line 841  namespace LinuxSampler {
841          BeginTransaction();          BeginTransaction();
842          try {          try {
843              int dirId = GetDirectoryId(Dir);              int dirId = GetDirectoryId(Dir);
844              if(dirId == -1) throw Exception("Unknown DB directory: " + Dir);              if(dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
845    
846              StringListPtr pInstrs;              StringListPtr pInstrs;
847    
# Line 1099  namespace LinuxSampler { Line 855  namespace LinuxSampler {
855                  sql << "SELECT instr_name FROM instruments WHERE dir_id=" << dirId;                  sql << "SELECT instr_name FROM instruments WHERE dir_id=" << dirId;
856    
857                  pInstrs = ExecSqlStringList(sql.str());                  pInstrs = ExecSqlStringList(sql.str());
858                    // Converting to abstract names
859                    for (int i = 0; i < pInstrs->size(); i++) {
860                        for (int j = 0; j < pInstrs->at(i).length(); j++) {
861                            if (pInstrs->at(i).at(j) == '/') pInstrs->at(i).at(j) = '\0';
862                        }
863                    }
864              }              }
865              EndTransaction();              EndTransaction();
866              return pInstrs;              return pInstrs;
# Line 1123  namespace LinuxSampler { Line 885  namespace LinuxSampler {
885          std::stringstream sql;          std::stringstream sql;
886          sql << "SELECT instr_id FROM instruments WHERE dir_id=";          sql << "SELECT instr_id FROM instruments WHERE dir_id=";
887          sql << DirId << " AND instr_name=?";          sql << DirId << " AND instr_name=?";
888          return ExecSqlInt(sql.str(), InstrName);          return ExecSqlInt(sql.str(), toDbName(InstrName));
889      }      }
890    
891      String InstrumentsDb::GetInstrumentName(int InstrId) {      String InstrumentsDb::GetInstrumentName(int InstrId) {
892          dmsg(2,("InstrumentsDb: GetInstrumentName(InstrId=%d)\n", InstrId));          dmsg(2,("InstrumentsDb: GetInstrumentName(InstrId=%d)\n", InstrId));
893          std::stringstream sql;          std::stringstream sql;
894          sql << "SELECT instr_name FROM instruments WHERE instr_id=" << InstrId;          sql << "SELECT instr_name FROM instruments WHERE instr_id=" << InstrId;
895          return ExecSqlString(sql.str());          return toAbstractName(ExecSqlString(sql.str()));
896      }      }
897            
898      void InstrumentsDb::RemoveInstrument(String Instr) {      void InstrumentsDb::RemoveInstrument(String Instr) {
# Line 1142  namespace LinuxSampler { Line 904  namespace LinuxSampler {
904          try {          try {
905              int instrId = GetInstrumentId(Instr);              int instrId = GetInstrumentId(Instr);
906              if(instrId == -1) {              if(instrId == -1) {
907                  throw Exception("The specified instrument does not exist: " + Instr);                  throw Exception("The specified instrument does not exist: " + toEscapedPath(Instr));
908              }              }
909              RemoveInstrument(instrId);              RemoveInstrument(instrId);
910          } catch (Exception e) {          } catch (Exception e) {
# Line 1177  namespace LinuxSampler { Line 939  namespace LinuxSampler {
939          BeginTransaction();          BeginTransaction();
940          try {          try {
941              int id = GetInstrumentId(Instr);              int id = GetInstrumentId(Instr);
942              if(id == -1) throw Exception("Unknown DB instrument: " + Instr);              if(id == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
943              i = GetInstrumentInfo(id);              i = GetInstrumentInfo(id);
944          } catch (Exception e) {          } catch (Exception e) {
945              EndTransaction();              EndTransaction();
# Line 1236  namespace LinuxSampler { Line 998  namespace LinuxSampler {
998          BeginTransaction();          BeginTransaction();
999          try {          try {
1000              int dirId = GetDirectoryId(GetDirectoryPath(Instr));              int dirId = GetDirectoryId(GetDirectoryPath(Instr));
1001              if (dirId == -1) throw Exception("Unknown DB instrument: " + Instr);              if (dirId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1002    
1003              int instrId = GetInstrumentId(dirId, GetFileName(Instr));              int instrId = GetInstrumentId(dirId, GetFileName(Instr));
1004              if (instrId == -1) throw Exception("Unknown DB instrument: " + Instr);              if (instrId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1005    
1006              if (GetInstrumentId(dirId, Name) != -1) {              if (GetInstrumentId(dirId, Name) != -1) {
1007                  throw Exception("Cannot rename. Instrument with that name already exists: " + Name);                  String s = toEscapedPath(Name);
1008                    throw Exception("Cannot rename. Instrument with that name already exists: " + s);
1009              }              }
1010    
1011              if (GetDirectoryId(dirId, Name) != -1) {              if (GetDirectoryId(dirId, Name) != -1) {
1012                  throw Exception("Cannot rename. Directory with that name already exists: " + Name);                  String s = toEscapedPath(Name);
1013                    throw Exception("Cannot rename. Directory with that name already exists: " + s);
1014              }              }
1015    
1016              std::stringstream sql;              std::stringstream sql;
1017              sql << "UPDATE instruments SET instr_name=? WHERE instr_id=" << instrId;              sql << "UPDATE instruments SET instr_name=? WHERE instr_id=" << instrId;
1018              ExecSql(sql.str(), Name);              ExecSql(sql.str(), toDbName(Name));
1019          } catch (Exception e) {          } catch (Exception e) {
1020              EndTransaction();              EndTransaction();
1021              throw e;              throw e;
1022          }          }
1023          EndTransaction();          EndTransaction();
1024          FireInstrumentNameChanged(Instr, Name);          FireInstrumentNameChanged(Instr, toAbstractName(Name));
1025      }      }
1026    
1027      void InstrumentsDb::MoveInstrument(String Instr, String Dst) {      void InstrumentsDb::MoveInstrument(String Instr, String Dst) {
# Line 1267  namespace LinuxSampler { Line 1031  namespace LinuxSampler {
1031    
1032          BeginTransaction();          BeginTransaction();
1033          try {          try {
1034              int dirId = GetDirectoryId(GetDirectoryPath(Instr));              int dirId = GetDirectoryId(ParentDir);
1035              if (dirId == -1) throw Exception("Unknown DB instrument: " + Instr);              if (dirId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1036    
1037              String instrName = GetFileName(Instr);              String instrName = GetFileName(Instr);
1038              int instrId = GetInstrumentId(dirId, instrName);              int instrId = GetInstrumentId(dirId, instrName);
1039              if (instrId == -1) throw Exception("Unknown DB instrument: " + Instr);              if (instrId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1040    
1041              int dstId = GetDirectoryId(Dst);              int dstId = GetDirectoryId(Dst);
1042              if (dstId == -1) throw Exception("Unknown DB directory: " + Dst);              if (dstId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dst));
1043              if (dirId == dstId) {              if (dirId == dstId) {
1044                  EndTransaction();                  EndTransaction();
1045                  return;                  return;
1046              }              }
1047    
1048              if (GetInstrumentId(dstId, instrName) != -1) {              if (GetInstrumentId(dstId, instrName) != -1) {
1049                  throw Exception("Cannot move. Instrument with that name already exists: " + instrName);                  String s = toEscapedPath(instrName);
1050                    throw Exception("Cannot move. Instrument with that name already exists: " + s);
1051              }              }
1052    
1053              if (GetDirectoryId(dstId, instrName) != -1) {              if (GetDirectoryId(dstId, instrName) != -1) {
1054                  throw Exception("Cannot move. Directory with that name already exists: " + instrName);                  String s = toEscapedPath(instrName);
1055                    throw Exception("Cannot move. Directory with that name already exists: " + s);
1056              }              }
1057    
1058              std::stringstream sql;              std::stringstream sql;
# Line 1310  namespace LinuxSampler { Line 1076  namespace LinuxSampler {
1076          BeginTransaction();          BeginTransaction();
1077          try {          try {
1078              int dirId = GetDirectoryId(GetDirectoryPath(Instr));              int dirId = GetDirectoryId(GetDirectoryPath(Instr));
1079              if (dirId == -1) throw Exception("Unknown DB instrument: " + Instr);              if (dirId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1080    
1081              String instrName = GetFileName(Instr);              String instrName = GetFileName(Instr);
1082              int instrId = GetInstrumentId(dirId, instrName);              int instrId = GetInstrumentId(dirId, instrName);
1083              if (instrId == -1) throw Exception("Unknown DB instrument: " + Instr);              if (instrId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1084    
1085              int dstId = GetDirectoryId(Dst);              int dstId = GetDirectoryId(Dst);
1086              if (dstId == -1) throw Exception("Unknown DB directory: " + Dst);              if (dstId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dst));
1087              if (dirId == dstId) {              if (dirId == dstId) {
1088                  EndTransaction();                  EndTransaction();
1089                  return;                  return;
1090              }              }
1091    
             if (GetInstrumentId(dstId, instrName) != -1) {  
                 throw Exception("Cannot copy. Instrument with that name already exists: " + instrName);  
             }  
   
             if (GetDirectoryId(dstId, instrName) != -1) {  
                 throw Exception("Cannot copy. Directory with that name already exists: " + instrName);  
             }  
   
1092              CopyInstrument(instrId, instrName, dstId, Dst);              CopyInstrument(instrId, instrName, dstId, Dst);
1093          } catch (Exception e) {          } catch (Exception e) {
1094              EndTransaction();              EndTransaction();
# Line 1341  namespace LinuxSampler { Line 1099  namespace LinuxSampler {
1099      }      }
1100    
1101      void InstrumentsDb::CopyInstrument(int InstrId, String InstrName, int DstDirId, String DstDir) {      void InstrumentsDb::CopyInstrument(int InstrId, String InstrName, int DstDirId, String DstDir) {
1102            if (GetInstrumentId(DstDirId, InstrName) != -1) {
1103                String s = toEscapedPath(InstrName);
1104                throw Exception("Cannot copy. Instrument with that name already exists: " + s);
1105            }
1106    
1107            if (GetDirectoryId(DstDirId, InstrName) != -1) {
1108                String s = toEscapedPath(InstrName);
1109                throw Exception("Cannot copy. Directory with that name already exists: " + s);
1110            }
1111    
1112          DbInstrument i = GetInstrumentInfo(InstrId);          DbInstrument i = GetInstrumentInfo(InstrId);
1113          sqlite3_stmt *pStmt = NULL;          sqlite3_stmt *pStmt = NULL;
1114          std::stringstream sql;          std::stringstream sql;
# Line 1354  namespace LinuxSampler { Line 1122  namespace LinuxSampler {
1122              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1123          }          }
1124    
1125          BindTextParam(pStmt, 1, InstrName);          String s = toDbName(InstrName);
1126            BindTextParam(pStmt, 1, s);
1127          BindTextParam(pStmt, 2, i.InstrFile);          BindTextParam(pStmt, 2, i.InstrFile);
1128          BindTextParam(pStmt, 3, i.FormatFamily);          BindTextParam(pStmt, 3, i.FormatFamily);
1129          BindTextParam(pStmt, 4, i.FormatVersion);          BindTextParam(pStmt, 4, i.FormatVersion);
# Line 1379  namespace LinuxSampler { Line 1148  namespace LinuxSampler {
1148          BeginTransaction();          BeginTransaction();
1149          try {          try {
1150              int id = GetInstrumentId(Instr);              int id = GetInstrumentId(Instr);
1151              if(id == -1) throw Exception("Unknown DB instrument: " + Instr);              if(id == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1152    
1153              std::stringstream sql;              std::stringstream sql;
1154              sql << "UPDATE instruments SET description=?,modified=CURRENT_TIMESTAMP ";              sql << "UPDATE instruments SET description=?,modified=CURRENT_TIMESTAMP ";
# Line 1394  namespace LinuxSampler { Line 1163  namespace LinuxSampler {
1163          FireInstrumentInfoChanged(Instr);          FireInstrumentInfoChanged(Instr);
1164      }      }
1165    
1166      void InstrumentsDb::AddInstrumentsFromFile(String DbDir, String File, int Index) {      void InstrumentsDb::AddInstrumentsFromFile(String DbDir, String File, int Index, ScanProgress* pProgress) {
1167          dmsg(2,("InstrumentsDb: AddInstrumentsFromFile(DbDir=%s,File=%s,Index=%d)\n", DbDir.c_str(), File.c_str(), Index));          dmsg(2,("InstrumentsDb: AddInstrumentsFromFile(DbDir=%s,File=%s,Index=%d)\n", DbDir.c_str(), File.c_str(), Index));
1168                    
1169          if(File.length() < 4) return;          if(File.length() < 4) return;
1170                    
1171          try {          try {
1172              if(!strcasecmp(".gig", File.substr(File.length() - 4).c_str())) {              if(!strcasecmp(".gig", File.substr(File.length() - 4).c_str())) {
1173                  AddGigInstruments(DbDir, File, Index);                  if (pProgress != NULL) {
1174                        pProgress->SetStatus(0);
1175                        pProgress->CurrentFile = File;
1176                    }
1177    
1178                    AddGigInstruments(DbDir, File, Index, pProgress);
1179    
1180                    if (pProgress != NULL) {
1181                        pProgress->SetScannedFileCount(pProgress->GetScannedFileCount() + 1);
1182                    }
1183              }              }
1184          } catch(Exception e) {          } catch(Exception e) {
1185              std::cerr << e.Message() << std::endl;              e.PrintMessage();
1186          }          }
1187      }      }
1188    
1189      void InstrumentsDb::AddGigInstruments(String DbDir, String File, int Index) {      void InstrumentsDb::AddGigInstruments(String DbDir, String FilePath, int Index, ScanProgress* pProgress) {
1190          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));
1191          int dirId = GetDirectoryId(DbDir);          int dirId = GetDirectoryId(DbDir);
1192          if (dirId == -1) throw Exception("Invalid DB directory: " + DbDir);          if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedPath(DbDir));
1193    
1194          struct stat statBuf;          File f = File(FilePath);
1195          int res = stat(File.c_str(), &statBuf);          if (!f.Exist()) {
         if (res) {  
1196              std::stringstream ss;              std::stringstream ss;
1197              ss << "Fail to stat `" << File << "`: " << strerror(errno);              ss << "Fail to stat `" << FilePath << "`: " << f.GetErrorMsg();
1198              throw Exception(ss.str());              throw Exception(ss.str());
1199          }          }
1200    
1201          if (!S_ISREG(statBuf.st_mode)) {          if (!f.IsFile()) {
1202              std::stringstream ss;              std::stringstream ss;
1203              ss << "`" << File << "` is not a regular file";              ss << "`" << FilePath << "` is not a regular file";
1204              throw Exception(ss.str());              throw Exception(ss.str());
1205          }          }
1206    
1207            bool unlocked = false;
1208          RIFF::File* riff = NULL;          RIFF::File* riff = NULL;
1209          gig::File* gig = NULL;          gig::File* gig = NULL;
1210          try {          try {
1211              riff = new RIFF::File(File);              riff = new RIFF::File(FilePath);
1212              gig::File* gig = new gig::File(riff);              gig::File* gig = new gig::File(riff);
1213                            gig->SetAutoLoad(false); // avoid time consuming samples scanning
1214    
1215              std::stringstream sql;              std::stringstream sql;
1216              sql << "INSERT INTO instruments (dir_id,instr_name,instr_file,";              sql << "INSERT INTO instruments (dir_id,instr_name,instr_file,";
1217              sql << "instr_nr,format_family,format_version,instr_size,";              sql << "instr_nr,format_family,format_version,instr_size,";
1218              sql << "description,is_drum,product,artists,keywords) VALUES (";              sql << "description,is_drum,product,artists,keywords) VALUES (";
1219              sql << dirId << ",?,?,?,'GIG',?," << statBuf.st_size << ",?,?,?,?,?)";              sql << dirId << ",?,?,?,'GIG',?," << f.GetSize() << ",?,?,?,?,?)";
1220    
1221              sqlite3_stmt* pStmt = NULL;              sqlite3_stmt* pStmt = NULL;
1222    
# Line 1446  namespace LinuxSampler { Line 1225  namespace LinuxSampler {
1225                  throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));                  throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1226              }              }
1227    
1228              BindTextParam(pStmt, 2, File);              String s = FilePath;
1229                s = toEscapedFsPath(s);
1230                BindTextParam(pStmt, 2, s);
1231              String ver = "";              String ver = "";
1232              if (gig->pVersion != NULL) ver = ToString(gig->pVersion->major);              if (gig->pVersion != NULL) ver = ToString(gig->pVersion->major);
1233              BindTextParam(pStmt, 4, ver);              BindTextParam(pStmt, 4, ver);
1234    
1235              if (Index == -1) {              if (Index == -1) {
1236                  int instrIndex = 0;                  int instrIndex = 0;
1237                    // Assume that it's locked and should be unlocked at this point
1238                    // to be able to use the database from another threads
1239                    if (!InTransaction) {
1240                        DbInstrumentsMutex.Unlock();
1241                        unlocked = true;
1242                    } else {
1243                        std::cerr << "Shouldn't be in transaction when adding instruments." << std::endl;
1244                    }
1245    
1246                    if (pProgress != NULL) gig->GetInstrument(0, &(pProgress->GigFileProgress)); // TODO: this workaround should be fixed
1247                  gig::Instrument* pInstrument = gig->GetFirstInstrument();                  gig::Instrument* pInstrument = gig->GetFirstInstrument();
1248    
1249                    if (!InTransaction) DbInstrumentsMutex.Lock();
1250                  while (pInstrument) {                  while (pInstrument) {
1251                      BindTextParam(pStmt, 7, gig->pInfo->Product);                      BindTextParam(pStmt, 7, gig->pInfo->Product);
1252                      BindTextParam(pStmt, 8, gig->pInfo->Artists);                      BindTextParam(pStmt, 8, gig->pInfo->Artists);
1253                      BindTextParam(pStmt, 9, gig->pInfo->Keywords);                      BindTextParam(pStmt, 9, gig->pInfo->Keywords);
1254                      AddGigInstrument(pStmt, DbDir, dirId, File, pInstrument, instrIndex);                      AddGigInstrument(pStmt, DbDir, dirId, FilePath, pInstrument, instrIndex);
1255    
1256                      instrIndex++;                      instrIndex++;
1257                      pInstrument = gig->GetNextInstrument();                      pInstrument = gig->GetNextInstrument();
1258                  }                  }
1259              } else {              } else {
1260                  gig::Instrument* pInstrument = gig->GetInstrument(Index);                  gig::Instrument* pInstrument;
1261                    if (pProgress == NULL) pInstrument = gig->GetInstrument(Index);
1262                    else pInstrument = gig->GetInstrument(Index, &(pProgress->GigFileProgress));
1263                  if (pInstrument != NULL) {                  if (pInstrument != NULL) {
1264                      BindTextParam(pStmt, 7, gig->pInfo->Product);                      BindTextParam(pStmt, 7, gig->pInfo->Product);
1265                      BindTextParam(pStmt, 8, gig->pInfo->Artists);                      BindTextParam(pStmt, 8, gig->pInfo->Artists);
1266                      BindTextParam(pStmt, 9, gig->pInfo->Keywords);                      BindTextParam(pStmt, 9, gig->pInfo->Keywords);
1267                      AddGigInstrument(pStmt, DbDir, dirId, File, pInstrument, Index);                      AddGigInstrument(pStmt, DbDir, dirId, FilePath, pInstrument, Index);
1268                  }                  }
1269              }              }
1270    
# Line 1479  namespace LinuxSampler { Line 1274  namespace LinuxSampler {
1274          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
1275              if (gig != NULL) delete gig;              if (gig != NULL) delete gig;
1276              if (riff != NULL) delete riff;              if (riff != NULL) delete riff;
1277                if (unlocked) DbInstrumentsMutex.Lock();
1278              std::stringstream ss;              std::stringstream ss;
1279              ss << "Failed to scan `" << File << "`: " << e.Message;              ss << "Failed to scan `" << FilePath << "`: " << e.Message;
1280                            
1281              throw Exception(ss.str());              throw Exception(ss.str());
1282          } catch (Exception e) {          } catch (Exception e) {
1283              if (gig != NULL) delete gig;              if (gig != NULL) delete gig;
1284              if (riff != NULL) delete riff;              if (riff != NULL) delete riff;
1285                if (unlocked) DbInstrumentsMutex.Lock();
1286              throw e;              throw e;
1287          } catch (...) {          } catch (...) {
1288              if (gig != NULL) delete gig;              if (gig != NULL) delete gig;
1289              if (riff != NULL) delete riff;              if (riff != NULL) delete riff;
1290              throw Exception("Failed to scan `" + File + "`");              if (unlocked) DbInstrumentsMutex.Lock();
1291                throw Exception("Failed to scan `" + FilePath + "`");
1292          }          }
1293      }      }
1294    
1295      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) {
1296            dmsg(2,("InstrumentsDb: AddGigInstrument(DbDir=%s,DirId=%d,File=%s,Index=%d)\n", DbDir.c_str(), DirId, File.c_str(), Index));
1297          String name = pInstrument->pInfo->Name;          String name = pInstrument->pInfo->Name;
1298          if (name == "") return;          if (name == "") return;
1299          name = GetUniqueInstrumentName(DirId, name);          name = GetUniqueName(DirId, name);
1300                    
1301          std::stringstream sql2;          std::stringstream sql2;
1302          sql2 << "SELECT COUNT(*) FROM instruments WHERE instr_file=? AND ";          sql2 << "SELECT COUNT(*) FROM instruments WHERE instr_file=? AND ";
1303          sql2 << "instr_nr=" << Index;          sql2 << "instr_nr=" << Index;
1304          if (ExecSqlInt(sql2.str(), File) > 0) return;          String s = toEscapedFsPath(File);
1305            if (ExecSqlInt(sql2.str(), s) > 0) return;
1306    
1307          BindTextParam(pStmt, 1, name);          BindTextParam(pStmt, 1, name);
1308          BindIntParam(pStmt, 3, Index);          BindIntParam(pStmt, 3, Index);
# Line 1531  namespace LinuxSampler { Line 1331  namespace LinuxSampler {
1331          FireInstrumentCountChanged(DbDir);          FireInstrumentCountChanged(DbDir);
1332      }      }
1333    
1334      void InstrumentsDb::DirectoryTreeWalk(String Path, DirectoryHandler* pHandler) {      void InstrumentsDb::DirectoryTreeWalk(String AbstractPath, DirectoryHandler* pHandler) {
1335          int DirId = GetDirectoryId(Path);          int DirId = GetDirectoryId(AbstractPath);
1336          if(DirId == -1) throw Exception("Unknown DB directory: " + Path);          if(DirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(AbstractPath));
1337          DirectoryTreeWalk(pHandler, Path, DirId, 0);          DirectoryTreeWalk(pHandler, AbstractPath, DirId, 0);
1338      }      }
1339    
1340      void InstrumentsDb::DirectoryTreeWalk(DirectoryHandler* pHandler, String Path, int DirId, int Level) {      void InstrumentsDb::DirectoryTreeWalk(DirectoryHandler* pHandler, String AbstractPath, int DirId, int Level) {
1341          if(Level == 1000) throw Exception("Possible infinite loop detected");          if(Level == 1000) throw Exception("Possible infinite loop detected");
1342          pHandler->ProcessDirectory(Path, DirId);          pHandler->ProcessDirectory(AbstractPath, DirId);
1343                    
1344          String s;          String s;
1345          StringListPtr pDirs = GetDirectories(DirId);          StringListPtr pDirs = GetDirectories(DirId);
1346          for(int i = 0; i < pDirs->size(); i++) {          for(int i = 0; i < pDirs->size(); i++) {
1347              if (Path.length() == 1 && Path.at(0) == '/') s = "/" + pDirs->at(i);              if (AbstractPath.length() == 1 && AbstractPath.at(0) == '/') {
1348              else s = Path + "/" + pDirs->at(i);                  s = "/" + pDirs->at(i);
1349                } else {
1350                    s = AbstractPath + "/" + pDirs->at(i);
1351                }
1352              DirectoryTreeWalk(pHandler, s, GetDirectoryId(DirId, pDirs->at(i)), Level + 1);              DirectoryTreeWalk(pHandler, s, GetDirectoryId(DirId, pDirs->at(i)), Level + 1);
1353          }          }
1354      }      }
# Line 1557  namespace LinuxSampler { Line 1360  namespace LinuxSampler {
1360          BeginTransaction();          BeginTransaction();
1361          try {          try {
1362              int DirId = GetDirectoryId(Dir);              int DirId = GetDirectoryId(Dir);
1363              if(DirId == -1) throw Exception("Unknown DB directory: " + Dir);              if(DirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
1364    
1365              if (Recursive) DirectoryTreeWalk(Dir, &directoryFinder);              if (Recursive) DirectoryTreeWalk(Dir, &directoryFinder);
1366              else directoryFinder.ProcessDirectory(Dir, DirId);              else directoryFinder.ProcessDirectory(Dir, DirId);
# Line 1577  namespace LinuxSampler { Line 1380  namespace LinuxSampler {
1380          BeginTransaction();          BeginTransaction();
1381          try {          try {
1382              int DirId = GetDirectoryId(Dir);              int DirId = GetDirectoryId(Dir);
1383              if(DirId == -1) throw Exception("Unknown DB directory: " + Dir);              if(DirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
1384    
1385              if (Recursive) DirectoryTreeWalk(Dir, &instrumentFinder);              if (Recursive) DirectoryTreeWalk(Dir, &instrumentFinder);
1386              else instrumentFinder.ProcessDirectory(Dir, DirId);              else instrumentFinder.ProcessDirectory(Dir, DirId);
# Line 1589  namespace LinuxSampler { Line 1392  namespace LinuxSampler {
1392    
1393          return instrumentFinder.GetInstruments();          return instrumentFinder.GetInstruments();
1394      }      }
1395        
1396        StringListPtr InstrumentsDb::FindLostInstrumentFiles() {
1397            dmsg(2,("InstrumentsDb: FindLostInstrumentFiles()\n"));
1398    
1399            BeginTransaction();
1400            try {
1401                StringListPtr files = ExecSqlStringList("SELECT DISTINCT instr_file FROM instruments");
1402                StringListPtr result(new std::vector<String>);
1403                for (int i = 0; i < files->size(); i++) {
1404                    File f(toNonEscapedFsPath(files->at(i)));
1405                    if (!f.Exist()) result->push_back(files->at(i));
1406                }
1407                return result;
1408            } catch (Exception e) {
1409                EndTransaction();
1410                throw e;
1411            }
1412            EndTransaction();
1413        }
1414        
1415        void InstrumentsDb::SetInstrumentFilePath(String OldPath, String NewPath) {
1416            if (OldPath == NewPath) return;
1417            StringListPtr instrs;
1418            BeginTransaction();
1419            try {
1420                std::vector<String> params(2);
1421                params[0] = toEscapedFsPath(NewPath);
1422                params[1] = toEscapedFsPath(OldPath);
1423                instrs = GetInstrumentsByFile(OldPath);
1424                ExecSql("UPDATE instruments SET instr_file=? WHERE instr_file=?", params);
1425            } catch (Exception e) {
1426                EndTransaction();
1427                throw e;
1428            }
1429            EndTransaction();
1430            
1431            for (int i = 0; i < instrs->size(); i++) {
1432                FireInstrumentInfoChanged(instrs->at(i));
1433            }
1434        }
1435    
1436      void InstrumentsDb::BeginTransaction() {      void InstrumentsDb::BeginTransaction() {
1437          dmsg(2,("InstrumentsDb: BeginTransaction(InTransaction=%d)\n", InTransaction));          dmsg(2,("InstrumentsDb: BeginTransaction(InTransaction=%d)\n", InTransaction));
# Line 1650  namespace LinuxSampler { Line 1493  namespace LinuxSampler {
1493    
1494      void InstrumentsDb::ExecSql(String Sql) {      void InstrumentsDb::ExecSql(String Sql) {
1495          dmsg(2,("InstrumentsDb: ExecSql(Sql=%s)\n", Sql.c_str()));          dmsg(2,("InstrumentsDb: ExecSql(Sql=%s)\n", Sql.c_str()));
1496          sqlite3_stmt *pStmt = NULL;          std::vector<String> Params;
1497                    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);  
1498      }      }
1499    
1500      void InstrumentsDb::ExecSql(String Sql, String Param) {      void InstrumentsDb::ExecSql(String Sql, String Param) {
1501          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()));
1502            std::vector<String> Params;
1503            Params.push_back(Param);
1504            ExecSql(Sql, Params);
1505        }
1506    
1507        void InstrumentsDb::ExecSql(String Sql, std::vector<String>& Params) {
1508            dmsg(2,("InstrumentsDb: ExecSql(Sql=%s,Params)\n", Sql.c_str()));
1509          sqlite3_stmt *pStmt = NULL;          sqlite3_stmt *pStmt = NULL;
1510                    
1511          int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);          int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);
# Line 1676  namespace LinuxSampler { Line 1514  namespace LinuxSampler {
1514              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1515          }          }
1516    
1517          BindTextParam(pStmt, 1, Param);          for(int i = 0; i < Params.size(); i++) {
1518                BindTextParam(pStmt, i + 1, Params[i]);
1519            }
1520    
1521          res = sqlite3_step(pStmt);          res = sqlite3_step(pStmt);
1522          if (res != SQLITE_DONE) {          if (res != SQLITE_DONE) {
# Line 1758  namespace LinuxSampler { Line 1598  namespace LinuxSampler {
1598      }      }
1599    
1600      IntListPtr InstrumentsDb::ExecSqlIntList(String Sql) {      IntListPtr InstrumentsDb::ExecSqlIntList(String Sql) {
1601            dmsg(2,("InstrumentsDb: ExecSqlIntList(Sql=%s)\n", Sql.c_str()));
1602            std::vector<String> Params;
1603            return ExecSqlIntList(Sql, Params);
1604        }
1605    
1606        IntListPtr InstrumentsDb::ExecSqlIntList(String Sql, String Param) {
1607            dmsg(2,("InstrumentsDb: ExecSqlIntList(Sql=%s,Param=%s)\n", Sql.c_str(), Param.c_str()));
1608            std::vector<String> Params;
1609            Params.push_back(Param);
1610            return ExecSqlIntList(Sql, Params);
1611        }
1612    
1613        IntListPtr InstrumentsDb::ExecSqlIntList(String Sql, std::vector<String>& Params) {
1614            dmsg(2,("InstrumentsDb: ExecSqlIntList(Sql=%s)\n", Sql.c_str()));
1615          IntListPtr intList(new std::vector<int>);          IntListPtr intList(new std::vector<int>);
1616                    
1617          sqlite3_stmt *pStmt = NULL;          sqlite3_stmt *pStmt = NULL;
# Line 1767  namespace LinuxSampler { Line 1621  namespace LinuxSampler {
1621              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));              throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1622          }          }
1623                    
1624            for(int i = 0; i < Params.size(); i++) {
1625                BindTextParam(pStmt, i + 1, Params[i]);
1626            }
1627            
1628          res = sqlite3_step(pStmt);          res = sqlite3_step(pStmt);
1629          while(res == SQLITE_ROW) {          while(res == SQLITE_ROW) {
1630              intList->push_back(sqlite3_column_int(pStmt, 0));              intList->push_back(sqlite3_column_int(pStmt, 0));
# Line 1784  namespace LinuxSampler { Line 1642  namespace LinuxSampler {
1642      }      }
1643            
1644      StringListPtr InstrumentsDb::ExecSqlStringList(String Sql) {      StringListPtr InstrumentsDb::ExecSqlStringList(String Sql) {
1645            dmsg(2,("InstrumentsDb: ExecSqlStringList(Sql=%s)\n", Sql.c_str()));
1646          StringListPtr stringList(new std::vector<String>);          StringListPtr stringList(new std::vector<String>);
1647                    
1648          sqlite3_stmt *pStmt = NULL;          sqlite3_stmt *pStmt = NULL;
# Line 1827  namespace LinuxSampler { Line 1686  namespace LinuxSampler {
1686          }          }
1687      }      }
1688    
1689    #ifndef WIN32
1690      void InstrumentsDb::Regexp(sqlite3_context* pContext, int argc, sqlite3_value** ppValue) {      void InstrumentsDb::Regexp(sqlite3_context* pContext, int argc, sqlite3_value** ppValue) {
1691          if (argc != 2) return;          if (argc != 2) return;
1692    
# Line 1837  namespace LinuxSampler { Line 1697  namespace LinuxSampler {
1697              sqlite3_result_int(pContext, 1);              sqlite3_result_int(pContext, 1);
1698          }          }
1699      }      }
1700    #endif
1701    
1702      String InstrumentsDb::GetDirectoryPath(String File) {      String InstrumentsDb::GetDirectoryPath(String File) {
1703          if (File.empty()) return String("");          if (File.empty()) return String("");
# Line 1879  namespace LinuxSampler { Line 1740  namespace LinuxSampler {
1740          return Dir.substr(0, i);          return Dir.substr(0, i);
1741      }      }
1742    
1743        void InstrumentsDb::Format() {
1744            DbInstrumentsMutex.Lock();
1745            if (db != NULL) {
1746                sqlite3_close(db);
1747                db = NULL;
1748            }
1749    
1750            if (DbFile.empty()) DbFile = CONFIG_DEFAULT_INSTRUMENTS_DB_LOCATION;
1751            String bkp = DbFile + ".bkp";
1752            remove(bkp.c_str());
1753            if (rename(DbFile.c_str(), bkp.c_str()) && errno != ENOENT) {
1754                DbInstrumentsMutex.Unlock();
1755                throw Exception(String("Failed to backup database: ") + strerror(errno));
1756            }
1757            
1758            String f = DbFile;
1759            DbFile = "";
1760            try { CreateInstrumentsDb(f); }
1761            catch(Exception e) {
1762                DbInstrumentsMutex.Unlock();
1763                throw e;
1764            }
1765            DbInstrumentsMutex.Unlock();
1766            
1767            FireDirectoryCountChanged("/");
1768            FireInstrumentCountChanged("/");
1769        }
1770    
1771      void InstrumentsDb::CheckFileName(String File) {      void InstrumentsDb::CheckFileName(String File) {
1772          if (File.empty()) throw Exception("Invalid file name: " + File);          if (File.empty()) throw Exception("Invalid file name: " + File);
         if (File.find('/') != std::string::npos) {  
             throw Exception("Invalid file name: " + File);  
         }  
1773      }      }
1774    
1775      String InstrumentsDb::GetUniqueInstrumentName(int DirId, String Name) {      String InstrumentsDb::GetUniqueName(int DirId, String Name) {
1776          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()));
1777    
1778          if (GetInstrumentId(DirId, Name) == -1 && GetDirectoryId(DirId, Name) == -1) return Name;          if (GetInstrumentId(DirId, Name) == -1 && GetDirectoryId(DirId, Name) == -1) return Name;
# Line 1902  namespace LinuxSampler { Line 1788  namespace LinuxSampler {
1788          throw Exception("Unable to find an unique name: " + Name);          throw Exception("Unable to find an unique name: " + Name);
1789      }      }
1790            
1791        String InstrumentsDb::PrepareSubdirectory(String DbDir, String FsPath) {
1792            std::string dir = Path::getBaseName(FsPath);
1793            dir = toAbstractName(dir);
1794            if(dir.empty()) dir = "New Directory";
1795            dir = GetUniqueName(GetDirectoryId(DbDir), dir);
1796            dir = AppendNode(DbDir, dir);
1797            AddDirectory(dir);
1798            return dir;
1799        }
1800    
1801        String InstrumentsDb::AppendNode(String DbDir, String Node) {
1802            if(DbDir.length() == 1 && DbDir.at(0) == '/') return DbDir + Node;
1803            if(DbDir.at(DbDir.length() - 1) == '/') return DbDir + Node;
1804            return DbDir + "/" + Node;
1805        }
1806    
1807        String InstrumentsDb::toDbName(String AbstractName) {
1808            for (int i = 0; i < AbstractName.length(); i++) {
1809                if (AbstractName.at(i) == '\0') AbstractName.at(i) = '/';
1810            }
1811            return AbstractName;
1812        }
1813    
1814        String InstrumentsDb::toEscapedPath(String AbstractName) {
1815            for (int i = 0; i < AbstractName.length(); i++) {
1816                if (AbstractName.at(i) == '\0')      AbstractName.replace(i++, 1, "\\x2f");
1817                else if (AbstractName.at(i) == '\\') AbstractName.replace(i++, 1, "\\\\");
1818                else if (AbstractName.at(i) == '\'') AbstractName.replace(i++, 1, "\\'");
1819                else if (AbstractName.at(i) == '"')  AbstractName.replace(i++, 1, "\\\"");
1820                else if (AbstractName.at(i) == '\r') AbstractName.replace(i++, 1, "\\r");
1821                else if (AbstractName.at(i) == '\n') AbstractName.replace(i++, 1, "\\n");
1822            }
1823            return AbstractName;
1824        }
1825        
1826        String InstrumentsDb::toEscapedText(String text) {
1827            for (int i = 0; i < text.length(); i++) {
1828                if (text.at(i) == '\\')      text.replace(i++, 1, "\\\\");
1829                else if (text.at(i) == '\'') text.replace(i++, 1, "\\'");
1830                else if (text.at(i) == '"')  text.replace(i++, 1, "\\\"");
1831                else if (text.at(i) == '\r') text.replace(i++, 1, "\\r");
1832                else if (text.at(i) == '\n') text.replace(i++, 1, "\\n");
1833            }
1834            return text;
1835        }
1836        
1837        String InstrumentsDb::toNonEscapedText(String text) {
1838            String sb;
1839            for (int i = 0; i < text.length(); i++) {
1840                char c = text.at(i);
1841                            if(c == '\\') {
1842                                    if(i >= text.length()) {
1843                                            std::cerr << "Broken escape sequence!" << std::endl;
1844                                            break;
1845                                    }
1846                                    char c2 = text.at(++i);
1847                                    if(c2 == '\'')      sb.push_back('\'');
1848                                    else if(c2 == '"')  sb.push_back('"');
1849                                    else if(c2 == '\\') sb.push_back('\\');
1850                                    else if(c2 == 'r')  sb.push_back('\r');
1851                                    else if(c2 == 'n')  sb.push_back('\n');
1852                                    else std::cerr << "Unknown escape sequence \\" << c2 << std::endl;
1853                            } else {
1854                                    sb.push_back(c);
1855                            }
1856            }
1857            return sb;
1858        }
1859        
1860        String InstrumentsDb::toEscapedFsPath(String FsPath) {
1861    #ifdef WIN32
1862            replace(FsPath.begin(), FsPath.end(), '\\', '/');
1863    #endif
1864            return toEscapedText(FsPath);
1865        }
1866        
1867        String InstrumentsDb::toNonEscapedFsPath(String FsPath) {
1868            FsPath = toNonEscapedText(FsPath);
1869    #ifdef WIN32
1870            replace(FsPath.begin(), FsPath.end(), '/', '\\');
1871    #endif
1872            return FsPath;
1873        }
1874        
1875        String InstrumentsDb::toAbstractName(String DbName) {
1876            for (int i = 0; i < DbName.length(); i++) {
1877                if (DbName.at(i) == '/') DbName.at(i) = '\0';
1878            }
1879            return DbName;
1880        }
1881    
1882      void InstrumentsDb::FireDirectoryCountChanged(String Dir) {      void InstrumentsDb::FireDirectoryCountChanged(String Dir) {
1883          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1884              llInstrumentsDbListeners.GetListener(i)->DirectoryCountChanged(Dir);              llInstrumentsDbListeners.GetListener(i)->DirectoryCountChanged(Dir);
1885          }          }
1886      }      }
1887        
1888      void InstrumentsDb::FireDirectoryInfoChanged(String Dir) {      void InstrumentsDb::FireDirectoryInfoChanged(String Dir) {
1889          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1890              llInstrumentsDbListeners.GetListener(i)->DirectoryInfoChanged(Dir);              llInstrumentsDbListeners.GetListener(i)->DirectoryInfoChanged(Dir);
1891          }          }
1892      }      }
1893        
1894      void InstrumentsDb::FireDirectoryNameChanged(String Dir, String NewName) {      void InstrumentsDb::FireDirectoryNameChanged(String Dir, String NewName) {
1895          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1896              llInstrumentsDbListeners.GetListener(i)->DirectoryNameChanged(Dir, NewName);              llInstrumentsDbListeners.GetListener(i)->DirectoryNameChanged(Dir, NewName);
1897          }          }
1898      }      }
1899        
1900      void InstrumentsDb::FireInstrumentCountChanged(String Dir) {      void InstrumentsDb::FireInstrumentCountChanged(String Dir) {
1901          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1902              llInstrumentsDbListeners.GetListener(i)->InstrumentCountChanged(Dir);              llInstrumentsDbListeners.GetListener(i)->InstrumentCountChanged(Dir);
1903          }          }
1904      }      }
1905        
1906      void InstrumentsDb::FireInstrumentInfoChanged(String Instr) {      void InstrumentsDb::FireInstrumentInfoChanged(String Instr) {
1907          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1908              llInstrumentsDbListeners.GetListener(i)->InstrumentInfoChanged(Instr);              llInstrumentsDbListeners.GetListener(i)->InstrumentInfoChanged(Instr);
1909          }          }
1910      }      }
1911        
1912      void InstrumentsDb::FireInstrumentNameChanged(String Instr, String NewName) {      void InstrumentsDb::FireInstrumentNameChanged(String Instr, String NewName) {
1913          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1914              llInstrumentsDbListeners.GetListener(i)->InstrumentNameChanged(Instr, NewName);              llInstrumentsDbListeners.GetListener(i)->InstrumentNameChanged(Instr, NewName);
1915          }          }
1916      }      }
       
   
     String DirectoryScanner::DbDir;  
     String DirectoryScanner::FsDir;  
     bool DirectoryScanner::Flat;  
   
     void DirectoryScanner::Scan(String DbDir, String FsDir, bool Flat) {  
         dmsg(2,("DirectoryScanner: Scan(DbDir=%s,FsDir=%s,Flat=%d)\n", DbDir.c_str(), FsDir.c_str(), Flat));  
         if (DbDir.empty() || FsDir.empty()) throw Exception("Directory expected");  
           
         struct stat statBuf;  
         int res = stat(FsDir.c_str(), &statBuf);  
         if (res) {  
             std::stringstream ss;  
             ss << "Fail to stat `" << FsDir << "`: " << strerror(errno);  
             throw Exception(ss.str());  
         }  
1917    
1918          if (!S_ISDIR(statBuf.st_mode)) {      void InstrumentsDb::FireJobStatusChanged(int JobId) {
1919              throw Exception("Directory expected");          for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1920          }              llInstrumentsDbListeners.GetListener(i)->JobStatusChanged(JobId);
           
         DirectoryScanner::DbDir = DbDir;  
         DirectoryScanner::FsDir = FsDir;  
         if (DbDir.at(DbDir.length() - 1) != '/') {  
             DirectoryScanner::DbDir.append("/");  
         }  
         if (FsDir.at(FsDir.length() - 1) != '/') {  
             DirectoryScanner::FsDir.append("/");  
1921          }          }
         DirectoryScanner::Flat = Flat;  
           
         ftw(FsDir.c_str(), FtwCallback, 10);  
1922      }      }
1923    
     int DirectoryScanner::FtwCallback(const char* fpath, const struct stat* sb, int typeflag) {  
         dmsg(2,("DirectoryScanner: FtwCallback(fpath=%s)\n", fpath));  
         if (typeflag != FTW_D) return 0;  
   
         String dir = DbDir;  
         if (!Flat) {  
             String subdir = fpath;  
             if(subdir.length() > FsDir.length()) {  
                 subdir = subdir.substr(FsDir.length());  
                 dir += subdir;  
             }  
         }  
           
         InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();  
         if (!db->DirectoryExist(dir)) db->AddDirectory(dir);  
   
         db->AddInstrumentsNonrecursive(dir, String(fpath));  
   
         return 0;  
     };  
   
1924  } // namespace LinuxSampler  } // namespace LinuxSampler
   
 #endif // HAVE_SQLITE3  

Legend:
Removed from v.1187  
changed lines
  Added in v.1944

  ViewVC Help
Powered by ViewVC