1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Types and functionalities to declare and initialize gdnative classes.
//!
//! ## API endpoints
//!
//! Three endpoints are automatically invoked by the engine during startup and shutdown:
//!
//! - [`godot_gdnative_init`](macro.godot_gdnative_init.html),
//! - [`godot_nativescript_init`](macro.godot_nativescript_init.html),
//! - [`godot_gdnative_terminate`](macro.godot_gdnative_terminate.html),
//!
//! All three must be present.
//!
//! ## Registering a class using the `godot_class` macro
//!
//! See the [spinning_cube example](https://github.com/GodotNativeTools/godot-rust/tree/master/examples/spinning_cube)
//! in the repositiory.
//!
//! ## Registering a class manually
//!
//! See the [manually_registered example](https://github.com/GodotNativeTools/godot-rust/tree/master/examples/manually_registered)
//! in the repositiory.
//!

use super::*;
use get_api;
use Variant;
use ToVariant;
use NativeClass;
use std::mem;
use std::ops::Range;
use std::ffi::CString;
use std::marker::PhantomData;
use std::ptr;
use libc;

/// A handle that can register new classes to the engine during initialization.
///
/// See [`godot_nativescript_init`](macro.godot_nativescript_init.html).
#[derive(Copy, Clone)]
pub struct InitHandle {
    #[doc(hidden)]
    handle: *mut libc::c_void,
}

impl InitHandle {
    #[doc(hidden)]
    pub unsafe fn new(handle: *mut libc::c_void) -> Self { InitHandle { handle } }

    /// Registers a new class to the engine.
    ///
    /// The return `ClassBuilder` can be used to add methods, signals and properties
    /// to the class.
    pub fn add_class<C>(&self, desc: ClassDescriptor) -> ClassBuilder<C>
    where C: NativeClass {
        unsafe {
            let class_name = CString::new(desc.name).unwrap();
            let base_name = CString::new(desc.base_class).unwrap();

            let create = sys::godot_instance_create_func {
                create_func: desc.constructor,
                method_data: ptr::null_mut(),
                free_func: None,
            };

            let destroy = sys::godot_instance_destroy_func {
                destroy_func: desc.destructor,
                method_data: ptr::null_mut(),
                free_func: None,
            };

            (get_api().godot_nativescript_register_class)(
                self.handle as *mut _,
                class_name.as_ptr() as *const _,
                base_name.as_ptr() as *const _,
                create,
                destroy
            );

            ClassBuilder {
                init_handle: self.handle,
                class_name,
                _marker: PhantomData,
            }
        }
    }
}

pub type ScriptMethodFn = unsafe extern "C" fn(
    *mut sys::godot_object,
    *mut libc::c_void,
    *mut libc::c_void,
    libc::c_int,
    *mut *mut sys::godot_variant
) -> sys::godot_variant;

pub type ScriptConstructorFn = unsafe extern "C" fn(
    *mut sys::godot_object,
    *mut libc::c_void
) -> *mut libc::c_void;

pub type ScriptDestructorFn = unsafe extern "C" fn(
    *mut sys::godot_object,
    *mut libc::c_void,
    *mut libc::c_void
) -> ();

pub enum RpcMode {
    Disabled,
    Remote,
    Sync,
    Mater,
    Slave
}

pub struct ScriptMethodAttributes {
    pub rpc_mode: RpcMode
}

pub struct ScriptMethod<'l> {
    pub name: &'l str,
    pub method_ptr: Option<ScriptMethodFn>,
    pub attributes: ScriptMethodAttributes,

    pub method_data: *mut libc::c_void,
    pub free_func: Option<unsafe extern "C" fn(*mut libc::c_void) -> ()>,
}

pub struct ClassDescriptor<'l> {
    pub name: &'l str,
    pub base_class: &'l str,
    pub constructor: Option<ScriptConstructorFn>,
    pub destructor: Option<ScriptDestructorFn>,
}

