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
use crate::session::Session;
use std::{borrow::Cow, ops::Deref};
use widestring::{WideCStr, WideCString, WideChar};

pub use std::{marker::PhantomData, ptr::NonNull};

#[cfg(feature = "visualobject")]
pub use winapi::shared::{minwindef::HINSTANCE, windef::HWND};

pub mod ffi;

pub type pbint = i16;
pub type pbuint = u16;
pub type pblong = i32;
pub type pbulong = u32;
pub type pblonglong = i64;
pub type pbbyte = u8;
pub type pbreal = f32;
pub type pbdouble = f64;

#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, Eq, Default)]
pub struct pbboolean(i16);

impl pbboolean {
    #[inline]
    pub fn to_bool(self) -> bool {
        if self.0 == 1 {
            true
        } else {
            false
        }
    }
}

impl PartialEq<bool> for pbboolean {
    fn eq(&self, other: &bool) -> bool { self.to_bool() == *other }
}

impl From<bool> for pbboolean {
    fn from(b: bool) -> Self {
        pbboolean(if b {
            1
        } else {
            0
        })
    }
}

impl From<pbboolean> for bool {
    fn from(b: pbboolean) -> Self { b.to_bool() }
}

pub type LPCTSTR = *const WideChar;
pub type PBChar = WideChar;
pub type PBStr = WideCStr;
pub type PBString = WideCString;

/// `PBStr`抽象
pub trait AsPBStr {
    fn as_pbstr(&self) -> Cow<'_, PBStr>;
}

impl AsPBStr for &PBStr {
    fn as_pbstr(&self) -> Cow<'_, PBStr> { (*self).into() }
}
impl AsPBStr for PBString {
    fn as_pbstr(&self) -> Cow<'_, PBStr> { self.deref().into() }
}
impl AsPBStr for String {
    fn as_pbstr(&self) -> Cow<'_, PBStr> {
        PBString::from_str(self).expect("incompatible utf-8 string").into()
    }
}
impl AsPBStr for &str {
    fn as_pbstr(&self) -> Cow<'_, PBStr> {
        PBString::from_str(self).expect("incompatible utf-8 string").into()
    }
}
impl AsPBStr for Cow<'_, PBStr> {
    fn as_pbstr(&self) -> Cow<'_, PBStr> { self.as_ref().into() }
}

pub trait FromPBStrPtr {
    unsafe fn from_pbstr_unchecked(ptr: LPCTSTR) -> Self;
}

impl FromPBStrPtr for String {
    unsafe fn from_pbstr_unchecked(ptr: LPCTSTR) -> Self { PBStr::from_ptr_str(ptr).to_string_lossy() }
}
impl FromPBStrPtr for PBString {
    unsafe fn from_pbstr_unchecked(ptr: LPCTSTR) -> Self { PBStr::from_ptr_str(ptr).to_ucstring() }
}

pub fn type_id<T: ?Sized + 'static>() -> u64 {
    use std::any::TypeId;
    let tid = TypeId::of::<T>();
    unsafe { *(&tid as *const TypeId as *const u64) }
}

macro_rules! declare_handle {
    ($name:ident, $inner:ident) => {
        #[repr(C)]
        pub struct $inner([u8; 0]);
        pub type $name = NonNull<$inner>;
    };
}

declare_handle!(pbvm, _IPB_VM);
declare_handle!(pbsession, _IPB_Session);
declare_handle!(pbvalue, _IPB_Value);
declare_handle!(pbarguments, _IPB_Arguments);
declare_handle!(pbclass, _pbclass);
declare_handle!(pbgroup, _pbgroup);
declare_handle!(pbstring, _pbstring);
declare_handle!(pbobject, _pbobject);
declare_handle!(pbarray, _pbarray);
declare_handle!(pbdec, _pbdec);
declare_handle!(pbdate, _pbdate);
declare_handle!(pbtime, _pbtime);
declare_handle!(pbdatetime, _pbdatetime);
declare_handle!(pbblob, _pbblob);
declare_handle!(pbuserobject, _IUserObject);

#[cfg(feature = "nonvisualobject")]
#[repr(C)]
pub struct NVOM<T: Sized> {
    pub ctx: NonNull<T>,
    pub type_id: u64,
    pub destory: unsafe extern "C" fn(NonNull<T>),
    pub invoke: unsafe extern "C" fn(NonNull<T>, Session, pbobject, MethodId, pbcallinfo) -> PBXRESULT
}

#[cfg(feature = "visualobject")]
#[repr(C)]
pub struct VOM<T: Sized> {
    pub ctx: NonNull<T>,
    pub type_id: u64,
    pub cls_name: LPCTSTR,
    pub destory: unsafe extern "C" fn(NonNull<T>),
    pub invoke: unsafe extern "C" fn(NonNull<T>, Session, pbobject, MethodId, pbcallinfo) -> PBXRESULT,
    pub create_control:
        unsafe extern "C" fn(NonNull<T>, u32, LPCTSTR, u32, i32, i32, i32, i32, HWND, HINSTANCE) -> HWND,
    pub get_event_id: unsafe extern "C" fn(NonNull<T>, HWND, u16, u32, u32) -> i32
}

#[repr(C)]
pub struct _PBCallInfo {
    pub pArgs: pbarguments,
    pub returnValue: pbvalue,
    pub returnClass: pbclass
}
pub type pbcallinfo = NonNull<_PBCallInfo>;

