logo
  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
// This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).

/*!
# Rust bindings library for Sciter engine.

[Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine
with GPU accelerated rendering designed to render modern desktop application UI.
It's a compact, single dll/dylib/so file (4-8 mb) engine without any additional dependencies.

Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples)
of the desktop UI examples.

Sciter supports all standard elements defined in HTML5 specification
[with some additions](https://sciter.com/developers/for-web-programmers/).
CSS is extended to better support the Desktop UI development,
e.g. flow and flex units, vertical and horizontal alignment, OS theming.

[Sciter SDK](https://sciter.com/download/) comes with a demo "browser" with builtin DOM inspector,
script debugger and documentation viewer:

![Sciter tools](https://sciter.com/images/sciter-tools.png)

Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/)
for engine principles, architecture and more.


## Brief look:

Here is a minimal sciter app:

```no_run
extern crate sciter;

fn main() {
    let mut frame = sciter::Window::new();
    frame.load_file("minimal.htm");
    frame.run_app();
}
```

It looks similar like this:

![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png)

Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples)
folder for more complex usage and module-level sections for the guides about:

* [Window](window/index.html) creation.
* [Behaviors](dom/event/index.html) and event handling.
* [DOM](dom/index.html) access methods.
* Sciter [Value](value/index.html) interface.

*/

#![doc(html_logo_url = "https://sciter.com/screenshots/slide-sciter-osx.png",
       html_favicon_url = "https://sciter.com/wp-content/themes/sciter/!images/favicon.ico")]

// documentation test:
// #![warn(missing_docs)]


/* Clippy lints */

#![allow(clippy::needless_return, clippy::let_and_return)] // past habits
#![allow(clippy::redundant_field_names)] // since Rust 1.17 and less readable
#![allow(clippy::unreadable_literal)] // C++ SDK constants
#![allow(clippy::upper_case_acronyms)]// C++ SDK constants
#![allow(clippy::deprecated_semver)]  // `#[deprecated(since="Sciter 4.4.3.24")]` is not a semver format.
#![allow(clippy::result_unit_err)]		// Sciter returns BOOL, but `Result<(), ()>` is more strict even without error description.
// #![allow(clippy::cast_ptr_alignment)] // 0.0.195 only


/* Macros */

#[cfg(target_os = "macos")]
#[macro_use] extern crate objc;
#[macro_use] extern crate lazy_static;


#[macro_use] pub mod macros;

mod capi;

#[doc(hidden)]
pub use capi::scdom::{HELEMENT};
pub use capi::scdef::{GFX_LAYER, SCRIPT_RUNTIME_FEATURES};

/* Rust interface */
mod platform;
mod eventhandler;

pub mod dom;
pub mod graphics;
pub mod host;
pub mod om;
pub mod request;
pub mod types;
pub mod utf;
pub mod value;
pub mod video;
pub mod window;
pub mod windowless;

pub use dom::Element;
pub use dom::event::EventHandler;
pub use host::{Archive, Host, HostHandler};
pub use value::{Value, FromValue};
pub use window::Window;


/// Builder pattern for window creation. See [`window::Builder`](window/struct.Builder.html) documentation.
///
/// For example,
///
/// ```rust,no_run
/// let mut frame = sciter::WindowBuilder::main_window()
///   .with_size((800,600))
///   .glassy()
///   .fixed()
///   .create();
/// ```
pub type WindowBuilder = window::Builder;


/* Loader */
pub use capi::scapi::{ISciterAPI};
use capi::scgraphics::SciterGraphicsAPI;
use capi::screquest::SciterRequestAPI;

#[cfg(windows)]
mod ext {
	// Note:
	// Sciter 4.x shipped with universal "sciter.dll" library for different builds:
	// bin/32, bin/64, bin/skia32, bin/skia64
	// However it is quite inconvenient now (e.g. we can not put x64 and x86 builds in %PATH%)
	//
	#![allow(non_snake_case, non_camel_case_types)]
	use capi::scapi::{ISciterAPI};
	use capi::sctypes::{LPCSTR, LPCVOID, BOOL};

  type ApiType = *const ISciterAPI;
	type FuncType = extern "system" fn () -> *const ISciterAPI;

  pub static mut CUSTOM_DLL_PATH: Option<String> = None;

