Debian Codegraph @

src/dos/drive_cache.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2002-2010 The DOSBox Team
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 */
18
19 /* $Id: drive_cache.cpp,v 1.59 2009-04-16 12:28:30 qbix79 Exp $ */
20
21 #include "drives.h"
22 #include "dos_inc.h"
23 #include "support.h"
24 #include "cross.h"
25
26 // STL stuff
27 #include <vector>
28 #include <iterator>
29 #include <algorithm>
30
31 #if defined (WIN32) /* Win 32 */
32 #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from
33 #include <windows.h>
34 #endif
35
36 #if defined (OS2)
37 #define INCL_DOSERRORS
38 #define INCL_DOSFILEMGR
39 #include <os2.h>
40 #endif
41
42 int fileInfoCounter = 0;
43
44 bool SortByName(DOS_Drive_Cache::CFileInfo* const &a, DOS_Drive_Cache::CFileInfo* const &b) {
45 return strcmp(a->shortname,b->shortname)<0;
46 }
47
48 bool SortByNameRev(DOS_Drive_Cache::CFileInfo* const &a, DOS_Drive_Cache::CFileInfo* const &b) {
49 return strcmp(a->shortname,b->shortname)>0;
50 }
51
52 bool SortByDirName(DOS_Drive_Cache::CFileInfo* const &a, DOS_Drive_Cache::CFileInfo* const &b) {
53 // Directories first...
54 if (a->isDir!=b->isDir) return (a->isDir>b->isDir);
55 return strcmp(a->shortname,b->shortname)<0;
56 }
57
58 bool SortByDirNameRev(DOS_Drive_Cache::CFileInfo* const &a, DOS_Drive_Cache::CFileInfo* const &b) {
59 // Directories first...
60 if (a->isDir!=b->isDir) return (a->isDir>b->isDir);
61 return strcmp(a->shortname,b->shortname)>0;
62 }
63
64 DOS_Drive_Cache::DOS_Drive_Cache(void) {
65 dirBase = new CFileInfo;
66 save_dir = 0;
67 srchNr = 0;
68 label[0] = 0;
69 nextFreeFindFirst = 0;
70 for (Bit32u i=0; i<MAX_OPENDIRS; i++) { dirSearch[i] = 0; free[i] = true; dirFindFirst[i] = 0; };
71 SetDirSort(DIRALPHABETICAL);
72 updatelabel = true;
73 }
74
75 DOS_Drive_Cache::DOS_Drive_Cache(const char* path) {
76 dirBase = new CFileInfo;
77 save_dir = 0;
78 srchNr = 0;
79 label[0] = 0;
80 nextFreeFindFirst = 0;
81 for (Bit32u i=0; i<MAX_OPENDIRS; i++) { dirSearch[i] = 0; free[i] = true; dirFindFirst[i] = 0; };
82 SetDirSort(DIRALPHABETICAL);
83 SetBaseDir(path);
84 updatelabel = true;
85 }
86
87 DOS_Drive_Cache::~DOS_Drive_Cache(void) {
88 Clear();
89 for (Bit32u i=0; i<MAX_OPENDIRS; i++) { delete dirFindFirst[i]; dirFindFirst[i]=0; };
90 }
91
92 void DOS_Drive_Cache::Clear(void) {
93 delete dirBase; dirBase = 0;
94 nextFreeFindFirst = 0;
95 for (Bit32u i=0; i<MAX_OPENDIRS; i++) dirSearch[i] = 0;
96 }
97
98 void DOS_Drive_Cache::EmptyCache(void) {
99 // Empty Cache and reinit
100 Clear();
101 dirBase = new CFileInfo;
102 save_dir = 0;
103 srchNr = 0;
104 for (Bit32u i=0; i<MAX_OPENDIRS; i++) free[i] = true;
105 SetBaseDir(basePath);
106 }
107
108 void DOS_Drive_Cache::SetLabel(const char* vname,bool cdrom,bool allowupdate) {
109 /* allowupdate defaults to true. if mount sets a label then allowupdate is
110 * false and will this function return at once after the first call.
111 * The label will be set at the first call. */
112
113 if(!this->updatelabel) return;
114 this->updatelabel = allowupdate;
115 Set_Label(vname,label,cdrom);
116 LOG(LOG_DOSMISC,LOG_NORMAL)("DIRCACHE: Set volume label to %s",label);
117 }
118
119 Bit16u DOS_Drive_Cache::GetFreeID(CFileInfo* dir) {
120 for (Bit16u i=0; i<MAX_OPENDIRS; i++) if (free[i] || (dir==dirSearch[i])) return i;
121 LOG(LOG_FILES,LOG_NORMAL)("DIRCACHE: Too many open directories!");
122 return 0;
123 }
124
125 void DOS_Drive_Cache::SetBaseDir(const char* baseDir) {
126 Bit16u id;
127 strcpy(basePath,baseDir);
128 if (OpenDir(baseDir,id)) {
129 char* result = 0;
130 ReadDir(id,result);
131 };
132 // Get Volume Label
133 #if defined (WIN32) || defined (OS2)
134 bool cdrom = false;
135 char labellocal[256]={ 0 };
136 char drive[4] = "C:\\";
137 drive[0] = basePath[0];
138 #if defined (WIN32)
139 if (GetVolumeInformation(drive,labellocal,256,NULL,NULL,NULL,NULL,0)) {
140 UINT test = GetDriveType(drive);
141 if(test == DRIVE_CDROM) cdrom = true;
142 #else // OS2
143 //TODO determine wether cdrom or not!
144 FSINFO fsinfo;
145 ULONG drivenumber = drive[0];
146 if (drivenumber > 26) { // drive letter was lowercase
147 drivenumber = drive[0] - 'a' + 1;
148 }
149 APIRET rc = DosQueryFSInfo(drivenumber, FSIL_VOLSER, &fsinfo, sizeof(FSINFO));
150 if (rc == NO_ERROR) {
151 #endif
152 /* Set label and allow being updated */
153 SetLabel(labellocal,cdrom,true);
154 }
155 #endif
156 }
157
158 void DOS_Drive_Cache::ExpandName(char* path) {
159 strcpy(path,GetExpandName(path));
160 }
161
162 char* DOS_Drive_Cache::GetExpandName(const char* path) {
163 static char work [CROSS_LEN] = { 0 };
164 char dir [CROSS_LEN];
165
166 work[0] = 0;
167 strcpy (dir,path);
168
169 const char* pos = strrchr(path,CROSS_FILESPLIT);
170
171 if (pos) dir[pos-path+1] = 0;
172 CFileInfo* dirInfo = FindDirInfo(dir, work);
173
174 if (pos) {
175 // Last Entry = File
176 strcpy(dir,pos+1);
177 GetLongName(dirInfo, dir);
178 strcat(work,dir);
179 }
180
181 if (*work) {
182 size_t len = strlen(work);
183 #if defined (WIN32)
184 if((work[len-1] == CROSS_FILESPLIT ) && (len >= 2) && (work[len-2] != ':')) {
185 #else
186 if((len > 1) && (work[len-1] == CROSS_FILESPLIT )) {
187 #endif
188 work[len-1] = 0; // Remove trailing slashes except when in root
189 }
190 }
191 return work;
192 }
193
194 void DOS_Drive_Cache::AddEntry(const char* path, bool checkExists) {
195 // Get Last part...
196 char file [CROSS_LEN];
197 char expand [CROSS_LEN];
198
199 CFileInfo* dir = FindDirInfo(path,expand);
200 const char* pos = strrchr(path,CROSS_FILESPLIT);
201
202 if (pos) {
203 strcpy(file,pos+1);
204 // Check if file already exists, then don't add new entry...
205 if (checkExists) {
206 if (GetLongName(dir,file)>=0) return;
207 }
208
209 CreateEntry(dir,file,false);
210
211 Bits index = GetLongName(dir,file);
212 if (index>=0) {
213 Bit32u i;
214 // Check if there are any open search dir that are affected by this...
215 if (dir) for (i=0; i<MAX_OPENDIRS; i++) {
216 if ((dirSearch[i]==dir) && ((Bit32u)index<=dirSearch[i]->nextEntry))
217 dirSearch[i]->nextEntry++;
218 }
219 }
220 // LOG_DEBUG("DIR: Added Entry %s",path);
221 } else {
222 // LOG_DEBUG("DIR: Error: Failed to add %s",path);
223 }
224 }
225
226 void DOS_Drive_Cache::DeleteEntry(const char* path, bool ignoreLastDir) {
227 CacheOut(path,ignoreLastDir);
228 if (dirSearch[srchNr] && (dirSearch[srchNr]->nextEntry>0)) dirSearch[srchNr]->nextEntry--;
229
230 if (!ignoreLastDir) {
231 // Check if there are any open search dir that are affected by this...
232 Bit32u i;
233 char expand [CROSS_LEN];
234 CFileInfo* dir = FindDirInfo(path,expand);
235 if (dir) for (i=0; i<MAX_OPENDIRS; i++) {
236 if ((dirSearch[i]==dir) && (dirSearch[i]->nextEntry>0))
237 dirSearch[i]->nextEntry--;
238 }
239 }
240 }
241
242 void DOS_Drive_Cache::CacheOut(const char* path, bool ignoreLastDir) {
243 char expand[CROSS_LEN] = { 0 };
244 CFileInfo* dir;
245
246 if (ignoreLastDir) {
247 char tmp[CROSS_LEN] = { 0 };
248 Bit32s len=0;
249 const char* pos = strrchr(path,CROSS_FILESPLIT);
250 if (pos) len = (Bit32s)(pos - path);
251 if (len>0) {
252 safe_strncpy(tmp,path,len+1);
253 } else {
254 strcpy(tmp,path);
255 }
256 dir = FindDirInfo(tmp,expand);
257 } else {
258 dir = FindDirInfo(path,expand);
259 }
260
261 // LOG_DEBUG("DIR: Caching out %s : dir %s",expand,dir->orgname);
262 // delete file objects...
263 for(Bit32u i=0; i<dir->fileList.size(); i++) {
264 if (dirSearch[srchNr]==dir->fileList[i]) dirSearch[srchNr] = 0;
265 delete dir->fileList[i]; dir->fileList[i] = 0;
266 }
267 // clear lists
268 dir->fileList.clear();
269 dir->longNameList.clear();
270 save_dir = 0;
271 }
272
273 bool DOS_Drive_Cache::IsCachedIn(CFileInfo* curDir) {
274 return (curDir->fileList.size()>0);
275 }
276
277
278 bool DOS_Drive_Cache::GetShortName(const char* fullname, char* shortname) {
279 // Get Dir Info
280 char expand[CROSS_LEN] = {0};
281 CFileInfo* curDir = FindDirInfo(fullname,expand);
282
283 std::vector<CFileInfo*>::size_type filelist_size = curDir->longNameList.size();
284 if (GCC_UNLIKELY(filelist_size<=0)) return false;
285
286 Bits low = 0;
287 Bits high = (Bits)(filelist_size-1);
288 Bits mid, res;
289
290 while (low<=high) {
291 mid = (low+high)/2;
292 res = strcmp(fullname,curDir->longNameList[mid]->orgname);
293 if (res>0) low = mid+1; else
294 if (res<0) high = mid-1;
295 else {
296 strcpy(shortname,curDir->longNameList[mid]->shortname);
297 return true;
298 };
299 }
300 return false;
301 }
302
303 int DOS_Drive_Cache::CompareShortname(const char* compareName, const char* shortName) {
304 char const* cpos = strchr(shortName,'~');
305 if (cpos) {
306 /* the following code is replaced as it's not safe when char* is 64 bits */
307 /* Bits compareCount1 = (int)cpos - (int)shortName;
308 char* endPos = strchr(cpos,'.');
309 Bitu numberSize = endPos ? int(endPos)-int(cpos) : strlen(cpos);
310
311 char* lpos = strchr(compareName,'.');
312 Bits compareCount2 = lpos ? int(lpos)-int(compareName) : strlen(compareName);
313 if (compareCount2>8) compareCount2 = 8;
314
315 compareCount2 -= numberSize;
316 if (compareCount2>compareCount1) compareCount1 = compareCount2;
317 */
318 size_t compareCount1 = strcspn(shortName,"~");
319 size_t numberSize = strcspn(cpos,".");
320 size_t compareCount2 = strcspn(compareName,".");
321 if(compareCount2 > 8) compareCount2 = 8;
322 /* We want
323 * compareCount2 -= numberSize;
324 * if (compareCount2>compareCount1) compareCount1 = compareCount2;
325 * but to prevent negative numbers:
326 */
327 if(compareCount2 > compareCount1 + numberSize)
328 compareCount1 = compareCount2 - numberSize;
329 return strncmp(compareName,shortName,compareCount1);
330 }
331 return strcmp(compareName,shortName);
332 }
333
334 Bitu DOS_Drive_Cache::CreateShortNameID(CFileInfo* curDir, const char* name) {
335 std::vector<CFileInfo*>::size_type filelist_size = curDir->longNameList.size();
336 if (GCC_UNLIKELY(filelist_size<=0)) return 1; // shortener IDs start with 1
337
338 Bitu foundNr = 0;
339 Bits low = 0;
340 Bits high = (Bits)(filelist_size-1);
341 Bits mid, res;
342
343 while (low<=high) {
344 mid = (low+high)/2;
345 res = CompareShortname(name,curDir->longNameList[mid]->shortname);
346
347 if (res>0) low = mid+1; else
348 if (res<0) high = mid-1;
349 else {
350 // any more same x chars in next entries ?
351 do {
352 foundNr = curDir->longNameList[mid]->shortNr;
353 mid++;
354 } while((Bitu)mid<curDir->longNameList.size() && (CompareShortname(name,curDir->longNameList[mid]->shortname)==0));
355 break;
356 };
357 }
358 return foundNr+1;
359 }
360
361 bool DOS_Drive_Cache::RemoveTrailingDot(char* shortname) {
362 // remove trailing '.' if no extension is available (Linux compatibility)
363 size_t len = strlen(shortname);
364 if (len && (shortname[len-1]=='.')) {
365 if (len==1) return false;
366 if ((len==2) && (shortname[0]=='.')) return false;
367 shortname[len-1] = 0;
368 return true;
369 }
370 return false;
371 }
372
373 #define WINE_DRIVE_SUPPORT 1
374 #if WINE_DRIVE_SUPPORT
375 //Changes to interact with WINE by supporting their namemangling.
376 //The code is rather slow, because orglist is unordered, so it needs to be avoided if possible.
377 //Hence the tests in GetLongFileName
378
379
380 // From the Wine project
381 static Bits wine_hash_short_file_name( char* name, char* buffer )
382 {
383 static const char hash_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
384 static const char invalid_chars[] = { '*','?','<','>','|','"','+','=',',',';','[',']',' ','\345','~','.',0 };
385 char* p;
386 char* ext;
387 char* end = name + strlen(name);
388 char* dst;
389 unsigned short hash;
390 int i;
391
392 // Compute the hash code of the file name
393 for (p = name, hash = 0xbeef; p < end - 1; p++)
394 hash = (hash<<3) ^ (hash>>5) ^ tolower(*p) ^ (tolower(p[1]) << 8);
395 hash = (hash<<3) ^ (hash>>5) ^ tolower(*p); // Last character
396
397
398 // Find last dot for start of the extension
399 for (p = name + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
400
401 // Copy first 4 chars, replacing invalid chars with '_'
402 for (i = 4, p = name, dst = buffer; i > 0; i--, p++)
403 {
404 if (p == end || p == ext) break;
405 *dst++ = (*p < 0 || strchr( invalid_chars, *p ) != NULL) ? '_' : toupper(*p);
406 }
407 // Pad to 5 chars with '~'
408 while (i-- >= 0) *dst++ = '~';
409
410 // Insert hash code converted to 3 ASCII chars
411 *dst++ = hash_chars[(hash >> 10) & 0x1f];
412 *dst++ = hash_chars[(hash >> 5) & 0x1f];
413 *dst++ = hash_chars[hash & 0x1f];
414
415 // Copy the first 3 chars of the extension (if any)
416 if (ext)
417 {
418 *dst++ = '.';
419 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
420 *dst++ = (*ext < 0 || strchr( invalid_chars, *ext ) != NULL) ? '_' : toupper(*ext);
421 }
422
423 return dst - buffer;
424 }
425 #endif
426
427 Bits DOS_Drive_Cache::GetLongName(CFileInfo* curDir, char* shortName) {
428 std::vector<CFileInfo*>::size_type filelist_size = curDir->fileList.size();
429 if (GCC_UNLIKELY(filelist_size<=0)) return -1;
430
431 // Remove dot, if no extension...
432 RemoveTrailingDot(shortName);
433 // Search long name and return array number of element
434 Bits low = 0;
435 Bits high = (Bits)(filelist_size-1);
436 Bits mid,res;
437 while (low<=high) {
438 mid = (low+high)/2;
439 res = strcmp(shortName,curDir->fileList[mid]->shortname);
440 if (res>0) low = mid+1; else
441 if (res<0) high = mid-1; else
442 { // Found
443 strcpy(shortName,curDir->fileList[mid]->orgname);
444 return mid;
445 };
446 }
447 #ifdef WINE_DRIVE_SUPPORT
448 if (strlen(shortName) < 8 || shortName[4] != '~' || shortName[5] == '.' || shortName[6] == '.' || shortName[7] == '.') return -1; // not available
449 // else it's most likely a Wine style short name ABCD~###, # = not dot (length at least 8)
450 // The above test is rather strict as the following loop can be really slow if filelist_size is large.
451 char buff[CROSS_LEN];
452 for (Bits i = 0; i < filelist_size; i++) {
453 res = wine_hash_short_file_name(curDir->fileList[i]->orgname,buff);
454 buff[res] = 0;
455 if (!strcmp(shortName,buff)) {
456 // Found
457 strcpy(shortName,curDir->fileList[i]->orgname);
458 return i;
459 }
460 }
461 #endif
462 // not available
463 return -1;
464 }
465
466 bool DOS_Drive_Cache::RemoveSpaces(char* str) {
467 // Removes all spaces
468 char* curpos = str;
469 char* chkpos = str;
470 while (*chkpos!=0) {
471 if (*chkpos==' ') chkpos++; else *curpos++ = *chkpos++;
472 }
473 *curpos = 0;
474 return (curpos!=chkpos);
475 }
476
477 void DOS_Drive_Cache::CreateShortName(CFileInfo* curDir, CFileInfo* info) {
478 Bits len = 0;
479 bool createShort = false;
480
481 char tmpNameBuffer[CROSS_LEN];
482
483 char* tmpName = tmpNameBuffer;
484
485 // Remove Spaces
486 strcpy(tmpName,info->orgname);
487 upcase(tmpName);
488 createShort = RemoveSpaces(tmpName);
489
490 // Get Length of filename
491 char* pos = strchr(tmpName,'.');
492 if (pos) {
493 // ignore preceding '.' if extension is longer than "3"
494 if (strlen(pos)>4) {
495 while (*tmpName=='.') tmpName++;
496 createShort = true;
497 }
498 pos = strchr(tmpName,'.');
499 if (pos) len = (Bits)(pos - tmpName);
500 else len = (Bits)strlen(tmpName);
501 } else {
502 len = (Bits)strlen(tmpName);
503 }
504
505 // Should shortname version be created ?
506 createShort = createShort || (len>8);
507 if (!createShort) {
508 char buffer[CROSS_LEN];
509 strcpy(buffer,tmpName);
510 createShort = (GetLongName(curDir,buffer)>=0);
511 }
512
513 if (createShort) {
514 // Create number
515 char buffer[8];
516 info->shortNr = CreateShortNameID(curDir,tmpName);
517 sprintf(buffer,"%d",info->shortNr);
518 // Copy first letters
519 Bits tocopy = 0;
520 size_t buflen = strlen(buffer);
521 if (len+buflen+1>8) tocopy = (Bits)(8 - buflen - 1);
522 else tocopy = len;
523 safe_strncpy(info->shortname,tmpName,tocopy+1);
524 // Copy number
525 strcat(info->shortname,"~");
526 strcat(info->shortname,buffer);
527 // Add (and cut) Extension, if available
528 if (pos) {
529 // Step to last extension...
530 pos = strrchr(tmpName, '.');
531 // add extension
532 strncat(info->shortname,pos,4);
533 info->shortname[DOS_NAMELENGTH] = 0;
534 }
535
536 // keep list sorted for CreateShortNameID to work correctly
537 if (curDir->longNameList.size()>0) {
538 if (!(strcmp(info->shortname,curDir->longNameList.back()->shortname)<0)) {
539 // append at end of list
540 curDir->longNameList.push_back(info);
541 } else {
542 // look for position where to insert this element
543 bool found=false;
544 std::vector<CFileInfo*>::iterator it;
545 for (it=curDir->longNameList.begin(); it!=curDir->longNameList.end(); ++it) {
546 if (strcmp(info->shortname,(*it)->shortname)<0) {
547 found = true;
548 break;
549 }
550 }
551 // Put it in longname list...
552 if (found) curDir->longNameList.insert(it,info);
553 else curDir->longNameList.push_back(info);
554 }
555 } else {
556 // empty file list, append
557 curDir->longNameList.push_back(info);
558 }
559 } else {
560 strcpy(info->shortname,tmpName);
561 }
562 RemoveTrailingDot(info->shortname);
563 }
564
565 DOS_Drive_Cache::CFileInfo* DOS_Drive_Cache::FindDirInfo(const char* path, char* expandedPath) {
566 // statics
567 static char split[2] = { CROSS_FILESPLIT,0 };
568
569 char dir [CROSS_LEN];
570 char work [CROSS_LEN];
571 const char* start = path;
572 const char* pos;
573 CFileInfo* curDir = dirBase;
574 Bit16u id;
575
576 if (save_dir && (strcmp(path,save_path)==0)) {
577 strcpy(expandedPath,save_expanded);
578 return save_dir;
579 };
580
581 // LOG_DEBUG("DIR: Find %s",path);
582
583 // Remove base dir path
584 start += strlen(basePath);
585 strcpy(expandedPath,basePath);
586
587 // hehe, baseDir should be cached in...
588 if (!IsCachedIn(curDir)) {
589 strcpy(work,basePath);
590 if (OpenDir(curDir,work,id)) {
591 char buffer[CROSS_LEN];
592 char* result = 0;
593 strcpy(buffer,dirPath);
594 ReadDir(id,result);
595 strcpy(dirPath,buffer);
596 free[id] = true;
597 };
598 };
599
600 do {
601 // bool errorcheck = false;
602 pos = strchr(start,CROSS_FILESPLIT);
603 if (pos) { safe_strncpy(dir,start,pos-start+1); /*errorcheck = true;*/ }
604 else { strcpy(dir,start); };
605
606 // Path found
607 Bits nextDir = GetLongName(curDir,dir);
608 strcat(expandedPath,dir);
609
610 // Error check
611 /* if ((errorcheck) && (nextDir<0)) {
612 LOG_DEBUG("DIR: Error: %s not found.",expandedPath);
613 };
614 */
615 // Follow Directory
616 if ((nextDir>=0) && curDir->fileList[nextDir]->isDir) {
617 curDir = curDir->fileList[nextDir];
618 strcpy (curDir->orgname,dir);
619 if (!IsCachedIn(curDir)) {
620 if (OpenDir(curDir,expandedPath,id)) {
621 char buffer[CROSS_LEN];
622 char* result = 0;
623 strcpy(buffer,dirPath);
624 ReadDir(id,result);
625 strcpy(dirPath,buffer);
626 free[id] = true;
627 };
628 }
629 };
630 if (pos) {
631 strcat(expandedPath,split);
632 start = pos+1;
633 }
634 } while (pos);
635
636 // Save last result for faster access next time
637 strcpy(save_path,path);
638 strcpy(save_expanded,expandedPath);
639 save_dir = curDir;
640
641 return curDir;
642 }
643
644 bool DOS_Drive_Cache::OpenDir(const char* path, Bit16u& id) {
645 char expand[CROSS_LEN] = {0};
646 CFileInfo* dir = FindDirInfo(path,expand);
647 if (OpenDir(dir,expand,id)) {
648 dirSearch[id]->nextEntry = 0;
649 return true;
650 }
651 return false;
652 }
653
654 bool DOS_Drive_Cache::OpenDir(CFileInfo* dir, const char* expand, Bit16u& id) {
655 id = GetFreeID(dir);
656 dirSearch[id] = dir;
657 char expandcopy [CROSS_LEN];
658 strcpy(expandcopy,expand);
659 // Add "/"
660 char end[2]={CROSS_FILESPLIT,0};
661 if (expandcopy[strlen(expandcopy)-1]!=CROSS_FILESPLIT) strcat(expandcopy,end);
662 // open dir
663 if (dirSearch[id]) {
664 // open dir
665 dir_information* dirp = open_directory(expandcopy);
666 if (dirp) {
667 // Reset it..
668 close_directory(dirp);
669 strcpy(dirPath,expandcopy);
670 free[id] = false;
671 return true;
672 }
673 };
674 return false;
675 }
676
677 void DOS_Drive_Cache::CreateEntry(CFileInfo* dir, const char* name, bool is_directory) {
678 CFileInfo* info = new CFileInfo;
679 strcpy(info->orgname, name);
680 info->shortNr = 0;
681 info->isDir = is_directory;
682
683 // Check for long filenames...
684 CreateShortName(dir, info);
685
686 bool found = false;
687
688 // keep list sorted (so GetLongName works correctly, used by CreateShortName in this routine)
689 if (dir->fileList.size()>0) {
690 if (!(strcmp(info->shortname,dir->fileList.back()->shortname)<0)) {
691 // append at end of list
692 dir->fileList.push_back(info);
693 } else {
694 // look for position where to insert this element
695 std::vector<CFileInfo*>::iterator it;
696 for (it=dir->fileList.begin(); it!=dir->fileList.end(); ++it) {
697 if (strcmp(info->shortname,(*it)->shortname)<0) {
698 found = true;
699 break;
700 }
701 }
702 // Put file in lists
703 if (found) dir->fileList.insert(it,info);
704 else dir->fileList.push_back(info);
705 }
706 } else {
707 // empty file list, append
708 dir->fileList.push_back(info);
709 }
710 }
711
712 void DOS_Drive_Cache::CopyEntry(CFileInfo* dir, CFileInfo* from) {
713 CFileInfo* info = new CFileInfo;
714 // just copy things into new fileinfo
715 strcpy(info->orgname, from->orgname);
716 strcpy(info->shortname, from->shortname);
717 info->shortNr = from->shortNr;
718 info->isDir = from->isDir;
719
720 dir->fileList.push_back(info);
721 }
722
723 bool DOS_Drive_Cache::ReadDir(Bit16u id, char* &result) {
724 // shouldnt happen...
725 if (id>MAX_OPENDIRS) return false;
726
727 if (!IsCachedIn(dirSearch[id])) {
728 // Try to open directory
729 dir_information* dirp = open_directory(dirPath);
730 if (!dirp) {
731 free[id] = true;
732 return false;
733 }
734 // Read complete directory
735 char dir_name[CROSS_LEN];
736 bool is_directory;
737 if (read_directory_first(dirp, dir_name, is_directory)) {
738 CreateEntry(dirSearch[id], dir_name, is_directory);
739 while (read_directory_next(dirp, dir_name, is_directory)) {
740 CreateEntry(dirSearch[id], dir_name, is_directory);
741 }
742 }
743
744 // close dir
745 close_directory(dirp);
746
747 // Info
748 /* if (!dirp) {
749 LOG_DEBUG("DIR: Error Caching in %s",dirPath);
750 return false;
751 } else {
752 char buffer[128];
753 sprintf(buffer,"DIR: Caching in %s (%d Files)",dirPath,dirSearch[srchNr]->fileList.size());
754 LOG_DEBUG(buffer);
755 };*/
756 };
757 if (SetResult(dirSearch[id], result, dirSearch[id]->nextEntry)) return true;
758 free[id] = true;
759 return false;
760 }
761
762 bool DOS_Drive_Cache::SetResult(CFileInfo* dir, char* &result, Bitu entryNr)
763 {
764 static char res[CROSS_LEN] = { 0 };
765
766 result = res;
767 if (entryNr>=dir->fileList.size()) return false;
768 CFileInfo* info = dir->fileList[entryNr];
769 // copy filename, short version
770 strcpy(res,info->shortname);
771 // Set to next Entry
772 dir->nextEntry = entryNr+1;
773 return true;
774 }
775
776 // FindFirst / FindNext
777 bool DOS_Drive_Cache::FindFirst(char* path, Bit16u& id) {
778 Bit16u dirID;
779 // Cache directory in
780 if (!OpenDir(path,dirID)) return false;
781
782 //Find a free slot.
783 //If the next one isn't free, move on to the next, if none is free => reset and assume the worst
784 Bit16u local_findcounter = 0;
785 while ( local_findcounter < MAX_OPENDIRS ) {
786 if (dirFindFirst[this->nextFreeFindFirst] == 0) break;
787 if (++this->nextFreeFindFirst >= MAX_OPENDIRS) this->nextFreeFindFirst = 0; //Wrap around
788 local_findcounter++;
789 }
790
791 Bit16u dirFindFirstID = this->nextFreeFindFirst++;
792 if (this->nextFreeFindFirst >= MAX_OPENDIRS) this->nextFreeFindFirst = 0; //Increase and wrap around for the next search.
793
794 if (local_findcounter == MAX_OPENDIRS) { //Here is the reset from above.
795 // no free slot found...
796 LOG(LOG_MISC,LOG_ERROR)("DIRCACHE: FindFirst/Next: All slots full. Resetting");
797 // Clear the internal list then.
798 dirFindFirstID = 0;
799 this->nextFreeFindFirst = 1; //the next free one after this search
800 for(Bitu n=0; n<MAX_OPENDIRS;n++) {
801 // Clear and reuse slot
802 delete dirFindFirst[n];
803 dirFindFirst[n]=0;
804 }
805
806 }
807 dirFindFirst[dirFindFirstID] = new CFileInfo();
808 dirFindFirst[dirFindFirstID]-> nextEntry = 0;
809
810 // Copy entries to use with FindNext
811 for (Bitu i=0; i<dirSearch[dirID]->fileList.size(); i++) {
812 CopyEntry(dirFindFirst[dirFindFirstID],dirSearch[dirID]->fileList[i]);
813 }
814 // Now re-sort the fileList accordingly to output
815 switch (sortDirType) {
816 case ALPHABETICAL : break;
817 // case ALPHABETICAL : std::sort(dirFindFirst[dirFindFirstID]->fileList.begin(), dirFindFirst[dirFindFirstID]->fileList.end(), SortByName); break;
818 case DIRALPHABETICAL : std::sort(dirFindFirst[dirFindFirstID]->fileList.begin(), dirFindFirst[dirFindFirstID]->fileList.end(), SortByDirName); break;
819 case ALPHABETICALREV : std::sort(dirFindFirst[dirFindFirstID]->fileList.begin(), dirFindFirst[dirFindFirstID]->fileList.end(), SortByNameRev); break;
820 case DIRALPHABETICALREV : std::sort(dirFindFirst[dirFindFirstID]->fileList.begin(), dirFindFirst[dirFindFirstID]->fileList.end(), SortByDirNameRev); break;
821 case NOSORT : break;
822 }
823
824 // LOG(LOG_MISC,LOG_ERROR)("DIRCACHE: FindFirst : %s (ID:%02X)",path,dirFindFirstID);
825 id = dirFindFirstID;
826 return true;
827 }
828
829 bool DOS_Drive_Cache::FindNext(Bit16u id, char* &result) {
830 // out of range ?
831 if ((id>=MAX_OPENDIRS) || !dirFindFirst[id]) {
832 LOG(LOG_MISC,LOG_ERROR)("DIRCACHE: FindFirst/Next failure : ID out of range: %04X",id);
833 return false;
834 }
835 if (!SetResult(dirFindFirst[id], result, dirFindFirst[id]->nextEntry)) {
836 // free slot
837 delete dirFindFirst[id]; dirFindFirst[id] = 0;
838 return false;
839 }
840 return true;
841 }