]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitadaemon.ml
Removed dependency of Matitaweb from GTK libraries.
[helm.git] / matitaB / matita / matitadaemon.ml
1 open Printf;;
2 open Http_types;;
3
4 module Stack = Continuationals.Stack
5
6 let utf8_length = Netconversion.ustring_length `Enc_utf8
7
8 let utf8_parsed_text s floc =
9   let start, stop = HExtlib.loc_of_floc floc in
10   let len = stop - start in
11   let res = Netconversion.ustring_sub `Enc_utf8 start len s in
12   res, String.length res
13
14 (*** from matitaScript.ml ***)
15 (* let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$" *)
16
17 let eval_statement include_paths (* (buffer : GText.buffer) *) status (* script *)
18  statement
19 =
20   let ast,unparsed_text =
21     match statement with
22     | `Raw text ->
23         (* if Pcre.pmatch ~rex:only_dust_RE text then raise Margin; *)
24         let strm =
25          GrafiteParser.parsable_statement status
26           (Ulexing.from_utf8_string text) in
27         let ast = MatitaEngine.get_ast status include_paths strm in
28          ast, text
29     | `Ast (st, text) -> st, text
30   in
31   let floc = match ast with
32   | GrafiteAst.Executable (loc, _)
33   | GrafiteAst.Comment (loc, _) -> loc in
34   
35   let _,lend = HExtlib.loc_of_floc floc in 
36   let parsed_text, _parsed_text_len = 
37     utf8_parsed_text unparsed_text (HExtlib.floc_of_loc (0,lend)) in
38   let byte_parsed_text_len = String.length parsed_text in
39   let unparsed_txt' = 
40     String.sub unparsed_text byte_parsed_text_len 
41       (String.length unparsed_text - byte_parsed_text_len)
42   in
43   
44   let status = 
45     MatitaEngine.eval_ast ~include_paths ~do_heavy_checks:false status ("",0,ast)
46   in 
47   (status, parsed_text, unparsed_txt'),"",(*parsed_text_len*)
48     utf8_length parsed_text
49
50
51 let status = ref (new MatitaEngine.status "cic:/matita");;
52 let history = ref [!status];;
53 let sequent_size = ref 40;;
54
55 let include_paths = ref [];;
56
57 (* <metasenv>
58  *   <meta number="...">
59  *     <metaname>...</metaname>
60  *     <goal>...</goal>
61  *   </meta>
62  *
63  *   ...
64  * </metasenv> *)
65 let output_status s =
66   let _,_,metasenv,subst,_ = s#obj in
67   let render_switch = function 
68   | Stack.Open i -> "?" ^ (string_of_int i) 
69   | Stack.Closed i -> "<S>?" ^ (string_of_int i) ^ "</S>"
70   in
71   let int_of_switch = function
72   | Stack.Open i | Stack.Closed i -> i
73   in
74   let sequent = function
75   | Stack.Open i ->
76       let meta = List.assoc i metasenv in
77       snd (ApplyTransformation.ntxt_of_cic_sequent 
78         ~metasenv ~subst ~map_unicode_to_tex:false !sequent_size s (i,meta))
79   | Stack.Closed _ -> "This goal has already been closed."
80   in
81   let render_sequent is_loc acc depth tag (pos,sw) =
82     let metano = int_of_switch sw in
83     let markup = 
84       if is_loc then
85         (match depth, pos with
86          | 0, 0 -> "<B>" ^ (render_switch sw) ^ "</B>"
87          | 0, _ -> 
88             Printf.sprintf "<B>|<SUB>%d</SUB>: %s</B>" pos (render_switch sw)
89          | 1, pos when Stack.head_tag s#stack = `BranchTag ->
90              Printf.sprintf "|<SUB>%d</SUB> : %s" pos (render_switch sw)
91          | _ -> render_switch sw)
92       else render_switch sw
93     in
94     prerr_endline "pippo1";
95     let markup = 
96       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () markup in
97     let markup = "<metaname>" ^ markup ^ "</metaname>" in
98     prerr_endline "pippo2";
99     let sequent =
100       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () (sequent sw)
101     in      
102     let txt0 = "<goal>" ^ sequent ^ "</goal>" in
103     "<meta number=\"" ^ (string_of_int metano) ^ "\">" ^ markup ^
104     txt0 ^ "</meta>" ^ acc
105   in
106   let res = "<metasenv>" ^
107     (Stack.fold 
108       ~env:(render_sequent true) ~cont:(render_sequent false) 
109       ~todo:(render_sequent false) "" s#stack) ^
110     "</metasenv>"
111   in 
112   prerr_endline ("sending metasenv:\n" ^ res); res
113 ;;
114
115 (* let html_of_status s =
116   let _,_,metasenv,subst,_ = s#obj in
117   let txt = List.fold_left 
118     (fun acc (nmeta,_ as meta) ->
119        let txt0 = snd (ApplyTransformation.ntxt_of_cic_sequent 
120          ~metasenv ~subst ~map_unicode_to_tex:false 80 s meta)
121        in
122        prerr_endline ("### txt0 = " ^ txt0);
123       ("<B>Goal ?" ^ (string_of_int nmeta) ^ "</B>\n" ^ txt0)::acc)
124     [] metasenv
125   in
126   String.concat "\n\n" txt
127 ;; *)
128
129 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*";;
130
131 let first_line s =
132   let s = Pcre.replace ~rex:heading_nl_RE s in
133   try
134     let nl_pos = String.index s '\n' in
135     String.sub s 0 nl_pos
136   with Not_found -> s
137 ;;
138
139 let read_file fname =
140   let chan = open_in fname in
141   let lines = ref [] in
142   (try
143      while true do
144        lines := input_line chan :: !lines
145      done;
146    with End_of_file -> close_in chan);
147   String.concat "\n" (List.rev !lines)
148 ;;
149
150 let load_index outchan =
151   let s = read_file "index.html" in
152   Http_daemon.respond ~headers:["Content-Type", "text/html"] ~code:(`Code 200) ~body:s outchan
153 ;;
154
155 let load_doc filename outchan =
156   let s = read_file filename in
157   let is_png = 
158     try String.sub filename (String.length filename - 4) 4 = ".png"
159     with Invalid_argument _ -> false
160   in
161   let contenttype = if is_png then "image/png" else "text/html" in
162   Http_daemon.respond ~headers:["Content-Type", contenttype] ~code:(`Code 200) ~body:s outchan
163 ;;
164
165 let retrieve (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
166   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
167   cgi # set_header 
168     ~cache:`No_cache 
169     ~content_type:"text/xml; charset=\"utf-8\""
170     ();
171   let filename = cgi # argument_value "file" in
172   prerr_endline ("reading file " ^ filename);
173   let body = 
174     Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () 
175       (read_file filename) in
176   prerr_endline ("sending:\nBEGIN\n" ^ body ^ "\nEND");
177   let body = "<file>" ^ body ^ "</file>" in
178   let baseuri, incpaths = 
179     try 
180       let root, baseuri, _fname, _tgt = 
181         Librarian.baseuri_of_script ~include_paths:[] filename in 
182       let includes =
183        try
184         Str.split (Str.regexp " ") 
185          (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
186        with Not_found -> []
187       in
188       let rc = root :: includes in
189        List.iter (HLog.debug) rc; baseuri, rc
190      with 
191        Librarian.NoRootFor _ | Librarian.FileNotFound _ -> "",[] in
192   include_paths := incpaths;
193   status := (!status)#set_baseuri baseuri;
194   cgi#out_channel#output_string body;
195   cgi#out_channel#commit_work()
196 ;;
197
198 let advance0 text =
199   let (st,new_statements,new_unparsed),(* newtext TODO *) _,parsed_len =
200        (* try *)
201          eval_statement !include_paths (*buffer*) !status (`Raw text)
202        (* with End_of_file -> raise Margin *)
203      in
204   status := st;
205   history := st :: !history;
206   parsed_len, new_unparsed
207
208
209 (* returns the length of the executed text and an html representation of the
210  * current metasenv*)
211 let advance (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
212   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
213   cgi # set_header 
214     ~cache:`No_cache 
215     ~content_type:"text/xml; charset=\"utf-8\""
216     ();
217   let text = cgi#argument_value "body" in
218   prerr_endline ("body =\n" ^ text);
219   let parsed_len, new_unparsed = advance0 text in
220   let txt = output_status !status in
221   let body = 
222      "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\" />" ^ txt 
223      ^ "</response>"
224   in 
225   prerr_endline ("sending advance response:\n" ^ body);
226   cgi#out_channel#output_string body;
227   cgi#out_channel#commit_work()
228 ;;
229
230 let gotoBottom (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
231   let rec aux parsed_len text =
232     try
233       prerr_endline ("evaluating: " ^ first_line text);
234       let plen,new_unparsed = advance0 text in
235       aux (parsed_len+plen) new_unparsed
236     with 
237     | _ -> parsed_len
238   in 
239   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
240   cgi # set_header 
241     ~cache:`No_cache 
242     ~content_type:"text/xml; charset=\"utf-8\""
243     ();
244   let text = cgi#argument_value "body" in
245   prerr_endline ("body =\n" ^ text);
246   let parsed_len = aux 0 text in
247   let txt = output_status !status in
248   let body = 
249      "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\" />" ^ txt 
250      ^ "</response>"
251   in 
252   prerr_endline ("sending goto bottom response:\n" ^ body);
253   cgi#out_channel#output_string body;
254   cgi#out_channel#commit_work() 
255 ;;
256
257 let retract (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
258   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
259   cgi # set_header 
260     ~cache:`No_cache 
261     ~content_type:"text/xml; charset=\"utf-8\""
262     ();
263   let new_history,new_status =
264      match !history with
265        _::(status::_ as history) ->
266         history, status
267     | [_] -> (prerr_endline "singleton";failwith "retract")
268     | _ -> (prerr_endline "nil"; assert false) in
269   NCicLibrary.time_travel !status;
270   history := new_history;
271   status := new_status;
272   let body = output_status !status in
273   cgi#out_channel#output_string body;
274   cgi#out_channel#commit_work() 
275 ;;
276
277
278 open Netcgi1_compat.Netcgi_types;;
279
280 (**********************************************************************)
281 (* Create the webserver                                               *)
282 (**********************************************************************)
283
284
285 let start() =
286   let (opt_list, cmdline_cfg) = Netplex_main.args() in
287
288   let use_mt = ref true in
289
290   let opt_list' =
291     [ "-mt", Arg.Set use_mt,
292       "  Use multi-threading instead of multi-processing"
293     ] @ opt_list in
294
295   Arg.parse 
296     opt_list'
297     (fun s -> raise (Arg.Bad ("Don't know what to do with: " ^ s)))
298     "usage: netplex [options]";
299   let parallelizer = 
300     if !use_mt then
301       Netplex_mt.mt()     (* multi-threading *)
302     else
303       Netplex_mp.mp() in  (* multi-processing *)
304 (*
305   let adder =
306     { Nethttpd_services.dyn_handler = (fun _ -> process1);
307       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
308       dyn_uri = None;                 (* not needed *)
309       dyn_translator = (fun _ -> ""); (* not needed *)
310       dyn_accept_all_conditionals = false;
311     } in
312 *)
313   let do_advance =
314     { Nethttpd_services.dyn_handler = (fun _ -> advance);
315       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
316       dyn_uri = None;                 (* not needed *)
317       dyn_translator = (fun _ -> ""); (* not needed *)
318       dyn_accept_all_conditionals = false;
319     } in
320   let do_retract =
321     { Nethttpd_services.dyn_handler = (fun _ -> retract);
322       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
323       dyn_uri = None;                 (* not needed *)
324       dyn_translator = (fun _ -> ""); (* not needed *)
325       dyn_accept_all_conditionals = false;
326     } in
327   let goto_bottom =
328     { Nethttpd_services.dyn_handler = (fun _ -> gotoBottom);
329       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
330       dyn_uri = None;                 (* not needed *)
331       dyn_translator = (fun _ -> ""); (* not needed *)
332       dyn_accept_all_conditionals = false;
333     } in
334   let retrieve =
335     { Nethttpd_services.dyn_handler = (fun _ -> retrieve);
336       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
337       dyn_uri = None;                 (* not needed *)
338       dyn_translator = (fun _ -> ""); (* not needed *)
339       dyn_accept_all_conditionals = false;
340     } in
341   
342   let nethttpd_factory = 
343     Nethttpd_plex.nethttpd_factory
344       ~handlers:[ "advance", do_advance
345                 ; "retract", do_retract
346                 ; "bottom", goto_bottom
347                 ; "open", retrieve ]
348       () in
349   MatitaInit.initialize_all ();
350   Netplex_main.startup
351     parallelizer
352     Netplex_log.logger_factories   (* allow all built-in logging styles *)
353     Netplex_workload.workload_manager_factories (* ... all ways of workload management *)
354     [ nethttpd_factory ]           (* make this nethttpd available *)
355     cmdline_cfg
356 ;;
357
358 Sys.set_signal Sys.sigpipe Sys.Signal_ignore;
359 start();;