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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Documentation for this crate is work in progress.
//!
//! For now, please see the C API documentation at <https://developer.rebble.io/developer.pebble.com/docs/c/index.html> for more information.

#![no_std]
#![doc(html_root_url = "https://docs.rs/pebble-sys/0.0.1")]
#![feature(extern_types)]
#![warn(clippy::pedantic)]
#![allow(clippy::match_bool)]
// Matching the SDK documentation.
#![allow(clippy::module_name_repetitions)]

use core::panic::PanicInfo;
use foundation::logging::app_log;
use standard_c::memory::c_str;

pub mod prelude {
	pub use super::standard_c::prelude::*;
}

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
	unsafe {
		let panic = &*("### PANIC ###\0" as *const str as *const _ as *const c_str);
		let todo = &*("TODO: Output trace somehow.\0" as *const str as *const _ as *const c_str);
		app_log(1, panic, -1, todo);
	}
	loop {}
}

extern "C" {
	/// Marker type for unsized newtypes.
	type ExternData;
}

pub mod foundation {
	pub mod app {
		extern "C" {
			pub fn app_event_loop();
		}
	}

	pub mod logging {
		use crate::standard_c::memory::{c_str, int};

		//TODO: Enum AppLogLevel

		extern "C" {
			pub fn app_log(
				log_level: u8,
				src_filename: &c_str,
				src_line_number: int,
				fmt: &c_str,
				...
			);
		}
	}

	pub mod resources {
		use crate::standard_c::memory::void;

		#[derive(Copy, Clone)]
		#[repr(transparent)]
		pub struct ResHandle(*const void);

		extern "C" {
			pub fn resource_get_handle(resource_id: u32) -> ResHandle;
			pub fn resource_size(h: ResHandle) -> usize;
			pub fn resource_load(h: ResHandle, buffer: *mut u8, max_length: usize) -> usize;
			pub fn resource_load_byte_range(
				h: ResHandle,
				start_offset: u32,
				buffer: *mut u8,
				num_bytes: usize,
			) -> usize;
		}
	}
}

pub mod graphics {
	pub mod graphics_types {
		#[repr(C)]
		pub struct GPoint {
			pub x: i16,
			pub y: i16,
		}

		#[repr(C)]
		pub struct GRect {
			pub origin: GPoint,
			pub size: GSize,
		}

		#[repr(C)]
		pub struct GSize {
			pub w: i16,
			pub h: i16,
		}

		#[repr(C)]
		pub union GColor8 {
			pub argb: u8,
		}

		pub type GColor = GColor8;

		extern "C" {
			pub type GBitmap;
			pub type GBitmapSequence;
			pub type GContext;
		}

		pub mod color_definitions {
			use super::GColor8;

			macro_rules! colors {
				($name:ident = $value:literal $(, $further_name:ident = $further_value:literal)*$(,)?) => {
					pub const $name: GColor8 = GColor8 {
						argb: $value,
					};
					$(colors!($further_name = $further_value);)*
				};
			}

			colors! {
				BLUE_MOON = 0b_11_00_01_11,
				MELON = 0b_11_11_10_10,
				YELLOW = 0b_11_11_11_00,
			}
		}
	}
}

pub mod user_interface {
	pub mod clicks {
		use crate::standard_c::memory::void;

		#[repr(C)] //TODO
		pub enum ButtonId {
			_A, //TODO
		}

		#[repr(transparent)]
		pub struct ClickRecognizerRef(*mut void);
		pub type ClickHandler = extern "C" fn(recognizer: ClickRecognizerRef, context: *mut void);
		pub type ClickConfigProvider = extern "C" fn(context: *mut void);
	}

	pub mod layers {
		use super::window::Window;
		use crate::{
			graphics::graphics_types::{GContext, GPoint, GRect},
			standard_c::memory::void,
		};
		use core::ptr::NonNull;

		pub type LayerUpdateProc = extern "C" fn(layer: NonNull<Layer>, NonNull<GContext>);

