Subversion Repositories SvarDOS

Rev

Rev 2193 | Rev 2196 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
421 mateuszvis 1
/* This file is part of the SvarCOM project and is published under the terms
2
 * of the MIT license.
3
 *
1716 mateusz.vi 4
 * Copyright (C) 2021-2024 Mateusz Viste
421 mateuszvis 5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a
7
 * copy of this software and associated documentation files (the "Software"),
8
 * to deal in the Software without restriction, including without limitation
9
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10
 * and/or sell copies of the Software, and to permit persons to whom the
11
 * Software is furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
 * DEALINGS IN THE SOFTWARE.
23
 */
24
 
368 mateuszvis 25
/*
26
 * dir
27
 *
28
 * Displays a list of files and subdirectories in a directory.
29
 *
30
 * DIR [drive:][path][filename] [/P] [/W] [/A[:]attributes] [/O[[:]sortorder]] [/S] [/B] [/L]
31
 *
32
 * /P Pauses after each screenful of information.
33
 * /W Uses wide list format.
34
 *
35
 * /A Displays file with specified attributes:
36
 *     D Directories           R Read-only files     H Hidden files
37
 *     A Ready for archiving   S System files        - prefix meaning "not"
38
 *
39
 * /O List files in sorted order:
40
 *     N by name            S by size              E by extension
41
 *     D by date            G group dirs first     - prefix to reverse order
42
 *
43
 * /S Displays files in specified directory and all subdirectories.
44
 * /B Uses bare format (no heading information or summary)
45
 * /L Uses lowercases
2189 mateusz.vi 46
 *
47
 * about /S - recursive DIR on specified (or current) path and subdirectories:
48
 * prerequisite: some sort of mechanism that works as a stack pile of DTAs
49
 *
50
 * /S logic:
51
 * 1. do a FindFirst on current directory
52
 * 2. do FindNext calls in a loop, if a DIR entry is encountered, remember its
53
 *    name and put a copy of the current DTA on stack, then continue the
54
 *    listing without further interruption
55
 * 3. if a new DIR was discovered, do a FindFirst on it and jmp to 2.
56
 *    if no DIR found, then go to 4.
57
 * 4. look on the stack for a DTA.
58
 *    if any found, pop it and jmp to 2.
59
 *    otherwise job is done, exit.
368 mateuszvis 60
 */
61
 
396 mateuszvis 62
/* NOTE: /A attributes are matched in an exclusive way, ie. only files with
63
 *       the specified attributes are matched. This is different from how DOS
64
 *       itself matches attributes hence DIR cannot rely on the attributes
65
 *       filter within FindFirst.
66
 *
67
 * NOTE: Multiple /A are not supported - only the last one is significant.
68
 */
69
 
420 mateuszvis 70
 
1991 mateusz.vi 71
/* width of a column in wide mode output: 15 chars is the MINIMUM because
72
 * directories are enclosed in [BRACKETS] and they may have an extension, too.
73
 * Hence "[12345678.123]" is the longest we can get. Plus a delimiter space. */
74
#define WCOLWIDTH 15
424 mateuszvis 75
 
1991 mateusz.vi 76
 
1716 mateusz.vi 77
/* a "tiny" DTA is a DTA that is stripped from bytes that are not needed for
78
 * DIR operations */
79
_Packed struct TINYDTA {
80
/*  char reserved[21];
81
  unsigned char attr; */
82
  unsigned short time_sec2:5;
83
  unsigned short time_min:6;
84
  unsigned short time_hour:5;
85
  unsigned short date_dy:5;
86
  unsigned short date_mo:4;
87
  unsigned short date_yr:7;
88
  unsigned long size;
89
/*  char fname[13]; */
90
  char fname[12];
91
};
92
 
93
 
424 mateuszvis 94
/* fills freebytes with free bytes for drv (A=0, B=1, etc)
95
 * returns DOS ERR code on failure */
96
static unsigned short cmd_dir_df(unsigned long *freebytes, unsigned char drv) {
97
  unsigned short res = 0;
98
  unsigned short sects_per_clust = 0, avail_clusts = 0, bytes_per_sect = 0;
99
 
100
  _asm {
101
    push ax
102
    push bx
103
    push cx
104
    push dx
105
 
106
    mov ah, 0x36  /* DOS 2+ -- Get Disk Free Space */
107
    mov dl, [drv] /* A=1, B=2, etc (0 = DEFAULT DRIVE) */
108
    inc dl
109
    int 0x21      /* AX=sects_per_clust, BX=avail_clusts, CX=bytes_per_sect, DX=tot_clusters */
110
    cmp ax, 0xffff /* AX=0xffff on error (invalid drive) */
111
    jne COMPUTEDF
112
    mov [res], 0x0f /* fill res with DOS error code 15 ("invalid drive") */
113
    jmp DONE
114
 
115
    COMPUTEDF:
116
    /* freebytes = AX * BX * CX */
117
    mov [sects_per_clust], ax
118
    mov [avail_clusts], bx
119
    mov [bytes_per_sect], cx
120
 
121
    DONE:
122
    pop dx
123
    pop cx
124
    pop bx
125
    pop ax
126
  }
127
 
128
  /* multiple steps to avoid uint16 overflow */
129
  *freebytes = sects_per_clust;
130
  *freebytes *= avail_clusts;
131
  *freebytes *= bytes_per_sect;
132
 
133
  return(res);
134
}
135
 
136
 
528 mateuszvis 137
static void dir_pagination(unsigned short *availrows) {
138
  *availrows -= 1;
139
  if (*availrows == 0) {
140
    press_any_key();
141
    *availrows = screen_getheight() - 1;
142
  }
143
}
144
 
145
 
