Compare commits

...

131 Commits
1.1.6 ... 1.1.8

Author SHA1 Message Date
rustdesk
1a54c50c6f fix cpal crash on alsa linu 2021-08-23 13:04:21 +08:00
RustDesk
5d26dbaa90 Merge pull request #202 from open-trade/patch-1
My stupidness
2021-08-20 13:59:21 +08:00
open-trade
c52f4af17d My stupidness 2021-08-20 13:57:53 +08:00
rustdesk
b2a6c592ba linux clipboard sync issue https://github.com/rustdesk/rustdesk/issues/118 2021-08-20 12:39:10 +08:00
rustdesk
2df4da89dc somebody not tidy, but like tidy code, :), https://github.com/rustdesk/rustdesk/issues/198 2021-08-16 21:28:59 +08:00
rustdesk
aaffbe476e fix 32 2021-08-14 01:13:40 +08:00
rustdesk
dae3a2b43b compile error 2021-08-14 01:06:06 +08:00
rustdesk
64b4d14629 fix on 32 2021-08-14 01:02:39 +08:00
rustdesk
d03172e2f3 prepare 32 2021-08-14 00:45:12 +08:00
rustdesk
44f6233df0 tokio 1.10 2021-08-13 13:02:03 +08:00
RustDesk
88a3266a73 Update CONTRIBUTING.md 2021-08-13 01:31:47 +08:00
rustdesk
3cd9ee2aa3 unify menu style 2021-08-12 20:16:57 +08:00
rustdesk
a76916c520 ignore abnormal latency 2021-08-12 10:55:21 +08:00
rustdesk
2102813ed9 refactor 2021-08-12 01:25:32 +08:00
rustdesk
c970e5b22b shared memory for future usage, but it has permission problem on
Windows, not find way to make files writable for all users on Windows
2021-08-11 21:08:05 +08:00
rustdesk
3a7d64bf34 atomic 2021-08-11 18:29:03 +08:00
rustdesk
4e85841398 refactor msgbox retry 2021-08-11 01:28:53 +08:00
rustdesk
6130792734 fix cm style 2021-08-10 23:50:32 +08:00
rustdesk
61caaa3365 refactor, will do with shared memory 2021-08-10 16:01:39 +08:00
rustdesk
c3a3c1a1c7 atexit crash on mac 2021-08-10 12:19:42 +08:00
rustdesk
e510d2744d fix apps key 2021-08-10 12:18:10 +08:00
rustdesk
bb25964307 safe exit 2021-08-09 04:21:42 +08:00
rustdesk
8affa24400 how about fix_modifiers? 2021-08-09 02:07:54 +08:00
rustdesk
ad182a5f3c comment on altgr 2021-08-08 18:23:44 +08:00
rustdesk
6ed9526a65 comment on jp/kr key mapping 2021-08-08 18:06:26 +08:00
rustdesk
ccd1cab6bc down as press only for linux and non-modifier 2021-08-08 17:29:39 +08:00
rustdesk
ab4843b76e fixing win key problem https://github.com/rustdesk/rustdesk/issues/35 2021-08-08 01:44:37 +08:00
rustdesk
3200002e52 fix unexpected repeating key input on remote linux https://github.com/rustdesk/rustdesk/issues/189 2021-08-06 14:23:50 +08:00
rustdesk
9d7dced7e7 .gitattributes 2021-08-05 11:27:56 +08:00
rustdesk
a70e3e93b0 fix remote_cursor https://github.com/rustdesk/rustdesk/issues/82, host
has higher priority to control mouse https://github.com/rustdesk/rustdesk/issues/40
2021-08-04 15:40:34 +08:00
rustdesk
646b11a3ae typo 2021-08-04 15:30:47 +08:00
rustdesk
eb76f7cecc fix mac key mapping, https://github.com/rustdesk/rustdesk/issues/186, https://github.com/rustdesk/rustdesk/issues/86 2021-08-04 03:44:00 +08:00
rustdesk
39f0dd28b4 <video> can not be relative, add another wrapper to make img cursor work 2021-08-04 00:57:48 +08:00
rustdesk
66bd97c0b3 bigger client timeout 2021-08-04 00:57:03 +08:00
rustdesk
a0b2450888 fix on --password 2021-08-03 20:16:38 +08:00
rustdesk
f558c12866 --password https://github.com/rustdesk/rustdesk/issues/187 2021-08-03 14:59:45 +08:00
rustdesk
c385d88708 https://github.com/rustdesk/rustdesk/issues/133 https://github.com/rustdesk/rustdesk/issues/112 https://github.com/rustdesk/rustdesk/issues/43 2021-08-01 14:51:53 +08:00
rustdesk
2e305e8f11 fix on rubato 2021-08-01 11:05:45 +08:00
rustdesk
e949023dda try out the other audio resampler 2021-08-01 11:01:04 +08:00
rustdesk
25c10453e5 password eye padding 2021-07-31 22:25:04 +08:00
rustdesk
935676468b disable systray which has compatibility issue 2021-07-31 03:51:10 +08:00
rustdesk
49dff161dd enable dxgi https://github.com/rustdesk/rustdesk/issues/79, may fix https://github.com/rustdesk/rustdesk/issues/169 2021-07-31 03:00:07 +08:00
rustdesk
7282a462f4 scrap readme 2021-07-29 13:33:26 +08:00
rustdesk
a740870b67 fix on android 2021-07-29 13:30:12 +08:00
rustdesk
cd9c189c64 bigger relay timeout 2021-07-28 19:41:34 +08:00
rustdesk
905a3a2936 fix sciter-rs utf 2021-07-28 00:00:11 +08:00
rustdesk
e6744d031d connection type 2021-07-27 23:53:12 +08:00
rustdesk
a3f5ffc15a fix on linux numpadenter 2021-07-27 20:12:53 +08:00
rustdesk
191fdc6691 fix keyboard abnormal, https://github.com/rustdesk/rustdesk/issues/146 https://github.com/rustdesk/rustdesk/issues/135 https://github.com/rustdesk/rustdesk/issues/127 2021-07-27 20:10:04 +08:00
rustdesk
f07ce11425 https://github.com/rustdesk/rustdesk/issues/130 better toolbar hide/show 2021-07-26 23:40:58 +08:00
rustdesk
7324cb607c wheel issue for new sciter 2021-07-26 21:34:05 +08:00
rustdesk
1ee92c9f68 fix for file transfer: sort row and remove empty dir 2021-07-26 02:50:33 +08:00
rustdesk
9a86a595ff fix compatibility issue for new sciter 2021-07-26 01:50:47 +08:00
rustdesk
879c300563 boundery check, https://github.com/rustdesk/rustdesk/issues/107 2021-07-25 21:04:11 +08:00
rustdesk
bebe136834 less green 2021-07-25 02:09:57 +08:00
rustdesk
d89d5ef825 https://github.com/rustdesk/rustdesk/issues/132#issuecomment-886069737 2021-07-25 02:06:20 +08:00
rustdesk
56dfcffd1e restore Fedora vpx fix 2021-07-24 20:00:56 +08:00
rustdesk
7c5915e3d3 vpxmt -> vpx after vcpkg upgraded 2021-07-24 19:33:11 +08:00
rustdesk
cb2864202f upgrade vcpkg 2021-07-24 19:06:32 +08:00
RustDesk
dae2814951 Update Dockerfile 2021-07-24 18:41:22 +08:00
rustdesk
6922a1de4c refactor and upgrade sciter 2021-07-24 18:25:07 +08:00
RustDesk
7282c3a16d Update README.md 2021-07-23 17:54:16 +08:00
rustdesk
c15c44788c try out wayland 2021-07-23 17:52:38 +08:00
RustDesk
d83163b6a0 Merge pull request #170 from sitiom/nsis-setup
Replace InnoSetup with improved NSIS Setup
2021-07-15 21:48:55 +08:00
Ryan Caezar Itang
5383c09e3d Replace InnoSetup with improved NSIS Setup 2021-07-15 20:51:41 +08:00
RustDesk
6f8483ece6 Add files via upload 2021-07-14 22:23:42 +08:00
RustDesk
e65aa61fb7 Update README-FR.md 2021-07-08 22:57:07 +08:00
rustdesk
2522c99f47 update readme 2021-07-08 22:55:03 +08:00
rustdesk
fcf24e04bd Merge branch 'master' of https://github.com/rustdesk/rustdesk 2021-07-07 10:53:27 +08:00
rustdesk
2ec5fbb333 opacity 2021-07-07 10:53:13 +08:00
RustDesk
c1b241a8d1 Merge pull request #143 from SET19724/patch-2
Better translation pl readme
2021-07-07 00:38:27 +08:00
SET19724
b13aef98c2 Better translation
Not Polskie :)
Polski
2021-07-06 18:33:46 +02:00
RustDesk
b25c2c0551 Update README.md 2021-07-07 00:30:45 +08:00
rustdesk
e303a3b9b8 fix PL 2021-07-07 00:27:26 +08:00
RustDesk
ec8255b20f Merge pull request #142 from SET19724/patch-1
README-PL.md Tłumaczenie na Polski PL Polish
2021-07-07 00:23:57 +08:00
SET19724
529048bb8e Update README.md
City name fix
2021-07-06 18:23:28 +02:00
SET19724
926d3ca546 Tłumaczenie na Polski PL Polish
;)
2021-07-06 18:20:05 +02:00
rustdesk
7d316f9a51 https://github.com/rustdesk/rustdesk/issues/140 2021-07-06 10:47:49 +08:00
rustdesk
c27865d3ed change to dallas 2021-07-03 14:14:16 +08:00
rustdesk
d769b79a6f update servers 2021-07-03 10:27:34 +08:00
RustDesk
3aa4bdd1fa Merge pull request #137 from ToasterUwU/master
German README and correction of links in other MDs ("Deutsche" to "Deutsch")
2021-07-03 07:52:51 +08:00
mis1852
ad8b23d1a7 German README and correction of links in other mds 2021-07-02 19:29:26 +02:00
RustDesk
e8b8a260fd Merge pull request #128 from SantiagoValdez/patch-1
Update README.md - Fix spanish spelling
2021-06-29 08:52:58 +08:00
Santiago Valdez
b4467370a8 Update README.md - Fix spanish spelling
Spanish language is called Español or in some cases Castellano. 
Referring to Spanish language as 'Española' is not grammatically valid.
2021-06-28 17:14:01 -04:00
RustDesk
25ffaa7966 Merge pull request #122 from EmPablo/patch-2
Update : Panic message is not a string literal.
2021-06-26 12:18:07 +08:00
RustDesk
00b2b30778 Merge pull request #121 from EmPablo/patch-1
Update to the current release version number.
2021-06-26 12:17:49 +08:00
EmPablo
78692793a5 Update : Panic message is not a string literal. 2021-06-26 11:46:22 +08:00
EmPablo
5b9c90809c Update to the current release version number. 2021-06-26 11:43:38 +08:00
rustdesk
05c4dacbe9 ipc windows work 2021-06-26 01:14:22 +08:00
rustdesk
6f796db523 new namedpipe 2021-06-26 00:47:45 +08:00
rustdesk
2d515815ed Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-06-25 21:36:09 +08:00
rustdesk
dc3fcda2c9 tokio1, windows not test yet 2021-06-25 19:42:51 +08:00
RustDesk
25a83f6b4a Update README.md 2021-06-23 00:44:10 +08:00
RustDesk
086d1f9124 Add files via upload 2021-06-23 00:40:08 +08:00
rustdesk
5339b40104 ISSUE TEMPLATE 2021-06-22 11:34:07 +08:00
RustDesk
be9f0a22a0 Update README.md 2021-06-21 23:32:52 +08:00
RustDesk
fc3f76973d Update README.md 2021-06-21 23:32:07 +08:00
RustDesk
0d0c75e2a9 Merge pull request #101 from geshii/master
Create README-FR.md, French translation
2021-06-21 23:28:55 +08:00
Geshi
da7e044f16 Create README-FR.md 2021-06-21 16:16:37 +02:00
RustDesk
2ccbda2bb8 Update README-ES.md 2021-06-21 18:29:46 +08:00
RustDesk
87e161eddb Update README-ZH.md 2021-06-21 18:29:18 +08:00
RustDesk
592630fac4 Update README.md 2021-06-21 18:29:01 +08:00
RustDesk
aa67aab1f2 Merge pull request #97 from geshii/patch-1
Creating security guidelines, also known as SECURITY.md
2021-06-21 17:02:39 +08:00
Geshi
7e873f1c8b Create SECURITY.md 2021-06-21 10:56:43 +02:00
RustDesk
ba00e4daf2 Update README.md 2021-06-21 16:31:01 +08:00
RustDesk
8ef831ee5c Add files via upload 2021-06-21 16:27:16 +08:00
RustDesk
7cc5d138a0 Update README.md 2021-06-21 12:55:34 +08:00
RustDesk
7b4d5bc704 Update README.md 2021-06-21 12:49:05 +08:00
RustDesk
a4a09d5bfc Create README-ZH.md 2021-06-21 12:44:34 +08:00
RustDesk
c8465f9a5d Update README.md 2021-06-21 12:19:13 +08:00
RustDesk
2159423431 Update README.md 2021-06-21 12:18:56 +08:00
RustDesk
9d5cfb04ac Update README.md 2021-06-21 12:18:28 +08:00
RustDesk
43200f236a Merge pull request #94 from mtoohey31/docker-build
Support builds via Docker
2021-06-21 09:53:38 +08:00
mtoohey31
9383e4ecbb Support builds via Docker 2021-06-20 15:12:46 -04:00
RustDesk
6862406e68 Update README.md 2021-06-20 16:02:35 +08:00
RustDesk
c3b6dabcc8 Update README.md 2021-06-20 15:46:24 +08:00
RustDesk
a99e6f38e5 Merge pull request #89 from mtoohey31/display-server-fix
Check for Xorg running in tty
2021-06-20 12:02:05 +08:00
mtoohey31
142eebc9e2 https://github.com/rustdesk/rustdesk/issues/87 2021-06-19 14:35:40 -04:00
RustDesk
ec294451e3 Update README.md 2021-06-17 12:55:34 +08:00
RustDesk
7daeddf560 Update README.md 2021-06-17 12:55:11 +08:00
RustDesk
562b0c79dd Update README.md 2021-06-17 11:41:21 +08:00
RustDesk
b0f3ec40ce Update README.md 2021-06-17 11:41:07 +08:00
rustdesk
51903ede3d rs-ny.rustdesk.com 2021-06-15 11:21:10 +08:00
rustdesk
e06217536b Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-06-14 17:52:33 +08:00
rustdesk
002ca33cec Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-05-23 11:01:56 +08:00
rustdesk
cd21f61d9c Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-05-23 10:57:49 +08:00
rustdesk
3a570de31e Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-05-20 17:16:01 +08:00
rustdesk
d7b9c1aa72 enable tray and fix various install problems caused by format and
encoding
2021-05-20 17:06:25 +08:00
rustdesk
c05dd0b1b7 Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-05-17 20:46:31 +08:00
rustdesk
7a8cf58ab1 Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-04-26 11:46:36 +08:00
rustdesk
7b067ed28d recreate udp socket 2021-04-26 11:44:47 +08:00
212 changed files with 4168 additions and 24275 deletions

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto

