HackStudioWidget.cpp 57 KB

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