2193 mateusz.vi 146
/* add a new dirname to path, C:\XXX\*.EXE + YYY -> C:\XXX\YYY\*.EXE */
147
static void path_add(char *path, const char *dirname) {
148
  short i, ostatni = -1, slen;
149
  printf("path_add(%s,%s) -> ", path, dirname);
150
  /* find the last backslash */
151
  for (i = 0; path[i] != 0; i++) {
152
    if (path[i] == '\\') ostatni = i;
153
  }
154
  /* abort on error */
155
  if (ostatni == -1) return;
156
  /* do the trick */
157
  slen = strlen(dirname);
158
  memmove(path + ostatni + slen + 1, path + ostatni, slen + 1);
159
  memcpy(path + ostatni + 1, dirname, slen);
160
  printf("'%s'\n", path);
161
}
162
 
163
 
164
/* take back last dir from path, C:\XXX\YYY\*.EXE -> C:\XXX\*.EXE */
165
static void path_back(char *path) {
166
  short i, ostatni = -1, przedostatni = -1;
167
  /* find the two last backslashes */
168
  for (i = 0; path[i] != 0; i++) {
169
    if (path[i] == '\\') {
170
      przedostatni = ostatni;
171
      ostatni = i;
172
    }
173
  }
174
  /* abort on error */
175
  if (przedostatni == -1) return;
176
  /* do the trick */
177
  for (i = przedostatni; path[i] != 0; i++) {
178
    path[i] = path[ostatni++];
179
  }
180
}
181
 
182
 
542 mateuszvis 183
/* parse an attr list like "Ar-hS" and fill bitfield into attrfilter_may and attrfilter_must.
184
 * /AHS   -> adds S and H to mandatory attribs ("must")
185
 * /A-S   -> removes S from allowed attribs ("may")
186
 * returns non-zero on error. */
187
static int dir_parse_attr_list(const char *arg, unsigned char *attrfilter_may, unsigned char *attrfilter_must) {
188
  for (; *arg != 0; arg++) {
189
    unsigned char curattr;
190
    char not;
191
    if (*arg == '-') {
192
      not = 1;
193
      arg++;
194
    } else {
195
      not = 0;
196
    }
197
    switch (*arg) {
198
      case 'd':
199
      case 'D':
200
        curattr = DOS_ATTR_DIR;
201
        break;
202
      case 'r':
203
      case 'R':
204
        curattr = DOS_ATTR_RO;
205
        break;
206
      case 'a':
207
      case 'A':
208
        curattr = DOS_ATTR_ARC;
209
        break;
210
      case 'h':
211
      case 'H':
212
        curattr = DOS_ATTR_HID;
213
        break;
214
      case 's':
215
      case 'S':
216
        curattr = DOS_ATTR_SYS;
217
        break;
218
      default:
219
        return(-1);
220
    }
221
    /* update res bitfield */
222
    if (not) {
223
      *attrfilter_may &= ~curattr;
224
    } else {
225
      *attrfilter_must |= curattr;
226
    }
227
  }
228
  return(0);
229
}
230
 
231
 
1716 mateusz.vi 232
/* compare attributes in a DTA node to mandatory and optional attributes. returns 1 on match, 0 otherwise */
233
static int filter_attribs(const struct DTA *dta, unsigned char attrfilter_must, unsigned char attrfilter_may) {
234
  /* if mandatory attribs are requested, filter them now */
235
  if ((attrfilter_must & dta->attr) != attrfilter_must) return(0);
236
 
237
  /* if file contains attributes that are not allowed -> skip */
238
  if ((~attrfilter_may & dta->attr) != 0) return(0);
239
 
240
  return(1);
241
}
242
 
243
 
1719 mateusz.vi 244
static struct {
245
  struct TINYDTA far *dtabuf_root;
246
  char order[8]; /* GNESD values (ucase = lower first ; lcase = higher first) */
1739 mateusz.vi 247
  unsigned char sortownia[256]; /* collation table (used for NLS-aware sorts) */
1719 mateusz.vi 248
} glob_sortcmp_dat;
1716 mateusz.vi 249
 
1719 mateusz.vi 250
 
251
/* translates an order string like "GNE-S" into values fed into the order[]
252
 * table of glob_sortcmp_dat. returns 0 on success, non-zero otherwise. */
1724 mateusz.vi 253
static int dir_process_order_directive(const char *ordstring) {
1719 mateusz.vi 254
  const char *gnesd = "gnesd"; /* must be lower case */
255
  int ordi, orderi = 0, i;
256
 
257
  /* tabula rasa */
258
  glob_sortcmp_dat.order[0] = 0;
259
 
1721 mateusz.vi 260
  /* /O alone is a short hand for /OGN */
261
  if (*ordstring == 0) {
262
    glob_sortcmp_dat.order[0] = 'G';
263
    glob_sortcmp_dat.order[1] = 'N';
264
    glob_sortcmp_dat.order[2] = 0;
265
  }
266
 
1726 mateusz.vi 267
  /* stupid MSDOS compatibility ("DIR /O:GNE") */
268
  if (*ordstring == ':') ordstring++;
269
 
1719 mateusz.vi 270
  /* parsing */
271
  for (ordi = 0; ordstring[ordi] != 0; ordi++) {
272
    if (ordstring[ordi] == '-') {
273
      if ((ordstring[ordi + 1] == '-') || (ordstring[ordi + 1] == 0)) return(-1);
274
      continue;
275
    }
276
    if (orderi == sizeof(glob_sortcmp_dat.order)) return(-1);
277
 
278
    for (i = 0; gnesd[i] != 0; i++) {
279
      if ((ordstring[ordi] | 32) == gnesd[i]) { /* | 32 is lcase-ing the char */
280
        if ((ordi > 0) && (ordstring[ordi - 1] == '-')) {
281
          glob_sortcmp_dat.order[orderi] = gnesd[i];
282
        } else {
283
          glob_sortcmp_dat.order[orderi] = gnesd[i] ^ 32;
284
        }
285
        orderi++;
286
        break;
287
      }
288
    }
289
    if (gnesd[i] == 0) return(-1);
290
  }
291
 
292
  return(0);
293
}
294
 
