HackStudioWidget.cpp 78 KB

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