80d5ddcbcaf1435707ee9a74dfbe7d99d491a8db
[chise/xemacs-chise.git.1] / src / dired-msw.c
1 /* fast dired replacement routines for mswindows.
2    Copyright (C) 1998 Darryl Okahata
3    Portions Copyright (C) 1992, 1994 by Sebastian Kremer <sk@thp.uni-koeln.de>
4
5 This file is part of XEmacs.
6
7 XEmacs is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
10 later version.
11
12 XEmacs is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with XEmacs; see the file COPYING.  If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 /* Synched up with: Not in FSF. */
23
24 /*
25  * Parts of this code (& comments) were taken from ls-lisp.el
26  * Author: Sebastian Kremer <sk@thp.uni-koeln.de>
27  */
28
29 /*
30  * insert-directory
31  * - must insert _exactly_one_line_ describing FILE if WILDCARD and
32  * FULL-DIRECTORY-P is nil.
33  * The single line of output must display FILE's name as it was
34  * given, namely, an absolute path name.
35  * - must insert exactly one line for each file if WILDCARD or
36  * FULL-DIRECTORY-P is t, plus one optional "total" line
37  * before the file lines, plus optional text after the file lines.
38  * Lines are delimited by "\n", so filenames containing "\n" are not
39  * allowed.
40  * File lines should display the basename.
41  * - must be consistent with
42  * - functions dired-move-to-filename, (these two define what a file line is)
43  * dired-move-to-end-of-filename,
44  * dired-between-files, (shortcut for (not (dired-move-to-filename)))
45  * dired-insert-headerline
46  * dired-after-subdir-garbage (defines what a "total" line is)
47  * - variable dired-subdir-regexp
48  */
49
50 /*
51  * Insert directory listing for FILE, formatted according to SWITCHES.
52  * Leaves point after the inserted text.
53  * SWITCHES may be a string of options, or a list of strings.
54  * Optional third arg WILDCARD means treat FILE as shell wildcard.
55  * Optional fourth arg FULL-DIRECTORY-P means file is a directory and
56  * switches do not contain `d', so that a full listing is expected.
57  *
58  * This works by running a directory listing program
59  * whose name is in the variable `insert-directory-program'.
60  * If WILDCARD, it also runs the shell specified by `shell-file-name'."
61  */
62
63 /*
64  * Set INDENT_LISTING to non-zero if the inserted text should be shifted
65  * over by two spaces.
66  */
67 #define INDENT_LISTING                  0
68
69 #define ROUND_FILE_SIZES                4096
70
71
72 #include <config.h>
73 #include "lisp.h"
74
75 #include "buffer.h"
76 #include "regex.h"
77
78 #include "sysfile.h"
79 #include "sysdir.h"
80 #include "sysproc.h"
81
82 #include <limits.h>
83 #include <time.h>
84
85 #include <winsock.h>            /* To make nt.h happy */
86 #include "nt.h"         /* For prototypes */
87
88 #if ROUND_FILE_SIZES > 0
89 #include <math.h>               /* for floor() */
90 #endif
91
92
93 static int mswindows_ls_sort_case_insensitive;
94 static int mswindows_ls_round_file_size;
95
96 Lisp_Object             Qmswindows_insert_directory;
97
98 extern Lisp_Object      Vmswindows_downcase_file_names; /* in device-msw.c */
99
100
101
102 enum mswindows_sortby {
103   MSWINDOWS_SORT_BY_NAME,
104   MSWINDOWS_SORT_BY_NAME_NOCASE,
105   MSWINDOWS_SORT_BY_MOD_DATE,
106   MSWINDOWS_SORT_BY_SIZE
107 };
108
109
110 static enum mswindows_sortby    mswindows_sort_method;
111 static int                      mswindows_reverse_sort;
112
113
114 #define CMPDWORDS(t1a, t1b, t2a, t2b) \
115 (((t1a) == (t2a)) ? (((t1b) == (t2b)) ? 0 : (((t1b) < (t2b)) ? -1 : 1)) \
116  : (((t1a) < (t2a)) ? -1 : 1))
117
118
119 static int
120 mswindows_ls_sort_fcn (const void *elem1, const void *elem2)
121 {
122   WIN32_FIND_DATA               *e1, *e2;
123   int                           status;
124
125   e1 = *(WIN32_FIND_DATA **)elem1;
126   e2 = *(WIN32_FIND_DATA **)elem2;
127   switch (mswindows_sort_method)
128     {
129     case MSWINDOWS_SORT_BY_NAME:
130       status = strcmp(e1->cFileName, e2->cFileName);
131       break;
132     case MSWINDOWS_SORT_BY_NAME_NOCASE:
133       status = _stricmp(e1->cFileName, e2->cFileName);
134       break;
135     case MSWINDOWS_SORT_BY_MOD_DATE:
136       status = CMPDWORDS(e1->ftLastWriteTime.dwHighDateTime,
137                          e1->ftLastWriteTime.dwLowDateTime,
138                          e2->ftLastWriteTime.dwHighDateTime,
139                          e2->ftLastWriteTime.dwLowDateTime);
140       break;
141     case MSWINDOWS_SORT_BY_SIZE:
142       status = CMPDWORDS(e1->nFileSizeHigh, e1->nFileSizeLow,
143                          e2->nFileSizeHigh, e2->nFileSizeLow);
144       break;
145     default:
146       status = 0;
147       break;
148     }
149   if (mswindows_reverse_sort)
150     {
151       status = -status;
152     }
153   return (status);
154 }
155
156
157 static void
158 mswindows_sort_files (WIN32_FIND_DATA **files, int nfiles,
159                       enum mswindows_sortby sort_by, int reverse)
160 {
161   mswindows_sort_method = sort_by;
162   mswindows_reverse_sort = reverse;
163   qsort(files, nfiles, sizeof(WIN32_FIND_DATA *), mswindows_ls_sort_fcn);
164 }
165
166
167 static WIN32_FIND_DATA *
168 mswindows_get_files (char *dirfile, int nowild, Lisp_Object pattern,
169                      int hide_dot, int hide_system, int *nfiles)
170 {
171   WIN32_FIND_DATA               *files;
172   int                           array_size;
173   struct re_pattern_buffer      *bufp = NULL;
174   int                           findex, len;
175   char                          win32pattern[MAXNAMLEN+3];
176   HANDLE                        fh;
177
178   /*
179    * Much of the following code and comments were taken from dired.c.
180    * Yes, this is something of a waste, but we want speed, speed, SPEED.
181    */
182   files = NULL;
183   array_size = *nfiles = 0;
184   while (1)
185     {
186       if (!NILP(pattern))
187         {
188           /* PATTERN might be a flawed regular expression.  Rather than
189              catching and signalling our own errors, we just call
190              compile_pattern to do the work for us.  */
191           bufp = compile_pattern (pattern, 0, 0, 0, ERROR_ME);
192         }
193       /* Now *bufp is the compiled form of PATTERN; don't call anything
194          which might compile a new regexp until we're done with the loop! */
195
196       /* Initialize file info array */
197       array_size = 100;         /* initial size */
198       files = xmalloc(array_size * sizeof (WIN32_FIND_DATA));
199
200       /* for Win32, we need to insure that the pathname ends with "\*". */
201       strcpy (win32pattern, dirfile);
202       if (!nowild)
203         {
204           len = strlen (win32pattern) - 1;
205           if (!IS_DIRECTORY_SEP (win32pattern[len]))
206             strcat (win32pattern, "\\");
207           strcat (win32pattern, "*");
208         }
209
210       /*
211        * Here, we use FindFirstFile()/FindNextFile() instead of opendir(),
212        * stat(), & friends, because stat() is VERY expensive in terms of
213        * time.  Hence, we take the time to write complicated Win32-specific
214        * code, instead of simple Unix-style stuff.
215        */
216       findex = 0;
217       fh = INVALID_HANDLE_VALUE;
218
219       while (1)
220         {
221           int           len;
222           char  *filename;
223           int           result;
224
225           if (fh == INVALID_HANDLE_VALUE)
226             {
227               fh = FindFirstFile(win32pattern, &files[findex]);
228               if (fh == INVALID_HANDLE_VALUE)
229                 {
230                   report_file_error ("Opening directory",
231                                      list1(build_string(dirfile)));
232                 }
233             }
234           else
235             {
236               if (!FindNextFile(fh, &files[findex]))
237                 {
238                   if (GetLastError() == ERROR_NO_MORE_FILES)
239                     {
240                       break;
241                     }
242                   FindClose(fh);
243                   report_file_error ("Reading directory",
244                                      list1(build_string(dirfile)));
245                 }
246             }
247
248           filename = files[findex].cFileName;
249           if (!NILP(Vmswindows_downcase_file_names))
250           {
251               strlwr(filename);
252           }
253           len = strlen(filename);
254           result = (NILP(pattern)
255                     || (0 <= re_search (bufp, filename, 
256                                         len, 0, len, 0)));
257           if (result)
258             {
259               if ( ! (filename[0] == '.' &&
260                       ((hide_system && (filename[1] == '\0' ||
261                                         (filename[1] == '.' &&
262                                          filename[2] == '\0'))) ||
263                        hide_dot)))
264                 {
265                   if (++findex >= array_size)
266                     {
267                       array_size = findex * 2;
268                       files = xrealloc(files,
269                                        array_size * sizeof(WIN32_FIND_DATA));
270                     }
271                 }
272             }
273         }
274       if (fh != INVALID_HANDLE_VALUE)
275         {
276           FindClose (fh);
277         }
278       *nfiles = findex;
279       break;
280     }
281   return (files);
282 }
283
284
285 static void
286 mswindows_format_file (WIN32_FIND_DATA *file, char *buf, int display_size,
287                        int add_newline)
288 {
289   char                  *cptr;
290   int                   len;
291   Lisp_Object           luser;
292   double                file_size;
293
294   len = strlen(file->cFileName);
295   file_size =
296     file->nFileSizeHigh * (double)UINT_MAX + file->nFileSizeLow;
297   cptr = buf;
298 #if INDENT_LISTING
299   *cptr++ = ' ';
300   *cptr++ = ' ';
301 #endif
302   if (display_size)
303     {
304       sprintf(cptr, "%6d ", (int)((file_size + 1023.) / 1024.));
305       cptr += 7;
306     }
307   if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
308     {
309       *cptr++ = 'd';
310     } else {
311       *cptr++ = '-';
312     }
313   cptr[0] = cptr[3] = cptr[6] = 'r';
314   if (file->dwFileAttributes & FILE_ATTRIBUTE_READONLY)
315     {
316       cptr[1] = cptr[4] = cptr[7] = '-';
317     } else {
318       cptr[1] = cptr[4] = cptr[7] = 'w';
319     }
320   if ((file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
321       (len > 4 &&
322        (_stricmp(&file->cFileName[len - 4], ".exe") == 0
323         || _stricmp(&file->cFileName[len - 4], ".com") == 0
324         || _stricmp(&file->cFileName[len - 4], ".bat") == 0
325 #if 0
326         || _stricmp(&file->cFileName[len - 4], ".pif") == 0
327 #endif
328         )))
329     {
330       cptr[2] = cptr[5] = cptr[8] = 'x';
331     } else {
332       cptr[2] = cptr[5] = cptr[8] = '-';
333     }
334   cptr += 9;
335   if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
336     {
337       strcpy(cptr, "   2 ");
338     } else {
339       strcpy(cptr, "   1 ");
340     }
341   cptr += 5;
342   luser = Fuser_login_name(Qnil);
343   if (!STRINGP(luser))
344     {
345       sprintf(cptr, "%-9d", 0);
346     } else {
347       char              *str;
348
349       str = XSTRING_DATA(luser);
350       sprintf(cptr, "%-8s ", str);
351     }
352   while (*cptr)
353     {
354       ++cptr;
355     }
356   sprintf(cptr, "%-8d ", getgid());
357   cptr += 9;
358   if (file_size > 99999999.0)
359     {
360       file_size = (file_size + 1023.0) / 1024.;
361       if (file_size > 999999.0)
362         {
363           sprintf(cptr, "%6.0fMB ", (file_size + 1023.0) / 1024.);
364         } else {
365           sprintf(cptr, "%6.0fKB ", file_size);
366         }
367     } else {
368       sprintf(cptr, "%8.0f ", file_size);
369     }
370   while (*cptr)
371     {
372       ++cptr;
373     }
374   {
375     time_t              t, now;
376     char                *ctimebuf;
377     extern char         *sys_ctime(const time_t *t);    /* in nt.c */
378
379     if (
380 #if 0
381         /*
382          * This doesn't work.
383          * This code should be correct ...
384          */
385         FileTimeToLocalFileTime(&file->ftLastWriteTime, &localtime) &&
386         ((t = convert_time(localtime)) != 0) &&
387 #else
388         /*
389          * But this code "works" ...
390          */
391         ((t = convert_time(file->ftLastWriteTime)) != 0) &&
392 #endif
393         ((ctimebuf = sys_ctime(&t)) != NULL))
394       {
395         memcpy(cptr, &ctimebuf[4], 7);
396         now = time(NULL);
397         if (now - t > (365. / 2.0) * 86400.)
398           {
399             /* more than 6 months */
400             cptr[7] = ' ';
401             memcpy(&cptr[8], &ctimebuf[20], 4);
402           } else {
403             /* less than 6 months */
404             memcpy(&cptr[7], &ctimebuf[11], 5);
405           }
406         cptr += 12;
407         *cptr++ = ' ';
408       }
409   }
410   if (add_newline)
411     {
412       sprintf(cptr, "%s\n", file->cFileName);
413     }
414   else
415     {
416       strcpy(cptr, file->cFileName);
417     }
418 }
419
420
421 DEFUN ("mswindows-insert-directory", Fmswindows_insert_directory, 2, 4, 0, /*
422 Insert directory listing for FILE, formatted according to SWITCHES.
423 Leaves point after the inserted text.
424 SWITCHES may be a string of options, or a list of strings.
425 Optional third arg WILDCARD means treat FILE as shell wildcard.
426 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
427 switches do not contain `d', so that a full listing is expected.
428 */
429        (file, switches, wildcard, full_directory_p))
430 {
431   Lisp_Object           result, handler, wildpat, fns, basename;
432   char                  *filename;
433   char                  *switchstr;
434   int                   len, nfiles, i;
435   int                   hide_system, hide_dot, reverse, display_size;
436   WIN32_FIND_DATA       *files, **sorted_files;
437   enum mswindows_sortby sort_by;
438   char                  fmtbuf[MAXNAMLEN+100];  /* larger than necessary */
439   struct gcpro          gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
440
441   result = Qnil;
442   wildpat = Qnil;
443   fns = Qnil;
444   basename = Qnil;
445   GCPRO5(result, file, wildpat, fns, basename);
446   sorted_files = NULL;
447   switchstr = NULL;
448   hide_system = 1;
449   hide_dot = 1;
450   display_size = 0;
451   reverse = 0;
452   sort_by = (mswindows_ls_sort_case_insensitive
453              ? MSWINDOWS_SORT_BY_NAME_NOCASE
454              : MSWINDOWS_SORT_BY_NAME);
455   nfiles = 0;
456   while (1)
457     {
458       handler = Ffind_file_name_handler (file, Qmswindows_insert_directory);
459       if (!NILP(handler))
460         {
461           result = call5(handler, Qmswindows_insert_directory, file, switches,
462                          wildcard, full_directory_p);
463           break;
464         }
465       CHECK_STRING (file);
466       if (!NILP(switches))
467         {
468           char  *cptr;
469
470           CHECK_STRING (switches);
471           switchstr = XSTRING_DATA(switches);
472           for (cptr = switchstr; *cptr; ++cptr)
473             {
474               switch (*cptr)
475                 {
476                 case 'A':
477                   hide_dot = 0;
478                   break;
479                 case 'a':
480                   hide_system = 0;
481                   hide_dot = 0;
482                   break;
483                 case 'r':
484                   reverse = 1;
485                   break;
486                 case 's':
487                   display_size = 1;
488                   break;
489                 case 'S':
490                   sort_by = MSWINDOWS_SORT_BY_SIZE;
491                   break;
492                 case 't':
493                   sort_by = MSWINDOWS_SORT_BY_MOD_DATE;
494                   break;
495                 }
496             }
497         }
498
499       /*
500        * Sometimes we get ".../foo* /" as FILE (without the space).
501        * While the shell and `ls' don't mind, we certainly do,
502        * because it makes us think there is no wildcard, only a
503        * directory name.
504        */
505       if (!NILP(Fstring_match(build_string("[[?*]"), file, Qnil, Qnil)))
506         {
507           wildcard = Qt;
508           filename = XSTRING_DATA(file);
509           len = strlen(filename);
510           if (len > 0 && (filename[len - 1] == '\\' ||
511                           filename[len - 1] == '/'))
512             {
513               filename[len - 1] = '\0';
514             }
515           file = build_string(filename);
516         }
517       if (!NILP(wildcard))
518         {
519           Lisp_Object   newfile;
520
521           basename = Ffile_name_nondirectory(file);
522           fns = intern("wildcard-to-regexp");
523           wildpat = call1(fns, basename);
524           newfile = Ffile_name_directory(file);
525           if (NILP(newfile))
526             {
527               /* Ffile_name_directory() can GC */
528               newfile = Ffile_name_directory(Fexpand_file_name(file, Qnil));
529             }
530           file = newfile;
531         }
532       if (!NILP(wildcard) || !NILP(full_directory_p))
533         {
534           CHECK_STRING(file);
535           if (!NILP(wildpat))
536             {
537               CHECK_STRING(wildpat);
538             }
539
540           files = mswindows_get_files(XSTRING_DATA(file), FALSE, wildpat,
541                                       hide_dot, hide_system, &nfiles);
542           if (files == NULL || nfiles == 0)
543             {
544               break;
545             }
546         }
547       else
548         {
549           files = mswindows_get_files(XSTRING_DATA(file), TRUE, wildpat,
550                                       hide_dot, hide_system, &nfiles);
551         }
552       if ((sorted_files = xmalloc(nfiles * sizeof(WIN32_FIND_DATA *)))
553           == NULL)
554         {
555           break;
556         }
557       for (i = 0; i < nfiles; ++i)
558         {
559           sorted_files[i] = &files[i];
560         }
561       if (nfiles > 1)
562         {
563           mswindows_sort_files(sorted_files, nfiles, sort_by, reverse);
564         }
565       if (!NILP(wildcard) || !NILP(full_directory_p))
566         {
567           /*
568            * By using doubles, we can handle files up to 2^53 bytes in
569            * size (IEEE doubles have 53 bits of resolution).  However,
570            * as we divide by 1024 (or 2^10), the total size is
571            * accurate up to 2^(53+10) --> 2^63 bytes.
572            *
573            * Hopefully, we won't have to handle these file sizes anytime
574            * soon.
575            */
576           double                total_size, file_size, block_size;
577
578           if ((block_size = mswindows_ls_round_file_size) <= 0)
579           {
580               block_size = 0;
581           }
582           total_size = 0;
583           for (i = 0; i < nfiles; ++i)
584             {
585               file_size =
586                 sorted_files[i]->nFileSizeHigh * (double)UINT_MAX +
587                 sorted_files[i]->nFileSizeLow;
588               if (block_size > 0)
589               {
590                   /*
591                    * Round file_size up to the next nearest block size.
592                    */
593                   file_size =
594                       floor((file_size + block_size - 1) / block_size)
595                       * block_size;
596               }
597               /* Here, we round to the nearest 1K */
598               total_size += floor((file_size + 512.) / 1024.);
599             }
600           sprintf(fmtbuf,
601 #if INDENT_LISTING
602                   /* ANSI C compilers auto-concatenate adjacent strings */
603                   "  "
604 #endif
605                   "total %.0f\n", total_size);
606           buffer_insert1(current_buffer, build_string(fmtbuf));
607         }
608       for (i = 0; i < nfiles; ++i)
609         {
610           mswindows_format_file(sorted_files[i], fmtbuf, display_size, TRUE);
611           buffer_insert1(current_buffer, build_string(fmtbuf));
612         }
613       break;
614     }
615   if (sorted_files)
616     {
617       xfree(sorted_files);
618     }
619   UNGCPRO;
620   return (result);
621 }
622
623
624 \f
625 /************************************************************************/
626 /*                            initialization                            */
627 /************************************************************************/
628
629 void
630 syms_of_dired_mswindows (void)
631 {
632   defsymbol (&Qmswindows_insert_directory, "mswindows-insert-directory");
633
634   DEFSUBR (Fmswindows_insert_directory);
635 }
636
637
638 void
639 vars_of_dired_mswindows (void)
640 {
641   DEFVAR_BOOL ("mswindows-ls-sort-case-insensitive", &mswindows_ls_sort_case_insensitive /*
642 *Non-nil means filenames are sorted in a case-insensitive fashion.
643 Nil means filenames are sorted in a case-sensitive fashion, just like Unix.
644 */ );
645   mswindows_ls_sort_case_insensitive = 1;
646
647   DEFVAR_INT ("mswindows-ls-round-file-size", &mswindows_ls_round_file_size /*
648 *If non-zero, file sizes are rounded in terms of this block size when
649 the file totals are being calculated.  This is useful for getting a more
650 accurate estimate of allocated disk space.  Note that this only affects
651 the total size calculation; the individual displayed file sizes are not
652 changed.  This block size should also be a power of 2 (but this is not
653 enforced), as filesystem block (cluster) sizes are typically powers-of-2.
654 */ );
655   /*
656    * Here, we choose 4096 because it's the cluster size for both FAT32
657    * and NTFS (?).  This is probably much too small for people using
658    * plain FAT, but, hopefully, plain FAT will go away someday.
659    *
660    * We should allow something like a alist here, to make the size
661    * dependent on the drive letter, etc..
662    */
663   mswindows_ls_round_file_size = 4096;
664 }