295
 
296
static int sortcmp(const void *dtaid1, const void *dtaid2) {
297
  struct TINYDTA far *dta1 = &(glob_sortcmp_dat.dtabuf_root[*((unsigned short *)dtaid1)]);
298
  struct TINYDTA far *dta2 = &(glob_sortcmp_dat.dtabuf_root[*((unsigned short *)dtaid2)]);
299
  char *ordconf = glob_sortcmp_dat.order;
300
 
301
  /* debug stuff
302
  {
303
    int i;
304
    printf("%lu vs %lu | ", dta1->size, dta2->size);
305
    for (i = 0; dta1->fname[i] != 0; i++) printf("%c", dta1->fname[i]);
306
    printf(" vs ");
307
    for (i = 0; dta2->fname[i] != 0; i++) printf("%c", dta2->fname[i]);
308
    printf("\n");
309
  } */
310
 
311
  for (;;) {
312
    int r = -1;
313
    if (*ordconf & 32) r = 1;
314
 
315
    switch (*ordconf | 32) {
316
      case 'g': /* sort by type (directories first, then files) */
317
        if ((dta1->time_sec2 & DOS_ATTR_DIR) > (dta2->time_sec2 & DOS_ATTR_DIR)) return(0 - r);
318
        if ((dta1->time_sec2 & DOS_ATTR_DIR) < (dta2->time_sec2 & DOS_ATTR_DIR)) return(r);
319
        break;
320
      case ' ': /* default (last resort) sort: by name */
321
      case 'e': /* sort by extension */
322
      case 'n': /* sort by filename */
323
      {
324
        const char far *f1 = dta1->fname;
325
        const char far *f2 = dta2->fname;
326
        int i, limit = 12;
327
        /* special handling for '.' and '..' entries */
328
        if ((f1[0] == '.') && (f2[0] != '.')) return(0 - r);
329
        if ((f2[0] == '.') && (f1[0] != '.')) return(r);
330
 
331
        if ((*ordconf | 32) == 'e') {
332
          /* fast-forward to extension or end of filename */
333
          while ((*f1 != 0) && (*f1 != '.')) f1++;
334
          while ((*f2 != 0) && (*f2 != '.')) f2++;
335
          limit = 4; /* TINYDTA structs are not nul-terminated */
336
        }
337
        /* cmp */
338
        for (i = 0; i < limit; i++) {
1739 mateusz.vi 339
          if ((glob_sortcmp_dat.sortownia[(unsigned char)(*f1)]) < (glob_sortcmp_dat.sortownia[(unsigned char)(*f2)])) return(0 - r);
340
          if ((glob_sortcmp_dat.sortownia[(unsigned char)(*f1)]) > (glob_sortcmp_dat.sortownia[(unsigned char)(*f2)])) return(r);
1719 mateusz.vi 341
          if (*f1 == 0) break;
342
          f1++;
343
          f2++;
344
        }
345
      }
346
        break;
347
      case 's': /* sort by size */
348
        if (dta1->size > dta2->size) return(r);
349
        if (dta1->size < dta2->size) return(0 - r);
350
        break;
351
      case 'd': /* sort by date */
352
        if (dta1->date_yr < dta2->date_yr) return(0 - r);
353
        if (dta1->date_yr > dta2->date_yr) return(r);
354
        if (dta1->date_mo < dta2->date_mo) return(0 - r);
355
        if (dta1->date_mo > dta2->date_mo) return(r);
356
        if (dta1->date_dy < dta2->date_dy) return(0 - r);
357
        if (dta1->date_dy > dta2->date_dy) return(r);
358
        if (dta1->time_hour < dta2->time_hour) return(0 - r);
359
        if (dta1->time_hour > dta2->time_hour) return(r);
360
        if (dta1->time_min < dta2->time_min) return(0 - r);
361
        if (dta1->time_min > dta2->time_min) return(r);
362
        break;
363
    }
364
 
365
    if (*ordconf == 0) break;
366
    ordconf++;
367
  }
368
 
369
  return(0);
370
}
371
 
372
 
542 mateuszvis 373
#define DIR_ATTR_DEFAULT (DOS_ATTR_RO | DOS_ATTR_DIR | DOS_ATTR_ARC)
374
 
1724 mateusz.vi 375
struct dirrequest {
376
  unsigned char attrfilter_may;
377
  unsigned char attrfilter_must;
378
  const char *filespecptr;
420 mateuszvis 379
 
396 mateuszvis 380
  #define DIR_FLAG_PAUSE  1
381
  #define DIR_FLAG_RECUR  4
420 mateuszvis 382
  #define DIR_FLAG_LCASE  8
1719 mateusz.vi 383
  #define DIR_FLAG_SORT  16
1724 mateusz.vi 384
  unsigned char flags;
368 mateuszvis 385
 
420 mateuszvis 386
  #define DIR_OUTPUT_NORM 1
387
  #define DIR_OUTPUT_WIDE 2
388
  #define DIR_OUTPUT_BARE 3
1724 mateusz.vi 389
  unsigned char format;
390
};
420 mateuszvis 391
 
1719 mateusz.vi 392
 
