refactor and upgrade sciter

This commit is contained in:
rustdesk 2021-07-24 18:25:07 +08:00
parent 7282c3a16d
commit 6922a1de4c
141 changed files with 308 additions and 22557 deletions

769
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -28,10 +28,10 @@ lazy_static = "1.4"
sha2 = "0.9"
repng = "0.2"
libc = "0.2"
parity-tokio-ipc = { path = "libs/parity-tokio-ipc" }
parity-tokio-ipc = { git = "https://github.com/open-trade/parity-tokio-ipc" }
flexi_logger = "0.16"
runas = "0.2"
magnum-opus = { path = "libs/magnum-opus" }
magnum-opus = { git = "https://github.com/open-trade/magnum-opus" }
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"] }
async-trait = "0.1"
crc32fast = "1.2"
@ -46,10 +46,10 @@ cpal = { git = "https://github.com/rustaudio/cpal" }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
machine-uid = "0.2"
mac_address = "1.1"
sciter-rs = { path = "libs/rust-sciter" }
sciter-rs = { git = "https://github.com/sciter-sdk/rust-sciter" }
[target.'cfg(target_os = "windows")'.dependencies]
systray = { path = "libs/systray-rs" }
systray = { git = "https://github.com/open-trade/systray-rs" }
winapi = { version = "0.3", features = ["winuser"] }
winreg = "0.7"
windows-service = { git = 'https://github.com/mullvad/windows-service-rs.git' }
@ -64,7 +64,7 @@ core-graphics = "0.22"
[target.'cfg(target_os = "linux")'.dependencies]
libpulse-simple-binding = "2.16"
libpulse-binding = "2.16"
rust-pulsectl = { path = "libs/pulsectl" }
rust-pulsectl = { git = "https://github.com/open-trade/pulsectl" }
ctrlc = "3.1"
[target.'cfg(not(any(target_os = "windows", target_os = "android", target_os = "ios")))'.dependencies]

View File

