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
/* SPDX-License-Identifier: BSD-3-Clause */
/* Copyright © 2020 Fragcolor Pte. Ltd. */

#![macro_use]

use crate::shard::shard_construct;
use crate::shard::Shard;
use crate::shardsc::SHBool;
use crate::shardsc::SHWireState;
use crate::shardsc::SHContext;
use crate::shardsc::SHCore;
use crate::shardsc::SHOptionalString;
use crate::shardsc::SHString;
use crate::shardsc::SHStrings;
use crate::shardsc::SHVar;
use crate::shardsc::ShardPtr;
use crate::types::WireRef;
use crate::types::WireState;
use crate::types::ClonedVar;
use crate::types::Context;
use crate::types::DerivedType;
use crate::types::ExternalVar;
use crate::types::InstanceData;
use crate::types::Mesh;
use crate::types::ParameterInfo;
use crate::types::Parameters;
use crate::types::Var;
use core::convert::TryInto;
use core::ffi::c_void;
use core::slice;
use std::ffi::CStr;
use std::ffi::CString;
use std::os::raw::c_char;

const ABI_VERSION: u32 = 0x20200101;

pub static mut Core: *mut SHCore = core::ptr::null_mut();
pub static mut ScriptEnvCreate: Option<
  unsafe extern "C" fn(path: *const ::std::os::raw::c_char) -> *mut ::core::ffi::c_void,
> = None;
pub static mut ScriptEnvCreateSub: Option<
  unsafe extern "C" fn(parent_env: *mut ::core::ffi::c_void) -> *mut ::core::ffi::c_void,
> = None;
pub static mut ScriptEnvDestroy: Option<unsafe extern "C" fn(env: *mut ::core::ffi::c_void)> = None;
pub static mut ScriptEval: Option<
  unsafe extern "C" fn(
    env: *mut ::core::ffi::c_void,
    script: *const ::std::os::raw::c_char,
    output: *mut SHVar,
  ) -> bool,
> = None;
static mut init_done: bool = false;

#[cfg(feature = "dllshard")]
mod internal_core_init {
  extern crate dlopen;
  use super::*;
  use crate::shardsc::shardsInterface;
  use crate::core::SHCore;
  use crate::core::ABI_VERSION;
  use dlopen::symbor::Library;

  fn try_load_dlls() -> Option<Library> {
    if let Ok(lib) = Library::open("libshards.dylib") {
      Some(lib)
    } else if let Ok(lib) = Library::open("libshards.so") {
      Some(lib)
    } else if let Ok(lib) = Library::open("libshards.dll") {
      Some(lib)
    } else {
      None
    }
  }

  pub static mut SHDLL: Option<Library> = None;

  pub unsafe fn initScripting(lib: &Library) {
    let fun = lib.symbol::<unsafe extern "C" fn(
      path: *const ::std::os::raw::c_char,
    ) -> *mut ::core::ffi::c_void>("shLispCreate");
    if let Ok(fun) = fun {
      ScriptEnvCreate = Some(*fun);
    } else {
      // short circuit here
      return;
    }

    let fun = lib.symbol::<unsafe extern "C" fn(env: *mut ::core::ffi::c_void)>("shLispDestroy");
    ScriptEnvDestroy = Some(*fun.unwrap());

    let fun = lib
      .symbol::<unsafe extern "C" fn(env: *mut ::core::ffi::c_void) -> *mut ::core::ffi::c_void>(
        "shLispCreateSub",
      );
    ScriptEnvCreateSub = Some(*fun.unwrap());

    let fun = lib.symbol::<unsafe extern "C" fn(
      env: *mut ::core::ffi::c_void,
      script: *const ::std::os::raw::c_char,
      output: *mut SHVar,
    ) -> bool>("shLispEval");
    ScriptEval = Some(*fun.unwrap());

    // trigger initializations... fix me in the future to something more elegant
    let current_dir = std::env::current_dir().unwrap();
    let current_dir = current_dir.to_str().unwrap();
    let current_dir = std::ffi::CString::new(current_dir).unwrap();
    let env = ScriptEnvCreate.unwrap()(current_dir.as_ptr());
    ScriptEnvDestroy.unwrap()(env);
  }

