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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
/// This module provides API functions for the frontend. Could be used by
/// `invoke` in EMCAScript
pub mod frontend_api {
use std::{net::SocketAddr, path::Path};
use tauri::{async_runtime::block_on, State, Window};
use crate::{
dprintln,
interface::{
parser::Parser,
storage::{
FileShareStatus::{Client, Private, Server},
HistorianFile,
},
},
io::file_io,
menu::file::close_checker,
modules::riscv::basic::interface::{
assembler::RiscVAssembler,
parser::{RISCVExtension, RISCVParser, RISCV},
},
remote::{Modification, OpRange},
simulator::simulator::RISCVSimulator,
storage::rope_store,
types::{
menu_types::OpenShareFile,
middleware_types::*,
rpc_types::{CursorPosition, FileOperation, RpcState},
},
utility::{
ptr::Ptr,
state_helper::state::{self, get_current_tab_name, set_current_tab_name},
},
CURSOR_LIST,
};
/// Creates a new tab with content loaded from a specified file path.
/// - `tab_map`: Current state of all open tabs.
/// - `filepath`: Path to the file from which content will be loaded.
///
/// Returns `Optional` indicating the success or failure of tab creation.
#[tauri::command]
pub fn create_tab(tab_map: State<TabMap>, filepath: &str) -> Optional {
if tab_map.tabs.lock().unwrap().contains_key(filepath) {
return Optional {
success: false,
message: "Tab already exists".to_string(),
};
}
match rope_store::Text::from_path_str(filepath) {
Ok(content) => {
let tab = Tab {
text: Box::new(content),
parser: Box::new(RISCVParser::new(&vec![RISCVExtension::RV32I])),
assembler: Box::new(RiscVAssembler::new()),
simulator: Box::new(RISCVSimulator::new(filepath)),
assembly_cache: Default::default(),
};
tab_map
.tabs
.lock()
.unwrap()
.insert(filepath.to_string(), tab);
Optional {
success: true,
message: String::new(),
}
}
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Closes the tab associated with the given file path.
/// - `window`: Window handle.
/// - `cur_name`: Current name of the tab in focus.
/// - `tab_map`: Current state of all open tabs.
/// - `filepath`: Path to the file associated with the tab to close.
///
/// Returns `Optional` indicating the success or failure of tab close if
/// success, return the new tab to focus on, else return error message.
#[tauri::command]
pub fn close_tab(
window: Window,
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
filepath: &str,
) -> Optional {
let mut tabs = tab_map.tabs.lock().unwrap();
match tabs.get_mut(filepath) {
None => Optional {
success: false,
message: "Tab not found".to_string(),
},
Some(tab) => {
close_checker(&window, filepath, tab);
tabs.remove(filepath);
cur_tab_name.name.lock().unwrap().clear();
Optional {
success: true,
message: String::new(),
}
}
}
}
/// Changes the current tab to the one specified by the new path.
/// - `cur_name`: Current name of the tab in focus.
/// - `newpath`: Path to the file associated with the new tab to focus.
/// - `tab_map`: Current state of all open tabs.
///
/// Returns `bool` indicating whether the operation was successful.
/// The only case where it would fail is if the tab with the specified
/// path does not exist in opened tabs.
#[tauri::command]
pub fn change_current_tab(
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
newpath: &str,
) -> bool {
let lock = tab_map.tabs.lock().unwrap();
if lock.contains_key(newpath) {
*cur_tab_name.name.lock().unwrap() = newpath.to_string();
true
} else {
false
}
}
/// Sets the cursor position in current tab associated with the given file
/// path. This could be useful for live sharing of code.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: Current state of all open tabs.
/// - `rpc_state`: State containing the RPC server/client.
/// - `row`: Row number of the cursor.
/// - `col`: Column number of the cursor.
///
/// Returns `Optional` indicating the success or failure of the operation.
///
/// # Deprecated
/// This function is deprecated and will be removed in the future. The
/// feature of set cursor is no longer supported.
#[tauri::command]
#[deprecated(
since = "0.1.0",
note = "This function is deprecated and will be removed in the future. The feature of set cursor is no longer supported."
)]
pub fn set_cursor(
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
rpc_state: State<RpcState>,
row: u64,
col: u64,
) -> Optional {
let mut tabs = tab_map.tabs.lock().unwrap();
let mut tab = tabs.get_mut(&get_current_tab_name(&cur_tab_name)).unwrap();
match tab.text.get_share_status() {
Server => {
let mut server = rpc_state.rpc_server.lock().unwrap();
server.set_host_cursor(row, col);
}
Client => {
todo!("");
}
Private => {}
}
Optional {
success: true,
message: String::new(),
}
}
/// Updates the content of the tab associated with the given file path.
/// - `window`: Window handle.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: Current state of all open tabs.
/// - `rpc_state`: State containing the RPC server/client.
/// - `op`: File operation to be performed.
/// - `start`: Starting position of the content to be updated.
/// - `end`: Ending position of the content to be updated.
/// - `content`: New content to be inserted.
///
/// Will emit event: `front_update_content`
/// - [payload](crate::types::middleware_types::UpdateContent)
///
/// Returns `Optional` indicating the success or failure of the update.
#[tauri::command]
pub fn modify_current_tab(
window: Window,
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
rpc_state: State<RpcState>,
op: FileOperation,
start: CursorPosition,
end: CursorPosition,
content: &str,
) -> Optional {
let filepath = cur_tab_name.name.lock().unwrap().clone();
match tab_map.tabs.lock().unwrap().get_mut(&filepath) {
Some(tab) => {
if tab.text.get_share_status() != Client {
match tab.text.handle_modify(&Modification {
op: op.into(),
op_range: OpRange { start, end },
version: tab.text.get_version() as u64,
modified_content: content.to_owned(),
}) {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
} else {
let mut client = rpc_state.rpc_client.lock().unwrap();
for _ in 1..10 {
match block_on(client.send_update_content(
tab.text.get_version() as u64,
&Modification {
op: op.clone().into(),
op_range: OpRange {
start: start.clone(),
end: end.clone(),
},
version: tab.text.get_version() as u64,
modified_content: content.to_owned(),
},
)) {
Ok(res) => {
if res.success {
tab.text
.handle_modify(&Modification {
op: op.into(),
op_range: OpRange { start, end },
version: 0,
modified_content: content.to_owned(),
})
.unwrap();
return Optional {
success: true,
message: String::new(),
};
} else {
let reply = block_on(
client.send_get_content(tab.text.get_version() as u64),
)
.unwrap();
for h in reply.history {
tab.text.handle_modify(&h.clone().into()).unwrap();
let op_range = h.op_range.as_ref().unwrap();
let start = op_range.start.as_ref().unwrap();
let end = op_range.end.as_ref().unwrap();
let _ = window.emit(
"front_update_content",
UpdateContent {
file_name: get_current_tab_name(&cur_tab_name),
op: h.op.clone() as i32,
start: (start.row, start.col),
end: (end.row, end.col),
content: h.modified_content.clone(),
},
);
}
continue;
}
}
Err(e) => {
dprintln!("Failed to send modify request: {}", e);
break;
}
}
}
Optional {
success: true,
message: String::new(),
}
}
}
None => Optional {
success: false,
message: "Tab not found".to_string(),
},
}
}
/// Reads the content of a tab from the file at the specified path.
/// - `filepath`: Path to the file to read.
///
/// Returns `Optional` containing the file content if successful, or an
/// error message if not.
#[tauri::command]
pub fn read_tab(filepath: &str) -> Optional {
match file_io::read_file_str(filepath) {
Ok(data) => Optional {
success: true,
message: data,
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Writes data in specific tab to the file path.
/// - `filepath`: Path to the file where data should be written.
/// - `data`: Content to write to the file.
///
/// Returns `Optional` indicating the success or failure of the write
/// operation.
#[tauri::command]
pub fn write_tab(filepath: &str, data: &str) -> Optional {
match file_io::write_file_str(filepath, data) {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Sets the range [start, end] of data to be returned by the assembly and
/// simulator for the current tab. Default is [0, 0].
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
/// - `start`: Start of the range (aligned to 4 bytes)
/// - `len`: Length of the range (aligned to 4 bytes)
///
/// Returns `Optional` indicating the success or failure of the operation.
#[tauri::command]
pub fn set_return_data_range(
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
range: MemoryReturnRange,
) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.set_memory_return_range(range) {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Assembles the code in the currently active tab.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
///
/// Returns `AssembleResult` indicating the outcome of the assembly process.
#[tauri::command]
pub fn assembly(cur_tab_name: State<CurTabName>, tab_map: State<TabMap>) -> AssembleResult {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
let code = tab.text.to_string();
let cache = &mut tab.assembly_cache;
if cache.code != code {
cache.parser_cache = Default::default();
cache.parser_result = Default::default();
cache.assembler_result = Default::default();
}
cache.code = code;
if !parse(cache, &mut tab.parser) {
AssembleResult::Error(cache.parser_result.clone().unwrap())
} else if cache.assembler_result.is_some() {
cache.assembler_result.clone().unwrap()
} else {
match tab.assembler.assemble(cache.parser_cache.clone().unwrap()) {
Ok(res) => {
if let Err(e) = tab.simulator.load_inst(res) {
return AssembleResult::Error(vec![AssembleError {
line: 0,
column: 0,
msg: e.to_string(),
}]);
}
cache.assembler_result = Some(AssembleResult::Success(AssembleSuccess {
text: tab
.simulator
.get_raw_inst()
.as_ref()
.unwrap()
.instruction
.iter()
.map(|inst| AssembleText {
line: inst.line_number,
address: inst.address,
code: inst.code,
basic: inst.basic.to_string(),
})
.collect(),
}));
}
Err(mut e) => {
cache.assembler_result = Some(AssembleResult::Error(
e.iter_mut()
.map(|err| AssembleError {
line: err.line as u64,
column: 0,
msg: std::mem::take(&mut err.msg),
})
.collect(),
));
}
}
cache.assembler_result.clone().unwrap()
}
}
/// Dump the code in the currently active tab.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
///
/// Returns `DumpResult` indicating whether the dump was successful.
#[tauri::command]
pub fn dump(cur_tab_name: State<CurTabName>, tab_map: State<TabMap>) -> DumpResult {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
let code = tab.text.to_string();
let cache = &mut tab.assembly_cache;
if cache.code != code {
cache.parser_result = Default::default();
cache.assembler_result = Default::default();
}
cache.code = code;
if !parse(cache, &mut tab.parser) {
return DumpResult::Error(cache.parser_result.clone().unwrap());
}
match tab.assembler.dump(cache.parser_cache.clone().unwrap()) {
Ok(mem) => {
for (ext, data) in [("text", &mem.text), ("data", &mem.data)] {
if let Err(e) =
file_io::write_file(tab.text.get_path().with_extension(ext).as_path(), data)
{
return DumpResult::Error(vec![AssembleError {
line: 0,
column: 0,
msg: e.to_string(),
}]);
}
}
DumpResult::Success(())
}
Err(mut e) => DumpResult::Error(
e.iter_mut()
.map(|err| AssembleError {
line: err.line as u64,
column: 0,
msg: std::mem::take(&mut err.msg),
})
.collect(),
),
}
}
/// Run the code in the currently active tab in normal mode(won't stop at
/// exist break point).
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
///
/// Returns `Optional` indicating whether the run session was successfully
/// started.
#[tauri::command]
pub fn run(cur_tab_name: State<CurTabName>, tab_map: State<TabMap>) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.run() {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Run the code in the currently active tab in debug mode.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
///
/// Returns `Optional` indicating whether the debug session was successfully
/// started.
#[tauri::command]
pub fn debug(cur_tab_name: State<CurTabName>, tab_map: State<TabMap>) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.debug() {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Stops the currently active tab's simulator.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
///
/// Returns `Optional` indicating whether the stop was successful.
#[tauri::command]
pub fn stop(cur_tab_name: State<CurTabName>, tab_map: State<TabMap>) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.stop() {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Resumes the currently active tab's simulator.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
///
/// Returns `Optional` indicating whether the resume was successful.
#[tauri::command]
pub fn resume(cur_tab_name: State<CurTabName>, tab_map: State<TabMap>) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.resume() {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Steps through the code in the currently active tab.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
///
/// Returns `Optional` indicating whether the step was successful.
#[tauri::command]
pub fn step(cur_tab_name: State<CurTabName>, tab_map: State<TabMap>) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.step() {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Resets the state of the currently active tab's simulator.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
///
/// Returns `Optional` indicating whether the reset was successful.
#[tauri::command]
pub fn reset(cur_tab_name: State<CurTabName>, tab_map: State<TabMap>) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.reset() {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Undoes the last instruction for current activate tab's simulator.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
///
/// Returns `Optional` indicating whether the undo was successful.
#[tauri::command]
pub fn undo(cur_tab_name: State<CurTabName>, tab_map: State<TabMap>) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.undo() {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Sets a breakpoint at a specified line in the code of the current tab.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
/// - `line`: Line number at which to set the breakpoint.
///
/// Returns `Optional` indicating whether the breakpoint was successfully
/// set.
#[tauri::command]
pub fn set_breakpoint(
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
line: u64,
) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.set_breakpoint(line as usize) {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Removes a breakpoint at a specified line in the code of the current tab.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
/// - `line`: Line number at which to remove the breakpoint.
///
/// Returns `Optional` indicating whether the breakpoint was successfully
/// removed.
#[tauri::command]
pub fn remove_breakpoint(
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
line: u64,
) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.remove_breakpoint(line as usize) {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Send a syscall input to current tab's simulator.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
/// - `val`: Value of the input as a string.
///
/// Returns `Optional` indicating whether the syscall input was successfully
#[tauri::command]
pub fn syscall_input(
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
val: String,
) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
match tab.simulator.syscall_input(&val) {
Ok(_) => Optional {
success: true,
message: String::new(),
},
Err(e) => Optional {
success: false,
message: e.to_string(),
},
}
}
/// Updates the assembler settings for the current tab.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
/// - `settings`: New assembler settings to be applied.
///
/// Returns `Optional` indicating whether the settings were successfully
/// updated.
#[tauri::command]
pub fn update_assembler_settings(
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
settings: AssemblerConfig,
) -> Optional {
let name = cur_tab_name.name.lock().unwrap().clone();
let mut lock = tab_map.tabs.lock().unwrap();
let tab = lock.get_mut(&name).unwrap();
if let Err(e) = tab.simulator.update_config(&settings) {
return Optional {
success: false,
message: e.to_string(),
};
}
tab.assembler.update_config(&settings);
Optional {
success: true,
message: String::new(),
}
}
/// Starts the RPC server for the current tab.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
/// - `rpc_state`: State containing the RPC server/client.
/// - `password`: Password to be used for the RPC server.
///
/// Returns `Optional` indicating the success or failure of the RPC server
#[tauri::command]
pub fn start_share_server(
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
rpc_state: State<RpcState>,
port: u16,
password: &str,
) -> Optional {
let mut tabs_lock = tab_map.tabs.lock().unwrap();
if tabs_lock.len() == 0 {
return Optional {
success: false,
message: "No tab had been opened".to_string(),
};
}
let mut server_lock = rpc_state.rpc_server.lock().unwrap();
if server_lock.is_running() {
return Optional {
success: false,
message: "Server already running".to_string(),
};
} else if let Err(e) = server_lock.set_port(port) {
return Optional {
success: false,
message: e.to_string(),
};
}
server_lock.change_password(password);
if let Err(e) = server_lock.start_server(
state::get_current_tab_name(&cur_tab_name),
Ptr::new(&tab_map),
&CURSOR_LIST,
) {
Optional {
success: false,
message: e.to_string(),
}
} else {
let mut tab = tabs_lock
.get_mut(&get_current_tab_name(&cur_tab_name))
.unwrap();
tab.text.change_share_status(Server);
Optional {
success: true,
message: String::new(),
}
}
}
/// Authorize and connect to a remote RPC server as client.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
/// - `rpc_state`: State containing the RPC server/client.
/// - `ip`: IPV4 address of the remote server.
/// - `port`: Port number of the remote server.
/// - `password`: Password to be used for the connection.
///
/// Will emit event `front_share_client`
/// - [payload](crate::types::menu_types::OpenShareFile)
///
/// Returns `Optional` indicating the success or failure of the connection.
#[tauri::command]
pub fn authorize_share_client(
window: Window,
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
rpc_state: State<RpcState>,
ip: String,
port: u16,
password: String,
) -> Optional {
let mut client = rpc_state.rpc_client.lock().unwrap();
let addr: SocketAddr = match format!("{}:{}", ip, port).parse() {
Ok(val) => val,
Err(_) => {
return Optional {
success: false,
message: "Invalid IP or port".to_string(),
};
}
};
if let Err(e) = client.set_server_addr(addr) {
return Optional {
success: false,
message: e.to_string(),
};
} else if let Err(e) = client.start() {
return Optional {
success: false,
message: e.to_string(),
};
}
match block_on(client.send_authorize(&password)) {
Ok(val) => {
let mut client_text = rope_store::Text::from_str(Path::new(&val.0), &val.2);
client_text.change_share_status(Client);
let emit_val = OpenShareFile {
file_path: val.0.clone(),
content: val.2,
};
let client_tab = Tab {
text: Box::new(client_text),
parser: Box::new(RISCVParser::new(&vec![RISCVExtension::RV32I])),
assembler: Box::new(RiscVAssembler::new()),
simulator: Box::new(RISCVSimulator::new(&val.0)),
assembly_cache: Default::default(),
};
tab_map
.tabs
.lock()
.unwrap()
.insert(val.0.clone(), client_tab);
set_current_tab_name(&cur_tab_name, &val.0);
if let Err(e) = window.emit("front_share_client", emit_val) {
return Optional {
success: false,
message: e.to_string(),
};
} else {
Optional {
success: true,
message: String::new(),
}
}
}
Err(e) => {
let _ = client.stop();
Optional {
success: false,
message: e.to_string(),
}
}
}
}
/// Stop the share server for the current tab.
/// - `cur_tab_name`: State containing the current tab name.
/// - `tab_map`: State containing the map of all tabs.
/// - `rpc_state`: State containing the RPC server/client.
///
/// Returns `bool` indicating the success or failure, failure means the
/// server is not running.
#[tauri::command]
pub fn stop_share_server(
cur_tab_name: State<CurTabName>,
tab_map: State<TabMap>,
rpc_state: State<RpcState>,
) -> bool {
let mut server = rpc_state.rpc_server.lock().unwrap();
if !server.is_running() {
false
} else {
server.stop_server();
let mut tabs = tab_map.tabs.lock().unwrap();
let mut tab = tabs.get_mut(&get_current_tab_name(&cur_tab_name)).unwrap();
tab.text.change_share_status(Private);
true
}
}
/// helper function
fn parse(cache: &mut AssembleCache, parser: &mut Box<dyn Parser<RISCV>>) -> bool {
if cache.parser_cache.is_some() {
true
} else if cache.parser_result.is_some() {
false
} else {
match parser.parse(&cache.code) {
Ok(res) => {
cache.parser_cache = Some(res);
cache.parser_result = None;
true
}
Err(mut e) => {
cache.parser_cache = None;
cache.parser_result = Some(
e.iter_mut()
.map(|err| AssembleError {
line: err.pos.0 as u64,
column: err.pos.1 as u64,
msg: std::mem::take(&mut err.msg),
})
.collect(),
);
false
}
}
}
}
}
/// This module provides API functions for the backend of a Tauri application
/// to emit event to the frontend, and the frontend needs to handle the event by
/// `listen`.
pub mod backend_api {
use strum::VariantArray;
use tauri::Manager;
use crate::{
interface::simulator::Simulator,
modules::riscv::basic::interface::parser::RV32IRegister,
types::middleware_types::{
Optional,
Register,
SimulatorData,
SyscallOutput,
SyscallRequest,
},
APP_HANDLE,
};
/// Emits a simulator update event to the frontend.
/// - `simulator`: Simulator instance to update its state.
/// - `simulator_res`: Result of the simulator operation.
///
/// Returns `Result` indicating the success or failure of the event
/// emission.
///
/// This function will emit a `front_simulator_update` event to the
/// frontend, and the payload is a `SimulatorData` containing the
/// current pc index, register and memory values.
///
/// [SimulatorData](crate::types::middleware_types::SimulatorData):
/// - `filepath`: string
/// - `success`: bool
/// - `paused`: bool
/// - `has_current_text`: bool
/// - `current_text`: u64
/// - `registers`: Vec<[Register](crate::types::middleware_types::Register)>
/// - `data`: Vec<u32>
/// - `message`: string
pub fn simulator_update(
simulator: &mut dyn Simulator,
simulator_res: Optional,
paused: bool,
) -> Result<(), String> {
if let Some(app_handle) = APP_HANDLE.lock().unwrap().as_ref() {
if let Ok(_) = app_handle.emit_all(
"front_simulator_update",
SimulatorData {
filepath: simulator.get_filepath().to_string(),
success: simulator_res.success,
paused,
has_current_text: simulator.get_pc_idx().is_some(),
current_text: simulator.get_pc_idx().unwrap_or(0) as u64,
registers: simulator
.get_register()
.iter()
.enumerate()
.map(|(i, &val)| Register {
name: RV32IRegister::VARIANTS[i].to_string(),
number: i.to_string(),
value: val as u64,
})
.collect(),
data: simulator.get_memory(),
message: simulator_res.message,
},
) {
Ok(())
} else {
Err("Failed to emit simulator update event!".to_string())
}
} else {
Err("AppHandle is not initialized!".to_string())
}
}
/// Emits a print syscall output event to the frontend.
/// - `pathname`: Identifier for the tab to which the output should be sent.
/// - `output`: Output to be printed.
///
/// Returns `Result` indicating the success or failure of the event
/// emission.
///
/// This function will emit a `front_syscall_print` event to the frontend,
/// and the payload is a `SyscallOutput` containing the filepath and output
/// to be printed.
///
/// [SyscallOutput](crate::types::middleware_types::SyscallOutput):
/// - `filepath`: string
/// - `data`: string
pub fn syscall_output_print(pathname: &str, output: &str) -> Result<(), String> {
if let Some(app_handle) = APP_HANDLE.lock().unwrap().as_ref() {
if let Ok(_) = app_handle.emit_all(
"front_syscall_print",
SyscallOutput {
filepath: pathname.to_string(),
data: output.to_string(),
},
) {
Ok(())
} else {
Err("Failed to emit syscall output print event!".to_string())
}
} else {
Err("AppHandle is not initialized!".to_string())
}
}
/// Emits a print syscall output event to the frontend.
/// - `pathname`: Identifier for the tab to which the output should be sent.
///
/// Returns `Result` indicating the success or failure of the event
/// emission.
///
/// This function will emit a `front_syscall_request` event to the frontend,
/// and the payload is a `SyscallRequest` containing the filepath.
///
/// [SyscallRequest](crate::types::middleware_types::SyscallRequest):
/// - `filepath`: string
pub fn syscall_input_request(pathname: &str) -> Result<(), String> {
if let Some(app_handle) = APP_HANDLE.lock().unwrap().as_ref() {
if let Ok(_) = app_handle.emit_all(
"front_syscall_request",
SyscallRequest {
filepath: pathname.to_string(),
},
) {
Ok(())
} else {
Err("Failed to emit syscall input request event!".to_string())
}
} else {
Err("AppHandle is not initialized!".to_string())
}
}
}