main.cpp 33 KB

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