-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.rs
More file actions
1889 lines (1696 loc) · 67.4 KB
/
Copy pathapp.rs
File metadata and controls
1889 lines (1696 loc) · 67.4 KB
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::db::{
Circuit, Clock, DB, Gate, GateKind, InstanceId, InstanceKind, Label, LabelId, Lamp,
ModuleDefId, Pin, Power, Wire,
};
use std::collections::HashSet;
use std::fmt::Write as _;
use egui::{
Align, Button, Color32, CornerRadius, Image, Layout, Pos2, Rect, Response, Sense, Stroke,
StrokeKind, Ui, Vec2, Widget as _, pos2, vec2,
};
use crate::assets::PinKind;
use crate::drag::CanvasDrag;
use crate::simulator::{SimulationStatus, Simulator, Value, lamp_input, wire_start};
use crate::{
assets::{self},
config::CanvasConfig,
connection_manager::{Connection, ConnectionManager},
drag::Drag,
};
pub const PANEL_BUTTON_MAX_HEIGHT: f32 = 50.0;
pub const LABEL_EDIT_TEXT_SIZE: f32 = 16.0;
pub const LABEL_DISPLAY_TEXT_SIZE: f32 = 19.0;
// Grid
pub const GRID_SIZE: f32 = 20.0;
pub const COLOR_GRID_LIGHT: Color32 = Color32::from_rgb(230, 230, 230);
pub const COLOR_GRID_DARK: Color32 = Color32::from_rgb(40, 40, 40);
pub const COLOR_PIN_DETACH_HINT: Color32 = Color32::RED;
pub const COLOR_PIN_POWERED_OUTLINE: Color32 = Color32::GREEN;
pub const COLOR_WIRE_POWERED: Color32 = Color32::GREEN;
pub const COLOR_WIRE_IDLE: Color32 = Color32::LIGHT_BLUE;
// Hover
pub const COLOR_WIRE_HOVER: Color32 = Color32::GRAY;
pub const COLOR_HOVER_INSTANCE_OUTLINE: Color32 = Color32::GRAY;
pub const COLOR_HOVER_PIN_TO_WIRE: Color32 = Color32::GRAY;
pub const COLOR_HOVER_PIN_DETACH: Color32 = Color32::RED;
pub const PIN_HOVER_THRESHOLD: f32 = 10.0;
pub const INSTANEC_OUTLINE_EXPAND: f32 = 6.0;
pub const INSTANEC_OUTLINE: Vec2 = vec2(6.0, 6.0);
pub const INSTANEC_OUTLINE_THICKNESS: f32 = 2.0;
pub const NEW_PIN_ON_WIRE_THRESHOLD: f32 = 10.0;
// Connections
pub const COLOR_POTENTIAL_CONN_HIGHLIGHT: Color32 = Color32::LIGHT_BLUE;
pub const WIRE_HIT_DISTANCE: f32 = 8.0;
pub const SNAP_THRESHOLD: f32 = 10.0;
pub const PIN_MOVE_HINT_D: f32 = 10.0;
pub const PIN_MOVE_HINT_COLOR: Color32 = Color32::GRAY;
pub const COLOR_SELECTION_HIGHLIGHT: Color32 = Color32::GRAY;
pub const COLOR_SELECTION_BOX: Color32 = Color32::LIGHT_BLUE;
pub const MIN_WIRE_SIZE: f32 = 40.0;
#[derive(serde::Deserialize, serde::Serialize, Eq, PartialEq, Hash, Copy, Debug, Clone)]
pub enum Hover {
Pin(Pin),
Instance(InstanceId),
}
impl Hover {
pub fn instance(&self) -> InstanceId {
match self {
Self::Pin(pin) => pin.ins,
Self::Instance(instance_id) => *instance_id,
}
}
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
pub enum ClipBoardItem {
Gate(GateKind, Vec2),
Power(Vec2),
Wire(Vec2, Vec2),
Lamp(Vec2),
Clock(Vec2),
// Index to definition
Module(ModuleDefId, Vec2),
Label(String, Vec2),
}
pub fn current_dirty() -> bool {
true
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClockState {
Stopped,
Running,
}
#[derive(Debug, Clone)]
pub struct ClockController {
pub voltage: bool,
pub state: ClockState,
pub tick_accumulator: f32,
pub tick_interval: f32, // seconds between ticks
}
impl Default for ClockController {
fn default() -> Self {
Self {
voltage: false,
state: ClockState::Running,
tick_accumulator: 0.0,
tick_interval: 0.5, // 0.5 seconds = 2 Hz
}
}
}
#[derive(Debug, Clone)]
pub struct ViewModule {
pub module_id: InstanceId,
pub viewport_offset: Vec2,
}
#[derive(serde::Deserialize, serde::Serialize)]
pub struct App {
pub canvas_config: CanvasConfig,
pub drag: Option<Drag>,
pub hovered: Option<Hover>,
pub db: DB,
// connection manager for handling spatial indexing and validation
#[serde(skip)]
pub connection_manager: ConnectionManager,
// possible connections while dragging
pub potential_connections: HashSet<Connection>,
// mark when current needs recomputation
#[serde(skip, default = "current_dirty")]
pub current_dirty: bool,
pub show_debug: bool,
// selection set and move preview
// TODO: Selection is not handling labels.
pub selected: HashSet<InstanceId>,
//Copied. Items with their offset compared to a middle point in the rectangle
pub clipboard: Vec<ClipBoardItem>,
// Where are we in the world
pub viewport_offset: Vec2,
// For web load functionality - stores pending JSON to load
#[serde(skip)]
pub pending_load_json: Option<String>,
#[serde(skip)]
pub panning: bool,
#[serde(skip)]
pub panel_width: f32,
// Label editing state
#[serde(skip)]
pub editing_label: Option<LabelId>,
#[serde(skip)]
pub label_edit_buffer: String,
// Module creation dialog state
#[serde(skip)]
pub creating_module: bool,
#[serde(skip)]
pub module_name_buffer: String,
#[serde(skip)]
pub module_creation_error: Option<String>,
// Simulation service - holds simulation state and results
#[serde(skip)]
pub simulator: Simulator,
// Clock controller for managing clock ticking
#[serde(skip, default = "ClockController::default")]
pub clock_controller: ClockController,
#[serde(skip)]
pub viewing_module: Option<ViewModule>,
}
impl Default for App {
fn default() -> Self {
let canvas_config = CanvasConfig::default();
let db = DB::default();
let c = ConnectionManager::new(&db.circuit, &canvas_config, &db);
Self {
db,
canvas_config,
drag: Default::default(),
hovered: Default::default(),
connection_manager: c,
potential_connections: Default::default(),
current_dirty: true,
show_debug: true,
selected: Default::default(),
clipboard: Default::default(),
pending_load_json: None,
viewport_offset: Vec2::ZERO,
panning: false,
panel_width: 0.0,
editing_label: None,
label_edit_buffer: String::new(),
creating_module: false,
module_name_buffer: String::new(),
module_creation_error: None,
simulator: Simulator::default(),
clock_controller: ClockController::default(),
viewing_module: None,
}
}
}
impl eframe::App for App {
fn save(&mut self, storage: &mut dyn eframe::Storage) {
eframe::set_value(storage, eframe::APP_KEY, self);
}
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::TopBottomPanel::top("top_panel").show(ctx, |ui| {
egui::MenuBar::new().ui(ui, |ui| {
let is_web = cfg!(target_arch = "wasm32");
ui.menu_button("File", |ui| {
if ui.button("Save Circuit").clicked()
&& let Err(e) = self.save_to_file()
{
log::error!("Failed to save circuit: {e}");
}
if ui.button("Load Circuit").clicked()
&& let Err(e) = self.load_from_file()
{
log::error!("Failed to load circuit: {e}");
}
if !is_web {
ui.separator();
if ui.button("Quit").clicked() {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
});
ui.add_space(16.0);
ui.menu_button("View", |ui| {
ui.checkbox(&mut self.show_debug, "World Debug");
});
ui.add_space(16.0);
ui.menu_button("Tools", |ui| {
if ui.button("Create module").clicked() {
self.create_module();
}
});
ui.add_space(16.0);
ui.label("Clock:");
if ui.button("⏹ Stop").clicked() {
self.clock_controller.state = ClockState::Stopped;
}
if ui.button("⏭ Step").clicked() {
self.clock_controller.state = ClockState::Stopped;
self.clock_controller.voltage = !self.clock_controller.voltage;
self.current_dirty = true;
}
if ui.button("▶ Start").clicked() {
self.clock_controller.state = ClockState::Running;
self.clock_controller.tick_accumulator = 0.0;
}
ui.add_space(8.0);
// Clock speed slider
ui.label("Speed:");
let mut speed_hz = 1.0 / self.clock_controller.tick_interval;
if ui
.add(egui::Slider::new(&mut speed_hz, 0.5..=5.0).text("Hz"))
.changed()
{
self.clock_controller.tick_interval = 1.0 / speed_hz;
}
ui.add_space(16.0);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
egui::widgets::global_theme_preference_buttons(ui);
ui.add_space(16.0);
});
});
});
let dt = ctx.input(|i| i.stable_dt);
let should_tick = match self.clock_controller.state {
ClockState::Running => {
self.clock_controller.tick_accumulator += dt;
if self.clock_controller.tick_accumulator >= self.clock_controller.tick_interval {
self.clock_controller.tick_accumulator -= self.clock_controller.tick_interval;
true
} else {
false
}
}
ClockState::Stopped => false,
};
if should_tick {
self.clock_controller.voltage = !self.clock_controller.voltage;
self.current_dirty = true;
}
egui::CentralPanel::default().show(ctx, |ui| {
self.draw_main(ui);
});
if self.clock_controller.state == ClockState::Running {
ctx.request_repaint();
}
}
}
impl App {
pub fn circuit(&self) -> &Circuit {
&self.db.circuit
}
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
egui_extras::install_image_loaders(&cc.egui_ctx);
if let Some(storage) = cc.storage {
eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default()
} else {
Default::default()
}
}
fn is_on(&self, pin: Pin) -> bool {
let pin = pin.is_passthrough(&self.db).unwrap_or(pin);
let Some(v) = self.simulator.current.get(&pin) else {
return false;
};
*v == Value::One
}
pub fn draw_main(&mut self, ui: &mut Ui) {
self.process_pending_load();
if self.show_debug {
egui::Window::new("Debug logs").show(ui.ctx(), |ui| {
egui_logger::logger_ui().show(ui);
});
}
if self.creating_module {
egui::Window::new("Create Module")
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ui.ctx(), |ui| {
ui.vertical(|ui| {
ui.label("Enter module name:");
let response = ui.text_edit_singleline(&mut self.module_name_buffer);
// Auto-focus the text input when dialog opens
response.request_focus();
// Check for Enter key to confirm
if ui.input(|i| i.key_pressed(egui::Key::Enter))
&& !self.module_name_buffer.trim().is_empty()
{
self.confirm_module_creation();
}
// Check for Escape key to cancel
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
self.creating_module = false;
self.module_name_buffer.clear();
self.module_creation_error = None;
}
// Show error message if any
if let Some(error) = &self.module_creation_error {
ui.colored_label(egui::Color32::RED, error);
}
ui.horizontal(|ui| {
if ui.button("Create").clicked() {
self.confirm_module_creation();
}
if ui.button("Cancel").clicked() {
self.creating_module = false;
self.module_name_buffer.clear();
self.module_creation_error = None;
}
});
});
});
}
if let Some(mut view_module) = self.viewing_module.take() {
let module_id = view_module.module_id;
let mut is_open = true;
let module_name = if let InstanceKind::Module(def_id) = self.circuit().ty(module_id) {
self.db.get_module_def(def_id).name.clone()
} else {
"Module View".to_owned()
};
egui::Window::new(format!("Module View: {module_name}"))
.open(&mut is_open)
.resizable(true)
.default_size([800.0, 600.0])
.show(ui.ctx(), |ui| {
self.draw_module_view(ui, module_id, &mut view_module);
});
if is_open {
self.viewing_module = Some(view_module);
}
}
ui.with_layout(Layout::left_to_right(Align::Min), |ui| {
self.canvas_config = CanvasConfig::default();
if self.show_debug {
let full_h = ui.available_height();
egui::ScrollArea::vertical().show(ui, |ui| {
let mut dbg = self.debug_string(ui);
ui.add_sized(vec2(320.0, full_h), egui::TextEdit::multiline(&mut dbg));
});
}
let panel_rect = ui
.vertical(|ui| {
ui.heading("Tools");
self.draw_panel(ui);
})
.response
.rect;
self.panel_width = panel_rect.width();
ui.separator();
ui.vertical(|ui| {
ui.heading("Canvas");
ui.label("press backspace/d to remove object");
ui.label("right click on powers to toggle");
ui.label("right click on canvas to drag");
self.draw_canvas(ui);
});
});
}
fn draw_panel(&mut self, ui: &mut Ui) {
egui::ScrollArea::vertical()
.auto_shrink([true, false])
.show(ui, |ui| {
self.draw_panel_button(ui, InstanceKind::Gate(GateKind::And));
self.draw_panel_button(ui, InstanceKind::Gate(GateKind::Nand));
self.draw_panel_button(ui, InstanceKind::Gate(GateKind::Or));
self.draw_panel_button(ui, InstanceKind::Gate(GateKind::Nor));
self.draw_panel_button(ui, InstanceKind::Gate(GateKind::Xor));
self.draw_panel_button(ui, InstanceKind::Gate(GateKind::Xnor));
self.draw_panel_button(ui, InstanceKind::Gate(GateKind::Not));
self.draw_panel_button(ui, InstanceKind::Power);
self.draw_panel_button(ui, InstanceKind::Lamp);
self.draw_panel_button(ui, InstanceKind::Clock);
self.draw_panel_button(ui, InstanceKind::Wire);
ui.add_space(8.0);
self.draw_label_button(ui);
if !self.db.module_definitions.is_empty() {
ui.add_space(8.0);
ui.label("Modules:");
}
let keys: Vec<ModuleDefId> = self.db.module_definitions.keys().collect();
for i in keys {
self.draw_panel_button(ui, InstanceKind::Module(i));
}
ui.add_space(8.0);
if Button::new("Clear")
.min_size(vec2(PANEL_BUTTON_MAX_HEIGHT, 30.0))
.ui(ui)
.clicked()
{
self.db = DB::default();
self.hovered = None;
self.selected.clear();
self.drag = None;
self.connection_manager =
ConnectionManager::new(self.circuit(), &self.canvas_config, &self.db);
self.simulator = Simulator::new();
self.viewport_offset = Vec2::ZERO;
}
});
}
fn draw_panel_button(&mut self, ui: &mut Ui, kind: InstanceKind) -> Response {
let resp = match kind {
InstanceKind::Gate(gate_kind) => {
let s = get_icon(ui, gate_kind.graphics().svg.clone())
.fit_to_exact_size(vec2(PANEL_BUTTON_MAX_HEIGHT, PANEL_BUTTON_MAX_HEIGHT));
ui.add(egui::Button::image(s).sense(Sense::click_and_drag()))
}
InstanceKind::Power => {
let s = get_icon(
ui,
Power {
pos: Pos2::ZERO,
on: true,
}
.graphics()
.svg
.clone(),
)
.fit_to_exact_size(vec2(PANEL_BUTTON_MAX_HEIGHT, PANEL_BUTTON_MAX_HEIGHT));
ui.add(egui::Button::image(s).sense(Sense::click_and_drag()))
}
InstanceKind::Lamp => {
let s = get_icon(ui, Lamp { pos: Pos2::ZERO }.graphics().svg.clone())
.fit_to_exact_size(vec2(PANEL_BUTTON_MAX_HEIGHT, PANEL_BUTTON_MAX_HEIGHT));
ui.add(egui::Button::image(s).sense(Sense::click_and_drag()))
}
InstanceKind::Clock => {
let s = get_icon(ui, Clock { pos: Pos2::ZERO }.graphics().svg.clone())
.fit_to_exact_size(vec2(PANEL_BUTTON_MAX_HEIGHT, PANEL_BUTTON_MAX_HEIGHT));
ui.add(egui::Button::image(s).sense(Sense::click_and_drag()))
}
InstanceKind::Wire => ui.add(
Button::new("Wire")
.sense(Sense::click_and_drag())
.min_size(vec2(PANEL_BUTTON_MAX_HEIGHT, 30.0)),
),
InstanceKind::Module(i) => ui.add(
Button::new(self.db.get_module_def(i).name.clone())
.sense(Sense::click_and_drag())
.min_size(vec2(PANEL_BUTTON_MAX_HEIGHT, 30.0)),
),
};
let mouse_pos_world = self.mouse_pos_world(ui);
if resp.drag_started()
&& let Some(pos) = mouse_pos_world
{
let id = match kind {
InstanceKind::Gate(kind) => self.db.circuit.new_gate(Gate { pos, kind }),
InstanceKind::Power => self.db.circuit.new_power(Power { pos, on: true }),
InstanceKind::Wire => self.db.circuit.new_wire(Wire::new_at(pos)),
InstanceKind::Lamp => self.db.circuit.new_lamp(Lamp { pos }),
InstanceKind::Clock => self.db.circuit.new_clock(Clock { pos }),
InstanceKind::Module(c) => self.db.new_module(c, pos),
};
self.set_drag(Drag::Canvas(crate::drag::CanvasDrag::Single {
id,
offset: Vec2::ZERO,
}));
}
let d_pressed = ui.input(|i| i.key_pressed(egui::Key::D));
if resp.hovered()
&& d_pressed
&& let InstanceKind::Module(i) = kind
{
let mut ids = Vec::new();
for (id, m) in &self.circuit().modules {
if m.definition_id == i {
ids.push(id);
}
}
for id in ids {
self.delete_instance(id);
}
self.db.module_definitions.remove(i);
}
ui.add_space(8.0);
resp
}
fn draw_label_button(&mut self, ui: &mut Ui) -> Response {
let resp = ui.add(
Button::new("Label")
.sense(Sense::click_and_drag())
.min_size(vec2(PANEL_BUTTON_MAX_HEIGHT, 30.0)),
);
let mouse = self.mouse_pos_world(ui);
if resp.drag_started()
&& let Some(pos) = mouse
{
let id = self.db.circuit.new_label(Label::new(pos));
self.set_drag(Drag::Label {
id,
offset: Vec2::ZERO,
});
}
ui.add_space(8.0);
resp
}
fn handle_copy_pasting(&mut self, ui: &Ui, mouse_pos_world: Option<Pos2>) {
if self.creating_module {
return;
}
let mut copy_event_detected = false;
let mut paste_event_detected = false;
ui.ctx().input(|i| {
for event in &i.events {
if matches!(event, egui::Event::Copy) {
log::info!("Copy detected");
copy_event_detected = true;
}
if let egui::Event::Paste(_) = event {
// TODO(paste-json): If user pasted json convert it to gates and add it.
paste_event_detected = true;
}
}
});
if copy_event_detected {
self.copy_to_clipboard();
}
if paste_event_detected
&& !self.clipboard.is_empty()
&& let Some(mouse) = mouse_pos_world
{
self.paste_from_clipboard(mouse);
self.current_dirty = true;
}
}
fn handle_deletion(&mut self, ui: &Ui) {
if self.creating_module {
return;
}
let bs_pressed = ui.input(|i| i.key_pressed(egui::Key::Backspace));
let d_pressed = ui.input(|i| i.key_pressed(egui::Key::D));
if bs_pressed || d_pressed {
if let Some(id) = self.hovered.take() {
match id {
Hover::Pin(pin) => self.delete_instance(pin.ins),
Hover::Instance(instance_id) => self.delete_instance(instance_id),
}
} else if self.hovered.is_none() && !self.selected.is_empty() {
let ids_to_delete: Vec<InstanceId> = self.selected.drain().collect();
for id in ids_to_delete {
self.delete_instance(id);
}
}
}
}
pub fn delete_instance(&mut self, id: InstanceId) {
self.hovered.take();
self.drag.take();
self.selected.remove(&id);
self.connection_manager.dirty_instances.remove(&id);
self.db.remove_instance(id);
self.connection_manager
.rebuild_spatial_index(&self.db.circuit, &self.db);
self.current_dirty = true;
}
pub fn delete_label(&mut self, id: LabelId) {
self.db.circuit.labels.remove(id);
if self.editing_label == Some(id) {
self.editing_label = None;
}
self.hovered.take();
self.drag.take();
}
fn draw_module_view(
&mut self,
ui: &mut Ui,
module_id: InstanceId,
view_module: &mut ViewModule,
) {
// Get the module definition
let InstanceKind::Module(module_def_id) = self.circuit().ty(module_id) else {
return; // Not a module, shouldn't happen
};
// Allocate space for the canvas
let (resp, _painter) = ui.allocate_painter(ui.available_size(), Sense::click_and_drag());
let canvas_rect = resp.rect;
// Set clip rectangle to prevent drawing outside bounds
ui.set_clip_rect(canvas_rect);
// Draw grid with module's viewport offset
Self::draw_grid(ui, canvas_rect, view_module.viewport_offset);
// Handle panning with right-click drag
let right_down = ui.input(|i| i.pointer.secondary_down());
let right_released = ui.input(|i| i.pointer.secondary_released());
let mouse_is_visible = resp.contains_pointer();
// Simple panning for module view
if right_down && mouse_is_visible {
view_module.viewport_offset += ui.input(|i| i.pointer.delta());
}
// Temporarily swap viewport to render with module's viewport
let original_viewport = self.viewport_offset;
self.viewport_offset = view_module.viewport_offset;
// Get instances that belong to this module
let module_instances = self.db.get_instances_for_module(module_id);
let module_instance_set: std::collections::HashSet<_> =
module_instances.into_iter().collect();
// Draw only the instances that belong to this module
// Save original hovered state and set to None to prevent interactions
let original_hovered = self.hovered.take();
self.draw_circuit_components(ui, |id| module_instance_set.contains(&id));
self.hovered = original_hovered;
// Restore original viewport
self.viewport_offset = original_viewport;
}
fn draw_canvas(&mut self, ui: &mut Ui) {
let (resp, _painter) = ui.allocate_painter(ui.available_size(), Sense::click_and_drag());
let canvas_rect = resp.rect;
// Set clip rectangle to prevent canvas objects from drawing outside canvas bounds
ui.set_clip_rect(canvas_rect);
Self::draw_grid(ui, canvas_rect, self.viewport_offset);
let mouse_clicked_canvas = resp.clicked();
let mouse_dragging_canvas = resp.dragged_by(egui::PointerButton::Primary);
let double_clicked = ui.input(|i| {
i.pointer
.button_double_clicked(egui::PointerButton::Primary)
});
let mouse_is_visible = resp.contains_pointer();
let mouse_pos_world = self.mouse_pos_world(ui);
let mouse_up = ui.input(|i| i.pointer.any_released());
// To use the canvas clicked we need to set everything on objects. Right now some stuff are
// on canvas rect
let mouse_clicked = ui.input(|i| i.pointer.primary_pressed()) && mouse_is_visible;
let right_released = ui.input(|i| i.pointer.secondary_released());
let right_down = ui.input(|i| i.pointer.secondary_down());
let right_clicked = ui.input(|i| i.pointer.secondary_clicked());
let enter_pressed = ui.input(|i| i.key_pressed(egui::Key::Enter));
let esc_pressed = ui.input(|i| i.key_released(egui::Key::Escape));
if !self.creating_module {
if right_down && mouse_is_visible && self.hovered.is_none() {
self.panning = true;
}
if right_released || !mouse_is_visible {
self.panning = false;
}
if self.panning {
self.viewport_offset += ui.input(|i| i.pointer.delta());
}
self.handle_copy_pasting(ui, mouse_pos_world);
self.handle_deletion(ui);
if let Some(editing_id) = self.editing_label {
let label = self.db.circuit.get_label_mut(editing_id);
label.text = self.label_edit_buffer.clone();
if mouse_up || enter_pressed || esc_pressed {
self.editing_label = None;
self.label_edit_buffer.clear();
}
}
if double_clicked
&& self.hovered.is_none()
&& let Some(mouse) = mouse_pos_world
{
let id = self.db.circuit.new_label(Label::new(mouse));
self.editing_label = Some(id);
self.label_edit_buffer = String::from("Label");
}
if let Some(mouse) = mouse_pos_world {
if mouse_dragging_canvas {
self.set_drag(Drag::Selecting { start: mouse });
}
let instance_dragging = self.drag.is_some();
if instance_dragging {
self.handle_dragging(ui, mouse);
}
if mouse_up && instance_dragging {
self.handle_drag_end(mouse);
if self.connection_manager.update_connections(&mut self.db) {
self.current_dirty = true;
}
}
}
}
if !self.creating_module {
if self.selected.len() == 1 {
self.highlight_selected_actions(ui, mouse_pos_world, mouse_clicked);
}
if mouse_clicked_canvas {
self.selected.clear();
}
if right_clicked
&& let Some(id) = self.hovered.as_ref().map(|i| i.instance())
&& matches!(self.circuit().ty(id), InstanceKind::Power)
{
let p = self.db.circuit.get_power_mut(id);
p.on = !p.on;
self.current_dirty = true;
}
// Right-click context menu for modules
if right_clicked
&& let Some(id) = self.hovered.as_ref().map(|i| i.instance())
&& matches!(self.circuit().ty(id), InstanceKind::Module(_))
{
self.viewing_module = Some(ViewModule {
module_id: id,
viewport_offset: Vec2::ZERO,
});
}
}
if self.current_dirty {
self.simulator.clocks_on = self.clock_controller.voltage;
self.simulator.compute(&self.db, &self.db.circuit);
self.current_dirty = false;
}
self.hovered = None;
let all_ids: Vec<InstanceId> = self.db.circuit.types.keys().collect();
let hidden_instances: std::collections::HashSet<_> = all_ids
.into_iter()
.filter(|id| self.db.is_hidden(*id))
.collect();
self.draw_circuit_components(ui, |id| !hidden_instances.contains(&id));
for c in &self.potential_connections {
// Highlight the pin that it's going to attach. The stable pin.
let pin_to_highlight = c.b;
let p = self
.circuit()
.pin_position(pin_to_highlight, &self.canvas_config, &self.db);
ui.painter().circle_filled(
p - self.viewport_offset,
SNAP_THRESHOLD,
COLOR_POTENTIAL_CONN_HIGHLIGHT,
);
}
if self.drag.is_none() {
self.highlight_hovered(ui);
}
self.draw_selection_highlight(ui);
}
/// Draw circuit components with an optional filter
/// If filter returns false for an instance, it won't be drawn
fn draw_circuit_components<F>(&mut self, ui: &mut Ui, mut filter: F)
where
F: FnMut(InstanceId) -> bool,
{
// Draw world - apply filter to determine which instances to draw
for id in self.db.circuit.gate_ids() {
if filter(id) {
self.draw_gate(ui, id);
}
}
for id in self.db.circuit.power_ids() {
if filter(id) {
self.draw_power(ui, id);
}
}
for id in self.db.circuit.lamp_ids() {
if filter(id) {
self.draw_lamp(ui, id);
}
}
for id in self.db.circuit.clock_ids() {
if filter(id) {
self.draw_clock(ui, id);
}
}
for id in self.db.circuit.module_ids() {
if filter(id) {
self.draw_module(ui, id);
}
}
for id in self.db.circuit.wire_ids() {
if filter(id) {
let has_current = self.is_on(wire_start(id));
self.draw_wire(
ui,
id,
self.hovered
.as_ref()
.is_some_and(|f| matches!(f, Hover::Instance(_)) && f.instance() == id),
has_current,
);
}
}
// Collect labels to avoid borrowing issues
for id in self.db.circuit.label_ids() {
self.draw_label(ui, id);
}
}
fn draw_grid(ui: &Ui, canvas_rect: Rect, viewport_offset: Vec2) {
let grid_color = if ui.visuals().dark_mode {
COLOR_GRID_DARK
} else {
COLOR_GRID_LIGHT
};
let painter = ui.painter();
// Draw vertical lines
let start_x =
(canvas_rect.left() / GRID_SIZE).floor() * GRID_SIZE - viewport_offset.x % GRID_SIZE;
let mut x = start_x;
while x <= canvas_rect.right() {
if x >= canvas_rect.left() {
painter.line_segment(
[pos2(x, canvas_rect.top()), pos2(x, canvas_rect.bottom())],
Stroke::new(1.0, grid_color),
);
}
x += GRID_SIZE;
}
// Draw horizontal lines
let start_y =
(canvas_rect.top() / GRID_SIZE).floor() * GRID_SIZE - viewport_offset.y % GRID_SIZE;
let mut y = start_y;
while y <= canvas_rect.bottom() {
if y >= canvas_rect.top() {
painter.line_segment(
[pos2(canvas_rect.left(), y), pos2(canvas_rect.right(), y)],
Stroke::new(1.0, grid_color),
);
}
y += GRID_SIZE;
}
}
fn draw_instance_graphics(
&mut self,
ui: &mut Ui,
graphics: assets::InstanceGraphics,
pos: Pos2,
id: InstanceId,
) -> Rect {
let rect = Rect::from_center_size(pos, self.canvas_config.base_gate_size);
let image = get_icon(ui, graphics.svg)
.fit_to_exact_size(rect.size())
.sense(Sense::click_and_drag());
let rect = rect.expand(INSTANEC_OUTLINE_EXPAND);
let response = ui.put(rect, image);
if response.clicked() {
self.selected.clear();
self.selected.insert(id);
}
if response.hovered() {
self.hovered = Some(Hover::Instance(id));
}
if response.dragged()
&& let Some(mouse) = ui.ctx().pointer_interact_pos()
{
// Only clear selection if dragging an unselected item
if !self.selected.contains(&id) {
self.selected.clear();
}
self.set_drag(Drag::Canvas(CanvasDrag::Single {
id,
offset: pos - mouse,
}));
}
for (i, pin) in graphics.pins.iter().enumerate() {
let pin_pos = pos + pin.offset;
let color = match pin.kind {
assets::PinKind::Input => self.canvas_config.base_input_pin_color,
assets::PinKind::Output => self.canvas_config.base_output_pin_color,
};
let rect = Rect::from_center_size(
pin_pos,
Vec2::splat(self.canvas_config.base_pin_size + PIN_HOVER_THRESHOLD),
);
let pin_resp = ui.allocate_rect(rect, Sense::drag());
ui.painter()