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
/*!
    Low level events functions
*/
/*
    Copyright (C) 2016  Gabriel Dubé

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

use std::mem;
use std::ptr;
use std::hash::Hash;
use std::any::TypeId;

use winapi::{HWND, HMENU, UINT, WPARAM, LPARAM, UINT_PTR, DWORD_PTR, LRESULT, DWORD};

use ui::UiInner;
use events::{Event, EventArgs};
use controls::{ControlType, AnyHandle, Timer};

/// A magic number to identify the NWG subclass that dispatches events
const EVENTS_DISPATCH_ID: UINT_PTR = 2465;

fn parse_listbox_command(id: u64, ncode: u32) -> Option<(u64, Event, EventArgs)> {
  use low::defs::{LBN_SELCHANGE, LBN_DBLCLK, LBN_SETFOCUS, LBN_KILLFOCUS};

  match ncode {
    LBN_SELCHANGE => Some((id, Event::SelectionChanged, EventArgs::None)),
    LBN_DBLCLK => Some((id, Event::DoubleClick, EventArgs::None)),
    LBN_SETFOCUS | LBN_KILLFOCUS => Some((id, Event::Focus, EventArgs::Focus(ncode==LBN_SETFOCUS))),
    _ => None
  }
}

fn parse_button_command(id: u64, ncode: u32) -> Option<(u64, Event, EventArgs)> {
  use low::defs::{BN_CLICKED, BN_DBLCLK, BN_SETFOCUS, BN_KILLFOCUS};
  match ncode {
    BN_CLICKED => Some((id, Event::Click, EventArgs::None)),
    BN_DBLCLK => Some((id, Event::DoubleClick, EventArgs::None)),
    BN_SETFOCUS | BN_KILLFOCUS => Some((id, Event::Focus, EventArgs::Focus(ncode==BN_SETFOCUS))),
    _ => None
  }
}

fn parse_edit_command(id: u64, ncode: u32) -> Option<(u64, Event, EventArgs)> {
  use low::defs::{EN_SETFOCUS, EN_KILLFOCUS, EN_UPDATE, EN_MAXTEXT};
  match ncode {
    EN_UPDATE => Some((id, Event::ValueChanged, EventArgs::None)),
    EN_MAXTEXT => Some((id, Event::LimitReached, EventArgs::None)),
    EN_SETFOCUS | EN_KILLFOCUS => Some((id, Event::Focus, EventArgs::Focus(ncode==EN_SETFOCUS))),
    _ => None
  }
}

fn parse_static_command(id: u64, ncode: u32) -> Option<(u64, Event, EventArgs)> {
  use low::defs::{STN_CLICKED, STN_DBLCLK};
  match ncode {
    STN_CLICKED => Some((id, Event::Click, EventArgs::None)),
    STN_DBLCLK => Some((id, Event::DoubleClick, EventArgs::None)),
    _ => None
  }
}

/**
  Parse the common controls notification passed through the `WM_COMMAND` message.
*/
#[inline(always)]
fn parse_command(id: u64, control_type: ControlType, w: WPARAM) -> Option<(u64, Event, EventArgs)> {
  use winapi::HIWORD;

  let ncode = HIWORD(w as DWORD) as u32;
  match control_type {
    ControlType::ListBox => parse_listbox_command(id, ncode),
    ControlType::Button => parse_button_command(id, ncode),
    ControlType::TextInput | ControlType::TextBox => parse_edit_command(id, ncode),
    ControlType::Label => parse_static_command(id, ncode),
    _ => None
  }
}

