Initial Commit
[packages] / xemacs-packages / eieio / chart.el
1 ;;; chart.el --- Draw charts (bar charts, etc)
2
3 ;;; Copyright (C) 1996, 1998, 1999, 2001, 2004, 2005, 2007 Eric M. Ludlam
4 ;;
5 ;; Author: <zappo@gnu.org>
6 ;; Version: 0.2
7 ;; RCS: $Id: chart.el,v 1.4 2007-11-26 15:01:03 michaels Exp $
8 ;; Keywords: OO, chart, graph
9 ;;                                                                          
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14 ;;
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19 ;;
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
24 ;;
25 ;; Please send bug reports, etc. to zappo@gnu.org
26
27 ;;; Commentary:
28 ;;
29 ;;   This package is an experiment of mine aiding in the debugging of
30 ;; eieio, and proved to be neat enough that others may like to use
31 ;; it.  To quickly see what you can do with chart, run the command
32 ;; `chart-test-it-all'.
33 ;;
34 ;;   Chart current can display bar-charts in either of two
35 ;; directions.  It also supports ranged (integer) axis, and axis
36 ;; defined by some set of strings or names.  These name can be
37 ;; automatically derived from data sequences, which are just lists of
38 ;; anything encapsulated in a nice eieio object.
39 ;;
40 ;;   Current example apps for chart can be accessed via these commands:
41 ;; `chart-file-count'     - count files w/ matching extensions
42 ;; `chart-space-usage'    - display space used by files/directories
43 ;; `chart-emacs-storage'  - Emacs storage units used/free (garbage-collect)
44 ;; `chart-emacs-lists'    - length of Emacs lists
45 ;; `chart-rmail-from'     - who sends you the most mail (in -summary only)
46 ;;
47 ;; Customization:
48 ;;
49 ;;   If you find the default colors and pixmaps unpleasant, or too
50 ;; short, you can change them.  The variable `chart-face-color-list'
51 ;; contains a list of colors, and `chart-face-pixmap-list' contains
52 ;; all the pixmaps to use.  The current pixmaps are those found on
53 ;; several systems I found.  The two lists should be the same length,
54 ;; as the long list will just be truncated.
55 ;;
56 ;;   If you would like to draw your own stipples, simply create some
57 ;; xbm's and put them in a directory, then you can add:
58 ;;
59 ;; (setq x-bitmap-file-path (cons "~/mybitmaps" x-bitmap-file-path))
60 ;;
61 ;; to your .emacs (or wherever) and load the `chart-face-pixmap-list'
62 ;; with all the bitmaps you want to use.
63
64 (require 'eieio)
65
66 ;;; Code:
67 (defvar chart-map nil "Keymap used in chart mode.")
68 (if chart-map
69     ()
70   (setq chart-map (make-sparse-keymap))
71   )
72
73 (defvar chart-local-object nil
74   "Local variable containing the locally displayed chart object.")
75 (make-variable-buffer-local 'chart-local-object)
76
77 (defvar chart-face-list nil
78   "Faces used to colorize charts.
79 List is limited currently, which is ok since you really can't display
80 too much in text characters anyways.")
81
82 (defvar chart-face-color-list '("red" "green" "blue"
83                                 "cyan" "yellow" "purple")
84   "Colors to use when generating `chart-face-list'.
85 Colors will be the background color.")
86
87 (defvar chart-face-pixmap-list
88   (if (and (fboundp 'display-graphic-p)
89            (display-graphic-p))
90       '("dimple1" "scales" "dot" "cross_weave" "boxes" "dimple3"))
91   "If pixmaps are allowed, display these background pixmaps.
92 Useful if new Emacs is used on B&W display")
93
94 (defcustom chart-face-use-pixmaps nil
95   "*Non-nil to use fancy pixmaps in the background of chart face colors."
96   :group 'eieio
97   :type 'boolean)
98
99 (if (and (if (fboundp 'display-color-p)
100              (display-color-p)
101            window-system)
102          (not chart-face-list))
103     (let ((cl chart-face-color-list)
104           (pl chart-face-pixmap-list)
105           nf)
106       (while cl
107         (setq nf (make-face (intern (concat "chart-" (car cl) "-" (car pl)))))
108         (if (condition-case nil
109                 (> (x-display-color-cells) 4)
110               (error t))
111             (set-face-background nf (car cl))
112           (set-face-background nf "white"))
113         (set-face-foreground nf "black")
114         (if (and chart-face-use-pixmaps
115                  pl
116                  (fboundp 'set-face-background-pixmap))
117             (condition-case nil
118                 (set-face-background-pixmap nf (car pl))
119               (error (message "Cannot set background pixmap %s" (car pl)))))
120         (setq chart-face-list (cons nf chart-face-list))
121         (setq cl (cdr cl)
122               pl (cdr pl)))))
123
124 (defun chart-mode ()
125   "Define a mode in Emacs for displaying a chart."
126   (kill-all-local-variables)
127   (use-local-map chart-map)
128   (setq major-mode 'chart-mode
129         mode-name "CHART")
130   (run-hooks 'chart-mode-hook)
131   )
132
133 (defun chart-new-buffer (obj)
134   "Create a new buffer NAME in which the chart OBJ is displayed.
135 Returns the newly created buffer"
136   (save-excursion
137     (set-buffer (get-buffer-create (format "*%s*" (oref obj title))))
138     (chart-mode)
139     (setq chart-local-object obj)
140     (current-buffer)))
141
142 (defclass chart ()
143   ((title :initarg :title
144           :initform "Emacs Chart")
145    (title-face :initarg :title-face
146                :initform 'bold-italic)
147    (x-axis :initarg :x-axis
148            :initform nil )
149    (x-margin :initarg :x-margin
150              :initform 5)
151    (x-width :initarg :x-width
152             )
153    (y-axis :initarg :y-axis
154            :initform nil)
155    (y-margin :initarg :y-margin
156              :initform 5)
157    (y-width :initarg :y-width
158             )
159    (key-label :initarg :key-label
160               :initform "Key")
161    (sequences :initarg :sequences
162               :initform nil)
163    )
164   "Superclass for all charts to be displayed in an emacs buffer")
165
166 (defmethod initialize-instance :AFTER ((obj chart) &rest fields)
167   "Initialize the chart OBJ being created with FIELDS.
168 Make sure the width/height is correct."
169   (oset obj x-width (- (window-width) 10))
170   (oset obj y-width (- (window-height) 12)))
171
172 (defclass chart-axis ()
173   ((name :initarg :name
174          :initform "Generic Axis")
175    (loweredge :initarg :loweredge
176               :initform t)
177    (name-face :initarg :name-face
178               :initform 'bold)
179    (labels-face :initarg :lables-face
180                 :initform 'italic)
181    (chart :initarg :chart
182           :initform nil)
183    )
184   "Superclass used for display of an axis.")
185
186 (defclass chart-axis-range (chart-axis)
187   ((bounds :initarg :bounds
188            :initform '(0.0 . 50.0))
189    )
190   "Class used to display an axis defined by a range of values")
191
192 (defclass chart-axis-names (chart-axis)
193   ((items :initarg :items
194           :initform nil)
195    )
196   "Class used to display an axis which represents different named items")
197
198 (defclass chart-sequece ()
199   ((data :initarg :data
200          :initform nil)
201    (name :initarg :name
202          :initform "Data")
203    )
204   "Class used for all data in different charts")
205
206 (defclass chart-bar (chart)
207   ((direction :initarg :direction
208               :initform vertical))
209   "Subclass for bar charts. (Vertical or horizontal)")
210
211 (defmethod chart-draw ((c chart) &optional buff)
212   "Start drawing a chart object C in optional BUFF.
213 Erases current contents of buffer"
214   (save-excursion
215     (if buff (set-buffer buff))
216     (erase-buffer)
217     (insert (make-string 100 ?\n))
218     ;; Start by displaying the axis
219     (chart-draw-axis c)
220     ;; Display title
221     (chart-draw-title c)
222     ;; Display data
223     (message "Rendering chart...")
224     (sit-for 0)
225     (chart-draw-data c)
226     ;; Display key
227     ; (chart-draw-key c)
228     (message "Rendering chart...done")
229     ))
230
231 (defmethod chart-draw-title ((c chart))
232   "Draw a title upon the chart.
233 Argument C is the chart object."
234   (chart-display-label (oref c title) 'horizontal 0 0 (window-width)
235                        (oref c title-face)))
236
237 (defmethod chart-size-in-dir ((c chart) dir)
238   "Return the physical size of chart C in direction DIR."
239   (if (eq dir 'vertical)
240       (oref c y-width)
241     (oref c x-width)))
242
243 (defmethod chart-draw-axis ((c chart))
244   "Draw axis into the current buffer defined by chart C."
245   (let ((ymarg (oref c y-margin))
246         (xmarg (oref c x-margin))
247         (ylen (oref c y-width))
248         (xlen (oref c x-width)))
249     (chart-axis-draw (oref c y-axis) 'vertical ymarg
250                      (if (oref (oref c y-axis) loweredge) nil xlen)
251                      xmarg (+ xmarg ylen))
252     (chart-axis-draw (oref c x-axis) 'horizontal xmarg
253                      (if (oref (oref c x-axis) loweredge) nil ylen)
254                      ymarg (+ ymarg xlen)))
255   )
256
257 (defmethod chart-axis-draw ((a chart-axis) &optional dir margin zone start end)
258   "Draw some axis for A in direction DIR at with MARGIN in boundry.
259 ZONE is a zone specification.
260 START and END represent the boundary."
261   (chart-draw-line dir (+ margin (if zone zone 0)) start end)
262   (chart-display-label (oref a name) dir (if zone (+ zone margin 3)
263                                            (if (eq dir 'horizontal)
264                                                1 0))
265                        start end (oref a name-face)))
266
267 (defmethod chart-translate-xpos ((c chart) x)
268   "Translate in chart C the coordinate X into a screen column."
269   (let ((range (oref (oref c x-axis) bounds)))
270     (+ (oref c x-margin)
271        (round (* (float (- x (car range)))
272                  (/ (float (oref c x-width))
273                     (float (- (cdr range) (car range))))))))
274   )
275
276 (defmethod chart-translate-ypos ((c chart) y)
277   "Translate in chart C the coordinate Y into a screen row."
278   (let ((range (oref (oref c y-axis) bounds)))
279     (+ (oref c x-margin)
280        (- (oref c y-width)
281           (round (* (float (- y (car range)))
282                     (/ (float (oref c y-width))
283                        (float (- (cdr range) (car range)))))))))
284   )
285
286 (defmethod chart-axis-draw ((a chart-axis-range) &optional dir margin zone start end)
287   "Draw axis information based upon a range to be spread along the edge.
288 A is the chart to draw.  DIR is the direction.
289 MARGIN, ZONE, START, and END specify restrictions in chart space."
290   (call-next-method)
291   ;; We prefer about 5 spaces between each value
292   (let* ((i (car (oref a bounds)))
293          (e (cdr (oref a bounds)))
294          (z (if zone zone 0))
295          (s nil)
296          (rng (- e i))
297          ;; want to jump by units of 5 spaces or so
298          (j (/ rng (/  (chart-size-in-dir (oref a chart) dir) 4)))
299          p1)
300     (if (= j 0) (setq j 1))
301     (while (<= i e)
302       (setq s
303             (cond ((> i 999999)
304                    (format "%dM" (/ i 1000000)))
305                   ((> i 999)
306                    (format "%dK" (/ i 1000)))
307                   (t
308                    (format "%d" i))))
309       (if (eq dir 'vertical)
310           (let ((x (+ (+ margin z) (if (oref a loweredge)
311                                        (- (length s)) 1))))
312             (if (< x 1) (setq x 1))
313             (chart-goto-xy x (chart-translate-ypos (oref a chart) i)))
314         (chart-goto-xy (chart-translate-xpos (oref a chart) i)
315                        (+ margin z (if (oref a loweredge) -1 1))))
316       (setq p1 (point))
317       (insert s)
318       (chart-zap-chars (length s))
319       (put-text-property p1 (point) 'face (oref a labels-face))
320       (setq i (+ i j))))
321 )
322
323 (defmethod chart-translate-namezone ((c chart) n)
324   "Return a dot-pair representing a positional range for a name.
325 The name in chart C of the Nth name resides.
326 Automatically compensates for for direction."
327   (let* ((dir (oref c direction))
328          (w (if (eq dir 'vertical) (oref c x-width) (oref c y-width)))
329          (m (if (eq dir 'vertical) (oref c y-margin) (oref c x-margin)))
330          (ns (length
331               (oref (if (eq dir 'vertical) (oref c x-axis) (oref c y-axis))
332                     items)))
333          (lpn (/ (+ 1.0 (float w)) (float ns)))
334          )
335     (cons (+ m (round (* lpn (float n))))
336           (+ m -1 (round (* lpn (+ 1.0 (float n))))))
337     ))
338
339 (defmethod chart-axis-draw ((a chart-axis-names) &optional dir margin zone start end)
340   "Draw axis information based upon A range to be spread along the edge.
341 Optional argument DIR the direction of the chart.
342 Optional argument MARGIN , ZONE, START and END specify boundaries of the drawing."
343   (call-next-method)
344   ;; We prefer about 5 spaces between each value
345   (let* ((i 0)
346          (s (oref a items))
347          (z (if zone zone 0))
348          (r nil)
349          (p nil)
350          (odd nil)
351          p1)
352     (while s
353       (setq odd (= (% (length s) 2) 1))
354       (setq r (chart-translate-namezone (oref a chart) i))
355       (if (eq dir 'vertical)
356           (setq p (/ (+ (car r) (cdr r)) 2))
357         (setq p (- (+ (car r) (/ (- (cdr r) (car r)) 2))
358                    (/ (length (car s)) 2))))
359       (if (eq dir 'vertical)
360           (let ((x (+ (+ margin z) (if (oref a loweredge)
361                                        (- (length (car s)))
362                                      (length (car s))))))
363             (if (< x 1) (setq x 1))
364             (if (> (length (car s)) (1- margin))
365                 (setq x (+ x margin)))
366             (chart-goto-xy x p))
367         (chart-goto-xy p (+ (+ margin z) (if (oref a loweredge)
368                                              (if odd -2 -1)
369                                            (if odd 2 1)))))
370       (setq p1 (point))
371       (insert (car s))
372       (chart-zap-chars (length (car s)))
373       (put-text-property p1 (point) 'face (oref a labels-face))
374       (setq i (+ i 1)
375             s (cdr s))))
376 )
377
378 (defmethod chart-draw-data ((c chart-bar))
379   "Display the data available in a bar chart C."
380   (let* ((data (oref c sequences))
381          (dir (oref c direction))
382          (odir (if (eq dir 'vertical) 'horizontal 'vertical))
383         )
384     (while data
385       (if (stringp (car (oref (car data) data)))
386           ;; skip string lists...
387           nil
388         ;; display number lists...
389         (let ((i 0)
390               (seq (oref (car data) data)))
391           (while seq
392             (let* ((rng (chart-translate-namezone c i))
393                    (dp (if (eq dir 'vertical)
394                            (chart-translate-ypos c (car seq))
395                          (chart-translate-xpos c (car seq))))
396                   (zp (if (eq dir 'vertical)
397                           (chart-translate-ypos c 0)
398                         (chart-translate-xpos c 0)))
399                   (fc (if chart-face-list
400                           (nth (% i (length chart-face-list)) chart-face-list)
401                         'default))
402                   )
403               (if (< dp zp)
404                   (progn
405                     (chart-draw-line dir (car rng) dp zp)
406                     (chart-draw-line dir (cdr rng) dp zp))
407                 (chart-draw-line dir (car rng) zp (1+ dp))
408                 (chart-draw-line dir (cdr rng) zp (1+ dp)))
409               (if (= (car rng) (cdr rng)) nil
410                 (chart-draw-line odir dp (1+ (car rng)) (cdr rng))
411                 (chart-draw-line odir zp (car rng) (1+ (cdr rng))))
412               (if (< dp zp)
413                   (chart-deface-rectangle dir rng (cons dp zp) fc)
414                 (chart-deface-rectangle dir rng (cons zp dp) fc))
415               )
416             ;; find the bounds, and chart it!
417             ;; for now, only do one!
418             (setq i (1+ i)
419                   seq (cdr seq)))))
420       (setq data (cdr data))))
421   )
422
423 (defmethod chart-add-sequence ((c chart) &optional seq axis-label)
424   "Add to chart object C the sequence object SEQ.
425 If AXIS-LABEL, then the axis stored in C is updated with the bounds of SEQ,
426 or is created with the bounds of SEQ."
427   (if axis-label
428       (let ((axis (eieio-oref c axis-label)))
429         (if (stringp (car (oref seq data)))
430             (let ((labels (oref seq data)))
431               (if (not axis)
432                   (setq axis (make-instance chart-axis-names
433                                             :name (oref seq name)
434                                             :items labels
435                                             :chart c))
436                 (oset axis items labels)))
437           (let ((range (cons 0 1))
438                 (l (oref seq data)))
439             (if (not axis)
440                 (setq axis (make-instance chart-axis-range
441                                           :name (oref seq name)
442                                           :chart c)))
443             (while l
444               (if (< (car l) (car range)) (setcar range (car l)))
445               (if (> (car l) (cdr range)) (setcdr range (car l)))
446               (setq l (cdr l)))
447             (oset axis bounds range)))
448         (if (eq axis-label 'x-axis) (oset axis loweredge nil))
449         (eieio-oset c axis-label axis)
450         ))
451   (oset c sequences (append (oref c sequences) (list seq))))
452
453 ;;; Charting optimizers
454
455 (defmethod chart-trim ((c chart) max)
456   "Trim all sequences in chart C to be at most MAX elements long."
457   (let ((s (oref c sequences)))
458     (while s
459       (let ((sl (oref (car s) data)))
460         (if (> (length sl) max)
461             (setcdr (nthcdr (1- max) sl) nil)))
462       (setq s (cdr s))))
463   )
464
465 (defmethod chart-sort ((c chart) pred)
466   "Sort the data in chart C using predicate PRED.
467 See `chart-sort-matchlist' for more details"
468   (let* ((sl (oref c sequences))
469          (s1 (car sl))
470          (s2 (car (cdr sl)))
471          (s nil))
472     (if (stringp (car (oref s1 data)))
473         (progn
474           (chart-sort-matchlist s1 s2 pred)
475           (setq s (oref s1 data)))
476       (if (stringp (car (oref s2 data)))
477           (progn
478             (chart-sort-matchlist s2 s1 pred)
479             (setq s (oref s2 data)))
480         (error "Sorting of chart %s not supported" (object-name c))))
481     (if (eq (oref c direction) 'horizontal)
482         (oset (oref c y-axis) items s)
483       (oset (oref c x-axis) items s)
484         ))
485   )
486
487 (defun chart-sort-matchlist (namelst numlst pred)
488   "Sort NAMELST and NUMLST (both SEQUENCE objects) based on predicate PRED.
489 PRED should be the equivalent of '<, except it must expect two
490 cons cells of the form (NAME . NUM).  See SORT for more details."
491   ;; 1 - create 1 list of cons cells
492   (let ((newlist nil)
493         (alst (oref namelst data))
494         (ulst (oref numlst data)))
495     (while alst
496       ;; this is reversed, but were are sorting anyway
497       (setq newlist (cons (cons (car alst) (car ulst)) newlist))
498       (setq alst (cdr alst)
499             ulst (cdr ulst)))
500     ;; 2 - Run sort routine on it
501     (setq newlist (sort newlist pred)
502           alst nil
503           ulst nil)
504     ;; 3 - Separate the lists
505     (while newlist
506       (setq alst (cons (car (car newlist)) alst)
507             ulst (cons (cdr (car newlist)) ulst))
508       (setq newlist (cdr newlist)))
509     ;; 4 - Store them back
510     (oset namelst data (reverse alst))
511     (oset numlst data (reverse ulst))))
512
513 ;;; Utilities
514
515 (defun chart-goto-xy (x y)
516   "Move cursor to position X Y in buffer, and add spaces and CRs if needed."
517
518   (let ((indent-tabs-mode nil)
519         (num (goto-line (1+ y))))
520     (if (and (= 0 num) (/= 0 (current-column))) (newline 1))
521     (if (eobp) (newline num))
522     (if (< x 0) (setq x 0))
523     (if (< y 0) (setq y 0))
524     ;; Now, a quicky column moveto/forceto method.
525     (or (= (move-to-column x) x)
526         (let ((p (point)))
527           (indent-to x)
528           (remove-text-properties p (point) '(face))))))
529
530 (defun chart-zap-chars (n)
531   "Zap up to N chars without deleteting EOLs."
532   (if (not (eobp))
533       (if (< n (- (save-excursion (end-of-line) (point)) (point)))
534           (delete-char n)
535         (delete-region (point) (save-excursion (end-of-line) (point))))))
536
537 (defun chart-display-label (label dir zone start end &optional face)
538   "Display LABEL in direction DIR in column/row ZONE between START and END.
539 Optional argument FACE is the property we wish to place on this text."
540   (if (eq dir 'horizontal)
541       (let (p1)
542         (chart-goto-xy (+ start (- (/ (- end start) 2) (/ (length label) 2)))
543                        zone)
544         (setq p1 (point))
545         (insert label)
546         (chart-zap-chars (length label))
547         (put-text-property p1 (point) 'face face)
548         )
549     (let ((i 0)
550           (stz (+ start (- (/ (- end start) 2) (/ (length label) 2)))))
551       (while (< i (length label))
552         (chart-goto-xy zone (+ stz i))
553         (insert (aref label i))
554         (chart-zap-chars 1)
555         (put-text-property (1- (point)) (point) 'face face)
556         (setq i (1+ i))))))
557
558 (defun chart-draw-line (dir zone start end)
559   "Draw a line using line-drawing characters in direction DIR.
560 Use column or row ZONE between START and END"
561   (chart-display-label
562    (make-string (- end start) (if (eq dir 'vertical) ?| ?\-))
563    dir zone start end))
564
565 (defun chart-deface-rectangle (dir r1 r2 face)
566   "Colorize a rectangle in direction DIR across range R1 by range R2.
567 R1 and R2 are dotted pairs.  Colorize it with FACE."
568   (let* ((range1 (if (eq dir 'vertical) r1 r2))
569          (range2 (if (eq dir 'vertical) r2 r1))
570          (y (car range2)))
571     (while (<= y (cdr range2))
572       (chart-goto-xy (car range1) y)
573       (put-text-property (point) (+ (point) (1+ (- (cdr range1) (car range1))))
574                          'face face)
575       (setq y (1+ y)))))
576
577 ;;; Helpful `I don't want to learn eieio just now' washover functions
578
579 (defun chart-bar-quickie (dir title namelst nametitle numlst numtitle
580                               &optional max sort-pred)
581   "Wash over the complex eieio stuff and create a nice bar chart.
582 Creat it going in direction DIR ['horizontal 'vertical] with TITLE
583 using a name sequence NAMELST labeled NAMETITLE with values NUMLST
584 labeled NUMTITLE.
585 Optional arguments:
586 Set the charts' max element display to MAX, and sort lists with
587 SORT-PRED if desired."
588   (let ((nc (make-instance chart-bar
589                            :title title
590                            :key-label "8-m"  ; This is a text key pic
591                            :direction dir
592                            ))
593         (iv (eq dir 'vertical)))
594     (chart-add-sequence nc
595                         (make-instance chart-sequece
596                                        :data namelst
597                                        :name nametitle)
598                         (if iv 'x-axis 'y-axis))
599     (chart-add-sequence nc
600                         (make-instance chart-sequece
601                                        :data numlst
602                                        :name numtitle)
603                         (if iv 'y-axis 'x-axis))
604     (if sort-pred (chart-sort nc sort-pred))
605     (if (integerp max) (chart-trim nc max))
606     (switch-to-buffer (chart-new-buffer nc))
607     (chart-draw nc)))
608
609 ;;; Test code
610
611 (defun chart-test-it-all ()
612   "Test out various charting features."
613   (interactive)
614   (chart-bar-quickie 'vertical "Test Bar Chart"
615                      '( "U1" "ME2" "C3" "B4" "QT" "EZ") "Items"
616                      '( 5 -10 23 20 30 -3) "Values")
617   )
618
619 ;;; Sample utility function
620
621 (defun chart-file-count (dir)
622   "Draw a chart displaying the number of different file extentions in DIR."
623   (interactive "DDirectory: ")
624   (if (not (string-match "/$" dir))
625       (setq dir (concat dir "/")))
626   (message "Collecting statistics...")
627   (let ((flst (directory-files dir nil nil t))
628         (extlst (list "<dir>"))
629         (cntlst (list 0)))
630     (while flst
631       (let* ((j (string-match "[^\\.]\\(\\.[a-zA-Z]+\\|~\\|#\\)$" (car flst)))
632              (s (if (file-accessible-directory-p (concat dir (car flst)))
633                     "<dir>"
634                   (if j
635                       (substring (car flst) (match-beginning 1) (match-end 1))
636                     nil)))
637              (m (member s extlst)))
638         (if (not s) nil
639           (if m
640               (let ((cell (nthcdr (- (length extlst) (length m)) cntlst)))
641                 (setcar cell (1+ (car cell))))
642             (setq extlst (cons s extlst)
643                   cntlst (cons 1 cntlst)))))
644       (setq flst (cdr flst)))
645     ;; Lets create the chart!
646     (chart-bar-quickie 'vertical "Files Extension Distribution"
647                        extlst "File Extensions"
648                        cntlst "# of occurances"
649                        10
650                        '(lambda (a b) (> (cdr a) (cdr b))))
651     ))
652
653 (defun chart-space-usage (d)
654   "Display a top usage chart for directory D."
655   (interactive "DDirectory: ")
656   (message "Collecting statistics...")
657   (let ((nmlst nil)
658         (cntlst nil)
659         (b (get-buffer-create " *du-tmp*")))
660     (set-buffer b)
661     (erase-buffer)
662     (insert "cd " d ";du -sk * \n")
663     (message "Running `cd %s;du -sk *'..." d)
664     (call-process-region (point-min) (point-max) shell-file-name t
665                          (current-buffer) nil)
666     (goto-char (point-min))
667     (message "Scanning output ...")
668     (while (re-search-forward "^\\([0-9]+\\)[ \t]+\\([^ \n]+\\)$" nil t)
669       (let* ((nam (buffer-substring (match-beginning 2) (match-end 2)))
670              (num (buffer-substring (match-beginning 1) (match-end 1))))
671         (setq nmlst (cons nam nmlst)
672               ;; * 1000 to put it into bytes
673               cntlst (cons (* (string-to-number num) 1000) cntlst))))
674     (if (not nmlst)
675         (error "No files found!"))
676     (chart-bar-quickie 'vertical (format "Largest files in %s" d)
677                        nmlst "File Name"
678                        cntlst "File Size"
679                        10
680                        '(lambda (a b) (> (cdr a) (cdr b))))
681     ))
682
683 (defun chart-emacs-storage ()
684   "Chart the current storage requirements of Emacs."
685   (interactive)
686   (let* ((data (garbage-collect))
687          (names '("strings/2" "vectors"
688                   "conses" "free cons"
689                   "syms" "free syms"
690                   "markers" "free mark"
691                   ;; "floats" "free flt"
692                   ))
693          (nums (list (/ (nth 3 data) 2)
694                      (nth 4 data)
695                      (car (car data))   ; conses
696                      (cdr (car data))
697                      (car (nth 1 data)) ; syms
698                      (cdr (nth 1 data))
699                      (car (nth 2 data)) ; markers
700                      (cdr (nth 2 data))
701                      ;(car (nth 5 data)) ; floats are Emacs only
702                      ;(cdr (nth 5 data))
703                      )))
704     ;; Lets create the chart!
705     (chart-bar-quickie 'vertical "Emacs Runtime Storage Usage"
706                        names "Storage Items"
707                        nums "Objects")))
708
709 (defun chart-emacs-lists ()
710   "Chart out the size of various important lists."
711   (interactive)
712   (let* ((names '("buffers" "frames" "processes" "faces"))
713          (nums (list (length (buffer-list))
714                      (length (frame-list))
715                      (length (process-list))
716                      (length (face-list))
717                      )))
718     (if (fboundp 'x-display-list)
719         (setq names (append names '("x-displays"))
720               nums (append nums (list (length (x-display-list))))))
721     ;; Lets create the chart!
722     (chart-bar-quickie 'vertical "Emacs List Size Chart"
723                        names "Various Lists"
724                        nums "Objects")))
725
726 (defun chart-rmail-from ()
727   "If we are in an rmail summary buffer, then chart out the froms."
728   (interactive)
729   (if (not (eq major-mode 'rmail-summary-mode))
730       (error "You must invoke chart-rmail-from in an rmail summary buffer"))
731   (let ((nmlst nil)
732         (cntlst nil))
733     (save-excursion
734       (goto-char (point-min))
735       (while (re-search-forward "\\-[A-Z][a-z][a-z] +\\(\\w+\\)@\\w+" nil t)
736         (let* ((nam (buffer-substring (match-beginning 1) (match-end 1)))
737                (m (member nam nmlst)))
738           (message "Scanned username %s" nam)
739           (if m
740               (let ((cell (nthcdr (- (length nmlst) (length m)) cntlst)))
741                 (setcar cell (1+ (car cell))))
742             (setq nmlst (cons nam nmlst)
743                   cntlst (cons 1 cntlst))))))
744     (chart-bar-quickie 'vertical "Username Occurance in RMAIL box"
745                        nmlst "User Names"
746                        cntlst "# of occurances"
747                        10
748                        '(lambda (a b) (> (cdr a) (cdr b))))
749     ))
750
751
752 (provide 'chart)
753
754 ;;; chart.el ends here