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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod show_iterator;

#[cfg(feature = "show_nalgebra")]
mod show_nalgebra;

#[cfg(feature = "show_ndarray")]
mod show_ndarray;

#[cfg(feature = "show_image")]
mod show_image;

use anyhow::Error;
use std::path::Path;
use std::path::PathBuf;
use std::time::SystemTime;

pub struct ContentInfo {
    pub mime_type: String,
    pub content: String,
}

pub trait Showable {
    fn to_content_info(&self) -> Result<ContentInfo, Error>;

    // the name of this function is hardcoded by evcxr
    fn evcxr_display(&self) {
        let ci = self
            .to_content_info()
            .expect("to be convertible into ContentInfo");
        show_text_in_jupyter(ci.mime_type, ci.content);
    }

    fn to_html_page(&self) -> Result<String, Error> {
        let dod = self.to_content_info()?;
        let content = CONTENT_EMBED_HTML_TEMPLATE.replace("{{ content }}", &dod.content);
        Ok(content.into())
    }

    fn to_html_file(&self) -> Result<PathBuf, Error> {
        let mut dir = std::env::temp_dir();
        dir.push(env!("CARGO_PKG_NAME"));
        //TODO security check that the user can read/write only his own files
        std::fs::create_dir_all(&dir)?;
        //TODO generate random/timestamp file
        let epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;

        let path = dir.join(format!("show-{}.html", epoch.as_nanos()));
        let html = self.to_html_page()?;
        std::fs::write(&path, html)?;
        Ok(path)
    }

    fn show_in_browser(&self) -> Result<(), Error> {
        let path = self.to_html_file()?;
        opener::open(path.as_os_str())?;
        Ok(())
    }

    fn show(&self) -> Result<(), Error> {
        match select_output() {
            Medium::Browser => self.show_in_browser(),
            Medium::Jupyter => {
                self.evcxr_display();
                Ok(())
            }
            _ => Ok(()),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Medium {
    Noop,
    Auto,
    Jupyter,
    Browser,
}

pub static OUTPUT: Medium = Medium::Auto;

fn select_output() -> Medium {
    use std::env;
    match OUTPUT {
        Medium::Auto if env::var("SHOWATA_MEDIUM").is_ok() => {
            match env::var("SHOWATA_MEDIUM").unwrap().to_lowercase().as_ref() {
                "jupyter" => Medium::Jupyter,
                "browser" => Medium::Browser,
                _ => Medium::Noop,
            }
        }
        Medium::Auto if env::var("EVCXR_IS_RUNTIME").is_ok() => Medium::Jupyter,
        Medium::Auto => Medium::Browser,
        ref m => m.clone(),
    }
}

const CONTENT_EMBED_HTML_TEMPLATE: &str = r#"
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
</head>
<body>

<div id="vis">
{{ content }}
</div>
</body>
</html>
"#;

/// Display content as text
///
/// ```rust
/// use showata::*;
///
/// let content = ".....";
/// show_text_in_jupyter("text/plain", content);
/// ```
/// TODO replace by evcxr_runtime ?
pub fn show_text_in_jupyter<M: AsRef<str>, S: AsRef<str>>(mime_type: M, text: S) {
    println!(
        "EVCXR_BEGIN_CONTENT {}\n{}\nEVCXR_END_CONTENT",
        mime_type.as_ref(),
        text.as_ref()
    );
}

/// Display bytes as base64 encoded
///
/// ```rust
/// use showata::*;
///
/// let buffer: Vec<u8> = vec![];
/// show_bytes_in_jupyter("image/png", &buffer);
/// ```
// TODO replace by evcxr_runtime ?
pub fn show_bytes_in_jupyter<S: AsRef<str>>(mime_type: S, buffer: &[u8]) {
    show_text_in_jupyter(mime_type, base64::encode(buffer))
}

/// Display the content of a local file.
///
/// ```rust
/// use showata::*;
/// use mime;
///
/// show_file_in_jupyter("local-img.png", "image/png", false);
/// show_file_in_jupyter("local-img.png", mime::IMAGE_PNG, false);
///
/// show_file_in_jupyter("hello.html", "text/html", true);
/// show_file_in_jupyter("hello.svg", mime::IMAGE_SVG, true);
/// ```
pub fn show_file_in_jupyter<P: AsRef<Path>, S: AsRef<str>>(
    path: P,
    mime_type: S,
    as_text: bool,
) -> Result<(), std::io::Error> {
    let buffer = std::fs::read(path)?;
    if as_text {
        let text = String::from_utf8_lossy(&buffer);
        show_text_in_jupyter(mime_type, &text);
    } else {
        show_bytes_in_jupyter(mime_type, &buffer);
    }
    Ok(())
}