The Battle for Wesnoth  1.19.0-dev
generic_event.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2006 - 2024
3  by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de>
4  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY.
12 
13  See the COPYING file for more details.
14 */
15 
16 #include "generic_event.hpp"
17 
18 #include <algorithm>
19 
20 namespace events{
21 
22 generic_event::generic_event(const std::string& name) :
23  name_(name),
24  observers_(),
25  change_handler_(false),
26  notify_active_(false)
27 {
28 }
29 
31  bool handler_attached = false;
32 
33  //make sure observers are not notified right now
34  if (!notify_active_){
35  change_handler_ = true;
36  try{
37  std::vector<observer*>::const_iterator it = std::find(observers_.begin(), observers_.end(), obs);
38  if (it != observers_.end()){
39  handler_attached = false;
40  }
41  else{
42  observers_.push_back(obs);
43  handler_attached = true;
44  }
45  }
46  catch (...){
47  change_handler_ = false;
48  throw;
49  }
50  change_handler_ = false;
51  }
52 
53  return handler_attached;
54 }
55 
57  bool handler_detached = false;
58 
59  //make sure observers are not notified right now
60  if (!notify_active_){
61  auto it = std::find(observers_.begin(), observers_.end(), obs);
62  if (it == observers_.end()){
63  handler_detached = false;
64  }
65  else{
66  observers_.erase(it);
67  handler_detached = true;
68  }
69  change_handler_ = false;
70  }
71 
72  return handler_detached;
73 }
74 
76  if (!change_handler_){
77  notify_active_ = true;
78  try{
79  for (std::vector<observer*>::const_iterator it = observers_.begin();
80  it != observers_.end(); ++it){
81  (*it)->handle_generic_event(name_);
82  }
83  }
84  catch (...){
85  //reset the flag if event handlers throw exceptions and don't catch them
86  notify_active_ = false;
87  throw;
88  }
89  notify_active_ = false;
90  }
91 }
92 
93 } //namespace events
generic_event(const std::string &name)
std::vector< observer * > observers_
virtual bool attach_handler(observer *obs)
virtual bool detach_handler(observer *obs)
virtual void notify_observers()
Handling of system events.