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 19Notifier::Notifier() 20 : fListeners(2), 21 fSuspended(0), 22 fPendingNotifications(false) 23{ 24} 25 26// destructor 27Notifier::~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 40bool 41Notifier::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 50bool 51Notifier::RemoveListener(Listener* listener) 52{ 53 return fListeners.RemoveItem((void*)listener); 54} 55 56// CountListeners 57int32 58Notifier::CountListeners() const 59{ 60 return fListeners.CountItems(); 61} 62 63// ListenerAtFast 64Listener* 65Notifier::ListenerAtFast(int32 index) const 66{ 67 return (Listener*)fListeners.ItemAtFast(index); 68} 69 70// #pragma mark - 71 72// Notify 73void 74Notifier::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 88void 89Notifier::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