		extern "C" {
			pub type Layer;

			pub fn layer_create(frame: GRect) -> *mut Layer;
			pub fn layer_create_with_data(frame: GRect, data_size: usize) -> *mut Layer;
			pub fn layer_destroy(layer: &'static mut Layer);
			pub fn layer_mark_dirty(layer: NonNull<Layer>);
			pub fn layer_set_update_proc(
				layer: NonNull<Layer>,
				update_proc: Option<LayerUpdateProc>, //TODO: Check if this is legal!
			);
			pub fn layer_set_frame(layer: NonNull<Layer>, frame: GRect);
			pub fn layer_get_frame(layer: NonNull<Layer>) -> GRect;
			pub fn layer_set_bounds(layer: NonNull<Layer>, bounds: GRect);
			pub fn layer_get_bounds(layer: NonNull<Layer>) -> GRect;
			pub fn layer_convert_point_to_screen(layer: NonNull<Layer>, point: GPoint) -> GPoint;
			pub fn layer_convert_rect_to_screen(layer: NonNull<Layer>, rect: GRect) -> GRect;
			pub fn layer_get_window(layer: NonNull<Layer>) -> *mut Window;
			pub fn layer_remove_from_parent(child: NonNull<Layer>);
			pub fn layer_remove_child_layers(parent: NonNull<Layer>);
			pub fn layer_add_child(parent: NonNull<Layer>, child: NonNull<Layer>);
			pub fn layer_insert_below_sibling(
				layer_to_insert: NonNull<Layer>,
				below_sibling_layer: NonNull<Layer>,
			);
			pub fn layer_insert_above_sibling(
				layer_to_insert: NonNull<Layer>,
				above_sibling_layer: NonNull<Layer>,
			);
			pub fn layer_set_hidden(layer: NonNull<Layer>, hidden: bool);
			pub fn layer_get_hidden(layer: NonNull<Layer>) -> bool;
			pub fn layer_set_clips(layer: NonNull<Layer>, clips: bool);
			pub fn layer_get_clips(layer: NonNull<Layer>) -> bool;
			pub fn layer_get_data(layer: NonNull<Layer>) -> NonNull<void>;

		//TODO: #define GRect layer_get_unobstructed_bounds(const Layer* layer);
		}
	}

	pub mod vibes {
		use core::marker::PhantomData;

		#[repr(C)]
		pub struct VibePattern<'a> {
			/// Pointer to an array of segment durations in on(off on)*off? order, up to 10_000ms each.
			/// There must be at least one duration!
			pub durations: *const u32,
			/// Length of the array.
			pub num_segments: u32,
			pub phantom: PhantomData<&'a u32>,
		}

		extern "C" {
			pub fn vibes_cancel();
			pub fn vibes_short_pulse();
			pub fn vibes_long_pulse();
			pub fn vibes_double_pulse();
			pub fn vibes_enqueue_custom_pattern(pattern: VibePattern);
		}
	}

	pub mod window {
		use super::{
			clicks::{ButtonId, ClickConfigProvider, ClickHandler},
			layers::Layer,
		};
		use crate::{graphics::graphics_types::GColor8, standard_c::memory::void};
		use core::ptr::NonNull;

		#[repr(C)]
		pub struct WindowHandlers {
			pub load: Option<WindowHandler>,
			pub appear: Option<WindowHandler>,
			pub disappear: Option<WindowHandler>,
			pub unload: Option<WindowHandler>,
		}

		pub type WindowHandler = extern "C" fn(window: &mut Window);

