aboutsummaryrefslogtreecommitdiffstats
path: root/components/devtools/actors/console.rs
blob: aedc70aaa58313e4fbd1bd7a90ebcd823c947b83 (plain) (blame)
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
/* 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/. */

/// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webconsole.js).
/// Mediates interaction between the remote web console and equivalent functionality (object
/// inspection, JS evaluation, autocompletion) in Servo.

use actor::{Actor, ActorRegistry};
use protocol::JsonPacketStream;

use devtools_traits::{EvaluateJS, NullValue, VoidValue, NumberValue, StringValue, BooleanValue};
use devtools_traits::{ActorValue, DevtoolScriptControlMsg};
use msg::constellation_msg::PipelineId;

use collections::BTreeMap;
use core::cell::RefCell;
use serialize::json::{self, Json, ToJson};
use std::io::TcpStream;
use std::num::Float;
use std::sync::mpsc::{channel, Sender};

#[derive(RustcEncodable)]
struct StartedListenersTraits {
    customNetworkRequest: bool,
}

#[derive(RustcEncodable)]
struct StartedListenersReply {
    from: String,
    nativeConsoleAPI: bool,
    startedListeners: Vec<String>,
    traits: StartedListenersTraits,
}

#[derive(RustcEncodable)]
#[allow(dead_code)]
struct ConsoleAPIMessage {
    _type: String, //FIXME: should this be __type__ instead?
}

#[derive(RustcEncodable)]
#[allow(dead_code)]
struct PageErrorMessage {
    _type: String, //FIXME: should this be __type__ instead?
    errorMessage: String,
    sourceName: String,
    lineText: String,
    lineNumber: uint,
    columnNumber: uint,
    category: String,
    timeStamp: uint,
    warning: bool,
    error: bool,
    exception: bool,
    strict: bool,
    private: bool,
}

#[derive(RustcEncodable)]
#[allow(dead_code)]
struct LogMessage {
    _type: String, //FIXME: should this be __type__ instead?
    timeStamp: uint,
    message: String,
}

#[derive(RustcEncodable)]
#[allow(dead_code)]
enum ConsoleMessageType {
    ConsoleAPIType(ConsoleAPIMessage),
    PageErrorType(PageErrorMessage),
    LogMessageType(LogMessage),
}

#[derive(RustcEncodable)]
struct GetCachedMessagesReply {
    from: String,
    messages: Vec<json::Object>,
}

#[derive(RustcEncodable)]
struct StopListenersReply {
    from: String,
    stoppedListeners: Vec<String>,
}

#[derive(RustcEncodable)]
struct AutocompleteReply {
    from: String,
    matches: Vec<String>,
    matchProp: String,
}

#[derive(RustcEncodable)]
struct EvaluateJSReply {
    from: String,
    input: String,
    result: Json,
    timestamp: uint,
    exception: Json,
    exceptionMessage: String,
    helperResult: Json,
}

pub struct ConsoleActor {
    pub name: String,
    pub pipeline: PipelineId,
    pub script_chan: Sender<DevtoolScriptControlMsg>,
    pub streams: RefCell<Vec<TcpStream>>,
}

impl Actor for ConsoleActor {
    fn name(&self) -> String {
        self.name.clone()
    }

