main.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "CursorTool.h"
  27. #include "Debugger/DebugInfoWidget.h"
  28. #include "Debugger/Debugger.h"
  29. #include "Debugger/DisassemblyWidget.h"
  30. #include "Editor.h"
  31. #include "EditorWrapper.h"
  32. #include "FindInFilesWidget.h"
  33. #include "FormEditorWidget.h"
  34. #include "FormWidget.h"
  35. #include "Git/DiffViewer.h"
  36. #include "Git/GitWidget.h"
  37. #include "HackStudio.h"
  38. #include "Locator.h"
  39. #include "Project.h"
  40. #include "TerminalWrapper.h"
  41. #include "WidgetTool.h"
  42. #include "WidgetTreeModel.h"
  43. #include <AK/StringBuilder.h>
  44. #include <LibCore/ArgsParser.h>
  45. #include <LibCore/Event.h>
  46. #include <LibCore/EventLoop.h>
  47. #include <LibCore/File.h>
  48. #include <LibDebug/DebugSession.h>
  49. #include <LibGUI/AboutDialog.h>
  50. #include <LibGUI/Action.h>
  51. #include <LibGUI/ActionGroup.h>
  52. #include <LibGUI/Application.h>
  53. #include <LibGUI/BoxLayout.h>
  54. #include <LibGUI/Button.h>
  55. #include <LibGUI/CppSyntaxHighlighter.h>
  56. #include <LibGUI/FilePicker.h>
  57. #include <LibGUI/INISyntaxHighlighter.h>
  58. #include <LibGUI/InputBox.h>
  59. #include <LibGUI/JSSyntaxHighlighter.h>
  60. #include <LibGUI/Label.h>
  61. #include <LibGUI/Menu.h>
  62. #include <LibGUI/MenuBar.h>
  63. #include <LibGUI/MessageBox.h>
  64. #include <LibGUI/Splitter.h>
  65. #include <LibGUI/StackWidget.h>
  66. #include <LibGUI/TabWidget.h>
  67. #include <LibGUI/TableView.h>
  68. #include <LibGUI/TextBox.h>
  69. #include <LibGUI/TextEditor.h>
  70. #include <LibGUI/ToolBar.h>
  71. #include <LibGUI/ToolBarContainer.h>
  72. #include <LibGUI/TreeView.h>
  73. #include <LibGUI/Widget.h>
  74. #include <LibGUI/Window.h>
  75. #include <LibThread/Lock.h>
  76. #include <LibThread/Thread.h>
  77. #include <LibVT/TerminalWidget.h>
  78. #include <fcntl.h>
  79. #include <spawn.h>
  80. #include <stdio.h>
  81. #include <sys/types.h>
  82. #include <sys/wait.h>
  83. #include <unistd.h>
  84. using namespace HackStudio;
  85. namespace HackStudio {
  86. NonnullRefPtrVector<EditorWrapper> g_all_editor_wrappers;
  87. RefPtr<EditorWrapper> g_current_editor_wrapper;
  88. Function<void(String)> g_open_file;
  89. String g_currently_open_file;
  90. OwnPtr<Project> g_project;
  91. RefPtr<GUI::Window> g_window;
  92. RefPtr<GUI::TreeView> g_project_tree_view;
  93. RefPtr<GUI::VerticalSplitter> g_right_hand_splitter;
  94. RefPtr<GUI::StackWidget> g_right_hand_stack;
  95. RefPtr<GUI::Splitter> g_editors_splitter;
  96. RefPtr<GUI::Widget> g_form_inner_container;
  97. RefPtr<FormEditorWidget> g_form_editor_widget;
  98. RefPtr<DiffViewer> g_diff_viewer;
  99. static RefPtr<GUI::TabWidget> s_action_tab_widget;
  100. static void add_new_editor(GUI::Widget& parent)
  101. {
  102. auto wrapper = EditorWrapper::construct(Debugger::on_breakpoint_change);
  103. if (s_action_tab_widget) {
  104. parent.insert_child_before(wrapper, *s_action_tab_widget);
  105. } else {
  106. parent.add_child(wrapper);
  107. }
  108. g_current_editor_wrapper = wrapper;
  109. g_all_editor_wrappers.append(wrapper);
  110. wrapper->editor().set_focus(true);
  111. }
  112. enum class EditMode {
  113. Text,
  114. Form,
  115. Diff,
  116. };
  117. static void set_edit_mode(EditMode mode)
  118. {
  119. if (mode == EditMode::Text) {
  120. g_right_hand_stack->set_active_widget(g_editors_splitter);
  121. } else if (mode == EditMode::Form) {
  122. g_right_hand_stack->set_active_widget(g_form_inner_container);
  123. } else if (mode == EditMode::Diff) {
  124. g_right_hand_stack->set_active_widget(g_diff_viewer);
  125. } else {
  126. ASSERT_NOT_REACHED();
  127. }
  128. g_right_hand_stack->active_widget()->update();
  129. }
  130. static void build(TerminalWrapper&);
  131. static void run(TerminalWrapper&);
  132. void open_project(String);
  133. void open_file(const String&);
  134. bool make_is_available();
  135. static EditorWrapper& current_editor_wrapper()
  136. {
  137. ASSERT(g_current_editor_wrapper);
  138. return *g_current_editor_wrapper;
  139. }
  140. GUI::TextEditor& current_editor()
  141. {
  142. return current_editor_wrapper().editor();
  143. }
  144. static String get_full_path_of_serenity_source(const String& file)
  145. {
  146. auto path_parts = LexicalPath(file).parts();
  147. ASSERT(path_parts[0] == "..");
  148. path_parts.remove(0);
  149. StringBuilder relative_path_builder;
  150. relative_path_builder.join("/", path_parts);
  151. constexpr char SERENITY_LIBS_PREFIX[] = "/usr/src/serenity";
  152. LexicalPath serenity_sources_base(SERENITY_LIBS_PREFIX);
  153. return String::format("%s/%s", serenity_sources_base.string().characters(), relative_path_builder.to_string().characters());
  154. }
  155. static NonnullRefPtr<EditorWrapper> get_editor_of_file(const String& file)
  156. {
  157. String file_path = file;
  158. // TODO: We can probably do a more specific condition here, something like
  159. // "if (file.starts_with("../Libraries/") || file.starts_with("../AK/"))"
  160. if (file.starts_with("../")) {
  161. file_path = get_full_path_of_serenity_source(file);
  162. }
  163. open_file(file_path);
  164. return current_editor_wrapper();
  165. }
  166. static String get_project_executable_path()
  167. {
  168. // e.g /my/project.hsp => /my/project
  169. // TODO: Perhaps a Makefile rule for getting the value of $(PROGRAM) would be better?
  170. return g_project->path().substring(0, g_project->path().index_of(".").value());
  171. }
  172. static int main_impl(int argc, char** argv)
  173. {
  174. if (pledge("stdio tty accept rpath cpath wpath shared_buffer proc exec unix fattr thread", nullptr) < 0) {
  175. perror("pledge");
  176. return 1;
  177. }
  178. auto app = GUI::Application::construct(argc, argv);
  179. if (pledge("stdio tty accept rpath cpath wpath shared_buffer proc exec fattr thread", nullptr) < 0) {
  180. perror("pledge");
  181. return 1;
  182. }
  183. Function<void()> update_actions;
  184. Function<void()> on_action_tab_change;
  185. g_window = GUI::Window::construct();
  186. g_window->resize(840, 600);
  187. g_window->set_title("HackStudio");
  188. auto& widget = g_window->set_main_widget<GUI::Widget>();
  189. widget.set_fill_with_background_color(true);
  190. widget.set_layout<GUI::VerticalBoxLayout>();
  191. widget.layout()->set_spacing(2);
  192. StringBuilder path;
  193. path.append(getenv("PATH"));
  194. if (path.length())
  195. path.append(":");
  196. path.append("/bin:/usr/bin:/usr/local/bin");
  197. setenv("PATH", path.to_string().characters(), true);
  198. if (!make_is_available())
  199. GUI::MessageBox::show(g_window, "The 'make' command is not available. You probably want to install the binutils, gcc, and make ports from the root of the Serenity repository.", "Error", GUI::MessageBox::Type::Error);
  200. const char* path_argument = nullptr;
  201. Core::ArgsParser args_parser;
  202. args_parser.add_positional_argument(path_argument, "Path to a workspace or a file", "path", Core::ArgsParser::Required::No);
  203. args_parser.parse(argc, argv);
  204. auto argument_absolute_path = Core::File::real_path_for(path_argument);
  205. if (argument_absolute_path.ends_with(".hsp"))
  206. open_project(argument_absolute_path);
  207. else
  208. open_project("/home/anon/Source/little/little.hsp");
  209. auto& toolbar_container = widget.add<GUI::ToolBarContainer>();
  210. auto& toolbar = toolbar_container.add<GUI::ToolBar>();
  211. auto selected_file_names = [&] {
  212. Vector<String> files;
  213. g_project_tree_view->selection().for_each_index([&](const GUI::ModelIndex& index) {
  214. files.append(index.data().as_string());
  215. });
  216. return files;
  217. };
  218. auto new_action = GUI::Action::create("Add new file to project...", { Mod_Ctrl, Key_N }, Gfx::Bitmap::load_from_file("/res/icons/16x16/new.png"), [&](const GUI::Action&) {
  219. String filename;
  220. if (GUI::InputBox::show(filename, g_window, "Enter name of new file:", "Add new file to project") != GUI::InputBox::ExecOK)
  221. return;
  222. auto file = Core::File::construct(filename);
  223. if (!file->open((Core::IODevice::OpenMode)(Core::IODevice::WriteOnly | Core::IODevice::MustBeNew))) {
  224. GUI::MessageBox::show(g_window, String::format("Failed to create '%s'", filename.characters()), "Error", GUI::MessageBox::Type::Error);
  225. return;
  226. }
  227. if (!g_project->add_file(filename)) {
  228. GUI::MessageBox::show(g_window, String::format("Failed to add '%s' to project", filename.characters()), "Error", GUI::MessageBox::Type::Error);
  229. // FIXME: Should we unlink the file here maybe?
  230. return;
  231. }
  232. g_project_tree_view->toggle_index(g_project_tree_view->model()->index(0, 0));
  233. open_file(filename);
  234. });
  235. auto open_selected_action = GUI::Action::create("Open", [&](const GUI::Action&) {
  236. auto files = selected_file_names();
  237. for (auto& file : files)
  238. open_file(file);
  239. });
  240. open_selected_action->set_enabled(true);
  241. auto add_existing_file_action = GUI::Action::create("Add existing file to project...", Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"), [&](auto&) {
  242. auto result = GUI::FilePicker::get_open_filepath(g_window, "Add existing file to project");
  243. if (!result.has_value())
  244. return;
  245. auto& filename = result.value();
  246. if (!g_project->add_file(filename)) {
  247. GUI::MessageBox::show(g_window, String::format("Failed to add '%s' to project", filename.characters()), "Error", GUI::MessageBox::Type::Error);
  248. return;
  249. }
  250. g_project_tree_view->toggle_index(g_project_tree_view->model()->index(0, 0));
  251. open_file(filename);
  252. });
  253. auto delete_action = GUI::CommonActions::make_delete_action([&](const GUI::Action&) {
  254. auto files = selected_file_names();
  255. if (files.is_empty())
  256. return;
  257. String message;
  258. if (files.size() == 1) {
  259. message = String::format("Really remove %s from the project?", LexicalPath(files[0]).basename().characters());
  260. } else {
  261. message = String::format("Really remove %d files from the project?", files.size());
  262. }
  263. auto result = GUI::MessageBox::show(g_window,
  264. message,
  265. "Confirm deletion",
  266. GUI::MessageBox::Type::Warning,
  267. GUI::MessageBox::InputType::OKCancel);
  268. if (result == GUI::MessageBox::ExecCancel)
  269. return;
  270. for (auto& file : files) {
  271. if (!g_project->remove_file(file)) {
  272. GUI::MessageBox::show(g_window,
  273. String::format("Removing file %s from the project failed.", file.characters()),
  274. "Removal failed",
  275. GUI::MessageBox::Type::Error);
  276. break;
  277. }
  278. }
  279. });
  280. delete_action->set_enabled(false);
  281. auto project_tree_view_context_menu = GUI::Menu::construct("Project Files");
  282. project_tree_view_context_menu->add_action(open_selected_action);
  283. // TODO: Rename, cut, copy, duplicate with new name, show containing folder ...
  284. project_tree_view_context_menu->add_separator();
  285. project_tree_view_context_menu->add_action(new_action);
  286. project_tree_view_context_menu->add_action(add_existing_file_action);
  287. project_tree_view_context_menu->add_action(delete_action);
  288. auto& outer_splitter = widget.add<GUI::HorizontalSplitter>();
  289. g_project_tree_view = outer_splitter.add<GUI::TreeView>();
  290. g_project_tree_view->set_model(g_project->model());
  291. g_project_tree_view->set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill);
  292. g_project_tree_view->set_preferred_size(140, 0);
  293. g_project_tree_view->toggle_index(g_project_tree_view->model()->index(0, 0));
  294. g_project_tree_view->on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
  295. if (index.is_valid()) {
  296. project_tree_view_context_menu->popup(event.screen_position(), open_selected_action);
  297. }
  298. };
  299. g_project_tree_view->on_selection_change = [&] {
  300. open_selected_action->set_enabled(!g_project_tree_view->selection().is_empty());
  301. delete_action->set_enabled(!g_project_tree_view->selection().is_empty());
  302. };
  303. g_right_hand_splitter = outer_splitter.add<GUI::VerticalSplitter>();
  304. g_right_hand_stack = g_right_hand_splitter->add<GUI::StackWidget>();
  305. g_form_inner_container = g_right_hand_stack->add<GUI::Widget>();
  306. g_form_inner_container->set_layout<GUI::HorizontalBoxLayout>();
  307. auto& form_widgets_toolbar = g_form_inner_container->add<GUI::ToolBar>(Orientation::Vertical, 26);
  308. form_widgets_toolbar.set_preferred_size(38, 0);
  309. GUI::ActionGroup tool_actions;
  310. tool_actions.set_exclusive(true);
  311. auto cursor_tool_action = GUI::Action::create_checkable("Cursor", Gfx::Bitmap::load_from_file("/res/icons/hackstudio/Cursor.png"), [&](auto&) {
  312. g_form_editor_widget->set_tool(make<CursorTool>(*g_form_editor_widget));
  313. });
  314. cursor_tool_action->set_checked(true);
  315. tool_actions.add_action(cursor_tool_action);
  316. form_widgets_toolbar.add_action(cursor_tool_action);
  317. GUI::WidgetClassRegistration::for_each([&](const GUI::WidgetClassRegistration& reg) {
  318. auto icon_path = String::format("/res/icons/hackstudio/G%s.png", reg.class_name().characters());
  319. auto action = GUI::Action::create_checkable(reg.class_name(), Gfx::Bitmap::load_from_file(icon_path), [&reg](auto&) {
  320. g_form_editor_widget->set_tool(make<WidgetTool>(*g_form_editor_widget, reg));
  321. auto widget = reg.construct();
  322. g_form_editor_widget->form_widget().add_child(widget);
  323. widget->set_relative_rect(30, 30, 30, 30);
  324. g_form_editor_widget->model().update();
  325. });
  326. action->set_checked(false);
  327. tool_actions.add_action(action);
  328. form_widgets_toolbar.add_action(move(action));
  329. });
  330. auto& form_editor_inner_splitter = g_form_inner_container->add<GUI::HorizontalSplitter>();
  331. g_form_editor_widget = form_editor_inner_splitter.add<FormEditorWidget>();
  332. auto& form_editing_pane_container = form_editor_inner_splitter.add<GUI::VerticalSplitter>();
  333. form_editing_pane_container.set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill);
  334. form_editing_pane_container.set_preferred_size(190, 0);
  335. form_editing_pane_container.set_layout<GUI::VerticalBoxLayout>();
  336. auto add_properties_pane = [&](auto& text, auto pane_widget) {
  337. auto& wrapper = form_editing_pane_container.add<GUI::Widget>();
  338. wrapper.set_layout<GUI::VerticalBoxLayout>();
  339. auto& label = wrapper.add<GUI::Label>(text);
  340. label.set_fill_with_background_color(true);
  341. label.set_text_alignment(Gfx::TextAlignment::CenterLeft);
  342. label.set_font(Gfx::Font::default_bold_font());
  343. label.set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
  344. label.set_preferred_size(0, 16);
  345. wrapper.add_child(pane_widget);
  346. };
  347. auto form_widget_tree_view = GUI::TreeView::construct();
  348. form_widget_tree_view->set_model(g_form_editor_widget->model());
  349. form_widget_tree_view->on_selection_change = [&] {
  350. g_form_editor_widget->selection().disable_hooks();
  351. g_form_editor_widget->selection().clear();
  352. form_widget_tree_view->selection().for_each_index([&](auto& index) {
  353. // NOTE: Make sure we don't add the FormWidget itself to the selection,
  354. // since that would allow you to drag-move the FormWidget.
  355. if (index.internal_data() != &g_form_editor_widget->form_widget())
  356. g_form_editor_widget->selection().add(*(GUI::Widget*)index.internal_data());
  357. });
  358. g_form_editor_widget->update();
  359. g_form_editor_widget->selection().enable_hooks();
  360. };
  361. g_form_editor_widget->selection().on_add = [&](auto& widget) {
  362. form_widget_tree_view->selection().add(g_form_editor_widget->model().index_for_widget(widget));
  363. };
  364. g_form_editor_widget->selection().on_remove = [&](auto& widget) {
  365. form_widget_tree_view->selection().remove(g_form_editor_widget->model().index_for_widget(widget));
  366. };
  367. g_form_editor_widget->selection().on_clear = [&] {
  368. form_widget_tree_view->selection().clear();
  369. };
  370. add_properties_pane("Form widget tree:", form_widget_tree_view);
  371. add_properties_pane("Widget properties:", GUI::TableView::construct());
  372. g_diff_viewer = g_right_hand_stack->add<DiffViewer>();
  373. g_editors_splitter = g_right_hand_stack->add<GUI::VerticalSplitter>();
  374. g_editors_splitter->layout()->set_margins({ 0, 3, 0, 0 });
  375. add_new_editor(*g_editors_splitter);
  376. auto switch_to_next_editor = GUI::Action::create("Switch to next editor", { Mod_Ctrl, Key_E }, [&](auto&) {
  377. if (g_all_editor_wrappers.size() <= 1)
  378. return;
  379. Vector<EditorWrapper*> wrappers;
  380. g_editors_splitter->for_each_child_of_type<EditorWrapper>([&](auto& child) {
  381. wrappers.append(&child);
  382. return IterationDecision::Continue;
  383. });
  384. for (size_t i = 0; i < wrappers.size(); ++i) {
  385. if (g_current_editor_wrapper.ptr() == wrappers[i]) {
  386. if (i == wrappers.size() - 1)
  387. wrappers[0]->editor().set_focus(true);
  388. else
  389. wrappers[i + 1]->editor().set_focus(true);
  390. }
  391. }
  392. });
  393. auto switch_to_previous_editor = GUI::Action::create("Switch to previous editor", { Mod_Ctrl | Mod_Shift, Key_E }, [&](auto&) {
  394. if (g_all_editor_wrappers.size() <= 1)
  395. return;
  396. Vector<EditorWrapper*> wrappers;
  397. g_editors_splitter->for_each_child_of_type<EditorWrapper>([&](auto& child) {
  398. wrappers.append(&child);
  399. return IterationDecision::Continue;
  400. });
  401. for (int i = wrappers.size() - 1; i >= 0; --i) {
  402. if (g_current_editor_wrapper.ptr() == wrappers[i]) {
  403. if (i == 0)
  404. wrappers.last()->editor().set_focus(true);
  405. else
  406. wrappers[i - 1]->editor().set_focus(true);
  407. }
  408. }
  409. });
  410. auto remove_current_editor_action = GUI::Action::create("Remove current editor", { Mod_Alt | Mod_Shift, Key_E }, [&](auto&) {
  411. if (g_all_editor_wrappers.size() <= 1)
  412. return;
  413. auto wrapper = g_current_editor_wrapper;
  414. switch_to_next_editor->activate();
  415. g_editors_splitter->remove_child(*wrapper);
  416. g_all_editor_wrappers.remove_first_matching([&](auto& entry) { return entry == wrapper.ptr(); });
  417. update_actions();
  418. });
  419. auto open_action = GUI::Action::create("Open project...", { Mod_Ctrl | Mod_Shift, Key_O }, Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"), [&](auto&) {
  420. auto open_path = GUI::FilePicker::get_open_filepath(g_window, "Open project");
  421. if (!open_path.has_value())
  422. return;
  423. open_project(open_path.value());
  424. open_file(g_project->default_file());
  425. update_actions();
  426. });
  427. auto save_action = GUI::Action::create("Save", { Mod_Ctrl, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"), [&](auto&) {
  428. if (g_currently_open_file.is_empty())
  429. return;
  430. current_editor().write_to_file(g_currently_open_file);
  431. });
  432. toolbar.add_action(new_action);
  433. toolbar.add_action(add_existing_file_action);
  434. toolbar.add_action(save_action);
  435. toolbar.add_action(delete_action);
  436. toolbar.add_separator();
  437. toolbar.add_action(GUI::CommonActions::make_cut_action([&](auto&) { current_editor().cut_action().activate(); }));
  438. toolbar.add_action(GUI::CommonActions::make_copy_action([&](auto&) { current_editor().copy_action().activate(); }));
  439. toolbar.add_action(GUI::CommonActions::make_paste_action([&](auto&) { current_editor().paste_action().activate(); }));
  440. toolbar.add_separator();
  441. toolbar.add_action(GUI::CommonActions::make_undo_action([&](auto&) { current_editor().undo_action().activate(); }));
  442. toolbar.add_action(GUI::CommonActions::make_redo_action([&](auto&) { current_editor().redo_action().activate(); }));
  443. toolbar.add_separator();
  444. g_project_tree_view->on_activation = [&](auto& index) {
  445. auto filename = index.data(GUI::ModelRole::Custom).to_string();
  446. open_file(filename);
  447. };
  448. s_action_tab_widget = g_right_hand_splitter->add<GUI::TabWidget>();
  449. s_action_tab_widget->set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
  450. s_action_tab_widget->set_preferred_size(0, 24);
  451. s_action_tab_widget->on_change = [&](auto&) {
  452. on_action_tab_change();
  453. static bool first_time = true;
  454. if (!first_time)
  455. s_action_tab_widget->set_preferred_size(0, 200);
  456. first_time = false;
  457. };
  458. auto reveal_action_tab = [&](auto& widget) {
  459. if (s_action_tab_widget->preferred_size().height() < 200)
  460. s_action_tab_widget->set_preferred_size(0, 200);
  461. s_action_tab_widget->set_active_widget(&widget);
  462. };
  463. auto hide_action_tabs = [&] {
  464. s_action_tab_widget->set_preferred_size(0, 24);
  465. };
  466. auto hide_action_tabs_action = GUI::Action::create("Hide action tabs", { Mod_Ctrl | Mod_Shift, Key_X }, [&](auto&) {
  467. hide_action_tabs();
  468. });
  469. auto add_editor_action = GUI::Action::create("Add new editor", { Mod_Ctrl | Mod_Alt, Key_E },
  470. Gfx::Bitmap::load_from_file("/res/icons/16x16/app-text-editor.png"),
  471. [&](auto&) {
  472. add_new_editor(*g_editors_splitter);
  473. update_actions();
  474. });
  475. auto add_terminal_action = GUI::Action::create("Add new Terminal", { Mod_Ctrl | Mod_Alt, Key_T },
  476. Gfx::Bitmap::load_from_file("/res/icons/16x16/app-terminal.png"),
  477. [&](auto&) {
  478. auto& terminal = s_action_tab_widget->add_tab<TerminalWrapper>("Terminal");
  479. reveal_action_tab(terminal);
  480. update_actions();
  481. terminal.terminal()->set_focus(true);
  482. });
  483. auto remove_current_terminal_action = GUI::Action::create("Remove current Terminal", { Mod_Alt | Mod_Shift, Key_T }, [&](auto&) {
  484. auto widget = s_action_tab_widget->active_widget();
  485. if (!widget)
  486. return;
  487. if (strcmp(widget->class_name(), "TerminalWrapper") != 0)
  488. return;
  489. auto terminal = reinterpret_cast<TerminalWrapper*>(widget);
  490. if (!terminal->user_spawned())
  491. return;
  492. s_action_tab_widget->remove_tab(*terminal);
  493. update_actions();
  494. });
  495. auto& find_in_files_widget = s_action_tab_widget->add_tab<FindInFilesWidget>("Find in files");
  496. auto& terminal_wrapper = s_action_tab_widget->add_tab<TerminalWrapper>("Build", false);
  497. auto& debug_info_widget = s_action_tab_widget->add_tab<DebugInfoWidget>("Debug");
  498. auto& disassembly_widget = s_action_tab_widget->add_tab<DisassemblyWidget>("Disassembly");
  499. auto& git_widget = s_action_tab_widget->add_tab<GitWidget>("Git", LexicalPath(g_project->root_directory()));
  500. git_widget.set_view_diff_callback([](const auto& original_content, const auto& diff) {
  501. g_diff_viewer->set_content(original_content, diff);
  502. set_edit_mode(EditMode::Diff);
  503. });
  504. auto& locator = widget.add<Locator>();
  505. auto open_locator_action = GUI::Action::create("Open Locator...", { Mod_Ctrl, Key_K }, [&](auto&) {
  506. locator.open();
  507. });
  508. auto menubar = GUI::MenuBar::construct();
  509. auto& app_menu = menubar->add_menu("HackStudio");
  510. app_menu.add_action(open_action);
  511. app_menu.add_action(save_action);
  512. app_menu.add_separator();
  513. app_menu.add_action(GUI::CommonActions::make_quit_action([&](auto&) {
  514. app->quit();
  515. }));
  516. auto& project_menu = menubar->add_menu("Project");
  517. project_menu.add_action(new_action);
  518. project_menu.add_action(add_existing_file_action);
  519. auto& edit_menu = menubar->add_menu("Edit");
  520. edit_menu.add_action(GUI::Action::create("Find in files...", { Mod_Ctrl | Mod_Shift, Key_F }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"), [&](auto&) {
  521. reveal_action_tab(find_in_files_widget);
  522. find_in_files_widget.focus_textbox_and_select_all();
  523. }));
  524. auto stop_action = GUI::Action::create("Stop", Gfx::Bitmap::load_from_file("/res/icons/16x16/program-stop.png"), [&](auto&) {
  525. terminal_wrapper.kill_running_command();
  526. });
  527. stop_action->set_enabled(false);
  528. terminal_wrapper.on_command_exit = [&] {
  529. stop_action->set_enabled(false);
  530. };
  531. auto build_action = GUI::Action::create("Build", { Mod_Ctrl, Key_B }, Gfx::Bitmap::load_from_file("/res/icons/16x16/build.png"), [&](auto&) {
  532. reveal_action_tab(terminal_wrapper);
  533. build(terminal_wrapper);
  534. stop_action->set_enabled(true);
  535. });
  536. toolbar.add_action(build_action);
  537. toolbar.add_separator();
  538. auto run_action = GUI::Action::create("Run", { Mod_Ctrl, Key_R }, Gfx::Bitmap::load_from_file("/res/icons/16x16/program-run.png"), [&](auto&) {
  539. reveal_action_tab(terminal_wrapper);
  540. run(terminal_wrapper);
  541. stop_action->set_enabled(true);
  542. });
  543. RefPtr<LibThread::Thread> debugger_thread;
  544. auto debug_action = GUI::Action::create("Debug", Gfx::Bitmap::load_from_file("/res/icons/16x16/debug-run.png"), [&](auto&) {
  545. if (g_project->type() != ProjectType::Cpp) {
  546. GUI::MessageBox::show(g_window, String::format("Cannot debug current project type", get_project_executable_path().characters()), "Error", GUI::MessageBox::Type::Error);
  547. return;
  548. }
  549. if (!GUI::FilePicker::file_exists(get_project_executable_path())) {
  550. GUI::MessageBox::show(g_window, String::format("Could not find file: %s. (did you build the project?)", get_project_executable_path().characters()), "Error", GUI::MessageBox::Type::Error);
  551. return;
  552. }
  553. if (Debugger::the().session()) {
  554. GUI::MessageBox::show(g_window, "Debugger is already running", "Error", GUI::MessageBox::Type::Error);
  555. return;
  556. }
  557. Debugger::the().set_executable_path(get_project_executable_path());
  558. debugger_thread = adopt(*new LibThread::Thread(Debugger::start_static));
  559. debugger_thread->start();
  560. });
  561. toolbar.add_separator();
  562. toolbar.add_action(debug_action);
  563. RefPtr<EditorWrapper> current_editor_in_execution;
  564. Debugger::initialize(
  565. [&](const PtraceRegisters& regs) {
  566. ASSERT(Debugger::the().session());
  567. const auto& debug_session = *Debugger::the().session();
  568. auto source_position = debug_session.debug_info().get_source_position(regs.eip);
  569. if (!source_position.has_value()) {
  570. dbg() << "Could not find source position for address: " << (void*)regs.eip;
  571. return Debugger::HasControlPassedToUser::No;
  572. }
  573. Core::EventLoop::main().post_event(
  574. *g_window,
  575. make<Core::DeferredInvocationEvent>(
  576. [&, source_position](auto&) {
  577. current_editor_in_execution = get_editor_of_file(source_position.value().file_path);
  578. current_editor_in_execution->editor().set_execution_position(source_position.value().line_number - 1);
  579. debug_info_widget.update_state(*Debugger::the().session(), regs);
  580. debug_info_widget.set_debug_actions_enabled(true);
  581. disassembly_widget.update_state(*Debugger::the().session(), regs);
  582. reveal_action_tab(debug_info_widget);
  583. }));
  584. Core::EventLoop::wake();
  585. return Debugger::HasControlPassedToUser::Yes;
  586. },
  587. [&]() {
  588. Core::EventLoop::main().post_event(*g_window, make<Core::DeferredInvocationEvent>([&](auto&) {
  589. debug_info_widget.set_debug_actions_enabled(false);
  590. if (current_editor_in_execution) {
  591. current_editor_in_execution->editor().clear_execution_position();
  592. }
  593. }));
  594. Core::EventLoop::wake();
  595. },
  596. [&]() {
  597. Core::EventLoop::main().post_event(*g_window, make<Core::DeferredInvocationEvent>([&](auto&) {
  598. debug_info_widget.program_stopped();
  599. disassembly_widget.program_stopped();
  600. hide_action_tabs();
  601. GUI::MessageBox::show(g_window, "Program Exited", "Debugger", GUI::MessageBox::Type::Information);
  602. }));
  603. Core::EventLoop::wake();
  604. });
  605. auto& build_menu = menubar->add_menu("Build");
  606. build_menu.add_action(build_action);
  607. build_menu.add_separator();
  608. build_menu.add_action(run_action);
  609. build_menu.add_action(stop_action);
  610. build_menu.add_separator();
  611. build_menu.add_action(debug_action);
  612. auto& view_menu = menubar->add_menu("View");
  613. view_menu.add_action(hide_action_tabs_action);
  614. view_menu.add_action(open_locator_action);
  615. view_menu.add_separator();
  616. view_menu.add_action(add_editor_action);
  617. view_menu.add_action(remove_current_editor_action);
  618. view_menu.add_action(add_terminal_action);
  619. view_menu.add_action(remove_current_terminal_action);
  620. auto& help_menu = menubar->add_menu("Help");
  621. help_menu.add_action(GUI::Action::create("About", [&](auto&) {
  622. GUI::AboutDialog::show("HackStudio", Gfx::Bitmap::load_from_file("/res/icons/32x32/app-hack-studio.png"), g_window);
  623. }));
  624. app->set_menubar(move(menubar));
  625. g_window->set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-hack-studio.png"));
  626. g_window->show();
  627. update_actions = [&]() {
  628. auto is_remove_terminal_enabled = []() {
  629. auto widget = s_action_tab_widget->active_widget();
  630. if (!widget)
  631. return false;
  632. if (StringView { "TerminalWrapper" } != widget->class_name())
  633. return false;
  634. if (!reinterpret_cast<TerminalWrapper*>(widget)->user_spawned())
  635. return false;
  636. return true;
  637. };
  638. remove_current_editor_action->set_enabled(g_all_editor_wrappers.size() > 1);
  639. remove_current_terminal_action->set_enabled(is_remove_terminal_enabled());
  640. };
  641. on_action_tab_change = [&]() {
  642. update_actions();
  643. auto git_widget = s_action_tab_widget->active_widget();
  644. if (!git_widget)
  645. return;
  646. if (StringView { "GitWidget" } != git_widget->class_name())
  647. return;
  648. reinterpret_cast<GitWidget*>(git_widget)->refresh();
  649. };
  650. g_open_file = open_file;
  651. if (!argument_absolute_path.is_empty() && !argument_absolute_path.ends_with(".hsp"))
  652. open_file(argument_absolute_path);
  653. else
  654. open_file(g_project->default_file());
  655. update_actions();
  656. return app->exec();
  657. }
  658. void build(TerminalWrapper& wrapper)
  659. {
  660. if (g_project->type() == ProjectType::JavaScript && g_currently_open_file.ends_with(".js"))
  661. wrapper.run_command(String::format("js -A %s", g_currently_open_file.characters()));
  662. else
  663. wrapper.run_command("make");
  664. }
  665. void run(TerminalWrapper& wrapper)
  666. {
  667. if (g_project->type() == ProjectType::JavaScript && g_currently_open_file.ends_with(".js"))
  668. wrapper.run_command(String::format("js %s", g_currently_open_file.characters()));
  669. else
  670. wrapper.run_command("make run");
  671. }
  672. void open_project(String filename)
  673. {
  674. LexicalPath lexical_path(filename);
  675. if (chdir(lexical_path.dirname().characters()) < 0) {
  676. perror("chdir");
  677. exit(1);
  678. }
  679. g_project = Project::load_from_file(filename);
  680. ASSERT(g_project);
  681. if (g_project_tree_view) {
  682. g_project_tree_view->set_model(g_project->model());
  683. g_project_tree_view->toggle_index(g_project_tree_view->model()->index(0, 0));
  684. g_project_tree_view->update();
  685. }
  686. if (Debugger::is_initialized()) {
  687. Debugger::the().reset_breakpoints();
  688. }
  689. }
  690. void open_file(const String& filename)
  691. {
  692. auto project_file = g_project->get_file(filename);
  693. if (project_file) {
  694. current_editor().set_document(const_cast<GUI::TextDocument&>(project_file->document()));
  695. current_editor().set_mode(GUI::TextEditor::Editable);
  696. } else {
  697. auto external_file = ProjectFile::construct_with_name(filename);
  698. current_editor().set_document(const_cast<GUI::TextDocument&>(external_file->document()));
  699. current_editor().set_mode(GUI::TextEditor::ReadOnly);
  700. }
  701. if (filename.ends_with(".cpp") || filename.ends_with(".h"))
  702. current_editor().set_syntax_highlighter(make<GUI::CppSyntaxHighlighter>());
  703. else if (filename.ends_with(".js"))
  704. current_editor().set_syntax_highlighter(make<GUI::JSSyntaxHighlighter>());
  705. else if (filename.ends_with(".ini"))
  706. current_editor().set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  707. else
  708. current_editor().set_syntax_highlighter(nullptr);
  709. if (filename.ends_with(".frm")) {
  710. set_edit_mode(EditMode::Form);
  711. } else {
  712. set_edit_mode(EditMode::Text);
  713. }
  714. g_currently_open_file = filename;
  715. g_window->set_title(String::format("%s - HackStudio", g_currently_open_file.characters()));
  716. g_project_tree_view->update();
  717. current_editor_wrapper().filename_label().set_text(filename);
  718. current_editor().set_focus(true);
  719. }
  720. bool make_is_available()
  721. {
  722. pid_t pid;
  723. const char* argv[] = { "make", "--version", nullptr };
  724. posix_spawn_file_actions_t action;
  725. posix_spawn_file_actions_init(&action);
  726. posix_spawn_file_actions_addopen(&action, STDOUT_FILENO, "/dev/null", O_WRONLY, 0);
  727. if ((errno = posix_spawnp(&pid, "make", &action, nullptr, const_cast<char**>(argv), environ))) {
  728. perror("posix_spawn");
  729. return false;
  730. }
  731. int wstatus;
  732. waitpid(pid, &wstatus, 0);
  733. posix_spawn_file_actions_destroy(&action);
  734. return WEXITSTATUS(wstatus) == 0;
  735. }
  736. }
  737. int main(int argc, char** argv)
  738. {
  739. return main_impl(argc, argv);
  740. }