File: xdiskusage.C

package info (click to toggle)
xdiskusage 1.44-2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 180 kB
  • ctags: 117
  • sloc: cpp: 745; sh: 152; makefile: 94
file content (863 lines) | stat: -rw-r--r-- 23,635 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
// xdiskusage.C

const char* copyright = 
"xdiskusage version 1.44\n"
"Copyright (C) 2000 Bill Spitzak    spitzak@d2.com\n"
"Based on xdu by Phillip C. Dykstra\n"
"\n"
"This program is free software; you can redistribute it and/or modify "
"it under the terms of the GNU General Public License as published by "
"the Free Software Foundation; either version 2 of the License, or "
"(at your option) any later version.\n"
"\n"
"This program is distributed in the hope that it will be useful, "
"but WITHOUT ANY WARRANTY; without even the implied warranty of "
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the "
"GNU General Public License for more details.\n"
"\n"
"You should have received a copy of the GNU General Public License "
"along with this software; if not, write to the Free Software "
"Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 "
"USA.";


#if defined(__hpux)
# define DF_COMMAND "df -P"
# define DU_COMMAND "du -kx"
#elif defined(__bsdi__)
# define DF_COMMAND "df"
# define DU_COMMAND "du -x"
#elif defined(SVR4)
# define DF_COMMAND "df -k"
# define DU_COMMAND "du -kd"
#else // linux and irix
# define DF_COMMAND "df -k"
# define DU_COMMAND "du -kx"
#endif

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>

#include "panels.H"
#include <FL/fl_draw.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Menu_Button.H>
#include <FL/fl_ask.H>

typedef unsigned long ulong;

// turn number of K into user-friendly text:
const char* formatk(ulong k) {
  static char buffer[10];
  if (k >= 1024*1024) sprintf(buffer,"%.4gG",(double)k/(1024*1024));
  else if (k >= 1024) sprintf(buffer,"%.4gM",(double)k/1024);
  else sprintf(buffer,"%ldK",k);
  return buffer;
}

// Holds data read from 'df' for each disk
struct Disk {
  const char* mount;
  ulong total;
  ulong used;
  ulong avail;
  Disk* next;
};

Disk* firstdisk;

// Run 'df' and create a list of Disk structures, fill in browser:
void reload_cb(Fl_Button*, void*) {
  FILE* f = popen(DF_COMMAND, "r");
  if (!f) {
    fprintf(stderr,"Can't run df, %s\n", strerror(errno));
    exit(1);
  }
  Disk** pointer = &firstdisk;
  for (;;) {
    char buffer[1024];
    if (!fgets(buffer, 1024, f)) break;
    int n = 0; // number of words
    char* word[10]; // pointer to each word
    for (char* p = buffer; n < 10;) {
      // skip leading whitespace:
      while (*p && isspace(*p)) p++;
      if (!*p) break;
      // skip over the word:
      word[n++] = p;
      while (*p && !isspace(*p)) p++;
      if (!*p) break;
      *p++ = 0;
    }
    if (n < 5 || word[n-1][0] != '/') continue;
    // ok we found a line with a /xyz at the end:
    Disk* d = new Disk;
    d->mount = strdup(word[n-1]);
    d->total = strtol(word[n-5],0,10);
    d->used=strtol(word[n-4],0,10);
    d->avail=strtol(word[n-3],0,10);
    *pointer = d;
    d->next = 0;
    pointer = &d->next;
  }
  pclose(f);

  if (!firstdisk) {
    fl_alert("Something went wrong with df, no disks found.");
  } else {
    disk_browser->clear();
  }

  for (Disk* d = firstdisk; d; d = d->next) {
    char buf[512];
    int pct;
    ulong sum = d->used + d->avail;
    if (!sum) {
      pct = 0;
    } else {
      pct = int((d->used*100+d->used/2)/sum);
      if (!pct && d->used) pct = 1;
    }
    sprintf(buf, "@b%s\t@r%s %2d%%\n", d->mount, formatk(d->total), pct);
    disk_browser->add(buf);
  }
  disk_browser->position(0);
}