32
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,32 @@
---
name: Bug Report
about: Report a bug (English only, Please).
title: ""
labels: bug
assignees: ''
---
<!-- Hey there, thank you for creating an issue! -->
**Describe the bug you encountered:**
...
**What did you expect to happen instead?**
...
**How did you install `RustDesk`?**
<!-- GitHub release, build from source, Windows portable version, etc. -->
---
**RustDesk version and environment**
<!--
In order to reproduce your issue, please add some information about the environment
in which you're running RustDesk.
-->

2
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,2 @@
blank_issues_enabled: true

View File

@@ -0,0 +1,10 @@
---
name: Feature Request
about: Suggest an idea for this project ((English only, Please).
title: ''
labels: feature-request
assignees: ''
---

10
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View File

@@ -0,0 +1,10 @@
---
name: Question
about: Ask a question about 'RustDesk' (English only, Please).
title: ''
labels: question
assignees: ''
---

View File

@@ -28,7 +28,7 @@ efforts from contributors on the same issue.
- Commits should be accompanied by a Developer Certificate of Origin
(http://developercertificate.org) sign-off, which indicates that you (and
your employer if applicable) agree to be bound by the terms of the
[project license](LICENSE.md). In git, this is the `-s` option to `git commit`
[project license](LICENSE). In git, this is the `-s` option to `git commit`
- If your patch is not getting reviewed or you need a specific person to review
it, you can @-reply a reviewer asking for a review in the pull request or a

2135
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +1,23 @@
[package]
name = "rustdesk"
version = "1.1.2"
version = "1.1.6"
authors = ["rustdesk <info@rustdesk.com>"]
edition = "2018"
build= "build.rs"
description = "A remote control software."
[lib]
crate-type = ["cdylib", "staticlib", "rlib"]
[features]
inline = []
cli = []
use_samplerate = ["samplerate"]
use_rubato = ["rubato"]
use_dasp = ["dasp"]
default = ["use_dasp"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
whoami = "0.9"
whoami = "1.1"
scrap = { path = "libs/scrap" }
hbb_common = { path = "libs/hbb_common" }
enigo = { path = "libs/enigo" }
@@ -28,28 +29,31 @@ lazy_static = "1.4"
sha2 = "0.9"
repng = "0.2"
libc = "0.2"
parity-tokio-ipc = { path = "libs/parity-tokio-ipc" }
flexi_logger = "0.16"
parity-tokio-ipc = { git = "https://github.com/open-trade/parity-tokio-ipc" }
flexi_logger = "0.17"
runas = "0.2"
magnum-opus = { path = "libs/magnum-opus" }
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"] }
magnum-opus = { git = "https://github.com/open-trade/magnum-opus" }
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"], optional = true }
rubato = { version = "0.8", optional = true }
samplerate = { version = "0.2", optional = true }
async-trait = "0.1"
crc32fast = "1.2"
uuid = { version = "0.8", features = ["v4"] }
copypasta = "0.7"
clap = "2.33"
rpassword = "5.0"
[target.'cfg(not(any(target_os = "android")))'.dependencies]
cpal = { git = "https://github.com/rustaudio/cpal" }
cpal = { git = "https://github.com/open-trade/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/open-trade/rust-sciter", branch = "dyn" }
ctrlc = "3.2"
arboard = "2.0"
[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,8 +68,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" }
ctrlc = "3.1"
rust-pulsectl = { git = "https://github.com/open-trade/pulsectl" }
[target.'cfg(not(any(target_os = "windows", target_os = "android", target_os = "ios")))'.dependencies]
psutil = "3.2"

20
Dockerfile Normal file
View File

@@ -0,0 +1,20 @@
FROM debian
WORKDIR /
RUN apt update -y && apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake unzip zip sudo
RUN git clone https://github.com/microsoft/vcpkg && cd vcpkg && git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
RUN /vcpkg/bootstrap-vcpkg.sh -disableMetrics
RUN /vcpkg/vcpkg --disable-metrics install libvpx libyuv opus
RUN groupadd -r user && useradd -r -g user user --home /home/user && mkdir -p /home/user && chown user /home/user
WORKDIR /home/user
RUN wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
USER user
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup.sh
RUN chmod +x rustup.sh
RUN ./rustup.sh -y
USER root
COPY ./entrypoint /
ENTRYPOINT ["/entrypoint"]

151
README-DE.md Normal file
View File

@@ -0,0 +1,151 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#kostenlose-öffentliche-server">Server</a> •
<a href="#die-groben-schritte-zum-kompilieren">Kompilieren</a> •
<a href="#auf-docker-kompilieren">Docker</a> •
<a href="#dateistruktur">Dateistruktur</a> •
<a href="#screenshots">Screenshots</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Wir brauchen deine Hilfe um diese README Datei zu verbessern und aktualisieren</b>
</p>
Rede mit uns: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Das hier ist ein Programm was man nutzen kann, um einen Computer fernzusteuern, es wurde in Rust geschrieben. Es funktioniert ohne Konfiguration oder ähnliches, man kann es einfach direkt nutzen. Es ist eine gute Alternative zu Programmen wie TeamViewer und AnyDesk! Du hast volle Kontrolle über deine Daten und brauchst dir daher auch keine Sorgen um die Sicherheit dieser Daten zu machen. Du kannst unseren rendezvous/relay Server nutzen, [einen eigenen Server eröffnen](https://rustdesk.com/blog/id-relay-set/) oder [einen neuen eigenen Server programmieren](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk heißt jegliche Mitarbeit willkommen. Schau dir [`CONTRIBUTING.md`](CONTRIBUTING.md) an, wenn du Hilfe brauchst für den Start.
[**PROGRAMM DOWNLOAD**](https://github.com/rustdesk/rustdesk/releases)
## Kostenlose öffentliche Server
Hier sind die Server die du kostenlos nutzen kannst, es kann sein das sich diese Liste immer mal wieder ändert. Falls du nicht in der Nähe einer dieser Server bist, kann es sein, dass deine Verbindung langsam sein wird.
| Standort | Serverart | Spezifikationen | Kommentare |
| --------- | ------------- | ------------------ | ---------------------------------------- |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM | |
| Singapore | Vultr | 1 VCPU / 1GB RAM | |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Abhängigkeiten
Die Desktop Versionen nutzen [Sciter](https://sciter.com/) für die Oberfläche, bitte lade die dynamische Sciter Bibliothek selbst herunter.
[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
* Installiere [vcpkg](https://github.com/microsoft/vcpkg) und füge die `VCPKG_ROOT` Systemumgebungsvariable hinzu
- Windows: `vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static`
- Linux/MacOS: `vcpkg install libvpx libyuv opus`
* Nutze `cargo run`
## Kompilieren auf Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### vcpkg installieren
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### libvpx reparieren (Für Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Kompilieren
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
## Auf Docker Kompilieren
Beginne damit das Repository zu klonen und den Docker Container zu bauen:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Jedes Mal, wenn du das Programm Kompilieren musst, nutze diesen Befehl:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Bedenke, dass das erste Mal Kompilieren länger dauern kann, da die Abhängigkeiten erst kompiliert werden müssen bevor sie zwischengespeichert werden können. Darauf folgende Kompiliervorgänge werden schneller sein. Falls du zusätzliche oder andere Argumente für den Kompilierbefehl angeben musst, kannst du diese am Ende des Befehls an der `<OPTIONAL-ARGS>` Position machen. Wenn du zum Beispiel eine optimierte Releaseversion kompilieren willst, kannst du das tun indem du `--release` am Ende des Befehls anhängst. Das daraus entstehende Programm kannst du im “target” Ordner auf deinem System finden. Du kannst es mit folgenden Befehlen ausführen:
```sh
target/debug/rustdesk
```
Oder, wenn du eine Releaseversion benutzt:
```sh
target/release/rustdesk
```
Bitte gehe sicher, dass du diese Befehle vom Stammverzeichnis vom RustDesk Repository nutzt, sonst kann es passieren, dass das Programm die Ressourcen nicht finden kann. Bitte bedenke auch, dass Unterbefehle von Cargo, wie z.B. `install` oder `run` aktuell noch nicht unterstützt werden, da sie das Programm innerhalb des Containers starten oder installieren würden, anstatt auf deinem eigentlichen System.
### Ändere Wayland zu X11 (Xorg)
RustDesk unterstützt "Wayland" nicht. Siehe [hier](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) um Xorg als Standard GNOME Session zu nutzen.
## Dateistruktur
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: Video Codec, Konfiguration, TCP/UDP Wrapper, Protokoll Puffer, fs Funktionen für Dateitransfer, und ein paar andere nützliche Funktionen
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: Bildschirmaufnahme
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: Plattformspezifische Maus und Tastatur Steuerung
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: Audio/Zwischenablage/Eingabe/Videodienste und Netzwerk Verbindungen
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: Starten einer Peer-Verbindung
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Mit [rustdesk-server](https://github.com/rustdesk/rustdesk-server) kommunizieren, für Verbindung von außen warten, direkt (TCP hole punching) oder weitergeleitet
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: Plattformspezifischer Code
## Screenshots
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

148
README-ES.md Normal file
View File

@@ -0,0 +1,148 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#servidores-gratis-de-uso-público">Servidores</a> •
<a href="#pasos-para-compilar-desde-el-inicio">Compilar</a> •
<a href="#como-compilar-con-docker">Docker</a> •
<a href="#estructura-de-archivos">Estructura</a> •
<a href="#captura-de-pantalla">Captura de pantalla</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Necesitamos tu ayuda para traducir este README a tu idioma</b>
</p>
Chat with us: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Otro software de escritorio remoto, escrito en Rust. Funciona de forma inmediata, sin necesidad de configuración. Gran alternativa a TeamViewer o AnyDesk. Tienes el control total de sus datos, sin preocupaciones sobre la seguridad. Puedes utilizar nuestro servidor de rendezvous/relay, [set up your own](https://rustdesk.com/blog/id-relay-set/), o [escribir tu propio servidor rendezvous/relay](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk agradece la contribución de todo el mundo. Ve [`CONTRIBUTING.md`](CONTRIBUTING.md) para ayuda inicial.
[**DESCARGA DE BINARIOS**](https://github.com/rustdesk/rustdesk/releases)
## Servidores gratis de uso público
A continuación se muestran los servidores que está utilizando de forma gratuita, puede cambiar en algún momento. Si no estás cerca de uno de ellos, tu red puede ser lenta.
- Seoul, AWS lightsail, 1 VCPU/0.5G RAM
- Singapore, Vultr, 1 VCPU/1G RAM
- Dallas, Vultr, 1 VCPU/1G RAM
## Dependencies
La versión Desktop usa [sciter](https://sciter.com/) para GUI, por favor bajate la librería sciter tu mismo..
[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.
* Instala [vcpkg](https://github.com/microsoft/vcpkg), y configura la variable de entono `VCPKG_ROOT` correctamente.
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx: vcpkg install libvpx libyuv opus
* run `cargo run`
## Como compilar en linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Install vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Soluciona libvpx (For Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Compila
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
## Como compilar con Docker
Empieza clonando el repositorio y compilando el contenedor de docker:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Entonces, cada vez que necesites compilar una modificación, ejecuta el siguiente comando:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Ten en cuenta que la primera compilación puede tardar más tiempo antes de que las dependencias se almacenen en la caché, las siguientes compilaciones serán más rápidas. Además, si necesitas especificar diferentes argumentos a la orden de compilación, puede hacerlo al final de la linea de comandos en el apartado`<OPTIONAL-ARGS>`. Por ejemplo, si desea compilar una versión optimizada para publicación, deberá ejecutar el comando anterior seguido de `---release`. El ejecutable resultante estará disponible en la carpeta de destino en su sistema, y puede ser ejecutado con:
```sh
target/debug/rustdesk
```
O si estas ejecutando una versión para su publicación:
```sh
target/release/rustdesk
```
Por favor, asegurate de que estás ejecutando estos comandos desde la raíz del repositorio de RustDesk, de lo contrario la aplicación puede ser incapaz de encontrar los recursos necesarios. También hay que tener en cuenta que otros subcomandos de carga como `install` o `run` no estan actualmente soportados via este metodo y podrían requerir ser instalados dentro del contenedor y no en el host.
### Cambia Wayland a X11 (Xorg)
RustDesk no soporta Wayland. Comprueba [aquí](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) para configurar Xorg en la sesión por defecto de GNOME.
## Estructura de archivos
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: video codec, configuración, tcp/udp wrapper, protobuf, fs funciones para transferencia de ficheros, y alguna función de utilidad.
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: captura de pantalla
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: control específico por cada plataforma para el teclado/ratón
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: sonido/portapapeles/entrada/servicios de video, y conexiones de red
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: iniciar una conexión "peer to peer"
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Comunicación con [rustdesk-server](https://github.com/rustdesk/rustdesk-server), esperar la conexión remota directa ("TCP hole punching") o conexión indirecta ("relayed")
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: código específico de cada plataforma
## Captura de pantalla
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

148
README-FR.md Normal file
View File

@@ -0,0 +1,148 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#serveurs-publics-libres">Serveurs</a> -
<a href="#étapes-brutes-de-la-compilationbuild">Build</a> -
<a href="#comment-construire-avec-docker">Docker</a> -
<a href="#structure-du-projet">Structure</a> -
<a href="#images">Images</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-ES.md">Española</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Nous avons besoin de votre aide pour traduire ce README dans votre langue maternelle</b>.
</p>
Chattez avec nous : [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Encore un autre logiciel de bureau à distance, écrit en Rust. Fonctionne directement, aucune configuration n'est nécessaire. Une excellente alternative à TeamViewer et AnyDesk ! Vous avez le contrôle total de vos données, sans aucun souci de sécurité. Vous pouvez utiliser notre serveur de rendez-vous/relais, [configurer le vôtre](https://rustdesk.com/blog/id-relay-set/), ou [écrire votre propre serveur de rendez-vous/relais](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk accueille les contributions de tout le monde. Voir [`CONTRIBUTING.md`](CONTRIBUTING.md) pour plus d'informations.
[**TÉLÉCHARGEMENT BINAIRE**](https://github.com/rustdesk/rustdesk/releases)
## Serveurs publics libres
Ci-dessous se trouvent les serveurs que vous utilisez gratuitement, cela peut changer au fil du temps. Si vous n'êtes pas proche de l'un d'entre eux, votre réseau peut être lent.
- Séoul, AWS lightsail, 1 VCPU/0.5G RAM
- Singapour, Vultr, 1 VCPU/1G RAM
- Dallas, Vultr, 1 VCPU/1G RAM
## Dépendances
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://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++.
* Installez [vcpkg](https://github.com/microsoft/vcpkg), et définissez correctement la variable d'environnement `VCPKG_ROOT`.
- Windows : vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx : vcpkg install libvpx libyuv opus
* Exécuter `cargo run`
## Comment compiler/build sous Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Installer vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Corriger libvpx (Pour Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Construire
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p cible/debug
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
```
## Comment construire avec Docker
Commencez par cloner le dépôt et construire le conteneur Docker :
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Ensuite, chaque fois que vous devez build le logiciel, exécutez la commande suivante :
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Notez que le premier build peut prendre plus de temps avant que les dépendances ne soient mises en cache, les constructions suivantes seront plus rapides. De plus, si vous devez spécifier différents arguments à la commande de compilation, vous pouvez le faire à la fin de la commande dans la position `<OPTIONAL-ARGS>`. Par exemple, si vous voulez construire une version optimisée de la version release, vous devez exécuter la commande ci-dessus suivie de `---release`. L'exécutable résultant sera disponible dans le dossier cible sur votre système, et peut être lancé avec :
```sh
target/debug/rustdesk
```
Ou, si vous exécutez un exécutable provenant d'une release :
```sh
target/release/rustdesk
```
Veuillez vous assurer que vous exécutez ces commandes à partir de la racine du référentiel RustDesk, sinon l'application ne pourra pas trouver les ressources requises. Notez également que les autres sous-commandes de cargo telles que `install` ou `run` ne sont pas actuellement supportées par cette méthode car elles installeraient ou exécuteraient le programme à l'intérieur du conteneur au lieu de l'hôte.
### Changer Wayland en X11 (Xorg)
RustDesk ne supporte pas Wayland. Lisez [cela](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) pour configurer Xorg comme la session GNOME par défaut.
## Structure du projet
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)** : codec vidéo, config, wrapper tcp/udp, protobuf, fonctions fs pour le transfert de fichiers, et quelques autres fonctions utilitaires.
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)** : capture d'écran
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)** : contrôle clavier/souris spécifique à la plate-forme
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)** : INTERFACE GRAPHIQUE
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)** : services audio/clipboard/input/vidéo, et connexions réseau
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)** : démarrer une connexion entre pairs
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)** : Communiquer avec [rustdesk-server](https://github.com/rustdesk/rustdesk-server), attendre une connexion distante directe (TCP hole punching) ou relayée.
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)** : code spécifique à la plateforme
## Images
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

152
README-PL.md Normal file
View File

@@ -0,0 +1,152 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#darmowe-serwery-publiczne">Serwery</a> •
<a href="#podstawowe-kroki-do-kompilacji">Kompilacja</a> •
<a href="#jak-kompilować-za-pomocą-dockera">Docker</a> •
<a href="#struktura-plików">Struktura</a> •
<a href="#migawkisnapshoty">Snapshot</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-ES.md">Española</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Potrzebujemy twojej pomocy w tłumaczeniu README na twój ojczysty język</b>
</p>
Porozmawiaj z nami na: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Kolejny program do zdalnego pulpitu, napisany w Rust. Działa od samego początku, nie wymaga konfiguracji. Świetna alternatywa dla TeamViewera i AnyDesk! Masz pełną kontrolę nad swoimi danymi, bez obaw o bezpieczeństwo. Możesz skorzystać z naszego darmowego serwera publicznego , [skonfigurować własny](https://rustdesk.com/blog/id-relay-set/), lub [napisać własny serwer rendezvous/relay server](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk zaprasza do współpracy każdego. Zobacz [`CONTRIBUTING.md`](CONTRIBUTING.md) pomoc w uruchomieniu programu.
[**POBIERZ KOMPILACJE**](https://github.com/rustdesk/rustdesk/releases)
## Darmowe Serwery Publiczne
Poniżej znajdują się serwery, z których można korzystać za darmo, może się to zmienić z upływem czasu. Jeśli nie znajdujesz się w pobliżu jednego z nich, Twoja prędkość połączenia może być niska.
| Lokalizacja | Dostawca | Specyfikacja |
| --------- | ------------- | ------------------ |
| Seul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapur | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Zależności
Wersje desktopowe używają [sciter](https://sciter.com/) dla GUI, proszę pobrać bibliotekę dynamiczną sciter samodzielnie.
[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++
* Zainstaluj [vcpkg](https://github.com/microsoft/vcpkg), i ustaw `VCPKG_ROOT` env zmienną prawidłowo
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/MacOS: vcpkg install libvpx libyuv opus
* uruchom `cargo run`
## Jak Kompilować na Linuxie
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Zainstaluj vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Fix libvpx (For Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Kompilacja
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
## Jak kompilować za pomocą Dockera
Rozpocznij od sklonowania repozytorium i stworzenia kontenera docker:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Następnie, za każdym razem, gdy potrzebujesz skompilować aplikację, uruchom następujące polecenie:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Zauważ, że pierwsza kompilacja może potrwać dłużej zanim zależności zostaną zbuforowane, kolejne będą szybsze. Dodatkowo, jeśli potrzebujesz określić inne argumenty dla polecenia budowania, możesz to zrobić na końcu komendy w miejscu `<OPTIONAL-ARGS>`. Na przykład, jeśli chciałbyś zbudować zoptymalizowaną wersję wydania, uruchomiłbyś powyższą komendę a następnie `---release`. Powstały plik wykonywalny będzie dostępny w folderze docelowym w twoim systemie, i może być uruchomiony z:
```sh
target/debug/rustdesk
```
Lub, jeśli uruchamiasz plik wykonywalny wersji:
```sh
target/release/rustdesk
```
Upewnij się, że uruchamiasz te polecenia z katalogu głównego repozytorium RustDesk, w przeciwnym razie aplikacja może nie być w stanie znaleźć wymaganych zasobów. Należy również pamiętać, że inne podpolecenia ładowania, takie jak `install` lub `run` nie są obecnie obsługiwane za pomocą tej metody, ponieważ instalowałyby lub uruchamiały program wewnątrz kontenera zamiast na hoście.
### Zmień Wayland na X11 (Xorg)
RustDesk nie obsługuje Waylanda. Sprawdź [this](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) by skonfigurować Xorg jako domyślną sesję GNOME.
## Struktura plików
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: kodek wideo, config, wrapper tcp/udp, protobuf, funkcje fs do transferu plików i kilka innych funkcji użytkowych
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: przechwytywanie ekranu
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: specyficzne dla danej platformy sterowanie klawiaturą/myszą
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: audio/schowek/wejście(input)/wideo oraz połączenia sieciowe
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: uruchamia połączenie peer
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Komunikacja z [rustdesk-server](https://github.com/rustdesk/rustdesk-server), wait for remote direct (TCP hole punching) or relayed connection
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: specyficzny dla danej platformy kod
## Migawki(Snapshoty)
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

154
README-ZH.md Normal file
View File

@@ -0,0 +1,154 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#免费公共服务器">服务器</a> •
<a href="#基本构建步骤">编译</a> •
<a href="#使用Docker编译">Docker</a> •
<a href="#文件结构">结构</a> •
<a href="#截图">截图</a><br>
[<a href="README.md">English</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
</p>
Chat with us: [知乎](https://www.zhihu.com/people/rustdesk) | [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
远程桌面软件开箱即用无需任何配置替代TeamViewer和AnyDesk。您完全掌控数据不用担心安全问题。您可以使用我们的注册/中继服务器,
或者[自己设置](https://rustdesk.com/blog/id-relay-set/)
亦或者[开发您的版本](https://github.com/rustdesk/rustdesk-server-demo)。
欢迎大家贡献代码, 请看 [`CONTRIBUTING.md`](CONTRIBUTING.md).
[**可执行程序下载**](https://github.com/rustdesk/rustdesk/releases)
## 免费公共服务器
以下是您免费使用的服务器,它可能会随着时间的推移而变化。如果您不靠近其中之一,您的网络可能会很慢。
- 首尔, AWS lightsail, 1 VCPU/0.5G RAM
- 新加坡, Vultr, 1 VCPU/1G RAM
- 达拉斯, Vultr, 1 VCPU/1G RAM
## 依赖
桌面版本界面使用[sciter](https://sciter.com/), 请自行下载。
[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++编译环境
* 安装[vcpkg](https://github.com/microsoft/vcpkg), 正确设置`VCPKG_ROOT`环境变量
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx: vcpkg install libvpx libyuv opus
* 运行 `cargo run`
## 在Linux上编译
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### 安装vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### 修复libvpx (仅仅针对Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### 构建
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
## 使用Docker编译
首先克隆存储库并构建 docker 容器:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
然后,每次需要构建应用程序时,运行以下命令:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
请注意,第一次构建可能需要比较长的时间,因为需要缓存依赖项,后续构建会更快。此外,如果您需要为构建命令指定不同的参数,
您可以在命令末尾的 `<OPTIONAL-ARGS>` 位置执行此操作。例如,如果你想构建一个优化的发布版本,你可以在命令后跟 `---release`
将在target下产生可执行程序请通过以下方式运行调试版本
```sh
target/debug/rustdesk
```
或者运行发布版本:
```sh
target/release/rustdesk
```
请确保您从 RustDesk 存储库的根目录运行这些命令,否则应用程序可能无法找到所需的资源。另请注意,此方法当前不支持其他`Cargo`子命令,
例如 `install``run`,因为运行在容器里,而不是宿主机上。
### 把Wayland修改成X11 (Xorg)
RustDesk暂时不支持Wayland不过正在积极开发中.
请查看[this](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/)配置X11.
## 文件结构
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: 视频编解码, 配置, tcp/udp封装, protobuf, 文件传输相关文件系统操作函数, 以及一些其他实用函数
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: 截屏
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: 平台相关的鼠标键盘输入
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: 被控端服务audio/clipboard/input/video服务, 已经连接实现
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: 控制端
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: 与[rustdesk-server](https://github.com/rustdesk/rustdesk-server)保持UDP通讯, 等待远程连接(通过打洞直连或者中继)
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: 平台服务相关代码
## 截图
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

View File

@@ -1,22 +1,39 @@
# RustDesk | Your Remote Desktop Software
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#free-public-servers">Servers</a> •
<a href="#raw-steps-to-build">Build</a> •
<a href="#how-to-build-with-docker">Docker</a> •
<a href="#file-structure">Structure</a> •
<a href="#snapshot">Snapshot</a><br>
[<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>We need your help to translate this README to your native language</b>
</p>
Chat with us: [Discord](https://discord.gg/nDceKgxnkV)
Chat with us: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
An open-source remote desktop client software, written in Rust. Works out of the box, no configuration required. Great alternative to TeamViewer and AnyDesk! You have full control of your data, with no concerns about security. You can use our rendezvous/relay server, [set up your own](https://rustdesk.com/blog/id-relay-set/), or [write your own rendezvous/relay server](https://github.com/rustdesk/rustdesk-server-demo).
Yet another remote desktop software, written in Rust. Works out of the box, no configuration required. Great alternative to TeamViewer and AnyDesk! You have full control of your data, with no concerns about security. You can use our rendezvous/relay server, [set up your own](https://rustdesk.com/blog/id-relay-set/), or [write your own rendezvous/relay server](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk welcomes contribution from everyone. See [`CONTRIBUTING.md`](CONTRIBUTING.md) for help getting started.
[**BINARY DOWNLOAD**](https://github.com/rustdesk/rustdesk/releases)
## Free Public Servers
Below are the servers you are using for free, it may change along the time. If you are not close to one of these, your network may be slow.
| Location | Vendor | Specification |
| --------- | ------------- | ------------------ |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapore | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Dependencies
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
@@ -24,37 +41,40 @@ Desktop versions use [sciter](https://sciter.com/) for GUI, please download scit
* Install [vcpkg](https://github.com/microsoft/vcpkg), and set `VCPKG_ROOT` env variable correctly
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx: vcpkg install libvpx libyuv opus
- Linux/MacOS: vcpkg install libvpx libyuv opus
* run `cargo run`
## How to build on Linux
### Ubuntu 18 (Debian 10)
```
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Install vcpkg
```
git clone https://github.com/microsoft/vcpkg --branch 2020.11-1
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Fix libvpx (For Fedora)
```
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
@@ -66,17 +86,47 @@ cd
```
### Build
```
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
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
```
## How to build with Docker
Begin by cloning the repository and building the docker container:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Then, each time you need to build the application, run the following command:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Note that the first build may take longer before dependencies are cached, subsequent builds will be faster. Additionally, if you need to specify different arguments to the build command, you may do so at the end of the command in the `<OPTIONAL-ARGS>` position. For instance, if you wanted to build an optimized release version, you would run the command above followed by `---release`. The resulting executable will be available in the target folder on your system, and can be run with:
```sh
target/debug/rustdesk
```
Or, if you're running a release executable:
```sh
target/release/rustdesk
```
Please ensure that you are running these commands from the root of the RustDesk repository, otherwise the application may be unable to find the required resources. Also note that other cargo subcommands such as `install` or `run` are not currently supported via this method as they would install or run the program inside the container instead of the host.
### Change Wayland to X11 (Xorg)
RustDesk does not support Wayland. Check [this](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) to configuring Xorg as the default GNOME session.

13
SECURITY.md Normal file
View File

@@ -0,0 +1,13 @@
# Security Policy
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| 1.1.x | :white_check_mark: |
| 1.x | :white_check_mark: |
| Below 1.0 | :x: |
## Reporting a Vulnerability
Here we should write what to do in case of a security vulnerability

42
entrypoint Executable file
View File

@@ -0,0 +1,42 @@
#!/bin/sh
if [ "$(id -u)" != "${PUID:-1000}" ] || [ "$(id -g)" != "${PGID:-1000}" ]; then
usermod -o -u "${PUID:-1000}" user
groupmod -o -g "${PGID:-1000}" user
chown -R user /home/user
sudo -u user /entrypoint $@
exit 0
fi
cd $HOME/rustdesk
. $HOME/.cargo/env
argv=$@
while test $# -gt 0; do
case "$1" in
--release)
mkdir -p target/release
test -f target/release/libsciter-gtk.so || cp $HOME/libsciter-gtk.so target/release/
release=1
shift
;;
--target)
shift
if test $# -gt 0; then
rustup target add $1
shift
fi
;;
*)
shift
;;
esac
done
if [ -z $release ]; then
mkdir -p target/debug
test -f target/debug/libsciter-gtk.so || cp $HOME/libsciter-gtk.so target/debug/
fi
VCPKG_ROOT=/vcpkg cargo build $argv

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

@@ -299,7 +299,7 @@ pub enum Key {
/// meta key (also known as "windows", "super", and "command")
Meta,
/// option key on macOS (alt key on Linux and Windows)
Option,
Option, // deprecated, use Alt instead
/// page down key
PageDown,
/// page up key
@@ -347,8 +347,6 @@ pub enum Key {
///
Clear,
///
Menu, // deprecated, use alt instead
///
Pause,
///
Kana,

View File

@@ -238,7 +238,6 @@ fn keysequence<'a>(key: Key) -> Cow<'a, str> {
Key::Decimal => "U2E", //"KP_Decimal",
Key::Cancel => "Cancel",
Key::Clear => "Clear",
Key::Menu => "Menu",
Key::Pause => "Pause",
Key::Kana => "Kana",
Key::Hangul => "Hangul",
@@ -261,7 +260,7 @@ fn keysequence<'a>(key: Key) -> Cow<'a, str> {
Key::Scroll => "Scroll_Lock",
Key::NumLock => "Num_Lock",
Key::RWin => "Super_R",
Key::Apps => "",
Key::Apps => "Menu",
Key::Multiply => "KP_Multiply",
Key::Add => "KP_Add",
Key::Subtract => "KP_Subtract",

View File

@@ -71,3 +71,50 @@ pub const kVK_ANSI_KeypadEnter: u16 = 0x4C;
pub const kVK_ANSI_KeypadMinus: u16 = 0x4E;
pub const kVK_ANSI_KeypadEquals: u16 = 0x51;
pub const kVK_RIGHT_COMMAND: u16 = 0x36;
pub const kVK_ANSI_A : u16 = 0x00;
pub const kVK_ANSI_S : u16 = 0x01;
pub const kVK_ANSI_D : u16 = 0x02;
pub const kVK_ANSI_F : u16 = 0x03;
pub const kVK_ANSI_H : u16 = 0x04;
pub const kVK_ANSI_G : u16 = 0x05;
pub const kVK_ANSI_Z : u16 = 0x06;
pub const kVK_ANSI_X : u16 = 0x07;
pub const kVK_ANSI_C : u16 = 0x08;
pub const kVK_ANSI_V : u16 = 0x09;
pub const kVK_ANSI_B : u16 = 0x0B;
pub const kVK_ANSI_Q : u16 = 0x0C;
pub const kVK_ANSI_W : u16 = 0x0D;
pub const kVK_ANSI_E : u16 = 0x0E;
pub const kVK_ANSI_R : u16 = 0x0F;
pub const kVK_ANSI_Y : u16 = 0x10;
pub const kVK_ANSI_T : u16 = 0x11;
pub const kVK_ANSI_1 : u16 = 0x12;
pub const kVK_ANSI_2 : u16 = 0x13;
pub const kVK_ANSI_3 : u16 = 0x14;
pub const kVK_ANSI_4 : u16 = 0x15;
pub const kVK_ANSI_6 : u16 = 0x16;
pub const kVK_ANSI_5 : u16 = 0x17;
pub const kVK_ANSI_Equal : u16 = 0x18;
pub const kVK_ANSI_9 : u16 = 0x19;
pub const kVK_ANSI_7 : u16 = 0x1A;
pub const kVK_ANSI_Minus : u16 = 0x1B;
pub const kVK_ANSI_8 : u16 = 0x1C;
pub const kVK_ANSI_0 : u16 = 0x1D;
pub const kVK_ANSI_RightBracket : u16 = 0x1E;
pub const kVK_ANSI_O : u16 = 0x1F;
pub const kVK_ANSI_U : u16 = 0x20;
pub const kVK_ANSI_LeftBracket : u16 = 0x21;
pub const kVK_ANSI_I : u16 = 0x22;
pub const kVK_ANSI_P : u16 = 0x23;
pub const kVK_ANSI_L : u16 = 0x25;
pub const kVK_ANSI_J : u16 = 0x26;
pub const kVK_ANSI_Quote : u16 = 0x27;
pub const kVK_ANSI_K : u16 = 0x28;
pub const kVK_ANSI_Semicolon : u16 = 0x29;
pub const kVK_ANSI_Backslash : u16 = 0x2A;
pub const kVK_ANSI_Comma : u16 = 0x2B;
pub const kVK_ANSI_Slash : u16 = 0x2C;
pub const kVK_ANSI_N : u16 = 0x2D;
pub const kVK_ANSI_M : u16 = 0x2E;
pub const kVK_ANSI_Period : u16 = 0x2F;
pub const kVK_ANSI_Grave : u16 = 0x32;

View File

@@ -9,12 +9,6 @@ use self::core_graphics::event_source::*;
use crate::macos::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use objc::runtime::Class;
use std::ffi::CStr;
use std::os::raw::*;
// required for pressedMouseButtons on NSEvent
#[link(name = "AppKit", kind = "framework")]
extern "C" {}
struct MyCGEvent;
@@ -34,8 +28,6 @@ extern "C" {
fn CGEventSourceKeyState(stateID: i32, key: u16) -> bool;
}
pub type CFDataRef = *const c_void;
#[repr(C)]
#[derive(Clone, Copy)]
struct NSPoint {
@@ -43,162 +35,6 @@ struct NSPoint {
y: f64,
}
#[repr(C)]
pub struct __TISInputSource;
pub type TISInputSourceRef = *const __TISInputSource;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __CFString([u8; 0]);
pub type CFStringRef = *const __CFString;
pub type Boolean = c_uchar;
pub type UInt8 = c_uchar;
pub type SInt32 = c_int;
pub type UInt16 = c_ushort;
pub type UInt32 = c_uint;
pub type UniChar = UInt16;
pub type UniCharCount = c_ulong;
pub type OptionBits = UInt32;
pub type OSStatus = SInt32;
pub type CFStringEncoding = UInt32;
#[allow(non_upper_case_globals)]
pub const kUCKeyActionDisplay: _bindgen_ty_702 = _bindgen_ty_702::kUCKeyActionDisplay;
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum _bindgen_ty_702 {
// kUCKeyActionDown = 0,
// kUCKeyActionUp = 1,
// kUCKeyActionAutoKey = 2,
kUCKeyActionDisplay = 3,
}
#[allow(non_snake_case)]
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct UCKeyboardTypeHeader {
pub keyboardTypeFirst: UInt32,
pub keyboardTypeLast: UInt32,
pub keyModifiersToTableNumOffset: UInt32,
pub keyToCharTableIndexOffset: UInt32,
pub keyStateRecordsIndexOffset: UInt32,
pub keyStateTerminatorsOffset: UInt32,
pub keySequenceDataIndexOffset: UInt32,
}
#[allow(non_snake_case)]
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct UCKeyboardLayout {
pub keyLayoutHeaderFormat: UInt16,
pub keyLayoutDataVersion: UInt16,
pub keyLayoutFeatureInfoOffset: UInt32,
pub keyboardTypeCount: UInt32,
pub keyboardTypeList: [UCKeyboardTypeHeader; 1usize],
}
#[allow(non_upper_case_globals)]
pub const kUCKeyTranslateNoDeadKeysBit: _bindgen_ty_703 =
_bindgen_ty_703::kUCKeyTranslateNoDeadKeysBit;
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum _bindgen_ty_703 {
kUCKeyTranslateNoDeadKeysBit = 0,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __CFAllocator([u8; 0]);
pub type CFAllocatorRef = *const __CFAllocator;
// #[repr(u32)]
// #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
// pub enum _bindgen_ty_15 {
// kCFStringEncodingMacRoman = 0,
// kCFStringEncodingWindowsLatin1 = 1280,
// kCFStringEncodingISOLatin1 = 513,
// kCFStringEncodingNextStepLatin = 2817,
// kCFStringEncodingASCII = 1536,
// kCFStringEncodingUnicode = 256,
// kCFStringEncodingUTF8 = 134217984,
// kCFStringEncodingNonLossyASCII = 3071,
// kCFStringEncodingUTF16BE = 268435712,
// kCFStringEncodingUTF16LE = 335544576,
// kCFStringEncodingUTF32 = 201326848,
// kCFStringEncodingUTF32BE = 402653440,
// kCFStringEncodingUTF32LE = 469762304,
// }
#[allow(non_upper_case_globals)]
pub const kCFStringEncodingUTF8: u32 = 134_217_984;
#[allow(improper_ctypes)]
#[link(name = "Carbon", kind = "framework")]
extern "C" {
fn TISCopyCurrentKeyboardInputSource() -> TISInputSourceRef;
fn TISCopyCurrentKeyboardLayoutInputSource() -> TISInputSourceRef;
fn TISCopyCurrentASCIICapableKeyboardLayoutInputSource() -> TISInputSourceRef;
// extern void *
// TISGetInputSourceProperty(
// TISInputSourceRef inputSource,
// CFStringRef propertyKey)
#[allow(non_upper_case_globals)]
#[link_name = "kTISPropertyUnicodeKeyLayoutData"]
pub static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
#[allow(non_snake_case)]
pub fn TISGetInputSourceProperty(
inputSource: TISInputSourceRef,
propertyKey: CFStringRef,
) -> *mut c_void;
#[allow(non_snake_case)]
pub fn CFDataGetBytePtr(theData: CFDataRef) -> *const UInt8;
#[allow(non_snake_case)]
pub fn UCKeyTranslate(
keyLayoutPtr: *const UInt8, //*const UCKeyboardLayout,
virtualKeyCode: UInt16,
keyAction: UInt16,
modifierKeyState: UInt32,
keyboardType: UInt32,
keyTranslateOptions: OptionBits,
deadKeyState: *mut UInt32,
maxStringLength: UniCharCount,
actualStringLength: *mut UniCharCount,
unicodeString: *mut UniChar,
) -> OSStatus;
pub fn LMGetKbdType() -> UInt8;
#[allow(non_snake_case)]
pub fn CFStringCreateWithCharacters(
alloc: CFAllocatorRef,
chars: *const UniChar,
numChars: CFIndex,
) -> CFStringRef;
#[allow(non_upper_case_globals)]
#[link_name = "kCFAllocatorDefault"]
pub static kCFAllocatorDefault: CFAllocatorRef;
#[allow(non_snake_case)]
pub fn CFStringGetCString(
theString: CFStringRef,
buffer: *mut c_char,
bufferSize: CFIndex,
encoding: CFStringEncoding,
) -> Boolean;
}
// not present in servo/core-graphics
#[allow(dead_code)]
#[derive(Debug)]
@@ -211,7 +47,6 @@ enum ScrollUnit {
/// The main struct for handling the event emitting
pub struct Enigo {
event_source: Option<CGEventSource>,
keycode_to_string_map: std::collections::HashMap<String, CGKeyCode>,
double_click_interval: u32,
last_click_time: Option<std::time::Instant>,
multiple_click: i64,
@@ -263,7 +98,6 @@ impl Default for Enigo {
} else {
None
},
keycode_to_string_map: Default::default(),
double_click_interval,
multiple_click: 1,
last_click_time: None,
@@ -591,126 +425,65 @@ impl Enigo {
Key::RightAlt => kVK_RightOption,
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
Key::Layout(c) => self.map_key_board(c),
Key::Super | Key::Command | Key::Windows | Key::Meta => kVK_Command,
_ => 0,
}
}
fn get_layoutdependent_keycode(&mut self, string: String) -> CGKeyCode {
if self.keycode_to_string_map.is_empty() {
self.init_map();
#[inline]
fn map_key_board(&self, ch: char) -> CGKeyCode {
match ch {
'a' => kVK_ANSI_A,
'b' => kVK_ANSI_B,
'c' => kVK_ANSI_C,
'd' => kVK_ANSI_D,
'e' => kVK_ANSI_E,
'f' => kVK_ANSI_F,
'g' => kVK_ANSI_G,
'h' => kVK_ANSI_H,
'i' => kVK_ANSI_I,
'j' => kVK_ANSI_J,
'k' => kVK_ANSI_K,
'l' => kVK_ANSI_L,
'm' => kVK_ANSI_M,
'n' => kVK_ANSI_N,
'o' => kVK_ANSI_O,
'p' => kVK_ANSI_P,
'q' => kVK_ANSI_Q,
'r' => kVK_ANSI_R,
's' => kVK_ANSI_S,
't' => kVK_ANSI_T,
'u' => kVK_ANSI_U,
'v' => kVK_ANSI_V,
'w' => kVK_ANSI_W,
'x' => kVK_ANSI_X,
'y' => kVK_ANSI_Y,
'z' => kVK_ANSI_Z,
'0' => kVK_ANSI_0,
'1' => kVK_ANSI_1,
'2' => kVK_ANSI_2,
'3' => kVK_ANSI_3,
'4' => kVK_ANSI_4,
'5' => kVK_ANSI_5,
'6' => kVK_ANSI_6,
'7' => kVK_ANSI_7,
'8' => kVK_ANSI_8,
'9' => kVK_ANSI_9,
'-' => kVK_ANSI_Minus,
'=' => kVK_ANSI_Equal,
'[' => kVK_ANSI_LeftBracket,
']' => kVK_ANSI_RightBracket,
'\\' => kVK_ANSI_Backslash,
';' => kVK_ANSI_Semicolon,
'\'' => kVK_ANSI_Quote,
',' => kVK_ANSI_Comma,
'.' => kVK_ANSI_Period,
'/' => kVK_ANSI_Slash,
'`' => kVK_ANSI_Grave,
_ => 0,
}
*self.keycode_to_string_map.get(&string).unwrap_or(&0)
}
fn init_map(&mut self) {
println!("init_map");
self.keycode_to_string_map.insert("".to_owned(), 0);
// loop through every keycode (0 - 127)
for keycode in 0..128 {
// no modifier
if let Some(key_string) = self.keycode_to_string(keycode, 0x100) {
self.keycode_to_string_map.insert(key_string, keycode);
}
// shift modifier
if let Some(key_string) = self.keycode_to_string(keycode, 0x20102) {
self.keycode_to_string_map.insert(key_string, keycode);
}
// alt modifier
// if let Some(string) = self.keycode_to_string(keycode, 0x80120) {
// println!("{:?}", string);
// }
// alt + shift modifier
// if let Some(string) = self.keycode_to_string(keycode, 0xa0122) {
// println!("{:?}", string);
// }
}
}
fn keycode_to_string(&self, keycode: u16, modifier: u32) -> Option<String> {
let cf_string = self.create_string_for_key(keycode, modifier);
unsafe {
if !cf_string.is_null() {
let mut buf: [i8; 255] = [0; 255];
let success = CFStringGetCString(
cf_string,
buf.as_mut_ptr(),
buf.len() as _,
kCFStringEncodingUTF8,
);
if success != 0 {
let name: &CStr = CStr::from_ptr(buf.as_ptr());
if let Ok(name) = name.to_str() {
return Some(name.to_owned());
}
}
}
}
None
}
fn create_string_for_key(&self, keycode: u16, modifier: u32) -> CFStringRef {
let current_keyboard = unsafe { TISCopyCurrentKeyboardInputSource() };
let mut layout_data = std::ptr::null_mut();
if !current_keyboard.is_null() {
layout_data = unsafe {
TISGetInputSourceProperty(current_keyboard, kTISPropertyUnicodeKeyLayoutData)
};
}
if layout_data.is_null() {
// https://github.com/microsoft/vscode/issues/23833
let current_keyboard = unsafe { TISCopyCurrentKeyboardLayoutInputSource() };
if !current_keyboard.is_null() {
layout_data = unsafe {
TISGetInputSourceProperty(current_keyboard, kTISPropertyUnicodeKeyLayoutData)
};
}
}
if layout_data.is_null() {
let current_keyboard = unsafe { TISCopyCurrentASCIICapableKeyboardLayoutInputSource() };
if !current_keyboard.is_null() {
layout_data = unsafe {
TISGetInputSourceProperty(current_keyboard, kTISPropertyUnicodeKeyLayoutData)
};
}
}
if layout_data.is_null() {
// to-do: try out manual mapping in https://github.com/stweil/OSXvnc
// we do see crash like this, also not easy to reproduce, no sure if it related
/*
0 rustdesk 0x000000010f921bc9 std::collections::hash::map::HashMap$LT$K$C$V$C$S$GT$::insert::h84e28c51a3292e7a + 473
1 rustdesk 0x000000010f921884 enigo::macos::macos_impl::Enigo::key_to_keycode::h85ead82e9b1075ae + 1428
2 rustdesk 0x000000010f922a8c _$LT$enigo..macos..macos_impl..Enigo$u20$as$u20$enigo..KeyboardControllable$GT$::key_down::h54f24da6d274b948 + 44
*/
return std::ptr::null() as _;
}
let keyboard_layout = unsafe { CFDataGetBytePtr(layout_data) };
let mut keys_down: UInt32 = 0;
let mut chars: u16 = 0;
// let mut chars: *mut c_void;//[UniChar; 4];
let mut real_length: UniCharCount = 0;
unsafe {
UCKeyTranslate(
keyboard_layout,
keycode,
kUCKeyActionDisplay as u16,
modifier,
LMGetKbdType() as u32,
kUCKeyTranslateNoDeadKeysBit as u32,
&mut keys_down,
8, // sizeof(chars) / sizeof(chars[0]),
&mut real_length,
&mut chars,
);
}
unsafe { CFStringCreateWithCharacters(kCFAllocatorDefault, &chars, 1) }
}
}

View File

@@ -1,4 +1,7 @@
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731
//
// JP/KR mapping https://github.com/TigerVNC/tigervnc/blob/1a008c1380305648ab50f1d99e73439747e9d61d/vncviewer/win32.c#L267
// altgr handle: https://github.com/TigerVNC/tigervnc/blob/dccb95f345f7a9c5aa785a19d1bfa3fdecd8f8e0/vncviewer/Viewport.cxx#L1066
pub const EVK_RETURN: u16 = 0x0D;
pub const EVK_TAB: u16 = 0x09;

View File

@@ -176,13 +176,13 @@ impl KeyboardControllable for Enigo {
}
fn key_click(&mut self, key: Key) {
let scancode = self.key_to_scancode(key);
keybd_event(KEYEVENTF_SCANCODE, 0, scancode);
keybd_event(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE, 0, scancode);
let vk = self.key_to_keycode(key);
keybd_event(0, vk, 0);
keybd_event(KEYEVENTF_KEYUP, vk, 0);
}
fn key_down(&mut self, key: Key) -> crate::ResultType {
let res = keybd_event(KEYEVENTF_SCANCODE, 0, self.key_to_scancode(key));
let res = keybd_event(0, self.key_to_keycode(key), 0);
if res == 0 {
let err = get_error();
if !err.is_empty() {
@@ -193,11 +193,7 @@ impl KeyboardControllable for Enigo {
}
fn key_up(&mut self, key: Key) {
keybd_event(
KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE,
0,
self.key_to_scancode(key),
);
keybd_event(KEYEVENTF_KEYUP, self.key_to_keycode(key), 0);
}
fn get_key_state(&mut self, key: Key) -> bool {
@@ -307,7 +303,6 @@ impl Enigo {
Key::Numpad9 => EVK_NUMPAD9,
Key::Cancel => EVK_CANCEL,
Key::Clear => EVK_CLEAR,
Key::Menu => EVK_MENU,
Key::Pause => EVK_PAUSE,
Key::Kana => EVK_KANA,
Key::Hangul => EVK_HANGUL,
@@ -345,15 +340,9 @@ impl Enigo {
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
Key::Super | Key::Command | Key::Windows | Key::Meta => EVK_LWIN,
_ => 0,
}
}
fn key_to_scancode(&self, key: Key) -> u16 {
let keycode = self.key_to_keycode(key);
unsafe { MapVirtualKeyW(keycode as u32, 0) as u16 }
}
fn get_layoutdependent_keycode(&self, string: String) -> u16 {
// get the first char from the string ignore the rest
// ensure its not a multybyte char

View File

@@ -8,23 +8,23 @@ edition = "2018"
[dependencies]
protobuf = { version = "3.0.0-pre", git = "https://github.com/stepancheg/rust-protobuf" }
tokio = { version = "0.2", features = ["full"] }
tokio-util = { version = "0.3", features = ["full"] }
tokio = { version = "1.10", features = ["full"] }
tokio-util = { version = "0.6", features = ["full"] }
futures = "0.3"
bytes = "0.5"
bytes = "1.0"
log = "0.4"
env_logger = "0.8"
env_logger = "0.9"
socket2 = { version = "0.3", features = ["reuseport"] }
zstd = "0.5"
zstd = "0.9"
quinn = {version = "0.6", optional = true }
anyhow = "1.0"
futures-util = "0.3"
directories-next = "2.0"
rand = "0.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

@@ -6,11 +6,19 @@ message RegisterPeer {
int32 serial = 2;
}
enum ConnType {
DEFAULT_CONN = 0;
FILE_TRANSFER = 1;
PORT_FORWARD = 2;
RDP = 3;
}
message RegisterPeerResponse { bool request_pk = 2; }
message PunchHoleRequest {
string id = 1;
NatType nat_type = 2;
ConnType conn_type = 4;
}
message PunchHole {
@@ -52,6 +60,11 @@ message RegisterPkResponse {
enum Result {
OK = 1;
UUID_MISMATCH = 2;
ID_EXISTS = 3;
TOO_FREQUENT = 4;
INVALID_ID_FORMAT = 5;
NOT_SUPPORT = 6;
SERVER_ERROR = 7;
}
Result result = 1;
}
@@ -62,6 +75,8 @@ message PunchHoleResponse {
enum Failure {
ID_NOT_EXIST = 1;
OFFLINE = 2;
LICENCE_MISMATCH = 3;
LICENCE_OVERUSE = 4;
}
Failure failure = 3;
string relay_server = 4;
@@ -69,6 +84,7 @@ message PunchHoleResponse {
NatType nat_type = 5;
bool is_local = 6;
}
string other_failure = 7;
}
message ConfigUpdate {
@@ -82,6 +98,7 @@ message RequestRelay {
bytes socket_addr = 3;
string relay_server = 4;
bool secure = 5;
ConnType conn_type = 7;
}
message RelayResponse {
@@ -92,6 +109,7 @@ message RelayResponse {
string id = 4;
bytes pk = 5;
}
string refuse_reason = 6;
}
message SoftwareUpdate { string url = 1; }

View File

@@ -17,7 +17,7 @@ pub const BIND_INTERFACE: &str = "0.0.0.0";
pub const RENDEZVOUS_TIMEOUT: u64 = 12_000;
pub const CONNECT_TIMEOUT: u64 = 18_000;
pub const COMPRESS_LEVEL: i32 = 3;
const SERIAL: i32 = 0;
const SERIAL: i32 = 1;
// 128x128
#[cfg(target_os = "macos")] // 128x128 on 160x160 canvas, then shrink to 128, mac looks better with padding
pub const ICON: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAyVBMVEUAAAAAcf8Acf8Acf8Acv8Acf8Acf8Acf8Acf8AcP8Acf8Ab/8AcP8Acf////8AaP/z+f/o8v/k7v/5/v/T5f8AYP/u9v/X6f+hx/+Kuv95pP8Aef/B1/+TwP9xoP8BdP/g6P+Irv9ZmP8Bgf/E3f98q/9sn/+01f+Es/9nm/9Jif8hhv8off/M4P+syP+avP86iP/c7f+xy/9yqf9Om/9hk/9Rjv+60P99tv9fpf88lv8yjf8Tgf8deP+kvP8BiP8NeP8hkP80gP8oj2VLAAAADXRSTlMA7o7qLvnaxZ1FOxYPjH9HWgAABHJJREFUeNrtm+tW4jAQgBfwuu7MtIUWsOUiCCioIIgLiqvr+z/UHq/LJKVkmwTcc/r9E2nzlU4mSTP9lpGRkZGR8VX5cZjfL+yCEXYL+/nDH//U/Pd8DgyTy39Xbv7oIAcWyB0cqbW/sweW2NtRaj8H1sgpGOwUIAH7Bkd7YJW9dXFwAJY5WNP/cmCZQnJvzIN18on5LwfWySXlxEPYAIcad8D6PdiHDbCfIFCADVBIENiFDbCbIACKPPXrZ+cP8E6/0znvP4EymgIEravIRcTxu8HxNSJ60a8W0AYECKrlAN+YwAthCd9wm1Ug6wKzIn5SgRduXfwkqDasCjx0XFzi9PV6zwNcIuhcWBOg+ikySq8C9UD4dEKWBCoOcspvAuLHTo9sCDQiFPHotRM48j8G5gVur1FdAN2uaYEuiz7xFsgEJ2RUoMUakXuBTHHoGxQYOBhHjeUBAefEnMAowFhaLBOKuOemBBbxLRQrH2PBCgMvNCPQGMeevTb9zLrPxz2Mo+QbEaijzPUcOOHMQZkKGRAIPem39+bypREMPTkQW/oCfk866zAkiIFG4yIKRE/aAnfiSd0WrORY6pFdXQEqi9mvAQm0RIOSnoCcZ8vJoz3diCnjRk+g8VP4/fuQDJ2Lxr6WwG0gXs9aTpDzW0vgDBlVUpixR8gYk44AD8FrUKHr8JQJGgIDnoDqoALxmWPQSi9AVVzm8gKUuEPGr/QCvptwJkbSYT/TC4S8C96DGjTj86aHtAI0x2WaBIq0eSYYpRa4EsdWVVwWu9O0Aj6f6dyBMnwEraeOgSYu0wZlauzA47QCbT7DgAQSE+hZWoEBF/BBmWOewNMK3BsSqKUW4MGcWqCSVmDkbvkXGKQOwg6PAUO9oL3xXhA20yaiCjuwYygRVQlUOTWTCf2SuNJTxeFjgaHByGuAIvd8ItdPLTDhS7IuqEE1YSKVOgbayLhSFQhMzYh8hwfBs1r7c505YVIQYEdNoKwxK06MJiyrpUFHiF0NAfCQUVHoiRclIXJIR6C2fqG37pBHvcWpgwzvAtYwkR5UGV2e42UISdBJETl3mg8ouo54Rcnti1/vaT+iuUQBt500Cgo4U10BeHSkk57FB0JjWkKRMWgLUA0lLodtImAQdaMiiri3+gIAPZQoutHNsgKF1aaDMhMyIdBf8Th+Bh8MTjGWCpl5Wv43tDmnF+IUVMrcZgRoiAxhtrloYizNkZaAnF5leglbNhj0wYCAbCDvGb0mP4nib7O7ZlcYQ2m1gPtIZgVgGNNMeaVAaWR+57TrqgtUnm3sHQ+kYeE6fufUubG1ez50FXbPnWgBlgSABmN3TTcsRl2yWkHRrwbiunvk/W2+Mg1hPZplPDeXRbZzStFH15s1QIVd3UImP5z/bHpeeQLvRJ7XLFUffQIlCvqlXETQbgN9/rlYABGosv+Vi9m2Xs639YLGrZd0br+odetlvdsvbN56abfd4vbCzv9Q3v/ygoOV21A4OPpfXvH4Ai+5ZGRkZGRkbJA/t/I0QMzoMiEAAAAASUVORK5CYII=
@@ -48,6 +48,7 @@ const CHARS: &'static [char] = &[
];
pub const RENDEZVOUS_SERVERS: &'static [&'static str] = &[
"rs-ny.rustdesk.com",
"rs-sg.rustdesk.com",
"rs-cn.rustdesk.com",
];
@@ -271,6 +272,7 @@ impl Config {
}
pub fn log_path() -> PathBuf {
#[allow(unreachable_code)]
#[cfg(target_os = "macos")]
{
if let Some(path) = dirs_next::home_dir().as_mut() {
@@ -547,7 +549,7 @@ impl Config {
// to-do: how about if one ip register a lot of ids?
let id = Self::get_id();
let mut rng = rand::thread_rng();
let new_id = rng.gen_range(1_000_000_000, 2_000_000_000).to_string();
let new_id = rng.gen_range(1_000_000_000..2_000_000_000).to_string();
Config::set_id(&new_id);
log::info!("id updated from {} to {}", id, new_id);
}

View File

@@ -7,7 +7,7 @@ use crate::{
};
#[cfg(windows)]
use std::os::windows::prelude::*;
use tokio::{fs::File, prelude::*};
use tokio::{fs::File, io::*};
pub fn read_dir(path: &PathBuf, include_hidden: bool) -> ResultType<FileDirectory> {
let mut dir = FileDirectory {

View File

@@ -6,7 +6,6 @@ pub mod rendezvous_proto;
pub use bytes;
pub use futures;
pub use protobuf;
use socket2::{Domain, Socket, Type};
use std::{
fs::File,
io::{self, BufRead},
@@ -36,7 +35,7 @@ pub type Stream = tcp::FramedStream;
#[inline]
pub async fn sleep(sec: f32) {
tokio::time::delay_for(time::Duration::from_secs_f32(sec)).await;
tokio::time::sleep(time::Duration::from_secs_f32(sec)).await;
}
#[macro_export]
@@ -61,30 +60,6 @@ pub fn timeout<T: std::future::Future>(ms: u64, future: T) -> tokio::time::Timeo
tokio::time::timeout(std::time::Duration::from_millis(ms), future)
}
fn new_socket(addr: SocketAddr, tcp: bool, reuse: bool) -> Result<Socket, std::io::Error> {
let stype = {
if tcp {
Type::stream()
} else {
Type::dgram()
}
};
let socket = match addr {
SocketAddr::V4(..) => Socket::new(Domain::ipv4(), stype, None),
SocketAddr::V6(..) => Socket::new(Domain::ipv6(), stype, None),
}?;
if reuse {
// windows has no reuse_port, but it's reuse_address
// almost equals to unix's reuse_port + reuse_address,
// though may introduce nondeterministic bahavior
#[cfg(unix)]
socket.set_reuse_port(true)?;
socket.set_reuse_address(true)?;
}
socket.bind(&addr.into())?;
Ok(socket)
}
pub type ResultType<F, E = anyhow::Error> = anyhow::Result<F, E>;
/// Certain router and firewalls scan the packet and if they
@@ -100,10 +75,10 @@ impl AddrMangle {
.duration_since(UNIX_EPOCH)
.unwrap()
.as_micros() as u32) as u128;
let ip = u32::from_ne_bytes(addr_v4.ip().octets()) as u128;
let ip = u32::from_le_bytes(addr_v4.ip().octets()) as u128;
let port = addr.port() as u128;
let v = ((ip + tm) << 49) | (tm << 17) | (port + (tm & 0xFFFF));
let bytes = v.to_ne_bytes();
let bytes = v.to_le_bytes();
let mut n_padding = 0;
for i in bytes.iter().rev() {
if i == &0u8 {
@@ -123,9 +98,9 @@ impl AddrMangle {
pub fn decode(bytes: &[u8]) -> SocketAddr {
let mut padded = [0u8; 16];
padded[..bytes.len()].copy_from_slice(&bytes);
let number = u128::from_ne_bytes(padded);
let number = u128::from_le_bytes(padded);
let tm = (number >> 17) & (u32::max_value() as u128);
let ip = (((number >> 49) - tm) as u32).to_ne_bytes();
let ip = (((number >> 49) - tm) as u32).to_le_bytes();
let port = (number & 0xFFFFFF) - (tm & 0xFFFF);
SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]),

View File

@@ -1,16 +1,13 @@
use crate::{bail, bytes_codec::BytesCodec, ResultType};
use bytes::{BufMut, Bytes, BytesMut};
use futures::SinkExt;
use futures::{SinkExt, StreamExt};
use protobuf::Message;
use sodiumoxide::crypto::secretbox::{self, Key, Nonce};
use std::{
io::{Error, ErrorKind},
ops::{Deref, DerefMut},
};
use tokio::{
net::{TcpListener, TcpStream, ToSocketAddrs},
stream::StreamExt,
};
use tokio::net::{lookup_host, TcpListener, TcpSocket, TcpStream, ToSocketAddrs};
use tokio_util::codec::Framed;
pub struct FramedStream(Framed<TcpStream, BytesCodec>, Option<(Key, u64, u64)>);
@@ -29,25 +26,37 @@ impl DerefMut for FramedStream {
}
}
fn new_socket(addr: std::net::SocketAddr, reuse: bool) -> Result<TcpSocket, std::io::Error> {
let socket = match addr {
std::net::SocketAddr::V4(..) => TcpSocket::new_v4()?,
std::net::SocketAddr::V6(..) => TcpSocket::new_v6()?,
};
if reuse {
// windows has no reuse_port, but it's reuse_address
// almost equals to unix's reuse_port + reuse_address,
// though may introduce nondeterministic bahavior
#[cfg(unix)]
socket.set_reuseport(true)?;
socket.set_reuseaddr(true)?;
}
socket.bind(addr)?;
Ok(socket)
}
impl FramedStream {
pub async fn new<T: ToSocketAddrs, T2: ToSocketAddrs>(
remote_addr: T,
local_addr: T2,
ms_timeout: u64,
) -> ResultType<Self> {
for local_addr in local_addr.to_socket_addrs().await? {
for remote_addr in remote_addr.to_socket_addrs().await? {
if let Ok(stream) = super::timeout(
for local_addr in lookup_host(&local_addr).await? {
for remote_addr in lookup_host(&remote_addr).await? {
let stream = super::timeout(
ms_timeout,
TcpStream::connect_std(
super::new_socket(local_addr, true, true)?.into_tcp_stream(),
&remote_addr,
),
new_socket(local_addr, true)?.connect(remote_addr),
)
.await?
{
return Ok(Self(Framed::new(stream, BytesCodec::new()), None));
}
.await??;
return Ok(Self(Framed::new(stream, BytesCodec::new()), None));
}
}
bail!("could not resolve to any address");
@@ -124,22 +133,21 @@ impl FramedStream {
fn get_nonce(seqnum: u64) -> Nonce {
let mut nonce = Nonce([0u8; secretbox::NONCEBYTES]);
nonce.0[..std::mem::size_of_val(&seqnum)].copy_from_slice(&seqnum.to_ne_bytes());
nonce.0[..std::mem::size_of_val(&seqnum)].copy_from_slice(&seqnum.to_le_bytes());
nonce
}
}
const DEFAULT_BACKLOG: i32 = 128;
const DEFAULT_BACKLOG: u32 = 128;
#[allow(clippy::never_loop)]
pub async fn new_listener<T: ToSocketAddrs>(addr: T, reuse: bool) -> ResultType<TcpListener> {
if !reuse {
Ok(TcpListener::bind(addr).await?)
} else {
for addr in addr.to_socket_addrs().await? {
let socket = super::new_socket(addr, true, true)?;
socket.listen(DEFAULT_BACKLOG)?;
return Ok(TcpListener::from_std(socket.into_tcp_listener())?);
for addr in lookup_host(&addr).await? {
let socket = new_socket(addr, true)?;
return Ok(socket.listen(DEFAULT_BACKLOG)?);
}
bail!("could not resolve to any address");
}

View File

@@ -1,13 +1,14 @@
use crate::{bail, ResultType};
use bytes::BytesMut;
use futures::SinkExt;
use futures::{SinkExt, StreamExt};
use protobuf::Message;
use socket2::{Domain, Socket, Type};
use std::{
io::Error,
net::SocketAddr,
ops::{Deref, DerefMut},
};
use tokio::{net::ToSocketAddrs, net::UdpSocket, stream::StreamExt};
use tokio::{net::ToSocketAddrs, net::UdpSocket};
use tokio_util::{codec::BytesCodec, udp::UdpFramed};
pub struct FramedSocket(UdpFramed<BytesCodec>);
@@ -20,6 +21,23 @@ impl Deref for FramedSocket {
}
}
fn new_socket(addr: SocketAddr, reuse: bool) -> Result<Socket, std::io::Error> {
let socket = match addr {
SocketAddr::V4(..) => Socket::new(Domain::ipv4(), Type::dgram(), None),
SocketAddr::V6(..) => Socket::new(Domain::ipv6(), Type::dgram(), None),
}?;
if reuse {
// windows has no reuse_port, but it's reuse_address
// almost equals to unix's reuse_port + reuse_address,
// though may introduce nondeterministic bahavior
#[cfg(unix)]
socket.set_reuse_port(true)?;
socket.set_reuse_address(true)?;
}
socket.bind(&addr.into())?;
Ok(socket)
}
impl DerefMut for FramedSocket {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
@@ -33,10 +51,10 @@ impl FramedSocket {
}
#[allow(clippy::never_loop)]
pub async fn new_reuse<T: ToSocketAddrs>(addr: T) -> ResultType<Self> {
for addr in addr.to_socket_addrs().await? {
pub async fn new_reuse<T: std::net::ToSocketAddrs>(addr: T) -> ResultType<Self> {
for addr in addr.to_socket_addrs()? {
return Ok(Self(UdpFramed::new(
UdpSocket::from_std(super::new_socket(addr, false, true)?.into_udp_socket())?,
UdpSocket::from_std(new_socket(addr, true)?.into_udp_socket())?,
BytesCodec::new(),
)));
}

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.7"
tokio = { version = "0.2", features = ["io-driver", "io-util", "uds", "stream", "rt-core", "macros", "time"] }
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, prelude::*};
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::delay_for(std::time::Duration::from_secs(2)).await;
}
}

View File

@@ -1,47 +0,0 @@
use futures::StreamExt as _;
use tokio::{
prelude::*,
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,154 +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, Incoming};
#[cfg(unix)]
pub use unix::{SecurityAttributes, Endpoint, Connection, 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 tokio::prelude::*;
use futures::{channel::oneshot, StreamExt as _, FutureExt as _};
use std::time::Duration;
use tokio::{
self,
io::split,
};
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::delay_for(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::delay_for(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::delay_for(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,163 +0,0 @@
use libc::chmod;
use std::ffi::CString;
use std::io::{self, Error};
use tokio::prelude::*;
use tokio::net::{UnixListener, UnixStream};
use std::path::Path;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::mem::MaybeUninit;
/// 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 {
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [MaybeUninit<u8>]) -> bool {
self.inner.prepare_uninitialized_buffer(buf)
}
fn poll_read(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
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, io::Error>> {
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<(), io::Error>> {
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<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_shutdown(ctx)
}
}

View File

@@ -1,488 +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::ptr;
use futures::Stream;
use tokio::prelude::*;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::path::Path;
use std::mem::MaybeUninit;
use tokio::io::PollEvented;
type NamedPipe = PollEvented<mio_named_pipes::NamedPipe>;
const PIPE_AVAILABILITY_TIMEOUT: u64 = 5000;
/// Endpoint implementation for windows
pub struct Endpoint {
path: String,
security_attributes: SecurityAttributes,
}
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<NamedPipe> {
use miow::pipe::NamedPipeBuilder;
use std::os::windows::io::*;
let raw_handle = unsafe {
NamedPipeBuilder::new(&self.path)
.first(true)
.inbound(true)
.outbound(true)
.out_buffer_size(65536)
.in_buffer_size(65536)
.with_security_attributes(self.security_attributes.as_ptr())?
.into_raw_handle()
};
let mio_pipe = unsafe { mio_named_pipes::NamedPipe::from_raw_handle(raw_handle) };
NamedPipe::new(mio_pipe)
}
/// 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<Connection> {
Ok(Connection::wrap(Self::connect_inner(path.as_ref())?))
}
fn connect_inner(path: &Path) -> io::Result<NamedPipe> {
use std::fs::OpenOptions;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::{FromRawHandle, IntoRawHandle};
use winapi::um::winbase::FILE_FLAG_OVERLAPPED;
// Wait for the pipe to become available or fail after 5 seconds.
miow::pipe::NamedPipe::wait(
path,
Some(std::time::Duration::from_millis(PIPE_AVAILABILITY_TIMEOUT)),
)?;
let file = OpenOptions::new()
.read(true)
.write(true)
.custom_flags(FILE_FLAG_OVERLAPPED)
.open(path)?;
let mio_pipe =
unsafe { mio_named_pipes::NamedPipe::from_raw_handle(file.into_raw_handle()) };
let pipe = NamedPipe::new(mio_pipe)?;
Ok(pipe)
}
/// New IPC endpoint at the given path
pub fn new(path: String) -> Self {
Endpoint {
path,
security_attributes: SecurityAttributes::empty(),
}
}
}
struct NamedPipeSupport {
path: String,
pipe: NamedPipe,
security_attributes: SecurityAttributes,
}
impl NamedPipeSupport {
fn replacement_pipe(&mut self) -> io::Result<NamedPipe> {
use miow::pipe::NamedPipeBuilder;
use std::os::windows::io::*;
let raw_handle = unsafe {
NamedPipeBuilder::new(&self.path)
.first(false)
.inbound(true)
.outbound(true)
.out_buffer_size(65536)
.in_buffer_size(65536)
.with_security_attributes(self.security_attributes.as_ptr())?
.into_raw_handle()
};
let mio_pipe = unsafe { mio_named_pipes::NamedPipe::from_raw_handle(raw_handle) };
NamedPipe::new(mio_pipe)
}
}
/// Stream of incoming connections
pub struct Incoming {
#[allow(dead_code)]
path: String,
inner: NamedPipeSupport,
}
impl Stream for Incoming {
type Item = tokio::io::Result<Connection>;
fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.inner.pipe.get_ref().connect() {
Ok(()) => {
log::trace!("Incoming connection polled successfully");
let new_listener = self.inner.replacement_pipe()?;
Poll::Ready(
Some(Ok(Connection::wrap(std::mem::replace(&mut self.inner.pipe, new_listener))))
)
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
self.inner.pipe.clear_write_ready(ctx);
Poll::Pending
} else {
Poll::Ready(Some(Err(e)))
}
}
}
}
}
/// IPC connection.
pub struct Connection {
inner: NamedPipe,
}
impl Connection {
pub fn wrap(pipe: NamedPipe) -> Self {
Self { inner: pipe }
}
}
impl AsyncRead for Connection {
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [MaybeUninit<u8>]) -> bool {
self.inner.prepare_uninitialized_buffer(buf)
}
fn poll_read(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
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, io::Error>> {
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<(), io::Error>> {
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<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_shutdown(ctx)
}
}
/// 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();
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.0"
[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>

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