pub struct ClassBuilder<C: NativeClass> {
    #[doc(hidden)]
    pub init_handle: *mut libc::c_void,
    class_name: CString,
    _marker: PhantomData<C>,
}

impl<C: NativeClass> ClassBuilder<C> {

    pub fn add_method_advanced(&self, method: ScriptMethod) {
        let method_name = CString::new(method.name).unwrap();
        let attr = sys::godot_method_attributes {
            rpc_type: sys::godot_method_rpc_mode_GODOT_METHOD_RPC_MODE_DISABLED
        };

        let method_desc = sys::godot_instance_method {
            method: method.method_ptr,
            method_data: method.method_data,
            free_func: method.free_func
        };

        unsafe {
            (get_api().godot_nativescript_register_method)(
                self.init_handle,
                self.class_name.as_ptr() as *const _,
                method_name.as_ptr() as *const _,
                attr,
                method_desc
            );
        }
    }

    pub fn add_method(&self, name: &str, method: ScriptMethodFn) {
        self.add_method_advanced(
            ScriptMethod {
                name: name,
                method_ptr: Some(method),
                attributes: ScriptMethodAttributes {
                    rpc_mode: RpcMode::Disabled
                },
                method_data: ptr::null_mut(),
                free_func: None
            },
        );
    }

    pub fn add_property<T, S, G>(&self, property: Property<T, S, G>)
    where
        T: ToVariant,
        S: PropertySetter<C, T>,
        G: PropertyGetter<C, T>,
    {
        unsafe {
            let hint_text = match property.hint {
                PropertyHint::Range { ref range, step, slider } => {

                    if slider {
                        Some(format!("{},{},{},slider", range.start, range.end, step))
                    } else {
                        Some(format!("{},{},{}", range.start, range.end, step))
                    }
                }
                PropertyHint::Enum { values } | PropertyHint::Flags { values } => { Some(values.join(",")) }
                PropertyHint::NodePathToEditedNode | PropertyHint::None => { None }
            };
            let hint_string = if let Some(text) = hint_text {
                GodotString::from_str(text)
            } else {
                GodotString::default()
            };

            let default: Variant = property.default.to_variant();
            let ty = default.get_type();

            let mut attr = sys::godot_property_attributes {
                rset_type: sys::godot_method_rpc_mode_GODOT_METHOD_RPC_MODE_DISABLED, // TODO:
                type_: mem::transmute(ty),
                hint: property.hint.to_sys(),
                hint_string: hint_string.to_sys(),
                usage: property.usage.to_sys(),
                default_value: default.to_sys(),
            };

            let path = ::std::ffi::CString::new(property.name).unwrap();

            let set = property.setter.as_godot_function();
            let get = property.getter.as_godot_function();

            (get_api().godot_nativescript_register_property)(
                self.init_handle,
                self.class_name.as_ptr(),
                path.as_ptr() as *const _,
                &mut attr, set, get
            );
        }
    }

    pub fn add_signal(&self, signal: Signal) {
        use std::ptr;
        unsafe {
            let name = GodotString::from_str(signal.name);
            let mut args = signal.args
                .iter()
                .map(|arg| {
                    let arg_name = GodotString::from_str(arg.name);
                    let hint_string = GodotString::new();
                    sys::godot_signal_argument {
                        name: arg_name.to_sys(),
                        type_: arg.default.get_type() as i32,
                        hint: arg.hint.to_sys(),
                        hint_string: hint_string.to_sys(),
                        usage: arg.usage.to_sys(),
                        default_value: arg.default.to_sys(),
                    }
                })
                .collect::<Vec<_>>();
            (get_api().godot_nativescript_register_signal)(
                self.init_handle,
                self.class_name.as_ptr(),
                &sys::godot_signal {
                    name: name.to_sys(),
                    num_args: args.len() as i32,
                    args: args.as_mut_ptr(),
                    num_default_args: 0,
                    default_args: ptr::null_mut(),
                }
            );
        }
    }
}

