native-windows-gui 1.0.12

A rust library to develop native GUI applications on the desktop for Microsoft Windows. Native-windows-gui wraps the native win32 window controls in a rustic API
Documentation
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
# Native Windows GUI


Welcome to Native Windows GUI (aka NWG). A rust library to develop native GUI applications on the desktop for Microsoft Windows.

NWG is a very light wrapper over WINAPI. It allows you, the developer, to handle
the quirks and rough edges of the API by providing a simple, safe and rust-like interface.

Native Windows GUI keeps things simple. This means small compile times, minimal resource usage,
less time searching the documentation and more time for you to develop your application.

Of course, you don't have to take my word for it, check out the [showcase](showcase) and the 
[examples](native-windows-gui/examples).

This is the 3rd and final version of NWG. It is considered "mature" or, as I would say
"the backlog is empty, and it will most likely stay that way". This version implements pretty much
everything required to develop applications on Windows. Don't bother using the older versions as they
have "irreconcilable design decisions" and cannot support some key features. Future development will be done
in other libraries.

If you've managed to read through this introduction, you should know that my twitter handle
is [#gdube_dev](https://twitter.com/gdube_dev) and you can support this project with [*GitHub Sponsors*](https://github.com/sponsors/gabdube).

Any support is greatly appreciated.

## Installation


To use NWG in your project add it to cargo.toml:

```toml
[dependencies]
native-windows-gui = "1.0.12"
native-windows-derive = "1.0.3" # Optional. Only if the derive macro is used.
```

And then, in main.rs or lib.rs :

```rust
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;  // Optional. Only if the derive macro is used.
```

### Rust 2018 aliasing


You can skip the `extern crate` define in your source code by adding the following code in `Cargo.toml`
Note that procedural macros still require an `extern crate` definition, so this wont work with `native-windows-derive`

```toml
[dependencies]
nwg = {version = "^1.0.12", package = "native-windows-gui"}
```


## Trying it out


See it for yourself. NWG has plenty of examples and a fully interactive test suite. The only thing you need to do is:

```bash
git clone git@github.com:gabdube/native-windows-gui.git

cd native-windows-gui/native-windows-gui # Running the tests from the workspace screws up the features

cargo test everything --features "all"  # For the test suite
cargo run --example basic
cargo run --example calculator
cargo run --example message_bank
cargo run --example image_decoder_d --features "extern-canvas"
cargo run --example partials --features "listbox frame combobox"
cargo run --example system_tray --features "tray-notification message-window menu cursor"
cargo run --example dialog_multithreading_d --features "notice"
cargo run --example image_decoder_d --features "image-decoder file-dialog"
cargo run --example month_name_d --features "winnls textbox"
cargo run --example splash_screen_d --features "image-decoder"
cargo run --example drop_files_d --features "textbox"

cd examples/opengl_canvas
cargo run

# The closest thing to a real application in the examples

cd ../examples/sync-draw
cargo run

# Requires the console to be run as Admin because of the embed resource

cd ../examples/embed_resources
cargo run
```

### Cross-compiling from Ubuntu


Requirement: MinGW compiler

    sudo apt install gcc-mingw-w64-x86-64

Requirement: Rust support

    rustup target add x86_64-pc-windows-gnu

Compiling and running basic example:

    cargo build --release --target=x86_64-pc-windows-gnu
    cargo build --release --target=x86_64-pc-windows-gnu --example basic
    wine target/x86_64-pc-windows-gnu/release/examples/basic.exe

## Supported features


- The WHOLE winapi control library [(reference)]https://docs.microsoft.com/en-us/windows/win32/controls/individual-control-info
  - Some very niche controls are not supported: flat scroll bar, ip control, rebar, and pager.
- Menus and menu bar
- Image and font resource
  - BMP
  - ICO
  - CUR
  - PNG*
  - GIF*
  - JPG*
  - TIFF*
  - DDS*
  - *: Extended image formats with the Windows Imaging Component (WIC).
- Localization support
  - Uses Windows National Language Support internally [(reference)]https://docs.microsoft.com/en-us/windows/win32/intl/national-language-support
- Tooltip
- System tray notification
- Cursor handling
- A full clipboard wrapper
- Partial templates support
  - Split large application into chunks
- Dynamic controls support
  - Add/Remove controls at runtime
  - Bind or unbind new events at runtime
- Multithreaded application support
  - Communicate to the GUI thread from another thread
  - Run multiple windows on different threads
- Simple layout configurations
  - FlexboxLayout
  - GridLayout
- Drag and drop
  - Drop files from the desktop to a window
- The most common dialog boxes
  - File dialog (save, open, open folder)
  - Font dialog
  - Color dialog
- A canvas that can be used by external rendering APIs
- High-DPI aware
- Support for accessibility functions
  - Tab navigation
- Support for low level system message capture (HWND, MSG, WPARAM, LPARAM)
- Cross compiling and testing from Linux to Windows with Wine and mingw.
  - Not all features are supported (but the majority are, thanks WINE!)
  - See `https://zork.net/~st/jottings/rust-windows-and-debian.html` for the steps to follow

## Performance


This was measured on a `Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz, 3401 Mhz, 4 Core(s), 8 Logical Processor(s)`

In release mode, the `basic` example weighs **163kb** on disk and takes **900kb** in memory. Launch time is instantaneous.

The interactive test suite (with every feature and 100s of tests) weighs **931 kb** on disk and takes **8MB** in memory. Launch time is still instantaneous.

Initial build time takes around **22 seconds** for a basic application. This is mainly due to `winapi-rs` initial compile time. Subsequent compile time takes around **0.7 seconds**.

## Development


The development of this library is considered "done". By that, I mean that
there won't be any change to the API. Issues can be raised if a bug is found or
if some area in the documentation is unclear. If I overlooked a very important feature,
it will most likely be added.

## License


NWG uses the MIT license

## Code example


### With native windows derive


```rust
#![windows_subsystem = "windows"]

/*!
    A very simple application that shows your name in a message box.
    Unlike `basic_d`, this example uses layout to position the controls in the window
*/


extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;

use nwd::NwgUi;
use nwg::NativeUi;


#[derive(Default, NwgUi)]

pub struct BasicApp {
    #[nwg_control(size: (300, 115), position: (300, 300), title: "Basic example", flags: "WINDOW|VISIBLE")]
    #[nwg_events( OnWindowClose: [BasicApp::say_goodbye] )]
    window: nwg::Window,

    #[nwg_layout(parent: window, spacing: 1)]
    grid: nwg::GridLayout,

    #[nwg_control(text: "Heisenberg", focus: true)]
    #[nwg_layout_item(layout: grid, row: 0, col: 0)]
    name_edit: nwg::TextInput,

    #[nwg_control(text: "Say my name")]
    #[nwg_layout_item(layout: grid, col: 0, row: 1, row_span: 2)]
    #[nwg_events( OnButtonClick: [BasicApp::say_hello] )]
    hello_button: nwg::Button
}

impl BasicApp {

    fn say_hello(&self) {
        nwg::modal_info_message(&self.window, "Hello", &format!("Hello {}", self.name_edit.text()));
    }
    
    fn say_goodbye(&self) {
        nwg::modal_info_message(&self.window, "Goodbye", &format!("Goodbye {}", self.name_edit.text()));
        nwg::stop_thread_dispatch();
    }

}

fn main() {
    nwg::init().expect("Failed to init Native Windows GUI");
    nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
    let _app = BasicApp::build_ui(Default::default()).expect("Failed to build UI");
    nwg::dispatch_thread_events();
}
```

### Barebone example. Suitable if you only need a simple static UI


```rust
#![windows_subsystem = "windows"]

/**
    A very simple application that show your name in a message box.

    This demo shows how to use NWG without the NativeUi trait boilerplate.
    Note that this way of doing things is alot less extensible and cannot make use of native windows derive.

    See `basic` for the NativeUi version and `basic_d` for the derive version
*/
extern crate native_windows_gui as nwg;
use std::rc::Rc;

fn main() {
    nwg::init().expect("Failed to init Native Windows GUI");
    nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");

    let mut window = Default::default();
    let mut name_edit = Default::default();
    let mut hello_button = Default::default();
    let layout = Default::default();

    nwg::Window::builder()
        .size((300, 115))
        .position((300, 300))
        .title("Basic example")
        .build(&mut window)
        .unwrap();

    nwg::TextInput::builder()
        .text("Heisenberg")
        .focus(true)
        .parent(&window)
        .build(&mut name_edit)
        .unwrap();

    nwg::Button::builder()
        .text("Say my name")
        .parent(&window)
        .build(&mut hello_button)
        .unwrap();

    nwg::GridLayout::builder()
        .parent(&window)
        .spacing(1)
        .child(0, 0, &name_edit)
        .child_item(nwg::GridLayoutItem::new(&hello_button, 0, 1, 1, 2))
        .build(&layout)
        .unwrap();

    let window = Rc::new(window);
    let events_window = window.clone();

    let handler = nwg::full_bind_event_handler(&window.handle, move |evt, _evt_data, handle| {
        use nwg::Event as E;

        match evt {
            E::OnWindowClose => 
                if &handle == &events_window as &nwg::Window {
                    nwg::modal_info_message(&events_window.handle, "Goodbye", &format!("Goodbye {}", name_edit.text()));
                    nwg::stop_thread_dispatch();
                },
            E::OnButtonClick => 
                if &handle == &hello_button {
                    nwg::modal_info_message(&events_window.handle, "Hello", &format!("Hello {}", name_edit.text()));
                },
            _ => {}
        }
    });

    nwg::dispatch_thread_events();
    nwg::unbind_event_handler(&handler);
}
```

### With the NativeUi boilerplate


```rust
#![windows_subsystem = "windows"]

/*!
    A very simple application that shows your name in a message box.
    Uses layouts to position the controls in the window
*/

extern crate native_windows_gui as nwg;
use nwg::NativeUi;


#[derive(Default)]

pub struct BasicApp {
    window: nwg::Window,
    layout: nwg::GridLayout,
    name_edit: nwg::TextInput,
    hello_button: nwg::Button
}

impl BasicApp {

    fn say_hello(&self) {
        nwg::modal_info_message(&self.window, "Hello", &format!("Hello {}", self.name_edit.text()));
    }
    
    fn say_goodbye(&self) {
        nwg::modal_info_message(&self.window, "Goodbye", &format!("Goodbye {}", self.name_edit.text()));
        nwg::stop_thread_dispatch();
    }

}

//
// ALL of this stuff is handled by native-windows-derive
//
mod basic_app_ui {
    use native_windows_gui as nwg;
    use super::*;
    use std::rc::Rc;
    use std::cell::RefCell;
    use std::ops::Deref;

    pub struct BasicAppUi {
        inner: Rc<BasicApp>,
        default_handler: RefCell<Option<nwg::EventHandler>>
    }

    impl nwg::NativeUi<BasicAppUi> for BasicApp {
        fn build_ui(mut data: BasicApp) -> Result<BasicAppUi, nwg::NwgError> {
            use nwg::Event as E;
            
            // Controls
            nwg::Window::builder()
                .flags(nwg::WindowFlags::WINDOW | nwg::WindowFlags::VISIBLE)
                .size((300, 115))
                .position((300, 300))
                .title("Basic example")
                .build(&mut data.window)?;

            nwg::TextInput::builder()
                .text("Heisenberg")
                .parent(&data.window)
                .focus(true)
                .build(&mut data.name_edit)?;

            nwg::Button::builder()
                .text("Say my name")
                .parent(&data.window)
                .build(&mut data.hello_button)?;

            // Wrap-up
            let ui = BasicAppUi {
                inner: Rc::new(data),
                default_handler: Default::default(),
            };

            // Events
            let evt_ui = Rc::downgrade(&ui.inner);
            let handle_events = move |evt, _evt_data, handle| {
                if let Some(ui) = evt_ui.upgrade() {
                    match evt {
                        E::OnButtonClick => 
                            if &handle == &ui.hello_button {
                                BasicApp::say_hello(&ui);
                            },
                        E::OnWindowClose => 
                            if &handle == &ui.window {
                                BasicApp::say_goodbye(&ui);
                            },
                        _ => {}
                    }
                }
            };

           *ui.default_handler.borrow_mut() = Some(nwg::full_bind_event_handler(&ui.window.handle, handle_events));

           // Layouts
           nwg::GridLayout::builder()
            .parent(&ui.window)
            .spacing(1)
            .child(0, 0, &ui.name_edit)
            .child_item(nwg::GridLayoutItem::new(&ui.hello_button, 0, 1, 1, 2))
            .build(&ui.layout)?;

            return Ok(ui);
        }
    }

    impl Drop for BasicAppUi {
        /// To make sure that everything is freed without issues, the default handler must be unbound.
        fn drop(&mut self) {
            let handler = self.default_handler.borrow();
            if handler.is_some() {
                nwg::unbind_event_handler(handler.as_ref().unwrap());
            }
        }
    }

    impl Deref for BasicAppUi {
        type Target = BasicApp;

        fn deref(&self) -> &BasicApp {
            &self.inner
        }
    }
}

fn main() {
    nwg::init().expect("Failed to init Native Windows GUI");
    nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
    let _ui = BasicApp::build_ui(Default::default()).expect("Failed to build UI");
    nwg::dispatch_thread_events();
}
```

## Attributions


For the icons used in the test suite (and only there):

- **love.ico** is made by [Smashicons]https://smashicons.com/ from [www.flaticon.com]https://www.flaticon.com/
- **popcorn.bmp** is made by [Freepik]https://www.freepik.com from [www.flaticon.com]https://www.flaticon.com/
- **ball.bmp** is made by [Freepik]https://www.freepik.com from [www.flaticon.com]https://www.flaticon.com/
- **cat.jpg** is made by [Freepik]https://www.freepik.com from [www.flaticon.com]https://www.flaticon.com/
- **weird_cat.png** is made by [Freepik]https://www.freepik.com from [www.flaticon.com]https://www.flaticon.com/
- **list_0.png**, **list_1.png**, **list_2.png**, **list_3.png** are made by [Smashicons]https://smashicons.com/ from [www.flaticon.com]https://www.flaticon.com/
- **ice.cur** is made by nrox653 from [rw-designer]http://www.rw-designer.com/cursor-set/icepackpro