/
constellation.rs
1611 lines (1416 loc) · 70.6 KB
/
constellation.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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/. */
//! The `Constellation`, Servo's Grand Central Station
//!
//! The primary duty of a `Constellation` is to mediate between the
//! graphics compositor and the many `Pipeline`s in the browser's
//! navigation context, each `Pipeline` encompassing a `ScriptTask`,
//! `LayoutTask`, and `PaintTask`.
use CompositorMsg as FromCompositorMsg;
use canvas::canvas_paint_task::CanvasPaintTask;
use canvas::webgl_paint_task::WebGLPaintTask;
use canvas_traits::CanvasMsg;
use clipboard::ClipboardContext;
use compositor_task::CompositorProxy;
use compositor_task::Msg as ToCompositorMsg;
use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg};
use euclid::scale_factor::ScaleFactor;
use euclid::size::{Size2D, TypedSize2D};
use gaol;
use gaol::sandbox::{self, Sandbox, SandboxMethods};
use gfx::font_cache_task::FontCacheTask;
use ipc_channel::ipc::{self, IpcOneShotServer, IpcSender};
use ipc_channel::router::ROUTER;
use layout_traits::{LayoutControlChan, LayoutTaskFactory};
use msg::compositor_msg::Epoch;
use msg::constellation_msg::AnimationState;
use msg::constellation_msg::PaintMsg as FromPaintMsg;
use msg::constellation_msg::WebDriverCommandMsg;
use msg::constellation_msg::{FrameId, PipelineId};
use msg::constellation_msg::{IframeLoadInfo, IFrameSandboxState, MozBrowserEvent, NavigationDirection};
use msg::constellation_msg::{Key, KeyModifiers, KeyState, LoadData};
use msg::constellation_msg::{PipelineNamespace, PipelineNamespaceId};
use msg::constellation_msg::{SubpageId, WindowSizeData};
use msg::constellation_msg::{self, ConstellationChan, Failure};
use msg::webdriver_msg;
use net_traits::image_cache_task::ImageCacheTask;
use net_traits::storage_task::{StorageTask, StorageTaskMsg};
use net_traits::{self, ResourceTask};
use offscreen_gl_context::GLContextAttributes;
use pipeline::{CompositionPipeline, InitialPipelineState, Pipeline, UnprivilegedPipelineContent};
use profile_traits::mem;
use profile_traits::time;
use sandboxing;
use script_traits::{CompositorEvent, ConstellationControlMsg, LayoutControlMsg};
use script_traits::{ScriptMsg as FromScriptMsg, ScriptState, ScriptTaskFactory};
use script_traits::{TimerEventRequest};
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::env;
use std::io::{self, Write};
use std::marker::PhantomData;
use std::mem::replace;
use std::process;
use std::sync::mpsc::{Sender, channel, Receiver};
use style_traits::viewport::ViewportConstraints;
use timer_scheduler::TimerScheduler;
use url::Url;
use util::cursor::Cursor;
use util::geometry::PagePx;
use util::task::spawn_named;
use util::{opts, prefs};
#[derive(Debug, PartialEq)]
enum ReadyToSave {
NoRootFrame,
WebFontNotLoaded,
DocumentLoading,
EpochMismatch,
PipelineUnknown,
Ready,
}
/// Maintains the pipelines and navigation context and grants permission to composite.
///
/// It is parameterized over a `LayoutTaskFactory` and a
/// `ScriptTaskFactory` (which in practice are implemented by
/// `LayoutTask` in the `layout` crate, and `ScriptTask` in
/// the `script` crate).
pub struct Constellation<LTF, STF> {
/// A channel through which script messages can be sent to this object.
pub script_sender: ConstellationChan<FromScriptMsg>,
/// A channel through which compositor messages can be sent to this object.
pub compositor_sender: Sender<FromCompositorMsg>,
/// A channel through which paint task messages can be sent to this object.
pub painter_sender: ConstellationChan<FromPaintMsg>,
/// Receives messages from scripts.
pub script_receiver: Receiver<FromScriptMsg>,
/// Receives messages from the compositor
pub compositor_receiver: Receiver<FromCompositorMsg>,
/// Receives messages from paint task.
pub painter_receiver: Receiver<FromPaintMsg>,
/// A channel (the implementation of which is port-specific) through which messages can be sent
/// to the compositor.
pub compositor_proxy: Box<CompositorProxy>,
/// A channel through which messages can be sent to the resource task.
pub resource_task: ResourceTask,
/// A channel through which messages can be sent to the image cache task.
pub image_cache_task: ImageCacheTask,
/// A channel through which messages can be sent to the developer tools.
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
/// A channel through which messages can be sent to the storage task.
storage_task: StorageTask,
/// A list of all the pipelines. (See the `pipeline` module for more details.)
pipelines: HashMap<PipelineId, Pipeline>,
/// A list of all the frames
frames: HashMap<FrameId, Frame>,
/// Maps from pipeline ID to the frame that contains it.
pipeline_to_frame_map: HashMap<PipelineId, FrameId>,
/// Maps from a (parent pipeline, subpage) to the actual child pipeline ID.
subpage_map: HashMap<(PipelineId, SubpageId), PipelineId>,
/// A channel through which messages can be sent to the font cache.
font_cache_task: FontCacheTask,
/// ID of the root frame.
root_frame_id: Option<FrameId>,
/// The next free ID to assign to a pipeline ID namespace.
next_pipeline_namespace_id: PipelineNamespaceId,
/// The next free ID to assign to a frame.
next_frame_id: FrameId,
/// Pipeline ID that has currently focused element for key events.
focus_pipeline_id: Option<PipelineId>,
/// Navigation operations that are in progress.
pending_frames: Vec<FrameChange>,
/// A channel through which messages can be sent to the time profiler.
pub time_profiler_chan: time::ProfilerChan,
/// A channel through which messages can be sent to the memory profiler.
pub mem_profiler_chan: mem::ProfilerChan,
phantom: PhantomData<(LTF, STF)>,
pub window_size: WindowSizeData,
/// Means of accessing the clipboard
clipboard_ctx: Option<ClipboardContext>,
/// Bits of state used to interact with the webdriver implementation
webdriver: WebDriverData,
/// A list of in-process senders to `CanvasPaintTask`s.
canvas_paint_tasks: Vec<Sender<CanvasMsg>>,
/// A list of in-process senders to `WebGLPaintTask`s.
webgl_paint_tasks: Vec<Sender<CanvasMsg>>,
scheduler_chan: IpcSender<TimerEventRequest>,
/// A list of child content processes.
child_processes: Vec<ChildProcess>,
}
/// State needed to construct a constellation.
pub struct InitialConstellationState {
/// A channel through which messages can be sent to the compositor.
pub compositor_proxy: Box<CompositorProxy + Send>,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<Sender<DevtoolsControlMsg>>,
/// A channel to the image cache task.
pub image_cache_task: ImageCacheTask,
/// A channel to the font cache task.
pub font_cache_task: FontCacheTask,
/// A channel to the resource task.
pub resource_task: ResourceTask,
/// A channel to the storage task.
pub storage_task: StorageTask,
/// A channel to the time profiler thread.
pub time_profiler_chan: time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// Whether the constellation supports the clipboard.
pub supports_clipboard: bool,
}
/// Stores the navigation context for a single frame in the frame tree.
pub struct Frame {
prev: Vec<PipelineId>,
current: PipelineId,
next: Vec<PipelineId>,
}
impl Frame {
fn new(pipeline_id: PipelineId) -> Frame {
Frame {
prev: vec!(),
current: pipeline_id,
next: vec!(),
}
}
fn load(&mut self, pipeline_id: PipelineId) -> Vec<PipelineId> {
// TODO(gw): To also allow navigations within subframes
// to affect the parent navigation history, this should bubble
// up the navigation change to each parent.
self.prev.push(self.current);
self.current = pipeline_id;
replace(&mut self.next, vec!())
}
}
/// Represents a pending change in the frame tree, that will be applied
/// once the new pipeline has loaded and completed initial layout / paint.
struct FrameChange {
old_pipeline_id: Option<PipelineId>,
new_pipeline_id: PipelineId,
painter_ready: bool,
}
/// An iterator over a frame tree, returning nodes in depth-first order.
/// Note that this iterator should _not_ be used to mutate nodes _during_
/// iteration. Mutating nodes once the iterator is out of scope is OK.
struct FrameTreeIterator<'a> {
stack: Vec<FrameId>,
frames: &'a HashMap<FrameId, Frame>,
pipelines: &'a HashMap<PipelineId, Pipeline>,
}
impl<'a> Iterator for FrameTreeIterator<'a> {
type Item = &'a Frame;
fn next(&mut self) -> Option<&'a Frame> {
self.stack.pop().map(|next| {
let frame = self.frames.get(&next).unwrap();
let pipeline = self.pipelines.get(&frame.current).unwrap();
self.stack.extend(pipeline.children.iter().map(|&c| c));
frame
})
}
}
pub struct SendableFrameTree {
pub pipeline: CompositionPipeline,
pub size: Option<TypedSize2D<PagePx, f32>>,
pub children: Vec<SendableFrameTree>,
}
struct WebDriverData {
load_channel: Option<(PipelineId, IpcSender<webdriver_msg::LoadStatus>)>
}
impl WebDriverData {
pub fn new() -> WebDriverData {
WebDriverData {
load_channel: None
}
}
}
#[derive(Clone, Copy)]
enum ExitPipelineMode {
Normal,
Force,
}
enum ChildProcess {
Sandboxed(gaol::platform::process::Process),
Unsandboxed(process::Child),
}
impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> {
pub fn start(state: InitialConstellationState) -> Sender<FromCompositorMsg> {
let (ipc_script_receiver, ipc_script_sender) = ConstellationChan::<FromScriptMsg>::new();
let script_receiver = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(ipc_script_receiver);
let (compositor_sender, compositor_receiver) = channel();
let (ipc_painter_receiver, ipc_painter_sender) = ConstellationChan::<FromPaintMsg>::new();
let painter_receiver = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(ipc_painter_receiver);
let compositor_sender_clone = compositor_sender.clone();
spawn_named("Constellation".to_owned(), move || {
let mut constellation: Constellation<LTF, STF> = Constellation {
script_sender: ipc_script_sender,
compositor_sender: compositor_sender_clone,
painter_sender: ipc_painter_sender,
script_receiver: script_receiver,
compositor_receiver: compositor_receiver,
painter_receiver: painter_receiver,
compositor_proxy: state.compositor_proxy,
devtools_chan: state.devtools_chan,
resource_task: state.resource_task,
image_cache_task: state.image_cache_task,
font_cache_task: state.font_cache_task,
storage_task: state.storage_task,
pipelines: HashMap::new(),
frames: HashMap::new(),
pipeline_to_frame_map: HashMap::new(),
subpage_map: HashMap::new(),
pending_frames: vec!(),
next_pipeline_namespace_id: PipelineNamespaceId(0),
root_frame_id: None,
next_frame_id: FrameId(0),
focus_pipeline_id: None,
time_profiler_chan: state.time_profiler_chan,
mem_profiler_chan: state.mem_profiler_chan,
window_size: WindowSizeData {
visible_viewport: opts::get().initial_window_size.as_f32() *
ScaleFactor::new(1.0),
initial_viewport: opts::get().initial_window_size.as_f32() *
ScaleFactor::new(1.0),
device_pixel_ratio:
ScaleFactor::new(opts::get().device_pixels_per_px.unwrap_or(1.0)),
},
phantom: PhantomData,
clipboard_ctx: if state.supports_clipboard {
ClipboardContext::new().ok()
} else {
None
},
webdriver: WebDriverData::new(),
canvas_paint_tasks: Vec::new(),
webgl_paint_tasks: Vec::new(),
scheduler_chan: TimerScheduler::start(),
child_processes: Vec::new(),
};
let namespace_id = constellation.next_pipeline_namespace_id();
PipelineNamespace::install(namespace_id);
constellation.run();
});
compositor_sender
}
fn run(&mut self) {
loop {
if !self.handle_request() {
break;
}
}
}
fn next_pipeline_namespace_id(&mut self) -> PipelineNamespaceId {
let namespace_id = self.next_pipeline_namespace_id;
let PipelineNamespaceId(ref mut i) = self.next_pipeline_namespace_id;
*i += 1;
namespace_id
}
/// Helper function for creating a pipeline
fn new_pipeline(&mut self,
pipeline_id: PipelineId,
parent_info: Option<(PipelineId, SubpageId)>,
initial_window_size: Option<TypedSize2D<PagePx, f32>>,
script_channel: Option<IpcSender<ConstellationControlMsg>>,
load_data: LoadData) {
let spawning_paint_only = script_channel.is_some();
let (pipeline, unprivileged_pipeline_content, privileged_pipeline_content) =
Pipeline::create::<LTF, STF>(InitialPipelineState {
id: pipeline_id,
parent_info: parent_info,
constellation_chan: self.script_sender.clone(),
painter_chan: self.painter_sender.clone(),
scheduler_chan: self.scheduler_chan.clone(),
compositor_proxy: self.compositor_proxy.clone_compositor_proxy(),
devtools_chan: self.devtools_chan.clone(),
image_cache_task: self.image_cache_task.clone(),
font_cache_task: self.font_cache_task.clone(),
resource_task: self.resource_task.clone(),
storage_task: self.storage_task.clone(),
time_profiler_chan: self.time_profiler_chan.clone(),
mem_profiler_chan: self.mem_profiler_chan.clone(),
window_size: initial_window_size,
script_chan: script_channel,
load_data: load_data,
device_pixel_ratio: self.window_size.device_pixel_ratio,
pipeline_namespace_id: self.next_pipeline_namespace_id(),
});
if spawning_paint_only {
privileged_pipeline_content.start_paint_task();
} else {
privileged_pipeline_content.start_all();
// Spawn the child process.
//
// Yes, that's all there is to it!
if opts::multiprocess() {
let (server, token) =
IpcOneShotServer::<IpcSender<UnprivilegedPipelineContent>>::new().unwrap();
// If there is a sandbox, use the `gaol` API to create the child process.
let child_process = if opts::get().sandbox {
let mut command = sandbox::Command::me().unwrap();
command.arg("--content-process").arg(token);
let profile = sandboxing::content_process_sandbox_profile();
ChildProcess::Sandboxed(Sandbox::new(profile).start(&mut command).expect(
"Failed to start sandboxed child process!"))
} else {
let path_to_self = env::current_exe().unwrap();
let mut child_process = process::Command::new(path_to_self);
child_process.arg("--content-process");
child_process.arg(token);
ChildProcess::Unsandboxed(child_process.spawn().unwrap())
};
self.child_processes.push(child_process);
let (_receiver, sender) = server.accept().unwrap();
sender.send(unprivileged_pipeline_content).unwrap();
} else {
unprivileged_pipeline_content.start_all::<LTF, STF>(false);
}
}
assert!(!self.pipelines.contains_key(&pipeline_id));
self.pipelines.insert(pipeline_id, pipeline);
}
// Push a new (loading) pipeline to the list of pending frame changes
fn push_pending_frame(&mut self, new_pipeline_id: PipelineId,
old_pipeline_id: Option<PipelineId>) {
self.pending_frames.push(FrameChange {
old_pipeline_id: old_pipeline_id,
new_pipeline_id: new_pipeline_id,
painter_ready: false,
});
}
// Get an iterator for the current frame tree. Specify self.root_frame_id to
// iterate the entire tree, or a specific frame id to iterate only that sub-tree.
fn current_frame_tree_iter(&self, frame_id_root: Option<FrameId>) -> FrameTreeIterator {
let mut stack = vec!();
if let Some(frame_id_root) = frame_id_root {
stack.push(frame_id_root);
}
FrameTreeIterator {
stack: stack,
pipelines: &self.pipelines,
frames: &self.frames,
}
}
// Create a new frame and update the internal bookkeeping.
fn new_frame(&mut self, pipeline_id: PipelineId) -> FrameId {
let id = self.next_frame_id;
let FrameId(ref mut i) = self.next_frame_id;
*i += 1;
let frame = Frame::new(pipeline_id);
assert!(!self.pipeline_to_frame_map.contains_key(&pipeline_id));
assert!(!self.frames.contains_key(&id));
self.pipeline_to_frame_map.insert(pipeline_id, id);
self.frames.insert(id, frame);
id
}
/// Handles loading pages, navigation, and granting access to the compositor
#[allow(unsafe_code)]
fn handle_request(&mut self) -> bool {
enum Request {
Script(FromScriptMsg),
Compositor(FromCompositorMsg),
Paint(FromPaintMsg)
}
let request = {
let receiver_from_script = &self.script_receiver;
let receiver_from_compositor = &self.compositor_receiver;
let receiver_from_paint = &self.painter_receiver;
select! {
msg = receiver_from_script.recv() =>
Request::Script(msg.unwrap()),
msg = receiver_from_compositor.recv() =>
Request::Compositor(msg.unwrap()),
msg = receiver_from_paint.recv() =>
Request::Paint(msg.unwrap())
}
};
match request {
// Messages from compositor
Request::Compositor(FromCompositorMsg::Exit) => {
debug!("constellation exiting");
self.handle_exit();
return false;
}
// The compositor discovered the size of a subframe. This needs to be reflected by all
// frame trees in the navigation context containing the subframe.
Request::Compositor(FromCompositorMsg::FrameSize(pipeline_id, size)) => {
debug!("constellation got frame size message");
self.handle_frame_size_msg(pipeline_id, &Size2D::from_untyped(&size));
}
Request::Compositor(FromCompositorMsg::GetFrame(pipeline_id, resp_chan)) => {
debug!("constellation got get root pipeline message");
self.handle_get_frame(pipeline_id, resp_chan);
}
Request::Compositor(FromCompositorMsg::GetPipeline(frame_id, resp_chan)) => {
debug!("constellation got get root pipeline message");
self.handle_get_pipeline(frame_id, resp_chan);
}
Request::Compositor(FromCompositorMsg::GetPipelineTitle(pipeline_id)) => {
debug!("constellation got get-pipeline-title message");
self.handle_get_pipeline_title_msg(pipeline_id);
}
Request::Compositor(FromCompositorMsg::KeyEvent(key, state, modifiers)) => {
debug!("constellation got key event message");
self.handle_key_msg(key, state, modifiers);
}
// Load a new page from a typed url
// If there is already a pending page (self.pending_frames), it will not be overridden;
// However, if the id is not encompassed by another change, it will be.
Request::Compositor(FromCompositorMsg::LoadUrl(source_id, load_data)) => {
debug!("constellation got URL load message from compositor");
self.handle_load_url_msg(source_id, load_data);
}
Request::Compositor(FromCompositorMsg::IsReadyToSaveImage(pipeline_states)) => {
let is_ready = self.handle_is_ready_to_save_image(pipeline_states);
if opts::get().is_running_problem_test {
println!("got ready to save image query, result is {:?}", is_ready);
}
let is_ready = is_ready == ReadyToSave::Ready;
self.compositor_proxy.send(ToCompositorMsg::IsReadyToSaveImageReply(is_ready));
if opts::get().is_running_problem_test {
println!("sent response");
}
}
// This should only be called once per constellation, and only by the browser
Request::Compositor(FromCompositorMsg::InitLoadUrl(url)) => {
debug!("constellation got init load URL message");
self.handle_init_load(url);
}
// Handle a forward or back request
Request::Compositor(FromCompositorMsg::Navigate(pipeline_info, direction)) => {
debug!("constellation got navigation message from compositor");
self.handle_navigate_msg(pipeline_info, direction);
}
Request::Compositor(FromCompositorMsg::ResizedWindow(new_size)) => {
debug!("constellation got window resize message");
self.handle_resized_window_msg(new_size);
}
Request::Compositor(FromCompositorMsg::TickAnimation(pipeline_id)) => {
self.handle_tick_animation(pipeline_id)
}
Request::Compositor(FromCompositorMsg::WebDriverCommand(command)) => {
debug!("constellation got webdriver command message");
self.handle_webdriver_msg(command);
}
// Messages from script
Request::Script(FromScriptMsg::Failure(Failure { pipeline_id, parent_info })) => {
debug!("handling script failure message from pipeline {:?}, {:?}", pipeline_id, parent_info);
self.handle_failure_msg(pipeline_id, parent_info);
}
Request::Script(FromScriptMsg::ScriptLoadedURLInIFrame(load_info)) => {
debug!("constellation got iframe URL load message {:?} {:?} {:?}",
load_info.containing_pipeline_id,
load_info.old_subpage_id,
load_info.new_subpage_id);
self.handle_script_loaded_url_in_iframe_msg(load_info);
}
Request::Script(FromScriptMsg::SetCursor(cursor)) => {
self.handle_set_cursor_msg(cursor)
}
Request::Script(FromScriptMsg::ChangeRunningAnimationsState(pipeline_id, animation_state)) => {
self.handle_change_running_animations_state(pipeline_id, animation_state)
}
// Load a new page from a mouse click
// If there is already a pending page (self.pending_frames), it will not be overridden;
// However, if the id is not encompassed by another change, it will be.
Request::Script(FromScriptMsg::LoadUrl(source_id, load_data)) => {
debug!("constellation got URL load message from script");
self.handle_load_url_msg(source_id, load_data);
}
// A page loaded has completed all parsing, script, and reflow messages have been sent.
Request::Script(FromScriptMsg::LoadComplete(pipeline_id)) => {
debug!("constellation got load complete message");
self.handle_load_complete_msg(&pipeline_id)
}
// The DOM load event fired on a document
Request::Script(FromScriptMsg::DOMLoad(pipeline_id)) => {
debug!("constellation got dom load message");
self.handle_dom_load(pipeline_id)
}
// Handle a forward or back request
Request::Script(FromScriptMsg::Navigate(pipeline_info, direction)) => {
debug!("constellation got navigation message from script");
self.handle_navigate_msg(pipeline_info, direction);
}
Request::Script(FromScriptMsg::MozBrowserEvent(pipeline_id,
subpage_id,
event)) => {
debug!("constellation got mozbrowser event message");
self.handle_mozbrowser_event_msg(pipeline_id,
subpage_id,
event);
}
Request::Script(FromScriptMsg::Focus(pipeline_id)) => {
debug!("constellation got focus message");
self.handle_focus_msg(pipeline_id);
}
Request::Script(FromScriptMsg::ForwardMouseButtonEvent(
pipeline_id, event_type, button, point)) => {
if let Some(pipeline) = self.pipelines.get(&pipeline_id) {
pipeline.script_chan.send(ConstellationControlMsg::SendEvent(pipeline_id,
CompositorEvent::MouseButtonEvent(event_type, button, point))).unwrap();
}
}
Request::Script(FromScriptMsg::ForwardMouseMoveEvent(pipeline_id, point)) => {
if let Some(pipeline) = self.pipelines.get(&pipeline_id) {
pipeline.script_chan.send(ConstellationControlMsg::SendEvent(pipeline_id,
CompositorEvent::MouseMoveEvent(Some(point)))).unwrap();
}
}
Request::Script(FromScriptMsg::GetClipboardContents(sender)) => {
let result = self.clipboard_ctx.as_ref().map_or(
"".to_owned(),
|ctx| ctx.get_contents().unwrap_or_else(|e| {
debug!("Error getting clipboard contents ({}), defaulting to empty string", e);
"".to_owned()
})
);
sender.send(result).unwrap();
}
Request::Script(FromScriptMsg::SetClipboardContents(s)) => {
if let Some(ref mut ctx) = self.clipboard_ctx {
if let Err(e) = ctx.set_contents(s) {
debug!("Error setting clipboard contents ({})", e);
}
}
}
Request::Script(FromScriptMsg::ViewportConstrained(pipeline_id, constraints)) => {
debug!("constellation got viewport-constrained event message");
self.handle_viewport_constrained_msg(pipeline_id, constraints);
}
Request::Script(FromScriptMsg::RemoveIFrame(pipeline_id)) => {
debug!("constellation got remove iframe message");
self.handle_remove_iframe_msg(pipeline_id);
}
Request::Script(FromScriptMsg::NewFavicon(url)) => {
debug!("constellation got new favicon message");
self.compositor_proxy.send(ToCompositorMsg::NewFavicon(url));
}
Request::Script(FromScriptMsg::HeadParsed) => {
debug!("constellation got head parsed message");
self.compositor_proxy.send(ToCompositorMsg::HeadParsed);
}
Request::Script(FromScriptMsg::CreateCanvasPaintTask(size, sender)) => {
debug!("constellation got create-canvas-paint-task message");
self.handle_create_canvas_paint_task_msg(&size, sender)
}
Request::Script(FromScriptMsg::CreateWebGLPaintTask(size, attributes, sender)) => {
debug!("constellation got create-WebGL-paint-task message");
self.handle_create_webgl_paint_task_msg(&size, attributes, sender)
}
Request::Script(FromScriptMsg::NodeStatus(message)) => {
debug!("constellation got NodeStatus message");
self.compositor_proxy.send(ToCompositorMsg::Status(message));
}
// Messages from paint task
// Notification that painting has finished and is requesting permission to paint.
Request::Paint(FromPaintMsg::Ready(pipeline_id)) => {
debug!("constellation got painter ready message");
self.handle_painter_ready_msg(pipeline_id);
}
Request::Paint(FromPaintMsg::Failure(Failure { pipeline_id, parent_info })) => {
debug!("handling paint failure message from pipeline {:?}, {:?}", pipeline_id, parent_info);
self.handle_failure_msg(pipeline_id, parent_info);
}
}
true
}
fn handle_exit(&mut self) {
for (_id, ref pipeline) in &self.pipelines {
pipeline.exit();
}
self.image_cache_task.exit();
self.resource_task.send(net_traits::ControlMsg::Exit).unwrap();
self.devtools_chan.as_ref().map(|chan| {
chan.send(DevtoolsControlMsg::FromChrome(
ChromeToDevtoolsControlMsg::ServerExitMsg)).unwrap();
});
self.storage_task.send(StorageTaskMsg::Exit).unwrap();
self.font_cache_task.exit();
self.compositor_proxy.send(ToCompositorMsg::ShutdownComplete);
}
fn handle_failure_msg(&mut self,
pipeline_id: PipelineId,
parent_info: Option<(PipelineId, SubpageId)>) {
if opts::get().hard_fail {
// It's quite difficult to make Servo exit cleanly if some tasks have failed.
// Hard fail exists for test runners so we crash and that's good enough.
let mut stderr = io::stderr();
stderr.write_all("Pipeline failed in hard-fail mode. Crashing!\n".as_bytes()).unwrap();
process::exit(1);
}
self.close_pipeline(pipeline_id, ExitPipelineMode::Force);
while let Some(pending_pipeline_id) = self.pending_frames.iter().find(|pending| {
pending.old_pipeline_id == Some(pipeline_id)
}).map(|frame| frame.new_pipeline_id) {
debug!("removing pending frame change for failed pipeline");
self.close_pipeline(pending_pipeline_id, ExitPipelineMode::Force);
}
debug!("creating replacement pipeline for about:failure");
let window_size = self.pipeline(pipeline_id).size;
let new_pipeline_id = PipelineId::new();
self.new_pipeline(new_pipeline_id,
parent_info,
window_size,
None,
LoadData::new(url!("about:failure")));
self.push_pending_frame(new_pipeline_id, Some(pipeline_id));
}
fn handle_init_load(&mut self, url: Url) {
let window_size = self.window_size.visible_viewport;
let root_pipeline_id = PipelineId::new();
debug_assert!(PipelineId::fake_root_pipeline_id() == root_pipeline_id);
self.new_pipeline(root_pipeline_id, None, Some(window_size), None, LoadData::new(url.clone()));
self.handle_load_start_msg(&root_pipeline_id);
self.push_pending_frame(root_pipeline_id, None);
self.compositor_proxy.send(ToCompositorMsg::ChangePageUrl(root_pipeline_id, url));
}
fn handle_frame_size_msg(&mut self,
pipeline_id: PipelineId,
size: &TypedSize2D<PagePx, f32>) {
// Store the new rect inside the pipeline
let script_chan = {
// Find the pipeline that corresponds to this rectangle. It's possible that this
// pipeline may have already exited before we process this message, so just
// early exit if that occurs.
match self.pipelines.get_mut(&pipeline_id) {
Some(pipeline) => {
pipeline.size = Some(*size);
pipeline.script_chan.clone()
}
None => return,
}
};
script_chan.send(ConstellationControlMsg::Resize(pipeline_id, WindowSizeData {
visible_viewport: *size,
initial_viewport: *size * ScaleFactor::new(1.0),
device_pixel_ratio: self.window_size.device_pixel_ratio,
})).unwrap();
}
fn handle_subframe_loaded(&mut self, pipeline_id: PipelineId) {
let subframe_pipeline = self.pipeline(pipeline_id);
let subframe_parent = match subframe_pipeline.parent_info {
Some(ref parent) => parent,
None => return,
};
let parent_pipeline = self.pipeline(subframe_parent.0);
let msg = ConstellationControlMsg::DispatchFrameLoadEvent {
target: pipeline_id,
parent: subframe_parent.0
};
parent_pipeline.script_chan.send(msg).unwrap();
}
// The script task associated with pipeline_id has loaded a URL in an iframe via script. This
// will result in a new pipeline being spawned and a frame tree being added to
// containing_page_pipeline_id's frame tree's children. This message is never the result of a
// page navigation.
fn handle_script_loaded_url_in_iframe_msg(&mut self, load_info: IframeLoadInfo) {
// Compare the pipeline's url to the new url. If the origin is the same,
// then reuse the script task in creating the new pipeline
let script_chan = {
let source_pipeline = self.pipeline(load_info.containing_pipeline_id);
let source_url = source_pipeline.url.clone();
let same_script = (source_url.host() == load_info.url.host() &&
source_url.port() == load_info.url.port()) &&
load_info.sandbox == IFrameSandboxState::IFrameUnsandboxed;
// FIXME(tkuehn): Need to follow the standardized spec for checking same-origin
// Reuse the script task if the URL is same-origin
if same_script {
debug!("Constellation: loading same-origin iframe, \
parent url {:?}, iframe url {:?}", source_url, load_info.url);
Some(source_pipeline.script_chan.clone())
} else {
debug!("Constellation: loading cross-origin iframe, \
parent url {:?}, iframe url {:?}", source_url, load_info.url);
None
}
};
// Create the new pipeline, attached to the parent and push to pending frames
let old_pipeline_id = load_info.old_subpage_id.map(|old_subpage_id| {
self.find_subpage(load_info.containing_pipeline_id, old_subpage_id).id
});
let window_size = old_pipeline_id.and_then(|old_pipeline_id| {
self.pipeline(old_pipeline_id).size
});
self.new_pipeline(load_info.new_pipeline_id,
Some((load_info.containing_pipeline_id, load_info.new_subpage_id)),
window_size,
script_chan,
LoadData::new(load_info.url));
self.subpage_map.insert((load_info.containing_pipeline_id, load_info.new_subpage_id),
load_info.new_pipeline_id);
self.push_pending_frame(load_info.new_pipeline_id, old_pipeline_id);
}
fn handle_set_cursor_msg(&mut self, cursor: Cursor) {
self.compositor_proxy.send(ToCompositorMsg::SetCursor(cursor))
}
fn handle_change_running_animations_state(&mut self,
pipeline_id: PipelineId,
animation_state: AnimationState) {
self.compositor_proxy.send(ToCompositorMsg::ChangeRunningAnimationsState(pipeline_id,
animation_state))
}
fn handle_tick_animation(&mut self, pipeline_id: PipelineId) {
self.pipeline(pipeline_id)
.layout_chan
.0
.send(LayoutControlMsg::TickAnimations)
.unwrap();
}
fn handle_load_url_msg(&mut self, source_id: PipelineId, load_data: LoadData) {
self.load_url(source_id, load_data);
}
fn load_url(&mut self, source_id: PipelineId, load_data: LoadData) -> Option<PipelineId> {
// If this load targets an iframe, its framing element may exist
// in a separate script task than the framed document that initiated
// the new load. The framing element must be notified about the
// requested change so it can update its internal state.
match self.pipeline(source_id).parent_info {
Some((parent_pipeline_id, subpage_id)) => {
self.handle_load_start_msg(&source_id);
// Message the constellation to find the script task for this iframe
// and issue an iframe load through there.
let parent_pipeline = self.pipeline(parent_pipeline_id);
let script_channel = &parent_pipeline.script_chan;
script_channel.send(ConstellationControlMsg::Navigate(parent_pipeline_id,
subpage_id,
load_data)).unwrap();
Some(source_id)
}
None => {
// Make sure no pending page would be overridden.
for frame_change in &self.pending_frames {
if frame_change.old_pipeline_id == Some(source_id) {
// id that sent load msg is being changed already; abort
return None;
}
}
self.handle_load_start_msg(&source_id);
// Being here means either there are no pending frames, or none of the pending
// changes would be overridden by changing the subframe associated with source_id.
// Create the new pipeline
let window_size = self.pipeline(source_id).size;
let new_pipeline_id = PipelineId::new();
self.new_pipeline(new_pipeline_id, None, window_size, None, load_data);
self.push_pending_frame(new_pipeline_id, Some(source_id));
// Send message to ScriptTask that will suspend all timers
let old_pipeline = self.pipelines.get(&source_id).unwrap();
old_pipeline.freeze();
Some(new_pipeline_id)
}
}
}
fn handle_load_start_msg(&mut self, pipeline_id: &PipelineId) {
if let Some(id) = self.pipeline_to_frame_map.get(pipeline_id) {
let forward = !self.frame(*id).next.is_empty();
let back = !self.frame(*id).prev.is_empty();
self.compositor_proxy.send(ToCompositorMsg::LoadStart(back, forward));
}
}
fn handle_load_complete_msg(&mut self, pipeline_id: &PipelineId) {
let frame_id = match self.pipeline_to_frame_map.get(pipeline_id) {
Some(frame) => *frame,
None => {
debug!("frame not found for pipeline id {:?}", pipeline_id);
return
}
};
let forward = !self.frame(frame_id).next.is_empty();
let back = !self.frame(frame_id).prev.is_empty();
self.compositor_proxy.send(ToCompositorMsg::LoadComplete(back, forward));
}
fn handle_dom_load(&mut self,
pipeline_id: PipelineId) {
let mut webdriver_reset = false;
if let Some((expected_pipeline_id, ref reply_chan)) = self.webdriver.load_channel {
debug!("Sending load to WebDriver");
if expected_pipeline_id == pipeline_id {
let _ = reply_chan.send(webdriver_msg::LoadStatus::LoadComplete);
webdriver_reset = true;
}
}
if webdriver_reset {
self.webdriver.load_channel = None;
}
self.handle_subframe_loaded(pipeline_id);
}
fn handle_navigate_msg(&mut self,
pipeline_info: Option<(PipelineId, SubpageId)>,
direction: constellation_msg::NavigationDirection) {
debug!("received message to navigate {:?}", direction);
// Get the frame id associated with the pipeline that sent
// the navigate message, or use root frame id by default.
let frame_id = pipeline_info.map_or(self.root_frame_id, |(containing_pipeline_id, subpage_id)| {
let pipeline_id = self.find_subpage(containing_pipeline_id, subpage_id).id;
self.pipeline_to_frame_map.get(&pipeline_id).map(|id| *id)
}).unwrap();
// Check if the currently focused pipeline is the pipeline being replaced
// (or a child of it). This has to be done here, before the current
// frame tree is modified below.
let update_focus_pipeline = self.focused_pipeline_in_tree(frame_id);
// Get the ids for the previous and next pipelines.
let (prev_pipeline_id, next_pipeline_id) = {
let frame = self.mut_frame(frame_id);
let next = match direction {
NavigationDirection::Forward => {
match frame.next.pop() {
None => {
debug!("no next page to navigate to");
return;
},
Some(next) => {
frame.prev.push(frame.current);
next
},
}
}
NavigationDirection::Back => {
match frame.prev.pop() {
None => {
debug!("no previous page to navigate to");
return;
},
Some(prev) => {
frame.next.push(frame.current);
prev
},
}
}
};
let prev = frame.current;
frame.current = next;
(prev, next)
};
// If the currently focused pipeline is the one being changed (or a child
// of the pipeline being changed) then update the focus pipeline to be
// the replacement.
if update_focus_pipeline {
self.focus_pipeline_id = Some(next_pipeline_id);
}
// Suspend the old pipeline, and resume the new one.