@ -32,9 +32,9 @@ Hier sind die Server die du kostenlos nutzen kannst, es kann sein das sich diese
Die Desktop Versionen nutzen [Sciter](https://sciter.com/) für die Oberfläche, bitte lade die dynamische Sciter Bibliothek selbst herunter.
[Windows](https://github.com/c-smile/sciter-sdk/blob/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.win/x64/sciter.dll) |
[Linux](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.osx/sciter-osx-64.dylib)
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Die groben Schritte zum Kompilieren
* Bereite deine Rust Entwicklungsumgebung und C++ Entwicklungsumgebung vor
@ -90,7 +90,7 @@ source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```

View File

@ -29,9 +29,9 @@ A continuación se muestran los servidores que está utilizando de forma gratuit
La versión Desktop usa [sciter](https://sciter.com/) para GUI, por favor bajate la librería sciter tu mismo..
[Windows](https://github.com/c-smile/sciter-sdk/blob/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.win/x64/sciter.dll) |
[Linux](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.osx/sciter-osx-64.dylib)
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Pasos para compilar desde el inicio
* Prepara el entono de desarrollode Rust y el entorno de compilación de C++ y Rust.
@ -87,7 +87,7 @@ source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```

View File

@ -29,9 +29,9 @@ Ci-dessous se trouvent les serveurs que vous utilisez gratuitement, cela peut ch
Les versions de bureau utilisent [sciter](https://sciter.com/) pour l'interface graphique, veuillez télécharger la bibliothèque dynamique sciter vous-même.
[Windows](https://github.com/c-smile/sciter-sdk/blob/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.win/x64/sciter.dll) |
[Linux](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so)
[macOS](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.osx/sciter-osx-64.dylib)
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so)
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Étapes brutes de la compilation/build
* Préparez votre environnement de développement Rust et votre environnement de compilation C++.
@ -87,7 +87,7 @@ source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p cible/debug
wget https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
Exécution du cargo
```

View File

@ -31,9 +31,9 @@ Poniżej znajdują się serwery, z których można korzystać za darmo, może si
Wersje desktopowe używają [sciter](https://sciter.com/) dla GUI, proszę pobrać bibliotekę dynamiczną sciter samodzielnie.
[Windows](https://github.com/c-smile/sciter-sdk/blob/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.win/x64/sciter.dll) |
[Linux](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.osx/sciter-osx-64.dylib)
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Podstawowe kroki do kompilacji.
* Przygotuj środowisko programistyczne Rust i środowisko programowania C++
@ -89,7 +89,7 @@ source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```

View File

@ -30,9 +30,9 @@ Chat with us: [知乎](https://www.zhihu.com/people/rustdesk) | [Discord](https:
桌面版本界面使用[sciter](https://sciter.com/), 请自行下载。
[Windows](https://github.com/c-smile/sciter-sdk/blob/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.win/x64/sciter.dll) |
[Linux](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.osx/sciter-osx-64.dylib)
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## 基本构建步骤
* 请准备好Rust开发环境和C++编译环境
@ -88,7 +88,7 @@ source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```

View File

@ -31,9 +31,9 @@ Below are the servers you are using for free, it may change along the time. If y
Desktop versions use [sciter](https://sciter.com/) for GUI, please download sciter dynamic library yourself.
[Windows](https://github.com/c-smile/sciter-sdk/blob/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.win/x64/sciter.dll) |
[Linux](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.osx/sciter-osx-64.dylib)
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Raw steps to build
* Prepare your Rust development env and C++ build env
@ -89,7 +89,7 @@ source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```

14
libs/confy/.gitignore vendored
View File

@ -1,14 +0,0 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
/target
**/*.rs.bk
Cargo.lock

View File

@ -1,26 +0,0 @@
[package]
name = "confy"
version = "0.4.1"
authors = ["Katharina Fey <kookie@spacekookie.de>"]
description = "Boilerplate-free configuration management"
license = "MIT/X11 OR Apache-2.0"
documentation = "https://docs.rs/confy"
repository = "https://github.com/rust-clique/confy"
edition = "2018"
[dependencies]
serde = "^1.0"
toml = { version = "^0.5", optional = true }
directories = "^2.0"
serde_yaml = { version = "0.8", optional = true }
[features]
default = ["toml_conf"]
toml_conf = ["toml"]
yaml_conf = ["serde_yaml"]
[[example]]
name = "simple"
[dev-dependencies]
serde_derive = "^1.0"

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2018 rust-clique
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,39 +0,0 @@
# confy
Chat with us: [Discord](https://discord.gg/dwq4Zme)
Zero-boilerplate configuration management.
Focus on storing the right data, instead of worrying about how or where to store it.
```rust
use serde_derive::{Serialize, Deserialize};
#[derive(Default, Debug, Serialize, Deserialize)]
struct MyConfig {
version: u8,
api_key: String,
}
fn main() -> Result<(), ::std::io::Error> {
let cfg: MyConfig = confy::load("my-app-name")?;
dbg!(cfg);
Ok(())
}
```
## Using yaml
Enabling the `yaml_conf` feature while disabling the default `toml_conf`
feature causes confy to use a YAML config file instead of TOML.
```
[dependencies.confy]
features = ["yaml_conf"]
default-features = false
```
## Breakings changes
Starting with version 0.4.0 the configuration file are stored in the expected place for your system. See the [`directories`] crates for more information.
Before version 0.4.0, the configuration file was written in the current directory.
[`directories`]: https://crates.io/crates/directories

View File

@ -1,29 +0,0 @@
//! The most simplest examples of how to use confy
extern crate confy;
#[macro_use]
extern crate serde_derive;
#[derive(Debug, Serialize, Deserialize)]
struct ConfyConfig {
name: String,
comfy: bool,
foo: i64,
}
impl Default for ConfyConfig {
fn default() -> Self {
ConfyConfig {
name: "Unknown".to_string(),
comfy: true,
foo: 42,
}
}
}
fn main() -> Result<(), confy::ConfyError> {
let cfg: ConfyConfig = confy::load("confy_simple_app")?;
println!("{:#?}", cfg);
Ok(())
}

View File

@ -1,300 +0,0 @@
//! Zero-boilerplate configuration management
//!
//! ## Why?
//!
//! There are a lot of different requirements when
//! selecting, loading and writing a config,
//! depending on the operating system and other
//! environment factors.
//!
//! In many applications this burden is left to you,
//! the developer of an application, to figure out
//! where to place the configuration files.
//!
//! This is where `confy` comes in.
//!
//! ## Idea
//!
//! `confy` takes care of figuring out operating system
//! specific and environment paths before reading and
//! writing a configuration.
//!
//! It gives you easy access to a configuration file
//! which is mirrored into a Rust `struct` via [serde].
//! This way you only need to worry about the layout of
//! your configuration, not where and how to store it.
//!
//! [serde]: https://docs.rs/crates/serde
//!
//! `confy` uses the [`Default`] trait in Rust to automatically
//! create a new configuration, if none is available to read
//! from yet.
//! This means that you can simply assume your application
//! to have a configuration, which will be created with
//! default values of your choosing, without requiring
//! any special logic to handle creation.
//!
//! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html
//!
//! ```rust,no_run
//! use serde_derive::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct MyConfig {
//! version: u8,
//! api_key: String,
//! }
//!
//! /// `MyConfig` implements `Default`
//! impl ::std::default::Default for MyConfig {
//! fn default() -> Self { Self { version: 0, api_key: "".into() } }
//! }
//!
//! fn main() -> Result<(), confy::ConfyError> {
//! let cfg = confy::load("my-app-name")?;
//! Ok(())
//! }
//! ```
//!
//! Updating the configuration is then done via the [`store`] function.
//!
//! [`store`]: fn.store.html
//!
mod utils;
use utils::*;
use directories::ProjectDirs;
use serde::{de::DeserializeOwned, Serialize};
use std::error::Error;
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{ErrorKind::NotFound, Write};
use std::path::{Path, PathBuf};
#[cfg(not(any(feature = "toml_conf", feature = "yaml_conf")))]
compile_error!("Exactly one config language feature must be enabled to use \
confy. Please enable one of either the `toml_conf` or `yaml_conf` \
features.");
#[cfg(all(feature = "toml_conf", feature = "yaml_conf"))]
compile_error!("Exactly one config language feature must be enabled to compile \
confy. Please disable one of either the `toml_conf` or `yaml_conf` features. \
NOTE: `toml_conf` is a default feature, so disabling it might mean switching off \
default features for confy in your Cargo.toml");
#[cfg(all(feature = "toml_conf", not(feature = "yaml_conf")))]
const EXTENSION: &str = "toml";
#[cfg(feature = "yaml_conf")]
const EXTENSION: &str = "yml";
/// Load an application configuration from disk
///
/// A new configuration file is created with default values if none
/// exists.
///
/// Errors that are returned from this function are I/O related,
/// for example if the writing of the new configuration fails
/// or `confy` encounters an operating system or environment
/// that it does not support.
///
/// **Note:** The type of configuration needs to be declared in some way
/// that is inferrable by the compiler. Also note that your
/// configuration needs to implement `Default`.
///
/// ```rust,no_run
/// # use confy::ConfyError;
/// # use serde_derive::{Serialize, Deserialize};
/// # fn main() -> Result<(), ConfyError> {
/// #[derive(Default, Serialize, Deserialize)]
/// struct MyConfig {}
///
/// let cfg: MyConfig = confy::load("my-app-name")?;
/// # Ok(())
/// # }
/// ```
pub fn load<T: Serialize + DeserializeOwned + Default>(name: &str) -> Result<T, ConfyError> {
let project = ProjectDirs::from("rs", "", name).ok_or(ConfyError::BadConfigDirectoryStr)?;
let config_dir_str = get_configuration_directory_str(&project)?;
let path: PathBuf = [config_dir_str, &format!("{}.{}", name, EXTENSION)].iter().collect();
load_path(path)
}
/// Load an application configuration from a specified path.
///
/// This is an alternate version of [`load`] that allows the specification of
/// an aritrary path instead of a system one. For more information on errors
/// and behavior, see [`load`]'s documentation.
///
/// [`load`]: fn.load.html
pub fn load_path<T: Serialize + DeserializeOwned + Default>(path: impl AsRef<Path>) -> Result<T, ConfyError> {
match File::open(&path) {
Ok(mut cfg) => {
let cfg_string = cfg
.get_string()
.map_err(ConfyError::ReadConfigurationFileError)?;
#[cfg(feature = "toml_conf")] {
let cfg_data = toml::from_str(&cfg_string);
cfg_data.map_err(ConfyError::BadTomlData)
}
#[cfg(feature = "yaml_conf")] {
let cfg_data = serde_yaml::from_str(&cfg_string);
cfg_data.map_err(ConfyError::BadYamlData)
}
}
Err(ref e) if e.kind() == NotFound => {
if let Some(parent) = path.as_ref().parent() {
fs::create_dir_all(parent)
.map_err(ConfyError::DirectoryCreationFailed)?;
}
store_path(path, T::default())?;
Ok(T::default())
}
Err(e) => Err(ConfyError::GeneralLoadError(e)),
}
}
/// The errors the confy crate can encounter.
#[derive(Debug)]
pub enum ConfyError {
#[cfg(feature = "toml_conf")]
BadTomlData(toml::de::Error),
#[cfg(feature = "yaml_conf")]
BadYamlData(serde_yaml::Error),
DirectoryCreationFailed(std::io::Error),
GeneralLoadError(std::io::Error),
BadConfigDirectoryStr,
#[cfg(feature = "toml_conf")]
SerializeTomlError(toml::ser::Error),
#[cfg(feature = "yaml_conf")]
SerializeYamlError(serde_yaml::Error),
WriteConfigurationFileError(std::io::Error),
ReadConfigurationFileError(std::io::Error),
OpenConfigurationFileError(std::io::Error),
}
impl fmt::Display for ConfyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
#[cfg(feature = "toml_conf")]
ConfyError::BadTomlData(e) => write!(f, "Bad TOML data: {}", e),
#[cfg(feature = "toml_conf")]
ConfyError::SerializeTomlError(_) => write!(f, "Failed to serialize configuration data into TOML."),
#[cfg(feature = "yaml_conf")]
ConfyError::BadYamlData(e) => write!(f, "Bad YAML data: {}", e),
#[cfg(feature = "yaml_conf")]
ConfyError::SerializeYamlError(_) => write!(f, "Failed to serialize configuration data into YAML."),
ConfyError::DirectoryCreationFailed(e) => write!(f, "Failed to create directory: {}", e),
ConfyError::GeneralLoadError(_) => write!(f, "Failed to load configuration file."),
ConfyError::BadConfigDirectoryStr => write!(f, "Failed to convert directory name to str."),
ConfyError::WriteConfigurationFileError(_) => write!(f, "Failed to write configuration file."),
ConfyError::ReadConfigurationFileError(_) => write!(f, "Failed to read configuration file."),
ConfyError::OpenConfigurationFileError(_) => write!(f, "Failed to open configuration file."),
}
}
}
impl Error for ConfyError {}
/// Save changes made to a configuration object
///
/// This function will update a configuration,
/// with the provided values, and create a new one,
/// if none exists.
///
/// You can also use this function to create a new configuration
/// with different initial values than which are provided
/// by your `Default` trait implementation, or if your
/// configuration structure _can't_ implement `Default`.
///
/// ```rust,no_run
/// # use serde_derive::{Serialize, Deserialize};
/// # use confy::ConfyError;
/// # fn main() -> Result<(), ConfyError> {
/// #[derive(Serialize, Deserialize)]
/// struct MyConf {}
///
/// let my_cfg = MyConf {};
/// confy::store("my-app-name", my_cfg)?;
/// # Ok(())
/// # }
/// ```
///
/// Errors returned are I/O errors related to not being
/// able to write the configuration file or if `confy`
/// encounters an operating system or environment it does
/// not support.
pub fn store<T: Serialize>(name: &str, cfg: T) -> Result<(), ConfyError> {
let project = ProjectDirs::from("rs", "", name).ok_or(ConfyError::BadConfigDirectoryStr)?;
fs::create_dir_all(project.config_dir()).map_err(ConfyError::DirectoryCreationFailed)?;
let config_dir_str = get_configuration_directory_str(&project)?;
let path: PathBuf = [config_dir_str, &format!("{}.{}", name, EXTENSION)].iter().collect();
store_path(path, cfg)
}
/// Save changes made to a configuration object at a specified path
///
/// This is an alternate version of [`store`] that allows the specification of
/// an aritrary path instead of a system one. For more information on errors
/// and behavior, see [`store`]'s documentation.
///
/// [`store`]: fn.store.html
pub fn store_path<T: Serialize>(path: impl AsRef<Path>, cfg: T) -> Result<(), ConfyError> {
let path = path.as_ref();
let mut path_tmp = path.to_path_buf();
use std::time::{SystemTime, UNIX_EPOCH};
let mut i = 0;
loop {
i += 1;
path_tmp.set_extension(SystemTime::now().duration_since(UNIX_EPOCH).map(|x| x.as_nanos()).unwrap_or(i).to_string());
if !path_tmp.exists() {
break;
}
}
let mut f = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&path_tmp)
.map_err(ConfyError::OpenConfigurationFileError)?;
let s;
#[cfg(feature = "toml_conf")] {
s = toml::to_string(&cfg).map_err(ConfyError::SerializeTomlError)?;
}
#[cfg(feature = "yaml_conf")] {
s = serde_yaml::to_string(&cfg).map_err(ConfyError::SerializeYamlError)?;
}
f.write_all(s.as_bytes())
.map_err(ConfyError::WriteConfigurationFileError)?;
std::fs::rename(path_tmp, path)
.map_err(ConfyError::WriteConfigurationFileError)?;
Ok(())
}
fn get_configuration_directory_str(project: &ProjectDirs) -> Result<&str, ConfyError> {
let config_dir_option = project.config_dir().to_str();
match config_dir_option {
Some(x) => Ok(x),
None => Err(ConfyError::BadConfigDirectoryStr),
}
}

View File

@ -1,16 +0,0 @@
//! Some storage utilities
use std::fs::File;
use std::io::{Error as IoError, Read};
pub trait CheckedStringRead {
fn get_string(&mut self) -> Result<String, IoError>;
}
impl CheckedStringRead for File {
fn get_string(&mut self) -> Result<String, IoError> {
let mut s = String::new();
self.read_to_string(&mut s)?;
Ok(s)
}
}

View File

@ -24,7 +24,7 @@ rand = "0.8"
serde_derive = "1.0"
serde = "1.0"
lazy_static = "1.4"
confy = { path = "../confy" }
confy = { git = "https://github.com/open-trade/confy" }
dirs-next = "2.0"
filetime = "0.2"
sodiumoxide = "0.2"

View File

@ -1,2 +0,0 @@
target
Cargo.lock

View File

@ -1,18 +0,0 @@
[package]
name = "magnum-opus"
version = "0.3.4"
authors = ["Tad Hardesty <tad@platymuus.com>", "Sergey Duck <sergeypechnikov326@gmail.com>"]
edition = "2018"
description = "Safe Rust bindings for libopus"
readme = "README.md"
license = "MIT/Apache-2.0"
keywords = ["opus", "codec", "voice", "sound", "audio"]
categories = ["api-bindings", "encoding", "compression",
"multimedia::audio", "multimedia::encoding"]
repository = "https://github.com/DuckerMan/magnum-opus"
documentation = "https://docs.rs/magnum-opus"
[build-dependencies]
target_build_utils = "0.3"
bindgen = "0.53"

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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
http://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.

View File

@ -1,19 +0,0 @@
Copyright (c) 2016 Tad Hardesty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,22 +0,0 @@
# magnum-opus [![](https://meritbadge.herokuapp.com/magnum-opus)](https://crates.io/crates/magnum-opus) [![](https://img.shields.io/badge/docs-online-2020ff.svg)](https://docs.rs/magnum-opus)
### This is the fork of @SpaceManiac repo, which now is abandoned
Safe Rust bindings for libopus. The rustdoc (available through `cargo doc`)
includes brief descriptions for methods, and detailed API information can be
found at the [libopus documentation](https://opus-codec.org/docs/opus_api-1.1.2/).
## License
Licensed under either of
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

View File

@ -1,89 +0,0 @@
use std::{
env,
path::{Path, PathBuf},
};
fn find_package(name: &str) -> Vec<PathBuf> {
let vcpkg_root = std::env::var("VCPKG_ROOT").unwrap();
let mut path: PathBuf = vcpkg_root.into();
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
if target_arch == "x86_64" {
target_arch = "x64".to_owned();
} else if target_arch == "aarch64" {
target_arch = "arm64".to_owned();
} else {
target_arch = "arm".to_owned();
}
let target = if target_os == "macos" {
"x64-osx".to_owned()
} else if target_os == "windows" {
"x64-windows-static".to_owned()
} else if target_os == "android" {
format!("{}-android-static", target_arch)
} else {
"x64-linux".to_owned()
};
println!("cargo:info={}", target);
path.push("installed");
path.push(target);
println!(
"{}",
format!("cargo:rustc-link-lib={}", name.trim_start_matches("lib"))
);
println!(
"{}",
format!(
"cargo:rustc-link-search={}",
path.join("lib").to_str().unwrap()
)
);
let include = path.join("include");
println!("{}", format!("cargo:include={}", include.to_str().unwrap()));
vec![include]
}
fn generate_bindings(ffi_header: &Path, include_paths: &[PathBuf], ffi_rs: &Path) {
#[derive(Debug)]
struct ParseCallbacks;
impl bindgen::callbacks::ParseCallbacks for ParseCallbacks {
fn int_macro(&self, name: &str, _value: i64) -> Option<bindgen::callbacks::IntKind> {
if name.starts_with("OPUS") {
Some(bindgen::callbacks::IntKind::Int)
} else {
None
}
}
}
let mut b = bindgen::Builder::default()
.header(ffi_header.to_str().unwrap())
.parse_callbacks(Box::new(ParseCallbacks))
.generate_comments(false);
for dir in include_paths {
b = b.clang_arg(format!("-I{}", dir.display()));
}
b.generate().unwrap().write_to_file(ffi_rs).unwrap();
}
fn gen_opus() {
let includes = find_package("opus");
let src_dir = env::var_os("CARGO_MANIFEST_DIR").unwrap();
let src_dir = Path::new(&src_dir);
let out_dir = env::var_os("OUT_DIR").unwrap();
let out_dir = Path::new(&out_dir);
let ffi_header = src_dir.join("opus_ffi.h");
println!("rerun-if-changed={}", ffi_header.display());
for dir in &includes {
println!("rerun-if-changed={}", dir.display());
}
let ffi_rs = out_dir.join("opus_ffi.rs");
generate_bindings(&ffi_header, &includes, &ffi_rs);
}
fn main() {
gen_opus()
}

View File

@ -1 +0,0 @@
#include <opus/opus_multistream.h>

View File

@ -1,843 +0,0 @@
// Copyright 2016 Tad Hardesty
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! High-level bindings for libopus.
//!
//! Only brief descriptions are included here. For detailed information, consult
//! the [libopus documentation](https://opus-codec.org/docs/opus_api-1.1.2/).
#![warn(missing_docs)]
mod opus_ffi;
use opus_ffi as ffi;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::os::raw::c_int;
// ============================================================================
// Constants
// Generic CTLs
const OPUS_RESET_STATE: c_int = 4028; // void
const OPUS_GET_FINAL_RANGE: c_int = 4031; // out *u32
const OPUS_GET_BANDWIDTH: c_int = 4009; // out *i32
const OPUS_GET_SAMPLE_RATE: c_int = 4029; // out *i32
// Encoder CTLs
const OPUS_SET_BITRATE: c_int = 4002; // in i32
const OPUS_GET_BITRATE: c_int = 4003; // out *i32
const OPUS_SET_VBR: c_int = 4006; // in i32
const OPUS_GET_VBR: c_int = 4007; // out *i32
const OPUS_SET_VBR_CONSTRAINT: c_int = 4020; // in i32
const OPUS_GET_VBR_CONSTRAINT: c_int = 4021; // out *i32
const OPUS_SET_INBAND_FEC: c_int = 4012; // in i32
const OPUS_GET_INBAND_FEC: c_int = 4013; // out *i32
const OPUS_SET_PACKET_LOSS_PERC: c_int = 4014; // in i32
const OPUS_GET_PACKET_LOSS_PERC: c_int = 4015; // out *i32
const OPUS_GET_LOOKAHEAD: c_int = 4027; // out *i32
// Decoder CTLs
const OPUS_SET_GAIN: c_int = 4034; // in i32
const OPUS_GET_GAIN: c_int = 4045; // out *i32
const OPUS_GET_LAST_PACKET_DURATION: c_int = 4039; // out *i32
const OPUS_GET_PITCH: c_int = 4033; // out *i32
// Bitrate
const OPUS_AUTO: c_int = -1000;
const OPUS_BITRATE_MAX: c_int = -1;
/// The possible applications for the codec.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Application {
/// Best for most VoIP/videoconference applications where listening quality
/// and intelligibility matter most.
Voip = 2048,
/// Best for broadcast/high-fidelity application where the decoded audio
/// should be as close as possible to the input.
Audio = 2049,
/// Only use when lowest-achievable latency is what matters most.
LowDelay = 2051,
}
/// The available channel setings.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Channels {
/// One channel.
Mono = 1,
/// Two channels, left and right.
Stereo = 2,
}
/// The available bandwidth level settings.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Bandwidth {
/// Auto/default setting.
Auto = -1000,
/// 4kHz bandpass.
Narrowband = 1101,
/// 6kHz bandpass.
Mediumband = 1102,
/// 8kHz bandpass.
Wideband = 1103,
/// 12kHz bandpass.
Superwideband = 1104,
/// 20kHz bandpass.
Fullband = 1105,
}
impl Bandwidth {
fn from_int(value: i32) -> Option<Bandwidth> {
Some(match value {
-1000 => Bandwidth::Auto,
1101 => Bandwidth::Narrowband,
1102 => Bandwidth::Mediumband,
1103 => Bandwidth::Wideband,
1104 => Bandwidth::Superwideband,
1105 => Bandwidth::Fullband,
_ => return None,
})
}
fn decode(value: i32, what: &'static str) -> Result<Bandwidth> {
match Bandwidth::from_int(value) {
Some(bandwidth) => Ok(bandwidth),
None => Err(Error::bad_arg(what)),
}
}
}
/// Possible error codes.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum ErrorCode {
/// One or more invalid/out of range arguments.
BadArg = -1,
/// Not enough bytes allocated in the buffer.
BufferTooSmall = -2,
/// An internal error was detected.
InternalError = -3,
/// The compressed data passed is corrupted.
InvalidPacket = -4,
/// Invalid/unsupported request number.
Unimplemented = -5,
/// An encoder or decoder structure is invalid or already freed.
InvalidState = -6,
/// Memory allocation has failed.
AllocFail = -7,
/// An unknown failure.
Unknown = -8,
}
impl ErrorCode {
fn from_int(value: c_int) -> ErrorCode {
use ErrorCode::*;
match value {
ffi::OPUS_BAD_ARG => BadArg,
ffi::OPUS_BUFFER_TOO_SMALL => BufferTooSmall,
ffi::OPUS_INTERNAL_ERROR => InternalError,
ffi::OPUS_INVALID_PACKET => InvalidPacket,
ffi::OPUS_UNIMPLEMENTED => Unimplemented,
ffi::OPUS_INVALID_STATE => InvalidState,
ffi::OPUS_ALLOC_FAIL => AllocFail,
_ => Unknown,
}
}
/// Get a human-readable error string for this error code.
pub fn description(self) -> &'static str {
// should always be ASCII and non-null for any input
unsafe { CStr::from_ptr(ffi::opus_strerror(self as c_int)) }.to_str().unwrap()
}
}
/// Possible bitrates.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Bitrate {
/// Explicit bitrate choice (in bits/second).
Bits(i32),
/// Maximum bitrate allowed (up to maximum number of bytes for the packet).
Max,
/// Default bitrate decided by the encoder (not recommended).
Auto,
}
/// Get the libopus version string.
///
/// Applications may look for the substring "-fixed" in the version string to
/// determine whether they have a fixed-point or floating-point build at
/// runtime.
pub fn version() -> &'static str {
// verison string should always be ASCII
unsafe { CStr::from_ptr(ffi::opus_get_version_string()) }.to_str().unwrap()
}
macro_rules! ffi {
($f:ident $(, $rest:expr)*) => {
match unsafe { ffi::$f($($rest),*) } {
code if code < 0 => return Err(Error::from_code(stringify!($f), code)),
code => code,
}
}
}
macro_rules! ctl {
($f:ident, $this:ident, $ctl:ident, $($rest:expr),*) => {
match unsafe { ffi::$f($this.ptr, $ctl, $($rest),*) } {
code if code < 0 => return Err(Error::from_code(
concat!(stringify!($f), "(", stringify!($ctl), ")"),
code,
)),
_ => (),
}
}
}
// ============================================================================
// Encoder
macro_rules! enc_ctl {
($this:ident, $ctl:ident $(, $rest:expr)*) => {
ctl!(opus_encoder_ctl, $this, $ctl, $($rest),*)
}
}
/// An Opus encoder with associated state.
#[derive(Debug)]
pub struct Encoder {
ptr: *mut ffi::OpusEncoder,
channels: Channels,
}
impl Encoder {
/// Create and initialize an encoder.
pub fn new(sample_rate: u32, channels: Channels, mode: Application) -> Result<Encoder> {
let mut error = 0;
let ptr = unsafe { ffi::opus_encoder_create(
sample_rate as i32,
channels as c_int,
mode as c_int,
&mut error) };
if error != ffi::OPUS_OK || ptr.is_null() {
Err(Error::from_code("opus_encoder_create", error))
} else {
Ok(Encoder { ptr: ptr, channels: channels })
}
}
/// Encode an Opus frame.
pub fn encode(&mut self, input: &[i16], output: &mut [u8]) -> Result<usize> {
let len = ffi!(opus_encode, self.ptr,
input.as_ptr(), len(input) / self.channels as c_int,
output.as_mut_ptr(), len(output));
Ok(len as usize)
}
/// Encode an Opus frame from floating point input.
pub fn encode_float(&mut self, input: &[f32], output: &mut [u8]) -> Result<usize> {
let len = ffi!(opus_encode_float, self.ptr,
input.as_ptr(), len(input) / self.channels as c_int,
output.as_mut_ptr(), len(output));
Ok(len as usize)
}
/// Encode an Opus frame to a new buffer.
pub fn encode_vec(&mut self, input: &[i16], max_size: usize) -> Result<Vec<u8>> {
let mut output: Vec<u8> = vec![0; max_size];
let result = self.encode(input, output.as_mut_slice())?;
output.truncate(result);
Ok(output)
}
/// Encode an Opus frame from floating point input to a new buffer.
pub fn encode_vec_float(&mut self, input: &[f32], max_size: usize) -> Result<Vec<u8>> {
let mut output: Vec<u8> = vec![0; max_size];
let result = self.encode_float(input, output.as_mut_slice())?;
output.truncate(result);
Ok(output)
}
// ------------
// Generic CTLs
/// Reset the codec state to be equivalent to a freshly initialized state.
pub fn reset_state(&mut self) -> Result<()> {
enc_ctl!(self, OPUS_RESET_STATE);
Ok(())
}
/// Get the final range of the codec's entropy coder.
pub fn get_final_range(&mut self) -> Result<u32> {
let mut value: u32 = 0;
enc_ctl!(self, OPUS_GET_FINAL_RANGE, &mut value);
Ok(value)
}
/// Get the encoder's configured bandpass.
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_BANDWIDTH, &mut value);
Bandwidth::decode(value, "opus_encoder_ctl(OPUS_GET_BANDWIDTH)")
}
/// Get the samping rate the encoder was intialized with.
pub fn get_sample_rate(&mut self) -> Result<u32> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_SAMPLE_RATE, &mut value);
Ok(value as u32)
}
// ------------
// Encoder CTLs
/// Set the encoder's bitrate.
pub fn set_bitrate(&mut self, value: Bitrate) -> Result<()> {
let value: i32 = match value {
Bitrate::Auto => OPUS_AUTO,
Bitrate::Max => OPUS_BITRATE_MAX,
Bitrate::Bits(b) => b,
};
enc_ctl!(self, OPUS_SET_BITRATE, value);
Ok(())
}
/// Get the encoder's bitrate.
pub fn get_bitrate(&mut self) -> Result<Bitrate> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_BITRATE, &mut value);
Ok(match value {
OPUS_AUTO => Bitrate::Auto,
OPUS_BITRATE_MAX => Bitrate::Max,
_ => Bitrate::Bits(value),
})
}
/// Enable or disable variable bitrate.
pub fn set_vbr(&mut self, vbr: bool) -> Result<()> {
let value: i32 = if vbr { 1 } else { 0 };
enc_ctl!(self, OPUS_SET_VBR, value);
Ok(())
}
/// Determine if variable bitrate is enabled.
pub fn get_vbr(&mut self) -> Result<bool> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_VBR, &mut value);
Ok(value != 0)
}
/// Enable or disable constrained VBR.
pub fn set_vbr_constraint(&mut self, vbr: bool) -> Result<()> {
let value: i32 = if vbr { 1 } else { 0 };
enc_ctl!(self, OPUS_SET_VBR_CONSTRAINT, value);
Ok(())
}
/// Determine if constrained VBR is enabled.
pub fn get_vbr_constraint(&mut self) -> Result<bool> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_VBR_CONSTRAINT, &mut value);
Ok(value != 0)
}
/// Configures the encoder's use of inband forward error correction (FEC).
pub fn set_inband_fec(&mut self, value: bool) -> Result<()> {
let value: i32 = if value { 1 } else { 0 };
enc_ctl!(self, OPUS_SET_INBAND_FEC, value);
Ok(())
}
/// Gets encoder's configured use of inband forward error correction.
pub fn get_inband_fec(&mut self) -> Result<bool> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_INBAND_FEC, &mut value);
Ok(value != 0)
}
/// Sets the encoder's expected packet loss percentage.
pub fn set_packet_loss_perc(&mut self, value: i32) -> Result<()> {
enc_ctl!(self, OPUS_SET_PACKET_LOSS_PERC, value);
Ok(())
}
/// Gets the encoder's expected packet loss percentage.
pub fn get_packet_loss_perc(&mut self) -> Result<i32> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_PACKET_LOSS_PERC, &mut value);
Ok(value)
}
/// Gets the total samples of delay added by the entire codec.
pub fn get_lookahead(&mut self) -> Result<i32> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_LOOKAHEAD, &mut value);
Ok(value)
}
// TODO: Encoder-specific CTLs
}
impl Drop for Encoder {
fn drop(&mut self) {
unsafe { ffi::opus_encoder_destroy(self.ptr) }
}
}
// "A single codec state may only be accessed from a single thread at
// a time and any required locking must be performed by the caller. Separate
// streams must be decoded with separate decoder states and can be decoded
// in parallel unless the library was compiled with NONTHREADSAFE_PSEUDOSTACK
// defined."
//
// In other words, opus states may be moved between threads at will. A special
// compilation mode intended for embedded platforms forbids multithreaded use
// of the library as a whole rather than on a per-state basis, but the opus-sys
// crate does not use this mode.
unsafe impl Send for Encoder {}
// ============================================================================
// Decoder
macro_rules! dec_ctl {
($this:ident, $ctl:ident $(, $rest:expr)*) => {
ctl!(opus_decoder_ctl, $this, $ctl, $($rest),*)
}
}
/// An Opus decoder with associated state.
#[derive(Debug)]
pub struct Decoder {
ptr: *mut ffi::OpusDecoder,
channels: Channels,
}
impl Decoder {
/// Create and initialize a decoder.
pub fn new(sample_rate: u32, channels: Channels) -> Result<Decoder> {
let mut error = 0;
let ptr = unsafe { ffi::opus_decoder_create(
sample_rate as i32,
channels as c_int,
&mut error) };
if error != ffi::OPUS_OK || ptr.is_null() {
Err(Error::from_code("opus_decoder_create", error))
} else {
Ok(Decoder { ptr: ptr, channels: channels })
}
}
/// Decode an Opus packet.
pub fn decode(&mut self, input: &[u8], output: &mut [i16], fec: bool) -> Result<usize> {
let ptr = match input.len() {
0 => std::ptr::null(),
_ => input.as_ptr(),
};
let len = ffi!(opus_decode, self.ptr,
ptr, len(input),
output.as_mut_ptr(), len(output) / self.channels as c_int,
fec as c_int);
Ok(len as usize)
}
/// Decode an Opus packet with floating point output.
pub fn decode_float(&mut self, input: &[u8], output: &mut [f32], fec: bool) -> Result<usize> {
let ptr = match input.len() {
0 => std::ptr::null(),
_ => input.as_ptr(),
};
let len = ffi!(opus_decode_float, self.ptr,
ptr, len(input),
output.as_mut_ptr(), len(output) / self.channels as c_int,
fec as c_int);
Ok(len as usize)
}
/// Get the number of samples of an Opus packet.
pub fn get_nb_samples(&self, packet: &[u8]) -> Result<usize> {
let len = ffi!(opus_decoder_get_nb_samples, self.ptr,
packet.as_ptr(), packet.len() as i32);
Ok(len as usize)
}
// ------------
// Generic CTLs
/// Reset the codec state to be equivalent to a freshly initialized state.
pub fn reset_state(&mut self) -> Result<()> {
dec_ctl!(self, OPUS_RESET_STATE);
Ok(())
}
/// Get the final range of the codec's entropy coder.
pub fn get_final_range(&mut self) -> Result<u32> {
let mut value: u32 = 0;
dec_ctl!(self, OPUS_GET_FINAL_RANGE, &mut value);
Ok(value)
}
/// Get the decoder's last bandpass.
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_BANDWIDTH, &mut value);
Bandwidth::decode(value, "opus_decoder_ctl(OPUS_GET_BANDWIDTH)")
}
/// Get the samping rate the decoder was intialized with.
pub fn get_sample_rate(&mut self) -> Result<u32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_SAMPLE_RATE, &mut value);
Ok(value as u32)
}
// ------------
// Decoder CTLs
/// Configures decoder gain adjustment.
///
/// Scales the decoded output by a factor specified in Q8 dB units. This has
/// a maximum range of -32768 to 32768 inclusive, and returns `BadArg`
/// otherwise. The default is zero indicating no adjustment. This setting
/// survives decoder reset.
///
/// `gain = pow(10, x / (20.0 * 256))`
pub fn set_gain(&mut self, gain: i32) -> Result<()> {
dec_ctl!(self, OPUS_SET_GAIN, gain);
Ok(())
}
/// Gets the decoder's configured gain adjustment.
pub fn get_gain(&mut self) -> Result<i32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_GAIN, &mut value);
Ok(value)
}
/// Gets the duration (in samples) of the last packet successfully decoded
/// or concealed.
pub fn get_last_packet_duration(&mut self) -> Result<u32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_LAST_PACKET_DURATION, &mut value);
Ok(value as u32)
}
/// Gets the pitch of the last decoded frame, if available.
///
/// This can be used for any post-processing algorithm requiring the use of
/// pitch, e.g. time stretching/shortening. If the last frame was not
/// voiced, or if the pitch was not coded in the frame, then zero is
/// returned.
pub fn get_pitch(&mut self) -> Result<i32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_PITCH, &mut value);
Ok(value)
}
}
impl Drop for Decoder {
fn drop(&mut self) {
unsafe { ffi::opus_decoder_destroy(self.ptr) }
}
}
// See `unsafe impl Send for Encoder`.
unsafe impl Send for Decoder {}
// ============================================================================
// Packet Analysis
/// Analyze raw Opus packets.
pub mod packet {
use super::*;
use super::ffi;
use std::{ptr, slice};
/// Get the bandwidth of an Opus packet.
pub fn get_bandwidth(packet: &[u8]) -> Result<Bandwidth> {
if packet.len() < 1 {
return Err(Error::bad_arg("opus_packet_get_bandwidth"));
}
let bandwidth = ffi!(opus_packet_get_bandwidth, packet.as_ptr());
Bandwidth::decode(bandwidth, "opus_packet_get_bandwidth")
}
/// Get the number of channels from an Opus packet.
pub fn get_nb_channels(packet: &[u8]) -> Result<Channels> {
if packet.len() < 1 {
return Err(Error::bad_arg("opus_packet_get_nb_channels"));
}
let channels = ffi!(opus_packet_get_nb_channels, packet.as_ptr());
match channels {
1 => Ok(Channels::Mono),
2 => Ok(Channels::Stereo),
_ => Err(Error::bad_arg("opus_packet_get_nb_channels")),
}
}
/// Get the number of frames in an Opus packet.
pub fn get_nb_frames(packet: &[u8]) -> Result<usize> {
let frames = ffi!(opus_packet_get_nb_frames, packet.as_ptr(), len(packet));
Ok(frames as usize)
}
/// Get the number of samples of an Opus packet.
pub fn get_nb_samples(packet: &[u8], sample_rate: u32) -> Result<usize> {
let frames = ffi!(opus_packet_get_nb_samples,
packet.as_ptr(), len(packet),
sample_rate as c_int);
Ok(frames as usize)
}
/// Get the number of samples per frame from an Opus packet.
pub fn get_samples_per_frame(packet: &[u8], sample_rate: u32) -> Result<usize> {
if packet.len() < 1 {
return Err(Error::bad_arg("opus_packet_get_samples_per_frame"))
}
let samples = ffi!(opus_packet_get_samples_per_frame,
packet.as_ptr(), sample_rate as c_int);
Ok(samples as usize)
}
/// Parse an Opus packet into one or more frames.
pub fn parse(packet: &[u8]) -> Result<Packet> {
let mut toc: u8 = 0;
let mut frames = [ptr::null(); 48];
let mut sizes = [0i16; 48];
let mut payload_offset: i32 = 0;
let num_frames = ffi!(opus_packet_parse,
packet.as_ptr(), len(packet),
&mut toc, frames.as_mut_ptr(),
sizes.as_mut_ptr(), &mut payload_offset);
let mut frames_vec = Vec::with_capacity(num_frames as usize);
for i in 0..num_frames as usize {
frames_vec.push(unsafe { slice::from_raw_parts(frames[i], sizes[i] as usize) });
}
Ok(Packet {
toc: toc,
frames: frames_vec,
payload_offset: payload_offset as usize,
})
}
/// A parsed Opus packet, retuned from `parse`.
#[derive(Debug)]
pub struct Packet<'a> {
/// The TOC byte of the packet.
pub toc: u8,
/// The frames contained in the packet.
pub frames: Vec<&'a [u8]>,
/// The offset into the packet at which the payload is located.
pub payload_offset: usize,
}
/// Pad a given Opus packet to a larger size.
///
/// The packet will be extended from the first `prev_len` bytes of the
/// buffer into the rest of the available space.
pub fn pad(packet: &mut [u8], prev_len: usize) -> Result<usize> {
let result = ffi!(opus_packet_pad, packet.as_mut_ptr(),
check_len(prev_len), len(packet));
Ok(result as usize)
}
/// Remove all padding from a given Opus packet and rewrite the TOC sequence
/// to minimize space usage.
pub fn unpad(packet: &mut [u8]) -> Result<usize> {
let result = ffi!(opus_packet_unpad, packet.as_mut_ptr(), len(packet));
Ok(result as usize)
}
}
// ============================================================================
// Float Soft Clipping
/// Soft-clipping to bring a float signal within the [-1,1] range.
#[derive(Debug)]
pub struct SoftClip {
channels: Channels,
memory: [f32; 2],
}
impl SoftClip {
/// Initialize a new soft-clipping state.
pub fn new(channels: Channels) -> SoftClip {
SoftClip { channels: channels, memory: [0.0; 2] }
}
/// Apply soft-clipping to a float signal.
pub fn apply(&mut self, signal: &mut [f32]) {
unsafe { ffi::opus_pcm_soft_clip(
signal.as_mut_ptr(),
len(signal) / self.channels as c_int,
self.channels as c_int,
self.memory.as_mut_ptr()) };
}
}
// ============================================================================
// Repacketizer
/// A repacketizer used to merge together or split apart multiple Opus packets.
#[derive(Debug)]
pub struct Repacketizer {
ptr: *mut ffi::OpusRepacketizer,
}
impl Repacketizer {
/// Create and initialize a repacketizer.
pub fn new() -> Result<Repacketizer> {
let ptr = unsafe { ffi::opus_repacketizer_create() };
if ptr.is_null() {
Err(Error::from_code("opus_repacketizer_create", ffi::OPUS_ALLOC_FAIL))
} else {
Ok(Repacketizer { ptr: ptr })
}
}
/// Shortcut to combine several smaller packets into one larger one.
pub fn combine(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<usize> {
let mut state = self.begin();
for &packet in input {
state.cat(packet)?;
}
state.out(output)
}
/// Begin using the repacketizer.
pub fn begin<'rp, 'buf>(&'rp mut self) -> RepacketizerState<'rp, 'buf> {
unsafe { ffi::opus_repacketizer_init(self.ptr); }
RepacketizerState { rp: self, phantom: PhantomData }
}
}
impl Drop for Repacketizer {
fn drop(&mut self) {
unsafe { ffi::opus_repacketizer_destroy(self.ptr) }
}
}
// See `unsafe impl Send for Encoder`.
unsafe impl Send for Repacketizer {}
// To understand why these lifetime bounds are needed, imagine that the
// repacketizer keeps an internal Vec<&'buf [u8]>, which is added to by cat()
// and accessed by get_nb_frames(), out(), and out_range(). To prove that these
// lifetime bounds are correct, a dummy implementation with the same signatures
// but a real Vec<&'buf [u8]> rather than unsafe blocks may be substituted.
/// An in-progress repacketization.
#[derive(Debug)]
pub struct RepacketizerState<'rp, 'buf> {
rp: &'rp mut Repacketizer,
phantom: PhantomData<&'buf [u8]>,
}
impl<'rp, 'buf> RepacketizerState<'rp, 'buf> {
/// Add a packet to the current repacketizer state.
pub fn cat(&mut self, packet: &'buf [u8]) -> Result<()> {
ffi!(opus_repacketizer_cat, self.rp.ptr,
packet.as_ptr(), len(packet));
Ok(())
}
/// Add a packet to the current repacketizer state, moving it.
#[inline]
pub fn cat_move<'b2>(self, packet: &'b2 [u8]) -> Result<RepacketizerState<'rp, 'b2>> where 'buf: 'b2 {
let mut shorter = self;
shorter.cat(packet)?;
Ok(shorter)
}
/// Get the total number of frames contained in packet data submitted so
/// far via `cat`.
pub fn get_nb_frames(&mut self) -> usize {
unsafe { ffi::opus_repacketizer_get_nb_frames(self.rp.ptr) as usize }
}
/// Construct a new packet from data previously submitted via `cat`.
///
/// All previously submitted frames are used.
pub fn out(&mut self, buffer: &mut [u8]) -> Result<usize> {
let result = ffi!(opus_repacketizer_out, self.rp.ptr,
buffer.as_mut_ptr(), len(buffer));
Ok(result as usize)
}
/// Construct a new packet from data previously submitted via `cat`, with
/// a manually specified subrange.
///
/// The `end` index should not exceed the value of `get_nb_frames()`.
pub fn out_range(&mut self, begin: usize, end: usize, buffer: &mut [u8]) -> Result<usize> {
let result = ffi!(opus_repacketizer_out_range, self.rp.ptr,
check_len(begin), check_len(end),
buffer.as_mut_ptr(), len(buffer));
Ok(result as usize)
}
}
// ============================================================================
// TODO: Multistream API
// ============================================================================
// Error Handling
/// Opus error Result alias.
pub type Result<T> = std::result::Result<T, Error>;
/// An error generated by the Opus library.
#[derive(Debug)]
pub struct Error {
function: &'static str,
code: ErrorCode,
}
impl Error {
fn bad_arg(what: &'static str) -> Error {
Error { function: what, code: ErrorCode::BadArg }
}
fn from_code(what: &'static str, code: c_int) -> Error {
Error { function: what, code: ErrorCode::from_int(code) }
}
/// Get the name of the Opus function from which the error originated.
#[inline]
pub fn function(&self) -> &'static str { self.function }
/// Get a textual description of the error provided by Opus.
#[inline]
pub fn description(&self) -> &'static str { self.code.description() }
/// Get the Opus error code of the error.
#[inline]
pub fn code(&self) -> ErrorCode { self.code }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}: {}", self.function, self.description())
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
self.code.description()
}
}
fn check_len(val: usize) -> c_int {
let len = val as c_int;
if len as usize != val {
panic!("length out of range: {}", val);
}
len
}
#[inline]
fn len<T>(slice: &[T]) -> c_int {
check_len(slice.len())
}

View File

@ -1,6 +0,0 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
include!(concat!(env!("OUT_DIR"), "/opus_ffi.rs"));

View File

@ -1,10 +0,0 @@
extern crate opus;
fn main() {
let mut rp = opus::Repacketizer::new().unwrap();
let mut wip = rp.begin().cat_move(
&[1, 2, 3]
//~^ ERROR borrowed value does not live long enough
).unwrap();
wip.out(&mut []);
}

View File

@ -1,13 +0,0 @@
//! Test that supplying empty packets does forward error correction.
extern crate magnum_opus;
use magnum_opus::*;
#[test]
fn blah() {
let mut magnum_opus = Decoder::new(48000, Channels::Mono).unwrap();
let mut output = vec![0i16; 5760];
let size = magnum_opus.decode(&[], &mut output[..], true).unwrap();
assert_eq!(size, 5760);
}

View File

@ -1,29 +0,0 @@
// Based on libmagnum_opus/tests/test_magnum_opus_padding.c
/* Check for overflow in reading the padding length.
* http://lists.xiph.org/pipermail/magnum_opus/2012-November/001834.html
*/
extern crate magnum_opus;
#[test]
fn test_overflow() {
const PACKETSIZE: usize = 16909318;
const CHANNELS: magnum_opus::Channels = magnum_opus::Channels::Stereo;
const FRAMESIZE: usize = 5760;
let mut input = vec![0xff; PACKETSIZE];
let mut output = vec![0i16; FRAMESIZE * 2];
input[0] = 0xff;
input[1] = 0x41;
*input.last_mut().unwrap() = 0x0b;
let mut decoder = magnum_opus::Decoder::new(48000, CHANNELS).unwrap();
let result = decoder.decode(&input[..], &mut output[..], false);
drop(decoder);
drop(input);
drop(output);
assert_eq!(result.unwrap_err().code(), magnum_opus::ErrorCode::InvalidPacket);
}

View File

@ -1,127 +0,0 @@
extern crate magnum_opus;
fn check_ascii(s: &str) -> &str {
for &b in s.as_bytes() {
assert!(b < 0x80, "Non-ASCII character in string");
assert!(b > 0x00, "NUL in string")
}
std::str::from_utf8(s.as_bytes()).unwrap()
}
#[test]
fn strings_ascii() {
use magnum_opus::ErrorCode::*;
println!("\nVersion: {}", check_ascii(magnum_opus::version()));
let codes = [BadArg, BufferTooSmall, InternalError, InvalidPacket,
Unimplemented, InvalidState, AllocFail, Unknown];
for &code in codes.iter() {
println!("{:?}: {}", code, check_ascii(code.description()));
}
}
// 48000Hz * 1 channel * 20 ms / 1000
const MONO_20MS: usize = 48000 * 1 * 20 / 1000;
#[test]
fn encode_mono() {
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Mono, magnum_opus::Application::Audio).unwrap();
let mut output = [0; 256];
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[248, 255, 254]);
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[248, 255, 254]);
let len = encoder.encode(&[1_i16; MONO_20MS], &mut output).unwrap();
assert!(len > 190 && len < 220);
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
assert!(len > 170 && len < 190);
let myvec = encoder.encode_vec(&[1_i16; MONO_20MS], output.len()).unwrap();
assert!(myvec.len() > 120 && myvec.len() < 140);
}
#[test]
fn encode_stereo() {
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Stereo, magnum_opus::Application::Audio).unwrap();
let mut output = [0; 512];
let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[252, 255, 254]);
let len = encoder.encode(&[0_i16; 4 * MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[253, 255, 254, 255, 254]);
let len = encoder.encode(&[17_i16; 2 * MONO_20MS], &mut output).unwrap();
assert!(len > 240);
let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
assert!(len > 240);
// Very small buffer should still succeed
let len = encoder.encode(&[95_i16; 2 * MONO_20MS], &mut [0; 20]).unwrap();
assert!(len <= 20);
let myvec = encoder.encode_vec(&[95_i16; 2 * MONO_20MS], 20).unwrap();
assert!(myvec.len() <= 20);
}
#[test]
fn encode_bad_rate() {
match magnum_opus::Encoder::new(48001, magnum_opus::Channels::Mono, magnum_opus::Application::Audio) {
Ok(_) => panic!("Encoder::new did not return BadArg"),
Err(err) => assert_eq!(err.code(), magnum_opus::ErrorCode::BadArg),
}
}
#[test]
fn encode_bad_buffer() {
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Stereo, magnum_opus::Application::Audio).unwrap();
match encoder.encode(&[1_i16; 2 * MONO_20MS], &mut [0; 0]) {
Ok(_) => panic!("encode with 0-length buffer did not return BadArg"),
Err(err) => assert_eq!(err.code(), magnum_opus::ErrorCode::BadArg),
}
}
#[test]
fn repacketizer() {
let mut rp = magnum_opus::Repacketizer::new().unwrap();
let mut out = [0; 256];
for _ in 0..2 {
let packet1 = [249, 255, 254, 255, 254];
let packet2 = [248, 255, 254];
let mut state = rp.begin();
state.cat(&packet1).unwrap();
state.cat(&packet2).unwrap();
let len = state.out(&mut out).unwrap();
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
}
for _ in 0..2 {
let packet = [248, 255, 254];
let state = rp.begin().cat_move(&packet).unwrap();
let packet = [249, 255, 254, 255, 254];
let state = state.cat_move(&packet).unwrap();
let len = {state}.out(&mut out).unwrap();
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
}
for _ in 0..2 {
let len = rp.combine(&[
&[249, 255, 254, 255, 254],
&[248, 255, 254],
], &mut out).unwrap();
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
}
for _ in 0..2 {
let len = rp.begin()
.cat_move(&[248, 255, 254]).unwrap()
.cat_move(&[248, 71, 71]).unwrap()
.out(&mut out).unwrap();
assert_eq!(&out[..len], &[249, 255, 254, 71, 71]);
}
}

View File

@ -1,3 +0,0 @@
target
Cargo.lock
.idea

View File

@ -1,20 +0,0 @@
language: rust
rust:
- stable
- beta
- nightly
matrix:
allow_failures:
- rust: nightly
after_success:
- |-
[ $TRAVIS_BRANCH = master ] &&
[ $TRAVIS_PULL_REQUEST = false ] &&
cargo doc --all --no-deps &&
echo '<meta http-equiv=refresh content=0;url=parity_tokio_ipc/index.html>' > target/doc/index.html &&
pip install --user ghp-import &&
/home/travis/.local/bin/ghp-import -n target/doc &&
git push -fq https://${TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
env:
global:
secure: eUHPLjVMSVclRcEgwgybIKZQJTBW8QDjcjgIsEhOHZn7Kpzw0+rwJVoKkvr/uqyJwyY7pHy36mWX31J8YDSbSiM3W8jXeI97sk+FTUkleqUffPzXnbnR1D4kHZlKndFIbcuO5Z+rtVgsAv5E/u1w9XR+mvgK2lfaIEay+26gBl6dl/1TxWvrwDBeMvfq1JGVDQH4Etubncpi3LSWhbRkie1AKnVnsDIY9sUYVKSnIqjxx0qW6Z7EiCdwZ8gf04LNnqyIoKDpyldotL+nJ67ZlVI2O2DrbOOt55nliFHsH4BcWZIZOyIAM4PxIwhDl8g9E55FLkkUX9VUpVtqjTu9RWkVl7rzyrSxLoBUEjguIPrpFWBwLo0FSDvplB2XCXt8x035Io5PEg6m5dVxx5iytTIbI6HQwcA0ESTuDPuAdRJMNvJS/9e2UzPukdYYaaxF6g8wSmiIQjLuZU/nGBdmAl7Uw6cFlQnyLc/GXQg0oZ+B/J8sc4W2C/Z64oB8jK72RLNTKeeWs/XSOt8NxQiNkWeFIhGqiYOPJgjBiTCLSKJPY3CUTiBT8QpAcpj1x1gsWi+5fRoXYxNig/CmeTwZjuxKNxfQIu3J+lJbNdt44x7whnwhZ/AKVuLFPNNiC2OBNpa738UY60VYDoNZyhomWSdBnz3E6i1VtdiSnujFFnc=

View File

@ -1,24 +0,0 @@
[package]
name = "parity-tokio-ipc"
version = "0.7.2"
edition = "2018"
authors = ["NikVolf <nikvolf@gmail.com>"]
license = "MIT/Apache-2.0"
readme = "README.md"
repository = "https://github.com/nikvolf/parity-tokio-ipc"
homepage = "https://github.com/nikvolf/parity-tokio-ipc"
description = """
Interprocess communication library for tokio.
"""
[dependencies]
futures = "0.3"
log = "0.4"
mio-named-pipes = "0.1"
miow = "0.3"
rand = "0.8"
tokio = { version = "1.7", features = ["full"] }
libc = "0.2"
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winbase", "winnt", "accctrl", "aclapi", "securitybaseapi", "minwinbase", "winbase"] }

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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
http://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.

View File

@ -1,25 +0,0 @@
Copyright (c) 2017 Nikolay Volf
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,28 +0,0 @@
# parity-tokio-ipc
[![Build Status](https://travis-ci.org/NikVolf/parity-tokio-ipc.svg?branch=master)](https://travis-ci.org/NikVolf/parity-tokio-ipc)
[Documentation](https://nikvolf.github.io/parity-tokio-ipc)
This crate abstracts interprocess transport for UNIX/Windows. On UNIX it utilizes unix sockets (`tokio_uds` crate) and named pipe on windows (experimental `tokio-named-pipes` crate).
Endpoint is transport-agnostic interface for incoming connections:
```rust
let endpoint = Endpoint::new(endpoint_addr, handle).unwrap();
endpoint.incoming().for_each(|_| println!("Connection received!"));
```
And IpcStream is transport-agnostic io:
```rust
let endpoint = Endpoint::new(endpoint_addr, handle).unwrap();
endpoint.incoming().for_each(|(ipc_stream: IpcStream, _)| io::write_all(ipc_stream, b"Hello!"));
```
# License
`parity-tokio-ipc` is primarily distributed under the terms of both the MIT
license and the Apache License (Version 2.0), with portions covered by various
BSD-like licenses.
See LICENSE-APACHE, and LICENSE-MIT for details.

View File

@ -1,16 +0,0 @@
environment:
matrix:
- TARGET: x86_64-pc-windows-msvc
install:
- curl -sSf -o rustup-init.exe https://win.rustup.rs/
- rustup-init.exe -y --default-host %TARGET%
- set PATH=%PATH%;C:\Users\appveyor\.cargo\bin;C:\MinGW\bin
- rustc -vV
- cargo -vV
build: false
test_script:
- cargo test

View File

@ -1,24 +0,0 @@
use tokio::{self, io::*};
use parity_tokio_ipc::Endpoint;
#[tokio::main]
async fn main() {
let path = std::env::args().nth(1).expect("Run it with server path to connect as argument");
let mut client = Endpoint::connect(&path).await
.expect("Failed to connect client.");
loop {
let mut buf = [0u8; 4];
println!("SEND: PING");
client.write_all(b"ping").await.expect("Unable to write message to client");
client.read_exact(&mut buf[..]).await.expect("Unable to read buffer");
if let Ok("pong") = std::str::from_utf8(&buf[..]) {
println!("RECEIVED: PONG");
} else {
break;
}
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}
}

View File

@ -1,46 +0,0 @@
use tokio::{
io::*,
self,
io::split,
};
use parity_tokio_ipc::{Endpoint, SecurityAttributes};
async fn run_server(path: String) {
let mut endpoint = Endpoint::new(path);
endpoint.set_security_attributes(SecurityAttributes::allow_everyone_create().unwrap());
let mut incoming = endpoint.incoming().expect("failed to open new socket");
while let Some(result) = incoming.next().await
{
match result {
Ok(stream) => {
let (mut reader, mut writer) = split(stream);
tokio::spawn(async move {
loop {
let mut buf = [0u8; 4];
let pong_buf = b"pong";
if let Err(_) = reader.read_exact(&mut buf).await {
println!("Closing socket");
break;
}
if let Ok("ping") = std::str::from_utf8(&buf[..]) {
println!("RECIEVED: PING");
writer.write_all(pong_buf).await.expect("unable to write to socket");
println!("SEND: PONG");
}
}
});
}
_ => unreachable!("ideally")
}
};
}
#[tokio::main]
async fn main() {
let path = std::env::args().nth(1).expect("Run it with server path as argument");
run_server(path).await
}

View File

@ -1,7 +0,0 @@
#!/bin/bash
echo "Spawning 100 processes"
for i in {1..100} ;
do
( cargo run --example client -- /tmp/test.ipc & )
done

View File

@ -1,155 +0,0 @@
//! Tokio IPC transport. Under the hood uses Unix Domain Sockets for Linux/Mac
//! and Named Pipes for Windows.
//#![warn(missing_docs)]
//#![deny(rust_2018_idioms)]
#[cfg(windows)]
mod win;
#[cfg(not(windows))]
mod unix;
/// Endpoint for IPC transport
///
/// # Examples
///
/// ```ignore
/// use parity_tokio_ipc::{Endpoint, dummy_endpoint};
/// use futures::{future, Future, Stream, StreamExt};
/// use tokio::runtime::Runtime;
///
/// fn main() {
/// let mut runtime = Runtime::new().unwrap();
/// let mut endpoint = Endpoint::new(dummy_endpoint());
/// let server = endpoint.incoming()
/// .expect("failed to open up a new pipe/socket")
/// .for_each(|_stream| {
/// println!("Connection received");
/// futures::future::ready(())
/// });
/// runtime.block_on(server)
/// }
///```
#[cfg(windows)]
pub use win::{SecurityAttributes, Endpoint, Connection, ConnectionClient, Incoming};
#[cfg(unix)]
pub use unix::{SecurityAttributes, Endpoint, Connection, ConnectionClient, Incoming};
/// For testing/examples
pub fn dummy_endpoint() -> String {
let num: u64 = rand::Rng::gen(&mut rand::thread_rng());
if cfg!(windows) {
format!(r"\\.\pipe\my-pipe-{}", num)
} else {
format!(r"/tmp/my-uds-{}", num)
}
}
#[cfg(test)]
mod tests {
use futures::{channel::oneshot, FutureExt as _};
use std::time::Duration;
use tokio::{
self,
io::split,
};
use tokio::io::AsyncWriteExt;
use tokio::io::AsyncReadExt;
use super::{dummy_endpoint, Endpoint, SecurityAttributes};
use std::path::Path;
use futures::future::{Either, select, ready};
async fn run_server(path: String) {
let path = path.to_owned();
let mut endpoint = Endpoint::new(path);
endpoint.set_security_attributes(
SecurityAttributes::empty()
.set_mode(0o777)
.unwrap()
);
let mut incoming = endpoint.incoming().expect("failed to open up a new socket");
while let Some(result) = incoming.next().await {
match result {
Ok(stream) => {
let (mut reader, mut writer) = split(stream);
let mut buf = [0u8; 5];
reader.read_exact(&mut buf).await.expect("unable to read from socket");
writer.write_all(&buf[..]).await.expect("unable to write to socket");
}
_ => unreachable!("ideally")
}
};
}
#[tokio::test]
async fn smoke_test() {
let path = dummy_endpoint();
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let server = select(Box::pin(run_server(path.clone())), shutdown_rx)
.then(|either| {
match either {
Either::Right((_, server)) => {
drop(server);
}
_ => unreachable!("also ideally")
};
ready(())
});
tokio::spawn(server);
tokio::time::sleep(Duration::from_secs(2)).await;
println!("Connecting to client 0...");
let mut client_0 = Endpoint::connect(&path).await
.expect("failed to open client_0");
tokio::time::sleep(Duration::from_secs(2)).await;
println!("Connecting to client 1...");
let mut client_1 = Endpoint::connect(&path).await
.expect("failed to open client_1");
let msg = b"hello";
let mut rx_buf = vec![0u8; msg.len()];
client_0.write_all(msg).await.expect("Unable to write message to client");
client_0.read_exact(&mut rx_buf).await.expect("Unable to read message from client");
let mut rx_buf2 = vec![0u8; msg.len()];
client_1.write_all(msg).await.expect("Unable to write message to client");
client_1.read_exact(&mut rx_buf2).await.expect("Unable to read message from client");
assert_eq!(rx_buf, msg);
assert_eq!(rx_buf2, msg);
// shutdown server
if let Ok(()) = shutdown_tx.send(()) {
// wait one second for the file to be deleted.
tokio::time::sleep(Duration::from_secs(1)).await;
let path = Path::new(&path);
// assert that it has
assert!(!path.exists());
}
}
#[cfg(windows)]
fn create_pipe_with_permissions(attr: SecurityAttributes) -> ::std::io::Result<()> {
let path = dummy_endpoint();
let mut endpoint = Endpoint::new(path);
endpoint.set_security_attributes(attr);
endpoint.incoming().map(|_| ())
}
#[cfg(windows)]
#[tokio::test]
async fn test_pipe_permissions() {
create_pipe_with_permissions(SecurityAttributes::empty())
.expect("failed with no attributes");
create_pipe_with_permissions(SecurityAttributes::allow_everyone_create().unwrap())
.expect("failed with attributes for creating");
create_pipe_with_permissions(SecurityAttributes::empty().allow_everyone_connect().unwrap())
.expect("failed with attributes for connecting");
}
}

View File

@ -1,160 +0,0 @@
use libc::chmod;
use std::ffi::CString;
use std::io::{self, Error};
use tokio::io::*;
use tokio::net::{UnixListener, UnixStream};
use std::path::Path;
use std::pin::Pin;
use std::task::{Context, Poll};
/// Socket permissions and ownership on UNIX
pub struct SecurityAttributes {
// read/write permissions for owner, group and others in unix octal.
mode: Option<u16>
}
impl SecurityAttributes {
/// New default security attributes.
pub fn empty() -> Self {
SecurityAttributes {
mode: None
}
}
/// New security attributes that allow everyone to connect.
pub fn allow_everyone_connect(mut self) -> io::Result<Self> {
self.mode = Some(0o777);
Ok(self)
}
/// Set a custom permission on the socket
pub fn set_mode(mut self, mode: u16) -> io::Result<Self> {
self.mode = Some(mode);
Ok(self)
}
/// New security attributes that allow everyone to create.
pub fn allow_everyone_create() -> io::Result<Self> {
Ok(SecurityAttributes {
mode: None
})
}
/// called in unix, after server socket has been created
/// will apply security attributes to the socket.
pub(crate) unsafe fn apply_permissions(&self, path: &str) -> io::Result<()> {
let path = CString::new(path.to_owned())?;
if let Some(mode) = self.mode {
if chmod(path.as_ptr(), mode as _) == -1 {
return Err(Error::last_os_error())
}
}
Ok(())
}
}
/// Endpoint implementation for unix systems
pub struct Endpoint {
path: String,
security_attributes: SecurityAttributes,
}
pub struct Incoming {
socket: UnixListener,
}
impl Incoming {
pub async fn next(&mut self) -> Option<io::Result<Connection>> {
match self.socket.accept().await {
Ok((stream, _)) => Some(Ok(Connection::wrap(stream))),
Err(err) => Some(Err(err))
}
}
}
impl Endpoint {
/// Stream of incoming connections
pub fn incoming(&mut self) -> io::Result<Incoming> {
unsafe {
// the call to bind in `inner()` creates the file
// `apply_permission()` will set the file permissions.
self.security_attributes.apply_permissions(&self.path)?;
};
let socket = self.inner()?;
Ok(Incoming { socket })
}
/// Inner platform-dependant state of the endpoint
fn inner(&self) -> io::Result<UnixListener> {
UnixListener::bind(&self.path)
}
/// Set security attributes for the connection
pub fn set_security_attributes(&mut self, security_attributes: SecurityAttributes) {
self.security_attributes = security_attributes;
}
/// Make new connection using the provided path and running event pool
pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<Connection> {
Ok(Connection::wrap(UnixStream::connect(path.as_ref()).await?))
}
/// Returns the path of the endpoint.
pub fn path(&self) -> &str {
&self.path
}
/// New IPC endpoint at the given path
pub fn new(path: String) -> Self {
Endpoint {
path,
security_attributes: SecurityAttributes::empty(),
}
}
}
/// IPC connection.
pub struct Connection {
inner: UnixStream,
}
impl Connection {
fn wrap(stream: UnixStream) -> Self {
Self { inner: stream }
}
}
impl AsyncRead for Connection {
fn poll_read(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_read(ctx, buf)
}
}
impl AsyncWrite for Connection {
fn poll_write(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_write(ctx, buf)
}
fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<()>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_flush(ctx)
}
fn poll_shutdown(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<()>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_shutdown(ctx)
}
}
pub type ConnectionClient = Connection;

View File

@ -1,399 +0,0 @@
use winapi::shared::winerror::ERROR_SUCCESS;
use winapi::um::accctrl::*;
use winapi::um::aclapi::*;
use winapi::um::minwinbase::{LPTR, PSECURITY_ATTRIBUTES, SECURITY_ATTRIBUTES};
use winapi::um::securitybaseapi::*;
use winapi::um::winbase::{LocalAlloc, LocalFree};
use winapi::um::winnt::*;
use std::io;
use std::marker;
use std::mem;
use std::path::Path;
use std::ptr;
use tokio::net::windows::named_pipe::*;
pub type ConnectionClient = NamedPipeClient;
pub type Connection = NamedPipeServer;
/// Endpoint implementation for windows
pub struct Endpoint {
path: String,
security_attributes: SecurityAttributes,
}
fn create_server(path: &str, first: bool, attr: *mut libc::c_void) -> io::Result<NamedPipeServer> {
unsafe {
ServerOptions::new()
.access_inbound(true)
.access_outbound(true)
.out_buffer_size(65536)
.in_buffer_size(65536)
.first_pipe_instance(first)
.create_with_security_attributes_raw(path, attr)
}
}
impl Endpoint {
/// Stream of incoming connections
pub fn incoming(mut self) -> io::Result<Incoming> {
let pipe = self.inner()?;
Ok(Incoming {
path: self.path.clone(),
inner: NamedPipeSupport {
path: self.path,
pipe,
security_attributes: self.security_attributes,
},
})
}
/// Inner platform-dependant state of the endpoint
fn inner(&mut self) -> io::Result<NamedPipeServer> {
unsafe { create_server(&self.path, true, self.security_attributes.as_ptr() as _) }
}
/// Set security attributes for the connection
pub fn set_security_attributes(&mut self, security_attributes: SecurityAttributes) {
self.security_attributes = security_attributes;
}
/// Returns the path of the endpoint.
pub fn path(&self) -> &str {
&self.path
}
/// Make new connection using the provided path and running event pool.
pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<ConnectionClient> {
Self::connect_inner(path.as_ref()).await
}
async fn connect_inner(path: &Path) -> io::Result<NamedPipeClient> {
let client = loop {
match ClientOptions::new().read(true).write(true).open(path) {
Ok(client) => break client,
Err(e)
if e.raw_os_error()
== Some(winapi::shared::winerror::ERROR_PIPE_BUSY as i32) =>
{
()
}
Err(e) => return Err(e),
}
tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
};
Ok(client)
}
/// New IPC endpoint at the given path
pub fn new(path: String) -> Self {
Endpoint {
path,
security_attributes: SecurityAttributes::empty(),
}
}
}
struct NamedPipeSupport {
path: String,
pipe: NamedPipeServer,
security_attributes: SecurityAttributes,
}
/// Stream of incoming connections
pub struct Incoming {
#[allow(dead_code)]
path: String,
inner: NamedPipeSupport,
}
impl Incoming {
async fn next_(&mut self) -> io::Result<NamedPipeServer> {
self.inner.pipe.connect().await?;
let new_listener = unsafe {
create_server(
&self.inner.path,
false,
self.inner.security_attributes.as_ptr() as _,
)?
};
Ok(std::mem::replace(&mut self.inner.pipe, new_listener))
}
pub async fn next(&mut self) -> Option<io::Result<NamedPipeServer>> {
Some(self.next_().await)
}
}
/// Security attributes.
pub struct SecurityAttributes {
attributes: Option<InnerAttributes>,
}
impl SecurityAttributes {
/// New default security attributes.
pub fn empty() -> SecurityAttributes {
SecurityAttributes { attributes: None }
}
/// New default security attributes that allow everyone to connect.
pub fn allow_everyone_connect(&self) -> io::Result<SecurityAttributes> {
let attributes = Some(InnerAttributes::allow_everyone(
GENERIC_READ | FILE_WRITE_DATA,
)?);
Ok(SecurityAttributes { attributes })
}
/// Set a custom permission on the socket
pub fn set_mode(self, _mode: u32) -> io::Result<Self> {
// for now, does nothing.
Ok(self)
}
/// New default security attributes that allow everyone to create.
pub fn allow_everyone_create() -> io::Result<SecurityAttributes> {
let attributes = Some(InnerAttributes::allow_everyone(
GENERIC_READ | GENERIC_WRITE,
)?);
Ok(SecurityAttributes { attributes })
}
/// Return raw handle of security attributes.
pub(crate) unsafe fn as_ptr(&mut self) -> PSECURITY_ATTRIBUTES {
match self.attributes.as_mut() {
Some(attributes) => attributes.as_ptr(),
None => ptr::null_mut(),
}
}
}
unsafe impl Send for SecurityAttributes {}
struct Sid {
sid_ptr: PSID,
}
impl Sid {
fn everyone_sid() -> io::Result<Sid> {
let mut sid_ptr = ptr::null_mut();
#[allow(const_item_mutation)]
let result = unsafe {
AllocateAndInitializeSid(
SECURITY_WORLD_SID_AUTHORITY.as_mut_ptr() as *mut _,
1,
SECURITY_WORLD_RID,
0,
0,
0,
0,
0,
0,
0,
&mut sid_ptr,
)
};
if result == 0 {
Err(io::Error::last_os_error())
} else {
Ok(Sid { sid_ptr })
}
}
// Unsafe - the returned pointer is only valid for the lifetime of self.
unsafe fn as_ptr(&self) -> PSID {
self.sid_ptr
}
}
impl Drop for Sid {
fn drop(&mut self) {
if !self.sid_ptr.is_null() {
unsafe {
FreeSid(self.sid_ptr);
}
}
}
}
struct AceWithSid<'a> {
explicit_access: EXPLICIT_ACCESS_W,
_marker: marker::PhantomData<&'a Sid>,
}
impl<'a> AceWithSid<'a> {
fn new(sid: &'a Sid, trustee_type: u32) -> AceWithSid<'a> {
let mut explicit_access = unsafe { mem::zeroed::<EXPLICIT_ACCESS_W>() };
explicit_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
explicit_access.Trustee.TrusteeType = trustee_type;
explicit_access.Trustee.ptstrName = unsafe { sid.as_ptr() as *mut _ };
AceWithSid {
explicit_access,
_marker: marker::PhantomData,
}
}
fn set_access_mode(&mut self, access_mode: u32) -> &mut Self {
self.explicit_access.grfAccessMode = access_mode;
self
}
fn set_access_permissions(&mut self, access_permissions: u32) -> &mut Self {
self.explicit_access.grfAccessPermissions = access_permissions;
self
}
fn allow_inheritance(&mut self, inheritance_flags: u32) -> &mut Self {
self.explicit_access.grfInheritance = inheritance_flags;
self
}
}
struct Acl {
acl_ptr: PACL,
}
impl Acl {
fn empty() -> io::Result<Acl> {
Self::new(&mut [])
}
fn new(entries: &mut [AceWithSid<'_>]) -> io::Result<Acl> {
let mut acl_ptr = ptr::null_mut();
let result = unsafe {
SetEntriesInAclW(
entries.len() as u32,
entries.as_mut_ptr() as *mut _,
ptr::null_mut(),
&mut acl_ptr,
)
};
if result != ERROR_SUCCESS {
return Err(io::Error::from_raw_os_error(result as i32));
}
Ok(Acl { acl_ptr })
}
unsafe fn as_ptr(&self) -> PACL {
self.acl_ptr
}
}
impl Drop for Acl {
fn drop(&mut self) {
if !self.acl_ptr.is_null() {
unsafe { LocalFree(self.acl_ptr as *mut _) };
}
}
}
struct SecurityDescriptor {
descriptor_ptr: PSECURITY_DESCRIPTOR,
}
impl SecurityDescriptor {
fn new() -> io::Result<Self> {
let descriptor_ptr = unsafe { LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH) };
if descriptor_ptr.is_null() {
return Err(io::Error::new(
io::ErrorKind::Other,
"Failed to allocate security descriptor",
));
}
if unsafe {
InitializeSecurityDescriptor(descriptor_ptr, SECURITY_DESCRIPTOR_REVISION) == 0
} {
return Err(io::Error::last_os_error());
};
Ok(SecurityDescriptor { descriptor_ptr })
}
fn set_dacl(&mut self, acl: &Acl) -> io::Result<()> {
if unsafe {
SetSecurityDescriptorDacl(self.descriptor_ptr, true as i32, acl.as_ptr(), false as i32)
== 0
} {
return Err(io::Error::last_os_error());
}
Ok(())
}
unsafe fn as_ptr(&self) -> PSECURITY_DESCRIPTOR {
self.descriptor_ptr
}
}
impl Drop for SecurityDescriptor {
fn drop(&mut self) {
if !self.descriptor_ptr.is_null() {
unsafe { LocalFree(self.descriptor_ptr) };
self.descriptor_ptr = ptr::null_mut();
}
}
}
struct InnerAttributes {
descriptor: SecurityDescriptor,
acl: Acl,
attrs: SECURITY_ATTRIBUTES,
}
impl InnerAttributes {
fn empty() -> io::Result<InnerAttributes> {
let descriptor = SecurityDescriptor::new()?;
let mut attrs = unsafe { mem::zeroed::<SECURITY_ATTRIBUTES>() };
attrs.nLength = mem::size_of::<SECURITY_ATTRIBUTES>() as u32;
attrs.lpSecurityDescriptor = unsafe { descriptor.as_ptr() };
attrs.bInheritHandle = false as i32;
let acl = Acl::empty().expect("this should never fail");
Ok(InnerAttributes {
acl,
descriptor,
attrs,
})
}
fn allow_everyone(permissions: u32) -> io::Result<InnerAttributes> {
let mut attributes = Self::empty()?;
let sid = Sid::everyone_sid()?;
let mut everyone_ace = AceWithSid::new(&sid, TRUSTEE_IS_WELL_KNOWN_GROUP);
everyone_ace
.set_access_mode(SET_ACCESS)
.set_access_permissions(permissions)
.allow_inheritance(false as u32);
let mut entries = vec![everyone_ace];
attributes.acl = Acl::new(&mut entries)?;
attributes.descriptor.set_dacl(&attributes.acl)?;
Ok(attributes)
}
unsafe fn as_ptr(&mut self) -> PSECURITY_ATTRIBUTES {
&mut self.attrs as *mut _
}
}
#[cfg(test)]
mod test {
use super::SecurityAttributes;
#[test]
fn test_allow_everyone_everything() {
SecurityAttributes::allow_everyone_create()
.expect("failed to create security attributes that allow everyone to create a pipe");
}
#[test]
fn test_allow_eveyone_read_write() {
SecurityAttributes::empty()
.allow_everyone_connect()
.expect("failed to create security attributes that allow everyone to read and write to/from a pipe");
}
}

View File

@ -1,4 +0,0 @@
**/target
/target
**/*.rs.bk
.idea/

129
libs/pulsectl/Cargo.lock generated
View File

@ -1,129 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "libc"
version = "0.2.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a31a0627fdf1f6a39ec0dd577e101440b7db22672c0901fe00a9a6fbb5c24e8"
[[package]]
name = "libpulse-binding"
version = "2.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe925a4d3a96961316c9c1488f97a95938a6093f0d4691eec888776057ce965e"
dependencies = [
"libc",
"libpulse-sys",
"num-derive",
"num-traits",
"winapi",
]
[[package]]
name = "libpulse-sys"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d9073c83dda6aff9b611dc368e8db6e0aa29027546d8800a18b4417e182b4d5"
dependencies = [
"libc",
"num-derive",
"num-traits",
"pkg-config",
"winapi",
]
[[package]]
name = "num-derive"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "num-traits"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
dependencies = [
"autocfg",
]
[[package]]
name = "pkg-config"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677"
[[package]]
name = "proc-macro2"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rust-pulsectl"
version = "0.2.9"
dependencies = [
"libpulse-binding",
]
[[package]]
name = "syn"
version = "1.0.51"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b4f34193997d92804d359ed09953e25d5138df6bcc055a71bf68ee89fdf9223"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

View File

@ -1,19 +0,0 @@
[package]
name = "rust-pulsectl"
version = "0.2.10"
authors = ["Kristopher Ruzic <krruzic@gmail.com>"]
edition = "2018"
license = "GPL-3.0+"
description = "A higher level API for libpulse_binding"
readme = "README.md"
keywords = ["pulse", "pulseaudio", "binding", "audio", "api"]
categories = ["api-bindings", "multimedia::audio"]
homepage = "https://github.com/krruzic/pulsectl"
repository = "https://github.com/krruzic/pulsectl"
[lib]
name = "pulsectl"
path = "src/lib.rs"
[dependencies]
libpulse-binding = "2.21"

View File

@ -1,13 +0,0 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@ -1,43 +0,0 @@
Rust PulsecAudio API
====================
`pulsectl-rust` is a API wrapper for `libpulse_binding` to make pulseaudio application development easier.
This is a wrapper around the introspector, and thus this library is only capable of modifying PulseAudio data (changing volume, routing applications and muting right now).
### Usage
Add this to your `Cargo.toml`:
```toml
[dependencies]
rust-pulsectl = "0.2.6"
```
Then, connect to PulseAudio by creating a `SinkController` for audio playback devices and apps or a `SourceController` for audio recording devices and apps.
```rust
// Simple application that lists all playback devices and their status
// See examples/change_device_vol.rs for a more complete example
extern crate pulsectl;
use std::io;
use pulsectl::controllers::SinkController;
use pulsectl::controllers::DeviceControl;
fn main() {
// create handler that calls functions on playback devices and apps
let mut handler = SinkController::create();
let devices = handler
.list_devices()
.expect("Could not get list of playback devices");
println!("Playback Devices");
for dev in devices.clone() {
println!(
"[{}] {}, [Volume: {}]",
dev.index,
dev.description.as_ref().unwrap(),
dev.volume.print()
);
}
}
```

View File

@ -1,34 +0,0 @@
extern crate pulsectl;
use std::io;
use pulsectl::controllers::DeviceControl;
use pulsectl::controllers::SinkController;
fn main() {
// create handler that calls functions on playback devices and apps
let mut handler = SinkController::create().unwrap();
let devices = handler
.list_devices()
.expect("Could not get list of playback devices");
println!("Playback Devices");
for dev in devices.clone() {
println!(
"[{}] {}, [Volume: {}]",
dev.index,
dev.description.as_ref().unwrap(),
dev.volume.print()
);
}
let mut selection = String::new();
io::stdin()
.read_line(&mut selection)
.expect("error: unable to read user input");
for dev in devices.clone() {
if let true = selection.trim() == dev.index.to_string() {
handler.increase_device_volume_by_percent(dev.index, 0.05);
}
}
}

View File

@ -1,51 +0,0 @@
use std::fmt;
use crate::PulseCtlError;
/// if the error occurs within the Mainloop, we bubble up the error with
/// this conversion
impl From<PulseCtlError> for ControllerError {
fn from(error: super::errors::PulseCtlError) -> Self {
ControllerError {
error: ControllerErrorType::PulseCtlError,
message: format!("{:?}", error),
}
}
}
impl fmt::Debug for ControllerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut error_string = String::new();
match self.error {
ControllerErrorType::PulseCtlError => {
error_string.push_str("PulseCtlError");
}
ControllerErrorType::GetInfoError => {
error_string.push_str("GetInfoError");
}
}
write!(f, "[{}]: {}", error_string, self.message)
}
}
pub(crate) enum ControllerErrorType {
PulseCtlError,
GetInfoError,
}
/// Error thrown while fetching data from pulseaudio,
/// has two variants: PulseCtlError for when PulseAudio returns an error code
/// and GetInfoError when a request for data fails for whatever reason
pub struct ControllerError {
error: ControllerErrorType,
message: String,
}
impl ControllerError {
pub(crate) fn new(err: ControllerErrorType, msg: &str) -> Self {
ControllerError {
error: err,
message: msg.to_string(),
}
}
}

View File

@ -1,595 +0,0 @@
/// Source = microphone etc. something that takes in audio
/// Source Output = application consuming that audio
///
/// Sink = headphones etc. something that plays out audio
/// Sink Input = application producing that audio
/// When you create a `SinkController`, you are working with audio playback devices and applications
/// if you want to manipulate recording devices such as microphone volume,
/// you'll need to use a `SourceController`. Both of these implement the same api, defined by
/// the traits DeviceControl and AppControl
use std::cell::RefCell;
use std::clone::Clone;
use std::rc::Rc;
use pulse::{
callbacks::ListResult,
context::introspect,
volume::{ChannelVolumes, Volume},
};
use errors::{ControllerError, ControllerErrorType::*};
use types::{ApplicationInfo, DeviceInfo, ServerInfo};
use crate::Handler;
pub(crate) mod errors;
pub mod types;
pub trait DeviceControl<T> {
fn get_default_device(&mut self) -> Result<T, ControllerError>;
fn set_default_device(&mut self, name: &str) -> Result<bool, ControllerError>;
fn list_devices(&mut self) -> Result<Vec<T>, ControllerError>;
fn get_device_by_index(&mut self, index: u32) -> Result<T, ControllerError>;
fn get_device_by_name(&mut self, name: &str) -> Result<T, ControllerError>;
fn set_device_volume_by_index(&mut self, index: u32, volume: &ChannelVolumes);
fn set_device_volume_by_name(&mut self, name: &str, volume: &ChannelVolumes);
fn increase_device_volume_by_percent(&mut self, index: u32, delta: f64);
fn decrease_device_volume_by_percent(&mut self, index: u32, delta: f64);
}
pub trait AppControl<T> {
fn list_applications(&mut self) -> Result<Vec<T>, ControllerError>;
fn get_app_by_index(&mut self, index: u32) -> Result<T, ControllerError>;
fn increase_app_volume_by_percent(&mut self, index: u32, delta: f64);
fn decrease_app_volume_by_percent(&mut self, index: u32, delta: f64);
fn move_app_by_index(
&mut self,
stream_index: u32,
device_index: u32,
) -> Result<bool, ControllerError>;
fn move_app_by_name(
&mut self,
stream_index: u32,
device_name: &str,
) -> Result<bool, ControllerError>;
fn set_app_mute(&mut self, index: u32, mute: bool) -> Result<bool, ControllerError>;
}
fn volume_from_percent(volume: f64) -> f64 {
(volume * 100.0) * (f64::from(pulse::volume::VOLUME_NORM.0) / 100.0)
}
pub struct SinkController {
pub handler: Handler,
}
impl SinkController {
pub fn create() -> Result<Self, ControllerError> {
let handler = Handler::connect("SinkController")?;
Ok(SinkController { handler })
}
pub fn get_server_info(&mut self) -> Result<ServerInfo, ControllerError> {
let server = Rc::new(RefCell::new(Some(None)));
let server_ref = server.clone();
let op = self.handler.introspect.get_server_info(move |res| {
server_ref
.borrow_mut()
.as_mut()
.unwrap()
.replace(res.into());
});
self.handler.wait_for_operation(op)?;
let mut result = server.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting information about the server",
))
}
}
impl DeviceControl<DeviceInfo> for SinkController {
fn get_default_device(&mut self) -> Result<DeviceInfo, ControllerError> {
let server_info = self.get_server_info();
match server_info {
Ok(info) => self.get_device_by_name(info.default_sink_name.unwrap().as_ref()),
Err(e) => Err(e),
}
}
fn set_default_device(&mut self, name: &str) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self
.handler
.context
.borrow_mut()
.set_default_sink(name, move |res| success_ref.borrow_mut().clone_from(&res));
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn list_devices(&mut self) -> Result<Vec<DeviceInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_sink_info_list(
move |sink_list: ListResult<&introspect::SinkInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting device list",
))
}
fn get_device_by_index(&mut self, index: u32) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_sink_info_by_index(
index,
move |sink_list: ListResult<&introspect::SinkInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting requested device",
))
}
fn get_device_by_name(&mut self, name: &str) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_sink_info_by_name(
name,
move |sink_list: ListResult<&introspect::SinkInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting requested device",
))
}
fn set_device_volume_by_index(&mut self, index: u32, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_sink_volume_by_index(index, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn set_device_volume_by_name(&mut self, name: &str, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_sink_volume_by_name(name, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn increase_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_sink_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_sink_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
}
impl AppControl<ApplicationInfo> for SinkController {
fn list_applications(&mut self) -> Result<Vec<ApplicationInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_sink_input_info_list(
move |sink_list: ListResult<&introspect::SinkInputInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_app_by_index(&mut self, index: u32) -> Result<ApplicationInfo, ControllerError> {
let app = Rc::new(RefCell::new(Some(None)));
let app_ref = app.clone();
let op = self.handler.introspect.get_sink_input_info(
index,
move |sink_list: ListResult<&introspect::SinkInputInfo>| {
if let ListResult::Item(item) = sink_list {
app_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = app.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting requested app",
))
}
fn increase_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_sink_input_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_sink_input_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn move_app_by_index(
&mut self,
stream_index: u32,
device_index: u32,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_sink_input_by_index(
stream_index,
device_index,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn move_app_by_name(
&mut self,
stream_index: u32,
device_name: &str,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_sink_input_by_name(
stream_index,
device_name,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn set_app_mute(&mut self, index: u32, mute: bool) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.set_sink_input_mute(
index,
mute,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
}
pub struct SourceController {
pub handler: Handler,
}
impl SourceController {
pub fn create() -> Result<Self, ControllerError> {
let handler = Handler::connect("SourceController")?;
Ok(SourceController { handler })
}
pub fn get_server_info(&mut self) -> Result<ServerInfo, ControllerError> {
let server = Rc::new(RefCell::new(Some(None)));
let server_ref = server.clone();
let op = self.handler.introspect.get_server_info(move |res| {
server_ref
.borrow_mut()
.as_mut()
.unwrap()
.replace(res.into());
});
self.handler.wait_for_operation(op)?;
let mut result = server.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
}
impl DeviceControl<DeviceInfo> for SourceController {
fn get_default_device(&mut self) -> Result<DeviceInfo, ControllerError> {
let server_info = self.get_server_info();
match server_info {
Ok(info) => self.get_device_by_name(info.default_sink_name.unwrap().as_ref()),
Err(e) => Err(e),
}
}
fn set_default_device(&mut self, name: &str) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self
.handler
.context
.borrow_mut()
.set_default_source(name, move |res| success_ref.borrow_mut().clone_from(&res));
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn list_devices(&mut self) -> Result<Vec<DeviceInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_source_info_list(
move |sink_list: ListResult<&introspect::SourceInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_device_by_index(&mut self, index: u32) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_source_info_by_index(
index,
move |sink_list: ListResult<&introspect::SourceInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_device_by_name(&mut self, name: &str) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_source_info_by_name(
name,
move |sink_list: ListResult<&introspect::SourceInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn set_device_volume_by_index(&mut self, index: u32, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_source_volume_by_index(index, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn set_device_volume_by_name(&mut self, name: &str, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_source_volume_by_name(name, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn increase_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_source_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_source_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
}
impl AppControl<ApplicationInfo> for SourceController {
fn list_applications(&mut self) -> Result<Vec<ApplicationInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_source_output_info_list(
move |sink_list: ListResult<&introspect::SourceOutputInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_app_by_index(&mut self, index: u32) -> Result<ApplicationInfo, ControllerError> {
let app = Rc::new(RefCell::new(Some(None)));
let app_ref = app.clone();
let op = self.handler.introspect.get_source_output_info(
index,
move |sink_list: ListResult<&introspect::SourceOutputInfo>| {
if let ListResult::Item(item) = sink_list {
app_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = app.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn increase_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_source_output_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_source_output_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn move_app_by_index(
&mut self,
stream_index: u32,
device_index: u32,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_source_output_by_index(
stream_index,
device_index,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn move_app_by_name(
&mut self,
stream_index: u32,
device_name: &str,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_source_output_by_name(
stream_index,
device_name,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn set_app_mute(&mut self, index: u32, mute: bool) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.set_source_mute_by_index(
index,
mute,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
}

View File

@ -1,354 +0,0 @@
use pulse::{
channelmap,
context::introspect,
def,
def::PortAvailable,
format,
proplist::Proplist,
sample,
time::MicroSeconds,
volume::{ChannelVolumes, Volume},
};
/// These structs are direct representations of what libpulse_binding gives
/// created to be copyable / cloneable for use in and out of callbacks
/// This is a wrapper around SinkPortInfo and SourcePortInfo as they have the same members
#[derive(Clone)]
pub struct DevicePortInfo {
/// Name of the sink.
pub name: Option<String>,
/// Description of this sink.
pub description: Option<String>,
/// The higher this value is, the more useful this port is as a default.
pub priority: u32,
/// A flag indicating availability status of this port.
pub available: PortAvailable,
}
impl<'a> From<&'a Box<introspect::SinkPortInfo<'a>>> for DevicePortInfo {
fn from(item: &'a Box<introspect::SinkPortInfo<'a>>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
impl<'a> From<&'a introspect::SinkPortInfo<'a>> for DevicePortInfo {
fn from(item: &'a introspect::SinkPortInfo<'a>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
impl<'a> From<&'a Box<introspect::SourcePortInfo<'a>>> for DevicePortInfo {
fn from(item: &'a Box<introspect::SourcePortInfo<'a>>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
impl<'a> From<&'a introspect::SourcePortInfo<'a>> for DevicePortInfo {
fn from(item: &'a introspect::SourcePortInfo<'a>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
/// This is a wrapper around SinkState and SourceState as they have the same values
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum DevState {
/// This state is used when the server does not support sink state introspection.
Invalid = -1,
/// Running, sink is playing and used by at least one non-corked sink-input.
Running = 0,
/// When idle, the sink is playing but there is no non-corked sink-input attached to it.
Idle = 1,
/// When suspended, actual sink access can be closed, for instance.
Suspended = 2,
}
impl<'a> From<def::SourceState> for DevState {
fn from(s: def::SourceState) -> Self {
match s {
def::SourceState::Idle => DevState::Idle,
def::SourceState::Invalid => DevState::Invalid,
def::SourceState::Running => DevState::Running,
def::SourceState::Suspended => DevState::Suspended,
}
}
}
impl<'a> From<def::SinkState> for DevState {
fn from(s: def::SinkState) -> Self {
match s {
def::SinkState::Idle => DevState::Idle,
def::SinkState::Invalid => DevState::Invalid,
def::SinkState::Running => DevState::Running,
def::SinkState::Suspended => DevState::Suspended,
}
}
}
#[derive(Clone)]
pub enum Flags {
SourceFLags(def::SourceFlagSet),
SinkFlags(def::SinkFlagSet),
}
#[derive(Clone)]
pub struct DeviceInfo {
/// Index of the sink.
pub index: u32,
/// Name of the sink.
pub name: Option<String>,
/// Description of this sink.
pub description: Option<String>,
/// Sample spec of this sink.
pub sample_spec: sample::Spec,
/// Channel map.
pub channel_map: channelmap::Map,
/// Index of the owning module of this sink, or `None` if is invalid.
pub owner_module: Option<u32>,
/// Volume of the sink.
pub volume: ChannelVolumes,
/// Mute switch of the sink.
pub mute: bool,
/// Index of the monitor source connected to this sink.
pub monitor: Option<u32>,
/// The name of the monitor source.
pub monitor_name: Option<String>,
/// Length of queued audio in the output buffer.
pub latency: MicroSeconds,
/// Driver name.
pub driver: Option<String>,
/// Flags.
pub flags: Flags,
/// Property list.
pub proplist: Proplist,
/// The latency this device has been configured to.
pub configured_latency: MicroSeconds,
/// Some kind of “base” volume that refers to unamplified/unattenuated volume in the context of
/// the output device.
pub base_volume: Volume,
/// State.
pub state: DevState,
/// Number of volume steps for sinks which do not support arbitrary volumes.
pub n_volume_steps: u32,
/// Card index, or `None` if invalid.
pub card: Option<u32>,
/// Set of available ports.
pub ports: Vec<DevicePortInfo>,
// Pointer to active port in the set, or None.
pub active_port: Option<DevicePortInfo>,
/// Set of formats supported by the sink.
pub formats: Vec<format::Info>,
}
impl<'a> From<&'a introspect::SinkInfo<'a>> for DeviceInfo {
fn from(item: &'a introspect::SinkInfo<'a>) -> Self {
DeviceInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
index: item.index,
description: item.description.as_ref().map(|cow| cow.to_string()),
sample_spec: item.sample_spec,
channel_map: item.channel_map,
owner_module: item.owner_module,
volume: item.volume,
mute: item.mute,
monitor: Some(item.monitor_source),
monitor_name: item.monitor_source_name.as_ref().map(|cow| cow.to_string()),
latency: item.latency,
driver: item.driver.as_ref().map(|cow| cow.to_string()),
flags: Flags::SinkFlags(item.flags),
proplist: item.proplist.clone(),
configured_latency: item.configured_latency,
base_volume: item.base_volume,
state: DevState::from(item.state),
n_volume_steps: item.n_volume_steps,
card: item.card,
ports: item.ports.iter().map(From::from).collect(),
active_port: item.active_port.as_ref().map(From::from),
formats: item.formats.clone(),
}
}
}
impl<'a> From<&'a introspect::SourceInfo<'a>> for DeviceInfo {
fn from(item: &'a introspect::SourceInfo<'a>) -> Self {
DeviceInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
index: item.index,
description: item.description.as_ref().map(|cow| cow.to_string()),
sample_spec: item.sample_spec,
channel_map: item.channel_map,
owner_module: item.owner_module,
volume: item.volume,
mute: item.mute,
monitor: item.monitor_of_sink,
monitor_name: item
.monitor_of_sink_name
.as_ref()
.map(|cow| cow.to_string()),
latency: item.latency,
driver: item.driver.as_ref().map(|cow| cow.to_string()),
flags: Flags::SourceFLags(item.flags),
proplist: item.proplist.clone(),
configured_latency: item.configured_latency,
base_volume: item.base_volume,
state: DevState::from(item.state),
n_volume_steps: item.n_volume_steps,
card: item.card,
ports: item.ports.iter().map(From::from).collect(),
active_port: item.active_port.as_ref().map(From::from),
formats: item.formats.clone(),
}
}
}
#[derive(Clone)]
pub struct ApplicationInfo {
/// Index of the sink input.
pub index: u32,
/// Name of the sink input.
pub name: Option<String>,
/// Index of the module this sink input belongs to, or `None` when it does not belong to any
/// module.
pub owner_module: Option<u32>,
/// Index of the client this sink input belongs to, or invalid when it does not belong to any
/// client.
pub client: Option<u32>,
/// Index of the connected sink/source.
pub connection_id: u32,
/// The sample specification of the sink input.
pub sample_spec: sample::Spec,
/// Channel map.
pub channel_map: channelmap::Map,
/// The volume of this sink input.
pub volume: ChannelVolumes,
/// Latency due to buffering in sink input, see
/// [`def::TimingInfo`](../../def/struct.TimingInfo.html) for details.
pub buffer_usec: MicroSeconds,
/// Latency of the sink device, see
/// [`def::TimingInfo`](../../def/struct.TimingInfo.html) for details.
pub connection_usec: MicroSeconds,
/// The resampling method used by this sink input.
pub resample_method: Option<String>,
/// Driver name.
pub driver: Option<String>,
/// Stream muted.
pub mute: bool,
/// Property list.
pub proplist: Proplist,
/// Stream corked.
pub corked: bool,
/// Stream has volume. If not set, then the meaning of this structs volume member is unspecified.
pub has_volume: bool,
/// The volume can be set. If not set, the volume can still change even though clients cant
/// control the volume.
pub volume_writable: bool,
/// Stream format information.
pub format: format::Info,
}
impl<'a> From<&'a introspect::SinkInputInfo<'a>> for ApplicationInfo {
fn from(item: &'a introspect::SinkInputInfo<'a>) -> Self {
ApplicationInfo {
index: item.index,
name: item.name.as_ref().map(|cow| cow.to_string()),
owner_module: item.owner_module,
client: item.client,
connection_id: item.sink,
sample_spec: item.sample_spec,
channel_map: item.channel_map,
volume: item.volume,
buffer_usec: item.buffer_usec,
connection_usec: item.sink_usec,
resample_method: item.resample_method.as_ref().map(|cow| cow.to_string()),
driver: item.driver.as_ref().map(|cow| cow.to_string()),
mute: item.mute,
proplist: item.proplist.clone(),
corked: item.corked,
has_volume: item.has_volume,
volume_writable: item.volume_writable,
format: item.format.clone(),
}
}
}
impl<'a> From<&'a introspect::SourceOutputInfo<'a>> for ApplicationInfo {
fn from(item: &'a introspect::SourceOutputInfo<'a>) -> Self {
ApplicationInfo {
index: item.index,
name: item.name.as_ref().map(|cow| cow.to_string()),
owner_module: item.owner_module,
client: item.client,
connection_id: item.source,
sample_spec: item.sample_spec,
channel_map: item.channel_map,
volume: item.volume,
buffer_usec: item.buffer_usec,
connection_usec: item.source_usec,
resample_method: item.resample_method.as_ref().map(|cow| cow.to_string()),
driver: item.driver.as_ref().map(|cow| cow.to_string()),
mute: item.mute,
proplist: item.proplist.clone(),
corked: item.corked,
has_volume: item.has_volume,
volume_writable: item.volume_writable,
format: item.format.clone(),
}
}
}
pub struct ServerInfo {
/// User name of the daemon process.
pub user_name: Option<String>,
/// Host name the daemon is running on.
pub host_name: Option<String>,
/// Version string of the daemon.
pub server_version: Option<String>,
/// Server package name (usually “pulseaudio”).
pub server_name: Option<String>,
/// Default sample specification.
pub sample_spec: sample::Spec,
/// Name of default sink.
pub default_sink_name: Option<String>,
/// Name of default source.
pub default_source_name: Option<String>,
/// A random cookie for identifying this instance of PulseAudio.
pub cookie: u32,
/// Default channel map.
pub channel_map: channelmap::Map,
}
impl<'a> From<&'a introspect::ServerInfo<'a>> for ServerInfo {
fn from(info: &'a introspect::ServerInfo<'a>) -> Self {
ServerInfo {
user_name: info.user_name.as_ref().map(|cow| cow.to_string()),
host_name: info.host_name.as_ref().map(|cow| cow.to_string()),
server_version: info.server_version.as_ref().map(|cow| cow.to_string()),
server_name: info.server_name.as_ref().map(|cow| cow.to_string()),
sample_spec: info.sample_spec,
default_sink_name: info.default_sink_name.as_ref().map(|cow| cow.to_string()),
default_source_name: info.default_source_name.as_ref().map(|cow| cow.to_string()),
cookie: info.cookie,
channel_map: info.channel_map,
}
}
}

View File

@ -1,54 +0,0 @@
use std::fmt;
use pulse::error::{PAErr};
impl From<PAErr> for PulseCtlError {
fn from(error: PAErr) -> Self {
PulseCtlError {
error: PulseCtlErrorType::PulseAudioError,
message: format!("PulseAudio returned error: {}", error.to_string().unwrap_or("Unknown".to_owned())),
}
}
}
impl fmt::Debug for PulseCtlError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut error_string = String::new();
match self.error {
PulseCtlErrorType::ConnectError => {
error_string.push_str("ConnectError");
}
PulseCtlErrorType::OperationError => {
error_string.push_str("OperationError");
}
PulseCtlErrorType::PulseAudioError => {
error_string.push_str("PulseAudioError");
}
}
write!(f, "[{}]: {}", error_string, self.message)
}
}
pub(crate) enum PulseCtlErrorType {
ConnectError,
OperationError,
PulseAudioError,
}
/// Error thrown when PulseAudio throws an error code, there are 3 variants
/// `PulseCtlErrorType::ConnectError` when there's an error establishing a connection
/// `PulseCtlErrorType::OperationError` when the requested operation quis unexpecdatly or is cancelled
/// `PulseCtlErrorType::PulseAudioError` when PulseAudio returns an error code in any circumstance
pub struct PulseCtlError {
error: PulseCtlErrorType,
message: String,
}
impl PulseCtlError {
pub(crate) fn new(err: PulseCtlErrorType, msg: &str) -> Self {
PulseCtlError {
error: err,
message: msg.to_string(),
}
}
}

View File

@ -1,166 +0,0 @@
/// `pulsectl` is a high level wrapper around the PulseAudio bindings supplied by
/// `libpulse_binding`. It provides simple access to sinks, inputs, sources and outputs allowing
/// one to write audio control programs with ease.
///
/// ## Quick Example
///
/// The following example demonstrates listing all of the playback devices currently connected
///
/// See examples/change_device_vol.rs for a more complete example
/// ```no_run
/// extern crate pulsectl;
///
/// use std::io;
///
/// use pulsectl::controllers::SinkController;
/// use pulsectl::controllers::DeviceControl;
/// fn main() {
/// // create handler that calls functions on playback devices and apps
/// let mut handler = SinkController::create().unwrap();
/// let devices = handler
/// .list_devices()
/// .expect("Could not get list of playback devices");
///
/// println!("Playback Devices");
/// for dev in devices.clone() {
/// println!(
/// "[{}] {}, Volume: {}",
/// dev.index,
/// dev.description.as_ref().unwrap(),
/// dev.volume.print()
/// );
/// }
/// }
/// ```
extern crate libpulse_binding as pulse;
use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;
use pulse::{
context::{introspect, Context},
mainloop::standard::{IterateResult, Mainloop},
operation::{Operation, State},
proplist::Proplist,
};
use crate::errors::{PulseCtlError, PulseCtlErrorType::*};
pub mod controllers;
mod errors;
pub struct Handler {
pub mainloop: Rc<RefCell<Mainloop>>,
pub context: Rc<RefCell<Context>>,
pub introspect: introspect::Introspector,
}
fn connect_error(err: &str) -> PulseCtlError {
PulseCtlError::new(ConnectError, err)
}
impl Handler {
pub fn connect(name: &str) -> Result<Handler, PulseCtlError> {
let mut proplist = Proplist::new().unwrap();
proplist
.set_str(pulse::proplist::properties::APPLICATION_NAME, name)
.unwrap();
let mainloop;
if let Some(m) = Mainloop::new() {
mainloop = Rc::new(RefCell::new(m));
} else {
return Err(connect_error("Failed to create mainloop"));
}
let context;
if let Some(c) =
Context::new_with_proplist(mainloop.borrow().deref(), "MainConn", &proplist)
{
context = Rc::new(RefCell::new(c));
} else {
return Err(connect_error("Failed to create new context"));
}
context
.borrow_mut()
.connect(None, pulse::context::flags::NOFLAGS, None)
.map_err(|_| connect_error("Failed to connect context"))?;
loop {
match mainloop.borrow_mut().iterate(false) {
IterateResult::Err(e) => {
eprintln!("iterate state was not success, quitting...");
return Err(e.into());
}
IterateResult::Success(_) => {}
IterateResult::Quit(_) => {
eprintln!("iterate state was not success, quitting...");
return Err(PulseCtlError::new(
ConnectError,
"Iterate state quit without an error",
));
}
}
match context.borrow().get_state() {
pulse::context::State::Ready => break,
pulse::context::State::Failed | pulse::context::State::Terminated => {
eprintln!("context state failed/terminated, quitting...");
return Err(PulseCtlError::new(
ConnectError,
"Context state failed/terminated without an error",
));
}
_ => {}
}
}
let introspect = context.borrow_mut().introspect();
Ok(Handler {
mainloop,
context,
introspect,
})
}
// loop until the passed operation is completed
pub fn wait_for_operation<G: ?Sized>(
&mut self,
op: Operation<G>,
) -> Result<(), errors::PulseCtlError> {
loop {
match self.mainloop.borrow_mut().iterate(false) {
IterateResult::Err(e) => return Err(e.into()),
IterateResult::Success(_) => {}
IterateResult::Quit(_) => {
return Err(PulseCtlError::new(
OperationError,
"Iterate state quit without an error",
));
}
}
match op.get_state() {
State::Done => {
break;
}
State::Running => {}
State::Cancelled => {
return Err(PulseCtlError::new(
OperationError,
"Operation cancelled without an error",
));
}
}
}
Ok(())
}
}
impl Drop for Handler {
fn drop(&mut self) {
self.context.borrow_mut().disconnect();
self.mainloop.borrow_mut().quit(pulse::def::Retval(0));
}
}

View File

@ -1,98 +0,0 @@
version: 0.5.0.{build}
branches:
only:
- master
- travis
image:
- Visual Studio 2017
environment:
matrix:
- TARGET: x86_64-pc-windows-msvc
CHANNEL: stable
ARCH: 64
- TARGET: i686-pc-windows-msvc
CHANNEL: stable
ARCH: 32
- TARGET: x86_64-pc-windows-msvc
CHANNEL: stable
ARCH: 64skia
- TARGET: i686-pc-windows-msvc
CHANNEL: stable
ARCH: 32skia
- TARGET: x86_64-pc-windows-msvc
CHANNEL: stable
ARCH: 64
FEATURES: --features "dynamic"
- TARGET: i686-pc-windows-msvc
CHANNEL: stable
ARCH: 32
FEATURES: --features "dynamic"
- TARGET: x86_64-pc-windows-msvc
CHANNEL: nightly
ARCH: 64
- TARGET: i686-pc-windows-msvc
CHANNEL: nightly
ARCH: 32
- TARGET: x86_64-pc-windows-msvc
CHANNEL: 1.38.0
ARCH: 64
- TARGET: i686-pc-windows-msvc
CHANNEL: 1.38.0
ARCH: 32
- TARGET: x86_64-pc-windows-msvc
CHANNEL: 1.38.0
ARCH: 64
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
cache:
- C:\Users\appveyor\.cargo\registry
#- C:\projects\deps -> appveyor.yml
#- target
install:
- cmd: echo Testing sciter%ARCH% with Rust %CHANNEL%.
- cmd: echo Current directory is %APPVEYOR_BUILD_FOLDER%
- cmd: mkdir ..\deps
- curl -sSLo "..\deps\sciter.dll" "https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x%ARCH%/sciter.dll"
- curl -sSLo "..\deps\rustup-init.exe" "https://win.rustup.rs/"
- ..\deps\rustup-init.exe -y --default-host %TARGET% --default-toolchain %CHANNEL%
- cmd: set PATH=%PATH%;C:\Users\appveyor\.cargo\bin;C:\projects\deps
before_build:
- cmd: cd
- rustc --version
- cargo update
build_script:
- cmd: echo Building library
- cargo build --release --all %FEATURES%
- cmd: echo Building examples
- cargo build --example first --verbose
- cargo build --example windowless --features windowless
- cargo build --release --examples %FEATURES%
test_script:
- cargo run --example first %FEATURES%
- cargo run --example first %FEATURES%
- cargo run --example first %FEATURES% -- C:/projects/deps/sciter.dll
- cargo test -p sciter-rs %FEATURES%
- cargo test -p sciter-rs %FEATURES% --release
- cargo test -p sciter-serde %FEATURES%
- cargo test -p sciter-serde %FEATURES% --release

View File

@ -1 +0,0 @@
doc-valid-idents = ["TIScript"]

View File

@ -1,20 +0,0 @@
# EditorConfig is awesome: http://EditorConfig.org
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.rs]
indent_style = tab
indent_size = 2
tab_width = 2
[*.{yml,toml,md}]
indent_style = space
indent_size = 2
tab_width = 2
[*.md]
trim_trailing_whitespace = false

View File

@ -1,115 +0,0 @@
name: Build-n-Test
on:
push:
branches:
- master
- travis
pull_request:
branches:
- master
# Look:
# https://github.com/actions/starter-workflows/blob/master/ci/rust.yml
#
# Simple, right? Right.
# But we need to:
# * download a specific Sciter library matching the running OS
# * figure out where to save it
# * add it to the $PATH
#
# yet,
# * in case of macOS realize that it doesn't have Rust installed, so
# * install it manually and don't forget to add cargo and rustc to the $PATH on each step
# * and in case of Linux install additional packages for GTK3
#
# So, now we're ended up with this ugly script.
jobs:
fetch:
name: Fetch dependencies
runs-on: ${{ matrix.os }}
strategy:
matrix:
# macOS doesn't have Rust installed
# https://help.github.com/en/actions/automating-your-workflow-with-github-actions/software-installed-on-github-hosted-runners#macos-1015
# we will try to install it manually below.
os: [macos-latest, ubuntu-latest, windows-latest]
steps:
- name: Environment
shell: bash
env:
RUNNER_CONTEXT: ${{ toJson(runner) }}
SCITER_DEPS: ${{ runner.workspace }}
run: |
echo HOME is "$HOME"
echo workspace is "$SCITER_DEPS"
echo temp is "$TEMP"
echo runner is "$RUNNER_CONTEXT"
echo cargo is at `which cargo`
echo rustc is at `which rustc`
command -v cargo && rustc -vV
echo done
build:
needs: [fetch]
name: Build and test
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-latest, ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v2
- name: Windows deps
if: runner.os == 'Windows'
# Windows: download sciter library
run: curl -sSLo "%SCITER_DEPS%/sciter.dll" "https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll"
shell: cmd
env:
SCITER_DEPS: ${{ runner.workspace }}
- name: Linux deps
if: runner.os == 'Linux'
# Linux: download sciter library && install libgtk-3-dev
run: |
curl -so "$SCITER_DEPS/libsciter-gtk.so" "https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so"
sudo apt-get update -y && sudo apt-get install libgtk-3-dev libgtk-3-0 libstdc++-6-pic -y
env:
SCITER_DEPS: ${{ runner.workspace }}
- name: macOS deps
if: runner.os == 'macOS'
# OSX: download sciter library && install rustup
run: |
curl -so "$SCITER_DEPS/sciter-osx-64.dylib" "https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/sciter-osx-64.dylib"
curl https://sh.rustup.rs -sSf | sh -s -- --profile minimal -y
test -f $HOME/.cargo/env && source $HOME/.cargo/env
echo cargo is at `which cargo`
echo rustc is at `which rustc`
env:
SCITER_DEPS: ${{ runner.workspace }}
- name: Build
shell: bash
run: |
test -f $HOME/.cargo/env && source $HOME/.cargo/env
cargo build --all
cargo build --examples
- name: Tests
shell: bash
run: |
test -f $HOME/.cargo/env && source $HOME/.cargo/env
export PATH="$PATH:$SCITER_DEPS"
cargo run --example first
cargo test -p sciter-rs
cargo test -p sciter-serde
env:
SCITER_DEPS: ${{ runner.workspace }}

View File

@ -1,4 +0,0 @@
target
Cargo.lock
.vscode/
.vs/

View File

@ -1,6 +0,0 @@
# `rustfmt --config-help` for formatting options
max_width = 140
ideal_width = 120
tab_spaces = 2
hard_tabs = true
blank_lines_upper_bound = 2

View File

@ -1,99 +0,0 @@
# Based on the "trust" template v0.1.2
# https://github.com/japaric/trust/tree/v0.1.2
dist: xenial
sudo: false
language: rust
compiler: gcc
os:
- linux
- osx
rust:
- stable
- nightly
- 1.40.0
matrix:
include:
- os: osx
osx_image: xcode8
- os: osx
osx_image: xcode11
branches:
only:
- master
- travis
notifications:
email: change
cache: cargo
before_cache:
# Travis can't cache files that are not readable by "others"
- chmod -R a+r $HOME/.cargo
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- libgtk-3-dev
- libgtk-3-0
- libstdc++-6-pic
before_install:
- set -e
- rustup self update
install:
- source ~/.cargo/env || true
- export SDK_URL=https://raw.githubusercontent.com/c-smile/sciter-sdk/master
- if [ "$TRAVIS_OS_NAME" = "osx" ]; then export SDK_DLL="$TRAVIS_BUILD_DIR/sciter-osx-64.dylib"; fi
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then export SDK_DLL="$TRAVIS_BUILD_DIR/libsciter-gtk.so"; fi
- if [ "$TRAVIS_OS_NAME" = "osx" ]; then curl -so "$SDK_DLL" $SDK_URL/bin.osx/sciter-osx-64.dylib; fi
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then curl -so "$SDK_DLL" $SDK_URL/bin.lnx/x64/libsciter-gtk.so; fi
before_script:
- if [ "$TRAVIS_OS_NAME" = "osx" ]; then export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$TRAVIS_BUILD_DIR"; fi
- if [ "$TRAVIS_OS_NAME" = "osx" ]; then cp "$TRAVIS_BUILD_DIR/sciter-osx-64.dylib" "$TRAVIS_BUILD_DIR/libsciter-osx-64.dylib"; fi
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TRAVIS_BUILD_DIR"; fi
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then export RUSTFLAGS='-C link-arg=-Wl,--unresolved-symbols=ignore-in-shared-libs'; fi
- export PATH="$PATH:$TRAVIS_BUILD_DIR"
- export LIBRARY_PATH="$LIBRARY_PATH:$TRAVIS_BUILD_DIR"
- export RUST_BACKTRACE=full
- #ls /usr/lib/x86_64-linux-gnu/libstdc++*
- #strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIBC
- #file $SDK_DLL
- gcc --version
- rustc --version
script:
- cargo update
- cargo build --example first --verbose
- cargo run --example first
- cargo run --example first --features "dynamic"
- cargo run --example first --features "dynamic" -- "$SDK_DLL"
- cargo build --all
- cargo build --all --release
- cargo build --examples --release
- cargo build --example windowless --features windowless
- cargo test -p sciter-rs
- cargo test -p sciter-rs --release
- cargo test -p sciter-serde
- cargo test -p sciter-serde --release
after_script: set +e

View File

@ -1,111 +0,0 @@
[package]
name = "sciter-rs"
version = "0.5.53"
description = "Rust bindings for Sciter - Embeddable HTML/CSS/script engine (cross-platform desktop GUI toolkit). Also capable with DirectX / OpenGL."
keywords = ["gui", "gtk", "cocoa", "opengl", "skia"]
categories = ["gui", "web-programming", "rendering::graphics-api", "api-bindings"]
authors = ["pravic <ehysta@gmail.com>"]
repository = "https://github.com/sciter-sdk/rust-sciter"
documentation = "https://docs.rs/sciter-rs"
readme = "README.md"
license = "MIT"
exclude = [".gitignore", ".editorconfig", ".appveyor.yml", "clippy.toml"]
[badges]
appveyor = { repository = "sciter-sdk/rust-sciter" }
travis-ci = { repository = "sciter-sdk/rust-sciter" }
maintenance = { status = "passively-maintained" }
[lib]
name = "sciter"
path = "src/lib.rs"
crate-type = ["rlib"]
[features]
default = ["dynamic"]
# Enable nightly compiler features (currently doesn't use any).
nightly = []
# Build as a Sciter extension library.
# see "examples/extension"
# note: this feature can't be tested.
extension = []
# Load Sciter DLL dynamically from the path specified by `sciter::set_library`.
# Otherwise, links statically to `libsciter-gtk.so` or `sciter-osx-64.dylib`.
dynamic = []
# Build this crate specifically for Sciter.Lite versions
# which are incompatible with the regular ones.
windowless = []
[dependencies]
libc = "0.2"
lazy_static = "1.4"
[target.x86_64-apple-darwin.dependencies]
objc = "0.2"
objc-foundation = "0.1"
[dev-dependencies]
winit = "0.19"
winapi = { version = "0.3", features = [
"impl-default",
"winuser",
"wingdi",
"sysinfoapi",
] }
raw-window-handle = "0.3"
[[example]]
name = "first"
path = "examples/first.rs"
[[example]]
name = "minimal"
path = "examples/minimal.rs"
[[example]]
name = "download"
path = "examples/download.rs"
[[example]]
name = "dom"
path = "examples/dom.rs"
[[example]]
name = "fire_event"
path = "examples/fire_event.rs"
[[example]]
name = "interop"
path = "examples/interop.rs"
[[example]]
name = "threads"
path = "examples/threads.rs"
[[example]]
name = "archived"
path = "examples/archived.rs"
[[example]]
name = "video"
path = "examples/video.rs"
[[example]]
name = "clock"
path = "examples/clock.rs"
[[example]]
name = "windowless"
path = "examples/windowless.rs"
[[example]]
name = "som"
path = "examples/som.rs"

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright 2019 pravic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,159 +0,0 @@
# Rust bindings for Sciter
[![Build status](https://ci.appveyor.com/api/projects/status/cbrisyh792mmmd08/branch/master?svg=true)](https://ci.appveyor.com/project/pravic/rust-sciter)
[![Build Status](https://img.shields.io/travis/sciter-sdk/rust-sciter/master.svg)](https://travis-ci.org/sciter-sdk/rust-sciter)
[![Minimum supported Rust version](https://img.shields.io/badge/rustc-1.38+-green.svg)](https://github.com/sciter-sdk/rust-sciter/commits/master/.travis.yml)
[![Current Version](https://img.shields.io/crates/v/sciter-rs.svg)](https://crates.io/crates/sciter-rs)
[![Documentation](https://docs.rs/sciter-rs/badge.svg)](https://docs.rs/sciter-rs)
[![License](https://img.shields.io/crates/l/sciter-rs.svg)](https://crates.io/crates/sciter-rs)
[![Join the forums at https://sciter.com/forums](https://img.shields.io/badge/forum-sciter.com-orange.svg)](https://sciter.com/forums)
Check [this page](https://sciter.com/developers/sciter-sdk-bindings/) for other language bindings (Delphi / D / Go / .NET / Python / Rust).
----
## Introduction
Sciter 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.
## Screenshots
Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples) of desktop UI examples
and [DirectX UI integration](https://github.com/pravic/rust-gfx-sciter) via [Rust GFX](https://github.com/gfx-rs/gfx).
## Description
Physically Sciter is a mono library which contains:
* [HTML and CSS](https://sciter.com/developers/for-web-programmers/) rendering engine based on the H-SMILE core used in [HTMLayout](https://terrainformatica.com/a-homepage-section/htmlayout/),
* JavaScript alike [Scripting engine](https://sciter.com/developers/sciter-docs/) core of [TIScript](https://sciter.com/developers/for-web-programmers/tiscript-vs-javascript/) which by itself is based on [c-smile](https://c-smile.sourceforge.net/) engine,
* Persistent [Database](https://sciter.com/docs/content/script/Storage.htm) (a.k.a. [JSON DB](https://terrainformatica.com/2006/10/what-the-hell-is-that-json-db/)) based on excellent DB products of [Konstantin Knizhnik](http://garret.ru/databases.html).
* [Graphics](https://sciter.com/docs/content/sciter/Graphics.htm) module that uses native graphics primitives provided by supported platforms: Direct2D on Windows 7 and above, GDI+ on Windows XP, CoreGraphics on MacOS, Cairo on Linux/GTK. Yet there is an option to use built-in [Skia/OpenGL](https://skia.org/) backend on each platform.
* Network communication module, it relies on platform HTTP client primitives and/or [Libcurl](https://curl.haxx.se/).
Internally it contains the following modules:
* **CSS** CSS parser and the collection of parsed CSS rules, etc.
* **HTML DOM** HTML parser and DOM tree implementation.
* **layout managers** collection of various layout managers text layout, default block layout, flex layouts. Support of positioned floating elements is also here. This module does the layout calculations heavy lifting. This module is also responsible for the rendering of layouts.
* **input behaviors** a collection of built-in behaviors code behind "active" DOM elements: `<input>`, `<select>`, `<textarea>`, etc.
* **script module** source-to-bytecode compiler and virtual machine (VM) with compacting garbage collector (GC). This module also contains runtime implementation of standard classes and objects: Array, Object, Function and others.
* **script DOM** runtime classes that expose DOM and DOM view (a.k.a. window) to the script.
* **graphics abstraction layer** abstract graphics implementation that isolates the modules mentioned above from the particular platform details:
* Direct2D/DirectWrite graphics backend (Windows);
* GDI+ graphics backend (Windows);
* CoreGraphics backend (Mac OS X);
* Cairo backend (GTK on all Linux platforms);
* Skia/OpenGL backend (all platforms)
* **core primitives** set of common primitives: string, arrays, hash maps and so on.
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 a builtin DOM inspector, script debugger and documentation viewer:
![Sciter tools](https://sciter.com/wp-content/uploads/2015/10/dom-tree-in-inspector-640x438.png)
Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/) for engine principles, architecture and more.
## Getting started:
1. Download the [Sciter SDK](https://sciter.com/download/) and extract it somewhere.
2. Add the corresponding target platform binaries to PATH (`bin.win`, `bin.osx` or `bin.lnx`).
3. If you do not already have it installed, you need GTK 3 development tools installed to continue:
sudo apt-get install libgtk-3-dev
4. Build the crate and run a minimal sciter sample: `cargo run --example minimal`.
5. For your apps add the following dependency to the Cargo.toml: `sciter-rs = "*"`.
## Brief look:
Here is a minimal sciter app:
```rust
extern crate sciter;
fn main() {
let mut frame = sciter::Window::new();
frame.load_file("minimal.htm");
frame.run_app();
}
```
It looks similar to this:
![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png)
### Interoperability
In respect of [tiscript](https://www.codeproject.com/Articles/33662/TIScript-language-a-gentle-extension-of-JavaScript) functions calling:
```rust
use sciter::{Element, Value};
let root = Element::from_window(hwnd);
let result: Value = root.call_function("namespace.name", &make_args!(1,"2",3));
```
Calling Rust from script can be implemented as following:
```rust
struct Handler;
impl Handler {
fn calc_sum(&self, a: i32, b: i32) -> i32 {
a + b
}
}
impl sciter::EventHandler for Handler {
dispatch_script_call! {
fn calc_sum(i32, i32);
}
}
```
And we can access this function from script:
```js
// `view` represents window where script is runnung.
// `stdout` stream is a standard output stream (shell or debugger console, for example)
stdout.printf("2 + 3 = %d\n", view.calc_sum(2, 3));
```
_Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples) folder for more complex usage_.
## [Library documentation](https://docs.rs/sciter-rs/).
## What is supported right now:
* [x] [sciter::window](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-window.hpp) which brings together window creation, host and event handlers.
* [x] [sciter::host](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-host-callback.h) with basic event handling, needs to be redesigned.
* [x] [sciter::event_handler](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-behavior.h) with event handling and auto dispatching script calls to native code.
* [x] [sciter::dom](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-dom.hpp) for HTML DOM access and manipulation methods.
* [x] [sciter::value](https://github.com/c-smile/sciter-sdk/blob/master/include/value.hpp) Rust wrapper.
* [x] [sciter::behavior_factory](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-behavior.h) - global factory for native behaviors.
* [x] [sciter::graphics](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-graphics.hpp) - platform independent graphics native interface (can be used in native behaviors).
* [x] [sciter::request](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-request.hpp) - resource request object, used for custom resource downloading and handling.
* [x] [sciter::video](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-video-api.h) - custom video rendering.
* [x] [sciter::archive](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-host-callback.h) - Sciter's compressed archive produced by `sdk/bin/packfolder` tool.
* [x] [sciter::msg](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-x-msg.h) - backend-independent input event processing.
* [x] [sciter::om](https://github.com/c-smile/sciter-sdk/blob/master/include/sciter-om.h) - Sciter Object Model, extending Sciter by native code.
* [x] [NSE](https://sciter.com/include-library-name-native-extensions/) - native Sciter extensions.
### Platforms:
* [x] Windows
* [x] OSX
* [x] Linux
* [x] Raspberry Pi
## License
Bindings library licensed under [MIT license](https://opensource.org/licenses/MIT). Sciter Engine has the [own license terms](https://sciter.com/prices/) and [end used license agreement](https://github.com/c-smile/sciter-sdk/blob/master/license.htm) for SDK usage.

View File

@ -1,17 +0,0 @@
//! Sciter sample with archived resources.
extern crate sciter;
fn main() {
let resources = include_bytes!("archived.rc");
let mut frame = sciter::WindowBuilder::main_window()
.fixed()
.with_size((600, 400))
.create();
frame.archive_handler(resources).expect("Invalid archive");
frame.load_file("this://app/index.htm");
frame.run_app();
}

View File

@ -1,162 +0,0 @@
<html>
<head>
<title>Clock</title>
<style>
body { padding: 5dip; }
#clocks {
size: *;
flow: horizontal-flow;
}
.city {
flow: vertical;
size: *;
}
.city > caption {
width: *;
padding: 5dip;
flow:horizontal;
horizontal-align: center;
font-size: 11pt;
font-weight: 700;
}
.city > clock, .edit {
margin-right: *;
margin-left: *;
margin-bottom: 5dip;
}
.city > .edit {
flow: horizontal;
width: max-content;
}
clock {
behavior: native-clock;
display: block;
min-width: 150dip;
min-height: 150dip;
}
.native-text {
behavior: native-text;
display: block;
min-height: 100dip;
min-width: 100dip;
outline: 1px solid orange;
}
.italic {
font-style: italic;
}
.bold {
font-weight: bold;
}
</style>
<script type="text/tiscript">
// called from Rust
function getLocalTime() {
var d = new Date();
return [d.hour, d.minute, d.second];
}
function getUtcTime(offset) {
var d = new Date();
d.UTChour += offset;
return [d.UTChour, d.UTCminute, d.UTCsecond];
}
var timeSet = $(#set-time);
var timeEdit = $(#edit-time);
var timeShow = $(#show-time);
timeEdit << event change {
var now = this.value;
var local = [now.hour, now.minute, now.second];
stdout.printf("timeEdit: %v %v\n", now, local);
timeShow.value = local;
}
timeSet << event click {
var now = new Date();
var local = [now.hour, now.minute, now.second];
stdout.printf("timeSet: %v %v\n", now, local);
timeEdit.value = now;
timeShow.value = local;
}
function self.ready() {
var now = new Date();
var local = [now.hour, now.minute, now.second];
stdout.printf("initial time: %v %v\n", now, local);
timeShow.value = local;
}
// update window icon
function setIcon() {
var clock = $(clock);
// get clock element size
var (w, h) = clock.box(#dimension, #border);
if (w == 0 || h == 0)
return;
// make a snapshot of it with 32x32 size
var img = new Image(clock, w, h, 32, 32);
var png = img.toBytes();
img.destroy();
// make an icon from the snapshot
var icon = Image.fromBytes(png);
view.windowIcon = icon;
return true; // continue to update icon ;)
}
self.timer(1000, setIcon);
</script>
</head>
<body>
<div id="clocks" some>
<div class="city">
<caption>London</caption>
<clock utc="0" title="UTC+0"></clock>
</div>
<div class="city">
<caption>Tokyo</caption>
<clock utc="+9" title="UTC+9"></clock>
</div>
<div class="city">
<caption>New York</caption>
<clock utc="-4" title="UTC-4"></clock>
</div>
</div>
<div id="local" some>
<div class="city">
<caption>Frozen time</caption>
<clock frozen id="show-time"></clock>
<div class="edit">
<widget type="time" value="now" id="edit-time" title="Change time of the drawn clock" />
<widget type="button" id="set-time" title="Reset back to local time">=</widget>
</div>
</div>
</div>
<div>
<div class="city">
<caption>Text</caption>
<div class="native-text">static text</div>
</div>
</div>
</body>
</html>

View File

@ -1,368 +0,0 @@
//#![windows_subsystem = "windows"]
#[macro_use]
extern crate sciter;
use sciter::dom::event::{MethodParams, DRAW_EVENTS, EVENT_GROUPS};
use sciter::dom::{Element, HELEMENT};
use sciter::graphics::{self, rgb, Graphics, HGFX};
use sciter::types::RECT;
use sciter::Value;
// 24:60:60, will be drawn as analog clock
type Time = [u8; 3usize];
/// Clock native behavior.
///
/// ## Behavior-specific HTML attributes:
///
/// * `utc="integer"` - time zone offset, positive or negative.
/// * `frozen` - time is not updated automtically.
///
/// ## Value
///
/// *read/write* Current time value in `HH::MM::SS` or `[HH, MM, SS]` form.
///
/// ## Events
///
/// N/A - this element does not generate any specific events.
///
#[derive(Default)]
struct Clock {
element: Option<Element>,
now: Time,
gmt: i8,
is_frozen: bool,
}
impl sciter::EventHandler for Clock {
/// Claim what kind of events we want to receive.
fn get_subscription(&mut self) -> Option<EVENT_GROUPS> {
// we need timer and draw events
// also behavior method calls
Some(EVENT_GROUPS::HANDLE_TIMER
| EVENT_GROUPS::HANDLE_DRAW
| EVENT_GROUPS::HANDLE_METHOD_CALL
)
}
/// Our element is constructed. But scripts in HTML are not loaded yet.
fn attached(&mut self, root: HELEMENT) {
self.element = Some(Element::from(root));
let me = self.element.as_ref().unwrap();
// get attributes to initialize our clock
if let Some(attr) = me.get_attribute("utc") {
if let Ok(v) = attr.parse::<i8>() {
self.gmt = v;
}
}
// we don't update frozen clocks
if let Some(_attr) = me.get_attribute("frozen") {
self.is_frozen = true;
}
// timer to redraw our clock
if !self.is_frozen {
me.start_timer(300, 1).expect("Can't set timer");
}
}
/// Our behavior methods.
fn on_method_call(&mut self, _root: HELEMENT, params: MethodParams) -> bool {
match params {
MethodParams::GetValue(retval) => {
// engine wants out current value (e.g. `current = element.value`)
let v: Value = self.now.iter().map(|v| i32::from(*v)).collect();
println!("return current time as {:?}", v);
*retval = v;
}
MethodParams::SetValue(v) => {
// engine sets our value (e.g. `element.value = new`)
println!("set current time from {:?}", v);
// "10:20:30"
if v.is_string() {
let s = v.as_string().unwrap();
let t = s.split(':').take(3).map(|n| n.parse::<u8>());
let mut new_time = Time::default();
for (i, n) in t.enumerate() {
if let Err(_) = n {
eprintln!("clock::set_value({:?}) is invalid", v);
return true; // consume this event anyway
}
new_time[i] = n.unwrap();
}
// use it as a new time
self.set_time(new_time);
// [10, 20, 30]
} else if v.is_varray() {
let mut new_time = Time::default();
for (i, n) in v.values().take(3).map(|n| n.to_int()).enumerate() {
if n.is_none() {
eprintln!("clock::set_value({:?}) is invalid", v);
return true;
}
new_time[i] = n.unwrap() as u8
}
// use it as a new time
self.set_time(new_time);
} else {
// unknown format
eprintln!("clock::set_value({:?}) is unsupported", v);
return true;
}
}
_ => {
// unsupported event, skip it
return false;
}
}
// mark this event as handled (consume it)
return true;
}
/// Redraw our element on each tick.
fn on_timer(&mut self, root: HELEMENT, _timer_id: u64) -> bool {
if self.update_time() {
// redraw our clock
Element::from(root).refresh().expect("Can't refresh element");
}
true
}
/// Request to draw our element.
fn on_draw(&mut self, _root: HELEMENT, gfx: HGFX, area: &RECT, layer: DRAW_EVENTS) -> bool {
if layer == DRAW_EVENTS::DRAW_CONTENT {
// draw content only
// leave the back- and foreground to be default
let mut gfx = Graphics::from(gfx);
self
.draw_clock(&mut gfx, &area)
.map_err(|e| println!("error in draw_clock: {:?}", e) )
.ok();
}
// allow default drawing anyway
return false;
}
}
// 360°
const PI2: f32 = 2.0 * std::f32::consts::PI;
impl Clock {
/// Update current time and say if changed.
fn update_time(&mut self) -> bool {
if self.is_frozen {
return false;
}
// ask our script for the current time
if let Some(now) = self.get_time() {
let update = self.now != now;
self.now = now;
update
} else {
false
}
}
/// Set the new time and redraw our element.
fn set_time(&mut self, new_time: Time) {
// set new time and redraw our clock
self.now = new_time;
if let Some(el) = self.element.as_ref() {
el.refresh().ok();
}
}
/// Get current time from script.
fn get_time(&self) -> Option<Time> {
let el = self.element.as_ref().unwrap();
let script_func = if self.is_frozen { "getLocalTime" } else { "getUtcTime" };
if let Ok(time) = el.call_function(script_func, &make_args!(self.gmt as i32)) {
assert_eq!(time.len(), 3);
let mut now = Time::default();
for (i, n) in time.values().take(3).map(|n| n.to_int()).enumerate() {
now[i] = n.unwrap() as u8;
}
Some(now)
} else {
eprintln!("error: can't eval get time script");
None
}
}
/// Draw our element.
fn draw_clock(&mut self, gfx: &mut Graphics, area: &RECT) -> graphics::Result<()> {
// save previous state
let mut gfx = gfx.save_state()?;
// setup our attributes
let left = area.left as f32;
let top = area.top as f32;
let width = area.width() as f32;
let height = area.height() as f32;
let scale = if width < height { width / 300.0 } else { height / 300.0 };
// translate to its center and rotate 45° left.
gfx
.translate((left + width / 2.0, top + height / 2.0))?
.scale((scale, scale))?
.rotate(-PI2 / 4.)?;
gfx.line_color(0)?.line_cap(graphics::LINE_CAP::ROUND)?;
// draw clock background
self.draw_outline(&mut *gfx)?;
// draw clock sticks
self.draw_time(&mut *gfx)?;
Ok(())
}
/// Draw clock static area (hour/minute marks).
fn draw_outline(&mut self, gfx: &mut Graphics) -> graphics::Result<()> {
// hour marks (every 5 ticks)
{
let mut gfx = gfx.save_state()?;
gfx.line_width(8.0)?.line_color(rgb(0x32, 0x5F, 0xA2))?;
for _ in 0..12 {
gfx.rotate(PI2 / 12.)?.line((137., 0.), (144., 0.))?;
}
}
// minute marks (every but 5th tick)
{
let mut gfx = gfx.save_state()?;
gfx.line_width(3.0)?.line_color(rgb(0xA5, 0x2A, 0x2A))?;
for i in 0..60 {
if i % 5 != 0 {
// skip hours
gfx.line((143., 0.), (146., 0.))?;
}
gfx.rotate(PI2 / 60.)?;
}
}
Ok(())
}
/// Draw clock arrows.
fn draw_time(&mut self, gfx: &mut Graphics) -> graphics::Result<()> {
let time = &self.now;
let hours = f32::from(time[0]);
let minutes = f32::from(time[1]);
let seconds = f32::from(time[2]);
{
// hours
let mut gfx = gfx.save_state()?;
// 2PI*/12, 2PI/720,
gfx.rotate(hours * (PI2 / 12 as f32) + minutes * (PI2 / (12 * 60) as f32) + seconds * (PI2 / (12 * 60 * 60) as f32))?;
gfx
.line_width(14.0)?
.line_color(rgb(0x32, 0x5F, 0xA2))?
.line((-20., 0.), (70., 0.))?;
}
{
// minutes
let mut gfx = gfx.save_state()?;
gfx.rotate(minutes * (PI2 / 60 as f32) + seconds * (PI2 / (60 * 60) as f32))?;
gfx
.line_width(10.0)?
.line_color(rgb(0x32, 0x5F, 0xA2))?
.line((-28., 0.), (100., 0.))?;
}
{
// seconds
let mut gfx = gfx.save_state()?;
gfx.rotate(seconds * (PI2 / 60 as f32))?;
gfx
.line_width(6.0)?
.line_color(rgb(0xD4, 0, 0))?
.fill_color(rgb(0xD4, 0, 0))?
.line((-30., 0.), (83., 0.))?
.circle((0., 0.), 10.)?;
}
Ok(())
}
}
////////////////////////////////////
#[derive(Default)]
struct Text;
impl sciter::EventHandler for Text {
fn get_subscription(&mut self) -> Option<EVENT_GROUPS> {
Some(EVENT_GROUPS::HANDLE_DRAW)
}
fn attached(&mut self, _root: HELEMENT) {
}
fn on_draw(&mut self, _root: HELEMENT, gfx: HGFX, area: &RECT, layer: DRAW_EVENTS) -> bool {
if layer == DRAW_EVENTS::DRAW_CONTENT {
// draw content only
// leave the back- and foreground to be default
let mut gfx = Graphics::from(gfx);
let e = Element::from(_root);
self
.draw_text(&e, &mut gfx, &area)
.map_err(|e| println!("error in draw_clock: {:?}", e) )
.ok();
return true;
}
// allow default drawing anyway
return false;
}
}
impl Text {
fn draw_text(&mut self, e: &Element, gfx: &mut Graphics, area: &RECT) -> graphics::Result<()> {
// save previous state
let mut gfx = gfx.save_state()?;
// setup our attributes
// let left = area.left as f32;
// let top = area.top as f32;
// let width = area.width() as f32;
// let height = area.height() as f32;
// println!("text::draw on {} at {} {} {} {}", e, left, top, width, height);
use sciter::graphics::Text;
let t = Text::with_style(&e, "native text", "font-style: italic")?;
gfx.draw_text(&t, (area.left as f32, area.top as f32), 7)?;
Ok(())
}
}
fn main() {
let mut frame = sciter::WindowBuilder::main_window().with_size((800, 600)).create();
frame.register_behavior("native-clock", || Box::new(Clock::default()));
frame.register_behavior("native-text", || Box::new(Text::default()));
frame.load_html(include_bytes!("clock.htm"), Some("example://clock.htm"));
frame.run_app();
}

