HackStudioWidget.cpp 55 KB

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