HackStudioWidget.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  4. * Copyright (c) 2020-2021, 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/LexicalPath.h>
  26. #include <AK/StringBuilder.h>
  27. #include <Kernel/API/InodeWatcherEvent.h>
  28. #include <LibCore/ArgsParser.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/InputBox.h>
  44. #include <LibGUI/ItemListModel.h>
  45. #include <LibGUI/Label.h>
  46. #include <LibGUI/Menu.h>
  47. #include <LibGUI/Menubar.h>
  48. #include <LibGUI/MessageBox.h>
  49. #include <LibGUI/RegularEditingEngine.h>
  50. #include <LibGUI/Splitter.h>
  51. #include <LibGUI/StackWidget.h>
  52. #include <LibGUI/Statusbar.h>
  53. #include <LibGUI/TabWidget.h>
  54. #include <LibGUI/TableView.h>
  55. #include <LibGUI/TextBox.h>
  56. #include <LibGUI/TextEditor.h>
  57. #include <LibGUI/Toolbar.h>
  58. #include <LibGUI/ToolbarContainer.h>
  59. #include <LibGUI/TreeView.h>
  60. #include <LibGUI/VimEditingEngine.h>
  61. #include <LibGUI/Widget.h>
  62. #include <LibGUI/Window.h>
  63. #include <LibGfx/FontDatabase.h>
  64. #include <LibGfx/Palette.h>
  65. #include <LibThreading/Mutex.h>
  66. #include <LibThreading/Thread.h>
  67. #include <LibVT/TerminalWidget.h>
  68. #include <fcntl.h>
  69. #include <spawn.h>
  70. #include <stdio.h>
  71. #include <sys/stat.h>
  72. #include <sys/types.h>
  73. #include <sys/wait.h>
  74. #include <unistd.h>
  75. namespace HackStudio {
  76. HackStudioWidget::HackStudioWidget(const String& path_to_project)
  77. {
  78. set_fill_with_background_color(true);
  79. set_layout<GUI::VerticalBoxLayout>();
  80. layout()->set_spacing(2);
  81. open_project(path_to_project);
  82. auto& toolbar_container = add<GUI::ToolbarContainer>();
  83. auto& outer_splitter = add<GUI::HorizontalSplitter>();
  84. outer_splitter.layout()->set_spacing(5);
  85. auto& left_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  86. left_hand_splitter.layout()->set_spacing(5);
  87. left_hand_splitter.set_fixed_width(150);
  88. create_project_tab(left_hand_splitter);
  89. m_project_tree_view_context_menu = create_project_tree_view_context_menu();
  90. create_open_files_view(left_hand_splitter);
  91. m_right_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  92. m_right_hand_stack = m_right_hand_splitter->add<GUI::StackWidget>();
  93. // Put a placeholder widget front & center since we don't have a file open yet.
  94. m_right_hand_stack->add<GUI::Widget>();
  95. m_diff_viewer = m_right_hand_stack->add<DiffViewer>();
  96. m_editors_splitter = m_right_hand_stack->add<GUI::VerticalSplitter>();
  97. m_editors_splitter->layout()->set_spacing(5);
  98. m_editors_splitter->layout()->set_margins({ 3, 0, 0 });
  99. add_new_editor(*m_editors_splitter);
  100. m_switch_to_next_editor = create_switch_to_next_editor_action();
  101. m_switch_to_previous_editor = create_switch_to_previous_editor_action();
  102. m_remove_current_editor_action = create_remove_current_editor_action();
  103. m_open_action = create_open_action();
  104. m_save_action = create_save_action();
  105. m_save_as_action = create_save_as_action();
  106. m_new_project_action = create_new_project_action();
  107. create_action_tab(*m_right_hand_splitter);
  108. m_add_editor_action = create_add_editor_action();
  109. m_add_terminal_action = create_add_terminal_action();
  110. m_remove_current_terminal_action = create_remove_current_terminal_action();
  111. m_locator = add<Locator>();
  112. m_terminal_wrapper->on_command_exit = [this] {
  113. m_stop_action->set_enabled(false);
  114. };
  115. m_build_action = create_build_action();
  116. m_run_action = create_run_action();
  117. m_stop_action = create_stop_action();
  118. m_debug_action = create_debug_action();
  119. initialize_debugger();
  120. create_toolbar(toolbar_container);
  121. m_statusbar = add<GUI::Statusbar>(3);
  122. auto maybe_watcher = Core::FileWatcher::create();
  123. if (maybe_watcher.is_error()) {
  124. warnln("Couldn't create a file watcher, deleted files won't be noticed! Error: {}", maybe_watcher.error());
  125. } else {
  126. m_file_watcher = maybe_watcher.release_value();
  127. m_file_watcher->on_change = [this](Core::FileWatcherEvent const& event) {
  128. if (event.type != Core::FileWatcherEvent::Type::Deleted)
  129. return;
  130. if (event.event_path.starts_with(project().root_path())) {
  131. String relative_path = LexicalPath::relative_path(event.event_path, project().root_path());
  132. handle_external_file_deletion(relative_path);
  133. } else {
  134. handle_external_file_deletion(event.event_path);
  135. }
  136. };
  137. }
  138. }
  139. void HackStudioWidget::update_actions()
  140. {
  141. auto is_remove_terminal_enabled = [this]() {
  142. auto widget = m_action_tab_widget->active_widget();
  143. if (!widget)
  144. return false;
  145. if ("TerminalWrapper"sv != widget->class_name())
  146. return false;
  147. if (!reinterpret_cast<TerminalWrapper*>(widget)->user_spawned())
  148. return false;
  149. return true;
  150. };
  151. m_remove_current_editor_action->set_enabled(m_all_editor_wrappers.size() > 1);
  152. m_remove_current_terminal_action->set_enabled(is_remove_terminal_enabled());
  153. }
  154. void HackStudioWidget::on_action_tab_change()
  155. {
  156. update_actions();
  157. if (auto* active_widget = m_action_tab_widget->active_widget()) {
  158. if (is<GitWidget>(*active_widget))
  159. static_cast<GitWidget&>(*active_widget).refresh();
  160. }
  161. }
  162. void HackStudioWidget::open_project(const String& root_path)
  163. {
  164. if (chdir(root_path.characters()) < 0) {
  165. perror("chdir");
  166. exit(1);
  167. }
  168. if (m_project) {
  169. close_current_project();
  170. }
  171. m_project = Project::open_with_root_path(root_path);
  172. VERIFY(m_project);
  173. if (m_project_tree_view) {
  174. m_project_tree_view->set_model(m_project->model());
  175. m_project_tree_view->update();
  176. }
  177. if (Debugger::is_initialized()) {
  178. auto& debugger = Debugger::the();
  179. debugger.reset_breakpoints();
  180. debugger.set_source_root(m_project->root_path());
  181. }
  182. for (auto& editor_wrapper : m_all_editor_wrappers)
  183. editor_wrapper.set_project_root(LexicalPath(m_project->root_path()));
  184. }
  185. Vector<String> HackStudioWidget::selected_file_paths() const
  186. {
  187. Vector<String> files;
  188. m_project_tree_view->selection().for_each_index([&](const GUI::ModelIndex& index) {
  189. String sub_path = index.data().as_string();
  190. GUI::ModelIndex parent_or_invalid = index.parent();
  191. while (parent_or_invalid.is_valid()) {
  192. sub_path = String::formatted("{}/{}", parent_or_invalid.data().as_string(), sub_path);
  193. parent_or_invalid = parent_or_invalid.parent();
  194. }
  195. files.append(sub_path);
  196. });
  197. return files;
  198. }
  199. bool HackStudioWidget::open_file(const String& full_filename)
  200. {
  201. String filename = full_filename;
  202. if (full_filename.starts_with(project().root_path())) {
  203. filename = LexicalPath::relative_path(full_filename, project().root_path());
  204. }
  205. dbgln("HackStudio is opening {}", filename);
  206. if (Core::File::is_directory(filename) || !Core::File::exists(filename))
  207. return false;
  208. if (!active_file().is_empty()) {
  209. // Since the file is previously open, it should always be in m_open_files.
  210. VERIFY(m_open_files.find(active_file()) != m_open_files.end());
  211. auto previous_open_project_file = m_open_files.get(active_file()).value();
  212. // Update the scrollbar values of the previous_open_project_file and save them to m_open_files.
  213. previous_open_project_file->vertical_scroll_value(current_editor().vertical_scrollbar().value());
  214. previous_open_project_file->horizontal_scroll_value(current_editor().horizontal_scrollbar().value());
  215. }
  216. RefPtr<ProjectFile> new_project_file = nullptr;
  217. if (auto it = m_open_files.find(filename); it != m_open_files.end()) {
  218. new_project_file = it->value;
  219. } else {
  220. new_project_file = m_project->get_file(filename);
  221. m_open_files.set(filename, *new_project_file);
  222. m_open_files_vector.append(filename);
  223. if (!m_file_watcher.is_null()) {
  224. auto watch_result = m_file_watcher->add_watch(filename, Core::FileWatcherEvent::Type::Deleted);
  225. if (watch_result.is_error()) {
  226. warnln("Couldn't watch '{}'", filename);
  227. }
  228. }
  229. m_open_files_view->model()->invalidate();
  230. }
  231. current_editor().set_document(const_cast<GUI::TextDocument&>(new_project_file->document()));
  232. if (new_project_file->could_render_text()) {
  233. current_editor_wrapper().set_mode_displayable();
  234. } else {
  235. current_editor_wrapper().set_mode_non_displayable();
  236. }
  237. current_editor().horizontal_scrollbar().set_value(new_project_file->horizontal_scroll_value());
  238. current_editor().vertical_scrollbar().set_value(new_project_file->vertical_scroll_value());
  239. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  240. set_edit_mode(EditMode::Text);
  241. String relative_file_path = filename;
  242. if (filename.starts_with(m_project->root_path()))
  243. relative_file_path = filename.substring(m_project->root_path().length() + 1);
  244. m_project_tree_view->update();
  245. current_editor_wrapper().set_filename(filename);
  246. current_editor().set_focus(true);
  247. current_editor().on_cursor_change = [this] { update_statusbar(); };
  248. current_editor().on_change = [this] { update_gml_preview(); };
  249. update_gml_preview();
  250. return true;
  251. }
  252. void HackStudioWidget::close_file_in_all_editors(String const& filename)
  253. {
  254. m_open_files.remove(filename);
  255. m_open_files_vector.remove_all_matching(
  256. [&filename](String const& element) { return element == filename; });
  257. for (auto& editor_wrapper : m_all_editor_wrappers) {
  258. Editor& editor = editor_wrapper.editor();
  259. String editor_file_path = editor.code_document().file_path();
  260. String relative_editor_file_path = LexicalPath::relative_path(editor_file_path, project().root_path());
  261. if (relative_editor_file_path == filename) {
  262. if (m_open_files_vector.is_empty()) {
  263. editor.set_document(CodeDocument::create());
  264. editor_wrapper.set_filename("");
  265. } else {
  266. auto& first_path = m_open_files_vector[0];
  267. auto& document = m_open_files.get(first_path).value()->code_document();
  268. editor.set_document(document);
  269. editor_wrapper.set_filename(first_path);
  270. }
  271. }
  272. }
  273. m_open_files_view->model()->invalidate();
  274. }
  275. EditorWrapper& HackStudioWidget::current_editor_wrapper()
  276. {
  277. VERIFY(m_current_editor_wrapper);
  278. return *m_current_editor_wrapper;
  279. }
  280. GUI::TextEditor& HackStudioWidget::current_editor()
  281. {
  282. return current_editor_wrapper().editor();
  283. }
  284. void HackStudioWidget::set_edit_mode(EditMode mode)
  285. {
  286. if (mode == EditMode::Text) {
  287. m_right_hand_stack->set_active_widget(m_editors_splitter);
  288. } else if (mode == EditMode::Diff) {
  289. m_right_hand_stack->set_active_widget(m_diff_viewer);
  290. } else {
  291. VERIFY_NOT_REACHED();
  292. }
  293. m_right_hand_stack->active_widget()->update();
  294. }
  295. NonnullRefPtr<GUI::Menu> HackStudioWidget::create_project_tree_view_context_menu()
  296. {
  297. m_open_selected_action = create_open_selected_action();
  298. m_show_in_file_manager_action = create_show_in_file_manager_action();
  299. m_new_file_action = create_new_file_action();
  300. m_new_directory_action = create_new_directory_action();
  301. m_delete_action = create_delete_action();
  302. auto project_tree_view_context_menu = GUI::Menu::construct("Project Files");
  303. project_tree_view_context_menu->add_action(*m_open_selected_action);
  304. project_tree_view_context_menu->add_action(*m_show_in_file_manager_action);
  305. // TODO: Rename, cut, copy, duplicate with new name...
  306. project_tree_view_context_menu->add_separator();
  307. project_tree_view_context_menu->add_action(*m_new_file_action);
  308. project_tree_view_context_menu->add_action(*m_new_directory_action);
  309. project_tree_view_context_menu->add_action(*m_delete_action);
  310. return project_tree_view_context_menu;
  311. }
  312. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_file_action()
  313. {
  314. return GUI::Action::create("New &File...", { Mod_Ctrl, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/new.png"), [this](const GUI::Action&) {
  315. String filename;
  316. if (GUI::InputBox::show(window(), filename, "Enter name of new file:", "Add new file to project") != GUI::InputBox::ExecOK)
  317. return;
  318. auto path_to_selected = selected_file_paths();
  319. String filepath;
  320. if (!path_to_selected.is_empty()) {
  321. VERIFY(Core::File::exists(path_to_selected.first()));
  322. LexicalPath selected(path_to_selected.first());
  323. String dir_path;
  324. if (Core::File::is_directory(selected.string()))
  325. dir_path = selected.string();
  326. else
  327. dir_path = selected.dirname();
  328. filepath = String::formatted("{}/", dir_path);
  329. }
  330. filepath = String::formatted("{}{}", filepath, filename);
  331. auto file = Core::File::construct(filepath);
  332. if (!file->open((Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::MustBeNew))) {
  333. GUI::MessageBox::show(window(), String::formatted("Failed to create '{}'", filepath), "Error", GUI::MessageBox::Type::Error);
  334. return;
  335. }
  336. open_file(filepath);
  337. });
  338. }
  339. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_directory_action()
  340. {
  341. return GUI::Action::create("&New Directory...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/mkdir.png"), [this](const GUI::Action&) {
  342. String directory_name;
  343. if (GUI::InputBox::show(window(), directory_name, "Enter name of new directory:", "Add new folder to project") != GUI::InputBox::ExecOK)
  344. return;
  345. auto path_to_selected = selected_file_paths();
  346. if (!path_to_selected.is_empty()) {
  347. LexicalPath selected(path_to_selected.first());
  348. String dir_path;
  349. if (Core::File::is_directory(selected.string()))
  350. dir_path = selected.string();
  351. else
  352. dir_path = selected.dirname();
  353. directory_name = String::formatted("{}/{}", dir_path, directory_name);
  354. }
  355. auto formatted_dir_name = LexicalPath::canonicalized_path(String::formatted("{}/{}", m_project->model().root_path(), directory_name));
  356. int rc = mkdir(formatted_dir_name.characters(), 0755);
  357. if (rc < 0) {
  358. GUI::MessageBox::show(window(), "Failed to create new directory", "Error", GUI::MessageBox::Type::Error);
  359. return;
  360. }
  361. });
  362. }
  363. NonnullRefPtr<GUI::Action> HackStudioWidget::create_open_selected_action()
  364. {
  365. auto open_selected_action = GUI::Action::create("Open", [this](const GUI::Action&) {
  366. auto files = selected_file_paths();
  367. for (auto& file : files)
  368. open_file(file);
  369. });
  370. open_selected_action->set_enabled(true);
  371. return open_selected_action;
  372. }
  373. NonnullRefPtr<GUI::Action> HackStudioWidget::create_show_in_file_manager_action()
  374. {
  375. auto show_in_file_manager_action = GUI::Action::create("Show in File Manager", [this](const GUI::Action&) {
  376. auto files = selected_file_paths();
  377. for (auto& file : files)
  378. Desktop::Launcher::open(URL::create_with_file_protocol(m_project->root_path(), file));
  379. });
  380. show_in_file_manager_action->set_enabled(true);
  381. show_in_file_manager_action->set_icon(GUI::Icon::default_icon("app-file-manager").bitmap_for_size(16));
  382. return show_in_file_manager_action;
  383. }
  384. NonnullRefPtr<GUI::Action> HackStudioWidget::create_delete_action()
  385. {
  386. auto delete_action = GUI::CommonActions::make_delete_action([this](const GUI::Action&) {
  387. auto files = selected_file_paths();
  388. if (files.is_empty())
  389. return;
  390. String message;
  391. if (files.size() == 1) {
  392. LexicalPath file(files[0]);
  393. message = String::formatted("Really remove {} from disk?", file.basename());
  394. } else {
  395. message = String::formatted("Really remove {} files from disk?", files.size());
  396. }
  397. auto result = GUI::MessageBox::show(window(),
  398. message,
  399. "Confirm deletion",
  400. GUI::MessageBox::Type::Warning,
  401. GUI::MessageBox::InputType::OKCancel);
  402. if (result == GUI::MessageBox::ExecCancel)
  403. return;
  404. for (auto& file : files) {
  405. struct stat st;
  406. if (lstat(file.characters(), &st) < 0) {
  407. GUI::MessageBox::show(window(),
  408. String::formatted("lstat ({}) failed: {}", file, strerror(errno)),
  409. "Removal failed",
  410. GUI::MessageBox::Type::Error);
  411. break;
  412. }
  413. bool is_directory = S_ISDIR(st.st_mode);
  414. auto result = Core::File::remove(file, Core::File::RecursionMode::Allowed, false);
  415. if (result.is_error()) {
  416. auto& error = result.error();
  417. if (is_directory) {
  418. GUI::MessageBox::show(window(),
  419. String::formatted("Removing directory {} from the project failed: {}", error.file, error.error_code),
  420. "Removal failed",
  421. GUI::MessageBox::Type::Error);
  422. } else {
  423. GUI::MessageBox::show(window(),
  424. String::formatted("Removing file {} from the project failed: {}", error.file, error.error_code),
  425. "Removal failed",
  426. GUI::MessageBox::Type::Error);
  427. }
  428. }
  429. }
  430. });
  431. delete_action->set_enabled(false);
  432. return delete_action;
  433. }
  434. NonnullRefPtr<GUI::Action> HackStudioWidget::create_new_project_action()
  435. {
  436. return GUI::Action::create("&New Project...", { Mod_Ctrl | Mod_Shift, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/hackstudio-project.png"), [this](const GUI::Action&) {
  437. auto dialog = NewProjectDialog::construct(window());
  438. dialog->set_icon(window()->icon());
  439. auto result = dialog->exec();
  440. if (result == GUI::Dialog::ExecResult::ExecOK && dialog->created_project_path().has_value())
  441. open_project(dialog->created_project_path().value());
  442. });
  443. }
  444. void HackStudioWidget::add_new_editor(GUI::Widget& parent)
  445. {
  446. auto wrapper = EditorWrapper::construct();
  447. if (m_action_tab_widget) {
  448. parent.insert_child_before(wrapper, *m_action_tab_widget);
  449. } else {
  450. parent.add_child(wrapper);
  451. }
  452. m_current_editor_wrapper = wrapper;
  453. m_all_editor_wrappers.append(wrapper);
  454. wrapper->editor().set_focus(true);
  455. wrapper->set_project_root(LexicalPath(m_project->root_path()));
  456. wrapper->editor().on_cursor_change = [this] { update_statusbar(); };
  457. wrapper->editor().on_change = [this] { update_gml_preview(); };
  458. set_edit_mode(EditMode::Text);
  459. }
  460. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_next_editor_action()
  461. {
  462. return GUI::Action::create("Switch to &Next Editor", { Mod_Ctrl, Key_E }, [this](auto&) {
  463. if (m_all_editor_wrappers.size() <= 1)
  464. return;
  465. Vector<EditorWrapper&> wrappers;
  466. m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) {
  467. wrappers.append(child);
  468. return IterationDecision::Continue;
  469. });
  470. for (size_t i = 0; i < wrappers.size(); ++i) {
  471. if (m_current_editor_wrapper.ptr() == &wrappers[i]) {
  472. if (i == wrappers.size() - 1)
  473. wrappers[0].editor().set_focus(true);
  474. else
  475. wrappers[i + 1].editor().set_focus(true);
  476. }
  477. }
  478. });
  479. }
  480. NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_previous_editor_action()
  481. {
  482. return GUI::Action::create("Switch to &Previous Editor", { Mod_Ctrl | Mod_Shift, Key_E }, [this](auto&) {
  483. if (m_all_editor_wrappers.size() <= 1)
  484. return;
  485. Vector<EditorWrapper&> wrappers;
  486. m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) {
  487. wrappers.append(child);
  488. return IterationDecision::Continue;
  489. });
  490. for (int i = wrappers.size() - 1; i >= 0; --i) {
  491. if (m_current_editor_wrapper.ptr() == &wrappers[i]) {
  492. if (i == 0)
  493. wrappers.last().editor().set_focus(true);
  494. else
  495. wrappers[i - 1].editor().set_focus(true);
  496. }
  497. }
  498. });
  499. }
  500. NonnullRefPtr<GUI::Action> HackStudioWidget::create_remove_current_editor_action()
  501. {
  502. return GUI::Action::create("&Remove Current Editor", { Mod_Alt | Mod_Shift, Key_E }, [this](auto&) {
  503. if (m_all_editor_wrappers.size() <= 1)
  504. return;
  505. auto wrapper = m_current_editor_wrapper;
  506. m_switch_to_next_editor->activate();
  507. m_editors_splitter->remove_child(*wrapper);
  508. auto child_editors = m_editors_splitter->child_widgets();
  509. bool has_child_to_fill_space = false;
  510. for (auto& editor : child_editors) {
  511. if (editor.max_height() == -1) {
  512. has_child_to_fill_space = true;
  513. break;
  514. }
  515. }
  516. if (!has_child_to_fill_space)
  517. child_editors.last().set_max_height(-1);
  518. m_all_editor_wrappers.remove_first_matching([&wrapper](auto& entry) { return entry == wrapper.ptr(); });
  519. update_actions();
  520. });
  521. }
  522. NonnullRefPtr<GUI::Action> HackStudioWidget::create_open_action()
  523. {
  524. return GUI::Action::create("&Open Project...", { Mod_Ctrl | Mod_Shift, Key_O }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/open.png"), [this](auto&) {
  525. auto open_path = GUI::FilePicker::get_open_filepath(window(), "Open project", m_project->root_path(), true);
  526. if (!open_path.has_value())
  527. return;
  528. open_project(open_path.value());
  529. update_actions();
  530. });
  531. }
  532. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_action()
  533. {
  534. return GUI::CommonActions::make_save_action([&](auto&) {
  535. if (active_file().is_empty())
  536. m_save_as_action->activate();
  537. current_editor_wrapper().save();
  538. if (m_git_widget->initialized())
  539. m_git_widget->refresh();
  540. });
  541. }
  542. NonnullRefPtr<GUI::Action> HackStudioWidget::create_save_as_action()
  543. {
  544. return GUI::CommonActions::make_save_as_action([&](auto&) {
  545. auto const old_filename = current_editor_wrapper().filename();
  546. LexicalPath const old_path(old_filename);
  547. Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(),
  548. old_filename.is_null() ? "Untitled" : old_path.title(),
  549. old_filename.is_null() ? "txt" : old_path.extension(),
  550. Core::File::absolute_path(old_path.dirname()));
  551. if (!save_path.has_value()) {
  552. return;
  553. }
  554. current_editor_wrapper().set_filename(save_path.value());
  555. current_editor_wrapper().save();
  556. auto new_project_file = m_project->get_file(save_path.value());
  557. m_open_files.set(save_path.value(), *new_project_file);
  558. m_open_files_vector.append(save_path.value());
  559. update_window_title();
  560. });
  561. }
  562. NonnullRefPtr<GUI::Action> HackStudioWidget::create_remove_current_terminal_action()
  563. {
  564. return GUI::Action::create("Remove &Current Terminal", { Mod_Alt | Mod_Shift, Key_T }, [this](auto&) {
  565. auto widget = m_action_tab_widget->active_widget();
  566. if (!widget)
  567. return;
  568. if (!is<TerminalWrapper>(widget))
  569. return;
  570. auto& terminal = *static_cast<TerminalWrapper*>(widget);
  571. if (!terminal.user_spawned())
  572. return;
  573. m_action_tab_widget->remove_tab(terminal);
  574. update_actions();
  575. });
  576. }
  577. NonnullRefPtr<GUI::Action> HackStudioWidget::create_add_editor_action()
  578. {
  579. return GUI::Action::create("Add New &Editor", { Mod_Ctrl | Mod_Alt, Key_E },
  580. Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-text-editor.png"),
  581. [this](auto&) {
  582. add_new_editor(*m_editors_splitter);
  583. update_actions();
  584. });
  585. }
  586. NonnullRefPtr<GUI::Action> HackStudioWidget::create_add_terminal_action()
  587. {
  588. return GUI::Action::create("Add New &Terminal", { Mod_Ctrl | Mod_Alt, Key_T },
  589. Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-terminal.png"),
  590. [this](auto&) {
  591. auto& terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Terminal");
  592. reveal_action_tab(terminal_wrapper);
  593. update_actions();
  594. terminal_wrapper.terminal().set_focus(true);
  595. });
  596. }
  597. void HackStudioWidget::reveal_action_tab(GUI::Widget& widget)
  598. {
  599. if (m_action_tab_widget->min_height() < 200)
  600. m_action_tab_widget->set_fixed_height(200);
  601. m_action_tab_widget->set_active_widget(&widget);
  602. }
  603. NonnullRefPtr<GUI::Action> HackStudioWidget::create_debug_action()
  604. {
  605. return GUI::Action::create("&Debug", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/debug-run.png"), [this](auto&) {
  606. if (!Core::File::exists(get_project_executable_path())) {
  607. GUI::MessageBox::show(window(), String::formatted("Could not find file: {}. (did you build the project?)", get_project_executable_path()), "Error", GUI::MessageBox::Type::Error);
  608. return;
  609. }
  610. if (Debugger::the().session()) {
  611. GUI::MessageBox::show(window(), "Debugger is already running", "Error", GUI::MessageBox::Type::Error);
  612. return;
  613. }
  614. Debugger::the().set_executable_path(get_project_executable_path());
  615. m_debugger_thread = Threading::Thread::construct(Debugger::start_static);
  616. m_debugger_thread->start();
  617. m_stop_action->set_enabled(true);
  618. m_run_action->set_enabled(false);
  619. for (auto& editor_wrapper : m_all_editor_wrappers) {
  620. editor_wrapper.set_debug_mode(true);
  621. }
  622. });
  623. }
  624. void HackStudioWidget::initialize_debugger()
  625. {
  626. Debugger::initialize(
  627. m_project->root_path(),
  628. [this](const PtraceRegisters& regs) {
  629. VERIFY(Debugger::the().session());
  630. const auto& debug_session = *Debugger::the().session();
  631. auto source_position = debug_session.get_source_position(regs.ip());
  632. if (!source_position.has_value()) {
  633. dbgln("Could not find source position for address: {:p}", regs.ip());
  634. return Debugger::HasControlPassedToUser::No;
  635. }
  636. dbgln("Debugger stopped at source position: {}:{}", source_position.value().file_path, source_position.value().line_number);
  637. Core::EventLoop::main().post_event(
  638. *window(),
  639. make<Core::DeferredInvocationEvent>(
  640. [this, source_position, &regs](auto&) {
  641. m_current_editor_in_execution = get_editor_of_file(source_position.value().file_path);
  642. if (m_current_editor_in_execution)
  643. m_current_editor_in_execution->editor().set_execution_position(source_position.value().line_number - 1);
  644. m_debug_info_widget->update_state(*Debugger::the().session(), regs);
  645. m_debug_info_widget->set_debug_actions_enabled(true);
  646. m_disassembly_widget->update_state(*Debugger::the().session(), regs);
  647. HackStudioWidget::reveal_action_tab(*m_debug_info_widget);
  648. }));
  649. Core::EventLoop::wake();
  650. return Debugger::HasControlPassedToUser::Yes;
  651. },
  652. [this]() {
  653. Core::EventLoop::main().post_event(*window(), make<Core::DeferredInvocationEvent>([this](auto&) {
  654. m_debug_info_widget->set_debug_actions_enabled(false);
  655. if (m_current_editor_in_execution)
  656. m_current_editor_in_execution->editor().clear_execution_position();
  657. }));
  658. Core::EventLoop::wake();
  659. },
  660. [this]() {
  661. Core::EventLoop::main().post_event(*window(), make<Core::DeferredInvocationEvent>([this](auto&) {
  662. m_debug_info_widget->set_debug_actions_enabled(false);
  663. if (m_current_editor_in_execution)
  664. m_current_editor_in_execution->editor().clear_execution_position();
  665. m_debug_info_widget->program_stopped();
  666. m_disassembly_widget->program_stopped();
  667. m_stop_action->set_enabled(false);
  668. m_run_action->set_enabled(true);
  669. m_debugger_thread.clear();
  670. for (auto& editor_wrapper : m_all_editor_wrappers) {
  671. editor_wrapper.set_debug_mode(false);
  672. }
  673. HackStudioWidget::hide_action_tabs();
  674. GUI::MessageBox::show(window(), "Program Exited", "Debugger", GUI::MessageBox::Type::Information);
  675. }));
  676. Core::EventLoop::wake();
  677. });
  678. }
  679. String HackStudioWidget::get_full_path_of_serenity_source(const String& file)
  680. {
  681. auto path_parts = LexicalPath(file).parts();
  682. VERIFY(path_parts[0] == "..");
  683. path_parts.remove(0);
  684. StringBuilder relative_path_builder;
  685. relative_path_builder.join("/", path_parts);
  686. constexpr char SERENITY_LIBS_PREFIX[] = "/usr/src/serenity";
  687. LexicalPath serenity_sources_base(SERENITY_LIBS_PREFIX);
  688. return String::formatted("{}/{}", serenity_sources_base, relative_path_builder.to_string());
  689. }
  690. RefPtr<EditorWrapper> HackStudioWidget::get_editor_of_file(const String& filename)
  691. {
  692. String file_path = filename;
  693. // TODO: We can probably do a more specific condition here, something like
  694. // "if (file.starts_with("../Libraries/") || file.starts_with("../AK/"))"
  695. if (filename.starts_with("../")) {
  696. file_path = get_full_path_of_serenity_source(filename);
  697. }
  698. if (!open_file(file_path))
  699. return nullptr;
  700. return current_editor_wrapper();
  701. }
  702. String HackStudioWidget::get_project_executable_path() const
  703. {
  704. // FIXME: Dumb heuristic ahead!
  705. // e.g /my/project => /my/project/project
  706. // TODO: Perhaps a Makefile rule for getting the value of $(PROGRAM) would be better?
  707. return String::formatted("{}/{}", m_project->root_path(), LexicalPath::basename(m_project->root_path()));
  708. }
  709. void HackStudioWidget::build(TerminalWrapper& wrapper)
  710. {
  711. if (active_file().ends_with(".js"))
  712. wrapper.run_command(String::formatted("js -A {}", active_file()));
  713. else
  714. wrapper.run_command("make");
  715. }
  716. void HackStudioWidget::run(TerminalWrapper& wrapper)
  717. {
  718. if (active_file().ends_with(".js"))
  719. wrapper.run_command(String::formatted("js {}", active_file()));
  720. else
  721. wrapper.run_command("make run");
  722. }
  723. void HackStudioWidget::hide_action_tabs()
  724. {
  725. m_action_tab_widget->set_fixed_height(24);
  726. };
  727. Project& HackStudioWidget::project()
  728. {
  729. return *m_project;
  730. }
  731. void HackStudioWidget::set_current_editor_wrapper(RefPtr<EditorWrapper> editor_wrapper)
  732. {
  733. m_current_editor_wrapper = editor_wrapper;
  734. update_window_title();
  735. }
  736. void HackStudioWidget::configure_project_tree_view()
  737. {
  738. m_project_tree_view->set_model(m_project->model());
  739. m_project_tree_view->set_selection_mode(GUI::AbstractView::SelectionMode::MultiSelection);
  740. for (int column_index = 0; column_index < m_project->model().column_count(); ++column_index)
  741. m_project_tree_view->set_column_visible(column_index, false);
  742. m_project_tree_view->set_column_visible(GUI::FileSystemModel::Column::Name, true);
  743. m_project_tree_view->on_context_menu_request = [this](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  744. if (index.is_valid()) {
  745. m_project_tree_view_context_menu->popup(event.screen_position(), m_open_selected_action);
  746. }
  747. };
  748. m_project_tree_view->on_selection_change = [this] {
  749. m_open_selected_action->set_enabled(!m_project_tree_view->selection().is_empty());
  750. auto selections = m_project_tree_view->selection().indices();
  751. auto it = selections.find_if([&](auto selected_file) {
  752. return access(m_project->model().full_path(selected_file.parent()).characters(), W_OK) == 0;
  753. });
  754. bool has_permissions = it != selections.end();
  755. m_delete_action->set_enabled(!m_project_tree_view->selection().is_empty() && has_permissions);
  756. };
  757. m_project_tree_view->on_activation = [this](auto& index) {
  758. auto full_path_to_file = m_project->model().full_path(index);
  759. open_file(full_path_to_file);
  760. };
  761. }
  762. void HackStudioWidget::create_open_files_view(GUI::Widget& parent)
  763. {
  764. m_open_files_view = parent.add<GUI::ListView>();
  765. auto open_files_model = GUI::ItemListModel<String>::create(m_open_files_vector);
  766. m_open_files_view->set_model(open_files_model);
  767. m_open_files_view->on_activation = [this](auto& index) {
  768. open_file(index.data().to_string());
  769. };
  770. }
  771. void HackStudioWidget::create_toolbar(GUI::Widget& parent)
  772. {
  773. auto& toolbar = parent.add<GUI::Toolbar>();
  774. toolbar.add_action(*m_new_file_action);
  775. toolbar.add_action(*m_new_directory_action);
  776. toolbar.add_action(*m_save_action);
  777. toolbar.add_action(*m_delete_action);
  778. toolbar.add_separator();
  779. toolbar.add_action(GUI::CommonActions::make_cut_action([this](auto&) { current_editor().cut_action().activate(); }));
  780. toolbar.add_action(GUI::CommonActions::make_copy_action([this](auto&) { current_editor().copy_action().activate(); }));
  781. toolbar.add_action(GUI::CommonActions::make_paste_action([this](auto&) { current_editor().paste_action().activate(); }));
  782. toolbar.add_separator();
  783. toolbar.add_action(GUI::CommonActions::make_undo_action([this](auto&) { current_editor().undo_action().activate(); }));
  784. toolbar.add_action(GUI::CommonActions::make_redo_action([this](auto&) { current_editor().redo_action().activate(); }));
  785. toolbar.add_separator();
  786. toolbar.add_action(*m_build_action);
  787. toolbar.add_separator();
  788. toolbar.add_action(*m_run_action);
  789. toolbar.add_action(*m_stop_action);
  790. toolbar.add_separator();
  791. toolbar.add_action(*m_debug_action);
  792. }
  793. NonnullRefPtr<GUI::Action> HackStudioWidget::create_build_action()
  794. {
  795. return GUI::Action::create("&Build", { Mod_Ctrl, Key_B }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/build.png"), [this](auto&) {
  796. if (warn_unsaved_changes("There are unsaved changes, do you want to save before building?") == ContinueDecision::No)
  797. return;
  798. reveal_action_tab(*m_terminal_wrapper);
  799. build(*m_terminal_wrapper);
  800. m_stop_action->set_enabled(true);
  801. });
  802. }
  803. NonnullRefPtr<GUI::Action> HackStudioWidget::create_run_action()
  804. {
  805. return GUI::Action::create("&Run", { Mod_Ctrl, Key_R }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-run.png"), [this](auto&) {
  806. reveal_action_tab(*m_terminal_wrapper);
  807. run(*m_terminal_wrapper);
  808. m_stop_action->set_enabled(true);
  809. });
  810. }
  811. void HackStudioWidget::create_action_tab(GUI::Widget& parent)
  812. {
  813. m_action_tab_widget = parent.add<GUI::TabWidget>();
  814. m_action_tab_widget->set_fixed_height(24);
  815. m_action_tab_widget->on_change = [this](auto&) {
  816. on_action_tab_change();
  817. static bool first_time = true;
  818. if (!first_time)
  819. m_action_tab_widget->set_fixed_height(200);
  820. first_time = false;
  821. };
  822. m_find_in_files_widget = m_action_tab_widget->add_tab<FindInFilesWidget>("Find in files");
  823. m_todo_entries_widget = m_action_tab_widget->add_tab<ToDoEntriesWidget>("TODO");
  824. m_terminal_wrapper = m_action_tab_widget->add_tab<TerminalWrapper>("Build", false);
  825. m_debug_info_widget = m_action_tab_widget->add_tab<DebugInfoWidget>("Debug");
  826. m_disassembly_widget = m_action_tab_widget->add_tab<DisassemblyWidget>("Disassembly");
  827. m_git_widget = m_action_tab_widget->add_tab<GitWidget>("Git", LexicalPath(m_project->root_path()));
  828. m_git_widget->set_view_diff_callback([this](const auto& original_content, const auto& diff) {
  829. m_diff_viewer->set_content(original_content, diff);
  830. set_edit_mode(EditMode::Diff);
  831. });
  832. m_gml_preview_widget = m_action_tab_widget->add_tab<GMLPreviewWidget>("GML Preview", "");
  833. ToDoEntries::the().on_update = [this]() {
  834. m_todo_entries_widget->refresh();
  835. };
  836. }
  837. void HackStudioWidget::create_project_tab(GUI::Widget& parent)
  838. {
  839. m_project_tab = parent.add<GUI::TabWidget>();
  840. m_project_tab->set_tab_position(GUI::TabWidget::TabPosition::Bottom);
  841. auto& tree_view_container = m_project_tab->add_tab<GUI::Widget>("Files");
  842. tree_view_container.set_layout<GUI::VerticalBoxLayout>();
  843. tree_view_container.layout()->set_margins(2);
  844. m_project_tree_view = tree_view_container.add<GUI::TreeView>();
  845. configure_project_tree_view();
  846. auto& class_view_container = m_project_tab->add_tab<GUI::Widget>("Classes");
  847. class_view_container.set_layout<GUI::VerticalBoxLayout>();
  848. class_view_container.layout()->set_margins(2);
  849. m_class_view = class_view_container.add<ClassViewWidget>();
  850. ProjectDeclarations::the().on_update = [this]() {
  851. m_class_view->refresh();
  852. };
  853. }
  854. void HackStudioWidget::create_file_menu(GUI::Window& window)
  855. {
  856. auto& file_menu = window.add_menu("&File");
  857. file_menu.add_action(*m_new_project_action);
  858. file_menu.add_action(*m_open_action);
  859. file_menu.add_action(*m_save_action);
  860. file_menu.add_action(*m_save_as_action);
  861. file_menu.add_separator();
  862. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  863. GUI::Application::the()->quit();
  864. }));
  865. }
  866. void HackStudioWidget::create_project_menu(GUI::Window& window)
  867. {
  868. auto& project_menu = window.add_menu("&Project");
  869. project_menu.add_action(*m_new_file_action);
  870. project_menu.add_action(*m_new_directory_action);
  871. }
  872. void HackStudioWidget::create_edit_menu(GUI::Window& window)
  873. {
  874. auto& edit_menu = window.add_menu("&Edit");
  875. 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"), [this](auto&) {
  876. reveal_action_tab(*m_find_in_files_widget);
  877. m_find_in_files_widget->focus_textbox_and_select_all();
  878. }));
  879. edit_menu.add_separator();
  880. auto vim_emulation_setting_action = GUI::Action::create_checkable("&Vim Emulation", { Mod_Ctrl | Mod_Shift | Mod_Alt, Key_V }, [this](auto& action) {
  881. if (action.is_checked())
  882. current_editor().set_editing_engine(make<GUI::VimEditingEngine>());
  883. else
  884. current_editor().set_editing_engine(make<GUI::RegularEditingEngine>());
  885. });
  886. vim_emulation_setting_action->set_checked(false);
  887. edit_menu.add_action(vim_emulation_setting_action);
  888. }
  889. void HackStudioWidget::create_build_menu(GUI::Window& window)
  890. {
  891. auto& build_menu = window.add_menu("&Build");
  892. build_menu.add_action(*m_build_action);
  893. build_menu.add_separator();
  894. build_menu.add_action(*m_run_action);
  895. build_menu.add_action(*m_stop_action);
  896. build_menu.add_separator();
  897. build_menu.add_action(*m_debug_action);
  898. }
  899. void HackStudioWidget::create_view_menu(GUI::Window& window)
  900. {
  901. auto hide_action_tabs_action = GUI::Action::create("&Hide Action Tabs", { Mod_Ctrl | Mod_Shift, Key_X }, [this](auto&) {
  902. hide_action_tabs();
  903. });
  904. auto open_locator_action = GUI::Action::create("Open &Locator", { Mod_Ctrl, Key_K }, [this](auto&) {
  905. m_locator->open();
  906. });
  907. auto& view_menu = window.add_menu("&View");
  908. view_menu.add_action(hide_action_tabs_action);
  909. view_menu.add_action(open_locator_action);
  910. view_menu.add_separator();
  911. m_wrapping_mode_actions.set_exclusive(true);
  912. auto& wrapping_mode_menu = view_menu.add_submenu("&Wrapping Mode");
  913. m_no_wrapping_action = GUI::Action::create_checkable("&No Wrapping", [&](auto&) {
  914. for (auto& wrapper : m_all_editor_wrappers)
  915. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  916. });
  917. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap &Anywhere", [&](auto&) {
  918. for (auto& wrapper : m_all_editor_wrappers)
  919. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  920. });
  921. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at &Words", [&](auto&) {
  922. for (auto& wrapper : m_all_editor_wrappers)
  923. wrapper.editor().set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  924. });
  925. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  926. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  927. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  928. wrapping_mode_menu.add_action(*m_no_wrapping_action);
  929. wrapping_mode_menu.add_action(*m_wrap_anywhere_action);
  930. wrapping_mode_menu.add_action(*m_wrap_at_words_action);
  931. m_no_wrapping_action->set_checked(true);
  932. view_menu.add_separator();
  933. view_menu.add_action(*m_add_editor_action);
  934. view_menu.add_action(*m_remove_current_editor_action);
  935. view_menu.add_action(*m_add_terminal_action);
  936. view_menu.add_action(*m_remove_current_terminal_action);
  937. }
  938. void HackStudioWidget::create_help_menu(GUI::Window& window)
  939. {
  940. auto& help_menu = window.add_menu("&Help");
  941. help_menu.add_action(GUI::CommonActions::make_about_action("Hack Studio", GUI::Icon::default_icon("app-hack-studio"), &window));
  942. }
  943. NonnullRefPtr<GUI::Action> HackStudioWidget::create_stop_action()
  944. {
  945. auto action = GUI::Action::create("&Stop", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/program-stop.png"), [this](auto&) {
  946. if (!Debugger::the().session()) {
  947. m_terminal_wrapper->kill_running_command();
  948. return;
  949. }
  950. Debugger::the().stop();
  951. });
  952. action->set_enabled(false);
  953. return action;
  954. }
  955. void HackStudioWidget::initialize_menubar(GUI::Window& window)
  956. {
  957. create_file_menu(window);
  958. create_project_menu(window);
  959. create_edit_menu(window);
  960. create_build_menu(window);
  961. create_view_menu(window);
  962. create_help_menu(window);
  963. }
  964. void HackStudioWidget::update_statusbar()
  965. {
  966. m_statusbar->set_text(0, String::formatted("Ln {}, Col {}", current_editor().cursor().line() + 1, current_editor().cursor().column()));
  967. StringBuilder builder;
  968. if (current_editor().has_selection()) {
  969. String selected_text = current_editor().selected_text();
  970. auto word_count = current_editor().number_of_selected_words();
  971. builder.appendff("Selected: {} {} ({} {})", selected_text.length(), selected_text.length() == 1 ? "character" : "characters", word_count, word_count != 1 ? "words" : "word");
  972. }
  973. m_statusbar->set_text(1, builder.to_string());
  974. m_statusbar->set_text(2, current_editor_wrapper().editor().code_document().language_name());
  975. }
  976. void HackStudioWidget::handle_external_file_deletion(const String& filepath)
  977. {
  978. close_file_in_all_editors(filepath);
  979. }
  980. void HackStudioWidget::stop_debugger_if_running()
  981. {
  982. if (!m_debugger_thread.is_null()) {
  983. Debugger::the().stop();
  984. dbgln("Waiting for debugger thread to terminate");
  985. auto rc = m_debugger_thread->join();
  986. if (rc.is_error()) {
  987. warnln("pthread_join: {}", strerror(rc.error().value()));
  988. dbgln("error joining debugger thread");
  989. }
  990. }
  991. }
  992. void HackStudioWidget::close_current_project()
  993. {
  994. m_editors_splitter->remove_all_children();
  995. m_all_editor_wrappers.clear();
  996. m_open_files.clear();
  997. m_open_files_vector.clear();
  998. add_new_editor(*m_editors_splitter);
  999. m_find_in_files_widget->reset();
  1000. m_todo_entries_widget->clear();
  1001. m_terminal_wrapper->clear_including_history();
  1002. stop_debugger_if_running();
  1003. update_gml_preview();
  1004. }
  1005. HackStudioWidget::~HackStudioWidget()
  1006. {
  1007. stop_debugger_if_running();
  1008. }
  1009. HackStudioWidget::ContinueDecision HackStudioWidget::warn_unsaved_changes(const String& prompt)
  1010. {
  1011. if (!any_document_is_dirty())
  1012. return ContinueDecision::Yes;
  1013. auto result = GUI::MessageBox::show(window(), prompt, "Unsaved changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  1014. if (result == GUI::MessageBox::ExecCancel)
  1015. return ContinueDecision::No;
  1016. if (result == GUI::MessageBox::ExecYes) {
  1017. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1018. if (editor_wrapper.document_dirty()) {
  1019. editor_wrapper.save();
  1020. }
  1021. }
  1022. }
  1023. return ContinueDecision::Yes;
  1024. }
  1025. bool HackStudioWidget::any_document_is_dirty() const
  1026. {
  1027. for (auto& editor_wrapper : m_all_editor_wrappers) {
  1028. if (editor_wrapper.document_dirty()) {
  1029. return true;
  1030. }
  1031. }
  1032. return false;
  1033. }
  1034. void HackStudioWidget::update_gml_preview()
  1035. {
  1036. auto gml_content = current_editor_wrapper().filename().ends_with(".gml") ? current_editor_wrapper().editor().text() : "";
  1037. m_gml_preview_widget->load_gml(gml_content);
  1038. }
  1039. void HackStudioWidget::update_window_title()
  1040. {
  1041. window()->set_title(String::formatted("{} - {} - Hack Studio", m_current_editor_wrapper->filename_label().text(), m_project->name()));
  1042. }
  1043. }