AbstractView.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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 <AK/StringBuilder.h>
  27. #include <AK/Utf8View.h>
  28. #include <AK/Vector.h>
  29. #include <LibCore/Timer.h>
  30. #include <LibGUI/AbstractView.h>
  31. #include <LibGUI/DragOperation.h>
  32. #include <LibGUI/Model.h>
  33. #include <LibGUI/ModelEditingDelegate.h>
  34. #include <LibGUI/Painter.h>
  35. #include <LibGUI/ScrollBar.h>
  36. #include <LibGUI/TextBox.h>
  37. #include <LibGfx/Palette.h>
  38. namespace GUI {
  39. AbstractView::AbstractView()
  40. : m_sort_order(SortOrder::Ascending)
  41. , m_selection(*this)
  42. {
  43. }
  44. AbstractView::~AbstractView()
  45. {
  46. if (m_searching_timer)
  47. m_searching_timer->stop();
  48. if (m_model)
  49. m_model->unregister_view({}, *this);
  50. }
  51. void AbstractView::set_model(RefPtr<Model> model)
  52. {
  53. if (model == m_model)
  54. return;
  55. if (m_model)
  56. m_model->unregister_view({}, *this);
  57. m_model = move(model);
  58. if (m_model)
  59. m_model->register_view({}, *this);
  60. did_update_model(GUI::Model::InvalidateAllIndexes);
  61. scroll_to_top();
  62. }
  63. void AbstractView::did_update_model(unsigned flags)
  64. {
  65. // FIXME: It's unfortunate that we lose so much view state when the model updates in any way.
  66. stop_editing();
  67. m_edit_index = {};
  68. m_hovered_index = {};
  69. if (!model() || (flags & GUI::Model::InvalidateAllIndexes)) {
  70. clear_selection();
  71. } else {
  72. selection().remove_matching([this](auto& index) { return !model()->is_valid(index); });
  73. }
  74. }
  75. void AbstractView::clear_selection()
  76. {
  77. m_selection.clear();
  78. }
  79. void AbstractView::set_selection(const ModelIndex& new_index)
  80. {
  81. m_selection.set(new_index);
  82. }
  83. void AbstractView::add_selection(const ModelIndex& new_index)
  84. {
  85. m_selection.add(new_index);
  86. }
  87. void AbstractView::remove_selection(const ModelIndex& new_index)
  88. {
  89. m_selection.remove(new_index);
  90. }
  91. void AbstractView::toggle_selection(const ModelIndex& new_index)
  92. {
  93. m_selection.toggle(new_index);
  94. }
  95. void AbstractView::did_update_selection()
  96. {
  97. if (!model() || selection().first() != m_edit_index)
  98. stop_editing();
  99. if (model() && on_selection && selection().first().is_valid())
  100. on_selection(selection().first());
  101. }
  102. void AbstractView::did_scroll()
  103. {
  104. update_edit_widget_position();
  105. }
  106. void AbstractView::update_edit_widget_position()
  107. {
  108. if (!m_edit_widget)
  109. return;
  110. m_edit_widget->set_relative_rect(m_edit_widget_content_rect.translated(-horizontal_scrollbar().value(), -vertical_scrollbar().value()));
  111. }
  112. void AbstractView::begin_editing(const ModelIndex& index)
  113. {
  114. ASSERT(is_editable());
  115. ASSERT(model());
  116. if (m_edit_index == index)
  117. return;
  118. if (!model()->is_editable(index))
  119. return;
  120. if (m_edit_widget) {
  121. remove_child(*m_edit_widget);
  122. m_edit_widget = nullptr;
  123. }
  124. m_edit_index = index;
  125. ASSERT(aid_create_editing_delegate);
  126. m_editing_delegate = aid_create_editing_delegate(index);
  127. m_editing_delegate->bind(*model(), index);
  128. m_editing_delegate->set_value(index.data());
  129. m_edit_widget = m_editing_delegate->widget();
  130. add_child(*m_edit_widget);
  131. m_edit_widget->move_to_back();
  132. m_edit_widget_content_rect = content_rect(index).translated(frame_thickness(), frame_thickness());
  133. update_edit_widget_position();
  134. m_edit_widget->set_focus(true);
  135. m_editing_delegate->will_begin_editing();
  136. m_editing_delegate->on_commit = [this] {
  137. ASSERT(model());
  138. model()->set_data(m_edit_index, m_editing_delegate->value());
  139. stop_editing();
  140. };
  141. m_editing_delegate->on_rollback = [this] {
  142. ASSERT(model());
  143. stop_editing();
  144. };
  145. }
  146. void AbstractView::stop_editing()
  147. {
  148. bool take_back_focus = false;
  149. m_edit_index = {};
  150. if (m_edit_widget) {
  151. take_back_focus = m_edit_widget->is_focused();
  152. remove_child(*m_edit_widget);
  153. m_edit_widget = nullptr;
  154. }
  155. if (take_back_focus)
  156. set_focus(true);
  157. }
  158. void AbstractView::activate(const ModelIndex& index)
  159. {
  160. if (on_activation)
  161. on_activation(index);
  162. }
  163. void AbstractView::activate_selected()
  164. {
  165. if (!on_activation)
  166. return;
  167. selection().for_each_index([this](auto& index) {
  168. on_activation(index);
  169. });
  170. }
  171. void AbstractView::notify_selection_changed(Badge<ModelSelection>)
  172. {
  173. did_update_selection();
  174. if (on_selection_change)
  175. on_selection_change();
  176. update();
  177. }
  178. NonnullRefPtr<Gfx::Font> AbstractView::font_for_index(const ModelIndex& index) const
  179. {
  180. if (!model())
  181. return font();
  182. auto font_data = index.data(ModelRole::Font);
  183. if (font_data.is_font())
  184. return font_data.as_font();
  185. return font();
  186. }
  187. void AbstractView::mousedown_event(MouseEvent& event)
  188. {
  189. ScrollableWidget::mousedown_event(event);
  190. if (!model())
  191. return;
  192. if (event.button() == MouseButton::Left)
  193. m_left_mousedown_position = event.position();
  194. auto index = index_at_event_position(event.position());
  195. m_might_drag = false;
  196. if (!index.is_valid()) {
  197. clear_selection();
  198. } else if (event.modifiers() & Mod_Ctrl) {
  199. set_cursor(index, SelectionUpdate::Ctrl);
  200. } else if (event.button() == MouseButton::Left && m_selection.contains(index) && !m_model->drag_data_type().is_null()) {
  201. // We might be starting a drag, so don't throw away other selected items yet.
  202. m_might_drag = true;
  203. } else if (event.button() == MouseButton::Right) {
  204. set_cursor(index, SelectionUpdate::ClearIfNotSelected);
  205. } else {
  206. set_cursor(index, SelectionUpdate::Set);
  207. }
  208. update();
  209. }
  210. void AbstractView::set_hovered_index(const ModelIndex& index)
  211. {
  212. if (m_hovered_index == index)
  213. return;
  214. auto old_index = m_hovered_index;
  215. m_hovered_index = index;
  216. did_change_hovered_index(old_index, index);
  217. update();
  218. }
  219. void AbstractView::leave_event(Core::Event& event)
  220. {
  221. ScrollableWidget::leave_event(event);
  222. set_hovered_index({});
  223. }
  224. void AbstractView::mousemove_event(MouseEvent& event)
  225. {
  226. if (!model())
  227. return ScrollableWidget::mousemove_event(event);
  228. auto hovered_index = index_at_event_position(event.position());
  229. set_hovered_index(hovered_index);
  230. if (!m_might_drag)
  231. return ScrollableWidget::mousemove_event(event);
  232. if (!(event.buttons() & MouseButton::Left) || m_selection.is_empty()) {
  233. m_might_drag = false;
  234. return ScrollableWidget::mousemove_event(event);
  235. }
  236. auto diff = event.position() - m_left_mousedown_position;
  237. auto distance_travelled_squared = diff.x() * diff.x() + diff.y() * diff.y();
  238. constexpr int drag_distance_threshold = 5;
  239. if (distance_travelled_squared <= drag_distance_threshold)
  240. return ScrollableWidget::mousemove_event(event);
  241. auto data_type = m_model->drag_data_type();
  242. ASSERT(!data_type.is_null());
  243. dbg() << "Initiate drag!";
  244. auto drag_operation = DragOperation::construct();
  245. RefPtr<Gfx::Bitmap> bitmap;
  246. StringBuilder text_builder;
  247. StringBuilder data_builder;
  248. bool first = true;
  249. m_selection.for_each_index([&](auto& index) {
  250. auto text_data = index.data();
  251. if (!first)
  252. text_builder.append(", ");
  253. text_builder.append(text_data.to_string());
  254. auto drag_data = index.data(ModelRole::DragData);
  255. data_builder.append(drag_data.to_string());
  256. data_builder.append('\n');
  257. first = false;
  258. if (!bitmap) {
  259. Variant icon_data = index.data(ModelRole::Icon);
  260. if (icon_data.is_icon())
  261. bitmap = icon_data.as_icon().bitmap_for_size(32);
  262. }
  263. });
  264. drag_operation->set_text(text_builder.to_string());
  265. drag_operation->set_bitmap(bitmap);
  266. drag_operation->set_data(data_type, data_builder.to_string());
  267. auto outcome = drag_operation->exec();
  268. switch (outcome) {
  269. case DragOperation::Outcome::Accepted:
  270. dbg() << "Drag was accepted!";
  271. break;
  272. case DragOperation::Outcome::Cancelled:
  273. dbg() << "Drag was cancelled!";
  274. break;
  275. default:
  276. ASSERT_NOT_REACHED();
  277. break;
  278. }
  279. }
  280. void AbstractView::mouseup_event(MouseEvent& event)
  281. {
  282. ScrollableWidget::mouseup_event(event);
  283. if (!model())
  284. return;
  285. if (m_might_drag) {
  286. // We were unsure about unselecting items other than the current one
  287. // in mousedown_event(), because we could be seeing a start of a drag.
  288. // Since we're here, it was not that; so fix up the selection now.
  289. auto index = index_at_event_position(event.position());
  290. if (index.is_valid())
  291. set_selection(index);
  292. else
  293. clear_selection();
  294. m_might_drag = false;
  295. update();
  296. }
  297. if (activates_on_selection())
  298. activate_selected();
  299. }
  300. void AbstractView::doubleclick_event(MouseEvent& event)
  301. {
  302. if (!model())
  303. return;
  304. if (event.button() != MouseButton::Left)
  305. return;
  306. m_might_drag = false;
  307. auto index = index_at_event_position(event.position());
  308. if (!index.is_valid())
  309. clear_selection();
  310. else if (!m_selection.contains(index))
  311. set_selection(index);
  312. if (is_editable() && edit_triggers() & EditTrigger::DoubleClicked)
  313. begin_editing(cursor_index());
  314. else
  315. activate(cursor_index());
  316. }
  317. void AbstractView::context_menu_event(ContextMenuEvent& event)
  318. {
  319. if (!model())
  320. return;
  321. auto index = index_at_event_position(event.position());
  322. if (index.is_valid())
  323. add_selection(index);
  324. else
  325. clear_selection();
  326. if (on_context_menu_request)
  327. on_context_menu_request(index, event);
  328. }
  329. void AbstractView::drop_event(DropEvent& event)
  330. {
  331. event.accept();
  332. if (!model())
  333. return;
  334. auto index = index_at_event_position(event.position());
  335. if (on_drop)
  336. on_drop(index, event);
  337. }
  338. void AbstractView::set_multi_select(bool multi_select)
  339. {
  340. if (m_multi_select == multi_select)
  341. return;
  342. m_multi_select = multi_select;
  343. if (!multi_select && m_selection.size() > 1) {
  344. auto first_selected = m_selection.first();
  345. m_selection.clear();
  346. m_selection.set(first_selected);
  347. }
  348. }
  349. void AbstractView::set_key_column_and_sort_order(int column, SortOrder sort_order)
  350. {
  351. m_key_column = column;
  352. m_sort_order = sort_order;
  353. if (model())
  354. model()->sort(column, sort_order);
  355. update();
  356. }
  357. void AbstractView::set_cursor(ModelIndex index, SelectionUpdate selection_update, bool scroll_cursor_into_view)
  358. {
  359. if (!model() || !index.is_valid()) {
  360. m_cursor_index = {};
  361. cancel_searching();
  362. return;
  363. }
  364. if (!m_cursor_index.is_valid() || model()->parent_index(m_cursor_index) != model()->parent_index(index))
  365. cancel_searching();
  366. if (model()->is_valid(index)) {
  367. if (selection_update == SelectionUpdate::Set)
  368. set_selection(index);
  369. else if (selection_update == SelectionUpdate::Ctrl)
  370. toggle_selection(index);
  371. else if (selection_update == SelectionUpdate::ClearIfNotSelected) {
  372. if (!m_selection.contains(index))
  373. clear_selection();
  374. }
  375. // FIXME: Support the other SelectionUpdate types
  376. auto old_cursor_index = m_cursor_index;
  377. m_cursor_index = index;
  378. did_change_cursor_index(old_cursor_index, m_cursor_index);
  379. if (scroll_cursor_into_view)
  380. scroll_into_view(index, true, true);
  381. update();
  382. }
  383. }
  384. void AbstractView::set_edit_triggers(unsigned triggers)
  385. {
  386. m_edit_triggers = triggers;
  387. }
  388. void AbstractView::hide_event(HideEvent& event)
  389. {
  390. stop_editing();
  391. ScrollableWidget::hide_event(event);
  392. }
  393. void AbstractView::keydown_event(KeyEvent& event)
  394. {
  395. if (event.key() == KeyCode::Key_F2) {
  396. if (is_editable() && edit_triggers() & EditTrigger::EditKeyPressed) {
  397. begin_editing(cursor_index());
  398. event.accept();
  399. return;
  400. }
  401. }
  402. if (event.key() == KeyCode::Key_Return) {
  403. activate_selected();
  404. event.accept();
  405. return;
  406. }
  407. SelectionUpdate selection_update = SelectionUpdate::Set;
  408. if (event.modifiers() == KeyModifier::Mod_Shift) {
  409. selection_update = SelectionUpdate::Shift;
  410. }
  411. if (event.key() == KeyCode::Key_Left) {
  412. move_cursor(CursorMovement::Left, selection_update);
  413. event.accept();
  414. return;
  415. }
  416. if (event.key() == KeyCode::Key_Right) {
  417. move_cursor(CursorMovement::Right, selection_update);
  418. event.accept();
  419. return;
  420. }
  421. if (event.key() == KeyCode::Key_Up) {
  422. move_cursor(CursorMovement::Up, selection_update);
  423. event.accept();
  424. return;
  425. }
  426. if (event.key() == KeyCode::Key_Down) {
  427. move_cursor(CursorMovement::Down, selection_update);
  428. event.accept();
  429. return;
  430. }
  431. if (event.key() == KeyCode::Key_Home) {
  432. move_cursor(CursorMovement::Home, selection_update);
  433. event.accept();
  434. return;
  435. }
  436. if (event.key() == KeyCode::Key_End) {
  437. move_cursor(CursorMovement::End, selection_update);
  438. event.accept();
  439. return;
  440. }
  441. if (event.key() == KeyCode::Key_PageUp) {
  442. move_cursor(CursorMovement::PageUp, selection_update);
  443. event.accept();
  444. return;
  445. }
  446. if (event.key() == KeyCode::Key_PageDown) {
  447. move_cursor(CursorMovement::PageDown, selection_update);
  448. event.accept();
  449. return;
  450. }
  451. if (is_searchable()) {
  452. if (event.key() == KeyCode::Key_Backspace) {
  453. if (is_searching()) {
  454. //if (event.modifiers() == Mod_Ctrl) {
  455. // TODO: delete last word
  456. //}
  457. Utf8View view(m_searching);
  458. size_t n_code_points = view.length();
  459. if (n_code_points > 1) {
  460. n_code_points--;
  461. StringBuilder sb;
  462. for (auto it = view.begin(); it != view.end(); ++it) {
  463. if (n_code_points == 0)
  464. break;
  465. n_code_points--;
  466. sb.append_code_point(*it);
  467. }
  468. do_search(sb.to_string());
  469. start_searching_timer();
  470. } else {
  471. cancel_searching();
  472. }
  473. event.accept();
  474. return;
  475. }
  476. } else if (event.key() == KeyCode::Key_Escape) {
  477. if (is_searching()) {
  478. cancel_searching();
  479. event.accept();
  480. return;
  481. }
  482. } else if (event.key() != KeyCode::Key_Tab && !event.ctrl() && !event.alt() && event.code_point() != 0) {
  483. StringBuilder sb;
  484. sb.append(m_searching);
  485. sb.append_code_point(event.code_point());
  486. do_search(sb.to_string());
  487. start_searching_timer();
  488. event.accept();
  489. return;
  490. }
  491. }
  492. ScrollableWidget::keydown_event(event);
  493. }
  494. void AbstractView::cancel_searching()
  495. {
  496. m_searching = nullptr;
  497. if (m_searching_timer)
  498. m_searching_timer->stop();
  499. if (m_highlighted_search_index.is_valid()) {
  500. m_highlighted_search_index = {};
  501. update();
  502. }
  503. }
  504. void AbstractView::start_searching_timer()
  505. {
  506. if (!m_searching_timer) {
  507. m_searching_timer = add<Core::Timer>();
  508. m_searching_timer->set_single_shot(true);
  509. m_searching_timer->on_timeout = [this] {
  510. cancel_searching();
  511. };
  512. }
  513. m_searching_timer->set_interval(5 * 1000);
  514. m_searching_timer->restart();
  515. }
  516. void AbstractView::do_search(String&& searching)
  517. {
  518. if (searching.is_empty() || !model()) {
  519. cancel_searching();
  520. return;
  521. }
  522. auto found_indexes = model()->matches(searching, Model::MatchesFlag::FirstMatchOnly | Model::MatchesFlag::MatchAtStart | Model::MatchesFlag::CaseInsensitive, model()->parent_index(cursor_index()));
  523. if (!found_indexes.is_empty() && found_indexes[0].is_valid()) {
  524. auto& index = found_indexes[0];
  525. m_highlighted_search_index = index;
  526. m_searching = move(searching);
  527. set_selection(index);
  528. scroll_into_view(index);
  529. update();
  530. }
  531. }
  532. bool AbstractView::is_searchable() const
  533. {
  534. if (!m_searchable || !model())
  535. return false;
  536. return model()->is_searchable();
  537. }
  538. void AbstractView::set_searchable(bool searchable)
  539. {
  540. if (m_searchable == searchable)
  541. return;
  542. m_searchable = searchable;
  543. if (!m_searchable)
  544. cancel_searching();
  545. }
  546. bool AbstractView::is_highlighting_searching(const ModelIndex& index) const
  547. {
  548. return index == m_highlighted_search_index;
  549. }
  550. void AbstractView::draw_item_text(Gfx::Painter& painter, const ModelIndex& index, bool is_selected, const Gfx::IntRect& text_rect, const StringView& item_text, const Gfx::Font& font, Gfx::TextAlignment alignment, Gfx::TextElision elision)
  551. {
  552. Color text_color;
  553. if (is_selected)
  554. text_color = is_focused() ? palette().selection_text() : palette().inactive_selection_text();
  555. else
  556. text_color = index.data(ModelRole::ForegroundColor).to_color(palette().color(foreground_role()));
  557. if (is_highlighting_searching(index)) {
  558. Utf8View searching_text(searching());
  559. auto searching_length = searching_text.length();
  560. // Highlight the text background first
  561. painter.draw_text([&](const Gfx::IntRect& rect, u32) {
  562. if (searching_length > 0) {
  563. searching_length--;
  564. painter.fill_rect(rect.inflated(0, 2), palette().highlight_searching());
  565. }
  566. },
  567. text_rect, item_text, font, alignment, elision);
  568. // Then draw the text
  569. auto highlight_text_color = palette().highlight_searching_text();
  570. searching_length = searching_text.length();
  571. painter.draw_text([&](const Gfx::IntRect& rect, u32 code_point) {
  572. if (searching_length > 0) {
  573. searching_length--;
  574. painter.draw_glyph_or_emoji(rect.location(), code_point, font, highlight_text_color);
  575. } else {
  576. painter.draw_glyph_or_emoji(rect.location(), code_point, font, text_color);
  577. }
  578. },
  579. text_rect, item_text, font, alignment, elision);
  580. } else {
  581. painter.draw_text(text_rect, item_text, font, alignment, text_color, elision);
  582. }
  583. }
  584. }