HackStudioWidget.cpp 72 KB

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