View File

@ -1,272 +0,0 @@
#![allow(unused_variables)]
#![allow(unused_must_use)]
extern crate sciter;
use sciter::{Value, Element, HELEMENT};
use sciter::dom::event::*;
#[derive(Default)]
struct DocumentHandler;
impl sciter::EventHandler for DocumentHandler {
fn attached(&mut self, _root: sciter::HELEMENT) {
println!("attached");
}
fn detached(&mut self, root: sciter::HELEMENT) {
let root = Element::from(root);
println!("detaching from {}", root);
}
fn document_complete(&mut self, root: sciter::HELEMENT, source: sciter::HELEMENT) {
println!("document is loaded.");
let root = Element::from(root);
assert_eq!(root.get_tag(), "html");
println!("root {:?}", root);
let head = root.first_child().expect("empty <html>?");
assert_eq!(head.get_tag(), "head");
assert_eq!(head.index(), 0);
println!("head {:?}", head);
let body = head.next_sibling().expect("only <head>?");
assert_eq!(body.get_tag(), "body");
assert_eq!(body.index(), 1);
println!("body {:?}", body);
assert_eq!(body.first_sibling().expect("must be head"), head);
assert_eq!(body.last_sibling().expect("must be body"), body);
println!("for loop in children");
for e in root.children() {
println!("child {:?}", e);
}
println!("for loop in ref");
for e in &root {
println!("child {:?}", e);
}
if let Ok(Some(h1)) = body.find_first("body > h1") {
println!("h1 {:?}", h1);
let h1_parent = h1.parent().expect("come on!");
assert_eq!(h1_parent, body);
let text = h1.get_text();
assert_eq!(text, "Herman Melville - Moby-Dick");
let html = h1.get_html(true);
assert_eq!(html.as_slice(), br"<h1>Herman Melville - Moby-Dick</h1>".as_ref());
let value = h1.get_value();
assert!(value.is_string());
assert_eq!(value.as_string().unwrap(), text);
}
if let Some(mut h1) = body.first_child() {
println!("changing h1 attributes");
h1.set_style_attribute("color", "green");
h1.set_style_attribute("outline", "1px solid orange");
h1.set_attribute("title", "yellow!");
}
{
let all: Vec<Element> = body.find_all("div > p").unwrap().expect("must be at least one 'div > p'");
assert!(!all.is_empty());
assert_eq!(all.len(), 1);
all.len();
}
if let Ok(Some(mut body)) = root.find_first("html > body") {
let mut div = Element::with_parent("div", &mut body).unwrap();
div.set_attribute("id", "requests");
div.set_style_attribute("outline", "1px solid orange");
div.set_style_attribute("margin", "10dip 0");
div.set_style_attribute("padding", "4dip");
let e = Element::with_text("label", "Requests:").unwrap();
div.append(&e).unwrap();
let d = Element::with_text("div", "data").unwrap();
div.append(&d).unwrap();
let c = Element::with_text("div", "footer").unwrap();
div.append(&c).unwrap();
d.request_html("https://sciter.com/test/text.txt", None).unwrap();
// d.send_get_request("https://sciter.com/test/text.txt", None).expect("can't send an http request");
// d.send_get_request("http://httpbin.org/html", None).expect("can't send an http request");
// d.send_get_request("http://httpbin.org/get?one=1&two=2", None).expect("can't send an http request");
// let params = [("one", "1"), ("two", "2")];
// let method = sciter::request::REQUEST_TYPE::AsyncGet;
// let data_type = sciter::request::RESOURCE_TYPE::HTML;
// d.send_request("http://httpbin.org/html", Some(&params), Some(method), Some(data_type)).expect("can't send an http request");
}
if let Ok(Some(mut body)) = root.find_first("html > body") {
println!("creating some elments");
// DOM manipulation.
// After creating the new Element, we can set only attributes for it until we'll attach it to the DOM.
//
let mut div = Element::with_parent("div", &mut body).unwrap();
div.set_style_attribute("outline", "1px solid orange");
div.set_style_attribute("width", "max-content");
div.set_style_attribute("padding", "5dip");
let mut lb = Element::with_text("label", "Output: ").unwrap();
div.append(&lb).expect("wtf?"); // push as reference, we can access this `lb` still.
let mut date = Element::with_type("input", "date").unwrap();
date.set_attribute("id", "mydate");
date.set_attribute("value", "now");
lb.append(&date).expect("wtf?");
date.set_style_attribute("width", "100px");
date.set_style_attribute("outline", "1px dotted gray");
date.set_style_attribute("margin", "10px");
lb.set_attribute("accesskey", "o");
lb.set_style_attribute("color", "lightblue");
lb.set_style_attribute("vertical-align", "middle");
let mut progress = Element::create("progress").unwrap();
progress.set_attribute("max", "100");
progress.set_attribute("id", "id1");
progress.set_attribute("title", "Click to start timer.");
div.append(&progress).expect("wtf?");
// after attaching Element to DOM, we can set its styles, text, html or value.
progress.set_value(Value::from(42));
progress.set_style_attribute("behavior", "progress clickable");
// attach a new handler to this element;
// since timers are not sinking/bubbling, we need to attach
// a dedicated handler to that element directly.
let handler = ProgressHandler::default();
progress.attach_handler(handler).expect("can't attach?");
let mut e = Element::with_text("span", " <-- check tooltip").unwrap();
div.append(&e);
e.set_style_attribute("font-style", "italic");
}
}
}
#[derive(Default)]
struct ProgressHandler {
progress: Option<Element>,
start_timer: bool,
}
impl sciter::EventHandler for ProgressHandler {
fn get_subscription(&mut self) -> Option<EVENT_GROUPS> {
Some(default_events() | EVENT_GROUPS::HANDLE_TIMER)
}
fn attached(&mut self, root: sciter::HELEMENT) {
let root = Element::from(root);
println!("attached an element event handler to {}", root);
if root.test("progress") {
self.progress = Some(root.clone());
self.start_timer = false;
}
}
fn detached(&mut self, root: sciter::HELEMENT) {
let root = Element::from(root);
println!("detaching from {}", root);
}
fn on_event(&mut self, root: HELEMENT, source: HELEMENT, target: HELEMENT, code: BEHAVIOR_EVENTS, phase: PHASE_MASK, reason: EventReason) -> bool {
if phase != PHASE_MASK::BUBBLING {
return false;
}
match code {
BEHAVIOR_EVENTS::BUTTON_CLICK => {
let source = Element::from(source);
let mut target = Element::from(target);
println!("button click on target {}", target);
if self.progress.is_some() && *self.progress.as_ref().unwrap() == target {
self.start_timer = !self.start_timer;
if self.start_timer {
println!("starting timer");
target.set_value(Value::from(0));
target.start_timer(1000, 1).ok();
} else {
println!("stopping timer");
target.stop_timer(1);
let cur = target.get_value();
target.set_attribute("title", &format!("Current value is {}. Click to start the timer again.", cur));
}
}
true
}
_ => false
}
}
fn on_timer(&mut self, root: HELEMENT, timer_id: u64) -> bool {
println!("timer {} tick on {}", timer_id, Element::from(root));
if timer_id == 1 && self.progress.is_some() {
let e = self.progress.as_mut().unwrap();
let max_attr = e.get_attribute("max").unwrap();
let max: f64 = max_attr.parse().unwrap();
let v = e.get_value();
let next = v.to_float().unwrap() + 5.0;
if next > max {
println!("that's enough, finish.");
self.start_timer = false;
e.stop_timer(1);
}
e.set_value(Value::from(next));
e.set_attribute("title", &format!("Current value is {}. Click to stop the timer if need.", next));
return true;
}
false
}
}
fn main() {
let mut frame = sciter::WindowBuilder::main_window()
.with_size((750, 950))
.debug()
.create();
println!("attaching an event handler for the whole window");
frame.event_handler(DocumentHandler::default());
frame.set_title("DOM sample");
println!("loading the page...");
frame.load_file("http://httpbin.org/html");
println!("running the app");
frame.run_app();
}

