HackStudioWidget.cpp 70 KB

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