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
//! A wrapper around the FileMaker plug-in SDK.
//!
//! Replicates much of the functionality found in the C++ library provided by FileMaker, which is mostly wrapping the C ffi, as well as some convenience functions.
//!
//! Has only been tested with FileMaker 18 and 19 (windows, macos, and linux); your mileage may vary with older versions.
//!
//! # Quick Start
//!
//! You'll want to make your project a library with a crate-type of `cdylib`.
//!
//! ```toml
//! [lib]
//! path = "src/lib.rs"
//! crate-type = ["cdylib"]
//! ```
//!
//! Each custom function/script step must be configured in a [`FileMakerFunction`] implementation.
//!
//! ```rust
//! # use fm_plugin::prelude::*;
//! # use fm_plugin::{ExprEnv, DataVect, Data, log};
//! pub struct MyFunction;
//!
//! impl FileMakerFunction for MyFunction {
//!     fn function(id: i16, env: &ExprEnv, args: &DataVect, result: &mut Data) -> FMError {
//!         //log some info to the desktop (plugin.log)
//!         log("some troubleshooting info");
//!
//!         FMError::NoError
//!     }
//! }
//! ```
//!
//! Next you'll need to implement [`Plugin`] for your plugin's struct, defining all the information about the plug-in, as well as registering all the functions.
//!
//! ```rust
//! use fm_plugin::prelude::*;
//! # use fm_plugin::{ExprEnv, DataVect, Data, FMError};
//! # struct MyFunction;
//! # impl FileMakerFunction for MyFunction {
//! # fn function(id: i16, env: &ExprEnv, args: &DataVect, result: &mut Data) -> FMError {
//! #     FMError::NoError
//! # }
//! # }
//! struct MyPlugin;
//!
//! impl Plugin for MyPlugin {
//!     fn id() -> &'static [u8; 4] { &b"MyPl" }
//!     fn name() -> &'static str { "MY PLUGIN" }
//!     fn description() -> &'static str { "Does all sorts of great things." }
//!     fn url() -> &'static str { "http://myplugin.com" }
//!
//!     fn register_functions() -> Vec<Registration> {
//!         vec![Registration::Function {
//!             id: 100,
//!             name: "MyPlugin_MyFunction",
//!             definition: "MyPlugin_MyFunction( arg1 ; arg2 )",
//!             description: "Does some really great stuff.",
//!             min_args: 2,
//!             max_args: 2,
//!             compatible_flags: DisplayInAllDialogs | FutureCompatible,
//!             min_version: ExternVersion::V160,
//!             function_ptr: Some(MyFunction::extern_func),
//!             }
//!         ]
//!     }
//! }
//! ```
//! Lastly you'll need to register the plug-in.
//! ```rust
//! # use fm_plugin::prelude::*;
//! # struct MyPlugin;
//! # impl Plugin for MyPlugin {
//! #    fn id() -> &'static [u8; 4] { &b"MyPl" }
//! #    fn name() -> &'static str { "MY PLUGIN" }
//! #    fn description() -> &'static str { "Does all sorts of great things." }
//! #    fn url() -> &'static str { "http://myplugin.com" }
//! #    fn register_functions() -> Vec<Registration> { Vec::new() }
//! # }
//! register_plugin!(MyPlugin);
//! ```
//! [`Plugin`]: trait.Plugin.html
//! [`FileMakerFunction`]: ffi/calc_engine/trait.FileMakerFunction.html

#![allow(non_camel_case_types)]
#![allow(non_snake_case)]

pub mod config;
pub mod ffi;
pub mod helpers;
pub mod post_build;
pub use config::kill_filemaker;
pub use ffi::*;
pub use helpers::{log, write_to_u16_buff};

pub mod prelude {
    //! Re-exports everything necessary for the register_plugin macro.
    pub use crate::PluginFlag::*;
    pub use crate::{
        fmx_ExternCallStruct, fmx_ptrtype, register_plugin, write_to_u16_buff, ExternStringType,
        ExternVersion, FMError, FMExternCallType, FileMakerFunction, IdleType, Plugin, QuadChar,
        Registration,
    };
}

