1 ;;; chart.el --- Draw charts (bar charts, etc)
3 ;; Copyright (C) 1996, 1998-1999, 2001, 2004-2005, 2007-2011 Free Software Foundation, Inc.
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
7 ;; Keywords: OO, chart, graph
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; This package is an experiment of mine aiding in the debugging of
27 ;; eieio, and proved to be neat enough that others may like to use
28 ;; it. To quickly see what you can do with chart, run the command
29 ;; `chart-test-it-all'.
31 ;; Chart current can display bar-charts in either of two
32 ;; directions. It also supports ranged (integer) axis, and axis
33 ;; defined by some set of strings or names. These name can be
34 ;; automatically derived from data sequences, which are just lists of
35 ;; anything encapsulated in a nice eieio object.
37 ;; Current example apps for chart can be accessed via these commands:
38 ;; `chart-file-count' - count files w/ matching extensions
39 ;; `chart-space-usage' - display space used by files/directories
40 ;; `chart-emacs-storage' - Emacs storage units used/free (garbage-collect)
41 ;; `chart-emacs-lists' - length of Emacs lists
42 ;; `chart-rmail-from' - who sends you the most mail (in -summary only)
46 ;; If you find the default colors and pixmaps unpleasant, or too
47 ;; short, you can change them. The variable `chart-face-color-list'
48 ;; contains a list of colors, and `chart-face-pixmap-list' contains
49 ;; all the pixmaps to use. The current pixmaps are those found on
50 ;; several systems I found. The two lists should be the same length,
51 ;; as the long list will just be truncated.
53 ;; If you would like to draw your own stipples, simply create some
54 ;; xbm's and put them in a directory, then you can add:
56 ;; (setq x-bitmap-file-path (cons "~/mybitmaps" x-bitmap-file-path))
58 ;; to your .emacs (or wherever) and load the `chart-face-pixmap-list'
59 ;; with all the bitmaps you want to use.
64 (defvar chart-mode-map (make-sparse-keymap) "Keymap used in chart mode.")
65 (define-obsolete-variable-alias 'chart-map 'chart-mode-map "24.1")
67 (defvar chart-local-object nil
68 "Local variable containing the locally displayed chart object.")
69 (make-variable-buffer-local 'chart-local-object)
71 (defvar chart-face-color-list '("red" "green" "blue"
72 "cyan" "yellow" "purple")
73 "Colors to use when generating `chart-face-list'.
74 Colors will be the background color.")
76 (defvar chart-face-pixmap-list
77 (if (and (fboundp 'display-graphic-p)
79 '("dimple1" "scales" "dot" "cross_weave" "boxes" "dimple3"))
80 "If pixmaps are allowed, display these background pixmaps.
81 Useful if new Emacs is used on B&W display.")
83 (defcustom chart-face-use-pixmaps nil
84 "*Non-nil to use fancy pixmaps in the background of chart face colors."
88 (defvar chart-face-list
89 (if (if (fboundp 'display-color-p)
92 (let ((cl chart-face-color-list)
93 (pl chart-face-pixmap-list)
98 (intern (concat "chart-" (car cl) "-" (car pl)))))
99 (set-face-background nf (if (condition-case nil
100 (> (x-display-color-cells) 4)
104 (set-face-foreground nf "black")
105 (if (and chart-face-use-pixmaps
107 (fboundp 'set-face-background-pixmap))
109 (set-face-background-pixmap nf (car pl))
110 (error (message "Cannot set background pixmap %s" (car pl)))))
115 "Faces used to colorize charts.
116 List is limited currently, which is ok since you really can't display
117 too much in text characters anyways.")
119 (define-derived-mode chart-mode fundamental-mode "CHART"
120 "Define a mode in Emacs for displaying a chart."
121 (buffer-disable-undo)
122 (set (make-local-variable 'font-lock-global-modes) nil)
123 (font-lock-mode -1) ;Isn't it off already? --Stef
126 (defun chart-new-buffer (obj)
127 "Create a new buffer NAME in which the chart OBJ is displayed.
128 Returns the newly created buffer."
129 (with-current-buffer (get-buffer-create (format "*%s*" (oref obj title)))
131 (setq chart-local-object obj)
135 ((title :initarg :title
136 :initform "Emacs Chart")
137 (title-face :initarg :title-face
138 :initform 'bold-italic)
139 (x-axis :initarg :x-axis
141 (x-margin :initarg :x-margin
143 (x-width :initarg :x-width
145 (y-axis :initarg :y-axis
147 (y-margin :initarg :y-margin
149 (y-width :initarg :y-width
151 (key-label :initarg :key-label
153 (sequences :initarg :sequences
156 "Superclass for all charts to be displayed in an Emacs buffer.")
158 (defmethod initialize-instance :AFTER ((obj chart) &rest fields)
159 "Initialize the chart OBJ being created with FIELDS.
160 Make sure the width/height is correct."
161 (oset obj x-width (- (window-width) 10))
162 (oset obj y-width (- (window-height) 12)))
164 (defclass chart-axis ()
165 ((name :initarg :name
166 :initform "Generic Axis")
167 (loweredge :initarg :loweredge
169 (name-face :initarg :name-face
171 (labels-face :initarg :lables-face
173 (chart :initarg :chart
176 "Superclass used for display of an axis.")
178 (defclass chart-axis-range (chart-axis)
179 ((bounds :initarg :bounds
180 :initform '(0.0 . 50.0))
182 "Class used to display an axis defined by a range of values.")
184 (defclass chart-axis-names (chart-axis)
185 ((items :initarg :items
188 "Class used to display an axis which represents different named items.")
190 (defclass chart-sequece ()
191 ((data :initarg :data
196 "Class used for all data in different charts.")
198 (defclass chart-bar (chart)
199 ((direction :initarg :direction
201 "Subclass for bar charts (vertical or horizontal).")
203 (defmethod chart-draw ((c chart) &optional buff)
204 "Start drawing a chart object C in optional BUFF.
205 Erases current contents of buffer."
207 (if buff (set-buffer buff))
209 (insert (make-string 100 ?\n))
210 ;; Start by displaying the axis
215 (message "Rendering chart...")
220 (message "Rendering chart...done")
223 (defmethod chart-draw-title ((c chart))
224 "Draw a title upon the chart.
225 Argument C is the chart object."
226 (chart-display-label (oref c title) 'horizontal 0 0 (window-width)
227 (oref c title-face)))
229 (defmethod chart-size-in-dir ((c chart) dir)
230 "Return the physical size of chart C in direction DIR."
231 (if (eq dir 'vertical)
235 (defmethod chart-draw-axis ((c chart))
236 "Draw axis into the current buffer defined by chart C."
237 (let ((ymarg (oref c y-margin))
238 (xmarg (oref c x-margin))
239 (ylen (oref c y-width))
240 (xlen (oref c x-width)))
241 (chart-axis-draw (oref c y-axis) 'vertical ymarg
242 (if (oref (oref c y-axis) loweredge) nil xlen)
243 xmarg (+ xmarg ylen))
244 (chart-axis-draw (oref c x-axis) 'horizontal xmarg
245 (if (oref (oref c x-axis) loweredge) nil ylen)
246 ymarg (+ ymarg xlen)))
249 (defmethod chart-axis-draw ((a chart-axis) &optional dir margin zone start end)
250 "Draw some axis for A in direction DIR with MARGIN in boundary.
251 ZONE is a zone specification.
252 START and END represent the boundary."
253 (chart-draw-line dir (+ margin (if zone zone 0)) start end)
254 (chart-display-label (oref a name) dir (if zone (+ zone margin 3)
255 (if (eq dir 'horizontal)
257 start end (oref a name-face)))
259 (defmethod chart-translate-xpos ((c chart) x)
260 "Translate in chart C the coordinate X into a screen column."
261 (let ((range (oref (oref c x-axis) bounds)))
263 (round (* (float (- x (car range)))
264 (/ (float (oref c x-width))
265 (float (- (cdr range) (car range))))))))
268 (defmethod chart-translate-ypos ((c chart) y)
269 "Translate in chart C the coordinate Y into a screen row."
270 (let ((range (oref (oref c y-axis) bounds)))
273 (round (* (float (- y (car range)))
274 (/ (float (oref c y-width))
275 (float (- (cdr range) (car range)))))))))
278 (defmethod chart-axis-draw ((a chart-axis-range) &optional dir margin zone start end)
279 "Draw axis information based upon a range to be spread along the edge.
280 A is the chart to draw. DIR is the direction.
281 MARGIN, ZONE, START, and END specify restrictions in chart space."
283 ;; We prefer about 5 spaces between each value
284 (let* ((i (car (oref a bounds)))
285 (e (cdr (oref a bounds)))
289 ;; want to jump by units of 5 spaces or so
290 (j (/ rng (/ (chart-size-in-dir (oref a chart) dir) 4)))
292 (if (= j 0) (setq j 1))
296 (format "%dM" (/ i 1000000)))
298 (format "%dK" (/ i 1000)))
301 (if (eq dir 'vertical)
302 (let ((x (+ (+ margin z) (if (oref a loweredge)
304 (if (< x 1) (setq x 1))
305 (chart-goto-xy x (chart-translate-ypos (oref a chart) i)))
306 (chart-goto-xy (chart-translate-xpos (oref a chart) i)
307 (+ margin z (if (oref a loweredge) -1 1))))
310 (chart-zap-chars (length s))
311 (put-text-property p1 (point) 'face (oref a labels-face))
315 (defmethod chart-translate-namezone ((c chart) n)
316 "Return a dot-pair representing a positional range for a name.
317 The name in chart C of the Nth name resides.
318 Automatically compensates for direction."
319 (let* ((dir (oref c direction))
320 (w (if (eq dir 'vertical) (oref c x-width) (oref c y-width)))
321 (m (if (eq dir 'vertical) (oref c y-margin) (oref c x-margin)))
323 (oref (if (eq dir 'vertical) (oref c x-axis) (oref c y-axis))
325 (lpn (/ (+ 1.0 (float w)) (float ns)))
327 (cons (+ m (round (* lpn (float n))))
328 (+ m -1 (round (* lpn (+ 1.0 (float n))))))
331 (defmethod chart-axis-draw ((a chart-axis-names) &optional dir margin zone start end)
332 "Draw axis information based upon A range to be spread along the edge.
333 Optional argument DIR is the direction of the chart.
334 Optional arguments MARGIN, ZONE, START and END specify boundaries of the drawing."
336 ;; We prefer about 5 spaces between each value
345 (setq odd (= (% (length s) 2) 1))
346 (setq r (chart-translate-namezone (oref a chart) i))
347 (if (eq dir 'vertical)
348 (setq p (/ (+ (car r) (cdr r)) 2))
349 (setq p (- (+ (car r) (/ (- (cdr r) (car r)) 2))
350 (/ (length (car s)) 2))))
351 (if (eq dir 'vertical)
352 (let ((x (+ (+ margin z) (if (oref a loweredge)
355 (if (< x 1) (setq x 1))
356 (if (> (length (car s)) (1- margin))
357 (setq x (+ x margin)))
359 (chart-goto-xy p (+ (+ margin z) (if (oref a loweredge)
364 (chart-zap-chars (length (car s)))
365 (put-text-property p1 (point) 'face (oref a labels-face))
370 (defmethod chart-draw-data ((c chart-bar))
371 "Display the data available in a bar chart C."
372 (let* ((data (oref c sequences))
373 (dir (oref c direction))
374 (odir (if (eq dir 'vertical) 'horizontal 'vertical))
377 (if (stringp (car (oref (car data) data)))
378 ;; skip string lists...
380 ;; display number lists...
382 (seq (oref (car data) data)))
384 (let* ((rng (chart-translate-namezone c i))
385 (dp (if (eq dir 'vertical)
386 (chart-translate-ypos c (car seq))
387 (chart-translate-xpos c (car seq))))
388 (zp (if (eq dir 'vertical)
389 (chart-translate-ypos c 0)
390 (chart-translate-xpos c 0)))
391 (fc (if chart-face-list
392 (nth (% i (length chart-face-list)) chart-face-list)
397 (chart-draw-line dir (car rng) dp zp)
398 (chart-draw-line dir (cdr rng) dp zp))
399 (chart-draw-line dir (car rng) zp (1+ dp))
400 (chart-draw-line dir (cdr rng) zp (1+ dp)))
401 (if (= (car rng) (cdr rng)) nil
402 (chart-draw-line odir dp (1+ (car rng)) (cdr rng))
403 (chart-draw-line odir zp (car rng) (1+ (cdr rng))))
405 (chart-deface-rectangle dir rng (cons dp zp) fc)
406 (chart-deface-rectangle dir rng (cons zp dp) fc))
408 ;; find the bounds, and chart it!
409 ;; for now, only do one!
412 (setq data (cdr data))))
415 (defmethod chart-add-sequence ((c chart) &optional seq axis-label)
416 "Add to chart object C the sequence object SEQ.
417 If AXIS-LABEL, then the axis stored in C is updated with the bounds of SEQ,
418 or is created with the bounds of SEQ."
420 (let ((axis (eieio-oref c axis-label)))
421 (if (stringp (car (oref seq data)))
422 (let ((labels (oref seq data)))
424 (setq axis (make-instance chart-axis-names
425 :name (oref seq name)
428 (oset axis items labels)))
429 (let ((range (cons 0 1))
432 (setq axis (make-instance chart-axis-range
433 :name (oref seq name)
436 (if (< (car l) (car range)) (setcar range (car l)))
437 (if (> (car l) (cdr range)) (setcdr range (car l)))
439 (oset axis bounds range)))
440 (if (eq axis-label 'x-axis) (oset axis loweredge nil))
441 (eieio-oset c axis-label axis)
443 (oset c sequences (append (oref c sequences) (list seq))))
445 ;;; Charting optimizers
447 (defmethod chart-trim ((c chart) max)
448 "Trim all sequences in chart C to be at most MAX elements long."
449 (let ((s (oref c sequences)))
451 (let ((sl (oref (car s) data)))
452 (if (> (length sl) max)
453 (setcdr (nthcdr (1- max) sl) nil)))
457 (defmethod chart-sort ((c chart) pred)
458 "Sort the data in chart C using predicate PRED.
459 See `chart-sort-matchlist' for more details."
460 (let* ((sl (oref c sequences))
464 (if (stringp (car (oref s1 data)))
466 (chart-sort-matchlist s1 s2 pred)
467 (setq s (oref s1 data)))
468 (if (stringp (car (oref s2 data)))
470 (chart-sort-matchlist s2 s1 pred)
471 (setq s (oref s2 data)))
472 (error "Sorting of chart %s not supported" (object-name c))))
473 (if (eq (oref c direction) 'horizontal)
474 (oset (oref c y-axis) items s)
475 (oset (oref c x-axis) items s)
479 (defun chart-sort-matchlist (namelst numlst pred)
480 "Sort NAMELST and NUMLST (both sequence objects) based on predicate PRED.
481 PRED should be the equivalent of '<, except it must expect two
482 cons cells of the form (NAME . NUM). See `sort' for more details."
483 ;; 1 - create 1 list of cons cells
485 (alst (oref namelst data))
486 (ulst (oref numlst data)))
488 ;; this is reversed, but were are sorting anyway
489 (setq newlist (cons (cons (car alst) (car ulst)) newlist))
490 (setq alst (cdr alst)
492 ;; 2 - Run sort routine on it
493 (setq newlist (sort newlist pred)
496 ;; 3 - Separate the lists
498 (setq alst (cons (car (car newlist)) alst)
499 ulst (cons (cdr (car newlist)) ulst))
500 (setq newlist (cdr newlist)))
501 ;; 4 - Store them back
502 (oset namelst data (reverse alst))
503 (oset numlst data (reverse ulst))))
507 (defun chart-goto-xy (x y)
508 "Move cursor to position X Y in buffer, and add spaces and CRs if needed."
509 (let ((indent-tabs-mode nil)
510 (num (progn (goto-char (point-min)) (forward-line y))))
511 (if (and (= 0 num) (/= 0 (current-column))) (newline 1))
512 (if (eobp) (newline num))
513 (if (< x 0) (setq x 0))
514 (if (< y 0) (setq y 0))
515 ;; Now, a quicky column moveto/forceto method.
516 (or (= (move-to-column x) x)
519 (remove-text-properties p (point) '(face))))))
521 (defun chart-zap-chars (n)
522 "Zap up to N chars without deleting EOLs."
524 (if (< n (- (point-at-eol) (point)))
526 (delete-region (point) (point-at-eol)))))
528 (defun chart-display-label (label dir zone start end &optional face)
529 "Display LABEL in direction DIR in column/row ZONE between START and END.
530 Optional argument FACE is the property we wish to place on this text."
531 (if (eq dir 'horizontal)
533 (chart-goto-xy (+ start (- (/ (- end start) 2) (/ (length label) 2)))
537 (chart-zap-chars (length label))
538 (put-text-property p1 (point) 'face face)
541 (stz (+ start (- (/ (- end start) 2) (/ (length label) 2)))))
542 (while (< i (length label))
543 (chart-goto-xy zone (+ stz i))
544 (insert (aref label i))
546 (put-text-property (1- (point)) (point) 'face face)
549 (defun chart-draw-line (dir zone start end)
550 "Draw a line using line-drawing characters in direction DIR.
551 Use column or row ZONE between START and END."
553 (make-string (- end start) (if (eq dir 'vertical) ?| ?\-))
556 (defun chart-deface-rectangle (dir r1 r2 face)
557 "Colorize a rectangle in direction DIR across range R1 by range R2.
558 R1 and R2 are dotted pairs. Colorize it with FACE."
559 (let* ((range1 (if (eq dir 'vertical) r1 r2))
560 (range2 (if (eq dir 'vertical) r2 r1))
562 (while (<= y (cdr range2))
563 (chart-goto-xy (car range1) y)
564 (put-text-property (point) (+ (point) (1+ (- (cdr range1) (car range1))))
568 ;;; Helpful `I don't want to learn eieio just now' washover functions
570 (defun chart-bar-quickie (dir title namelst nametitle numlst numtitle
571 &optional max sort-pred)
572 "Wash over the complex EIEIO stuff and create a nice bar chart.
573 Create it going in direction DIR ['horizontal 'vertical] with TITLE
574 using a name sequence NAMELST labeled NAMETITLE with values NUMLST
577 Set the chart's max element display to MAX, and sort lists with
578 SORT-PRED if desired."
579 (let ((nc (make-instance chart-bar
581 :key-label "8-m" ; This is a text key pic
584 (iv (eq dir 'vertical)))
585 (chart-add-sequence nc
586 (make-instance chart-sequece
589 (if iv 'x-axis 'y-axis))
590 (chart-add-sequence nc
591 (make-instance chart-sequece
594 (if iv 'y-axis 'x-axis))
595 (if sort-pred (chart-sort nc sort-pred))
596 (if (integerp max) (chart-trim nc max))
597 (switch-to-buffer (chart-new-buffer nc))
602 (defun chart-test-it-all ()
603 "Test out various charting features."
605 (chart-bar-quickie 'vertical "Test Bar Chart"
606 '( "U1" "ME2" "C3" "B4" "QT" "EZ") "Items"
607 '( 5 -10 23 20 30 -3) "Values")
610 ;;; Sample utility function
612 (defun chart-file-count (dir)
613 "Draw a chart displaying the number of different file extensions in DIR."
614 (interactive "DDirectory: ")
615 (if (not (string-match "/$" dir))
616 (setq dir (concat dir "/")))
617 (message "Collecting statistics...")
618 (let ((flst (directory-files dir nil nil t))
619 (extlst (list "<dir>"))
622 (let* ((j (string-match "[^\\.]\\(\\.[a-zA-Z]+\\|~\\|#\\)$" (car flst)))
623 (s (if (file-accessible-directory-p (concat dir (car flst)))
626 (substring (car flst) (match-beginning 1) (match-end 1))
628 (m (member s extlst)))
631 (let ((cell (nthcdr (- (length extlst) (length m)) cntlst)))
632 (setcar cell (1+ (car cell))))
633 (setq extlst (cons s extlst)
634 cntlst (cons 1 cntlst)))))
635 (setq flst (cdr flst)))
636 ;; Lets create the chart!
637 (chart-bar-quickie 'vertical "Files Extension Distribution"
638 extlst "File Extensions"
639 cntlst "# of occurrences"
641 '(lambda (a b) (> (cdr a) (cdr b))))
644 (defun chart-space-usage (d)
645 "Display a top usage chart for directory D."
646 (interactive "DDirectory: ")
647 (message "Collecting statistics...")
650 (b (get-buffer-create " *du-tmp*")))
653 (insert "cd " d ";du -sk * \n")
654 (message "Running `cd %s;du -sk *'..." d)
655 (call-process-region (point-min) (point-max) shell-file-name t
656 (current-buffer) nil)
657 (goto-char (point-min))
658 (message "Scanning output ...")
659 (while (re-search-forward "^\\([0-9]+\\)[ \t]+\\([^ \n]+\\)$" nil t)
660 (let* ((nam (buffer-substring (match-beginning 2) (match-end 2)))
661 (num (buffer-substring (match-beginning 1) (match-end 1))))
662 (setq nmlst (cons nam nmlst)
663 ;; * 1000 to put it into bytes
664 cntlst (cons (* (string-to-number num) 1000) cntlst))))
666 (error "No files found!"))
667 (chart-bar-quickie 'vertical (format "Largest files in %s" d)
671 '(lambda (a b) (> (cdr a) (cdr b))))
674 (defun chart-emacs-storage ()
675 "Chart the current storage requirements of Emacs."
677 (let* ((data (garbage-collect))
678 (names '("strings/2" "vectors"
681 "markers" "free mark"
682 ;; "floats" "free flt"
684 (nums (list (/ (nth 3 data) 2)
686 (car (car data)) ; conses
688 (car (nth 1 data)) ; syms
690 (car (nth 2 data)) ; markers
692 ;(car (nth 5 data)) ; floats are Emacs only
695 ;; Lets create the chart!
696 (chart-bar-quickie 'vertical "Emacs Runtime Storage Usage"
697 names "Storage Items"
700 (defun chart-emacs-lists ()
701 "Chart out the size of various important lists."
703 (let* ((names '("buffers" "frames" "processes" "faces"))
704 (nums (list (length (buffer-list))
705 (length (frame-list))
706 (length (process-list))
709 (if (fboundp 'x-display-list)
710 (setq names (append names '("x-displays"))
711 nums (append nums (list (length (x-display-list))))))
712 ;; Lets create the chart!
713 (chart-bar-quickie 'vertical "Emacs List Size Chart"
714 names "Various Lists"
717 (defun chart-rmail-from ()
718 "If we are in an rmail summary buffer, then chart out the froms."
720 (if (not (eq major-mode 'rmail-summary-mode))
721 (error "You must invoke chart-rmail-from in an rmail summary buffer"))
725 (goto-char (point-min))
726 (while (re-search-forward "\\-[A-Z][a-z][a-z] +\\(\\w+\\)@\\w+" nil t)
727 (let* ((nam (buffer-substring (match-beginning 1) (match-end 1)))
728 (m (member nam nmlst)))
729 (message "Scanned username %s" nam)
731 (let ((cell (nthcdr (- (length nmlst) (length m)) cntlst)))
732 (setcar cell (1+ (car cell))))
733 (setq nmlst (cons nam nmlst)
734 cntlst (cons 1 cntlst))))))
735 (chart-bar-quickie 'vertical "Username Occurrence in RMAIL box"
737 cntlst "# of occurrences"
739 '(lambda (a b) (> (cdr a) (cdr b))))
745 ;;; chart.el ends here