View File

@ -1,69 +0,0 @@
//! Download http content (Go sciter example port).
#![allow(dead_code)]
extern crate sciter;
use sciter::dom::HELEMENT;
use sciter::host;
use sciter::utf;
use std::rc::{Rc, Weak};
struct Handler {
host: Weak<sciter::Host>,
}
impl sciter::EventHandler for Handler {
fn document_complete(&mut self, _root: HELEMENT, _target: HELEMENT) {
if let Some(host) = self.host.upgrade() {
// eval script inside the document to receive a "user@machine" string.
let result = host.eval_script("[Sciter.userName(), Sciter.machineName(true)].join(`@`)");
match result {
Ok(name) => {
println!("running on {}", name);
}
Err(e) => {
println!("error! {}", e.as_string().unwrap_or("?".to_string()));
}
}
}
}
}
impl sciter::HostHandler for Handler {
fn on_data_loaded(&mut self, pnm: &host::SCN_DATA_LOADED) {
println!("data loaded, uri: `{}`, {} bytes.", utf::w2s(pnm.uri), pnm.dataSize);
}
fn on_attach_behavior(&mut self, pnm: &mut host::SCN_ATTACH_BEHAVIOR) -> bool {
let el = sciter::Element::from(pnm.element);
let name = utf::u2s(pnm.name);
println!("{}: behavior {}", el, name);
false
}
}
impl Drop for Handler {
fn drop(&mut self) {
// called 2 times because it is created 2 times
println!("Good bye, window");
}
}
fn main() {
let mut frame = sciter::WindowBuilder::main_window().with_size((1024, 768)).create();
// Can't use something like `frame.sciter_handler(Rc::new(handler))` yet.
let handler = Handler {
host: Rc::downgrade(&frame.get_host()),
};
frame.sciter_handler(handler);
let handler = Handler {
host: Rc::downgrade(&frame.get_host()),
};
frame.event_handler(handler);
frame.set_title("Download sample");
frame.load_file("http://httpbin.org/html");
frame.run_app();
}