    fn handle_message(&self,
                      _registry: &ActorRegistry,
                      msg_type: &String,
                      msg: &json::Object,
                      stream: &mut TcpStream) -> Result<bool, ()> {
        Ok(match msg_type.as_slice() {
            "getCachedMessages" => {
                let types = msg.get(&"messageTypes".to_string()).unwrap().as_array().unwrap();
                let /*mut*/ messages = vec!();
                for msg_type in types.iter() {
                    let msg_type = msg_type.as_string().unwrap();
                    match msg_type.as_slice() {
                        "ConsoleAPI" => {
                            //TODO: figure out all consoleapi properties from FFOX source
                        }

                        "PageError" => {
                            //TODO: make script error reporter pass all reported errors
                            //      to devtools and cache them for returning here.

                            /*let message = PageErrorMessage {
                                _type: msg_type.to_string(),
                                sourceName: "".to_string(),
                                lineText: "".to_string(),
                                lineNumber: 0,
                                columnNumber: 0,
                                category: "".to_string(),
                                warning: false,
                                error: true,
                                exception: false,
                                strict: false,
                                private: false,
                                timeStamp: 0,
                                errorMessage: "page error test".to_string(),
                            };
                            messages.push(json::from_str(json::encode(&message).as_slice()).unwrap().as_object().unwrap().clone());*/
                        }

                        "LogMessage" => {
                            //TODO: figure out when LogMessage is necessary
                            /*let message = LogMessage {
                                _type: msg_type.to_string(),
                                timeStamp: 0,
                                message: "log message test".to_string(),
                            };
                            messages.push(json::from_str(json::encode(&message).as_slice()).unwrap().as_object().unwrap().clone());*/
                        }

                        s => println!("unrecognized message type requested: \"{}\"", s),
                    }
                }

                let msg = GetCachedMessagesReply {
                    from: self.name(),
                    messages: messages,
                };
                stream.write_json_packet(&msg);
                true
            }

            "startListeners" => {
                //TODO: actually implement listener filters that support starting/stopping
                let msg = StartedListenersReply {
                    from: self.name(),
                    nativeConsoleAPI: true,
                    startedListeners:
                        vec!("PageError".to_string(), "ConsoleAPI".to_string()),
                    traits: StartedListenersTraits {
                        customNetworkRequest: true,
                    }
                };
                stream.write_json_packet(&msg);
                true
            }

            "stopListeners" => {
                //TODO: actually implement listener filters that support starting/stopping
                let msg = StopListenersReply {
                    from: self.name(),
                    stoppedListeners: msg.get(&"listeners".to_string())
                                         .unwrap()
                                         .as_array()
                                         .unwrap_or(&vec!())
                                         .iter()
                                         .map(|listener| listener.as_string().unwrap().to_string())
                                         .collect(),
                };
                stream.write_json_packet(&msg);
                true
            }

            //TODO: implement autocompletion like onAutocomplete in
            //      http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webconsole.js
            "autocomplete" => {
                let msg = AutocompleteReply {
                    from: self.name(),
                    matches: vec!(),
                    matchProp: "".to_string(),
                };
                stream.write_json_packet(&msg);
                true
            }

            "evaluateJS" => {
                let input = msg.get(&"text".to_string()).unwrap().as_string().unwrap().to_string();
                let (chan, port) = channel();
                self.script_chan.send(EvaluateJS(self.pipeline, input.clone(), chan)).unwrap();

                //TODO: extract conversion into protocol module or some other useful place
                let result = match try!(port.recv().map_err(|_| ())) {
                    VoidValue => {
                        let mut m = BTreeMap::new();
                        m.insert("type".to_string(), "undefined".to_string().to_json());
                        Json::Object(m)
                    }
                    NullValue => {
                        let mut m = BTreeMap::new();
                        m.insert("type".to_string(), "null".to_string().to_json());
                        Json::Object(m)
                    }
                    BooleanValue(val) => val.to_json(),
                    NumberValue(val) => {
                        if val.is_nan() {
                            let mut m = BTreeMap::new();
                            m.insert("type".to_string(), "NaN".to_string().to_json());
                            Json::Object(m)
                        } else if val.is_infinite() {
                            let mut m = BTreeMap::new();
                            if val < 0. {
                                m.insert("type".to_string(), "-Infinity".to_string().to_json());
                            } else {
                                m.insert("type".to_string(), "Infinity".to_string().to_json());
                            }
                            Json::Object(m)
                        } else if val == Float::neg_zero() {
                            let mut m = BTreeMap::new();
                            m.insert("type".to_string(), "-0".to_string().to_json());
                            Json::Object(m)
                        } else {
                            val.to_json()
                        }
                    }
                    StringValue(s) => s.to_json(),
                    ActorValue(s) => {
                        //TODO: make initial ActorValue message include these properties.
                        let mut m = BTreeMap::new();
                        m.insert("type".to_string(), "object".to_string().to_json());
                        m.insert("class".to_string(), "???".to_string().to_json());
                        m.insert("actor".to_string(), s.to_json());
                        m.insert("extensible".to_string(), true.to_json());
                        m.insert("frozen".to_string(), false.to_json());
                        m.insert("sealed".to_string(), false.to_json());
                        Json::Object(m)
                    }
                };

                //TODO: catch and return exception values from JS evaluation
                let msg = EvaluateJSReply {
                    from: self.name(),
                    input: input,
                    result: result,
                    timestamp: 0,
                    exception: Json::Object(BTreeMap::new()),
                    exceptionMessage: "".to_string(),
                    helperResult: Json::Object(BTreeMap::new()),
                };
                stream.write_json_packet(&msg);
                true
            }

            _ => false
        })
    }
}