Initialize Tizen 2.3
[framework/web/wrt-commons.git] / modules / event / include / dpl / event / inter_context_delegate.h
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /*
17  * @file        inter_context_delegate.h
18  * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
19  * @version     1.0
20  * @brief       This file is the header file of inter context delegate
21  */
22
23 #ifndef DPL_INTER_CONTEXT_DELEGATE_H_
24 #define DPL_INTER_CONTEXT_DELEGATE_H_
25
26 #ifndef __GXX_EXPERIMENTAL_CXX0X__ // C++11 compatibility check
27 # include <bits/c++0x_warning.h>
28 #else
29
30 #include <functional>
31 #include <list>
32 #include <memory>
33 #include <mutex>
34 #include <tuple>
35
36 #include <dpl/event/event_support.h>
37 #include <dpl/event/thread_event_dispatcher.h>
38 #include <dpl/event/main_event_dispatcher.h>
39 #include <dpl/generic_event.h>
40 #include <dpl/foreach.h>
41 #include <dpl/noncopyable.h>
42 #include <dpl/log/wrt_log.h>
43 #include <dpl/assert.h>
44 #include <dpl/apply.h>
45 #include <dpl/bind.h>
46
47 /*
48  * - Created ICDelegate can be passed freely to other threads.
49  * - ICDelegate can be called just once. All following calls will be
50  *   silently ignored.
51  * - When ICDelegateSupport is destroyed, all its ICDelegates
52  *   are invalidated and safetly removed.
53  * - ICDelegate can be invalidated by call to disable method on it.
54  * - To use ICDelegate you have to do two steps:
55  *
56  * 1. Class that will be used to create delegate have to derive from templated
57  *    class ICDelegateSupport<T>
58  *
59  * 2. Create instance of ICDelegate by calling
60  *    makeICDelegate and passing to it pointer to method
61  *
62  *    class A : ICDelegateSupport<A>
63  *    {
64  *    void methodA(int) {}
65  *    void createDelegate() {
66  *        ICDelegate<int> dlg;
67  *        dlg = makeICDelegate(&A::MethodA);
68  *    };
69  */
70
71 namespace DPL {
72 namespace Event {
73 //forward declaration
74 template <typename ... ArgTypesList>
75 class ICDelegate;
76
77 namespace ICD {
78 // This Type defines whether ICDelegate should be destroyed after the call, or
79 // could be reused later.
80 enum class Reuse
81 {
82     Yes, No
83 };
84 }
85
86 namespace ICDPrivate {
87 // Base for all ICDSharedDatas. Needed for auto disabling and deleting of
88 // ICDSharedDatas.
89 // If ICDSharedData is disabled, delegate won't be called anymore.
90 class ICDSharedDataBase
91 {
92   public:
93     typedef std::shared_ptr<ICDSharedDataBase> ICDSharedDataBasePtr;
94     typedef std::list<ICDSharedDataBasePtr> ICDSharedDataBaseList;
95
96     class ScopedLock : DPL::Noncopyable
97     {
98       public:
99         explicit ScopedLock(ICDSharedDataBasePtr helperBase) :
100             m_scopedLock(helperBase->m_mutex)
101         {}
102
103       private:
104         std::lock_guard<std::recursive_mutex> m_scopedLock;
105     };
106
107     ICDSharedDataBase() : m_disabled(false)
108     {}
109     virtual ~ICDSharedDataBase()
110     {}
111
112     bool isDisabled() const
113     {
114         return m_disabled;
115     }
116     virtual void disable()
117     {
118         m_disabled = true;
119     }
120
121     void setIterator(ICDSharedDataBaseList::iterator pos)
122     {
123         m_position = pos;
124     }
125
126     ICDSharedDataBaseList::iterator getIterator() const
127     {
128         return m_position;
129     }
130
131   private:
132     bool m_disabled;
133     std::recursive_mutex m_mutex;
134     ICDSharedDataBaseList::iterator m_position;
135 };
136
137 // Pure Event to remove ICDSharedData.
138 class DeleteICDSharedDataBaseEventCall : public DPL::Event::AbstractEventCall
139 {
140   public:
141     DeleteICDSharedDataBaseEventCall(
142         ICDSharedDataBase::ICDSharedDataBasePtr helperBase) :
143         m_helperBase(helperBase)
144     {}
145     virtual void Call()
146     {
147         m_helperBase.reset();
148     }
149
150   private:
151     ICDSharedDataBase::ICDSharedDataBasePtr m_helperBase;
152 };
153
154 class ICDelegateSupportInterface
155 {
156   protected:
157     virtual ~ICDelegateSupportInterface()
158     {}
159     virtual void unregisterICDSharedData(
160         ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) = 0;
161     virtual void registerICDSharedData(
162         ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) = 0;
163
164   private:
165     template <typename ... ArgTypesList>
166     friend class DPL::Event::ICDelegate;
167 };
168 } //ICDPrivate
169
170 template<typename ThisType, typename ... ArgTypesList>
171 std::function<void (ArgTypesList ...)>
172 makeDelegate(ThisType* This,
173              void (ThisType::*Func)(ArgTypesList ...))
174 {
175     return DPL::Bind(Func, This);
176 }
177
178 // ICDelegate class represents delegate that can be called from
179 // any context (thread). The actual calling context (thread) is allways the same
180 // as the context in which it was created.
181 template <typename ... ArgTypesList>
182 class ICDelegate
183 {
184   public:
185     ICDelegate()
186     {}
187     ICDelegate(ICDPrivate::ICDelegateSupportInterface* base,
188                std::function<void (ArgTypesList ...)> outerDelegate,
189                ICD::Reuse reuse)
190     {
191         ICDSharedData* hlp = new ICDSharedData(base, outerDelegate, reuse);
192         m_helper.reset(hlp);
193     }
194
195     // Calling operator will pass all args passed to it to correct context and
196     // will call apropriate method that was registered with.
197     void operator()(ArgTypesList ... args)
198     {
199         Assert(m_helper);
200         ICDPrivate::ICDSharedDataBase::ScopedLock lock(
201             std::static_pointer_cast<ICDPrivate::ICDSharedDataBase>(m_helper));
202         m_helper->CallDelegate(args ...);
203     }
204
205     //Disable delegate (it won't be called anymore)
206     void disable()
207     {
208         Assert(m_helper);
209         ICDPrivate::ICDSharedDataBase::ScopedLock lock(
210             std::static_pointer_cast<ICDPrivate::ICDSharedDataBase>(m_helper));
211         m_helper->disable();
212     }
213
214   protected:
215     ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr
216     getRelatedICDSharedData() const
217     {
218         return std::static_pointer_cast<ICDPrivate::ICDSharedDataBase>(m_helper);
219     }
220
221   private:
222     template<typename ThisType>
223     friend class ICDelegateSupport;
224     class ICDSharedData;
225     typedef std::shared_ptr<ICDSharedData> ICDSharedDataPtr;
226
227     struct PrivateEvent
228     {
229         PrivateEvent(ICDSharedDataPtr a_helper,
230                      ArgTypesList ... arguments) :
231             helper(a_helper),
232             args(std::make_tuple(arguments ...))
233         {}
234
235         ICDSharedDataPtr helper;
236         std::tuple<ArgTypesList ...> args;
237     };
238
239     typedef std::function<void (const PrivateEvent&)>
240     ICDSharedDataDelegateType;
241     class ICDSharedData : private DPL::Event::EventSupport<PrivateEvent>,
242         public std::enable_shared_from_this<ICDSharedData>,
243         public ICDPrivate::ICDSharedDataBase
244     {
245       public:
246         ICDSharedData(
247             ICDPrivate::ICDelegateSupportInterface *base,
248             std::function<void (ArgTypesList ...)> outerDelegate,
249             ICD::Reuse reuse) :
250             m_base(base),
251             m_outerDelegate(outerDelegate),
252             m_reuse(reuse)
253         {
254             Assert(m_base);
255             // lock is not needed: this object is not shared at that moment
256             m_subDelegate =
257                 DPL::Event::makeDelegate(this,
258                                          &ICDSharedData::delegateForwarder);
259             EventSupport<PrivateEvent>::AddListener(m_subDelegate);
260         }
261
262         void CallDelegate(ArgTypesList ... args)
263         {
264             ICDPrivate::ICDSharedDataBase::ScopedLock lock(
265                 std::static_pointer_cast<ICDPrivate::ICDSharedDataBase>(
266                     this->shared_from_this()));
267             if (!isDisabled()) {
268                 EmitEvent(PrivateEvent(this->shared_from_this(),
269                                        args ...));
270             }
271         }
272
273         virtual void disable()
274         {
275             ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr ptr(
276                 std::static_pointer_cast<ICDSharedDataBase>(
277                     this->shared_from_this()));
278             ICDPrivate::ICDSharedDataBase::ScopedLock lock(ptr);
279             if (!isDisabled()) {
280                 ICDPrivate::ICDSharedDataBase::disable();
281                 EventSupport<PrivateEvent>::RemoveListener(m_subDelegate);
282                 m_base->unregisterICDSharedData(ptr);
283             }
284         }
285
286       private:
287         friend class std::shared_ptr<ICDSharedData>;
288         ICDSharedDataDelegateType m_subDelegate;
289         ICDPrivate::ICDelegateSupportInterface* m_base;
290         std::function<void (ArgTypesList ...)> m_outerDelegate;
291         ICD::Reuse m_reuse;
292
293         void delegateForwarder(const PrivateEvent& event)
294         {
295             ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr ptr(
296                 std::static_pointer_cast<ICDSharedDataBase>(event.helper));
297             ICDPrivate::ICDSharedDataBase::ScopedLock lock(ptr);
298
299             Assert(m_outerDelegate);
300             if (ptr->isDisabled()) {
301                 WrtLogD("ICDSharedData has been disabled - call is ignored");
302             } else {
303                 DPL::Apply(m_outerDelegate, event.args);
304
305                 if (m_reuse == ICD::Reuse::Yes) {
306                     return;
307                 }
308
309                 disable();
310                 deleteICDSharedDataBase(ptr);
311             }
312         }
313     };
314
315     // Schedules helper removal.
316     static void deleteICDSharedDataBase(
317         ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper)
318     {
319         using namespace ICDPrivate;
320         ICDSharedDataBase::ScopedLock lock(helper);
321         DeleteICDSharedDataBaseEventCall* event =
322             new DeleteICDSharedDataBaseEventCall(helper);
323         if (DPL::Thread::GetCurrentThread() == NULL) {
324             DPL::Event::GetMainEventDispatcherInstance().AddEventCall(event);
325         } else {
326             DPL::Event::ThreadEventDispatcher dispatcher;
327             dispatcher.SetThread(DPL::Thread::GetCurrentThread());
328             dispatcher.AddEventCall(event);
329         }
330     }
331
332     ICDSharedDataPtr m_helper;
333 };
334
335 template <typename ThisType>
336 class ICDelegateSupport : public ICDPrivate::ICDelegateSupportInterface
337 {
338   protected:
339     template<typename ... ArgTypesList>
340     ICDelegate<ArgTypesList ...> makeICDelegate(
341         void (ThisType::*Func)(ArgTypesList ...),
342         ICD::Reuse reuse = ICD::Reuse::No)
343     {
344         ThisType* This = static_cast<ThisType*>(this);
345         ICDelegate<ArgTypesList ...> icdelegate(
346             This,
347             makeDelegate(This, Func),
348             reuse);
349         this->registerICDSharedData(icdelegate.getRelatedICDSharedData());
350         return icdelegate;
351     }
352
353     ICDelegateSupport()
354     {}
355
356     ~ICDelegateSupport()
357     {
358         ICDPrivate::ICDSharedDataBase::ICDSharedDataBaseList list =
359             m_ICDSharedDatas;
360         FOREACH(helper, list) {
361             ICDPrivate::ICDSharedDataBase::ScopedLock lock(
362                 std::static_pointer_cast<ICDPrivate::ICDSharedDataBase>(*helper));
363             (*helper)->disable();
364         }
365         m_ICDSharedDatas.clear();
366     }
367
368   private:
369     virtual void unregisterICDSharedData(
370         ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper)
371     {
372         m_ICDSharedDatas.erase(helper->getIterator());
373     }
374
375     virtual void registerICDSharedData(
376         ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper)
377     {
378         helper->setIterator(
379             m_ICDSharedDatas.insert(m_ICDSharedDatas.begin(),
380                                     helper));
381     }
382
383   private:
384     ICDPrivate::ICDSharedDataBase::ICDSharedDataBaseList m_ICDSharedDatas;
385 };
386 }
387 } //namespace
388
389 #endif // __GXX_EXPERIMENTAL_CXX0X__
390
391 #endif //DPL_INTER_CONTEXT_DELEGATE_H_