  pub unsafe fn initInternal() {
    let exe = Library::open_self().ok().unwrap();

    let exefun = exe
      .symbol::<unsafe extern "C" fn(abi_version: u32) -> *mut SHCore>("shardsInterface")
      .ok();
    if let Some(fun) = exefun {
      // init scripting first if possible!
      initScripting(&exe);
      Core = fun(ABI_VERSION);
      if Core.is_null() {
        panic!("Failed to aquire shards interface, version not compatible.");
      }
    } else {
      let lib = try_load_dlls().unwrap();
      let fun = lib
        .symbol::<unsafe extern "C" fn(abi_version: u32) -> *mut SHCore>("shardsInterface")
        .unwrap();
      // init scripting first if possible!
      initScripting(&lib);
      Core = fun(ABI_VERSION);
      if Core.is_null() {
        panic!("Failed to aquire shards interface, version not compatible.");
      }
      SHDLL = Some(lib);
    }
  }
}

#[cfg(not(feature = "dllshard"))]
mod internal_core_init {
  pub unsafe fn initInternal() {}
}

#[inline(always)]
pub fn init() {
  unsafe {
    if !init_done {
      internal_core_init::initInternal();
      init_done = true;
    }
  }
}

#[inline(always)]
pub fn log(s: &str) {
  unsafe {
    (*Core).log.unwrap()(s.as_ptr() as *const std::os::raw::c_char);
  }
}

#[inline(always)]
pub fn logLevel(level: i32, s: &str) {
  unsafe {
    (*Core).logLevel.unwrap()(level, s.as_ptr() as *const std::os::raw::c_char);
  }
}

#[macro_export]
#[cfg(debug_assertions)]
macro_rules! shlog_debug {
  ($text:expr, $($arg:expr),*) => {
      use std::io::Write as __stdWrite;
      let mut buf = vec![];
      ::std::write!(&mut buf, concat!($text, "\0"), $($arg),*).unwrap();
      $crate::core::logLevel(1, ::std::str::from_utf8(&buf).unwrap());
  };

  ($text:expr) => {
    $crate::core::logLevel(1, concat!($text, "\0"));
  };
}

#[macro_export]
#[cfg(not(debug_assertions))]
macro_rules! shlog_debug {
  ($text:expr, $($arg:expr),*) => {};

  ($text:expr) => {};
}

#[macro_export]
macro_rules! shlog {
    ($text:expr, $($arg:expr),*) => {
        use std::io::Write as __stdWrite;
        let mut buf = vec![];
        ::std::write!(&mut buf, concat!($text, "\0"), $($arg),*).unwrap();
        $crate::core::log(::std::str::from_utf8(&buf).unwrap());
    };

    ($text:expr) => {
      $crate::core::log(concat!($text, "\0"));
    };
}

#[inline(always)]
pub fn sleep(seconds: f64) {
  unsafe {
    (*Core).sleep.unwrap()(seconds, true);
  }
}

#[inline(always)]
pub fn suspend(context: &SHContext, seconds: f64) -> WireState {
  unsafe {
    let ctx = context as *const SHContext as *mut SHContext;
    (*Core).suspend.unwrap()(ctx, seconds).into()
  }
}

#[inline(always)]
pub fn getState(context: &SHContext) -> WireState {
  unsafe {
    let ctx = context as *const SHContext as *mut SHContext;
    (*Core).getState.unwrap()(ctx).into()
  }
}

#[inline(always)]
pub fn abortWire(context: &SHContext, message: &str) {
  let cmsg = CString::new(message).unwrap();
  unsafe {
    let ctx = context as *const SHContext as *mut SHContext;
    (*Core).abortWire.unwrap()(ctx, cmsg.as_ptr());
  }
}

#[inline(always)]
pub fn registerShard<T: Default + Shard>() {
  unsafe {
    (*Core).registerShard.unwrap()(
      T::registerName().as_ptr() as *const c_char,
      Some(shard_construct::<T>),
    );
  }
}