	extern "system"
	{
		fn LoadLibraryA(lpFileName: LPCSTR) -> LPCVOID;
    fn FreeLibrary(dll: LPCVOID) -> BOOL;
		fn GetProcAddress(hModule: LPCVOID, lpProcName: LPCSTR) -> LPCVOID;
	}

  pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> {
    use std::ffi::CString;
    use std::path::Path;

    fn try_load(path: &Path) -> Option<LPCVOID> {
      let path = CString::new(format!("{}", path.display())).expect("invalid library path");
      let dll = unsafe { LoadLibraryA(path.as_ptr()) };
      if !dll.is_null() {
        Some(dll)
      } else {
        None
      }
    }

    fn in_global() -> Option<LPCVOID> {
      // modern dll name
      let mut dll = unsafe { LoadLibraryA(b"sciter.dll\0".as_ptr() as LPCSTR) };
      if dll.is_null() {
        // try to load with old names
        let alternate = if cfg!(target_arch = "x86_64") { b"sciter64.dll\0" } else { b"sciter32.dll\0" };
        dll = unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) };
      }
      if !dll.is_null() {
        Some(dll)
      } else {
        None
      }
    }

    // try specified path first (and only if present)
    // and several paths to lookup then
    let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } {
      try_load(Path::new(path))
    } else {
      in_global()
    };

    if let Some(dll) = dll {
      // get the "SciterAPI" exported symbol
      let sym = unsafe { GetProcAddress(dll, b"SciterAPI\0".as_ptr() as LPCSTR) };
      if sym.is_null() {
        return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned());
      }

      if !permanent {
        unsafe { FreeLibrary(dll) };
        return Ok(0 as ApiType);
      }

      let get_api: FuncType = unsafe { std::mem::transmute(sym) };
      return Ok(get_api());
    }
    let sdkbin = if cfg!(target_arch = "x86_64") { "bin/64" } else { "bin/32" };
    let msg = format!("Please verify that Sciter SDK is installed and its binaries (from SDK/{}) are available in PATH.", sdkbin);
    Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n  {}", "sciter.dll", msg))
  }

	pub unsafe fn SciterAPI() -> *const ISciterAPI {
    match try_load_library(true) {
      Ok(api) => api,
      Err(error) => panic!("{}", error),
    }
	}
}

#[cfg(all(feature = "dynamic", unix))]
mod ext {
  #![allow(non_snake_case, non_camel_case_types)]
  extern crate libc;

  pub static mut CUSTOM_DLL_PATH: Option<String> = None;

  #[cfg(target_os = "linux")]
  const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ];

	// "libsciter.dylib" since Sciter 4.4.6.3.
  #[cfg(target_os = "macos")]
  const DLL_NAMES: &[&str] = &[ "libsciter.dylib", "sciter-osx-64.dylib" ];

  use capi::scapi::ISciterAPI;
  use capi::sctypes::{LPVOID, LPCSTR};

  type FuncType = extern "system" fn () -> *const ISciterAPI;
  type ApiType = *const ISciterAPI;


  pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;
    use std::path::{Path};


    // Try to load the library from a specified absolute path.
    fn try_load(path: &Path) -> Option<LPVOID> {
      let bytes = path.as_os_str().as_bytes();
      if let Ok(cstr) = CString::new(bytes) {
        let dll = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) };
        if !dll.is_null() {
          return Some(dll)
        }
      }
      None
    }

    // Try to find a library (by one of its names) in a specified path.
    fn try_load_from(dir: Option<&Path>) -> Option<LPVOID> {

      let dll = DLL_NAMES.iter()
        .map(|name| {
          let mut path = dir.map(Path::to_owned).unwrap_or_default();
          path.push(name);
          path
        })
        .map(|path| try_load(&path))
        .find(|dll| dll.is_some())
        .map(|o| o.unwrap());

      if dll.is_some() {
        return dll;
      }

      None
    }

    // Try to load from the current directory.
    fn in_current_dir() -> Option<LPVOID> {
      if let Ok(dir) = ::std::env::current_exe() {
        if let Some(dir) = dir.parent() {
          let dll = try_load_from(Some(dir));
          if dll.is_some() {
            return dll;
          }

          if cfg!(target_os = "macos") {
            // "(bundle folder)/Contents/Frameworks/"
            let mut path = dir.to_owned();
            path.push("../Frameworks/libsciter.dylib");
            let dll = try_load(&path);
						if dll.is_some() {
							return dll;
						}

            let mut path = dir.to_owned();
            path.push("../Frameworks/sciter-osx-64.dylib");
            let dll = try_load(&path);
						if dll.is_some() {
							return dll;
						}
          }
        }
      }
      None
    }

    // Try to load indirectly via `dlopen("dll.so")`.
    fn in_global() -> Option<LPVOID> {
      try_load_from(None)
    }

    // Try to find in $PATH.
    fn in_paths() -> Option<LPVOID> {
      use std::env;
      if let Some(paths) = env::var_os("PATH") {
        for path in env::split_paths(&paths) {
          if let Some(dll) = try_load_from(Some(&path)) {
            return Some(dll);
          }
        }
      }
      None
    }

    // try specified path first (and only if present)
    // and several paths to lookup then
    let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } {
      try_load(Path::new(path))
    } else {
      in_current_dir().or_else(in_paths).or_else(in_global)
    };

    if let Some(dll) = dll {
      // get the "SciterAPI" exported symbol
      let sym = unsafe { libc::dlsym(dll, b"SciterAPI\0".as_ptr() as LPCSTR) };
      if sym.is_null() {
        return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned());
      }

      if !permanent {
        unsafe { libc::dlclose(dll) };
        return Ok(0 as ApiType);
      }

      let get_api: FuncType = unsafe { std::mem::transmute(sym) };
      return Ok(get_api());
    }

    let sdkbin = if cfg!(target_os = "macos") { "bin.osx" } else { "bin.lnx" };
    let msg = format!("Please verify that Sciter SDK is installed and its binaries (from {}) are available in PATH.", sdkbin);
    Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n  {}", DLL_NAMES[0], msg))
  }

  pub fn SciterAPI() -> *const ISciterAPI {
    match try_load_library(true) {
      Ok(api) => api,
      Err(error) => panic!("{}", error),
    }
  }
}


