SpreadsheetView.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. auto const 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(), event.wheel_raw_delta_x(), event.wheel_raw_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. Vector<CellChange> cell_changes;
  200. selection().for_each_index([&](auto& index) {
  201. if (index == m_starting_selection_index)
  202. return;
  203. auto& sheet = static_cast<SheetModel&>(*this->model()).sheet();
  204. Vector<Position> to;
  205. Position position { (size_t)index.column(), (size_t)index.row() };
  206. to.append(position);
  207. auto cell_change = sheet.copy_cells(from, to);
  208. cell_changes.extend(cell_change);
  209. });
  210. if (static_cast<SheetModel&>(*this->model()).on_cells_data_change)
  211. static_cast<SheetModel&>(*this->model()).on_cells_data_change(cell_changes);
  212. update();
  213. }
  214. m_is_dragging_for_select = false;
  215. m_is_dragging_for_cut = false;
  216. m_is_dragging_for_extend = false;
  217. m_has_committed_to_cutting = false;
  218. m_has_committed_to_extending = false;
  219. if (m_is_hovering_cut_zone || m_is_hovering_extend_zone) {
  220. auto rect = content_rect_minus_scrollbars(m_target_cell);
  221. 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(), event.wheel_raw_delta_x(), event.wheel_raw_delta_y() };
  222. TableView::mouseup_event(adjusted_event);
  223. } else {
  224. TableView::mouseup_event(event);
  225. }
  226. }
  227. void InfinitelyScrollableTableView::drop_event(GUI::DropEvent& event)
  228. {
  229. m_is_dragging_for_cut = false;
  230. set_override_cursor(Gfx::StandardCursor::Arrow);
  231. if (!index_at_event_position(event.position()).is_valid())
  232. return;
  233. TableView::drop_event(event);
  234. auto drop_index = index_at_event_position(event.position());
  235. if (selection().size() > 0) {
  236. // Get top left index position of previous selection
  237. auto top_left_most_index = selection().first();
  238. selection().for_each_index([&](auto& index) {
  239. if (index.row() < top_left_most_index.row())
  240. top_left_most_index = index;
  241. else if (index.column() < top_left_most_index.column())
  242. top_left_most_index = index;
  243. });
  244. // Compare with drag location
  245. auto x_diff = drop_index.column() - top_left_most_index.column();
  246. auto y_diff = drop_index.row() - top_left_most_index.row();
  247. // Set new selection
  248. Vector<GUI::ModelIndex> new_selection;
  249. for (auto& index : selection().indices()) {
  250. auto new_index = model()->index(index.row() + y_diff, index.column() + x_diff);
  251. new_selection.append(move(new_index));
  252. }
  253. selection().clear();
  254. AbstractTableView::set_cursor(drop_index, SelectionUpdate::Set);
  255. selection().add_all(new_selection);
  256. }
  257. }
  258. void SpreadsheetView::update_with_model()
  259. {
  260. m_sheet_model->update();
  261. m_table_view->update();
  262. }
  263. SpreadsheetView::SpreadsheetView(Sheet& sheet)
  264. : m_sheet(sheet)
  265. , m_sheet_model(SheetModel::create(*m_sheet))
  266. {
  267. set_layout<GUI::VerticalBoxLayout>().set_margins(2);
  268. m_table_view = add<InfinitelyScrollableTableView>();
  269. m_table_view->set_grid_style(GUI::TableView::GridStyle::Both);
  270. m_table_view->set_selection_behavior(GUI::AbstractView::SelectionBehavior::SelectItems);
  271. m_table_view->set_edit_triggers(GUI::AbstractView::EditTrigger::EditKeyPressed | GUI::AbstractView::AnyKeyPressed | GUI::AbstractView::DoubleClicked);
  272. m_table_view->set_tab_key_navigation_enabled(true);
  273. m_table_view->row_header().set_visible(true);
  274. m_table_view->set_model(m_sheet_model);
  275. m_table_view->on_reaching_vertical_end = [&]() {
  276. for (size_t i = 0; i < 100; ++i) {
  277. auto index = m_sheet->add_row();
  278. m_table_view->set_column_painting_delegate(index, make<TableCellPainter>(*m_table_view));
  279. };
  280. update_with_model();
  281. };
  282. m_table_view->on_reaching_horizontal_end = [&]() {
  283. for (size_t i = 0; i < 10; ++i) {
  284. m_sheet->add_column();
  285. auto last_column_index = m_sheet->column_count() - 1;
  286. m_table_view->set_column_width(last_column_index, 50);
  287. m_table_view->set_default_column_width(last_column_index, 50);
  288. m_table_view->set_column_header_alignment(last_column_index, Gfx::TextAlignment::Center);
  289. m_table_view->set_column_painting_delegate(last_column_index, make<TableCellPainter>(*m_table_view));
  290. }
  291. update_with_model();
  292. };
  293. set_focus_proxy(m_table_view);
  294. // FIXME: This is dumb.
  295. for (size_t i = 0; i < m_sheet->column_count(); ++i) {
  296. m_table_view->set_column_painting_delegate(i, make<TableCellPainter>(*m_table_view));
  297. m_table_view->set_column_width(i, 50);
  298. m_table_view->set_default_column_width(i, 50);
  299. m_table_view->set_column_header_alignment(i, Gfx::TextAlignment::Center);
  300. }
  301. m_table_view->set_alternating_row_colors(false);
  302. m_table_view->set_highlight_selected_rows(false);
  303. m_table_view->set_editable(true);
  304. m_table_view->aid_create_editing_delegate = [this](auto&) {
  305. auto delegate = make<EditingDelegate>(*m_sheet);
  306. delegate->on_cursor_key_pressed = [this](auto& event) {
  307. m_table_view->stop_editing();
  308. m_table_view->dispatch_event(event);
  309. };
  310. delegate->on_cell_focusout = [this](auto& index, auto& value) {
  311. m_table_view->model()->set_data(index, value);
  312. };
  313. return delegate;
  314. };
  315. m_table_view->on_selection_change = [&] {
  316. m_sheet->selected_cells().clear();
  317. for (auto& index : m_table_view->selection().indices()) {
  318. Position position { (size_t)index.column(), (size_t)index.row() };
  319. m_sheet->selected_cells().set(position);
  320. }
  321. if (m_table_view->selection().is_empty() && on_selection_dropped)
  322. return on_selection_dropped();
  323. Vector<Position> selected_positions;
  324. selected_positions.ensure_capacity(m_table_view->selection().size());
  325. for (auto& selection : m_table_view->selection().indices())
  326. selected_positions.empend((size_t)selection.column(), (size_t)selection.row());
  327. if (on_selection_changed) {
  328. on_selection_changed(move(selected_positions));
  329. update_with_model();
  330. };
  331. };
  332. m_table_view->on_activation = [this](auto&) {
  333. m_table_view->move_cursor(GUI::AbstractView::CursorMovement::Down, GUI::AbstractView::SelectionUpdate::Set);
  334. };
  335. m_table_view->on_context_menu_request = [&](const GUI::ModelIndex&, const GUI::ContextMenuEvent& event) {
  336. // NOTE: We ignore the specific cell for now.
  337. m_cell_range_context_menu->popup(event.screen_position());
  338. };
  339. m_cell_range_context_menu = GUI::Menu::construct();
  340. m_cell_range_context_menu->add_action(GUI::Action::create("Type and Formatting...", [this](auto&) {
  341. Vector<Position> positions;
  342. for (auto& index : m_table_view->selection().indices()) {
  343. Position position { (size_t)index.column(), (size_t)index.row() };
  344. positions.append(move(position));
  345. }
  346. if (positions.is_empty()) {
  347. auto& index = m_table_view->cursor_index();
  348. Position position { (size_t)index.column(), (size_t)index.row() };
  349. positions.append(move(position));
  350. }
  351. auto dialog = CellTypeDialog::construct(positions, *m_sheet, window());
  352. if (dialog->exec() == GUI::Dialog::ExecResult::OK) {
  353. for (auto& position : positions) {
  354. auto& cell = m_sheet->ensure(position);
  355. cell.set_type(dialog->type());
  356. cell.set_type_metadata(dialog->metadata());
  357. cell.set_conditional_formats(dialog->conditional_formats());
  358. }
  359. m_table_view->update();
  360. }
  361. }));
  362. m_table_view->on_drop = [&](const GUI::ModelIndex& index, const GUI::DropEvent& event) {
  363. if (!index.is_valid())
  364. return;
  365. ScopeGuard update_after_drop { [this] { update(); } };
  366. if (event.mime_data().has_format("text/x-spreadsheet-data")) {
  367. auto const& data = event.mime_data().data("text/x-spreadsheet-data");
  368. StringView urls { data.data(), data.size() };
  369. Vector<Position> source_positions, target_positions;
  370. for (auto& line : urls.lines(false)) {
  371. auto position = m_sheet->position_from_url(line);
  372. if (position.has_value())
  373. source_positions.append(position.release_value());
  374. }
  375. // Drop always has a single target.
  376. Position target { (size_t)index.column(), (size_t)index.row() };
  377. target_positions.append(move(target));
  378. if (source_positions.is_empty())
  379. return;
  380. auto first_position = source_positions.take_first();
  381. auto cell_changes = m_sheet->copy_cells(move(source_positions), move(target_positions), first_position, Spreadsheet::Sheet::CopyOperation::Cut);
  382. if (model()->on_cells_data_change)
  383. model()->on_cells_data_change(cell_changes);
  384. return;
  385. }
  386. if (event.mime_data().has_text()) {
  387. auto& target_cell = m_sheet->ensure({ (size_t)index.column(), (size_t)index.row() });
  388. target_cell.set_data(event.text());
  389. return;
  390. }
  391. };
  392. }
  393. void SpreadsheetView::hide_event(GUI::HideEvent&)
  394. {
  395. if (on_selection_dropped)
  396. on_selection_dropped();
  397. }
  398. void SpreadsheetView::show_event(GUI::ShowEvent&)
  399. {
  400. if (on_selection_changed && !m_table_view->selection().is_empty()) {
  401. Vector<Position> selected_positions;
  402. selected_positions.ensure_capacity(m_table_view->selection().size());
  403. for (auto& selection : m_table_view->selection().indices())
  404. selected_positions.empend((size_t)selection.column(), (size_t)selection.row());
  405. on_selection_changed(move(selected_positions));
  406. }
  407. }
  408. void SpreadsheetView::move_cursor(GUI::AbstractView::CursorMovement direction)
  409. {
  410. m_table_view->move_cursor(direction, GUI::AbstractView::SelectionUpdate::Set);
  411. }
  412. void SpreadsheetView::TableCellPainter::paint(GUI::Painter& painter, Gfx::IntRect const& rect, Gfx::Palette const& palette, const GUI::ModelIndex& index)
  413. {
  414. // Draw a border.
  415. // Undo the horizontal padding done by the table view...
  416. auto cell_rect = rect.inflated(m_table_view.horizontal_padding() * 2, 0);
  417. if (auto bg = index.data(GUI::ModelRole::BackgroundColor); bg.is_color())
  418. painter.fill_rect(cell_rect, bg.as_color());
  419. if (m_table_view.selection().contains(index)) {
  420. Color fill_color = palette.selection();
  421. fill_color.set_alpha(80);
  422. painter.fill_rect(cell_rect, fill_color);
  423. }
  424. auto text_color = index.data(GUI::ModelRole::ForegroundColor).to_color(palette.color(m_table_view.foreground_role()));
  425. auto data = index.data();
  426. auto text_alignment = index.data(GUI::ModelRole::TextAlignment).to_text_alignment(Gfx::TextAlignment::CenterRight);
  427. painter.draw_text(rect, data.to_string(), m_table_view.font_for_index(index), text_alignment, text_color, Gfx::TextElision::Right);
  428. }
  429. }