-
Notifications
You must be signed in to change notification settings - Fork 14
/
converter.rs
839 lines (736 loc) · 25.6 KB
/
converter.rs
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
use crate::module_loader::import_map::{url_for_path, vega_themes_url, vega_url, VlVersion};
use crate::module_loader::VlConvertModuleLoader;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use deno_runtime::deno_core::anyhow::bail;
use deno_runtime::deno_core::error::AnyError;
use deno_runtime::deno_core::{serde_v8, v8, Extension};
use deno_core::op;
use deno_runtime::deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_runtime::deno_core;
use deno_runtime::deno_web::BlobStore;
use deno_runtime::permissions::Permissions;
use deno_runtime::worker::MainWorker;
use deno_runtime::worker::WorkerOptions;
use std::thread;
use std::thread::JoinHandle;
use crate::anyhow::anyhow;
use futures::channel::{mpsc, mpsc::Sender, oneshot};
use futures_util::{SinkExt, StreamExt};
use crate::text::{op_text_width, USVG_OPTIONS};
lazy_static! {
pub static ref TOKIO_RUNTIME: tokio::runtime::Runtime =
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
static ref JSON_ARGS: Arc<Mutex<HashMap<i32, String>>> = Arc::new(Mutex::new(HashMap::new()));
static ref NEXT_ARG_ID: Arc<Mutex<i32>> = Arc::new(Mutex::new(0));
}
#[derive(Debug, Clone, Default)]
pub struct VlOpts {
pub config: Option<serde_json::Value>,
pub theme: Option<String>,
pub vl_version: VlVersion,
}
fn set_json_arg(arg: serde_json::Value) -> Result<i32, AnyError> {
// Increment arg id
let id = match NEXT_ARG_ID.lock() {
Ok(mut guard) => {
let id = *guard;
*guard = (*guard + 1) % i32::MAX;
id
}
Err(err) => {
bail!("Failed to acquire lock: {}", err.to_string())
}
};
// Add Arg at id to args
match JSON_ARGS.lock() {
Ok(mut guard) => {
guard.insert(id, serde_json::to_string(&arg).unwrap());
}
Err(err) => {
bail!("Failed to acquire lock: {}", err.to_string())
}
}
Ok(id)
}
#[op]
fn op_get_json_arg(arg_id: i32) -> Result<String, AnyError> {
match JSON_ARGS.lock() {
Ok(mut guard) => {
if let Some(arg) = guard.remove(&arg_id) {
Ok(arg)
} else {
bail!("Arg id not found")
}
}
Err(err) => {
bail!("Failed to acquire lock: {}", err.to_string())
}
}
}
fn get_error_class_name(e: &AnyError) -> &'static str {
deno_runtime::errors::get_error_class_name(e).unwrap_or("Error")
}
/// Struct that interacts directly with the Deno JavaScript runtime. Not Sendable
struct InnerVlConverter {
worker: MainWorker,
initialized_vl_versions: HashSet<VlVersion>,
vega_initialized: bool,
module_loader: Rc<VlConvertModuleLoader>,
}
impl InnerVlConverter {
async fn init_vega(&mut self) -> Result<(), AnyError> {
if !self.vega_initialized {
let import_str = format!(
r#"
var vega;
import('{vega_url}').then((imported) => {{
vega = imported;
}})
var vegaThemes;
import('{vega_themes_url}').then((imported) => {{
vegaThemes = imported;
}})
"#,
vega_url = vega_url(),
vega_themes_url = vega_themes_url(),
);
self.worker.execute_script("<anon>", &import_str)?;
self.worker.run_event_loop(false).await?;
// Override text width measurement in vega-scenegraph
for path in self.module_loader.import_map.keys() {
if path.ends_with("vega-scenegraph.js") {
let script = format!(
r#"
import('{url}').then((sg) => {{
sg.textMetrics.width = (item, text) => {{
let style = item.fontStyle;
let variant = item.fontVariant;
let weight = item.fontWeight;
let size = sg.fontSize(item);
let family = sg.fontFamily(item);
let text_info = JSON.stringify({{
style, variant, weight, size, family, text
}}, null, 2);
return Deno.core.ops.op_text_width(text_info)
}};
}})
"#,
url = url_for_path(path)
);
self.worker.execute_script("<anon>", &script)?;
self.worker.run_event_loop(false).await?;
}
}
// Create and initialize svg function string
let function_str = r#"
function vegaToSvg(vgSpec) {
let runtime = vega.parse(vgSpec);
let view = new vega.View(runtime, {renderer: 'none'});
let svgPromise = view.toSVG();
return svgPromise
}
"#;
self.worker.execute_script("<anon>", function_str)?;
self.worker.run_event_loop(false).await?;
self.vega_initialized = true;
}
Ok(())
}
async fn init_vl_version(&mut self, vl_version: &VlVersion) -> Result<(), AnyError> {
if !self.initialized_vl_versions.contains(vl_version) {
// Create and evaluate import string
let import_str = format!(
r#"
var {ver_name};
import('{vl_url}').then((imported) => {{
{ver_name} = imported;
}})
"#,
ver_name = format!("{:?}", vl_version),
vl_url = vl_version.to_url()
);
self.worker.execute_script("<anon>", &import_str)?;
self.worker.run_event_loop(false).await?;
// Create and initialize function string
let function_str = format!(
r#"
function compileVegaLite_{ver_name}(vlSpec, config, theme) {{
let options = {{}};
// Handle config and theme
let usermetaTheme = ((vlSpec.usermeta ?? {{}}).embedOptions ?? {{}}).theme;
let namedTheme = theme ?? usermetaTheme;
if (namedTheme != null) {{
options["config"] = vega.mergeConfig(vegaThemes[namedTheme], config ?? {{}});
}} else if (config != null) {{
options["config"] = config;
}}
return {ver_name}.compile(vlSpec, options).spec
}}
function vegaLiteToSvg_{ver_name}(vlSpec, config, theme) {{
let options = {{}};
// Handle config and theme
let usermetaTheme = ((vlSpec.usermeta ?? {{}}).embedOptions ?? {{}}).theme;
let namedTheme = theme ?? usermetaTheme;
if (namedTheme != null) {{
options["config"] = vega.mergeConfig(vegaThemes[namedTheme], config ?? {{}});
}} else if (config != null) {{
options["config"] = config;
}}
let vgSpec = {ver_name}.compile(vlSpec, options).spec;
return vegaToSvg(vgSpec)
}}
"#,
ver_name = format!("{:?}", vl_version),
);
self.worker.execute_script("<anon>", &function_str)?;
self.worker.run_event_loop(false).await?;
// Register that this Vega-Lite version has been initialized
self.initialized_vl_versions.insert(*vl_version);
}
Ok(())
}
pub async fn try_new() -> Result<Self, AnyError> {
let module_loader = Rc::new(VlConvertModuleLoader::new());
let ext = Extension::builder()
.ops(vec![
// Op to measure text width with resvg
op_text_width::decl(),
op_get_json_arg::decl(),
])
.build();
let create_web_worker_cb = Arc::new(|_| {
todo!("Web workers are not supported");
});
let web_worker_event_cb = Arc::new(|_| {
todo!("Web workers are not supported");
});
let options = WorkerOptions {
bootstrap: Default::default(),
extensions: vec![ext],
startup_snapshot: None,
unsafely_ignore_certificate_errors: None,
root_cert_store: None,
seed: None,
source_map_getter: None,
format_js_error_fn: None,
web_worker_preload_module_cb: web_worker_event_cb.clone(),
web_worker_pre_execute_module_cb: web_worker_event_cb,
create_web_worker_cb,
maybe_inspector_server: None,
should_break_on_first_statement: false,
module_loader: module_loader.clone(),
npm_resolver: None,
get_error_class_fn: Some(&get_error_class_name),
cache_storage_dir: None,
origin_storage_dir: None,
blob_store: BlobStore::default(),
broadcast_channel: InMemoryBroadcastChannel::default(),
shared_array_buffer_store: None,
compiled_wasm_module_store: None,
stdio: Default::default(),
should_wait_for_inspector_session: false,
};
let js_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("vl-convert-rs.js");
let main_module = deno_core::resolve_path(&js_path.to_string_lossy())?;
let permissions = Permissions::allow_all();
let mut worker =
MainWorker::bootstrap_from_options(main_module.clone(), permissions, options);
worker.execute_main_module(&main_module).await?;
worker.run_event_loop(false).await?;
let this = Self {
worker,
initialized_vl_versions: Default::default(),
vega_initialized: false,
module_loader,
};
Ok(this)
}
async fn execute_script_to_json(
&mut self,
script: &str,
) -> Result<serde_json::Value, AnyError> {
let res = self.worker.js_runtime.execute_script("<anon>", script)?;
self.worker.run_event_loop(false).await?;
let scope = &mut self.worker.js_runtime.handle_scope();
let local = v8::Local::new(scope, res);
// Deserialize a `v8` object into a Rust type using `serde_v8`,
// in this case deserialize to a JSON `Value`.
let deserialized_value = serde_v8::from_v8::<serde_json::Value>(scope, local);
deserialized_value.map_err(|err| {
anyhow!(
"Failed to deserialize JavaScript value: {}",
err.to_string()
)
})
}
async fn execute_script_to_string(&mut self, script: &str) -> Result<String, AnyError> {
let res = self.worker.js_runtime.execute_script("<anon>", script)?;
self.worker.run_event_loop(false).await?;
let scope = &mut self.worker.js_runtime.handle_scope();
let local = v8::Local::new(scope, res);
// Deserialize a `v8` object into a Rust type using `serde_v8`,
// in this case deserialize to a JSON `Value`.
let deserialized_value = serde_v8::from_v8::<serde_json::Value>(scope, local);
let value = match deserialized_value {
Ok(value) => {
let value = value.as_str();
value.unwrap().to_string()
}
Err(err) => bail!("{}", err.to_string()),
};
Ok(value)
}
pub async fn vegalite_to_vega(
&mut self,
vl_spec: &serde_json::Value,
vl_opts: VlOpts,
) -> Result<serde_json::Value, AnyError> {
self.init_vega().await?;
self.init_vl_version(&vl_opts.vl_version).await?;
let config = vl_opts.config.clone().unwrap_or(serde_json::Value::Null);
let spec_arg_id = set_json_arg(vl_spec.clone())?;
let config_arg_id = set_json_arg(config)?;
let theme_arg = match &vl_opts.theme {
None => "null".to_string(),
Some(s) => format!("'{}'", s),
};
let code = format!(
r#"
compileVegaLite_{ver_name:?}(
JSON.parse(Deno.core.ops.op_get_json_arg({spec_arg_id})),
JSON.parse(Deno.core.ops.op_get_json_arg({config_arg_id})),
{theme_arg}
)
"#,
ver_name = vl_opts.vl_version,
spec_arg_id = spec_arg_id,
config_arg_id = config_arg_id,
theme_arg = theme_arg,
);
let value = self.execute_script_to_json(&code).await?;
Ok(value)
}
pub async fn vegalite_to_svg(
&mut self,
vl_spec: &serde_json::Value,
vl_opts: VlOpts,
) -> Result<String, AnyError> {
self.init_vega().await?;
self.init_vl_version(&vl_opts.vl_version).await?;
let config = vl_opts.config.clone().unwrap_or(serde_json::Value::Null);
let spec_arg_id = set_json_arg(vl_spec.clone())?;
let config_arg_id = set_json_arg(config)?;
let theme_arg = match &vl_opts.theme {
None => "null".to_string(),
Some(s) => format!("'{}'", s),
};
let code = format!(
r#"
var svg;
vegaLiteToSvg_{ver_name:?}(
JSON.parse(Deno.core.ops.op_get_json_arg({spec_arg_id})),
JSON.parse(Deno.core.ops.op_get_json_arg({config_arg_id})),
{theme_arg}
).then((result) => {{
svg = result;
}});
"#,
ver_name = vl_opts.vl_version,
spec_arg_id = spec_arg_id,
config_arg_id = config_arg_id,
theme_arg = theme_arg,
);
self.worker.execute_script("<anon>", &code)?;
self.worker.run_event_loop(false).await?;
let value = self.execute_script_to_string("svg").await?;
Ok(value)
}
pub async fn vega_to_svg(&mut self, vg_spec: &serde_json::Value) -> Result<String, AnyError> {
self.init_vega().await?;
let arg_id = set_json_arg(vg_spec.clone())?;
let code = format!(
r#"
var svg;
vegaToSvg(
JSON.parse(Deno.core.ops.op_get_json_arg({arg_id}))
).then((result) => {{
svg = result;
}})
"#,
arg_id = arg_id
);
self.worker.execute_script("<anon>", &code)?;
self.worker.run_event_loop(false).await?;
let value = self.execute_script_to_string("svg").await?;
Ok(value)
}
pub async fn get_local_tz(&mut self) -> Result<Option<String>, AnyError> {
let code = "var localTz = Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'undefined';";
self.worker.execute_script("<anon>", code)?;
self.worker.run_event_loop(false).await?;
let value = self.execute_script_to_string("localTz").await?;
if value == "undefined" {
Ok(None)
} else {
Ok(Some(value))
}
}
pub async fn get_themes(&mut self) -> Result<serde_json::Value, AnyError> {
self.init_vega().await?;
let code = r#"
var themes = Object.assign({}, vegaThemes);
delete themes.version
delete themes.default
"#;
self.worker.execute_script("<anon>", code)?;
self.worker.run_event_loop(false).await?;
let value = self.execute_script_to_json("themes").await?;
Ok(value)
}
}
pub enum VlConvertCommand {
VlToVg {
vl_spec: serde_json::Value,
vl_opts: VlOpts,
responder: oneshot::Sender<Result<serde_json::Value, AnyError>>,
},
VgToSvg {
vg_spec: serde_json::Value,
responder: oneshot::Sender<Result<String, AnyError>>,
},
VlToSvg {
vl_spec: serde_json::Value,
vl_opts: VlOpts,
responder: oneshot::Sender<Result<String, AnyError>>,
},
GetLocalTz {
responder: oneshot::Sender<Result<Option<String>, AnyError>>,
},
GetThemes {
responder: oneshot::Sender<Result<serde_json::Value, AnyError>>,
},
}
/// Struct for performing Vega-Lite to Vega conversions using the Deno v8 Runtime
///
/// # Examples
///
/// ```
/// use vl_convert_rs::{VlConverter, VlVersion};
/// let mut converter = VlConverter::new();
///
/// let vl_spec: serde_json::Value = serde_json::from_str(r#"
/// {
/// "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
/// "data": {"url": "data/movies.json"},
/// "mark": "circle",
/// "encoding": {
/// "x": {
/// "bin": {"maxbins": 10},
/// "field": "IMDB Rating"
/// },
/// "y": {
/// "bin": {"maxbins": 10},
/// "field": "Rotten Tomatoes Rating"
/// },
/// "size": {"aggregate": "count"}
/// }
/// } "#).unwrap();
///
/// let vega_spec = futures::executor::block_on(
/// converter.vegalite_to_vega(vl_spec, Default::default())
/// ).expect(
/// "Failed to perform Vega-Lite to Vega conversion"
/// );
///
/// println!("{}", vega_spec)
/// ```
#[derive(Clone)]
pub struct VlConverter {
sender: Sender<VlConvertCommand>,
_handle: Arc<JoinHandle<Result<(), AnyError>>>,
}
impl VlConverter {
pub fn new() -> Self {
let (sender, mut receiver) = mpsc::channel::<VlConvertCommand>(32);
let handle = Arc::new(thread::spawn(move || {
let mut inner = TOKIO_RUNTIME.block_on(InnerVlConverter::try_new())?;
while let Some(cmd) = TOKIO_RUNTIME.block_on(receiver.next()) {
match cmd {
VlConvertCommand::VlToVg {
vl_spec,
vl_opts,
responder,
} => {
let vega_spec =
TOKIO_RUNTIME.block_on(inner.vegalite_to_vega(&vl_spec, vl_opts));
responder.send(vega_spec).ok();
}
VlConvertCommand::VgToSvg { vg_spec, responder } => {
let svg_result = TOKIO_RUNTIME.block_on(inner.vega_to_svg(&vg_spec));
responder.send(svg_result).ok();
}
VlConvertCommand::VlToSvg {
vl_spec,
vl_opts,
responder,
} => {
let svg_result =
TOKIO_RUNTIME.block_on(inner.vegalite_to_svg(&vl_spec, vl_opts));
responder.send(svg_result).ok();
}
VlConvertCommand::GetLocalTz { responder } => {
let local_tz = TOKIO_RUNTIME.block_on(inner.get_local_tz());
responder.send(local_tz).ok();
}
VlConvertCommand::GetThemes { responder } => {
let themes = TOKIO_RUNTIME.block_on(inner.get_themes());
responder.send(themes).ok();
}
}
}
Ok(())
}));
Self {
sender,
_handle: handle,
}
}
pub async fn vegalite_to_vega(
&mut self,
vl_spec: serde_json::Value,
vl_opts: VlOpts,
) -> Result<serde_json::Value, AnyError> {
let (resp_tx, resp_rx) = oneshot::channel::<Result<serde_json::Value, AnyError>>();
let cmd = VlConvertCommand::VlToVg {
vl_spec,
vl_opts,
responder: resp_tx,
};
// Send request
match self.sender.send(cmd).await {
Ok(_) => {
// All good
}
Err(err) => {
bail!("Failed to send conversion request: {}", err.to_string())
}
}
// Wait for result
match resp_rx.await {
Ok(vega_spec_result) => vega_spec_result,
Err(err) => bail!("Failed to retrieve conversion result: {}", err.to_string()),
}
}
pub async fn vega_to_svg(&mut self, vg_spec: serde_json::Value) -> Result<String, AnyError> {
let (resp_tx, resp_rx) = oneshot::channel::<Result<String, AnyError>>();
let cmd = VlConvertCommand::VgToSvg {
vg_spec,
responder: resp_tx,
};
// Send request
match self.sender.send(cmd).await {
Ok(_) => {
// All good
}
Err(err) => {
bail!("Failed to send SVG conversion request: {}", err.to_string())
}
}
// Wait for result
match resp_rx.await {
Ok(svg_result) => svg_result,
Err(err) => bail!("Failed to retrieve conversion result: {}", err.to_string()),
}
}
pub async fn vegalite_to_svg(
&mut self,
vl_spec: serde_json::Value,
vl_opts: VlOpts,
) -> Result<String, AnyError> {
let (resp_tx, resp_rx) = oneshot::channel::<Result<String, AnyError>>();
let cmd = VlConvertCommand::VlToSvg {
vl_spec,
vl_opts,
responder: resp_tx,
};
// Send request
match self.sender.send(cmd).await {
Ok(_) => {
// All good
}
Err(err) => {
bail!("Failed to send SVG conversion request: {}", err.to_string())
}
}
// Wait for result
match resp_rx.await {
Ok(svg_result) => svg_result,
Err(err) => bail!("Failed to retrieve conversion result: {}", err.to_string()),
}
}
pub async fn vega_to_png(
&mut self,
vg_spec: serde_json::Value,
scale: Option<f32>,
) -> Result<Vec<u8>, AnyError> {
let scale = scale.unwrap_or(1.0);
let svg = self.vega_to_svg(vg_spec).await?;
Self::svg_to_png(&svg, scale)
}
pub async fn vegalite_to_png(
&mut self,
vl_spec: serde_json::Value,
vl_opts: VlOpts,
scale: Option<f32>,
) -> Result<Vec<u8>, AnyError> {
let scale = scale.unwrap_or(1.0);
let svg = self.vegalite_to_svg(vl_spec, vl_opts).await?;
Self::svg_to_png(&svg, scale)
}
fn svg_to_png(svg: &str, scale: f32) -> Result<Vec<u8>, AnyError> {
let opts = USVG_OPTIONS
.lock()
.map_err(|err| anyhow!("Failed to acquire usvg options lock: {}", err.to_string()))?;
let rtree = match usvg::Tree::from_str(svg, &opts.to_ref()) {
Ok(rtree) => rtree,
Err(err) => {
bail!("Failed to parse SVG string: {}", err.to_string())
}
};
let pixmap_size = rtree.size.to_screen_size();
let mut pixmap = tiny_skia::Pixmap::new(
(pixmap_size.width() as f32 * scale) as u32,
(pixmap_size.height() as f32 * scale) as u32,
)
.unwrap();
resvg::render(
&rtree,
usvg::FitTo::Zoom(scale),
tiny_skia::Transform::default(),
pixmap.as_mut(),
)
.unwrap();
match pixmap.encode_png() {
Ok(png_data) => Ok(png_data),
Err(err) => {
bail!("Failed to encode PNG: {}", err.to_string())
}
}
}
pub async fn get_local_tz(&mut self) -> Result<Option<String>, AnyError> {
let (resp_tx, resp_rx) = oneshot::channel::<Result<Option<String>, AnyError>>();
let cmd = VlConvertCommand::GetLocalTz { responder: resp_tx };
// Send request
match self.sender.send(cmd).await {
Ok(_) => {
// All good
}
Err(err) => {
bail!("Failed to send get_local_tz request: {}", err.to_string())
}
}
// Wait for result
match resp_rx.await {
Ok(local_tz_result) => local_tz_result,
Err(err) => bail!(
"Failed to retrieve get_local_tz result: {}",
err.to_string()
),
}
}
pub async fn get_themes(&mut self) -> Result<serde_json::Value, AnyError> {
let (resp_tx, resp_rx) = oneshot::channel::<Result<serde_json::Value, AnyError>>();
let cmd = VlConvertCommand::GetThemes { responder: resp_tx };
// Send request
match self.sender.send(cmd).await {
Ok(_) => {
// All good
}
Err(err) => {
bail!("Failed to send get_themes request: {}", err.to_string())
}
}
// Wait for result
match resp_rx.await {
Ok(themes_result) => themes_result,
Err(err) => bail!("Failed to retrieve get_themes result: {}", err.to_string()),
}
}
}
impl Default for VlConverter {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_convert_context() {
let mut ctx = VlConverter::new();
let vl_spec: serde_json::Value = serde_json::from_str(r##"
{
"data": {"url": "https://raw.githubusercontent.com/vega/vega-datasets/master/data/seattle-weather.csv"},
"mark": "bar",
"encoding": {
"x": {"timeUnit": "month", "field": "date", "type": "ordinal"},
"y": {"aggregate": "mean", "field": "precipitation"}
}
}
"##).unwrap();
let vg_spec = ctx
.vegalite_to_vega(
vl_spec,
VlOpts {
vl_version: VlVersion::v4_17,
..Default::default()
},
)
.await
.unwrap();
println!("vg_spec: {}", vg_spec)
}
#[tokio::test]
async fn test_multi_convert_context() {
let vl_spec: serde_json::Value = serde_json::from_str(r##"
{
"data": {"url": "https://raw.githubusercontent.com/vega/vega-datasets/master/data/seattle-weather.csv"},
"mark": "bar",
"encoding": {
"x": {"timeUnit": "month", "field": "date", "type": "ordinal"},
"y": {"aggregate": "mean", "field": "precipitation"}
}
}
"##).unwrap();
let mut ctx1 = VlConverter::new();
let vg_spec1 = ctx1
.vegalite_to_vega(
vl_spec.clone(),
VlOpts {
vl_version: VlVersion::v4_17,
..Default::default()
},
)
.await
.unwrap();
println!("vg_spec1: {}", vg_spec1);
let mut ctx1 = VlConverter::new();
let vg_spec2 = ctx1
.vegalite_to_vega(
vl_spec,
VlOpts {
vl_version: VlVersion::v5_5,
..Default::default()
},
)
.await
.unwrap();
println!("vg_spec2: {}", vg_spec2);
}
}