HackStudioWidget.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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. project_menu.add_separator();
  774. project_menu.add_action(*create_set_autocomplete_mode_action());
  775. }
  776. void HackStudioWidget::create_edit_menubar(GUI::Menubar& menubar)
  777. {
  778. auto& edit_menu = menubar.add_menu("&Edit");
  779. 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&) {
  780. reveal_action_tab(*m_find_in_files_widget);
  781. m_find_in_files_widget->focus_textbox_and_select_all();
  782. }));
  783. edit_menu.add_separator();
  784. auto vim_emulation_setting_action = GUI::Action::create_checkable("&Vim Emulation", { Mod_Ctrl | Mod_Shift | Mod_Alt, Key_V }, [this](auto& action) {
  785. if (action.is_checked())
  786. current_editor().set_editing_engine(make<GUI::VimEditingEngine>());
  787. else
  788. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  789. });
  790. vim_emulation_setting_action->set_checked(false);
  791. edit_menu.add_action(vim_emulation_setting_action);
  792. }
  793. void HackStudioWidget::create_build_menubar(GUI::Menubar& menubar)
  794. {
  795. auto& build_menu = menubar.add_menu("&Build");
  796. build_menu.add_action(*m_build_action);
  797. build_menu.add_separator();
  798. build_menu.add_action(*m_run_action);
  799. build_menu.add_action(*m_stop_action);
  800. build_menu.add_separator();
  801. build_menu.add_action(*m_debug_action);
  802. }
  803. void HackStudioWidget::create_view_menubar(GUI::Menubar& menubar)
  804. {
  805. auto hide_action_tabs_action = GUI::Action::create("&Hide Action Tabs", { Mod_Ctrl | Mod_Shift, Key_X }, [this](auto&) {
  806. hide_action_tabs();
  807. });
  808. auto open_locator_action = GUI::Action::create("Open &Locator", { Mod_Ctrl, Key_K }, [this](auto&) {
  809. m_locator->open();
  810. });
  811. auto& view_menu = menubar.add_menu("&View");
  812. view_menu.add_action(hide_action_tabs_action);
  813. view_menu.add_action(open_locator_action);
  814. view_menu.add_separator();
  815. m_wrapping_mode_actions.set_exclusive(true);
  816. auto& wrapping_mode_menu = view_menu.add_submenu("&Wrapping Mode");
  817. m_no_wrapping_action = GUI::Action::create_checkable("&No Wrapping", [&](auto&) {
  818. for (auto& wrapper : m_all_editor_wrappers)
  819. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  820. });
  821. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap &Anywhere", [&](auto&) {
  822. for (auto& wrapper : m_all_editor_wrappers)
  823. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  824. });
  825. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at &Words", [&](auto&) {
  826. for (auto& wrapper : m_all_editor_wrappers)
  827. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  828. });
  829. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  830. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  831. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  832. wrapping_mode_menu.add_action(*m_no_wrapping_action);
  833. wrapping_mode_menu.add_action(*m_wrap_anywhere_action);
  834. wrapping_mode_menu.add_action(*m_wrap_at_words_action);
  835. m_no_wrapping_action->set_checked(true);
  836. view_menu.add_separator();
  837. view_menu.add_action(*m_add_editor_action);
  838. view_menu.add_action(*m_remove_current_editor_action);
  839. view_menu.add_action(*m_add_terminal_action);
  840. view_menu.add_action(*m_remove_current_terminal_action);
  841. }
  842. void HackStudioWidget::create_help_menubar(GUI::Menubar& menubar)
  843. {
  844. auto& help_menu = menubar.add_menu("&Help");
  845. help_menu.add_action(GUI::CommonActions::make_about_action("Hack Studio", GUI::Icon::default_icon("app-hack-studio"), window()));
  846. }
  847. NonnullRefPtr<GUI::Action> HackStudioWidget::create_stop_action()
  848. {
  849. auto action = GUI::Action::create("&Stop", Gfx::Bitmap::load_from_file("/res/icons/16x16/program-stop.png"), [this](auto&) {
  850. if (!Debugger::the().session()) {
  851. m_terminal_wrapper->kill_running_command();
  852. return;
  853. }
  854. Debugger::the().stop();
  855. });
  856. action->set_enabled(false);
  857. return action;
  858. }
  859. NonnullRefPtr<GUI::Action> HackStudioWidget::create_set_autocomplete_mode_action()
  860. {
  861. auto action = GUI::Action::create_checkable("AutoComplete C++ with &Parser", [this](auto& action) {
  862. get_language_client<LanguageClients::Cpp::ServerConnection>(project().root_path())->set_autocomplete_mode(action.is_checked() ? "Parser" : "Lexer");
  863. });
  864. action->set_checked(true);
  865. return action;
  866. }
  867. void HackStudioWidget::initialize_menubar(GUI::Menubar& menubar)
  868. {
  869. create_file_menubar(menubar);
  870. create_project_menubar(menubar);
  871. create_edit_menubar(menubar);
  872. create_build_menubar(menubar);
  873. create_view_menubar(menubar);
  874. create_help_menubar(menubar);
  875. }
  876. void HackStudioWidget::handle_external_file_deletion(const String& filepath)
  877. {
  878. m_open_files.remove(filepath);
  879. m_open_files_vector.remove_all_matching(
  880. [&filepath](const String& element) { return element == filepath; });
  881. for (auto& editor_wrapper : m_all_editor_wrappers) {
  882. Editor& editor = editor_wrapper.editor();
  883. String editor_file_path = editor.code_document().file_path();
  884. String relative_editor_file_path = LexicalPath::relative_path(editor_file_path, project().root_path());
  885. if (relative_editor_file_path == filepath) {
  886. if (m_open_files_vector.is_empty()) {
  887. editor.set_document(CodeDocument::create());
  888. editor_wrapper.set_filename("");
  889. } else {
  890. auto& first_path = m_open_files_vector[0];
  891. auto& document = m_open_files.get(first_path).value()->code_document();
  892. editor.set_document(document);
  893. editor_wrapper.set_filename(first_path);
  894. }
  895. }
  896. }
  897. m_open_files_view->model()->update();
  898. }
  899. HackStudioWidget::~HackStudioWidget()
  900. {
  901. if (!m_debugger_thread.is_null()) {
  902. Debugger::the().stop();
  903. dbgln("Waiting for debugger thread to terminate");
  904. auto rc = m_debugger_thread->join();
  905. if (rc.is_error()) {
  906. warnln("pthread_join: {}", strerror(rc.error().value()));
  907. dbgln("error joining debugger thread");
  908. }
  909. }
  910. }
  911. HackStudioWidget::ContinueDecision HackStudioWidget::warn_unsaved_changes(const String& prompt)
  912. {
  913. if (!any_document_is_dirty())
  914. return ContinueDecision::Yes;
  915. auto result = GUI::MessageBox::show(window(), prompt, "Unsaved changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  916. if (result == GUI::MessageBox::ExecCancel)
  917. return ContinueDecision::No;
  918. if (result == GUI::MessageBox::ExecYes) {
  919. for (auto& editor_wrapper : m_all_editor_wrappers) {
  920. if (editor_wrapper.document_dirty()) {
  921. editor_wrapper.save();
  922. }
  923. }
  924. }
  925. return ContinueDecision::Yes;
  926. }
  927. bool HackStudioWidget::any_document_is_dirty() const
  928. {
  929. for (auto& editor_wrapper : m_all_editor_wrappers) {
  930. if (editor_wrapper.document_dirty()) {
  931. return true;
  932. }
  933. }
  934. return false;
  935. }
  936. }