summaryrefslogtreecommitdiff
path: root/testing/embedder_test_timer_handling_delegate.h
blob: 0137aae45f978eb8b6e87e39978ce26c14cc2e60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright 2015 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef TESTING_EMBEDDER_TEST_TIMER_HANDLING_DELEGATE_H_
#define TESTING_EMBEDDER_TEST_TIMER_HANDLING_DELEGATE_H_

#include <map>
#include <utility>
#include <vector>

#include "embedder_test.h"

class EmbedderTestTimerHandlingDelegate : public EmbedderTest::Delegate {
 public:
  struct ReceivedAlert {
    ReceivedAlert(FPDF_WIDESTRING message_in,
                  FPDF_WIDESTRING title_in,
                  int type_in,
                  int icon_in)
        : message(message_in), title(title_in), type(type_in), icon(icon_in) {}

    FPDF_WIDESTRING message;
    FPDF_WIDESTRING title;
    int type;
    int icon;
  };

  int Alert(FPDF_WIDESTRING message,
            FPDF_WIDESTRING title,
            int type,
            int icon) override {
    alerts_.push_back(ReceivedAlert(message, title, type, icon));
    return 0;
  }

  int SetTimer(int msecs, TimerCallback fn) override {
    expiry_to_timer_map_.insert(std::pair<int, Timer>(
        msecs + imaginary_elapsed_msecs_, Timer(++next_timer_id_, fn)));
    return next_timer_id_;
  }

  void KillTimer(int id) override {
    for (auto iter = expiry_to_timer_map_.begin();
         iter != expiry_to_timer_map_.end(); ++iter) {
      if (iter->second.first == id) {
        expiry_to_timer_map_.erase(iter);
        break;
      }
    }
  }

  void AdvanceTime(int increment_msecs) {
    imaginary_elapsed_msecs_ += increment_msecs;
    while (1) {
      auto iter = expiry_to_timer_map_.begin();
      if (iter == expiry_to_timer_map_.end()) {
        break;
      }
      Timer t = iter->second;
      if (t.first > imaginary_elapsed_msecs_) {
        break;
      }
      expiry_to_timer_map_.erase(iter);
      t.second(t.first);  // Fire timer.
    }
  }

  const std::vector<ReceivedAlert>& GetAlerts() const { return alerts_; }

 protected:
  using Timer = std::pair<int, TimerCallback>;     // ID, callback pair.
  std::multimap<int, Timer> expiry_to_timer_map_;  // Keyed by timeout.
  int next_timer_id_ = 0;
  int imaginary_elapsed_msecs_ = 0;
  std::vector<ReceivedAlert> alerts_;
};

#endif  // TESTING_EMBEDDER_TEST_TIMER_HANDLING_DELEGATE_H_