HackStudioWidget.cpp 74 KB

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