#[cfg(all(target_os = "linux", not(feature = "dynamic")))]
mod ext {
	// Note:
	// Since 4.1.4 library name has been changed to "libsciter-gtk" (without 32/64 suffix).
	// Since 3.3.1.6 library name was changed to "libsciter".
	// However CC requires `-l sciter` form.
	#[link(name = "sciter-gtk")]
	extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI;	}
}

#[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "dynamic")))]
mod ext {
	#[link(name = "libsciter", kind = "dylib")]
	extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI;	}
}

/// Getting ISciterAPI reference, can be used for manual API calling.
#[doc(hidden)]
#[allow(non_snake_case)]
pub fn SciterAPI<'a>() -> &'a ISciterAPI {
	let ap = unsafe {
		if cfg!(feature="extension") {
			// TODO: it's not good to raise a panic inside `lazy_static!`,
      // because it wents into recursive panicing.
      //
			// Somehow, `cargo test --all` tests all the features,
      // also sometimes it comes even without `cfg!(test)`.
      // Well, the culprit is "examples/extensions" which uses the "extension" feature,
      // but how on earth it builds without `cfg(test)`?
      //
			if cfg!(test) {
				&*ext::SciterAPI()
			} else {
				EXT_API
					//.or_else(|| Some(&*ext::SciterAPI()))
					.expect("Sciter API is not available yet, call `sciter::set_api()` first.")
			}
		} else {
			&*ext::SciterAPI()
		}
	};

	let abi_version = ap.version;

	if cfg!(feature = "windowless") {
		assert!(abi_version >= 0x0001_0001, "Incompatible Sciter build and \"windowless\" feature");
	}
	if cfg!(not(feature = "windowless")) {
		assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature");
	}

	return ap;
}

/// Getting ISciterAPI reference, can be used for manual API calling.
///
/// Bypasses ABI compatability checks.
#[doc(hidden)]
#[allow(non_snake_case)]
pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI {
	let ap = unsafe {
		if cfg!(feature="extension") {
			EXT_API.expect("Sciter API is not available yet, call `sciter::set_api()` first.")
		} else {
			&*ext::SciterAPI()
		}
	};

	return ap;
}


lazy_static! {
	static ref _API: &'static ISciterAPI = SciterAPI();
	static ref _GAPI: &'static SciterGraphicsAPI = {
		if version_num() < 0x0401_0A00 {
			panic!("Graphics API is incompatible since 4.1.10 (your version is {})", version());
		}
		unsafe { &*(SciterAPI().GetSciterGraphicsAPI)() }
	};
	static ref _RAPI: &'static SciterRequestAPI = unsafe { &*(SciterAPI().GetSciterRequestAPI)() };
}

