po: A couple of line wrapping tweaks in the Czech translation.
[wine/multimedia.git] / programs / cmd / directory.c
blob52b998c3b9f2a1cc1bfadc769bbe2b7f2626982e
1 /*
2 * CMD - Wine-compatible command line interface - Directory functions.
4 * Copyright (C) 1999 D A Pickles
5 * Copyright (C) 2007 J Edmeades
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #define WIN32_LEAN_AND_MEAN
24 #include "wcmd.h"
25 #include "wine/debug.h"
27 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
29 typedef enum _DISPLAYTIME
31 Creation = 0,
32 Access,
33 Written
34 } DISPLAYTIME;
36 typedef enum _DISPLAYORDER
38 Name = 0,
39 Extension,
40 Size,
41 Date
42 } DISPLAYORDER;
44 static int file_total, dir_total, max_width;
45 static ULONGLONG byte_total;
46 static DISPLAYTIME dirTime;
47 static DISPLAYORDER dirOrder;
48 static BOOL orderReverse, orderGroupDirs, orderGroupDirsReverse, orderByCol;
49 static BOOL paged_mode, recurse, wide, bare, lower, shortname, usernames, separator;
50 static ULONG showattrs, attrsbits;
52 /*****************************************************************************
53 * WCMD_strrev
55 * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
57 static WCHAR * WCMD_strrev (WCHAR *buff) {
59 int r, i;
60 WCHAR b;
62 r = strlenW (buff);
63 for (i=0; i<r/2; i++) {
64 b = buff[i];
65 buff[i] = buff[r-i-1];
66 buff[r-i-1] = b;
68 return (buff);
71 /*****************************************************************************
72 * WCMD_filesize64
74 * Convert a 64-bit number into a WCHARacter string, with commas every three digits.
75 * Result is returned in a static string overwritten with each call.
76 * FIXME: There must be a better algorithm!
78 static WCHAR * WCMD_filesize64 (ULONGLONG n) {
80 ULONGLONG q;
81 unsigned int r, i;
82 WCHAR *p;
83 static WCHAR buff[32];
85 p = buff;
86 i = -3;
87 do {
88 if (separator && ((++i)%3 == 1)) *p++ = ',';
89 q = n / 10;
90 r = n - (q * 10);
91 *p++ = r + '0';
92 *p = '\0';
93 n = q;
94 } while (n != 0);
95 WCMD_strrev (buff);
96 return buff;
99 /*****************************************************************************
100 * WCMD_dir_sort
102 * Sort based on the /O options supplied on the command line
104 static int WCMD_dir_sort (const void *a, const void *b)
106 const WIN32_FIND_DATAW *filea = (const WIN32_FIND_DATAW *)a;
107 const WIN32_FIND_DATAW *fileb = (const WIN32_FIND_DATAW *)b;
108 int result = 0;
110 /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
111 requested sort order for the directory components */
112 if (orderGroupDirs &&
113 ((filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
114 (fileb->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
116 BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
117 if (aDir) result = -1;
118 else result = 1;
119 if (orderGroupDirsReverse) result = -result;
120 return result;
122 /* Order by Name: */
123 } else if (dirOrder == Name) {
124 result = lstrcmpiW(filea->cFileName, fileb->cFileName);
126 /* Order by Size: */
127 } else if (dirOrder == Size) {
128 ULONG64 sizea = (((ULONG64)filea->nFileSizeHigh) << 32) + filea->nFileSizeLow;
129 ULONG64 sizeb = (((ULONG64)fileb->nFileSizeHigh) << 32) + fileb->nFileSizeLow;
130 if( sizea < sizeb ) result = -1;
131 else if( sizea == sizeb ) result = 0;
132 else result = 1;
134 /* Order by Date: (Takes into account which date (/T option) */
135 } else if (dirOrder == Date) {
137 const FILETIME *ft;
138 ULONG64 timea, timeb;
140 if (dirTime == Written) {
141 ft = &filea->ftLastWriteTime;
142 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
143 ft = &fileb->ftLastWriteTime;
144 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
145 } else if (dirTime == Access) {
146 ft = &filea->ftLastAccessTime;
147 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
148 ft = &fileb->ftLastAccessTime;
149 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
150 } else {
151 ft = &filea->ftCreationTime;
152 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
153 ft = &fileb->ftCreationTime;
154 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
156 if( timea < timeb ) result = -1;
157 else if( timea == timeb ) result = 0;
158 else result = 1;
160 /* Order by Extension: (Takes into account which date (/T option) */
161 } else if (dirOrder == Extension) {
162 WCHAR drive[10];
163 WCHAR dir[MAX_PATH];
164 WCHAR fname[MAX_PATH];
165 WCHAR extA[MAX_PATH];
166 WCHAR extB[MAX_PATH];
168 /* Split into components */
169 WCMD_splitpath(filea->cFileName, drive, dir, fname, extA);
170 WCMD_splitpath(fileb->cFileName, drive, dir, fname, extB);
171 result = lstrcmpiW(extA, extB);
174 if (orderReverse) result = -result;
175 return result;
178 /*****************************************************************************
179 * WCMD_getfileowner
181 * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
183 static void WCMD_getfileowner(WCHAR *filename, WCHAR *owner, int ownerlen) {
185 ULONG sizeNeeded = 0;
186 DWORD rc;
187 WCHAR name[MAXSTRING];
188 WCHAR domain[MAXSTRING];
190 /* In case of error, return empty string */
191 *owner = 0x00;
193 /* Find out how much space we need for the owner security descriptor */
194 GetFileSecurityW(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
195 rc = GetLastError();
197 if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
199 LPBYTE secBuffer;
200 PSID pSID = NULL;
201 BOOL defaulted = FALSE;
202 ULONG nameLen = MAXSTRING;
203 ULONG domainLen = MAXSTRING;
204 SID_NAME_USE nameuse;
206 secBuffer = HeapAlloc(GetProcessHeap(),0,sizeNeeded * sizeof(BYTE));
207 if(!secBuffer) return;
209 /* Get the owners security descriptor */
210 if(!GetFileSecurityW(filename, OWNER_SECURITY_INFORMATION, secBuffer,
211 sizeNeeded, &sizeNeeded)) {
212 HeapFree(GetProcessHeap(),0,secBuffer);
213 return;
216 /* Get the SID from the SD */
217 if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
218 HeapFree(GetProcessHeap(),0,secBuffer);
219 return;
222 /* Convert to a username */
223 if (LookupAccountSidW(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
224 static const WCHAR fmt[] = {'%','s','%','c','%','s','\0'};
225 snprintfW(owner, ownerlen, fmt, domain, '\\', name);
227 HeapFree(GetProcessHeap(),0,secBuffer);
229 return;
232 /*****************************************************************************
233 * WCMD_list_directory
235 * List a single file directory. This function (and those below it) can be called
236 * recursively when the /S switch is used.
238 * FIXME: Assumes 24-line display for the /P qualifier.
241 static DIRECTORY_STACK *WCMD_list_directory (DIRECTORY_STACK *inputparms, int level) {
243 WCHAR string[1024], datestring[32], timestring[32];
244 WCHAR real_path[MAX_PATH];
245 WIN32_FIND_DATAW *fd;
246 FILETIME ft;
247 SYSTEMTIME st;
248 HANDLE hff;
249 int dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
250 int numCols, numRows;
251 int rows, cols;
252 ULARGE_INTEGER byte_count, file_size;
253 DIRECTORY_STACK *parms;
254 int concurrentDirs = 0;
255 BOOL done_header = FALSE;
257 static const WCHAR fmtDir[] = {'%','1','!','1','0','s','!',' ',' ','%','2','!','8','s','!',' ',' ',
258 '<','D','I','R','>',' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
259 static const WCHAR fmtFile[] = {'%','1','!','1','0','s','!',' ',' ','%','2','!','8','s','!',' ',' ',
260 ' ',' ','%','3','!','1','0','s','!',' ',' ','\0'};
261 static const WCHAR fmt2[] = {'%','1','!','-','1','3','s','!','\0'};
262 static const WCHAR fmt3[] = {'%','1','!','-','2','3','s','!','\0'};
263 static const WCHAR fmt4[] = {'%','1','\0'};
264 static const WCHAR fmt5[] = {'%','1','%','2','\0'};
266 dir_count = 0;
267 file_count = 0;
268 entry_count = 0;
269 byte_count.QuadPart = 0;
270 widest = 0;
271 cur_width = 0;
273 /* Loop merging all the files from consecutive parms which relate to the
274 same directory. Note issuing a directory header with no contents
275 mirrors what windows does */
276 parms = inputparms;
277 fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATAW));
278 while (parms && strcmpW(inputparms->dirName, parms->dirName) == 0) {
279 concurrentDirs++;
281 /* Work out the full path + filename */
282 strcpyW(real_path, parms->dirName);
283 strcatW(real_path, parms->fileName);
285 /* Load all files into an in memory structure */
286 WINE_TRACE("Looking for matches to '%s'\n", wine_dbgstr_w(real_path));
287 hff = FindFirstFileW(real_path, (fd+entry_count));
288 if (hff != INVALID_HANDLE_VALUE) {
289 do {
290 /* Skip any which are filtered out by attribute */
291 if (((fd+entry_count)->dwFileAttributes & attrsbits) != showattrs) continue;
293 entry_count++;
295 /* Keep running track of longest filename for wide output */
296 if (wide || orderByCol) {
297 int tmpLen = strlenW((fd+(entry_count-1))->cFileName) + 3;
298 if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
299 if (tmpLen > widest) widest = tmpLen;
302 fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATAW));
303 if (fd == NULL) {
304 FindClose (hff);
305 WINE_ERR("Out of memory\n");
306 errorlevel = 1;
307 return parms->next;
309 } while (FindNextFileW(hff, (fd+entry_count)) != 0);
310 FindClose (hff);
313 /* Work out the actual current directory name without a trailing \ */
314 strcpyW(real_path, parms->dirName);
315 real_path[strlenW(parms->dirName)-1] = 0x00;
317 /* Output the results */
318 if (!bare) {
319 if (level != 0 && (entry_count > 0)) WCMD_output_asis (newlineW);
320 if (!recurse || ((entry_count > 0) && done_header==FALSE)) {
321 static const WCHAR headerW[] = {'D','i','r','e','c','t','o','r','y',' ','o','f',
322 ' ','%','1','\n','\n','\0'};
323 WCMD_output (headerW, real_path);
324 done_header = TRUE;
328 /* Move to next parm */
329 parms = parms->next;
332 /* Handle case where everything is filtered out */
333 if (entry_count > 0) {
335 /* Sort the list of files */
336 qsort (fd, entry_count, sizeof(WIN32_FIND_DATAW), WCMD_dir_sort);
338 /* Work out the number of columns */
339 WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
340 if (wide || orderByCol) {
341 numCols = max(1, (int)max_width / widest);
342 numRows = entry_count / numCols;
343 if (entry_count % numCols) numRows++;
344 } else {
345 numCols = 1;
346 numRows = entry_count;
348 WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
350 for (rows=0; rows<numRows; rows++) {
351 BOOL addNewLine = TRUE;
352 for (cols=0; cols<numCols; cols++) {
353 WCHAR username[24];
355 /* Work out the index of the entry being pointed to */
356 if (orderByCol) {
357 i = (cols * numRows) + rows;
358 if (i >= entry_count) continue;
359 } else {
360 i = (rows * numCols) + cols;
361 if (i >= entry_count) continue;
364 /* /L convers all names to lower case */
365 if (lower) {
366 WCHAR *p = (fd+i)->cFileName;
367 while ( (*p = tolower(*p)) ) ++p;
370 /* /Q gets file ownership information */
371 if (usernames) {
372 strcpyW (string, inputparms->dirName);
373 strcatW (string, (fd+i)->cFileName);
374 WCMD_getfileowner(string, username, sizeof(username)/sizeof(WCHAR));
377 if (dirTime == Written) {
378 FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
379 } else if (dirTime == Access) {
380 FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
381 } else {
382 FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
384 FileTimeToSystemTime (&ft, &st);
385 GetDateFormatW(0, DATE_SHORTDATE, &st, NULL, datestring,
386 sizeof(datestring)/sizeof(WCHAR));
387 GetTimeFormatW(0, TIME_NOSECONDS, &st,
388 NULL, timestring, sizeof(timestring)/sizeof(WCHAR));
390 if (wide) {
392 tmp_width = cur_width;
393 if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
394 static const WCHAR fmt[] = {'[','%','1',']','\0'};
395 WCMD_output (fmt, (fd+i)->cFileName);
396 dir_count++;
397 tmp_width = tmp_width + strlenW((fd+i)->cFileName) + 2;
398 } else {
399 static const WCHAR fmt[] = {'%','1','\0'};
400 WCMD_output (fmt, (fd+i)->cFileName);
401 tmp_width = tmp_width + strlenW((fd+i)->cFileName) ;
402 file_count++;
403 file_size.u.LowPart = (fd+i)->nFileSizeLow;
404 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
405 byte_count.QuadPart += file_size.QuadPart;
407 cur_width = cur_width + widest;
409 if ((cur_width + widest) > max_width) {
410 cur_width = 0;
411 } else {
412 static const WCHAR padfmt[] = {'%','1','!','*','s','!','\0'};
413 WCMD_output(padfmt, cur_width - tmp_width, nullW);
416 } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
417 dir_count++;
419 if (!bare) {
420 WCMD_output (fmtDir, datestring, timestring);
421 if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
422 if (usernames) WCMD_output (fmt3, username);
423 WCMD_output(fmt4,(fd+i)->cFileName);
424 } else {
425 if (!((strcmpW((fd+i)->cFileName, dotW) == 0) ||
426 (strcmpW((fd+i)->cFileName, dotdotW) == 0))) {
427 WCMD_output (fmt5, recurse?inputparms->dirName:nullW, (fd+i)->cFileName);
428 } else {
429 addNewLine = FALSE;
433 else {
434 file_count++;
435 file_size.u.LowPart = (fd+i)->nFileSizeLow;
436 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
437 byte_count.QuadPart += file_size.QuadPart;
438 if (!bare) {
439 WCMD_output (fmtFile, datestring, timestring,
440 WCMD_filesize64(file_size.QuadPart));
441 if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
442 if (usernames) WCMD_output (fmt3, username);
443 WCMD_output(fmt4,(fd+i)->cFileName);
444 } else {
445 WCMD_output (fmt5, recurse?inputparms->dirName:nullW, (fd+i)->cFileName);
449 if (addNewLine) WCMD_output_asis (newlineW);
450 cur_width = 0;
453 if (!bare) {
454 if (file_count == 1) {
455 static const WCHAR fmt[] = {' ',' ',' ',' ',' ',' ',' ','1',' ','f','i','l','e',' ',
456 '%','1','!','2','5','s','!',' ','b','y','t','e','s','\n','\0'};
457 WCMD_output (fmt, WCMD_filesize64 (byte_count.QuadPart));
459 else {
460 static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','f','i','l','e','s',' ','%','2','!','2','4','s','!',
461 ' ','b','y','t','e','s','\n','\0'};
462 WCMD_output (fmt, file_count, WCMD_filesize64 (byte_count.QuadPart));
465 byte_total = byte_total + byte_count.QuadPart;
466 file_total = file_total + file_count;
467 dir_total = dir_total + dir_count;
469 if (!bare && !recurse) {
470 if (dir_count == 1) {
471 static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','y',
472 ' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
473 WCMD_output (fmt, 1);
474 } else {
475 static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','i',
476 'e','s','\0'};
477 WCMD_output (fmt, dir_count);
481 HeapFree(GetProcessHeap(),0,fd);
483 /* When recursing, look in all subdirectories for matches */
484 if (recurse) {
485 DIRECTORY_STACK *dirStack = NULL;
486 DIRECTORY_STACK *lastEntry = NULL;
487 WIN32_FIND_DATAW finddata;
489 /* Build path to search */
490 strcpyW(string, inputparms->dirName);
491 strcatW(string, starW);
493 WINE_TRACE("Recursive, looking for '%s'\n", wine_dbgstr_w(string));
494 hff = FindFirstFileW(string, &finddata);
495 if (hff != INVALID_HANDLE_VALUE) {
496 do {
497 if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
498 (strcmpW(finddata.cFileName, dotdotW) != 0) &&
499 (strcmpW(finddata.cFileName, dotW) != 0)) {
501 DIRECTORY_STACK *thisDir;
502 int dirsToCopy = concurrentDirs;
504 /* Loop creating list of subdirs for all concurrent entries */
505 parms = inputparms;
506 while (dirsToCopy > 0) {
507 dirsToCopy--;
509 /* Work out search parameter in sub dir */
510 strcpyW (string, inputparms->dirName);
511 strcatW (string, finddata.cFileName);
512 strcatW (string, slashW);
513 WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(string));
515 /* Allocate memory, add to list */
516 thisDir = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
517 if (dirStack == NULL) dirStack = thisDir;
518 if (lastEntry != NULL) lastEntry->next = thisDir;
519 lastEntry = thisDir;
520 thisDir->next = NULL;
521 thisDir->dirName = HeapAlloc(GetProcessHeap(),0,
522 sizeof(WCHAR) * (strlenW(string)+1));
523 strcpyW(thisDir->dirName, string);
524 thisDir->fileName = HeapAlloc(GetProcessHeap(),0,
525 sizeof(WCHAR) * (strlenW(parms->fileName)+1));
526 strcpyW(thisDir->fileName, parms->fileName);
527 parms = parms->next;
530 } while (FindNextFileW(hff, &finddata) != 0);
531 FindClose (hff);
533 while (dirStack != NULL) {
534 DIRECTORY_STACK *thisDir = dirStack;
535 dirStack = WCMD_list_directory (thisDir, 1);
536 while (thisDir != dirStack) {
537 DIRECTORY_STACK *tempDir = thisDir->next;
538 HeapFree(GetProcessHeap(),0,thisDir->dirName);
539 HeapFree(GetProcessHeap(),0,thisDir->fileName);
540 HeapFree(GetProcessHeap(),0,thisDir);
541 thisDir = tempDir;
547 /* Handle case where everything is filtered out */
548 if ((file_total + dir_total == 0) && (level == 0)) {
549 SetLastError (ERROR_FILE_NOT_FOUND);
550 WCMD_print_error ();
551 errorlevel = 1;
554 return parms;
557 /*****************************************************************************
558 * WCMD_dir_trailer
560 * Print out the trailer for the supplied drive letter
562 static void WCMD_dir_trailer(WCHAR drive) {
563 ULARGE_INTEGER avail, total, freebytes;
564 DWORD status;
565 WCHAR driveName[] = {'c',':','\\','\0'};
567 driveName[0] = drive;
568 status = GetDiskFreeSpaceExW(driveName, &avail, &total, &freebytes);
569 WINE_TRACE("Writing trailer for '%s' gave %d(%d)\n", wine_dbgstr_w(driveName),
570 status, GetLastError());
572 if (errorlevel==0 && !bare) {
573 if (recurse) {
574 static const WCHAR fmt1[] = {'\n',' ',' ',' ',' ',' ','T','o','t','a','l',' ','f','i','l','e','s',
575 ' ','l','i','s','t','e','d',':','\n','%','1','!','8','d','!',' ','f','i','l','e',
576 's','%','2','!','2','5','s','!',' ','b','y','t','e','s','\n','\0'};
577 static const WCHAR fmt2[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','i','e','s',' ','%',
578 '2','!','1','8','s','!',' ','b','y','t','e','s',' ','f','r','e','e','\n','\n',
579 '\0'};
580 WCMD_output (fmt1, file_total, WCMD_filesize64 (byte_total));
581 WCMD_output (fmt2, dir_total, WCMD_filesize64 (freebytes.QuadPart));
582 } else {
583 static const WCHAR fmt[] = {' ','%','1','!','1','8','s','!',' ','b','y','t','e','s',' ','f','r','e','e',
584 '\n','\n','\0'};
585 WCMD_output (fmt, WCMD_filesize64 (freebytes.QuadPart));
590 /*****************************************************************************
591 * WCMD_directory
593 * List a file directory.
597 void WCMD_directory (WCHAR *cmd)
599 WCHAR path[MAX_PATH], cwd[MAX_PATH];
600 DWORD status;
601 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
602 WCHAR *p;
603 WCHAR string[MAXSTRING];
604 int argno = 0;
605 WCHAR *argN = cmd;
606 WCHAR lastDrive;
607 BOOL trailerReqd = FALSE;
608 DIRECTORY_STACK *fullParms = NULL;
609 DIRECTORY_STACK *prevEntry = NULL;
610 DIRECTORY_STACK *thisEntry = NULL;
611 WCHAR drive[10];
612 WCHAR dir[MAX_PATH];
613 WCHAR fname[MAX_PATH];
614 WCHAR ext[MAX_PATH];
615 static const WCHAR dircmdW[] = {'D','I','R','C','M','D','\0'};
617 errorlevel = 0;
619 /* Prefill quals with (uppercased) DIRCMD env var */
620 if (GetEnvironmentVariableW(dircmdW, string, sizeof(string)/sizeof(WCHAR))) {
621 p = string;
622 while ( (*p = toupper(*p)) ) ++p;
623 strcatW(string,quals);
624 strcpyW(quals, string);
627 byte_total = 0;
628 file_total = dir_total = 0;
630 /* Initialize all flags to their defaults as if no DIRCMD or quals */
631 paged_mode = FALSE;
632 recurse = FALSE;
633 wide = FALSE;
634 bare = FALSE;
635 lower = FALSE;
636 shortname = FALSE;
637 usernames = FALSE;
638 orderByCol = FALSE;
639 separator = TRUE;
640 dirTime = Written;
641 dirOrder = Name;
642 orderReverse = FALSE;
643 orderGroupDirs = FALSE;
644 orderGroupDirsReverse = FALSE;
645 showattrs = 0;
646 attrsbits = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
648 /* Handle args - Loop through so right most is the effective one */
649 /* Note: /- appears to be a negate rather than an off, eg. dir
650 /-W is wide, or dir /w /-w /-w is also wide */
651 p = quals;
652 while (*p && (*p=='/' || *p==' ')) {
653 BOOL negate = FALSE;
654 if (*p++==' ') continue; /* Skip / and blanks introduced through DIRCMD */
656 if (*p=='-') {
657 negate = TRUE;
658 p++;
661 WINE_TRACE("Processing arg '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
662 switch (*p) {
663 case 'P': if (negate) paged_mode = !paged_mode;
664 else paged_mode = TRUE;
665 break;
666 case 'S': if (negate) recurse = !recurse;
667 else recurse = TRUE;
668 break;
669 case 'W': if (negate) wide = !wide;
670 else wide = TRUE;
671 break;
672 case 'B': if (negate) bare = !bare;
673 else bare = TRUE;
674 break;
675 case 'L': if (negate) lower = !lower;
676 else lower = TRUE;
677 break;
678 case 'X': if (negate) shortname = !shortname;
679 else shortname = TRUE;
680 break;
681 case 'Q': if (negate) usernames = !usernames;
682 else usernames = TRUE;
683 break;
684 case 'D': if (negate) orderByCol = !orderByCol;
685 else orderByCol = TRUE;
686 break;
687 case 'C': if (negate) separator = !separator;
688 else separator = TRUE;
689 break;
690 case 'T': p = p + 1;
691 if (*p==':') p++; /* Skip optional : */
693 if (*p == 'A') dirTime = Access;
694 else if (*p == 'C') dirTime = Creation;
695 else if (*p == 'W') dirTime = Written;
697 /* Support /T and /T: with no parms, default to written */
698 else if (*p == 0x00 || *p == '/') {
699 dirTime = Written;
700 p = p - 1; /* So when step on, move to '/' */
701 } else {
702 SetLastError(ERROR_INVALID_PARAMETER);
703 WCMD_print_error();
704 errorlevel = 1;
705 return;
707 break;
708 case 'O': p = p + 1;
709 if (*p==':') p++; /* Skip optional : */
710 while (*p && *p != '/') {
711 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
712 switch (*p) {
713 case 'N': dirOrder = Name; break;
714 case 'E': dirOrder = Extension; break;
715 case 'S': dirOrder = Size; break;
716 case 'D': dirOrder = Date; break;
717 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
718 else orderReverse = TRUE;
719 break;
720 case 'G': orderGroupDirs = TRUE; break;
721 default:
722 SetLastError(ERROR_INVALID_PARAMETER);
723 WCMD_print_error();
724 errorlevel = 1;
725 return;
727 p++;
729 p = p - 1; /* So when step on, move to '/' */
730 break;
731 case 'A': p = p + 1;
732 showattrs = 0;
733 attrsbits = 0;
734 if (*p==':') p++; /* Skip optional : */
735 while (*p && *p != '/') {
736 BOOL anegate = FALSE;
737 ULONG mask;
739 /* Note /A: - options are 'offs' not toggles */
740 if (*p=='-') {
741 anegate = TRUE;
742 p++;
745 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
746 switch (*p) {
747 case 'D': mask = FILE_ATTRIBUTE_DIRECTORY; break;
748 case 'H': mask = FILE_ATTRIBUTE_HIDDEN; break;
749 case 'S': mask = FILE_ATTRIBUTE_SYSTEM; break;
750 case 'R': mask = FILE_ATTRIBUTE_READONLY; break;
751 case 'A': mask = FILE_ATTRIBUTE_ARCHIVE; break;
752 default:
753 SetLastError(ERROR_INVALID_PARAMETER);
754 WCMD_print_error();
755 errorlevel = 1;
756 return;
759 /* Keep running list of bits we care about */
760 attrsbits |= mask;
762 /* Mask shows what MUST be in the bits we care about */
763 if (anegate) showattrs = showattrs & ~mask;
764 else showattrs |= mask;
766 p++;
768 p = p - 1; /* So when step on, move to '/' */
769 WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs, attrsbits);
770 break;
771 default:
772 SetLastError(ERROR_INVALID_PARAMETER);
773 WCMD_print_error();
774 errorlevel = 1;
775 return;
777 p = p + 1;
780 /* Handle conflicting args and initialization */
781 if (bare || shortname) wide = FALSE;
782 if (bare) shortname = FALSE;
783 if (wide) usernames = FALSE;
784 if (orderByCol) wide = TRUE;
786 if (wide) {
787 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
788 max_width = consoleInfo.dwSize.X;
789 else
790 max_width = 80;
792 if (paged_mode) {
793 WCMD_enter_paged_mode(NULL);
796 argno = 0;
797 argN = cmd;
798 GetCurrentDirectoryW(MAX_PATH, cwd);
799 strcatW(cwd, slashW);
801 /* Loop through all args, calculating full effective directory */
802 fullParms = NULL;
803 prevEntry = NULL;
804 while (argN) {
805 WCHAR fullname[MAXSTRING];
806 WCHAR *thisArg = WCMD_parameter(cmd, argno++, &argN, NULL);
807 if (argN && argN[0] != '/') {
809 WINE_TRACE("Found parm '%s'\n", wine_dbgstr_w(thisArg));
810 if (thisArg[1] == ':' && thisArg[2] == '\\') {
811 strcpyW(fullname, thisArg);
812 } else if (thisArg[1] == ':' && thisArg[2] != '\\') {
813 WCHAR envvar[4];
814 static const WCHAR envFmt[] = {'=','%','c',':','\0'};
815 wsprintfW(envvar, envFmt, thisArg[0]);
816 if (!GetEnvironmentVariableW(envvar, fullname, MAX_PATH)) {
817 static const WCHAR noEnvFmt[] = {'%','c',':','\0'};
818 wsprintfW(fullname, noEnvFmt, thisArg[0]);
820 strcatW(fullname, slashW);
821 strcatW(fullname, &thisArg[2]);
822 } else if (thisArg[0] == '\\') {
823 memcpy(fullname, cwd, 2 * sizeof(WCHAR));
824 strcpyW(fullname+2, thisArg);
825 } else {
826 strcpyW(fullname, cwd);
827 strcatW(fullname, thisArg);
829 WINE_TRACE("Using location '%s'\n", wine_dbgstr_w(fullname));
831 status = GetFullPathNameW(fullname, sizeof(path)/sizeof(WCHAR), path, NULL);
834 * If the path supplied does not include a wildcard, and the endpoint of the
835 * path references a directory, we need to list the *contents* of that
836 * directory not the directory file itself.
838 if ((strchrW(path, '*') == NULL) && (strchrW(path, '%') == NULL)) {
839 status = GetFileAttributesW(path);
840 if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
841 if (path[strlenW(path)-1] == '\\') {
842 strcatW (path, starW);
844 else {
845 static const WCHAR slashStarW[] = {'\\','*','\0'};
846 strcatW (path, slashStarW);
849 } else {
850 /* Special case wildcard search with no extension (ie parameters ending in '.') as
851 GetFullPathName strips off the additional '.' */
852 if (fullname[strlenW(fullname)-1] == '.') strcatW(path, dotW);
855 WINE_TRACE("Using path '%s'\n", wine_dbgstr_w(path));
856 thisEntry = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
857 if (fullParms == NULL) fullParms = thisEntry;
858 if (prevEntry != NULL) prevEntry->next = thisEntry;
859 prevEntry = thisEntry;
860 thisEntry->next = NULL;
862 /* Split into components */
863 WCMD_splitpath(path, drive, dir, fname, ext);
864 WINE_TRACE("Path Parts: drive: '%s' dir: '%s' name: '%s' ext:'%s'\n",
865 wine_dbgstr_w(drive), wine_dbgstr_w(dir),
866 wine_dbgstr_w(fname), wine_dbgstr_w(ext));
868 thisEntry->dirName = HeapAlloc(GetProcessHeap(),0,
869 sizeof(WCHAR) * (strlenW(drive)+strlenW(dir)+1));
870 strcpyW(thisEntry->dirName, drive);
871 strcatW(thisEntry->dirName, dir);
873 thisEntry->fileName = HeapAlloc(GetProcessHeap(),0,
874 sizeof(WCHAR) * (strlenW(fname)+strlenW(ext)+1));
875 strcpyW(thisEntry->fileName, fname);
876 strcatW(thisEntry->fileName, ext);
881 /* If just 'dir' entered, a '*' parameter is assumed */
882 if (fullParms == NULL) {
883 WINE_TRACE("Inserting default '*'\n");
884 fullParms = HeapAlloc(GetProcessHeap(),0, sizeof(DIRECTORY_STACK));
885 fullParms->next = NULL;
886 fullParms->dirName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * (strlenW(cwd)+1));
887 strcpyW(fullParms->dirName, cwd);
888 fullParms->fileName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * 2);
889 strcpyW(fullParms->fileName, starW);
892 lastDrive = '?';
893 prevEntry = NULL;
894 thisEntry = fullParms;
895 trailerReqd = FALSE;
897 while (thisEntry != NULL) {
899 /* Output disk free (trailer) and volume information (header) if the drive
900 letter changes */
901 if (lastDrive != toupper(thisEntry->dirName[0])) {
903 /* Trailer Information */
904 if (lastDrive != '?') {
905 trailerReqd = FALSE;
906 WCMD_dir_trailer(prevEntry->dirName[0]);
909 lastDrive = toupper(thisEntry->dirName[0]);
911 if (!bare) {
912 WCHAR drive[3];
914 WINE_TRACE("Writing volume for '%c:'\n", thisEntry->dirName[0]);
915 memcpy(drive, thisEntry->dirName, 2 * sizeof(WCHAR));
916 drive[2] = 0x00;
917 status = WCMD_volume (0, drive);
918 trailerReqd = TRUE;
919 if (!status) {
920 errorlevel = 1;
921 goto exit;
924 } else {
925 static const WCHAR newLine2[] = {'\n','\n','\0'};
926 if (!bare) WCMD_output_asis (newLine2);
929 /* Clear any errors from previous invocations, and process it */
930 errorlevel = 0;
931 prevEntry = thisEntry;
932 thisEntry = WCMD_list_directory (thisEntry, 0);
935 /* Trailer Information */
936 if (trailerReqd) {
937 WCMD_dir_trailer(prevEntry->dirName[0]);
940 exit:
941 if (paged_mode) WCMD_leave_paged_mode();
943 /* Free storage allocated for parms */
944 while (fullParms != NULL) {
945 prevEntry = fullParms;
946 fullParms = prevEntry->next;
947 HeapFree(GetProcessHeap(),0,prevEntry->dirName);
948 HeapFree(GetProcessHeap(),0,prevEntry->fileName);
949 HeapFree(GetProcessHeap(),0,prevEntry);