View File

@ -1,18 +0,0 @@
<html>
<head>
<title>extension test</title>
<style type="text/css">
</style>
<script type="text/tiscript">
// copy "extension.dll" next to the "sciter.dll"
const ext = include library "extension";
debug: ext;
debug: ext.add(1,2);
debug: ext.sub(1,2);
</script>
</head>
<body>
<h4>see logs in Inspector</h4>
</body>
</html>

View File

@ -1,17 +0,0 @@
[package]
name = "extension"
version = "0.1.0"
description = "A simple Sciter extension library"
authors = ["pravic <ehysta@gmail.com>"]
homepage = "https://sciter.com/include-library-name-native-extensions/"
edition = "2018"
publish = false
[lib]
path = "src/extension.rs"
crate-type = ["cdylib"]
test = false
bench = false
[dependencies]
sciter-rs = { version = "0.5", path="../../", features = ["extension"] }

View File

@ -1,50 +0,0 @@
//! Sciter extension library example.
//!
//! See the [blog post](https://sciter.com/include-library-name-native-extensions/).
#[macro_use]
extern crate sciter;
use sciter::types::{BOOL, VALUE};
use sciter::Value;
/// Extension entry point.
#[no_mangle]
pub extern "system" fn SciterLibraryInit(api: &'static sciter::ISciterAPI, exported: &mut VALUE) -> BOOL {
sciter::set_host_api(api);
let ext_api = vmap! {
"add" => add,
"sub" => sub,
};
ext_api.pack_to(exported);
true as BOOL
}
/// Calculate the sum of all the given arguments.
pub fn add(args: &[Value]) -> Value {
let sum: i32 = args
.iter()
.map(|v| v.to_int())
.filter(|v| v.is_some())
.map(|v| v.unwrap())
.sum();
sum.into()
}
/// `function sub(a, b) { return a - b; }`
pub fn sub(args: &[Value]) -> std::result::Result<Value, String> {
if let [a, b] = args {
let a = a.to_int().ok_or("`a` is not an int")?;
let b = b.to_int().ok_or("`b` is not an int")?;
let result = a - b;
Ok(result.into())
} else {
Err(format!("sub(a,b) expects 2 parameters, given {} instead.", args.len()))
}
}

View File

@ -1,50 +0,0 @@
<html>
<head>
<title>Fire event demo</title>
<style>
html {
background: radial-gradient(75% 75%, circle farthest-side, white, orange, rgb(0, 0, 204));
color: #fff;
}
#message {
margin: 10dip 0dip;
padding: 5dip;
width: 60%%;
min-height: 60dip;
color: black;
background: #ccc;
outline: 1px solid orange;
}
</style>
<script type="text/tiscript">
view.caption = $(head > title).value;
$(#machine).text = Sciter.machineName();
$(#post).on("click", : {
$(#message).postEvent(Event.CHANGE, 0, this, "hello?");
});
$(#message).on("change", function(e) {
this.text = String.printf("Event from `%s`: %v\n", e.source.id, e.data);
});
</script>
</head>
<body>
<h1>Fire event</h1>
<p>Running on <em #machine/> machine</p>
<button id="post">Post event</button>
<button id="send">Send event</button>
<button id="fire">Fire event</button>
<div id="message"></div>
</body>
</html>

View File

@ -1,60 +0,0 @@
//! Fire event Sciter sample.
#![allow(unused_variables)]
#![allow(non_snake_case)]
extern crate sciter;
use sciter::Element;
use self::sciter::dom::event::*;
use self::sciter::dom::HELEMENT;
use self::sciter::value::Value;
struct FireEvent;
impl sciter::EventHandler for FireEvent {
fn on_event(&mut self, root: HELEMENT, source: HELEMENT, target: HELEMENT, code: BEHAVIOR_EVENTS, phase: PHASE_MASK, reason: EventReason) -> bool {
if phase != PHASE_MASK::BUBBLING {
return false;
}
if code == BEHAVIOR_EVENTS::BUTTON_CLICK {
// `root` points to attached element, usually it is an `<html>`.
let root = Element::from(root).root();
let message = root.find_first("#message").unwrap().expect("div#message not found");
let source = Element::from(source);
println!("our root is {:?}, message is {:?} and source is {:?}", root, message, source);
if let Some(id) = source.get_attribute("id") {
if id == "send" {
// just send a simple event
source.send_event(BEHAVIOR_EVENTS::CHANGE, None, Some(message.as_ptr())).expect("Failed to send event");
return true;
} else if id == "fire" {
// fire event with specified params
let data = Value::from("Rusty param");
source.fire_event(BEHAVIOR_EVENTS::CHANGE, None, Some(message.as_ptr()), false, Some(data)).expect("Failed to fire event");
return true;
}
};
};
false
}
}
fn main() {
let html = include_bytes!("fire_event.htm");
let mut frame = sciter::Window::new();
frame.event_handler(FireEvent);
frame.load_html(html, Some("example://fire_event.htm"));
frame.run_app();
}

View File

@ -1,35 +0,0 @@
//! An example showing various information about Sciter.
extern crate sciter;
fn main() {
// can be called as `examples/first ~/lib/libsciter.so`
if cfg!(feature = "dynamic") {
if let Some(arg) = std::env::args().nth(1) {
println!("using {:?}", arg);
if let Err(e) = sciter::set_library(&arg) {
panic!("Invalid library path specified: {}", e);
}
}
}
let arch = if cfg!(target_arch = "x86_64") { "x64" } else { "x86" };
println!("calling SciterAPI {}", arch);
// bypass the ABI compatability checks (e.g. in windowless builds)
let scapi = sciter::SciterAPI_unchecked();
let abi_version = scapi.version;
println!("sciter abi version: {:#0x}, windowless: {}", abi_version, abi_version >= 0x0001_0001);
let class_name = sciter::utf::w2s((scapi.SciterClassName)());
println!("sciter class name: {:?}", class_name);
// Sciter library version
use sciter::types::BOOL;
let v1 = (scapi.SciterVersion)(true as BOOL);
let v2 = (scapi.SciterVersion)(false as BOOL);
let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF];
let version = num.iter().map(|&x| x.to_string()).collect::<Vec<_>>().join(".");
println!("sciter version: {} {:?}", version, num);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

View File