Fl_Window *copyright_window;
void copyright_cb(Fl_Button*, void*) {
  if (!copyright_window) {
    copyright_window = new Fl_Window(400,270,"Copyright");
    copyright_window->color(FL_WHITE);
    Fl_Box *b = new Fl_Box(10,0,380,270,copyright);
#ifdef FL_NORMAL_SIZE
    b->labelsize(12);
#endif
    b->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE|FL_ALIGN_WRAP);
    copyright_window->end();
  }
  copyright_window->hotspot(copyright_window);
  copyright_window->set_non_modal();
  copyright_window->show();
}

////////////////////////////////////////////////////////////////

struct Node {
  Node* child;
  Node* brother;
  const char* name;
  ulong size;
  ulong ordinal;
};

// default sizes of new windows, changed by user actions on other windows:
int window_w = 600;
int window_h = 480;
int ncols = 5;
#define MAXDEPTH 80

class Display : public Fl_Window {
  void draw();
  int handle(int);
  void resize(int,int,int,int);
  Node* root;
  Node* current_root;
  Node* parents[MAXDEPTH];
  int depth;
  int ncols;
  Fl_Menu_Button menu_button;
  Display(int w, int h, const char* l) : Fl_Window(w,h,l),
    menu_button(0,0,w,h) {}
  void draw_tree(Node* n, int column, ulong row, double scale);
  void print_tree(FILE* f, Node* n, int column, ulong row, double scale, int W, int H);
  void setroot(Node* n, int depth);
public:
  static void root_cb(Fl_Widget*, void*);
  static void out_cb(Fl_Widget*, void*);
  static void in_cb(Fl_Widget*, void*);
  static void next_cb(Fl_Widget*, void*);
  static void previous_cb(Fl_Widget*, void*);
  static void sort_cb(Fl_Widget* o, void*);
  static void columns_cb(Fl_Widget* o, void*);
  static void copy_cb(Fl_Widget* o, void*);
  static void print_cb(Fl_Widget* o, void*);
  static Node* sort(Node* n, int (*compare)(const Node*, const Node*));
  static Display* make(const char*, Disk* = 0);
  ~Display();
};

int all_files;
int arg_cb(int, char **argv, int &i) {
  const char *s = argv[i];
  if (s && s[0] == '-' && s[1] == 'a') {all_files = 1; i++; return 1;}
  return 0;
}

int main(int argc, char**argv) {
  // Make fltk look more like KDE/Windoze:
#ifndef FL_NORMAL_SIZE // detect new versions of fltk where this is a variable
  FL_NORMAL_SIZE = 12;
#endif
  Fl::set_color(FL_SELECTION_COLOR,0,0,128);
  // Parse and -x switches understood by fltk:
  int n; Fl::args(argc,argv,n, arg_cb);
  // Any remaining words are files/directories:
  if (n < argc) {
    if (argv[n][0] == '-') {
      if (argv[n][1]) { // unknown switch
	fprintf(stderr,
"xdiskusage		display browser of disks to run du on\n"
"xdiskusage directory...	run du on each named directory\n"
"xdiskusage file...	assume the file contains du output\n"
"du ... | xdiskusage	pipe du output to xdiskusage\n"
" -a	show all files\n%s\n -help\n", Fl::help);
	return 1;
      }
    }
    while (n < argc) {
      Display* d = Display::make(argv[n++]);
      if (d) d->show(argc,argv);
    }
  } else if (!isatty(0)) {
    // test for pipe, if so read stdin:
    Display* d = Display::make(0);
    if (d) d->show(argc,argv);
  } else {
    // normal gui:
    make_diskchooser();
    reload_cb(0,0);
    disk_chooser->show(argc,argv);
  }
  return Fl::run();
}

void disk_browser_cb(Fl_Browser*b, void*) {
  int i = b->value();
  if (!i) return;
  Disk* d;
  for (d = firstdisk; i > 1; i--) d = d->next;
  all_files = all_files_button->value();
  Display* w = Display::make(d->mount, d);
  if (w) w->show();
  //b->value(0);
}

