1// Copyright 2014 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#ifndef ANDROID_WEBVIEW_BROWSER_DEFERRED_GPU_COMMAND_SERVICE_H_
6#define ANDROID_WEBVIEW_BROWSER_DEFERRED_GPU_COMMAND_SERVICE_H_
7
8#include <queue>
9#include <utility>
10
11#include "base/lazy_instance.h"
12#include "base/memory/ref_counted.h"
13#include "base/threading/thread_local.h"
14#include "base/time/time.h"
15#include "gpu/command_buffer/service/in_process_command_buffer.h"
16
17namespace android_webview {
18
19class ScopedAllowGL {
20 public:
21  ScopedAllowGL();
22  ~ScopedAllowGL();
23
24  static bool IsAllowed();
25
26 private:
27  static base::LazyInstance<base::ThreadLocalBoolean> allow_gl;
28
29  DISALLOW_COPY_AND_ASSIGN(ScopedAllowGL);
30};
31
32class DeferredGpuCommandService
33    : public gpu::InProcessCommandBuffer::Service,
34      public base::RefCountedThreadSafe<DeferredGpuCommandService> {
35 public:
36  static void SetInstance();
37  static DeferredGpuCommandService* GetInstance();
38
39  virtual void ScheduleTask(const base::Closure& task) OVERRIDE;
40  virtual void ScheduleIdleWork(const base::Closure& task) OVERRIDE;
41  virtual bool UseVirtualizedGLContexts() OVERRIDE;
42  virtual scoped_refptr<gpu::gles2::ShaderTranslatorCache>
43      shader_translator_cache() OVERRIDE;
44
45  void RunTasks();
46  // If |is_idle| is false, this will only run older idle tasks.
47  void PerformIdleWork(bool is_idle);
48  // Flush the idle queue until it is empty. This is different from
49  // PerformIdleWork(is_idle = true), which does not run any newly scheduled
50  // idle tasks during the idle run.
51  void PerformAllIdleWork();
52
53  virtual void AddRef() const OVERRIDE;
54  virtual void Release() const OVERRIDE;
55
56 protected:
57  virtual ~DeferredGpuCommandService();
58  friend class base::RefCountedThreadSafe<DeferredGpuCommandService>;
59
60 private:
61  friend class ScopedAllowGL;
62  static void RequestProcessGL();
63
64  DeferredGpuCommandService();
65  size_t IdleQueueSize();
66
67  base::Lock tasks_lock_;
68  std::queue<base::Closure> tasks_;
69  std::queue<std::pair<base::Time, base::Closure> > idle_tasks_;
70
71  scoped_refptr<gpu::gles2::ShaderTranslatorCache> shader_translator_cache_;
72  DISALLOW_COPY_AND_ASSIGN(DeferredGpuCommandService);
73};
74
75}  // namespace android_webview
76
77#endif  // ANDROID_WEBVIEW_BROWSER_DEFERRED_GPU_COMMAND_SERVICE_H_
78