#[repr(C)]
pub struct _PBArrayInfo {
    // OUT variable, automatically set by GetArrayInfo(), don't set manually
    pub arrayType: ArrayType,
    pub itemGroup: pbgroup,
    pub valueType: ValueType,
    pub numDimensions: pbuint,
    pub bounds: [ArrayBound; 0]
}
pub type pbarrayinfo = NonNull<_PBArrayInfo>;

#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum ArrayType {
    BoundedArray,
    UnboundedArray
}

#[repr(C)]
pub struct ArrayBound {
    pub upperBound: pblong,
    pub lowerBound: pblong
}

/// 函数ID
#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct MethodId(u16);

impl MethodId {
    /// 创建一个函数ID
    ///
    /// # Safety
    ///
    /// 指定无效的函数ID可能导致未定义行为
    pub unsafe fn new(id: u16) -> MethodId { MethodId(id) }

    /// 函数ID的值
    pub fn value(self) -> u16 { self.0 }

    pub(crate) fn is_undefined(self) -> bool {
        const kUndefinedMethodID: u16 = 0xffff;
        self.0 == kUndefinedMethodID
    }
}

impl PartialEq<u16> for MethodId {
    fn eq(&self, other: &u16) -> bool { self.0.eq(other) }
}
impl PartialOrd<u16> for MethodId {
    fn partial_cmp(&self, other: &u16) -> Option<std::cmp::Ordering> { self.0.partial_cmp(other) }
}

/// 字段ID
#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FieldId(u16);

impl FieldId {
    /// 创建一个字段ID
    ///
    /// # Safety
    ///
    /// 指定无效的字段ID可能导致未定义行为
    pub unsafe fn new(id: u16) -> FieldId { FieldId(id) }

    /// 字段ID的值
    pub fn value(self) -> u16 { self.0 }

    pub(crate) fn is_undefined(self) -> bool {
        const kUndefinedFieldID: u16 = 0xffff;
        self.0 == kUndefinedFieldID
    }
}

impl PartialEq<u16> for FieldId {
    fn eq(&self, other: &u16) -> bool { self.0.eq(other) }
}
impl PartialOrd<u16> for FieldId {
    fn partial_cmp(&self, other: &u16) -> Option<std::cmp::Ordering> { self.0.partial_cmp(other) }
}

#[repr(i32)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum GroupType {
    Application = 0,
    DataWindow,
    Function,
    Menu,
    Proxy,
    Structure,
    UserObject,
    Window,
    Unknown
}

impl From<i32> for GroupType {
    fn from(v: i32) -> Self { unsafe { std::mem::transmute(v) } }
}

#[repr(u16)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ValueType {
    NoType = 0,
    Int,
    Long,
    Real,
    Double,
    Decimal,
    String,
    Boolean,
    Any,
    Uint,
    Ulong,
    Blob,
    Date,
    Time,
    DateTime,
    Dummy1,
    Dummy2,
    Dummy3,
    Char,
    Dummy4,
    LongLong,
    Byte
}

impl From<pbuint> for ValueType {
    fn from(v: pbuint) -> Self { unsafe { std::mem::transmute(v) } }
}
impl From<i32> for ValueType {
    fn from(v: i32) -> Self { unsafe { std::mem::transmute(v as u16) } }
}

#[repr(i32)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum RoutineType {
    Function = 0,
    Event,
    Any
}

impl From<i32> for RoutineType {
    fn from(v: i32) -> Self { unsafe { std::mem::transmute(v) } }
}

/// 返回值错误码
#[repr(i32)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum PBXRESULT {
    OK = 0,
    //SUCCESS = 0,
    //FAIL = -1,
    E_NO_REGISTER_FUNCTION = -1,
    E_REGISTRATION_FAILED = -2,
    E_BUILD_GROUP_FAILED = -3,
    E_INVALID_ARGUMENT = -4,
    E_INVOKE_METHOD_INACCESSABLE = -5,
    E_INVOKE_WRONG_NUM_ARGS = -6,
    E_INVOKE_REFARG_ERROR = -7,
    E_INVOKE_METHOD_AMBIGUOUS = -8,
    E_INVOKE_FAILURE = -9,
    E_MISMATCHED_DATA_TYPE = -10,
    E_OUTOF_MEMORY = -11,
    E_GET_PBVM_FAILED = -12,
    E_NO_SUCH_CLASS = -13,
    E_CAN_NOT_LOCATE_APPLICATION = -14,
    E_INVALID_METHOD_ID = -15,
    E_READONLY_ARGS = -16,
    E_ARRAY_INDEX_OUTOF_BOUNDS = -100,

    //pbni-rs Custom
    E_NULL_ERROR = -10000
}

impl PBXRESULT {
    pub fn is_ok(self) -> bool { self == PBXRESULT::OK }
    pub fn is_err(self) -> bool { self != PBXRESULT::OK }
}

impl From<i32> for PBXRESULT {
    fn from(v: i32) -> Self { unsafe { std::mem::transmute(v) } }
}

impl<T: Default> From<PBXRESULT> for crate::Result<T> {
    fn from(pbxr: PBXRESULT) -> Self {
        if pbxr == PBXRESULT::OK {
            Ok(Default::default())
        } else {
            Err(pbxr)
        }
    }
}

impl<T> From<crate::Result<T>> for PBXRESULT {
    fn from(pbxr: crate::Result<T>) -> Self {
        if let Err(e) = pbxr {
            e
        } else {
            PBXRESULT::OK
        }
    }
}