#include <FL/filename.H>

void disk_input_cb(Fl_Input* i, void*) {
  all_files = all_files_button->value();
  Display* w = Display::make(i->value(), 0);
  if (w) w->show();
}

void close_cb(Fl_Widget* o, void*) {
  Display* d = (Display*)o;
  delete d;
}

static int cancelled;

void cancel_cb(Fl_Button*, void*) {
  cancelled = 1;
}

void delete_tree(Node* n) {
  while (n) {
    if (n->child) delete_tree(n->child);
    Node* next = n->brother;
    free((void*)n->name);
    delete n;
    n = next;
  }
}

// fill in missing totals by adding all sons:
void fix_tree(Node* n) {
  if (n->size) return;
  ulong total = 0;
  for (Node *x = n->child; x; x = x->brother) total += x->size;
  n->size = total;
}

static int ordinal;

Node* newnode(const char* name, ulong size, Node* parent, Node* & brother) {
  Node* n = new Node;
  n->child = n->brother = 0;
  n->name = strdup(name);
  n->size = size;
  n->ordinal = ++ordinal;
  if (parent->child) {
    brother->brother = n;
  } else {
    parent->child = n;
  }	
  brother = n;
  return n;
}

static Fl_Menu_Item menutable[] = {
  {"in", FL_Right, Display::in_cb},
  {"next", FL_Down, Display::next_cb},
  {"previous", FL_Up, Display::previous_cb},
  {"out", FL_Left, Display::out_cb},
  {"root", '/', Display::root_cb},
  {"sort", 0, 0, 0, FL_SUBMENU},
    {"largest first", 's', Display::sort_cb, (void*)'s'},
    {"smallest first", 'r', Display::sort_cb, (void*)'r'},
    {"alphabetical", 'a', Display::sort_cb, (void*)'a'},
    {"reverse alphabetical", 'z', Display::sort_cb, (void*)'z'},
    {"unsorted", 'u', Display::sort_cb, (void*)'u'},
    {0},
  {"columns", 0, 0, 0, FL_SUBMENU},
    {"2", '2', Display::columns_cb, (void*)2},
    {"3", '3', Display::columns_cb, (void*)3},
    {"4", '4', Display::columns_cb, (void*)4},
    {"5", '5', Display::columns_cb, (void*)5},
    {"6", '6', Display::columns_cb, (void*)6},
    {"7", '7', Display::columns_cb, (void*)7},
    {"8", '8', Display::columns_cb, (void*)8},
    {"9", '9', Display::columns_cb, (void*)9},
    {"10", '0', Display::columns_cb, (void*)10},
    {"11", '1', Display::columns_cb, (void*)11},
    {0},
  {"copy to clipboard", 'c', Display::copy_cb},
  {"print", 'p', Display::print_cb},
  {0}
};

static int largestfirst(const Node* a, const Node* b) {
  return (a->size > b->size) ? -1 : 1;
}

