Subversion Repositories SvarDOS

Rev

Rev 1991 | Rev 2190 | 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
 
542 mateuszvis 146
/* parse an attr list like "Ar-hS" and fill bitfield into attrfilter_may and attrfilter_must.
147
 * /AHS   -> adds S and H to mandatory attribs ("must")
148
 * /A-S   -> removes S from allowed attribs ("may")
149
 * returns non-zero on error. */
150
static int dir_parse_attr_list(const char *arg, unsigned char *attrfilter_may, unsigned char *attrfilter_must) {
151
  for (; *arg != 0; arg++) {
152
    unsigned char curattr;
153
    char not;
154
    if (*arg == '-') {
155
      not = 1;
156
      arg++;
157
    } else {
158
      not = 0;
159
    }
160
    switch (*arg) {
161
      case 'd':
162
      case 'D':
163
        curattr = DOS_ATTR_DIR;
164
        break;
165
      case 'r':
166
      case 'R':
167
        curattr = DOS_ATTR_RO;
168
        break;
169
      case 'a':
170
      case 'A':
171
        curattr = DOS_ATTR_ARC;
172
        break;
173
      case 'h':
174
      case 'H':
175
        curattr = DOS_ATTR_HID;
176
        break;
177
      case 's':
178
      case 'S':
179
        curattr = DOS_ATTR_SYS;
180
        break;
181
      default:
182
        return(-1);
183
    }
184
    /* update res bitfield */
185
    if (not) {
186
      *attrfilter_may &= ~curattr;
187
    } else {
188
      *attrfilter_must |= curattr;
189
    }
190
  }
191
  return(0);
192
}
193
 
194
 
1716 mateusz.vi 195
/* compare attributes in a DTA node to mandatory and optional attributes. returns 1 on match, 0 otherwise */
196
static int filter_attribs(const struct DTA *dta, unsigned char attrfilter_must, unsigned char attrfilter_may) {
197
  /* if mandatory attribs are requested, filter them now */
198
  if ((attrfilter_must & dta->attr) != attrfilter_must) return(0);
199
 
200
  /* if file contains attributes that are not allowed -> skip */
201
  if ((~attrfilter_may & dta->attr) != 0) return(0);
202
 
203
  return(1);
204
}
205
 
206
 
1719 mateusz.vi 207
static struct {
208
  struct TINYDTA far *dtabuf_root;
209
  char order[8]; /* GNESD values (ucase = lower first ; lcase = higher first) */
1739 mateusz.vi 210
  unsigned char sortownia[256]; /* collation table (used for NLS-aware sorts) */
1719 mateusz.vi 211
} glob_sortcmp_dat;
1716 mateusz.vi 212
 
1719 mateusz.vi 213
 
214
/* translates an order string like "GNE-S" into values fed into the order[]
215
 * table of glob_sortcmp_dat. returns 0 on success, non-zero otherwise. */
1724 mateusz.vi 216
static int dir_process_order_directive(const char *ordstring) {
1719 mateusz.vi 217
  const char *gnesd = "gnesd"; /* must be lower case */
218
  int ordi, orderi = 0, i;
219
 
220
  /* tabula rasa */
221
  glob_sortcmp_dat.order[0] = 0;
222
 
1721 mateusz.vi 223
  /* /O alone is a short hand for /OGN */
224
  if (*ordstring == 0) {
225
    glob_sortcmp_dat.order[0] = 'G';
226
    glob_sortcmp_dat.order[1] = 'N';
227
    glob_sortcmp_dat.order[2] = 0;
228
  }
229
 
1726 mateusz.vi 230
  /* stupid MSDOS compatibility ("DIR /O:GNE") */
231
  if (*ordstring == ':') ordstring++;
232
 
1719 mateusz.vi 233
  /* parsing */
234
  for (ordi = 0; ordstring[ordi] != 0; ordi++) {
235
    if (ordstring[ordi] == '-') {
236
      if ((ordstring[ordi + 1] == '-') || (ordstring[ordi + 1] == 0)) return(-1);
237
      continue;
238
    }
239
    if (orderi == sizeof(glob_sortcmp_dat.order)) return(-1);
240
 
241
    for (i = 0; gnesd[i] != 0; i++) {
242
      if ((ordstring[ordi] | 32) == gnesd[i]) { /* | 32 is lcase-ing the char */
243
        if ((ordi > 0) && (ordstring[ordi - 1] == '-')) {
244
          glob_sortcmp_dat.order[orderi] = gnesd[i];
245
        } else {
246
          glob_sortcmp_dat.order[orderi] = gnesd[i] ^ 32;
247
        }
248
        orderi++;
249
        break;
250
      }
251
    }
252
    if (gnesd[i] == 0) return(-1);
253
  }
254
 
255
  return(0);
256
}
257
 
