HackStudioWidget.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  4. * Copyright (c) 2020-2021, 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/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/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(const 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(5);
  88. auto& left_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  89. left_hand_splitter.layout()->set_spacing(5);
  90. left_hand_splitter.set_fixed_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_spacing(5);
  101. m_editors_splitter->layout()->set_margins({ 3, 0, 0 });
  102. add_new_editor(*m_editors_splitter);
  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_action = create_remove_current_editor_action();
  106. m_open_action = create_open_action();
  107. m_save_action = create_save_action();
  108. m_save_as_action = create_save_as_action();
  109. m_new_project_action = create_new_project_action();
  110. create_action_tab(*m_right_hand_splitter);
  111. m_add_editor_action = create_add_editor_action();
  112. m_add_terminal_action = create_add_terminal_action();
  113. m_remove_current_terminal_action = create_remove_current_terminal_action();
  114. m_locator = add<Locator>();
  115. m_terminal_wrapper->on_command_exit = [this] {
  116. m_stop_action->set_enabled(false);
  117. };
  118. m_build_action = create_build_action();
  119. m_run_action = create_run_action();
  120. m_stop_action = create_stop_action();
  121. m_debug_action = create_debug_action();
  122. initialize_debugger();
  123. create_toolbar(toolbar_container);
  124. m_statusbar = add<GUI::Statusbar>(3);
  125. auto maybe_watcher = Core::FileWatcher::create();
  126. if (maybe_watcher.is_error()) {
  127. warnln("Couldn't create a file watcher, deleted files won't be noticed! Error: {}", maybe_watcher.error());
  128. } else {
  129. m_file_watcher = maybe_watcher.release_value();
  130. m_file_watcher->on_change = [this](Core::FileWatcherEvent const& event) {
  131. if (event.type != Core::FileWatcherEvent::Type::Deleted)
  132. return;
  133. if (event.event_path.starts_with(project().root_path())) {
  134. String relative_path = LexicalPath::relative_path(event.event_path, project().root_path());
  135. handle_external_file_deletion(relative_path);
  136. } else {
  137. handle_external_file_deletion(event.event_path);
  138. }
  139. };
  140. }
  141. }
  142. void HackStudioWidget::update_actions()
  143. {
  144. auto is_remove_terminal_enabled = [this]() {
  145. auto widget = m_action_tab_widget->active_widget();
  146. if (!widget)
  147. return false;
  148. if ("TerminalWrapper"sv != widget->class_name())
  149. return false;
  150. if (!reinterpret_cast<TerminalWrapper*>(widget)->user_spawned())
  151. return false;
  152. return true;
  153. };
  154. m_remove_current_editor_action->set_enabled(m_all_editor_wrappers.size() > 1);
  155. m_remove_current_terminal_action->set_enabled(is_remove_terminal_enabled());
  156. }
  157. void HackStudioWidget::on_action_tab_change()
  158. {
  159. update_actions();
  160. if (auto* active_widget = m_action_tab_widget->active_widget()) {
  161. if (is<GitWidget>(*active_widget))
  162. static_cast<GitWidget&>(*active_widget).refresh();
  163. }
  164. }
  165. void HackStudioWidget::open_project(const String& root_path)
  166. {
  167. if (warn_unsaved_changes("There are unsaved changes, do you want to save before closing current project?") == ContinueDecision::No)
  168. return;
  169. if (chdir(root_path.characters()) < 0) {
  170. perror("chdir");
  171. exit(1);
  172. }
  173. if (m_project) {
  174. close_current_project();
  175. }
  176. m_project = Project::open_with_root_path(root_path);
  177. VERIFY(m_project);
  178. if (m_project_tree_view) {
  179. m_project_tree_view->set_model(m_project->model());
  180. m_project_tree_view->update();
  181. }
  182. if (m_git_widget) {
  183. m_git_widget->change_repo(LexicalPath(root_path));
  184. m_git_widget->refresh();
  185. }
  186. if (Debugger::is_initialized()) {
  187. auto& debugger = Debugger::the();
  188. debugger.reset_breakpoints();
  189. debugger.set_source_root(m_project->root_path());
  190. }
  191. for (auto& editor_wrapper : m_all_editor_wrappers)
  192. editor_wrapper.set_project_root(LexicalPath(m_project->root_path()));
  193. m_locations_history.clear();
  194. m_locations_history_end_index = 0;
  195. m_project->model().on_rename_successful = [this](auto& absolute_old_path, auto& absolute_new_path) {
  196. file_renamed(
  197. LexicalPath::relative_path(absolute_old_path, m_project->root_path()),
  198. LexicalPath::relative_path(absolute_new_path, m_project->root_path()));
  199. };
  200. }
  201. Vector<String> HackStudioWidget::selected_file_paths() const
  202. {
  203. Vector<String> files;
  204. m_project_tree_view->selection().for_each_index([&](const GUI::ModelIndex& index) {
  205. String sub_path = index.data().as_string();
  206. GUI::ModelIndex parent_or_invalid = index.parent();
  207. while (parent_or_invalid.is_valid()) {
  208. sub_path = String::formatted("{}/{}", parent_or_invalid.data().as_string(), sub_path);
  209. parent_or_invalid = parent_or_invalid.parent();
  210. }
  211. files.append(sub_path);
  212. });
  213. return files;
  214. }
  215. bool HackStudioWidget::open_file(const String& full_filename, size_t line, size_t column)
  216. {
  217. String filename = full_filename;
  218. if (full_filename.starts_with(project().root_path())) {
  219. filename = LexicalPath::relative_path(full_filename, project().root_path());
  220. }
  221. if (Core::File::is_directory(filename) || !Core::File::exists(filename))
  222. return false;
  223. if (!active_file().is_empty()) {
  224. // Since the file is previously open, it should always be in m_open_files.
  225. VERIFY(m_open_files.find(active_file()) != m_open_files.end());
  226. auto previous_open_project_file = m_open_files.get(active_file()).value();
  227. // Update the scrollbar values of the previous_open_project_file and save them to m_open_files.
  228. previous_open_project_file->vertical_scroll_value(current_editor().vertical_scrollbar().value());
  229. previous_open_project_file->horizontal_scroll_value(current_editor().horizontal_scrollbar().value());
  230. }
  231. RefPtr<ProjectFile> new_project_file = nullptr;
  232. if (auto it = m_open_files.find(filename); it != m_open_files.end()) {
  233. new_project_file = it->value;
  234. } else {
  235. new_project_file = m_project->create_file(filename);
  236. m_open_files.set(filename, *new_project_file);
  237. m_open_files_vector.append(filename);
  238. if (!m_file_watcher.is_null()) {
  239. auto watch_result = m_file_watcher->add_watch(filename, Core::FileWatcherEvent::Type::Deleted);
  240. if (watch_result.is_error()) {
  241. warnln("Couldn't watch '{}'", filename);
  242. }
  243. }
  244. m_open_files_view->model()->invalidate();
  245. }
  246. current_editor().on_cursor_change = nullptr; // Disable callback while we're swapping the document.
  247. current_editor().set_document(const_cast<GUI::TextDocument&>(new_project_file->document()));
  248. if (new_project_file->could_render_text()) {
  249. current_editor_wrapper().set_mode_displayable();
  250. } else {
  251. current_editor_wrapper().set_mode_non_displayable();
  252. }
  253. current_editor().horizontal_scrollbar().set_value(new_project_file->horizontal_scroll_value());
  254. current_editor().vertical_scrollbar().set_value(new_project_file->vertical_scroll_value());
  255. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  256. set_edit_mode(EditMode::Text);
  257. String relative_file_path = filename;
  258. if (filename.starts_with(m_project->root_path()))
  259. relative_file_path = filename.substring(m_project->root_path().length() + 1);
  260. m_project_tree_view->update();
  261. current_editor_wrapper().set_filename(filename);
  262. current_editor().set_focus(true);
  263. current_editor().on_cursor_change = [this] { on_cursor_change(); };
  264. current_editor_wrapper().on_change = [this] { update_gml_preview(); };
  265. current_editor().set_cursor(line, column);
  266. update_gml_preview();
  267. return true;
  268. }
  269. void HackStudioWidget::close_file_in_all_editors(String const& filename)
  270. {
  271. m_open_files.remove(filename);
  272. m_open_files_vector.remove_all_matching(
  273. [&filename](String const& element) { return element == filename; });
  274. for (auto& editor_wrapper : m_all_editor_wrappers) {
  275. Editor& editor = editor_wrapper.editor();
  276. String editor_file_path = editor.code_document().file_path();
  277. String relative_editor_file_path = LexicalPath::relative_path(editor_file_path, project().root_path());
  278. if (relative_editor_file_path == filename) {
  279. if (m_open_files_vector.is_empty()) {
  280. editor.set_document(CodeDocument::create());
  281. editor_wrapper.set_filename("");
  282. } else {
  283. auto& first_path = m_open_files_vector[0];
  284. auto& document = m_open_files.get(first_path).value()->code_document();
  285. editor.set_document(document);
  286. editor_wrapper.set_filename(first_path);
  287. }
  288. }
  289. }
  290. m_open_files_view->model()->invalidate();
  291. }
  292. EditorWrapper& HackStudioWidget::current_editor_wrapper()
  293. {
  294. VERIFY(m_current_editor_wrapper);
  295. return *m_current_editor_wrapper;
  296. }
  297. EditorWrapper const& HackStudioWidget::current_editor_wrapper() const
  298. {
  299. VERIFY(m_current_editor_wrapper);
  300. return *m_current_editor_wrapper;
  301. }
  302. GUI::TextEditor& HackStudioWidget::current_editor()
  303. {
  304. return current_editor_wrapper().editor();
  305. }
  306. GUI::TextEditor const& HackStudioWidget::current_editor() const
  307. {
  308. return current_editor_wrapper().editor();
  309. }
  310. void HackStudioWidget::set_edit_mode(EditMode mode)
  311. {
  312. if (mode == EditMode::Text) {
  313. m_right_hand_stack->set_active_widget(m_editors_splitter);
  314. } else if (mode == EditMode::Diff) {
  315. m_right_hand_stack->set_active_widget(m_diff_viewer);
  316. } else {
  317. VERIFY_NOT_REACHED();
  318. }
  319. m_right_hand_stack->active_widget()->update();
  320. }
  321. NonnullRefPtr<GUI::Menu> HackStudioWidget::create_project_tree_view_context_menu()
  322. {
  323. m_new_file_actions.append(create_new_file_action("C++ Source File", "/res/icons/16x16/filetype-cplusplus.png", "cpp"));
  324. m_new_file_actions.append(create_new_file_action("C++ Header File", "/res/icons/16x16/filetype-header.png", "h"));
  325. // FIXME: Create a file icon for GML files
  326. m_new_file_actions.append(create_new_file_action("GML File", "/res/icons/16x16/new.png", "gml"));
  327. m_new_file_actions.append(create_new_file_action("JavaScript Source File", "/res/icons/16x16/filetype-javascript.png", "js"));
  328. m_new_file_actions.append(create_new_file_action("HTML File", "/res/icons/16x16/filetype-html.png", "html"));
  329. // FIXME: Create a file icon for CSS files
  330. m_new_file_actions.append(create_new_file_action("CSS File", "/res/icons/16x16/new.png", "css"));
  331. m_new_plain_file_action = create_new_file_action("Plain File", "/res/icons/16x16/new.png", "");
  332. m_open_selected_action = create_open_selected_action();
  333. m_show_in_file_manager_action = create_show_in_file_manager_action();
  334. m_new_directory_action = create_new_directory_action();
  335. m_delete_action = create_delete_action();
  336. m_tree_view_rename_action = GUI::CommonActions::make_rename_action([this](GUI::Action const&) {
  337. m_project_tree_view->begin_editing(m_project_tree_view->cursor_index());
  338. });
  339. auto project_tree_view_context_menu = GUI::Menu::construct("Project Files");
  340. auto& new_file_submenu = project_tree_view_context_menu->add_submenu("New");
  341. for (auto& new_file_action : m_new_file_actions) {
  342. new_file_submenu.add_action(new_file_action);
  343. }
  344. new_file_submenu.add_action(*m_new_plain_file_action);
  345. new_file_submenu.add_separator();
  346. new_file_submenu.add_action(*m_new_directory_action);
  347. project_tree_view_context_menu->add_action(*m_open_selected_action);
  348. project_tree_view_context_menu->add_action(*m_show_in_file_manager_action);
  349. // TODO: Cut, copy, duplicate with new name...
  350. project_tree_view_context_menu->add_separator();
  351. project_tree_view_context_menu->add_action(*m_tree_view_rename_action);
  352. project_tree_view_context_menu->add_action(*m_delete_action);
  353. return project_tree_view_context_menu;
  354. }
  355. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_file_action(String const& label, String const& icon, String const& extension)
  356. {
  357. return GUI::Action::create(label, Gfx::Bitmap::try_load_from_file(icon), [this, extension](const GUI::Action&) {
  358. String filename;
  359. if (GUI::InputBox::show(window(), filename, "Enter name of new file:", "Add new file to project") != GUI::InputBox::ExecOK)
  360. return;
  361. if (!extension.is_empty() && !filename.ends_with(String::formatted(".{}", extension))) {
  362. filename = String::formatted("{}.{}", filename, extension);
  363. }
  364. auto path_to_selected = selected_file_paths();
  365. String filepath;
  366. if (!path_to_selected.is_empty()) {
  367. VERIFY(Core::File::exists(path_to_selected.first()));
  368. LexicalPath selected(path_to_selected.first());
  369. String dir_path;
  370. if (Core::File::is_directory(selected.string()))
  371. dir_path = selected.string();
  372. else
  373. dir_path = selected.dirname();
  374. filepath = String::formatted("{}/", dir_path);
  375. }
  376. filepath = String::formatted("{}{}", filepath, filename);
  377. auto file = Core::File::construct(filepath);
  378. if (!file->open((Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::MustBeNew))) {
  379. GUI::MessageBox::show(window(), String::formatted("Failed to create '{}'", filepath), "Error", GUI::MessageBox::Type::Error);
  380. return;
  381. }
  382. open_file(filepath);
  383. });
  384. }
  385. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_directory_action()
  386. {
  387. return GUI::Action::create("&New Directory...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/mkdir.png"), [this](const GUI::Action&) {
  388. String directory_name;
  389. if (GUI::InputBox::show(window(), directory_name, "Enter name of new directory:", "Add new folder to project") != GUI::InputBox::ExecOK)
  390. return;
  391. auto path_to_selected = selected_file_paths();
  392. if (!path_to_selected.is_empty()) {
  393. LexicalPath selected(path_to_selected.first());
  394. String dir_path;
  395. if (Core::File::is_directory(selected.string()))
  396. dir_path = selected.string();
  397. else
  398. dir_path = selected.dirname();
  399. directory_name = String::formatted("{}/{}", dir_path, directory_name);
  400. }
  401. auto formatted_dir_name = LexicalPath::canonicalized_path(String::formatted("{}/{}", m_project->model().root_path(), directory_name));
  402. int rc = mkdir(formatted_dir_name.characters(), 0755);
  403. if (rc < 0) {
  404. GUI::MessageBox::show(window(), "Failed to create new directory", "Error", GUI::MessageBox::Type::Error);
  405. return;
  406. }
  407. });
  408. }
  409. NonnullRefPtr<GUI::Action> HackStudioWidget::create_open_selected_action()
  410. {
  411. auto open_selected_action = GUI::Action::create("Open", [this](const GUI::Action&) {
  412. auto files = selected_file_paths();
  413. for (auto& file : files)
  414. open_file(file);
  415. });
  416. open_selected_action->set_enabled(true);
  417. return open_selected_action;
  418. }
  419. NonnullRefPtr<GUI::Action> HackStudioWidget::create_show_in_file_manager_action()
  420. {
  421. auto show_in_file_manager_action = GUI::Action::create("Show in File Manager", [this](const GUI::Action&) {
  422. auto files = selected_file_paths();
  423. for (auto& file : files)
  424. Desktop::Launcher::open(URL::create_with_file_protocol(m_project->root_path(), file));
  425. });
  426. show_in_file_manager_action->set_enabled(true);
  427. show_in_file_manager_action->set_icon(GUI::Icon::default_icon("app-file-manager").bitmap_for_size(16));
  428. return show_in_file_manager_action;
  429. }
  430. NonnullRefPtr<GUI::Action> HackStudioWidget::create_delete_action()
  431. {
  432. auto delete_action = GUI::CommonActions::make_delete_action([this](const GUI::Action&) {
  433. auto files = selected_file_paths();
  434. if (files.is_empty())
  435. return;
  436. String message;
  437. if (files.size() == 1) {
  438. LexicalPath file(files[0]);
  439. message = String::formatted("Really remove {} from disk?", file.basename());
  440. } else {
  441. message = String::formatted("Really remove {} files from disk?", files.size());
  442. }
  443. auto result = GUI::MessageBox::show(window(),
  444. message,
  445. "Confirm deletion",
  446. GUI::MessageBox::Type::Warning,
  447. GUI::MessageBox::InputType::OKCancel);
  448. if (result == GUI::MessageBox::ExecCancel)
  449. return;
  450. for (auto& file : files) {
  451. struct stat st;
  452. if (lstat(file.characters(), &st) < 0) {
  453. GUI::MessageBox::show(window(),
  454. String::formatted("lstat ({}) failed: {}", file, strerror(errno)),
  455. "Removal failed",
  456. GUI::MessageBox::Type::Error);
  457. break;
  458. }
  459. bool is_directory = S_ISDIR(st.st_mode);
  460. auto result = Core::File::remove(file, Core::File::RecursionMode::Allowed, false);
  461. if (result.is_error()) {
  462. auto& error = result.error();
  463. if (is_directory) {
  464. GUI::MessageBox::show(window(),
  465. String::formatted("Removing directory {} from the project failed: {}", error.file, error.error_code),
  466. "Removal failed",
  467. GUI::MessageBox::Type::Error);
  468. } else {
  469. GUI::MessageBox::show(window(),
  470. String::formatted("Removing file {} from the project failed: {}", error.file, error.error_code),
  471. "Removal failed",
  472. GUI::MessageBox::Type::Error);
  473. }
  474. }
  475. }
  476. });
  477. delete_action->set_enabled(false);
  478. return delete_action;
  479. }
  480. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_project_action()
  481. {
  482. return GUI::Action::create("&New Project...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/hackstudio-project.png"), [this](const GUI::Action&) {
  483. auto dialog = NewProjectDialog::construct(window());
  484. dialog->set_icon(window()->icon());
  485. auto result = dialog->exec();
  486. if (result == GUI::Dialog::ExecResult::ExecOK && dialog->created_project_path().has_value())
  487. open_project(dialog->created_project_path().value());
  488. });
  489. }
  490. void HackStudioWidget::add_new_editor(GUI::Widget& parent)
  491. {
  492. auto wrapper = EditorWrapper::construct();
  493. if (m_action_tab_widget) {
  494. parent.insert_child_before(wrapper, *m_action_tab_widget);
  495. } else {
  496. parent.add_child(wrapper);
  497. }
  498. m_current_editor_wrapper = wrapper;
  499. m_all_editor_wrappers.append(wrapper);
  500. wrapper->editor().set_focus(true);
  501. wrapper->editor().set_font(*m_editor_font);
  502. wrapper->set_project_root(LexicalPath(m_project->root_path()));
  503. wrapper->editor().on_cursor_change = [this] { on_cursor_change(); };
  504. wrapper->on_change = [this] { update_gml_preview(); };
  505. set_edit_mode(EditMode::Text);
  506. }
  507. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_next_editor_action()
  508. {
  509. return GUI::Action::create("Switch to &Next Editor", { Mod_Ctrl, Key_E }, [this](auto&) {
  510. if (m_all_editor_wrappers.size() <= 1)
  511. return;
  512. Vector<EditorWrapper&> wrappers;
  513. m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) {
  514. wrappers.append(child);
  515. return IterationDecision::Continue;
  516. });
  517. for (size_t i = 0; i < wrappers.size(); ++i) {
  518. if (m_current_editor_wrapper.ptr() == &wrappers[i]) {
  519. if (i == wrappers.size() - 1)
  520. wrappers[0].editor().set_focus(true);
  521. else
  522. wrappers[i + 1].editor().set_focus(true);
  523. }
  524. }
  525. });
  526. }
  527. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_previous_editor_action()
  528. {
  529. return GUI::Action::create("Switch to &Previous Editor", { Mod_Ctrl | Mod_Shift, Key_E }, [this](auto&) {
  530. if (m_all_editor_wrappers.size() <= 1)
  531. return;
  532. Vector<EditorWrapper&> wrappers;
  533. m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) {
  534. wrappers.append(child);
  535. return IterationDecision::Continue;
  536. });
  537. for (int i = wrappers.size() - 1; i >= 0; --i) {
  538. if (m_current_editor_wrapper.ptr() == &wrappers[i]) {
  539. if (i == 0)
  540. wrappers.last().editor().set_focus(true);
  541. else
  542. wrappers[i - 1].editor().set_focus(true);
  543. }
  544. }
  545. });
  546. }
  547. NonnullRefPtr<GUI::Action> HackStudioWidget::create_remove_current_editor_action()
  548. {
  549. return GUI::Action::create("&Remove Current Editor", { Mod_Alt | Mod_Shift, Key_E }, [this](auto&) {
  550. if (m_all_editor_wrappers.size() <= 1)
  551. return;
  552. auto wrapper = m_current_editor_wrapper;
  553. m_switch_to_next_editor->activate();
  554. m_editors_splitter->remove_child(*wrapper);
  555. auto child_editors = m_editors_splitter->child_widgets();
  556. bool has_child_to_fill_space = false;
  557. for (auto& editor : child_editors) {
  558. if (editor.max_height() == -1) {
  559. has_child_to_fill_space = true;
  560. break;
  561. }
  562. }
  563. if (!has_child_to_fill_space)
  564. child_editors.last().set_max_height(-1);
  565. m_all_editor_wrappers.remove_first_matching([&wrapper](auto& entry) { return entry == wrapper.ptr(); });
  566. update_actions();
  567. });
  568. }
  569. NonnullRefPtr<GUI::Action> HackStudioWidget::create_open_action()
  570. {
  571. return GUI::Action::create("&Open Project...", { Mod_Ctrl | Mod_Shift, Key_O }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/open.png"), [this](auto&) {
  572. auto open_path = GUI::FilePicker::get_open_filepath(window(), "Open project", m_project->root_path(), true);
  573. if (!open_path.has_value())
  574. return;
  575. open_project(open_path.value());
  576. update_actions();
  577. });
  578. }
  579. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_action()
  580. {
  581. return GUI::CommonActions::make_save_action([&](auto&) {
  582. if (active_file().is_empty())
  583. m_save_as_action->activate();
  584. current_editor_wrapper().save();
  585. if (m_git_widget->initialized())
  586. m_git_widget->refresh();
  587. });
  588. }
  589. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_as_action()
  590. {
  591. return GUI::CommonActions::make_save_as_action([&](auto&) {
  592. auto const old_filename = current_editor_wrapper().filename();
  593. LexicalPath const old_path(old_filename);
  594. Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(),
  595. old_filename.is_null() ? "Untitled" : old_path.title(),
  596. old_filename.is_null() ? "txt" : old_path.extension(),
  597. Core::File::absolute_path(old_path.dirname()));
  598. if (!save_path.has_value()) {
  599. return;
  600. }
  601. String const relative_file_path = LexicalPath::relative_path(save_path.value(), m_project->root_path());
  602. if (current_editor_wrapper().filename().is_null()) {
  603. current_editor_wrapper().set_filename(relative_file_path);
  604. } else {
  605. for (auto& editor_wrapper : m_all_editor_wrappers) {
  606. if (editor_wrapper.filename() == old_filename)
  607. editor_wrapper.set_filename(relative_file_path);
  608. }
  609. }
  610. current_editor_wrapper().save();
  611. auto new_project_file = m_project->create_file(relative_file_path);
  612. m_open_files.set(relative_file_path, *new_project_file);
  613. m_open_files.remove(old_filename);
  614. m_open_files_vector.append(relative_file_path);
  615. m_open_files_vector.remove_all_matching([&old_filename](auto const& element) { return element == old_filename; });
  616. update_window_title();
  617. m_project->model().invalidate();
  618. update_tree_view();
  619. });
  620. }
  621. NonnullRefPtr<GUI::Action> HackStudioWidget::create_remove_current_terminal_action()
  622. {
  623. return GUI::Action::create("Remove &Current Terminal", { Mod_Alt | Mod_Shift, Key_T }, [this](auto&) {
  624. auto widget = m_action_tab_widget->active_widget();
  625. if (!widget)
  626. return;
  627. if (!is<TerminalWrapper>(widget))
  628. return;
  629. auto& terminal = *static_cast<TerminalWrapper*>(widget);
  630. if (!terminal.user_spawned())
  631. return;
  632. m_action_tab_widget->remove_tab(terminal);
  633. update_actions();
  634. });
  635. }
  636. NonnullRefPtr<GUI::Action> HackStudioWidget::create_add_editor_action()
  637. {
  638. return GUI::Action::create("Add New &Editor", { Mod_Ctrl | Mod_Alt, Key_E },
  639. Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-text-editor.png"),
  640. [this](auto&) {
  641. add_new_editor(*m_editors_splitter);
  642. update_actions();
  643. });
  644. }
  645. NonnullRefPtr<GUI::Action> HackStudioWidget::create_add_terminal_action()
  646. {
  647. return GUI::Action::create("Add New &Terminal", { Mod_Ctrl | Mod_Alt, Key_T },
  648. Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-terminal.png"),
  649. [this](auto&) {
  650. auto& terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Terminal");
  651. reveal_action_tab(terminal_wrapper);
  652. update_actions();
  653. terminal_wrapper.terminal().set_focus(true);
  654. });
  655. }
  656. void HackStudioWidget::reveal_action_tab(GUI::Widget& widget)
  657. {
  658. if (m_action_tab_widget->min_height() < 200)
  659. m_action_tab_widget->set_fixed_height(200);
  660. m_action_tab_widget->set_active_widget(&widget);
  661. }
  662. NonnullRefPtr<GUI::Action> HackStudioWidget::create_debug_action()
  663. {
  664. return GUI::Action::create("&Debug", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/debug-run.png"), [this](auto&) {
  665. if (!Core::File::exists(get_project_executable_path())) {
  666. GUI::MessageBox::show(window(), String::formatted("Could not find file: {}. (did you build the project?)", get_project_executable_path()), "Error", GUI::MessageBox::Type::Error);
  667. return;
  668. }
  669. if (Debugger::the().session()) {
  670. GUI::MessageBox::show(window(), "Debugger is already running", "Error", GUI::MessageBox::Type::Error);
  671. return;
  672. }
  673. Debugger::the().set_executable_path(get_project_executable_path());
  674. m_debugger_thread = Threading::Thread::construct(Debugger::start_static);
  675. m_debugger_thread->start();
  676. m_stop_action->set_enabled(true);
  677. m_run_action->set_enabled(false);
  678. for (auto& editor_wrapper : m_all_editor_wrappers) {
  679. editor_wrapper.set_debug_mode(true);
  680. }
  681. });
  682. }
  683. void HackStudioWidget::initialize_debugger()
  684. {
  685. Debugger::initialize(
  686. m_project->root_path(),
  687. [this](const PtraceRegisters& regs) {
  688. VERIFY(Debugger::the().session());
  689. const auto& debug_session = *Debugger::the().session();
  690. auto source_position = debug_session.get_source_position(regs.ip());
  691. if (!source_position.has_value()) {
  692. dbgln("Could not find source position for address: {:p}", regs.ip());
  693. return Debugger::HasControlPassedToUser::No;
  694. }
  695. dbgln("Debugger stopped at source position: {}:{}", source_position.value().file_path, source_position.value().line_number);
  696. deferred_invoke([this, source_position, &regs] {
  697. m_current_editor_in_execution = get_editor_of_file(source_position.value().file_path);
  698. if (m_current_editor_in_execution)
  699. m_current_editor_in_execution->editor().set_execution_position(source_position.value().line_number - 1);
  700. m_debug_info_widget->update_state(*Debugger::the().session(), regs);
  701. m_debug_info_widget->set_debug_actions_enabled(true);
  702. m_disassembly_widget->update_state(*Debugger::the().session(), regs);
  703. HackStudioWidget::reveal_action_tab(*m_debug_info_widget);
  704. });
  705. Core::EventLoop::wake();
  706. return Debugger::HasControlPassedToUser::Yes;
  707. },
  708. [this]() {
  709. deferred_invoke([this] {
  710. m_debug_info_widget->set_debug_actions_enabled(false);
  711. if (m_current_editor_in_execution)
  712. m_current_editor_in_execution->editor().clear_execution_position();
  713. });
  714. Core::EventLoop::wake();
  715. },
  716. [this]() {
  717. deferred_invoke([this] {
  718. m_debug_info_widget->set_debug_actions_enabled(false);
  719. if (m_current_editor_in_execution)
  720. m_current_editor_in_execution->editor().clear_execution_position();
  721. m_debug_info_widget->program_stopped();
  722. m_disassembly_widget->program_stopped();
  723. m_stop_action->set_enabled(false);
  724. m_run_action->set_enabled(true);
  725. m_debugger_thread.clear();
  726. for (auto& editor_wrapper : m_all_editor_wrappers) {
  727. editor_wrapper.set_debug_mode(false);
  728. }
  729. HackStudioWidget::hide_action_tabs();
  730. GUI::MessageBox::show(window(), "Program Exited", "Debugger", GUI::MessageBox::Type::Information);
  731. });
  732. Core::EventLoop::wake();
  733. });
  734. }
  735. String HackStudioWidget::get_full_path_of_serenity_source(const String& file)
  736. {
  737. auto path_parts = LexicalPath(file).parts();
  738. VERIFY(path_parts[0] == "..");
  739. path_parts.remove(0);
  740. StringBuilder relative_path_builder;
  741. relative_path_builder.join("/", path_parts);
  742. constexpr char SERENITY_LIBS_PREFIX[] = "/usr/src/serenity";
  743. LexicalPath serenity_sources_base(SERENITY_LIBS_PREFIX);
  744. return String::formatted("{}/{}", serenity_sources_base, relative_path_builder.to_string());
  745. }
  746. RefPtr<EditorWrapper> HackStudioWidget::get_editor_of_file(const String& filename)
  747. {
  748. String file_path = filename;
  749. // TODO: We can probably do a more specific condition here, something like
  750. // "if (file.starts_with("../Libraries/") || file.starts_with("../AK/"))"
  751. if (filename.starts_with("../")) {
  752. file_path = get_full_path_of_serenity_source(filename);
  753. }
  754. if (!open_file(file_path))
  755. return nullptr;
  756. return current_editor_wrapper();
  757. }
  758. String HackStudioWidget::get_project_executable_path() const
  759. {
  760. // FIXME: Dumb heuristic ahead!
  761. // e.g /my/project => /my/project/project
  762. // TODO: Perhaps a Makefile rule for getting the value of $(PROGRAM) would be better?
  763. return String::formatted("{}/{}", m_project->root_path(), LexicalPath::basename(m_project->root_path()));
  764. }
  765. void HackStudioWidget::build(TerminalWrapper& wrapper)
  766. {
  767. if (active_file().ends_with(".js"))
  768. wrapper.run_command(String::formatted("js -A {}", active_file()));
  769. else
  770. wrapper.run_command("make");
  771. }
  772. void HackStudioWidget::run(TerminalWrapper& wrapper)
  773. {
  774. if (active_file().ends_with(".js"))
  775. wrapper.run_command(String::formatted("js {}", active_file()));
  776. else
  777. wrapper.run_command("make run");
  778. }
  779. void HackStudioWidget::hide_action_tabs()
  780. {
  781. m_action_tab_widget->set_fixed_height(24);
  782. };
  783. Project& HackStudioWidget::project()
  784. {
  785. return *m_project;
  786. }
  787. void HackStudioWidget::set_current_editor_wrapper(RefPtr<EditorWrapper> editor_wrapper)
  788. {
  789. m_current_editor_wrapper = editor_wrapper;
  790. update_window_title();
  791. update_tree_view();
  792. }
  793. void HackStudioWidget::file_renamed(String const& old_name, String const& new_name)
  794. {
  795. auto editor_or_none = m_all_editor_wrappers.first_matching([&old_name](auto const& editor) {
  796. return editor->filename() == old_name;
  797. });
  798. if (editor_or_none.has_value()) {
  799. (*editor_or_none)->set_filename(new_name);
  800. (*editor_or_none)->set_name(new_name);
  801. }
  802. if (m_open_files.contains(old_name)) {
  803. VERIFY(m_open_files_vector.remove_first_matching([&old_name](auto const& file) { return file == old_name; }));
  804. m_open_files_vector.append(new_name);
  805. ProjectFile* f = m_open_files.get(old_name).release_value();
  806. m_open_files.set(new_name, *f);
  807. m_open_files.remove(old_name);
  808. m_open_files_view->model()->invalidate();
  809. }
  810. if (m_file_watcher->is_watching(old_name)) {
  811. VERIFY(!m_file_watcher->remove_watch(old_name).is_error());
  812. VERIFY(!m_file_watcher->add_watch(new_name, Core::FileWatcherEvent::Type::Deleted).is_error());
  813. }
  814. }
  815. void HackStudioWidget::configure_project_tree_view()
  816. {
  817. m_project_tree_view->set_model(m_project->model());
  818. m_project_tree_view->set_selection_mode(GUI::AbstractView::SelectionMode::MultiSelection);
  819. m_project_tree_view->set_editable(true);
  820. m_project_tree_view->aid_create_editing_delegate = [](auto&) {
  821. return make<GUI::StringModelEditingDelegate>();
  822. };
  823. for (int column_index = 0; column_index < m_project->model().column_count(); ++column_index)
  824. m_project_tree_view->set_column_visible(column_index, false);
  825. m_project_tree_view->set_column_visible(GUI::FileSystemModel::Column::Name, true);
  826. m_project_tree_view->on_context_menu_request = [this](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  827. if (index.is_valid()) {
  828. m_project_tree_view_context_menu->popup(event.screen_position(), m_open_selected_action);
  829. }
  830. };
  831. m_project_tree_view->on_selection_change = [this] {
  832. m_open_selected_action->set_enabled(!m_project_tree_view->selection().is_empty());
  833. auto selections = m_project_tree_view->selection().indices();
  834. auto it = selections.find_if([&](auto selected_file) {
  835. return access(m_project->model().full_path(selected_file.parent()).characters(), W_OK) == 0;
  836. });
  837. bool has_permissions = it != selections.end();
  838. m_delete_action->set_enabled(!m_project_tree_view->selection().is_empty() && has_permissions);
  839. };
  840. m_project_tree_view->on_activation = [this](auto& index) {
  841. auto full_path_to_file = m_project->model().full_path(index);
  842. open_file(full_path_to_file);
  843. };
  844. }
  845. void HackStudioWidget::create_open_files_view(GUI::Widget& parent)
  846. {
  847. m_open_files_view = parent.add<GUI::ListView>();
  848. auto open_files_model = GUI::ItemListModel<String>::create(m_open_files_vector);
  849. m_open_files_view->set_model(open_files_model);
  850. m_open_files_view->on_activation = [this](auto& index) {
  851. open_file(index.data().to_string());
  852. };
  853. }
  854. void HackStudioWidget::create_toolbar(GUI::Widget& parent)
  855. {
  856. auto& toolbar = parent.add<GUI::Toolbar>();
  857. toolbar.add_action(*m_new_plain_file_action);
  858. toolbar.add_action(*m_new_directory_action);
  859. toolbar.add_action(*m_save_action);
  860. toolbar.add_action(*m_delete_action);
  861. toolbar.add_separator();
  862. toolbar.add_action(GUI::CommonActions::make_cut_action([this](auto&) { current_editor().cut_action().activate(); }));
  863. toolbar.add_action(GUI::CommonActions::make_copy_action([this](auto&) { current_editor().copy_action().activate(); }));
  864. toolbar.add_action(GUI::CommonActions::make_paste_action([this](auto&) { current_editor().paste_action().activate(); }));
  865. toolbar.add_separator();
  866. toolbar.add_action(GUI::CommonActions::make_undo_action([this](auto&) { current_editor().undo_action().activate(); }));
  867. toolbar.add_action(GUI::CommonActions::make_redo_action([this](auto&) { current_editor().redo_action().activate(); }));
  868. toolbar.add_separator();
  869. toolbar.add_action(*m_build_action);
  870. toolbar.add_separator();
  871. toolbar.add_action(*m_run_action);
  872. toolbar.add_action(*m_stop_action);
  873. toolbar.add_separator();
  874. toolbar.add_action(*m_debug_action);
  875. }
  876. NonnullRefPtr<GUI::Action> HackStudioWidget::create_build_action()
  877. {
  878. return GUI::Action::create("&Build", { Mod_Ctrl, Key_B }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/build.png"), [this](auto&) {
  879. if (warn_unsaved_changes("There are unsaved changes, do you want to save before building?") == ContinueDecision::No)
  880. return;
  881. reveal_action_tab(*m_terminal_wrapper);
  882. build(*m_terminal_wrapper);
  883. m_stop_action->set_enabled(true);
  884. });
  885. }
  886. NonnullRefPtr<GUI::Action> HackStudioWidget::create_run_action()
  887. {
  888. return GUI::Action::create("&Run", { Mod_Ctrl, Key_R }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-run.png"), [this](auto&) {
  889. reveal_action_tab(*m_terminal_wrapper);
  890. run(*m_terminal_wrapper);
  891. m_stop_action->set_enabled(true);
  892. });
  893. }
  894. void HackStudioWidget::create_action_tab(GUI::Widget& parent)
  895. {
  896. m_action_tab_widget = parent.add<GUI::TabWidget>();
  897. m_action_tab_widget->set_fixed_height(24);
  898. m_action_tab_widget->on_change = [this](auto&) {
  899. on_action_tab_change();
  900. static bool first_time = true;
  901. if (!first_time)
  902. m_action_tab_widget->set_fixed_height(200);
  903. first_time = false;
  904. };
  905. m_find_in_files_widget = m_action_tab_widget->add_tab<FindInFilesWidget>("Find in files");
  906. m_todo_entries_widget = m_action_tab_widget->add_tab<ToDoEntriesWidget>("TODO");
  907. m_terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Build", false);
  908. m_debug_info_widget = m_action_tab_widget->add_tab<DebugInfoWidget>("Debug");
  909. m_disassembly_widget = m_action_tab_widget->add_tab<DisassemblyWidget>("Disassembly");
  910. m_git_widget = m_action_tab_widget->add_tab<GitWidget>("Git", LexicalPath(m_project->root_path()));
  911. m_git_widget->set_view_diff_callback([this](const auto& original_content, const auto& diff) {
  912. m_diff_viewer->set_content(original_content, diff);
  913. set_edit_mode(EditMode::Diff);
  914. });
  915. m_gml_preview_widget = m_action_tab_widget->add_tab<GMLPreviewWidget>("GML Preview", "");
  916. ToDoEntries::the().on_update = [this]() {
  917. m_todo_entries_widget->refresh();
  918. };
  919. }
  920. void HackStudioWidget::create_project_tab(GUI::Widget& parent)
  921. {
  922. m_project_tab = parent.add<GUI::TabWidget>();
  923. m_project_tab->set_tab_position(GUI::TabWidget::TabPosition::Bottom);
  924. auto& tree_view_container = m_project_tab->add_tab<GUI::Widget>("Files");
  925. tree_view_container.set_layout<GUI::VerticalBoxLayout>();
  926. tree_view_container.layout()->set_margins(2);
  927. m_project_tree_view = tree_view_container.add<GUI::TreeView>();
  928. configure_project_tree_view();
  929. auto& class_view_container = m_project_tab->add_tab<GUI::Widget>("Classes");
  930. class_view_container.set_layout<GUI::VerticalBoxLayout>();
  931. class_view_container.layout()->set_margins(2);
  932. m_class_view = class_view_container.add<ClassViewWidget>();
  933. ProjectDeclarations::the().on_update = [this]() {
  934. m_class_view->refresh();
  935. };
  936. }
  937. void HackStudioWidget::create_file_menu(GUI::Window& window)
  938. {
  939. auto& file_menu = window.add_menu("&File");
  940. file_menu.add_action(*m_new_project_action);
  941. file_menu.add_action(*m_open_action);
  942. file_menu.add_action(*m_save_action);
  943. file_menu.add_action(*m_save_as_action);
  944. file_menu.add_separator();
  945. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  946. GUI::Application::the()->quit();
  947. }));
  948. }
  949. void HackStudioWidget::create_project_menu(GUI::Window& window)
  950. {
  951. auto& project_menu = window.add_menu("&Project");
  952. auto& new_submenu = project_menu.add_submenu("New");
  953. for (auto& new_file_action : m_new_file_actions) {
  954. new_submenu.add_action(new_file_action);
  955. }
  956. new_submenu.add_action(*m_new_plain_file_action);
  957. new_submenu.add_separator();
  958. new_submenu.add_action(*m_new_directory_action);
  959. }
  960. void HackStudioWidget::create_edit_menu(GUI::Window& window)
  961. {
  962. auto& edit_menu = window.add_menu("&Edit");
  963. 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"), [this](auto&) {
  964. reveal_action_tab(*m_find_in_files_widget);
  965. m_find_in_files_widget->focus_textbox_and_select_all();
  966. }));
  967. edit_menu.add_separator();
  968. auto vim_emulation_setting_action = GUI::Action::create_checkable("&Vim Emulation", { Mod_Ctrl | Mod_Shift | Mod_Alt, Key_V }, [this](auto& action) {
  969. if (action.is_checked())
  970. current_editor().set_editing_engine(make<GUI::VimEditingEngine>());
  971. else
  972. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  973. });
  974. vim_emulation_setting_action->set_checked(false);
  975. edit_menu.add_action(vim_emulation_setting_action);
  976. }
  977. void HackStudioWidget::create_build_menu(GUI::Window& window)
  978. {
  979. auto& build_menu = window.add_menu("&Build");
  980. build_menu.add_action(*m_build_action);
  981. build_menu.add_separator();
  982. build_menu.add_action(*m_run_action);
  983. build_menu.add_action(*m_stop_action);
  984. build_menu.add_separator();
  985. build_menu.add_action(*m_debug_action);
  986. }
  987. void HackStudioWidget::create_view_menu(GUI::Window& window)
  988. {
  989. auto hide_action_tabs_action = GUI::Action::create("&Hide Action Tabs", { Mod_Ctrl | Mod_Shift, Key_X }, [this](auto&) {
  990. hide_action_tabs();
  991. });
  992. auto open_locator_action = GUI::Action::create("Open &Locator", { Mod_Ctrl, Key_K }, [this](auto&) {
  993. m_locator->open();
  994. });
  995. auto show_dotfiles_action = GUI::Action::create_checkable("S&how Dotfiles", { Mod_Ctrl, Key_H }, [&](auto& checked) {
  996. project().model().set_should_show_dotfiles(checked.is_checked());
  997. });
  998. auto& view_menu = window.add_menu("&View");
  999. view_menu.add_action(hide_action_tabs_action);
  1000. view_menu.add_action(open_locator_action);
  1001. view_menu.add_action(show_dotfiles_action);
  1002. view_menu.add_separator();
  1003. m_wrapping_mode_actions.set_exclusive(true);
  1004. auto& wrapping_mode_menu = view_menu.add_submenu("&Wrapping Mode");
  1005. m_no_wrapping_action = GUI::Action::create_checkable("&No Wrapping", [&](auto&) {
  1006. for (auto& wrapper : m_all_editor_wrappers)
  1007. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  1008. });
  1009. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap &Anywhere", [&](auto&) {
  1010. for (auto& wrapper : m_all_editor_wrappers)
  1011. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  1012. });
  1013. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at &Words", [&](auto&) {
  1014. for (auto& wrapper : m_all_editor_wrappers)
  1015. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  1016. });
  1017. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  1018. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  1019. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  1020. wrapping_mode_menu.add_action(*m_no_wrapping_action);
  1021. wrapping_mode_menu.add_action(*m_wrap_anywhere_action);
  1022. wrapping_mode_menu.add_action(*m_wrap_at_words_action);
  1023. m_no_wrapping_action->set_checked(true);
  1024. m_editor_font_action = GUI::Action::create("Editor &Font...", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-font-editor.png"),
  1025. [&](auto&) {
  1026. auto picker = GUI::FontPicker::construct(&window, m_editor_font, false);
  1027. if (picker->exec() == GUI::Dialog::ExecOK) {
  1028. change_editor_font(picker->font());
  1029. }
  1030. });
  1031. view_menu.add_action(*m_editor_font_action);
  1032. view_menu.add_separator();
  1033. view_menu.add_action(*m_add_editor_action);
  1034. view_menu.add_action(*m_remove_current_editor_action);
  1035. view_menu.add_action(*m_add_terminal_action);
  1036. view_menu.add_action(*m_remove_current_terminal_action);
  1037. view_menu.add_separator();
  1038. create_location_history_actions();
  1039. view_menu.add_action(*m_locations_history_back_action);
  1040. view_menu.add_action(*m_locations_history_forward_action);
  1041. }
  1042. void HackStudioWidget::create_help_menu(GUI::Window& window)
  1043. {
  1044. auto& help_menu = window.add_menu("&Help");
  1045. help_menu.add_action(GUI::CommonActions::make_about_action("Hack Studio", GUI::Icon::default_icon("app-hack-studio"), &window));
  1046. }
  1047. NonnullRefPtr<GUI::Action> HackStudioWidget::create_stop_action()
  1048. {
  1049. auto action = GUI::Action::create("&Stop", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-stop.png"), [this](auto&) {
  1050. if (!Debugger::the().session()) {
  1051. m_terminal_wrapper->kill_running_command();
  1052. return;
  1053. }
  1054. Debugger::the().stop();
  1055. });
  1056. action->set_enabled(false);
  1057. return action;
  1058. }
  1059. void HackStudioWidget::initialize_menubar(GUI::Window& window)
  1060. {
  1061. create_file_menu(window);
  1062. create_project_menu(window);
  1063. create_edit_menu(window);
  1064. create_build_menu(window);
  1065. create_view_menu(window);
  1066. create_help_menu(window);
  1067. }
  1068. void HackStudioWidget::update_statusbar()
  1069. {
  1070. m_statusbar->set_text(0, String::formatted("Ln {}, Col {}", current_editor().cursor().line() + 1, current_editor().cursor().column()));
  1071. StringBuilder builder;
  1072. if (current_editor().has_selection()) {
  1073. String selected_text = current_editor().selected_text();
  1074. auto word_count = current_editor().number_of_selected_words();
  1075. builder.appendff("Selected: {} {} ({} {})", selected_text.length(), selected_text.length() == 1 ? "character" : "characters", word_count, word_count != 1 ? "words" : "word");
  1076. }
  1077. m_statusbar->set_text(1, builder.to_string());
  1078. m_statusbar->set_text(2, current_editor_wrapper().editor().code_document().language_name());
  1079. }
  1080. void HackStudioWidget::handle_external_file_deletion(const String& filepath)
  1081. {
  1082. close_file_in_all_editors(filepath);
  1083. }
  1084. void HackStudioWidget::stop_debugger_if_running()
  1085. {
  1086. if (!m_debugger_thread.is_null()) {
  1087. Debugger::the().stop();
  1088. dbgln("Waiting for debugger thread to terminate");
  1089. auto rc = m_debugger_thread->join();
  1090. if (rc.is_error()) {
  1091. warnln("pthread_join: {}", strerror(rc.error().value()));
  1092. dbgln("error joining debugger thread");
  1093. }
  1094. }
  1095. }
  1096. void HackStudioWidget::close_current_project()
  1097. {
  1098. m_editors_splitter->remove_all_children();
  1099. m_all_editor_wrappers.clear();
  1100. m_open_files.clear();
  1101. m_open_files_vector.clear();
  1102. add_new_editor(*m_editors_splitter);
  1103. m_find_in_files_widget->reset();
  1104. m_todo_entries_widget->clear();
  1105. m_terminal_wrapper->clear_including_history();
  1106. stop_debugger_if_running();
  1107. update_gml_preview();
  1108. }
  1109. HackStudioWidget::~HackStudioWidget()
  1110. {
  1111. stop_debugger_if_running();
  1112. }
  1113. HackStudioWidget::ContinueDecision HackStudioWidget::warn_unsaved_changes(const String& prompt)
  1114. {
  1115. if (!any_document_is_dirty())
  1116. return ContinueDecision::Yes;
  1117. auto result = GUI::MessageBox::show(window(), prompt, "Unsaved changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  1118. if (result == GUI::MessageBox::ExecCancel)
  1119. return ContinueDecision::No;
  1120. if (result == GUI::MessageBox::ExecYes) {
  1121. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1122. if (editor_wrapper.editor().document().is_modified()) {
  1123. editor_wrapper.save();
  1124. }
  1125. }
  1126. }
  1127. return ContinueDecision::Yes;
  1128. }
  1129. bool HackStudioWidget::any_document_is_dirty() const
  1130. {
  1131. return any_of(m_all_editor_wrappers, [](auto& editor_wrapper) {
  1132. return editor_wrapper.editor().document().is_modified();
  1133. });
  1134. }
  1135. void HackStudioWidget::update_gml_preview()
  1136. {
  1137. auto gml_content = current_editor_wrapper().filename().ends_with(".gml") ? current_editor_wrapper().editor().text() : "";
  1138. m_gml_preview_widget->load_gml(gml_content);
  1139. }
  1140. void HackStudioWidget::update_tree_view()
  1141. {
  1142. auto index = m_project->model().index(m_current_editor_wrapper->filename(), GUI::FileSystemModel::Column::Name);
  1143. if (index.is_valid()) {
  1144. m_project_tree_view->expand_all_parents_of(index);
  1145. m_project_tree_view->set_cursor(index, GUI::AbstractView::SelectionUpdate::Set);
  1146. }
  1147. }
  1148. void HackStudioWidget::update_window_title()
  1149. {
  1150. window()->set_title(String::formatted("{} - {} - Hack Studio", m_current_editor_wrapper->filename_label().text(), m_project->name()));
  1151. }
  1152. void HackStudioWidget::on_cursor_change()
  1153. {
  1154. update_statusbar();
  1155. if (current_editor_wrapper().filename().is_null())
  1156. return;
  1157. auto current_location = current_project_location();
  1158. if (m_locations_history_end_index != 0) {
  1159. auto last = m_locations_history[m_locations_history_end_index - 1];
  1160. if (current_location.filename == last.filename && current_location.line == last.line)
  1161. return;
  1162. }
  1163. // Clear "Go Forward" locations
  1164. VERIFY(m_locations_history_end_index <= m_locations_history.size());
  1165. m_locations_history.remove(m_locations_history_end_index, m_locations_history.size() - m_locations_history_end_index);
  1166. m_locations_history.append(current_location);
  1167. constexpr size_t max_locations = 30;
  1168. if (m_locations_history.size() > max_locations)
  1169. m_locations_history.take_first();
  1170. m_locations_history_end_index = m_locations_history.size();
  1171. update_history_actions();
  1172. }
  1173. void HackStudioWidget::create_location_history_actions()
  1174. {
  1175. 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"), [this](auto&) {
  1176. if (m_locations_history_end_index <= 1)
  1177. return;
  1178. auto location = m_locations_history[m_locations_history_end_index - 2];
  1179. --m_locations_history_end_index;
  1180. m_locations_history_disabled = true;
  1181. open_file(location.filename, location.line, location.column);
  1182. m_locations_history_disabled = false;
  1183. update_history_actions();
  1184. });
  1185. 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"), [this](auto&) {
  1186. if (m_locations_history_end_index == m_locations_history.size())
  1187. return;
  1188. auto location = m_locations_history[m_locations_history_end_index];
  1189. ++m_locations_history_end_index;
  1190. m_locations_history_disabled = true;
  1191. open_file(location.filename, location.line, location.column);
  1192. m_locations_history_disabled = false;
  1193. update_history_actions();
  1194. });
  1195. m_locations_history_forward_action->set_enabled(false);
  1196. }
  1197. HackStudioWidget::ProjectLocation HackStudioWidget::current_project_location() const
  1198. {
  1199. return ProjectLocation { current_editor_wrapper().filename(), current_editor().cursor().line(), current_editor().cursor().column() };
  1200. }
  1201. void HackStudioWidget::update_history_actions()
  1202. {
  1203. if (m_locations_history_end_index <= 1)
  1204. m_locations_history_back_action->set_enabled(false);
  1205. else
  1206. m_locations_history_back_action->set_enabled(true);
  1207. if (m_locations_history_end_index == m_locations_history.size())
  1208. m_locations_history_forward_action->set_enabled(false);
  1209. else
  1210. m_locations_history_forward_action->set_enabled(true);
  1211. }
  1212. RefPtr<Gfx::Font> HackStudioWidget::read_editor_font_from_config()
  1213. {
  1214. auto font_family = Config::read_string("HackStudio", "EditorFont", "Family", "Csilla");
  1215. auto font_variant = Config::read_string("HackStudio", "EditorFont", "Variant", "Regular");
  1216. auto font_size = Config::read_i32("HackStudio", "EditorFont", "Size", 10);
  1217. auto font = Gfx::FontDatabase::the().get(font_family, font_variant, font_size);
  1218. if (font.is_null())
  1219. return Gfx::FontDatabase::the().default_fixed_width_font();
  1220. return font;
  1221. }
  1222. void HackStudioWidget::change_editor_font(RefPtr<Gfx::Font> font)
  1223. {
  1224. m_editor_font = move(font);
  1225. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1226. editor_wrapper.editor().set_font(*m_editor_font);
  1227. }
  1228. Config::write_string("HackStudio", "EditorFont", "Family", m_editor_font->family());
  1229. Config::write_string("HackStudio", "EditorFont", "Variant", m_editor_font->variant());
  1230. Config::write_i32("HackStudio", "EditorFont", "Size", m_editor_font->presentation_size());
  1231. }
  1232. }