Display* Display::make(const char* path, Disk* disk) {

  cancelled = 0;

  FILE* f;
  bool true_file;
  char buffer[1024];
  char pathbuf[1024];

  if (!path) {
    // it is a pipe
    true_file = true;
    f = stdin;
  } else {
    if (!disk) {
      // follow all symbolic links...
      strncpy(pathbuf, path, 1024);
      for (int i=0; i<10; i++) {
	char *p = (char*)filename_name(pathbuf);
	int i = readlink(pathbuf, p, 1024-(p-pathbuf));
	if (i < 0) {
	  if (errno != EINVAL) {
	    strcat(pathbuf, ": no such file");
	    fl_alert(pathbuf);
	    return 0;
	  }
	  break;
	}
	if (*p == '/') {memmove(pathbuf, p, i); p = pathbuf;}
	p[i] = 0;
	path = pathbuf;
      }
    }
    // First, determine if the path we're given is an actual file, and
    // not a directory.  If it is a file, assume it's the output from a
    // du command the user ran by hand.
    struct stat stbuf;
    if (stat(path, &stbuf) < 0) {
      fl_alert("%s : %s", path, strerror(errno));
      return 0;
    }
    true_file = S_ISREG(stbuf.st_mode);
    f = fopen(path, "r");
    if (!f) {
      fl_alert("%s : %s", path, strerror(errno));
      return 0;
    }
  }

  if (!true_file) {
    // It's a directory; popen a du command starting at that directory.
    
#ifdef __sgi
    // sgi has the -x and -L switches somehow confused.  You cannot turn
    // off descent into mount points (with -x) without turning on descent
    // into symbolic links (at least for a stat()).  At DD all the symbolic
    // links are on the /usr disk so I special case it:
    if (!strcmp(path, "/usr"))
      sprintf(buffer, "du -k%c \"%s\"", all_files ? 'a' : ' ', path);
    else
#endif
      sprintf(buffer, DU_COMMAND"%c \"%s\"", all_files ? 'a' : ' ', path);
    
    f = popen(buffer,"r");
    if (!f) {
      fl_alert("Problem running '%s' : %s", buffer, strerror(errno));
      return 0;
    }
  }

  if (!wait_window) make_wait_window();
  wait_slider->type(disk ? FL_HOR_FILL_SLIDER : FL_HOR_SLIDER);
  wait_slider->value(0.0);
  if (!(path && true_file)) {
    wait_window->show();
    while (wait_window->damage()) Fl::wait(.1);
  }

  Node* root = new Node;
  root->child = root->brother = 0;
  root->name = 0; //if (!true_file) root->name = strdup(path);
  root->size = 0;
  root->ordinal = 0;
  ordinal = 0;

  Node* lastnode[MAXDEPTH];
  ulong runningtotal;
  ulong totals[MAXDEPTH];
  lastnode[0] = root;
  runningtotal = 0;
  totals[0] = 0;
  int currentdepth = 0;

  for (;;) {
    if (!(path && true_file)) Fl::check();
    if (cancelled) {
      delete_tree(root);
      if (true_file) {
	if (path) fclose(f);
      } else {
	pclose(f);
      }
      wait_window->hide();
      return 0;
    }

    if (!fgets(buffer, 1024, f)) break;

    // null-terminate the line:
    char* p = buffer+strlen(buffer);
    if (p > buffer && p[-1] == '\n') p[-1] = 0;

    ulong size = strtoul(buffer, &p, 10);
    if (!isspace(*p) || p == buffer) {
      if (!*p || *p=='#') continue; // ignore blank lines or comments (?)
      fl_alert("%s does not look like du output", path);
      cancelled = 1;
      continue;
    }

    while (isspace(*p)) p++;

    // split the path into parts:
    int newdepth = 0;
    const char* parts[MAXDEPTH];
    if (*p == '/') {
      if (!root->name) root->name = strdup("/");
      p++;
    }
    for (newdepth = 0; newdepth < MAXDEPTH && *p;) {
      parts[++newdepth] = p++;
      while (*p && *p != '/') p++;
      if (*p == '/') *p++ = 0;
    }

    // find out how many of the fields match:
    int match = 0;
    for (; match < newdepth && match < currentdepth; match++) {
      if (strcmp(parts[match+1],lastnode[match+1]->name)) break;
    }

    // give a total to any subdirectories we are leaving that du did
    // not report a total for:
    for (int j = currentdepth; j > match; j--) fix_tree(lastnode[j]);

    if (match == newdepth) {
      Node* p = lastnode[newdepth];
      ulong t = totals[newdepth]+size;
      p->size = size;
      runningtotal = t;
    } else {
      Node* p = lastnode[match];
      for (int j = match+1; j <= newdepth; j++) {
	totals[j] = runningtotal;
	p = newnode(parts[j], 0, p, lastnode[j]);
      }
      p->size = size;
      runningtotal += size;
    }

    currentdepth = newdepth;
    totals[newdepth] = runningtotal;

    wait_slider->value(disk ? (double)runningtotal/disk->used :
		       (double)(ordinal%1024)/1024);
  }
  if (!root->name) root->name = strdup(path);

  if (true_file) {
    if (path) fclose(f);
  } else {
    pclose(f);
  }
  wait_window->hide();

  // remove all the common roots that were not given sizes by du:
  while (root->child && !root->size && !root->child->brother) {
    Node* child = root->child;
    if (root->name) {
      char buffer[1024];
      char* p = buffer;
      const char* q = root->name;
      while (*q) *p++ = *q++;
      if (p[-1] != '/') *p++ = '/';
      strcpy(p, child->name);
      free((void*)(root->name));
      root->name = strdup(buffer);
      free((void*)(child->name));
    } else {
      root->name = child->name;
    }
    root->size = child->size;
    root->child = child->child;
    delete child;
    for (int j = 1; j < currentdepth; j++) lastnode[j] = lastnode[j+1];
    currentdepth--;
  }
    
  // give a total to any subdirectories we are leaving that du did
  // not report a total for:
  for (int j = currentdepth; j > 0; j--) fix_tree(lastnode[j]);

  // Add dummy nodes to report more information we learned from df:
  if (disk) {
    // find last child so we can add after it:
    Node* n = root->child;
    while (n && n->brother) n = n->brother;
    if (disk->used > runningtotal) {
      // missing stuff (probably permission denied errors):
      newnode("(permission denied)", disk->used-runningtotal, root, n);
      runningtotal = disk->used;
    }
    if (disk->avail) {
      newnode("(free)", disk->avail, root, n);
      runningtotal += disk->avail;
    }
    if (disk->total > runningtotal) {
      newnode("(inodes)", disk->total-runningtotal, root, n);
      runningtotal = disk->total;
    }
  }

  root->size = runningtotal;

  Display* d = new Display(window_w, window_h, root->name);
  d->ncols = ::ncols;
  d->root = d->current_root = sort(root, largestfirst);
  d->resizable(d);
  d->menu_button.menu(menutable);
  d->menu_button.box(FL_NO_BOX);
  d->callback(close_cb);
  d->depth = 0;

  return d;
}

