HackStudioWidget.cpp 40 KB

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