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
/*! High level window wrapper.

To create instance of Sciter you will need either to create new Sciter window or to attach (mix-in) Sciter engine to existing window.

Handle of the Sciter engine is defined as `HWINDOW` type which is:

* `HWND` handle on Microsoft Windows.
* `NSView*` – pointer to [`NSView`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/) instance that is a contentView of Sciter window on OS X.
* `GtkWidget*` – pointer to [`GtkWidget`](https://developer.gnome.org/gtk3/stable/GtkWidget.html) instance
that is a root widget of Sciter window on Linux/GTK.

## Creation of new window

```no_run
extern crate sciter;

fn main() {
	let mut frame = sciter::Window::new();
	frame.load_file("minimal.htm");
	frame.run_app();
}
```

Also you can register the [host](../host/trait.HostHandler.html) and [DOM](../dom/event/index.html) event handlers.

.
*/
use ::{_API};
use capi::sctypes::*;

use platform::{BaseWindow, OsWindow};
use host::{Host, HostHandler};
use dom::event::{EventHandler};

use std::rc::Rc;


/// `SCITER_CREATE_WINDOW_FLAGS` alias.
pub type Flags = SCITER_CREATE_WINDOW_FLAGS;

pub use capi::scdef::{SCITER_CREATE_WINDOW_FLAGS};


/// Per-window sciter engine options.
///
/// Used by [`Window::set_options()`](struct.Window.html#method.set_options).
///
/// See also [global options](../enum.RuntimeOptions.html).
#[derive(Copy, Clone)]
pub enum Options {
	/// Enable smooth scrolling, enabled by default.
	SmoothScroll(bool),

	/// Font rendering, value: `0` - system default, `1` - no smoothing, `2` - standard smoothing, `3` - ClearType.
	FontSmoothing(u8),

	/// Windows Aero support, value: `false` - normal drawing, `true` - window has transparent background after calls
	/// [`DwmExtendFrameIntoClientArea()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969512(v=vs.85).aspx)
	/// or [`DwmEnableBlurBehindWindow()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969508(v=vs.85).aspx).
	TransparentWindow(bool),

	/// Transparent windows support. When enabled, window uses per pixel alpha
  /// (e.g. [`WS_EX_LAYERED`](https://msdn.microsoft.com/en-us/library/ms997507.aspx?f=255&MSPPError=-2147217396) window).
	AlphaWindow(bool),

  /// global or per-window; enables Sciter Inspector for this window, must be called before loading HTML.
  DebugMode(bool),

  /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](../enum.SCRIPT_RUNTIME_FEATURES.html) flags.
	ScriptFeatures(u8),

	/// Window is main, will destroy all other dependent windows on close, since 4.3.0.12
	MainWindow(bool),
}


/// Sciter window.
pub struct Window
{
	base: OsWindow,
	host: Rc<Host>,
}

// `Window::new()` is rather expensive operation to make it default.
#[allow(clippy::new_without_default)]
impl Window {

	#[cfg(not(feature = "windowless"))]
	/// Create a new main window.
	pub fn new() -> Window {
		Builder::main_window().create()
	}

	/// Create a new window with the specified position, flags and an optional parent window.
	pub fn create(rect: RECT, flags: SCITER_CREATE_WINDOW_FLAGS, parent: Option<HWINDOW>) -> Window {
		if cfg!(feature = "windowless")
		{
			panic!("Sciter doesn't have windows in windowless mode!");
		}

		let mut base = OsWindow::new();
		let hwnd = base.create(rect, flags as UINT, parent.unwrap_or(0 as HWINDOW));
		assert!(!hwnd.is_null());

		let wnd = Window { base: base, host: Rc::new(Host::attach(hwnd))};
		return wnd;
	}

	/// Attach Sciter to an existing native window.
	pub fn attach(hwnd: HWINDOW) -> Window {
		// suppress warnings about unused method
		let _ = &OsWindow::new;

		assert!(!hwnd.is_null());
		Window { base: OsWindow::from(hwnd), host: Rc::new(Host::attach(hwnd)) }
	}

	/// Obtain reference to `Host` which allows you to control sciter engine and windows.
	pub fn get_host(&self) -> Rc<Host> {
		Rc::clone(&self.host)
	}

	/// Set callback for sciter engine events.
	pub fn sciter_handler<Callback: HostHandler + Sized>(&mut self, handler: Callback) {
		self.host.setup_callback(handler);
	}

	/// Attach `dom::EventHandler` to the Sciter window.
	///
	/// You can install Window EventHandler only once - it will survive all document reloads.
	pub fn event_handler<Handler: EventHandler>(&mut self, handler: Handler) {
		self.host.attach_handler(handler);
	}

  /// Register an archive produced by `packfolder`.
  ///
  /// See documentation of the [`Archive`](../host/struct.Archive.html).
  pub fn archive_handler(&mut self, resource: &[u8]) -> Result<(), ()> {
    self.host.register_archive(resource)
  }

