guard.rs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::sync::{
  19. atomic::{AtomicU32, Ordering},
  20. Arc,
  21. };
  22. use super::{ModifyAction, PropertyPtr, Role};
  23. static BATCH_ID: AtomicU32 = AtomicU32::new(0);
  24. /// This schedules all property updates to happen at the end of the scope.
  25. /// We can therefore have fine-grained control about when property updates are
  26. /// propagated to the rest of the scenegraph.
  27. ///
  28. /// This way we avoid triggering draw updates mid draw, and changes are atomic.
  29. /// For example resizing the content view, will trigger the editbox background to
  30. /// redraw while a current window wide draw is in progress. Since the window draw
  31. /// triggered the change when we submit the draw update, it will be discarded by
  32. /// the editbox bg triggered update. However this update won't have the current
  33. /// rect and will be stale.
  34. ///
  35. /// 1. Content draw starts
  36. /// 2. Dependent property triggers and submits editbox bg redraw.
  37. /// 3. Content draw continues and now draws editbox bg with updated rect.
  38. /// 4. Finished content draw's editbox bg update is discarded in favour of #2.
  39. /// However #2 used the pre-updated rect and is now stale.
  40. ///
  41. /// We solve the above issue by batching all updates until after the draw call is finished.
  42. /// This also has the unintended side-effect of making draws much faster since they aren't
  43. /// interrupted halfway through by extra compute.
  44. pub struct PropertyAtomicGuard {
  45. pub batch_id: BatchGuardId,
  46. updates: Vec<(PropertyPtr, Role, ModifyAction)>,
  47. end_batch: Option<BatchGuardCb>,
  48. parent: Option<BatchGuardPtr>,
  49. }
  50. impl PropertyAtomicGuard {
  51. pub fn new(start_batch: BatchGuardCb, end_batch: BatchGuardCb) -> Self {
  52. let batch_id = BATCH_ID.fetch_add(1, Ordering::Relaxed);
  53. start_batch(batch_id);
  54. Self { batch_id, updates: vec![], end_batch: Some(end_batch), parent: None }
  55. }
  56. /// Should only be used when there's an explicit end_batch() called manually at the end
  57. /// of the context.
  58. /// You probably mostly want to either `batch.spawn()` from an existing batch
  59. /// or use `render_api.make_guard()`.
  60. pub fn none() -> Self {
  61. Self::new(Box::new(|_| {}), Box::new(|_| {}))
  62. }
  63. pub(super) fn add(&mut self, prop: PropertyPtr, role: Role, action: ModifyAction) {
  64. self.updates.push((prop, role, action));
  65. }
  66. }
  67. impl Drop for PropertyAtomicGuard {
  68. fn drop(&mut self) {
  69. let guard = Arc::new(BatchGuard {
  70. id: self.batch_id,
  71. end_batch: self.end_batch.take(),
  72. _parent: self.parent.take(),
  73. });
  74. for (prop, role, action) in std::mem::take(&mut self.updates) {
  75. prop.on_modify.notify((role, action, guard.clone()));
  76. }
  77. }
  78. }
  79. impl std::fmt::Debug for PropertyAtomicGuard {
  80. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  81. write!(f, "@{:?}", self.batch_id)
  82. }
  83. }
  84. pub type BatchGuardId = u32;
  85. type BatchGuardCb = Box<dyn FnOnce(BatchGuardId) + Send + Sync>;
  86. pub type BatchGuardPtr = Arc<BatchGuard>;
  87. pub struct BatchGuard {
  88. pub id: BatchGuardId,
  89. end_batch: Option<BatchGuardCb>,
  90. _parent: Option<BatchGuardPtr>,
  91. }
  92. impl BatchGuard {
  93. pub fn spawn(self: &Arc<Self>) -> PropertyAtomicGuard {
  94. PropertyAtomicGuard {
  95. batch_id: self.id,
  96. updates: vec![],
  97. end_batch: Some(Box::new(|_| {})),
  98. parent: Some(self.clone()),
  99. }
  100. }
  101. }
  102. impl Drop for BatchGuard {
  103. fn drop(&mut self) {
  104. let end_batch = self.end_batch.take().unwrap();
  105. end_batch(self.id);
  106. }
  107. }
  108. impl std::fmt::Debug for BatchGuard {
  109. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  110. f.debug_struct("BatchGuard").field("id", &self.id).finish()
  111. }
  112. }