HackStudioWidget.cpp 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Itamar S. <itamar8910@gmail.com>
  4. * Copyright (c) 2023-2024, Abhishek R. <raturiabhi1000@gmail.com>
  5. * Copyright (c) 2020-2022, the SerenityOS developers.
  6. * Copyright (c) 2024, Sam Atkins <atkinssj@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include "HackStudioWidget.h"
  11. #include "Debugger/DebugInfoWidget.h"
  12. #include "Debugger/Debugger.h"
  13. #include "Debugger/DisassemblyWidget.h"
  14. #include "Dialogs/NewProjectDialog.h"
  15. #include "Editor.h"
  16. #include "EditorWrapper.h"
  17. #include "FindInFilesWidget.h"
  18. #include "Git/DiffViewer.h"
  19. #include "Git/GitWidget.h"
  20. #include "HackStudio.h"
  21. #include "Locator.h"
  22. #include "Project.h"
  23. #include "ProjectDeclarations.h"
  24. #include "TerminalWrapper.h"
  25. #include "ToDoEntries.h"
  26. #include <AK/JsonParser.h>
  27. #include <AK/LexicalPath.h>
  28. #include <AK/StringBuilder.h>
  29. #include <Kernel/API/InodeWatcherEvent.h>
  30. #include <LibConfig/Client.h>
  31. #include <LibCore/Event.h>
  32. #include <LibCore/EventLoop.h>
  33. #include <LibCore/FileWatcher.h>
  34. #include <LibCore/System.h>
  35. #include <LibDebug/DebugSession.h>
  36. #include <LibDesktop/Launcher.h>
  37. #include <LibFileSystem/FileSystem.h>
  38. #include <LibGUI/Action.h>
  39. #include <LibGUI/ActionGroup.h>
  40. #include <LibGUI/Application.h>
  41. #include <LibGUI/BoxLayout.h>
  42. #include <LibGUI/Button.h>
  43. #include <LibGUI/Dialog.h>
  44. #include <LibGUI/EditingEngine.h>
  45. #include <LibGUI/FilePicker.h>
  46. #include <LibGUI/FontPicker.h>
  47. #include <LibGUI/InputBox.h>
  48. #include <LibGUI/ItemListModel.h>
  49. #include <LibGUI/Label.h>
  50. #include <LibGUI/Menu.h>
  51. #include <LibGUI/Menubar.h>
  52. #include <LibGUI/MessageBox.h>
  53. #include <LibGUI/ModelEditingDelegate.h>
  54. #include <LibGUI/RegularEditingEngine.h>
  55. #include <LibGUI/Splitter.h>
  56. #include <LibGUI/StackWidget.h>
  57. #include <LibGUI/Statusbar.h>
  58. #include <LibGUI/TabWidget.h>
  59. #include <LibGUI/TableView.h>
  60. #include <LibGUI/TextBox.h>
  61. #include <LibGUI/TextEditor.h>
  62. #include <LibGUI/Toolbar.h>
  63. #include <LibGUI/ToolbarContainer.h>
  64. #include <LibGUI/TreeView.h>
  65. #include <LibGUI/VimEditingEngine.h>
  66. #include <LibGUI/Widget.h>
  67. #include <LibGUI/Window.h>
  68. #include <LibGfx/Font/FontDatabase.h>
  69. #include <LibGfx/Palette.h>
  70. #include <LibThreading/Mutex.h>
  71. #include <LibThreading/Thread.h>
  72. #include <LibVT/TerminalWidget.h>
  73. #include <fcntl.h>
  74. #include <stdio.h>
  75. #include <sys/stat.h>
  76. #include <sys/types.h>
  77. #include <sys/wait.h>
  78. #include <unistd.h>
  79. namespace HackStudio {
  80. ErrorOr<NonnullRefPtr<HackStudioWidget>> HackStudioWidget::create(ByteString path_to_project)
  81. {
  82. auto widget = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) HackStudioWidget));
  83. widget->m_editor_font = widget->read_editor_font_from_config();
  84. widget->set_fill_with_background_color(true);
  85. widget->set_layout<GUI::VerticalBoxLayout>(GUI::Margins {}, 2);
  86. auto& toolbar_container = widget->add<GUI::ToolbarContainer>();
  87. auto& outer_splitter = widget->add<GUI::HorizontalSplitter>();
  88. outer_splitter.layout()->set_spacing(4);
  89. auto& left_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  90. left_hand_splitter.layout()->set_spacing(6);
  91. left_hand_splitter.set_preferred_width(150);
  92. widget->m_project_tree_view_context_menu = TRY(widget->create_project_tree_view_context_menu());
  93. widget->m_right_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  94. widget->m_right_hand_stack = widget->m_right_hand_splitter->add<GUI::StackWidget>();
  95. TRY(widget->create_action_tab(*widget->m_right_hand_splitter));
  96. widget->open_project(path_to_project);
  97. widget->create_project_tab(left_hand_splitter);
  98. widget->create_open_files_view(left_hand_splitter);
  99. // Put a placeholder widget front & center since we don't have a file open yet.
  100. widget->m_right_hand_stack->add<GUI::Widget>();
  101. widget->m_diff_viewer = widget->m_right_hand_stack->add<DiffViewer>();
  102. widget->m_editors_splitter = widget->m_right_hand_stack->add<GUI::VerticalSplitter>();
  103. widget->m_editors_splitter->layout()->set_margins({ 3, 0, 0 });
  104. widget->add_new_editor_tab_widget(*widget->m_editors_splitter);
  105. widget->m_switch_to_next_editor_tab_widget = widget->create_switch_to_next_editor_tab_widget_action();
  106. widget->m_switch_to_next_editor = widget->create_switch_to_next_editor_action();
  107. widget->m_switch_to_previous_editor = widget->create_switch_to_previous_editor_action();
  108. widget->m_remove_current_editor_tab_widget_action = widget->create_remove_current_editor_tab_widget_action();
  109. widget->m_remove_current_editor_action = TRY(widget->create_remove_current_editor_action());
  110. widget->m_open_action = TRY(widget->create_open_action());
  111. widget->m_save_action = widget->create_save_action();
  112. widget->m_save_as_action = widget->create_save_as_action();
  113. widget->m_new_project_action = TRY(widget->create_new_project_action());
  114. widget->m_add_editor_tab_widget_action = widget->create_add_editor_tab_widget_action();
  115. widget->m_add_editor_action = TRY(widget->create_add_editor_action());
  116. widget->m_add_terminal_action = TRY(widget->create_add_terminal_action());
  117. widget->m_remove_current_terminal_action = TRY(widget->create_remove_current_terminal_action());
  118. widget->m_locator = widget->add<Locator>();
  119. widget->m_terminal_wrapper->on_command_exit = [widget] {
  120. widget->m_stop_action->set_enabled(false);
  121. };
  122. widget->m_open_project_configuration_action = TRY(widget->create_open_project_configuration_action());
  123. widget->m_build_action = TRY(widget->create_build_action());
  124. widget->m_run_action = TRY(widget->create_run_action());
  125. widget->m_stop_action = TRY(widget->create_stop_action());
  126. widget->m_debug_action = TRY(widget->create_debug_action());
  127. widget->initialize_debugger();
  128. widget->create_toolbar(toolbar_container);
  129. widget->m_statusbar = widget->add<GUI::Statusbar>(3);
  130. widget->m_statusbar->segment(1).set_mode(GUI::Statusbar::Segment::Mode::Auto);
  131. widget->m_statusbar->segment(2).set_mode(GUI::Statusbar::Segment::Mode::Fixed);
  132. auto width = widget->font().width("Ln 0,000 Col 000"sv) + widget->font().max_glyph_width();
  133. widget->m_statusbar->segment(2).set_fixed_width(width);
  134. widget->update_statusbar();
  135. GUI::Application::the()->on_action_enter = [widget](GUI::Action& action) {
  136. widget->m_statusbar->set_override_text(action.status_tip());
  137. };
  138. GUI::Application::the()->on_action_leave = [widget](GUI::Action&) {
  139. widget->m_statusbar->set_override_text({});
  140. };
  141. auto maybe_watcher = Core::FileWatcher::create();
  142. if (maybe_watcher.is_error()) {
  143. warnln("Couldn't create a file watcher, deleted files won't be noticed! Error: {}", maybe_watcher.error());
  144. } else {
  145. widget->m_file_watcher = maybe_watcher.release_value();
  146. widget->m_file_watcher->on_change = [widget](Core::FileWatcherEvent const& event) {
  147. if (event.type != Core::FileWatcherEvent::Type::Deleted)
  148. return;
  149. if (event.event_path.starts_with(widget->project().root_path())) {
  150. ByteString relative_path = LexicalPath::relative_path(event.event_path, widget->project().root_path());
  151. widget->handle_external_file_deletion(relative_path);
  152. } else {
  153. widget->handle_external_file_deletion(event.event_path);
  154. }
  155. };
  156. }
  157. widget->project().model().set_should_show_dotfiles(Config::read_bool("HackStudio"sv, "Global"sv, "ShowDotfiles"sv, false));
  158. return widget;
  159. }
  160. void HackStudioWidget::update_actions()
  161. {
  162. auto is_remove_terminal_enabled = [this]() {
  163. auto widget = m_action_tab_widget->active_widget();
  164. if (!widget)
  165. return false;
  166. if ("TerminalWrapper"sv != widget->class_name())
  167. return false;
  168. if (!reinterpret_cast<TerminalWrapper*>(widget)->user_spawned())
  169. return false;
  170. return true;
  171. };
  172. m_remove_current_editor_action->set_enabled(m_all_editor_wrappers.size() > 1);
  173. m_remove_current_terminal_action->set_enabled(is_remove_terminal_enabled());
  174. }
  175. void HackStudioWidget::on_action_tab_change()
  176. {
  177. update_actions();
  178. if (auto* active_widget = m_action_tab_widget->active_widget()) {
  179. if (is<GitWidget>(*active_widget))
  180. static_cast<GitWidget&>(*active_widget).refresh();
  181. }
  182. }
  183. Vector<ByteString> HackStudioWidget::read_recent_projects()
  184. {
  185. auto json = Config::read_string("HackStudio"sv, "Global"sv, "RecentProjects"sv);
  186. AK::JsonParser parser(json);
  187. auto value_or_error = parser.parse();
  188. if (value_or_error.is_error())
  189. return {};
  190. auto value = value_or_error.release_value();
  191. if (!value.is_array())
  192. return {};
  193. Vector<ByteString> paths;
  194. for (auto& json_value : value.as_array().values()) {
  195. if (!json_value.is_string())
  196. return {};
  197. paths.append(json_value.as_string());
  198. }
  199. return paths;
  200. }
  201. void HackStudioWidget::open_project(ByteString const& root_path)
  202. {
  203. if (warn_unsaved_changes("There are unsaved changes, do you want to save before closing current project?") == ContinueDecision::No)
  204. return;
  205. auto absolute_root_path = FileSystem::absolute_path(root_path).release_value_but_fixme_should_propagate_errors();
  206. if (auto result = Core::System::chdir(absolute_root_path); result.is_error()) {
  207. warnln("Failed to open project: {}", result.release_error());
  208. exit(1);
  209. }
  210. if (m_project) {
  211. close_current_project();
  212. }
  213. m_project = Project::open_with_root_path(absolute_root_path);
  214. VERIFY(m_project);
  215. m_project_builder = make<ProjectBuilder>(*m_terminal_wrapper, *m_project);
  216. if (m_project_tree_view) {
  217. m_project_tree_view->set_model(m_project->model());
  218. m_project_tree_view->update();
  219. }
  220. if (m_git_widget->initialized()) {
  221. m_git_widget->change_repo(absolute_root_path);
  222. m_git_widget->refresh();
  223. }
  224. if (Debugger::is_initialized()) {
  225. auto& debugger = Debugger::the();
  226. debugger.reset_breakpoints();
  227. debugger.set_source_root(m_project->root_path());
  228. }
  229. for (auto& editor_wrapper : m_all_editor_wrappers)
  230. editor_wrapper->set_project_root(m_project->root_path());
  231. m_locations_history.clear();
  232. m_locations_history_end_index = 0;
  233. m_project->model().on_rename_successful = [this](auto& absolute_old_path, auto& absolute_new_path) {
  234. file_renamed(
  235. LexicalPath::relative_path(absolute_old_path, m_project->root_path()),
  236. LexicalPath::relative_path(absolute_new_path, m_project->root_path()));
  237. };
  238. GUI::Application::the()->set_most_recently_open_file(absolute_root_path);
  239. }
  240. Vector<ByteString> HackStudioWidget::selected_file_paths() const
  241. {
  242. Vector<ByteString> files;
  243. m_project_tree_view->selection().for_each_index([&](const GUI::ModelIndex& index) {
  244. ByteString sub_path = index.data().as_string();
  245. GUI::ModelIndex parent_or_invalid = index.parent();
  246. while (parent_or_invalid.is_valid()) {
  247. sub_path = ByteString::formatted("{}/{}", parent_or_invalid.data().as_string(), sub_path);
  248. parent_or_invalid = parent_or_invalid.parent();
  249. }
  250. files.append(sub_path);
  251. });
  252. return files;
  253. }
  254. bool HackStudioWidget::open_file(ByteString const& full_filename, size_t line, size_t column)
  255. {
  256. ByteString filename = full_filename;
  257. if (full_filename.starts_with(project().root_path())) {
  258. filename = LexicalPath::relative_path(full_filename, project().root_path());
  259. }
  260. if (FileSystem::is_directory(filename) || !FileSystem::exists(filename))
  261. return false;
  262. auto editor_wrapper_or_none = m_all_editor_wrappers.first_matching([&](auto& wrapper) {
  263. return wrapper->filename() == filename;
  264. });
  265. if (editor_wrapper_or_none.has_value()) {
  266. set_current_editor_wrapper(editor_wrapper_or_none.release_value());
  267. current_editor().set_cursor_and_focus_line(line, column);
  268. return true;
  269. } else if (active_file().is_empty() && !current_editor().document().is_modified() && !full_filename.is_empty()) {
  270. // Replace "Untitled" blank file since it hasn't been modified
  271. } else {
  272. add_new_editor(*m_current_editor_tab_widget);
  273. }
  274. if (!active_file().is_empty()) {
  275. // Since the file is previously open, it should always be in m_open_files.
  276. VERIFY(m_open_files.find(active_file()) != m_open_files.end());
  277. auto previous_open_project_file = m_open_files.get(active_file()).value();
  278. // Update the scrollbar values of the previous_open_project_file and save them to m_open_files.
  279. previous_open_project_file->vertical_scroll_value(current_editor().vertical_scrollbar().value());
  280. previous_open_project_file->horizontal_scroll_value(current_editor().horizontal_scrollbar().value());
  281. }
  282. RefPtr<ProjectFile> new_project_file = nullptr;
  283. if (auto it = m_open_files.find(filename); it != m_open_files.end()) {
  284. new_project_file = it->value;
  285. } else {
  286. new_project_file = m_project->create_file(filename);
  287. m_open_files.set(filename, *new_project_file);
  288. m_open_files_vector.append(filename);
  289. if (!m_file_watcher.is_null()) {
  290. auto watch_result = m_file_watcher->add_watch(filename, Core::FileWatcherEvent::Type::Deleted);
  291. if (watch_result.is_error()) {
  292. warnln("Couldn't watch '{}'", filename);
  293. }
  294. }
  295. m_open_files_view->model()->invalidate();
  296. }
  297. current_editor().on_cursor_change = nullptr; // Disable callback while we're swapping the document.
  298. current_editor().set_document(const_cast<GUI::TextDocument&>(new_project_file->document()));
  299. if (new_project_file->could_render_text()) {
  300. current_editor_wrapper().set_mode_displayable();
  301. } else {
  302. current_editor_wrapper().set_mode_non_displayable();
  303. }
  304. current_editor().horizontal_scrollbar().set_value(new_project_file->horizontal_scroll_value());
  305. current_editor().vertical_scrollbar().set_value(new_project_file->vertical_scroll_value());
  306. if (current_editor().editing_engine()->is_regular())
  307. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  308. else if (current_editor().editing_engine()->is_vim())
  309. current_editor().set_editing_engine(make<GUI::VimEditingEngine>());
  310. else
  311. VERIFY_NOT_REACHED();
  312. set_edit_mode(EditMode::Text);
  313. ByteString relative_file_path = filename;
  314. if (filename.starts_with(m_project->root_path()))
  315. relative_file_path = filename.substring(m_project->root_path().length() + 1);
  316. m_project_tree_view->update();
  317. current_editor_wrapper().set_filename(filename);
  318. update_current_editor_title();
  319. current_editor().set_focus(true);
  320. current_editor().on_cursor_change = [this] { on_cursor_change(); };
  321. current_editor().on_change = [this] { update_window_title(); };
  322. current_editor_wrapper().on_change = [this] { update_gml_preview(); };
  323. current_editor().set_cursor_and_focus_line(line, column);
  324. update_gml_preview();
  325. return true;
  326. }
  327. void HackStudioWidget::close_file_in_all_editors(ByteString const& filename)
  328. {
  329. m_open_files.remove(filename);
  330. m_open_files_vector.remove_all_matching(
  331. [&filename](ByteString const& element) { return element == filename; });
  332. for (auto& editor_wrapper : m_all_editor_wrappers) {
  333. Editor& editor = editor_wrapper->editor();
  334. ByteString editor_file_path = editor.code_document().file_path();
  335. ByteString relative_editor_file_path = LexicalPath::relative_path(editor_file_path, project().root_path());
  336. if (relative_editor_file_path == filename) {
  337. if (m_open_files_vector.is_empty()) {
  338. editor.set_document(CodeDocument::create());
  339. editor_wrapper->set_filename("");
  340. } else {
  341. auto& first_path = m_open_files_vector[0];
  342. auto& document = m_open_files.get(first_path).value()->code_document();
  343. editor.set_document(document);
  344. editor_wrapper->set_filename(first_path);
  345. }
  346. }
  347. }
  348. m_open_files_view->model()->invalidate();
  349. }
  350. GUI::TabWidget& HackStudioWidget::current_editor_tab_widget()
  351. {
  352. VERIFY(m_current_editor_tab_widget);
  353. return *m_current_editor_tab_widget;
  354. }
  355. GUI::TabWidget const& HackStudioWidget::current_editor_tab_widget() const
  356. {
  357. VERIFY(m_current_editor_tab_widget);
  358. return *m_current_editor_tab_widget;
  359. }
  360. EditorWrapper& HackStudioWidget::current_editor_wrapper()
  361. {
  362. VERIFY(m_current_editor_wrapper);
  363. return *m_current_editor_wrapper;
  364. }
  365. EditorWrapper const& HackStudioWidget::current_editor_wrapper() const
  366. {
  367. VERIFY(m_current_editor_wrapper);
  368. return *m_current_editor_wrapper;
  369. }
  370. GUI::TextEditor& HackStudioWidget::current_editor()
  371. {
  372. return current_editor_wrapper().editor();
  373. }
  374. GUI::TextEditor const& HackStudioWidget::current_editor() const
  375. {
  376. return current_editor_wrapper().editor();
  377. }
  378. void HackStudioWidget::set_edit_mode(EditMode mode)
  379. {
  380. if (mode == EditMode::Text) {
  381. m_right_hand_stack->set_active_widget(m_editors_splitter);
  382. } else if (mode == EditMode::Diff) {
  383. m_right_hand_stack->set_active_widget(m_diff_viewer);
  384. } else {
  385. VERIFY_NOT_REACHED();
  386. }
  387. m_right_hand_stack->active_widget()->update();
  388. }
  389. ErrorOr<NonnullRefPtr<GUI::Menu>> HackStudioWidget::create_project_tree_view_context_menu()
  390. {
  391. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("&C++ Source File", "/res/icons/16x16/filetype-cplusplus.png", "cpp"))));
  392. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("C++ &Header File", "/res/icons/16x16/filetype-header.png", "h"))));
  393. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("&GML File", "/res/icons/16x16/filetype-gml.png", "gml"))));
  394. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("P&ython Source File", "/res/icons/16x16/filetype-python.png", "py"))));
  395. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("Ja&va Source File", "/res/icons/16x16/filetype-java.png", "java"))));
  396. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("C Source File", "/res/icons/16x16/filetype-c.png", "c"))));
  397. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("&JavaScript Source File", "/res/icons/16x16/filetype-javascript.png", "js"))));
  398. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("HT&ML File", "/res/icons/16x16/filetype-html.png", "html"))));
  399. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("C&SS File", "/res/icons/16x16/filetype-css.png", "css"))));
  400. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("&PHP File", "/res/icons/16x16/filetype-php.png", "php"))));
  401. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("&Wasm File", "/res/icons/16x16/filetype-wasm.png", "wasm"))));
  402. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("&INI File", "/res/icons/16x16/filetype-ini.png", "ini"))));
  403. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("JS&ON File", "/res/icons/16x16/filetype-json.png", "json"))));
  404. TRY(m_new_file_actions.try_append(TRY(create_new_file_action("Mark&down File", "/res/icons/16x16/filetype-markdown.png", "md"))));
  405. m_new_plain_file_action = TRY(create_new_file_action("Plain &File", "/res/icons/16x16/new.png", ""));
  406. m_open_selected_action = TRY(create_open_selected_action());
  407. m_show_in_file_manager_action = create_show_in_file_manager_action();
  408. m_copy_relative_path_action = create_copy_relative_path_action();
  409. m_copy_full_path_action = create_copy_full_path_action();
  410. m_new_directory_action = TRY(create_new_directory_action());
  411. m_delete_action = create_delete_action();
  412. m_tree_view_rename_action = GUI::CommonActions::make_rename_action([this](GUI::Action const&) {
  413. m_project_tree_view->begin_editing(m_project_tree_view->cursor_index());
  414. });
  415. auto project_tree_view_context_menu = GUI::Menu::construct("Project Files"_string);
  416. auto new_file_submenu = project_tree_view_context_menu->add_submenu("N&ew..."_string);
  417. for (auto& new_file_action : m_new_file_actions) {
  418. new_file_submenu->add_action(new_file_action);
  419. }
  420. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/new.png"sv));
  421. new_file_submenu->set_icon(icon);
  422. new_file_submenu->add_action(*m_new_plain_file_action);
  423. new_file_submenu->add_separator();
  424. new_file_submenu->add_action(*m_new_directory_action);
  425. project_tree_view_context_menu->add_action(*m_open_selected_action);
  426. project_tree_view_context_menu->add_action(*m_show_in_file_manager_action);
  427. project_tree_view_context_menu->add_action(*m_copy_relative_path_action);
  428. project_tree_view_context_menu->add_action(*m_copy_full_path_action);
  429. // TODO: Cut, copy, duplicate with new name...
  430. project_tree_view_context_menu->add_separator();
  431. project_tree_view_context_menu->add_action(*m_tree_view_rename_action);
  432. project_tree_view_context_menu->add_action(*m_delete_action);
  433. return project_tree_view_context_menu;
  434. }
  435. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_new_file_action(ByteString const& label, ByteString const& icon, ByteString const& extension)
  436. {
  437. auto icon_no_shadow = TRY(Gfx::Bitmap::load_from_file(icon));
  438. return GUI::Action::create(label, icon_no_shadow, [this, extension](const GUI::Action&) {
  439. String filename;
  440. if (GUI::InputBox::show(window(), filename, "Enter a name:"sv, "New File"sv) != GUI::InputBox::ExecResult::OK)
  441. return;
  442. if (!extension.is_empty() && !AK::StringUtils::ends_with(filename, ByteString::formatted(".{}", extension), CaseSensitivity::CaseSensitive)) {
  443. filename = String::formatted("{}.{}", filename, extension).release_value_but_fixme_should_propagate_errors();
  444. }
  445. auto path_to_selected = selected_file_paths();
  446. ByteString filepath;
  447. if (!path_to_selected.is_empty()) {
  448. VERIFY(FileSystem::exists(path_to_selected.first()));
  449. LexicalPath selected(path_to_selected.first());
  450. ByteString dir_path;
  451. if (FileSystem::is_directory(selected.string()))
  452. dir_path = selected.string();
  453. else
  454. dir_path = selected.dirname();
  455. filepath = ByteString::formatted("{}/", dir_path);
  456. }
  457. filepath = ByteString::formatted("{}{}", filepath, filename);
  458. auto file_or_error = Core::File::open(filepath, Core::File::OpenMode::Write | Core::File::OpenMode::MustBeNew);
  459. if (file_or_error.is_error()) {
  460. GUI::MessageBox::show_error(window(), ByteString::formatted("Failed to create '{}': {}", filepath, file_or_error.error()));
  461. return;
  462. }
  463. open_file(filepath);
  464. });
  465. }
  466. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_new_directory_action()
  467. {
  468. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/mkdir.png"sv));
  469. return GUI::Action::create("&Directory...", { Mod_Ctrl | Mod_Shift, Key_N }, icon, [this](const GUI::Action&) {
  470. String directory_name;
  471. if (GUI::InputBox::show(window(), directory_name, "Enter a name:"sv, "New Directory"sv) != GUI::InputBox::ExecResult::OK)
  472. return;
  473. auto path_to_selected = selected_file_paths();
  474. if (!path_to_selected.is_empty()) {
  475. LexicalPath selected(path_to_selected.first());
  476. ByteString dir_path;
  477. if (FileSystem::is_directory(selected.string()))
  478. dir_path = selected.string();
  479. else
  480. dir_path = selected.dirname();
  481. directory_name = String::formatted("{}/{}", dir_path, directory_name).release_value_but_fixme_should_propagate_errors();
  482. }
  483. auto formatted_dir_name = LexicalPath::canonicalized_path(ByteString::formatted("{}/{}", m_project->model().root_path(), directory_name));
  484. int rc = mkdir(formatted_dir_name.characters(), 0755);
  485. if (rc < 0) {
  486. GUI::MessageBox::show(window(), "Failed to create new directory"sv, "Error"sv, GUI::MessageBox::Type::Error);
  487. return;
  488. }
  489. });
  490. }
  491. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_open_selected_action()
  492. {
  493. auto open_selected_action = GUI::Action::create("&Open", [this](const GUI::Action&) {
  494. auto files = selected_file_paths();
  495. for (auto& file : files)
  496. open_file(file);
  497. });
  498. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"sv));
  499. open_selected_action->set_icon(icon);
  500. open_selected_action->set_enabled(true);
  501. return open_selected_action;
  502. }
  503. NonnullRefPtr<GUI::Action> HackStudioWidget::create_show_in_file_manager_action()
  504. {
  505. auto show_in_file_manager_action = GUI::Action::create("Show in File &Manager", [this](const GUI::Action&) {
  506. auto files = selected_file_paths();
  507. for (auto& file : files)
  508. Desktop::Launcher::open(URL::create_with_file_scheme(m_project->root_path(), file));
  509. });
  510. show_in_file_manager_action->set_enabled(true);
  511. show_in_file_manager_action->set_icon(GUI::Icon::default_icon("app-file-manager"sv).bitmap_for_size(16));
  512. return show_in_file_manager_action;
  513. }
  514. NonnullRefPtr<GUI::Action> HackStudioWidget::create_copy_relative_path_action()
  515. {
  516. auto copy_relative_path_action = GUI::Action::create("Copy &Relative Path", [this](const GUI::Action&) {
  517. auto paths = selected_file_paths();
  518. VERIFY(!paths.is_empty());
  519. auto paths_string = ByteString::join('\n', paths);
  520. GUI::Clipboard::the().set_plain_text(paths_string);
  521. });
  522. copy_relative_path_action->set_enabled(true);
  523. copy_relative_path_action->set_icon(GUI::Icon::default_icon("hard-disk"sv).bitmap_for_size(16));
  524. return copy_relative_path_action;
  525. }
  526. NonnullRefPtr<GUI::Action> HackStudioWidget::create_copy_full_path_action()
  527. {
  528. auto copy_full_path_action = GUI::Action::create("Copy &Full Path", [this](const GUI::Action&) {
  529. auto paths = selected_file_paths();
  530. VERIFY(!paths.is_empty());
  531. Vector<ByteString> full_paths;
  532. for (auto& path : paths)
  533. full_paths.append(get_absolute_path(path));
  534. auto paths_string = ByteString::join('\n', full_paths);
  535. GUI::Clipboard::the().set_plain_text(paths_string);
  536. });
  537. copy_full_path_action->set_enabled(true);
  538. copy_full_path_action->set_icon(GUI::Icon::default_icon("hard-disk"sv).bitmap_for_size(16));
  539. return copy_full_path_action;
  540. }
  541. NonnullRefPtr<GUI::Action> HackStudioWidget::create_delete_action()
  542. {
  543. auto delete_action = GUI::CommonActions::make_delete_action([this](const GUI::Action&) {
  544. auto files = selected_file_paths();
  545. if (files.is_empty())
  546. return;
  547. ByteString message;
  548. if (files.size() == 1) {
  549. LexicalPath file(files[0]);
  550. message = ByteString::formatted("Really remove \"{}\" from disk?", file.basename());
  551. } else {
  552. message = ByteString::formatted("Really remove \"{}\" files from disk?", files.size());
  553. }
  554. auto result = GUI::MessageBox::show(window(),
  555. message,
  556. "Confirm Deletion"sv,
  557. GUI::MessageBox::Type::Warning,
  558. GUI::MessageBox::InputType::OKCancel);
  559. if (result == GUI::MessageBox::ExecResult::Cancel)
  560. return;
  561. for (auto& file : files) {
  562. struct stat st;
  563. if (lstat(file.characters(), &st) < 0) {
  564. GUI::MessageBox::show(window(),
  565. ByteString::formatted("lstat ({}) failed: {}", file, strerror(errno)),
  566. "Removal Failed"sv,
  567. GUI::MessageBox::Type::Error);
  568. break;
  569. }
  570. bool is_directory = S_ISDIR(st.st_mode);
  571. if (auto result = FileSystem::remove(file, FileSystem::RecursionMode::Allowed); result.is_error()) {
  572. auto& error = result.error();
  573. if (is_directory) {
  574. GUI::MessageBox::show(window(),
  575. ByteString::formatted("Removing directory \"{}\" from the project failed: {}", file, error),
  576. "Removal Failed"sv,
  577. GUI::MessageBox::Type::Error);
  578. } else {
  579. GUI::MessageBox::show(window(),
  580. ByteString::formatted("Removing file \"{}\" from the project failed: {}", file, error),
  581. "Removal Failed"sv,
  582. GUI::MessageBox::Type::Error);
  583. }
  584. }
  585. }
  586. },
  587. m_project_tree_view);
  588. delete_action->set_enabled(false);
  589. return delete_action;
  590. }
  591. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_new_project_action()
  592. {
  593. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/hackstudio-project.png"sv));
  594. return GUI::Action::create(
  595. "&Project...", icon,
  596. [this](const GUI::Action&) {
  597. if (warn_unsaved_changes("There are unsaved changes. Would you like to save before creating a new project?") == ContinueDecision::No)
  598. return;
  599. // If the user wishes to save the changes, this occurs in warn_unsaved_changes. If they do not,
  600. // we need to mark the documents as clean so open_project works properly without asking again.
  601. for (auto& editor_wrapper : m_all_editor_wrappers)
  602. editor_wrapper->editor().document().set_unmodified();
  603. auto dialog = NewProjectDialog::construct(window());
  604. dialog->set_icon(window()->icon());
  605. auto result = dialog->exec();
  606. if (result == GUI::Dialog::ExecResult::OK && dialog->created_project_path().has_value())
  607. open_project(dialog->created_project_path().value());
  608. });
  609. }
  610. NonnullRefPtr<GUI::Action> HackStudioWidget::create_remove_current_editor_tab_widget_action()
  611. {
  612. return GUI::Action::create("Switch to Next Editor Group", { Mod_Alt | Mod_Shift, Key_Backslash }, [this](auto&) {
  613. if (m_all_editor_tab_widgets.size() <= 1)
  614. return;
  615. auto tab_widget = m_current_editor_tab_widget;
  616. while (tab_widget->children().size() > 1) {
  617. auto active_wrapper = tab_widget->active_widget();
  618. tab_widget->remove_tab(*active_wrapper);
  619. m_all_editor_wrappers.remove_first_matching([&active_wrapper](auto& entry) { return entry == active_wrapper; });
  620. }
  621. tab_widget->on_tab_close_click(*tab_widget->active_widget());
  622. });
  623. }
  624. void HackStudioWidget::add_new_editor_tab_widget(GUI::Widget& parent)
  625. {
  626. auto tab_widget = GUI::TabWidget::construct();
  627. if (m_action_tab_widget) {
  628. parent.insert_child_before(tab_widget, *m_action_tab_widget);
  629. } else {
  630. parent.add_child(tab_widget);
  631. }
  632. m_current_editor_tab_widget = tab_widget;
  633. m_all_editor_tab_widgets.append(tab_widget);
  634. tab_widget->set_reorder_allowed(true);
  635. if (m_all_editor_tab_widgets.size() > 1) {
  636. for (auto& widget : m_all_editor_tab_widgets)
  637. widget->set_close_button_enabled(true);
  638. }
  639. tab_widget->on_change = [&](auto& widget) {
  640. auto& wrapper = static_cast<EditorWrapper&>(widget);
  641. set_current_editor_wrapper(wrapper);
  642. current_editor().set_focus(true);
  643. };
  644. tab_widget->on_middle_click = [](auto& widget) {
  645. auto& wrapper = static_cast<EditorWrapper&>(widget);
  646. wrapper.on_tab_close_request(wrapper);
  647. };
  648. tab_widget->on_tab_close_click = [](auto& widget) {
  649. auto& wrapper = static_cast<EditorWrapper&>(widget);
  650. wrapper.on_tab_close_request(wrapper);
  651. };
  652. add_new_editor(*m_current_editor_tab_widget);
  653. }
  654. void HackStudioWidget::add_new_editor(GUI::TabWidget& parent)
  655. {
  656. auto& wrapper = parent.add_tab<EditorWrapper>("(Untitled)"_string);
  657. parent.set_active_widget(&wrapper);
  658. if (parent.children().size() > 1 || m_all_editor_tab_widgets.size() > 1)
  659. parent.set_close_button_enabled(true);
  660. auto previous_editor_wrapper = m_current_editor_wrapper;
  661. m_current_editor_wrapper = wrapper;
  662. m_all_editor_wrappers.append(wrapper);
  663. wrapper.editor().set_focus(true);
  664. wrapper.editor().set_font(*m_editor_font);
  665. wrapper.editor().set_wrapping_mode(m_wrapping_mode);
  666. wrapper.set_project_root(m_project->root_path());
  667. wrapper.editor().on_cursor_change = [this] { on_cursor_change(); };
  668. wrapper.on_change = [this] { update_gml_preview(); };
  669. set_edit_mode(EditMode::Text);
  670. if (previous_editor_wrapper && previous_editor_wrapper->editor().editing_engine()->is_regular())
  671. wrapper.editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  672. else if (previous_editor_wrapper && previous_editor_wrapper->editor().editing_engine()->is_vim())
  673. wrapper.editor().set_editing_engine(make<GUI::VimEditingEngine>());
  674. else
  675. wrapper.editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  676. wrapper.on_tab_close_request = [this, &parent](auto& tab) {
  677. parent.deferred_invoke([this, &parent, &tab] {
  678. tab.editor().document().unregister_client(tab.editor());
  679. set_current_editor_wrapper(tab);
  680. parent.remove_tab(tab);
  681. m_all_editor_wrappers.remove_first_matching([&tab](auto& entry) { return entry == &tab; });
  682. if (parent.children().is_empty() && m_all_editor_tab_widgets.size() > 1) {
  683. m_switch_to_next_editor_tab_widget->activate();
  684. m_editors_splitter->remove_child(parent);
  685. m_all_editor_tab_widgets.remove_first_matching([&parent](auto& entry) { return entry == &parent; });
  686. }
  687. update_actions();
  688. });
  689. };
  690. }
  691. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_next_editor_tab_widget_action()
  692. {
  693. return GUI::Action::create("Switch to Next Editor Group", { Mod_Ctrl | Mod_Shift, Key_T }, [this](auto&) {
  694. if (m_all_editor_tab_widgets.size() <= 1)
  695. return;
  696. Vector<GUI::TabWidget&> tab_widgets;
  697. m_editors_splitter->for_each_child_of_type<GUI::TabWidget>([&tab_widgets](auto& child) {
  698. tab_widgets.append(child);
  699. return IterationDecision::Continue;
  700. });
  701. for (size_t i = 0; i < tab_widgets.size(); ++i) {
  702. if (m_current_editor_tab_widget.ptr() == &tab_widgets[i]) {
  703. if (i == tab_widgets.size() - 1)
  704. m_current_editor_tab_widget = tab_widgets[0];
  705. else
  706. m_current_editor_tab_widget = tab_widgets[i + 1];
  707. auto wrapper = static_cast<EditorWrapper*>(m_current_editor_tab_widget->active_widget());
  708. set_current_editor_wrapper(wrapper);
  709. current_editor().set_focus(true);
  710. break;
  711. }
  712. }
  713. });
  714. }
  715. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_next_editor_action()
  716. {
  717. return GUI::Action::create("Switch to &Next Editor", { Mod_Ctrl, Key_E }, [this](auto&) {
  718. m_current_editor_tab_widget->activate_next_tab();
  719. });
  720. }
  721. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_previous_editor_action()
  722. {
  723. return GUI::Action::create("Switch to &Previous Editor", { Mod_Ctrl | Mod_Shift, Key_E }, [this](auto&) {
  724. m_current_editor_tab_widget->activate_previous_tab();
  725. });
  726. }
  727. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_remove_current_editor_action()
  728. {
  729. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/hackstudio/remove-editor.png"sv));
  730. return GUI::Action::create("&Remove Current Editor", { Mod_Alt | Mod_Shift, Key_E }, icon, [this](auto&) {
  731. if (m_all_editor_wrappers.size() <= 1)
  732. return;
  733. auto tab_widget = m_current_editor_tab_widget;
  734. auto* active_wrapper = tab_widget->active_widget();
  735. VERIFY(active_wrapper);
  736. tab_widget->on_tab_close_click(*active_wrapper);
  737. update_actions();
  738. });
  739. }
  740. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_toggle_open_file_in_single_click_action()
  741. {
  742. return GUI::Action::create_checkable("&Open File with Single Click", [this](auto&) {
  743. m_project_tree_view->set_activates_on_selection(!m_project_tree_view->activates_on_selection());
  744. });
  745. }
  746. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_open_action()
  747. {
  748. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"sv));
  749. return GUI::Action::create("&Open Project...", { Mod_Ctrl | Mod_Shift, Key_O }, icon, [this](auto&) {
  750. auto open_path = GUI::FilePicker::get_open_filepath(window(), "Open Project", m_project->root_path(), true);
  751. if (!open_path.has_value())
  752. return;
  753. open_project(open_path.value());
  754. update_actions();
  755. });
  756. }
  757. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_action()
  758. {
  759. return GUI::CommonActions::make_save_action([&](auto&) {
  760. if (active_file().is_empty())
  761. m_save_as_action->activate();
  762. // NOTE active_file() could still be empty after a cancelled save_as_action
  763. if (!active_file().is_empty())
  764. current_editor_wrapper().save();
  765. if (m_git_widget->initialized())
  766. m_git_widget->refresh();
  767. });
  768. }
  769. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_as_action()
  770. {
  771. return GUI::CommonActions::make_save_as_action([&](auto&) {
  772. auto const old_filename = current_editor_wrapper().filename();
  773. LexicalPath const old_path(old_filename);
  774. auto suggested_path = FileSystem::absolute_path(old_path.string()).release_value_but_fixme_should_propagate_errors();
  775. Optional<ByteString> save_path = GUI::FilePicker::get_save_filepath(window(),
  776. old_filename.is_empty() ? "Untitled"sv : old_path.title(),
  777. old_filename.is_empty() ? "txt"sv : old_path.extension(),
  778. suggested_path);
  779. if (!save_path.has_value()) {
  780. return;
  781. }
  782. ByteString const relative_file_path = LexicalPath::relative_path(save_path.value(), m_project->root_path());
  783. if (current_editor_wrapper().filename().is_empty()) {
  784. current_editor_wrapper().set_filename(relative_file_path);
  785. } else {
  786. for (auto& editor_wrapper : m_all_editor_wrappers) {
  787. if (editor_wrapper->filename() == old_filename)
  788. editor_wrapper->set_filename(relative_file_path);
  789. }
  790. }
  791. current_editor_wrapper().save();
  792. auto new_project_file = m_project->create_file(relative_file_path);
  793. m_open_files.set(relative_file_path, *new_project_file);
  794. m_open_files.remove(old_filename);
  795. m_open_files_vector.append(relative_file_path);
  796. m_open_files_vector.remove_all_matching([&old_filename](auto const& element) { return element == old_filename; });
  797. update_window_title();
  798. update_current_editor_title();
  799. m_project->model().invalidate();
  800. update_tree_view();
  801. });
  802. }
  803. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_remove_current_terminal_action()
  804. {
  805. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/hackstudio/remove-terminal.png"sv));
  806. return GUI::Action::create("Remove &Current Terminal", { Mod_Alt | Mod_Shift, Key_T }, icon, [this](auto&) {
  807. auto widget = m_action_tab_widget->active_widget();
  808. if (!widget)
  809. return;
  810. if (!is<TerminalWrapper>(widget))
  811. return;
  812. auto& terminal = *static_cast<TerminalWrapper*>(widget);
  813. if (!terminal.user_spawned())
  814. return;
  815. m_action_tab_widget->remove_tab(terminal);
  816. update_actions();
  817. });
  818. }
  819. NonnullRefPtr<GUI::Action> HackStudioWidget::create_add_editor_tab_widget_action()
  820. {
  821. return GUI::Action::create("Add New Editor Group", { Mod_Ctrl | Mod_Alt, Key_Backslash },
  822. [this](auto&) {
  823. add_new_editor_tab_widget(*m_editors_splitter);
  824. update_actions();
  825. });
  826. }
  827. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_add_editor_action()
  828. {
  829. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/hackstudio/add-editor.png"sv));
  830. return GUI::Action::create("Add New &Editor", { Mod_Ctrl | Mod_Alt, Key_E },
  831. icon,
  832. [this](auto&) {
  833. add_new_editor(*m_current_editor_tab_widget);
  834. update_actions();
  835. });
  836. }
  837. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_add_terminal_action()
  838. {
  839. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/hackstudio/add-terminal.png"sv));
  840. return GUI::Action::create("Add New &Terminal", { Mod_Ctrl | Mod_Alt, Key_T },
  841. icon,
  842. [this](auto&) {
  843. auto& terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Terminal"_string);
  844. terminal_wrapper.on_command_exit = [&]() {
  845. deferred_invoke([this]() {
  846. m_action_tab_widget->remove_tab(*m_action_tab_widget->active_widget());
  847. });
  848. };
  849. reveal_action_tab(terminal_wrapper);
  850. update_actions();
  851. terminal_wrapper.terminal().set_focus(true);
  852. });
  853. }
  854. void HackStudioWidget::reveal_action_tab(GUI::Widget& widget)
  855. {
  856. if (m_action_tab_widget->effective_min_size().height().as_int() < 200)
  857. m_action_tab_widget->set_preferred_height(200);
  858. m_action_tab_widget->set_active_widget(&widget);
  859. }
  860. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_debug_action()
  861. {
  862. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/debug-run.png"sv));
  863. return GUI::Action::create("&Debug", icon, [this](auto&) {
  864. if (!FileSystem::exists(get_project_executable_path())) {
  865. GUI::MessageBox::show(window(), ByteString::formatted("Could not find file: {}. (did you build the project?)", get_project_executable_path()), "Error"sv, GUI::MessageBox::Type::Error);
  866. return;
  867. }
  868. if (Debugger::the().session()) {
  869. GUI::MessageBox::show(window(), "Debugger is already running"sv, "Error"sv, GUI::MessageBox::Type::Error);
  870. return;
  871. }
  872. Debugger::the().set_executable_path(get_project_executable_path());
  873. m_terminal_wrapper->clear_including_history();
  874. // The debugger calls wait() on the debuggee, so the TerminalWrapper can't do that.
  875. auto ptm_res = m_terminal_wrapper->setup_master_pseudoterminal(TerminalWrapper::WaitForChildOnExit::No);
  876. if (ptm_res.is_error()) {
  877. warnln("Failed to set up master pseudoterminal: {}", ptm_res.release_error());
  878. return;
  879. }
  880. Debugger::the().set_child_setup_callback([this, ptm_res = ptm_res.release_value()]() {
  881. return m_terminal_wrapper->setup_slave_pseudoterminal(ptm_res);
  882. });
  883. m_debugger_thread = Threading::Thread::construct(Debugger::start_static);
  884. m_debugger_thread->start();
  885. m_stop_action->set_enabled(true);
  886. m_run_action->set_enabled(false);
  887. for (auto& editor_wrapper : m_all_editor_wrappers) {
  888. editor_wrapper->set_debug_mode(true);
  889. }
  890. });
  891. }
  892. void HackStudioWidget::initialize_debugger()
  893. {
  894. Debugger::initialize(
  895. m_project->root_path(),
  896. [this](PtraceRegisters const& regs) {
  897. VERIFY(Debugger::the().session());
  898. auto const& debug_session = *Debugger::the().session();
  899. auto source_position = debug_session.get_source_position(regs.ip());
  900. if (!source_position.has_value()) {
  901. dbgln("Could not find source position for address: {:p}", regs.ip());
  902. return Debugger::HasControlPassedToUser::No;
  903. }
  904. dbgln("Debugger stopped at source position: {}:{}", source_position.value().file_path, source_position.value().line_number);
  905. GUI::Application::the()->event_loop().deferred_invoke([this, source_position, &regs] {
  906. m_current_editor_in_execution = get_editor_of_file(source_position.value().file_path);
  907. if (m_current_editor_in_execution)
  908. m_current_editor_in_execution->editor().set_execution_position(source_position.value().line_number - 1);
  909. m_debug_info_widget->update_state(*Debugger::the().session(), regs);
  910. m_debug_info_widget->set_debug_actions_enabled(true, DebugInfoWidget::DebugActionsState::DebuggeeStopped);
  911. m_disassembly_widget->update_state(*Debugger::the().session(), regs);
  912. HackStudioWidget::reveal_action_tab(*m_debug_info_widget);
  913. });
  914. GUI::Application::the()->event_loop().wake();
  915. return Debugger::HasControlPassedToUser::Yes;
  916. },
  917. [this]() {
  918. GUI::Application::the()->event_loop().deferred_invoke([this] {
  919. m_debug_info_widget->set_debug_actions_enabled(true, DebugInfoWidget::DebugActionsState::DebuggeeRunning);
  920. if (m_current_editor_in_execution)
  921. m_current_editor_in_execution->editor().clear_execution_position();
  922. });
  923. GUI::Application::the()->event_loop().wake();
  924. },
  925. [this]() {
  926. GUI::Application::the()->event_loop().deferred_invoke([this] {
  927. m_debug_info_widget->set_debug_actions_enabled(false, {});
  928. if (m_current_editor_in_execution)
  929. m_current_editor_in_execution->editor().clear_execution_position();
  930. m_debug_info_widget->program_stopped();
  931. m_disassembly_widget->program_stopped();
  932. m_stop_action->set_enabled(false);
  933. m_run_action->set_enabled(true);
  934. m_debugger_thread.clear();
  935. for (auto& editor_wrapper : m_all_editor_wrappers) {
  936. editor_wrapper->set_debug_mode(false);
  937. }
  938. HackStudioWidget::hide_action_tabs();
  939. GUI::MessageBox::show(window(), "Program Exited"sv, "Debugger"sv, GUI::MessageBox::Type::Information);
  940. });
  941. GUI::Application::the()->event_loop().wake();
  942. },
  943. [](float progress) {
  944. if (GUI::Application::the()->active_window())
  945. GUI::Application::the()->active_window()->set_progress(progress * 100);
  946. });
  947. }
  948. ByteString HackStudioWidget::get_full_path_of_serenity_source(ByteString const& file)
  949. {
  950. auto path_parts = LexicalPath(file).parts();
  951. while (!path_parts.is_empty() && path_parts[0] == "..") {
  952. path_parts.remove(0);
  953. }
  954. StringBuilder relative_path_builder;
  955. relative_path_builder.join('/', path_parts);
  956. constexpr char SERENITY_LIBS_PREFIX[] = "/usr/src/serenity";
  957. LexicalPath serenity_sources_base(SERENITY_LIBS_PREFIX);
  958. return ByteString::formatted("{}/{}", serenity_sources_base, relative_path_builder.to_byte_string());
  959. }
  960. ByteString HackStudioWidget::get_absolute_path(ByteString const& path) const
  961. {
  962. // TODO: We can probably do a more specific condition here, something like
  963. // "if (file.starts_with("../Libraries/") || file.starts_with("../AK/"))"
  964. if (path.starts_with(".."sv)) {
  965. return get_full_path_of_serenity_source(path);
  966. }
  967. return m_project->to_absolute_path(path);
  968. }
  969. RefPtr<EditorWrapper> HackStudioWidget::get_editor_of_file(ByteString const& filename)
  970. {
  971. ByteString file_path = filename;
  972. if (filename.starts_with("../"sv)) {
  973. file_path = get_full_path_of_serenity_source(filename);
  974. }
  975. if (!open_file(file_path))
  976. return nullptr;
  977. return current_editor_wrapper();
  978. }
  979. ByteString HackStudioWidget::get_project_executable_path() const
  980. {
  981. // FIXME: Dumb heuristic ahead!
  982. // e.g /my/project => /my/project/project
  983. // TODO: Perhaps a Makefile rule for getting the value of $(PROGRAM) would be better?
  984. return ByteString::formatted("{}/{}", m_project->root_path(), LexicalPath::basename(m_project->root_path()));
  985. }
  986. void HackStudioWidget::build()
  987. {
  988. auto result = m_project_builder->build(active_file());
  989. if (result.is_error()) {
  990. GUI::MessageBox::show(window(), ByteString::formatted("{}", result.error()), "Build Failed"sv, GUI::MessageBox::Type::Error);
  991. m_build_action->set_enabled(true);
  992. m_stop_action->set_enabled(false);
  993. } else {
  994. m_stop_action->set_enabled(true);
  995. }
  996. }
  997. void HackStudioWidget::run()
  998. {
  999. auto result = m_project_builder->run(active_file());
  1000. if (result.is_error()) {
  1001. GUI::MessageBox::show(window(), ByteString::formatted("{}", result.error()), "Run Failed"sv, GUI::MessageBox::Type::Error);
  1002. m_run_action->set_enabled(true);
  1003. m_stop_action->set_enabled(false);
  1004. } else {
  1005. m_stop_action->set_enabled(true);
  1006. }
  1007. }
  1008. void HackStudioWidget::hide_action_tabs()
  1009. {
  1010. m_action_tab_widget->set_preferred_height(24);
  1011. }
  1012. Project& HackStudioWidget::project()
  1013. {
  1014. return *m_project;
  1015. }
  1016. void HackStudioWidget::set_current_editor_tab_widget(RefPtr<GUI::TabWidget> tab_widget)
  1017. {
  1018. m_current_editor_tab_widget = tab_widget;
  1019. }
  1020. void HackStudioWidget::set_current_editor_wrapper(RefPtr<EditorWrapper> editor_wrapper)
  1021. {
  1022. if (m_current_editor_wrapper)
  1023. m_current_editor_wrapper->editor().hide_autocomplete();
  1024. m_current_editor_wrapper = editor_wrapper;
  1025. update_window_title();
  1026. update_current_editor_title();
  1027. update_tree_view();
  1028. update_toolbar_actions();
  1029. set_current_editor_tab_widget(static_cast<GUI::TabWidget*>(m_current_editor_wrapper->parent()));
  1030. m_current_editor_tab_widget->set_active_widget(editor_wrapper);
  1031. update_statusbar();
  1032. }
  1033. void HackStudioWidget::file_renamed(ByteString const& old_name, ByteString const& new_name)
  1034. {
  1035. auto editor_or_none = m_all_editor_wrappers.first_matching([&old_name](auto const& editor) {
  1036. return editor->filename() == old_name;
  1037. });
  1038. if (editor_or_none.has_value()) {
  1039. (*editor_or_none)->set_filename(new_name);
  1040. (*editor_or_none)->set_name(new_name);
  1041. }
  1042. if (m_open_files.contains(old_name)) {
  1043. VERIFY(m_open_files_vector.remove_first_matching([&old_name](auto const& file) { return file == old_name; }));
  1044. m_open_files_vector.append(new_name);
  1045. ProjectFile* f = m_open_files.get(old_name).release_value();
  1046. m_open_files.set(new_name, *f);
  1047. m_open_files.remove(old_name);
  1048. m_open_files_view->model()->invalidate();
  1049. }
  1050. if (m_file_watcher->is_watching(old_name)) {
  1051. VERIFY(!m_file_watcher->remove_watch(old_name).is_error());
  1052. VERIFY(!m_file_watcher->add_watch(new_name, Core::FileWatcherEvent::Type::Deleted).is_error());
  1053. }
  1054. update_window_title();
  1055. update_current_editor_title();
  1056. }
  1057. void HackStudioWidget::configure_project_tree_view()
  1058. {
  1059. m_project_tree_view->set_model(m_project->model());
  1060. m_project_tree_view->set_selection_mode(GUI::AbstractView::SelectionMode::MultiSelection);
  1061. m_project_tree_view->set_editable(true);
  1062. m_project_tree_view->aid_create_editing_delegate = [](auto&) {
  1063. return make<GUI::StringModelEditingDelegate>();
  1064. };
  1065. for (int column_index = 0; column_index < m_project->model().column_count(); ++column_index)
  1066. m_project_tree_view->set_column_visible(column_index, false);
  1067. m_project_tree_view->set_column_visible(GUI::FileSystemModel::Column::Name, true);
  1068. m_project_tree_view->on_context_menu_request = [this](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  1069. if (index.is_valid()) {
  1070. m_project_tree_view_context_menu->popup(event.screen_position(), m_open_selected_action);
  1071. }
  1072. };
  1073. m_project_tree_view->on_selection_change = [this] {
  1074. m_open_selected_action->set_enabled(!m_project_tree_view->selection().is_empty());
  1075. auto selections = m_project_tree_view->selection().indices();
  1076. auto it = selections.find_if([&](auto selected_file) {
  1077. return FileSystem::can_delete_or_move(m_project->model().full_path(selected_file));
  1078. });
  1079. bool has_permissions = it != selections.end();
  1080. m_tree_view_rename_action->set_enabled(has_permissions);
  1081. m_delete_action->set_enabled(has_permissions);
  1082. };
  1083. m_project_tree_view->on_activation = [this](auto& index) {
  1084. auto full_path_to_file = m_project->model().full_path(index);
  1085. open_file(full_path_to_file);
  1086. };
  1087. }
  1088. void HackStudioWidget::create_open_files_view(GUI::Widget& parent)
  1089. {
  1090. m_open_files_view = parent.add<GUI::ListView>();
  1091. auto open_files_model = GUI::ItemListModel<ByteString>::create(m_open_files_vector);
  1092. m_open_files_view->set_model(open_files_model);
  1093. m_open_files_view->on_activation = [this](auto& index) {
  1094. open_file(index.data().to_byte_string());
  1095. };
  1096. }
  1097. void HackStudioWidget::create_toolbar(GUI::Widget& parent)
  1098. {
  1099. auto& toolbar = parent.add<GUI::Toolbar>();
  1100. toolbar.add_action(*m_new_plain_file_action);
  1101. toolbar.add_action(*m_new_directory_action);
  1102. toolbar.add_action(*m_save_action);
  1103. toolbar.add_action(*m_delete_action);
  1104. toolbar.add_separator();
  1105. m_cut_button = toolbar.add_action(current_editor().cut_action());
  1106. m_copy_button = toolbar.add_action(current_editor().copy_action());
  1107. m_paste_button = toolbar.add_action(current_editor().paste_action());
  1108. toolbar.add_separator();
  1109. toolbar.add_action(GUI::CommonActions::make_undo_action([this](auto&) { current_editor().undo_action().activate(); }, m_editors_splitter));
  1110. toolbar.add_action(GUI::CommonActions::make_redo_action([this](auto&) { current_editor().redo_action().activate(); }, m_editors_splitter));
  1111. toolbar.add_separator();
  1112. toolbar.add_action(*m_build_action);
  1113. toolbar.add_separator();
  1114. toolbar.add_action(*m_run_action);
  1115. toolbar.add_action(*m_stop_action);
  1116. toolbar.add_separator();
  1117. toolbar.add_action(*m_debug_action);
  1118. }
  1119. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_build_action()
  1120. {
  1121. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/build.png"sv));
  1122. return GUI::Action::create("&Build", { Mod_Ctrl, Key_B }, icon, [this](auto&) {
  1123. if (m_auto_save_before_build_or_run) {
  1124. if (!save_file_changes())
  1125. return;
  1126. } else {
  1127. if (warn_unsaved_changes("There are unsaved changes, do you want to save before building?") == ContinueDecision::No)
  1128. return;
  1129. }
  1130. reveal_action_tab(*m_terminal_wrapper);
  1131. build();
  1132. });
  1133. }
  1134. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_run_action()
  1135. {
  1136. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/program-run.png"sv));
  1137. return GUI::Action::create("&Run", { Mod_Ctrl, Key_R }, icon, [this](auto&) {
  1138. if (m_auto_save_before_build_or_run) {
  1139. if (!save_file_changes())
  1140. return;
  1141. } else {
  1142. if (warn_unsaved_changes("There are unsaved changes, do you want to save before running?") == ContinueDecision::No)
  1143. return;
  1144. }
  1145. reveal_action_tab(*m_terminal_wrapper);
  1146. run();
  1147. });
  1148. }
  1149. ErrorOr<void> HackStudioWidget::create_action_tab(GUI::Widget& parent)
  1150. {
  1151. m_action_tab_widget = parent.add<GUI::TabWidget>();
  1152. m_action_tab_widget->set_preferred_height(24);
  1153. m_action_tab_widget->on_change = [this](auto&) {
  1154. on_action_tab_change();
  1155. static bool first_time = true;
  1156. if (!first_time)
  1157. m_action_tab_widget->set_preferred_height(200);
  1158. first_time = false;
  1159. };
  1160. m_find_in_files_widget = m_action_tab_widget->add_tab<FindInFilesWidget>("Find"_string);
  1161. m_todo_entries_widget = m_action_tab_widget->add_tab<ToDoEntriesWidget>("TODO"_string);
  1162. m_terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Console"_string, false);
  1163. auto debug_info_widget = TRY(DebugInfoWidget::create());
  1164. m_action_tab_widget->add_tab(debug_info_widget, "Debug"_string);
  1165. m_debug_info_widget = debug_info_widget;
  1166. m_debug_info_widget->on_backtrace_frame_selection = [this](Debug::DebugInfo::SourcePosition const& source_position) {
  1167. open_file(get_absolute_path(source_position.file_path), source_position.line_number - 1);
  1168. };
  1169. m_disassembly_widget = m_action_tab_widget->add_tab<DisassemblyWidget>("Disassembly"_string);
  1170. m_git_widget = m_action_tab_widget->add_tab<GitWidget>("Git"_string);
  1171. m_git_widget->set_view_diff_callback([this](auto const& original_content, auto const& diff) {
  1172. m_diff_viewer->set_content(original_content, diff);
  1173. set_edit_mode(EditMode::Diff);
  1174. });
  1175. m_gml_preview_widget = m_action_tab_widget->add_tab<GMLPreviewWidget>("GML Preview"_string, "");
  1176. ToDoEntries::the().on_update = [this]() {
  1177. m_todo_entries_widget->refresh();
  1178. };
  1179. return {};
  1180. }
  1181. void HackStudioWidget::create_project_tab(GUI::Widget& parent)
  1182. {
  1183. m_project_tab = parent.add<GUI::TabWidget>();
  1184. m_project_tab->set_tab_position(TabPosition::Bottom);
  1185. auto& tree_view_container = m_project_tab->add_tab<GUI::Widget>("Files"_string);
  1186. tree_view_container.set_layout<GUI::VerticalBoxLayout>();
  1187. m_project_tree_view = tree_view_container.add<GUI::TreeView>();
  1188. configure_project_tree_view();
  1189. auto& class_view_container = m_project_tab->add_tab<GUI::Widget>("Classes"_string);
  1190. class_view_container.set_layout<GUI::VerticalBoxLayout>();
  1191. m_class_view = class_view_container.add<ClassViewWidget>();
  1192. ProjectDeclarations::the().on_update = [this]() {
  1193. m_class_view->refresh();
  1194. };
  1195. }
  1196. ErrorOr<void> HackStudioWidget::create_file_menu(GUI::Window& window)
  1197. {
  1198. auto file_menu = window.add_menu("&File"_string);
  1199. auto new_submenu = file_menu->add_submenu("&New..."_string);
  1200. new_submenu->add_action(*m_new_project_action);
  1201. new_submenu->add_separator();
  1202. for (auto& new_file_action : m_new_file_actions) {
  1203. new_submenu->add_action(new_file_action);
  1204. }
  1205. {
  1206. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/new.png"sv));
  1207. new_submenu->set_icon(icon);
  1208. }
  1209. new_submenu->add_action(*m_new_plain_file_action);
  1210. new_submenu->add_separator();
  1211. new_submenu->add_action(*m_new_directory_action);
  1212. file_menu->add_action(*m_open_action);
  1213. m_recent_projects_submenu = file_menu->add_submenu("Open &Recent"_string);
  1214. {
  1215. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/open-recent.png"sv));
  1216. m_recent_projects_submenu->set_icon(icon);
  1217. m_recent_projects_submenu->add_recent_files_list(
  1218. [this](GUI::Action& action) { open_project(action.text()); },
  1219. GUI::Menu::AddTrailingSeparator::No);
  1220. }
  1221. file_menu->add_action(*m_save_action);
  1222. file_menu->add_action(*m_save_as_action);
  1223. file_menu->add_separator();
  1224. file_menu->add_action(GUI::CommonActions::make_quit_action([](auto&) {
  1225. GUI::Application::the()->quit();
  1226. }));
  1227. return {};
  1228. }
  1229. ErrorOr<void> HackStudioWidget::create_edit_menu(GUI::Window& window)
  1230. {
  1231. auto edit_menu = window.add_menu("&Edit"_string);
  1232. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"sv));
  1233. edit_menu->add_action(GUI::Action::create("&Find in Files...", { Mod_Ctrl | Mod_Shift, Key_F }, icon, [this](auto&) {
  1234. reveal_action_tab(*m_find_in_files_widget);
  1235. m_find_in_files_widget->focus_textbox_and_select_all();
  1236. }));
  1237. edit_menu->add_separator();
  1238. auto vim_emulation_setting_action = GUI::Action::create_checkable("&Vim Emulation", { Mod_Ctrl | Mod_Shift | Mod_Alt, Key_V }, [this](auto& action) {
  1239. if (action.is_checked()) {
  1240. for (auto& editor_wrapper : m_all_editor_wrappers)
  1241. editor_wrapper->editor().set_editing_engine(make<GUI::VimEditingEngine>());
  1242. } else {
  1243. for (auto& editor_wrapper : m_all_editor_wrappers)
  1244. editor_wrapper->editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  1245. }
  1246. });
  1247. vim_emulation_setting_action->set_checked(false);
  1248. edit_menu->add_action(vim_emulation_setting_action);
  1249. auto auto_save_before_build_or_run_action = GUI::Action::create_checkable("&Auto Save before Build or Run", [this](auto& action) {
  1250. m_auto_save_before_build_or_run = action.is_checked();
  1251. Config::write_bool("HackStudio"sv, "Global"sv, "AutoSaveBeforeBuildOrRun"sv, m_auto_save_before_build_or_run);
  1252. });
  1253. m_auto_save_before_build_or_run = Config::read_bool("HackStudio"sv, "Global"sv, "AutoSaveBeforeBuildOrRun"sv, false);
  1254. auto_save_before_build_or_run_action->set_checked(m_auto_save_before_build_or_run);
  1255. edit_menu->add_action(auto_save_before_build_or_run_action);
  1256. edit_menu->add_separator();
  1257. edit_menu->add_action(*m_open_project_configuration_action);
  1258. return {};
  1259. }
  1260. void HackStudioWidget::create_build_menu(GUI::Window& window)
  1261. {
  1262. auto build_menu = window.add_menu("&Build"_string);
  1263. build_menu->add_action(*m_build_action);
  1264. build_menu->add_separator();
  1265. build_menu->add_action(*m_run_action);
  1266. build_menu->add_action(*m_stop_action);
  1267. build_menu->add_separator();
  1268. build_menu->add_action(*m_debug_action);
  1269. }
  1270. ErrorOr<void> HackStudioWidget::create_view_menu(GUI::Window& window)
  1271. {
  1272. auto hide_action_tabs_action = GUI::Action::create("&Hide Action Tabs", { Mod_Ctrl | Mod_Shift, Key_X }, [this](auto&) {
  1273. hide_action_tabs();
  1274. });
  1275. auto open_locator_action = GUI::Action::create("Open &Locator", { Mod_Ctrl, Key_K }, [this](auto&) {
  1276. m_locator->open();
  1277. });
  1278. auto show_dotfiles_action = GUI::Action::create_checkable("S&how Dotfiles", { Mod_Ctrl, Key_H }, [&](auto& checked) {
  1279. project().model().set_should_show_dotfiles(checked.is_checked());
  1280. Config::write_bool("HackStudio"sv, "Global"sv, "ShowDotfiles"sv, checked.is_checked());
  1281. });
  1282. show_dotfiles_action->set_checked(Config::read_bool("HackStudio"sv, "Global"sv, "ShowDotfiles"sv, false));
  1283. auto view_menu = window.add_menu("&View"_string);
  1284. view_menu->add_action(hide_action_tabs_action);
  1285. view_menu->add_action(open_locator_action);
  1286. view_menu->add_action(show_dotfiles_action);
  1287. m_toggle_semantic_highlighting_action = TRY(create_toggle_syntax_highlighting_mode_action());
  1288. view_menu->add_action(*m_toggle_semantic_highlighting_action);
  1289. m_toggle_view_file_in_single_click_action = TRY(create_toggle_open_file_in_single_click_action());
  1290. view_menu->add_action(*m_toggle_view_file_in_single_click_action);
  1291. view_menu->add_separator();
  1292. m_wrapping_mode_actions.set_exclusive(true);
  1293. auto wrapping_mode_menu = view_menu->add_submenu("&Wrapping Mode"_string);
  1294. m_no_wrapping_action = GUI::Action::create_checkable("&No Wrapping", [&](auto&) {
  1295. m_wrapping_mode = GUI::TextEditor::WrappingMode::NoWrap;
  1296. for (auto& wrapper : m_all_editor_wrappers)
  1297. wrapper->editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  1298. });
  1299. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap &Anywhere", [&](auto&) {
  1300. m_wrapping_mode = GUI::TextEditor::WrappingMode::WrapAnywhere;
  1301. for (auto& wrapper : m_all_editor_wrappers)
  1302. wrapper->editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  1303. });
  1304. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at &Words", [&](auto&) {
  1305. m_wrapping_mode = GUI::TextEditor::WrappingMode::WrapAtWords;
  1306. for (auto& wrapper : m_all_editor_wrappers)
  1307. wrapper->editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  1308. });
  1309. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  1310. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  1311. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  1312. wrapping_mode_menu->add_action(*m_no_wrapping_action);
  1313. wrapping_mode_menu->add_action(*m_wrap_anywhere_action);
  1314. wrapping_mode_menu->add_action(*m_wrap_at_words_action);
  1315. switch (m_wrapping_mode) {
  1316. case GUI::TextEditor::NoWrap:
  1317. m_no_wrapping_action->set_checked(true);
  1318. break;
  1319. case GUI::TextEditor::WrapAtWords:
  1320. m_wrap_at_words_action->set_checked(true);
  1321. break;
  1322. case GUI::TextEditor::WrapAnywhere:
  1323. m_wrap_anywhere_action->set_checked(true);
  1324. break;
  1325. }
  1326. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-font-editor.png"sv));
  1327. m_editor_font_action = GUI::Action::create("Change &Font...", icon,
  1328. [&](auto&) {
  1329. auto picker = GUI::FontPicker::construct(&window, m_editor_font, false);
  1330. if (picker->exec() == GUI::Dialog::ExecResult::OK) {
  1331. change_editor_font(picker->font());
  1332. }
  1333. });
  1334. view_menu->add_action(*m_editor_font_action);
  1335. view_menu->add_separator();
  1336. view_menu->add_action(*m_add_editor_tab_widget_action);
  1337. view_menu->add_action(*m_add_editor_action);
  1338. view_menu->add_action(*m_remove_current_editor_action);
  1339. view_menu->add_action(*m_add_terminal_action);
  1340. view_menu->add_action(*m_remove_current_terminal_action);
  1341. view_menu->add_separator();
  1342. TRY(create_location_history_actions());
  1343. view_menu->add_action(*m_locations_history_back_action);
  1344. view_menu->add_action(*m_locations_history_forward_action);
  1345. view_menu->add_separator();
  1346. view_menu->add_action(GUI::CommonActions::make_fullscreen_action([&](auto&) {
  1347. window.set_fullscreen(!window.is_fullscreen());
  1348. }));
  1349. return {};
  1350. }
  1351. void HackStudioWidget::create_help_menu(GUI::Window& window)
  1352. {
  1353. auto help_menu = window.add_menu("&Help"_string);
  1354. help_menu->add_action(GUI::CommonActions::make_command_palette_action(&window));
  1355. help_menu->add_action(GUI::CommonActions::make_about_action("Hack Studio"_string, GUI::Icon::default_icon("app-hack-studio"sv), &window));
  1356. }
  1357. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_stop_action()
  1358. {
  1359. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/program-stop.png"sv));
  1360. auto action = GUI::Action::create("&Stop", icon, [this](auto&) {
  1361. if (!Debugger::the().session()) {
  1362. if (auto result = m_terminal_wrapper->kill_running_command(); result.is_error())
  1363. warnln("{}", result.error());
  1364. return;
  1365. }
  1366. Debugger::the().stop();
  1367. });
  1368. action->set_enabled(false);
  1369. return action;
  1370. }
  1371. ErrorOr<void> HackStudioWidget::initialize_menubar(GUI::Window& window)
  1372. {
  1373. TRY(create_file_menu(window));
  1374. TRY(create_edit_menu(window));
  1375. create_build_menu(window);
  1376. TRY(create_view_menu(window));
  1377. create_help_menu(window);
  1378. return {};
  1379. }
  1380. void HackStudioWidget::update_statusbar()
  1381. {
  1382. StringBuilder builder;
  1383. if (current_editor().has_selection()) {
  1384. ByteString selected_text = current_editor().selected_text();
  1385. auto word_count = current_editor().number_of_selected_words();
  1386. builder.appendff("Selected: {:'d} {} ({:'d} {})", selected_text.length(), selected_text.length() == 1 ? "character" : "characters", word_count, word_count != 1 ? "words" : "word");
  1387. }
  1388. m_statusbar->set_text(0, builder.to_string().release_value_but_fixme_should_propagate_errors());
  1389. m_statusbar->set_text(1, String::from_utf8(Syntax::language_to_string(current_editor_wrapper().editor().code_document().language().value_or(Syntax::Language::PlainText))).release_value_but_fixme_should_propagate_errors());
  1390. m_statusbar->set_text(2, String::formatted("Ln {:'d} Col {:'d}", current_editor().cursor().line() + 1, current_editor().cursor().column()).release_value_but_fixme_should_propagate_errors());
  1391. }
  1392. void HackStudioWidget::handle_external_file_deletion(ByteString const& filepath)
  1393. {
  1394. close_file_in_all_editors(filepath);
  1395. }
  1396. void HackStudioWidget::stop_debugger_if_running()
  1397. {
  1398. if (!m_debugger_thread.is_null()) {
  1399. Debugger::the().stop();
  1400. dbgln("Waiting for debugger thread to terminate");
  1401. auto rc = m_debugger_thread->join();
  1402. if (rc.is_error()) {
  1403. warnln("pthread_join: {}", strerror(rc.error().value()));
  1404. dbgln("error joining debugger thread");
  1405. }
  1406. }
  1407. }
  1408. void HackStudioWidget::close_current_project()
  1409. {
  1410. m_editors_splitter->remove_all_children();
  1411. m_all_editor_tab_widgets.clear();
  1412. m_all_editor_wrappers.clear();
  1413. add_new_editor_tab_widget(*m_editors_splitter);
  1414. m_open_files.clear();
  1415. m_open_files_vector.clear();
  1416. m_find_in_files_widget->reset();
  1417. m_todo_entries_widget->clear();
  1418. m_terminal_wrapper->clear_including_history();
  1419. stop_debugger_if_running();
  1420. update_gml_preview();
  1421. }
  1422. HackStudioWidget::~HackStudioWidget()
  1423. {
  1424. stop_debugger_if_running();
  1425. }
  1426. HackStudioWidget::ContinueDecision HackStudioWidget::warn_unsaved_changes(ByteString const& prompt)
  1427. {
  1428. if (!any_document_is_dirty())
  1429. return ContinueDecision::Yes;
  1430. auto result = GUI::MessageBox::show(window(), prompt, "Unsaved Changes"sv, GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  1431. if (result == GUI::MessageBox::ExecResult::Cancel)
  1432. return ContinueDecision::No;
  1433. if (result == GUI::MessageBox::ExecResult::Yes) {
  1434. if (!save_file_changes())
  1435. return ContinueDecision::No;
  1436. }
  1437. return ContinueDecision::Yes;
  1438. }
  1439. bool HackStudioWidget::save_file_changes()
  1440. {
  1441. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1442. if (editor_wrapper->editor().document().is_modified()) {
  1443. if (!editor_wrapper->save())
  1444. return false;
  1445. }
  1446. }
  1447. return true;
  1448. }
  1449. bool HackStudioWidget::any_document_is_dirty() const
  1450. {
  1451. return any_of(m_all_editor_wrappers, [](auto& editor_wrapper) {
  1452. return editor_wrapper->editor().document().is_modified();
  1453. });
  1454. }
  1455. void HackStudioWidget::update_gml_preview()
  1456. {
  1457. auto gml_content = current_editor_wrapper().filename().ends_with(".gml"sv) ? current_editor_wrapper().editor().text() : ByteString::empty();
  1458. m_gml_preview_widget->load_gml(gml_content);
  1459. }
  1460. void HackStudioWidget::update_tree_view()
  1461. {
  1462. auto index = m_project->model().index(m_current_editor_wrapper->filename(), GUI::FileSystemModel::Column::Name);
  1463. if (index.is_valid()) {
  1464. m_project_tree_view->expand_all_parents_of(index);
  1465. m_project_tree_view->set_cursor(index, GUI::AbstractView::SelectionUpdate::Set);
  1466. }
  1467. }
  1468. void HackStudioWidget::update_toolbar_actions()
  1469. {
  1470. m_copy_button->set_action(current_editor().copy_action());
  1471. m_paste_button->set_action(current_editor().paste_action());
  1472. m_cut_button->set_action(current_editor().cut_action());
  1473. }
  1474. void HackStudioWidget::update_window_title()
  1475. {
  1476. window()->set_title(ByteString::formatted("{} - {} - Hack Studio", m_current_editor_wrapper->filename_title(), m_project->name()));
  1477. window()->set_modified(any_document_is_dirty());
  1478. }
  1479. void HackStudioWidget::update_current_editor_title()
  1480. {
  1481. current_editor_tab_widget().set_tab_title(current_editor_wrapper(), String::from_byte_string(current_editor_wrapper().filename_title()).release_value_but_fixme_should_propagate_errors());
  1482. }
  1483. void HackStudioWidget::on_cursor_change()
  1484. {
  1485. update_statusbar();
  1486. if (current_editor_wrapper().filename().is_empty())
  1487. return;
  1488. auto current_location = current_project_location();
  1489. if (m_locations_history_end_index != 0) {
  1490. auto last = m_locations_history[m_locations_history_end_index - 1];
  1491. if (current_location.filename == last.filename && current_location.line == last.line)
  1492. return;
  1493. }
  1494. // Clear "Go Forward" locations
  1495. VERIFY(m_locations_history_end_index <= m_locations_history.size());
  1496. m_locations_history.remove(m_locations_history_end_index, m_locations_history.size() - m_locations_history_end_index);
  1497. m_locations_history.append(current_location);
  1498. constexpr size_t max_locations = 30;
  1499. if (m_locations_history.size() > max_locations)
  1500. m_locations_history.take_first();
  1501. m_locations_history_end_index = m_locations_history.size();
  1502. update_history_actions();
  1503. }
  1504. ErrorOr<void> HackStudioWidget::create_location_history_actions()
  1505. {
  1506. {
  1507. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/go-back.png"sv));
  1508. m_locations_history_back_action = GUI::Action::create("Go Back", { Mod_Alt | Mod_Shift, Key_Left }, icon, [this](auto&) {
  1509. if (m_locations_history_end_index <= 1)
  1510. return;
  1511. auto location = m_locations_history[m_locations_history_end_index - 2];
  1512. --m_locations_history_end_index;
  1513. m_locations_history_disabled = true;
  1514. open_file(location.filename, location.line, location.column);
  1515. m_locations_history_disabled = false;
  1516. update_history_actions();
  1517. });
  1518. }
  1519. {
  1520. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"sv));
  1521. m_locations_history_forward_action = GUI::Action::create("Go Forward", { Mod_Alt | Mod_Shift, Key_Right }, icon, [this](auto&) {
  1522. if (m_locations_history_end_index == m_locations_history.size())
  1523. return;
  1524. auto location = m_locations_history[m_locations_history_end_index];
  1525. ++m_locations_history_end_index;
  1526. m_locations_history_disabled = true;
  1527. open_file(location.filename, location.line, location.column);
  1528. m_locations_history_disabled = false;
  1529. update_history_actions();
  1530. });
  1531. }
  1532. m_locations_history_forward_action->set_enabled(false);
  1533. return {};
  1534. }
  1535. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_open_project_configuration_action()
  1536. {
  1537. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/settings.png"sv));
  1538. return GUI::Action::create("Project Configuration", icon, [&](auto&) {
  1539. auto parent_directory = LexicalPath::dirname(Project::config_file_path);
  1540. auto absolute_config_file_path = LexicalPath::absolute_path(m_project->root_path(), Project::config_file_path);
  1541. ByteString formatted_error_string_holder;
  1542. auto save_configuration_or_error = [&]() -> ErrorOr<void> {
  1543. if (FileSystem::exists(absolute_config_file_path))
  1544. return {};
  1545. if (FileSystem::exists(parent_directory) && !FileSystem::is_directory(parent_directory)) {
  1546. formatted_error_string_holder = ByteString::formatted("Cannot create the '{}' directory because there is already a file with that name", parent_directory);
  1547. return Error::from_string_view(formatted_error_string_holder.view());
  1548. }
  1549. auto maybe_error = Core::System::mkdir(LexicalPath::absolute_path(m_project->root_path(), parent_directory), 0755);
  1550. if (maybe_error.is_error() && maybe_error.error().code() != EEXIST)
  1551. return maybe_error.release_error();
  1552. auto file = TRY(Core::File::open(absolute_config_file_path, Core::File::OpenMode::Write));
  1553. TRY(file->write_until_depleted(
  1554. "{\n"
  1555. " \"build_command\": \"your build command here\",\n"
  1556. " \"run_command\": \"your run command here\"\n"
  1557. "}\n"sv.bytes()));
  1558. return {};
  1559. }();
  1560. if (save_configuration_or_error.is_error()) {
  1561. GUI::MessageBox::show_error(window(), ByteString::formatted("Saving configuration failed: {}.", save_configuration_or_error.error()));
  1562. return;
  1563. }
  1564. open_file(Project::config_file_path);
  1565. });
  1566. }
  1567. HackStudioWidget::ProjectLocation HackStudioWidget::current_project_location() const
  1568. {
  1569. return ProjectLocation { current_editor_wrapper().filename(), current_editor().cursor().line(), current_editor().cursor().column() };
  1570. }
  1571. void HackStudioWidget::update_history_actions()
  1572. {
  1573. if (m_locations_history_end_index <= 1)
  1574. m_locations_history_back_action->set_enabled(false);
  1575. else
  1576. m_locations_history_back_action->set_enabled(true);
  1577. if (m_locations_history_end_index == m_locations_history.size())
  1578. m_locations_history_forward_action->set_enabled(false);
  1579. else
  1580. m_locations_history_forward_action->set_enabled(true);
  1581. }
  1582. RefPtr<Gfx::Font const> HackStudioWidget::read_editor_font_from_config()
  1583. {
  1584. auto font_family = Config::read_string("HackStudio"sv, "EditorFont"sv, "Family"sv);
  1585. auto font_variant = Config::read_string("HackStudio"sv, "EditorFont"sv, "Variant"sv);
  1586. auto font_size = Config::read_i32("HackStudio"sv, "EditorFont"sv, "Size"sv);
  1587. auto font = Gfx::FontDatabase::the().get(MUST(FlyString::from_deprecated_fly_string(font_family)), FlyString::from_deprecated_fly_string(font_variant).release_value_but_fixme_should_propagate_errors(), font_size);
  1588. if (font.is_null())
  1589. return Gfx::FontDatabase::the().default_fixed_width_font();
  1590. return font;
  1591. }
  1592. void HackStudioWidget::change_editor_font(RefPtr<Gfx::Font const> font)
  1593. {
  1594. m_editor_font = move(font);
  1595. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1596. editor_wrapper->editor().set_font(*m_editor_font);
  1597. }
  1598. Config::write_string("HackStudio"sv, "EditorFont"sv, "Family"sv, m_editor_font->family());
  1599. Config::write_string("HackStudio"sv, "EditorFont"sv, "Variant"sv, m_editor_font->variant());
  1600. Config::write_i32("HackStudio"sv, "EditorFont"sv, "Size"sv, m_editor_font->presentation_size());
  1601. }
  1602. void HackStudioWidget::open_coredump(StringView coredump_path)
  1603. {
  1604. open_project("/usr/src/serenity");
  1605. m_mode = Mode::Coredump;
  1606. m_coredump_inspector = Coredump::Inspector::create(coredump_path, [this](float progress) {
  1607. window()->set_progress(progress * 100);
  1608. });
  1609. window()->set_progress(0);
  1610. if (m_coredump_inspector) {
  1611. m_debug_info_widget->update_state(*m_coredump_inspector, m_coredump_inspector->get_registers());
  1612. reveal_action_tab(*m_debug_info_widget);
  1613. }
  1614. }
  1615. void HackStudioWidget::debug_process(pid_t pid)
  1616. {
  1617. open_project("/usr/src/serenity");
  1618. Debugger::the().set_pid_to_attach(pid);
  1619. m_debugger_thread = Threading::Thread::construct(Debugger::start_static);
  1620. m_debugger_thread->start();
  1621. m_stop_action->set_enabled(true);
  1622. m_run_action->set_enabled(false);
  1623. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1624. editor_wrapper->set_debug_mode(true);
  1625. }
  1626. }
  1627. void HackStudioWidget::for_each_open_file(Function<void(ProjectFile const&)> func)
  1628. {
  1629. for (auto& open_file : m_open_files) {
  1630. func(*open_file.value);
  1631. }
  1632. }
  1633. ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_toggle_syntax_highlighting_mode_action()
  1634. {
  1635. auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/filetype-cplusplus.png"sv));
  1636. auto action = GUI::Action::create_checkable("&Semantic Highlighting", icon, [this](auto& action) {
  1637. for (auto& editor_wrapper : m_all_editor_wrappers)
  1638. editor_wrapper->editor().set_semantic_syntax_highlighting(action.is_checked());
  1639. });
  1640. return action;
  1641. }
  1642. bool HackStudioWidget::semantic_syntax_highlighting_is_enabled() const
  1643. {
  1644. return m_toggle_semantic_highlighting_action->is_checked();
  1645. }
  1646. }