258
 
259
static int sortcmp(const void *dtaid1, const void *dtaid2) {
260
  struct TINYDTA far *dta1 = &(glob_sortcmp_dat.dtabuf_root[*((unsigned short *)dtaid1)]);
261
  struct TINYDTA far *dta2 = &(glob_sortcmp_dat.dtabuf_root[*((unsigned short *)dtaid2)]);
262
  char *ordconf = glob_sortcmp_dat.order;
263
 
264
  /* debug stuff
265
  {
266
    int i;
267
    printf("%lu vs %lu | ", dta1->size, dta2->size);
268
    for (i = 0; dta1->fname[i] != 0; i++) printf("%c", dta1->fname[i]);
269
    printf(" vs ");
270
    for (i = 0; dta2->fname[i] != 0; i++) printf("%c", dta2->fname[i]);
271
    printf("\n");
272
  } */
273
 
274
  for (;;) {
275
    int r = -1;
276
    if (*ordconf & 32) r = 1;
277
 
278
    switch (*ordconf | 32) {
279
      case 'g': /* sort by type (directories first, then files) */
280
        if ((dta1->time_sec2 & DOS_ATTR_DIR) > (dta2->time_sec2 & DOS_ATTR_DIR)) return(0 - r);
281
        if ((dta1->time_sec2 & DOS_ATTR_DIR) < (dta2->time_sec2 & DOS_ATTR_DIR)) return(r);
282
        break;
283
      case ' ': /* default (last resort) sort: by name */
284
      case 'e': /* sort by extension */
285
      case 'n': /* sort by filename */
286
      {
287
        const char far *f1 = dta1->fname;
288
        const char far *f2 = dta2->fname;
289
        int i, limit = 12;
290
        /* special handling for '.' and '..' entries */
291
        if ((f1[0] == '.') && (f2[0] != '.')) return(0 - r);
292
        if ((f2[0] == '.') && (f1[0] != '.')) return(r);
293
 
294
        if ((*ordconf | 32) == 'e') {
295
          /* fast-forward to extension or end of filename */
296
          while ((*f1 != 0) && (*f1 != '.')) f1++;
297
          while ((*f2 != 0) && (*f2 != '.')) f2++;
298
          limit = 4; /* TINYDTA structs are not nul-terminated */
299
        }
300
        /* cmp */
301
        for (i = 0; i < limit; i++) {
1739 mateusz.vi 302
          if ((glob_sortcmp_dat.sortownia[(unsigned char)(*f1)]) < (glob_sortcmp_dat.sortownia[(unsigned char)(*f2)])) return(0 - r);
303
          if ((glob_sortcmp_dat.sortownia[(unsigned char)(*f1)]) > (glob_sortcmp_dat.sortownia[(unsigned char)(*f2)])) return(r);
1719 mateusz.vi 304
          if (*f1 == 0) break;
305
          f1++;
306
          f2++;
307
        }
308
      }
309
        break;
310
      case 's': /* sort by size */
311
        if (dta1->size > dta2->size) return(r);
312
        if (dta1->size < dta2->size) return(0 - r);
313
        break;
314
      case 'd': /* sort by date */
315
        if (dta1->date_yr < dta2->date_yr) return(0 - r);
316
        if (dta1->date_yr > dta2->date_yr) return(r);
317
        if (dta1->date_mo < dta2->date_mo) return(0 - r);
318
        if (dta1->date_mo > dta2->date_mo) return(r);
319
        if (dta1->date_dy < dta2->date_dy) return(0 - r);
320
        if (dta1->date_dy > dta2->date_dy) return(r);
321
        if (dta1->time_hour < dta2->time_hour) return(0 - r);
322
        if (dta1->time_hour > dta2->time_hour) return(r);
323
        if (dta1->time_min < dta2->time_min) return(0 - r);
324
        if (dta1->time_min > dta2->time_min) return(r);
325
        break;
326
    }
327
 
328
    if (*ordconf == 0) break;
329
    ordconf++;
330
  }
331
 
332
  return(0);
333
}
334
 
335
 
542 mateuszvis 336
#define DIR_ATTR_DEFAULT (DOS_ATTR_RO | DOS_ATTR_DIR | DOS_ATTR_ARC)
337
 
