]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitadaemon.ml
Multi-user matita: changed the status object to include a ``user'' method
[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 (* FIXME: currently hard coded to single user mode *)
51 let status = ref (new MatitaEngine.status (Some "ricciott") "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   prerr_endline ("after advance0 history.length = " ^ string_of_int (List.length !history));
207   parsed_len, new_unparsed
208
209
210 (* returns the length of the executed text and an html representation of the
211  * current metasenv*)
212 let advance (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
213   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
214   cgi # set_header 
215     ~cache:`No_cache 
216     ~content_type:"text/xml; charset=\"utf-8\""
217     ();
218   let text = cgi#argument_value "body" in
219   prerr_endline ("body =\n" ^ text);
220   let parsed_len, new_unparsed = advance0 text in
221   let txt = output_status !status in
222   let body = 
223      "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\" />" ^ txt 
224      ^ "</response>"
225   in 
226   prerr_endline ("sending advance response:\n" ^ body);
227   cgi#out_channel#output_string body;
228   cgi#out_channel#commit_work()
229 ;;
230
231 let gotoBottom (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
232   let rec aux parsed_len text =
233     try
234       prerr_endline ("evaluating: " ^ first_line text);
235       let plen,new_unparsed = advance0 text in
236       aux (parsed_len+plen) new_unparsed
237     with 
238     | _ -> parsed_len
239   in 
240   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
241   cgi # set_header 
242     ~cache:`No_cache 
243     ~content_type:"text/xml; charset=\"utf-8\""
244     ();
245   let text = cgi#argument_value "body" in
246   prerr_endline ("body =\n" ^ text);
247   let parsed_len = aux 0 text in
248   let txt = output_status !status in
249   let body = 
250      "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\" />" ^ txt 
251      ^ "</response>"
252   in 
253   prerr_endline ("sending goto bottom response:\n" ^ body);
254   cgi#out_channel#output_string body;
255   cgi#out_channel#commit_work() 
256 ;;
257
258 let retract (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
259   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
260   cgi # set_header 
261     ~cache:`No_cache 
262     ~content_type:"text/xml; charset=\"utf-8\""
263     ();
264   let new_history,new_status =
265      match !history with
266        _::(status::_ as history) ->
267         history, status
268     | [_] -> (prerr_endline "singleton";failwith "retract")
269     | _ -> (prerr_endline "nil"; assert false) in
270   NCicLibrary.time_travel new_status;
271   history := new_history;
272   status := new_status;
273   prerr_endline ("after retract history.length = " ^ string_of_int (List.length !history));
274   let body = output_status !status in
275   cgi#out_channel#output_string body;
276   cgi#out_channel#commit_work() 
277 ;;
278
279
280 open Netcgi1_compat.Netcgi_types;;
281
282 (**********************************************************************)
283 (* Create the webserver                                               *)
284 (**********************************************************************)
285
286
287 let start() =
288   let (opt_list, cmdline_cfg) = Netplex_main.args() in
289
290   let use_mt = ref true in
291
292   let opt_list' =
293     [ "-mt", Arg.Set use_mt,
294       "  Use multi-threading instead of multi-processing"
295     ] @ opt_list in
296
297   Arg.parse 
298     opt_list'
299     (fun s -> raise (Arg.Bad ("Don't know what to do with: " ^ s)))
300     "usage: netplex [options]";
301   let parallelizer = 
302     if !use_mt then
303       Netplex_mt.mt()     (* multi-threading *)
304     else
305       Netplex_mp.mp() in  (* multi-processing *)
306 (*
307   let adder =
308     { Nethttpd_services.dyn_handler = (fun _ -> process1);
309       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
310       dyn_uri = None;                 (* not needed *)
311       dyn_translator = (fun _ -> ""); (* not needed *)
312       dyn_accept_all_conditionals = false;
313     } in
314 *)
315   let do_advance =
316     { Nethttpd_services.dyn_handler = (fun _ -> advance);
317       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
318       dyn_uri = None;                 (* not needed *)
319       dyn_translator = (fun _ -> ""); (* not needed *)
320       dyn_accept_all_conditionals = false;
321     } in
322   let do_retract =
323     { Nethttpd_services.dyn_handler = (fun _ -> retract);
324       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
325       dyn_uri = None;                 (* not needed *)
326       dyn_translator = (fun _ -> ""); (* not needed *)
327       dyn_accept_all_conditionals = false;
328     } in
329   let goto_bottom =
330     { Nethttpd_services.dyn_handler = (fun _ -> gotoBottom);
331       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
332       dyn_uri = None;                 (* not needed *)
333       dyn_translator = (fun _ -> ""); (* not needed *)
334       dyn_accept_all_conditionals = false;
335     } in
336   let retrieve =
337     { Nethttpd_services.dyn_handler = (fun _ -> retrieve);
338       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
339       dyn_uri = None;                 (* not needed *)
340       dyn_translator = (fun _ -> ""); (* not needed *)
341       dyn_accept_all_conditionals = false;
342     } in
343   
344   let nethttpd_factory = 
345     Nethttpd_plex.nethttpd_factory
346       ~handlers:[ "advance", do_advance
347                 ; "retract", do_retract
348                 ; "bottom", goto_bottom
349                 ; "open", retrieve ]
350       () in
351   MatitaInit.initialize_all ();
352   (* test begin *)
353   MatitaAuthentication.add_user "ricciott" "pippo123";
354   MatitaAuthentication.add_user "asperti" "pluto456";
355   (* test end *)
356   Netplex_main.startup
357     parallelizer
358     Netplex_log.logger_factories   (* allow all built-in logging styles *)
359     Netplex_workload.workload_manager_factories (* ... all ways of workload management *)
360     [ nethttpd_factory ]           (* make this nethttpd available *)
361     cmdline_cfg
362 ;;
363
364 Sys.set_signal Sys.sigpipe Sys.Signal_ignore;
365 start();;