/**
  Proc that dispatches the NWG events
*/
#[allow(unused_variables)]
unsafe extern "system" fn process_events<ID: Hash+Clone+'static>(hwnd: HWND, msg: UINT, w: WPARAM, l: LPARAM, id: UINT_PTR, data: DWORD_PTR) -> LRESULT {
  use comctl32::DefSubclassProc;
  use user32::GetClientRect;
  use winapi::{WM_KEYDOWN, WM_KEYUP, WM_UNICHAR, WM_CHAR, UNICODE_NOCHAR, WM_MENUCOMMAND, WM_CLOSE, WM_LBUTTONUP, WM_LBUTTONDOWN, 
    WM_RBUTTONUP, WM_RBUTTONDOWN, WM_MBUTTONUP, WM_MBUTTONDOWN, WM_COMMAND, WM_TIMER, WM_MOVE, WM_SIZING, WM_EXITSIZEMOVE, WM_SIZE,
    WM_PAINT, c_int, LOWORD, HIWORD, RECT};
  use low::menu_helper::get_menu_id;
  use low::defs::{NWG_CUSTOM_MIN, NWG_CUSTOM_MAX};

  let inner: &mut UiInner<ID> = mem::transmute(data);
  let inner_id: u64;

  let callback_data = match msg {
    WM_PAINT => {
      inner_id = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ).expect("Could not match system handle to ui control (msg: WM_PAINT)");;
      Some( (inner_id, Event::Paint, EventArgs::None) )
    },
    WM_COMMAND => {
      if l == 0 { 
        None 
      } else {
        // Somehow, WM_COMMAND messages get sent while freeing and so inner_id_from_handle can fail...
        let nhandle: HWND = mem::transmute(l);
        if let Some(id) = inner.inner_id_from_handle( &AnyHandle::HWND(nhandle) ) {
          let control_type = (&mut *inner.controls.get(&id).expect("Could not find a control with with the specified type ID").as_ptr()).control_type();
          parse_command(id, control_type, w)
        } else {
          None
        }
      }
    },
    WM_LBUTTONUP | WM_RBUTTONUP  | WM_MBUTTONUP => {
      inner_id = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ).expect("Could not match system handle to ui control (msg: WM_LBUTTONUP | WM_RBUTTONUP  | WM_MBUTTONUP)");;
      Some( (inner_id, Event::MouseUp, parse_mouse_click(msg, l)) )
    },
    WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => {
      inner_id = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ).expect("Could not match system handle to ui control (msg: WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN)");;
      Some( (inner_id, Event::MouseDown, parse_mouse_click(msg, l)) )
    },
    WM_KEYDOWN | WM_KEYUP => {
      inner_id = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ).expect("Could not match system handle to ui control (msg: WM_KEYDOWN | WM_KEYUP)");;
      let evt = if msg == WM_KEYDOWN { Event::KeyDown } else { Event::KeyUp };
      Some( (inner_id, evt, EventArgs::Key(w as u32)) )
    },
    WM_MENUCOMMAND => {
      let parent_menu: HMENU = mem::transmute(l);
      let handle = AnyHandle::HMENU_ITEM(parent_menu, get_menu_id(parent_menu, w as c_int));

      // Custom controls might have their own way to handle the message
      if let Some(inner_id) = inner.inner_id_from_handle( &handle ) { 
        Some( (inner_id, Event::Triggered, EventArgs::None) )
      } else {
        None
      }  
    },
    WM_UNICHAR | WM_CHAR => {
      inner_id = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ).expect("Could not match system handle to ui control (msg: WM_UNICHAR | WM_CHAR)");;
      if w == UNICODE_NOCHAR { return 1; } 
      if let Some(c) = ::std::char::from_u32(w as u32) {
        Some( (inner_id, Event::Char, EventArgs::Char( c )) )
      } else {
        None
      }
    },
    WM_TIMER => {
      let handle = AnyHandle::Custom(TypeId::of::<Timer>(), w as usize);

      // Here I assume WM_TIMER will only be sent by built-in timers. Using a user event might be a better idea.
      // Custom controls might have their own way to handle the message
      if let Some(inner_id) = inner.inner_id_from_handle( &handle ) {
        let timer: &mut Box<Timer> = mem::transmute( inner.controls.get(&inner_id).unwrap().as_ptr() );
        Some( (inner_id, Event::Tick, EventArgs::Tick(timer.elapsed())) )
      } else {
        None
      }
    },
    WM_MOVE => {
      inner_id = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ).expect("Could not match system handle to ui control (msg: WM_MOVE)");
      let (x, y) = (LOWORD(l as u32), HIWORD(l as u32));
      Some( (inner_id, Event::Moved, EventArgs::Position(x as i32, y as i32)) )
    },
    WM_SIZING | WM_SIZE => {
      inner_id = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ).expect("Could not match system handle to ui control (msg: WM_SIZING)");
      let mut r: RECT = mem::uninitialized();
      GetClientRect(hwnd, &mut r);
      let w: u32 = (r.right-r.left) as u32;
      let h: u32 = (r.bottom-r.top) as u32;
      Some( (inner_id, Event::Resized, EventArgs::Size(w, h)) )
    },
    WM_EXITSIZEMOVE => {
      inner_id = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ).expect("Could not match system handle to ui control (msg: WM_SIZING)");
      let mut r: RECT = mem::uninitialized();
      GetClientRect(hwnd, &mut r);
      let w: u32 = (r.right-r.left) as u32;
      let h: u32 = (r.bottom-r.top) as u32;
      Some( (inner_id, Event::Resized, EventArgs::Size(w, h)) )
    }
    WM_CLOSE => {
      inner_id = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ).expect("Could not match system handle to ui control (msg: WM_CLOSE)");
      Some( (inner_id, Event::Closed, EventArgs::None) )
    },
    _ => { None }
  };

  if let Some((inner_id, evt, params)) = callback_data {
    inner.trigger(inner_id, evt, params);
  }

  // Trigger a raw event 
  if msg < NWG_CUSTOM_MIN || msg > NWG_CUSTOM_MAX {
    if let Some(inner_id) = inner.inner_id_from_handle( &AnyHandle::HWND(hwnd) ) {
      inner.trigger(inner_id, Event::Raw, EventArgs::Raw(msg, w as usize, l as usize));
    }
  }

  DefSubclassProc(hwnd, msg, w, l)
}