void Display::draw_tree(Node* n, int column, ulong row, double scale) {
  if (!n || column >= ncols) return;
  int X = (w()-1)*column/ncols;
  int W = (w()-1)*(column+1)/ncols - X;
  for (; n; n = n->brother) {
    int Y,H;
    if (n == current_root) {Y = 0; H = h()-1;}
    else {Y = int(row*scale+.5); H = int((row+n->size)*scale+.5) - Y;}
    if (H > 1) {
      fl_color(FL_WHITE);
      fl_rectf(X,Y,W,H);
      fl_color(FL_BLACK);
      fl_rect(X,Y,W+1,H+1);
      if (H > 20) {
	fl_draw(n->name, X, Y, W, H/2, FL_ALIGN_BOTTOM);
	fl_draw(formatk(n->size), X, Y+H/2, W, H/2, FL_ALIGN_TOP);
      } else if (H > 10) {
	fl_draw(n->name, X, Y, W, H, FL_ALIGN_CENTER);
      }
      draw_tree(n->child, column+1, row, scale);
    } else {
      // draw a line for all children
      int endcolumn = column+1;
      for (Node* m = n->child; m && endcolumn < ncols; m=m->child) endcolumn++;
      fl_color(FL_BLACK);
      fl_line(X,Y,(w()-1)*endcolumn/ncols,Y);
    }
    if (n == current_root) return;
    row += n->size;
  }
}

void Display::draw() {
  fl_draw_box(box(),0,0,w(),h(),color());
  double scale = (double)(h()-1)/current_root->size;
  fl_font(0,10);
  draw_tree(current_root, 0, 0, scale);
}

