HackStudioWidget.cpp 69 KB

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