HackStudioWidget.cpp 40 KB

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