Subversion Repositories SvarDOS

Rev

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