// TODO: missing property hints.
pub enum PropertyHint<'l> {
    None,
    Range {
        range: Range<f64>,
        step: f64,
        slider: bool,
    },
    // ExpRange,
    Enum {
        values: &'l[&'l str],
    },
    // ExpEasing,
    // Length,
    // SpriteFrame,
    // KeyAccel,
    Flags {
        values: &'l[&'l str],
    },
    // Layers2DRender,
    // Layers2DPhysics,
    // Layers3DRender,
    // Layers3DPhysics,
    // File,
    // Dir,
    // GlobalFile,
    // GlobalDir,
    // ResourceType,
    // MultilineText,
    // ColorNoAlpha,
    // ImageCompressLossy,
    // IMageCompressLossless,
    // ObjectID,
    // TypeString,
    NodePathToEditedNode,
    // MethodOfVariantType,
    // MethodOfBaseType,
    // MethodOfInstance,
    // MethodOfScript,
    // PropertyOfVariantType,
    // PropertyOfBaseType,
    // PropertyOfInstance,
    // PropertyOfScript,
}

impl<'l> PropertyHint<'l> {
    pub fn to_sys(&self) -> sys::godot_property_hint {
        match *self {
            PropertyHint::None => sys::godot_property_hint_GODOT_PROPERTY_HINT_NONE,
            PropertyHint::Range { .. } => sys::godot_property_hint_GODOT_PROPERTY_HINT_RANGE,
            PropertyHint::Enum { .. } => sys::godot_property_hint_GODOT_PROPERTY_HINT_ENUM,
            PropertyHint::Flags { .. } => sys::godot_property_hint_GODOT_PROPERTY_HINT_FLAGS,
            PropertyHint::NodePathToEditedNode => sys::godot_property_hint_GODOT_PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE,
        }
    }
}

bitflags! {
    pub struct PropertyUsage: u32 {
        const STORAGE = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_STORAGE;
        const EDITOR = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_EDITOR;
        const NETWORK = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_NETWORK;
        const EDITOR_HELPER = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_EDITOR_HELPER;
        const CHECKABLE = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_CHECKABLE;
        const CHECKED = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_CHECKED;
        const INTERNATIONALIZED = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_INTERNATIONALIZED;
        const GROUP = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_GROUP;
        const CATEGORY = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_CATEGORY;
        const STORE_IF_NONZERO = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_STORE_IF_NONZERO;
        const STORE_IF_NONONE = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_STORE_IF_NONONE;
        const NO_INSTANCE_STATE = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_NO_INSTANCE_STATE;
        const RESTART_IF_CHANGED = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_RESTART_IF_CHANGED;
        const SCRIPT_VARIABLE  = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_SCRIPT_VARIABLE;
        const STORE_IF_NULL = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_STORE_IF_NULL;
        const ANIMATE_AS_TRIGGER = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_ANIMATE_AS_TRIGGER;
        const UPDATE_ALL_IF_MODIFIED = sys::godot_property_usage_flags_GODOT_PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED;

        const DEFAULT = Self::STORAGE.bits | Self::EDITOR.bits | Self::NETWORK.bits;
        const DEFAULT_INTL = Self::DEFAULT.bits | Self::INTERNATIONALIZED.bits;
        const NOEDITOR = Self::STORAGE.bits | Self::NETWORK.bits;
    }
}

impl PropertyUsage {
    pub fn to_sys(&self) -> sys::godot_property_usage_flags {
        unsafe { mem::transmute(*self) }
    }
}

pub struct Property<'l, T, S, G>
{
    pub name: &'l str,
    pub setter: S,
    pub getter: G,
    pub default: T,
    pub hint: PropertyHint<'l>,
    pub usage: PropertyUsage,
}

pub struct SignalArgument<'l> {
    pub name: &'l str,
    pub default: Variant,
    pub hint: PropertyHint<'l>,
    pub usage: PropertyUsage,
}

pub struct Signal<'l> {
    pub name: &'l str,
    pub args: &'l [SignalArgument<'l>],
}

pub unsafe trait PropertySetter<C: NativeClass, T: ToVariant> {
    unsafe fn as_godot_function(self) -> sys::godot_property_set_func;
}