int Display::handle(int event) {
  switch (event) {
  case FL_PUSH:
    if (Fl::event_button() != 1) return Fl_Window::handle(event);
    return 1;
  case FL_DRAG:
    return 1;
  case FL_RELEASE:
    break;
  default:
    return Fl_Window::handle(event);
  }
  // okay, it is a button-up, figure out what they clicked:
  int X = Fl::event_x();
  int Y = Fl::event_y();
  if (X < 0 || X >= w() || Y < 0 || Y >= h()) return 1;
  int column = X * ncols / w();
  if (!column) {
    // clicked on left column, go up one
    if (depth) setroot(parents[depth-1],depth-1);
    return 1;
  }
  column += depth;
  double scale = (double)(h()-1)/current_root->size;
  Node* n = current_root;
  int row = 0;
  int d = depth;
  while (d < column) {
    parents[d] = n;
    n = n->child;
    for (; ; n = n->brother) {
      if (!n) return 1;
      int Y1 = int((row+n->size)*scale+.5);
      if (Y < Y1) break;
      row += n->size;
    }
    d++;
  }
  setroot(n,d);
  return 1;
}

void Display::setroot(Node* n, int newdepth) {
  if (n == current_root) return;
  current_root = n;
  depth = newdepth;
  char buffer[1024];
  buffer[0] = 0;
  char* p = buffer;
  for (int i = 0; i < depth; i++) {
    const char* q = parents[i]->name;
    if (q && *q) {
      while (*q) *p++ = *q++;
      if (p[-1] != '/') *p++ = '/';
    }
  }
  strcpy(p,n->name);
  label(buffer);
  redraw();
}

void Display::copy_cb(Fl_Widget* o, void*) {
  Display* d = (Display*)(o->parent());
  char buffer[1024];
  char* p = buffer;
  for (int i = 0; i < d->depth; i++) {
    const char* q = d->parents[i]->name;
    while (*q) *p++ = *q++;
    if (p[-1] != '/') *p++ = '/';
  }
  strcpy(p,d->current_root->name);
  Fl::selection(*d, buffer, strlen(buffer));
}
  
Display::~Display() {
  delete_tree(root);
}

void Display::root_cb(Fl_Widget* o, void*) {
  Display* d = (Display*)(o->parent());
  d->setroot(d->root, 0);
}
void Display::out_cb(Fl_Widget* o, void*) {
  Display* d = (Display*)(o->parent());
  if (d->depth) d->setroot(d->parents[d->depth-1], d->depth-1);
}
void Display::in_cb(Fl_Widget* o, void*) {
  Display* d = (Display*)(o->parent());
  if (d->current_root->child) {
    d->parents[d->depth] = d->current_root;
    d->setroot(d->current_root->child, d->depth+1);
  }
}
void Display::next_cb(Fl_Widget* o, void*) {
  Display* d = (Display*)(o->parent());
  if (d->current_root->brother)
    d->setroot(d->current_root->brother, d->depth);
}
void Display::previous_cb(Fl_Widget* o, void*) {
  Display* d = (Display*)(o->parent());
  if (!d->depth) return;
  Node* n = d->parents[d->depth-1]->child;
  while (n) {
    if (n->brother == d->current_root) {
      d->setroot(n, d->depth);
      return;
    }
    n = n->brother;
  }
}

static int smallestfirst(const Node* a, const Node* b) {
  return (a->size < b->size) ? -1 : 1;
}
static int alphabetical(const Node* a, const Node* b) {
  return strcmp(a->name, b->name);
}
static int zalphabetical(const Node* a, const Node* b) {
  return -strcmp(a->name, b->name);
}
static int unsorted(const Node* a, const Node* b) {
  return (a->ordinal < b->ordinal) ? -1 : 1;
}

Node* Display::sort(Node* n, int (*compare)(const Node*, const Node*)) {
  if (!n) return 0;
  Node* head = 0;
  while (n) {
    Node* n1 = n->brother;
    Node** p = &head;
    while (*p) {if (compare(n, *p) < 0) break; p = &(*p)->brother;}
    n->brother = *p;
    *p = n;
    n->child = sort(n->child, compare);
    n = n1;
  }
  return head;
}

void Display::sort_cb(Fl_Widget* o, void*v) {
  Display* d = (Display*)(o->parent());
  int (*compare)(const Node*, const Node*);
  switch ((int)v) {
  case 's': compare = largestfirst; break;
  case 'r': compare = smallestfirst; break;
  case 'a': compare = alphabetical; break;
  case 'z': compare = zalphabetical; break;
  default: compare = unsorted; break;
  }
  d->root = sort(d->root, compare);
  d->redraw();
}

