HackStudioWidget.cpp 61 KB

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