rsgt 0.3.0

Rust simple GUI Toolkit
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//========================================================================
// RSGT | rframe.rs - https://overtimecoder.github.io
//------------------------------------------------------------------------
// Window processing
//------------------------------------------------------------------------
//
// Author LatteS
//
// File was created in 2022/12/31
//
//========================================================================

//! # Window Handling

use std::iter;
use crate::theme::ComponentColor;
use wgpu::{Device, Queue, RenderPipeline, Surface, SurfaceConfiguration, TextureFormat};
use winit::dpi::PhysicalSize;
use winit::event::{Event, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::platform::windows::WindowExtWindows;
use winit::window::{CursorIcon, Icon, WindowBuilder};
use winit::window::Window;
use crate::{RSGTError, Size};
use crate::wgpu::WGSL;
use crate::widget::Widget;

pub type ID = i32;

pub enum CloseOperation {
    ExitAndClose,
    HideAndClose,
}

struct State {
    // WGPU
    pub color:wgpu::Color,
    pub surface: Surface,
    // pub surface_format: TextureFormat,
    pub device: Device,
    pub queue: Queue,
    pub pipeline: RenderPipeline,
    pub config: SurfaceConfiguration,
    pub size: PhysicalSize<u32>
}

impl State{
    pub fn resize(&mut self, new_size: PhysicalSize<u32>) {
        if new_size.width > 0 && new_size.height > 0 {
            self.size = new_size;
            self.config.width = new_size.width;
            self.config.height = new_size.height;
            self.surface.configure(&self.device, &self.config);
        }
    }

    pub fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
        let frame = self.surface.get_current_texture().unwrap();
        let view = frame
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());

        let encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });

        {
            let mut encoder = self
                .device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("Render Encoder"),
                });

            {
                let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("Render Pass"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: &view,
                        resolve_target: None,
                        ops: wgpu::Operations {
                            load: wgpu::LoadOp::Clear(self.color),
                            store: true,
                        },
                    })],
                    depth_stencil_attachment: None,
                });
                rpass.set_pipeline(&self.pipeline);
            }
            self.queue.submit(iter::once(encoder.finish()));
            //rpass.draw(0..3, 0..1);
        }

        let command_buffer = encoder.finish();

        self.queue.submit(Some(command_buffer));

        frame.present();

        Ok(())
    }
}

pub struct RFrame {
    id: ID,
    handle: Window,
    event_loop: Option<EventLoop<()>>,

    close_operation: CloseOperation,

    // Listener
    window_listener: Box<dyn crate::event::WindowListener>,

    state: State
}

impl RFrame {
    pub fn new(title: impl Into<String>, id: ID, window_size:Size<u32>) -> Result<Self,RSGTError> {
        // Checking Arguments
        if window_size.0 == 0 || window_size.1 == 0 {
            return Err(RSGTError::illegal_argument("Either of the window sizes is set to 0. Window size is set to 0."));
        }
        println!("Err");
        let event_loop = EventLoop::new();

        let window_size: PhysicalSize<u32> = window_size.into();

        let window = WindowBuilder::new()
            .with_fullscreen(None)
            .with_inner_size(window_size)
            .with_title(title)
            .with_visible(false)
            .build(&event_loop)
            .unwrap();

        let instance = wgpu::Instance::new(wgpu::Backends::all());
        dbg!(instance.generate_report());

        let surface = unsafe { instance.create_surface(&window) };

        let adapter_options = wgpu::RequestAdapterOptions {
            compatible_surface: Some(&surface),
            ..Default::default()
        };
        let adapter_future = instance.request_adapter(&adapter_options);
        let adapter = pollster::block_on(adapter_future).unwrap();
        println!("Selected adapter: {}", adapter.get_info().name);

        let device_descriptor = wgpu::DeviceDescriptor::default();
        let device_future = adapter.request_device(&device_descriptor, None);
        let (device, queue) = pollster::block_on(device_future).unwrap();

        let wgsl = WGSL::new();
        let shader_code = wgsl.build();

        let descriptor = wgpu::ShaderModuleDescriptor {
            label: None,
            source: wgpu::ShaderSource::Wgsl(shader_code.into()),
        };
        let shader_module = device.create_shader_module(descriptor);

        let surface_format = surface.get_supported_formats(&adapter)[0];

        let color_target = wgpu::ColorTargetState {
            format: surface_format,
            blend: None,
            write_mask: Default::default(),
        };

        let color_targets = [Some(color_target)];

        let descriptor = wgpu::RenderPipelineDescriptor {
            label: None,
            primitive: Default::default(),
            vertex: wgpu::VertexState {
                buffers: &[],
                module: &shader_module,
                entry_point: "vs_main",
            },
            fragment: Some(wgpu::FragmentState {
                targets: &color_targets,
                module: &shader_module,
                entry_point: "fs_main",
            }),
            layout: None,
            depth_stencil: None,
            multisample: Default::default(),
            multiview: None,
        };
        let pipeline = device.create_render_pipeline(&descriptor);

        let config = SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface_format,
            width: window_size.width,
            height: window_size.height,
            present_mode: wgpu::PresentMode::Immediate,
            alpha_mode: wgpu::CompositeAlphaMode::Auto,
        };
       surface.configure(&device, &config);
        
