HackStudioWidget.cpp 75 KB

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