		extern "C" {
			pub type Window;

			pub fn window_create() -> Option<&'static mut Window>;
			pub fn window_destroy(window: &'static mut Window);
			pub fn window_set_click_config_provider(
				window: &mut Window,
				click_config_provider: Option<ClickConfigProvider>,
			);
			pub fn window_set_click_config_provider_with_context(
				window: &mut Window,
				click_config_provider: Option<ClickConfigProvider>,
				context: *mut void,
			);
			pub fn window_get_click_config_provider(window: &Window)
				-> Option<ClickConfigProvider>;
			pub fn window_get_click_config_context(window: &Window) -> *mut void;
			pub fn window_set_window_handlers(window: &mut Window, handlers: WindowHandlers);

			// The watch is single-threaded and everything's on the heap, so this *should* be fine.
			pub fn window_get_root_layer(window: &Window) -> &mut Layer;

			pub fn window_set_background_color(window: &mut Window, background_color: GColor8);
			pub fn window_is_loaded(window: &mut Window) -> bool;
			pub fn window_set_user_data(window: &mut Window, data: *mut void);
			pub fn window_get_user_data(window: &Window) -> *mut void;
			pub fn window_single_click_subscribe(button_id: ButtonId, handler: ClickHandler);
			pub fn window_single_repeating_click_subscribe(
				button_id: ButtonId,
				repeat_interval_ms: u16,
				handler: ClickHandler,
			);
			pub fn window_multi_click_subscribe(
				button_id: ButtonId,
				min_clicks: u8,
				max_clicks: u8,
				timeout: u16,
				last_click_only: bool,
				handler: ClickHandler,
			);
			pub fn window_long_click_subscribe(
				button_id: ButtonId,
				delay_ms: u16,
				down_handler: ClickHandler,
				up_handler: ClickHandler,
			);
			pub fn window_raw_click_subscribe(
				button_id: ButtonId,
				down_handler: ClickHandler,
				up_handler: ClickHandler,
				context: Option<NonNull<void>>,
			);
			pub fn window_set_click_context(button_id: ButtonId, context: *mut void);
		}

		pub mod number_window {
			//! A ready-made window prompting the user to pick a number.
			//!
			//! TODO: Images

			use super::Window;
			use crate::{
				standard_c::memory::{c_str, void},
				ExternData,
			};
			use core::{
				marker::PhantomData,
				ops::{Deref, DerefMut},
			};

			/// [`NumberWindow`] callbacks.
			#[repr(C)]
			pub struct NumberWindowCallbacks {
				/// Called as the value is incremented.
				pub incremented: Option<NumberWindowCallback>,
				/// Called as the value is decremented.
				pub decremented: Option<NumberWindowCallback>,
				/// Called as the value is confirmed, i.e. as the SELECT button is clicked.
				pub selected: Option<NumberWindowCallback>,
			}

			/// A [`NumberWindow`] callback.
			pub type NumberWindowCallback =
				for<'a> extern "C" fn(number_window: &'a mut NumberWindow<'a>, context: &mut void);

			/// Limited-lifetime foreign type. See [module](./index.html) documentation.  
			/// [`Deref`] and [`DerefMut`] towards [`Window`] (but destroying it as such might leak memory).
			///
			/// [`Deref`]: https://doc.rust-lang.org/stable/core/ops/trait.Deref.html
			/// [`DerefMut`]: https://doc.rust-lang.org/stable/core/ops/trait.DerefMut.html
			/// [`Window`]: ../foreigntype.Window.html
			#[repr(transparent)]
			pub struct NumberWindow<'a>(PhantomData<&'a ()>, ExternData);

			extern "C" {
				pub fn number_window_create<'a>(
					label: &'a c_str,
					callbacks: NumberWindowCallbacks,
					callback_context: &'static mut void,
				) -> Option<&'a mut NumberWindow<'a>>;

				pub fn number_window_destroy(number_window: &'static mut NumberWindow);
				pub fn number_window_set_label<'a>(
					number_window: &mut NumberWindow<'a>,
					label: &'a c_str,
				);
				pub fn number_window_set_max(number_window: &mut NumberWindow, max: i32);
				pub fn number_window_set_min(number_window: &mut NumberWindow, min: i32);
				pub fn number_window_set_value(number_window: &mut NumberWindow, value: i32);
				pub fn number_window_set_step_size(number_window: &mut NumberWindow, step: i32);
				pub fn number_window_get_value(number_window: &NumberWindow) -> i32;
				pub fn number_window_get_window<'a>(
					number_window: &'a NumberWindow<'a>,
				) -> &'a Window;
				#[allow(clashing_extern_declarations)]
				#[link_name = "number_window_get_window"]
				pub fn number_window_get_window_mut<'a>(
					number_window: &'a mut NumberWindow<'a>,
				) -> &'a mut Window;
			}

			impl<'a> Deref for NumberWindow<'a> {
				type Target = Window;

				fn deref(&self) -> &Self::Target {
					unsafe { &*(self as *const _ as *const Self::Target) }
				}
			}

			impl<'a> DerefMut for NumberWindow<'a> {
				fn deref_mut(&mut self) -> &mut Self::Target {
					unsafe { &mut *(self as *mut _ as *mut Self::Target) }
				}
			}
		}
	}

	pub mod window_stack {
		use super::window::Window;
		use core::ptr::NonNull;

		extern "C" {
			pub fn window_stack_push(window: &'static mut Window, animated: bool);
			pub fn window_stack_pop(animated: bool) -> Option<NonNull<Window>>;
			pub fn window_stack_pop_all(animated: bool);
			pub fn window_stack_remove(window: &mut Window, animated: bool) -> bool;
			pub fn window_stack_get_top_window() -> Option<NonNull<Window>>;
			pub fn window_stack_contains_window(window: &mut Window) -> bool;
		}
	}
}

pub mod standard_c {
	pub mod prelude {
		pub use super::memory::prelude::*;
	}

	pub mod memory {
		#![allow(non_camel_case_types)]

		use core::convert::TryFrom;

		pub mod prelude {
			pub use super::{
				CastUncheckedExt, CastUncheckedMutExt, OptionCastUncheckedMutExt, UpcastExt,
				UpcastMutExt,
			};
		}

		pub type int = i32;