void Display::columns_cb(Fl_Widget* o, void*v) {
  Display* d = (Display*)(o->parent());
  int n = (int)v;
  if (n == d->ncols) return;
  ::ncols = d->ncols = n;
  d->redraw();
}

void Display::resize(int X, int Y, int W, int H) {
  window_w = W;
  window_h = H;
  Fl_Window::resize(X,Y,W,H);
}

////////////////////////////////////////////////////////////////
// PostScript output

void Display::print_tree(FILE*f,Node* n, int column, ulong row, double scale,
			 int bboxw, int bboxh) {
  if (!n || column >= ncols) return;
  int X = bboxw*column/ncols;
  int W = bboxw*(column+1)/ncols - X;
  for (; n; n = n->brother) {
    double Y,H;
    if (n == current_root) {Y = 0; H = bboxh;}
    else {Y = row*scale; H = n->size*scale;}
    fprintf(f, "%d %g %d %g rect", X, -Y, W, -H);
    if (H > 20) {
      fprintf(f, " %d %g moveto (%s) show", X+5, -Y-H/2, n->name);
      fprintf(f, " %d %g moveto (%s) show", X+5, -Y-H/2-10,formatk(n->size));
    } else if (H > 10) {
      fprintf(f, " %d %g moveto (%s) show", X+5, -Y-H/2-4, n->name);
    }
    fprintf(f, "\n");
    print_tree(f, n->child, column+1, row, scale, bboxw, bboxh);
    if (n == current_root) return;
    row += n->size;
  }
}

void Display::print_cb(Fl_Widget* o, void*) {
  Display* d = (Display*)(o->parent());
  if (!print_panel) make_print_panel();
  print_panel->show();
  for (;;) {
    if (!print_panel->shown()) return;
    Fl_Widget* o = Fl::readqueue();
    if (o) {
      if (o == print_ok_button) break;
    } else {
      Fl::wait();
    }
  }
  print_panel->hide();
  FILE *f;
  if (print_file_button->value()) {
    f = fopen(print_file_input->value(), "w");
  } else {
    f = popen(print_command_input->value(), "w");
  }
  if (!f) {
    fl_alert("Can't open printer output stream");
    return;
  }
  fprintf(f, "%%!PS-Adobe-2.0\n");
  int W = 7*72+36;
  int H = 10*72;
  if (!print_portrait_button->value()) {int t = W; W = H; H = t;}
  int X = 0;
  int Y = 0;
  if (!fill_page_button->value()) {
    if (d->w()*H > d->h()*W) {int t = d->h()*W/d->w(); Y = (H-t)/2; H = t;}
    else {int t = d->w()*H/d->h(); X = (W-t)/2; W = t;}
  }
  if (print_portrait_button->value())
    fprintf(f, "%%%%BoundingBox: 36 36 %d %d\n",36+X+W,36+Y+H);
  else
    fprintf(f, "%%%%BoundingBox: 36 36 %d %d\n",36+Y+H,36+X+W);
  fprintf(f, "/rect {4 2 roll moveto dup 0 exch rlineto exch 0 rlineto neg 0 exch rlineto closepath stroke} bind def\n");
  fprintf(f, "/pagelevel save def\n");
  fprintf(f, "/Helvetica findfont 10 scalefont setfont\n");
  fprintf(f, "0 setlinewidth\n");
  if (print_portrait_button->value())
    fprintf(f, "%d %d translate\n", 36+X, 36+Y+H);
  else
    fprintf(f, "%d %d translate 90 rotate\n", 36+Y, 36+X);
  double scale = (double)H/d->current_root->size;
  d->print_tree(f, d->current_root, 0, 0, scale, W, H);
  fprintf(f,"showpage\npagelevel restore\n%%%%EOF\n");
  if (print_file_button->value()) {
    fclose(f);
  } else {
    pclose(f);
  }
}

// End of xdiskusage.C