1724 mateusz.vi 338
struct dirrequest {
339
  unsigned char attrfilter_may;
340
  unsigned char attrfilter_must;
341
  const char *filespecptr;
420 mateuszvis 342
 
396 mateuszvis 343
  #define DIR_FLAG_PAUSE  1
344
  #define DIR_FLAG_RECUR  4
420 mateuszvis 345
  #define DIR_FLAG_LCASE  8
1719 mateusz.vi 346
  #define DIR_FLAG_SORT  16
1724 mateusz.vi 347
  unsigned char flags;
368 mateuszvis 348
 
420 mateuszvis 349
  #define DIR_OUTPUT_NORM 1
350
  #define DIR_OUTPUT_WIDE 2
351
  #define DIR_OUTPUT_BARE 3
1724 mateusz.vi 352
  unsigned char format;
353
};
420 mateuszvis 354
 
1719 mateusz.vi 355
 
1724 mateusz.vi 356
static int dir_parse_cmdline(struct dirrequest *req, const char **argv) {
357
  for (; *argv != NULL; argv++) {
358
    if (*argv[0] == '/') {
359
      const char *arg = *argv + 1;
396 mateuszvis 360
      char neg = 0;
361
      /* detect negations and get actual argument */
542 mateuszvis 362
      if (*arg == '-') {
363
        neg = 1;
364
        arg++;
365
      }
396 mateuszvis 366
      /* */
542 mateuszvis 367
      switch (*arg) {
396 mateuszvis 368
        case 'a':
369
        case 'A':
542 mateuszvis 370
          arg++;
371
          /* preset defaults */
1724 mateusz.vi 372
          req->attrfilter_may = DIR_ATTR_DEFAULT;
373
          req->attrfilter_must = 0;
542 mateuszvis 374
          /* /-A only allowed without further parameters (used to cancel possible previous /Asmth) */
375
          if (neg) {
376
            if (*arg != 0) {
377
              nls_outputnl_err(0, 2); /* invalid switch */
1724 mateusz.vi 378
              return(-1);
542 mateuszvis 379
            }
380
          } else {
1085 mateusz.vi 381
            /* skip colon if present */
382
            if (*arg == ':') arg++;
542 mateuszvis 383
            /* start with "allow everything" */
1724 mateusz.vi 384
            req->attrfilter_may = (DOS_ATTR_ARC | DOS_ATTR_DIR | DOS_ATTR_HID | DOS_ATTR_SYS | DOS_ATTR_RO);
385
            if (dir_parse_attr_list(arg, &(req->attrfilter_may), &(req->attrfilter_must)) != 0) {
542 mateuszvis 386
              nls_outputnl_err(0, 3); /* invalid parameter format */
1724 mateusz.vi 387
              return(-1);
542 mateuszvis 388
            }
389
          }
396 mateuszvis 390
          break;
399 mateuszvis 391
        case 'b':
392
        case 'B':
1724 mateusz.vi 393
          req->format = DIR_OUTPUT_BARE;
399 mateuszvis 394
          break;
421 mateuszvis 395
        case 'l':
396
        case 'L':
1724 mateusz.vi 397
          req->flags |= DIR_FLAG_LCASE;
420 mateuszvis 398
          break;
421 mateuszvis 399
        case 'o':
400
        case 'O':
1720 mateusz.vi 401
          if (neg) {
1724 mateusz.vi 402
            req->flags &= (0xff ^ DIR_FLAG_SORT);
1720 mateusz.vi 403
            break;
404
          }
1724 mateusz.vi 405
          if (dir_process_order_directive(arg+1) != 0) {
1719 mateusz.vi 406
            nls_output_err(0, 3); /* invalid parameter format */
407
            output(": ");
408
            outputnl(arg);
1724 mateusz.vi 409
            return(-1);
1719 mateusz.vi 410
          }
1724 mateusz.vi 411
          req->flags |= DIR_FLAG_SORT;
421 mateuszvis 412
          break;
396 mateuszvis 413
        case 'p':
414
        case 'P':
1724 mateusz.vi 415
          req->flags |= DIR_FLAG_PAUSE;
416
          if (neg) req->flags &= (0xff ^ DIR_FLAG_PAUSE);
396 mateuszvis 417
          break;
421 mateuszvis 418
        case 's':
419
        case 'S':
420
          /* TODO */
421
          outputnl("/S NOT IMPLEMENTED YET");
1724 mateusz.vi 422
          return(-1);
420 mateuszvis 423
          break;
421 mateuszvis 424
        case 'w':
425
        case 'W':
1724 mateusz.vi 426
          req->format = DIR_OUTPUT_WIDE;
421 mateuszvis 427
          break;
393 mateuszvis 428
        default:
542 mateuszvis 429
          nls_outputnl_err(0, 2); /* invalid switch */
1724 mateusz.vi 430
          return(-1);
393 mateuszvis 431
      }
432
    } else {  /* filespec */
1724 mateusz.vi 433
      if (req->filespecptr != NULL) {
542 mateuszvis 434
        nls_outputnl_err(0, 4); /* too many parameters */
1724 mateusz.vi 435
        return(-1);
393 mateuszvis 436
      }
1724 mateusz.vi 437
      req->filespecptr = *argv;
393 mateuszvis 438
    }
439
  }
368 mateuszvis 440
 
1724 mateusz.vi 441
  return(0);
442
}
393 mateuszvis 443
 
