HackStudioWidget.cpp 77 KB

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