main.cpp 34 KB

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