(g2-UU+5B73): Add `=decomposition@hanyo-denshi'.
[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 "sysdir.h"
79 #include "sysproc.h"
80 #include "sysfile.h"
81
82 #include <time.h>
83
84 #include <winsock.h>            /* To make nt.h happy */
85 #include "nt.h"         /* For prototypes */
86
87 #if ROUND_FILE_SIZES > 0
88 #include <math.h>               /* for floor() */
89 #endif
90
91
92 static int mswindows_ls_sort_case_insensitive;
93 static Fixnum mswindows_ls_round_file_size;
94
95 Lisp_Object             Qmswindows_insert_directory;
96
97 extern Lisp_Object      Vmswindows_downcase_file_names; /* in device-msw.c */
98
99
100
101 enum mswindows_sortby {
102   MSWINDOWS_SORT_BY_NAME,
103   MSWINDOWS_SORT_BY_NAME_NOCASE,
104   MSWINDOWS_SORT_BY_MOD_DATE,
105   MSWINDOWS_SORT_BY_SIZE
106 };
107
108
109 static enum mswindows_sortby    mswindows_sort_method;
110 static int                      mswindows_reverse_sort;
111
112
113 #define CMPDWORDS(t1a, t1b, t2a, t2b) \
114 (((t1a) == (t2a)) ? (((t1b) == (t2b)) ? 0 : (((t1b) < (t2b)) ? -1 : 1)) \
115  : (((t1a) < (t2a)) ? -1 : 1))
116
117
118 static int
119 mswindows_ls_sort_fcn (const void *elem1, const void *elem2)
120 {
121   WIN32_FIND_DATA               *e1, *e2;
122   int                           status;
123
124   e1 = *(WIN32_FIND_DATA **)elem1;
125   e2 = *(WIN32_FIND_DATA **)elem2;
126   switch (mswindows_sort_method)
127     {
128     case MSWINDOWS_SORT_BY_NAME:
129       status = strcmp(e1->cFileName, e2->cFileName);
130       break;
131     case MSWINDOWS_SORT_BY_NAME_NOCASE:
132       status = _stricmp(e1->cFileName, e2->cFileName);
133       break;
134     case MSWINDOWS_SORT_BY_MOD_DATE:
135       status = CMPDWORDS(e1->ftLastWriteTime.dwHighDateTime,
136                          e1->ftLastWriteTime.dwLowDateTime,
137                          e2->ftLastWriteTime.dwHighDateTime,
138                          e2->ftLastWriteTime.dwLowDateTime);
139       break;
140     case MSWINDOWS_SORT_BY_SIZE:
141       status = CMPDWORDS(e1->nFileSizeHigh, e1->nFileSizeLow,
142                          e2->nFileSizeHigh, e2->nFileSizeLow);
143       break;
144     default:
145       status = 0;
146       break;
147     }
148   if (mswindows_reverse_sort)
149     {
150       status = -status;
151     }
152   return (status);
153 }
154
155
156 static void
157 mswindows_sort_files (WIN32_FIND_DATA **files, int nfiles,
158                       enum mswindows_sortby sort_by, int reverse)
159 {
160   mswindows_sort_method = sort_by;
161   mswindows_reverse_sort = reverse;
162   qsort(files, nfiles, sizeof(WIN32_FIND_DATA *), mswindows_ls_sort_fcn);
163 }
164
165
166 static WIN32_FIND_DATA *
167 mswindows_get_files (char *dirfile, int nowild, Lisp_Object pattern,
168                      int hide_dot, int hide_system, int *nfiles)
169 {
170   WIN32_FIND_DATA               *files;
171   int                           array_size;
172   struct re_pattern_buffer      *bufp = NULL;
173   int                           findex, len;
174   char                          win32pattern[MAXNAMLEN+3];
175   HANDLE                        fh;
176   int                           errm;
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, Qnil, 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        * xemacs_stat(), & friends, because xemacs_stat() is VERY expensive in
213        * terms of time.  Hence, we take the time to write complicated
214        * Win32-specific code, instead of simple Unix-style stuff.
215        */
216       findex = 0;
217       fh = INVALID_HANDLE_VALUE;
218       errm = SetErrorMode (SEM_FAILCRITICALERRORS
219                            | SEM_NOOPENFILEERRORBOX);
220
221       while (1)
222         {
223           int           len;
224           char  *filename;
225           int           result;
226
227           if (fh == INVALID_HANDLE_VALUE)
228             {
229               fh = FindFirstFile(win32pattern, &files[findex]);
230               if (fh == INVALID_HANDLE_VALUE)
231                 {
232                   SetErrorMode (errm);
233                   report_file_error ("Opening directory",
234                                      list1(build_string(dirfile)));
235                 }
236             }
237           else
238             {
239               if (!FindNextFile(fh, &files[findex]))
240                 {
241                   if (GetLastError() == ERROR_NO_MORE_FILES)
242                     {
243                       break;
244                     }
245                   FindClose(fh);
246                   SetErrorMode (errm);
247                   report_file_error ("Reading directory",
248                                      list1(build_string(dirfile)));
249                 }
250             }
251
252           filename = files[findex].cFileName;
253           if (!NILP(Vmswindows_downcase_file_names))
254           {
255               strlwr(filename);
256           }
257           len = strlen(filename);
258           result = (NILP(pattern)
259                     || (0 <= re_search (bufp, filename, 
260                                         len, 0, len, 0)));
261           if (result)
262             {
263               if ( ! (filename[0] == '.' &&
264                       ((hide_system && (filename[1] == '\0' ||
265                                         (filename[1] == '.' &&
266                                          filename[2] == '\0'))) ||
267                        hide_dot)))
268                 {
269                   if (++findex >= array_size)
270                     {
271                       array_size = findex * 2;
272                       files = xrealloc(files,
273                                        array_size * sizeof(WIN32_FIND_DATA));
274                     }
275                 }
276             }
277         }
278       if (fh != INVALID_HANDLE_VALUE)
279         {
280           FindClose (fh);
281         }
282       *nfiles = findex;
283       break;
284     }
285
286   SetErrorMode (errm);
287   return (files);
288 }
289
290
291 static void
292 mswindows_format_file (WIN32_FIND_DATA *file, char *buf, int display_size,
293                        int add_newline)
294 {
295   char                  *cptr;
296   int                   len;
297   Lisp_Object           luser;
298   double                file_size;
299
300   len = strlen(file->cFileName);
301   file_size =
302     file->nFileSizeHigh * (double)UINT_MAX + file->nFileSizeLow;
303   cptr = buf;
304 #if INDENT_LISTING
305   *cptr++ = ' ';
306   *cptr++ = ' ';
307 #endif
308   if (display_size)
309     {
310       sprintf(cptr, "%6d ", (int)((file_size + 1023.) / 1024.));
311       cptr += 7;
312     }
313   if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
314     {
315       *cptr++ = 'd';
316     } else {
317       *cptr++ = '-';
318     }
319   cptr[0] = cptr[3] = cptr[6] = 'r';
320   if (file->dwFileAttributes & FILE_ATTRIBUTE_READONLY)
321     {
322       cptr[1] = cptr[4] = cptr[7] = '-';
323     } else {
324       cptr[1] = cptr[4] = cptr[7] = 'w';
325     }
326   if ((file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
327       (len > 4 &&
328        (_stricmp(&file->cFileName[len - 4], ".exe") == 0
329         || _stricmp(&file->cFileName[len - 4], ".com") == 0
330         || _stricmp(&file->cFileName[len - 4], ".bat") == 0
331 #if 0
332         || _stricmp(&file->cFileName[len - 4], ".pif") == 0
333 #endif
334         )))
335     {
336       cptr[2] = cptr[5] = cptr[8] = 'x';
337     } else {
338       cptr[2] = cptr[5] = cptr[8] = '-';
339     }
340   cptr += 9;
341   if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
342     {
343       strcpy(cptr, "   2 ");
344     } else {
345       strcpy(cptr, "   1 ");
346     }
347   cptr += 5;
348   luser = Fuser_login_name(Qnil);
349   if (!STRINGP(luser))
350     {
351       sprintf(cptr, "%-9d", 0);
352     } else {
353       char              *str;
354
355       str = XSTRING_DATA(luser);
356       sprintf(cptr, "%-8s ", str);
357     }
358   while (*cptr)
359     {
360       ++cptr;
361     }
362   sprintf(cptr, "%-8d ", getgid());
363   cptr += 9;
364   if (file_size > 99999999.0)
365     {
366       file_size = (file_size + 1023.0) / 1024.;
367       if (file_size > 999999.0)
368         {
369           sprintf(cptr, "%6.0fMB ", (file_size + 1023.0) / 1024.);
370         } else {
371           sprintf(cptr, "%6.0fKB ", file_size);
372         }
373     } else {
374       sprintf(cptr, "%8.0f ", file_size);
375     }
376   while (*cptr)
377     {
378       ++cptr;
379     }
380   {
381     time_t              t, now;
382     char                *ctimebuf;
383     extern char         *sys_ctime(const time_t *t);    /* in nt.c */
384
385     if (
386 #if 0
387         /*
388          * This doesn't work.
389          * This code should be correct ...
390          */
391         FileTimeToLocalFileTime(&file->ftLastWriteTime, &localtime) &&
392         ((t = convert_time(localtime)) != 0) &&
393 #else
394         /*
395          * But this code "works" ...
396          */
397         ((t = convert_time(file->ftLastWriteTime)) != 0) &&
398 #endif
399         ((ctimebuf = sys_ctime(&t)) != NULL))
400       {
401         memcpy(cptr, &ctimebuf[4], 7);
402         now = time(NULL);
403         if (now - t > (365. / 2.0) * 86400.)
404           {
405             /* more than 6 months */
406             cptr[7] = ' ';
407             memcpy(&cptr[8], &ctimebuf[20], 4);
408           } else {
409             /* less than 6 months */
410             memcpy(&cptr[7], &ctimebuf[11], 5);
411           }
412         cptr += 12;
413         *cptr++ = ' ';
414       }
415   }
416   if (add_newline)
417     {
418       sprintf(cptr, "%s\n", file->cFileName);
419     }
420   else
421     {
422       strcpy(cptr, file->cFileName);
423     }
424 }
425
426
427 DEFUN ("mswindows-insert-directory", Fmswindows_insert_directory, 2, 4, 0, /*
428 Insert directory listing for FILE, formatted according to SWITCHES.
429 Leaves point after the inserted text.
430 SWITCHES may be a string of options, or a list of strings.
431 Optional third arg WILDCARD means treat FILE as shell wildcard.
432 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
433 switches do not contain `d', so that a full listing is expected.
434 */
435        (file, switches, wildcard, full_directory_p))
436 {
437   Lisp_Object           result, handler, wildpat, fns, basename;
438   char                  *switchstr;
439   int                   nfiles, i;
440   int                   hide_system, hide_dot, reverse, display_size;
441   WIN32_FIND_DATA       *files, **sorted_files;
442   enum mswindows_sortby sort_by;
443   char                  fmtbuf[MAXNAMLEN+100];  /* larger than necessary */
444   struct gcpro          gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
445
446   result = Qnil;
447   wildpat = Qnil;
448   fns = Qnil;
449   basename = Qnil;
450   GCPRO5(result, file, wildpat, fns, basename);
451   sorted_files = NULL;
452   switchstr = NULL;
453   hide_system = 1;
454   hide_dot = 1;
455   display_size = 0;
456   reverse = 0;
457   sort_by = (mswindows_ls_sort_case_insensitive
458              ? MSWINDOWS_SORT_BY_NAME_NOCASE
459              : MSWINDOWS_SORT_BY_NAME);
460   nfiles = 0;
461   while (1)
462     {
463       handler = Ffind_file_name_handler (file, Qmswindows_insert_directory);
464       if (!NILP(handler))
465         {
466           result = call5(handler, Qmswindows_insert_directory, file, switches,
467                          wildcard, full_directory_p);
468           break;
469         }
470       CHECK_STRING (file);
471       if (!NILP(switches))
472         {
473           char  *cptr;
474
475           CHECK_STRING (switches);
476           switchstr = XSTRING_DATA(switches);
477           for (cptr = switchstr; *cptr; ++cptr)
478             {
479               switch (*cptr)
480                 {
481                 case 'A':
482                   hide_dot = 0;
483                   break;
484                 case 'a':
485                   hide_system = 0;
486                   hide_dot = 0;
487                   break;
488                 case 'r':
489                   reverse = 1;
490                   break;
491                 case 's':
492                   display_size = 1;
493                   break;
494                 case 'S':
495                   sort_by = MSWINDOWS_SORT_BY_SIZE;
496                   break;
497                 case 't':
498                   sort_by = MSWINDOWS_SORT_BY_MOD_DATE;
499                   break;
500                 }
501             }
502         }
503
504       if (!NILP(wildcard))
505         {
506           Lisp_Object   newfile;
507
508           file = Fdirectory_file_name (file);
509           basename = Ffile_name_nondirectory(file);
510           fns = intern("wildcard-to-regexp");
511           wildpat = call1(fns, basename);
512           newfile = Ffile_name_directory(file);
513           if (NILP(newfile))
514             {
515               /* Ffile_name_directory() can GC */
516               newfile = Ffile_name_directory(Fexpand_file_name(file, Qnil));
517             }
518           file = newfile;
519         }
520       if (!NILP(wildcard) || !NILP(full_directory_p))
521         {
522           CHECK_STRING(file);
523           if (!NILP(wildpat))
524             {
525               CHECK_STRING(wildpat);
526             }
527
528           files = mswindows_get_files(XSTRING_DATA(file), FALSE, wildpat,
529                                       hide_dot, hide_system, &nfiles);
530           if (files == NULL || nfiles == 0)
531             {
532               break;
533             }
534         }
535       else
536         {
537           files = mswindows_get_files(XSTRING_DATA(file), TRUE, wildpat,
538                                       hide_dot, hide_system, &nfiles);
539         }
540       if ((sorted_files = xmalloc(nfiles * sizeof(WIN32_FIND_DATA *)))
541           == NULL)
542         {
543           break;
544         }
545       for (i = 0; i < nfiles; ++i)
546         {
547           sorted_files[i] = &files[i];
548         }
549       if (nfiles > 1)
550         {
551           mswindows_sort_files(sorted_files, nfiles, sort_by, reverse);
552         }
553       if (!NILP(wildcard) || !NILP(full_directory_p))
554         {
555           /*
556            * By using doubles, we can handle files up to 2^53 bytes in
557            * size (IEEE doubles have 53 bits of resolution).  However,
558            * as we divide by 1024 (or 2^10), the total size is
559            * accurate up to 2^(53+10) --> 2^63 bytes.
560            *
561            * Hopefully, we won't have to handle these file sizes anytime
562            * soon.
563            */
564           double                total_size, file_size, block_size;
565
566           if ((block_size = mswindows_ls_round_file_size) <= 0)
567           {
568               block_size = 0;
569           }
570           total_size = 0;
571           for (i = 0; i < nfiles; ++i)
572             {
573               file_size =
574                 sorted_files[i]->nFileSizeHigh * (double)UINT_MAX +
575                 sorted_files[i]->nFileSizeLow;
576               if (block_size > 0)
577               {
578                   /*
579                    * Round file_size up to the next nearest block size.
580                    */
581                   file_size =
582                       floor((file_size + block_size - 1) / block_size)
583                       * block_size;
584               }
585               /* Here, we round to the nearest 1K */
586               total_size += floor((file_size + 512.) / 1024.);
587             }
588           sprintf(fmtbuf,
589 #if INDENT_LISTING
590                   /* ANSI C compilers auto-concatenate adjacent strings */
591                   "  "
592 #endif
593                   "total %.0f\n", total_size);
594           buffer_insert1(current_buffer, build_string(fmtbuf));
595         }
596       for (i = 0; i < nfiles; ++i)
597         {
598           mswindows_format_file(sorted_files[i], fmtbuf, display_size, TRUE);
599           buffer_insert1(current_buffer, build_string(fmtbuf));
600         }
601       break;
602     }
603   if (sorted_files)
604     {
605       xfree(sorted_files);
606     }
607   UNGCPRO;
608   return (result);
609 }
610
611
612 \f
613 /************************************************************************/
614 /*                            initialization                            */
615 /************************************************************************/
616
617 void
618 syms_of_dired_mswindows (void)
619 {
620   defsymbol (&Qmswindows_insert_directory, "mswindows-insert-directory");
621
622   DEFSUBR (Fmswindows_insert_directory);
623 }
624
625
626 void
627 vars_of_dired_mswindows (void)
628 {
629   DEFVAR_BOOL ("mswindows-ls-sort-case-insensitive", &mswindows_ls_sort_case_insensitive /*
630 *Non-nil means filenames are sorted in a case-insensitive fashion.
631 Nil means filenames are sorted in a case-sensitive fashion, just like Unix.
632 */ );
633   mswindows_ls_sort_case_insensitive = 1;
634
635   DEFVAR_INT ("mswindows-ls-round-file-size", &mswindows_ls_round_file_size /*
636 *If non-zero, file sizes are rounded in terms of this block size when
637 the file totals are being calculated.  This is useful for getting a more
638 accurate estimate of allocated disk space.  Note that this only affects
639 the total size calculation; the individual displayed file sizes are not
640 changed.  This block size should also be a power of 2 (but this is not
641 enforced), as filesystem block (cluster) sizes are typically powers-of-2.
642 */ );
643   /*
644    * Here, we choose 4096 because it's the cluster size for both FAT32
645    * and NTFS (?).  This is probably much too small for people using
646    * plain FAT, but, hopefully, plain FAT will go away someday.
647    *
648    * We should allow something like a alist here, to make the size
649    * dependent on the drive letter, etc..
650    */
651   mswindows_ls_round_file_size = 4096;
652 }