/**
    Add a subclass that dispatches the system event to the application callbacks to a window control.
*/
pub fn hook_window_events<ID: Hash+Clone+'static>(uiinner: &mut UiInner<ID>, handle: HWND) { unsafe {
  use comctl32::SetWindowSubclass;

  // While definitely questionable in term of safety, the reference to the UiInner is actually (always)
  // a raw pointer belonging to a Ui. Also, when the Ui goes out of scope, every window control
  // gets destroyed BEFORE the UiInner, this guarantees that uinner lives long enough.
  let ui_inner_raw: *mut UiInner<ID> = uiinner as *mut UiInner<ID>;
  SetWindowSubclass(handle, Some(process_events::<ID>), EVENTS_DISPATCH_ID, mem::transmute(ui_inner_raw));
}}

/**
  Remove a subclass and free the associated data
*/
pub fn unhook_window_events<ID: Hash+Clone+'static>(handle: HWND) { unsafe {
  use comctl32::{RemoveWindowSubclass, GetWindowSubclass};
  use winapi::{TRUE, DWORD_PTR};

  let mut data: DWORD_PTR = 0;
  if GetWindowSubclass(handle, Some(process_events::<ID>), EVENTS_DISPATCH_ID, &mut data) == TRUE {
    RemoveWindowSubclass(handle, Some(process_events::<ID>), EVENTS_DISPATCH_ID);
  }
}}

/**
  Check if a window is hooked by nwg. If it is, return its ID, if not return None
*/
pub unsafe fn window_id<ID: Clone+Hash>(handle: HWND, inner_ref: *mut UiInner<ID>) -> Option<u64> {
  use comctl32::GetWindowSubclass;
  use winapi::{TRUE, DWORD_PTR};

  let mut data: DWORD_PTR = 0;
  if GetWindowSubclass(handle, Some(process_events::<ID>), EVENTS_DISPATCH_ID, &mut data) == TRUE {
    let data: *mut UiInner<ID> = mem::transmute(data);
    if data == inner_ref {
      (&*data).inner_id_from_handle( &AnyHandle::HWND(handle) )
    } else {
      None
    }
  } else {
    None
  }
}

/**
    Dispatch the messages waiting the the system message queue to the associated Uis. This includes NWG custom messages.

    Return once a quit event was received.
*/
#[inline(always)]
pub unsafe fn dispatch_events() {
  use winapi::MSG;
  use user32::{GetMessageW, TranslateMessage, DispatchMessageW};

  let mut msg: MSG = mem::uninitialized();
  while GetMessageW(&mut msg, ptr::null_mut(), 0, 0) != 0 {
      TranslateMessage(&msg); 
      DispatchMessageW(&msg); 
      // TODO dispatch events sent from other thread / other processes ( after first stable release )
  }
}

/**
    Send a WM_QUIT to the system queue. Breaks the dispatch_events loop.
*/
#[inline(always)]
pub unsafe fn exit() {
  use user32::PostMessageW;
  use winapi::WM_QUIT;

  PostMessageW(ptr::null_mut(), WM_QUIT, 0, 0);
}

fn parse_mouse_click(msg: UINT, l: LPARAM) -> EventArgs {
  use defs::MouseButton;
  use winapi::{WM_LBUTTONUP, WM_LBUTTONDOWN, WM_RBUTTONUP, WM_RBUTTONDOWN, WM_MBUTTONUP, WM_MBUTTONDOWN, 
    GET_X_LPARAM, GET_Y_LPARAM};

  let btn = match msg {
    WM_LBUTTONUP | WM_LBUTTONDOWN => MouseButton::Left,
    WM_RBUTTONUP | WM_RBUTTONDOWN => MouseButton::Right,
    WM_MBUTTONUP | WM_MBUTTONDOWN => MouseButton::Middle,
    _ => MouseButton::Left
  };

  let x = GET_X_LPARAM(l) as i32; 
  let y = GET_Y_LPARAM(l) as i32;

  EventArgs::MouseClick{btn: btn, pos: (x, y)}
}