1724 mateusz.vi 444
 
445
static enum cmd_result cmd_dir(struct cmd_funcparam *p) {
446
  struct DTA *dta = (void *)0x80; /* set DTA to its default location at 80h in PSP */
447
  struct TINYDTA far *dtabuf = NULL; /* used to buffer results when sorting is enabled */
448
  unsigned short dtabufcount = 0;
449
  unsigned short i;
450
  unsigned short availrows;  /* counter of available rows on display (used for /P) */
451
  unsigned short screenw = screen_getwidth();
452
  unsigned short wcols = screenw / WCOLWIDTH; /* number of columns in wide mode */
453
  unsigned char wcolcount;
454
  struct {
455
    struct nls_patterns nls;
456
    char buff64[64];
457
    char path[128];
458
    unsigned short orderidx[65535 / sizeof(struct TINYDTA)];
459
  } *buf = (void *)(p->BUFFER);
460
  unsigned long summary_fcount = 0;
461
  unsigned long summary_totsz = 0;
462
  unsigned char drv = 0;
463
  struct dirrequest req;
464
 
465
  /* make sure there's no risk of buffer overflow */
466
  if (sizeof(buf) > p->BUFFERSZ) {
467
    outputnl("INTERNAL MEM ERROR IN " __FILE__);
468
    return(CMD_FAIL);
469
  }
470
 
471
  if (cmd_ishlp(p)) {
472
    nls_outputnl(37,0); /* "Displays a list of files and subdirectories in a directory" */
473
    outputnl("");
474
    nls_outputnl(37,1); /* "DIR [drive:][path][filename] [/P] [/W] [/A[:]attributes] [/O[[:]sortorder]] [/S] [/B] [/L]" */
475
    outputnl("");
476
    nls_outputnl(37,2); /* "/P Pauses after each screenful of information" */
477
    nls_outputnl(37,3); /* "/W Uses wide list format" */
478
    outputnl("");
479
    nls_outputnl(37,4); /* "/A Displays files with specified attributes:" */
480
    nls_outputnl(37,5); /* "    D Directories            R Read-only files        H Hidden files" */
481
    nls_outputnl(37,6); /* "    A Ready for archiving    S System files           - prefix meaning "not"" */
482
    outputnl("");
483
    nls_outputnl(37,7); /* "/O List files in sorted order:" */
484
    nls_outputnl(37,8); /* "    N by name                S by size                E by extension" */
485
    nls_outputnl(37,9); /* "    D by date                G group dirs first       - prefix to reverse order" */
486
    outputnl("");
487
    nls_outputnl(37,10); /* "/S Displays files in specified directory and all subdirectories" */
488
    nls_outputnl(37,11); /* "/B Uses bare format (no heading information or summary)" */
489
    nls_outputnl(37,12); /* "/L Uses lowercases" */
490
    return(CMD_OK);
491
  }
492
 
1739 mateusz.vi 493
  /* zero out glob_sortcmp_dat and init the collation table */
494
  bzero(&glob_sortcmp_dat, sizeof(glob_sortcmp_dat));
495
  for (i = 0; i < 256; i++) {
496
    glob_sortcmp_dat.sortownia[i] = i;
497
    /* sorting should be case-insensitive */
1740 mateusz.vi 498
    if ((i >= 'A') && (i <= 'Z')) glob_sortcmp_dat.sortownia[i] |= 32;
1739 mateusz.vi 499
  }
500
 
1743 mateusz.vi 501
  /* try to replace (or complement) my naive collation table with an NLS-aware
1744 mateusz.vi 502
   * version provided by the kernel (or NLSFUNC)
1745 mateusz.vi 503
   * see https://github.com/SvarDOS/bugz/issues/68 for some thoughts */
504
  {
1743 mateusz.vi 505
    _Packed struct nlsseqtab {
506
      unsigned char id;
507
      unsigned short taboff;
508
      unsigned short tabseg;
509
    } collat;
510
    void *colptr = &collat;
511
    unsigned char errflag = 1;
512
    _asm {
513
      push ax
514
      push bx
515
      push cx
516
      push dx
517
      push di
518
      push es
519
 
520
      mov ax, 0x6506  /* DOS 3.3+ - Get collating sequence table */
521
      mov bx, 0xffff  /* code page, FFFFh = "current" */
522
      mov cx, 5       /* size of buffer at ES:DI */
523
      mov dx, 0xffff  /* country id, FFFFh = "current" */
524
      push ds
525
      pop es          /* ES:DI = address of buffer for the 5-bytes struct */
526
      mov di, colptr
527
      int 0x21
528
      jc FAIL
529
      xor al, al
530
      mov errflag, al
531
      FAIL:
532
 
533
      pop es
534
      pop di
535
      pop dx
536
      pop cx
537
      pop bx
538
      pop ax
539
    }
540
 
541
    if ((errflag == 0) && (collat.id == 6)) {
542
      unsigned char far *ptr = MK_FP(collat.tabseg, collat.taboff);
543
      unsigned short count = *(unsigned short far *)ptr;
1745 mateusz.vi 544
#ifdef DIR_DUMPNLSCOLLATE
545
      printf("NLS AT %04X:%04X (%u elements)\n", collat.tabseg, collat.taboff, count);
546
#endif
1743 mateusz.vi 547
      if (count <= 256) { /* you never know */
548
        ptr += 2; /* skip the count header */
549
        for (i = 0; i < count; i++) {
550
          glob_sortcmp_dat.sortownia[i] = ptr[i];
1745 mateusz.vi 551
#ifdef DIR_DUMPNLSCOLLATE
552
          printf(" %03u", ptr[i]);
553
          if ((i & 15) == 15) {
554
            printf("\n");
555
            fflush(stdout);
556
          }
557
#endif
1743 mateusz.vi 558
        }
559
      }
560
    }
561
  }
562
 
1724 mateusz.vi 563
  i = nls_getpatterns(&(buf->nls));
564
  if (i != 0) nls_outputnl_doserr(i);
565
 
566
  /* disable usage of thousands separator on narrow screens */
567
  if (screenw < 80) buf->nls.thousep[0] = 0;
568
 
1725 mateusz.vi 569
  /*** PARSING COMMAND LINE STARTS *******************************************/
570
 
571
  /* init req with some defaults */
572
  bzero(&req, sizeof(req));
573
  req.attrfilter_may = DIR_ATTR_DEFAULT;
574
  req.format = DIR_OUTPUT_NORM;
575
 
576
  /* process DIRCMD first (so it can be overidden by user's cmdline) */
577
  {
578
  const char far *dircmd = env_lookup_val(p->env_seg, "DIRCMD");
579
  if (dircmd != NULL) {
580
    const char *argvptrs[32];
581
    cmd_explode(buf->buff64, dircmd, argvptrs);
582
    if ((dir_parse_cmdline(&req, argvptrs) != 0) || (req.filespecptr != NULL)) {
583
      nls_output(255, 10);/* bad environment */
584
      output(" - ");
585
      outputnl("DIRCMD");
586
      return(CMD_FAIL);
587
    }
588
  }
589
  }
590
 
591
  /* parse user's command line */
1724 mateusz.vi 592
  if (dir_parse_cmdline(&req, p->argv) != 0) return(CMD_FAIL);
593
 
1725 mateusz.vi 594
  /* if no filespec provided, then it's about the current directory */
595
  if (req.filespecptr == NULL) req.filespecptr = ".";
596
 
597
  /*** PARSING COMMAND LINE DONE *********************************************/
598
 
599
 
528 mateuszvis 600
  availrows = screen_getheight() - 2;
601
 
417 mateuszvis 602
  /* special case: "DIR drive:" (truename() fails on "C:" under MS-DOS 6.0) */
1724 mateusz.vi 603
  if ((req.filespecptr[0] != 0) && (req.filespecptr[1] == ':') && (req.filespecptr[2] == 0)) {
604
    if ((req.filespecptr[0] >= 'a') && (req.filespecptr[0] <= 'z')) {
605
      buf->path[0] = req.filespecptr[0] - ('a' - 1);
417 mateuszvis 606
    } else {
1724 mateusz.vi 607
      buf->path[0] = req.filespecptr[0] - ('A' - 1);
399 mateuszvis 608
    }
1717 mateusz.vi 609
    i = curpathfordrv(buf->path, buf->path[0]);
417 mateuszvis 610
  } else {
1724 mateusz.vi 611
    i = file_truename(req.filespecptr, buf->path);
399 mateuszvis 612
  }
417 mateuszvis 613
  if (i != 0) {
538 mateuszvis 614
    nls_outputnl_doserr(i);
533 mateuszvis 615
    return(CMD_FAIL);
417 mateuszvis 616
  }
393 mateuszvis 617
 
1724 mateusz.vi 618
  if (req.format != DIR_OUTPUT_BARE) {
1717 mateusz.vi 619
    drv = buf->path[0];
399 mateuszvis 620
    if (drv >= 'a') {
621
      drv -= 'a';
622
    } else {
623
      drv -= 'A';
624
    }
1717 mateusz.vi 625
    cmd_vol_internal(drv, buf->buff64);
626
    sprintf(buf->buff64, svarlang_str(37,20)/*"Directory of %s"*/, buf->path);
399 mateuszvis 627
    /* trim at first '?', if any */
1717 mateusz.vi 628
    for (i = 0; buf->buff64[i] != 0; i++) if (buf->buff64[i] == '?') buf->buff64[i] = 0;
629
    outputnl(buf->buff64);
399 mateuszvis 630
    outputnl("");
528 mateuszvis 631
    availrows -= 3;
399 mateuszvis 632
  }
633
 
417 mateuszvis 634
  /* if dir: append a backslash (also get its len) */
1717 mateusz.vi 635
  i = path_appendbkslash_if_dir(buf->path);
393 mateuszvis 636
 
417 mateuszvis 637
  /* if ends with a \ then append ????????.??? */
1717 mateusz.vi 638
  if (buf->path[i - 1] == '\\') strcat(buf->path, "????????.???");
393 mateuszvis 639
 
542 mateuszvis 640
  /* ask DOS for list of files, but only with allowed attribs */
1724 mateusz.vi 641
  i = findfirst(dta, buf->path, req.attrfilter_may);
417 mateuszvis 642
  if (i != 0) {
538 mateuszvis 643
    nls_outputnl_doserr(i);
533 mateuszvis 644
    return(CMD_FAIL);
417 mateuszvis 645
  }
646
 
1716 mateusz.vi 647
  /* if sorting is involved, then let's buffer all results (and sort them) */
1724 mateusz.vi 648
  if (req.flags & DIR_FLAG_SORT) {
1716 mateusz.vi 649
    /* allocate a memory buffer - try several sizes until one succeeds */
1717 mateusz.vi 650
    const unsigned short memsz[] = {65500, 32000, 16000, 8000, 4000, 2000, 1000, 0};
1716 mateusz.vi 651
    unsigned short max_dta_bufcount = 0;
652
    for (i = 0; memsz[i] != 0; i++) {
653
      dtabuf = _fmalloc(memsz[i]);
654
      if (dtabuf != NULL) break;
655
    }
656
 
657
    if (dtabuf == NULL) {
658
      nls_outputnl_doserr(8); /* out of memory */
659
      return(CMD_FAIL);
660
    }
661
 
662
    /* remember the address so I can free it afterwards */
1719 mateusz.vi 663
    glob_sortcmp_dat.dtabuf_root = dtabuf;
1716 mateusz.vi 664
 
665
    /* compute the amount of DTAs I can buffer */
1717 mateusz.vi 666
    max_dta_bufcount = memsz[i] / sizeof(struct TINYDTA);
1719 mateusz.vi 667
    /* printf("max_dta_bufcount = %u\n", max_dta_bufcount); */
1716 mateusz.vi 668
 
669
    do {
670
      /* filter out files with uninteresting attributes */
1724 mateusz.vi 671
      if (filter_attribs(dta, req.attrfilter_must, req.attrfilter_may) == 0) continue;
1716 mateusz.vi 672
 
1719 mateusz.vi 673
      /* normalize "size" of directories to zero because kernel returns garbage
674
       * sizes for directories which might confuse the sorting routine later */
675
      if (dta->attr & DOS_ATTR_DIR) dta->size = 0;
676
 
1716 mateusz.vi 677
      _fmemcpy(&(dtabuf[dtabufcount]), ((char *)dta) + 22, sizeof(struct TINYDTA));
678
 
679
      /* save attribs in sec field, otherwise zero it (this field is not
680
       * displayed and dropping the attr field saves 2 bytes per entry) */
681
      dtabuf[dtabufcount++].time_sec2 = (dta->attr & 31);
682
 
683
      /* do I have any space left? */
684
      if (dtabufcount == max_dta_bufcount) {
1719 mateusz.vi 685
        //TODO some kind of user notification might be nice here
1716 mateusz.vi 686
        //outputnl("TOO MANY ENTRIES FOR SORTING! LIST IS UNSORTED");
687
        break;
688
      }
689
 
690
    } while (findnext(dta) == 0);
691
 
1742 mateusz.vi 692
    /* no match? kein gluck! (this can happen when filtering attribs with /A:xxx
693
     * because while findfirst() succeeds, all entries can be rejected) */
694
    if (dtabufcount == 0) {
695
      nls_outputnl_doserr(2); /* "File not found" */
696
      return(CMD_FAIL);
697
    }
698
 
1716 mateusz.vi 699
    /* sort the list - the tricky part is that my array is a far address while
1719 mateusz.vi 700
     * qsort works only with near pointers, so I have to use an ugly (and
701
     * global) auxiliary table */
702
    for (i = 0; i < dtabufcount; i++) buf->orderidx[i] = i;
703
    qsort(buf->orderidx, dtabufcount, 2, &sortcmp);
1716 mateusz.vi 704
 
1719 mateusz.vi 705
    /* preload first entry (last from orderidx, since entries are sorted in reverse) */
1716 mateusz.vi 706
    dtabufcount--;
1719 mateusz.vi 707
    _fmemcpy(((unsigned char *)dta) + 22, &(dtabuf[buf->orderidx[dtabufcount]]), sizeof(struct TINYDTA));
708
    dta->attr = dtabuf[buf->orderidx[dtabufcount]].time_sec2; /* restore attr from the abused time_sec2 field */
1716 mateusz.vi 709
  }
710
 
420 mateuszvis 711
  wcolcount = 0; /* may be used for columns counting with wide mode */
396 mateuszvis 712
 
1716 mateusz.vi 713
  for (;;) {
542 mateuszvis 714
 
1716 mateusz.vi 715
    /* filter out attributes (skip if entry comes from buffer, then it was already veted) */
1741 mateusz.vi 716
    if (filter_attribs(dta, req.attrfilter_must, req.attrfilter_may) == 0) goto NEXT_ENTRY;
542 mateuszvis 717
 
718
    /* turn string lcase (/L) */
1724 mateusz.vi 719
    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 720
 
424 mateuszvis 721
    summary_fcount++;
722
    if ((dta->attr & DOS_ATTR_DIR) == 0) summary_totsz += dta->size;
723
 
1724 mateusz.vi 724
    switch (req.format) {
420 mateuszvis 725
      case DIR_OUTPUT_NORM:
726
        /* print fname-space-extension (unless it's "." or "..", then print as-is) */
727
        if (dta->fname[0] == '.') {
728
          output(dta->fname);
729
          i = strlen(dta->fname);
730
          while (i++ < 12) output(" ");
731
        } else {
1717 mateusz.vi 732
          file_fname2fcb(buf->buff64, dta->fname);
733
          memmove(buf->buff64 + 9, buf->buff64 + 8, 4);
734
          buf->buff64[8] = ' ';
735
          output(buf->buff64);
420 mateuszvis 736
        }
737
        output(" ");
1960 mateusz.vi 738
        /* either <DIR> or right aligned 13 or 10 chars byte size, depending
739
         * on the presence of a thousands delimiter (max 2'000'000'000) */
740
        {
741
          unsigned short szlen = 10 + (strlen(buf->nls.thousep) * 3);
742
          memset(buf->buff64, ' ', 16);
743
          if (dta->attr & DOS_ATTR_DIR) {
744
            strcpy(buf->buff64 + szlen, svarlang_str(37,21));
745
          } else {
746
            nls_format_number(buf->buff64 + 12, dta->size, &(buf->nls));
747
          }
748
          output(buf->buff64 + strlen(buf->buff64) - szlen);
420 mateuszvis 749
        }
1960 mateusz.vi 750
        /* one spaces and NLS DATE */
1717 mateusz.vi 751
        buf->buff64[0] = ' ';
1141 mateusz.vi 752
        if (screenw >= 80) {
1960 mateusz.vi 753
          nls_format_date(buf->buff64 + 1, dta->date_yr + 1980, dta->date_mo, dta->date_dy, &(buf->nls));
1141 mateusz.vi 754
        } else {
1960 mateusz.vi 755
          nls_format_date(buf->buff64 + 1, (dta->date_yr + 80) % 100, dta->date_mo, dta->date_dy, &(buf->nls));
1141 mateusz.vi 756
        }
1717 mateusz.vi 757
        output(buf->buff64);
420 mateuszvis 758
 
759
        /* one space and NLS TIME */
1717 mateusz.vi 760
        nls_format_time(buf->buff64 + 1, dta->time_hour, dta->time_min, 0xff, &(buf->nls));
761
        outputnl(buf->buff64);
420 mateuszvis 762
        break;
763
 
764
      case DIR_OUTPUT_WIDE: /* display in columns of 12 chars per item */
765
        i = strlen(dta->fname);
766
        if (dta->attr & DOS_ATTR_DIR) {
767
          i += 2;
768
          output("[");
769
          output(dta->fname);
770
          output("]");
771
        } else {
772
          output(dta->fname);
773
        }
774
        while (i++ < WCOLWIDTH) output(" ");
775
        if (++wcolcount == wcols) {
776
          wcolcount = 0;
777
          outputnl("");
528 mateuszvis 778
        } else {
779
          availrows++; /* wide mode is the only one that does not write one line per file */
420 mateuszvis 780
        }
781
        break;
782
 
783
      case DIR_OUTPUT_BARE:
784
        outputnl(dta->fname);
785
        break;
396 mateuszvis 786
    }
368 mateuszvis 787
 
1724 mateusz.vi 788
    if (req.flags & DIR_FLAG_PAUSE) dir_pagination(&availrows);
420 mateuszvis 789
 
1741 mateusz.vi 790
    NEXT_ENTRY:
1716 mateusz.vi 791
    /* take next entry, either from buf or disk */
792
    if (dtabufcount > 0) {
793
      dtabufcount--;
1719 mateusz.vi 794
      _fmemcpy(((unsigned char *)dta) + 22, &(dtabuf[buf->orderidx[dtabufcount]]), sizeof(struct TINYDTA));
795
      dta->attr = dtabuf[buf->orderidx[dtabufcount]].time_sec2; /* restore attr from the abused time_sec2 field */
1716 mateusz.vi 796
    } else {
797
      if (findnext(dta) != 0) break;
798
    }
420 mateuszvis 799
 
1716 mateusz.vi 800
  }
801
 
528 mateuszvis 802
  if (wcolcount != 0) {
803
    outputnl(""); /* in wide mode make sure to end on a clear row */
1724 mateusz.vi 804
    if (req.flags & DIR_FLAG_PAUSE) dir_pagination(&availrows);
528 mateuszvis 805
  }
420 mateuszvis 806
 
424 mateuszvis 807
  /* print out summary (unless bare output mode) */
1724 mateusz.vi 808
  if (req.format != DIR_OUTPUT_BARE) {
424 mateuszvis 809
    unsigned short alignpos;
1960 mateusz.vi 810
    unsigned short uint32maxlen = 14; /* 13 is the max len of a 32 bit number with thousand separators (4'000'000'000) */
1141 mateusz.vi 811
    if (screenw < 80) uint32maxlen = 10;
1960 mateusz.vi 812
 
813
    /* x file(s) (maximum of files in a FAT-32 directory is 65'535) */
814
    memset(buf->buff64, ' ', 8);
815
    i = nls_format_number(buf->buff64 + 8, summary_fcount, &(buf->nls));
816
    alignpos = sprintf(buf->buff64 + 8 + i, " %s ", svarlang_str(37,22)/*"file(s)"*/);
1717 mateusz.vi 817
    output(buf->buff64 + i);
424 mateuszvis 818
    /* xxxx bytes */
1960 mateusz.vi 819
    memset(buf->buff64, ' ', 14);
1717 mateusz.vi 820
    i = nls_format_number(buf->buff64 + uint32maxlen, summary_totsz, &(buf->nls));
821
    output(buf->buff64 + i + 1);
424 mateuszvis 822
    output(" ");
990 mateusz.vi 823
    nls_outputnl(37,23); /* "bytes" */
1724 mateusz.vi 824
    if (req.flags & DIR_FLAG_PAUSE) dir_pagination(&availrows);
1960 mateusz.vi 825
 
424 mateuszvis 826
    /* xxxx bytes free */
827
    i = cmd_dir_df(&summary_totsz, drv);
538 mateuszvis 828
    if (i != 0) nls_outputnl_doserr(i);
1960 mateusz.vi 829
    alignpos += 8 + uint32maxlen;
1717 mateusz.vi 830
    memset(buf->buff64, ' ', alignpos); /* align the freebytes value to same column as totbytes */
831
    i = nls_format_number(buf->buff64 + alignpos, summary_totsz, &(buf->nls));
832
    output(buf->buff64 + i + 1);
424 mateuszvis 833
    output(" ");
990 mateusz.vi 834
    nls_outputnl(37,24); /* "bytes free" */
1724 mateusz.vi 835
    if (req.flags & DIR_FLAG_PAUSE) dir_pagination(&availrows);
424 mateuszvis 836
  }
837
 
1716 mateusz.vi 838
  /* free the buffer memory (if used) */
1719 mateusz.vi 839
  if (glob_sortcmp_dat.dtabuf_root != NULL) _ffree(glob_sortcmp_dat.dtabuf_root);
1716 mateusz.vi 840
 
533 mateuszvis 841
  return(CMD_OK);
368 mateuszvis 842
}