	/// Register a native event handler for the specified behavior name.
	///
	/// Behavior is a named event handler which is created for a particular DOM element.
	/// In Sciter’s sense, it is a function that is called for different UI events on the DOM element.
	/// Essentially it is an analog of the [WindowProc](https://en.wikipedia.org/wiki/WindowProc) in Windows.
	///
	/// In HTML, there is a `behavior` CSS property that defines name of a native module
	/// that is responsible for initialization and event handling on the element.
	/// For example, by defining `div {behavior:button}` you are asking all `<div>` elements in your markup
	/// to behave as buttons: generate [`BUTTON_CLICK`](../dom/event/enum.BEHAVIOR_EVENTS.html#variant.BUTTON_CLICK)
	/// DOM events when clicks on that element and be focusable.
	///
	/// When the engine discovers element having `behavior: xyz;` defined in its style,
	/// it sends the [`SC_ATTACH_BEHAVIOR`](../host/trait.HostHandler.html#method.on_attach_behavior) host notification
	/// with the name `"xyz"` and element handle to the application.
	/// You can consume the notification and respond to it yourself,
	/// or the default handler walks through the list of registered behavior factories
	/// and creates the instance of the corresponding [`dom::EventHandler`](../dom/event/trait.EventHandler.html).
	///
	/// ## Example:
	///
	/// ```rust,no_run
	/// struct Button;
	///
	/// impl sciter::EventHandler for Button {}
	///
	/// let mut frame = sciter::Window::new();
	/// frame.register_behavior("custom-button", || { Box::new(Button) });
	/// ```
	///
	/// And in HTML it can be used as:
	///
	/// ```html
	/// <button style="behavior: custom-button">Rusty button</button>
	/// ```
	pub fn register_behavior<Factory>(&mut self, name: &str, factory: Factory)
	where
		Factory: Fn() -> Box<dyn EventHandler> + 'static
	{
		self.host.register_behavior(name, factory);
	}

	/// Load an HTML document from file.
	///
	/// The specified `uri` should be either an absolute file path,
	/// or a full URL to the HTML to load.
	///
	/// Supported URL schemes are: `http://`, `file://`, `this://app/` (when used with [`archive_handler`](#archive_handler)).
	pub fn load_file(&mut self, uri: &str) {
		self.host.load_file(uri)
	}

	/// Load an HTML document from memory.
	pub fn load_html(&mut self, html: &[u8], uri: Option<&str>) {
		self.host.load_html(html, uri)
	}

	/// Get native window handle.
	pub fn get_hwnd(&self) -> HWINDOW {
		self.base.get_hwnd()
	}

	/// Minimize or hide window.
	pub fn collapse(&self, hide: bool) {
		self.base.collapse(hide)
	}

	/// Show or maximize window.
	pub fn expand(&self, maximize: bool) {
		self.base.expand(maximize)
	}

	/// Close window.
	pub fn dismiss(&self) {
		self.base.dismiss()
	}

	/// Set title of native window.
	pub fn set_title(&mut self, title: &str) {
		self.base.set_title(title)
	}

	/// Get native window title.
	pub fn get_title(&self) -> String {
		self.base.get_title()
	}

	/// Set various sciter engine options, see the [`Options`](enum.Options.html).
	pub fn set_options(&self, options: Options) -> Result<(), ()> {
		use capi::scdef::SCITER_RT_OPTIONS::*;
		use self::Options::*;
		let (option, value) = match options {
			SmoothScroll(enable) => (SCITER_SMOOTH_SCROLL, enable as usize),
			FontSmoothing(technology) => (SCITER_FONT_SMOOTHING, technology as usize),
			TransparentWindow(enable) => (SCITER_TRANSPARENT_WINDOW, enable as usize),
			AlphaWindow(enable) => (SCITER_ALPHA_WINDOW, enable as usize),
			MainWindow(enable) => (SCITER_SET_MAIN_WINDOW, enable as usize),
      DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize),
			ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize),
		};
		let ok = (_API.SciterSetOption)(self.get_hwnd(), option, value);
		if ok != 0 {
			Ok(())
		} else {
			Err(())
		}
	}

	/// Show window and run the main app message loop until window been closed.
	pub fn run_app(self) {
		self.base.expand(false);
		self.base.run_app();
	}

	/// Run the main app message loop with already configured window.
	pub fn run_loop(&self) {
		self.base.run_app();
	}

	/// Post app quit message.
	pub fn quit_app(&self) {
		self.base.quit_app()
	}
}


/// Generic rectangle struct.
/// NOTE that this is different from RECT type as it specifies width and height.
#[derive(Clone, Copy)]
pub struct Rectangle {
	pub x: i32,
	pub y: i32,
	pub width: i32,
	pub height: i32
}