@ -1,90 +0,0 @@
<html window-icon="https://sciter.com/wp-content/themes/sciter/!images/favicon.ico">
<head>
<title>Rust-sciter sample</title>
<style>
html {
background: radial-gradient(75% 75%, circle farthest-side, white, orange, rgb(0,0,204));
color:#fff;
}
html:rtl {
mapping: left-to-right(background);
}
</style>
<script type="text/tiscript">
view.caption = $(head > title).value;
$(#machine).text = Sciter.machineName();
$(#backend).text = view.backendName;
$(#version).text = String.printf("%d.%d.%d.%d",
(Sciter.VERSION >> 16) & 0xffff, Sciter.VERSION & 0xffff,
(Sciter.REVISION >> 16) & 0xffff, Sciter.REVISION & 0xffff);
var counter = 0;
$(button#append).on("click", function() {
$(body).$append(<h1#test>{ ++counter }</h1>);
});
$(button#open).on("click", function() {
var fn = view.selectFile(#open,
"HTML Files (*.htm,*.html)|*.HTM;*.HTML|All Files (*.*)|*.*" , "html" );
stdout.println("selected file: " + fn);
if (fn) {
$(body).$append(<h1#test>{fn}</h1>);
}
});
$(button#ti2py).on("click", function() {
var answer = view.NativeCall(view.caption);
$(body).$append(<h1#test>script -&gt; native: {answer}</h1>);
})
$(button#py2ti).on("click", function() {
var answer = view.ScriptCallTest("call arg");
})
$(button#sum).on("click", function() {
stdout.printf("2 + 3 = %d\n", view.calc_sum(2, 3));
})
function hello(who) {
$(body).$append(<h1#test>native -&gt; script: {who}</h1>);
return "its working!";
}
function raise_error(arg1, arg2, arg3) {
throw new Error(String.$(Unexpected type of input: {typeof arg1}, {typeof arg2}, {typeof arg3}.));
}
self.timer(2000, function() {
if(!view.api)
view.api = view.GetNativeApi();
// {add: function(a,b) { return a + b; }};
stdout.printf("2 + 3 = %d\n", view.api.add(2, 3));
stdout.printf("2 * 3 = %d\n", view.api.mul(2, 3));
stdout.printf("2 - 3 = %d\n", view.api.sub(2, 3));
});
</script>
</head>
<body>
<h1>Rust Sciter Application</h1>
<p>Running on <strong #machine /> machine via <strong #backend/> (<strong #version/>).</p>
<button #append>Append</button>
<button #open>Open</button>
<button #ti2py>Call native</button>
<button #py2ti>Call script</button>
<button #sum>Calc sum</button>
</body>
</html>

View File

@ -1,180 +0,0 @@
//! Sciter interop with native code and vice versa.
#![allow(unused_variables)]
#![allow(non_snake_case)]
#[macro_use]
extern crate sciter;
use sciter::{HELEMENT, Element, Value};
struct EventHandler {
root: Option<Element>,
}
impl Drop for EventHandler {
fn drop(&mut self) {
println!("interop::EventHandler: Bye bye, HTML!");
}
}
impl EventHandler {
fn script_call_test(&self, args: &[Value], root: &Element) -> Option<Value> {
println!("root: {:?}", root);
// return None;
println!("calling 'hello'");
let answer = root.call_function("hello", &make_args!("hello, rust!"));
println!(" answer {:?}", answer);
println!("get and call 'hello'");
let answer = root.eval_script(r"hello");
if answer.is_err() {
return None;
}
let obj = answer.unwrap();
let answer = obj.call(None, &make_args!("argument"), None);
println!(" answer is {:?}", answer);
println!("eval 'hello'");
let answer = root.eval_script(r#"hello("42");"#);
println!(" answer is {:?}", answer);
println!("calling 'raise_error'; the following exceptions are expected then:");
let answer = root.call_function("raise_error", &make_args!(17, "42", false));
println!(" answer is {:?}", answer);
println!("calling inexisting function");
let answer = root.call_function("raise_error2", &[]);
println!(" answer is {:?}", answer);
Some(Value::from(true))
}
fn NativeCall(&mut self, arg: String) -> Value {
Value::from(format!("Rust window ({})", arg))
}
fn GetNativeApi(&mut self) -> Value {
fn on_add(args: &[Value]) -> Value {
let ints = args.iter().map(|x| x.to_int().unwrap());
// let sum: i32 = ints.sum(); // error: issue #27739
let sum: i32 = ints.sum();
Value::from(sum)
}
fn on_sub(args: &[Value]) -> Value {
if args.len() != 2 || args.iter().any(|x| !x.is_int()) {
return Value::error("sub requires 2 integer arguments!");
}
let ints: Vec<_> = args.iter().map(|x| x.to_int().unwrap()).collect();
let (a,b) = (ints[0], ints[1]);
Value::from(a - b)
}
let on_mul = |args: &[Value]| -> Value {
let prod: i32 = args.iter().map(|x| x.to_int().unwrap()).product();
Value::from(prod)
};
let mut api = Value::new();
api.set_item("add", on_add);
api.set_item("sub", on_sub);
api.set_item("mul", on_mul);
println!("returning {:?}", api);
api
}
fn calc_sum(&mut self, a: i32, b: i32) -> i32 {
a + b
}
}
impl sciter::EventHandler for EventHandler {
fn attached(&mut self, root: HELEMENT) {
self.root = Some(Element::from(root));
}
dispatch_script_call! {
fn NativeCall(String);
fn GetNativeApi();
fn calc_sum(i32, i32);
}
fn on_script_call(&mut self, root: HELEMENT, name: &str, argv: &[Value]) -> Option<Value> {
let args = argv.iter().map(|x| format!("{:?}", &x)).collect::<Vec<String>>().join(", ");
println!("script->native: {}({}), root {:?}", name, args, Element::from(root));
let handled = self.dispatch_script_call(root, name, argv);
if handled.is_some() {
return handled;
}
if name == "ScriptCallTest" {
return self.script_call_test(argv, &Element::from(root));
}
None
}
}
fn check_options() {
sciter::set_options(sciter::RuntimeOptions::ScriptFeatures(
sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_SYSINFO as u8 // Enables `Sciter.machineName()`
| sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_FILE_IO as u8 // Enables opening file dialog (`view.selectFile()`)
)).ok();
for arg in std::env::args() {
if arg.starts_with("--sciter-gfx=") {
use sciter::GFX_LAYER;
let backend = match arg.split_at("--sciter-gfx=".len()).1.trim() {
"auto" => GFX_LAYER::AUTO,
"cpu" => GFX_LAYER::CPU,
"skia" | "skia-cpu" => GFX_LAYER::SKIA_CPU,
"skia-opengl" => GFX_LAYER::SKIA_OPENGL,
#[cfg(windows)]
"d2d" => GFX_LAYER::D2D,
#[cfg(windows)]
"warp" => GFX_LAYER::WARP,
_ => GFX_LAYER::AUTO,
};
println!("setting {:?} backend", backend);
let ok = sciter::set_options(sciter::RuntimeOptions::GfxLayer(backend));
if let Err(e) = ok {
println!("failed to set backend: {:?}", e);
}
} else if arg.starts_with("--ux-theme") {
#[cfg(windows)]
sciter::set_options(sciter::RuntimeOptions::UxTheming(true)).ok();
}
}
}
fn main() {
// interop --sciter-gfx=cpu --ux-theme
check_options();
let html = include_bytes!("interop.htm");
let handler = EventHandler { root: None };
let mut frame = sciter::Window::new();
frame.event_handler(handler);
frame.load_html(html, Some("example://interop.htm"));
frame.run_app();
}

View File

@ -1,88 +0,0 @@
<html window-icon="https://sciter.com/wp-content/themes/sciter/!images/favicon.ico">
<head>
<title>Minimalistic Sciter demo</title>
<style>
html {
background: radial-gradient(75% 75%, circle farthest-side, white, orange, rgb(0,0,204));
color: #fff;
}
html:rtl {
mapping: left-to-right(background);
}
a { color: white; }
code { font-weight: bold; }
</style>
<script type="text/tiscript">
view.caption = $(head > title).value;
$(#machine).text = Sciter.machineName();
$(#version).text = String.printf("%d.%d.%d.%d",
(Sciter.VERSION >> 16) & 0xffff, Sciter.VERSION & 0xffff,
(Sciter.REVISION >> 16) & 0xffff, Sciter.REVISION & 0xffff);
try {
// since 4.2.5.0
$(#revision).text = Sciter.BUILD.toString();
} catch(e) {
$(#revision).text = "N/A";
}
var counter = 0;
$(button#append).on("click", function() {
$(body).$append(<h1#test>{ ++counter }</h1>);
});
$(button#open).on("click", function() {
var fn = view.selectFile(#open,
"HTML Files (*.htm,*.html)|*.HTM;*.HTML|All Files (*.*)|*.*" , "html" );
// if the dialog was closed or
// filesystem interaction was disabled via `ALLOW_FILE_IO`
// the selected file `fn` would be `undefined`.
stdout.println("selected file: " + fn);
if (fn) {
$(body).$append(<h1#test>{fn}</h1>);
}
});
// Some tricks with hyperlinks:
$(a).on("click", function() {
Sciter.launch(this.attributes["href"]);
return true;
});
for (var a in $$(a)) {
a.attributes["title"] = a.attributes["href"];
}
</script>
</head>
<body>
<h1>Minimal Sciter Application</h1>
<p>Running on <em #machine /> machine</p>
<p>Sciter version <span #version /> rev <span #revision /></p>
<button #append>Append</button>
<button #open>Open</button>
<select>
<option>Some</option>
<option>Items</option>
<option>in select</option>
</select>
<section class=footer>
<p>You can inspect this window in the <a href="https://sciter.com/developers/development-tools/">Inspector tool</a>
from the <a href="https://sciter.com/download/">Sciter SDK</a>.</p>
<p>Run the Inspector first and then press <code>CTRL+SHIFT+I</code> in this window.</p>
</section>
</body>
</html>

View File

@ -1,43 +0,0 @@
//! Minimalistic Sciter sample.
// Specify the Windows subsystem to eliminate console window.
// Requires Rust 1.18.
#![windows_subsystem="windows"]
extern crate sciter;
fn main() {
// Step 1: Include the 'minimal.html' file as a byte array.
// Hint: Take a look into 'minimal.html' which contains some tiscript code.
let html = include_bytes!("minimal.htm");
// Step 2: Enable the features we need in our tiscript code.
sciter::set_options(sciter::RuntimeOptions::ScriptFeatures(
sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_SYSINFO as u8 // Enables `Sciter.machineName()`
| sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_FILE_IO as u8 // Enables opening file dialog (`view.selectFile()`)
)).unwrap();
// Enable debug mode for all windows, so that we can inspect them via Inspector.
sciter::set_options(sciter::RuntimeOptions::DebugMode(true)).unwrap();
// Step 3: Create a new main sciter window of type `sciter::Window`.
// Hint: The sciter Window wrapper (src/window.rs) contains more
// interesting functions to open or attach to another existing window.
let mut frame = sciter::Window::new();
if cfg!(target_os="macos") {
// a temporary workaround for OSX, see
// https://sciter.com/forums/topic/global-sciter_set_debug_mode-does-not-work-in-osx/
frame.set_options(sciter::window::Options::DebugMode(true)).unwrap();
}
// Step 4: Load HTML byte array from memory to `sciter::Window`.
// Hint: second parameter is an optional uri, it can be `None` in simple cases,
// but it is useful for debugging purposes (check the Inspector tool from the Sciter SDK).
// Also you can use a `load_file` method, but it requires an absolute path
// of the main document to resolve HTML resources properly.
frame.load_html(html, Some("example://minimal.htm"));
// Step 5: Show window and run the main app message loop until window been closed.
frame.run_app();
}

View File

@ -1,67 +0,0 @@
<html>
<head>
<title>SOM test</title>
<style type="text/css">
</style>
<script type="text/tiscript">
if(0) {
debug(asset traits);
debug: Asset.typeOf(TestGlobal);
debug: Asset.hasProperty(TestGlobal, #age);
debug: Asset.hasMethod(TestGlobal, #print);
debug(asset globals);
debug: TestGlobal;
debug: view.TestGlobal;
debug: view.root.TestGlobal;
debug(asset properties);
debug: TestGlobal.age;
TestGlobal.age = 17;
debug: TestGlobal.age;
TestGlobal.name = "Demogor";
debug: TestGlobal.name;
debug: TestGlobal.print();
}
/////////////////////////
if(1) {
debug(event handler);
debug(implicit access);
var prop = view.TestGlobal;
debug: prop;
var int_prop = prop.age;
debug: int_prop;
debug(explicit access);
debug: view.TestGlobal;
var val = view.TestGlobal.age;
debug: val;
debug: view.TestGlobal.age;
view.TestGlobal.age = 12;
debug: view.TestGlobal.age;
debug: view.TestGlobal.print();
debug: view.TestGlobal.add_year(12);
debug: view.TestGlobal.age;
}
</script>
</head>
<body>
<div>Hello, body</div>
<p>but open Inspector to see the logs</p>
</body>
</html>

View File

@ -1,193 +0,0 @@
// there are logs in console window
// #![windows_subsystem="windows"]
extern crate sciter;
use sciter::{HELEMENT, types::{BOOL, VALUE}};
#[derive(Default)]
pub struct Object {
age: i32,
name: String,
}
impl Object {
pub fn print(&self) -> String {
format!("name: {}, age: {}", self.name, self.age)
}
pub fn add_year(&mut self, v: i32) -> i32 {
self.age += v;
self.age
}
}
// SOM Passport of the asset.
// TODO: should be auto-generated.
impl sciter::om::Passport for Object {
fn get_passport(&self) -> &'static sciter::om::som_passport_t {
use sciter::om::*;
extern "C" fn on_print(thing: *mut som_asset_t, _argc: u32, _argv: *const VALUE, p_result: &mut VALUE) -> BOOL
{
let me = IAsset::<Object>::from_raw(&thing);
let r = me.print();
let r: sciter::Value = r.into();
r.pack_to(p_result);
return true as BOOL;
}
extern "C" fn on_add_year(thing: *mut som_asset_t, argc: u32, argv: *const VALUE, p_result: &mut VALUE) -> BOOL
{
let me = IAsset::<Object>::from_raw(&thing);
let args = unsafe { sciter::Value::unpack_from(argv, argc) };
let required = 1;
if args.len() != required {
let r = sciter::Value::error(&format!("{} error: {} of {} arguments provided.", "Object::add_year", args.len(), required));
r.pack_to(p_result);
return true as BOOL;
}
let r = me.add_year(
match sciter::FromValue::from_value(&args[0]) {
Some(arg) => arg,
None => {
let r = sciter::Value::error(&format!("{} error: invalid type of {} argument ({} expected, {:?} provided).",
"Object::add_year", 0, "i32", &args[0]
));
r.pack_to(p_result);
return true as BOOL;
}
},
);
let r: sciter::Value = r.into();
r.pack_to(p_result);
return true as BOOL;
}
extern "C" fn on_get_age(thing: *mut som_asset_t, p_value: &mut VALUE) -> BOOL
{
let me = IAsset::<Object>::from_raw(&thing);
let r = sciter::Value::from(&me.age);
r.pack_to(p_value);
return true as BOOL;
}
extern "C" fn on_set_age(thing: *mut som_asset_t, p_value: &VALUE) -> BOOL
{
let me = IAsset::<Object>::from_raw(&thing);
use sciter::FromValue;
let v = sciter::Value::from(p_value);
if let Some(v) = FromValue::from_value(&v) {
me.age = v;
true as BOOL
} else {
false as BOOL
}
}
extern "C" fn on_get_name(thing: *mut som_asset_t, p_value: &mut VALUE) -> BOOL
{
let me = IAsset::<Object>::from_raw(&thing);
let r = sciter::Value::from(&me.name);
r.pack_to(p_value);
return true as BOOL;
}
extern "C" fn on_set_name(thing: *mut som_asset_t, p_value: &VALUE) -> BOOL
{
let me = IAsset::<Object>::from_raw(&thing);
use sciter::FromValue;
let v = sciter::Value::from(p_value);
if let Some(v) = FromValue::from_value(&v) {
me.name = v;
true as BOOL
} else {
false as BOOL
}
}
type ObjectMethods = [som_method_def_t; 2];
let mut methods = Box::new(ObjectMethods::default());
let mut method = &mut methods[0];
method.name = atom("print");
method.func = Some(on_print);
method.params = 0;
let mut method = &mut methods[1];
method.name = atom("add_year");
method.func = Some(on_add_year);
method.params = 1;
type ObjectProps = [som_property_def_t; 2];
let mut props = Box::new(ObjectProps::default());
let mut prop = &mut props[0];
prop.name = atom("age");
prop.getter = Some(on_get_age);
prop.setter = Some(on_set_age);
let mut prop = &mut props[1];
prop.name = atom("name");
prop.getter = Some(on_get_name);
prop.setter = Some(on_set_name);
let mut pst = Box::new(som_passport_t::default());
pst.name = atom("TestGlobal");
pst.n_methods = 2;
pst.methods = Box::into_raw(methods) as *const _;
pst.n_properties = 2;
pst.properties = Box::into_raw(props) as *const _;
Box::leak(pst)
}
}
#[derive(Debug)]
struct Handler {
asset: sciter::om::IAssetRef<Object>,
}
impl sciter::EventHandler for Handler {
fn attached(&mut self, _root: HELEMENT) {
println!("attached");
}
fn detached(&mut self, _root: HELEMENT) {
println!("detached");
}
fn document_complete(&mut self, _root: HELEMENT, _target: HELEMENT) {
println!("loaded");
}
fn get_asset(&mut self) -> Option<&sciter::om::som_asset_t> {
Some(self.asset.as_ref())
}
}
fn main() {
sciter::set_options(sciter::RuntimeOptions::DebugMode(true)).unwrap();
let mut frame = sciter::Window::new();
let object = Object::default();
let object = sciter::om::IAsset::new(object);
sciter::om::into_global(object);
let object2 = Object::default();
let object2 = sciter::om::IAsset::new(object2);
let object2 = sciter::om::IAssetRef::from(object2);
let ptr = object2.as_ptr();
let psp = object2.get_passport();
println!{"asset {:?} psp {:?}", ptr, psp as *const _};
println!("asset: {:?}", object2);
let handler = Handler { asset: object2 };
frame.event_handler(handler);
let html = include_bytes!("som.htm");
frame.load_html(html, Some("example://som.htm"));
frame.run_app();
}

View File

@ -1,82 +0,0 @@
<html window-icon="https://cdn2.iconfinder.com/data/icons/arts-crafts-sewing/24/sewing_thread_handcraft_craft_1-32.png">
<head>
<title>Threads demo</title>
<style>
div#content { flow:horizontal; size:*; }
div#explanation { size:*; padding:20px; overflow:auto; }
div#explanation > pre { padding:10px; border:1px dotted #999; background:#ffffef; }
div#tasks { width:300px; height:*; }
div#tasks > select { size:*; display:block; }
div#tasks > select progress { margin-left: 5px; }
</style>
<script type="text/tiscript">
var taskNo = 0;
$(#start-task).onClick = function()
{
++taskNo;
var taskElem = $(div#tasks > select).$append(<option>Task { taskNo }<progress max=100 /> <span.result /></option>);
function onProgress(p100) { taskElem.$(progress).value = p100; }
function onDone(taskId) {
taskElem.$(span.result).text = "Done!";
taskElem.$(progress).remove();
}
view.exec_task(taskNo, onProgress, onDone);
}
</script>
</head>
<body>
<h2>Sciter UI, threads demo</h2>
<div id="content">
<div id="tasks">
<button id="start-task">Start Task</button>
<select type="select"></select>
</div>
<div id="explanation">
<p>The Start Task onClick handler is defined as</p>
<pre>
$(#start-task).onClick = function()
{
var taskElem = $(div#tasks > select)
.$append(&lt;option>Task { ++taskNo }
&lt;progress max=100 />
&lt;span.result />&lt;/option>);
function onProgress(p100) {
taskElem.$(progress).value = p100;
}
function onDone(taskId) {
taskElem.$(span.result).text = "Done!";
taskElem.$(progress).remove();
}
view.exec_task(taskId, onProgress, onDone);
}
</pre>
<p>It defines couple of callback functions and calls <code>view.exec_task()</code> with them.</p>
<p>The <code>view.exec_task()</code> native method is implemented in <code>EventHandler::exec_task()</code>.</p>
<p>The <code>EventHandler::exec_task()</code> starts worker thread passing <em>taskNo</em>, <em>onProgress</em> and
<em>onDone</em> parameters to it.</p>
<p>Worker thread body is defined in Rust code as:</p>
<pre>
// worker thread body, simulate time consuming task
fn thread_body(task_no: i32, progress: Value, done: Value)
{
for i in 1..100 {
std::thread::sleep(std::time::Duration::from_millis(100));
progress.call(None, &amp;make_args!(i), None).unwrap(); // report task progress
}
// report task completion,
// we can pass some result data here, for now just taskId
done.call(None, &amp;make_args!(task_no), None).unwrap();
}
</pre>
<p>As you see it calls passed callback functions.</p>
</div>
</div>
</body>
</html>

View File

@ -1,42 +0,0 @@
#[macro_use]
extern crate sciter;
use sciter::Value;
struct EventHandler;
impl EventHandler {
// script handler
fn exec_task(&self, task_no: i32, progress: sciter::Value, done: sciter::Value) -> bool {
use std::{thread, time};
thread::spawn(move || {
for i in 1..100 {
// call `onProgress` callback
thread::sleep(time::Duration::from_millis(100));
progress.call(None, &make_args!(i), None).unwrap();
}
// call `onDone` callback
done.call(None, &make_args!(task_no), None).unwrap();
});
true
}
}
impl sciter::EventHandler for EventHandler {
// route script calls to our handler
dispatch_script_call! {
fn exec_task(i32, Value, Value);
}
}
fn main() {
let html = include_bytes!("threads.htm");
let mut frame = sciter::WindowBuilder::main_window()
.with_size((1200, 900))
.create();
frame.event_handler(EventHandler);
frame.load_html(html, None);
frame.run_app();
}

View File

@ -1,122 +0,0 @@
<html window-icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAB1UlEQVR4nJWTP2hTcRDHP3epS4TqqHHtVNNCFzNFaZD8sxQkKQrOUnCLBoIoOIkG0nYQBbO4OiRLadpEIQ6dxEGxcdclg6Ngpt/vPZd78vqwBQ+O3933vtz97o4TEvKodDkP3ADyQNbgCXAIDJ6Ovh3G+RIZD0vZDNAENoF0MrHJDHgNdJ6NJlMABWiVljIBshUgjQBJB8iHANkMEAKkZu/QYo0A2WqVljJ/E3i06dHbHv3u0QceXWuPjroexaP99uhIPFqz2NS4TQBplFfywPCUb0fS2xl+3miUV+4CXWunnLqycOleiKyGSC1EboUIJ+hibiEzDZFiiCyGyJkQ+Tnn0LxV6Ccq/gBemv0YmAeKQB2oGT+vDs06FIcuvxp+ErNx6HmHVhxadui8YRcc2nNo3/ysOklhKgAx/5yT1KqTVCGGvegOP244SS1HmHp0YtO+ZhuJ9ItHczbxCHtinK/mT+RO5epzoAX8sj6TkgPenxBrq0MHDp3F+kyqOvTNP/CZQwcCUK8UtoFGbLpnewfjWbxUvVJIA79jnJ3ewfj+HIAX7QAXY6vcu1m9vguMzS94WI+t+y3QgdgxrVeL/3VMu/vvpscSRLJWLZ16znv7o2Pn/AeeJco8j/W3vQAAAABJRU5ErkJggg==">
<head>
<title>Video behavior demo</title>
<style>
body { background: gold; padding: 5dip; margin: 0; }
form { margin: 5dip; }
p { padding: 4dip; }
video.generator {
behavior: video-generator video;
border: 1px solid orange;
size: *;
foreground-size: contain;
}
</style>
<script type="text/tiscript">
$(video).onSize = function() {
var (w,h) = this.box(#dimension);
$(form).value = { width: w, height: h };
}
function self.ready() {
var (w,h) = this.box(#dimension);
$(form).value = { width: w, height: h };
}
event click $(#snapshot) {
var curframe = $(video).style.foregroundImage;
var fname = view.selectFile(#save, "Images|*.png;*.jpg|All files|*.*", "png");
if (fname) {
var image = curframe.toBytes();
image.save(fname);
}
}
var video = $(video);
var host;
var body = $(body);
event click $(#show-detached) {
if (body && !video.parent) {
// recreate element
video = body.$append(<video class="generator" />);
}
// It creates a new window and moves the current video element to it.
if( this.value )
{
host = view.window {
type: View.TOOL_WINDOW,
html: $(#templates).text,
width: 640,
height: 480,
alignment: 5,
};
video.detach();
host.root.$(body).append(video);
host.on("closing", function(evt) {
// detach
video.detach();
body.append(video);
$(#show-detached).value = false;
});
} else {
// and back
video.detach();
body.append(video);
host.close();
}
}
</script>
<script id="templates" type="text/html+template">
<html window-resizable>
<head>
<title>Hosted element</title>
<style>
body { margin: 0; padding: 0; }
video.generator {
display: block;
behavior: video-generator video;
size: *;
foreground-size: contain;
}
</style>
</head>
<body>
</body>
</html>
</script>
</head>
<body>
<p>This demo simulates partial video frame update.
On each frame (24 FPS) it updates another portion of the frame.</p>
<div>
<button id="snapshot">Save the current frame</button>
<button type=checkbox id="show-detached">Show video in a separate window</button>
</div>
<div>
<form>frame size: <output name=width /> x <output name=height /></form>
</div>
<video class="generator" />
</body>
</html>

View File

@ -1,177 +0,0 @@
#![allow(unused_variables, unused_must_use)]
extern crate sciter;
use sciter::dom::event::*;
use sciter::{Element, HELEMENT};
use sciter::video::{fragmented_video_destination, AssetPtr};
struct VideoGen {
thread: Option<std::thread::JoinHandle<()>>,
}
impl Drop for VideoGen {
fn drop(&mut self) {
println!("[video] behavior is destroyed");
}
}
impl VideoGen {
fn new() -> Self {
Self { thread: None }
}
fn generation_thread(site: AssetPtr<fragmented_video_destination>) {
println!("[video] thread is started");
// our video frame size and its part to update
const FRAME: (i32, i32) = (1200, 800);
const UPDATE: (i32, i32) = (256, 32);
// our frame data (RGBA)
let figure = [0xFF_FFA500u32; (UPDATE.0 * UPDATE.1) as usize];
// configure video output
let mut site = site;
let ok = site.start_streaming(FRAME, sciter::video::COLOR_SPACE::Rgb32, None);
println!("[video] initialized: {:?}", ok);
let mut x = 0;
let mut xd = 1;
let mut y = 0;
let mut yd = 1;
while site.is_alive() {
// send an update portion
let buf: &[u8] = unsafe { std::mem::transmute(figure.as_ref()) };
site.render_frame_part(buf, (x, y), UPDATE);
// set the next position
x += xd;
y += yd;
if x == 0 {
xd = 1;
} else if x + UPDATE.0 == FRAME.0 {
xd = -1;
}
if y == 0 {
yd = 1;
} else if y + UPDATE.1 == FRAME.1 {
yd = -1;
}
// simulate 25 FPS
std::thread::sleep(std::time::Duration::from_millis(1000 / 25));
}
site.stop_streaming();
println!("[video] thread is finished");
}
}
impl sciter::EventHandler for VideoGen {
fn get_subscription(&mut self) -> Option<EVENT_GROUPS> {
Some(EVENT_GROUPS::HANDLE_BEHAVIOR_EVENT)
}
fn detached(&mut self, _root: HELEMENT) {
println!("[video] <video> element is detached");
if let Some(h) = self.thread.take() {
h.join();
}
}
fn on_event(
&mut self,
root: HELEMENT,
source: HELEMENT,
target: HELEMENT,
code: BEHAVIOR_EVENTS,
phase: PHASE_MASK,
reason: EventReason,
) -> bool {
if phase != PHASE_MASK::BUBBLING {
return false;
}
match code {
BEHAVIOR_EVENTS::VIDEO_BIND_RQ => {
let source = Element::from(source);
println!("[video] {:?} {} ({:?})", code, source, reason);
if let EventReason::VideoBind(ptr) = reason {
if ptr.is_null() {
// first, consume the event to announce us as a video producer.
return true;
}
use sciter::video::*;
// `VideoBind` comes with a video_destination interface
let mut site = AssetPtr::from(ptr as *mut video_destination);
// query a fragmented video destination interface
if let Ok(fragmented) = AssetPtr::<fragmented_video_destination>::try_from(&mut site) {
// and use it
println!("[video] start video thread");
let tid = ::std::thread::spawn(|| VideoGen::generation_thread(fragmented));
self.thread = Some(tid);
}
}
}
BEHAVIOR_EVENTS::VIDEO_INITIALIZED => {
println!("[video] {:?}", code);
}
BEHAVIOR_EVENTS::VIDEO_STARTED => {
println!("[video] {:?}", code);
let source = Element::from(source);
use sciter::dom::ELEMENT_AREAS;
let flags = ELEMENT_AREAS::CONTENT_BOX as u32 | ELEMENT_AREAS::SELF_RELATIVE as u32;
let rc = source.get_location(flags).unwrap();
println!("[video] start video thread on <{}> which is about {:?} pixels", source, rc.size());
}
BEHAVIOR_EVENTS::VIDEO_STOPPED => {
println!("[video] {:?}", code);
}
_ => return false,
};
return true;
}
}
fn main() {
if cfg!(all(target_os = "windows", target_arch = "x86")) {
println!("\nerror: Sciter video will not work on Windows x86.");
println!("error: Consider using a nightly Rust version to enable `abi_thiscall`,");
println!("error: see https://github.com/rust-lang/rust/issues/42202");
println!("");
std::process::exit(126);
}
if sciter::version_num() < 0x04_04_02_0E {
// since 4.4.2.14
println!("\nerror: `sciter::video` requires SOM support.");
println!("error: Sciter API was changed in '4.4.2.14'");
println!("error: Sciter version is '{}' now", sciter::version());
println!("error: see https://sciter.com/native-code-exposure-to-script/");
println!("error: and https://sciter.com/developers/for-native-gui-programmers/sciter-object-model/");
println!("");
std::process::exit(126);
}
let mut frame = sciter::WindowBuilder::main_window()
.with_size((750, 750))
.create();
frame.set_title("Video renderer sample");
frame.register_behavior("video-generator", || Box::new(VideoGen::new()));
frame.load_html(include_bytes!("video.htm"), Some("example://video.htm"));
frame.run_app();
}

View File

@ -1,320 +0,0 @@
//! Windowless mode example (for Sciter.Lite build).
extern crate sciter;
extern crate winit;
extern crate winapi;
extern crate raw_window_handle;
fn main() {
// "Windowless" Sciter builds are incompatible with the regular ones.
if !cfg!(feature = "windowless") {
panic!("This example requires \"windowless\" feature!");
}
// We need this to explicitly set path to the windowless sciter dll.
if !cfg!(feature = "dynamic") {
panic!("This example requires the \"dynamic\" feature enabled.")
}
if let Some(arg) = std::env::args().nth(1) {
println!("loading sciter from {:?}", arg);
if let Err(_) = sciter::set_options(sciter::RuntimeOptions::LibraryPath(&arg)) {
panic!("Invalid sciter-lite dll specified.");
}
}
// prepare and create a new window
println!("create window");
let mut events = winit::EventsLoop::new();
use raw_window_handle::HasRawWindowHandle;
let wnd = winit::WindowBuilder::new();
let wnd = wnd.build(&events).expect("Failed to create window");
let window_handle = wnd.raw_window_handle();
// configure Sciter
println!("create sciter instance");
sciter::set_options(sciter::RuntimeOptions::UxTheming(true)).unwrap();
sciter::set_options(sciter::RuntimeOptions::DebugMode(true)).unwrap();
sciter::set_options(sciter::RuntimeOptions::ScriptFeatures(0xFF)).unwrap();
// create an engine instance with an opaque pointer as an identifier
use sciter::windowless::{Message, handle_message};
let scwnd = { &wnd as *const _ as sciter::types::HWINDOW };
handle_message(scwnd, Message::Create { backend: sciter::types::GFX_LAYER::SKIA_OPENGL, transparent: false, });
#[cfg(windows)]
{
// Windows-specific: we need to redraw window in responce to the corresponding notification.
// winit 0.20 has an explicit `Window::request_redraw` method,
// here we use `winapi::InvalidateRect` for this.
struct WindowlessHandler {
hwnd: winapi::shared::windef::HWND,
}
impl sciter::HostHandler for WindowlessHandler {
fn on_invalidate(&mut self, pnm: &sciter::host::SCN_INVALIDATE_RECT) {
unsafe {
let rc = &pnm.invalid_rect;
let dst = winapi::shared::windef::RECT {
left: rc.left,
top: rc.top,
right: rc.right,
bottom: rc.bottom,
};
winapi::um::winuser::InvalidateRect(self.hwnd, &dst as *const _, 0);
// println!("- {} {}", rc.width(), rc.height());
}
}
}
let handler = WindowlessHandler {
hwnd: match window_handle {
raw_window_handle::RawWindowHandle::Windows(data) => data.hwnd as winapi::shared::windef::HWND,
_ => unreachable!(),
},
};
let instance = sciter::Host::attach_with(scwnd, handler);
let html = include_bytes!("minimal.htm");
instance.load_html(html, Some("example://minimal.htm"));
}
// events processing
use sciter::windowless::{MouseEvent, KeyboardEvent, RenderEvent};
use sciter::windowless::{MOUSE_BUTTONS, MOUSE_EVENTS, KEYBOARD_STATES, KEY_EVENTS};
let mut mouse_button = MOUSE_BUTTONS::NONE;
let mut mouse_pos = (0, 0);
let as_keys = |modifiers: winit::ModifiersState| {
let mut keys = 0;
if modifiers.ctrl {
keys |= 0x01;
}
if modifiers.shift {
keys |= 0x02;
}
if modifiers.alt {
keys |= 0x04;
}
KEYBOARD_STATES::from(keys)
};
println!("running...");
use winit::{Event, WindowEvent};
let skip = ();
let mut poll_break = false;
let startup = std::time::Instant::now();
loop {
// release CPU a bit, hackish
std::thread::sleep(std::time::Duration::from_millis(0));
// Sciter processes timers and fading effects here
handle_message(scwnd, Message::Heartbit {
milliseconds: std::time::Instant::now().duration_since(startup).as_millis() as u32,
});
// the actual event loop polling
events.poll_events(|event: winit::Event| {
match event {
Event::WindowEvent { event, window_id: _ } => {
match event {
WindowEvent::Destroyed => {
// never called due to loop break on close
println!("destroy");
handle_message(scwnd, Message::Destroy);
poll_break = true;
},
WindowEvent::CloseRequested => {
println!("close");
poll_break = true;
},
WindowEvent::Resized(size) => {
// println!("{:?}, size: {:?}", event, size);
let (width, height): (u32, u32) = size.into();
handle_message(scwnd, Message::Size { width, height });
skip
},
WindowEvent::Refresh => {
let on_render = move |bitmap_area: &sciter::types::RECT, bitmap_data: &[u8]|
{
#[cfg(unix)]
{
let _ = bitmap_area;
let _ = bitmap_data;
let _ = window_handle;
}
// Windows-specific bitmap rendering on the window
#[cfg(windows)]
{
use winapi::um::winuser::*;
use winapi::um::wingdi::*;
use winapi::shared::minwindef::LPVOID;
let hwnd = match window_handle {
raw_window_handle::RawWindowHandle::Windows(data) => data.hwnd as winapi::shared::windef::HWND,
_ => unreachable!(),
};
unsafe {
// NOTE: we use `GetDC` here instead of `BeginPaint`, because the way
// winit 0.19 processed the `WM_PAINT` message (it always calls `DefWindowProcW`).
// let mut ps = PAINTSTRUCT::default();
// let hdc = BeginPaint(hwnd, &mut ps as *mut _);
let hdc = GetDC(hwnd);
let (w, h) = (bitmap_area.width(), bitmap_area.height());
let mem_dc = CreateCompatibleDC(hdc);
let mem_bm = CreateCompatibleBitmap(hdc, w, h);
let mut bmi = BITMAPINFO::default();
{
let mut info = &mut bmi.bmiHeader;
info.biSize = std::mem::size_of::<BITMAPINFO>() as u32;
info.biWidth = w;
info.biHeight = -h;
info.biPlanes = 1;
info.biBitCount = 32;
}
let old_bm = SelectObject(mem_dc, mem_bm as LPVOID);
let _copied = StretchDIBits(mem_dc, 0, 0, w, h, 0, 0, w, h, bitmap_data.as_ptr() as *const _, &bmi as *const _, 0, SRCCOPY);
let _ok = BitBlt(hdc, 0, 0, w, h, mem_dc, 0, 0, SRCCOPY);
SelectObject(mem_dc, old_bm);
// EndPaint(hwnd, &ps as *const _);
ReleaseDC(hwnd, hdc);
// println!("+ {} {}", w, h);
}
}
};
let cb = RenderEvent {
layer: None,
callback: Box::new(on_render),
};
handle_message(scwnd, Message::RenderTo(cb));
skip
},
WindowEvent::Focused(enter) => {
println!("focus {}", enter);
handle_message(scwnd, Message::Focus { enter });
skip
},
WindowEvent::CursorEntered { device_id: _ } => {
println!("mouse enter");
let event = MouseEvent {
event: MOUSE_EVENTS::MOUSE_ENTER,
button: mouse_button,
modifiers: KEYBOARD_STATES::from(0),
pos: sciter::types::POINT {
x: mouse_pos.0,
y: mouse_pos.1,
},
};
handle_message(scwnd, Message::Mouse(event));
skip
},
WindowEvent::CursorLeft { device_id: _ } => {
println!("mouse leave");
let event = MouseEvent {
event: MOUSE_EVENTS::MOUSE_LEAVE,
button: mouse_button,
modifiers: KEYBOARD_STATES::from(0),
pos: sciter::types::POINT {
x: mouse_pos.0,
y: mouse_pos.1,
},
};
handle_message(scwnd, Message::Mouse(event));
skip
},
WindowEvent::CursorMoved { device_id: _, position, modifiers } => {
mouse_pos = position.into();
let event = MouseEvent {
event: MOUSE_EVENTS::MOUSE_MOVE,
button: mouse_button,
modifiers: as_keys(modifiers),
pos: sciter::types::POINT {
x: mouse_pos.0,
y: mouse_pos.1,
},
};
handle_message(scwnd, Message::Mouse(event));
skip
},
WindowEvent::MouseInput { device_id: _, state, button, modifiers } => {
mouse_button = match button {
winit::MouseButton::Left => MOUSE_BUTTONS::MAIN,
winit::MouseButton::Right => MOUSE_BUTTONS::PROP,
winit::MouseButton::Middle => MOUSE_BUTTONS::MIDDLE,
_ => MOUSE_BUTTONS::NONE,
};
println!("mouse {:?} as {:?}", mouse_button, mouse_pos);
let event = MouseEvent {
event: if state == winit::ElementState::Pressed { MOUSE_EVENTS::MOUSE_DOWN } else { MOUSE_EVENTS::MOUSE_UP },
button: mouse_button,
modifiers: as_keys(modifiers),
pos: sciter::types::POINT {
x: mouse_pos.0,
y: mouse_pos.1,
},
};
handle_message(scwnd, Message::Mouse(event));
skip
},
WindowEvent::KeyboardInput { device_id: _, input } => {
println!("key {} {}", input.scancode, if input.state == winit::ElementState::Pressed { "down" } else { "up" });
let event = KeyboardEvent {
event: if input.state == winit::ElementState::Pressed { KEY_EVENTS::KEY_DOWN } else { KEY_EVENTS::KEY_UP },
code: input.scancode,
modifiers: as_keys(input.modifiers),
};
handle_message(scwnd, Message::Keyboard(event));
skip
},
_ => (),
}
},
_ => (),
}
});
if poll_break {
break;
}
}
println!("done, quit");
}

View File

@ -1,25 +0,0 @@
[package]
name = "sciter-serde"
version = "0.3.2"
description = "Serde support for Sciter engine."
keywords = ["serde", "gui", "gtk", "opengl", "skia"]
categories = ["gui", "web-programming", "rendering::graphics-api", "api-bindings"]
authors = ["pravic <ehysta@gmail.com>"]
repository = "https://github.com/sciter-sdk/rust-sciter"
documentation = "https://docs.rs/sciter-serde"
license = "MIT"
exclude = [".gitignore", ".editorconfig", ".appveyor.yml"]
[badges]
appveyor = { repository = "sciter-sdk/rust-sciter" }
travis-ci = { repository = "sciter-sdk/rust-sciter" }
[dependencies]
sciter-rs = { version = "0.5" }
serde = "1"
[dev-dependencies]
serde_derive = "1"
serde_bytes = "0.10"

View File

@ -1,278 +0,0 @@
/// Deserialization.
use serde::de::{self, Deserialize, Visitor};
use error::{Error, Result};
use sciter::{Value};
/// Deserializes a Sciter value to the specific Rust type.
pub fn from_value<'a, T>(input: &'a Value) -> Result<T>
where T: Deserialize<'a>
{
let p = Deserializer::from_value(input.clone());
T::deserialize(p)
}
/// Implementation of deserialization.
pub struct Deserializer {
input: Value,
}
impl<'de> Deserializer {
pub fn from_value(input: Value) -> Self {
Deserializer { input: input }
}
}
impl<'de, 'a> ::serde::de::Deserializer<'de> for Deserializer {
type Error = Error;
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value>
{
use sciter::value::VALUE_TYPE;
match self.input.get_type() {
VALUE_TYPE::T_UNDEFINED|VALUE_TYPE::T_NULL => visitor.visit_none(),
VALUE_TYPE::T_BOOL => visitor.visit_bool(self.input.to_bool().unwrap()),
VALUE_TYPE::T_INT => visitor.visit_i32(self.input.to_int().unwrap()),
VALUE_TYPE::T_FLOAT => visitor.visit_f64(self.input.to_float().unwrap()),
VALUE_TYPE::T_STRING => visitor.visit_str(&self.input.as_string().unwrap()),
VALUE_TYPE::T_ARRAY => visitor.visit_seq(SeqAccess::new(self)),
VALUE_TYPE::T_MAP => self.deserialize_map(visitor),
VALUE_TYPE::T_BYTES => visitor.visit_bytes(self.input.as_bytes().unwrap()),
VALUE_TYPE::T_OBJECT => self.deserialize_map(visitor),
_ => Err(Error::UnsupportedType),
}
}
fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
self.deserialize_any(visitor)
}
fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
if let Some(v) = self.input.to_bool() {
visitor.visit_bool(v)
} else {
Err(Error::ExpectedType(format!("expected {:?}, given {:?}", "bool", self.input)))
}
}
forward_to_deserialize_any! {
i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes byte_buf
}
fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
if self.input.is_undefined() || self.input.is_null() {
visitor.visit_none()
} else {
visitor.visit_some(self)
}
}
fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
if self.input.is_undefined() || self.input.is_null() {
visitor.visit_unit()
} else {
Err(Error::ExpectedType(format!("expected {:?}, given {:?}", "null", self.input)))
}
}
fn deserialize_unit_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value> {
self.deserialize_unit(visitor)
}
fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &str, visitor: V) -> Result<V::Value> {
visitor.visit_newtype_struct(self)
}
fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
if self.input.is_array() {
let it = self.input.values();
let sq = de::value::SeqDeserializer::new(it);
visitor.visit_seq(sq)
} else {
Err(Error::ExpectedType(format!("expected {:?}, given {:?}", "sequence", self.input)))
}
}
fn deserialize_tuple<V: Visitor<'de>>(self, _len: usize, visitor: V) -> Result<V::Value> {
self.deserialize_seq(visitor)
}
fn deserialize_tuple_struct<V: Visitor<'de>>(self, _name: &'static str, _len: usize, visitor: V) -> Result<V::Value> {
self.deserialize_seq(visitor)
}
fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
if self.input.is_map() {
let it = self.input.items().into_iter();
let sq = de::value::MapDeserializer::new(it);
visitor.visit_map(sq)
} else {
Err(Error::ExpectedType(format!("expected {:?}, given {:?}", "map", self.input)))
}
}
fn deserialize_struct<V: Visitor<'de>>(self, _name: &'static str, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
{
self.deserialize_map(visitor)
}
fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value>
{
self.deserialize_str(visitor)
}
fn deserialize_enum<V: Visitor<'de>>(self, _name: &'static str, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
{
// it can be `"A"`, `{"T": u8}`, `{S: {"x": u8}}`
match (self.input.is_string(), self.input.is_map()) {
(true, _) => {
use self::de::IntoDeserializer;
visitor.visit_enum(self.input.as_string().unwrap().into_deserializer())
},
(_, true) => {
visitor.visit_enum(SeqAccess::new(self))
},
_ => {
Err(Error::ExpectedType(format!("expected enum (as string or map), given {:?}", self.input)))
}
}
}
}
impl<'de> de::IntoDeserializer<'de, Error> for Value {
type Deserializer = Deserializer;
fn into_deserializer(self) -> Self::Deserializer {
Deserializer::from_value(self)
}
}
#[doc(hidden)]
struct SeqAccess {
de: Deserializer,
pos: usize,
len: usize,
key: Option<Value>,
}
impl SeqAccess {
fn new(d: Deserializer) -> Self {
let len = d.input.len();
SeqAccess {
de: d,
pos: 0,
len: len,
key: None,
}
}
}
impl<'de> de::SeqAccess<'de> for SeqAccess {
type Error = Error;
fn size_hint(&self) -> Option<usize> {
Some(self.len)
}
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
where T: de::DeserializeSeed<'de>
{
if self.pos < self.len {
self.pos += 1;
let v = self.de.input.get(self.pos - 1);
let inner = Deserializer::from_value(v);
seed.deserialize(inner).map(Some)
} else {
Ok(None)
}
}
}
impl<'de> de::MapAccess<'de> for SeqAccess {
type Error = Error;
fn size_hint(&self) -> Option<usize> {
Some(self.len)
}
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
where K: de::DeserializeSeed<'de>
{
if self.pos < self.len {
self.pos += 1;
let v = self.de.input.key_at(self.pos - 1);
let inner = Deserializer::from_value(v);
seed.deserialize(inner).map(Some)
} else {
Ok(None)
}
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
where V: de::DeserializeSeed<'de>
{
let v = self.de.input.get(self.pos - 1);
let inner = Deserializer::from_value(v);
seed.deserialize(inner)
}
}
impl<'de> de::EnumAccess<'de> for SeqAccess {
type Error = Error;
type Variant = Self;
fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant)>
where V: de::DeserializeSeed<'de>
{
// `{ "N": ... }`
// Here I suppose to deserialize the variant key.
let v = self.de.input.key_at(0);
self.key = Some(v.clone());
let vkey = seed.deserialize( Deserializer::from_value(v) )?;
Ok((vkey, self))
}
}
impl<'de> de::VariantAccess<'de> for SeqAccess {
type Error = Error;
fn unit_variant(self) -> Result<()> {
de::Deserialize::deserialize(self.de)
}
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
where T: de::DeserializeSeed<'de>
{
// `{ "N": u8 }`
let v = self.de.input.get_item(self.key.unwrap());
seed.deserialize( Deserializer::from_value(v) )
}
fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value>
where V: de::Visitor<'de>
{
// `{ "T": [u8, u8] }`
let v = self.de.input.get_item(self.key.unwrap());
de::Deserializer::deserialize_tuple(Deserializer::from_value(v), len, visitor)
}
fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>
where V: de::Visitor<'de>
{
// `{ "S": {r: u8, g: u8, b: u8} }`
let v = self.de.input.get_item(self.key.unwrap());
de::Deserializer::deserialize_struct(Deserializer::from_value(v), "", fields, visitor)
}
}

View File

@ -1,51 +0,0 @@
use std;
use std::fmt::{self, Display};
use serde::{ser, de};
/// Result type for serialization.
pub type Result<T> = std::result::Result<T, Error>;
/// Error type for serialization.
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
Message(String),
Unimplemented,
UnsupportedType,
ExpectedType(String),
}
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
impl de::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Message(ref msg) => msg,
Error::ExpectedType(ref msg) => msg,
Error::Unimplemented => "unimplemented",
Error::UnsupportedType => "unsupported",
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Message(ref msg) => write!(f, "error: {}", msg),
Error::ExpectedType(ref msg) => write!(f, "expected: {}", msg),
Error::UnsupportedType => write!(f, "unsupported type"),
Error::Unimplemented => write!(f, "unimplemented"),
}
}
}

View File

@ -1,155 +0,0 @@
// This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).
/*!
[Serde](https://docs.rs/serde) support for [Sciter](https://docs.rs/sciter-rs) engine.
While technically you could just use the `serde_json` crate and perform serialization via
an intermediate string (something like `sciter::Value::from_str(&serde_json::to_string(<your data>)?)?`),
you can also use direct serialization between your data and `sciter::Value`.
## Supported types of Sciter value
+ Bool (`bool`)
+ Integer (`i8`-`i32`)
+ Float (`f32`-`f64`)
+ String (`&str`, `String`)
+ Bytes (`&[u8]`)
+ Array (`&[T]`, `Vec<T>`)
+ Object (key-value mapping like `struct` or `HashMap`, `BTreeMap`, etc.)
Unsupported:
- Date
- Currency
- Length
- Range
- Duration
- Angle
- Color
## Supported types of the Serde data model
* [x] `bool`
* [x] integer types except the following:
* [-] `i64`/`u64` - 64-bit integers stored as `f64` in Sciter
* [x] strings
* [x] byte arrays
* [x] option
* [x] unit (stored as `null`)
* [x] unit struct (stored as `null`)
* [x] unit variant (aka `enum`, stored just as enum index of `i32` type)
* [x] newtype struct (aka `struct Io(u32)`, stored as underlaying value)
* [-] newtype variant
* [x] seq, like vector (stored as array)
* [x] tuple (stored as array)
* [x] tuple struct (stored as array)
* [-] tuple variant
* [x] map (stored as map)
* [x] struct (stored as map)
* [-] struct variant
See the [Serde data model](https://serde.rs/data-model.html) for reference.
# Examples
```rust
extern crate sciter;
extern crate sciter_serde;
use sciter::Value;
use sciter_serde::{from_value, to_value};
fn back_and_forth() {
let v: Value = to_value(&true).unwrap();
let b: bool = from_value(&v).unwrap();
assert_eq!(b, true);
}
fn main() {
// bool
let v: Value = to_value(&true).unwrap();
assert!(v.is_bool());
assert_eq!(v, Value::from(true));
// numbers
let v = to_value(&12u32).unwrap();
assert_eq!(v, 12.into());
let v = to_value(& 42.0f64).unwrap();
assert_eq!(v, 42.0f64.into());
// strings
let v = to_value("hello").unwrap();
assert_eq!(v, "hello".into());
// arrays
let a = [1,2,3];
let v = to_value(&a).unwrap();
assert_eq!(v, a.iter().cloned().collect());
// maps
let m = {
use std::collections::BTreeMap;
let mut m = BTreeMap::new();
m.insert("17", 17);
m.insert("42", 42);
m
};
let v = to_value(&m).unwrap();
assert_eq!(v, Value::parse(r#"{ "17": 17, "42": 42 }"#).unwrap());
}
```
With derived serialization:
```rust
# #![doc(test(no_crate_inject))]
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate sciter;
extern crate sciter_serde;
use sciter::Value;
use sciter_serde::to_value;
fn main() {
// structs
#[derive(Serialize)]
struct Test {
x: i32,
y: i32,
}
let v = to_value(&Test {x: 1, y: 2}).unwrap();
assert_eq!(v, Value::parse(r#"{ "x": 1, "y": 2 }"#).unwrap());
}
```
*/
#![allow(clippy::redundant_field_names)]
#![allow(clippy::tabs_in_doc_comments)]
#[macro_use]
extern crate serde;
extern crate sciter;
mod error;
mod ser;
mod de;
#[doc(inline)]
pub use ser::to_value;
#[doc(inline)]
pub use de::from_value;
pub use error::{Result, Error};

View File

@ -1,345 +0,0 @@
/// Serialization.
use serde::ser::{self, Serialize};
use error::{Error, Result};
use sciter::{Value};
/// Serialize the given data structure into Sciter value.
pub fn to_value<T: ?Sized + Serialize>(value: &T) -> Result<Value> {
let mut p = Serializer { output: Value::new() };
value.serialize(&mut p)?;
Ok(p.output)
}
/// Implementation of serialization.
pub struct Serializer {
output: Value,
}
// Helper structure for serialization of sequence data types (array, map, tuple ans so on).
#[doc(hidden)]
pub struct SeqSerializer<'a> {
ser: &'a mut Serializer,
output: Value,
key: Option<Value>,
outer: Option<Value>,
}
impl<'a> SeqSerializer<'a> {
fn typed(ser: &'a mut Serializer, typed: Value) -> Self {
SeqSerializer {
ser: ser,
output: typed,
key: None,
outer: None,
}
}
fn with_outer(ser: &'a mut Serializer, outer: Value, typed: Value) -> Self {
SeqSerializer {
ser: ser,
output: typed,
key: None,
outer: Some(outer),
}
}
}
// serde traits implementation
impl<'a> ser::SerializeSeq for SeqSerializer<'a> {
type Ok = ();
type Error = Error;
fn end(self) -> Result<()> {
self.ser.output = self.output;
Ok(())
}
fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> {
let dst = to_value(value)?;
self.output.push(dst);
Ok(())
}
}
impl<'a> ser::SerializeMap for SeqSerializer<'a> {
type Ok = ();
type Error = Error;
fn end(self) -> Result<()> {
ser::SerializeSeq::end(self)
}
fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<()> where K: ?Sized + Serialize, V: ?Sized + Serialize {
self.output.set_item(to_value(key)?, to_value(value)?);
Ok(())
}
fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<()> {
self.key = Some(to_value(key)?);
Ok(())
}
fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> {
let key = self.key.take();
self.output.set_item(key.unwrap(), to_value(value)?);
Ok(())
}
}
impl<'a> ser::SerializeStruct for SeqSerializer<'a> {
type Ok = ();
type Error = Error;
fn end(self) -> Result<()> {
ser::SerializeSeq::end(self)
}
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> {
self.output.set_item(key, to_value(value)?);
Ok(())
}
}
impl<'a> ser::SerializeStructVariant for SeqSerializer<'a> {
type Ok = ();
type Error = Error;
fn end(self) -> Result<()> {
// self.output: map
// self.outer: left key
let mut result = Value::new();
result.set_item(self.outer.unwrap(), self.output);
self.ser.output = result;
Ok(())
}
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<()> {
self.output.set_item(key, to_value(value)?);
Ok(())
}
}
impl<'a> ser::SerializeTuple for SeqSerializer<'a> {
type Ok = ();
type Error = Error;
fn end(self) -> Result<()> {
ser::SerializeSeq::end(self)
}
fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> {
ser::SerializeSeq::serialize_element(self, value)
}
}
impl<'a> ser::SerializeTupleStruct for SeqSerializer<'a> {
type Ok = ();
type Error = Error;
fn end(self) -> Result<()> {
ser::SerializeSeq::end(self)
}
fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> {
ser::SerializeSeq::serialize_element(self, value)
}
}
impl<'a> ser::SerializeTupleVariant for SeqSerializer<'a> {
type Ok = ();
type Error = Error;
fn end(self) -> Result<()> {
// self.output: array
// self.outer: left key
let mut result = Value::new();
result.set_item(self.outer.unwrap(), self.output);
self.ser.output = result;
Ok(())
}
fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<()> {
ser::SerializeSeq::serialize_element(self, value)
}
}
impl<'a> ser::Serializer for &'a mut Serializer {
type Ok = ();
type Error = Error;
type SerializeSeq = SeqSerializer<'a>;
type SerializeTuple = SeqSerializer<'a>;
type SerializeTupleStruct = SeqSerializer<'a>;
type SerializeTupleVariant = SeqSerializer<'a>;
type SerializeMap = SeqSerializer<'a>;
type SerializeStruct = SeqSerializer<'a>;
type SerializeStructVariant = SeqSerializer<'a>;
fn serialize_bool(self, v: bool) -> Result<()> {
self.output = v.into();
Ok(())
}
fn serialize_i8(self, v: i8) -> Result<()> {
self.serialize_i32(v as i32)
}
fn serialize_i16(self, v: i16) -> Result<()> {
self.serialize_i32(v as i32)
}
fn serialize_i32(self, v: i32) -> Result<()> {
self.output = v.into();
Ok(())
}
fn serialize_u8(self, v: u8) -> Result<()> {
self.serialize_i32(v as i32)
}
fn serialize_u16(self, v: u16) -> Result<()> {
self.serialize_i32(v as i32)
}
fn serialize_u32(self, v: u32) -> Result<()> {
if v <= i32::max_value() as u32 {
self.serialize_i32(v as i32)
} else {
self.serialize_f64(v as f64)
}
}
fn serialize_i64(self, _v: i64) -> Result<()> {
Err(Error::UnsupportedType)
}
fn serialize_u64(self, _v: u64) -> Result<()> {
Err(Error::UnsupportedType)
}
// Float values.
fn serialize_f32(self, v: f32) -> Result<()> {
self.serialize_f64(v as f64)
}
fn serialize_f64(self, v: f64) -> Result<()> {
self.output = v.into();
Ok(())
}
// A single character is passed as a string.
fn serialize_char(self, v: char) -> Result<()> {
self.serialize_str(&v.to_string())
}
// String itself.
fn serialize_str(self, v: &str) -> Result<()> {
self.output = v.into();
Ok(())
}
// Binary bytes.
fn serialize_bytes(self, v: &[u8]) -> Result<()> {
self.output = Value::from(v);
Ok(())
}
// A `None` value of `Option` type in Rust.
fn serialize_none(self) -> Result<()> {
self.output = Value::null();
Ok(())
}
// Some value of `Option` type in Rust.
fn serialize_some<T>(self, v: &T) -> Result<()> where T: ?Sized + Serialize {
v.serialize(self)
}
// The type of `()` in Rust.
fn serialize_unit(self) -> Result<()> {
self.serialize_none()
}
// A named value containing no data, like `struct Unit;`.
fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
self.serialize_none()
}
// Enums. Serialized as an externally tagged enum representation,
// see https://serde.rs/enum-representations.html.
// A unit variant of enum, like `E::A` of `enum E { A, B }`.
fn serialize_unit_variant(self, _name: &'static str, _index: u32, value: &'static str)
-> Result<()>
{
// `"A"`
self.serialize_str(value)
}
// For example the `E::N` in `enum E { N(u8) }`.
fn serialize_newtype_variant<T>(self, _name: &'static str, _index: u32, variant: &'static str, value: &T)
-> Result<()> where T: ?Sized + Serialize
{
// `{ "N": u8 }`
self.output.set_item(to_value(variant)?, to_value(value)?);
Ok(())
}
// For example the `E::T` in `enum E { T(u8, u8) }`.
fn serialize_tuple_variant(self, _name: &'static str, _index: u32, value: &'static str, _len: usize)
-> Result<Self::SerializeTupleVariant>
{
// `{ "T": [u8, u8] }`
let left = to_value(value)?;
Ok(SeqSerializer::with_outer(self, left, Value::array(0)))
}
// For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.
fn serialize_struct_variant(self, _name: &'static str, _index: u32, value: &'static str, _len: usize)
-> Result<Self::SerializeStructVariant>
{
// `{ "S": {r: u8, g: u8, b: u8} }`
let left = to_value(value)?;
Ok(SeqSerializer::with_outer(self, left, Value::map()))
}
// New-type struct, like `struct Celcius(u32)`.
fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
where T: ?Sized + Serialize
{
// Serialize the inner itself.
value.serialize(self)
}
// A variably sized heterogeneous sequence of values, for example `Vec<T>` or `HashSet<T>`.
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
// let init = if let Some(size) = len { Value::array(size) } else { Value::new() };
Ok(SeqSerializer::typed(self, Value::array(0)))
}
// A statically sized heterogeneous sequence of values, `[u64; 10]`, `(u8,)` or `(String, u64, Vec<T>)`.
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
self.serialize_seq(Some(len))
}
// A named tuple, for example `struct Rgb(u8, u8, u8)`.
fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct> {
self.serialize_seq(Some(len))
}
// A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
Ok(SeqSerializer::typed(self, Value::map()))
}
// A heterogeneous key-value pairing , for example `struct S { r: u8, g: u8, b: u8 }`.
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
self.serialize_map(Some(len))
}
}

