HackStudioWidget.cpp 69 KB

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