HackStudioWidget.cpp 72 KB

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