SpreadsheetView.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*
  2. * Copyright (c) 2020-2022, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "SpreadsheetView.h"
  7. #include "CellTypeDialog.h"
  8. #include <AK/ScopeGuard.h>
  9. #include <AK/URL.h>
  10. #include <LibCore/MimeData.h>
  11. #include <LibGUI/BoxLayout.h>
  12. #include <LibGUI/HeaderView.h>
  13. #include <LibGUI/Menu.h>
  14. #include <LibGUI/ModelEditingDelegate.h>
  15. #include <LibGUI/Painter.h>
  16. #include <LibGUI/Scrollbar.h>
  17. #include <LibGUI/TableView.h>
  18. #include <LibGfx/Palette.h>
  19. namespace Spreadsheet {
  20. void SpreadsheetView::EditingDelegate::set_value(GUI::Variant const& value, GUI::ModelEditingDelegate::SelectionBehavior selection_behavior)
  21. {
  22. if (value.as_string().is_null()) {
  23. StringModelEditingDelegate::set_value("", selection_behavior);
  24. commit();
  25. return;
  26. }
  27. if (m_has_set_initial_value)
  28. return StringModelEditingDelegate::set_value(value, selection_behavior);
  29. m_has_set_initial_value = true;
  30. const auto option = m_sheet.at({ (size_t)index().column(), (size_t)index().row() });
  31. if (option)
  32. return StringModelEditingDelegate::set_value(option->source(), selection_behavior);
  33. StringModelEditingDelegate::set_value("", selection_behavior);
  34. }
  35. void InfinitelyScrollableTableView::did_scroll()
  36. {
  37. TableView::did_scroll();
  38. auto& vscrollbar = vertical_scrollbar();
  39. auto& hscrollbar = horizontal_scrollbar();
  40. if (!m_vertical_scroll_end_timer->is_active()) {
  41. if (vscrollbar.is_visible() && vscrollbar.value() == vscrollbar.max()) {
  42. m_vertical_scroll_end_timer->on_timeout = [&] {
  43. if (on_reaching_vertical_end)
  44. on_reaching_vertical_end();
  45. m_vertical_scroll_end_timer->stop();
  46. };
  47. m_vertical_scroll_end_timer->start(50);
  48. }
  49. }
  50. if (!m_horizontal_scroll_end_timer->is_active()) {
  51. if (hscrollbar.is_visible() && hscrollbar.value() == hscrollbar.max()) {
  52. m_horizontal_scroll_end_timer->on_timeout = [&] {
  53. if (on_reaching_horizontal_end)
  54. on_reaching_horizontal_end();
  55. m_horizontal_scroll_end_timer->stop();
  56. };
  57. m_horizontal_scroll_end_timer->start(50);
  58. }
  59. }
  60. }
  61. void InfinitelyScrollableTableView::mousemove_event(GUI::MouseEvent& event)
  62. {
  63. if (auto model = this->model()) {
  64. auto index = index_at_event_position(event.position());
  65. if (!index.is_valid())
  66. return TableView::mousemove_event(event);
  67. auto& sheet = static_cast<SheetModel&>(*model).sheet();
  68. sheet.disable_updates();
  69. ScopeGuard sheet_update_enabler { [&] { sheet.enable_updates(); } };
  70. m_is_hovering_cut_zone = false;
  71. m_is_hovering_extend_zone = false;
  72. if (selection().size() > 0 && !m_is_dragging_for_select) {
  73. // Get top-left and bottom-right most cells of selection
  74. auto bottom_right_most_index = selection().first();
  75. auto top_left_most_index = selection().first();
  76. selection().for_each_index([&](auto& index) {
  77. if (index.row() > bottom_right_most_index.row())
  78. bottom_right_most_index = index;
  79. else if (index.column() > bottom_right_most_index.column())
  80. bottom_right_most_index = index;
  81. if (index.row() < top_left_most_index.row())
  82. top_left_most_index = index;
  83. else if (index.column() < top_left_most_index.column())
  84. top_left_most_index = index;
  85. });
  86. auto top_left_rect = content_rect_minus_scrollbars(top_left_most_index);
  87. auto bottom_right_rect = content_rect_minus_scrollbars(bottom_right_most_index);
  88. auto distance_tl = top_left_rect.center() - event.position();
  89. auto distance_br = bottom_right_rect.center() - event.position();
  90. auto is_over_top_line = false;
  91. auto is_over_bottom_line = false;
  92. auto is_over_left_line = false;
  93. auto is_over_right_line = false;
  94. // If cursor is within the bounds of the selection
  95. auto select_padding = 2;
  96. if ((distance_br.y() >= -(bottom_right_rect.height() / 2 + select_padding)) && (distance_tl.y() <= (top_left_rect.height() / 2 + select_padding)) && (distance_br.x() >= -(bottom_right_rect.width() / 2 + select_padding)) && (distance_tl.x() <= (top_left_rect.width() / 2 + select_padding))) {
  97. if (distance_tl.y() >= (top_left_rect.height() / 2 - select_padding))
  98. is_over_top_line = true;
  99. else if (distance_br.y() <= -(bottom_right_rect.height() / 2 - select_padding))
  100. is_over_bottom_line = true;
  101. if (distance_tl.x() >= (top_left_rect.width() / 2 - select_padding))
  102. is_over_left_line = true;
  103. else if (distance_br.x() <= -(bottom_right_rect.width() / 2 - select_padding))
  104. is_over_right_line = true;
  105. }
  106. if (is_over_bottom_line && is_over_right_line) {
  107. m_target_cell = bottom_right_most_index;
  108. m_is_hovering_extend_zone = true;
  109. } else if (is_over_top_line || is_over_bottom_line || is_over_left_line || is_over_right_line) {
  110. m_target_cell = top_left_most_index;
  111. m_is_hovering_cut_zone = true;
  112. }
  113. }
  114. if (m_is_hovering_cut_zone || m_is_dragging_for_cut)
  115. set_override_cursor(Gfx::StandardCursor::Drag);
  116. else if (m_is_hovering_extend_zone || m_is_dragging_for_extend)
  117. set_override_cursor(Gfx::StandardCursor::Crosshair);
  118. else
  119. set_override_cursor(Gfx::StandardCursor::Arrow);
  120. auto holding_left_button = !!(event.buttons() & GUI::MouseButton::Primary);
  121. if (m_is_dragging_for_cut) {
  122. m_is_dragging_for_select = false;
  123. if (holding_left_button) {
  124. m_has_committed_to_cutting = true;
  125. }
  126. } else if (!m_is_dragging_for_select) {
  127. if (!holding_left_button) {
  128. m_starting_selection_index = index;
  129. } else {
  130. m_is_dragging_for_select = true;
  131. m_might_drag = false;
  132. }
  133. }
  134. if (!m_has_committed_to_extending) {
  135. if (m_is_dragging_for_extend && holding_left_button) {
  136. m_has_committed_to_extending = true;
  137. m_starting_selection_index = m_target_cell;
  138. }
  139. }
  140. if (holding_left_button && m_is_dragging_for_select && !m_has_committed_to_cutting) {
  141. if (!m_starting_selection_index.is_valid())
  142. m_starting_selection_index = index;
  143. Vector<GUI::ModelIndex> new_selection;
  144. for (auto i = min(m_starting_selection_index.row(), index.row()), imax = max(m_starting_selection_index.row(), index.row()); i <= imax; ++i) {
  145. for (auto j = min(m_starting_selection_index.column(), index.column()), jmax = max(m_starting_selection_index.column(), index.column()); j <= jmax; ++j) {
  146. auto index = model->index(i, j);
  147. if (index.is_valid())
  148. new_selection.append(move(index));
  149. }
  150. }
  151. if (!event.ctrl())
  152. selection().clear();
  153. // Since the extend function has similarities to the select, then do
  154. // a check within the selection process to see if extending.
  155. if (m_has_committed_to_extending) {
  156. if (index.row() == m_target_cell.row() || index.column() == m_target_cell.column())
  157. selection().add_all(new_selection);
  158. else
  159. // Prevent the target cell from being unselected in the cases
  160. // when extending in a direction that is not in the same column or
  161. // row as the same. (Extension can only be done linearly, not diagonally)
  162. selection().add(m_target_cell);
  163. } else {
  164. selection().add_all(new_selection);
  165. }
  166. }
  167. }
  168. TableView::mousemove_event(event);
  169. }
  170. void InfinitelyScrollableTableView::mousedown_event(GUI::MouseEvent& event)
  171. {
  172. // Override the mouse event so that the the cell that is 'clicked' is not
  173. // the one right beneath the cursor but instead the one that is referred to
  174. // when m_is_hovering_cut_zone as it can be the case that the user is targetting
  175. // a cell yet be outside of its bounding box due to the select_padding.
  176. if (m_is_hovering_cut_zone || m_is_hovering_extend_zone) {
  177. if (m_is_hovering_cut_zone)
  178. m_is_dragging_for_cut = true;
  179. else if (m_is_hovering_extend_zone)
  180. m_is_dragging_for_extend = true;
  181. auto rect = content_rect_minus_scrollbars(m_target_cell);
  182. GUI::MouseEvent adjusted_event = { (GUI::Event::Type)event.type(), rect.center(), event.buttons(), event.button(), event.modifiers(), event.wheel_delta_x(), event.wheel_delta_y() };
  183. AbstractTableView::mousedown_event(adjusted_event);
  184. } else {
  185. AbstractTableView::mousedown_event(event);
  186. if (event.button() == GUI::Primary) {
  187. auto index = index_at_event_position(event.position());
  188. AbstractTableView::set_cursor(index, SelectionUpdate::Set);
  189. }
  190. }
  191. }
  192. void InfinitelyScrollableTableView::mouseup_event(GUI::MouseEvent& event)
  193. {
  194. // If done extending
  195. if (m_has_committed_to_extending) {
  196. Vector<Position> from;
  197. Position position { (size_t)m_target_cell.column(), (size_t)m_target_cell.row() };
  198. from.append(position);
  199. selection().for_each_index([&](auto& index) {
  200. if (index == m_starting_selection_index)
  201. return;
  202. auto& sheet = static_cast<SheetModel&>(*this->model()).sheet();
  203. Vector<Position> to;
  204. Position position { (size_t)index.column(), (size_t)index.row() };
  205. to.append(position);
  206. sheet.copy_cells(from, to);
  207. });
  208. update();
  209. }
  210. m_is_dragging_for_select = false;
  211. m_is_dragging_for_cut = false;
  212. m_is_dragging_for_extend = false;
  213. m_has_committed_to_cutting = false;
  214. m_has_committed_to_extending = false;
  215. if (m_is_hovering_cut_zone || m_is_hovering_extend_zone) {
  216. auto rect = content_rect_minus_scrollbars(m_target_cell);
  217. GUI::MouseEvent adjusted_event = { (GUI::Event::Type)event.type(), rect.center(), event.buttons(), event.button(), event.modifiers(), event.wheel_delta_x(), event.wheel_delta_y() };
  218. TableView::mouseup_event(adjusted_event);
  219. } else {
  220. TableView::mouseup_event(event);
  221. }
  222. }
  223. void InfinitelyScrollableTableView::drop_event(GUI::DropEvent& event)
  224. {
  225. m_is_dragging_for_cut = false;
  226. set_override_cursor(Gfx::StandardCursor::Arrow);
  227. if (!index_at_event_position(event.position()).is_valid())
  228. return;
  229. TableView::drop_event(event);
  230. auto drop_index = index_at_event_position(event.position());
  231. if (selection().size() > 0) {
  232. // Get top left index position of previous selection
  233. auto top_left_most_index = selection().first();
  234. selection().for_each_index([&](auto& index) {
  235. if (index.row() < top_left_most_index.row())
  236. top_left_most_index = index;
  237. else if (index.column() < top_left_most_index.column())
  238. top_left_most_index = index;
  239. });
  240. // Compare with drag location
  241. auto x_diff = drop_index.column() - top_left_most_index.column();
  242. auto y_diff = drop_index.row() - top_left_most_index.row();
  243. // Set new selection
  244. Vector<GUI::ModelIndex> new_selection;
  245. for (auto& index : selection().indices()) {
  246. auto new_index = model()->index(index.row() + y_diff, index.column() + x_diff);
  247. new_selection.append(move(new_index));
  248. }
  249. selection().clear();
  250. AbstractTableView::set_cursor(drop_index, SelectionUpdate::Set);
  251. selection().add_all(new_selection);
  252. }
  253. }
  254. void SpreadsheetView::update_with_model()
  255. {
  256. m_sheet_model->update();
  257. m_table_view->update();
  258. }
  259. SpreadsheetView::SpreadsheetView(Sheet& sheet)
  260. : m_sheet(sheet)
  261. , m_sheet_model(SheetModel::create(*m_sheet))
  262. {
  263. set_layout<GUI::VerticalBoxLayout>().set_margins(2);
  264. m_table_view = add<InfinitelyScrollableTableView>();
  265. m_table_view->set_grid_style(GUI::TableView::GridStyle::Both);
  266. m_table_view->set_selection_behavior(GUI::AbstractView::SelectionBehavior::SelectItems);
  267. m_table_view->set_edit_triggers(GUI::AbstractView::EditTrigger::EditKeyPressed | GUI::AbstractView::AnyKeyPressed | GUI::AbstractView::DoubleClicked);
  268. m_table_view->set_tab_key_navigation_enabled(true);
  269. m_table_view->row_header().set_visible(true);
  270. m_table_view->set_model(m_sheet_model);
  271. m_table_view->on_reaching_vertical_end = [&]() {
  272. for (size_t i = 0; i < 100; ++i) {
  273. auto index = m_sheet->add_row();
  274. m_table_view->set_column_painting_delegate(index, make<TableCellPainter>(*m_table_view));
  275. };
  276. update_with_model();
  277. };
  278. m_table_view->on_reaching_horizontal_end = [&]() {
  279. for (size_t i = 0; i < 10; ++i) {
  280. m_sheet->add_column();
  281. auto last_column_index = m_sheet->column_count() - 1;
  282. m_table_view->set_column_width(last_column_index, 50);
  283. m_table_view->set_default_column_width(last_column_index, 50);
  284. m_table_view->set_column_header_alignment(last_column_index, Gfx::TextAlignment::Center);
  285. m_table_view->set_column_painting_delegate(last_column_index, make<TableCellPainter>(*m_table_view));
  286. }
  287. update_with_model();
  288. };
  289. set_focus_proxy(m_table_view);
  290. // FIXME: This is dumb.
  291. for (size_t i = 0; i < m_sheet->column_count(); ++i) {
  292. m_table_view->set_column_painting_delegate(i, make<TableCellPainter>(*m_table_view));
  293. m_table_view->set_column_width(i, 50);
  294. m_table_view->set_default_column_width(i, 50);
  295. m_table_view->set_column_header_alignment(i, Gfx::TextAlignment::Center);
  296. }
  297. m_table_view->set_alternating_row_colors(false);
  298. m_table_view->set_highlight_selected_rows(false);
  299. m_table_view->set_editable(true);
  300. m_table_view->aid_create_editing_delegate = [this](auto&) {
  301. auto delegate = make<EditingDelegate>(*m_sheet);
  302. delegate->on_cursor_key_pressed = [this](auto& event) {
  303. m_table_view->stop_editing();
  304. m_table_view->dispatch_event(event);
  305. };
  306. delegate->on_cell_focusout = [this](auto& index, auto& value) {
  307. m_table_view->model()->set_data(index, value);
  308. };
  309. return delegate;
  310. };
  311. m_table_view->on_selection_change = [&] {
  312. m_sheet->selected_cells().clear();
  313. for (auto& index : m_table_view->selection().indices()) {
  314. Position position { (size_t)index.column(), (size_t)index.row() };
  315. m_sheet->selected_cells().set(position);
  316. }
  317. if (m_table_view->selection().is_empty() && on_selection_dropped)
  318. return on_selection_dropped();
  319. Vector<Position> selected_positions;
  320. selected_positions.ensure_capacity(m_table_view->selection().size());
  321. for (auto& selection : m_table_view->selection().indices())
  322. selected_positions.empend((size_t)selection.column(), (size_t)selection.row());
  323. if (on_selection_changed) {
  324. on_selection_changed(move(selected_positions));
  325. update_with_model();
  326. };
  327. };
  328. m_table_view->on_activation = [this](auto&) {
  329. m_table_view->move_cursor(GUI::AbstractView::CursorMovement::Down, GUI::AbstractView::SelectionUpdate::Set);
  330. };
  331. m_table_view->on_context_menu_request = [&](const GUI::ModelIndex&, const GUI::ContextMenuEvent& event) {
  332. // NOTE: We ignore the specific cell for now.
  333. m_cell_range_context_menu->popup(event.screen_position());
  334. };
  335. m_cell_range_context_menu = GUI::Menu::construct();
  336. m_cell_range_context_menu->add_action(GUI::Action::create("Type and Formatting...", [this](auto&) {
  337. Vector<Position> positions;
  338. for (auto& index : m_table_view->selection().indices()) {
  339. Position position { (size_t)index.column(), (size_t)index.row() };
  340. positions.append(move(position));
  341. }
  342. if (positions.is_empty()) {
  343. auto& index = m_table_view->cursor_index();
  344. Position position { (size_t)index.column(), (size_t)index.row() };
  345. positions.append(move(position));
  346. }
  347. auto dialog = CellTypeDialog::construct(positions, *m_sheet, window());
  348. if (dialog->exec() == GUI::Dialog::ExecOK) {
  349. for (auto& position : positions) {
  350. auto& cell = m_sheet->ensure(position);
  351. cell.set_type(dialog->type());
  352. cell.set_type_metadata(dialog->metadata());
  353. cell.set_conditional_formats(dialog->conditional_formats());
  354. }
  355. m_table_view->update();
  356. }
  357. }));
  358. m_table_view->on_drop = [&](const GUI::ModelIndex& index, const GUI::DropEvent& event) {
  359. if (!index.is_valid())
  360. return;
  361. ScopeGuard update_after_drop { [this] { update(); } };
  362. if (event.mime_data().has_format("text/x-spreadsheet-data")) {
  363. auto const& data = event.mime_data().data("text/x-spreadsheet-data");
  364. StringView urls { data.data(), data.size() };
  365. Vector<Position> source_positions, target_positions;
  366. for (auto& line : urls.lines(false)) {
  367. auto position = m_sheet->position_from_url(line);
  368. if (position.has_value())
  369. source_positions.append(position.release_value());
  370. }
  371. // Drop always has a single target.
  372. Position target { (size_t)index.column(), (size_t)index.row() };
  373. target_positions.append(move(target));
  374. if (source_positions.is_empty())
  375. return;
  376. auto first_position = source_positions.take_first();
  377. m_sheet->copy_cells(move(source_positions), move(target_positions), first_position, Spreadsheet::Sheet::CopyOperation::Cut);
  378. return;
  379. }
  380. if (event.mime_data().has_text()) {
  381. auto& target_cell = m_sheet->ensure({ (size_t)index.column(), (size_t)index.row() });
  382. target_cell.set_data(event.text());
  383. return;
  384. }
  385. };
  386. }
  387. void SpreadsheetView::hide_event(GUI::HideEvent&)
  388. {
  389. if (on_selection_dropped)
  390. on_selection_dropped();
  391. }
  392. void SpreadsheetView::show_event(GUI::ShowEvent&)
  393. {
  394. if (on_selection_changed && !m_table_view->selection().is_empty()) {
  395. Vector<Position> selected_positions;
  396. selected_positions.ensure_capacity(m_table_view->selection().size());
  397. for (auto& selection : m_table_view->selection().indices())
  398. selected_positions.empend((size_t)selection.column(), (size_t)selection.row());
  399. on_selection_changed(move(selected_positions));
  400. }
  401. }
  402. void SpreadsheetView::move_cursor(GUI::AbstractView::CursorMovement direction)
  403. {
  404. m_table_view->move_cursor(direction, GUI::AbstractView::SelectionUpdate::Set);
  405. }
  406. void SpreadsheetView::TableCellPainter::paint(GUI::Painter& painter, const Gfx::IntRect& rect, const Gfx::Palette& palette, const GUI::ModelIndex& index)
  407. {
  408. // Draw a border.
  409. // Undo the horizontal padding done by the table view...
  410. auto cell_rect = rect.inflated(m_table_view.horizontal_padding() * 2, 0);
  411. if (auto bg = index.data(GUI::ModelRole::BackgroundColor); bg.is_color())
  412. painter.fill_rect(cell_rect, bg.as_color());
  413. if (m_table_view.selection().contains(index)) {
  414. Color fill_color = palette.selection();
  415. fill_color.set_alpha(80);
  416. painter.fill_rect(cell_rect, fill_color);
  417. }
  418. auto text_color = index.data(GUI::ModelRole::ForegroundColor).to_color(palette.color(m_table_view.foreground_role()));
  419. auto data = index.data();
  420. auto text_alignment = index.data(GUI::ModelRole::TextAlignment).to_text_alignment(Gfx::TextAlignment::CenterRight);
  421. painter.draw_text(rect, data.to_string(), m_table_view.font_for_index(index), text_alignment, text_color, Gfx::TextElision::Right);
  422. }
  423. }