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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// Copyright 2022-2024 Vector 35 Inc.
//
// 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.

//! Interfaces for asking the user for information: forms, opening files, etc.

use binaryninjacore_sys::*;

use std::ffi::CStr;
use std::os::raw::{c_char, c_void};
use std::path::PathBuf;

use crate::binaryview::BinaryView;
use crate::rc::Ref;
use crate::string::{BnStrCompatible, BnString};

pub fn get_text_line_input(prompt: &str, title: &str) -> Option<String> {
    let mut value: *mut libc::c_char = std::ptr::null_mut();

    let result = unsafe {
        BNGetTextLineInput(
            &mut value,
            prompt.into_bytes_with_nul().as_ptr() as *mut _,
            title.into_bytes_with_nul().as_ptr() as *mut _,
        )
    };
    if !result {
        return None;
    }

    Some(unsafe { BnString::from_raw(value).to_string() })
}

pub fn get_integer_input(prompt: &str, title: &str) -> Option<i64> {
    let mut value: i64 = 0;

    let result = unsafe {
        BNGetIntegerInput(
            &mut value,
            prompt.into_bytes_with_nul().as_ptr() as *mut _,
            title.into_bytes_with_nul().as_ptr() as *mut _,
        )
    };

    if !result {
        return None;
    }

    Some(value)
}

pub fn get_address_input(prompt: &str, title: &str) -> Option<u64> {
    let mut value: u64 = 0;

    let result = unsafe {
        BNGetAddressInput(
            &mut value,
            prompt.into_bytes_with_nul().as_ptr() as *mut _,
            title.into_bytes_with_nul().as_ptr() as *mut _,
            std::ptr::null_mut(),
            0,
        )
    };

    if !result {
        return None;
    }

    Some(value)
}

pub fn get_open_filename_input(prompt: &str, extension: &str) -> Option<PathBuf> {
    let mut value: *mut libc::c_char = std::ptr::null_mut();

    let result = unsafe {
        BNGetOpenFileNameInput(
            &mut value,
            prompt.into_bytes_with_nul().as_ptr() as *mut _,
            extension.into_bytes_with_nul().as_ptr() as *mut _,
        )
    };
    if !result {
        return None;
    }

    let string = unsafe { BnString::from_raw(value) };
    Some(PathBuf::from(string.as_str()))
}

pub fn get_save_filename_input(prompt: &str, title: &str, default_name: &str) -> Option<PathBuf> {
    let mut value: *mut libc::c_char = std::ptr::null_mut();

    let result = unsafe {
        BNGetSaveFileNameInput(
            &mut value,
            prompt.into_bytes_with_nul().as_ptr() as *mut _,
            title.into_bytes_with_nul().as_ptr() as *mut _,
            default_name.into_bytes_with_nul().as_ptr() as *mut _,
        )
    };
    if !result {
        return None;
    }

    let string = unsafe { BnString::from_raw(value) };
    Some(PathBuf::from(string.as_str()))
}

pub fn get_directory_name_input(prompt: &str, default_name: &str) -> Option<PathBuf> {
    let mut value: *mut libc::c_char = std::ptr::null_mut();

    let result = unsafe {
        BNGetDirectoryNameInput(
            &mut value,
            prompt.into_bytes_with_nul().as_ptr() as *mut _,
            default_name.into_bytes_with_nul().as_ptr() as *mut _,
        )
    };
    if !result {
        return None;
    }

    let string = unsafe { BnString::from_raw(value) };
    Some(PathBuf::from(string.as_str()))
}

pub type MessageBoxButtonSet = BNMessageBoxButtonSet;
pub type MessageBoxIcon = BNMessageBoxIcon;
pub type MessageBoxButtonResult = BNMessageBoxButtonResult;
pub fn show_message_box(
    title: &str,
    text: &str,
    buttons: MessageBoxButtonSet,
    icon: MessageBoxIcon,
) -> MessageBoxButtonResult {
    unsafe {
        BNShowMessageBox(
            title.into_bytes_with_nul().as_ptr() as *mut _,
            text.into_bytes_with_nul().as_ptr() as *mut _,
            buttons,
            icon,
        )
    }
}

pub enum FormResponses {
    None,
    String(String),
    Integer(i64),
    Address(u64),
    Index(usize),
}

