HackStudioWidget.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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 <LibCore/ArgsParser.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/InputBox.h>
  44. #include <LibGUI/ItemListModel.h>
  45. #include <LibGUI/Label.h>
  46. #include <LibGUI/Menu.h>
  47. #include <LibGUI/Menubar.h>
  48. #include <LibGUI/MessageBox.h>
  49. #include <LibGUI/RegularEditingEngine.h>
  50. #include <LibGUI/Splitter.h>
  51. #include <LibGUI/StackWidget.h>
  52. #include <LibGUI/Statusbar.h>
  53. #include <LibGUI/TabWidget.h>
  54. #include <LibGUI/TableView.h>
  55. #include <LibGUI/TextBox.h>
  56. #include <LibGUI/TextEditor.h>
  57. #include <LibGUI/Toolbar.h>
  58. #include <LibGUI/ToolbarContainer.h>
  59. #include <LibGUI/TreeView.h>
  60. #include <LibGUI/VimEditingEngine.h>
  61. #include <LibGUI/Widget.h>
  62. #include <LibGUI/Window.h>
  63. #include <LibGfx/FontDatabase.h>
  64. #include <LibGfx/Palette.h>
  65. #include <LibThreading/Mutex.h>
  66. #include <LibThreading/Thread.h>
  67. #include <LibVT/TerminalWidget.h>
  68. #include <fcntl.h>
  69. #include <spawn.h>
  70. #include <stdio.h>
  71. #include <sys/stat.h>
  72. #include <sys/types.h>
  73. #include <sys/wait.h>
  74. #include <unistd.h>
  75. namespace HackStudio {
  76. HackStudioWidget::HackStudioWidget(const String& path_to_project)
  77. {
  78. set_fill_with_background_color(true);
  79. set_layout<GUI::VerticalBoxLayout>();
  80. layout()->set_spacing(2);
  81. open_project(path_to_project);
  82. auto& toolbar_container = add<GUI::ToolbarContainer>();
  83. auto& outer_splitter = add<GUI::HorizontalSplitter>();
  84. outer_splitter.layout()->set_spacing(5);
  85. auto& left_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  86. left_hand_splitter.layout()->set_spacing(5);
  87. left_hand_splitter.set_fixed_width(150);
  88. create_project_tab(left_hand_splitter);
  89. m_project_tree_view_context_menu = create_project_tree_view_context_menu();
  90. create_open_files_view(left_hand_splitter);
  91. m_right_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  92. m_right_hand_stack = m_right_hand_splitter->add<GUI::StackWidget>();
  93. // Put a placeholder widget front & center since we don't have a file open yet.
  94. m_right_hand_stack->add<GUI::Widget>();
  95. m_diff_viewer = m_right_hand_stack->add<DiffViewer>();
  96. m_editors_splitter = m_right_hand_stack->add<GUI::VerticalSplitter>();
  97. m_editors_splitter->layout()->set_spacing(5);
  98. m_editors_splitter->layout()->set_margins({ 3, 0, 0 });
  99. add_new_editor(*m_editors_splitter);
  100. m_switch_to_next_editor = create_switch_to_next_editor_action();
  101. m_switch_to_previous_editor = create_switch_to_previous_editor_action();
  102. m_remove_current_editor_action = create_remove_current_editor_action();
  103. m_open_action = create_open_action();
  104. m_save_action = create_save_action();
  105. m_save_as_action = create_save_as_action();
  106. m_new_project_action = create_new_project_action();
  107. create_action_tab(*m_right_hand_splitter);
  108. m_add_editor_action = create_add_editor_action();
  109. m_add_terminal_action = create_add_terminal_action();
  110. m_remove_current_terminal_action = create_remove_current_terminal_action();
  111. m_locator = add<Locator>();
  112. m_terminal_wrapper->on_command_exit = [this] {
  113. m_stop_action->set_enabled(false);
  114. };
  115. m_build_action = create_build_action();
  116. m_run_action = create_run_action();
  117. m_stop_action = create_stop_action();
  118. m_debug_action = create_debug_action();
  119. initialize_debugger();
  120. create_toolbar(toolbar_container);
  121. m_statusbar = add<GUI::Statusbar>(3);
  122. auto maybe_watcher = Core::FileWatcher::create();
  123. if (maybe_watcher.is_error()) {
  124. warnln("Couldn't create a file watcher, deleted files won't be noticed! Error: {}", maybe_watcher.error());
  125. } else {
  126. m_file_watcher = maybe_watcher.release_value();
  127. m_file_watcher->on_change = [this](Core::FileWatcherEvent const& event) {
  128. if (event.type != Core::FileWatcherEvent::Type::Deleted)
  129. return;
  130. if (event.event_path.starts_with(project().root_path())) {
  131. String relative_path = LexicalPath::relative_path(event.event_path, project().root_path());
  132. handle_external_file_deletion(relative_path);
  133. } else {
  134. handle_external_file_deletion(event.event_path);
  135. }
  136. };
  137. }
  138. }
  139. void HackStudioWidget::update_actions()
  140. {
  141. auto is_remove_terminal_enabled = [this]() {
  142. auto widget = m_action_tab_widget->active_widget();
  143. if (!widget)
  144. return false;
  145. if ("TerminalWrapper"sv != widget->class_name())
  146. return false;
  147. if (!reinterpret_cast<TerminalWrapper*>(widget)->user_spawned())
  148. return false;
  149. return true;
  150. };
  151. m_remove_current_editor_action->set_enabled(m_all_editor_wrappers.size() > 1);
  152. m_remove_current_terminal_action->set_enabled(is_remove_terminal_enabled());
  153. }
  154. void HackStudioWidget::on_action_tab_change()
  155. {
  156. update_actions();
  157. if (auto* active_widget = m_action_tab_widget->active_widget()) {
  158. if (is<GitWidget>(*active_widget))
  159. static_cast<GitWidget&>(*active_widget).refresh();
  160. }
  161. }
  162. void HackStudioWidget::open_project(const String& root_path)
  163. {
  164. if (chdir(root_path.characters()) < 0) {
  165. perror("chdir");
  166. exit(1);
  167. }
  168. if (m_project) {
  169. close_current_project();
  170. }
  171. m_project = Project::open_with_root_path(root_path);
  172. VERIFY(m_project);
  173. if (m_project_tree_view) {
  174. m_project_tree_view->set_model(m_project->model());
  175. m_project_tree_view->update();
  176. }
  177. if (m_git_widget) {
  178. m_git_widget->change_repo(LexicalPath(root_path));
  179. m_git_widget->refresh();
  180. }
  181. if (Debugger::is_initialized()) {
  182. auto& debugger = Debugger::the();
  183. debugger.reset_breakpoints();
  184. debugger.set_source_root(m_project->root_path());
  185. }
  186. for (auto& editor_wrapper : m_all_editor_wrappers)
  187. editor_wrapper.set_project_root(LexicalPath(m_project->root_path()));
  188. }
  189. Vector<String> HackStudioWidget::selected_file_paths() const
  190. {
  191. Vector<String> files;
  192. m_project_tree_view->selection().for_each_index([&](const GUI::ModelIndex& index) {
  193. String sub_path = index.data().as_string();
  194. GUI::ModelIndex parent_or_invalid = index.parent();
  195. while (parent_or_invalid.is_valid()) {
  196. sub_path = String::formatted("{}/{}", parent_or_invalid.data().as_string(), sub_path);
  197. parent_or_invalid = parent_or_invalid.parent();
  198. }
  199. files.append(sub_path);
  200. });
  201. return files;
  202. }
  203. bool HackStudioWidget::open_file(const String& full_filename)
  204. {
  205. String filename = full_filename;
  206. if (full_filename.starts_with(project().root_path())) {
  207. filename = LexicalPath::relative_path(full_filename, project().root_path());
  208. }
  209. dbgln("HackStudio is opening {}", filename);
  210. if (Core::File::is_directory(filename) || !Core::File::exists(filename))
  211. return false;
  212. if (!active_file().is_empty()) {
  213. // Since the file is previously open, it should always be in m_open_files.
  214. VERIFY(m_open_files.find(active_file()) != m_open_files.end());
  215. auto previous_open_project_file = m_open_files.get(active_file()).value();
  216. // Update the scrollbar values of the previous_open_project_file and save them to m_open_files.
  217. previous_open_project_file->vertical_scroll_value(current_editor().vertical_scrollbar().value());
  218. previous_open_project_file->horizontal_scroll_value(current_editor().horizontal_scrollbar().value());
  219. }
  220. RefPtr<ProjectFile> new_project_file = nullptr;
  221. if (auto it = m_open_files.find(filename); it != m_open_files.end()) {
  222. new_project_file = it->value;
  223. } else {
  224. new_project_file = m_project->get_file(filename);
  225. m_open_files.set(filename, *new_project_file);
  226. m_open_files_vector.append(filename);
  227. if (!m_file_watcher.is_null()) {
  228. auto watch_result = m_file_watcher->add_watch(filename, Core::FileWatcherEvent::Type::Deleted);
  229. if (watch_result.is_error()) {
  230. warnln("Couldn't watch '{}'", filename);
  231. }
  232. }
  233. m_open_files_view->model()->invalidate();
  234. }
  235. current_editor().set_document(const_cast<GUI::TextDocument&>(new_project_file->document()));
  236. if (new_project_file->could_render_text()) {
  237. current_editor_wrapper().set_mode_displayable();
  238. } else {
  239. current_editor_wrapper().set_mode_non_displayable();
  240. }
  241. current_editor().horizontal_scrollbar().set_value(new_project_file->horizontal_scroll_value());
  242. current_editor().vertical_scrollbar().set_value(new_project_file->vertical_scroll_value());
  243. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  244. set_edit_mode(EditMode::Text);
  245. String relative_file_path = filename;
  246. if (filename.starts_with(m_project->root_path()))
  247. relative_file_path = filename.substring(m_project->root_path().length() + 1);
  248. m_project_tree_view->update();
  249. current_editor_wrapper().set_filename(filename);
  250. current_editor().set_focus(true);
  251. current_editor().on_cursor_change = [this] { update_statusbar(); };
  252. current_editor_wrapper().on_change = [this] { update_gml_preview(); };
  253. update_gml_preview();
  254. return true;
  255. }
  256. void HackStudioWidget::close_file_in_all_editors(String const& filename)
  257. {
  258. m_open_files.remove(filename);
  259. m_open_files_vector.remove_all_matching(
  260. [&filename](String const& element) { return element == filename; });
  261. for (auto& editor_wrapper : m_all_editor_wrappers) {
  262. Editor& editor = editor_wrapper.editor();
  263. String editor_file_path = editor.code_document().file_path();
  264. String relative_editor_file_path = LexicalPath::relative_path(editor_file_path, project().root_path());
  265. if (relative_editor_file_path == filename) {
  266. if (m_open_files_vector.is_empty()) {
  267. editor.set_document(CodeDocument::create());
  268. editor_wrapper.set_filename("");
  269. } else {
  270. auto& first_path = m_open_files_vector[0];
  271. auto& document = m_open_files.get(first_path).value()->code_document();
  272. editor.set_document(document);
  273. editor_wrapper.set_filename(first_path);
  274. }
  275. }
  276. }
  277. m_open_files_view->model()->invalidate();
  278. }
  279. EditorWrapper& HackStudioWidget::current_editor_wrapper()
  280. {
  281. VERIFY(m_current_editor_wrapper);
  282. return *m_current_editor_wrapper;
  283. }
  284. GUI::TextEditor& HackStudioWidget::current_editor()
  285. {
  286. return current_editor_wrapper().editor();
  287. }
  288. void HackStudioWidget::set_edit_mode(EditMode mode)
  289. {
  290. if (mode == EditMode::Text) {
  291. m_right_hand_stack->set_active_widget(m_editors_splitter);
  292. } else if (mode == EditMode::Diff) {
  293. m_right_hand_stack->set_active_widget(m_diff_viewer);
  294. } else {
  295. VERIFY_NOT_REACHED();
  296. }
  297. m_right_hand_stack->active_widget()->update();
  298. }
  299. NonnullRefPtr<GUI::Menu> HackStudioWidget::create_project_tree_view_context_menu()
  300. {
  301. m_open_selected_action = create_open_selected_action();
  302. m_show_in_file_manager_action = create_show_in_file_manager_action();
  303. m_new_file_action = create_new_file_action();
  304. m_new_directory_action = create_new_directory_action();
  305. m_delete_action = create_delete_action();
  306. auto project_tree_view_context_menu = GUI::Menu::construct("Project Files");
  307. project_tree_view_context_menu->add_action(*m_open_selected_action);
  308. project_tree_view_context_menu->add_action(*m_show_in_file_manager_action);
  309. // TODO: Rename, cut, copy, duplicate with new name...
  310. project_tree_view_context_menu->add_separator();
  311. project_tree_view_context_menu->add_action(*m_new_file_action);
  312. project_tree_view_context_menu->add_action(*m_new_directory_action);
  313. project_tree_view_context_menu->add_action(*m_delete_action);
  314. return project_tree_view_context_menu;
  315. }
  316. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_file_action()
  317. {
  318. return GUI::Action::create("New &File...", { Mod_Ctrl, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/new.png"), [this](const GUI::Action&) {
  319. String filename;
  320. if (GUI::InputBox::show(window(), filename, "Enter name of new file:", "Add new file to project") != GUI::InputBox::ExecOK)
  321. return;
  322. auto path_to_selected = selected_file_paths();
  323. String filepath;
  324. if (!path_to_selected.is_empty()) {
  325. VERIFY(Core::File::exists(path_to_selected.first()));
  326. LexicalPath selected(path_to_selected.first());
  327. String dir_path;
  328. if (Core::File::is_directory(selected.string()))
  329. dir_path = selected.string();
  330. else
  331. dir_path = selected.dirname();
  332. filepath = String::formatted("{}/", dir_path);
  333. }
  334. filepath = String::formatted("{}{}", filepath, filename);
  335. auto file = Core::File::construct(filepath);
  336. if (!file->open((Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::MustBeNew))) {
  337. GUI::MessageBox::show(window(), String::formatted("Failed to create '{}'", filepath), "Error", GUI::MessageBox::Type::Error);
  338. return;
  339. }
  340. open_file(filepath);
  341. });
  342. }
  343. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_directory_action()
  344. {
  345. 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&) {
  346. String directory_name;
  347. if (GUI::InputBox::show(window(), directory_name, "Enter name of new directory:", "Add new folder to project") != GUI::InputBox::ExecOK)
  348. return;
  349. auto path_to_selected = selected_file_paths();
  350. if (!path_to_selected.is_empty()) {
  351. LexicalPath selected(path_to_selected.first());
  352. String dir_path;
  353. if (Core::File::is_directory(selected.string()))
  354. dir_path = selected.string();
  355. else
  356. dir_path = selected.dirname();
  357. directory_name = String::formatted("{}/{}", dir_path, directory_name);
  358. }
  359. auto formatted_dir_name = LexicalPath::canonicalized_path(String::formatted("{}/{}", m_project->model().root_path(), directory_name));
  360. int rc = mkdir(formatted_dir_name.characters(), 0755);
  361. if (rc < 0) {
  362. GUI::MessageBox::show(window(), "Failed to create new directory", "Error", GUI::MessageBox::Type::Error);
  363. return;
  364. }
  365. });
  366. }
  367. NonnullRefPtr<GUI::Action> HackStudioWidget::create_open_selected_action()
  368. {
  369. auto open_selected_action = GUI::Action::create("Open", [this](const GUI::Action&) {
  370. auto files = selected_file_paths();
  371. for (auto& file : files)
  372. open_file(file);
  373. });
  374. open_selected_action->set_enabled(true);
  375. return open_selected_action;
  376. }
  377. NonnullRefPtr<GUI::Action> HackStudioWidget::create_show_in_file_manager_action()
  378. {
  379. auto show_in_file_manager_action = GUI::Action::create("Show in File Manager", [this](const GUI::Action&) {
  380. auto files = selected_file_paths();
  381. for (auto& file : files)
  382. Desktop::Launcher::open(URL::create_with_file_protocol(m_project->root_path(), file));
  383. });
  384. show_in_file_manager_action->set_enabled(true);
  385. show_in_file_manager_action->set_icon(GUI::Icon::default_icon("app-file-manager").bitmap_for_size(16));
  386. return show_in_file_manager_action;
  387. }
  388. NonnullRefPtr<GUI::Action> HackStudioWidget::create_delete_action()
  389. {
  390. auto delete_action = GUI::CommonActions::make_delete_action([this](const GUI::Action&) {
  391. auto files = selected_file_paths();
  392. if (files.is_empty())
  393. return;
  394. String message;
  395. if (files.size() == 1) {
  396. LexicalPath file(files[0]);
  397. message = String::formatted("Really remove {} from disk?", file.basename());
  398. } else {
  399. message = String::formatted("Really remove {} files from disk?", files.size());
  400. }
  401. auto result = GUI::MessageBox::show(window(),
  402. message,
  403. "Confirm deletion",
  404. GUI::MessageBox::Type::Warning,
  405. GUI::MessageBox::InputType::OKCancel);
  406. if (result == GUI::MessageBox::ExecCancel)
  407. return;
  408. for (auto& file : files) {
  409. struct stat st;
  410. if (lstat(file.characters(), &st) < 0) {
  411. GUI::MessageBox::show(window(),
  412. String::formatted("lstat ({}) failed: {}", file, strerror(errno)),
  413. "Removal failed",
  414. GUI::MessageBox::Type::Error);
  415. break;
  416. }
  417. bool is_directory = S_ISDIR(st.st_mode);
  418. auto result = Core::File::remove(file, Core::File::RecursionMode::Allowed, false);
  419. if (result.is_error()) {
  420. auto& error = result.error();
  421. if (is_directory) {
  422. GUI::MessageBox::show(window(),
  423. String::formatted("Removing directory {} from the project failed: {}", error.file, error.error_code),
  424. "Removal failed",
  425. GUI::MessageBox::Type::Error);
  426. } else {
  427. GUI::MessageBox::show(window(),
  428. String::formatted("Removing file {} from the project failed: {}", error.file, error.error_code),
  429. "Removal failed",
  430. GUI::MessageBox::Type::Error);
  431. }
  432. }
  433. }
  434. });
  435. delete_action->set_enabled(false);
  436. return delete_action;
  437. }
  438. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_project_action()
  439. {
  440. 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&) {
  441. auto dialog = NewProjectDialog::construct(window());
  442. dialog->set_icon(window()->icon());
  443. auto result = dialog->exec();
  444. if (result == GUI::Dialog::ExecResult::ExecOK && dialog->created_project_path().has_value())
  445. open_project(dialog->created_project_path().value());
  446. });
  447. }
  448. void HackStudioWidget::add_new_editor(GUI::Widget& parent)
  449. {
  450. auto wrapper = EditorWrapper::construct();
  451. if (m_action_tab_widget) {
  452. parent.insert_child_before(wrapper, *m_action_tab_widget);
  453. } else {
  454. parent.add_child(wrapper);
  455. }
  456. m_current_editor_wrapper = wrapper;
  457. m_all_editor_wrappers.append(wrapper);
  458. wrapper->editor().set_focus(true);
  459. wrapper->set_project_root(LexicalPath(m_project->root_path()));
  460. wrapper->editor().on_cursor_change = [this] { update_statusbar(); };
  461. wrapper->on_change = [this] { update_gml_preview(); };
  462. set_edit_mode(EditMode::Text);
  463. }
  464. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_next_editor_action()
  465. {
  466. return GUI::Action::create("Switch to &Next Editor", { Mod_Ctrl, Key_E }, [this](auto&) {
  467. if (m_all_editor_wrappers.size() <= 1)
  468. return;
  469. Vector<EditorWrapper&> wrappers;
  470. m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) {
  471. wrappers.append(child);
  472. return IterationDecision::Continue;
  473. });
  474. for (size_t i = 0; i < wrappers.size(); ++i) {
  475. if (m_current_editor_wrapper.ptr() == &wrappers[i]) {
  476. if (i == wrappers.size() - 1)
  477. wrappers[0].editor().set_focus(true);
  478. else
  479. wrappers[i + 1].editor().set_focus(true);
  480. }
  481. }
  482. });
  483. }
  484. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_previous_editor_action()
  485. {
  486. return GUI::Action::create("Switch to &Previous Editor", { Mod_Ctrl | Mod_Shift, Key_E }, [this](auto&) {
  487. if (m_all_editor_wrappers.size() <= 1)
  488. return;
  489. Vector<EditorWrapper&> wrappers;
  490. m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) {
  491. wrappers.append(child);
  492. return IterationDecision::Continue;
  493. });
  494. for (int i = wrappers.size() - 1; i >= 0; --i) {
  495. if (m_current_editor_wrapper.ptr() == &wrappers[i]) {
  496. if (i == 0)
  497. wrappers.last().editor().set_focus(true);
  498. else
  499. wrappers[i - 1].editor().set_focus(true);
  500. }
  501. }
  502. });
  503. }
  504. NonnullRefPtr<GUI::Action> HackStudioWidget::create_remove_current_editor_action()
  505. {
  506. return GUI::Action::create("&Remove Current Editor", { Mod_Alt | Mod_Shift, Key_E }, [this](auto&) {
  507. if (m_all_editor_wrappers.size() <= 1)
  508. return;
  509. auto wrapper = m_current_editor_wrapper;
  510. m_switch_to_next_editor->activate();
  511. m_editors_splitter->remove_child(*wrapper);
  512. auto child_editors = m_editors_splitter->child_widgets();
  513. bool has_child_to_fill_space = false;
  514. for (auto& editor : child_editors) {
  515. if (editor.max_height() == -1) {
  516. has_child_to_fill_space = true;
  517. break;
  518. }
  519. }
  520. if (!has_child_to_fill_space)
  521. child_editors.last().set_max_height(-1);
  522. m_all_editor_wrappers.remove_first_matching([&wrapper](auto& entry) { return entry == wrapper.ptr(); });
  523. update_actions();
  524. });
  525. }
  526. NonnullRefPtr<GUI::Action> HackStudioWidget::create_open_action()
  527. {
  528. 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&) {
  529. auto open_path = GUI::FilePicker::get_open_filepath(window(), "Open project", m_project->root_path(), true);
  530. if (!open_path.has_value())
  531. return;
  532. open_project(open_path.value());
  533. update_actions();
  534. });
  535. }
  536. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_action()
  537. {
  538. return GUI::CommonActions::make_save_action([&](auto&) {
  539. if (active_file().is_empty())
  540. m_save_as_action->activate();
  541. current_editor_wrapper().save();
  542. if (m_git_widget->initialized())
  543. m_git_widget->refresh();
  544. });
  545. }
  546. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_as_action()
  547. {
  548. return GUI::CommonActions::make_save_as_action([&](auto&) {
  549. auto const old_filename = current_editor_wrapper().filename();
  550. LexicalPath const old_path(old_filename);
  551. Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(),
  552. old_filename.is_null() ? "Untitled" : old_path.title(),
  553. old_filename.is_null() ? "txt" : old_path.extension(),
  554. Core::File::absolute_path(old_path.dirname()));
  555. if (!save_path.has_value()) {
  556. return;
  557. }
  558. current_editor_wrapper().set_filename(save_path.value());
  559. current_editor_wrapper().save();
  560. auto new_project_file = m_project->get_file(save_path.value());
  561. m_open_files.set(save_path.value(), *new_project_file);
  562. m_open_files_vector.append(save_path.value());
  563. update_window_title();
  564. });
  565. }
  566. NonnullRefPtr<GUI::Action> HackStudioWidget::create_remove_current_terminal_action()
  567. {
  568. return GUI::Action::create("Remove &Current Terminal", { Mod_Alt | Mod_Shift, Key_T }, [this](auto&) {
  569. auto widget = m_action_tab_widget->active_widget();
  570. if (!widget)
  571. return;
  572. if (!is<TerminalWrapper>(widget))
  573. return;
  574. auto& terminal = *static_cast<TerminalWrapper*>(widget);
  575. if (!terminal.user_spawned())
  576. return;
  577. m_action_tab_widget->remove_tab(terminal);
  578. update_actions();
  579. });
  580. }
  581. NonnullRefPtr<GUI::Action> HackStudioWidget::create_add_editor_action()
  582. {
  583. return GUI::Action::create("Add New &Editor", { Mod_Ctrl | Mod_Alt, Key_E },
  584. Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-text-editor.png"),
  585. [this](auto&) {
  586. add_new_editor(*m_editors_splitter);
  587. update_actions();
  588. });
  589. }
  590. NonnullRefPtr<GUI::Action> HackStudioWidget::create_add_terminal_action()
  591. {
  592. return GUI::Action::create("Add New &Terminal", { Mod_Ctrl | Mod_Alt, Key_T },
  593. Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-terminal.png"),
  594. [this](auto&) {
  595. auto& terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Terminal");
  596. reveal_action_tab(terminal_wrapper);
  597. update_actions();
  598. terminal_wrapper.terminal().set_focus(true);
  599. });
  600. }
  601. void HackStudioWidget::reveal_action_tab(GUI::Widget& widget)
  602. {
  603. if (m_action_tab_widget->min_height() < 200)
  604. m_action_tab_widget->set_fixed_height(200);
  605. m_action_tab_widget->set_active_widget(&widget);
  606. }
  607. NonnullRefPtr<GUI::Action> HackStudioWidget::create_debug_action()
  608. {
  609. return GUI::Action::create("&Debug", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/debug-run.png"), [this](auto&) {
  610. if (!Core::File::exists(get_project_executable_path())) {
  611. GUI::MessageBox::show(window(), String::formatted("Could not find file: {}. (did you build the project?)", get_project_executable_path()), "Error", GUI::MessageBox::Type::Error);
  612. return;
  613. }
  614. if (Debugger::the().session()) {
  615. GUI::MessageBox::show(window(), "Debugger is already running", "Error", GUI::MessageBox::Type::Error);
  616. return;
  617. }
  618. Debugger::the().set_executable_path(get_project_executable_path());
  619. m_debugger_thread = Threading::Thread::construct(Debugger::start_static);
  620. m_debugger_thread->start();
  621. m_stop_action->set_enabled(true);
  622. m_run_action->set_enabled(false);
  623. for (auto& editor_wrapper : m_all_editor_wrappers) {
  624. editor_wrapper.set_debug_mode(true);
  625. }
  626. });
  627. }
  628. void HackStudioWidget::initialize_debugger()
  629. {
  630. Debugger::initialize(
  631. m_project->root_path(),
  632. [this](const PtraceRegisters& regs) {
  633. VERIFY(Debugger::the().session());
  634. const auto& debug_session = *Debugger::the().session();
  635. auto source_position = debug_session.get_source_position(regs.ip());
  636. if (!source_position.has_value()) {
  637. dbgln("Could not find source position for address: {:p}", regs.ip());
  638. return Debugger::HasControlPassedToUser::No;
  639. }
  640. dbgln("Debugger stopped at source position: {}:{}", source_position.value().file_path, source_position.value().line_number);
  641. Core::EventLoop::main().post_event(
  642. *window(),
  643. make<Core::DeferredInvocationEvent>(
  644. [this, source_position, &regs](auto&) {
  645. m_current_editor_in_execution = get_editor_of_file(source_position.value().file_path);
  646. if (m_current_editor_in_execution)
  647. m_current_editor_in_execution->editor().set_execution_position(source_position.value().line_number - 1);
  648. m_debug_info_widget->update_state(*Debugger::the().session(), regs);
  649. m_debug_info_widget->set_debug_actions_enabled(true);
  650. m_disassembly_widget->update_state(*Debugger::the().session(), regs);
  651. HackStudioWidget::reveal_action_tab(*m_debug_info_widget);
  652. }));
  653. Core::EventLoop::wake();
  654. return Debugger::HasControlPassedToUser::Yes;
  655. },
  656. [this]() {
  657. Core::EventLoop::main().post_event(*window(), make<Core::DeferredInvocationEvent>([this](auto&) {
  658. m_debug_info_widget->set_debug_actions_enabled(false);
  659. if (m_current_editor_in_execution)
  660. m_current_editor_in_execution->editor().clear_execution_position();
  661. }));
  662. Core::EventLoop::wake();
  663. },
  664. [this]() {
  665. Core::EventLoop::main().post_event(*window(), make<Core::DeferredInvocationEvent>([this](auto&) {
  666. m_debug_info_widget->set_debug_actions_enabled(false);
  667. if (m_current_editor_in_execution)
  668. m_current_editor_in_execution->editor().clear_execution_position();
  669. m_debug_info_widget->program_stopped();
  670. m_disassembly_widget->program_stopped();
  671. m_stop_action->set_enabled(false);
  672. m_run_action->set_enabled(true);
  673. m_debugger_thread.clear();
  674. for (auto& editor_wrapper : m_all_editor_wrappers) {
  675. editor_wrapper.set_debug_mode(false);
  676. }
  677. HackStudioWidget::hide_action_tabs();
  678. GUI::MessageBox::show(window(), "Program Exited", "Debugger", GUI::MessageBox::Type::Information);
  679. }));
  680. Core::EventLoop::wake();
  681. });
  682. }
  683. String HackStudioWidget::get_full_path_of_serenity_source(const String& file)
  684. {
  685. auto path_parts = LexicalPath(file).parts();
  686. VERIFY(path_parts[0] == "..");
  687. path_parts.remove(0);
  688. StringBuilder relative_path_builder;
  689. relative_path_builder.join("/", path_parts);
  690. constexpr char SERENITY_LIBS_PREFIX[] = "/usr/src/serenity";
  691. LexicalPath serenity_sources_base(SERENITY_LIBS_PREFIX);
  692. return String::formatted("{}/{}", serenity_sources_base, relative_path_builder.to_string());
  693. }
  694. RefPtr<EditorWrapper> HackStudioWidget::get_editor_of_file(const String& filename)
  695. {
  696. String file_path = filename;
  697. // TODO: We can probably do a more specific condition here, something like
  698. // "if (file.starts_with("../Libraries/") || file.starts_with("../AK/"))"
  699. if (filename.starts_with("../")) {
  700. file_path = get_full_path_of_serenity_source(filename);
  701. }
  702. if (!open_file(file_path))
  703. return nullptr;
  704. return current_editor_wrapper();
  705. }
  706. String HackStudioWidget::get_project_executable_path() const
  707. {
  708. // FIXME: Dumb heuristic ahead!
  709. // e.g /my/project => /my/project/project
  710. // TODO: Perhaps a Makefile rule for getting the value of $(PROGRAM) would be better?
  711. return String::formatted("{}/{}", m_project->root_path(), LexicalPath::basename(m_project->root_path()));
  712. }
  713. void HackStudioWidget::build(TerminalWrapper& wrapper)
  714. {
  715. if (active_file().ends_with(".js"))
  716. wrapper.run_command(String::formatted("js -A {}", active_file()));
  717. else
  718. wrapper.run_command("make");
  719. }
  720. void HackStudioWidget::run(TerminalWrapper& wrapper)
  721. {
  722. if (active_file().ends_with(".js"))
  723. wrapper.run_command(String::formatted("js {}", active_file()));
  724. else
  725. wrapper.run_command("make run");
  726. }
  727. void HackStudioWidget::hide_action_tabs()
  728. {
  729. m_action_tab_widget->set_fixed_height(24);
  730. };
  731. Project& HackStudioWidget::project()
  732. {
  733. return *m_project;
  734. }
  735. void HackStudioWidget::set_current_editor_wrapper(RefPtr<EditorWrapper> editor_wrapper)
  736. {
  737. m_current_editor_wrapper = editor_wrapper;
  738. update_window_title();
  739. }
  740. void HackStudioWidget::configure_project_tree_view()
  741. {
  742. m_project_tree_view->set_model(m_project->model());
  743. m_project_tree_view->set_selection_mode(GUI::AbstractView::SelectionMode::MultiSelection);
  744. for (int column_index = 0; column_index < m_project->model().column_count(); ++column_index)
  745. m_project_tree_view->set_column_visible(column_index, false);
  746. m_project_tree_view->set_column_visible(GUI::FileSystemModel::Column::Name, true);
  747. m_project_tree_view->on_context_menu_request = [this](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  748. if (index.is_valid()) {
  749. m_project_tree_view_context_menu->popup(event.screen_position(), m_open_selected_action);
  750. }
  751. };
  752. m_project_tree_view->on_selection_change = [this] {
  753. m_open_selected_action->set_enabled(!m_project_tree_view->selection().is_empty());
  754. auto selections = m_project_tree_view->selection().indices();
  755. auto it = selections.find_if([&](auto selected_file) {
  756. return access(m_project->model().full_path(selected_file.parent()).characters(), W_OK) == 0;
  757. });
  758. bool has_permissions = it != selections.end();
  759. m_delete_action->set_enabled(!m_project_tree_view->selection().is_empty() && has_permissions);
  760. };
  761. m_project_tree_view->on_activation = [this](auto& index) {
  762. auto full_path_to_file = m_project->model().full_path(index);
  763. open_file(full_path_to_file);
  764. };
  765. }
  766. void HackStudioWidget::create_open_files_view(GUI::Widget& parent)
  767. {
  768. m_open_files_view = parent.add<GUI::ListView>();
  769. auto open_files_model = GUI::ItemListModel<String>::create(m_open_files_vector);
  770. m_open_files_view->set_model(open_files_model);
  771. m_open_files_view->on_activation = [this](auto& index) {
  772. open_file(index.data().to_string());
  773. };
  774. }
  775. void HackStudioWidget::create_toolbar(GUI::Widget& parent)
  776. {
  777. auto& toolbar = parent.add<GUI::Toolbar>();
  778. toolbar.add_action(*m_new_file_action);
  779. toolbar.add_action(*m_new_directory_action);
  780. toolbar.add_action(*m_save_action);
  781. toolbar.add_action(*m_delete_action);
  782. toolbar.add_separator();
  783. toolbar.add_action(GUI::CommonActions::make_cut_action([this](auto&) { current_editor().cut_action().activate(); }));
  784. toolbar.add_action(GUI::CommonActions::make_copy_action([this](auto&) { current_editor().copy_action().activate(); }));
  785. toolbar.add_action(GUI::CommonActions::make_paste_action([this](auto&) { current_editor().paste_action().activate(); }));
  786. toolbar.add_separator();
  787. toolbar.add_action(GUI::CommonActions::make_undo_action([this](auto&) { current_editor().undo_action().activate(); }));
  788. toolbar.add_action(GUI::CommonActions::make_redo_action([this](auto&) { current_editor().redo_action().activate(); }));
  789. toolbar.add_separator();
  790. toolbar.add_action(*m_build_action);
  791. toolbar.add_separator();
  792. toolbar.add_action(*m_run_action);
  793. toolbar.add_action(*m_stop_action);
  794. toolbar.add_separator();
  795. toolbar.add_action(*m_debug_action);
  796. }
  797. NonnullRefPtr<GUI::Action> HackStudioWidget::create_build_action()
  798. {
  799. return GUI::Action::create("&Build", { Mod_Ctrl, Key_B }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/build.png"), [this](auto&) {
  800. if (warn_unsaved_changes("There are unsaved changes, do you want to save before building?") == ContinueDecision::No)
  801. return;
  802. reveal_action_tab(*m_terminal_wrapper);
  803. build(*m_terminal_wrapper);
  804. m_stop_action->set_enabled(true);
  805. });
  806. }
  807. NonnullRefPtr<GUI::Action> HackStudioWidget::create_run_action()
  808. {
  809. return GUI::Action::create("&Run", { Mod_Ctrl, Key_R }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-run.png"), [this](auto&) {
  810. reveal_action_tab(*m_terminal_wrapper);
  811. run(*m_terminal_wrapper);
  812. m_stop_action->set_enabled(true);
  813. });
  814. }
  815. void HackStudioWidget::create_action_tab(GUI::Widget& parent)
  816. {
  817. m_action_tab_widget = parent.add<GUI::TabWidget>();
  818. m_action_tab_widget->set_fixed_height(24);
  819. m_action_tab_widget->on_change = [this](auto&) {
  820. on_action_tab_change();
  821. static bool first_time = true;
  822. if (!first_time)
  823. m_action_tab_widget->set_fixed_height(200);
  824. first_time = false;
  825. };
  826. m_find_in_files_widget = m_action_tab_widget->add_tab<FindInFilesWidget>("Find in files");
  827. m_todo_entries_widget = m_action_tab_widget->add_tab<ToDoEntriesWidget>("TODO");
  828. m_terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Build", false);
  829. m_debug_info_widget = m_action_tab_widget->add_tab<DebugInfoWidget>("Debug");
  830. m_disassembly_widget = m_action_tab_widget->add_tab<DisassemblyWidget>("Disassembly");
  831. m_git_widget = m_action_tab_widget->add_tab<GitWidget>("Git", LexicalPath(m_project->root_path()));
  832. m_git_widget->set_view_diff_callback([this](const auto& original_content, const auto& diff) {
  833. m_diff_viewer->set_content(original_content, diff);
  834. set_edit_mode(EditMode::Diff);
  835. });
  836. m_gml_preview_widget = m_action_tab_widget->add_tab<GMLPreviewWidget>("GML Preview", "");
  837. ToDoEntries::the().on_update = [this]() {
  838. m_todo_entries_widget->refresh();
  839. };
  840. }
  841. void HackStudioWidget::create_project_tab(GUI::Widget& parent)
  842. {
  843. m_project_tab = parent.add<GUI::TabWidget>();
  844. m_project_tab->set_tab_position(GUI::TabWidget::TabPosition::Bottom);
  845. auto& tree_view_container = m_project_tab->add_tab<GUI::Widget>("Files");
  846. tree_view_container.set_layout<GUI::VerticalBoxLayout>();
  847. tree_view_container.layout()->set_margins(2);
  848. m_project_tree_view = tree_view_container.add<GUI::TreeView>();
  849. configure_project_tree_view();
  850. auto& class_view_container = m_project_tab->add_tab<GUI::Widget>("Classes");
  851. class_view_container.set_layout<GUI::VerticalBoxLayout>();
  852. class_view_container.layout()->set_margins(2);
  853. m_class_view = class_view_container.add<ClassViewWidget>();
  854. ProjectDeclarations::the().on_update = [this]() {
  855. m_class_view->refresh();
  856. };
  857. }
  858. void HackStudioWidget::create_file_menu(GUI::Window& window)
  859. {
  860. auto& file_menu = window.add_menu("&File");
  861. file_menu.add_action(*m_new_project_action);
  862. file_menu.add_action(*m_open_action);
  863. file_menu.add_action(*m_save_action);
  864. file_menu.add_action(*m_save_as_action);
  865. file_menu.add_separator();
  866. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  867. GUI::Application::the()->quit();
  868. }));
  869. }
  870. void HackStudioWidget::create_project_menu(GUI::Window& window)
  871. {
  872. auto& project_menu = window.add_menu("&Project");
  873. project_menu.add_action(*m_new_file_action);
  874. project_menu.add_action(*m_new_directory_action);
  875. }
  876. void HackStudioWidget::create_edit_menu(GUI::Window& window)
  877. {
  878. auto& edit_menu = window.add_menu("&Edit");
  879. 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&) {
  880. reveal_action_tab(*m_find_in_files_widget);
  881. m_find_in_files_widget->focus_textbox_and_select_all();
  882. }));
  883. edit_menu.add_separator();
  884. auto vim_emulation_setting_action = GUI::Action::create_checkable("&Vim Emulation", { Mod_Ctrl | Mod_Shift | Mod_Alt, Key_V }, [this](auto& action) {
  885. if (action.is_checked())
  886. current_editor().set_editing_engine(make<GUI::VimEditingEngine>());
  887. else
  888. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  889. });
  890. vim_emulation_setting_action->set_checked(false);
  891. edit_menu.add_action(vim_emulation_setting_action);
  892. }
  893. void HackStudioWidget::create_build_menu(GUI::Window& window)
  894. {
  895. auto& build_menu = window.add_menu("&Build");
  896. build_menu.add_action(*m_build_action);
  897. build_menu.add_separator();
  898. build_menu.add_action(*m_run_action);
  899. build_menu.add_action(*m_stop_action);
  900. build_menu.add_separator();
  901. build_menu.add_action(*m_debug_action);
  902. }
  903. void HackStudioWidget::create_view_menu(GUI::Window& window)
  904. {
  905. auto hide_action_tabs_action = GUI::Action::create("&Hide Action Tabs", { Mod_Ctrl | Mod_Shift, Key_X }, [this](auto&) {
  906. hide_action_tabs();
  907. });
  908. auto open_locator_action = GUI::Action::create("Open &Locator", { Mod_Ctrl, Key_K }, [this](auto&) {
  909. m_locator->open();
  910. });
  911. auto& view_menu = window.add_menu("&View");
  912. view_menu.add_action(hide_action_tabs_action);
  913. view_menu.add_action(open_locator_action);
  914. view_menu.add_separator();
  915. m_wrapping_mode_actions.set_exclusive(true);
  916. auto& wrapping_mode_menu = view_menu.add_submenu("&Wrapping Mode");
  917. m_no_wrapping_action = GUI::Action::create_checkable("&No Wrapping", [&](auto&) {
  918. for (auto& wrapper : m_all_editor_wrappers)
  919. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  920. });
  921. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap &Anywhere", [&](auto&) {
  922. for (auto& wrapper : m_all_editor_wrappers)
  923. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  924. });
  925. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at &Words", [&](auto&) {
  926. for (auto& wrapper : m_all_editor_wrappers)
  927. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  928. });
  929. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  930. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  931. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  932. wrapping_mode_menu.add_action(*m_no_wrapping_action);
  933. wrapping_mode_menu.add_action(*m_wrap_anywhere_action);
  934. wrapping_mode_menu.add_action(*m_wrap_at_words_action);
  935. m_no_wrapping_action->set_checked(true);
  936. view_menu.add_separator();
  937. view_menu.add_action(*m_add_editor_action);
  938. view_menu.add_action(*m_remove_current_editor_action);
  939. view_menu.add_action(*m_add_terminal_action);
  940. view_menu.add_action(*m_remove_current_terminal_action);
  941. }
  942. void HackStudioWidget::create_help_menu(GUI::Window& window)
  943. {
  944. auto& help_menu = window.add_menu("&Help");
  945. help_menu.add_action(GUI::CommonActions::make_about_action("Hack Studio", GUI::Icon::default_icon("app-hack-studio"), &window));
  946. }
  947. NonnullRefPtr<GUI::Action> HackStudioWidget::create_stop_action()
  948. {
  949. auto action = GUI::Action::create("&Stop", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-stop.png"), [this](auto&) {
  950. if (!Debugger::the().session()) {
  951. m_terminal_wrapper->kill_running_command();
  952. return;
  953. }
  954. Debugger::the().stop();
  955. });
  956. action->set_enabled(false);
  957. return action;
  958. }
  959. void HackStudioWidget::initialize_menubar(GUI::Window& window)
  960. {
  961. create_file_menu(window);
  962. create_project_menu(window);
  963. create_edit_menu(window);
  964. create_build_menu(window);
  965. create_view_menu(window);
  966. create_help_menu(window);
  967. }
  968. void HackStudioWidget::update_statusbar()
  969. {
  970. m_statusbar->set_text(0, String::formatted("Ln {}, Col {}", current_editor().cursor().line() + 1, current_editor().cursor().column()));
  971. StringBuilder builder;
  972. if (current_editor().has_selection()) {
  973. String selected_text = current_editor().selected_text();
  974. auto word_count = current_editor().number_of_selected_words();
  975. builder.appendff("Selected: {} {} ({} {})", selected_text.length(), selected_text.length() == 1 ? "character" : "characters", word_count, word_count != 1 ? "words" : "word");
  976. }
  977. m_statusbar->set_text(1, builder.to_string());
  978. m_statusbar->set_text(2, current_editor_wrapper().editor().code_document().language_name());
  979. }
  980. void HackStudioWidget::handle_external_file_deletion(const String& filepath)
  981. {
  982. close_file_in_all_editors(filepath);
  983. }
  984. void HackStudioWidget::stop_debugger_if_running()
  985. {
  986. if (!m_debugger_thread.is_null()) {
  987. Debugger::the().stop();
  988. dbgln("Waiting for debugger thread to terminate");
  989. auto rc = m_debugger_thread->join();
  990. if (rc.is_error()) {
  991. warnln("pthread_join: {}", strerror(rc.error().value()));
  992. dbgln("error joining debugger thread");
  993. }
  994. }
  995. }
  996. void HackStudioWidget::close_current_project()
  997. {
  998. m_editors_splitter->remove_all_children();
  999. m_all_editor_wrappers.clear();
  1000. m_open_files.clear();
  1001. m_open_files_vector.clear();
  1002. add_new_editor(*m_editors_splitter);
  1003. m_find_in_files_widget->reset();
  1004. m_todo_entries_widget->clear();
  1005. m_terminal_wrapper->clear_including_history();
  1006. stop_debugger_if_running();
  1007. update_gml_preview();
  1008. }
  1009. HackStudioWidget::~HackStudioWidget()
  1010. {
  1011. stop_debugger_if_running();
  1012. }
  1013. HackStudioWidget::ContinueDecision HackStudioWidget::warn_unsaved_changes(const String& prompt)
  1014. {
  1015. if (!any_document_is_dirty())
  1016. return ContinueDecision::Yes;
  1017. auto result = GUI::MessageBox::show(window(), prompt, "Unsaved changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  1018. if (result == GUI::MessageBox::ExecCancel)
  1019. return ContinueDecision::No;
  1020. if (result == GUI::MessageBox::ExecYes) {
  1021. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1022. if (editor_wrapper.document_dirty()) {
  1023. editor_wrapper.save();
  1024. }
  1025. }
  1026. }
  1027. return ContinueDecision::Yes;
  1028. }
  1029. bool HackStudioWidget::any_document_is_dirty() const
  1030. {
  1031. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1032. if (editor_wrapper.document_dirty()) {
  1033. return true;
  1034. }
  1035. }
  1036. return false;
  1037. }
  1038. void HackStudioWidget::update_gml_preview()
  1039. {
  1040. auto gml_content = current_editor_wrapper().filename().ends_with(".gml") ? current_editor_wrapper().editor().text() : "";
  1041. m_gml_preview_widget->load_gml(gml_content);
  1042. }
  1043. void HackStudioWidget::update_window_title()
  1044. {
  1045. window()->set_title(String::formatted("{} - {} - Hack Studio", m_current_editor_wrapper->filename_label().text(), m_project->name()));
  1046. }
  1047. }