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
use std::{
    fmt::{self, Debug},
    ptr::NonNull,
    time::{Duration, Instant, SystemTime},
};

use num_enum::{IntoPrimitive, TryFromPrimitive};
use winapi::{
    shared::{
        minwindef::DWORD,
        ntdef::LONG,
        windef::{HWINEVENTHOOK, HWINEVENTHOOK__, HWND, HWND__},
    },
    um::{sysinfoapi::GetTickCount, winuser::CHILDID_SELF},
};

use crate::raw_event;

/// A raw handle to a hook created using [`SetWinEventHook`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwineventhook).
pub type RawHookHandle = HWINEVENTHOOK;

/// A non null handle to a hook created using [`SetWinEventHook`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwineventhook).
pub type HookHandle = NonNull<HWINEVENTHOOK__>;

/// A raw handle to a window.
pub type RawWindowHandle = HWND;

/// A non null handle to a window.
pub type WindowHandle = NonNull<HWND__>;

/// A raw window event received by a [`WindowEventHook`](crate::WindowEventHook).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RawWindowEvent {
    /// Handle to the shared event hook function.
    pub hook_handle: HWINEVENTHOOK,
    /// Specifies the event that occurred
    pub event_id: DWORD,
    /// Handle to the window that generates the event, or `NULL` if no window is associated with the event.
    /// For example, the mouse pointer is not associated with a window.
    pub window_handle: HWND,
    /// Identifies the object associated with the event.
    pub object_id: LONG,
    /// Identifies whether the event was triggered by an object or a child element of the object.
    /// If this value is [`CHILDID_SELF`], the event was triggered by the object; otherwise, this value is the child ID of the element that triggered the event.
    pub child_id: LONG,
    /// Identifies the thread that generated the event.
    pub thread_id: DWORD,
    /// Specifies the time since system startup, in milliseconds, that the event was generated.
    pub timestamp: DWORD,
}

unsafe impl Send for RawWindowEvent {}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
/// A window event received by a [`WindowEventHook`](crate::WindowEventHook).
pub struct WindowEvent {
    /// The raw underlying event.
    pub raw: RawWindowEvent,
}

impl Debug for WindowEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut builder = f.debug_struct(stringify!(WindowEvent));
        let _ = builder.field("hook_handle", &self.hook_handle());
        let _ = builder.field("event_type", &self.event_type());
        let _ = builder.field("window_handle", &self.window_handle());
        let _ = builder.field("object_type", &self.object_type());
        let _ = builder.field("child_id", &self.child_id());
        let _ = builder.field("thread_id", &self.thread_id());
        let _ = builder.field("timestamp", &self.timestamp());
        builder.finish()
    }
}

impl WindowEvent {
    /// Creates a new [`WindowEvent`] from a raw event.
    #[must_use]
    pub fn from_raw(raw: RawWindowEvent) -> Self {
        Self { raw }
    }

    /// Returns the handle to the shared event hook function.
    #[must_use]
    pub fn hook_handle(&self) -> HookHandle {
        unsafe { HookHandle::new_unchecked(self.raw.hook_handle) }
    }

    /// Returns the type of event that occurred.
    #[must_use]
    pub fn event_type(&self) -> WindowEventType {
        (self.raw.event_id as i32).into()
    }

    /// Returns the handle to the window that generates the event, or [`None`] if no window is associated with the event.
    #[must_use]
    pub fn window_handle(&self) -> Option<WindowHandle> {
        NonNull::new(self.raw.window_handle.cast())
    }

    /// Returns the type of object associated with the event.
    #[must_use]
    pub fn object_type(&self) -> MaybeKnown<AccessibleObjectId> {
        self.raw.object_id.into()
    }

    /// Returns the child ID of the element that triggered the event, or [`None`] if the event was generated by the object itself.
    #[must_use]
    pub fn child_id(&self) -> Option<i32> {
        match self.raw.child_id {
            CHILDID_SELF => None,
            n => Some(n),
        }
    }

    /// Returns the id of the thread that generated the event.
    #[must_use]
    pub fn thread_id(&self) -> u32 {
        self.raw.thread_id
    }