/// Set a custom path to the Sciter dynamic library.
///
/// Note: Must be called first before any other function.
///
/// Returns error if the specified library can not be loaded.
///
/// # Example
///
/// ```rust
/// if sciter::set_library("~/lib/sciter/bin.gtk/x64/libsciter-gtk.so").is_ok() {
///   println!("loaded Sciter version {}", sciter::version());
/// }
/// ```
pub fn set_library(custom_path: &str) -> ::std::result::Result<(), String> {
  #[cfg(not(feature = "dynamic"))]
  fn set_impl(_: &str) -> ::std::result::Result<(), String> {
    Err("Don't use `sciter::set_library()` in static builds.\n  Build with the feature \"dynamic\" instead.".to_owned())
  }

  #[cfg(feature = "dynamic")]
  fn set_impl(path: &str) -> ::std::result::Result<(), String> {
    unsafe {
      ext::CUSTOM_DLL_PATH = Some(path.to_owned());
    }
    ext::try_load_library(false).map(|_| ())
  }

  set_impl(custom_path)
}

static mut EXT_API: Option<&'static ISciterAPI> = None;

/// Set the Sciter API coming from `SciterLibraryInit`.
///
/// Note: Must be called first before any other function.
pub fn set_host_api(api: &'static ISciterAPI) {
	if cfg!(feature="extension") {
		unsafe {
			EXT_API.replace(api);
		}
	}
}

/// Sciter engine version number (e.g. `0x03030200`).
///
/// Note: does not return the `build` part because it doesn't fit in `0..255` byte range.
/// Use [`sciter::version()`](fn.version.html) instead which returns the complete version string.
pub fn version_num() -> u32 {
	use types::BOOL;
	let v1 = (_API.SciterVersion)(true as BOOL);
	let v2 = (_API.SciterVersion)(false as BOOL);
	let (major, minor, revision, _build) = (v1 >> 16 & 0xFF, v1 & 0xFF, v2 >> 16 & 0xFF, v2 & 0xFF);
	let num = (major << 24) | (minor << 16) | (revision << 8);
	// let num = ((v1 >> 16) << 24) | ((v1 & 0xFFFF) << 16) | ((v2 >> 16) << 8) | (v2 & 0xFFFF);
	return num;
}

/// Sciter engine version string (e.g. "`3.3.2.0`").
pub fn version() -> String {
	use types::BOOL;
	let v1 = (_API.SciterVersion)(true as BOOL);
	let v2 = (_API.SciterVersion)(false as BOOL);
	let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF];
	let version = format!("{}.{}.{}.{}", num[0], num[1], num[2], num[3]);
	return version;
}

/// Sciter API version.
///
/// Returns:
///
/// * `0x0000_0001` for regular builds, `0x0001_0001` for windowless builds.
/// * `0x0000_0002` since 4.4.2.14 (a breaking change in assets with [SOM builds](https://sciter.com/native-code-exposure-to-script/))
/// * `0x0000_0003` since 4.4.2.16
/// * `0x0000_0004` since 4.4.2.17 (a breaking change in SOM passport)
/// * `0x0000_0005` since 4.4.3.20 (a breaking change in `INITIALIZATION_PARAMS`, SOM in event handlers fix)
/// * `0x0000_0006` since 4.4.3.24 (TIScript native API is gone, use SOM instead)
/// * `0x0000_0007` since 4.4.5.4  (DOM-Value conversion functions were added, no breaking change)
/// * `0x0000_0008` since 4.4.6.7 (Sciter and Sciter.Lite are unified in ISciterAPI)
/// * `0x0000_0009` since 4.4.7.0 (ISciterAPI unification between all platforms)
///
/// Since 4.4.0.3.
pub fn api_version() -> u32 {
	_API.version
}

/// Returns true for windowless builds.
pub fn is_windowless() -> bool {
	api_version() >= 0x0001_0001
}

