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
#![allow(unused_imports)]

use crossbeam_channel;

use crate::{
    button_handlers,
    ClientController,
    Task,
};

use self::crossbeam_channel::Sender;
use edit_common::commands::*;
use serde_json;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::*;
use wbg_rand::Rng;

#[cfg(target_arch = "wasm32")]
pub struct Scheduler {
    // tx: Sender<Task>,
    alive: Arc<AtomicBool>,
    monkey: Arc<AtomicBool>,
}

#[cfg(target_arch = "wasm32")]
impl Scheduler {
    pub fn new(
        // tx: Sender<Task>,
        alive: Arc<AtomicBool>,
        monkey: Arc<AtomicBool>,
    ) -> Self {
        Self {
            // tx,
            alive,
            monkey,
        }
    }

    pub fn schedule_random<F>(&mut self, bounds: (u64, u64), task: F)
    where
        F: Fn() -> ControllerCommand + 'static,
    {
        use crate::wasm::setTimeout;

        use ::wbg_rand::{
            wasm_rng,
            Rng,
        };

        // let tx = self.tx.clone();
        let alive = self.alive.clone();
        let monkey = self.monkey.clone();

        let task = Rc::new(task);
        let load_it: Rc<RefCell<Option<Box<dyn Fn()>>>> = Rc::new(RefCell::new(None));
        let load_it_clone = load_it.clone();
        *load_it.borrow_mut() = Some(Box::new(move || {
            // let tx = tx.clone();
            let alive = alive.clone();
            let monkey = monkey.clone();
            let task = task.clone();
            let load_it_clone = load_it_clone.clone();

            let outer = Rc::new(RefCell::new(Box::new(None)));

            let mut rng = wasm_rng();
            let delay = rng.gen_range(bounds.0, bounds.1);
            // console_log!(" - new delay: {:?}", delay);
            let inner = {
                let outer = outer.clone();
                Closure::new(move || {
                    (load_it_clone.borrow_mut().as_ref().unwrap())();

                    outer.borrow_mut().take(); // drop it

                    if alive.load(Ordering::Relaxed) && monkey.load(Ordering::Relaxed) {
                        let task_object = task();
                        let _task_str =
                            serde_json::to_string(&Task::ControllerCommand(task_object)).unwrap();

                        // FIXME This needs to send the task to the controller,
                        // but somehow that needs to be routed through the
                        // frontend?
                        // forwardWasmTask(&task_str);
                    }
                })
            };

            // TODO not drop inner
            setTimeout(&inner, delay as u32);

            // todo return inner
            **outer.borrow_mut() = Some(inner);
        }));

        (load_it.borrow_mut().as_ref().unwrap())();

        ::std::mem::forget(load_it);
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub struct Scheduler {
    tx: Sender<Task>,
    alive: Arc<AtomicBool>,
    monkey: Arc<AtomicBool>,
}

#[cfg(not(target_arch = "wasm32"))]
impl Scheduler {
    pub fn new(tx: Sender<Task>, alive: Arc<AtomicBool>, monkey: Arc<AtomicBool>) -> Self {
        Self { tx, alive, monkey }
    }

    pub fn schedule_random<F>(&mut self, bounds: (u64, u64), task: F)
    where
        F: Fn() -> ControllerCommand + 'static + Send,
    {
        use ::failure::Error;
        use ::std::thread;
        use ::std::time::Duration;
        use rand;

        // Proxy impl
        let tx = self.tx.clone();
        let alive = self.alive.clone();
        let monkey = self.monkey.clone();
        thread::spawn::<_, Result<(), Error>>(move || {
            let mut rng = rand::thread_rng();
            while alive.load(Ordering::Relaxed) {
                thread::sleep(Duration::from_millis(rng.gen_range(bounds.0, bounds.1)));
                if monkey.load(Ordering::Relaxed) {
                    let task_object = task();
                    tx.send(Task::ControllerCommand(task_object));
                }
            }
            Ok(())
        });
    }
}

pub type MonkeyParam = (u64, u64);

// "Human-like"
pub const MONKEY_BUTTON: MonkeyParam = (0, 1500);
pub const MONKEY_LETTER: MonkeyParam = (0, 200);
pub const MONKEY_ARROW: MonkeyParam = (0, 500);
pub const MONKEY_BACKSPACE: MonkeyParam = (0, 250);
pub const MONKEY_ENTER: MonkeyParam = (6_000, 10_000);
pub const MONKEY_CLICK: MonkeyParam = (400, 1000);

// Race
// const MONKEY_BUTTON: MonkeyParam = (0, 0, 100);
// const MONKEY_LETTER: MonkeyParam = (0, 0, 100);
// const MONKEY_ARROW: MonkeyParam = (0, 0, 100);
// const MONKEY_BACKSPACE: MonkeyParam = (0, 0, 100);
// const MONKEY_ENTER: MonkeyParam = (0, 0, 1_000);

#[cfg(target_arch = "wasm32")]
fn local_rng() -> impl Rng {
    use ::wbg_rand::{
        wasm_rng,
        Rng,
    };
    wasm_rng()
}

#[cfg(not(target_arch = "wasm32"))]
fn local_rng() -> impl Rng {
    use rand;
    rand::thread_rng()
}

#[allow(unused)]
pub fn setup_monkey<C: ClientController + Sized>(mut scheduler: Scheduler) {
    // let mut scheduler = Scheduler::new(alive, monkey);

    scheduler.schedule_random(MONKEY_BUTTON, || {
        let mut rng = local_rng();
        let index = rng.gen_range(0, button_handlers::<C>(None).0.len() as u32);
        ControllerCommand::Button { button: index }
    });

    scheduler.schedule_random(MONKEY_LETTER, || {
        let mut rng = local_rng();
        let char_list = vec![
            rng.gen_range(b'A', b'Z'),
            rng.gen_range(b'a', b'z'),
            rng.gen_range(b'0', b'9'),
            b' ',
        ];
        let c = *rng.choose(&char_list).unwrap() as u32;
        ControllerCommand::Character { char_code: c }
    });

    scheduler.schedule_random(MONKEY_ARROW, || {
        let mut rng = local_rng();
        let key_code = *rng.choose(&[37, 39, 37, 39, 37, 39, 38, 40]).unwrap();
        ControllerCommand::Keypress {
            key_code,
            meta_key: false,
            shift_key: false,
            alt_key: false,
        }
    });

    scheduler.schedule_random(MONKEY_BACKSPACE, || ControllerCommand::Keypress {
        key_code: 8,
        meta_key: false,
        shift_key: false,
        alt_key: false,
    });

    scheduler.schedule_random(MONKEY_ENTER, || ControllerCommand::Keypress {
        key_code: 13,
        meta_key: false,
        shift_key: false,
        alt_key: false,
    });

    scheduler.schedule_random(MONKEY_CLICK, || {
        let mut rng = local_rng();
        ControllerCommand::RandomTarget {
            position: rng.gen::<f64>(),
        }
    });
}