pub fn getShards() -> Vec<&'static CStr> {
  unsafe {
    let shard_names = (*Core).getShards.unwrap()();
    let mut res = Vec::new();
    let len = shard_names.len;
    let slice = slice::from_raw_parts(shard_names.elements, len.try_into().unwrap());
    for name in slice.iter() {
      res.push(CStr::from_ptr(*name));
    }
    (*Core).stringsFree.unwrap()(&shard_names as *const SHStrings as *mut SHStrings);
    res
  }
}

#[inline(always)]
pub fn getRootPath() -> &'static str {
  unsafe {
    CStr::from_ptr((*Core).getRootPath.unwrap()())
      .to_str()
      .unwrap()
  }
}

#[inline(always)]
pub fn createShardPtr(name: &str) -> ShardPtr {
  let cname = CString::new(name).unwrap();
  unsafe { (*Core).createShard.unwrap()(cname.as_ptr()) }
}

#[inline(always)]
pub fn createShard(name: &str) -> ShardInstance {
  let cname = CString::new(name).unwrap();
  unsafe {
    ShardInstance {
      ptr: (*Core).createShard.unwrap()(cname.as_ptr()),
    }
  }
}

#[inline(always)]
pub fn cloneVar(dst: &mut Var, src: &Var) {
  unsafe {
    (*Core).cloneVar.unwrap()(dst, src);
  }
}

#[inline(always)]
pub fn destroyVar(v: &mut Var) {
  unsafe {
    (*Core).destroyVar.unwrap()(v);
  }
}

pub fn readCachedString(id: u32) -> &'static str {
  unsafe {
    let s = (*Core).readCachedString.unwrap()(id);
    CStr::from_ptr(s.string).to_str().unwrap()
  }
}

