/
cacoo.el
1930 lines (1643 loc) · 70.1 KB
/
cacoo.el
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; cacoo.el --- Minor mode for Cacoo (http://cacoo.com)
;; Copyright (C) 2010, 2011, 2012 SAKURAI Masashi
;; Author: SAKURAI Masashi <m.sakurai atmark kiwanami.net>
;; Keywords: convenience, diagram
;; URL: https://github.com/kiwanami/emacs-cacoo/
;; 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 3 of the License, or
;; (at your option) any later version.
;; 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.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; A minor mode for editing a document with Cacoo diagrams. Diagrams
;; are saved for local cache so that you can use the diagrams in the
;; offline environment. Diagrams are re-sized by ImageMagick
;; automatically and displayed in-line.
;; Integrating Emacs with Cacoo, the diagramming tool on the Web,
;; I'm sure that Emacs becomes the most powerful documentation tool.
;; Not only Cacoo diagrams, but also any images those are indicated by
;; the URL can be displayed.
;;; Installation:
;; This program is dependent on followings:
;; - anything.el (http://www.emacswiki.org/emacs/Anything)
;; - deferred.el (http://github.com/kiwanami/emacs-deferred/raw/master/deferred.el)
;; - concurrent.el (http://github.com/kiwanami/emacs-deferred/raw/master/concurrent.el)
;; - wget, ImageMagick(convert, identify, display)
;; Put cacoo.el and cacoo-plugins.el in your load-path, and add following code.
;; (require 'cacoo)
;; (require 'cacoo-plugins) ; option
;; (setq cacoo:api-key "APIKEY") ; option
;; (global-set-key (kbd "M--") 'toggle-cacoo-minor-mode) ; key bind example
;;; Usage:
;; This program replaces following markups into diagram images.
;; [img:https://cacoo.com/diagrams/6m4ATG1ddlUiHPqd-0FAF7.png]
;; `cacoo-minor-mode' defines some key binding.
;; (You can customize key bindings through `cacoo-minor-mode-keymap'.
;; * For all diagram markups
;; C-c , T : Revert all diagrams to text in the buffer.
;; C-c , D : Display all diagrams in the buffer. (Using local cache files)
;; C-c , R : Clear all cache files and retrieve diagram images again.
;; * For the just following markup
;; C-c , t : Revert to text
;; C-c , d : Display the diagram
;; C-c , r : Clear the cache file and retrieve the diagram image again
;; C-c , e : Open Cacoo editor with the browser (https://cacoo.com/diagrams/xxxxx/edit)
;; C-c , v : Open Cacoo detail page with the browser (https://cacoo.com/diagrams/xxxxx)
;; C-c , V : Open the diagram image with the external viewer.
;; * In the editing markup
;; C-c , g : Toggle text and image
;; * For Cacoo integration
;; C-c , N : Create a new diagram with the browser (https://cacoo.com/diagrams/new)
;; C-c , l : Open the diagram list with the browser (https://cacoo.com/diagrams/)
;; * Navigation and editing
;; C-c , n : Move to the next diagram
;; C-c , p : Move to the previous diagram
;; C-c , i : Insert a blank diagram markup
;; C-c , y : Insert a diagram markup with the clipboard(or kill-ring) text
;; * Etc
;; C-c , C : Remove all files in the cache directory
;; You can display following URLs:
;; (Of course, you can not edit the images with Cacoo!)
;; - Images on the Web
;; [img:http://example.com/zzz.png]
;; - Local images (absolute path)
;; [img:file:///xxx/yyy/zzz.png]
;; - Local images (abstract path from the visiting buffer)
;; [img:zzz.png]
;; If an error is occurred, this program highlight the markup text.
;; You can check the error messages with the mouse over pop-up. In
;; most cases, the troubles are 'program (wget, convert, identify) not
;; found' and 'the indicated image not found'.
;;; Customize:
;; This program uses `cacoo:browser-function' as default browser.
;; The default value is `browse-url-browser-function'.
;; Ex: for safari on Mac
;; (setq cacoo:browser-function 'browse-url-generic)
;; (setq browse-url-generic-program "open")
;; Changing `cacoo:img-regexp' and `cacoo:img-pattern', you can adopt
;; other markup format. The variable `cacoo:img-regexp' accepts a list
;; of regexp strings.
;; The directory name for the local cache files is set by
;; `cacoo:img-dir'. If you don't need confirmation of creating
;; directories, set `cacoo:img-dir-ok' non-nil.
;; Large images are reduced by `cacoo:max-size'.
;; You can specify the image size individually, like this.
;; [img:file:///xxx/yyy/zzz.png 600]
;; The external image viewer is set by `cacoo:external-viewer'.
;; If this variable is nil, open the image with Emacs.
;; In Emacs 22, the transparent color of PNG images may display as black.
;; Then, following code maybe solve the problem.
;; (setq cacoo:png-background "white")
;; This program can be extended by the plugin mechanism. See the comments
;; for the details (cacoo:plugin-***).
;;; History:
;; Revision 2.0 2011/03/03 sakurai
;; English translation for docstrings.
;; Re-build on the architecture of concurrent.el and deferred.el.
;; Added the anything interface for Cacoo diagrams.
;;
;; Revision 1.6 2010/07/19 sakurai
;; Added SVG plugin.
;;
;; Revision 1.5 2010/07/05 sakurai
;; Removing parameter strings from the URL.
;; Added a variable `cacoo:browser-function'.
;;
;; Revision 1.4 2010/06/17 sakurai
;; Improved `cacoo:img-regexp' that accepts a list of regexp strings.
;; Added a plugin of 'hatena fotolife'
;;
;; Revision 1.3 2010/05/10 sakurai
;; Added the plugin mechanism.
;; Added a variable `cacoo:translation-exts'.
;;
;; Revision 1.2 2010/05/08 sakurai
;; Bug fixed: byte-compiling (thx id:kitokitoki)
;; Added: some documents.
;; Improved: mouse clicking.
;;
;; Revision 1.1 2010/05/08 sakurai
;; Improved: highlighting error markups by overlay.
;; Improved: asynchronous tasks.
;; Improved: adopting transparent PNG and older ImageMagick program.
;;
;; Revision 1.0 2010/05/07 sakurai
;; Initial revision
;;; Code:
(eval-when-compile (require 'cl))
(require 'url-file)
(require 'concurrent)
(require 'json)
(defvar cacoo:version nil "version number")
(setq cacoo:version "2.0")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Customize variables
(defvar cacoo:api-key nil "Set your API key!")
(defvar cacoo:img-regexp "\\[img:\\(.*\\)\\][^]\n\r]*$" "Markup regexp for searching diagrams.")
(defvar cacoo:img-pattern "[img:%s]" "Pattern for inserting a markup")
(defvar cacoo:img-dir ".cimg" "Directory name for cache files.")
(defvar cacoo:img-dir-ok nil "If non-nil, this program does not confirm creating a cache directory.")
(defvar cacoo:process-num 4 "Maximum external process number")
(defvar cacoo:cmd-copy "cp" "Copy command")
(defvar cacoo:copy-by-command t "If non-nil, this program copies files by the external command asynchronously. If nil, this program uses Emacs copy function `copy-file' synchronously.")
(defvar cacoo:max-size 450 "Default maximum image size.")
(defvar cacoo:external-viewer "display" "External viewer command. If nil, this program opens the image file in Emacs.")
(defvar cacoo:png-background nil "If the transparent color of PNG images seems not to be good, set it non-nil.")
(make-variable-buffer-local 'cacoo:png-background)
(defvar cacoo:translation-exts '("eps" "ps" "svg" "pdf" "tif") "A list of the extensions those need to translate to display in Emacs.")
(defvar cacoo:browser-function browse-url-browser-function "The browser to open the Cacoo editor.")
(defvar cacoo:http-get-file-cmd '("wget" "-q" "-S" "--no-check-certificate" "-O" output-file url))
(defvar cacoo:http-get-stdout-cmd '("wget" "-q" "-O" "-" url))
(defvar cacoo:api-diagrams-cache-dir "~/.emacs.d/cacoo/" "Cache directory for Cacoo data.")
(defvar cacoo:api-diagrams-cache-file "diagrams.dat" "Cache file for Cacoo diagrams.")
;;; Internal variables
(defvar cacoo:key-regexp "diagrams\\/\\([a-zA-Z0-9]*\\)" "Regexp for extracting a diagram key in Cacoo.")
(defvar cacoo:api-url-base "https://cacoo.com/api/v1/" "[internal] Cacoo API base URL.")
(defvar cacoo:base-url "https://cacoo.com/diagrams/" "[internal] The base URL in Cacoo")
(defvar cacoo:new-url (concat cacoo:base-url "new") "[internal] URL for creating a diagram in Cacoo")
(defvar cacoo:edit-url (concat cacoo:base-url "%KEY%/edit") "[internal] URL for editing a diagram in Cacoo")
(defvar cacoo:view-url (concat cacoo:base-url "%KEY%") "[internal] URL for the diagram details in Cacoo")
(defvar cacoo:list-url cacoo:base-url "[internal] URL for the diagram list in Cacoo")
(defvar cacoo:plugins nil "[internal] A list of plugin symbols.")
(defvar cacoo:process-semaphore nil "[internal] Semaphore object for external processes. The number of processes is controlled by `cacoo:process-num'.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Fundamental Functions
(defmacro cacoo:aif (test-form then-form &rest else-forms)
(declare (debug (form form &rest form)))
`(let ((it ,test-form))
(if it ,then-form ,@else-forms)))
(put 'cacoo:aif 'lisp-indent-function 2)
(defun cacoo:define-keymap (keymap-list)
(let ((map (make-sparse-keymap)))
(mapc
(lambda (i)
(define-key map
(if (stringp (car i))
(read-kbd-macro (car i)) (car i))
(cdr i)))
keymap-list)
map))
(defun cacoo:k (key alist)
(or (cdr (assq key alist)) ""))
;;; for debug
(eval-and-compile
(defvar cacoo:debug nil "Debug output switch.")) ; debug
(defvar cacoo:debug-count 0 "[internal] Debug output counter.") ; debug
(defmacro cacoo:log (&rest args)
"[internal] Debug macro."
(when cacoo:debug
`(progn
(with-current-buffer (get-buffer-create "*cacoo:debug*")
(save-excursion
(goto-char (point-max))
(insert (format "%5i %s\n" cacoo:debug-count (format ,@args)))))
(incf cacoo:debug-count))))
(defun cacoo:message-mark ()
"[internal] Debug marker."
(interactive)
(cacoo:log "==================== mark ==== %s"
(format-time-string "%H:%M:%S" (current-time))))
(defun cacoo:debug-report-semaphore ()
"[internal] Show current status of semaphores."
(interactive)
(message
"Semaphore: process permits: %s / waiting: %s preview permit: %s / waiting: %s"
(cc:semaphore-permits cacoo:process-semaphore)
(length (cc:semaphore-waiting-deferreds cacoo:process-semaphore))
(cc:semaphore-permits cacoo:preview-semaphore)
(length (cc:semaphore-waiting-deferreds cacoo:preview-semaphore))))
(defmacro cacoo:api-debug-deferred (d msg &rest args)
"[internal] Debug message output of deferred tasks."
`(deferred:nextc ,d
(lambda (x) (funcall 'message ,msg ,@args) x)))
(defun cacoo:api-debug-dbuffer (d)
"[internal] Debug pp output of deferred tasks."
(deferred:nextc d
(lambda (x)
(pop-to-buffer
(with-current-buffer (get-buffer-create "*cacoo:api*")
(erase-buffer)
(insert (pp-to-string x))
(current-buffer))))))
;;; File Utilities
(defun cacoo:get-cache-dir()
"[internal] Return the cache directory for current buffer. If
current buffer does not have visiting file, return
`default-directory'."
(let* ((base-dir (file-name-directory
(or buffer-file-name
default-directory))))
(expand-file-name cacoo:img-dir base-dir)))
(defun cacoo:fix-directory ()
"[internal] Make a directory for cache files in the current
directory which has visiting file."
(let* ((img-dir (cacoo:get-cache-dir)))
(unless (file-directory-p img-dir)
(when (or cacoo:img-dir-ok
(y-or-n-p
(format "Image directory [%s] not found. Create it ?"
cacoo:img-dir)))
(make-directory img-dir))
(unless (file-directory-p img-dir)
(error "Could not create a image directory.")))
img-dir))
(defun cacoo:get-cache-path (filename)
"[internal] Return an absolute path for the cache file for
FILENAME. FILENAME does not include directory path. If the cache
directory does not exist, this function creates it."
(expand-file-name
filename (cacoo:get-cache-dir)))
(defun cacoo:get-resize-path (filename size)
"[internal] Return an absolute path for the resized cache file for
FILENAME. FILENAME does not include directory path. If the cache
directory does not exist, this function creates it."
(let ((ext (file-name-extension filename)))
(expand-file-name
(format "resize_%s_%s"
size
(if (member ext cacoo:translation-exts)
(replace-regexp-in-string
(concat "\\." ext "$") ".png" filename)
filename))
(cacoo:get-cache-dir))))
(defun cacoo:get-filename-from-url (url)
"[internal] Return a filename that does not include directory
path from URL. URL can also be a local relative path."
(cond
((string-match "^http" url)
(url-file-nondirectory url))
(t
(if (string-match "[^/]*$" url)
(match-string 0 url)))))
(defun cacoo:get-cache-path-from-url (url)
"[internal] Return an absolute path for the cache of
URL. If the cache directory does not exist, this function creates
it."
(cacoo:get-cache-path (cacoo:get-filename-from-url url)))
(defun cacoo:get-resize-path-from-url (url size)
"[internal] Return an absolute path for the resized cache of
URL. If the cache directory does not exist, this function creates
it."
(cacoo:get-resize-path (cacoo:get-filename-from-url url) size))
(defun cacoo:get-local-path-from-url(url)
"[internal] Return an absolute path for the cache of URL for
local filesystem."
(cond
((string-match "^file://\\(.*\\)$" url) ; assuming full path
(match-string 1 url))
((cacoo:file-exists-p (expand-file-name url default-directory))
(expand-file-name url default-directory))
(t
nil)))
(defun cacoo:file-exists-p (file)
"[internal] Return non-nil, if FILE exists and the file size is
larger than zero byte."
(cond
((file-exists-p file)
(cond
((< 0 (nth 7 (file-attributes file))) t)
(t (delete-file file) nil)))
(t nil)))
(defun cacoo:get-image-type (file)
"[internal] Return the image type as symbol. This function
guesses from the filename extension."
(let ((type (intern (downcase (file-name-extension file)))))
(cond
((eq type 'jpg) 'jpeg)
(t type))))
(defun cacoo:get-key-from-url (url)
"[internal] Return the key string of the cacoo diagram of
URL. If URL has no key, return nil."
(if (string-match cacoo:key-regexp url)
(match-string 1 url)
nil))
(defun cacoo:make-url (tmpl-url key)
"[internal] Return an URL which is compiled from TMPL-URL and KEY."
(if key (replace-regexp-in-string "%KEY%" key tmpl-url t) nil))
(defun cacoo:list-template (template-list data-alist)
"[internal] Return an expanded list which is compiled
TEMPLATE-LIST and DATA-ALIST."
(loop for i in template-list
collect
(cond
((symbolp i)
(cacoo:k i data-alist))
(t i))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Cacoo API Functions
(defun cacoo:api-param-serialize (params)
"[internal] Return an serialized string for URL in which PARAMS are encoded."
(cond
(params
(mapconcat
'identity
(loop for p in params
collect (format "%s=%s" (car p) (cdr p)))
"&"))
(t "")))
(defvar cacoo:api-cancel-flag nil
"[internal] Global working state. The deferred tasks watch this variable.")
(defun cacoo:api-get-d (method &optional params)
"[internal] Return a deferred object which retrieves a JSON
data via cacoo API. The next deferred receives an alist that is
parsed as JSON. If something is wrong, `nil' is passed."
(lexical-let
((url (concat cacoo:api-url-base method ".json"
"?" (cacoo:api-param-serialize
(cons (cons 'apiKey cacoo:api-key)
params)))))
(cc:semaphore-with cacoo:process-semaphore
(lambda (x)
(unless cacoo:api-cancel-flag
(deferred:$
(apply 'deferred:process
(cacoo:list-template
cacoo:http-get-stdout-cmd `((url . ,url))))
(deferred:nextc it
(lambda (x)
(let ((json-array-type 'list))
(json-read-from-string x))))))))))
(defun cacoo:http-get-apikey (url)
"[internal] Return a cacoo diagram key which is extracted from
URL. If no key is found, return nil."
(if (and cacoo:api-key
(string-match (regexp-quote cacoo:api-url-base) url))
(concat url "?" (cacoo:api-param-serialize
(list (cons 'apiKey cacoo:api-key))))
url))
(defun cacoo:http-get-d (url output-path)
"[internal] Return a deferred object which retrieves a file via
HTTP GET. The received file is saved as OUTPUT-PATH. The next
deferred object receives `nil' if receiving finishes normally.
If something is wrong, the http-response text is passed."
(lexical-let ((url (cacoo:http-get-apikey url))
(output-path output-path))
(cacoo:log " >> URL %s" url)
(deferred:try
(deferred:$
(apply 'deferred:process
(cacoo:list-template
cacoo:http-get-file-cmd
`((output-file . ,output-path) (url . ,url))))
(deferred:nextc it
(lambda (response-text)
(cacoo:log " >> RESPONSE : %s" response-text)
(let* ((headers (split-string response-text "[\r\n]+"))
(response (car headers)))
(if (string-match "200" response)
nil
(ignore-errors (delete-file output-path))
(cacoo:log " >> RESPONSE : %s" response-text)
response)))))
:catch
(lambda (err)
(cacoo:log " >> HTTP GET Error : %s" err)
(error (format "Can not access / HTTP GET : %s" url))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Struct
;; cacoo:$img : Structure for the image markups
;; url : URL for an image or relative path. It is also a key for the dataflow variable.
;; start : Start point for a markup
;; end : End point for a markup
;; size : Maximum pixel size along the long axis.
(defstruct cacoo:$img url start end size)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Image Workplace
(defun cacoo:image-wp-resized-equal (a b)
"[internal] If the URL and image size of A is identical to ones of B, return non-nil."
(and (string-equal (car a) (car b))
(equal (cdr a) (cdr b))))
(defvar cacoo:image-wp-original nil "[internal] Dataflow environment object for cache files.")
(defvar cacoo:image-wp-resized nil "[internal] Dataflow environment object for resized cache files.")
(make-variable-buffer-local 'cacoo:image-wp-original)
(make-variable-buffer-local 'cacoo:image-wp-resized)
(defun cacoo:image-wp-init ()
"[internal] Initialize image workplaces those are implemented by dataflow objects."
(setq cacoo:process-semaphore (cc:semaphore-create cacoo:process-num)
cacoo:image-wp-original (cc:dataflow-environment nil 'equal)
cacoo:image-wp-resized (cc:dataflow-environment nil 'cacoo:image-wp-resized-equal))
(cc:dataflow-connect cacoo:image-wp-original 'get-first 'cacoo:image-wp-create-original)
(cc:dataflow-connect cacoo:image-wp-resized 'get-first 'cacoo:image-wp-create-resized)
(when cacoo:debug
(cc:dataflow-connect
cacoo:image-wp-original t (lambda (args) (cacoo:log "DF ORG / %S" args)))
(cc:dataflow-connect
cacoo:image-wp-resized t (lambda (args) (cacoo:log "DF RSZ / %S" args)))))
(defun cacoo:image-wp-get-resized-d (url size)
"[internal] Return a deferred object to get the resized cache
file from the image workplace. The next deferred object receives
the image path."
(cc:dataflow-get cacoo:image-wp-resized (cons url size)))
(defun cacoo:image-wp-get-original-d (url)
"[internal] Return a deferred object to get the cache file from
the image workplace. The next deferred object receives the image
path."
(cc:dataflow-get cacoo:image-wp-original url))
(defun cacoo:image-wp-set-resized (url size file)
"[internal] Bind the resized cache file to the cons pair (url . size)
in the image workplace. The waiting tasks will receive the notification of binding."
(cc:dataflow-set cacoo:image-wp-resized
(cons (substring-no-properties url) size) file))
(defun cacoo:image-wp-set-original (url file)
"[internal] Bind the cache file to the URL in the image
workplace. The waiting tasks will receive the notification of
binding."
(cc:dataflow-set cacoo:image-wp-original
(substring-no-properties url) file))
(defun cacoo:image-wp-clear-cache (url &optional size)
"[internal] Clear the information related to URL from the image
workplaces and delete the corresponding cache files."
;; remove the cache file for the original image.
(cacoo:aif (cc:dataflow-get-sync cacoo:image-wp-original url)
(progn
(if (and (stringp it) (file-exists-p it))
(ignore-errors (delete-file it)))
(cc:dataflow-clear cacoo:image-wp-original url))
(let ((file (cacoo:get-cache-path-from-url url)))
(when (cacoo:file-exists-p file)
(ignore-errors (delete-file file)))))
;; remove the cache file for the re-sized image.
(let ((remove-keys
(loop for i in (cc:dataflow-get-avalable-pairs
cacoo:image-wp-resized)
for key = (car i)
for key-url = (car key)
if (equal url key-url)
collect key)))
(loop for i in remove-keys
do
(cacoo:aif (cc:dataflow-get-sync cacoo:image-wp-resized i)
(progn
(if (and (stringp it) (file-exists-p it))
(ignore-errors (delete-file it)))
(cc:dataflow-clear cacoo:image-wp-resized i)))))
(when size
(let ((file (cacoo:get-resize-path-from-url url size)))
(when (cacoo:file-exists-p file)
(ignore-errors (delete-file file))))))
;;; Event handling
(defun cacoo:image-wp-create-resized (args)
"[internal] Event handler for `get-first' of
`cacoo:image-wp-resized'. This handler resizes the image and
registers it to the image workplace `cacoo:image-wp-resized'."
(destructuring-bind (event ((url . size))) args
(cacoo:resize-diagram url size)))
(defun cacoo:image-wp-create-original (args)
"[internal] Event handler for `get-first' of
`cacoo:image-wp-original'. This handler gets the image and
registers it to the image workplace `cacoo:image-wp-original'."
(destructuring-bind (event (url)) args
(cacoo:fix-directory)
(cond
((cacoo:plugin-url-p url) ; plugins
(cacoo:load-diagram-plugin url))
((string-match "^file:\\/\\/\\/" url) ; local
(cacoo:load-diagram-local url))
((string-match "^https?:\\/\\/" url) ; web
(cacoo:load-diagram-remote url))
(t ; relative path
(cacoo:load-diagram-local url)))))
;;; Create Original Image Cache
(defun cacoo:load-diagram-plugin(url)
"[internal] Make a resource by the plugin for URL and register it to the image workplace.
If something is wrong, the error message is registered."
(lexical-let ((url url) (cache-path (cacoo:get-cache-path-from-url url)))
(cond
((cacoo:file-exists-p cache-path)
(cacoo:log ">> found cache file : %s" cache-path)
(cacoo:image-wp-set-original url cache-path))
((cacoo:plugin-creator-get url)
(deferred:try
(deferred:$
(funcall (cacoo:plugin-creator-get url))
(deferred:nextc it
(lambda (x)
(if (cacoo:file-exists-p cache-path)
(cacoo:image-wp-set-original url cache-path)
(error "Can not get the image file.")))))
:catch
(lambda (e) (cacoo:image-wp-set-original url (cons 'error e)))))
(t
(cacoo:image-wp-set-original
url (cons 'error (format "Can not found plugin creator. (BUG) %S" url)))))))
(defun cacoo:load-diagram-remote(url)
"[internal] Retrieve a resource of URL and register it to the image workplace.
If something is wrong, the error message is registered."
(cacoo:log ">> cacoo:load-diagram-remote : %s" url)
(lexical-let* ((cache-path (cacoo:get-cache-path-from-url url))
(url url))
(cond
((cacoo:file-exists-p cache-path)
(cacoo:log ">> found cache file : %s" cache-path)
(cacoo:image-wp-set-original url cache-path))
(t
(cacoo:log ">> http request : %s" url)
(cc:semaphore-with cacoo:process-semaphore
(lambda (x)
(deferred:$
(cacoo:http-get-d url cache-path)
(deferred:nextc it
(lambda (x)
(cacoo:image-wp-set-original
url (if (cacoo:file-exists-p cache-path) cache-path
(cons 'error "File not found")))))))
(lambda (e)
(cacoo:image-wp-set-original url (cons 'error e))))))))
(defun cacoo:load-diagram-local(url)
"[internal] Retrieve a resource of URL and register it to the image workplace.
If something is wrong, the error message is registered."
(cacoo:log ">> cacoo:load-diagram-local : %s" url)
(lexical-let
((url url)
(from-path (cacoo:get-local-path-from-url url))
(cache-path (cacoo:get-cache-path-from-url url)))
(cond
((cacoo:file-exists-p cache-path)
(cacoo:log ">> found cache file : %s" cache-path)
(cacoo:image-wp-set-original url cache-path))
(t
(cc:semaphore-with cacoo:process-semaphore
(lambda (x)
(deferred:$
(cacoo:copy-file-d from-path cache-path)
(deferred:nextc it
(lambda (x) (cacoo:image-wp-set-original url cache-path)))))
(lambda (e)
(cacoo:image-wp-set-original
url (cons 'error (format "Can not copy file %s -> %s" from-path cache-path)))))))))
(defun cacoo:copy-file-d (from-path to-path)
"[internal] Return a deferred object to copy a file
asynchronously. If something is wrong, the copy task throws an
error that should be caught by some errorback."
(cacoo:log ">> local copy : %s" from-path)
(lexical-let ((from-path from-path) (to-path to-path))
(deferred:$
(if cacoo:copy-by-command
(deferred:process cacoo:cmd-copy from-path to-path)
(deferred:next
(lambda (x) (ignore-errors (copy-file from-path to-path t t)))))
(deferred:nextc it
(lambda (x)
(unless (cacoo:file-exists-p to-path)
(error "Can not copy the file : %s -> %s" from-path to-path)))))))
;;; Create Resized Image Cache
(defun cacoo:identify-diagram-d (filename)
"[internal] Return a deferred object to get image size. The next deferred object receives pixel size along the long axis."
(lexical-let ((filename filename))
(deferred:$
(deferred:process "identify" "-format" "%w %h" filename)
(deferred:nextc it
(lambda (line)
(cacoo:log ">> identify : %s" line)
(let* ((cols (split-string line " "))
(width (string-to-number (car cols)))
(height (string-to-number (cadr cols))))
(cacoo:log "SIZE %S > %s" line (max width height))
(max width height)))))))
(defun cacoo:resize-diagram (url max-size)
"[internal] Resize the cache file for URL with MAX-SIZE and
register the resized file to the image workplace. This function
gets the original cache file from the image workplace
`cacoo:image-wp-original'. The actual resizing task is executed by
the function `cacoo:resize-diagram-convert'."
(cacoo:log ">> cacoo:resize-diagram : %s / %s" url max-size)
(lexical-let ((url url) (max-size max-size))
(deferred:$
(cacoo:image-wp-get-original-d url)
(deferred:nextc it
(lambda (x)
(cacoo:log ">> get : %S" x)
(cond
((and x (consp x) (eq 'error (car x)))
(cacoo:image-wp-set-resized url max-size (cons 'error (cdr x))))
(t
(cacoo:resize-diagram-convert url max-size x))))))))
(defun cacoo:resize-diagram-convert (url max-size filename)
"[internal] Resize the cache file for URL with MAX-SIZE and
register the resized file to the image workplace. This function
is called by the function `cacoo:resize-diagram'."
(cacoo:log ">> cacoo:resize-diagram-convert : %s / %s" url max-size)
(lexical-let ((url url) (max-size max-size) (filename filename)
(resize-path (cacoo:get-resize-path-from-url url max-size)))
(cond
((cacoo:file-exists-p resize-path)
(cacoo:log ">> found cache file : %s" resize-path)
(cacoo:image-wp-set-resized url max-size resize-path))
(t
(cc:semaphore-with cacoo:process-semaphore
(lambda (x)
(deferred:$
(cacoo:identify-diagram-d filename)
(deferred:nextc it
(lambda (org-size)
(let ((not-resizep (< org-size max-size)))
(cond
((= 0 org-size)
(cacoo:image-wp-set-resized
url max-size (cons 'error (format "Can not copy file %s" url))))
(cacoo:png-background
(cacoo:resize-diagram-for-fillbg url max-size not-resizep))
(t
(cacoo:resize-diagram-for-transparent url max-size not-resizep)))
nil)))))
(lambda (e)
(cacoo:image-wp-set-resized url max-size (cons 'error e))))))))
(defun cacoo:resize-diagram-for-transparent (url max-size not-resizep)
"[internal] Resize the cache file for URL by the later version of command `convert'."
(cacoo:log ">> cacoo:resize-diagram-for-transparent : %s / %s / not-resize: %s"
url max-size not-resizep)
(lexical-let
((url url) (max-size max-size)
(cache-path (cacoo:get-cache-path-from-url url))
(resize-path (cacoo:get-resize-path-from-url url max-size)))
(deferred:try
(deferred:$
(if (and not-resizep
(equal (file-name-extension cache-path)
(file-name-extension resize-path)))
(cacoo:copy-file-d cache-path resize-path)
(deferred:process
"convert" "-resize" (format "%ix%i" max-size max-size)
"-transparent-color" "#ffffff"
cache-path (concat (file-name-extension resize-path)
":" resize-path)))
(deferred:nextc it
(lambda (msg)
(if (cacoo:file-exists-p resize-path)
(cacoo:image-wp-set-resized url max-size resize-path)))))
:catch
(lambda (msg)
(cacoo:image-wp-set-resized
url max-size (cons 'error (format "Can not resize image %s -> %s"
cache-path resize-path)))))))
(defun cacoo:get-background-img-path (path)
(expand-file-name
(format "back_%s" (file-name-nondirectory path))
(file-name-directory path)))
(defun cacoo:resize-diagram-for-fillbg (url max-size not-resizep)
(cacoo:log ">> cacoo:resize-diagram-for-fillbg : %s / %s / resize: %s" url max-size not-resizep)
(lexical-let*
((url url) (max-size max-size)
(cache-path (cacoo:get-cache-path-from-url url))
(resize-path (cacoo:get-resize-path-from-url url max-size))
resize-size
(tmpfile (cacoo:get-background-img-path cache-path)))
(deferred:$
(if (and not-resizep ; small
(equal (file-name-extension cache-path)
(file-name-extension resize-path)))
(cacoo:copy-file-d cache-path resize-path)
(deferred:process
"convert" cache-path "-resize" (format "%ix%i" max-size max-size)
(concat (file-name-extension resize-path) ":" resize-path)))
(deferred:processc it ; get the resized image size
"identify" "-format" "%wx%h" resize-path)
(deferred:nextc it ; make a background image
(lambda (dim) (deferred:process "convert" "-size" dim
(concat "xc:" cacoo:png-background) tmpfile)))
(deferred:processc it "convert" tmpfile resize-path "-flatten" resize-path)
(deferred:nextc it
(lambda (x)
(if (cacoo:file-exists-p resize-path)
(cacoo:image-wp-set-resized url max-size resize-path))))
(deferred:error it
(lambda (msg)
(cacoo:image-wp-set-resized url max-size
(cons 'error (format "Can not resize image %s -> %s"
cache-path resize-path))))))))
;;; Display
(defun cacoo:display-diagram-revert (data)
(let ((mod (buffer-modified-p))
(start (cacoo:$img-start data))
(end (cacoo:$img-end data)))
(remove-text-properties start end
'(display nil mouse-face nil help-echo nil keymap nil))
(cacoo:display-diagram-overlay-remove start end)
(set-buffer-modified-p mod)))
(defun cacoo:display-diagram (data)
(lexical-let ((data data)
(start (cacoo:$img-start data))
(end (cacoo:$img-end data)))
(cacoo:log ">> cacoo:display-diagram : %s / %s" (cacoo:$img-url data) (cacoo:$img-size data))
(cacoo:counter-add)
(deferred:$
(cacoo:image-wp-get-resized-d (cacoo:$img-url data) (cacoo:$img-size data))
(deferred:nextc it
(lambda (x)
(cacoo:log ">> get(display) : %S" x)
(if (and x (consp x) (eq 'error (car x))) (error (cdr x))
(cacoo:display-diagram-by-image x data))))
(deferred:error it
(lambda (e) (cacoo:display-diagram-by-text start end e)))
(deferred:watch it
(lambda (x) (cacoo:counter-burn))))))
(defun cacoo:display-diagram-by-image (image-file data)
(cacoo:log ">> cacoo:display-diagram-by-image : %s <- %s / %s"
image-file (cacoo:$img-url data) (cacoo:$img-size data))
(clear-image-cache)
(let ((img (ignore-errors
(create-image image-file
(cacoo:get-image-type image-file) nil
:relief 1)))
(start (cacoo:$img-start data))
(end (cacoo:$img-end data))
(map (make-sparse-keymap))
(mod (buffer-modified-p)))
(cond
((null img)
(cacoo:display-diagram-by-text
start end (format "The Emacs could not display this image type.")))
(t
(define-key map [mouse-1] 'cacoo:do-click-link)
(define-key map (kbd "\n") 'cacoo:do-click-link)
(add-text-properties
start end (list 'display img 'keymap map 'mouse-face 'highlight))
(cacoo:display-diagram-overlay-remove start end)
(set-buffer-modified-p mod)))))
(defun cacoo:do-click-link ()
(interactive)
(beginning-of-line)
(cacoo:do-next-diagram
(lambda (data)
(let ((url (cacoo:$img-url data))
(pos-end (cacoo:$img-start data))
(pos-start (cacoo:$img-start data)))
(goto-char pos-start)
(beginning-of-line)
(cond
((string-match "^file:\\/\\/\\/" url)
(cacoo:view-original-cached-image
(cacoo:$img-url data))
pos-end)
((string-match "^https?:\\/\\/" url)
(cacoo:edit-next-diagram-command)
pos-end)
(t ; assuming a relative path.
(cacoo:view-original-cached-image
(cacoo:$img-url data))
pos-end))))))
(defun cacoo:display-diagram-by-text (start end msg)
(cacoo:log ">> cacoo:display-diagram-by-text : %s" msg)
(let ((mod (buffer-modified-p)))
(put-text-property start end
'help-echo (format "Cacoo: Error %s" msg))
(cacoo:display-diagram-overlay-add start end)
(set-buffer-modified-p mod)))
;;; Error overlays
(defvar cacoo:display-diagram-overlays nil "[internal] a list of the overlay objects.")
(make-variable-buffer-local 'cacoo:display-diagram-overlays)
(defun cacoo:display-diagram-overlay-add (start end)
(when
(loop for i in cacoo:display-diagram-overlays
if (and ; checking current overlays
(< start (overlay-end i))
(> end (overlay-start i)))
return nil
finally return t)
(let ((ol (make-overlay start end)))
(overlay-put ol 'face 'next-error)
(push ol cacoo:display-diagram-overlays))))
(defun cacoo:display-diagram-overlay-remove (start end)
(setq cacoo:display-diagram-overlays
(loop for i in cacoo:display-diagram-overlays
if (and
(overlay-buffer i)
(or
(> start (overlay-end i))
(< end (overlay-start i))))
collect i
else
do (delete-overlay i))))
(defun cacoo:display-diagram-overlay-clear ()
(loop for i in cacoo:display-diagram-overlays
if (overlay-buffer i)
do (delete-overlay i))
(setq cacoo:display-diagram-overlays nil))
;;; Navigation
(defun cacoo:image-search (&optional backward)
"[internal] Return the point of beginning of the image
markup. If BACKWARD is non-nil, this function searches backward.
If the value `cacoo:img-regexp' is a string, this function just
uses it as a regexp. If the value is a list of strings, this
function tries all patterns and chooses the nearest point."
(let ((f (if backward 're-search-backward 're-search-forward))
(cmp (if backward '> '<)))
(cond
((stringp cacoo:img-regexp)
(funcall f cacoo:img-regexp nil t))
((listp cacoo:img-regexp)
(loop for re in cacoo:img-regexp
with val = nil ; (pos . match-data)
do
(save-excursion
(let ((pos (funcall f re nil t)))
(when pos
(when (or (null val) (funcall cmp pos (car val)))
(setq val (cons pos (match-data)))))))
finally return
(progn
(if val
(progn
(set-match-data (cdr val))
(goto-char (car val))
(car val))))))
(t
(error "cacoo:img-regexp is not regexp pattern. [%s]" cacoo:img-regexp)))))
(defun cacoo:try-plugins (start end content)
"[internal] If a plugin handles the region, return an image
object of structure `cacoo:$img'. Otherwise return nil."
(loop for i in cacoo:plugins
for (data . creator) = (funcall i start end content)
if data
return (progn
(cacoo:plugin-creator-add (cacoo:$img-url data) creator)