/// Various global Sciter engine options.
///
/// Used by [`sciter::set_options()`](fn.set_options.html).
///
/// See also [per-window options](window/enum.Options.html).
#[derive(Copy, Clone)]
pub enum RuntimeOptions<'a> {

  /// global; value: the full path to the Sciter dynamic library (dll/dylib/so),
  /// must be called before any other Sciter function.
  LibraryPath(&'a str),
  /// global; value: [`GFX_LAYER`](enum.GFX_LAYER.html), must be called before any window creation.
  GfxLayer(GFX_LAYER),
  /// global; value: `true` - the engine will use a "unisex" theme that is common for all platforms.
  /// That UX theme is not using OS primitives for rendering input elements.
  /// Use it if you want exactly the same (modulo fonts) look-n-feel on all platforms.
  UxTheming(bool),
  /// global or per-window; enables Sciter Inspector for all windows, must be called before any window creation.
  DebugMode(bool),
  /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](enum.SCRIPT_RUNTIME_FEATURES.html) flags.
  ///
  /// Note that these features have been disabled by default
  /// since [4.2.5.0](https://rawgit.com/c-smile/sciter-sdk/7036a9c7912ac30d9f369d9abb87b278d2d54c6d/logfile.htm).
  ScriptFeatures(u8),
	/// global; value: milliseconds, connection timeout of http client.
	ConnectionTimeout(u32),
	/// global; value: `0` - drop connection, `1` - use builtin dialog, `2` - accept connection silently.
	OnHttpsError(u8),
	// global; value: json with GPU black list, see the `gpu-blacklist.json` resource.
	// Not used in Sciter 4, in fact: https://sciter.com/forums/topic/how-to-use-the-gpu-blacklist/#post-59338
	// GpuBlacklist(&'a str),
	/// global; value: script source to be loaded into each view before any other script execution.
	InitScript(&'a str),
	/// global; value - max request length in megabytes (1024*1024 bytes), since 4.3.0.15.
	MaxHttpDataLength(usize),
	/// global or per-window; value: `true` - `1px` in CSS is treated as `1dip`, otherwise `1px` is a physical pixel (by default).
	///
	/// since [4.4.5.0](https://rawgit.com/c-smile/sciter-sdk/aafb625bb0bc317d79c0a14d02b5730f6a02b48a/logfile.htm).
	LogicalPixel(bool),
}

/// Set various global Sciter engine options, see the [`RuntimeOptions`](enum.RuntimeOptions.html).
pub fn set_options(options: RuntimeOptions) -> std::result::Result<(), ()> {
	use RuntimeOptions::*;
	use capi::scdef::SCITER_RT_OPTIONS::*;
	let (option, value) = match options {
		ConnectionTimeout(ms) => (SCITER_CONNECTION_TIMEOUT, ms as usize),
		OnHttpsError(behavior) => (SCITER_HTTPS_ERROR, behavior as usize),
		// GpuBlacklist(json) => (SCITER_SET_GPU_BLACKLIST, json.as_bytes().as_ptr() as usize),
		InitScript(script) => (SCITER_SET_INIT_SCRIPT, script.as_bytes().as_ptr() as usize),
		ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize),
		GfxLayer(backend) => (SCITER_SET_GFX_LAYER, backend as usize),
		DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize),
		UxTheming(enable) => (SCITER_SET_UX_THEMING, enable as usize),
		MaxHttpDataLength(value) => (SCITER_SET_MAX_HTTP_DATA_LENGTH, value),
		LogicalPixel(enable) => (SCITER_SET_PX_AS_DIP, enable as usize),

    LibraryPath(path) => {
      return set_library(path).map_err(|_|());
    }
	};
	let ok = (_API.SciterSetOption)(std::ptr::null_mut(), option, value);
	if ok != 0 {
		Ok(())
	} else {
		Err(())
	}
}

/// Set a global variable by its path to all windows.
///
/// This variable will be accessible in all windows via `globalThis[path]` or just `path`.
///
/// Note that this call affects only _new_ windows,
/// so it's preferred to call it before the main window creation.
///
/// See also per-window [`Window::set_variable`](window/struct.Window.html#method.set_variable)
/// to assign a global to a single window only.
pub fn set_variable(path: &str, value: Value) -> dom::Result<()> {
	let ws = s2u!(path);
	let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr());
	if ok == dom::SCDOM_RESULT::OK {
		Ok(())
	} else {
		Err(ok)
	}
}

/// Get a global variable by its path.
///
/// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable).
#[doc(hidden)]
pub fn get_variable(path: &str) -> dom::Result<Value> {
	let ws = s2u!(path);
	let mut value = Value::new();
	let ok = (_API.SciterGetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_mut_ptr());
	if ok == dom::SCDOM_RESULT::OK {
		Ok(value)
	} else {
		Err(ok)
	}
}