View File

@ -1,201 +0,0 @@
#![allow(unused_variables)]
extern crate sciter;
extern crate sciter_serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_bytes;
extern crate serde;
use sciter_serde::{from_value, to_value};
// serialize, deserialize and compare with the original value.
// taken from [serde_bincode](https://github.com/TyOverby/bincode/blob/master/tests/test.rs)
fn the_same<V>(actual: V, expr: &'static str)
where V: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug + 'static
{
let sv = to_value(&actual).expect(&format!("to_value({})", expr));
let dv = from_value(&sv).expect(&format!("from_value({})", expr));
let decoded = dv;
assert_eq!(actual, decoded, "the_same({:?})", expr);
}
macro_rules! the_same {
($e:expr) => {
the_same($e, stringify!($e))
}
}
#[test]
fn basic_types() {
the_same!(true);
the_same!(false);
the_same!(7i8);
the_same!(7i16);
the_same!(7i32);
// the_same!(7i64); there are no 64-bit integers in Sciter, only floats.
the_same!(7u8);
the_same!(7u16);
the_same!(7u32);
// the_same!(7u64); ditto
the_same!(7f32);
the_same!(7f64);
the_same!(-7i32);
// the_same!(-7isize);
the_same!(Box::new(7));
}
#[test]
fn strings() {
the_same!("7".to_string());
}
#[test]
fn tuples() {
the_same!( (1,) );
the_same!( (1,2) );
the_same!( (1,2,3) );
the_same!( (1, "7".to_string(), ()) );
}
#[test]
fn structs() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
struct Test {
x: bool,
y: i32,
z: String,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
struct Nested {
inner: Test,
payload: Option<String>,
}
let t = Test { x: true, y: 7, z: "42".to_string() };
the_same!(t.clone());
let n = Nested { inner: t.clone(), payload: Some("Some".to_string()) };
the_same!(n.clone());
}
#[test]
fn newtypes() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
struct Test(u32);
the_same!(Test(7));
}
#[test]
fn newtuples() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
struct Test(u32, bool);
the_same!(Test(7, false));
}
#[test]
fn options() {
the_same!(None::<bool>);
the_same!(Some(true));
the_same!(Some(false));
}
#[test]
fn enums() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
enum Test {
Zero,
One(u32),
Two(u32, u32),
Three { x: u32, y: u32, z: u32 },
Five,
}
the_same!(Test::Zero);
// the_same!(Test::One(7));
// the_same!(Test::Two(7, 7));
// the_same!(Test::Three { x: 1, y: 2, z: 3});
the_same!(Test::Five);
}
#[test]
fn arrays() {
let v = [1,2,3];
the_same!(v);
let v = vec![1,2,3];
the_same!(v);
}
#[test]
#[should_panic]
fn unsupported_u64() {
the_same!(7u64);
}
#[test]
#[should_panic]
fn unsupported_i64() {
the_same!(-7i64);
}
#[test]
#[should_panic]
fn unsupported_usize() {
the_same!(7usize);
}
#[test]
fn newtype_variant() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
enum Test {
Zero,
One(u32),
Two(u32, u32),
Three { x: u32, y: u32, z: u32 },
}
the_same!(Test::One(7));
}
#[test]
fn tuple_variant() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
enum Test {
Zero,
One(u32),
Two(u32, u32),
Three { x: u32, y: u32, z: u32 },
}
the_same!(Test::Two(7, 7));
}
#[test]
fn struct_variant() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
enum Test {
Zero,
One(u32),
Two(u32, u32),
Three { x: u32, y: u32, z: u32 },
}
the_same!(Test::Three { x: 1, y: 2, z: 3 });
}

View File

@ -1,94 +0,0 @@
#![allow(unused_variables)]
extern crate sciter;
extern crate sciter_serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_bytes;
extern crate serde;
use sciter::{Value};
use sciter_serde::{from_value, to_value};
#[test]
fn basic_types() {
// bool
let v: bool = from_value(&Value::from(true)).unwrap();
assert_eq!(v, true);
// integer types
let v: i32 = from_value(&Value::from(0)).unwrap();
assert_eq!(v, 0);
let v: i32 = from_value(&Value::from(7i32)).unwrap();
assert_eq!(v, 7i32);
// float
let v: f32 = from_value(&Value::from(7.0)).unwrap();
assert_eq!(v, 7.0);
let v: f64 = from_value(&Value::from(7.0)).unwrap();
assert_eq!(v, 7.0);
// Option
let v = Value::null();
let v: Option<i32> = from_value(&v).unwrap();
assert_eq!(v, None);
let v = Value::from(7);
let v: Option<i32> = from_value(&v).unwrap();
assert_eq!(v, Some(7));
}
#[test]
fn strings() {
let v: char = from_value(&Value::from("7")).unwrap();
assert_eq!(v, '7');
let v: String = from_value(&Value::from("7")).unwrap();
assert_eq!(v, "7");
let v: serde_bytes::ByteBuf = from_value(&Value::from(b"hello".as_ref())).unwrap();
let v: &[u8] = &v;
assert_eq!(v, b"hello".as_ref());
}
#[test]
fn arrays() {
let it = [1,2,3].iter();
let v: Value = it.cloned().collect();
let v: Vec<i32> = from_value(&v).unwrap();
assert_eq!(v, &[1,2,3]);
}
#[test]
fn structs() {
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Test {
int: u32,
seq: Vec<String>,
}
println!("");
let a = Test { int: 7, seq: vec!["a".to_owned(), "b".to_owned()]};
let v: Value = to_value(&a).unwrap();
println!("serialized Test:\n {:?}", v);
println!("keys:");
v.keys().inspect(|i| println!(" {:?}", i)).count();
println!("values:");
v.values().inspect(|i| println!(" {:?}", i)).count();
println!("items:");
v.items().iter().inspect(|i| println!(" {:?}", i)).count();
let e: Test = from_value(&v).unwrap();
println!("deserialized Test:\n {:?}", e);
assert_eq!(a, e);
}

View File

@ -1,113 +0,0 @@
#![allow(unused_variables)]
extern crate sciter;
extern crate sciter_serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_bytes;
extern crate serde;
use sciter::{Value};
use sciter_serde::{to_value};
#[test]
fn basic_types() {
// bool
let v = to_value(&true).unwrap();
assert!(v.is_bool());
assert_eq!(v, Value::from(true));
// integer types
let v = to_value(&0).unwrap();
assert!(v.is_int());
assert_eq!(v.to_int(), Some(0));
let v = to_value(&7u8).unwrap();
assert_eq!(v, Value::from(7));
let v = to_value(&7u16).unwrap();
assert_eq!(v, Value::from(7));
let v = to_value(&7u32).unwrap();
assert_eq!(v, Value::from(7));
let v = to_value(&7i8).unwrap();
assert_eq!(v, Value::from(7));
let v = to_value(&7i16).unwrap();
assert_eq!(v, Value::from(7));
let v = to_value(&7i32).unwrap();
assert_eq!(v, Value::from(7));
let v = to_value(&7.0).unwrap();
assert!(v.is_float());
// 64-bit
// let v = to_value(&7u64).unwrap();
// assert!(v.is_float());
// assert_eq!(v, Value::from(7.0));
// Option
// let v = to_value(&Some(7)).unwrap();
// assert!(v.is_int());
// let v = to_value(&None).unwrap();
// assert!(v.is_null());
}
#[test]
fn strings() {
// strings
let v = to_value(&'h').unwrap();
assert!(v.is_string());
assert_eq!(v, Value::from("h"));
let v = to_value("hello").unwrap();
assert!(v.is_string());
assert_eq!(v, Value::from("hello"));
// doesn't work because Rust doesn't have specialization yet (https://github.com/rust-lang/rust#31844)
// let v = to_value(b"hello").unwrap();
// println!("b'hello': {:?}", v);
// assert!(v.is_bytes());
// assert_eq!(v.as_bytes(), Some(b"hello".as_ref()));
use serde_bytes::Bytes;
let v = to_value(&Bytes::new(b"hello")).unwrap();
assert!(v.is_bytes());
assert_eq!(v.as_bytes(), Some(b"hello".as_ref()));
}
#[test]
fn arrays() {
let a = [1,2,3];
let v = to_value(&a).unwrap();
assert!(v.is_array());
assert_eq!(v.len(), a.len());
let a = vec![1,2,3];
let v = to_value(&a).unwrap();
assert!(v.is_array());
assert_eq!(v.len(), a.len());
}
#[test]
fn structs() {
#[derive(Serialize)]
struct Test {
int: u32,
seq: Vec<&'static str>,
}
let a = Test { int: 7, seq: vec!["a", "b"]};
let v = to_value(&a).unwrap();
assert!(v.is_map());
assert_eq!(v.len(), 2);
assert_eq!(v.get_item("int"), Value::from(7) );
assert_eq!(v.get_item("seq").len(), 2);
}

View File

@ -1,14 +0,0 @@
/*! C interface headers */
pub mod scapi;
pub mod scbehavior;
pub mod scdef;
pub mod scdom;
pub mod scgraphics;
pub mod screquest;
pub mod sctiscript;
pub mod sctypes;
pub mod scvalue;
pub mod schandler;
pub mod scmsg;
pub mod scom;

View File