pub fn writeCachedString(id: u32, string: &'static str) -> &'static str {
  unsafe {
    let s = (*Core).writeCachedString.unwrap()(id, string.as_ptr() as *const std::os::raw::c_char);
    CStr::from_ptr(s.string).to_str().unwrap()
  }
}

pub fn readCachedString1(id: u32) -> SHOptionalString {
  unsafe { (*Core).readCachedString.unwrap()(id) }
}

pub fn writeCachedString1(id: u32, string: &'static str) -> SHOptionalString {
  unsafe { (*Core).writeCachedString.unwrap()(id, string.as_ptr() as *const std::os::raw::c_char) }
}

pub fn deriveType(var: &Var, data: &InstanceData) -> DerivedType {
  let t = unsafe { (*Core).deriveTypeInfo.unwrap()(var as *const _, data as *const _) };
  DerivedType(t)
}

macro_rules! shccstr {
  ($string:literal) => {
    if cfg!(debug_assertions) {
      crate::core::writeCachedString1(compile_time_crc32::crc32!($string), cstr!($string))
    } else {
      crate::core::readCachedString1(compile_time_crc32::crc32!($string))
    }
  };
}

pub fn referenceMutVariable(context: &SHContext, name: SHString) -> &mut SHVar {
  unsafe {
    let ctx = context as *const SHContext as *mut SHContext;
    let shptr = (*Core).referenceVariable.unwrap()(ctx, name);
    shptr.as_mut().unwrap()
  }
}

pub fn referenceVariable(context: &SHContext, name: SHString) -> &SHVar {
  unsafe {
    let ctx = context as *const SHContext as *mut SHContext;
    let shptr = (*Core).referenceVariable.unwrap()(ctx, name);
    shptr.as_mut().unwrap()
  }
}

pub fn releaseMutVariable(var: &mut SHVar) {
  unsafe {
    let v = var as *mut SHVar;
    (*Core).releaseVariable.unwrap()(v);
  }
}

pub fn releaseVariable(var: &SHVar) {
  unsafe {
    let v = var as *const SHVar as *mut SHVar;
    (*Core).releaseVariable.unwrap()(v);
  }
}

impl WireRef {
  pub fn set_external(&self, name: &str, var: &mut ExternalVar) {
    let cname = CString::new(name).unwrap();
    unsafe {
      (*Core).setExternalVariable.unwrap()(
        self.0,
        cname.as_ptr() as *const _,
        &var.0 as *const _ as *mut _,
      );
    }
  }

  pub fn remove_external(&self, name: &str) {
    let cname = CString::new(name).unwrap();
    unsafe {
      (*Core).removeExternalVariable.unwrap()(self.0, cname.as_ptr() as *const _);
    }
  }

  pub fn get_result(&self) -> Result<Option<ClonedVar>, &str> {
    let info = unsafe { (*Core).getWireInfo.unwrap()(self.0) };

    if !info.isRunning {
      if info.failed {
        let msg = unsafe { CStr::from_ptr(info.failureMessage) };
        Err(msg.to_str().unwrap())
      } else {
        unsafe { Ok(Some((*info.finalOutput).into())) }
      }
    } else {
      Ok(None)
    }
  }
}

//--------------------------------------------------------------------------------------------------

unsafe extern "C" fn do_blocking_c_call(context: *mut SHContext, arg2: *mut c_void) -> SHVar {
  let trait_obj_ref: &mut &mut dyn FnMut() -> Result<SHVar, &'static str> =
    { &mut *(arg2 as *mut _) };
  match trait_obj_ref() {
    Ok(value) => value,
    Err(error) => {
      shlog_debug!("do_blocking failure detected"); // in case error leads to crash
      shlog_debug!("do_blocking failure: {}", error);
      abortWire(&(*context), error);
      Var::default()
    }
  }
}

pub fn do_blocking<F>(context: &SHContext, f: F) -> SHVar
where
  F: FnMut() -> Result<SHVar, &'static str>,
{
  unsafe {
    let ctx = context as *const SHContext as *mut SHContext;
    let mut trait_obj: &dyn FnMut() -> Result<SHVar, &'static str> = &f;
    let trait_obj_ref = &mut trait_obj;
    let closure_pointer_pointer = trait_obj_ref as *mut _ as *mut c_void;
    (*Core).asyncActivate.unwrap()(ctx, closure_pointer_pointer, Some(do_blocking_c_call), None)
  }
}

//--------------------------------------------------------------------------------------------------

pub trait BlockingShard {
  fn activate_blocking(&mut self, context: &Context, input: &Var) -> Result<Var, &str>;
  fn cancel_activation(&mut self, _context: &Context) {}
}

struct AsyncCallData<T: BlockingShard> {
  caller: *mut T,
  input: *const SHVar,
}

unsafe extern "C" fn activate_blocking_c_call<T: BlockingShard>(
  context: *mut SHContext,
  arg2: *mut c_void,
) -> SHVar {
  let data = arg2 as *mut AsyncCallData<T>;
  let res = (*(*data).caller).activate_blocking(&*context, &*(*data).input);
  match res {
    Ok(value) => value,
    Err(error) => {
      shlog_debug!("activate_blocking failure detected"); // in case error leads to crash
      shlog_debug!("activate_blocking failure: {}", error);
      abortWire(&(*context), error);
      Var::default()
    }
  }
}

unsafe extern "C" fn cancel_blocking_c_call<T: BlockingShard>(
  context: *mut SHContext,
  arg2: *mut c_void,
) {
  let data = arg2 as *mut AsyncCallData<T>;
  (*(*data).caller).cancel_activation(&*context);
}

pub fn activate_blocking<'a, T>(
  caller: &'a mut T,
  context: &'a SHContext,
  input: &'a SHVar,
) -> SHVar
where
  T: BlockingShard,
{
  unsafe {
    let data = AsyncCallData {
      caller: caller as *mut T,
      input: input as *const SHVar,
    };
    let ctx = context as *const SHContext as *mut SHContext;
    let data_ptr = &data as *const AsyncCallData<T> as *mut AsyncCallData<T> as *mut c_void;
    (*Core).asyncActivate.unwrap()(
      ctx,
      data_ptr,
      Some(activate_blocking_c_call::<T>),
      Some(cancel_blocking_c_call::<T>),
    )
  }
}

//--------------------------------------------------------------------------------------------------

pub struct ShardInstance {
  ptr: ShardPtr,
}

impl Drop for ShardInstance {
  fn drop(&mut self) {
    unsafe {
      if !(*self.ptr).owned {
        (*self.ptr).destroy.unwrap()(self.ptr);
      }
    }
  }
}