/// Builder pattern for window creation.
///
/// For example,
///
/// ```rust,no_run
/// let mut frame = sciter::window::Builder::main_window()
///   .with_size((800,600))
///   .resizeable()
///   .glassy()
///   .create();
/// ```
#[derive(Default)]
pub struct Builder {
	flags: Flags,
	rect: RECT,
	parent: Option<HWINDOW>,
}

// Note: https://rust-lang-nursery.github.io/api-guidelines/type-safety.html#non-consuming-builders-preferred
impl Builder {

	/// Main application window (resizeable with min/max buttons and title).
	/// Will terminate the app on close.
	pub fn main_window() -> Self {
		Builder::main()
			.resizeable()
			.closeable()
			.with_title()
	}

	/// Popup window (with min/max buttons and title).
	pub fn popup_window() -> Self {
		Builder::popup()
			.closeable()
			.with_title()
	}

	/// Child window style. if this flag is set all other flags are ignored.
	pub fn child_window() -> Self {
		Builder::with_flags(SCITER_CREATE_WINDOW_FLAGS::SW_CHILD)
	}

	/// If you want to start from scratch.
	pub fn none() -> Self {
		Builder::with_flags(SCITER_CREATE_WINDOW_FLAGS::SW_CHILD)	// 0
	}

	/// Start with some flags.
	pub fn with_flags(flags: Flags) -> Self {
		let mut me = Builder::default();
		me.flags = flags;
		me
	}

	/// Main window style (appears in taskbar).
	/// Will terminate the app on close.
	pub fn main() -> Self {
		Builder::with_flags(SCITER_CREATE_WINDOW_FLAGS::SW_MAIN)
	}

	/// Popup style, window is created as topmost.
	pub fn popup() -> Self {
		Builder::with_flags(SCITER_CREATE_WINDOW_FLAGS::SW_POPUP)
	}

	/// Tool window style (with thin titlebar).
	pub fn tool() -> Self {
		Builder::with_flags(SCITER_CREATE_WINDOW_FLAGS::SW_TOOL)
	}

	/// Specify the parent window (e.g. for child creation).
	pub fn with_parent(mut self, parent: HWINDOW) -> Self {
		self.parent = Some(parent);
		self
	}

	/// Specify the precise window size in `(width, height)` form.
	pub fn with_size(mut self, size: (i32, i32)) -> Self {
		self.rect.right = self.rect.left + size.0;
		self.rect.bottom = self.rect.top + size.1;
		self
	}

	/// Specify the precise window position in `(X, Y)` form.
	pub fn with_pos(mut self, position: (i32, i32)) -> Self {
		let size = self.rect.size();
		self.rect.left = position.0;
		self.rect.top = position.1;
		self.rect.right = position.0 + size.cx;
		self.rect.bottom = position.1 + size.cy;
		self
	}

	/// Specify the exact window rectangle in `(X, Y, W, H)` form.
	pub fn with_rect(mut self, rect: Rectangle) -> Self {
		self.rect = RECT {
			left: rect.x,
			top: rect.y,
			right: rect.x + rect.width,
			bottom: rect.y + rect.height,
		};
		self
	}

	/// Top level window, has titlebar.
	pub fn with_title(self) -> Self {
		self.or(SCITER_CREATE_WINDOW_FLAGS::SW_TITLEBAR)
	}

	/// Can be resized.
	pub fn resizeable(self) -> Self {
		self.or(SCITER_CREATE_WINDOW_FLAGS::SW_RESIZEABLE)
	}

	/// Can not be resized.
	pub fn fixed(self) -> Self {
		self.and(SCITER_CREATE_WINDOW_FLAGS::SW_RESIZEABLE)
	}

	/// Has minimize / maximize buttons.
	pub fn closeable(self) -> Self {
		self.or(SCITER_CREATE_WINDOW_FLAGS::SW_CONTROLS)
	}

	/// Glassy window ("Acrylic" on Windows and "Vibrant" on macOS).
	pub fn glassy(self) -> Self {
		self.or(SCITER_CREATE_WINDOW_FLAGS::SW_GLASSY)
	}

	/// Transparent window.
	pub fn alpha(self) -> Self {
		self.or(SCITER_CREATE_WINDOW_FLAGS::SW_ALPHA)
	}

	/// Can be debugged with Inspector.
	pub fn debug(self) -> Self {
		self.or(SCITER_CREATE_WINDOW_FLAGS::SW_ENABLE_DEBUG)
	}

	fn or(mut self, flag: Flags) -> Self {
		self.flags = self.flags | flag;
		self
	}

	fn and(mut self, flag: Flags) -> Self {
		let masked = self.flags as u32 & !(flag as u32);
		self.flags = unsafe { ::std::mem::transmute(masked) };
		self
	}

	#[cfg(not(feature = "windowless"))]
	/// Consume the builder and call [`Window::create()`](struct.Window.html#method.create) with built parameters.
	pub fn create(self) -> Window {
		Window::create(self.rect, self.flags, self.parent)
	}
}