1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "ui/events/event_source.h"
6
7#include <algorithm>
8
9#include "ui/events/event_processor.h"
10#include "ui/events/event_rewriter.h"
11
12namespace ui {
13
14EventSource::EventSource() {}
15
16EventSource::~EventSource() {}
17
18void EventSource::AddEventRewriter(EventRewriter* rewriter) {
19  DCHECK(rewriter);
20  DCHECK(rewriter_list_.end() ==
21         std::find(rewriter_list_.begin(), rewriter_list_.end(), rewriter));
22  rewriter_list_.push_back(rewriter);
23}
24
25void EventSource::RemoveEventRewriter(EventRewriter* rewriter) {
26  EventRewriterList::iterator find =
27      std::find(rewriter_list_.begin(), rewriter_list_.end(), rewriter);
28  if (find != rewriter_list_.end())
29    rewriter_list_.erase(find);
30}
31
32EventDispatchDetails EventSource::SendEventToProcessor(Event* event) {
33  scoped_ptr<Event> rewritten_event;
34  EventRewriteStatus status = EVENT_REWRITE_CONTINUE;
35  EventRewriterList::const_iterator it = rewriter_list_.begin(),
36                                    end = rewriter_list_.end();
37  for (; it != end; ++it) {
38    status = (*it)->RewriteEvent(*event, &rewritten_event);
39    if (status == EVENT_REWRITE_DISCARD) {
40      CHECK(!rewritten_event);
41      return EventDispatchDetails();
42    }
43    if (status == EVENT_REWRITE_CONTINUE) {
44      CHECK(!rewritten_event);
45      continue;
46    }
47    break;
48  }
49  CHECK((it == end && !rewritten_event) || rewritten_event);
50  EventDispatchDetails details =
51      DeliverEventToProcessor(rewritten_event ? rewritten_event.get() : event);
52  if (details.dispatcher_destroyed)
53    return details;
54
55  while (status == EVENT_REWRITE_DISPATCH_ANOTHER) {
56    scoped_ptr<Event> new_event;
57    status = (*it)->NextDispatchEvent(*rewritten_event, &new_event);
58    if (status == EVENT_REWRITE_DISCARD)
59      return EventDispatchDetails();
60    CHECK_NE(EVENT_REWRITE_CONTINUE, status);
61    CHECK(new_event);
62    details = DeliverEventToProcessor(new_event.get());
63    if (details.dispatcher_destroyed)
64      return details;
65    rewritten_event.reset(new_event.release());
66  }
67  return EventDispatchDetails();
68}
69
70EventDispatchDetails EventSource::DeliverEventToProcessor(Event* event) {
71  EventProcessor* processor = GetEventProcessor();
72  CHECK(processor);
73  return processor->OnEventFromSource(event);
74}
75
76}  // namespace ui
77