HackStudioWidget.cpp 51 KB

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