1 ;;; chart.el --- Draw charts (bar charts, etc)
3 ;;; Copyright (C) 1996, 1998, 1999, 2001, 2004, 2005, 2007 Eric M. Ludlam
5 ;; Author: <zappo@gnu.org>
7 ;; RCS: $Id: chart.el,v 1.4 2007-11-26 15:01:03 michaels Exp $
8 ;; Keywords: OO, chart, graph
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)
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.
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.
25 ;; Please send bug reports, etc. to zappo@gnu.org
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'.
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.
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)
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.
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:
59 ;; (setq x-bitmap-file-path (cons "~/mybitmaps" x-bitmap-file-path))
61 ;; to your .emacs (or wherever) and load the `chart-face-pixmap-list'
62 ;; with all the bitmaps you want to use.
67 (defvar chart-map nil "Keymap used in chart mode.")
70 (setq chart-map (make-sparse-keymap))
73 (defvar chart-local-object nil
74 "Local variable containing the locally displayed chart object.")
75 (make-variable-buffer-local 'chart-local-object)
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.")
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.")
87 (defvar chart-face-pixmap-list
88 (if (and (fboundp '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")
94 (defcustom chart-face-use-pixmaps nil
95 "*Non-nil to use fancy pixmaps in the background of chart face colors."
99 (if (and (if (fboundp 'display-color-p)
102 (not chart-face-list))
103 (let ((cl chart-face-color-list)
104 (pl chart-face-pixmap-list)
107 (setq nf (make-face (intern (concat "chart-" (car cl) "-" (car pl)))))
108 (if (condition-case nil
109 (> (x-display-color-cells) 4)
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
116 (fboundp 'set-face-background-pixmap))
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))
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
130 (run-hooks 'chart-mode-hook)
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"
137 (set-buffer (get-buffer-create (format "*%s*" (oref obj title))))
139 (setq chart-local-object obj)
143 ((title :initarg :title
144 :initform "Emacs Chart")
145 (title-face :initarg :title-face
146 :initform 'bold-italic)
147 (x-axis :initarg :x-axis
149 (x-margin :initarg :x-margin
151 (x-width :initarg :x-width
153 (y-axis :initarg :y-axis
155 (y-margin :initarg :y-margin
157 (y-width :initarg :y-width
159 (key-label :initarg :key-label
161 (sequences :initarg :sequences
164 "Superclass for all charts to be displayed in an emacs buffer")
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)))
172 (defclass chart-axis ()
173 ((name :initarg :name
174 :initform "Generic Axis")
175 (loweredge :initarg :loweredge
177 (name-face :initarg :name-face
179 (labels-face :initarg :lables-face
181 (chart :initarg :chart
184 "Superclass used for display of an axis.")
186 (defclass chart-axis-range (chart-axis)
187 ((bounds :initarg :bounds
188 :initform '(0.0 . 50.0))
190 "Class used to display an axis defined by a range of values")
192 (defclass chart-axis-names (chart-axis)
193 ((items :initarg :items
196 "Class used to display an axis which represents different named items")
198 (defclass chart-sequece ()
199 ((data :initarg :data
204 "Class used for all data in different charts")
206 (defclass chart-bar (chart)
207 ((direction :initarg :direction
209 "Subclass for bar charts. (Vertical or horizontal)")
211 (defmethod chart-draw ((c chart) &optional buff)
212 "Start drawing a chart object C in optional BUFF.
213 Erases current contents of buffer"
215 (if buff (set-buffer buff))
217 (insert (make-string 100 ?\n))
218 ;; Start by displaying the axis
223 (message "Rendering chart...")
228 (message "Rendering chart...done")
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)))
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)
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)))
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)
265 start end (oref a name-face)))
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)))
271 (round (* (float (- x (car range)))
272 (/ (float (oref c x-width))
273 (float (- (cdr range) (car range))))))))
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)))
281 (round (* (float (- y (car range)))
282 (/ (float (oref c y-width))
283 (float (- (cdr range) (car range)))))))))
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."
291 ;; We prefer about 5 spaces between each value
292 (let* ((i (car (oref a bounds)))
293 (e (cdr (oref a bounds)))
297 ;; want to jump by units of 5 spaces or so
298 (j (/ rng (/ (chart-size-in-dir (oref a chart) dir) 4)))
300 (if (= j 0) (setq j 1))
304 (format "%dM" (/ i 1000000)))
306 (format "%dK" (/ i 1000)))
309 (if (eq dir 'vertical)
310 (let ((x (+ (+ margin z) (if (oref a loweredge)
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))))
318 (chart-zap-chars (length s))
319 (put-text-property p1 (point) 'face (oref a labels-face))
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)))
331 (oref (if (eq dir 'vertical) (oref c x-axis) (oref c y-axis))
333 (lpn (/ (+ 1.0 (float w)) (float ns)))
335 (cons (+ m (round (* lpn (float n))))
336 (+ m -1 (round (* lpn (+ 1.0 (float n))))))
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."
344 ;; We prefer about 5 spaces between each value
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)
363 (if (< x 1) (setq x 1))
364 (if (> (length (car s)) (1- margin))
365 (setq x (+ x margin)))
367 (chart-goto-xy p (+ (+ margin z) (if (oref a loweredge)
372 (chart-zap-chars (length (car s)))
373 (put-text-property p1 (point) 'face (oref a labels-face))
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))
385 (if (stringp (car (oref (car data) data)))
386 ;; skip string lists...
388 ;; display number lists...
390 (seq (oref (car data) data)))
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)
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))))
413 (chart-deface-rectangle dir rng (cons dp zp) fc)
414 (chart-deface-rectangle dir rng (cons zp dp) fc))
416 ;; find the bounds, and chart it!
417 ;; for now, only do one!
420 (setq data (cdr data))))
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."
428 (let ((axis (eieio-oref c axis-label)))
429 (if (stringp (car (oref seq data)))
430 (let ((labels (oref seq data)))
432 (setq axis (make-instance chart-axis-names
433 :name (oref seq name)
436 (oset axis items labels)))
437 (let ((range (cons 0 1))
440 (setq axis (make-instance chart-axis-range
441 :name (oref seq name)
444 (if (< (car l) (car range)) (setcar range (car l)))
445 (if (> (car l) (cdr range)) (setcdr range (car l)))
447 (oset axis bounds range)))
448 (if (eq axis-label 'x-axis) (oset axis loweredge nil))
449 (eieio-oset c axis-label axis)
451 (oset c sequences (append (oref c sequences) (list seq))))
453 ;;; Charting optimizers
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)))
459 (let ((sl (oref (car s) data)))
460 (if (> (length sl) max)
461 (setcdr (nthcdr (1- max) sl) nil)))
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))
472 (if (stringp (car (oref s1 data)))
474 (chart-sort-matchlist s1 s2 pred)
475 (setq s (oref s1 data)))
476 (if (stringp (car (oref s2 data)))
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)
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
493 (alst (oref namelst data))
494 (ulst (oref numlst data)))
496 ;; this is reversed, but were are sorting anyway
497 (setq newlist (cons (cons (car alst) (car ulst)) newlist))
498 (setq alst (cdr alst)
500 ;; 2 - Run sort routine on it
501 (setq newlist (sort newlist pred)
504 ;; 3 - Separate the lists
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))))
515 (defun chart-goto-xy (x y)
516 "Move cursor to position X Y in buffer, and add spaces and CRs if needed."
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)
528 (remove-text-properties p (point) '(face))))))
530 (defun chart-zap-chars (n)
531 "Zap up to N chars without deleteting EOLs."
533 (if (< n (- (save-excursion (end-of-line) (point)) (point)))
535 (delete-region (point) (save-excursion (end-of-line) (point))))))
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)
542 (chart-goto-xy (+ start (- (/ (- end start) 2) (/ (length label) 2)))
546 (chart-zap-chars (length label))
547 (put-text-property p1 (point) 'face face)
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))
555 (put-text-property (1- (point)) (point) 'face face)
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"
562 (make-string (- end start) (if (eq dir 'vertical) ?| ?\-))
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))
571 (while (<= y (cdr range2))
572 (chart-goto-xy (car range1) y)
573 (put-text-property (point) (+ (point) (1+ (- (cdr range1) (car range1))))
577 ;;; Helpful `I don't want to learn eieio just now' washover functions
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
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
590 :key-label "8-m" ; This is a text key pic
593 (iv (eq dir 'vertical)))
594 (chart-add-sequence nc
595 (make-instance chart-sequece
598 (if iv 'x-axis 'y-axis))
599 (chart-add-sequence nc
600 (make-instance chart-sequece
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))
611 (defun chart-test-it-all ()
612 "Test out various charting features."
614 (chart-bar-quickie 'vertical "Test Bar Chart"
615 '( "U1" "ME2" "C3" "B4" "QT" "EZ") "Items"
616 '( 5 -10 23 20 30 -3) "Values")
619 ;;; Sample utility function
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>"))
631 (let* ((j (string-match "[^\\.]\\(\\.[a-zA-Z]+\\|~\\|#\\)$" (car flst)))
632 (s (if (file-accessible-directory-p (concat dir (car flst)))
635 (substring (car flst) (match-beginning 1) (match-end 1))
637 (m (member s extlst)))
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"
650 '(lambda (a b) (> (cdr a) (cdr b))))
653 (defun chart-space-usage (d)
654 "Display a top usage chart for directory D."
655 (interactive "DDirectory: ")
656 (message "Collecting statistics...")
659 (b (get-buffer-create " *du-tmp*")))
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))))
675 (error "No files found!"))
676 (chart-bar-quickie 'vertical (format "Largest files in %s" d)
680 '(lambda (a b) (> (cdr a) (cdr b))))
683 (defun chart-emacs-storage ()
684 "Chart the current storage requirements of Emacs."
686 (let* ((data (garbage-collect))
687 (names '("strings/2" "vectors"
690 "markers" "free mark"
691 ;; "floats" "free flt"
693 (nums (list (/ (nth 3 data) 2)
695 (car (car data)) ; conses
697 (car (nth 1 data)) ; syms
699 (car (nth 2 data)) ; markers
701 ;(car (nth 5 data)) ; floats are Emacs only
704 ;; Lets create the chart!
705 (chart-bar-quickie 'vertical "Emacs Runtime Storage Usage"
706 names "Storage Items"
709 (defun chart-emacs-lists ()
710 "Chart out the size of various important lists."
712 (let* ((names '("buffers" "frames" "processes" "faces"))
713 (nums (list (length (buffer-list))
714 (length (frame-list))
715 (length (process-list))
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"
726 (defun chart-rmail-from ()
727 "If we are in an rmail summary buffer, then chart out the froms."
729 (if (not (eq major-mode 'rmail-summary-mode))
730 (error "You must invoke chart-rmail-from in an rmail summary buffer"))
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)
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"
746 cntlst "# of occurances"
748 '(lambda (a b) (> (cdr a) (cdr b))))
754 ;;; chart.el ends here