enum FormData {
    Label {
        _text: BnString,
    },
    Text {
        _prompt: BnString,
        _default: Option<BnString>,
    },
    Choice {
        _prompt: BnString,
        _choices: Vec<BnString>,
        _raw: Vec<*const c_char>,
    },
    File {
        _prompt: BnString,
        _ext: BnString,
        _default: Option<BnString>,
    },
    FileSave {
        _prompt: BnString,
        _ext: BnString,
        _default_name: BnString,
        _default: Option<BnString>,
    },
}

pub struct FormInputBuilder {
    fields: Vec<BNFormInputField>,
    data: Vec<FormData>,
}

impl FormInputBuilder {
    pub fn new() -> Self {
        Self {
            fields: vec![],
            data: vec![],
        }
    }

    /// Form Field: Text output
    pub fn label_field(mut self, text: &str) -> Self {
        let text = BnString::new(text);

        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::LabelFormField;
        result.hasDefault = false;
        result.prompt = text.as_ref().as_ptr() as *const c_char;
        self.fields.push(result);

        self.data.push(FormData::Label { _text: text });
        self
    }

    /// Form Field: Vertical spacing
    pub fn seperator_field(mut self) -> Self {
        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::SeparatorFormField;
        result.hasDefault = false;
        self.fields.push(result);
        self
    }

    /// Form Field: Prompt for a string value
    pub fn text_field(mut self, prompt: &str, default: Option<&str>) -> Self {
        let prompt = BnString::new(prompt);
        let default = default.map(BnString::new);

        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::TextLineFormField;
        result.prompt = prompt.as_ref().as_ptr() as *const c_char;
        result.hasDefault = default.is_some();
        if let Some(ref default) = default {
            result.stringDefault = default.as_ref().as_ptr() as *const c_char;
        }
        self.fields.push(result);

        self.data.push(FormData::Text {
            _prompt: prompt,
            _default: default,
        });
        self
    }

    /// Form Field: Prompt for multi-line string value
    pub fn multiline_field(mut self, prompt: &str, default: Option<&str>) -> Self {
        let prompt = BnString::new(prompt);
        let default = default.map(BnString::new);

        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::MultilineTextFormField;
        result.prompt = prompt.as_ref().as_ptr() as *const c_char;
        result.hasDefault = default.is_some();
        if let Some(ref default) = default {
            result.stringDefault = default.as_ref().as_ptr() as *const c_char;
        }
        self.fields.push(result);

        self.data.push(FormData::Text {
            _prompt: prompt,
            _default: default,
        });
        self
    }

    /// Form Field: Prompt for an integer
    pub fn integer_field(mut self, prompt: &str, default: Option<i64>) -> Self {
        let prompt = BnString::new(prompt);

        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::IntegerFormField;
        result.prompt = prompt.as_ref().as_ptr() as *const c_char;
        result.hasDefault = default.is_some();
        if let Some(default) = default {
            result.intDefault = default;
        }
        self.fields.push(result);

        self.data.push(FormData::Label { _text: prompt });
        self
    }

    /// Form Field: Prompt for an address
    pub fn address_field(
        mut self,
        prompt: &str,
        view: Option<Ref<BinaryView>>,
        current_address: Option<u64>,
        default: Option<u64>,
    ) -> Self {
        let prompt = BnString::new(prompt);

        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::AddressFormField;
        result.prompt = prompt.as_ref().as_ptr() as *const c_char;
        if let Some(view) = view {
            // the view is being moved into result, there is no need to clone
            // and drop is intentionally being avoided with `Ref::into_raw`
            result.view = unsafe { Ref::into_raw(view) }.handle;
        }
        result.currentAddress = current_address.unwrap_or(0);
        result.hasDefault = default.is_some();
        if let Some(default) = default {
            result.addressDefault = default;
        }
        self.fields.push(result);

        self.data.push(FormData::Label { _text: prompt });
        self
    }