    /// Returns the timestamp of the event.
    #[must_use]
    pub fn timestamp(&self) -> Instant {
        let time_since_system_start = Duration::from_millis(unsafe { GetTickCount() as u64 });
        let event_time_relative_to_system_start = Duration::from_millis(self.raw.timestamp as u64);
        let now = Instant::now();
        let system_start_instant = now.checked_sub(time_since_system_start).unwrap_or_else(|| {
            // use unix epoch if Instant underflows, should never happen.
            let time_since_unix_epoch = SystemTime::UNIX_EPOCH.elapsed().unwrap();
            now.checked_sub(time_since_unix_epoch).unwrap()
        });
        system_start_instant + event_time_relative_to_system_start
    }
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, IntoPrimitive, TryFromPrimitive,
)]
#[repr(i32)]
/// The type of object associated with a window event.
pub enum AccessibleObjectId {
    /// An alert that is associated with a window or an application.
    Alert = -10,
    /// The text insertion bar (caret) in the window.
    Caret = -8,
    /// The window's client area.
    Client = -4,
    /// The mouse pointer.
    /// There is only one mouse pointer in the system, and it is not a child of any window.
    Cursor = -9,
    /// The window's horizontal scroll bar.
    HorizontalScroll = -6,
    /// In response to this object identifier, third-party applications can expose their own object model.
    /// Third-party applications can return any COM interface in response to this object identifier.
    NativeObjectModel = -16,
    /// The window's menu bar.
    Menu = -3,
    /// An object identifier that [`Oleacc.dll`] uses internally.
    /// For more information, see [Appendix F: Object Identifier Values for OBJID_QUERYCLASSNAMEIDX`](https://docs.microsoft.com/en-us/windows/win32/winauto/appendix-f--object-identifier-values-for-objid-queryclassnameidx).
    QueryClassNameIdx = -12,
    /// The window's size grip: an optional frame component located at the lower-right corner of the window frame.
    SizeGrip = -7,
    /// A sound object.
    /// Sound objects do not have screen locations or children, but they do have name and state attributes.
    /// They are children of the application that is playing the sound.
    Sound = -11,
    /// The window's system menu.
    SystemMenu = -1,
    /// The window's title bar.
    TitleBar = -2,
    /// The window's vertical scroll bar.
    VerticalScroll = -5,
    /// The window itself rather than a child object.
    Window = 0,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
/// The type of window event.
/// See [Event Constants](https://docs.microsoft.com/en-us/windows/win32/winauto/event-constants), [System-Level and Object-Level Events](https://docs.microsoft.com/en-us/windows/win32/winauto/system-level-and-object-level-events) and [Allocation of WinEvent IDs](https://docs.microsoft.com/en-us/windows/win32/winauto/allocation-of-winevent-ids) for more information.
pub enum WindowEventType {
    /// An event describing a situation affecting all applications in the system.
    System(MaybeKnown<SystemWindowEvent>),
    /// An event describing an OEM defined event.
    OemDefined(i32),
    /// An event indicating a change in a console window.
    Console(MaybeKnown<ConsoleWindowEvent>),
    /// An UI Automation event.
    UiaEvent(i32),
    /// An Ui Automation property change event.
    UiaPropertyChange(i32),
    /// An event pertaining to a situation specific to objects within one application.
    Object(MaybeKnown<ObjectWindowEvent>),
    /// An event that was allocated at runtime through the UI Automation extensibility API using [`GlobalAddAtom`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globaladdatoma).
    Atom(i32),
    /// An event defined by Accessibility Interoperability Alliance (AIA) specifications.
    Aia(i32),
    /// An unknown event.
    Other(i32),
    // TODO: add community reserved event range
}

impl From<i32> for WindowEventType {
    fn from(number: i32) -> Self {
        if raw_event::all_system().contains(&number) {
            Self::System(MaybeKnown::from(number))
        } else if raw_event::all_console().contains(&number) {
            Self::Console(MaybeKnown::from(number))
        } else if raw_event::all_object().contains(&number) {
            Self::Object(MaybeKnown::from(number))
        } else if raw_event::all_atom().contains(&number) {
            Self::Atom(number)
        } else if raw_event::all_aia().contains(&number) {
            Self::Aia(number)
        } else if raw_event::all_oem_defined().contains(&number) {
            Self::OemDefined(number)
        } else if raw_event::all_uia_event().contains(&number) {
            Self::UiaEvent(number)
        } else if raw_event::all_uia_property_change().contains(&number) {
            Self::UiaPropertyChange(number)
        } else {
            Self::Other(number)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A struct represting an event in a reserved range that may be a known common event or an unknown new or custom event.
pub enum MaybeKnown<T> {
    /// A known common event.
    Known(T),
    /// An unknown new or custom event.
    Unknown(i32),
}

impl<T> MaybeKnown<T> {
    /// Returns `true` if the event is known.
    #[must_use]
    pub fn is_known(&self) -> bool {
        matches!(self, Self::Known(_))
    }

    /// Returns `true` if the event is unknown.
    #[must_use]
    pub fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown(_))
    }

    /// Returns the event if it is known.
    #[must_use]
    pub fn known(&self) -> Option<&T> {
        match self {
            Self::Known(value) => Some(value),
            _ => None,
        }
    }

    /// Returns the code of the event if it is unknown.
    #[must_use]
    pub fn unknown(&self) -> Option<i32> {
        match self {
            Self::Unknown(value) => Some(*value),
            _ => None,
        }
    }
}

impl<T> MaybeKnown<T>
where
    T: Into<i32>,
{
    /// Returns the underlying event code.
    pub fn code(self) -> i32 {
        match self {
            MaybeKnown::Known(value) => value.into(),
            MaybeKnown::Unknown(value) => value,
        }
    }
}

impl<T> From<i32> for MaybeKnown<T>
where
    T: TryFrom<i32>,
{
    fn from(number: i32) -> Self {
        match T::try_from(number) {
            Ok(value) => Self::Known(value),
            Err(_) => Self::Unknown(number),
        }
    }
}

impl<T> From<MaybeKnown<T>> for i32
where
    T: Into<i32>,
{
    fn from(value: MaybeKnown<T>) -> Self {
        value.code()
    }
}

impl<T> PartialEq<T> for MaybeKnown<T>
where
    T: PartialEq,
{
    fn eq(&self, other: &T) -> bool {
        match self {
            MaybeKnown::Known(value) => value == other,
            MaybeKnown::Unknown(_) => false,
        }
    }
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, IntoPrimitive, TryFromPrimitive,
)]
#[repr(i32)]
/// A known event describing a situation affecting all applications in the system.
pub enum SystemWindowEvent {
    /// A sound has been played.
    Sound = raw_event::SYSTEM_SOUND,