@ -1,279 +0,0 @@
//! Sciter C API interface.
#![allow(non_snake_case, non_camel_case_types)]
use capi::sctypes::*;
use capi::scdef::*;
use capi::scdom::*;
use capi::scvalue::*;
use capi::sctiscript::{HVM, tiscript_value, tiscript_native_interface};
use capi::scbehavior::*;
use capi::scgraphics::SciterGraphicsAPI;
use capi::screquest::{SciterRequestAPI, HREQUEST, REQUEST_PARAM};
use capi::scmsg::{SCITER_X_MSG};
use capi::scom::som_asset_t;
/// Sciter API functions.
#[repr(C)]
#[allow(missing_docs)]
#[doc(hidden)]
pub struct ISciterAPI
{
pub version: UINT,
pub SciterClassName: extern "system" fn () -> LPCWSTR,
pub SciterVersion: extern "system" fn (major: BOOL) -> UINT,
pub SciterDataReady: extern "system" fn (hwnd: HWINDOW, uri: LPCWSTR, data: LPCBYTE, dataLength: UINT) -> BOOL,
pub SciterDataReadyAsync: extern "system" fn (hwnd: HWINDOW, uri: LPCWSTR, data: LPCBYTE, dataLength: UINT, requestId: HREQUEST) -> BOOL,
// #ifdef WINDOWS
#[cfg(all(windows, not(feature = "windowless")))]
pub SciterProc: extern "system" fn (hwnd: HWINDOW, msg: UINT, wParam: WPARAM, lParam: LPARAM) -> LRESULT,
#[cfg(all(windows, not(feature = "windowless")))]
pub SciterProcND: extern "system" fn (hwnd: HWINDOW, msg: UINT, wParam: WPARAM, lParam: LPARAM, pbHandled: * mut BOOL) -> LRESULT,
// #endif
pub SciterLoadFile: extern "system" fn (hWndSciter: HWINDOW, filename: LPCWSTR) -> BOOL,
pub SciterLoadHtml: extern "system" fn (hWndSciter: HWINDOW, html: LPCBYTE, htmlSize: UINT, baseUrl: LPCWSTR) -> BOOL,
pub SciterSetCallback: extern "system" fn (hWndSciter: HWINDOW, cb: SciterHostCallback, cbParam: LPVOID) -> VOID,
pub SciterSetMasterCSS: extern "system" fn (utf8: LPCBYTE, numBytes: UINT) -> BOOL,
pub SciterAppendMasterCSS: extern "system" fn (utf8: LPCBYTE, numBytes: UINT) -> BOOL,
pub SciterSetCSS: extern "system" fn (hWndSciter: HWINDOW, utf8: LPCBYTE, numBytes: UINT, baseUrl: LPCWSTR, mediaType: LPCWSTR) -> BOOL,
pub SciterSetMediaType: extern "system" fn (hWndSciter: HWINDOW, mediaType: LPCWSTR) -> BOOL,
pub SciterSetMediaVars: extern "system" fn (hWndSciter: HWINDOW, mediaVars: * const VALUE) -> BOOL,
pub SciterGetMinWidth: extern "system" fn (hWndSciter: HWINDOW) -> UINT,
pub SciterGetMinHeight: extern "system" fn (hWndSciter: HWINDOW, width: UINT) -> UINT,
pub SciterCall: extern "system" fn (hWnd: HWINDOW, functionName: LPCSTR, argc: UINT, argv: * const VALUE, retval: * mut VALUE) -> BOOL,
pub SciterEval: extern "system" fn (hwnd: HWINDOW, script: LPCWSTR, scriptLength: UINT, pretval: * mut VALUE) -> BOOL,
pub SciterUpdateWindow: extern "system" fn (hwnd: HWINDOW) -> VOID,
// #ifdef WINDOWS
#[cfg(all(windows, not(feature = "windowless")))]
pub SciterTranslateMessage: extern "system" fn (lpMsg: * mut MSG) -> BOOL,
// #endif
pub SciterSetOption: extern "system" fn (hWnd: HWINDOW, option: SCITER_RT_OPTIONS, value: UINT_PTR) -> BOOL,
pub SciterGetPPI: extern "system" fn (hWndSciter: HWINDOW, px: * mut UINT, py: * mut UINT) -> VOID,
pub SciterGetViewExpando: extern "system" fn (hwnd: HWINDOW, pval: * mut VALUE) -> BOOL,
// #ifdef WINDOWS
#[cfg(all(windows, not(feature = "windowless")))]
pub SciterRenderD2D: extern "system" fn (hWndSciter: HWINDOW, prt: * mut ID2D1RenderTarget) -> BOOL,
#[cfg(all(windows, not(feature = "windowless")))]
pub SciterD2DFactory: extern "system" fn (ppf: * mut* mut ID2D1Factory) -> BOOL,
#[cfg(all(windows, not(feature = "windowless")))]
pub SciterDWFactory: extern "system" fn (ppf: * mut* mut IDWriteFactory) -> BOOL,
// #endif
pub SciterGraphicsCaps: extern "system" fn (pcaps: LPUINT) -> BOOL,
pub SciterSetHomeURL: extern "system" fn (hWndSciter: HWINDOW, baseUrl: LPCWSTR) -> BOOL,
// #if defined(OSX)
#[cfg(all(target_os="macos", not(feature = "windowless")))]
pub SciterCreateNSView: extern "system" fn (frame: LPRECT) -> HWINDOW, // returns NSView*
// #endif
// #if defined(LINUX)
#[cfg(all(target_os="linux", not(feature = "windowless")))]
pub SciterCreateWidget: extern "system" fn (frame: LPRECT) -> HWINDOW, // returns GtkWidget
// #endif
#[cfg(not(feature = "windowless"))]
pub SciterCreateWindow: extern "system" fn (creationFlags: UINT, frame: LPCRECT, delegate: * const SciterWindowDelegate, delegateParam: LPVOID, parent: HWINDOW) -> HWINDOW,
pub SciterSetupDebugOutput: extern "system" fn (hwndOrNull: HWINDOW, param: LPVOID, pfOutput: DEBUG_OUTPUT_PROC),
//|
//| DOM Element API
//|
pub Sciter_UseElement: extern "system" fn (he: HELEMENT) -> SCDOM_RESULT,
pub Sciter_UnuseElement: extern "system" fn (he: HELEMENT) -> SCDOM_RESULT,
pub SciterGetRootElement: extern "system" fn (hwnd: HWINDOW, phe: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterGetFocusElement: extern "system" fn (hwnd: HWINDOW, phe: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterFindElement: extern "system" fn (hwnd: HWINDOW, pt: POINT, phe: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterGetChildrenCount: extern "system" fn (he: HELEMENT, count: * mut UINT) -> SCDOM_RESULT,
pub SciterGetNthChild: extern "system" fn (he: HELEMENT, n: UINT, phe: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterGetParentElement: extern "system" fn (he: HELEMENT, p_parent_he: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterGetElementHtmlCB: extern "system" fn (he: HELEMENT, outer: BOOL, rcv: LPCBYTE_RECEIVER, rcv_param: LPVOID) -> SCDOM_RESULT,
pub SciterGetElementTextCB: extern "system" fn (he: HELEMENT, rcv: LPCWSTR_RECEIVER, rcv_param: LPVOID) -> SCDOM_RESULT,
pub SciterSetElementText: extern "system" fn (he: HELEMENT, utf16: LPCWSTR, length: UINT) -> SCDOM_RESULT,
pub SciterGetAttributeCount: extern "system" fn (he: HELEMENT, p_count: LPUINT) -> SCDOM_RESULT,
pub SciterGetNthAttributeNameCB: extern "system" fn (he: HELEMENT, n: UINT, rcv: LPCSTR_RECEIVER, rcv_param: LPVOID) -> SCDOM_RESULT,
pub SciterGetNthAttributeValueCB: extern "system" fn (he: HELEMENT, n: UINT, rcv: LPCWSTR_RECEIVER, rcv_param: LPVOID) -> SCDOM_RESULT,
pub SciterGetAttributeByNameCB: extern "system" fn (he: HELEMENT, name: LPCSTR, rcv: LPCWSTR_RECEIVER, rcv_param: LPVOID) -> SCDOM_RESULT,
pub SciterSetAttributeByName: extern "system" fn (he: HELEMENT, name: LPCSTR, value: LPCWSTR) -> SCDOM_RESULT,
pub SciterClearAttributes: extern "system" fn (he: HELEMENT) -> SCDOM_RESULT,
pub SciterGetElementIndex: extern "system" fn (he: HELEMENT, p_index: LPUINT) -> SCDOM_RESULT,
pub SciterGetElementType: extern "system" fn (he: HELEMENT, p_type: * mut LPCSTR) -> SCDOM_RESULT,
pub SciterGetElementTypeCB: extern "system" fn (he: HELEMENT, rcv: LPCSTR_RECEIVER, rcv_param: LPVOID) -> SCDOM_RESULT,
pub SciterGetStyleAttributeCB: extern "system" fn (he: HELEMENT, name: LPCSTR, rcv: LPCWSTR_RECEIVER, rcv_param: LPVOID) -> SCDOM_RESULT,
pub SciterSetStyleAttribute: extern "system" fn (he: HELEMENT, name: LPCSTR, value: LPCWSTR) -> SCDOM_RESULT,
pub SciterGetElementLocation: extern "system" fn (he: HELEMENT, p_location: LPRECT, areas: UINT /*ELEMENT_AREAS*/) -> SCDOM_RESULT,
pub SciterScrollToView: extern "system" fn (he: HELEMENT, SciterScrollFlags: UINT) -> SCDOM_RESULT,
pub SciterUpdateElement: extern "system" fn (he: HELEMENT, andForceRender: BOOL) -> SCDOM_RESULT,
pub SciterRefreshElementArea: extern "system" fn (he: HELEMENT, rc: RECT) -> SCDOM_RESULT,
pub SciterSetCapture: extern "system" fn (he: HELEMENT) -> SCDOM_RESULT,
pub SciterReleaseCapture: extern "system" fn (he: HELEMENT) -> SCDOM_RESULT,
pub SciterGetElementHwnd: extern "system" fn (he: HELEMENT, p_hwnd: * mut HWINDOW, rootWindow: BOOL) -> SCDOM_RESULT,
pub SciterCombineURL: extern "system" fn (he: HELEMENT, szUrlBuffer: LPWSTR, UrlBufferSize: UINT) -> SCDOM_RESULT,
pub SciterSelectElements: extern "system" fn (he: HELEMENT, CSS_selectors: LPCSTR, callback: SciterElementCallback, param: LPVOID) -> SCDOM_RESULT,
pub SciterSelectElementsW: extern "system" fn (he: HELEMENT, CSS_selectors: LPCWSTR, callback: SciterElementCallback, param: LPVOID) -> SCDOM_RESULT,
pub SciterSelectParent: extern "system" fn (he: HELEMENT, selector: LPCSTR, depth: UINT, heFound: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterSelectParentW: extern "system" fn (he: HELEMENT, selector: LPCWSTR, depth: UINT, heFound: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterSetElementHtml: extern "system" fn (he: HELEMENT, html: * const BYTE, htmlLength: UINT, how: UINT) -> SCDOM_RESULT,
pub SciterGetElementUID: extern "system" fn (he: HELEMENT, puid: * mut UINT) -> SCDOM_RESULT,
pub SciterGetElementByUID: extern "system" fn (hwnd: HWINDOW, uid: UINT, phe: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterShowPopup: extern "system" fn (hePopup: HELEMENT, heAnchor: HELEMENT, placement: UINT) -> SCDOM_RESULT,
pub SciterShowPopupAt: extern "system" fn (hePopup: HELEMENT, pos: POINT, placement: UINT) -> SCDOM_RESULT,
pub SciterHidePopup: extern "system" fn (he: HELEMENT) -> SCDOM_RESULT,
pub SciterGetElementState: extern "system" fn (he: HELEMENT, pstateBits: * mut UINT) -> SCDOM_RESULT,
pub SciterSetElementState: extern "system" fn (he: HELEMENT, stateBitsToSet: UINT, stateBitsToClear: UINT, updateView: BOOL) -> SCDOM_RESULT,
pub SciterCreateElement: extern "system" fn (tagname: LPCSTR, textOrNull: LPCWSTR, /*out*/ phe: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterCloneElement: extern "system" fn (he: HELEMENT, /*out*/ phe: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterInsertElement: extern "system" fn (he: HELEMENT, hparent: HELEMENT, index: UINT) -> SCDOM_RESULT,
pub SciterDetachElement: extern "system" fn (he: HELEMENT) -> SCDOM_RESULT,
pub SciterDeleteElement: extern "system" fn (he: HELEMENT) -> SCDOM_RESULT,
pub SciterSetTimer: extern "system" fn (he: HELEMENT, milliseconds: UINT, timer_id: UINT_PTR) -> SCDOM_RESULT,
pub SciterDetachEventHandler: extern "system" fn (he: HELEMENT, pep: ElementEventProc, tag: LPVOID) -> SCDOM_RESULT,
pub SciterAttachEventHandler: extern "system" fn (he: HELEMENT, pep: ElementEventProc, tag: LPVOID) -> SCDOM_RESULT,
pub SciterWindowAttachEventHandler: extern "system" fn (hwndLayout: HWINDOW, pep: ElementEventProc, tag: LPVOID, subscription: UINT) -> SCDOM_RESULT,
pub SciterWindowDetachEventHandler: extern "system" fn (hwndLayout: HWINDOW, pep: ElementEventProc, tag: LPVOID) -> SCDOM_RESULT,
pub SciterSendEvent: extern "system" fn (he: HELEMENT, appEventCode: UINT, heSource: HELEMENT, reason: UINT_PTR, /*out*/ handled: * mut BOOL) -> SCDOM_RESULT,
pub SciterPostEvent: extern "system" fn (he: HELEMENT, appEventCode: UINT, heSource: HELEMENT, reason: UINT_PTR) -> SCDOM_RESULT,
pub SciterCallBehaviorMethod: extern "system" fn (he: HELEMENT, params: * const METHOD_PARAMS) -> SCDOM_RESULT,
pub SciterRequestElementData: extern "system" fn (he: HELEMENT, url: LPCWSTR, dataType: UINT, initiator: HELEMENT) -> SCDOM_RESULT,
pub SciterHttpRequest: extern "system" fn (he: HELEMENT, url: LPCWSTR, dataType: UINT, requestType: UINT, requestParams: * const REQUEST_PARAM, nParams: UINT) -> SCDOM_RESULT,
pub SciterGetScrollInfo: extern "system" fn (he: HELEMENT, scrollPos: LPPOINT, viewRect: LPRECT, contentSize: LPSIZE) -> SCDOM_RESULT,
pub SciterSetScrollPos: extern "system" fn (he: HELEMENT, scrollPos: POINT, smooth: BOOL) -> SCDOM_RESULT,
pub SciterGetElementIntrinsicWidths: extern "system" fn (he: HELEMENT, pMinWidth: * mut INT, pMaxWidth: * mut INT) -> SCDOM_RESULT,
pub SciterGetElementIntrinsicHeight: extern "system" fn (he: HELEMENT, forWidth: INT, pHeight: * mut INT) -> SCDOM_RESULT,
pub SciterIsElementVisible: extern "system" fn (he: HELEMENT, pVisible: * mut BOOL) -> SCDOM_RESULT,
pub SciterIsElementEnabled: extern "system" fn (he: HELEMENT, pEnabled: * mut BOOL) -> SCDOM_RESULT,
pub SciterSortElements: extern "system" fn (he: HELEMENT, firstIndex: UINT, lastIndex: UINT, cmpFunc: * mut ELEMENT_COMPARATOR, cmpFuncParam: LPVOID) -> SCDOM_RESULT,
pub SciterSwapElements: extern "system" fn (he1: HELEMENT, he2: HELEMENT) -> SCDOM_RESULT,
pub SciterTraverseUIEvent: extern "system" fn (evt: UINT, eventCtlStruct: LPVOID, bOutProcessed: * mut BOOL) -> SCDOM_RESULT,
pub SciterCallScriptingMethod: extern "system" fn (he: HELEMENT, name: LPCSTR, argv: * const VALUE, argc: UINT, retval: * mut VALUE) -> SCDOM_RESULT,
pub SciterCallScriptingFunction: extern "system" fn (he: HELEMENT, name: LPCSTR, argv: * const VALUE, argc: UINT, retval: * mut VALUE) -> SCDOM_RESULT,
pub SciterEvalElementScript: extern "system" fn (he: HELEMENT, script: LPCWSTR, scriptLength: UINT, retval: * mut VALUE) -> SCDOM_RESULT,
pub SciterAttachHwndToElement: extern "system" fn (he: HELEMENT, hwnd: HWINDOW) -> SCDOM_RESULT,
pub SciterControlGetType: extern "system" fn (he: HELEMENT, /*CTL_TYPE*/ pType: * mut UINT) -> SCDOM_RESULT,
pub SciterGetValue: extern "system" fn (he: HELEMENT, pval: * mut VALUE) -> SCDOM_RESULT,
pub SciterSetValue: extern "system" fn (he: HELEMENT, pval: * const VALUE) -> SCDOM_RESULT,
pub SciterGetExpando: extern "system" fn (he: HELEMENT, pval: * mut VALUE, forceCreation: BOOL) -> SCDOM_RESULT,
#[deprecated(since="Sciter 4.4.3.24", note="TIScript native API is gone, use SOM instead.")]
pub SciterGetObject: extern "system" fn (he: HELEMENT, pval: * mut tiscript_value, forceCreation: BOOL) -> SCDOM_RESULT,
#[deprecated(since="Sciter 4.4.3.24", note="TIScript native API is gone, use SOM instead.")]
pub SciterGetElementNamespace: extern "system" fn (he: HELEMENT, pval: * mut tiscript_value) -> SCDOM_RESULT,
pub SciterGetHighlightedElement: extern "system" fn (hwnd: HWINDOW, phe: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterSetHighlightedElement: extern "system" fn (hwnd: HWINDOW, he: HELEMENT) -> SCDOM_RESULT,
//|
//| DOM Node API
//|
pub SciterNodeAddRef: extern "system" fn (hn: HNODE) -> SCDOM_RESULT,
pub SciterNodeRelease: extern "system" fn (hn: HNODE) -> SCDOM_RESULT,
pub SciterNodeCastFromElement: extern "system" fn (he: HELEMENT, phn: * mut HNODE) -> SCDOM_RESULT,
pub SciterNodeCastToElement: extern "system" fn (hn: HNODE, he: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterNodeFirstChild: extern "system" fn (hn: HNODE, phn: * mut HNODE) -> SCDOM_RESULT,
pub SciterNodeLastChild: extern "system" fn (hn: HNODE, phn: * mut HNODE) -> SCDOM_RESULT,
pub SciterNodeNextSibling: extern "system" fn (hn: HNODE, phn: * mut HNODE) -> SCDOM_RESULT,
pub SciterNodePrevSibling: extern "system" fn (hn: HNODE, phn: * mut HNODE) -> SCDOM_RESULT,
pub SciterNodeParent: extern "system" fn (hnode: HNODE, pheParent: * mut HELEMENT) -> SCDOM_RESULT,
pub SciterNodeNthChild: extern "system" fn (hnode: HNODE, n: UINT, phn: * mut HNODE) -> SCDOM_RESULT,
pub SciterNodeChildrenCount: extern "system" fn (hnode: HNODE, pn: * mut UINT) -> SCDOM_RESULT,
pub SciterNodeType: extern "system" fn (hnode: HNODE, pNodeType: * mut UINT /*NODE_TYPE*/) -> SCDOM_RESULT,
pub SciterNodeGetText: extern "system" fn (hnode: HNODE, rcv: * mut LPCWSTR_RECEIVER, rcv_param: LPVOID) -> SCDOM_RESULT,
pub SciterNodeSetText: extern "system" fn (hnode: HNODE, text: LPCWSTR, textLength: UINT) -> SCDOM_RESULT,
pub SciterNodeInsert: extern "system" fn (hnode: HNODE, how: UINT /*NODE_INS_TARGET*/, what: HNODE) -> SCDOM_RESULT,
pub SciterNodeRemove: extern "system" fn (hnode: HNODE, finalize: BOOL) -> SCDOM_RESULT,
pub SciterCreateTextNode: extern "system" fn (text: LPCWSTR, textLength: UINT, phnode: * mut HNODE) -> SCDOM_RESULT,
pub SciterCreateCommentNode: extern "system" fn (text: LPCWSTR, textLength: UINT, phnode: * mut HNODE) -> SCDOM_RESULT,
//|
//| Value API
//|
pub ValueInit: extern "system" fn (pval: * mut VALUE) -> VALUE_RESULT,
pub ValueClear: extern "system" fn (pval: * mut VALUE) -> VALUE_RESULT,
pub ValueCompare: extern "system" fn (pval1: * const VALUE, pval2: * const VALUE) -> VALUE_RESULT,
pub ValueCopy: extern "system" fn (pdst: * mut VALUE, psrc: * const VALUE) -> VALUE_RESULT,
pub ValueIsolate: extern "system" fn (pdst: * mut VALUE) -> VALUE_RESULT,
pub ValueType: extern "system" fn (pval: * const VALUE, pType: * mut UINT, pUnits: * mut UINT) -> VALUE_RESULT,
pub ValueStringData: extern "system" fn (pval: * const VALUE, pChars: * mut LPCWSTR, pNumChars: * mut UINT) -> VALUE_RESULT,
pub ValueStringDataSet: extern "system" fn (pval: * mut VALUE, chars: LPCWSTR, numChars: UINT, units: UINT) -> VALUE_RESULT,
pub ValueIntData: extern "system" fn (pval: * const VALUE, pData: * mut INT) -> VALUE_RESULT,
pub ValueIntDataSet: extern "system" fn (pval: * mut VALUE, data: INT, vtype: UINT, units: UINT) -> VALUE_RESULT,
pub ValueInt64Data: extern "system" fn (pval: * const VALUE, pData: * mut INT64) -> VALUE_RESULT,
pub ValueInt64DataSet: extern "system" fn (pval: * mut VALUE, data: INT64, vtype: UINT, units: UINT) -> VALUE_RESULT,
pub ValueFloatData: extern "system" fn (pval: * const VALUE, pData: * mut FLOAT_VALUE) -> VALUE_RESULT,
pub ValueFloatDataSet: extern "system" fn (pval: * mut VALUE, data: FLOAT_VALUE, vtype: UINT, units: UINT) -> VALUE_RESULT,
pub ValueBinaryData: extern "system" fn (pval: * const VALUE, pBytes: * mut LPCBYTE, pnBytes: * mut UINT) -> VALUE_RESULT,
pub ValueBinaryDataSet: extern "system" fn (pval: * mut VALUE, pBytes: LPCBYTE, nBytes: UINT, vtype: UINT, units: UINT) -> VALUE_RESULT,
pub ValueElementsCount: extern "system" fn (pval: * const VALUE, pn: * mut INT) -> VALUE_RESULT,
pub ValueNthElementValue: extern "system" fn (pval: * const VALUE, n: INT, pretval: * mut VALUE) -> VALUE_RESULT,
pub ValueNthElementValueSet: extern "system" fn (pval: * mut VALUE, n: INT, pval_to_set: * const VALUE) -> VALUE_RESULT,
pub ValueNthElementKey: extern "system" fn (pval: * const VALUE, n: INT, pretval: * mut VALUE) -> VALUE_RESULT,
pub ValueEnumElements: extern "system" fn (pval: * const VALUE, penum: KeyValueCallback, param: LPVOID) -> VALUE_RESULT,
pub ValueSetValueToKey: extern "system" fn (pval: * mut VALUE, pkey: * const VALUE, pval_to_set: * const VALUE) -> VALUE_RESULT,
pub ValueGetValueOfKey: extern "system" fn (pval: * const VALUE, pkey: * const VALUE, pretval: * mut VALUE) -> VALUE_RESULT,
pub ValueToString: extern "system" fn (pval: * mut VALUE, how: VALUE_STRING_CVT_TYPE) -> VALUE_RESULT,
pub ValueFromString: extern "system" fn (pval: * mut VALUE, str: LPCWSTR, strLength: UINT, how: VALUE_STRING_CVT_TYPE) -> UINT,
pub ValueInvoke: extern "system" fn (pval: * const VALUE, pthis: * mut VALUE, argc: UINT, argv: * const VALUE, pretval: * mut VALUE, url: LPCWSTR) -> VALUE_RESULT,
pub ValueNativeFunctorSet: extern "system" fn (pval: * mut VALUE, pinvoke: NATIVE_FUNCTOR_INVOKE, prelease: NATIVE_FUNCTOR_RELEASE, tag: LPVOID) -> VALUE_RESULT,
pub ValueIsNativeFunctor: extern "system" fn (pval: * const VALUE) -> BOOL,
// tiscript VM API
#[deprecated(since="Sciter 4.4.3.24", note="TIScript native API is gone, use SOM instead.")]
pub TIScriptAPI: extern "system" fn () -> * mut tiscript_native_interface,
#[deprecated(since="Sciter 4.4.3.24", note="TIScript native API is gone, use SOM instead.")]
pub SciterGetVM: extern "system" fn (hwnd: HWINDOW) -> HVM,
// since 3.1.0.12
#[deprecated(since="Sciter 4.4.3.24", note="TIScript native API is gone, use SOM instead.")]
pub Sciter_v2V: extern "system" fn (vm: HVM, script_value: tiscript_value, value: * mut VALUE, isolate: BOOL) -> BOOL,
#[deprecated(since="Sciter 4.4.3.24", note="TIScript native API is gone, use SOM instead.")]
pub Sciter_V2v: extern "system" fn (vm: HVM, valuev: * const VALUE, script_value: * mut tiscript_value) -> BOOL,
// since 3.1.0.18
pub SciterOpenArchive: extern "system" fn (archiveData: LPCBYTE, archiveDataLength: UINT) -> HSARCHIVE,
pub SciterGetArchiveItem: extern "system" fn (harc: HSARCHIVE, path: LPCWSTR, pdata: * mut LPCBYTE, pdataLength: * mut UINT) -> BOOL,
pub SciterCloseArchive: extern "system" fn (harc: HSARCHIVE) -> BOOL,
// since 3.2.0.0
pub SciterFireEvent: extern "system" fn (evt: * const BEHAVIOR_EVENT_PARAMS, post: BOOL, handled: * mut BOOL) -> SCDOM_RESULT,
pub SciterGetCallbackParam: extern "system" fn (hwnd: HWINDOW) -> LPVOID,
pub SciterPostCallback: extern "system" fn (hwnd: HWINDOW, wparam: UINT_PTR, lparam: UINT_PTR, timeoutms: UINT) -> UINT_PTR,
// since 3.3.1.0
pub GetSciterGraphicsAPI: extern "system" fn () -> * const SciterGraphicsAPI,
// since 3.3.1.6
pub GetSciterRequestAPI: extern "system" fn () -> * const SciterRequestAPI,
// #ifdef WINDOWS
// since 3.3.1.4
#[cfg(all(windows, not(feature = "windowless")))]
pub SciterCreateOnDirectXWindow: extern "system" fn (hwnd: HWINDOW, pSwapChain: * mut IDXGISwapChain) -> BOOL,
#[cfg(all(windows, not(feature = "windowless")))]
pub SciterRenderOnDirectXWindow: extern "system" fn (hwnd: HWINDOW, elementToRenderOrNull: HELEMENT, frontLayer: BOOL) -> BOOL,
#[cfg(all(windows, not(feature = "windowless")))]
pub SciterRenderOnDirectXTexture: extern "system" fn (hwnd: HWINDOW, elementToRenderOrNull: HELEMENT, surface: * mut IDXGISurface) -> BOOL,
// #endif
// since 4.0.0.0
pub SciterProcX: extern "system" fn(hwnd: HWINDOW, msg: * const SCITER_X_MSG) -> BOOL,
// since 4.4.2.14
pub SciterAtomValue: extern "system" fn(name: LPCSTR) -> UINT64,
pub SciterAtomNameCB: extern "system" fn(atomv: UINT64, rcv: LPCSTR_RECEIVER, rcv_param: LPVOID) -> BOOL,
// since 4.4.2.16
pub SciterSetGlobalAsset: extern "system" fn(pass: *mut som_asset_t) -> BOOL,
}

View File

@ -1,543 +0,0 @@
//! C interface for behaviors support (a.k.a windowless controls).
#![allow(non_camel_case_types, non_snake_case)]
#![allow(dead_code)]
use capi::sctypes::*;
use capi::scdom::*;
use capi::scvalue::{VALUE};
use capi::scgraphics::{HGFX};
use capi::scom::{som_asset_t, som_passport_t};
#[repr(C)]
pub struct BEHAVIOR_EVENT_PARAMS
{
/// Behavior event code. See [`BEHAVIOR_EVENTS`](enum.BEHAVIOR_EVENTS.html).
pub cmd: UINT,
/// Target element handler.
pub heTarget: HELEMENT,
/// Source element.
pub he: HELEMENT,
/// UI action causing change.
pub reason: UINT_PTR,
/// Auxiliary data accompanied with the event.
pub data: VALUE,
/// Name of the custom event (when `cmd` is [`BEHAVIOR_EVENTS::CUSTOM`](enum.BEHAVIOR_EVENTS.html#variant.CUSTOM)).
/// Since 4.2.8.
pub name: LPCWSTR,
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
pub enum INITIALIZATION_EVENTS
{
BEHAVIOR_DETACH = 0,
BEHAVIOR_ATTACH = 1,
}
#[repr(C)]
pub struct INITIALIZATION_PARAMS
{
pub cmd: INITIALIZATION_EVENTS,
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
pub enum SOM_EVENTS
{
SOM_GET_PASSPORT = 0,
SOM_GET_ASSET = 1,
}
#[repr(C)]
pub union SOM_PARAMS_DATA
{
pub asset: *const som_asset_t,
pub passport: *const som_passport_t,
}
#[repr(C)]
pub struct SOM_PARAMS
{
pub cmd: SOM_EVENTS,
pub result: SOM_PARAMS_DATA,
}
/// Identifiers of methods currently supported by intrinsic behaviors.
#[repr(C)]
#[derive(Debug)]
pub enum BEHAVIOR_METHOD_IDENTIFIERS {
/// Raise a click event.
DO_CLICK = 1,
/// `IS_EMPTY_PARAMS::is_empty` reflects the `:empty` state of the element.
IS_EMPTY = 0xFC,
/// `VALUE_PARAMS`
GET_VALUE = 0xFD,
/// `VALUE_PARAMS`
SET_VALUE = 0xFE,
/// User method identifier used in custom behaviors.
///
/// All custom event codes shall be greater than this number.
/// All codes below this will be used solely by application - Sciter will not intrepret it
/// and will do just dispatching. To send event notifications with these codes use
/// `SciterCallBehaviorMethod` API.
FIRST_APPLICATION_METHOD_ID = 0x100,
}
/// Method arguments used in `SciterCallBehaviorMethod()` or `HANDLE_METHOD_CALL`.
#[repr(C)]
pub struct METHOD_PARAMS {
/// [`BEHAVIOR_METHOD_IDENTIFIERS`](enum.BEHAVIOR_METHOD_IDENTIFIERS.html) or user identifiers.
pub method: UINT,
}
#[repr(C)]
pub struct IS_EMPTY_PARAMS {
pub method: UINT,
pub is_empty: UINT,
}
#[repr(C)]
pub struct VALUE_PARAMS {
pub method: UINT,
pub value: VALUE,
}
#[repr(C)]
pub struct SCRIPTING_METHOD_PARAMS
{
pub name: LPCSTR,
pub argv: *const VALUE,
pub argc: UINT,
pub result: VALUE,
}
#[repr(C)]
pub struct TIMER_PARAMS
{
pub timerId: UINT_PTR,
}
#[repr(C)]
pub struct DRAW_PARAMS {
/// Element layer to draw.
pub layer: DRAW_EVENTS,
/// Graphics context.
pub gfx: HGFX,
/// Element area.
pub area: RECT,
/// Zero at the moment.
pub reserved: UINT,
}
/// Layer to draw.
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialEq)]
pub enum DRAW_EVENTS {
DRAW_BACKGROUND = 0,
DRAW_CONTENT,
DRAW_FOREGROUND,
/// Note: since 4.2.3.
DRAW_OUTLINE,
}
/// Event groups for subscription.
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
pub enum EVENT_GROUPS
{ /// Attached/detached.
HANDLE_INITIALIZATION = 0x0000,
/// Mouse events.
HANDLE_MOUSE = 0x0001,
/// Key events.
HANDLE_KEY = 0x0002,
/// Focus events, if this flag is set it also means that element it attached to is focusable.
HANDLE_FOCUS = 0x0004,
/// Scroll events.
HANDLE_SCROLL = 0x0008,
/// Timer event.
HANDLE_TIMER = 0x0010,
/// Size changed event.
HANDLE_SIZE = 0x0020,
/// Drawing request (event).
HANDLE_DRAW = 0x0040,
/// Requested data has been delivered.
HANDLE_DATA_ARRIVED = 0x080,
/// Logical, synthetic events:
/// `BUTTON_CLICK`, `HYPERLINK_CLICK`, etc.,
/// a.k.a. notifications from intrinsic behaviors.
HANDLE_BEHAVIOR_EVENT = 0x0100,
/// Behavior specific methods.
HANDLE_METHOD_CALL = 0x0200,
/// Behavior specific methods.
HANDLE_SCRIPTING_METHOD_CALL = 0x0400,
/// Behavior specific methods using direct `tiscript::value`'s.
#[deprecated(since="Sciter 4.4.3.24", note="TIScript native API is gone, use SOM instead.")]
HANDLE_TISCRIPT_METHOD_CALL = 0x0800,
/// System drag-n-drop.
HANDLE_EXCHANGE = 0x1000,
/// Touch input events.
HANDLE_GESTURE = 0x2000,
/// SOM passport and asset requests.
HANDLE_SOM = 0x8000,
/// All of them.
HANDLE_ALL = 0xFFFF,
/// Special value for getting subscription flags.
SUBSCRIPTIONS_REQUEST = -1,
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
/// Event propagation schema.
pub enum PHASE_MASK
{
/// Bubbling phase direction: from a child element to all its containers.
BUBBLING = 0,
/// Sinking phase direction: from containers to target child element.
SINKING = 0x0_8000,
/// Bubbling event consumed by some child.
BUBBLING_HANDLED= 0x1_0000,
/// Sinking event consumed by some child.
SINKING_HANDLED = 0x1_8000,
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
/// Mouse buttons.
pub enum MOUSE_BUTTONS
{
NONE = 0,
/// Left button.
MAIN = 1,
/// Right button.
PROP = 2,
/// Middle button.
MIDDLE = 3,
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
/// Keyboard modifier buttons state.
pub enum KEYBOARD_STATES
{
CONTROL_KEY_PRESSED = 0x01,
SHIFT_KEY_PRESSED = 0x02,
ALT_KEY_PRESSED = 0x04,
}
impl std::convert::From<u32> for KEYBOARD_STATES {
fn from(u: u32) -> Self {
unsafe { std::mem::transmute(u) }
}
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
/// Keyboard input events.
pub enum KEY_EVENTS
{
KEY_DOWN = 0,
KEY_UP,
KEY_CHAR,
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
/// Mouse events.
pub enum MOUSE_EVENTS
{
MOUSE_ENTER = 0,
MOUSE_LEAVE,
MOUSE_MOVE,
MOUSE_UP,
MOUSE_DOWN,
MOUSE_DCLICK,
MOUSE_WHEEL,
/// mouse pressed ticks
MOUSE_TICK,
/// mouse stay idle for some time
MOUSE_IDLE,
/// item dropped, target is that dropped item
DROP = 9,
/// drag arrived to the target element that is one of current drop targets.
DRAG_ENTER = 0xA,
/// drag left one of current drop targets. target is the drop target element.
DRAG_LEAVE = 0xB,
/// drag src notification before drag start. To cancel - return true from handler.
DRAG_REQUEST = 0xC,
/// mouse click event
MOUSE_CLICK = 0xFF,
/// This flag is `OR`ed with `MOUSE_ENTER..MOUSE_DOWN` codes if dragging operation is in effect.
/// E.g. event `DRAGGING | MOUSE_MOVE` is sent to underlying DOM elements while dragging.
DRAGGING = 0x100,
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
#[allow(missing_docs)]
/// General event source triggers
pub enum CLICK_REASON
{
/// By mouse button.
BY_MOUSE_CLICK,
/// By keyboard (e.g. spacebar).
BY_KEY_CLICK,
/// Synthesized, by code.
SYNTHESIZED,
/// Icon click, e.g. arrow icon on drop-down select.
BY_MOUSE_ON_ICON,
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
/// Edit control change trigger.
pub enum EDIT_CHANGED_REASON
{
/// Single char insertion.
BY_INS_CHAR,
/// Character range insertion, clipboard.
BY_INS_CHARS,
/// Single char deletion.
BY_DEL_CHAR,
/// Character range (selection) deletion.
BY_DEL_CHARS,
/// Undo/redo.
BY_UNDO_REDO,
/// Single char insertion, previous character was inserted in previous position.
CHANGE_BY_INS_CONSECUTIVE_CHAR,
/// Single char removal, previous character was removed in previous position
CHANGE_BY_DEL_CONSECUTIVE_CHAR,
CHANGE_BY_CODE,
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug, PartialOrd, PartialEq)]
/// Behavior event codes.
pub enum BEHAVIOR_EVENTS
{
/// click on button
BUTTON_CLICK = 0,
/// mouse down or key down in button
BUTTON_PRESS,
/// checkbox/radio/slider changed its state/value
BUTTON_STATE_CHANGED,
/// before text change
EDIT_VALUE_CHANGING,
/// after text change
EDIT_VALUE_CHANGED,
/// selection in `<select>` changed
SELECT_SELECTION_CHANGED,
/// node in select expanded/collapsed, heTarget is the node
SELECT_STATE_CHANGED,
/// request to show popup just received,
/// here DOM of popup element can be modifed.
POPUP_REQUEST,
/// popup element has been measured and ready to be shown on screen,
/// here you can use functions like `ScrollToView`.
POPUP_READY,
/// popup element is closed,
/// here DOM of popup element can be modifed again - e.g. some items can be removed to free memory.
POPUP_DISMISSED,
/// menu item activated by mouse hover or by keyboard,
MENU_ITEM_ACTIVE,
/// menu item click,
/// BEHAVIOR_EVENT_PARAMS structure layout
/// BEHAVIOR_EVENT_PARAMS.cmd - MENU_ITEM_CLICK/MENU_ITEM_ACTIVE
/// BEHAVIOR_EVENT_PARAMS.heTarget - owner(anchor) of the menu
/// BEHAVIOR_EVENT_PARAMS.he - the menu item, presumably `<li>` element
/// BEHAVIOR_EVENT_PARAMS.reason - BY_MOUSE_CLICK | BY_KEY_CLICK
MENU_ITEM_CLICK,
/// "right-click", BEHAVIOR_EVENT_PARAMS::he is current popup menu `HELEMENT` being processed or `NULL`.
/// application can provide its own `HELEMENT` here (if it is `NULL`) or modify current menu element.
CONTEXT_MENU_REQUEST = 0x10,
/// broadcast notification, sent to all elements of some container being shown or hidden
VISIUAL_STATUS_CHANGED,
/// broadcast notification, sent to all elements of some container that got new value of `:disabled` state
DISABLED_STATUS_CHANGED,
/// popup is about to be closed
POPUP_DISMISSING,
/// content has been changed, is posted to the element that gets content changed, reason is combination of `CONTENT_CHANGE_BITS`.
/// `target == NULL` means the window got new document and this event is dispatched only to the window.
CONTENT_CHANGED = 0x15,
/// generic click
CLICK = 0x16,
/// generic change
CHANGE = 0x17,
/// media changed (screen resolution, number of displays, etc.)
MEDIA_CHANGED = 0x18,
/// input language has changed, data is iso lang-country string
INPUT_LANGUAGE_CHANGED = 0x19,
/// editable content has changed
CONTENT_MODIFIED = 0x1A,
/// a broadcast notification being posted to all elements of some container
/// that changes its `:read-only` state.
READONLY_STATUS_CHANGED = 0x1B,
/// change in `aria-live="polite|assertive"`
ARIA_LIVE_AREA_CHANGED = 0x1C,
// "grey" event codes - notfications from behaviors from this SDK
/// hyperlink click
HYPERLINK_CLICK = 0x80,
PASTE_TEXT = 0x8E,
PASTE_HTML = 0x8F,
/// element was collapsed, so far only `behavior:tabs` is sending these two to the panels
ELEMENT_COLLAPSED = 0x90,
/// element was expanded,
ELEMENT_EXPANDED,
/// activate (select) child,
/// used, for example, by `accesskeys` behaviors to send activation request, e.g. tab on `behavior:tabs`.
ACTIVATE_CHILD,
/// ui state changed, observers shall update their visual states.
/// is sent, for example, by `behavior:richtext` when caret position/selection has changed.
UI_STATE_CHANGED = 0x95,
/// `behavior:form` detected submission event. `BEHAVIOR_EVENT_PARAMS::data` field contains data to be posted.
/// `BEHAVIOR_EVENT_PARAMS::data` is of type `T_MAP` in this case key/value pairs of data that is about
/// to be submitted. You can modify the data or discard submission by returning true from the handler.
FORM_SUBMIT,
/// `behavior:form` detected reset event (from `button type=reset`). `BEHAVIOR_EVENT_PARAMS::data` field contains data to be reset.
/// `BEHAVIOR_EVENT_PARAMS::data` is of type `T_MAP` in this case key/value pairs of data that is about
/// to be rest. You can modify the data or discard reset by returning true from the handler.
FORM_RESET,
/// document in `behavior:frame` or root document is complete.
DOCUMENT_COMPLETE,
/// requests to `behavior:history` (commands)
HISTORY_PUSH,
HISTORY_DROP,
HISTORY_PRIOR,
HISTORY_NEXT,
/// `behavior:history` notification - history stack has changed
HISTORY_STATE_CHANGED,
/// close popup request,
CLOSE_POPUP,
/// request tooltip, `evt.source` <- is the tooltip element.
TOOLTIP_REQUEST,
/// animation started (`reason=1`) or ended(`reason=0`) on the element.
ANIMATION = 0xA0,
/// document created, script namespace initialized. `target` -> the document
DOCUMENT_CREATED = 0xC0,
/// document is about to be closed, to cancel closing do: `evt.data = sciter::Value("cancel")`;
DOCUMENT_CLOSE_REQUEST,
/// last notification before document removal from the DOM
DOCUMENT_CLOSE,
/// document has got DOM structure, styles and behaviors of DOM elements. Script loading run is complete at this moment.
DOCUMENT_READY,
/// document just finished parsing - has got DOM structure. This event is generated before the `DOCUMENT_READY`.
/// Since 4.0.3.
DOCUMENT_PARSED = 0xC4,
/// `<video>` "ready" notification
VIDEO_INITIALIZED = 0xD1,
/// `<video>` playback started notification
VIDEO_STARTED,
/// `<video>` playback stoped/paused notification
VIDEO_STOPPED,
/// `<video>` request for frame source binding,
/// If you want to provide your own video frames source for the given target `<video>` element do the following:
///
/// 1. Handle and consume this `VIDEO_BIND_RQ` request
/// 2. You will receive second `VIDEO_BIND_RQ` request/event for the same `<video>` element
/// but this time with the `reason` field set to an instance of `sciter::video_destination` interface.
/// 3. `add_ref()` it and store it, for example, in a worker thread producing video frames.
/// 4. call `sciter::video_destination::start_streaming(...)` providing needed parameters
/// call `sciter::video_destination::render_frame(...)` as soon as they are available
/// call `sciter::video_destination::stop_streaming()` to stop the rendering (a.k.a. end of movie reached)
VIDEO_BIND_RQ,
/// `behavior:pager` starts pagination
PAGINATION_STARTS = 0xE0,
/// `behavior:pager` paginated page no, reason -> page no
PAGINATION_PAGE,
/// `behavior:pager` end pagination, reason -> total pages
PAGINATION_ENDS,
/// event with custom name.
/// Since 4.2.8.
CUSTOM = 0xF0,
/// SSX, delayed mount_component
MOUNT_COMPONENT = 0xF1,
/// all custom event codes shall be greater than this number. All codes below this will be used
/// solely by application - Sciter will not intrepret it and will do just dispatching.
/// To send event notifications with these codes use `SciterSend`/`PostEvent` API.
FIRST_APPLICATION_EVENT_CODE = 0x100,
}
impl ::std::ops::BitOr for EVENT_GROUPS {
type Output = EVENT_GROUPS;
fn bitor(self, rhs: Self::Output) -> Self::Output {
let rn = (self as UINT) | (rhs as UINT);
unsafe { ::std::mem::transmute(rn) }
}
}

View File

@ -1,388 +0,0 @@
//! Common Sciter declarations.
#![allow(non_camel_case_types, non_snake_case)]
#![allow(dead_code)]
use capi::sctypes::*;
use capi::scvalue::{VALUE};
use capi::screquest::{HREQUEST};
use capi::scdom::{HELEMENT};
use capi::scapi::ISciterAPI;
//////////////////////////////////////////////////////////////////////////////////
pub enum ID2D1RenderTarget {}
pub enum ID2D1Factory {}
pub enum IDWriteFactory {}
pub enum IDXGISwapChain {}
pub enum IDXGISurface {}
#[repr(C)]
#[derive(Debug, PartialOrd, PartialEq)]
/// `HostHandler::on_data_load()` result code.
///
/// This notification gives application a chance to override built-in loader and
/// implement loading of resources in its own way (for example, images can be loaded from
/// a database or other resource).
pub enum LOAD_RESULT {
/// Do the default loading if data is not set.
LOAD_DEFAULT,
/// Discard the request completely (data will not be loaded at the document).
LOAD_DISCARD,
/// Data will be delivered later by the host application.
LOAD_DELAYED,
/// You return this result to indicate that your (the host) application took or
/// will take care about `HREQUEST` in your code completely.
LOAD_MYSELF,
}
/// Script runtime options.
#[repr(C)]
#[derive(Debug)]
#[allow(missing_docs)]
pub enum SCRIPT_RUNTIME_FEATURES
{
ALLOW_FILE_IO = 0x1,
ALLOW_SOCKET_IO = 0x2,
ALLOW_EVAL = 0x4,
ALLOW_SYSINFO = 0x8,
}
/// Sciter graphics rendering backend.
#[repr(C)]
#[derive(Debug)]
#[derive(Copy, Clone)]
#[allow(missing_docs)]
pub enum GFX_LAYER
{
/// An auto-selected backend.
AUTO = 0xFFFF,
/// Depends on OS: GDI, Cairo or CoreGraphics.
CPU = 1,
/// A software rasterizer for Direct2D (Windows only).
#[cfg(windows)]
WARP = 2,
/// A hardware Direct2D mode (Windows only).
#[cfg(windows)]
D2D = 3,
/// Skia backend with CPU rasterization mode.
SKIA_CPU = 4,
/// Skia backend with OpenGL rendering.
SKIA_OPENGL = 5,
}
#[repr(C)]
#[derive(Debug, PartialOrd, PartialEq)]
/// Various Sciter engine options (global or per-window).
pub enum SCITER_RT_OPTIONS
{
/// value:TRUE - enable, value:FALSE - disable, enabled by default.
SCITER_SMOOTH_SCROLL = 1,
/// global; value: milliseconds, connection timeout of http client.
SCITER_CONNECTION_TIMEOUT = 2,
/// global; value: 0 - drop connection, 1 - use builtin dialog, 2 - accept connection silently.
SCITER_HTTPS_ERROR = 3,
/// value: 0 - system default, 1 - no smoothing, 2 - std smoothing, 3 - clear type.
SCITER_FONT_SMOOTHING = 4,
/// Windows Aero support, value:
/// 0 - normal drawing,
/// 1 - window has transparent background after calls `DwmExtendFrameIntoClientArea()` or `DwmEnableBlurBehindWindow()`.
SCITER_TRANSPARENT_WINDOW = 6,
/// global; value = LPCBYTE, json - GPU black list, see: gpu-blacklist.json resource.
/// Note: is not used since Sciter 4.
#[deprecated(since="4.0.1", note="This option isn't working since Sciter 4.0.1.1.")]
SCITER_SET_GPU_BLACKLIST = 7,
/// global or per-window; value - combination of [SCRIPT_RUNTIME_FEATURES](enum.SCRIPT_RUNTIME_FEATURES.html) flags.
SCITER_SET_SCRIPT_RUNTIME_FEATURES = 8,
/// global (must be called before any window creation); value - [GFX_LAYER](enum.GFX_LAYER.html).
SCITER_SET_GFX_LAYER = 9,
/// global or per-window; value - TRUE/FALSE
SCITER_SET_DEBUG_MODE = 10,
/// global; value - BOOL, TRUE - the engine will use "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.
SCITER_SET_UX_THEMING = 11,
/// value - TRUE/FALSE - window uses per pixel alpha (e.g. `WS_EX_LAYERED`/`UpdateLayeredWindow()` window).
SCITER_ALPHA_WINDOW = 12,
/// global; value: UTF-8 encoded script source to be loaded into each view before any other script execution.
SCITER_SET_INIT_SCRIPT = 13,
/// per-window; value - TRUE/FALSE - window is main, will destroy all other dependent windows on close.
SCITER_SET_MAIN_WINDOW = 14,
/// global; value - max request length in megabytes (1024*1024 bytes).
SCITER_SET_MAX_HTTP_DATA_LENGTH = 15,
}
/// Window flags
#[repr(C)]
pub enum SCITER_CREATE_WINDOW_FLAGS {
/// child window only, if this flag is set all other flags ignored.
SW_CHILD = 1,
/// toplevel window, has titlebar.
SW_TITLEBAR = 1 << 1,
/// has resizeable frame.
SW_RESIZEABLE = 1 << 2,
/// is tool window.
SW_TOOL = 1 << 3,
/// has minimize / maximize buttons.
SW_CONTROLS = 1 << 4,
/// glassy window - "Acrylic" on Windows and "Vibrant" on macOS.
SW_GLASSY = 1 << 5,
/// transparent window (e.g. `WS_EX_LAYERED` on Windows, macOS is supported too).
SW_ALPHA = 1 << 6,
/// main window of the app, will terminate the app on close.
SW_MAIN = 1 << 7,
/// the window is created as topmost window.
SW_POPUP = 1 << 8,
/// make this window inspector ready.
SW_ENABLE_DEBUG = 1 << 9,
/// it has its own script VM.
SW_OWNS_VM = 1 << 10,
}
impl Default for SCITER_CREATE_WINDOW_FLAGS {
fn default() -> Self {
SCITER_CREATE_WINDOW_FLAGS::SW_CHILD
}
}
/// Flags can be OR'ed as `SW_MAIN|SW_ALPHA`.
impl ::std::ops::BitOr for SCITER_CREATE_WINDOW_FLAGS {
type Output = SCITER_CREATE_WINDOW_FLAGS;
fn bitor(self, rhs: Self::Output) -> Self::Output {
let rn = (self as UINT) | (rhs as UINT);
unsafe { ::std::mem::transmute(rn) }
}
}
#[repr(C)]
#[derive(Debug, PartialOrd, PartialEq)]
pub enum SCITER_NOTIFICATION {
SC_LOAD_DATA = 1,
SC_DATA_LOADED = 2,
SC_ATTACH_BEHAVIOR = 4,
SC_ENGINE_DESTROYED = 5,
SC_POSTED_NOTIFICATION = 6,
SC_GRAPHICS_CRITICAL_FAILURE = 7,
SC_KEYBOARD_REQUEST = 8,
SC_INVALIDATE_RECT = 9,
}
#[repr(C)]
#[derive(Debug, PartialEq)]
/// The type of a loaded resource.
pub enum RESOURCE_TYPE {
/// HTML document.
HTML = 0,
/// Image.
IMAGE = 1,
/// CSS.
STYLE = 2,
/// Mouse cursor image.
CURSOR = 3,
/// TIScript document.
SCRIPT = 4,
/// Any data.
RAW = 5,
/// Font.
FONT,
/// Sound (wav bytes).
SOUND,
}
/// The type of a loaded resource.
pub type SCITER_RESOURCE_TYPE = RESOURCE_TYPE;
#[repr(C)]
#[derive(Debug)]
/// Notifies that Sciter is about to download a referred resource.
pub struct SCN_LOAD_DATA
{
/// `SC_LOAD_DATA` here.
pub code: UINT,
/// `HWINDOW` of the window this callback was attached to.
pub hwnd: HWINDOW,
/// [in] Zero terminated string, fully qualified uri, for example, "http://server/folder/file.ext".
pub uri: LPCWSTR,
/// [in,out] pointer to loaded data to return. If data exists in the cache then this field contain pointer to it.
pub outData: LPCBYTE,
/// [in,out] loaded data size to return.
pub outDataSize: UINT,
/// [in] resource type category
pub dataType: RESOURCE_TYPE,
/// [in] request handle that can be used with Sciter request API.
pub request_id: HREQUEST,
/// [in] destination element for request.
pub principal: HELEMENT,
/// [in] source element for request.
pub initiator: HELEMENT,
}
#[repr(C)]
#[derive(Debug)]
/// This notification indicates that external data (for example, image) download process has been completed.
pub struct SCN_DATA_LOADED
{
/// `SC_DATA_LOADED` here.
pub code: UINT,
/// `HWINDOW` of the window this callback was attached to.
pub hwnd: HWINDOW,
/// [in] zero terminated string, fully qualified uri, for example, "http://server/folder/file.ext".
pub uri: LPCWSTR,
/// [in] pointer to loaded data.
pub data: LPCBYTE,
/// [in] loaded data size (in bytes).
pub dataSize: UINT,
/// [in] resource type category
pub dataType: RESOURCE_TYPE,
/// Download status code:
///
/// * status = 0 and `dataSize == 0` - unknown error.
/// * status = 100..505 - http response status, note: 200 - OK!
/// * status > 12000 - wininet error code, see `ERROR_INTERNET_***` in wininet.h
pub status: UINT,
}
#[repr(C)]
/// This notification is sent on parsing the document and while processing elements
/// having non empty `behavior: ` style attribute value.
pub struct SCN_ATTACH_BEHAVIOR
{
/// `SC_ATTACH_BEHAVIOR` here.
pub code: UINT,
/// `HWINDOW` of the window this callback was attached to.
pub hwnd: HWINDOW,
/// [in] target DOM element handle
pub element: HELEMENT,
/// [in] zero terminated string, string appears as value of CSS `behavior: ` attribute.
pub name: LPCSTR,
/// [out] pointer to ElementEventProc function.
pub elementProc: ElementEventProc,
/// [out] tag value, passed as is into pointer ElementEventProc function.
pub elementTag: LPVOID,
}
#[repr(C)]
/// This notification is issued when keyboard needs to be shown
/// mobiles can show soft keyboard by handling it.
pub struct SCN_KEYBOARD_REQUEST
{
/// `SC_KEYBOARD_REQUEST` here.
pub code: UINT,
/// `HWINDOW` of the window this callback was attached to.
pub hwnd: HWINDOW,
pub keyboard_mode: UINT,
}
#[repr(C)]
/// This notification is sent when a specific window area
/// needs to be redrawn.
pub struct SCN_INVALIDATE_RECT
{
/// `SC_INVALIDATE_RECT` here.
pub code: UINT,
/// `HWINDOW` of the window this callback was attached to.
pub hwnd: HWINDOW,
/// Coordinates of the invalidated area.
pub invalid_rect: RECT,
}
#[repr(C)]
pub struct SCITER_CALLBACK_NOTIFICATION
{
pub code: UINT,
pub hwnd: HWINDOW,
}
pub type LPSCITER_CALLBACK_NOTIFICATION = *mut SCITER_CALLBACK_NOTIFICATION;
pub type SciterHostCallback = extern "system" fn (pns: LPSCITER_CALLBACK_NOTIFICATION, callbackParam: LPVOID) -> UINT;
pub type SciterWindowDelegate = extern "system" fn (hwnd: HWINDOW, msg: UINT, wParam: WPARAM, lParam: LPARAM, pParam: LPVOID, handled: * mut BOOL) -> LRESULT;
pub type ElementEventProc = extern "system" fn (tag: LPVOID, he: HELEMENT, evtg: UINT, prms: LPVOID) -> BOOL;
#[repr(C)]
#[derive(Debug, PartialOrd, PartialEq)]
/// Debug output categories.
pub enum OUTPUT_SUBSYTEMS
{
/// html parser & runtime
DOM = 0,
/// csss! parser & runtime
CSSS,
/// css parser
CSS,
/// TIS parser & runtime
TIS,
}
#[repr(C)]
#[derive(Debug, PartialOrd, PartialEq)]
#[allow(missing_docs)]
/// Debug output severity.
pub enum OUTPUT_SEVERITY
{
INFO,
WARNING,
ERROR,
}
pub type DEBUG_OUTPUT_PROC = extern "system" fn (param: LPVOID, subsystem: OUTPUT_SUBSYTEMS, severity: OUTPUT_SEVERITY, text: LPCWSTR, text_length: UINT);
pub type LPCWSTR_RECEIVER = extern "system" fn (szstr: LPCWSTR, str_length: UINT, param: LPVOID);
pub type LPCSTR_RECEIVER = extern "system" fn (szstr: LPCSTR, str_length: UINT, param: LPVOID);
pub type LPCBYTE_RECEIVER = extern "system" fn (szstr: LPCBYTE, str_length: UINT, param: LPVOID);
pub type ELEMENT_BITMAP_RECEIVER = extern "system" fn (rgba: LPCBYTE, x: INT, y: INT, width: UINT, height: UINT, param: LPVOID);
pub type KeyValueCallback = extern "system" fn (param: LPVOID, pkey: *const VALUE, pval: *const VALUE) -> BOOL;
/// Signature of Sciter extension library.
///
/// * `api` - Sciter API to be used inside the extension.
/// * `exported` - extension object, it can be [asset](https://sciter.com/developers/for-native-gui-programmers/sciter-object-model/),
/// function, or other `sciter::Value` supported type.
///
/// Return `true` if the `exported` object was initialized.
///
/// The extension should be placed in the same folder as "sciter.dll"
/// and export a `SciterLibraryInit` function:
///
/// ```rust,no_run
/// use sciter::types::{BOOL, VALUE};
/// use sciter::Value;
///
/// #[no_mangle]
/// pub extern "system"
/// fn SciterLibraryInit(api: &'static sciter::ISciterAPI, exported: &mut VALUE) -> BOOL
/// {
/// sciter::set_host_api(api);
///
/// unimplemented!("export some extension functions");
///
/// true as BOOL
/// }
/// ```
///
/// In script such extension library can be imported as:
///
/// ```javascript
/// const exported = include library "library-name";
/// ```
///
/// See the [blog post](https://sciter.com/include-library-name-native-extensions/) for more details.
///
pub type SciterLibraryInit = extern "system" fn (api: &'static ISciterAPI, exported: &mut VALUE) -> BOOL;

Some files were not shown because too many files have changed in this diff Show More