aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: d8e3e319218d31631ad3dbc93ec2ea9083390d12 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
extern crate libc;
extern crate steamworks_sys as sys;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate bitflags;

pub mod error;
pub use error::Result as SResult;
use error::ErrorKind;

mod utils;
pub use utils::*;
mod app;
pub use app::*;
mod friends;
pub use friends::*;

use std::sync::{Arc, Mutex};
use std::ffi::{CString, CStr};
use std::borrow::Cow;
use std::fmt::{
    Debug, Formatter, self
};

// A note about thread-safety:
// The steam api is assumed to be thread safe unless
// the documentation for a method states otherwise,
// however this is never stated anywhere in the docs
// that I could see.

/// The main entry point into the steam client.
///
/// This provides access to all of the steamworks api.
#[derive(Clone)]
pub struct Client {
    inner: Arc<ClientInner>,
}

struct ClientInner {
    client: *mut sys::ISteamClient,
    pipe: sys::HSteamPipe,

    callbacks: Mutex<Vec<*mut libc::c_void>>,
}

unsafe impl Send for ClientInner {}
unsafe impl Sync for ClientInner {}

impl Client {
    /// Attempts to initialize the steamworks api and returns
    /// a client to access the rest of the api.
    ///
    /// This should only ever have one instance per a program.
    ///
    /// # Errors
    ///
    /// This can fail if:
    /// * The steam client isn't running
    /// * The app ID of the game couldn't be determined.
    ///
    ///   If the game isn't being run through steam this can be provided by
    ///   placing a `steam_appid.txt` with the ID inside in the current
    ///   working directory
    /// * The game isn't running on the same user/level as the steam client
    /// * The user doesn't own a license for the game.
    /// * The app ID isn't completely set up.
    pub fn init() -> SResult<Client> {
        unsafe {
            if sys::SteamAPI_Init() == 0 {
                bail!(ErrorKind::InitFailed);
            }
            let client = sys::SteamInternal_CreateInterface(sys::STEAMCLIENT_INTERFACE_VERSION.as_ptr() as *const _);
            let client = Arc::new(ClientInner {
                client: client,
                pipe: sys::SteamAPI_ISteamClient_CreateSteamPipe(client),
                callbacks: Mutex::new(Vec::new()),
            });
            Ok(Client {
                inner: client,
            })
        }
    }

    /// Runs any currently pending callbacks
    ///
    /// This runs all currently pending callbacks on the current
    /// thread.
    ///
    /// This should be called frequently (e.g. once per a frame)
    /// in order to reduce the latency between recieving events.
    pub fn run_callbacks(&self) {
        unsafe {
            sys::SteamAPI_RunCallbacks();
        }
    }

    /// Registers the passed function as a callback for the
    /// given type.
    ///
    /// The callback will be run on the thread that `run_callbacks`
    /// is called when the event arrives.
    pub fn register_callback<C, F>(&self, f: F)
        where C: Callback,
              F: FnMut(C) + 'static + Send + Sync
    {
        unsafe {
            let userdata = Box::into_raw(Box::new(f));

            extern "C" fn run_func<C, F>(userdata: *mut libc::c_void, param: *mut libc::c_void)
                where C: Callback,
                      F: FnMut(C) + 'static
            {
                unsafe {
                    let func: &mut F = &mut *(userdata as *mut F);
                    let param = C::from_raw(param);
                    func(param);
                }
            }
            extern "C" fn dealloc<C, F>(userdata: *mut libc::c_void)
                where C: Callback,
                      F: FnMut(C) + 'static
            {
                let func: Box<F> = unsafe { Box::from_raw(userdata as _) };
                drop(func);
            }

            let ptr = sys::register_rust_steam_callback(
                C::size() as _,
                userdata as _,
                run_func::<C, F>,
                dealloc::<C, F>,
                C::id() as _
            );
            let mut cbs = self.inner.callbacks.lock().unwrap();
            cbs.push(ptr);
        }
    }

    /// Returns an accessor to the steam utils interface
    pub fn utils(&self) -> Utils {
        unsafe {
            let utils = sys::SteamAPI_ISteamClient_GetISteamUtils(
                self.inner.client, self.inner.pipe,
                sys::STEAMUTILS_INTERFACE_VERSION.as_ptr() as *const _
            );
            assert!(!utils.is_null());
            Utils {
                utils: utils,
                _client: self.inner.clone(),
            }
        }
    }

    /// Returns an accessor to the steam apps interface
    pub fn apps(&self) -> Apps {
        unsafe {
            let user = sys::SteamAPI_ISteamClient_ConnectToGlobalUser(self.inner.client, self.inner.pipe);
            let apps = sys::SteamAPI_ISteamClient_GetISteamApps(
                self.inner.client, user, self.inner.pipe,
                sys::STEAMAPPS_INTERFACE_VERSION.as_ptr() as *const _
            );
            assert!(!apps.is_null());
            Apps {
                apps: apps,
                _client: self.inner.clone(),
            }
        }
    }

    /// Returns an accessor to the steam friends interface
    pub fn friends(&self) -> Friends {
        unsafe {
            let user = sys::SteamAPI_ISteamClient_ConnectToGlobalUser(self.inner.client, self.inner.pipe);
            let friends = sys::SteamAPI_ISteamClient_GetISteamFriends(
                self.inner.client, user, self.inner.pipe,
                sys::STEAMFRIENDS_INTERFACE_VERSION.as_ptr() as *const _
            );
            assert!(!friends.is_null());
            Friends {
                friends: friends,
                _client: self.inner.clone(),
            }
        }

    }
}

impl Drop for ClientInner {
    fn drop(&mut self) {
        unsafe {
            for cb in &**self.callbacks.lock().unwrap() {
                sys::unregister_rust_steam_callback(*cb);
            }
            debug_assert!(sys::SteamAPI_ISteamClient_BReleaseSteamPipe(self.client, self.pipe) != 0);
            sys::SteamAPI_Shutdown();
        }
    }
}

/// A user's steam id
#[derive(Clone, Copy, Debug)]
pub struct SteamId(pub(crate) u64);

pub unsafe trait Callback {
    fn id() -> i32;
    fn size() -> i32;
    unsafe fn from_raw(raw: *mut libc::c_void) -> Self;
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn basic_test() {
        let client = Client::init().unwrap();

        client.register_callback(|p: PersonaStateChange| {
            println!("Got callback: {:?}", p);
        });

        let utils = client.utils();
        println!("Utils:");
        println!("AppId: {:?}", utils.app_id());
        println!("UI Language: {}", utils.ui_language());

        let apps = client.apps();
        println!("Apps");
        println!("IsInstalled(480): {}", apps.is_app_installed(AppId(480)));
        println!("InstallDir(480): {}", apps.app_install_dir(AppId(480)));
        println!("BuildId: {}", apps.app_build_id());
        println!("AppOwner: {:?}", apps.app_owner());
        println!("Langs: {:?}", apps.available_game_languages());
        println!("Lang: {}", apps.current_game_language());
        println!("Beta: {:?}", apps.current_beta_name());

        let friends = client.friends();
        println!("Friends");
        let list = friends.get_friends(FriendFlags::IMMEDIATE);
        println!("{:?}", list);
        for f in &list {
            println!("Friend: {:?} - {}({:?})", f.id(), f.name(), f.state());
            friends.request_user_information(f.id(), true);
        }
        friends.request_user_information(SteamId(76561198174976054), true);

        for _ in 0 .. 50 {
            client.run_callbacks();
            ::std::thread::sleep(::std::time::Duration::from_millis(100));
        }
    }
}