    /// An alert has been generated.
    Alert = raw_event::SYSTEM_ALERT,

    /// The foreground window has changed.
    Foreground = raw_event::SYSTEM_FOREGROUND,

    /// A menu item on the menu bar has been selected.
    MenuStart = raw_event::SYSTEM_MENUSTART,

    /// A menu from the menu bar has been closed.
    MenuEnd = raw_event::SYSTEM_MENUEND,

    /// A pop-up menu has been displayed.
    MenuPopupStart = raw_event::SYSTEM_MENUPOPUPSTART,

    /// A pop-up menu has been closed.
    MenuPopupEnd = raw_event::SYSTEM_MENUPOPUPEND,

    /// A window has received mouse capture.
    CaptureStart = raw_event::SYSTEM_CAPTURESTART,

    /// A window has lost mouse capture.
    CaptureEnd = raw_event::SYSTEM_CAPTUREEND,

    /// A window is being moved or resized.
    MoveSizeStart = raw_event::SYSTEM_MOVESIZESTART,

    /// The movement or resizing of a window has finished.
    MoveSizeEnd = raw_event::SYSTEM_MOVESIZEEND,

    /// A window has entered context-sensitive Help mode.
    ContextHelpStart = raw_event::SYSTEM_CONTEXTHELPSTART,

    /// A window has exited context-sensitive Help mode.
    ContextHelpEnd = raw_event::SYSTEM_CONTEXTHELPEND,

    /// An application is about to enter drag-and-drop mode.
    DragDropStart = raw_event::SYSTEM_DRAGDROPSTART,

    /// An application is about to exit drag-and-drop mode.
    DragDropEnd = raw_event::SYSTEM_DRAGDROPEND,

    /// A dialog box has been displayed.
    DialogStart = raw_event::SYSTEM_DIALOGSTART,

    /// An application is about to exit drag-and-drop mode.
    DialogEnd = raw_event::SYSTEM_DIALOGEND,

    /// Scrolling has started on a scroll bar.
    ScrollingStart = raw_event::SYSTEM_SCROLLINGSTART,

    /// Scrolling has ended on a scroll bar.
    ScrollingEnd = raw_event::SYSTEM_SCROLLINGEND,

    /// The user has pressed ALT+TAB, which activates the switch window.
    SwitchStart = raw_event::SYSTEM_SWITCHSTART,

    /// The user has released ALT+TAB.
    SwitchEnd = raw_event::SYSTEM_SWITCHEND,

    /// A window object is about to be minimized.
    MinimizeStart = raw_event::SYSTEM_MINIMIZESTART,

    /// A window object is about to be restored.
    MinimizeEnd = raw_event::SYSTEM_MINIMIZEEND,

    /// The active desktop has been switched.
    DesktopSwitch = raw_event::SYSTEM_DESKTOPSWITCH,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, IntoPrimitive, TryFromPrimitive,
)]
#[repr(i32)]
#[allow(missing_docs)]
/// A known event indicating a change in a console window.
pub enum ConsoleWindowEvent {
    Caret = raw_event::CONSOLE_CARET,
    UpdateRegion = raw_event::CONSOLE_UPDATE_REGION,
    UpdateSimple = raw_event::CONSOLE_UPDATE_SIMPLE,
    UpdateScroll = raw_event::CONSOLE_UPDATE_SCROLL,
    Layout = raw_event::CONSOLE_LAYOUT,
    StartApplication = raw_event::CONSOLE_START_APPLICATION,
    EndApplication = raw_event::CONSOLE_END_APPLICATION,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, IntoPrimitive, TryFromPrimitive,
)]
#[repr(i32)]
/// A known event indicating a change in a console window.
pub enum ObjectWindowEvent {
    /// An object has been created.
    Create = raw_event::OBJECT_CREATE,

