ui_access

source of pkg::alloy::window::win32

1// The window on Windows, through Win32, whose system libraries every2// Windows program can call: a window procedure receives every message.3// The process is aware of each monitor's DPI (the scale is the DPI over4// 96), frames `present` gives go through GDI and a GPU surface's through5// its swapchain, and DWM paces redraws one after another to the display. Input methods speak through6// IMM32, the program drawing their compositions. Screen readers read the7// program's tree through UI Automation (uia.alloy), and the shell's file8// dialogs and OLE's drops come through COM (shell.alloy), the window's9// thread a single-threaded apartment. Needs Windows 10 1703 or later.1011import std::ffi;12import std::option;13import std::string;14import std::vector;15import std::io;16import std::time;1718import window;19import unicode;20import pkg::alloy::com;21import uia;22import shell;2324type Procedure = extern (c_pointer, u32, u64, i64) -> i64;2526extern GetModuleHandleW(name: c_pointer) -> c_pointer;27extern SetProcessDpiAwarenessContext(context: c_pointer) -> i32;28extern RegisterClassExW(class: c_pointer) -> u16;29extern CreateWindowExW(30    extended: u32,31    class: c_pointer,32    title: c_pointer,33    style: u32,34    x: i32,35    y: i32,36    width: i32,37    height: i32,38    parent: c_pointer,39    menu: c_pointer,40    instance: c_pointer,41    parameter: c_pointer42) -> c_pointer;43extern OpenClipboard(hwnd: c_pointer) -> i32;44extern CloseClipboard() -> i32;45extern EmptyClipboard() -> i32;46extern GetClipboardData(format: u32) -> c_pointer;47extern SetClipboardData(format: u32, memory: c_pointer) -> c_pointer;48extern GlobalAlloc(flags: u32, bytes: c_size) -> c_pointer;49extern GlobalLock(memory: c_pointer) -> c_pointer;50extern GlobalUnlock(memory: c_pointer) -> i32;51extern GlobalFree(memory: c_pointer) -> c_pointer;52extern PostMessageW(hwnd: c_pointer, message: u32, wparam: u64, lparam: i64) -> i32;53extern SetTimer(hwnd: c_pointer, id: u64, milliseconds: u32, function: c_pointer) -> u64;54extern KillTimer(hwnd: c_pointer, id: u64) -> i32;55extern DefWindowProcW(hwnd: c_pointer, message: u32, wparam: u64, lparam: i64) -> i64;56extern PeekMessageW(message: c_pointer, hwnd: c_pointer, first: u32, last: u32, remove: u32) -> i32;57extern MsgWaitForMultipleObjects(58    count: u32,59    handles: c_pointer,60    all: i32,61    milliseconds: u32,62    mask: u3263) -> u32;64extern GetMessageW(message: c_pointer, hwnd: c_pointer, first: u32, last: u32) -> i32;65extern TranslateMessage(message: c_pointer) -> i32;66extern DispatchMessageW(message: c_pointer) -> i64;67extern ShowWindow(hwnd: c_pointer, command: i32) -> i32;68extern DestroyWindow(hwnd: c_pointer) -> i32;69extern SetWindowTextW(hwnd: c_pointer, text: c_pointer) -> i32;70extern InvalidateRect(hwnd: c_pointer, rect: c_pointer, erase: i32) -> i32;71extern BeginPaint(hwnd: c_pointer, paint: c_pointer) -> c_pointer;72extern EndPaint(hwnd: c_pointer, paint: c_pointer) -> i32;73extern GetDC(hwnd: c_pointer) -> c_pointer;74extern ReleaseDC(hwnd: c_pointer, dc: c_pointer) -> i32;75extern SetWindowLongPtrW(hwnd: c_pointer, index: i32, value: i64) -> i64;76extern GetWindowLongPtrW(hwnd: c_pointer, index: i32) -> i64;77extern SetWindowPos(78    hwnd: c_pointer,79    after: c_pointer,80    x: i32,81    y: i32,82    width: i32,83    height: i32,84    flags: u3285) -> i32;86extern AdjustWindowRectExForDpi(87    rect: c_pointer,88    style: u32,89    menu: i32,90    extended: u32,91    dpi: u3292) -> i32;93extern GetDpiForWindow(hwnd: c_pointer) -> u32;94extern LoadCursorW(instance: c_pointer, name: c_pointer) -> c_pointer;95extern SetCursor(cursor: c_pointer) -> c_pointer;96extern TrackMouseEvent(track: c_pointer) -> i32;97extern SetCapture(hwnd: c_pointer) -> c_pointer;98extern ReleaseCapture() -> i32;99extern GetKeyState(key: i32) -> i16;100extern MapVirtualKeyW(code: u32, kind: u32) -> u32;101extern StretchDIBits(102    dc: c_pointer,103    x: i32,104    y: i32,105    width: i32,106    height: i32,107    source_x: i32,108    source_y: i32,109    source_width: i32,110    source_height: i32,111    bits: c_pointer,112    info: c_pointer,113    usage: u32,114    operation: u32115) -> i32;116extern DwmFlush() -> i32;117extern SystemParametersInfoW(action: u32, parameter: u32, value: c_pointer, flags: u32) -> i32;118extern ImmGetContext(hwnd: c_pointer) -> c_pointer;119extern ImmReleaseContext(hwnd: c_pointer, context: c_pointer) -> i32;120extern ImmAssociateContextEx(hwnd: c_pointer, context: c_pointer, flags: u32) -> i32;121extern ImmGetCompositionStringW(122    context: c_pointer,123    index: u32,124    buffer: c_pointer,125    bytes: u32126) -> i32;127extern ImmSetCompositionWindow(context: c_pointer, form: c_pointer) -> i32;128extern ImmSetCandidateWindow(context: c_pointer, form: c_pointer) -> i32;129130pub type Win32 = struct {131    hwnd: c_pointer = 0,132    window: Window,133    handler: |&| (&var Window, &Event),134    painting: bool = false,135    destroyed: bool = false,136    tracking: bool = false, // whether WM_MOUSELEAVE is asked for137    buttons: u32 = 0, // how many are held, the pointer captured meanwhile138    surrogate: Option<u32> = ::None, // the first half of a character WM_CHAR splits139    position: Point = Point { .x = 0.0, .y = 0.0 },140    sized: bool = false, // whether the handler has had a Resized141    composing: bool = false, // whether a composition shows142    input_method: bool = false, // whether the input method is on143    // UI Automation, and drops and dialogs, once installed (window.alloy's144    // Start)145    uia: Option<Uia> = ::None,146    drops: c_pointer = 0, // the DropTarget147    showing_dialog: bool = false,148    dialogs: Vector<DialogRequest> = Vector<DialogRequest>::empty(), // waiting for the one showing149    parts: Parts = Parts {},150};151152// What the window procedure and the loop call of what a program153// installed, set as each starts, so that a program installing nothing154// links none of it: UI Automation's WM_GETOBJECT, what a screen reader155// asked, the handler's requests for it and the providers let go once the156// window is gone; the drop target's calls, the dialogs asked for and the157// target revoked as the window goes.158type Parts = struct {159    object: Option<(&var Win32, u64, i64) -> i64> = ::None,160    acted: Option<(&var Win32)> = ::None,161    access: Option<(&var Win32, &var Requests)> = ::None,162    access_gone: Option<(&var Win32)> = ::None,163    access_ended: Option<(&var Win32)> = ::None,164    dropped: Option<(&var Win32)> = ::None,165    dialogs: Option<(&var Win32, &var Requests)> = ::None,166    files_gone: Option<(&var Win32)> = ::None,167};168169const GWLP_USERDATA: i32 = -21;170171pub fn run_win32(config: &WindowConfig, handler: |&| (&var Window, &Event)) -> i32 {172    // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2173    SetProcessDpiAwarenessContext(~(0 to c_pointer) - 3);174    // a single-threaded apartment, which OLE's drops need175    initialize_ole();176    var w = Win32 { .window = Window::opening(&config, 1.0), .handler = move handler };177    const instance = GetModuleHandleW(0);178    const class_name = wide(&"AlloyWindow");179    // WNDCLASSEXW: its size, the procedure, the instance, no cursor180    // (WM_SETCURSOR sets the window's) and the class's name181    const procedure: Procedure = window_procedure;182    var class: [u64 : 10] = [0 : 10];183    class[0] = 80;184    class[1] = (procedure as c_pointer) to u64;185    class[3] = instance to u64;186    class[8] = c_pointer::of(&class_name.view()) to u64;187    RegisterClassExW(c_pointer::of(&class[..]));188    // WS_OVERLAPPEDWINDOW, without resizing when not resizable189    const style: u32 = if (config.resizable) 0x00CF0000 else 0x00C80000;190    const title = wide(&config.title);191    // CW_USEDEFAULT192    const default = (0x80000000 to u32) as i32;193    w.hwnd = CreateWindowExW(194        0,195        c_pointer::of(&class_name.view()),196        c_pointer::of(&title.view()),197        style,198        default,199        default,200        default,201        default,202        0,203        0,204        instance,205        0206    );207    if (w.hwnd == 0) {208        print_error(&"pkg::alloy::window: the window cannot be created\n");209        return 1;210    }211    SetWindowLongPtrW(w.hwnd, GWLP_USERDATA, c_pointer::from(&w) to i64);212    // no input method until the program asks for one213    ImmAssociateContextEx(w.hwnd, 0, 0);214    w.window.target = Target::Win32(Win32Target { .instance = instance, .window = w.hwnd });215    w.window.waker = Waker::Win32(w.hwnd);216    w.window.reduced_motion = reduced_motion();217    // the client area at the configured size, at the monitor's scale218    const dpi = GetDpiForWindow(w.hwnd);219    const scale = dpi to f32 / 96.0;220    const size = physical(&config.size, scale);221    var rect: [i32 : 4] = [0, 0, size.width as i32, size.height as i32];222    AdjustWindowRectExForDpi(c_pointer::of(&rect[..]), style, 0, 0, dpi);223    // SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE224    SetWindowPos(w.hwnd, 0, 0, 0, rect[2] - rect[0], rect[3] - rect[1], 0x16);225    if (scale != 1.0) {226        w.deliver(&Event::Scaled(scale));227    }228    w.resize(size);229    ShowWindow(w.hwnd, 5);230    // a MSG231    var message: [u64 : 6] = [0 : 6];232    while (!w.destroyed) {233        if (GetMessageW(c_pointer::of(&message[..]), 0, 0, 0) <= 0) {234            break;235        }236        TranslateMessage(c_pointer::of(&message[..]));237        DispatchMessageW(c_pointer::of(&message[..]));238    }239    if (w.parts.access_ended is ::Some |ended|) {240        ended(&var w);241    }242    return 0;243}244245/* --- What a program installs --- */246247// Answers UI Automation, the program sending its tree once asked.248pub fn start_automation(w: &var Win32) {249    w.uia = ::Some(Uia::create(w.hwnd));250    w.parts.object = ::Some(answer_automation);251    w.parts.acted = ::Some(automation_acted);252    w.parts.access = ::Some(give_automation);253    w.parts.access_gone = ::Some(disconnect_automation);254    w.parts.access_ended = ::Some(end_automation);255}256257// WM_GETOBJECT for UI Automation's root (UiaRootObjectId, -25): the258// program sends its tree from then on.259fn answer_automation(w: &var Win32, wparam: u64, lparam: i64) -> i64 {260    var requested = false;261    if (w.uia is ::Some |&var uia| && !uia.requested) {262        uia.requested = true;263        requested = true;264    }265    if (requested) {266        w.deliver(&Event::AccessRequested);267    }268    if (w.uia is ::Some |&var uia|) {269        return uia.answer(wparam, lparam);270    }271    return 0;272}273274// What a screen reader asked, each posting ACTED again.275fn automation_acted(w: &var Win32) {276    var actions = Vector<ActionRequest>::empty();277    if (w.uia is ::Some |&var uia|) {278        actions = move uia.actions;279        uia.actions = Vector<ActionRequest>::empty();280    }281    for (actions.items()) |&var action| {282        w.deliver(&Event::Action(move action));283    }284}285286// Gives UI Automation the window's language, the tree's updates and287// what to say.288fn give_automation(w: &var Win32, asked: &var Requests) {289    if (w.uia is ::Some |&var uia|) {290        if (asked.language) {291            uia.set_language(&w.window.language.view());292        }293        for (asked.access.items()) |&var update| {294            uia.update(move update);295        }296        for (asked.announcements.view()) |&said| {297            uia.announce(&said.text, said.assertive);298        }299    }300}301302fn disconnect_automation(w: &var Win32) {303    if (w.uia is ::Some |&var uia|) {304        uia.disconnect();305    }306}307308// UI Automation lets the providers it held go through a message it309// posts once the window is gone: waited for, a second at most.310fn end_automation(w: &var Win32) {311    var message: [u64 : 6] = [0 : 6];312    for ([..100 to u64]) |k| {313        const held = if (w.uia is ::Some |&uia|) uia.held() else false;314        if (!held) {315            break;316        }317        MsgWaitForMultipleObjects(0, 0, 0, 10, 0x04FF); // QS_ALLINPUT318        while (PeekMessageW(c_pointer::of(&message[..]), 0, 0, 0, 1) != 0) { // PM_REMOVE319            DispatchMessageW(c_pointer::of(&message[..]));320        }321    }322    if (w.uia is ::Some |&var uia|) {323        uia.finish();324    }325}326327// Takes drops through OLE and shows the shell's dialogs.328pub fn start_files_win32(w: &var Win32) {329    w.drops = register_drops(w.hwnd, DROPPED);330    w.parts.dropped = ::Some(give_drops);331    w.parts.dialogs = ::Some(show_dialogs);332    w.parts.files_gone = ::Some(revoke);333}334335// What the drop target's calls queued.336fn give_drops(w: &var Win32) {337    const target = &var w.drops.as_var<DropTarget>();338    var events = move target.events;339    target.events = Vector<Event>::empty();340    for (events.view()) |&event| {341        w.deliver(&event);342    }343}344345// A dialog's own loop goes on delivering events meanwhile, which may ask346// for more dialogs: those wait for it.347fn show_dialogs(w: &var Win32, asked: &var Requests) {348    for (asked.dialogs.items()) |&var dialog| {349        w.dialogs.push(move dialog);350    }351    if (!w.showing_dialog) {352        w.showing_dialog = true;353        var k: u64 = 0;354        while (k < w.dialogs.length() && !w.destroyed) {355            const dialog = copy w.dialogs.get(k);356            k += 1;357            var files = show_dialog(w.hwnd, &dialog);358            w.deliver(&Event::FilesChosen(Chosen { .request = dialog.id, .files = move files }));359        }360        w.dialogs.clear();361        w.showing_dialog = false;362    }363}364365fn revoke(w: &var Win32) {366    revoke_drops(w.hwnd, w.drops);367    w.drops = 0;368}369370// WM_APP + 1, posted by a Waker, and WM_APP + 3 after a drop target's371// call (uia.alloy's ACTED is WM_APP + 2)372const WAKE: u32 = 0x8001;373const DROPPED: u32 = 0x8003;374375// The timer giving the program's deadline (`wake_at`).376const DEADLINE: u64 = 1;377378// The messages the window procedure handles; it passes the others on to379// DefWindowProcW.380const WM_DESTROY: u32 = 0x0002;381const WM_SIZE: u32 = 0x0005;382const WM_SETFOCUS: u32 = 0x0007;383const WM_KILLFOCUS: u32 = 0x0008;384const WM_PAINT: u32 = 0x000F;385const WM_CLOSE: u32 = 0x0010;386const WM_ERASEBKGND: u32 = 0x0014;387const WM_SETTINGCHANGE: u32 = 0x001A;388const WM_SETCURSOR: u32 = 0x0020;389const WM_TIMER: u32 = 0x0113;390const WM_GETOBJECT: u32 = 0x003D;391const WM_KEYDOWN: u32 = 0x0100;392const WM_KEYUP: u32 = 0x0101;393const WM_CHAR: u32 = 0x0102;394const WM_SYSKEYDOWN: u32 = 0x0104;395const WM_SYSKEYUP: u32 = 0x0105;396const WM_IME_STARTCOMPOSITION: u32 = 0x010D;397const WM_IME_ENDCOMPOSITION: u32 = 0x010E;398const WM_IME_COMPOSITION: u32 = 0x010F;399const WM_MOUSEMOVE: u32 = 0x0200;400const WM_LBUTTONDOWN: u32 = 0x0201;401const WM_LBUTTONUP: u32 = 0x0202;402const WM_LBUTTONDBLCLK: u32 = 0x0203;403const WM_RBUTTONDOWN: u32 = 0x0204;404const WM_RBUTTONUP: u32 = 0x0205;405const WM_RBUTTONDBLCLK: u32 = 0x0206;406const WM_MBUTTONDOWN: u32 = 0x0207;407const WM_MBUTTONUP: u32 = 0x0208;408const WM_MBUTTONDBLCLK: u32 = 0x0209;409const WM_MOUSEWHEEL: u32 = 0x020A;410const WM_XBUTTONDOWN: u32 = 0x020B;411const WM_XBUTTONUP: u32 = 0x020C;412const WM_XBUTTONDBLCLK: u32 = 0x020D;413const WM_MOUSEHWHEEL: u32 = 0x020E;414const WM_IME_SETCONTEXT: u32 = 0x0281;415const WM_MOUSELEAVE: u32 = 0x02A3;416const WM_DPICHANGED: u32 = 0x02E0;417418// Whether "Animation effects" are off in Windows' settings419// (SPI_GETCLIENTAREAANIMATION).420fn reduced_motion() -> bool {421    var animated: [i32 : 1] = [1];422    SystemParametersInfoW(0x1042, 0, c_pointer::of(&animated[..]), 0);423    return animated[0] == 0;424}425426// Posts the window the message its procedure wakes the loop with.427pub fn wake_win32(hwnd: c_pointer) {428    PostMessageW(hwnd, WAKE, 0, 0);429}430431fn window_procedure(hwnd: c_pointer, message: u32, wparam: u64, lparam: i64) -> i64 {432    // set once CreateWindowExW returns; the messages before go to Windows433    const state = GetWindowLongPtrW(hwnd, GWLP_USERDATA) to c_pointer;434    if (state == 0) {435        return DefWindowProcW(hwnd, message, wparam, lparam);436    }437    const w: &var Win32 = &var state.as_var<Win32>();438    return w.on_message(message, wparam, lparam);439}440441fn on_message(self w: &var Win32, message: u32, wparam: u64, lparam: i64) -> i64 {442    match (message) {443        // what the window posted itself444        WAKE {445            w.deliver(&Event::Woken);446            return 0;447        }448        ACTED {449            if (w.parts.acted is ::Some |acted|) {450                acted(&var w);451            }452            return 0;453        }454        DROPPED {455            if (w.parts.dropped is ::Some |dropped|) {456                dropped(&var w);457            }458            return 0;459        }460        WM_TIMER {461            if (wparam == DEADLINE) {462                KillTimer(w.hwnd, DEADLINE);463                // a timer may come a little early, then waits again464                if (w.window.take_due()) {465                    w.deliver(&Event::Timer);466                } else {467                    w.arm_timer();468                }469            }470            return 0;471        }472        WM_PAINT {473            w.paint();474            return 0;475        }476        WM_ERASEBKGND {477            // the frame covers it all478            return 1;479        }480        WM_SETTINGCHANGE {481            const reduced = reduced_motion();482            if (reduced != w.window.reduced_motion) {483                w.deliver(&Event::ReducedMotion(reduced));484            }485            return 0;486        }487        WM_SIZE {488            const size = Size { .width = low(lparam), .height = high(lparam) };489            if (size.width != 0 && size.height != 0) {490                w.resize(size);491            }492            return 0;493        }494        WM_DPICHANGED {495            // the new DPI, and where Windows suggests the window goes496            const scale = (wparam & 0xFFFF) to f32 / 96.0;497            w.deliver(&Event::Scaled(scale));498            const rect = &(lparam to c_pointer).view<i32>(4);499            // SWP_NOZORDER | SWP_NOACTIVATE500            SetWindowPos(w.hwnd, 0, rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1], 0x14);501            return 0;502        }503        WM_GETOBJECT {504            // for UI Automation's root (UiaRootObjectId, -25)505            if ((lparam & 0xFFFFFFFF) == 0xFFFFFFE7 && w.parts.object is ::Some |answer|) {506                return answer(&var w, wparam, lparam);507            }508        }509        WM_CLOSE {510            // the program decides511            w.deliver(&Event::CloseRequested);512            return 0;513        }514        WM_DESTROY {515            w.destroyed = true;516            if (w.parts.access_gone is ::Some |gone|) {517                gone(&var w);518            }519            if (w.parts.files_gone is ::Some |gone|) {520                gone(&var w);521            }522            return 0;523        }524        WM_SETCURSOR {525            // over the client area (HTCLIENT)526            if ((lparam & 0xFFFF) == 1) {527                w.show_cursor();528                return 1;529            }530        }531        WM_SETFOCUS, WM_KILLFOCUS {532            w.deliver(&Event::Focused(message == WM_SETFOCUS));533            return 0;534        }535        WM_MOUSEMOVE {536            w.pointer_moved(lparam);537            return 0;538        }539        WM_MOUSELEAVE {540            w.tracking = false;541            w.deliver(&Event::PointerLeft);542            return 0;543        }544        WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK, WM_RBUTTONDOWN, WM_RBUTTONUP,545        WM_RBUTTONDBLCLK, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MBUTTONDBLCLK {546            w.button(message, wparam, lparam);547            return 0;548        }549        WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK {550            w.button(message, wparam, lparam);551            return 1;552        }553        WM_MOUSEWHEEL, WM_MOUSEHWHEEL {554            // notches of 120, the wheel's positive away from the user555            const notches = ((high(wparam as i64) to u16) as i16) to f32 / 120.0;556            const delta = if (557                message == WM_MOUSEWHEEL558            ) Point { .x = 0.0, .y = -notches } else Point { .x = notches, .y = 0.0 };559            const event = Event::Scroll(ScrollEvent {560                .delta = delta,561                .precise = false,562                .modifiers = modifiers()563            });564            w.deliver(&event);565            return 0;566        }567        WM_KEYDOWN, WM_SYSKEYDOWN, WM_KEYUP, WM_SYSKEYUP {568            // a key an input method takes comes as VK_PROCESSKEY569            if ((wparam & 0xFFFF) == 0xE5) {570                return 0;571            }572            const pressed = message == WM_KEYDOWN || message == WM_SYSKEYDOWN;573            const event = Event::Key(KeyEvent {574                .key = key((wparam & 0xFFFF) to u32),575                .pressed = pressed,576                .repeat = pressed && (lparam & 0x40000000) != 0,577                .modifiers = modifiers()578            });579            w.deliver(&event);580            if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP) {581                // Alt+F4 and the window menu582                return DefWindowProcW(w.hwnd, message, wparam, lparam);583            }584            return 0;585        }586        WM_CHAR {587            // UTF-16, a character outside the first plane in two588            w.character((wparam & 0xFFFF) to u32);589            return 0;590        }591        WM_IME_SETCONTEXT {592            // without the input method's composition window593            // (ISC_SHOWUICOMPOSITIONWINDOW), which the program draws594            return DefWindowProcW(w.hwnd, message, wparam, lparam & ~(0x80000000 to i64));595        }596        WM_IME_STARTCOMPOSITION {597            w.place_input_method();598            return 0;599        }600        WM_IME_COMPOSITION {601            w.composition(lparam);602            return 0;603        }604        WM_IME_ENDCOMPOSITION {605            w.end_composition();606            return 0;607        }608        else {}609    }610    return DefWindowProcW(w.hwnd, message, wparam, lparam);611}612613// The composition's committed text (GCS_RESULTSTR), then the one in614// progress (GCS_COMPSTR) with its caret (GCS_CURSORPOS).615fn composition(self w: &var Win32, lparam: i64) {616    const context = ImmGetContext(w.hwnd);617    if (context == 0) {618        return;619    }620    var result = String::empty();621    var preedit = Preedit { .text = String::empty(), .cursor = 0 };622    const has_result = (lparam & 0x800) != 0;623    const has_preedit = (lparam & 0x8) != 0;624    if (has_result) {625        result = composition_string(context, 0x800);626    }627    if (has_preedit) {628        preedit.text = composition_string(context, 0x8);629        const units = ImmGetCompositionStringW(context, 0x80, 0, 0);630        preedit.cursor = utf8_offset(&preedit.text.view(), if (units < 0) 0 else units to u64);631    }632    ImmReleaseContext(w.hwnd, context);633    if (result.length() != 0) {634        w.end_composition();635        w.deliver(&Event::Text(move result));636    }637    if (has_preedit && (preedit.text.length() != 0 || w.composing)) {638        w.composing = preedit.text.length() != 0;639        w.deliver(&Event::Preedit(move preedit));640    }641}642643fn end_composition(self w: &var Win32) {644    if (w.composing) {645        w.composing = false;646        w.deliver(&Event::Preedit(Preedit { .text = String::empty(), .cursor = 0 }));647    }648}649650// The composition string of the kind, as UTF-8.651fn composition_string(context: c_pointer, index: u32) -> String {652    const bytes = ImmGetCompositionStringW(context, index, 0, 0);653    if (bytes <= 0) {654        return String::empty();655    }656    var units: *var [u16] = new [0 to u16 : bytes to u64 / 2];657    ImmGetCompositionStringW(context, index, c_pointer::of(&units[..]), bytes as u32);658    return narrow(&units[..], false);659}660661// Turns the input method on or off as the window asks, and tells it662// where the caret is: its composition window at the caret, which it does663// not show, and its candidates kept clear of the caret's area. Only664// turning it on associates the context again, which would end a665// composition in progress, as the caret moving with it does each key. A666// password's field has none, as an ES_PASSWORD edit: its characters come667// as WM_CHAR, nothing composed nor remembered.668fn update_input_method(self w: &var Win32) {669    if (w.window.text_input is ::None || w.window.secret_input) {670        if (w.input_method) {671            w.end_composition();672            ImmAssociateContextEx(w.hwnd, 0, 0);673            w.input_method = false;674        }675        return;676    }677    if (!w.input_method) {678        // IACE_DEFAULT679        ImmAssociateContextEx(w.hwnd, 0, 0x10);680        w.input_method = true;681    }682    w.place_input_method();683}684685fn place_input_method(self w: &Win32) {686    if (w.window.text_input is ::Some |area|) {687        const context = ImmGetContext(w.hwnd);688        if (context == 0) {689            return;690        }691        const left = area.x to i32;692        const top = area.y to i32;693        const right = (area.x + area.width) to i32;694        const bottom = (area.y + area.height) to i32;695        // a COMPOSITIONFORM: CFS_POINT, its point696        var composition: [i32 : 7] = [2, left, top, 0, 0, 0, 0];697        ImmSetCompositionWindow(context, c_pointer::of(&composition[..]));698        // a CANDIDATEFORM: its index, CFS_EXCLUDE, a point, the area699        var candidates: [i32 : 8] = [0, 0x80, left, bottom, left, top, right, bottom];700        ImmSetCandidateWindow(context, c_pointer::of(&candidates[..]));701        ImmReleaseContext(w.hwnd, context);702    }703}704705// Shows the window's cursor: IDC_ARROW, IDC_HAND or IDC_IBEAM.706fn show_cursor(self w: &Win32) {707    const cursor = match (w.window.cursor) {708        ::Arrow LoadCursorW(0, 32512);709        ::Hand LoadCursorW(0, 32649);710        ::Text LoadCursorW(0, 32513);711    };712    SetCursor(cursor);713}714715// Gives the event to the handler, then does what it asked.716fn deliver(self w: &var Win32, event: &Event) {717    if (w.destroyed) {718        return;719    }720    w.window.apply(&event);721    w.handler(&var w.window, &event);722    var asked = w.window.take_requests();723    for (asked.starting.view()) |&start| {724        if (start is ::Win32 |f|) {725            f(&var w);726        }727    }728    if (asked.title) {729        const title = wide(&w.window.title.view());730        SetWindowTextW(w.hwnd, c_pointer::of(&title.view()));731    }732    if (asked.cursor && w.tracking) {733        w.show_cursor();734    }735    if (asked.text_input) {736        w.update_input_method();737    }738    if (asked.wake) {739        w.arm_timer();740    }741    if (w.window.presented && !w.painting) {742        // shown now, outside WM_PAINT743        w.window.presented = false;744        const dc = GetDC(w.hwnd);745        w.blit(dc);746        ReleaseDC(w.hwnd, dc);747    }748    if (w.window.redraw_requested && !w.painting) {749        w.window.redraw_requested = false;750        InvalidateRect(w.hwnd, 0, 0);751    }752    if (asked.clipboard is ::Some |&text|) {753        write_clipboard(w.hwnd, &text.view());754    }755    if (w.parts.access is ::Some |give|) {756        give(&var w, &var asked);757    }758    if (w.parts.dialogs is ::Some |show|) {759        show(&var w, &var asked);760    }761    if (asked.clipboard_wanted && !w.destroyed) {762        w.deliver(&Event::Clipboard(read_clipboard(w.hwnd)));763    }764    if (asked.close && !w.destroyed) {765        DestroyWindow(w.hwnd);766    }767}768769// Sets the timer for the program's deadline, whole milliseconds rounded770// up, or stops it when there is none.771fn arm_timer(self w: &Win32) {772    if (w.window.until_wake() is ::Some |left|) {773        // USER_TIMER_MAXIMUM is about 24 days774        const ms = (left.nanoseconds + 999999) / 1000000;775        SetTimer(776            w.hwnd,777            DEADLINE,778            if (ms < 1) 1 else if (ms > 0x7FFFFFFF) 0x7FFFFFFF else ms to u32,779            0780        );781    } else {782        KillTimer(w.hwnd, DEADLINE);783    }784}785786// CF_UNICODETEXT: UTF-16 ending in a NUL, lines ending in CR LF787const UNICODE_TEXT: u32 = 13;788789fn write_clipboard(hwnd: c_pointer, text: &[u8]) {790    var lines = String::empty();791    for ([..text.length()]) |k| {792        if (text[k] == '\n' && (k == 0 || text[k - 1] != '\r')) {793            lines.push('\r');794        }795        lines.push(text[k]);796    }797    const units = wide(&lines.view());798    if (OpenClipboard(hwnd) == 0) {799        return;800    }801    EmptyClipboard();802    // GMEM_MOVEABLE, which the clipboard owns once set803    const memory = GlobalAlloc(0x0002, (units.length() * 2) to c_size);804    if (memory != 0) {805        const at = GlobalLock(memory);806        if (at != 0) {807            at.view_var<u16>(units.length())[..] = units.view();808            GlobalUnlock(memory);809        }810        if (SetClipboardData(UNICODE_TEXT, memory) == 0) {811            GlobalFree(memory);812        }813    }814    CloseClipboard();815}816817// The clipboard's text, lines ending in LF; empty when it holds none.818fn read_clipboard(hwnd: c_pointer) -> String {819    var out = String::empty();820    if (OpenClipboard(hwnd) == 0) {821        return move out;822    }823    const memory = GetClipboardData(UNICODE_TEXT);824    if (memory != 0) {825        const at = GlobalLock(memory);826        if (at != 0) {827            var length: u64 = 0;828            while (at.view<u16>(length + 1)[length] != 0) {829                length += 1;830            }831            out = narrow(&at.view<u16>(length), true);832            GlobalUnlock(memory);833        }834    }835    CloseClipboard();836    return move out;837}838839fn paint(self w: &var Win32) {840    // a PAINTSTRUCT841    var paint: [u64 : 9] = [0 : 9];842    const dc = BeginPaint(w.hwnd, c_pointer::of(&paint[..]));843    w.painting = true;844    w.deliver(&Event::Redraw(w.window.now()));845    w.painting = false;846    w.window.presented = false;847    // a surface's frame is the GPU's to show, its presenting pacing the848    // next849    const surface = w.window.surface_presented;850    w.window.surface_presented = false;851    if (!surface) {852        w.blit(dc);853    }854    EndPaint(w.hwnd, c_pointer::of(&paint[..]));855    if (w.window.redraw_requested) {856        // the next frame once the display has shown this one857        w.window.redraw_requested = false;858        if (!surface) {859            DwmFlush();860        }861        InvalidateRect(w.hwnd, 0, 0);862    }863}864865// Draws the last frame presented over the window, scaled to it.866fn blit(self w: &Win32, dc: c_pointer) {867    const frame = w.window.frame_size;868    if (frame.width == 0 || frame.height == 0) {869        return;870    }871    // a BITMAPINFO: 32 bits a pixel, BI_RGB, rows from the top872    var info: [u32 : 11] = [0 : 11];873    info[0] = 40;874    info[1] = frame.width;875    info[2] = (-(frame.height as i32)) as u32;876    info[3] = 1 | (32 << 16);877    const size = w.window.size;878    // DIB_RGB_COLORS, SRCCOPY879    StretchDIBits(880        dc,881        0,882        0,883        size.width as i32,884        size.height as i32,885        0,886        0,887        frame.width as i32,888        frame.height as i32,889        c_pointer::of(&w.window.frame),890        c_pointer::of(&info[..]),891        0,892        0x00CC0020893    );894}895896fn resize(self w: &var Win32, size: Size) {897    if (size != w.window.size || !w.sized) {898        w.sized = true;899        w.deliver(&Event::Resized(size));900        InvalidateRect(w.hwnd, 0, 0);901    }902}903904fn pointer_moved(self w: &var Win32, lparam: i64) {905    if (!w.tracking) {906        // a TRACKMOUSEEVENT asking for WM_MOUSELEAVE (TME_LEAVE)907        var track: [u64 : 3] = [16 | (2 to u64 << 32), w.hwnd to u64, 0];908        TrackMouseEvent(c_pointer::of(&track[..]));909        w.tracking = true;910    }911    w.position = Point {912        .x = ((low(lparam) to u16) as i16) to f32,913        .y = ((high(lparam) to u16) as i16) to f32914    };915    w.deliver(&Event::PointerMoved(w.position));916}917918fn button(self w: &var Win32, message: u32, wparam: u64, lparam: i64) {919    // WM_LBUTTONDOWN and the next ones, in down, up, double-click920    // threes, the extra buttons' from WM_XBUTTONDOWN921    const extra = message >= WM_XBUTTONDOWN;922    const kind = if (extra) 3 else (message - WM_LBUTTONDOWN) / 3;923    const pressed = (if (extra) message - WM_XBUTTONDOWN else (message - WM_LBUTTONDOWN) % 3) != 1;924    const button = match (kind) {925        0 PointerButton::Left;926        1 PointerButton::Right;927        2 PointerButton::Middle;928        else if (high(wparam as i64) == 1) PointerButton::Back else PointerButton::Forward;929    };930    if (pressed) {931        if (w.buttons == 0) {932            SetCapture(w.hwnd);933        }934        w.buttons += 1;935    } else if (w.buttons > 0) {936        w.buttons -= 1;937        if (w.buttons == 0) {938            ReleaseCapture();939        }940    }941    w.position = Point {942        .x = ((low(lparam) to u16) as i16) to f32,943        .y = ((high(lparam) to u16) as i16) to f32944    };945    const event = Event::Button(ButtonEvent {946        .button = button,947        .pressed = pressed,948        .position = w.position,949        .modifiers = modifiers()950    });951    w.deliver(&event);952}953954fn character(self w: &var Win32, unit: u32) {955    if (unit >= 0xD800 && unit < 0xDC00) {956        w.surrogate = ::Some(unit);957        return;958    }959    var code = unit;960    if (unit >= 0xDC00 && unit < 0xE000) {961        const first = if (w.surrogate is ::Some |s|) s else {962            return;963        };964        code = 0x10000 + ((first - 0xD800) << 10) + (unit - 0xDC00);965    }966    w.surrogate = ::None;967    if (code < 32 || code == 127) {968        return;969    }970    var text = String::empty();971    utf8(code, &var text);972    w.deliver(&Event::Text(move text));973}974975fn modifiers() -> Modifiers {976    // VK_SHIFT, VK_CONTROL, VK_MENU, VK_LWIN and VK_RWIN, held when977    // their state's top bit is set978    return Modifiers {979        .shift = GetKeyState(0x10) < 0,980        .control = GetKeyState(0x11) < 0,981        .alt = GetKeyState(0x12) < 0,982        .super = GetKeyState(0x5B) < 0 || GetKeyState(0x5C) < 0983    };984}985986// The key of a virtual-key code.987fn key(code: u32) -> Key {988    if (code >= 0x70 && code <= 0x87) {989        return Key::Function((code - 0x70 + 1) to u8);990    }991    const named: Option<Key> = match (code) {992        0x0D ::Some(Key::Enter);993        0x1B ::Some(Key::Escape);994        0x08 ::Some(Key::Backspace);995        0x09 ::Some(Key::Tab);996        0x2E ::Some(Key::Delete);997        0x2D ::Some(Key::Insert);998        0x25 ::Some(Key::Left);999        0x27 ::Some(Key::Right);1000        0x26 ::Some(Key::Up);1001        0x28 ::Some(Key::Down);1002        0x24 ::Some(Key::Home);1003        0x23 ::Some(Key::End);1004        0x21 ::Some(Key::PageUp);1005        0x22 ::Some(Key::PageDown);1006        0x10 ::Some(Key::Shift);1007        0x11 ::Some(Key::Control);1008        0x12 ::Some(Key::Alt);1009        0x5B, 0x5C ::Some(Key::Super);1010        0x14 ::Some(Key::CapsLock);1011        0x5D ::Some(Key::Menu); // VK_APPS1012        0x20 ::Some(Key::Character(' '));1013        else ::None;1014    };1015    if (named is ::Some |k|) {1016        return k;1017    }1018    // the character the key writes alone (MAPVK_VK_TO_CHAR), a dead1019    // key's in the top bit1020    const character = MapVirtualKeyW(code, 2) & 0x7FFFFFFF;1021    if (character == 0) {1022        return Key::Unknown(code);1023    }1024    if (character >= 'A' && character <= 'Z') {1025        return Key::Character(character + 32);1026    }1027    return Key::Character(character);1028}10291030fn low(value: i64) -> u32 {1031    return (value & 0xFFFF) to u32;1032}10331034fn high(value: i64) -> u32 {1035    return ((value >> 16) & 0xFFFF) to u32;1036}10371038// The text as UTF-16 with a NUL after it, as Windows' W functions take it.