        let state = State {
            color: crate::wgpu::parse_color(ComponentColor::WhiteGray),
            surface,
            // surface_format,
            device,
            queue,
            pipeline,
            config,
            size: window_size,
        };

        Ok(Self {
            id,
            handle: window,
            event_loop: Some(event_loop),
            close_operation: CloseOperation::ExitAndClose,
            window_listener: Box::new(crate::event::DefaultWindowListener {}),
            state
        })
    }

    /// Add a window event listener
    pub fn add_window_listener(&mut self, listener: (impl crate::event::WindowListener + 'static)) {
        self.window_listener = Box::new(listener);
    }

    /// Show window
    pub fn show(&self) {
        self.handle.set_visible(true);
    }

    /// Hide window
    pub fn hide(&self) {
        self.handle.set_visible(false);
    }

    /// Maximize window
    pub fn set_maximized(&self) {
        self.handle.set_maximized(true);
    }

    /// Minimize window
    pub fn set_minimized(&self) {
        if self.handle.is_maximized() == false {
            self.handle.set_minimized(true);
        } else {
            self.handle.set_maximized(false);
        }
    }

    pub fn set_undecorated(&self) {
        self.handle.set_decorations(false);
    }

    pub fn set_decorated(&self) {
        self.handle.set_decorations(true);
    }

    pub fn set_enable(&self) {
        self.handle.set_enable(true);
    }

    pub fn set_disable(&self) {
        self.handle.set_enable(false);
    }

    /// Set window title
    pub fn set_title(&self, title: &str) {
        self.handle.set_title(title);
    }

    /// Set window size
    pub fn set_size(&mut self, width: u32, height: u32) {
        let window_size: PhysicalSize<u32> = (width, height).into();
        if width > 0 && height > 0 {
            self.state.size = window_size;
            self.state.config.width = window_size.width;
            self.state.config.height = window_size.height;
            self.state.surface.configure(&self.state.device, &self.state.config);
        }
        self.state.surface.configure(&self.state.device, &self.state.config);
    }

    pub fn set_location(&self, x: i32, y: i32) {
        self.handle
            .set_outer_position(winit::dpi::LogicalPosition::new(x, y));
    }

    pub fn set_maximum_window_size(&self,width:u32,height:u32) {
        self.handle.set_max_inner_size(Some(PhysicalSize::new(width,height)));
    }

    pub fn set_minimum_window_size(&self,width:u32,height:u32) {
        self.handle.set_min_inner_size(Some(PhysicalSize::new(width,height)));
    }

    pub fn set_resizable(&self) {
        self.handle.set_resizable(true);
    }

    pub fn set_non_resizable(&self) {
        self.handle.set_resizable(false);
    }

    /// Set window icon
    pub fn set_icon(&self, icon: winit::window::Icon) {
        self.handle.set_window_icon(Some(icon));
    }

    /// Set taskbar icon
    pub fn set_taskbar_icon(&self,icon: winit::window::Icon) {
        self.handle.set_taskbar_icon(Some(icon));
    }

    /// Set default close operation
    pub fn set_default_close_operation(&mut self, operation: CloseOperation) {
        self.close_operation = operation;
    }

    pub fn set_cursor_icon(&self,icon:crate::CursorIcon) {
        self.handle.set_cursor_icon(match icon {
            crate::CursorIcon::Arrow => {CursorIcon::Arrow}
            crate::CursorIcon::ScrollAll => {CursorIcon::AllScroll}
            crate::CursorIcon::CrossHair => {CursorIcon::Crosshair}
            crate::CursorIcon::Hand => {CursorIcon::Hand}
            crate::CursorIcon::Help => {CursorIcon::Help}
            crate::CursorIcon::NotAllowed => {CursorIcon::NotAllowed}
            crate::CursorIcon::Progress => {CursorIcon::Progress}
        });
    }

    // /// Set window theme
    // pub fn set_theme(&self, theme: WindowTheme) {
    //     self.handle.set_theme(match theme {
    //         WindowTheme::Auto => None,
    //         WindowTheme::Light => Some(Theme::Light),
    //         WindowTheme::Dark => Some(Theme::Dark),
    //     });
    // }

    pub fn set_background_color(&mut self,color: ComponentColor) {
        self.state.color = crate::wgpu::parse_color(color);
    }

    pub fn enable_ime(&self) {
        self.handle.set_ime_allowed(true);
    }

    pub fn disable_ime(&self) {
        self.handle.set_ime_allowed(false);
    }

    pub fn get_window_size(&self) -> (u32,u32) {
        (self.state.size.width,self.state.size.height)
    }

    pub fn is_resizable(&self) -> bool {
        self.handle.is_resizable()
    }

    pub fn is_decorated(&self) -> bool {
        self.handle.is_decorated()
    }

    pub fn is_maximized(&self) -> bool {
        self.handle.is_maximized()
    }

    /// Run and show window.
    pub fn run(mut self) {
        let event_loop = self.event_loop.take().unwrap();
        self.handle.set_visible(true);
        self.window_listener.window_opened(&self);
        event_loop.run(move |event, _, control_flow| {
            *control_flow = ControlFlow::Wait;

            match event {
                Event::RedrawRequested(window_id) if window_id == self.handle.id() => {
                    match self.state.render() {
                        Ok(_) => {}
                        Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => self.state.resize(self.state.size),
                        Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
                        Err(wgpu::SurfaceError::Timeout) => println!("Surface timeout"),
                    }
                }

                // On focused
                Event::WindowEvent {
                    event: WindowEvent::Focused(is_focused),
                    ..
                } => {
                    if is_focused == true {
                        self.window_listener
                            .window_focused(&self);
                    }
                }

                Event::WindowEvent {
                    event: WindowEvent::Moved(pos),
                    ..
                } => {
                    self.window_listener
                        .window_moved(pos,&self);
                }

                Event::WindowEvent {
                    event: WindowEvent::HoveredFile(pathbuf),
                    ..
                } => {
                    self.window_listener.window_hovered_file(pathbuf,&self);
                }

                Event::WindowEvent {
                    event: WindowEvent::HoveredFileCancelled,
                    ..
                } => {
                    self.window_listener.window_hovered_file_canceled(&self);
                }

                // Dropped file
                Event::WindowEvent {
                    event: WindowEvent::DroppedFile(pathbuf),
                    ..
                } => {
                    self.window_listener
                        .window_dropped_file(pathbuf, &self);
                }

                // Received character
                Event::WindowEvent {
                    event: WindowEvent::ReceivedCharacter(character),
                    ..
                } => {
                    self.window_listener
                        .window_received_character(character, &self);
                }

                // Window resized
                Event::WindowEvent {
                    event: WindowEvent::Resized(window_size),
                    ..
                } => {
                    self.state.resize(window_size);
                    self.window_listener
                        .window_resized(&self);
                }

                Event::WindowEvent {
                    event: WindowEvent::ScaleFactorChanged {
                        new_inner_size,
                        ..
                    },
                    ..
                } => {
                    self.set_size(new_inner_size.width,new_inner_size.height);
                }

                // Close requested.
                Event::WindowEvent {
                    event: WindowEvent::CloseRequested,
                    ..
                } => {
                    self.window_listener
                        .window_closed(&self);
                    match self.close_operation {
                        CloseOperation::ExitAndClose => {
                            *control_flow = ControlFlow::Exit;
                        }
                        CloseOperation::HideAndClose => {
                            *control_flow = ControlFlow::Wait;
                            self.hide();
                        }
                    }
                }

                _ => {}
            }
        });
    }

    // /// Specify which buttons to enable in the window buttons
    // pub fn set_enable_button(&self, button: WindowButton) {
    //     let buttons = self.handle.enabled_buttons();
    //     self.handle.set_enabled_buttons(
    //         buttons
    //             ^ match button {
    //                 WindowButton::Close => WindowButtons::CLOSE,
    //                 WindowButton::Maximize => WindowButtons::MAXIMIZE,
    //                 WindowButton::Minimize => WindowButtons::MINIMIZE,
    //             },
    //     );
    // }
}

