HackStudioWidget.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  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(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 && m_git_widget->initialized()) {
  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).release_value_but_fixme_should_propagate_errors(), [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").release_value_but_fixme_should_propagate_errors(), [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. if (auto result = Core::File::remove(file, Core::File::RecursionMode::Allowed, false); !result.is_error()) {
  461. auto& error = result.error();
  462. if (is_directory) {
  463. GUI::MessageBox::show(window(),
  464. String::formatted("Removing directory {} from the project failed: {}", error.file, static_cast<Error const&>(error)),
  465. "Removal failed",
  466. GUI::MessageBox::Type::Error);
  467. } else {
  468. GUI::MessageBox::show(window(),
  469. String::formatted("Removing file {} from the project failed: {}", error.file, static_cast<Error const&>(error)),
  470. "Removal failed",
  471. GUI::MessageBox::Type::Error);
  472. }
  473. }
  474. }
  475. },
  476. m_project_tree_view);
  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").release_value_but_fixme_should_propagate_errors(), [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").release_value_but_fixme_should_propagate_errors(), [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").release_value_but_fixme_should_propagate_errors(),
  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").release_value_but_fixme_should_propagate_errors(),
  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").release_value_but_fixme_should_propagate_errors(), [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. while (!path_parts.is_empty() && path_parts[0] == "..") {
  739. path_parts.remove(0);
  740. }
  741. StringBuilder relative_path_builder;
  742. relative_path_builder.join("/", path_parts);
  743. constexpr char SERENITY_LIBS_PREFIX[] = "/usr/src/serenity";
  744. LexicalPath serenity_sources_base(SERENITY_LIBS_PREFIX);
  745. return String::formatted("{}/{}", serenity_sources_base, relative_path_builder.to_string());
  746. }
  747. String HackStudioWidget::get_absolute_path(const String& path) const
  748. {
  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 (path.starts_with("..")) {
  752. return get_full_path_of_serenity_source(path);
  753. }
  754. return m_project->to_absolute_path(path);
  755. }
  756. RefPtr<EditorWrapper> HackStudioWidget::get_editor_of_file(const String& filename)
  757. {
  758. String file_path = filename;
  759. if (filename.starts_with("../")) {
  760. file_path = get_full_path_of_serenity_source(filename);
  761. }
  762. if (!open_file(file_path))
  763. return nullptr;
  764. return current_editor_wrapper();
  765. }
  766. String HackStudioWidget::get_project_executable_path() const
  767. {
  768. // FIXME: Dumb heuristic ahead!
  769. // e.g /my/project => /my/project/project
  770. // TODO: Perhaps a Makefile rule for getting the value of $(PROGRAM) would be better?
  771. return String::formatted("{}/{}", m_project->root_path(), LexicalPath::basename(m_project->root_path()));
  772. }
  773. void HackStudioWidget::build(TerminalWrapper& wrapper)
  774. {
  775. if (active_file().ends_with(".js"))
  776. wrapper.run_command(String::formatted("js -A {}", active_file()));
  777. else
  778. wrapper.run_command("make");
  779. }
  780. void HackStudioWidget::run(TerminalWrapper& wrapper)
  781. {
  782. if (active_file().ends_with(".js"))
  783. wrapper.run_command(String::formatted("js {}", active_file()));
  784. else
  785. wrapper.run_command("make run");
  786. }
  787. void HackStudioWidget::hide_action_tabs()
  788. {
  789. m_action_tab_widget->set_fixed_height(24);
  790. };
  791. Project& HackStudioWidget::project()
  792. {
  793. return *m_project;
  794. }
  795. void HackStudioWidget::set_current_editor_wrapper(RefPtr<EditorWrapper> editor_wrapper)
  796. {
  797. m_current_editor_wrapper = editor_wrapper;
  798. update_window_title();
  799. update_tree_view();
  800. }
  801. void HackStudioWidget::file_renamed(String const& old_name, String const& new_name)
  802. {
  803. auto editor_or_none = m_all_editor_wrappers.first_matching([&old_name](auto const& editor) {
  804. return editor->filename() == old_name;
  805. });
  806. if (editor_or_none.has_value()) {
  807. (*editor_or_none)->set_filename(new_name);
  808. (*editor_or_none)->set_name(new_name);
  809. }
  810. if (m_open_files.contains(old_name)) {
  811. VERIFY(m_open_files_vector.remove_first_matching([&old_name](auto const& file) { return file == old_name; }));
  812. m_open_files_vector.append(new_name);
  813. ProjectFile* f = m_open_files.get(old_name).release_value();
  814. m_open_files.set(new_name, *f);
  815. m_open_files.remove(old_name);
  816. m_open_files_view->model()->invalidate();
  817. }
  818. if (m_file_watcher->is_watching(old_name)) {
  819. VERIFY(!m_file_watcher->remove_watch(old_name).is_error());
  820. VERIFY(!m_file_watcher->add_watch(new_name, Core::FileWatcherEvent::Type::Deleted).is_error());
  821. }
  822. }
  823. void HackStudioWidget::configure_project_tree_view()
  824. {
  825. m_project_tree_view->set_model(m_project->model());
  826. m_project_tree_view->set_selection_mode(GUI::AbstractView::SelectionMode::MultiSelection);
  827. m_project_tree_view->set_editable(true);
  828. m_project_tree_view->aid_create_editing_delegate = [](auto&) {
  829. return make<GUI::StringModelEditingDelegate>();
  830. };
  831. for (int column_index = 0; column_index < m_project->model().column_count(); ++column_index)
  832. m_project_tree_view->set_column_visible(column_index, false);
  833. m_project_tree_view->set_column_visible(GUI::FileSystemModel::Column::Name, true);
  834. m_project_tree_view->on_context_menu_request = [this](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  835. if (index.is_valid()) {
  836. m_project_tree_view_context_menu->popup(event.screen_position(), m_open_selected_action);
  837. }
  838. };
  839. m_project_tree_view->on_selection_change = [this] {
  840. m_open_selected_action->set_enabled(!m_project_tree_view->selection().is_empty());
  841. auto selections = m_project_tree_view->selection().indices();
  842. auto it = selections.find_if([&](auto selected_file) {
  843. return access(m_project->model().full_path(selected_file.parent()).characters(), W_OK) == 0;
  844. });
  845. bool has_permissions = it != selections.end();
  846. m_tree_view_rename_action->set_enabled(has_permissions);
  847. m_delete_action->set_enabled(has_permissions);
  848. };
  849. m_project_tree_view->on_activation = [this](auto& index) {
  850. auto full_path_to_file = m_project->model().full_path(index);
  851. open_file(full_path_to_file);
  852. };
  853. }
  854. void HackStudioWidget::create_open_files_view(GUI::Widget& parent)
  855. {
  856. m_open_files_view = parent.add<GUI::ListView>();
  857. auto open_files_model = GUI::ItemListModel<String>::create(m_open_files_vector);
  858. m_open_files_view->set_model(open_files_model);
  859. m_open_files_view->on_activation = [this](auto& index) {
  860. open_file(index.data().to_string());
  861. };
  862. }
  863. void HackStudioWidget::create_toolbar(GUI::Widget& parent)
  864. {
  865. auto& toolbar = parent.add<GUI::Toolbar>();
  866. toolbar.add_action(*m_new_plain_file_action);
  867. toolbar.add_action(*m_new_directory_action);
  868. toolbar.add_action(*m_save_action);
  869. toolbar.add_action(*m_delete_action);
  870. toolbar.add_separator();
  871. toolbar.add_action(GUI::CommonActions::make_cut_action([this](auto&) { current_editor().cut_action().activate(); }));
  872. toolbar.add_action(GUI::CommonActions::make_copy_action([this](auto&) { current_editor().copy_action().activate(); }));
  873. toolbar.add_action(GUI::CommonActions::make_paste_action([this](auto&) { current_editor().paste_action().activate(); }));
  874. toolbar.add_separator();
  875. toolbar.add_action(GUI::CommonActions::make_undo_action([this](auto&) { current_editor().undo_action().activate(); }));
  876. toolbar.add_action(GUI::CommonActions::make_redo_action([this](auto&) { current_editor().redo_action().activate(); }));
  877. toolbar.add_separator();
  878. toolbar.add_action(*m_build_action);
  879. toolbar.add_separator();
  880. toolbar.add_action(*m_run_action);
  881. toolbar.add_action(*m_stop_action);
  882. toolbar.add_separator();
  883. toolbar.add_action(*m_debug_action);
  884. }
  885. NonnullRefPtr<GUI::Action> HackStudioWidget::create_build_action()
  886. {
  887. return GUI::Action::create("&Build", { Mod_Ctrl, Key_B }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/build.png").release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  888. if (warn_unsaved_changes("There are unsaved changes, do you want to save before building?") == ContinueDecision::No)
  889. return;
  890. reveal_action_tab(*m_terminal_wrapper);
  891. build(*m_terminal_wrapper);
  892. m_stop_action->set_enabled(true);
  893. });
  894. }
  895. NonnullRefPtr<GUI::Action> HackStudioWidget::create_run_action()
  896. {
  897. return GUI::Action::create("&Run", { Mod_Ctrl, Key_R }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-run.png").release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  898. reveal_action_tab(*m_terminal_wrapper);
  899. run(*m_terminal_wrapper);
  900. m_stop_action->set_enabled(true);
  901. });
  902. }
  903. void HackStudioWidget::create_action_tab(GUI::Widget& parent)
  904. {
  905. m_action_tab_widget = parent.add<GUI::TabWidget>();
  906. m_action_tab_widget->set_fixed_height(24);
  907. m_action_tab_widget->on_change = [this](auto&) {
  908. on_action_tab_change();
  909. static bool first_time = true;
  910. if (!first_time)
  911. m_action_tab_widget->set_fixed_height(200);
  912. first_time = false;
  913. };
  914. m_find_in_files_widget = m_action_tab_widget->add_tab<FindInFilesWidget>("Find in files");
  915. m_todo_entries_widget = m_action_tab_widget->add_tab<ToDoEntriesWidget>("TODO");
  916. m_terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Build", false);
  917. m_debug_info_widget = m_action_tab_widget->add_tab<DebugInfoWidget>("Debug");
  918. m_debug_info_widget->on_backtrace_frame_selection = [this](Debug::DebugInfo::SourcePosition const& source_position) {
  919. open_file(get_absolute_path(source_position.file_path), source_position.line_number - 1);
  920. };
  921. m_disassembly_widget = m_action_tab_widget->add_tab<DisassemblyWidget>("Disassembly");
  922. m_git_widget = m_action_tab_widget->add_tab<GitWidget>("Git", LexicalPath(m_project->root_path()));
  923. m_git_widget->set_view_diff_callback([this](const auto& original_content, const auto& diff) {
  924. m_diff_viewer->set_content(original_content, diff);
  925. set_edit_mode(EditMode::Diff);
  926. });
  927. m_gml_preview_widget = m_action_tab_widget->add_tab<GMLPreviewWidget>("GML Preview", "");
  928. ToDoEntries::the().on_update = [this]() {
  929. m_todo_entries_widget->refresh();
  930. };
  931. }
  932. void HackStudioWidget::create_project_tab(GUI::Widget& parent)
  933. {
  934. m_project_tab = parent.add<GUI::TabWidget>();
  935. m_project_tab->set_tab_position(GUI::TabWidget::TabPosition::Bottom);
  936. auto& tree_view_container = m_project_tab->add_tab<GUI::Widget>("Files");
  937. tree_view_container.set_layout<GUI::VerticalBoxLayout>();
  938. tree_view_container.layout()->set_margins(2);
  939. m_project_tree_view = tree_view_container.add<GUI::TreeView>();
  940. configure_project_tree_view();
  941. auto& class_view_container = m_project_tab->add_tab<GUI::Widget>("Classes");
  942. class_view_container.set_layout<GUI::VerticalBoxLayout>();
  943. class_view_container.layout()->set_margins(2);
  944. m_class_view = class_view_container.add<ClassViewWidget>();
  945. ProjectDeclarations::the().on_update = [this]() {
  946. m_class_view->refresh();
  947. };
  948. }
  949. void HackStudioWidget::create_file_menu(GUI::Window& window)
  950. {
  951. auto& file_menu = window.add_menu("&File");
  952. file_menu.add_action(*m_new_project_action);
  953. file_menu.add_action(*m_open_action);
  954. file_menu.add_action(*m_save_action);
  955. file_menu.add_action(*m_save_as_action);
  956. file_menu.add_separator();
  957. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  958. GUI::Application::the()->quit();
  959. }));
  960. }
  961. void HackStudioWidget::create_project_menu(GUI::Window& window)
  962. {
  963. auto& project_menu = window.add_menu("&Project");
  964. auto& new_submenu = project_menu.add_submenu("New");
  965. for (auto& new_file_action : m_new_file_actions) {
  966. new_submenu.add_action(new_file_action);
  967. }
  968. new_submenu.add_action(*m_new_plain_file_action);
  969. new_submenu.add_separator();
  970. new_submenu.add_action(*m_new_directory_action);
  971. }
  972. void HackStudioWidget::create_edit_menu(GUI::Window& window)
  973. {
  974. auto& edit_menu = window.add_menu("&Edit");
  975. edit_menu.add_action(GUI::Action::create("&Find in Files...", { Mod_Ctrl | Mod_Shift, Key_F }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find.png").release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  976. reveal_action_tab(*m_find_in_files_widget);
  977. m_find_in_files_widget->focus_textbox_and_select_all();
  978. }));
  979. edit_menu.add_separator();
  980. auto vim_emulation_setting_action = GUI::Action::create_checkable("&Vim Emulation", { Mod_Ctrl | Mod_Shift | Mod_Alt, Key_V }, [this](auto& action) {
  981. if (action.is_checked())
  982. current_editor().set_editing_engine(make<GUI::VimEditingEngine>());
  983. else
  984. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  985. });
  986. vim_emulation_setting_action->set_checked(false);
  987. edit_menu.add_action(vim_emulation_setting_action);
  988. }
  989. void HackStudioWidget::create_build_menu(GUI::Window& window)
  990. {
  991. auto& build_menu = window.add_menu("&Build");
  992. build_menu.add_action(*m_build_action);
  993. build_menu.add_separator();
  994. build_menu.add_action(*m_run_action);
  995. build_menu.add_action(*m_stop_action);
  996. build_menu.add_separator();
  997. build_menu.add_action(*m_debug_action);
  998. }
  999. void HackStudioWidget::create_view_menu(GUI::Window& window)
  1000. {
  1001. auto hide_action_tabs_action = GUI::Action::create("&Hide Action Tabs", { Mod_Ctrl | Mod_Shift, Key_X }, [this](auto&) {
  1002. hide_action_tabs();
  1003. });
  1004. auto open_locator_action = GUI::Action::create("Open &Locator", { Mod_Ctrl, Key_K }, [this](auto&) {
  1005. m_locator->open();
  1006. });
  1007. auto show_dotfiles_action = GUI::Action::create_checkable("S&how Dotfiles", { Mod_Ctrl, Key_H }, [&](auto& checked) {
  1008. project().model().set_should_show_dotfiles(checked.is_checked());
  1009. });
  1010. auto& view_menu = window.add_menu("&View");
  1011. view_menu.add_action(hide_action_tabs_action);
  1012. view_menu.add_action(open_locator_action);
  1013. view_menu.add_action(show_dotfiles_action);
  1014. view_menu.add_separator();
  1015. m_wrapping_mode_actions.set_exclusive(true);
  1016. auto& wrapping_mode_menu = view_menu.add_submenu("&Wrapping Mode");
  1017. m_no_wrapping_action = GUI::Action::create_checkable("&No Wrapping", [&](auto&) {
  1018. for (auto& wrapper : m_all_editor_wrappers)
  1019. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  1020. });
  1021. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap &Anywhere", [&](auto&) {
  1022. for (auto& wrapper : m_all_editor_wrappers)
  1023. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  1024. });
  1025. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at &Words", [&](auto&) {
  1026. for (auto& wrapper : m_all_editor_wrappers)
  1027. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  1028. });
  1029. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  1030. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  1031. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  1032. wrapping_mode_menu.add_action(*m_no_wrapping_action);
  1033. wrapping_mode_menu.add_action(*m_wrap_anywhere_action);
  1034. wrapping_mode_menu.add_action(*m_wrap_at_words_action);
  1035. m_no_wrapping_action->set_checked(true);
  1036. m_editor_font_action = GUI::Action::create("Editor &Font...", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-font-editor.png").release_value_but_fixme_should_propagate_errors(),
  1037. [&](auto&) {
  1038. auto picker = GUI::FontPicker::construct(&window, m_editor_font, false);
  1039. if (picker->exec() == GUI::Dialog::ExecOK) {
  1040. change_editor_font(picker->font());
  1041. }
  1042. });
  1043. view_menu.add_action(*m_editor_font_action);
  1044. view_menu.add_separator();
  1045. view_menu.add_action(*m_add_editor_action);
  1046. view_menu.add_action(*m_remove_current_editor_action);
  1047. view_menu.add_action(*m_add_terminal_action);
  1048. view_menu.add_action(*m_remove_current_terminal_action);
  1049. view_menu.add_separator();
  1050. create_location_history_actions();
  1051. view_menu.add_action(*m_locations_history_back_action);
  1052. view_menu.add_action(*m_locations_history_forward_action);
  1053. }
  1054. void HackStudioWidget::create_help_menu(GUI::Window& window)
  1055. {
  1056. auto& help_menu = window.add_menu("&Help");
  1057. help_menu.add_action(GUI::CommonActions::make_about_action("Hack Studio", GUI::Icon::default_icon("app-hack-studio"), &window));
  1058. }
  1059. NonnullRefPtr<GUI::Action> HackStudioWidget::create_stop_action()
  1060. {
  1061. auto action = GUI::Action::create("&Stop", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-stop.png").release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  1062. if (!Debugger::the().session()) {
  1063. m_terminal_wrapper->kill_running_command();
  1064. return;
  1065. }
  1066. Debugger::the().stop();
  1067. });
  1068. action->set_enabled(false);
  1069. return action;
  1070. }
  1071. void HackStudioWidget::initialize_menubar(GUI::Window& window)
  1072. {
  1073. create_file_menu(window);
  1074. create_project_menu(window);
  1075. create_edit_menu(window);
  1076. create_build_menu(window);
  1077. create_view_menu(window);
  1078. create_help_menu(window);
  1079. }
  1080. void HackStudioWidget::update_statusbar()
  1081. {
  1082. m_statusbar->set_text(0, String::formatted("Ln {}, Col {}", current_editor().cursor().line() + 1, current_editor().cursor().column()));
  1083. StringBuilder builder;
  1084. if (current_editor().has_selection()) {
  1085. String selected_text = current_editor().selected_text();
  1086. auto word_count = current_editor().number_of_selected_words();
  1087. builder.appendff("Selected: {} {} ({} {})", selected_text.length(), selected_text.length() == 1 ? "character" : "characters", word_count, word_count != 1 ? "words" : "word");
  1088. }
  1089. m_statusbar->set_text(1, builder.to_string());
  1090. m_statusbar->set_text(2, current_editor_wrapper().editor().code_document().language_name());
  1091. }
  1092. void HackStudioWidget::handle_external_file_deletion(const String& filepath)
  1093. {
  1094. close_file_in_all_editors(filepath);
  1095. }
  1096. void HackStudioWidget::stop_debugger_if_running()
  1097. {
  1098. if (!m_debugger_thread.is_null()) {
  1099. Debugger::the().stop();
  1100. dbgln("Waiting for debugger thread to terminate");
  1101. auto rc = m_debugger_thread->join();
  1102. if (rc.is_error()) {
  1103. warnln("pthread_join: {}", strerror(rc.error().value()));
  1104. dbgln("error joining debugger thread");
  1105. }
  1106. }
  1107. }
  1108. void HackStudioWidget::close_current_project()
  1109. {
  1110. m_editors_splitter->remove_all_children();
  1111. m_all_editor_wrappers.clear();
  1112. m_open_files.clear();
  1113. m_open_files_vector.clear();
  1114. add_new_editor(*m_editors_splitter);
  1115. m_find_in_files_widget->reset();
  1116. m_todo_entries_widget->clear();
  1117. m_terminal_wrapper->clear_including_history();
  1118. stop_debugger_if_running();
  1119. update_gml_preview();
  1120. }
  1121. HackStudioWidget::~HackStudioWidget()
  1122. {
  1123. stop_debugger_if_running();
  1124. }
  1125. HackStudioWidget::ContinueDecision HackStudioWidget::warn_unsaved_changes(const String& prompt)
  1126. {
  1127. if (!any_document_is_dirty())
  1128. return ContinueDecision::Yes;
  1129. auto result = GUI::MessageBox::show(window(), prompt, "Unsaved changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  1130. if (result == GUI::MessageBox::ExecCancel)
  1131. return ContinueDecision::No;
  1132. if (result == GUI::MessageBox::ExecYes) {
  1133. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1134. if (editor_wrapper.editor().document().is_modified()) {
  1135. editor_wrapper.save();
  1136. }
  1137. }
  1138. }
  1139. return ContinueDecision::Yes;
  1140. }
  1141. bool HackStudioWidget::any_document_is_dirty() const
  1142. {
  1143. return any_of(m_all_editor_wrappers, [](auto& editor_wrapper) {
  1144. return editor_wrapper.editor().document().is_modified();
  1145. });
  1146. }
  1147. void HackStudioWidget::update_gml_preview()
  1148. {
  1149. auto gml_content = current_editor_wrapper().filename().ends_with(".gml") ? current_editor_wrapper().editor().text() : "";
  1150. m_gml_preview_widget->load_gml(gml_content);
  1151. }
  1152. void HackStudioWidget::update_tree_view()
  1153. {
  1154. auto index = m_project->model().index(m_current_editor_wrapper->filename(), GUI::FileSystemModel::Column::Name);
  1155. if (index.is_valid()) {
  1156. m_project_tree_view->expand_all_parents_of(index);
  1157. m_project_tree_view->set_cursor(index, GUI::AbstractView::SelectionUpdate::Set);
  1158. }
  1159. }
  1160. void HackStudioWidget::update_window_title()
  1161. {
  1162. window()->set_title(String::formatted("{} - {} - Hack Studio", m_current_editor_wrapper->filename_label().text(), m_project->name()));
  1163. }
  1164. void HackStudioWidget::on_cursor_change()
  1165. {
  1166. update_statusbar();
  1167. if (current_editor_wrapper().filename().is_null())
  1168. return;
  1169. auto current_location = current_project_location();
  1170. if (m_locations_history_end_index != 0) {
  1171. auto last = m_locations_history[m_locations_history_end_index - 1];
  1172. if (current_location.filename == last.filename && current_location.line == last.line)
  1173. return;
  1174. }
  1175. // Clear "Go Forward" locations
  1176. VERIFY(m_locations_history_end_index <= m_locations_history.size());
  1177. m_locations_history.remove(m_locations_history_end_index, m_locations_history.size() - m_locations_history_end_index);
  1178. m_locations_history.append(current_location);
  1179. constexpr size_t max_locations = 30;
  1180. if (m_locations_history.size() > max_locations)
  1181. m_locations_history.take_first();
  1182. m_locations_history_end_index = m_locations_history.size();
  1183. update_history_actions();
  1184. }
  1185. void HackStudioWidget::create_location_history_actions()
  1186. {
  1187. m_locations_history_back_action = GUI::Action::create("Go Back", { Mod_Alt | Mod_Shift, Key_Left }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-back.png").release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  1188. if (m_locations_history_end_index <= 1)
  1189. return;
  1190. auto location = m_locations_history[m_locations_history_end_index - 2];
  1191. --m_locations_history_end_index;
  1192. m_locations_history_disabled = true;
  1193. open_file(location.filename, location.line, location.column);
  1194. m_locations_history_disabled = false;
  1195. update_history_actions();
  1196. });
  1197. m_locations_history_forward_action = GUI::Action::create("Go Forward", { Mod_Alt | Mod_Shift, Key_Right }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-forward.png").release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  1198. if (m_locations_history_end_index == m_locations_history.size())
  1199. return;
  1200. auto location = m_locations_history[m_locations_history_end_index];
  1201. ++m_locations_history_end_index;
  1202. m_locations_history_disabled = true;
  1203. open_file(location.filename, location.line, location.column);
  1204. m_locations_history_disabled = false;
  1205. update_history_actions();
  1206. });
  1207. m_locations_history_forward_action->set_enabled(false);
  1208. }
  1209. HackStudioWidget::ProjectLocation HackStudioWidget::current_project_location() const
  1210. {
  1211. return ProjectLocation { current_editor_wrapper().filename(), current_editor().cursor().line(), current_editor().cursor().column() };
  1212. }
  1213. void HackStudioWidget::update_history_actions()
  1214. {
  1215. if (m_locations_history_end_index <= 1)
  1216. m_locations_history_back_action->set_enabled(false);
  1217. else
  1218. m_locations_history_back_action->set_enabled(true);
  1219. if (m_locations_history_end_index == m_locations_history.size())
  1220. m_locations_history_forward_action->set_enabled(false);
  1221. else
  1222. m_locations_history_forward_action->set_enabled(true);
  1223. }
  1224. RefPtr<Gfx::Font> HackStudioWidget::read_editor_font_from_config()
  1225. {
  1226. auto font_family = Config::read_string("HackStudio", "EditorFont", "Family", "Csilla");
  1227. auto font_variant = Config::read_string("HackStudio", "EditorFont", "Variant", "Regular");
  1228. auto font_size = Config::read_i32("HackStudio", "EditorFont", "Size", 10);
  1229. auto font = Gfx::FontDatabase::the().get(font_family, font_variant, font_size);
  1230. if (font.is_null())
  1231. return Gfx::FontDatabase::the().default_fixed_width_font();
  1232. return font;
  1233. }
  1234. void HackStudioWidget::change_editor_font(RefPtr<Gfx::Font> font)
  1235. {
  1236. m_editor_font = move(font);
  1237. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1238. editor_wrapper.editor().set_font(*m_editor_font);
  1239. }
  1240. Config::write_string("HackStudio", "EditorFont", "Family", m_editor_font->family());
  1241. Config::write_string("HackStudio", "EditorFont", "Variant", m_editor_font->variant());
  1242. Config::write_i32("HackStudio", "EditorFont", "Size", m_editor_font->presentation_size());
  1243. }
  1244. void HackStudioWidget::open_coredump(String const& coredump_path)
  1245. {
  1246. open_project("/usr/src/serenity");
  1247. m_mode = Mode::Coredump;
  1248. m_coredump_inspector = Coredump::Inspector::create(coredump_path, [this](float progress) {
  1249. window()->set_progress(progress * 100);
  1250. });
  1251. window()->set_progress(0);
  1252. if (m_coredump_inspector) {
  1253. m_debug_info_widget->update_state(*m_coredump_inspector, m_coredump_inspector->get_registers());
  1254. reveal_action_tab(*m_debug_info_widget);
  1255. }
  1256. }
  1257. }