1724 mateusz.vi 393
static int dir_parse_cmdline(struct dirrequest *req, const char **argv) {
394
  for (; *argv != NULL; argv++) {
395
    if (*argv[0] == '/') {
396
      const char *arg = *argv + 1;
396 mateuszvis 397
      char neg = 0;
398
      /* detect negations and get actual argument */
542 mateuszvis 399
      if (*arg == '-') {
400
        neg = 1;
401
        arg++;
402
      }
396 mateuszvis 403
      /* */
542 mateuszvis 404
      switch (*arg) {
396 mateuszvis 405
        case 'a':
406
        case 'A':
542 mateuszvis 407
          arg++;
408
          /* preset defaults */
1724 mateusz.vi 409
          req->attrfilter_may = DIR_ATTR_DEFAULT;
410
          req->attrfilter_must = 0;
542 mateuszvis 411
          /* /-A only allowed without further parameters (used to cancel possible previous /Asmth) */
412
          if (neg) {
413
            if (*arg != 0) {
414
              nls_outputnl_err(0, 2); /* invalid switch */
1724 mateusz.vi 415
              return(-1);
542 mateuszvis 416
            }
417
          } else {
1085 mateusz.vi 418
            /* skip colon if present */
419
            if (*arg == ':') arg++;
542 mateuszvis 420
            /* start with "allow everything" */
1724 mateusz.vi 421
            req->attrfilter_may = (DOS_ATTR_ARC | DOS_ATTR_DIR | DOS_ATTR_HID | DOS_ATTR_SYS | DOS_ATTR_RO);
422
            if (dir_parse_attr_list(arg, &(req->attrfilter_may), &(req->attrfilter_must)) != 0) {
542 mateuszvis 423
              nls_outputnl_err(0, 3); /* invalid parameter format */
1724 mateusz.vi 424
              return(-1);
542 mateuszvis 425
            }
426
          }
396 mateuszvis 427
          break;
399 mateuszvis 428
        case 'b':
429
        case 'B':
1724 mateusz.vi 430
          req->format = DIR_OUTPUT_BARE;
399 mateuszvis 431
          break;
421 mateuszvis 432
        case 'l':
433
        case 'L':
1724 mateusz.vi 434
          req->flags |= DIR_FLAG_LCASE;
420 mateuszvis 435
          break;
421 mateuszvis 436
        case 'o':
437
        case 'O':
1720 mateusz.vi 438
          if (neg) {
1724 mateusz.vi 439
            req->flags &= (0xff ^ DIR_FLAG_SORT);
1720 mateusz.vi 440
            break;
441
          }
1724 mateusz.vi 442
          if (dir_process_order_directive(arg+1) != 0) {
1719 mateusz.vi 443
            nls_output_err(0, 3); /* invalid parameter format */
444
            output(": ");
445
            outputnl(arg);
1724 mateusz.vi 446
            return(-1);
1719 mateusz.vi 447
          }
1724 mateusz.vi 448
          req->flags |= DIR_FLAG_SORT;
421 mateuszvis 449
          break;
396 mateuszvis 450
        case 'p':
451
        case 'P':
1724 mateusz.vi 452
          req->flags |= DIR_FLAG_PAUSE;
453
          if (neg) req->flags &= (0xff ^ DIR_FLAG_PAUSE);
396 mateuszvis 454
          break;
421 mateuszvis 455
        case 's':
456
        case 'S':
2193 mateusz.vi 457
          req->flags |= DIR_FLAG_RECUR;
420 mateuszvis 458
          break;
421 mateuszvis 459
        case 'w':
460
        case 'W':
1724 mateusz.vi 461
          req->format = DIR_OUTPUT_WIDE;
421 mateuszvis 462
          break;
393 mateuszvis 463
        default:
542 mateuszvis 464
          nls_outputnl_err(0, 2); /* invalid switch */
1724 mateusz.vi 465
          return(-1);
393 mateuszvis 466
      }
467
    } else {  /* filespec */
1724 mateusz.vi 468
      if (req->filespecptr != NULL) {
542 mateuszvis 469
        nls_outputnl_err(0, 4); /* too many parameters */
1724 mateusz.vi 470
        return(-1);
393 mateuszvis 471
      }
1724 mateusz.vi 472
      req->filespecptr = *argv;
393 mateuszvis 473
    }
474
  }
368 mateuszvis 475
 
1724 mateusz.vi 476
  return(0);
477
}
393 mateuszvis 478
 
1724 mateusz.vi 479
 
2193 mateusz.vi 480
#define MAX_SORTABLE_FILES 8192
481
 
