HackStudioWidget.cpp 78 KB

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