HackStudioWidget.cpp 41 KB

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