1724 mateusz.vi 482
static enum cmd_result cmd_dir(struct cmd_funcparam *p) {
483
  struct DTA *dta = (void *)0x80; /* set DTA to its default location at 80h in PSP */
484
  struct TINYDTA far *dtabuf = NULL; /* used to buffer results when sorting is enabled */
485
  unsigned short dtabufcount = 0;
486
  unsigned short i;
487
  unsigned short availrows;  /* counter of available rows on display (used for /P) */
488
  unsigned short screenw = screen_getwidth();
489
  unsigned short wcols = screenw / WCOLWIDTH; /* number of columns in wide mode */
490
  unsigned char wcolcount;
491
  struct {
492
    struct nls_patterns nls;
493
    char buff64[64];
494
    char path[128];
2193 mateusz.vi 495
    struct DTA dtastack[64]; /* used for /S, max number of subdirs in DOS5 is 42 (A/B/C/...) */
496
    unsigned char dirpending; /* set if a dir has been added to dtastack */
497
    unsigned char dtastacklen;
498
    unsigned short orderidx[MAX_SORTABLE_FILES / sizeof(struct TINYDTA)];
499
  } *buf;
1724 mateusz.vi 500
  unsigned long summary_fcount = 0;
501
  unsigned long summary_totsz = 0;
502
  unsigned char drv = 0;
503
  struct dirrequest req;
504
 
505
  if (cmd_ishlp(p)) {
506
    nls_outputnl(37,0); /* "Displays a list of files and subdirectories in a directory" */
507
    outputnl("");
508
    nls_outputnl(37,1); /* "DIR [drive:][path][filename] [/P] [/W] [/A[:]attributes] [/O[[:]sortorder]] [/S] [/B] [/L]" */
509
    outputnl("");
510
    nls_outputnl(37,2); /* "/P Pauses after each screenful of information" */
511
    nls_outputnl(37,3); /* "/W Uses wide list format" */
512
    outputnl("");
513
    nls_outputnl(37,4); /* "/A Displays files with specified attributes:" */
514
    nls_outputnl(37,5); /* "    D Directories            R Read-only files        H Hidden files" */
515
    nls_outputnl(37,6); /* "    A Ready for archiving    S System files           - prefix meaning "not"" */
516
    outputnl("");
517
    nls_outputnl(37,7); /* "/O List files in sorted order:" */
518
    nls_outputnl(37,8); /* "    N by name                S by size                E by extension" */
519
    nls_outputnl(37,9); /* "    D by date                G group dirs first       - prefix to reverse order" */
520
    outputnl("");
521
    nls_outputnl(37,10); /* "/S Displays files in specified directory and all subdirectories" */
522
    nls_outputnl(37,11); /* "/B Uses bare format (no heading information or summary)" */
523
    nls_outputnl(37,12); /* "/L Uses lowercases" */
2193 mateusz.vi 524
    goto OK;
1724 mateusz.vi 525
  }
526
 
2193 mateusz.vi 527
  /* allocate buf */
528
  buf = calloc(sizeof(*buf), 1);
529
  if (buf == NULL) {
530
    nls_output_err(255, 8); /* insufficient memory */
531
    goto FAIL;
532
  }
533
 
1739 mateusz.vi 534
  /* zero out glob_sortcmp_dat and init the collation table */
535
  bzero(&glob_sortcmp_dat, sizeof(glob_sortcmp_dat));
536
  for (i = 0; i < 256; i++) {
537
    glob_sortcmp_dat.sortownia[i] = i;
538
    /* sorting should be case-insensitive */
1740 mateusz.vi 539
    if ((i >= 'A') && (i <= 'Z')) glob_sortcmp_dat.sortownia[i] |= 32;
1739 mateusz.vi 540
  }
541
 
1743 mateusz.vi 542
  /* try to replace (or complement) my naive collation table with an NLS-aware
1744 mateusz.vi 543
   * version provided by the kernel (or NLSFUNC)
1745 mateusz.vi 544
   * see https://github.com/SvarDOS/bugz/issues/68 for some thoughts */
545
  {
1743 mateusz.vi 546
    _Packed struct nlsseqtab {
547
      unsigned char id;
548
      unsigned short taboff;
549
      unsigned short tabseg;
550
    } collat;
551
    void *colptr = &collat;
552
    unsigned char errflag = 1;
553
    _asm {
554
      push ax
555
      push bx
556
      push cx
557
      push dx
558
      push di
559
      push es
560
 
561
      mov ax, 0x6506  /* DOS 3.3+ - Get collating sequence table */
562
      mov bx, 0xffff  /* code page, FFFFh = "current" */
563
      mov cx, 5       /* size of buffer at ES:DI */
564
      mov dx, 0xffff  /* country id, FFFFh = "current" */
565
      push ds
566
      pop es          /* ES:DI = address of buffer for the 5-bytes struct */
567
      mov di, colptr
568
      int 0x21
569
      jc FAIL
570
      xor al, al
571
      mov errflag, al
572
      FAIL:
573
 
574
      pop es
575
      pop di
576
      pop dx
577
      pop cx
578
      pop bx
579
      pop ax
580
    }
581
 
582
    if ((errflag == 0) && (collat.id == 6)) {
583
      unsigned char far *ptr = MK_FP(collat.tabseg, collat.taboff);
584
      unsigned short count = *(unsigned short far *)ptr;
1745 mateusz.vi 585
#ifdef DIR_DUMPNLSCOLLATE
586
      printf("NLS AT %04X:%04X (%u elements)\n", collat.tabseg, collat.taboff, count);
587
#endif
1743 mateusz.vi 588
      if (count <= 256) { /* you never know */
589
        ptr += 2; /* skip the count header */
590
        for (i = 0; i < count; i++) {
591
          glob_sortcmp_dat.sortownia[i] = ptr[i];
1745 mateusz.vi 592
#ifdef DIR_DUMPNLSCOLLATE
593
          printf(" %03u", ptr[i]);
594
          if ((i & 15) == 15) {
595
            printf("\n");
596
            fflush(stdout);
597
          }
598
#endif
1743 mateusz.vi 599
        }
600
      }
601
    }
602
  }
603
 
1724 mateusz.vi 604
  i = nls_getpatterns(&(buf->nls));
605
  if (i != 0) nls_outputnl_doserr(i);
606
 
607
  /* disable usage of thousands separator on narrow screens */
608
  if (screenw < 80) buf->nls.thousep[0] = 0;
609
 
1725 mateusz.vi 610
  /*** PARSING COMMAND LINE STARTS *******************************************/
611
 
612
  /* init req with some defaults */
613
  bzero(&req, sizeof(req));
614
  req.attrfilter_may = DIR_ATTR_DEFAULT;
615
  req.format = DIR_OUTPUT_NORM;
616
 
617
  /* process DIRCMD first (so it can be overidden by user's cmdline) */
618
  {
619
  const char far *dircmd = env_lookup_val(p->env_seg, "DIRCMD");
620
  if (dircmd != NULL) {
621
    const char *argvptrs[32];
622
    cmd_explode(buf->buff64, dircmd, argvptrs);
623
    if ((dir_parse_cmdline(&req, argvptrs) != 0) || (req.filespecptr != NULL)) {
624
      nls_output(255, 10);/* bad environment */
625
      output(" - ");
626
      outputnl("DIRCMD");
2193 mateusz.vi 627
      goto FAIL;
1725 mateusz.vi 628
    }
629
  }
630
  }
631
 
632
  /* parse user's command line */
2193 mateusz.vi 633
  if (dir_parse_cmdline(&req, p->argv) != 0) goto FAIL;
1724 mateusz.vi 634
 
2193 mateusz.vi 635
  /*** PARSING COMMAND LINE DONE *********************************************/
636
 
1725 mateusz.vi 637
  /* if no filespec provided, then it's about the current directory */
638
  if (req.filespecptr == NULL) req.filespecptr = ".";
639
 
528 mateuszvis 640
  availrows = screen_getheight() - 2;
641
 
417 mateuszvis 642
  /* special case: "DIR drive:" (truename() fails on "C:" under MS-DOS 6.0) */
1724 mateusz.vi 643
  if ((req.filespecptr[0] != 0) && (req.filespecptr[1] == ':') && (req.filespecptr[2] == 0)) {
644
    if ((req.filespecptr[0] >= 'a') && (req.filespecptr[0] <= 'z')) {
645
      buf->path[0] = req.filespecptr[0] - ('a' - 1);
417 mateuszvis 646
    } else {
1724 mateusz.vi 647
      buf->path[0] = req.filespecptr[0] - ('A' - 1);
399 mateuszvis 648
    }
1717 mateusz.vi 649
    i = curpathfordrv(buf->path, buf->path[0]);
417 mateuszvis 650
  } else {
1724 mateusz.vi 651
    i = file_truename(req.filespecptr, buf->path);
399 mateuszvis 652
  }
417 mateuszvis 653
  if (i != 0) {
538 mateuszvis 654
    nls_outputnl_doserr(i);
2193 mateusz.vi 655
    goto FAIL;
417 mateuszvis 656
  }
393 mateuszvis 657
 
1724 mateusz.vi 658
  if (req.format != DIR_OUTPUT_BARE) {
1717 mateusz.vi 659
    drv = buf->path[0];
399 mateuszvis 660
    if (drv >= 'a') {
661
      drv -= 'a';
662
    } else {
663
      drv -= 'A';
664
    }
1717 mateusz.vi 665
    cmd_vol_internal(drv, buf->buff64);
666
    sprintf(buf->buff64, svarlang_str(37,20)/*"Directory of %s"*/, buf->path);
399 mateuszvis 667
    /* trim at first '?', if any */
1717 mateusz.vi 668
    for (i = 0; buf->buff64[i] != 0; i++) if (buf->buff64[i] == '?') buf->buff64[i] = 0;
669
    outputnl(buf->buff64);
399 mateuszvis 670
    outputnl("");
528 mateuszvis 671
    availrows -= 3;
399 mateuszvis 672
  }
673
 
417 mateuszvis 674
  /* if dir: append a backslash (also get its len) */
1717 mateusz.vi 675
  i = path_appendbkslash_if_dir(buf->path);
393 mateuszvis 676
 
417 mateuszvis 677
  /* if ends with a \ then append ????????.??? */
1717 mateusz.vi 678
  if (buf->path[i - 1] == '\\') strcat(buf->path, "????????.???");
393 mateuszvis 679
 
2193 mateusz.vi 680
  NEXT_ITER: /* re-entry point for /S recursing */
681
 
682
  /* ask DOS for list of files, but only with allowed attribs (+directories, because
683
   * I need them for /S) */
684
  i = findfirst(dta, buf->path, req.attrfilter_may | DIR_FLAG_RECUR);
417 mateuszvis 685
  if (i != 0) {
538 mateuszvis 686
    nls_outputnl_doserr(i);
2193 mateusz.vi 687
    goto FAIL;
417 mateuszvis 688
  }
689
 
1716 mateusz.vi 690
  /* if sorting is involved, then let's buffer all results (and sort them) */
1724 mateusz.vi 691
  if (req.flags & DIR_FLAG_SORT) {
1716 mateusz.vi 692
    /* allocate a memory buffer - try several sizes until one succeeds */
2194 mateusz.vi 693
    unsigned short max_dta_bufcount;
694
 
695
    /* compute the amount of DTAs I can buffer */
696
    for (max_dta_bufcount = MAX_SORTABLE_FILES; max_dta_bufcount != 0; max_dta_bufcount /= 2) {
697
      dtabuf = _fmalloc(max_dta_bufcount * sizeof(struct TINYDTA));
1716 mateusz.vi 698
      if (dtabuf != NULL) break;
699
    }
2194 mateusz.vi 700
    /* printf("max_dta_bufcount = %u\n", max_dta_bufcount); */
1716 mateusz.vi 701
 
702
    if (dtabuf == NULL) {
703
      nls_outputnl_doserr(8); /* out of memory */
2193 mateusz.vi 704
      goto FAIL;
1716 mateusz.vi 705
    }
706
 
707
    /* remember the address so I can free it afterwards */
1719 mateusz.vi 708
    glob_sortcmp_dat.dtabuf_root = dtabuf;
1716 mateusz.vi 709
 
710
    do {
2193 mateusz.vi 711
      /* if /S then remember first directory encountered (but not . nor ..) */
712
      if ((req.flags & DIR_FLAG_RECUR) && (buf->dirpending == 0) && (dta->attr & DOS_ATTR_DIR) && (dta->fname[0] != '.')) {
713
        buf->dirpending = 1;
714
        memcpy(&(buf->dtastack[buf->dtastacklen]), dta, sizeof(struct DTA));
715
      }
716
 
1716 mateusz.vi 717
      /* filter out files with uninteresting attributes */
1724 mateusz.vi 718
      if (filter_attribs(dta, req.attrfilter_must, req.attrfilter_may) == 0) continue;
1716 mateusz.vi 719
 
1719 mateusz.vi 720
      /* normalize "size" of directories to zero because kernel returns garbage
721
       * sizes for directories which might confuse the sorting routine later */
722
      if (dta->attr & DOS_ATTR_DIR) dta->size = 0;
723
 
1716 mateusz.vi 724
      _fmemcpy(&(dtabuf[dtabufcount]), ((char *)dta) + 22, sizeof(struct TINYDTA));
725
 
726
      /* save attribs in sec field, otherwise zero it (this field is not
727
       * displayed and dropping the attr field saves 2 bytes per entry) */
728
      dtabuf[dtabufcount++].time_sec2 = (dta->attr & 31);
729
 
730
      /* do I have any space left? */
731
      if (dtabufcount == max_dta_bufcount) {
1719 mateusz.vi 732
        //TODO some kind of user notification might be nice here
1716 mateusz.vi 733
        //outputnl("TOO MANY ENTRIES FOR SORTING! LIST IS UNSORTED");
734
        break;
735
      }
736
 
737
    } while (findnext(dta) == 0);
738
 
1742 mateusz.vi 739
    /* no match? kein gluck! (this can happen when filtering attribs with /A:xxx
740
     * because while findfirst() succeeds, all entries can be rejected) */
741
    if (dtabufcount == 0) {
742
      nls_outputnl_doserr(2); /* "File not found" */
2193 mateusz.vi 743
      goto FAIL;
1742 mateusz.vi 744
    }
745
 
1716 mateusz.vi 746
    /* sort the list - the tricky part is that my array is a far address while
1719 mateusz.vi 747
     * qsort works only with near pointers, so I have to use an ugly (and
748
     * global) auxiliary table */
749
    for (i = 0; i < dtabufcount; i++) buf->orderidx[i] = i;
750
    qsort(buf->orderidx, dtabufcount, 2, &sortcmp);
1716 mateusz.vi 751
 
1719 mateusz.vi 752
    /* preload first entry (last from orderidx, since entries are sorted in reverse) */
1716 mateusz.vi 753
    dtabufcount--;
1719 mateusz.vi 754
    _fmemcpy(((unsigned char *)dta) + 22, &(dtabuf[buf->orderidx[dtabufcount]]), sizeof(struct TINYDTA));
755
    dta->attr = dtabuf[buf->orderidx[dtabufcount]].time_sec2; /* restore attr from the abused time_sec2 field */
1716 mateusz.vi 756
  }
757
 
420 mateuszvis 758
  wcolcount = 0; /* may be used for columns counting with wide mode */
396 mateuszvis 759
 
1716 mateusz.vi 760
  for (;;) {
542 mateuszvis 761
 
2193 mateusz.vi 762
    /* if /S then remember first directory encountered */
763
      if ((req.flags & DIR_FLAG_RECUR) && (buf->dirpending == 0) && (dta->attr & DOS_ATTR_DIR) && (dta->fname[0] != '.')) {
764
      buf->dirpending = 1;
765
      puts("GOT DIR (/S)");
766
      memcpy(&(buf->dtastack[buf->dtastacklen]), dta, sizeof(struct DTA));
767
    }
768
 
1716 mateusz.vi 769
    /* filter out attributes (skip if entry comes from buffer, then it was already veted) */
1741 mateusz.vi 770
    if (filter_attribs(dta, req.attrfilter_must, req.attrfilter_may) == 0) goto NEXT_ENTRY;
542 mateuszvis 771
 
772
    /* turn string lcase (/L) */
1724 mateusz.vi 773
    if (req.flags & DIR_FLAG_LCASE) _strlwr(dta->fname); /* OpenWatcom extension, probably does not care about NLS so results may be odd with non-A-Z characters... */
368 mateuszvis 774
 
424 mateuszvis 775
    summary_fcount++;
776
    if ((dta->attr & DOS_ATTR_DIR) == 0) summary_totsz += dta->size;
777
 
1724 mateusz.vi 778
    switch (req.format) {
420 mateuszvis 779
      case DIR_OUTPUT_NORM:
780
        /* print fname-space-extension (unless it's "." or "..", then print as-is) */
781
        if (dta->fname[0] == '.') {
782
          output(dta->fname);
783
          i = strlen(dta->fname);
784
          while (i++ < 12) output(" ");
785
        } else {
1717 mateusz.vi 786
          file_fname2fcb(buf->buff64, dta->fname);
787
          memmove(buf->buff64 + 9, buf->buff64 + 8, 4);
788
          buf->buff64[8] = ' ';
789
          output(buf->buff64);
420 mateuszvis 790
        }
791
        output(" ");
1960 mateusz.vi 792
        /* either <DIR> or right aligned 13 or 10 chars byte size, depending
793
         * on the presence of a thousands delimiter (max 2'000'000'000) */
794
        {
795
          unsigned short szlen = 10 + (strlen(buf->nls.thousep) * 3);
796
          memset(buf->buff64, ' ', 16);
797
          if (dta->attr & DOS_ATTR_DIR) {
798
            strcpy(buf->buff64 + szlen, svarlang_str(37,21));
799
          } else {
800
            nls_format_number(buf->buff64 + 12, dta->size, &(buf->nls));
801
          }
802
          output(buf->buff64 + strlen(buf->buff64) - szlen);
420 mateuszvis 803
        }
1960 mateusz.vi 804
        /* one spaces and NLS DATE */
1717 mateusz.vi 805
        buf->buff64[0] = ' ';
1141 mateusz.vi 806
        if (screenw >= 80) {
1960 mateusz.vi 807
          nls_format_date(buf->buff64 + 1, dta->date_yr + 1980, dta->date_mo, dta->date_dy, &(buf->nls));
1141 mateusz.vi 808
        } else {
1960 mateusz.vi 809
          nls_format_date(buf->buff64 + 1, (dta->date_yr + 80) % 100, dta->date_mo, dta->date_dy, &(buf->nls));
1141 mateusz.vi 810
        }
1717 mateusz.vi 811
        output(buf->buff64);
420 mateuszvis 812
 
813
        /* one space and NLS TIME */
1717 mateusz.vi 814
        nls_format_time(buf->buff64 + 1, dta->time_hour, dta->time_min, 0xff, &(buf->nls));
815
        outputnl(buf->buff64);
420 mateuszvis 816
        break;
817
 
818
      case DIR_OUTPUT_WIDE: /* display in columns of 12 chars per item */
819
        i = strlen(dta->fname);
820
        if (dta->attr & DOS_ATTR_DIR) {
821
          i += 2;
822
          output("[");
823
          output(dta->fname);
824
          output("]");
825
        } else {
826
          output(dta->fname);
827
        }
828
        while (i++ < WCOLWIDTH) output(" ");
829
        if (++wcolcount == wcols) {
830
          wcolcount = 0;
831
          outputnl("");
528 mateuszvis 832
        } else {
833
          availrows++; /* wide mode is the only one that does not write one line per file */
420 mateuszvis 834
        }
835
        break;
836
 
837
      case DIR_OUTPUT_BARE:
838
        outputnl(dta->fname);
839
        break;
396 mateuszvis 840
    }
368 mateuszvis 841
 
1724 mateusz.vi 842
    if (req.flags & DIR_FLAG_PAUSE) dir_pagination(&availrows);
420 mateuszvis 843
 
1741 mateusz.vi 844
    NEXT_ENTRY:
1716 mateusz.vi 845
    /* take next entry, either from buf or disk */
846
    if (dtabufcount > 0) {
847
      dtabufcount--;
1719 mateusz.vi 848
      _fmemcpy(((unsigned char *)dta) + 22, &(dtabuf[buf->orderidx[dtabufcount]]), sizeof(struct TINYDTA));
849
      dta->attr = dtabuf[buf->orderidx[dtabufcount]].time_sec2; /* restore attr from the abused time_sec2 field */
1716 mateusz.vi 850
    } else {
851
      if (findnext(dta) != 0) break;
852
    }
420 mateuszvis 853
 
1716 mateusz.vi 854
  }
855
 
528 mateuszvis 856
  if (wcolcount != 0) {
857
    outputnl(""); /* in wide mode make sure to end on a clear row */
1724 mateusz.vi 858
    if (req.flags & DIR_FLAG_PAUSE) dir_pagination(&availrows);
528 mateuszvis 859
  }
420 mateuszvis 860
 
424 mateuszvis 861
  /* print out summary (unless bare output mode) */
1724 mateusz.vi 862
  if (req.format != DIR_OUTPUT_BARE) {
424 mateuszvis 863
    unsigned short alignpos;
1960 mateusz.vi 864
    unsigned short uint32maxlen = 14; /* 13 is the max len of a 32 bit number with thousand separators (4'000'000'000) */
1141 mateusz.vi 865
    if (screenw < 80) uint32maxlen = 10;
1960 mateusz.vi 866
 
867
    /* x file(s) (maximum of files in a FAT-32 directory is 65'535) */
868
    memset(buf->buff64, ' ', 8);
869
    i = nls_format_number(buf->buff64 + 8, summary_fcount, &(buf->nls));
870
    alignpos = sprintf(buf->buff64 + 8 + i, " %s ", svarlang_str(37,22)/*"file(s)"*/);
1717 mateusz.vi 871
    output(buf->buff64 + i);
424 mateuszvis 872
    /* xxxx bytes */
1960 mateusz.vi 873
    memset(buf->buff64, ' ', 14);
1717 mateusz.vi 874
    i = nls_format_number(buf->buff64 + uint32maxlen, summary_totsz, &(buf->nls));
875
    output(buf->buff64 + i + 1);
424 mateuszvis 876
    output(" ");
990 mateusz.vi 877
    nls_outputnl(37,23); /* "bytes" */
1724 mateusz.vi 878
    if (req.flags & DIR_FLAG_PAUSE) dir_pagination(&availrows);
1960 mateusz.vi 879
 
424 mateuszvis 880
    /* xxxx bytes free */
881
    i = cmd_dir_df(&summary_totsz, drv);
538 mateuszvis 882
    if (i != 0) nls_outputnl_doserr(i);
1960 mateusz.vi 883
    alignpos += 8 + uint32maxlen;
1717 mateusz.vi 884
    memset(buf->buff64, ' ', alignpos); /* align the freebytes value to same column as totbytes */
885
    i = nls_format_number(buf->buff64 + alignpos, summary_totsz, &(buf->nls));
886
    output(buf->buff64 + i + 1);
424 mateuszvis 887
    output(" ");
990 mateusz.vi 888
    nls_outputnl(37,24); /* "bytes free" */
1724 mateusz.vi 889
    if (req.flags & DIR_FLAG_PAUSE) dir_pagination(&availrows);
424 mateuszvis 890
  }
891
 
2193 mateusz.vi 892
  /* /S processing */
893
  if (buf->dirpending) {
894
    buf->dirpending = 0;
895
    /* add dir to path and redo scan */
896
    printf("DIR PENDING: %s\n", buf->dtastack[buf->dtastacklen].fname);
897
    path_add(buf->path, buf->dtastack[buf->dtastacklen].fname);
898
    buf->dtastacklen++;
899
    goto NEXT_ITER;
900
  }
901
  while (buf->dtastacklen > 0) {
902
    /* rewind path one directory back, pop the next dta and do a FindNext */
903
    path_back(buf->path);
904
    buf->dtastacklen--;
905
    TRYNEXTENTRY:
906
    if (findnext(&(buf->dtastack[buf->dtastacklen])) != 0) continue;
907
    if ((buf->dtastack[buf->dtastacklen].attr & DOS_ATTR_DIR) == 0) goto TRYNEXTENTRY;
908
    /* something found -> add dir to path and redo scan */
909
    path_add(buf->path, buf->dtastack[buf->dtastacklen].fname);
910
    goto NEXT_ITER;
911
  }
912
 
1716 mateusz.vi 913
  /* free the buffer memory (if used) */
1719 mateusz.vi 914
  if (glob_sortcmp_dat.dtabuf_root != NULL) _ffree(glob_sortcmp_dat.dtabuf_root);
1716 mateusz.vi 915
 
2193 mateusz.vi 916
  FAIL:
917
  free(buf);
918
  return(CMD_FAIL);
919
 
920
  OK:
921
  free(buf);
533 mateuszvis 922
  return(CMD_OK);
368 mateuszvis 923
}