/// Implement this trait for your plugin struct. The different functions are used to give FileMaker information about the plugin. You also need to register all your functions/script steps in the trait implementation.
///
/// # Example
/// ```rust
/// # use fm_plugin::prelude::*;
/// # use fm_plugin::{DataVect, ExprEnv, Data, FMError};
/// # struct MyFunction;
/// # impl FileMakerFunction for MyFunction {
/// # fn function(id: i16, env: &ExprEnv, args: &DataVect, result: &mut Data) -> FMError {
/// #     FMError::NoError
/// # }
/// # }
/// struct MyPlugin;
///
/// impl Plugin for MyPlugin {
///     fn id() -> &'static [u8; 4] { &b"MyPl" }
///     fn name() -> &'static str { "MY PLUGIN" }
///     fn description() -> &'static str { "Does all sorts of great things." }
///     fn url() -> &'static str { "http://myplugin.com" }
///
///     fn register_functions() -> Vec<Registration> {
///         vec![Registration::Function {
///             id: 100,
///             name: "MyPlugin_MyFunction",
///             definition: "MyPlugin_MyFunction( arg1 ; arg2 )",
///             description: "Does some really great stuff.",
///             min_args: 2,
///             max_args: 2,
///             compatible_flags: DisplayInAllDialogs | FutureCompatible,
///             min_version: ExternVersion::V160,
///             function_ptr: Some(MyFunction::extern_func),
///             }
///         ]
///     }
/// }
/// ```
pub trait Plugin {
    /// Unique 4 letter identifier for the plug-in.
    fn id() -> &'static [u8; 4];
    /// Plug-in's name.
    fn name() -> &'static str;
    /// Description of the plug-in.
    fn description() -> &'static str;
    /// Url to send users to from the help in FileMaker. The function's name that the user  will be appended to the url when clicked.
    fn url() -> &'static str;

    /// Register all custom functions/script steps
    fn register_functions() -> Vec<Registration>;

    /// Defaults to false
    fn enable_configure_button() -> bool {
        false
    }
    /// Defaults to true
    fn enable_init_and_shutdown() -> bool {
        true
    }
    /// Defaults to false
    fn enable_idle() -> bool {
        false
    }
    /// Defaults to false
    fn enable_file_and_session_shutdown() -> bool {
        false
    }

    fn session_shutdown(_session_id: fmx_ptrtype) {}
    fn file_shutdown(_session_id: fmx_ptrtype, _file_id: fmx_ptrtype) {}
    fn preferences() {}
    fn idle(_session_id: fmx_ptrtype) {}
    fn not_idle(_session_id: fmx_ptrtype) {}
    fn script_paused(_session_id: fmx_ptrtype) {}
    fn script_running(_session_id: fmx_ptrtype) {}
    fn un_safe(_session_id: fmx_ptrtype) {}
}

