SpreadsheetView.cpp 21 KB

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