    /// Form Field: Prompt for a choice from provided options
    pub fn choice_field(mut self, prompt: &str, choices: &[&str], default: Option<usize>) -> Self {
        let prompt = BnString::new(prompt);
        let choices: Vec<BnString> = choices.iter().map(|&s| BnString::new(s)).collect();

        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::ChoiceFormField;
        result.prompt = prompt.as_ref().as_ptr() as *const c_char;
        let mut raw_choices: Vec<*const c_char> = choices
            .iter()
            .map(|c| c.as_ref().as_ptr() as *const c_char)
            .collect();
        result.choices = raw_choices.as_mut_ptr();
        result.count = choices.len();
        result.hasDefault = default.is_some();
        if let Some(default) = default {
            result.indexDefault = default;
        }
        self.fields.push(result);

        self.data.push(FormData::Choice {
            _prompt: prompt,
            _choices: choices,
            _raw: raw_choices,
        });
        self
    }

    /// Form Field: Prompt for file to open
    pub fn open_file_field(
        mut self,
        prompt: &str,
        ext: Option<&str>,
        default: Option<&str>,
    ) -> Self {
        let prompt = BnString::new(prompt);
        let ext = if let Some(ext) = ext {
            BnString::new(ext)
        } else {
            BnString::new("")
        };
        let default = default.map(BnString::new);

        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::OpenFileNameFormField;
        result.prompt = prompt.as_ref().as_ptr() as *const c_char;
        result.ext = ext.as_ref().as_ptr() as *const c_char;
        result.hasDefault = default.is_some();
        if let Some(ref default) = default {
            result.stringDefault = default.as_ref().as_ptr() as *const c_char;
        }
        self.fields.push(result);

        self.data.push(FormData::File {
            _prompt: prompt,
            _ext: ext,
            _default: default,
        });
        self
    }

    /// Form Field: Prompt for file to save to
    pub fn save_file_field(
        mut self,
        prompt: &str,
        ext: Option<&str>,
        default_name: Option<&str>,
        default: Option<&str>,
    ) -> Self {
        let prompt = BnString::new(prompt);
        let ext = if let Some(ext) = ext {
            BnString::new(ext)
        } else {
            BnString::new("")
        };
        let default_name = if let Some(default_name) = default_name {
            BnString::new(default_name)
        } else {
            BnString::new("")
        };
        let default = default.map(BnString::new);

        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::SaveFileNameFormField;
        result.prompt = prompt.as_ref().as_ptr() as *const c_char;
        result.ext = ext.as_ref().as_ptr() as *const c_char;
        result.defaultName = default_name.as_ref().as_ptr() as *const c_char;
        result.hasDefault = default.is_some();
        if let Some(ref default) = default {
            result.stringDefault = default.as_ref().as_ptr() as *const c_char;
        }
        self.fields.push(result);

        self.data.push(FormData::FileSave {
            _prompt: prompt,
            _ext: ext,
            _default_name: default_name,
            _default: default,
        });
        self
    }

    /// Form Field: Prompt for directory name
    pub fn directory_name_field(
        mut self,
        prompt: &str,
        default_name: Option<&str>,
        default: Option<&str>,
    ) -> Self {
        let prompt = BnString::new(prompt);
        let default_name = if let Some(default_name) = default_name {
            BnString::new(default_name)
        } else {
            BnString::new("")
        };
        let default = default.map(BnString::new);

        let mut result = unsafe { std::mem::zeroed::<BNFormInputField>() };
        result.type_ = BNFormInputFieldType::DirectoryNameFormField;
        result.prompt = prompt.as_ref().as_ptr() as *const c_char;
        result.defaultName = default_name.as_ref().as_ptr() as *const c_char;
        result.hasDefault = default.is_some();
        if let Some(ref default) = default {
            result.stringDefault = default.as_ref().as_ptr() as *const c_char;
        }
        self.fields.push(result);

        self.data.push(FormData::File {
            _prompt: prompt,
            _ext: default_name,
            _default: default,
        });
        self
    }

