/
run.rs
executable file
·437 lines (375 loc) · 18.7 KB
/
run.rs
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/* 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 http://mozilla.org/MPL/2.0/. */
use platform::{Application, Window};
use windowing::{ApplicationMethods, WindowEvent, WindowMethods};
use windowing::{IdleWindowEvent, ResizeWindowEvent, LoadUrlWindowEvent, MouseWindowEventClass};
use windowing::{ScrollWindowEvent, ZoomWindowEvent, NavigationWindowEvent, FinishedWindowEvent};
use windowing::{QuitWindowEvent, MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent};
use servo_msg::constellation_msg::{ConstellationChan, NavigateMsg, ResizedWindowMsg, LoadUrlMsg};
use servo_msg::constellation_msg;
use azure::azure_hl::SourceSurfaceMethods;
use azure::azure_hl;
use std::comm::Port;
use std::num::Orderable;
use std::vec;
use std::path::Path;
use std::rt::io::timer::Timer;
use geom::matrix::identity;
use geom::point::Point2D;
use geom::size::Size2D;
use geom::rect::Rect;
use layers::layers::{ContainerLayer, ContainerLayerKind};
use layers::rendergl;
use layers::scene::Scene;
use opengles::gl2;
use png;
use servo_util::{time, url};
use servo_util::time::profile;
use extra::future::Future;
use extra::time::precise_time_s;
use compositing::compositor_layer::CompositorLayer;
use compositing::*;
/// Starts the compositor, which listens for messages on the specified port.
pub fn run_compositor(compositor: &CompositorTask) {
let app: Application = ApplicationMethods::new();
let window: @mut Window = WindowMethods::new(&app);
// Create an initial layer tree.
//
// TODO: There should be no initial layer tree until the renderer creates one from the display
// list. This is only here because we don't have that logic in the renderer yet.
let context = rendergl::init_render_context();
let root_layer = @mut ContainerLayer();
let window_size = window.size();
let mut scene = Scene(ContainerLayerKind(root_layer), window_size, identity());
let mut window_size = Size2D(window_size.width as uint, window_size.height as uint);
let mut done = false;
let mut recomposite = false;
let graphics_context = CompositorTask::create_graphics_context();
// Keeps track of the current zoom factor
let mut world_zoom = 1f32;
let mut zoom_action = false;
let mut zoom_time = 0f64;
// The root CompositorLayer
let mut compositor_layer: Option<CompositorLayer> = None;
let mut constellation_chan: Option<ConstellationChan> = None;
// Get BufferRequests from each layer.
let ask_for_tiles = || {
let window_size_page = Size2D(window_size.width as f32 / world_zoom,
window_size.height as f32 / world_zoom);
for layer in compositor_layer.mut_iter() {
if !layer.hidden {
let rect = Rect(Point2D(0f32, 0f32), window_size_page);
recomposite = layer.get_buffer_request(&graphics_context, rect, world_zoom) ||
recomposite;
} else {
debug!("Compositor: root layer is hidden!");
}
}
};
let check_for_messages: &fn(&Port<Msg>) = |port: &Port<Msg>| {
// Handle messages
while port.peek() {
match port.recv() {
Exit => done = true,
ChangeReadyState(ready_state) => window.set_ready_state(ready_state),
ChangeRenderState(render_state) => window.set_render_state(render_state),
SetUnRenderedColor(_id, color) => {
match compositor_layer {
Some(ref mut layer) => {
layer.unrendered_color = color;
}
None => {}
}
}
SetIds(frame_tree, response_chan, new_constellation_chan) => {
response_chan.send(());
// This assumes there is at most one child, which should be the case.
match root_layer.first_child {
Some(old_layer) => root_layer.remove_child(old_layer),
None => {}
}
let layer = CompositorLayer::from_frame_tree(frame_tree,
compositor.opts.tile_size,
Some(10000000u),
compositor.opts.cpu_painting);
root_layer.add_child_start(ContainerLayerKind(layer.root_layer));
// If there's already a root layer, destroy it cleanly.
match compositor_layer {
None => {}
Some(ref mut compositor_layer) => compositor_layer.clear_all(),
}
compositor_layer = Some(layer);
// Initialize the new constellation channel by sending it the root window size.
let window_size = window.size();
let window_size = Size2D(window_size.width as uint,
window_size.height as uint);
new_constellation_chan.send(ResizedWindowMsg(window_size));
constellation_chan = Some(new_constellation_chan);
}
GetGraphicsMetadata(chan) => chan.send(azure_hl::current_graphics_metadata()),
NewLayer(_id, new_size) => {
// FIXME: This should create an additional layer instead of replacing the current one.
// Once ResizeLayer messages are set up, we can switch to the new functionality.
let p = match compositor_layer {
Some(ref compositor_layer) => compositor_layer.pipeline.clone(),
None => fail!("Compositor: Received new layer without initialized pipeline"),
};
let page_size = Size2D(new_size.width as f32, new_size.height as f32);
let new_layer = CompositorLayer::new(p,
Some(page_size),
compositor.opts.tile_size,
Some(10000000u),
compositor.opts.cpu_painting);
let current_child = root_layer.first_child;
// This assumes there is at most one child, which should be the case.
match current_child {
Some(old_layer) => root_layer.remove_child(old_layer),
None => {}
}
root_layer.add_child_start(ContainerLayerKind(new_layer.root_layer));
compositor_layer = Some(new_layer);
ask_for_tiles();
}
SetLayerPageSize(id, new_size, epoch) => {
match compositor_layer {
Some(ref mut layer) => {
let page_window = Size2D(window_size.width as f32 / world_zoom,
window_size.height as f32 / world_zoom);
assert!(layer.resize(id, new_size, page_window, epoch));
ask_for_tiles();
}
None => {}
}
}
SetLayerClipRect(id, new_rect) => {
match compositor_layer {
Some(ref mut layer) => {
assert!(layer.set_clipping_rect(id, new_rect));
ask_for_tiles();
}
None => {}
}
}
DeleteLayer(id) => {
match compositor_layer {
Some(ref mut layer) => {
assert!(layer.delete(&graphics_context, id));
ask_for_tiles();
}
None => {}
}
}
Paint(id, new_layer_buffer_set, epoch) => {
debug!("osmain: received new frame");
// From now on, if we destroy the buffers, they will leak.
let mut new_layer_buffer_set = new_layer_buffer_set;
new_layer_buffer_set.mark_will_leak();
match compositor_layer {
Some(ref mut layer) => {
assert!(layer.add_buffers(&graphics_context,
id,
new_layer_buffer_set,
epoch).is_none());
recomposite = true;
}
None => {
fail!("Compositor: given paint command with no CompositorLayer initialized");
}
}
// TODO: Recycle the old buffers; send them back to the renderer to reuse if
// it wishes.
}
InvalidateRect(id, rect) => {
match compositor_layer {
Some(ref mut layer) => {
layer.invalidate_rect(id, Rect(Point2D(rect.origin.x as f32,
rect.origin.y as f32),
Size2D(rect.size.width as f32,
rect.size.height as f32)));
ask_for_tiles();
}
None => {} // Nothing to do
}
}
ScrollFragmentPoint(id, point) => {
let page_window = Size2D(window_size.width as f32 / world_zoom,
window_size.height as f32 / world_zoom);
match compositor_layer {
Some(ref mut layer) if layer.pipeline.id == id => {
recomposite = layer.move(point, page_window) | recomposite;
ask_for_tiles();
}
Some(_) | None => {}
}
}
}
}
};
let check_for_window_messages: &fn(WindowEvent) = |event| {
match event {
IdleWindowEvent => {}
ResizeWindowEvent(width, height) => {
let new_size = Size2D(width, height);
if window_size != new_size {
debug!("osmain: window resized to {:u}x{:u}", width, height);
window_size = new_size;
match constellation_chan {
Some(ref chan) => chan.send(ResizedWindowMsg(new_size)),
None => error!("Compositor: Received resize event without initialized layout chan"),
}
} else {
debug!("osmain: dropping window resize since size is still {:u}x{:u}", width, height);
}
}
LoadUrlWindowEvent(url_string) => {
debug!("osmain: loading URL `{:s}`", url_string);
let root_pipeline_id = match compositor_layer {
Some(ref layer) => layer.pipeline.id.clone(),
None => fail!("Compositor: Received LoadUrlWindowEvent without initialized compositor layers"),
};
match constellation_chan {
Some(ref chan) => chan.send(LoadUrlMsg(root_pipeline_id,
url::make_url(url_string.to_str(), None),
Future::from_value(window_size))),
None => error!("Compositor: Received loadurl event without initialized layout chan"),
}
}
MouseWindowEventClass(mouse_window_event) => {
let point = match mouse_window_event {
MouseWindowClickEvent(_, p) => Point2D(p.x / world_zoom, p.y / world_zoom),
MouseWindowMouseDownEvent(_, p) => Point2D(p.x / world_zoom, p.y / world_zoom),
MouseWindowMouseUpEvent(_, p) => Point2D(p.x / world_zoom, p.y / world_zoom),
};
for layer in compositor_layer.iter() {
layer.send_mouse_event(mouse_window_event, point);
}
}
ScrollWindowEvent(delta, cursor) => {
// TODO: modify delta to snap scroll to pixels.
let page_delta = Point2D(delta.x as f32 / world_zoom, delta.y as f32 / world_zoom);
let page_cursor: Point2D<f32> = Point2D(cursor.x as f32 / world_zoom,
cursor.y as f32 / world_zoom);
let page_window = Size2D(window_size.width as f32 / world_zoom,
window_size.height as f32 / world_zoom);
for layer in compositor_layer.mut_iter() {
recomposite = layer.scroll(page_delta, page_cursor, page_window) || recomposite;
}
ask_for_tiles();
}
ZoomWindowEvent(magnification) => {
zoom_action = true;
zoom_time = precise_time_s();
let old_world_zoom = world_zoom;
// Determine zoom amount
world_zoom = (world_zoom * magnification).max(&1.0);
root_layer.common.set_transform(identity().scale(world_zoom, world_zoom, 1f32));
// Scroll as needed
let page_delta = Point2D(window_size.width as f32 * (1.0 / world_zoom - 1.0 / old_world_zoom) * 0.5,
window_size.height as f32 * (1.0 / world_zoom - 1.0 / old_world_zoom) * 0.5);
// TODO: modify delta to snap scroll to pixels.
let page_cursor = Point2D(-1f32, -1f32); // Make sure this hits the base layer
let page_window = Size2D(window_size.width as f32 / world_zoom,
window_size.height as f32 / world_zoom);
for layer in compositor_layer.mut_iter() {
layer.scroll(page_delta, page_cursor, page_window);
}
recomposite = true;
}
NavigationWindowEvent(direction) => {
let direction = match direction {
windowing::Forward => constellation_msg::Forward,
windowing::Back => constellation_msg::Back,
};
match constellation_chan {
Some(ref chan) => chan.send(NavigateMsg(direction)),
None => error!("Compositor: Received navigation event without initialized layout chan"),
}
}
FinishedWindowEvent => {
if compositor.opts.exit_after_load {
done = true;
}
}
QuitWindowEvent => {
done = true;
}
}
};
let profiler_chan = compositor.profiler_chan.clone();
let write_png = compositor.opts.output_file.is_some();
let exit = compositor.opts.exit_after_load;
let composite = || {
do profile(time::CompositingCategory, profiler_chan.clone()) {
debug!("compositor: compositing");
// Adjust the layer dimensions as necessary to correspond to the size of the window.
scene.size = window.size();
// Render the scene.
match compositor_layer {
Some(ref mut layer) => {
scene.background_color.r = layer.unrendered_color.r;
scene.background_color.g = layer.unrendered_color.g;
scene.background_color.b = layer.unrendered_color.b;
scene.background_color.a = layer.unrendered_color.a;
}
None => {}
}
rendergl::render_scene(context, &scene);
}
// Render to PNG. We must read from the back buffer (ie, before
// window.present()) as OpenGL ES 2 does not have glReadBuffer().
if write_png {
let (width, height) = (window_size.width as uint, window_size.height as uint);
let path = from_str::<Path>(*compositor.opts.output_file.get_ref()).unwrap();
let mut pixels = gl2::read_pixels(0, 0,
width as gl2::GLsizei,
height as gl2::GLsizei,
gl2::RGB, gl2::UNSIGNED_BYTE);
// flip image vertically (texture is upside down)
let orig_pixels = pixels.clone();
let stride = width * 3;
for y in range(0, height) {
let dst_start = y * stride;
let src_start = (height - y - 1) * stride;
vec::bytes::copy_memory(pixels.mut_slice(dst_start, dst_start + stride),
orig_pixels.slice(src_start, src_start + stride),
stride);
}
let img = png::Image {
width: width as u32,
height: height as u32,
color_type: png::RGBA8,
pixels: pixels,
};
let res = png::store_png(&img, &path);
assert!(res.is_ok());
done = true;
}
window.present();
if exit { done = true; }
};
// Enter the main event loop.
let mut tm = Timer::new().unwrap();
while !done {
// Check for new messages coming from the rendering task.
check_for_messages(&compositor.port);
// Check for messages coming from the windowing system.
check_for_window_messages(window.recv());
if recomposite {
recomposite = false;
composite();
}
tm.sleep(10);
// If a pinch-zoom happened recently, ask for tiles at the new resolution
if zoom_action && precise_time_s() - zoom_time > 0.3 {
zoom_action = false;
ask_for_tiles();
}
}
compositor.shutdown_chan.send(());
// Clear out the compositor layers so that painting tasks can destroy the buffers.
match compositor_layer {
None => {}
Some(ref mut layer) => layer.forget_all_tiles(),
}
}