]> gitweb.factorcode.org Git - factor.git/blob - extra/wolfram-alpha/wolfram-alpha.factor
core: Change lines -> read-lines, contents -> read-contents, string-lines -> lines
[factor.git] / extra / wolfram-alpha / wolfram-alpha.factor
1 ! Copyright (C) 2011 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3
4 USING: accessors colors.constants formatting http http.client
5 images.gif images.http io io.styles kernel namespaces sequences
6 splitting ui urls.encoding xml xml.data xml.traversal ;
7
8 IN: wolfram-alpha
9
10 SYMBOL: wolfram-api-id
11
12 ! "XXXXXX-XXXXXXXXXX" wolfram-api-id set-global
13
14 <PRIVATE
15
16 : query ( query -- xml )
17     url-encode wolfram-api-id get-global
18     "http://api.wolframalpha.com/v2/query?input=%s&appid=%s"
19     sprintf http-get nip string>xml
20     dup "error" tag-named [
21         "msg" tag-named children>string throw
22     ] when* ;
23
24 PRIVATE>
25
26 : wolfram-image. ( query -- )
27     query "pod" tags-named [
28         [
29             "title" attr "%s:\n" sprintf H{
30                 { foreground COLOR: slate-gray }
31                 { font-name "sans-serif" }
32                 { font-style bold }
33             } format
34         ] [
35             "img" deep-tags-named [
36                 "src" attr "  " write http-image.
37             ] each
38         ] bi
39     ] each ;
40
41 : wolfram-text. ( query -- )
42     query "pod" tags-named [
43         [ "title" attr "%s:\n" printf ]
44         [
45             "plaintext" deep-tags-named [
46                 children>string lines
47                 [ "  %s\n" printf ] each
48             ] each
49         ] bi
50     ] each ;
51
52 : wolfram. ( query -- )
53     ui-running? [ wolfram-image. ] [ wolfram-text. ] if ;