HackStudioWidget.cpp 59 KB

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