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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use std::cell::Cell;

use canvas_traits::webgl::WebGLError::*;
use canvas_traits::webgl::{webgl_channel, WebGLCommand, WebGLQueryId};
use dom_struct::dom_struct;

use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as constants;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::DomRoot;
use crate::dom::webglobject::WebGLObject;
use crate::dom::webglrenderingcontext::{Operation, WebGLRenderingContext};
use crate::task_source::TaskSource;

#[dom_struct]
pub struct WebGLQuery {
    webgl_object: WebGLObject,
    #[no_trace]
    gl_id: WebGLQueryId,
    gl_target: Cell<Option<u32>>,
    marked_for_deletion: Cell<bool>,
    query_result_available: Cell<Option<u32>>,
    query_result: Cell<u32>,
}

impl WebGLQuery {
    fn new_inherited(context: &WebGLRenderingContext, id: WebGLQueryId) -> Self {
        Self {
            webgl_object: WebGLObject::new_inherited(context),
            gl_id: id,
            gl_target: Cell::new(None),
            marked_for_deletion: Cell::new(false),
            query_result_available: Cell::new(None),
            query_result: Cell::new(0),
        }
    }

    pub fn new(context: &WebGLRenderingContext) -> DomRoot<Self> {
        let (sender, receiver) = webgl_channel().unwrap();
        context.send_command(WebGLCommand::GenerateQuery(sender));
        let id = receiver.recv().unwrap();

        reflect_dom_object(
            Box::new(Self::new_inherited(context, id)),
            &*context.global(),
        )
    }

    pub fn begin(
        &self,
        context: &WebGLRenderingContext,
        target: u32,
    ) -> Result<(), canvas_traits::webgl::WebGLError> {
        if self.marked_for_deletion.get() {
            return Err(InvalidOperation);
        }
        if let Some(current_target) = self.gl_target.get() {
            if current_target != target {
                return Err(InvalidOperation);
            }
        }
        match target {
            constants::ANY_SAMPLES_PASSED |
            constants::ANY_SAMPLES_PASSED_CONSERVATIVE |
            constants::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN => (),
            _ => return Err(InvalidEnum),
        }
        self.gl_target.set(Some(target));

        context.send_command(WebGLCommand::BeginQuery(target, self.gl_id));
        Ok(())
    }

    pub fn end(
        &self,
        context: &WebGLRenderingContext,
        target: u32,
    ) -> Result<(), canvas_traits::webgl::WebGLError> {
        if self.marked_for_deletion.get() {
            return Err(InvalidOperation);
        }
        if let Some(current_target) = self.gl_target.get() {
            if current_target != target {
                return Err(InvalidOperation);
            }
        }
        match target {
            constants::ANY_SAMPLES_PASSED |
            constants::ANY_SAMPLES_PASSED_CONSERVATIVE |
            constants::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN => (),
            _ => return Err(InvalidEnum),
        }
        context.send_command(WebGLCommand::EndQuery(target));
        Ok(())
    }

    pub fn delete(&self, operation_fallibility: Operation) {
        if !self.marked_for_deletion.get() {
            self.marked_for_deletion.set(true);

            let context = self.upcast::<WebGLObject>().context();
            let command = WebGLCommand::DeleteQuery(self.gl_id);
            match operation_fallibility {
                Operation::Fallible => context.send_command_ignored(command),
                Operation::Infallible => context.send_command(command),
            }
        }
    }

    pub fn is_valid(&self) -> bool {
        !self.marked_for_deletion.get() && self.target().is_some()
    }

    pub fn target(&self) -> Option<u32> {
        self.gl_target.get()
    }

    fn update_results(&self, context: &WebGLRenderingContext) {
        let (sender, receiver) = webgl_channel().unwrap();
        context.send_command(WebGLCommand::GetQueryState(
            sender,
            self.gl_id,
            constants::QUERY_RESULT_AVAILABLE,
        ));
        let is_available = receiver.recv().unwrap();
        if is_available == 0 {
            self.query_result_available.set(None);
            return;
        }

        let (sender, receiver) = webgl_channel().unwrap();
        context.send_command(WebGLCommand::GetQueryState(
            sender,
            self.gl_id,
            constants::QUERY_RESULT,
        ));

        self.query_result.set(receiver.recv().unwrap());
        self.query_result_available.set(Some(is_available));
    }

    #[rustfmt::skip]
    pub fn get_parameter(
        &self,
        context: &WebGLRenderingContext,
        pname: u32,
    ) -> Result<u32, canvas_traits::webgl::WebGLError> {
        if !self.is_valid() {
            return Err(InvalidOperation);
        }
        match pname {
            constants::QUERY_RESULT |
            constants::QUERY_RESULT_AVAILABLE => {},
            _ => return Err(InvalidEnum),
        }

        if self.query_result_available.get().is_none() {
            self.query_result_available.set(Some(0));

            let this = Trusted::new(self);
            let context = Trusted::new(context);
            let task = task!(request_query_state: move || {
                let this = this.root();
                let context = context.root();
                this.update_results(&context);
            });

            let global = self.global();
            global
                .as_window()
                .task_manager()
                .dom_manipulation_task_source()
                .queue(task, global.upcast())
                .unwrap();
        }

        match pname {
            constants::QUERY_RESULT => Ok(self.query_result.get()),
            constants::QUERY_RESULT_AVAILABLE => Ok(self.query_result_available.get().unwrap()),
            _ => unreachable!(),
        }
    }
}

impl Drop for WebGLQuery {
    fn drop(&mut self) {
        self.delete(Operation::Fallible);
    }
}