		extern "C" {
			pub type c_str;

			/// `void` can be safely passed back across the FFI as `&void` while [`core::ffi::c_void`] cannot.
			/// ([`c_void`] is NOT [unsized]!)
			///
			/// [`core::ffi::c_void`]: https://doc.rust-lang.org/stable/core/ffi/enum.c_void.html
			/// [`c_void`]: https://doc.rust-lang.org/stable/core/ffi/enum.c_void.html
			/// [unsized]: https://doc.rust-lang.org/stable/core/marker/trait.Sized.html
			pub type void;

			pub fn malloc(size: usize) -> Option<&'static mut void>;
			pub fn calloc(count: usize, size: usize) -> Option<&'static mut void>;
			pub fn realloc(ptr: *mut void, size: usize) -> Option<&'static mut void>;
			pub fn free(ptr: &'static mut void);
			pub fn memcmp(ptr1: &void, ptr2: &void, n: usize) -> int;
			pub fn memcpy(dest: &mut void, src: &void, n: usize) -> *mut void;
			pub fn memmove(dest: *mut void, src: *const void, n: usize) -> *mut void;
			pub fn memset(dest: &mut void, c: int, n: usize) -> *mut void;
		}

		impl<'a, T> From<&'a mut T> for &'a mut void {
			fn from(src: &'a mut T) -> Self {
				unsafe { &mut *(src as *mut _ as *mut void) }
			}
		}

		impl<'a, T> From<&'a T> for &'a void {
			fn from(src: &'a T) -> Self {
				unsafe { &*(src as *const _ as *const void) }
			}
		}

		pub trait CastUncheckedExt<'a> {
			/// Casts a mutable untyped heap reference ([`&void]) into a typed one.
			///
			/// # Safety
			///
			/// Horribly unsafe if T doesn't point to an **initialised** instance of T.
			unsafe fn cast_unchecked<T>(self) -> &'a T;
		}

		pub trait CastUncheckedMutExt<'a> {
			/// Casts a mutable untyped heap reference ([`&mut void]) into a typed one.
			///
			/// # Safety
			///
			/// Horribly unsafe if T doesn't point to an **initialised** instance of T.
			unsafe fn cast_unchecked_mut<T>(self) -> &'a mut T;
		}

		pub trait OptionCastUncheckedMutExt<'a> {
			/// Casts a mutable untyped heap reference ([`&mut void]) into a typed one.
			///
			/// # Safety
			///
			/// Horribly unsafe if T doesn't point to an **initialised** instance of T.
			unsafe fn cast_unchecked_mut<T>(self) -> Option<&'a mut T>;
		}

		pub trait UpcastExt<'a> {
			type Output;

			fn upcast(self) -> Self::Output;
		}

		pub trait UpcastMutExt<'a> {
			type Output;

			fn upcast_mut(self) -> Self::Output;
		}

		impl<'a> CastUncheckedExt<'a> for &'a void {
			unsafe fn cast_unchecked<T>(self) -> &'a T {
				&*(self as *const _ as *const T)
			}
		}

		impl<'a> CastUncheckedMutExt<'a> for &'a mut void {
			unsafe fn cast_unchecked_mut<T>(self) -> &'a mut T {
				&mut *(self as *mut _ as *mut T)
			}
		}

		impl<'a> OptionCastUncheckedMutExt<'a> for Option<&'a mut void> {
			unsafe fn cast_unchecked_mut<T>(self) -> Option<&'a mut T> {
				self.map(|void_ref| &mut *(void_ref as *mut _ as *mut T))
			}
		}

		impl<'a, T> UpcastMutExt<'a> for Option<&'a mut T> {
			type Output = Option<&'a mut void>;

			fn upcast_mut(self) -> Self::Output {
				self.map(|t_ref| t_ref.into())
			}
		}

		impl<'a, T> UpcastExt<'a> for &'a T {
			type Output = &'a void;

			fn upcast(self) -> Self::Output {
				self.into()
			}
		}

		impl<'a, T> UpcastMutExt<'a> for &'a mut T {
			type Output = &'a mut void;

			fn upcast_mut(self) -> Self::Output {
				self.into()
			}
		}

		impl c_str {
			/// Interprets a zero-terminated Rust [`str`] as [`c_str`].
			///
			/// # Errors
			///
			/// Iff `text` does not end with `'\0'`.
			pub fn ref_from_str(text: &str) -> Result<&Self, ()> {
				match text.ends_with('\0') {
					true => Ok(unsafe { &*(text as *const _ as *const c_str) }),
					false => Err(()),
				}
			}
		}

		impl<'a> TryFrom<&'a str> for &'a c_str {
			type Error = ();

			fn try_from(value: &'a str) -> Result<Self, Self::Error> {
				match value.ends_with('\0') {
					true => Ok(unsafe { &*(value as *const _ as *const c_str) }),
					false => Err(()),
				}
			}
		}
	}
}