1 /* 2 * Copyright 2006-2007, Haiku. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Stephan Aßmus <superstippi@gmx.de> 7 */ 8 9 #include "Notifier.h" 10 11 #include <stdio.h> 12 #include <typeinfo> 13 14 #include <OS.h> 15 16 #include "Listener.h" 17 18 // constructor 19 Notifier::Notifier() 20 : fListeners(2), 21 fSuspended(0), 22 fPendingNotifications(false) 23 { 24 } 25 26 // destructor 27 Notifier::~Notifier() 28 { 29 if (fListeners.CountItems() > 0) { 30 char message[256]; 31 Listener* o = (Listener*)fListeners.ItemAt(0); 32 sprintf(message, "Notifier::~Notifier() - %" B_PRId32 33 " listeners still watching, first: %s\n", 34 fListeners.CountItems(), typeid(*o).name()); 35 debugger(message); 36 } 37 } 38 39 // AddListener 40 bool 41 Notifier::AddListener(Listener* listener) 42 { 43 if (listener && !fListeners.HasItem((void*)listener)) { 44 return fListeners.AddItem((void*)listener); 45 } 46 return false; 47 } 48 49 // RemoveListener 50 bool 51 Notifier::RemoveListener(Listener* listener) 52 { 53 return fListeners.RemoveItem((void*)listener); 54 } 55 56 // CountListeners 57 int32 58 Notifier::CountListeners() const 59 { 60 return fListeners.CountItems(); 61 } 62 63 // ListenerAtFast 64 Listener* 65 Notifier::ListenerAtFast(int32 index) const 66 { 67 return (Listener*)fListeners.ItemAtFast(index); 68 } 69 70 // #pragma mark - 71 72 // Notify 73 void 74 Notifier::Notify() const 75 { 76 if (!fSuspended) { 77 BList observers(fListeners); 78 int32 count = observers.CountItems(); 79 for (int32 i = 0; i < count; i++) 80 ((Listener*)observers.ItemAtFast(i))->ObjectChanged(this); 81 fPendingNotifications = false; 82 } else { 83 fPendingNotifications = true; 84 } 85 } 86 87 // SuspendNotifications 88 void 89 Notifier::SuspendNotifications(bool suspend) 90 { 91 if (suspend) 92 fSuspended++; 93 else 94 fSuspended--; 95 96 if (fSuspended < 0) { 97 fprintf(stderr, "Notifier::SuspendNotifications(false) - " 98 "error: suspend level below zero!\n"); 99 fSuspended = 0; 100 } 101 102 if (!fSuspended && fPendingNotifications) 103 Notify(); 104 } 105 106