pub unsafe trait PropertyGetter<C: NativeClass, T: ToVariant> {
    unsafe fn as_godot_function(self) -> sys::godot_property_get_func;
}

extern "C" fn empty_setter(
    _this: *mut sys::godot_object,
    _method: *mut libc::c_void,
    _class: *mut libc::c_void,
    _val: *mut sys::godot_variant
) {}

extern "C" fn empty_getter(
    _this: *mut sys::godot_object,
    _method: *mut libc::c_void,
    _class: *mut libc::c_void
) -> sys::godot_variant {
    Variant::new().forget()
}

extern "C" fn empty_free_func(_data: *mut libc::c_void) {}

unsafe impl <C: NativeClass, T: ToVariant> PropertySetter<C, T> for () {
    unsafe fn as_godot_function(self) -> sys::godot_property_set_func {
        let mut set = sys::godot_property_set_func::default();
        set.set_func = Some(empty_setter);
        set.free_func = Some(empty_free_func);
        set
    }
}

unsafe impl <C: NativeClass, T: ToVariant> PropertyGetter<C, T> for () {
    unsafe fn as_godot_function(self) -> sys::godot_property_get_func {
        let mut get = sys::godot_property_get_func::default();
        get.get_func = Some(empty_getter);
        get.free_func = Some(empty_free_func);
        get
    }
}

unsafe impl <F, C, T> PropertySetter<C, T> for F
    where C: NativeClass,
          T: ToVariant,
          F: Fn(&mut C, T),
{
    unsafe fn as_godot_function(self) -> sys::godot_property_set_func {
        use std::cell::RefCell;
        let mut set = sys::godot_property_set_func::default();
        let data = Box::new(self);
        set.method_data = Box::into_raw(data) as *mut _;

        extern "C" fn invoke<C, F, T>(_this: *mut sys::godot_object, method: *mut libc::c_void, class: *mut libc::c_void, val: *mut sys::godot_variant)
            where C: NativeClass,
                T: ToVariant,
                F: Fn(&mut C, T),

        {
            unsafe {
                let rust_ty = &*(class as *mut RefCell<C>);
                let mut rust_ty = rust_ty.borrow_mut();
                let func = &mut *(method as *mut F);

                if let Some(val) = T::from_variant(Variant::cast_ref(val)) {
                    func(&mut *rust_ty, val);
                } else {
                    godot_error!("Incorrect type passed to property");
                }
            }
        }
        set.set_func = Some(invoke::<C, F, T>);

        extern "C" fn free_func<F>(data: *mut libc::c_void) {
            unsafe {
                drop(Box::from_raw(data as *mut F));
            }
        }
        set.free_func = Some(free_func::<F>);

        set
    }
}

unsafe impl <F, C, T> PropertyGetter<C, T> for F
    where C: NativeClass,
          T: ToVariant,
          F: Fn(&mut C) -> T,
{
    unsafe fn as_godot_function(self) -> sys::godot_property_get_func {
        use std::cell::RefCell;
        let mut get = sys::godot_property_get_func::default();
        let data = Box::new(self);
        get.method_data = Box::into_raw(data) as *mut _;

        extern "C" fn invoke<C, F, T>(_this: *mut sys::godot_object, method: *mut libc::c_void, class: *mut libc::c_void) -> sys::godot_variant
            where C: NativeClass,
                T: ToVariant,
                F: Fn(&mut C) -> T,

        {
            unsafe {
                let rust_ty = &*(class as *mut RefCell<C>);
                let mut rust_ty = rust_ty.borrow_mut();
                let func = &mut *(method as *mut F);
                let ret = func(&mut *rust_ty);
                ret.to_variant().forget()
            }
        }
        get.get_func = Some(invoke::<C, F, T>);

        extern "C" fn free_func<F>(data: *mut libc::c_void) {
            unsafe {
                drop(Box::from_raw(data as *mut F));
            }
        }
        get.free_func = Some(free_func::<F>);

        get
    }
}