HackStudioWidget.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  4. * Copyright (c) 2020-2021, the SerenityOS developers.
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include "HackStudioWidget.h"
  9. #include "Debugger/DebugInfoWidget.h"
  10. #include "Debugger/Debugger.h"
  11. #include "Debugger/DisassemblyWidget.h"
  12. #include "Dialogs/NewProjectDialog.h"
  13. #include "Editor.h"
  14. #include "EditorWrapper.h"
  15. #include "FindInFilesWidget.h"
  16. #include "Git/DiffViewer.h"
  17. #include "Git/GitWidget.h"
  18. #include "HackStudio.h"
  19. #include "HackStudioWidget.h"
  20. #include "Locator.h"
  21. #include "Project.h"
  22. #include "ProjectDeclarations.h"
  23. #include "TerminalWrapper.h"
  24. #include "ToDoEntries.h"
  25. #include <AK/LexicalPath.h>
  26. #include <AK/StringBuilder.h>
  27. #include <Kernel/API/InodeWatcherEvent.h>
  28. #include <LibCore/ArgsParser.h>
  29. #include <LibCore/Event.h>
  30. #include <LibCore/EventLoop.h>
  31. #include <LibCore/File.h>
  32. #include <LibCore/FileWatcher.h>
  33. #include <LibDebug/DebugSession.h>
  34. #include <LibDesktop/Launcher.h>
  35. #include <LibGUI/Action.h>
  36. #include <LibGUI/ActionGroup.h>
  37. #include <LibGUI/Application.h>
  38. #include <LibGUI/BoxLayout.h>
  39. #include <LibGUI/Button.h>
  40. #include <LibGUI/Dialog.h>
  41. #include <LibGUI/EditingEngine.h>
  42. #include <LibGUI/FilePicker.h>
  43. #include <LibGUI/InputBox.h>
  44. #include <LibGUI/ItemListModel.h>
  45. #include <LibGUI/Label.h>
  46. #include <LibGUI/Menu.h>
  47. #include <LibGUI/Menubar.h>
  48. #include <LibGUI/MessageBox.h>
  49. #include <LibGUI/RegularEditingEngine.h>
  50. #include <LibGUI/Splitter.h>
  51. #include <LibGUI/StackWidget.h>
  52. #include <LibGUI/Statusbar.h>
  53. #include <LibGUI/TabWidget.h>
  54. #include <LibGUI/TableView.h>
  55. #include <LibGUI/TextBox.h>
  56. #include <LibGUI/TextEditor.h>
  57. #include <LibGUI/Toolbar.h>
  58. #include <LibGUI/ToolbarContainer.h>
  59. #include <LibGUI/TreeView.h>
  60. #include <LibGUI/VimEditingEngine.h>
  61. #include <LibGUI/Widget.h>
  62. #include <LibGUI/Window.h>
  63. #include <LibGfx/FontDatabase.h>
  64. #include <LibGfx/Palette.h>
  65. #include <LibThreading/Mutex.h>
  66. #include <LibThreading/Thread.h>
  67. #include <LibVT/TerminalWidget.h>
  68. #include <fcntl.h>
  69. #include <spawn.h>
  70. #include <stdio.h>
  71. #include <sys/stat.h>
  72. #include <sys/types.h>
  73. #include <sys/wait.h>
  74. #include <unistd.h>
  75. namespace HackStudio {
  76. HackStudioWidget::HackStudioWidget(const String& path_to_project)
  77. {
  78. set_fill_with_background_color(true);
  79. set_layout<GUI::VerticalBoxLayout>();
  80. layout()->set_spacing(2);
  81. open_project(path_to_project);
  82. auto& toolbar_container = add<GUI::ToolbarContainer>();
  83. auto& outer_splitter = add<GUI::HorizontalSplitter>();
  84. outer_splitter.layout()->set_spacing(5);
  85. auto& left_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  86. left_hand_splitter.layout()->set_spacing(5);
  87. left_hand_splitter.set_fixed_width(150);
  88. create_project_tab(left_hand_splitter);
  89. m_project_tree_view_context_menu = create_project_tree_view_context_menu();
  90. create_open_files_view(left_hand_splitter);
  91. m_right_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  92. m_right_hand_stack = m_right_hand_splitter->add<GUI::StackWidget>();
  93. // Put a placeholder widget front & center since we don't have a file open yet.
  94. m_right_hand_stack->add<GUI::Widget>();
  95. m_diff_viewer = m_right_hand_stack->add<DiffViewer>();
  96. m_editors_splitter = m_right_hand_stack->add<GUI::VerticalSplitter>();
  97. m_editors_splitter->layout()->set_spacing(5);
  98. m_editors_splitter->layout()->set_margins({ 3, 0, 0 });
  99. add_new_editor(*m_editors_splitter);
  100. m_switch_to_next_editor = create_switch_to_next_editor_action();
  101. m_switch_to_previous_editor = create_switch_to_previous_editor_action();
  102. m_remove_current_editor_action = create_remove_current_editor_action();
  103. m_open_action = create_open_action();
  104. m_save_action = create_save_action();
  105. m_save_as_action = create_save_as_action();
  106. m_new_project_action = create_new_project_action();
  107. create_action_tab(*m_right_hand_splitter);
  108. m_add_editor_action = create_add_editor_action();
  109. m_add_terminal_action = create_add_terminal_action();
  110. m_remove_current_terminal_action = create_remove_current_terminal_action();
  111. m_locator = add<Locator>();
  112. m_terminal_wrapper->on_command_exit = [this] {
  113. m_stop_action->set_enabled(false);
  114. };
  115. m_build_action = create_build_action();
  116. m_run_action = create_run_action();
  117. m_stop_action = create_stop_action();
  118. m_debug_action = create_debug_action();
  119. initialize_debugger();
  120. create_toolbar(toolbar_container);
  121. m_statusbar = add<GUI::Statusbar>(3);
  122. auto maybe_watcher = Core::FileWatcher::create();
  123. if (maybe_watcher.is_error()) {
  124. warnln("Couldn't create a file watcher, deleted files won't be noticed! Error: {}", maybe_watcher.error());
  125. } else {
  126. m_file_watcher = maybe_watcher.release_value();
  127. m_file_watcher->on_change = [this](Core::FileWatcherEvent const& event) {
  128. if (event.type != Core::FileWatcherEvent::Type::Deleted)
  129. return;
  130. if (event.event_path.starts_with(project().root_path())) {
  131. String relative_path = LexicalPath::relative_path(event.event_path, project().root_path());
  132. handle_external_file_deletion(relative_path);
  133. } else {
  134. handle_external_file_deletion(event.event_path);
  135. }
  136. };
  137. }
  138. }
  139. void HackStudioWidget::update_actions()
  140. {
  141. auto is_remove_terminal_enabled = [this]() {
  142. auto widget = m_action_tab_widget->active_widget();
  143. if (!widget)
  144. return false;
  145. if ("TerminalWrapper"sv != widget->class_name())
  146. return false;
  147. if (!reinterpret_cast<TerminalWrapper*>(widget)->user_spawned())
  148. return false;
  149. return true;
  150. };
  151. m_remove_current_editor_action->set_enabled(m_all_editor_wrappers.size() > 1);
  152. m_remove_current_terminal_action->set_enabled(is_remove_terminal_enabled());
  153. }
  154. void HackStudioWidget::on_action_tab_change()
  155. {
  156. update_actions();
  157. if (auto* active_widget = m_action_tab_widget->active_widget()) {
  158. if (is<GitWidget>(*active_widget))
  159. static_cast<GitWidget&>(*active_widget).refresh();
  160. }
  161. }
  162. void HackStudioWidget::open_project(const String& root_path)
  163. {
  164. if (chdir(root_path.characters()) < 0) {
  165. perror("chdir");
  166. exit(1);
  167. }
  168. if (m_project) {
  169. m_editors_splitter->remove_all_children();
  170. m_all_editor_wrappers.clear();
  171. m_open_files.clear();
  172. m_open_files_vector.clear();
  173. add_new_editor(*m_editors_splitter);
  174. }
  175. m_project = Project::open_with_root_path(root_path);
  176. VERIFY(m_project);
  177. if (m_project_tree_view) {
  178. m_project_tree_view->set_model(m_project->model());
  179. m_project_tree_view->update();
  180. }
  181. if (Debugger::is_initialized()) {
  182. auto& debugger = Debugger::the();
  183. debugger.reset_breakpoints();
  184. debugger.set_source_root(m_project->root_path());
  185. }
  186. for (auto& editor_wrapper : m_all_editor_wrappers)
  187. editor_wrapper.set_project_root(LexicalPath(m_project->root_path()));
  188. }
  189. Vector<String> HackStudioWidget::selected_file_paths() const
  190. {
  191. Vector<String> files;
  192. m_project_tree_view->selection().for_each_index([&](const GUI::ModelIndex& index) {
  193. String sub_path = index.data().as_string();
  194. GUI::ModelIndex parent_or_invalid = index.parent();
  195. while (parent_or_invalid.is_valid()) {
  196. sub_path = String::formatted("{}/{}", parent_or_invalid.data().as_string(), sub_path);
  197. parent_or_invalid = parent_or_invalid.parent();
  198. }
  199. files.append(sub_path);
  200. });
  201. return files;
  202. }
  203. bool HackStudioWidget::open_file(const String& full_filename)
  204. {
  205. String filename = full_filename;
  206. if (full_filename.starts_with(project().root_path())) {
  207. filename = LexicalPath::relative_path(full_filename, project().root_path());
  208. }
  209. dbgln("HackStudio is opening {}", filename);
  210. if (Core::File::is_directory(filename) || !Core::File::exists(filename))
  211. return false;
  212. if (!active_file().is_empty()) {
  213. // Since the file is previously open, it should always be in m_open_files.
  214. VERIFY(m_open_files.find(active_file()) != m_open_files.end());
  215. auto previous_open_project_file = m_open_files.get(active_file()).value();
  216. // Update the scrollbar values of the previous_open_project_file and save them to m_open_files.
  217. previous_open_project_file->vertical_scroll_value(current_editor().vertical_scrollbar().value());
  218. previous_open_project_file->horizontal_scroll_value(current_editor().horizontal_scrollbar().value());
  219. }
  220. RefPtr<ProjectFile> new_project_file = nullptr;
  221. if (auto it = m_open_files.find(filename); it != m_open_files.end()) {
  222. new_project_file = it->value;
  223. } else {
  224. new_project_file = m_project->get_file(filename);
  225. m_open_files.set(filename, *new_project_file);
  226. m_open_files_vector.append(filename);
  227. if (!m_file_watcher.is_null()) {
  228. auto watch_result = m_file_watcher->add_watch(filename, Core::FileWatcherEvent::Type::Deleted);
  229. if (watch_result.is_error()) {
  230. warnln("Couldn't watch '{}'", filename);
  231. }
  232. }
  233. m_open_files_view->model()->invalidate();
  234. }
  235. current_editor().set_document(const_cast<GUI::TextDocument&>(new_project_file->document()));
  236. if (new_project_file->could_render_text()) {
  237. current_editor_wrapper().set_mode_displayable();
  238. } else {
  239. current_editor_wrapper().set_mode_non_displayable();
  240. }
  241. current_editor().horizontal_scrollbar().set_value(new_project_file->horizontal_scroll_value());
  242. current_editor().vertical_scrollbar().set_value(new_project_file->vertical_scroll_value());
  243. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  244. set_edit_mode(EditMode::Text);
  245. String relative_file_path = filename;
  246. if (filename.starts_with(m_project->root_path()))
  247. relative_file_path = filename.substring(m_project->root_path().length() + 1);
  248. window()->set_title(String::formatted("{} - {} - Hack Studio", relative_file_path, m_project->name()));
  249. m_project_tree_view->update();
  250. current_editor_wrapper().set_filename(filename);
  251. current_editor().set_focus(true);
  252. current_editor().on_cursor_change = [this] { update_statusbar(); };
  253. current_editor().on_change = [this] { update_gml_preview(); };
  254. update_gml_preview();
  255. return true;
  256. }
  257. EditorWrapper& HackStudioWidget::current_editor_wrapper()
  258. {
  259. VERIFY(m_current_editor_wrapper);
  260. return *m_current_editor_wrapper;
  261. }
  262. GUI::TextEditor& HackStudioWidget::current_editor()
  263. {
  264. return current_editor_wrapper().editor();
  265. }
  266. void HackStudioWidget::set_edit_mode(EditMode mode)
  267. {
  268. if (mode == EditMode::Text) {
  269. m_right_hand_stack->set_active_widget(m_editors_splitter);
  270. } else if (mode == EditMode::Diff) {
  271. m_right_hand_stack->set_active_widget(m_diff_viewer);
  272. } else {
  273. VERIFY_NOT_REACHED();
  274. }
  275. m_right_hand_stack->active_widget()->update();
  276. }
  277. NonnullRefPtr<GUI::Menu> HackStudioWidget::create_project_tree_view_context_menu()
  278. {
  279. m_open_selected_action = create_open_selected_action();
  280. m_show_in_file_manager_action = create_show_in_file_manager_action();
  281. m_new_file_action = create_new_file_action();
  282. m_new_directory_action = create_new_directory_action();
  283. m_delete_action = create_delete_action();
  284. auto project_tree_view_context_menu = GUI::Menu::construct("Project Files");
  285. project_tree_view_context_menu->add_action(*m_open_selected_action);
  286. project_tree_view_context_menu->add_action(*m_show_in_file_manager_action);
  287. // TODO: Rename, cut, copy, duplicate with new name...
  288. project_tree_view_context_menu->add_separator();
  289. project_tree_view_context_menu->add_action(*m_new_file_action);
  290. project_tree_view_context_menu->add_action(*m_new_directory_action);
  291. project_tree_view_context_menu->add_action(*m_delete_action);
  292. return project_tree_view_context_menu;
  293. }
  294. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_file_action()
  295. {
  296. return GUI::Action::create("New &File...", { Mod_Ctrl, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/new.png"), [this](const GUI::Action&) {
  297. String filename;
  298. if (GUI::InputBox::show(window(), filename, "Enter name of new file:", "Add new file to project") != GUI::InputBox::ExecOK)
  299. return;
  300. auto path_to_selected = selected_file_paths();
  301. String filepath;
  302. if (!path_to_selected.is_empty()) {
  303. VERIFY(Core::File::exists(path_to_selected.first()));
  304. LexicalPath selected(path_to_selected.first());
  305. String dir_path;
  306. if (Core::File::is_directory(selected.string()))
  307. dir_path = selected.string();
  308. else
  309. dir_path = selected.dirname();
  310. filepath = String::formatted("{}/", dir_path);
  311. }
  312. filepath = String::formatted("{}{}", filepath, filename);
  313. auto file = Core::File::construct(filepath);
  314. if (!file->open((Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::MustBeNew))) {
  315. GUI::MessageBox::show(window(), String::formatted("Failed to create '{}'", filepath), "Error", GUI::MessageBox::Type::Error);
  316. return;
  317. }
  318. open_file(filepath);
  319. });
  320. }
  321. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_directory_action()
  322. {
  323. return GUI::Action::create("&New Directory...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/mkdir.png"), [this](const GUI::Action&) {
  324. String directory_name;
  325. if (GUI::InputBox::show(window(), directory_name, "Enter name of new directory:", "Add new folder to project") != GUI::InputBox::ExecOK)
  326. return;
  327. auto path_to_selected = selected_file_paths();
  328. if (!path_to_selected.is_empty()) {
  329. LexicalPath selected(path_to_selected.first());
  330. String dir_path;
  331. if (Core::File::is_directory(selected.string()))
  332. dir_path = selected.string();
  333. else
  334. dir_path = selected.dirname();
  335. directory_name = String::formatted("{}/{}", dir_path, directory_name);
  336. }
  337. auto formatted_dir_name = LexicalPath::canonicalized_path(String::formatted("{}/{}", m_project->model().root_path(), directory_name));
  338. int rc = mkdir(formatted_dir_name.characters(), 0755);
  339. if (rc < 0) {
  340. GUI::MessageBox::show(window(), "Failed to create new directory", "Error", GUI::MessageBox::Type::Error);
  341. return;
  342. }
  343. });
  344. }
  345. NonnullRefPtr<GUI::Action> HackStudioWidget::create_open_selected_action()
  346. {
  347. auto open_selected_action = GUI::Action::create("Open", [this](const GUI::Action&) {
  348. auto files = selected_file_paths();
  349. for (auto& file : files)
  350. open_file(file);
  351. });
  352. open_selected_action->set_enabled(true);
  353. return open_selected_action;
  354. }
  355. NonnullRefPtr<GUI::Action> HackStudioWidget::create_show_in_file_manager_action()
  356. {
  357. auto show_in_file_manager_action = GUI::Action::create("Show in File Manager", [this](const GUI::Action&) {
  358. auto files = selected_file_paths();
  359. for (auto& file : files)
  360. Desktop::Launcher::open(URL::create_with_file_protocol(m_project->root_path(), file));
  361. });
  362. show_in_file_manager_action->set_enabled(true);
  363. show_in_file_manager_action->set_icon(GUI::Icon::default_icon("app-file-manager").bitmap_for_size(16));
  364. return show_in_file_manager_action;
  365. }
  366. NonnullRefPtr<GUI::Action> HackStudioWidget::create_delete_action()
  367. {
  368. auto delete_action = GUI::CommonActions::make_delete_action([this](const GUI::Action&) {
  369. auto files = selected_file_paths();
  370. if (files.is_empty())
  371. return;
  372. String message;
  373. if (files.size() == 1) {
  374. LexicalPath file(files[0]);
  375. message = String::formatted("Really remove {} from disk?", file.basename());
  376. } else {
  377. message = String::formatted("Really remove {} files from disk?", files.size());
  378. }
  379. auto result = GUI::MessageBox::show(window(),
  380. message,
  381. "Confirm deletion",
  382. GUI::MessageBox::Type::Warning,
  383. GUI::MessageBox::InputType::OKCancel);
  384. if (result == GUI::MessageBox::ExecCancel)
  385. return;
  386. for (auto& file : files) {
  387. struct stat st;
  388. if (lstat(file.characters(), &st) < 0) {
  389. GUI::MessageBox::show(window(),
  390. String::formatted("lstat ({}) failed: {}", file, strerror(errno)),
  391. "Removal failed",
  392. GUI::MessageBox::Type::Error);
  393. break;
  394. }
  395. bool is_directory = S_ISDIR(st.st_mode);
  396. auto result = Core::File::remove(file, Core::File::RecursionMode::Allowed, false);
  397. if (result.is_error()) {
  398. auto& error = result.error();
  399. if (is_directory) {
  400. GUI::MessageBox::show(window(),
  401. String::formatted("Removing directory {} from the project failed: {}", error.file, error.error_code),
  402. "Removal failed",
  403. GUI::MessageBox::Type::Error);
  404. } else {
  405. GUI::MessageBox::show(window(),
  406. String::formatted("Removing file {} from the project failed: {}", error.file, error.error_code),
  407. "Removal failed",
  408. GUI::MessageBox::Type::Error);
  409. }
  410. }
  411. }
  412. });
  413. delete_action->set_enabled(false);
  414. return delete_action;
  415. }
  416. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_project_action()
  417. {
  418. return GUI::Action::create("&New Project...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/hackstudio-project.png"), [this](const GUI::Action&) {
  419. auto dialog = NewProjectDialog::construct(window());
  420. dialog->set_icon(window()->icon());
  421. auto result = dialog->exec();
  422. if (result == GUI::Dialog::ExecResult::ExecOK && dialog->created_project_path().has_value())
  423. open_project(dialog->created_project_path().value());
  424. });
  425. }
  426. void HackStudioWidget::add_new_editor(GUI::Widget& parent)
  427. {
  428. auto wrapper = EditorWrapper::construct();
  429. if (m_action_tab_widget) {
  430. parent.insert_child_before(wrapper, *m_action_tab_widget);
  431. } else {
  432. parent.add_child(wrapper);
  433. }
  434. m_current_editor_wrapper = wrapper;
  435. m_all_editor_wrappers.append(wrapper);
  436. wrapper->editor().set_focus(true);
  437. wrapper->set_project_root(LexicalPath(m_project->root_path()));
  438. wrapper->editor().on_cursor_change = [this] { update_statusbar(); };
  439. wrapper->editor().on_change = [this] { update_gml_preview(); };
  440. set_edit_mode(EditMode::Text);
  441. }
  442. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_next_editor_action()
  443. {
  444. return GUI::Action::create("Switch to &Next Editor", { Mod_Ctrl, Key_E }, [this](auto&) {
  445. if (m_all_editor_wrappers.size() <= 1)
  446. return;
  447. Vector<EditorWrapper&> wrappers;
  448. m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) {
  449. wrappers.append(child);
  450. return IterationDecision::Continue;
  451. });
  452. for (size_t i = 0; i < wrappers.size(); ++i) {
  453. if (m_current_editor_wrapper.ptr() == &wrappers[i]) {
  454. if (i == wrappers.size() - 1)
  455. wrappers[0].editor().set_focus(true);
  456. else
  457. wrappers[i + 1].editor().set_focus(true);
  458. }
  459. }
  460. });
  461. }
  462. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_previous_editor_action()
  463. {
  464. return GUI::Action::create("Switch to &Previous Editor", { Mod_Ctrl | Mod_Shift, Key_E }, [this](auto&) {
  465. if (m_all_editor_wrappers.size() <= 1)
  466. return;
  467. Vector<EditorWrapper&> wrappers;
  468. m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) {
  469. wrappers.append(child);
  470. return IterationDecision::Continue;
  471. });
  472. for (int i = wrappers.size() - 1; i >= 0; --i) {
  473. if (m_current_editor_wrapper.ptr() == &wrappers[i]) {
  474. if (i == 0)
  475. wrappers.last().editor().set_focus(true);
  476. else
  477. wrappers[i - 1].editor().set_focus(true);
  478. }
  479. }
  480. });
  481. }
  482. NonnullRefPtr<GUI::Action> HackStudioWidget::create_remove_current_editor_action()
  483. {
  484. return GUI::Action::create("&Remove Current Editor", { Mod_Alt | Mod_Shift, Key_E }, [this](auto&) {
  485. if (m_all_editor_wrappers.size() <= 1)
  486. return;
  487. auto wrapper = m_current_editor_wrapper;
  488. m_switch_to_next_editor->activate();
  489. m_editors_splitter->remove_child(*wrapper);
  490. auto child_editors = m_editors_splitter->child_widgets();
  491. bool has_child_to_fill_space = false;
  492. for (auto& editor : child_editors) {
  493. if (editor.max_height() == -1) {
  494. has_child_to_fill_space = true;
  495. break;
  496. }
  497. }
  498. if (!has_child_to_fill_space)
  499. child_editors.last().set_max_height(-1);
  500. m_all_editor_wrappers.remove_first_matching([&wrapper](auto& entry) { return entry == wrapper.ptr(); });
  501. update_actions();
  502. });
  503. }
  504. NonnullRefPtr<GUI::Action> HackStudioWidget::create_open_action()
  505. {
  506. return GUI::Action::create("&Open Project...", { Mod_Ctrl | Mod_Shift, Key_O }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/open.png"), [this](auto&) {
  507. auto open_path = GUI::FilePicker::get_open_filepath(window(), "Open project", m_project->root_path(), true);
  508. if (!open_path.has_value())
  509. return;
  510. open_project(open_path.value());
  511. update_actions();
  512. });
  513. }
  514. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_action()
  515. {
  516. return GUI::CommonActions::make_save_action([&](auto&) {
  517. if (active_file().is_empty())
  518. m_save_as_action->activate();
  519. current_editor_wrapper().save();
  520. if (m_git_widget->initialized())
  521. m_git_widget->refresh();
  522. });
  523. }
  524. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_as_action()
  525. {
  526. return GUI::CommonActions::make_save_as_action([&](auto&) {
  527. auto const old_filename = current_editor_wrapper().filename();
  528. LexicalPath const old_path(old_filename);
  529. Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(),
  530. old_filename.is_null() ? "Untitled" : old_path.title(),
  531. old_filename.is_null() ? "txt" : old_path.extension(),
  532. Core::File::absolute_path(old_path.dirname()));
  533. if (!save_path.has_value()) {
  534. return;
  535. }
  536. current_editor_wrapper().set_filename(save_path.value());
  537. current_editor_wrapper().save();
  538. auto new_project_file = m_project->get_file(save_path.value());
  539. m_open_files.set(save_path.value(), *new_project_file);
  540. m_open_files_vector.append(save_path.value());
  541. });
  542. }
  543. NonnullRefPtr<GUI::Action> HackStudioWidget::create_remove_current_terminal_action()
  544. {
  545. return GUI::Action::create("Remove &Current Terminal", { Mod_Alt | Mod_Shift, Key_T }, [this](auto&) {
  546. auto widget = m_action_tab_widget->active_widget();
  547. if (!widget)
  548. return;
  549. if (!is<TerminalWrapper>(widget))
  550. return;
  551. auto& terminal = *static_cast<TerminalWrapper*>(widget);
  552. if (!terminal.user_spawned())
  553. return;
  554. m_action_tab_widget->remove_tab(terminal);
  555. update_actions();
  556. });
  557. }
  558. NonnullRefPtr<GUI::Action> HackStudioWidget::create_add_editor_action()
  559. {
  560. return GUI::Action::create("Add New &Editor", { Mod_Ctrl | Mod_Alt, Key_E },
  561. Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-text-editor.png"),
  562. [this](auto&) {
  563. add_new_editor(*m_editors_splitter);
  564. update_actions();
  565. });
  566. }
  567. NonnullRefPtr<GUI::Action> HackStudioWidget::create_add_terminal_action()
  568. {
  569. return GUI::Action::create("Add New &Terminal", { Mod_Ctrl | Mod_Alt, Key_T },
  570. Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-terminal.png"),
  571. [this](auto&) {
  572. auto& terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Terminal");
  573. reveal_action_tab(terminal_wrapper);
  574. update_actions();
  575. terminal_wrapper.terminal().set_focus(true);
  576. });
  577. }
  578. void HackStudioWidget::reveal_action_tab(GUI::Widget& widget)
  579. {
  580. if (m_action_tab_widget->min_height() < 200)
  581. m_action_tab_widget->set_fixed_height(200);
  582. m_action_tab_widget->set_active_widget(&widget);
  583. }
  584. NonnullRefPtr<GUI::Action> HackStudioWidget::create_debug_action()
  585. {
  586. return GUI::Action::create("&Debug", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/debug-run.png"), [this](auto&) {
  587. if (!Core::File::exists(get_project_executable_path())) {
  588. GUI::MessageBox::show(window(), String::formatted("Could not find file: {}. (did you build the project?)", get_project_executable_path()), "Error", GUI::MessageBox::Type::Error);
  589. return;
  590. }
  591. if (Debugger::the().session()) {
  592. GUI::MessageBox::show(window(), "Debugger is already running", "Error", GUI::MessageBox::Type::Error);
  593. return;
  594. }
  595. Debugger::the().set_executable_path(get_project_executable_path());
  596. m_debugger_thread = Threading::Thread::construct(Debugger::start_static);
  597. m_debugger_thread->start();
  598. m_stop_action->set_enabled(true);
  599. m_run_action->set_enabled(false);
  600. for (auto& editor_wrapper : m_all_editor_wrappers) {
  601. editor_wrapper.set_debug_mode(true);
  602. }
  603. });
  604. }
  605. void HackStudioWidget::initialize_debugger()
  606. {
  607. Debugger::initialize(
  608. m_project->root_path(),
  609. [this](const PtraceRegisters& regs) {
  610. VERIFY(Debugger::the().session());
  611. const auto& debug_session = *Debugger::the().session();
  612. auto source_position = debug_session.get_source_position(regs.ip());
  613. if (!source_position.has_value()) {
  614. dbgln("Could not find source position for address: {:p}", regs.ip());
  615. return Debugger::HasControlPassedToUser::No;
  616. }
  617. dbgln("Debugger stopped at source position: {}:{}", source_position.value().file_path, source_position.value().line_number);
  618. Core::EventLoop::main().post_event(
  619. *window(),
  620. make<Core::DeferredInvocationEvent>(
  621. [this, source_position, &regs](auto&) {
  622. m_current_editor_in_execution = get_editor_of_file(source_position.value().file_path);
  623. if (m_current_editor_in_execution)
  624. m_current_editor_in_execution->editor().set_execution_position(source_position.value().line_number - 1);
  625. m_debug_info_widget->update_state(*Debugger::the().session(), regs);
  626. m_debug_info_widget->set_debug_actions_enabled(true);
  627. m_disassembly_widget->update_state(*Debugger::the().session(), regs);
  628. HackStudioWidget::reveal_action_tab(*m_debug_info_widget);
  629. }));
  630. Core::EventLoop::wake();
  631. return Debugger::HasControlPassedToUser::Yes;
  632. },
  633. [this]() {
  634. Core::EventLoop::main().post_event(*window(), make<Core::DeferredInvocationEvent>([this](auto&) {
  635. m_debug_info_widget->set_debug_actions_enabled(false);
  636. if (m_current_editor_in_execution)
  637. m_current_editor_in_execution->editor().clear_execution_position();
  638. }));
  639. Core::EventLoop::wake();
  640. },
  641. [this]() {
  642. Core::EventLoop::main().post_event(*window(), make<Core::DeferredInvocationEvent>([this](auto&) {
  643. m_debug_info_widget->set_debug_actions_enabled(false);
  644. if (m_current_editor_in_execution)
  645. m_current_editor_in_execution->editor().clear_execution_position();
  646. m_debug_info_widget->program_stopped();
  647. m_disassembly_widget->program_stopped();
  648. m_stop_action->set_enabled(false);
  649. m_run_action->set_enabled(true);
  650. m_debugger_thread.clear();
  651. for (auto& editor_wrapper : m_all_editor_wrappers) {
  652. editor_wrapper.set_debug_mode(false);
  653. }
  654. HackStudioWidget::hide_action_tabs();
  655. GUI::MessageBox::show(window(), "Program Exited", "Debugger", GUI::MessageBox::Type::Information);
  656. }));
  657. Core::EventLoop::wake();
  658. });
  659. }
  660. String HackStudioWidget::get_full_path_of_serenity_source(const String& file)
  661. {
  662. auto path_parts = LexicalPath(file).parts();
  663. VERIFY(path_parts[0] == "..");
  664. path_parts.remove(0);
  665. StringBuilder relative_path_builder;
  666. relative_path_builder.join("/", path_parts);
  667. constexpr char SERENITY_LIBS_PREFIX[] = "/usr/src/serenity";
  668. LexicalPath serenity_sources_base(SERENITY_LIBS_PREFIX);
  669. return String::formatted("{}/{}", serenity_sources_base, relative_path_builder.to_string());
  670. }
  671. RefPtr<EditorWrapper> HackStudioWidget::get_editor_of_file(const String& filename)
  672. {
  673. String file_path = filename;
  674. // TODO: We can probably do a more specific condition here, something like
  675. // "if (file.starts_with("../Libraries/") || file.starts_with("../AK/"))"
  676. if (filename.starts_with("../")) {
  677. file_path = get_full_path_of_serenity_source(filename);
  678. }
  679. if (!open_file(file_path))
  680. return nullptr;
  681. return current_editor_wrapper();
  682. }
  683. String HackStudioWidget::get_project_executable_path() const
  684. {
  685. // FIXME: Dumb heuristic ahead!
  686. // e.g /my/project => /my/project/project
  687. // TODO: Perhaps a Makefile rule for getting the value of $(PROGRAM) would be better?
  688. return String::formatted("{}/{}", m_project->root_path(), LexicalPath::basename(m_project->root_path()));
  689. }
  690. void HackStudioWidget::build(TerminalWrapper& wrapper)
  691. {
  692. if (active_file().ends_with(".js"))
  693. wrapper.run_command(String::formatted("js -A {}", active_file()));
  694. else
  695. wrapper.run_command("make");
  696. }
  697. void HackStudioWidget::run(TerminalWrapper& wrapper)
  698. {
  699. if (active_file().ends_with(".js"))
  700. wrapper.run_command(String::formatted("js {}", active_file()));
  701. else
  702. wrapper.run_command("make run");
  703. }
  704. void HackStudioWidget::hide_action_tabs()
  705. {
  706. m_action_tab_widget->set_fixed_height(24);
  707. };
  708. Project& HackStudioWidget::project()
  709. {
  710. return *m_project;
  711. }
  712. void HackStudioWidget::set_current_editor_wrapper(RefPtr<EditorWrapper> editor_wrapper)
  713. {
  714. m_current_editor_wrapper = editor_wrapper;
  715. }
  716. void HackStudioWidget::configure_project_tree_view()
  717. {
  718. m_project_tree_view->set_model(m_project->model());
  719. m_project_tree_view->set_selection_mode(GUI::AbstractView::SelectionMode::MultiSelection);
  720. for (int column_index = 0; column_index < m_project->model().column_count(); ++column_index)
  721. m_project_tree_view->set_column_visible(column_index, false);
  722. m_project_tree_view->set_column_visible(GUI::FileSystemModel::Column::Name, true);
  723. m_project_tree_view->on_context_menu_request = [this](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  724. if (index.is_valid()) {
  725. m_project_tree_view_context_menu->popup(event.screen_position(), m_open_selected_action);
  726. }
  727. };
  728. m_project_tree_view->on_selection_change = [this] {
  729. m_open_selected_action->set_enabled(!m_project_tree_view->selection().is_empty());
  730. auto selections = m_project_tree_view->selection().indices();
  731. auto it = selections.find_if([&](auto selected_file) {
  732. return access(m_project->model().full_path(selected_file.parent()).characters(), W_OK) == 0;
  733. });
  734. bool has_permissions = it != selections.end();
  735. m_delete_action->set_enabled(!m_project_tree_view->selection().is_empty() && has_permissions);
  736. };
  737. m_project_tree_view->on_activation = [this](auto& index) {
  738. auto full_path_to_file = m_project->model().full_path(index);
  739. open_file(full_path_to_file);
  740. };
  741. }
  742. void HackStudioWidget::create_open_files_view(GUI::Widget& parent)
  743. {
  744. m_open_files_view = parent.add<GUI::ListView>();
  745. auto open_files_model = GUI::ItemListModel<String>::create(m_open_files_vector);
  746. m_open_files_view->set_model(open_files_model);
  747. m_open_files_view->on_activation = [this](auto& index) {
  748. open_file(index.data().to_string());
  749. };
  750. }
  751. void HackStudioWidget::create_toolbar(GUI::Widget& parent)
  752. {
  753. auto& toolbar = parent.add<GUI::Toolbar>();
  754. toolbar.add_action(*m_new_file_action);
  755. toolbar.add_action(*m_new_directory_action);
  756. toolbar.add_action(*m_save_action);
  757. toolbar.add_action(*m_delete_action);
  758. toolbar.add_separator();
  759. toolbar.add_action(GUI::CommonActions::make_cut_action([this](auto&) { current_editor().cut_action().activate(); }));
  760. toolbar.add_action(GUI::CommonActions::make_copy_action([this](auto&) { current_editor().copy_action().activate(); }));
  761. toolbar.add_action(GUI::CommonActions::make_paste_action([this](auto&) { current_editor().paste_action().activate(); }));
  762. toolbar.add_separator();
  763. toolbar.add_action(GUI::CommonActions::make_undo_action([this](auto&) { current_editor().undo_action().activate(); }));
  764. toolbar.add_action(GUI::CommonActions::make_redo_action([this](auto&) { current_editor().redo_action().activate(); }));
  765. toolbar.add_separator();
  766. toolbar.add_action(*m_build_action);
  767. toolbar.add_separator();
  768. toolbar.add_action(*m_run_action);
  769. toolbar.add_action(*m_stop_action);
  770. toolbar.add_separator();
  771. toolbar.add_action(*m_debug_action);
  772. }
  773. NonnullRefPtr<GUI::Action> HackStudioWidget::create_build_action()
  774. {
  775. return GUI::Action::create("&Build", { Mod_Ctrl, Key_B }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/build.png"), [this](auto&) {
  776. if (warn_unsaved_changes("There are unsaved changes, do you want to save before building?") == ContinueDecision::No)
  777. return;
  778. reveal_action_tab(*m_terminal_wrapper);
  779. build(*m_terminal_wrapper);
  780. m_stop_action->set_enabled(true);
  781. });
  782. }
  783. NonnullRefPtr<GUI::Action> HackStudioWidget::create_run_action()
  784. {
  785. return GUI::Action::create("&Run", { Mod_Ctrl, Key_R }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-run.png"), [this](auto&) {
  786. reveal_action_tab(*m_terminal_wrapper);
  787. run(*m_terminal_wrapper);
  788. m_stop_action->set_enabled(true);
  789. });
  790. }
  791. void HackStudioWidget::create_action_tab(GUI::Widget& parent)
  792. {
  793. m_action_tab_widget = parent.add<GUI::TabWidget>();
  794. m_action_tab_widget->set_fixed_height(24);
  795. m_action_tab_widget->on_change = [this](auto&) {
  796. on_action_tab_change();
  797. static bool first_time = true;
  798. if (!first_time)
  799. m_action_tab_widget->set_fixed_height(200);
  800. first_time = false;
  801. };
  802. m_find_in_files_widget = m_action_tab_widget->add_tab<FindInFilesWidget>("Find in files");
  803. m_todo_entries_widget = m_action_tab_widget->add_tab<ToDoEntriesWidget>("TODO");
  804. m_terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Build", false);
  805. m_debug_info_widget = m_action_tab_widget->add_tab<DebugInfoWidget>("Debug");
  806. m_disassembly_widget = m_action_tab_widget->add_tab<DisassemblyWidget>("Disassembly");
  807. m_git_widget = m_action_tab_widget->add_tab<GitWidget>("Git", LexicalPath(m_project->root_path()));
  808. m_git_widget->set_view_diff_callback([this](const auto& original_content, const auto& diff) {
  809. m_diff_viewer->set_content(original_content, diff);
  810. set_edit_mode(EditMode::Diff);
  811. });
  812. m_gml_preview_widget = m_action_tab_widget->add_tab<GMLPreviewWidget>("GML Preview", "");
  813. ToDoEntries::the().on_update = [this]() {
  814. m_todo_entries_widget->refresh();
  815. };
  816. }
  817. void HackStudioWidget::create_project_tab(GUI::Widget& parent)
  818. {
  819. m_project_tab = parent.add<GUI::TabWidget>();
  820. m_project_tab->set_tab_position(GUI::TabWidget::TabPosition::Bottom);
  821. auto& tree_view_container = m_project_tab->add_tab<GUI::Widget>("Files");
  822. tree_view_container.set_layout<GUI::VerticalBoxLayout>();
  823. tree_view_container.layout()->set_margins(2);
  824. m_project_tree_view = tree_view_container.add<GUI::TreeView>();
  825. configure_project_tree_view();
  826. auto& class_view_container = m_project_tab->add_tab<GUI::Widget>("Classes");
  827. class_view_container.set_layout<GUI::VerticalBoxLayout>();
  828. class_view_container.layout()->set_margins(2);
  829. m_class_view = class_view_container.add<ClassViewWidget>();
  830. ProjectDeclarations::the().on_update = [this]() {
  831. m_class_view->refresh();
  832. };
  833. }
  834. void HackStudioWidget::create_file_menu(GUI::Window& window)
  835. {
  836. auto& file_menu = window.add_menu("&File");
  837. file_menu.add_action(*m_new_project_action);
  838. file_menu.add_action(*m_open_action);
  839. file_menu.add_action(*m_save_action);
  840. file_menu.add_action(*m_save_as_action);
  841. file_menu.add_separator();
  842. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  843. GUI::Application::the()->quit();
  844. }));
  845. }
  846. void HackStudioWidget::create_project_menu(GUI::Window& window)
  847. {
  848. auto& project_menu = window.add_menu("&Project");
  849. project_menu.add_action(*m_new_file_action);
  850. project_menu.add_action(*m_new_directory_action);
  851. }
  852. void HackStudioWidget::create_edit_menu(GUI::Window& window)
  853. {
  854. auto& edit_menu = window.add_menu("&Edit");
  855. edit_menu.add_action(GUI::Action::create("&Find in Files...", { Mod_Ctrl | Mod_Shift, Key_F }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find.png"), [this](auto&) {
  856. reveal_action_tab(*m_find_in_files_widget);
  857. m_find_in_files_widget->focus_textbox_and_select_all();
  858. }));
  859. edit_menu.add_separator();
  860. auto vim_emulation_setting_action = GUI::Action::create_checkable("&Vim Emulation", { Mod_Ctrl | Mod_Shift | Mod_Alt, Key_V }, [this](auto& action) {
  861. if (action.is_checked())
  862. current_editor().set_editing_engine(make<GUI::VimEditingEngine>());
  863. else
  864. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  865. });
  866. vim_emulation_setting_action->set_checked(false);
  867. edit_menu.add_action(vim_emulation_setting_action);
  868. }
  869. void HackStudioWidget::create_build_menu(GUI::Window& window)
  870. {
  871. auto& build_menu = window.add_menu("&Build");
  872. build_menu.add_action(*m_build_action);
  873. build_menu.add_separator();
  874. build_menu.add_action(*m_run_action);
  875. build_menu.add_action(*m_stop_action);
  876. build_menu.add_separator();
  877. build_menu.add_action(*m_debug_action);
  878. }
  879. void HackStudioWidget::create_view_menu(GUI::Window& window)
  880. {
  881. auto hide_action_tabs_action = GUI::Action::create("&Hide Action Tabs", { Mod_Ctrl | Mod_Shift, Key_X }, [this](auto&) {
  882. hide_action_tabs();
  883. });
  884. auto open_locator_action = GUI::Action::create("Open &Locator", { Mod_Ctrl, Key_K }, [this](auto&) {
  885. m_locator->open();
  886. });
  887. auto& view_menu = window.add_menu("&View");
  888. view_menu.add_action(hide_action_tabs_action);
  889. view_menu.add_action(open_locator_action);
  890. view_menu.add_separator();
  891. m_wrapping_mode_actions.set_exclusive(true);
  892. auto& wrapping_mode_menu = view_menu.add_submenu("&Wrapping Mode");
  893. m_no_wrapping_action = GUI::Action::create_checkable("&No Wrapping", [&](auto&) {
  894. for (auto& wrapper : m_all_editor_wrappers)
  895. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  896. });
  897. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap &Anywhere", [&](auto&) {
  898. for (auto& wrapper : m_all_editor_wrappers)
  899. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  900. });
  901. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at &Words", [&](auto&) {
  902. for (auto& wrapper : m_all_editor_wrappers)
  903. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  904. });
  905. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  906. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  907. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  908. wrapping_mode_menu.add_action(*m_no_wrapping_action);
  909. wrapping_mode_menu.add_action(*m_wrap_anywhere_action);
  910. wrapping_mode_menu.add_action(*m_wrap_at_words_action);
  911. m_no_wrapping_action->set_checked(true);
  912. view_menu.add_separator();
  913. view_menu.add_action(*m_add_editor_action);
  914. view_menu.add_action(*m_remove_current_editor_action);
  915. view_menu.add_action(*m_add_terminal_action);
  916. view_menu.add_action(*m_remove_current_terminal_action);
  917. }
  918. void HackStudioWidget::create_help_menu(GUI::Window& window)
  919. {
  920. auto& help_menu = window.add_menu("&Help");
  921. help_menu.add_action(GUI::CommonActions::make_about_action("Hack Studio", GUI::Icon::default_icon("app-hack-studio"), &window));
  922. }
  923. NonnullRefPtr<GUI::Action> HackStudioWidget::create_stop_action()
  924. {
  925. auto action = GUI::Action::create("&Stop", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-stop.png"), [this](auto&) {
  926. if (!Debugger::the().session()) {
  927. m_terminal_wrapper->kill_running_command();
  928. return;
  929. }
  930. Debugger::the().stop();
  931. });
  932. action->set_enabled(false);
  933. return action;
  934. }
  935. void HackStudioWidget::initialize_menubar(GUI::Window& window)
  936. {
  937. create_file_menu(window);
  938. create_project_menu(window);
  939. create_edit_menu(window);
  940. create_build_menu(window);
  941. create_view_menu(window);
  942. create_help_menu(window);
  943. }
  944. void HackStudioWidget::update_statusbar()
  945. {
  946. m_statusbar->set_text(0, String::formatted("Ln {}, Col {}", current_editor().cursor().line() + 1, current_editor().cursor().column()));
  947. StringBuilder builder;
  948. if (current_editor().has_selection()) {
  949. String selected_text = current_editor().selected_text();
  950. auto word_count = current_editor().number_of_selected_words();
  951. builder.appendff("Selected: {} {} ({} {})", selected_text.length(), selected_text.length() == 1 ? "character" : "characters", word_count, word_count != 1 ? "words" : "word");
  952. }
  953. m_statusbar->set_text(1, builder.to_string());
  954. m_statusbar->set_text(2, current_editor_wrapper().editor().code_document().language_name());
  955. }
  956. void HackStudioWidget::handle_external_file_deletion(const String& filepath)
  957. {
  958. m_open_files.remove(filepath);
  959. m_open_files_vector.remove_all_matching(
  960. [&filepath](const String& element) { return element == filepath; });
  961. for (auto& editor_wrapper : m_all_editor_wrappers) {
  962. Editor& editor = editor_wrapper.editor();
  963. String editor_file_path = editor.code_document().file_path();
  964. String relative_editor_file_path = LexicalPath::relative_path(editor_file_path, project().root_path());
  965. if (relative_editor_file_path == filepath) {
  966. if (m_open_files_vector.is_empty()) {
  967. editor.set_document(CodeDocument::create());
  968. editor_wrapper.set_filename("");
  969. } else {
  970. auto& first_path = m_open_files_vector[0];
  971. auto& document = m_open_files.get(first_path).value()->code_document();
  972. editor.set_document(document);
  973. editor_wrapper.set_filename(first_path);
  974. }
  975. }
  976. }
  977. m_open_files_view->model()->invalidate();
  978. }
  979. HackStudioWidget::~HackStudioWidget()
  980. {
  981. if (!m_debugger_thread.is_null()) {
  982. Debugger::the().stop();
  983. dbgln("Waiting for debugger thread to terminate");
  984. auto rc = m_debugger_thread->join();
  985. if (rc.is_error()) {
  986. warnln("pthread_join: {}", strerror(rc.error().value()));
  987. dbgln("error joining debugger thread");
  988. }
  989. }
  990. }
  991. HackStudioWidget::ContinueDecision HackStudioWidget::warn_unsaved_changes(const String& prompt)
  992. {
  993. if (!any_document_is_dirty())
  994. return ContinueDecision::Yes;
  995. auto result = GUI::MessageBox::show(window(), prompt, "Unsaved changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  996. if (result == GUI::MessageBox::ExecCancel)
  997. return ContinueDecision::No;
  998. if (result == GUI::MessageBox::ExecYes) {
  999. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1000. if (editor_wrapper.document_dirty()) {
  1001. editor_wrapper.save();
  1002. }
  1003. }
  1004. }
  1005. return ContinueDecision::Yes;
  1006. }
  1007. bool HackStudioWidget::any_document_is_dirty() const
  1008. {
  1009. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1010. if (editor_wrapper.document_dirty()) {
  1011. return true;
  1012. }
  1013. }
  1014. return false;
  1015. }
  1016. void HackStudioWidget::update_gml_preview()
  1017. {
  1018. auto gml_content = current_editor_wrapper().filename().ends_with(".gml") ? current_editor_wrapper().editor().text() : "";
  1019. m_gml_preview_widget->load_gml(gml_content);
  1020. }
  1021. }