mshtml: Convert dialogs to po files.
[wine/multimedia.git] / programs / cmd / directory.c
blob7fc60a7e97a12e5c8ffd3a86ffde6d8cdbc6d5f5
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','0','s',' ',' ','%','8','s',' ',' ',
258 '<','D','I','R','>',' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
259 static const WCHAR fmtFile[] = {'%','1','0','s',' ',' ','%','8','s',' ',' ',
260 ' ',' ','%','1','0','s',' ',' ','\0'};
261 static const WCHAR fmt2[] = {'%','-','1','3','s','\0'};
262 static const WCHAR fmt3[] = {'%','-','2','3','s','\0'};
263 static const WCHAR fmt4[] = {'%','s','\0'};
264 static const WCHAR fmt5[] = {'%','s','%','s','\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 (newline);
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 ' ','%','s','\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[] = {'[','%','s',']','\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[] = {'%','s','\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 int padding = cur_width - tmp_width;
413 int toWrite = 0;
414 WCHAR temp[101];
416 /* Note: WCMD_output uses wvsprintf which does not allow %*
417 so manually pad with spaces to appropriate width */
418 strcpyW(temp, nullW);
419 while (padding > 0) {
420 strcatW(&temp[toWrite], space);
421 toWrite++;
422 if (toWrite > 99) {
423 WCMD_output_asis(temp);
424 toWrite = 0;
425 strcpyW(temp, nullW);
427 padding--;
429 WCMD_output_asis(temp);
432 } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
433 dir_count++;
435 if (!bare) {
436 WCMD_output (fmtDir, datestring, timestring);
437 if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
438 if (usernames) WCMD_output (fmt3, username);
439 WCMD_output(fmt4,(fd+i)->cFileName);
440 } else {
441 if (!((strcmpW((fd+i)->cFileName, dotW) == 0) ||
442 (strcmpW((fd+i)->cFileName, dotdotW) == 0))) {
443 WCMD_output (fmt5, recurse?inputparms->dirName:nullW, (fd+i)->cFileName);
444 } else {
445 addNewLine = FALSE;
449 else {
450 file_count++;
451 file_size.u.LowPart = (fd+i)->nFileSizeLow;
452 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
453 byte_count.QuadPart += file_size.QuadPart;
454 if (!bare) {
455 WCMD_output (fmtFile, datestring, timestring,
456 WCMD_filesize64(file_size.QuadPart));
457 if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
458 if (usernames) WCMD_output (fmt3, username);
459 WCMD_output(fmt4,(fd+i)->cFileName);
460 } else {
461 WCMD_output (fmt5, recurse?inputparms->dirName:nullW, (fd+i)->cFileName);
465 if (addNewLine) WCMD_output_asis (newline);
466 cur_width = 0;
469 if (!bare) {
470 if (file_count == 1) {
471 static const WCHAR fmt[] = {' ',' ',' ',' ',' ',' ',' ','1',' ','f','i','l','e',' ',
472 '%','2','5','s',' ','b','y','t','e','s','\n','\0'};
473 WCMD_output (fmt, WCMD_filesize64 (byte_count.QuadPart));
475 else {
476 static const WCHAR fmt[] = {'%','8','d',' ','f','i','l','e','s',' ','%','2','4','s',
477 ' ','b','y','t','e','s','\n','\0'};
478 WCMD_output (fmt, file_count, WCMD_filesize64 (byte_count.QuadPart));
481 byte_total = byte_total + byte_count.QuadPart;
482 file_total = file_total + file_count;
483 dir_total = dir_total + dir_count;
485 if (!bare && !recurse) {
486 if (dir_count == 1) {
487 static const WCHAR fmt[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','y',
488 ' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
489 WCMD_output (fmt, 1);
490 } else {
491 static const WCHAR fmt[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','i',
492 'e','s','\0'};
493 WCMD_output (fmt, dir_count);
497 HeapFree(GetProcessHeap(),0,fd);
499 /* When recursing, look in all subdirectories for matches */
500 if (recurse) {
501 DIRECTORY_STACK *dirStack = NULL;
502 DIRECTORY_STACK *lastEntry = NULL;
503 WIN32_FIND_DATAW finddata;
505 /* Build path to search */
506 strcpyW(string, inputparms->dirName);
507 strcatW(string, starW);
509 WINE_TRACE("Recursive, looking for '%s'\n", wine_dbgstr_w(string));
510 hff = FindFirstFileW(string, &finddata);
511 if (hff != INVALID_HANDLE_VALUE) {
512 do {
513 if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
514 (strcmpW(finddata.cFileName, dotdotW) != 0) &&
515 (strcmpW(finddata.cFileName, dotW) != 0)) {
517 DIRECTORY_STACK *thisDir;
518 int dirsToCopy = concurrentDirs;
520 /* Loop creating list of subdirs for all concurrent entries */
521 parms = inputparms;
522 while (dirsToCopy > 0) {
523 dirsToCopy--;
525 /* Work out search parameter in sub dir */
526 strcpyW (string, inputparms->dirName);
527 strcatW (string, finddata.cFileName);
528 strcatW (string, slashW);
529 WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(string));
531 /* Allocate memory, add to list */
532 thisDir = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
533 if (dirStack == NULL) dirStack = thisDir;
534 if (lastEntry != NULL) lastEntry->next = thisDir;
535 lastEntry = thisDir;
536 thisDir->next = NULL;
537 thisDir->dirName = HeapAlloc(GetProcessHeap(),0,
538 sizeof(WCHAR) * (strlenW(string)+1));
539 strcpyW(thisDir->dirName, string);
540 thisDir->fileName = HeapAlloc(GetProcessHeap(),0,
541 sizeof(WCHAR) * (strlenW(parms->fileName)+1));
542 strcpyW(thisDir->fileName, parms->fileName);
543 parms = parms->next;
546 } while (FindNextFileW(hff, &finddata) != 0);
547 FindClose (hff);
549 while (dirStack != NULL) {
550 DIRECTORY_STACK *thisDir = dirStack;
551 dirStack = WCMD_list_directory (thisDir, 1);
552 while (thisDir != dirStack) {
553 DIRECTORY_STACK *tempDir = thisDir->next;
554 HeapFree(GetProcessHeap(),0,thisDir->dirName);
555 HeapFree(GetProcessHeap(),0,thisDir->fileName);
556 HeapFree(GetProcessHeap(),0,thisDir);
557 thisDir = tempDir;
563 /* Handle case where everything is filtered out */
564 if ((file_total + dir_total == 0) && (level == 0)) {
565 SetLastError (ERROR_FILE_NOT_FOUND);
566 WCMD_print_error ();
567 errorlevel = 1;
570 return parms;
573 /*****************************************************************************
574 * WCMD_dir_trailer
576 * Print out the trailer for the supplied drive letter
578 static void WCMD_dir_trailer(WCHAR drive) {
579 ULARGE_INTEGER avail, total, freebytes;
580 DWORD status;
581 WCHAR driveName[4] = {'c',':','\\','\0'};
583 driveName[0] = drive;
584 status = GetDiskFreeSpaceExW(driveName, &avail, &total, &freebytes);
585 WINE_TRACE("Writing trailer for '%s' gave %d(%d)\n", wine_dbgstr_w(driveName),
586 status, GetLastError());
588 if (errorlevel==0 && !bare) {
589 if (recurse) {
590 static const WCHAR fmt1[] = {'\n',' ',' ',' ',' ',' ','T','o','t','a','l',' ','f','i','l','e','s',
591 ' ','l','i','s','t','e','d',':','\n','%','8','d',' ','f','i','l','e',
592 's','%','2','5','s',' ','b','y','t','e','s','\n','\0'};
593 static const WCHAR fmt2[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','i','e','s',' ','%',
594 '1','8','s',' ','b','y','t','e','s',' ','f','r','e','e','\n','\n',
595 '\0'};
596 WCMD_output (fmt1, file_total, WCMD_filesize64 (byte_total));
597 WCMD_output (fmt2, dir_total, WCMD_filesize64 (freebytes.QuadPart));
598 } else {
599 static const WCHAR fmt[] = {' ','%','1','8','s',' ','b','y','t','e','s',' ','f','r','e','e',
600 '\n','\n','\0'};
601 WCMD_output (fmt, WCMD_filesize64 (freebytes.QuadPart));
606 /*****************************************************************************
607 * WCMD_directory
609 * List a file directory.
613 void WCMD_directory (WCHAR *cmd)
615 WCHAR path[MAX_PATH], cwd[MAX_PATH];
616 DWORD status;
617 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
618 WCHAR *p;
619 WCHAR string[MAXSTRING];
620 int argno = 0;
621 WCHAR *argN = cmd;
622 WCHAR lastDrive;
623 BOOL trailerReqd = FALSE;
624 DIRECTORY_STACK *fullParms = NULL;
625 DIRECTORY_STACK *prevEntry = NULL;
626 DIRECTORY_STACK *thisEntry = NULL;
627 WCHAR drive[10];
628 WCHAR dir[MAX_PATH];
629 WCHAR fname[MAX_PATH];
630 WCHAR ext[MAX_PATH];
631 static const WCHAR dircmdW[] = {'D','I','R','C','M','D','\0'};
633 errorlevel = 0;
635 /* Prefill quals with (uppercased) DIRCMD env var */
636 if (GetEnvironmentVariableW(dircmdW, string, sizeof(string)/sizeof(WCHAR))) {
637 p = string;
638 while ( (*p = toupper(*p)) ) ++p;
639 strcatW(string,quals);
640 strcpyW(quals, string);
643 byte_total = 0;
644 file_total = dir_total = 0;
646 /* Initialize all flags to their defaults as if no DIRCMD or quals */
647 paged_mode = FALSE;
648 recurse = FALSE;
649 wide = FALSE;
650 bare = FALSE;
651 lower = FALSE;
652 shortname = FALSE;
653 usernames = FALSE;
654 orderByCol = FALSE;
655 separator = TRUE;
656 dirTime = Written;
657 dirOrder = Name;
658 orderReverse = FALSE;
659 orderGroupDirs = FALSE;
660 orderGroupDirsReverse = FALSE;
661 showattrs = 0;
662 attrsbits = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
664 /* Handle args - Loop through so right most is the effective one */
665 /* Note: /- appears to be a negate rather than an off, eg. dir
666 /-W is wide, or dir /w /-w /-w is also wide */
667 p = quals;
668 while (*p && (*p=='/' || *p==' ')) {
669 BOOL negate = FALSE;
670 if (*p++==' ') continue; /* Skip / and blanks introduced through DIRCMD */
672 if (*p=='-') {
673 negate = TRUE;
674 p++;
677 WINE_TRACE("Processing arg '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
678 switch (*p) {
679 case 'P': if (negate) paged_mode = !paged_mode;
680 else paged_mode = TRUE;
681 break;
682 case 'S': if (negate) recurse = !recurse;
683 else recurse = TRUE;
684 break;
685 case 'W': if (negate) wide = !wide;
686 else wide = TRUE;
687 break;
688 case 'B': if (negate) bare = !bare;
689 else bare = TRUE;
690 break;
691 case 'L': if (negate) lower = !lower;
692 else lower = TRUE;
693 break;
694 case 'X': if (negate) shortname = !shortname;
695 else shortname = TRUE;
696 break;
697 case 'Q': if (negate) usernames = !usernames;
698 else usernames = TRUE;
699 break;
700 case 'D': if (negate) orderByCol = !orderByCol;
701 else orderByCol = TRUE;
702 break;
703 case 'C': if (negate) separator = !separator;
704 else separator = TRUE;
705 break;
706 case 'T': p = p + 1;
707 if (*p==':') p++; /* Skip optional : */
709 if (*p == 'A') dirTime = Access;
710 else if (*p == 'C') dirTime = Creation;
711 else if (*p == 'W') dirTime = Written;
713 /* Support /T and /T: with no parms, default to written */
714 else if (*p == 0x00 || *p == '/') {
715 dirTime = Written;
716 p = p - 1; /* So when step on, move to '/' */
717 } else {
718 SetLastError(ERROR_INVALID_PARAMETER);
719 WCMD_print_error();
720 errorlevel = 1;
721 return;
723 break;
724 case 'O': p = p + 1;
725 if (*p==':') p++; /* Skip optional : */
726 while (*p && *p != '/') {
727 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
728 switch (*p) {
729 case 'N': dirOrder = Name; break;
730 case 'E': dirOrder = Extension; break;
731 case 'S': dirOrder = Size; break;
732 case 'D': dirOrder = Date; break;
733 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
734 else orderReverse = TRUE;
735 break;
736 case 'G': orderGroupDirs = TRUE; break;
737 default:
738 SetLastError(ERROR_INVALID_PARAMETER);
739 WCMD_print_error();
740 errorlevel = 1;
741 return;
743 p++;
745 p = p - 1; /* So when step on, move to '/' */
746 break;
747 case 'A': p = p + 1;
748 showattrs = 0;
749 attrsbits = 0;
750 if (*p==':') p++; /* Skip optional : */
751 while (*p && *p != '/') {
752 BOOL anegate = FALSE;
753 ULONG mask;
755 /* Note /A: - options are 'offs' not toggles */
756 if (*p=='-') {
757 anegate = TRUE;
758 p++;
761 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
762 switch (*p) {
763 case 'D': mask = FILE_ATTRIBUTE_DIRECTORY; break;
764 case 'H': mask = FILE_ATTRIBUTE_HIDDEN; break;
765 case 'S': mask = FILE_ATTRIBUTE_SYSTEM; break;
766 case 'R': mask = FILE_ATTRIBUTE_READONLY; break;
767 case 'A': mask = FILE_ATTRIBUTE_ARCHIVE; break;
768 default:
769 SetLastError(ERROR_INVALID_PARAMETER);
770 WCMD_print_error();
771 errorlevel = 1;
772 return;
775 /* Keep running list of bits we care about */
776 attrsbits |= mask;
778 /* Mask shows what MUST be in the bits we care about */
779 if (anegate) showattrs = showattrs & ~mask;
780 else showattrs |= mask;
782 p++;
784 p = p - 1; /* So when step on, move to '/' */
785 WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs, attrsbits);
786 break;
787 default:
788 SetLastError(ERROR_INVALID_PARAMETER);
789 WCMD_print_error();
790 errorlevel = 1;
791 return;
793 p = p + 1;
796 /* Handle conflicting args and initialization */
797 if (bare || shortname) wide = FALSE;
798 if (bare) shortname = FALSE;
799 if (wide) usernames = FALSE;
800 if (orderByCol) wide = TRUE;
802 if (wide) {
803 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
804 max_width = consoleInfo.dwSize.X;
805 else
806 max_width = 80;
808 if (paged_mode) {
809 WCMD_enter_paged_mode(NULL);
812 argno = 0;
813 argN = cmd;
814 GetCurrentDirectoryW(MAX_PATH, cwd);
815 strcatW(cwd, slashW);
817 /* Loop through all args, calculating full effective directory */
818 fullParms = NULL;
819 prevEntry = NULL;
820 while (argN) {
821 WCHAR fullname[MAXSTRING];
822 WCHAR *thisArg = WCMD_parameter(cmd, argno++, &argN, NULL);
823 if (argN && argN[0] != '/') {
825 WINE_TRACE("Found parm '%s'\n", wine_dbgstr_w(thisArg));
826 if (thisArg[1] == ':' && thisArg[2] == '\\') {
827 strcpyW(fullname, thisArg);
828 } else if (thisArg[1] == ':' && thisArg[2] != '\\') {
829 WCHAR envvar[4];
830 static const WCHAR envFmt[] = {'=','%','c',':','\0'};
831 wsprintfW(envvar, envFmt, thisArg[0]);
832 if (!GetEnvironmentVariableW(envvar, fullname, MAX_PATH)) {
833 static const WCHAR noEnvFmt[] = {'%','c',':','\0'};
834 wsprintfW(fullname, noEnvFmt, thisArg[0]);
836 strcatW(fullname, slashW);
837 strcatW(fullname, &thisArg[2]);
838 } else if (thisArg[0] == '\\') {
839 memcpy(fullname, cwd, 2 * sizeof(WCHAR));
840 strcpyW(fullname+2, thisArg);
841 } else {
842 strcpyW(fullname, cwd);
843 strcatW(fullname, thisArg);
845 WINE_TRACE("Using location '%s'\n", wine_dbgstr_w(fullname));
847 status = GetFullPathNameW(fullname, sizeof(path)/sizeof(WCHAR), path, NULL);
850 * If the path supplied does not include a wildcard, and the endpoint of the
851 * path references a directory, we need to list the *contents* of that
852 * directory not the directory file itself.
854 if ((strchrW(path, '*') == NULL) && (strchrW(path, '%') == NULL)) {
855 status = GetFileAttributesW(path);
856 if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
857 if (path[strlenW(path)-1] == '\\') {
858 strcatW (path, starW);
860 else {
861 static const WCHAR slashStarW[] = {'\\','*','\0'};
862 strcatW (path, slashStarW);
865 } else {
866 /* Special case wildcard search with no extension (ie parameters ending in '.') as
867 GetFullPathName strips off the additional '.' */
868 if (fullname[strlenW(fullname)-1] == '.') strcatW(path, dotW);
871 WINE_TRACE("Using path '%s'\n", wine_dbgstr_w(path));
872 thisEntry = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
873 if (fullParms == NULL) fullParms = thisEntry;
874 if (prevEntry != NULL) prevEntry->next = thisEntry;
875 prevEntry = thisEntry;
876 thisEntry->next = NULL;
878 /* Split into components */
879 WCMD_splitpath(path, drive, dir, fname, ext);
880 WINE_TRACE("Path Parts: drive: '%s' dir: '%s' name: '%s' ext:'%s'\n",
881 wine_dbgstr_w(drive), wine_dbgstr_w(dir),
882 wine_dbgstr_w(fname), wine_dbgstr_w(ext));
884 thisEntry->dirName = HeapAlloc(GetProcessHeap(),0,
885 sizeof(WCHAR) * (strlenW(drive)+strlenW(dir)+1));
886 strcpyW(thisEntry->dirName, drive);
887 strcatW(thisEntry->dirName, dir);
889 thisEntry->fileName = HeapAlloc(GetProcessHeap(),0,
890 sizeof(WCHAR) * (strlenW(fname)+strlenW(ext)+1));
891 strcpyW(thisEntry->fileName, fname);
892 strcatW(thisEntry->fileName, ext);
897 /* If just 'dir' entered, a '*' parameter is assumed */
898 if (fullParms == NULL) {
899 WINE_TRACE("Inserting default '*'\n");
900 fullParms = HeapAlloc(GetProcessHeap(),0, sizeof(DIRECTORY_STACK));
901 fullParms->next = NULL;
902 fullParms->dirName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * (strlenW(cwd)+1));
903 strcpyW(fullParms->dirName, cwd);
904 fullParms->fileName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * 2);
905 strcpyW(fullParms->fileName, starW);
908 lastDrive = '?';
909 prevEntry = NULL;
910 thisEntry = fullParms;
911 trailerReqd = FALSE;
913 while (thisEntry != NULL) {
915 /* Output disk free (trailer) and volume information (header) if the drive
916 letter changes */
917 if (lastDrive != toupper(thisEntry->dirName[0])) {
919 /* Trailer Information */
920 if (lastDrive != '?') {
921 trailerReqd = FALSE;
922 WCMD_dir_trailer(prevEntry->dirName[0]);
925 lastDrive = toupper(thisEntry->dirName[0]);
927 if (!bare) {
928 WCHAR drive[3];
930 WINE_TRACE("Writing volume for '%c:'\n", thisEntry->dirName[0]);
931 memcpy(drive, thisEntry->dirName, 2 * sizeof(WCHAR));
932 drive[2] = 0x00;
933 status = WCMD_volume (0, drive);
934 trailerReqd = TRUE;
935 if (!status) {
936 errorlevel = 1;
937 goto exit;
940 } else {
941 static const WCHAR newLine2[] = {'\n','\n','\0'};
942 if (!bare) WCMD_output_asis (newLine2);
945 /* Clear any errors from previous invocations, and process it */
946 errorlevel = 0;
947 prevEntry = thisEntry;
948 thisEntry = WCMD_list_directory (thisEntry, 0);
951 /* Trailer Information */
952 if (trailerReqd) {
953 WCMD_dir_trailer(prevEntry->dirName[0]);
956 exit:
957 if (paged_mode) WCMD_leave_paged_mode();
959 /* Free storage allocated for parms */
960 while (fullParms != NULL) {
961 prevEntry = fullParms;
962 fullParms = prevEntry->next;
963 HeapFree(GetProcessHeap(),0,prevEntry->dirName);
964 HeapFree(GetProcessHeap(),0,prevEntry->fileName);
965 HeapFree(GetProcessHeap(),0,prevEntry);