HackStudioWidget.cpp 72 KB

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