/// Sets up the entry point for every FileMaker call into the plug-in. The function then dispatches the calls to the various trait functions you can implement.
/// Impl [`Plugin`][Plugin] for your plugin struct, and then call the macro on it.
///
/// # Example
/// ```rust
/// use fm_plugin::prelude::*;
///
/// struct MyPlugin;
///
/// impl Plugin for MyPlugin {
/// # fn id()-> &'static [u8; 4] { b"TEST" }
/// # fn name()-> &'static str { "TEST" }
/// # fn description()-> &'static str { "TEST" }
/// # fn url()-> &'static str { "TEST" }
/// # fn register_functions()-> Vec<Registration> { Vec::new() }
/// }
///
/// register_plugin!(MyPlugin);
/// ```
///
/// # Macro Contents
///```rust
/// # #[macro_export]
/// # macro_rules! register_plugin {
/// #     ($x:ident) => {
/// #[no_mangle]
/// pub static mut gfmx_ExternCallPtr: *mut fmx_ExternCallStruct = std::ptr::null_mut();
///
/// #[no_mangle]
/// unsafe extern "C" fn FMExternCallProc(pb: *mut fmx_ExternCallStruct) {
///     // Setup global defined in fmxExtern.h (this will be obsoleted in a later header file)
///     gfmx_ExternCallPtr = pb;
///     use FMExternCallType::*;
///
///     // Message dispatcher
///     match FMExternCallType::from((*pb).whichCall) {
///         Init => (*pb).result = initialize((*pb).extnVersion) as u64,
///         Idle => {
///             use IdleType::*;
///             match IdleType::from((*pb).parm1) {
///                 Idle => $x::idle((*pb).parm2),
///                 NotIdle => $x::not_idle((*pb).parm2),
///                 ScriptPaused => $x::script_paused((*pb).parm2),
///                 ScriptRunning => $x::script_running((*pb).parm2),
///                 Unsafe => $x::un_safe((*pb).parm2),
///             }
///         }
///         Shutdown => shutdown((*pb).extnVersion),
///         AppPrefs => $x::preferences(),
///         GetString => get_string(
///             (*pb).parm1.into(),
///             (*pb).parm2 as u32,
///             (*pb).parm3 as u32,
///             (*pb).result as *mut u16,
///         ),
///         SessionShutdown => $x::session_shutdown((*pb).parm2),
///         FileShutdown => $x::file_shutdown((*pb).parm2, (*pb).parm3),
///     }
/// }
///
/// fn get_string(
///     which_string: ExternStringType,
///     _win_lang_id: u32,
///     out_buffer_size: u32,
///     out_buffer: *mut u16,
/// ) {
///     use ExternStringType::*;
///     let string = match which_string {
///         Name => $x::name().to_string(),
///         AppConfig => $x::description().to_string(),
///         Options => {
///             let mut options: String = ::std::str::from_utf8($x::id()).unwrap().to_string();
///             options.push('1');
///             options.push(if $x::enable_configure_button() {
///                 'Y'
///             } else {
///                 'n'
///             });
///             options.push('n');
///             options.push(if $x::enable_init_and_shutdown() {
///                 'Y'
///             } else {
///                 'n'
///             });
///             options.push(if $x::enable_idle() { 'Y' } else { 'n' });
///             options.push(if $x::enable_file_and_session_shutdown() {
///                 'Y'
///             } else {
///                 'n'
///             });
///             options.push('n');
///             options
///         }
///         HelpUrl => $x::url().to_string(),
///         Blank => "".to_string(),
///     };
///     unsafe { write_to_u16_buff(out_buffer, out_buffer_size, &string) }
/// }
///
/// fn initialize(version: ExternVersion) -> ExternVersion {
///     let plugin_id = QuadChar::new($x::id());
///     for f in $x::register_functions() {
///         if version < f.min_version() {
///             continue;
///         }
///         if f.register(&plugin_id) != FMError::NoError {
///             return ExternVersion::DoNotEnable;
///         }
///     }
///     ExternVersion::V190
/// }
///
/// fn shutdown(version: ExternVersion) {
///     let plugin_id = QuadChar::new($x::id());
///     for f in $x::register_functions() {
///         if version < f.min_version() {
///             continue;
///         }
///         f.unregister(&plugin_id);
///     }
/// }
/// # };}
/// ```
#[macro_export]
macro_rules! register_plugin {
    ($x:ident) => {
        #[no_mangle]
        pub static mut gfmx_ExternCallPtr: *mut fmx_ExternCallStruct = std::ptr::null_mut();

        #[no_mangle]
        unsafe extern "C" fn FMExternCallProc(pb: *mut fmx_ExternCallStruct) {
            // Setup global defined in fmxExtern.h (this will be obsoleted in a later header file)
            gfmx_ExternCallPtr = pb;
            use FMExternCallType::*;

            // Message dispatcher
            match FMExternCallType::from((*pb).whichCall) {
                Init => (*pb).result = initialize((*pb).extnVersion) as u64,
                Idle => {
                    use IdleType::*;
                    match IdleType::from((*pb).parm1) {
                        Idle => $x::idle((*pb).parm2),
                        NotIdle => $x::not_idle((*pb).parm2),
                        ScriptPaused => $x::script_paused((*pb).parm2),
                        ScriptRunning => $x::script_running((*pb).parm2),
                        Unsafe => $x::un_safe((*pb).parm2),
                    }
                }
                Shutdown => shutdown((*pb).extnVersion),
                AppPrefs => $x::preferences(),
                GetString => get_string(
                    (*pb).parm1.into(),
                    (*pb).parm2 as u32,
                    (*pb).parm3 as u32,
                    (*pb).result as *mut u16,
                ),
                SessionShutdown => $x::session_shutdown((*pb).parm2),
                FileShutdown => $x::file_shutdown((*pb).parm2, (*pb).parm3),
            }
        }

        fn get_string(
            which_string: ExternStringType,
            _win_lang_id: u32,
            out_buffer_size: u32,
            out_buffer: *mut u16,
        ) {
            use ExternStringType::*;
            let string = match which_string {
                Name => $x::name().to_string(),
                AppConfig => $x::description().to_string(),
                Options => {
                    let mut options: String = ::std::str::from_utf8($x::id()).unwrap().to_string();
                    options.push('1');
                    options.push(if $x::enable_configure_button() {
                        'Y'
                    } else {
                        'n'
                    });
                    options.push('n');
                    options.push(if $x::enable_init_and_shutdown() {
                        'Y'
                    } else {
                        'n'
                    });
                    options.push(if $x::enable_idle() { 'Y' } else { 'n' });
                    options.push(if $x::enable_file_and_session_shutdown() {
                        'Y'
                    } else {
                        'n'
                    });
                    options.push('n');
                    options
                }
                HelpUrl => $x::url().to_string(),
                Blank => "".to_string(),
            };
            unsafe { write_to_u16_buff(out_buffer, out_buffer_size, &string) }
        }

        fn initialize(version: ExternVersion) -> ExternVersion {
            let plugin_id = QuadChar::new($x::id());
            for f in $x::register_functions() {
                if version < f.min_version() {
                    continue;
                }
                if f.register(&plugin_id) != FMError::NoError {
                    return ExternVersion::DoNotEnable;
                }
            }
            ExternVersion::V190
        }

        fn shutdown(version: ExternVersion) {
            let plugin_id = QuadChar::new($x::id());
            for f in $x::register_functions() {
                if version < f.min_version() {
                    continue;
                }
                f.unregister(&plugin_id);
            }
        }
    };
}