    /// An object has been destroyed.
    Destroy = raw_event::OBJECT_DESTROY,

    /// A hidden object is shown.
    Show = raw_event::OBJECT_SHOW,

    /// An object is hidden.
    Hide = raw_event::OBJECT_HIDE,

    /// A container object has added, removed, or reordered its children.
    Reorder = raw_event::OBJECT_REORDER,

    /// An object has received the keyboard focus.
    Focus = raw_event::OBJECT_FOCUS,

    /// The selection within a container object has changed.
    Selection = raw_event::OBJECT_SELECTION,

    /// A child within a container object has been added to an existing selection.
    SelectionAdd = raw_event::OBJECT_SELECTIONADD,

    /// An item within a container object has been removed from the selection.
    SelectionRemove = raw_event::OBJECT_SELECTIONREMOVE,

    /// Numerous selection changes have occurred within a container object.
    SelectionWithin = raw_event::OBJECT_SELECTIONWITHIN,

    /// An object's state has changed.
    StateChange = raw_event::OBJECT_STATECHANGE,

    /// An object has changed location, shape, or size.
    LocationChange = raw_event::OBJECT_LOCATIONCHANGE,

    /// An object's Name property has changed.
    NameChange = raw_event::OBJECT_NAMECHANGE,

    /// An object's Description property has changed.
    DescriptionChange = raw_event::OBJECT_DESCRIPTIONCHANGE,

    /// An object's Value property has changed.
    ValueChange = raw_event::OBJECT_VALUECHANGE,

    /// An object has a new parent object.
    ParentChange = raw_event::OBJECT_PARENTCHANGE,

    /// An object's Help property has changed.
    HelpChange = raw_event::OBJECT_HELPCHANGE,

    /// An object's DefaultAction property has changed.
    DefaultActionChange = raw_event::OBJECT_DEFACTIONCHANGE,

    /// An object's KeyboardShortcut property has changed.
    AcceloratorChange = raw_event::OBJECT_ACCELERATORCHANGE,

    /// An object has been invoked; for example, the user has clicked a button.
    Invoked = raw_event::OBJECT_INVOKED,

    /// An object's text selection has changed.
    TextSelectionChanged = raw_event::OBJECT_TEXTSELECTIONCHANGED,

    /// A window object's scrolling has ended.
    ContentScrolled = raw_event::OBJECT_CONTENTSCROLLED,

    /// A preview rectangle is being displayed.
    ArrangementPreview = raw_event::SYSTEM_ARRANGMENTPREVIEW,

    /// Sent when a window is cloaked.
    /// A cloaked window still exists, but is invisible to the user.
    Cloaked = raw_event::OBJECT_CLOAKED,

    /// Sent when a window is uncloaked.
    /// A cloaked window still exists, but is invisible to the user.
    Uncloaked = raw_event::OBJECT_UNCLOAKED,

    /// An object that is part of a live region has changed.
    /// A live region is an area of an application that changes frequently and/or asynchronously.
    LiveRegionChanged = raw_event::OBJECT_LIVEREGIONCHANGED,

    /// A window that hosts other accessible objects has changed the hosted objects.
    HostedObjectsInvalidated = raw_event::OBJECT_HOSTEDOBJECTSINVALIDATED,

    /// The user started to drag an element.
    DragStart = raw_event::OBJECT_DRAGSTART,

    /// The user has ended a drag operation before dropping the dragged element on a drop target.
    DragCancel = raw_event::OBJECT_DRAGCANCEL,

    /// The user dropped an element on a drop target.
    DragComplete = raw_event::OBJECT_DRAG_COMPLETE,

    /// The user dragged an element into a drop target's boundary.
    DragEnter = raw_event::OBJECT_DRAGENTER,

    /// The user dragged an element out of a drop target's boundary.
    DragLeave = raw_event::OBJECT_DRAGLEAVE,

    /// The user dropped an element on a drop target.
    DragDropped = raw_event::OBJECT_DRAGDROPPED,

    /// An IME window has become visible.
    ImeShow = raw_event::OBJECT_IME_SHOW,

    /// An IME window has become hidden.
    ImeHide = raw_event::OBJECT_IME_HIDE,

    /// The size or position of an IME window has changed.
    ImeChange = raw_event::OBJECT_IME_CHANGE,

    /// The conversion target within an IME composition has changed.
    /// The conversion target is the subset of the IME composition which is actively selected as the target for user-initiated conversions.
    TextEditConversionTargetChanged = raw_event::OBJECT_TEXTEDIT_CONVERSIONTARGETCHANGED,
}