    /// Prompts the user for a set of inputs specified in `fields` with given title.
    /// The fields parameter is a list which can contain the following types:
    ///
    /// This API is flexible and works both in the UI via a pop-up dialog and on the command-line.
    ///
    /// ```no_run
    /// # use binaryninja::interaction::FormInputBuilder;
    /// # use binaryninja::interaction::FormResponses;
    /// let responses = FormInputBuilder::new()
    ///     .text_field("First Name", None)
    ///     .text_field("Last Name", None)
    ///     .choice_field(
    ///         "Favorite Food",
    ///         &vec![
    ///             "Pizza",
    ///             "Also Pizza",
    ///             "Also Pizza",
    ///             "Yummy Pizza",
    ///             "Wrong Answer",
    ///         ],
    ///         Some(0),
    ///     )
    ///     .get_form_input("Form Title");
    ///
    /// let food = match responses[2] {
    ///     FormResponses::Index(0) => "Pizza",
    ///     FormResponses::Index(1) => "Also Pizza",
    ///     FormResponses::Index(2) => "Also Pizza",
    ///     FormResponses::Index(3) => "Wrong Answer",
    ///     _ => panic!("This person doesn't like pizza?!?"),
    /// };
    ///
    /// let FormResponses::String(last_name) = &responses[0] else {
    ///    unreachable!()
    /// };
    /// let FormResponses::String(first_name) = &responses[1] else {
    ///    unreachable!()
    /// };
    ///
    /// println!("{} {} likes {}", &first_name, &last_name, food);
    /// ```
    pub fn get_form_input(&mut self, title: &str) -> Vec<FormResponses> {
        if unsafe {
            BNGetFormInput(
                self.fields.as_mut_ptr(),
                self.fields.len(),
                title.into_bytes_with_nul().as_ptr() as *const _,
            )
        } {
            let result = self
                .fields
                .iter()
                .map(|form_field| match form_field.type_ {
                    BNFormInputFieldType::LabelFormField
                    | BNFormInputFieldType::SeparatorFormField => FormResponses::None,

                    BNFormInputFieldType::TextLineFormField
                    | BNFormInputFieldType::MultilineTextFormField
                    | BNFormInputFieldType::OpenFileNameFormField
                    | BNFormInputFieldType::SaveFileNameFormField
                    | BNFormInputFieldType::DirectoryNameFormField => {
                        FormResponses::String(unsafe {
                            CStr::from_ptr(form_field.stringResult)
                                .to_str()
                                .unwrap()
                                .to_owned()
                        })
                    }

                    BNFormInputFieldType::IntegerFormField => {
                        FormResponses::Integer(form_field.intResult)
                    }
                    BNFormInputFieldType::AddressFormField => {
                        FormResponses::Address(form_field.addressResult)
                    }
                    BNFormInputFieldType::ChoiceFormField => {
                        FormResponses::Index(form_field.indexResult)
                    }
                })
                .collect();
            unsafe { BNFreeFormInputResults(self.fields.as_mut_ptr(), self.fields.len()) };
            result
        } else {
            vec![]
        }
    }
}

impl Default for FormInputBuilder {
    fn default() -> Self {
        Self::new()
    }
}

struct TaskContext<F: Fn(Box<dyn Fn(usize, usize) -> Result<(), ()>>)>(F);

pub fn run_progress_dialog<F: Fn(Box<dyn Fn(usize, usize) -> Result<(), ()>>)>(
    title: &str,
    can_cancel: bool,
    task: F,
) -> Result<(), ()> {
    let mut ctxt = TaskContext::<F>(task);

    unsafe extern "C" fn cb_task<F: Fn(Box<dyn Fn(usize, usize) -> Result<(), ()>>)>(
        ctxt: *mut c_void,
        progress: Option<unsafe extern "C" fn(*mut c_void, usize, usize) -> bool>,
        progress_ctxt: *mut c_void,
    ) {
        ffi_wrap!("run_progress_dialog", {
            let context = ctxt as *mut TaskContext<F>;
            let progress_fn = Box::new(move |cur: usize, max: usize| -> Result<(), ()> {
                match progress {
                    Some(func) => {
                        if (func)(progress_ctxt, cur, max) {
                            Ok(())
                        } else {
                            Err(())
                        }
                    }
                    None => Ok(()),
                }
            });
            ((*context).0)(progress_fn);
        })
    }

    if unsafe {
        BNRunProgressDialog(
            title.into_bytes_with_nul().as_ptr() as *mut _,
            can_cancel,
            Some(cb_task::<F>),
            &mut ctxt as *mut _ as *mut c_void,
        )
    } {
        Ok(())
    } else {
        Err(())
    }
}