pub struct RFrameBuilder {
    title: String,
    size: Size<u32>,
    visible: bool,
    icon: Option<Icon>,
    close_operation: CloseOperation
}

impl RFrameBuilder {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn with_title(mut self, title:impl Into<String>) -> Self {
        self.title = title.into();
        self
    }
    
    pub fn with_size(mut self,size:Size<u32>) -> Self {
        self.size = size;
        self
    }

    pub fn with_visible(mut self,visible:bool) -> Self {
        self.visible = visible;
        self
    }

    pub fn with_icon(mut self,icon:Icon) -> Self {
        self.icon = Some(icon);
        self
    }

    pub fn with_close_operation(mut self,operation: CloseOperation) -> Self {
        self.close_operation = operation;
        self
    }

    pub fn build(self) -> Result<RFrame,RSGTError> {
        let mut rf = match RFrame::new(self.title, 0, self.size) {
            Ok(rf) => {rf}
            Err(err) => return Err(err)
        };
        match self.icon {
            None => {}
            Some(icn) => {rf.set_icon(icn);}
        };
        rf.set_default_close_operation(self.close_operation);
        Ok(rf)
    }
}

impl Default for RFrameBuilder {
    fn default() -> Self {
        Self {
            title: "RSGT window".parse().unwrap(),
            size: Size(400,400),
            visible: false,
            icon: None,
            close_operation: CloseOperation::ExitAndClose
        }
    }
}

pub struct RegistrationContentPanel {
    components: Vec<Box<dyn Widget>>,
}

impl RegistrationContentPanel {
    pub fn new() -> Self {
        Self {
            components: vec![],
        }
    }

    pub fn add(&mut self, widget: (impl Widget + 'static)) {
        self.components.push(Box::new(widget));
    }

    pub fn draw_all(&self) {

    }

    pub fn draw_by_id(&self) {

    }
}