]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/gTopLevel.ml
e4af786ceb2e4e81a83f6f2c109f4bb881cf6ec4
[helm.git] / helm / gTopLevel / gTopLevel.ml
1 (* Copyright (C) 2000-2002, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (******************************************************************************)
27 (*                                                                            *)
28 (*                               PROJECT HELM                                 *)
29 (*                                                                            *)
30 (*                Claudio Sacerdoti Coen <sacerdot@cs.unibo.it>               *)
31 (*                                 06/01/2002                                 *)
32 (*                                                                            *)
33 (*                                                                            *)
34 (******************************************************************************)
35
36
37 (* CSC: quick fix: a function from [uri#xpointer(path)] to [uri#path] *)
38 let wrong_xpointer_format_from_wrong_xpointer_format' uri =
39  try
40   let index_sharp =  String.index uri '#' in
41   let index_rest = index_sharp + 10 in
42    let baseuri = String.sub uri 0 index_sharp in
43    let rest = String.sub uri index_rest (String.length uri - index_rest - 1) in
44     baseuri ^ "#" ^ rest
45  with Not_found -> uri
46 ;;
47
48 (* GLOBAL CONSTANTS *)
49
50 let helmns = Gdome.domString "http://www.cs.unibo.it/helm";;
51 let xlinkns = Gdome.domString "http://www.w3.org/1999/xlink";;
52
53 let htmlheader =
54  "<html>" ^
55  " <body bgColor=\"white\">"
56 ;;
57
58 let htmlfooter =
59  " </body>" ^
60  "</html>"
61 ;;
62
63 (*
64 let prooffile = "/home/tassi/miohelm/tmp/currentproof";;
65 let prooffile = "/public/sacerdot/currentproof";;
66 *)
67
68 let prooffile = "/public/sacerdot/currentproof";;
69 let prooffiletype = "/public/sacerdot/currentprooftype";;
70
71 (*CSC: the getter should handle the innertypes, not the FS *)
72 (*
73 let innertypesfile = "/home/tassi/miohelm/tmp/innertypes";;
74 let innertypesfile = "/public/sacerdot/innertypes";;
75 *)
76
77 let innertypesfile = "/public/sacerdot/innertypes";;
78 let constanttypefile = "/public/sacerdot/constanttype";;
79
80 let empty_id_to_uris = ([],function _ -> None);;
81
82
83 (* GLOBAL REFERENCES (USED BY CALLBACKS) *)
84
85 let htmlheader_and_content = ref htmlheader;;
86
87 let current_cic_infos = ref None;;
88 let current_goal_infos = ref None;;
89 let current_scratch_infos = ref None;;
90
91 let id_to_uris = ref empty_id_to_uris;;
92
93 let check_term = ref (fun _ _ _ -> assert false);;
94 let mml_of_cic_term_ref = ref (fun _ _ -> assert false);;
95
96 exception RenderingWindowsNotInitialized;;
97
98 let set_rendering_window,rendering_window =
99  let rendering_window_ref = ref None in
100   (function rw -> rendering_window_ref := Some rw),
101   (function () ->
102     match !rendering_window_ref with
103        None -> raise RenderingWindowsNotInitialized
104      | Some rw -> rw
105   )
106 ;;
107
108 exception SettingsWindowsNotInitialized;;
109
110 let set_settings_window,settings_window =
111  let settings_window_ref = ref None in
112   (function rw -> settings_window_ref := Some rw),
113   (function () ->
114     match !settings_window_ref with
115        None -> raise SettingsWindowsNotInitialized
116      | Some rw -> rw
117   )
118 ;;
119
120 exception OutputHtmlNotInitialized;;
121
122 let set_outputhtml,outputhtml =
123  let outputhtml_ref = ref None in
124   (function rw -> outputhtml_ref := Some rw),
125   (function () ->
126     match !outputhtml_ref with
127        None -> raise OutputHtmlNotInitialized
128      | Some outputhtml -> outputhtml
129   )
130 ;;
131
132 exception QedSetSensitiveNotInitialized;;
133 let qed_set_sensitive =
134  ref (function _ -> raise QedSetSensitiveNotInitialized)
135 ;;
136
137 exception SaveSetSensitiveNotInitialized;;
138 let save_set_sensitive =
139  ref (function _ -> raise SaveSetSensitiveNotInitialized)
140 ;;
141
142 (* COMMAND LINE OPTIONS *)
143
144 let usedb = ref true
145
146 let argspec =
147   [
148     "-nodb", Arg.Clear usedb, "disable use of MathQL DB"
149   ]
150 in
151 Arg.parse argspec ignore ""
152
153 (* A WIDGET TO ENTER CIC TERMS *)
154
155 class term_editor ?packing ?width ?height ?isnotempty_callback () =
156  let input = GEdit.text ~editable:true ?width ?height ?packing () in
157  let _ =
158   match isnotempty_callback with
159      None -> ()
160    | Some callback ->
161       ignore(input#connect#changed (function () -> callback (input#length > 0)))
162  in
163 object(self)
164  method coerce = input#coerce
165  method reset =
166   input#delete_text 0 input#length
167  (* CSC: txt is now a string, but should be of type Cic.term *)
168  method set_term txt =
169   self#reset ;
170   ignore ((input#insert_text txt) ~pos:0)
171  (* CSC: this method should disappear *)
172  method get_as_string =
173   input#get_chars 0 input#length
174  method get_term ~context ~metasenv =
175   let lexbuf = Lexing.from_string (input#get_chars 0 input#length) in
176    CicTextualParserContext.main ~context ~metasenv CicTextualLexer.token lexbuf
177 end
178 ;;
179
180 (* MISC FUNCTIONS *)
181
182 exception IllFormedUri of string;;
183
184 let cic_textual_parser_uri_of_string uri' =
185  try
186   (* Constant *)
187   if String.sub uri' (String.length uri' - 4) 4 = ".con" then
188    CicTextualParser0.ConUri (UriManager.uri_of_string uri')
189   else
190    if String.sub uri' (String.length uri' - 4) 4 = ".var" then
191     CicTextualParser0.VarUri (UriManager.uri_of_string uri')
192    else
193     (try
194       (* Inductive Type *)
195       let uri'',typeno = CicTextualLexer.indtyuri_of_uri uri' in
196        CicTextualParser0.IndTyUri (uri'',typeno)
197      with
198       _ ->
199        (* Constructor of an Inductive Type *)
200        let uri'',typeno,consno =
201         CicTextualLexer.indconuri_of_uri uri'
202        in
203         CicTextualParser0.IndConUri (uri'',typeno,consno)
204     )
205  with
206   _ -> raise (IllFormedUri uri')
207 ;;
208
209 let term_of_cic_textual_parser_uri uri =
210  let module C = Cic in
211  let module CTP = CicTextualParser0 in
212   match uri with
213      CTP.ConUri uri -> C.Const (uri,[])
214    | CTP.VarUri uri -> C.Var (uri,[])
215    | CTP.IndTyUri (uri,tyno) -> C.MutInd (uri,tyno,[])
216    | CTP.IndConUri (uri,tyno,consno) -> C.MutConstruct (uri,tyno,consno,[])
217 ;;
218
219 let string_of_cic_textual_parser_uri uri =
220  let module C = Cic in
221  let module CTP = CicTextualParser0 in
222   let uri' =
223    match uri with
224       CTP.ConUri uri -> UriManager.string_of_uri uri
225     | CTP.VarUri uri -> UriManager.string_of_uri uri
226     | CTP.IndTyUri (uri,tyno) ->
227        UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1)
228     | CTP.IndConUri (uri,tyno,consno) ->
229        UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1) ^ "/" ^
230         string_of_int consno
231   in
232    (* 4 = String.length "cic:" *)
233    String.sub uri' 4 (String.length uri' - 4)
234 ;;
235
236 let output_html outputhtml msg =
237  htmlheader_and_content := !htmlheader_and_content ^ msg ;
238  outputhtml#source (!htmlheader_and_content ^ htmlfooter) ;
239  outputhtml#set_topline (-1)
240 ;;
241
242 (* UTILITY FUNCTIONS TO DISAMBIGUATE AN URI *)
243
244 (* Check window *)
245
246 let check_window outputhtml uris =
247  let window =
248   GWindow.window
249    ~width:800 ~modal:true ~title:"Check" ~border_width:2 () in
250  let notebook =
251   GPack.notebook ~scrollable:true ~packing:window#add () in
252  window#show () ;
253  let render_terms =
254   List.map
255    (function uri ->
256      let scrolled_window =
257       GBin.scrolled_window ~border_width:10
258        ~packing:
259          (notebook#append_page ~tab_label:((GMisc.label ~text:uri ())#coerce))
260        ()
261      in
262       lazy 
263        (let mmlwidget =
264          GMathView.math_view
265           ~packing:scrolled_window#add ~width:400 ~height:280 () in
266         let expr =
267          let term =
268           term_of_cic_textual_parser_uri (cic_textual_parser_uri_of_string uri)
269          in
270           (Cic.Cast (term, CicTypeChecker.type_of_aux' [] [] term))
271         in
272          try
273           let mml = !mml_of_cic_term_ref 111 expr in
274 prerr_endline ("### " ^ CicPp.ppterm expr) ;
275            mmlwidget#load_tree ~dom:mml
276          with
277           e ->
278            output_html outputhtml
279             ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
280        )
281    ) uris
282  in
283   ignore
284    (notebook#connect#switch_page
285      (function i -> Lazy.force (List.nth render_terms i)))
286 ;;
287
288 exception NoChoice;;
289
290 let
291  interactive_user_uri_choice ~selection_mode ?(ok="Ok") ~title ~msg uris
292 =
293  let choices = ref [] in
294  let chosen = ref false in
295  let window =
296   GWindow.dialog ~modal:true ~title ~width:600 () in
297  let lMessage =
298   GMisc.label ~text:msg
299    ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
300  let scrolled_window =
301   GBin.scrolled_window ~border_width:10
302    ~packing:(window#vbox#pack ~expand:true ~fill:true ~padding:5) () in
303  let clist =
304   let expected_height = 18 * List.length uris in
305    let height = if expected_height > 400 then 400 else expected_height in
306     GList.clist ~columns:1 ~packing:scrolled_window#add
307      ~height ~selection_mode () in
308  let _ = List.map (function x -> clist#append [x]) uris in
309  let hbox2 =
310   GPack.hbox ~border_width:0
311    ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
312  let explain_label =
313   GMisc.label ~text:"None of the above. Try this one:"
314    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
315  let manual_input =
316   GEdit.entry ~editable:true
317    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
318  let hbox =
319   GPack.hbox ~border_width:0 ~packing:window#action_area#add () in
320  let okb =
321   GButton.button ~label:ok
322    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
323  let _ = okb#misc#set_sensitive false in
324  let checkb =
325   GButton.button ~label:"Check"
326    ~packing:(hbox#pack ~padding:5) () in
327  let _ = checkb#misc#set_sensitive false in
328  let cancelb =
329   GButton.button ~label:"Abort"
330    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
331  (* actions *)
332  let check_callback () =
333   assert (List.length !choices > 0) ;
334   check_window (outputhtml ()) !choices
335  in
336   ignore (window#connect#destroy GMain.Main.quit) ;
337   ignore (cancelb#connect#clicked window#destroy) ;
338   ignore
339    (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
340   ignore (checkb#connect#clicked check_callback) ;
341   ignore
342    (clist#connect#select_row
343      (fun ~row ~column ~event ->
344        checkb#misc#set_sensitive true ;
345        okb#misc#set_sensitive true ;
346        choices := (List.nth uris row)::!choices)) ;
347   ignore
348    (clist#connect#unselect_row
349      (fun ~row ~column ~event ->
350        choices :=
351         List.filter (function uri -> uri != (List.nth uris row)) !choices)) ;
352   ignore
353    (manual_input#connect#changed
354      (fun _ ->
355        if manual_input#text = "" then
356         begin
357          choices := [] ;
358          checkb#misc#set_sensitive false ;
359          okb#misc#set_sensitive false ;
360          clist#misc#set_sensitive true
361         end
362        else
363         begin
364          choices := [manual_input#text] ;
365          clist#unselect_all () ;
366          checkb#misc#set_sensitive true ;
367          okb#misc#set_sensitive true ;
368          clist#misc#set_sensitive false
369         end));
370   window#set_position `CENTER ;
371   window#show () ;
372   GMain.Main.main () ;
373   if !chosen && List.length !choices > 0 then
374    !choices
375   else
376    raise NoChoice
377 ;;
378
379 let interactive_interpretation_choice interpretations =
380  let chosen = ref None in
381  let window =
382   GWindow.window
383    ~modal:true ~title:"Ambiguous well-typed input." ~border_width:2 () in
384  let vbox = GPack.vbox ~packing:window#add () in
385  let lMessage =
386   GMisc.label
387    ~text:
388     ("Ambiguous input since there are many well-typed interpretations." ^
389      " Please, choose one of them.")
390    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
391  let notebook =
392   GPack.notebook ~scrollable:true
393    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
394  let _ =
395   List.map
396    (function interpretation ->
397      let clist =
398       let expected_height = 18 * List.length interpretation in
399        let height = if expected_height > 400 then 400 else expected_height in
400         GList.clist ~columns:2 ~packing:notebook#append_page ~height
401          ~titles:["id" ; "URI"] ()
402      in
403       ignore
404        (List.map
405          (function (id,uri) ->
406            let n = clist#append [id;uri] in
407             clist#set_row ~selectable:false n
408          ) interpretation
409        ) ;
410       clist#columns_autosize ()
411    ) interpretations in
412  let hbox =
413   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
414  let okb =
415   GButton.button ~label:"Ok"
416    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
417  let cancelb =
418   GButton.button ~label:"Abort"
419    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
420  (* actions *)
421  ignore (window#connect#destroy GMain.Main.quit) ;
422  ignore (cancelb#connect#clicked window#destroy) ;
423  ignore
424   (okb#connect#clicked
425     (function () -> chosen := Some notebook#current_page ; window#destroy ())) ;
426  window#set_position `CENTER ;
427  window#show () ;
428  GMain.Main.main () ;
429  match !chosen with
430     None -> raise NoChoice
431   | Some n -> n
432 ;;
433
434
435 (* MISC FUNCTIONS *)
436
437 (* CSC: IMPERATIVE AND NOT VERY CLEAN, TO GET THE LAST ISSUED QUERY *)
438 let get_last_query = 
439  let query = ref "" in
440   MQueryGenerator.set_confirm_query
441    (function q -> query := MQueryUtil.text_of_query q ; true) ;
442   function result -> !query ^ " <h1>Result:</h1> " ^ MQueryUtil.text_of_result result "<br>"
443 ;;
444
445 let domImpl = Gdome.domImplementation ();;
446
447 let parseStyle name =
448  let style =
449   domImpl#createDocumentFromURI
450 (*
451    ~uri:("http://phd.cs.unibo.it:8081/getxslt?uri=" ^ name) ?mode:None
452 *)
453    ~uri:("styles/" ^ name) ()
454  in
455   Gdome_xslt.processStylesheet style
456 ;;
457
458 let d_c = parseStyle "drop_coercions.xsl";;
459 let tc1 = parseStyle "objtheorycontent.xsl";;
460 let hc2 = parseStyle "content_to_html.xsl";;
461 let l   = parseStyle "link.xsl";;
462
463 let c1 = parseStyle "rootcontent.xsl";;
464 let g  = parseStyle "genmmlid.xsl";;
465 let c2 = parseStyle "annotatedpres.xsl";;
466
467
468 let getterURL = Configuration.getter_url;;
469 let processorURL = Configuration.processor_url;;
470
471 let mml_styles = [d_c ; c1 ; g ; c2 ; l];;
472 let mml_args ~explode_all =
473  ("explodeall",(if explode_all then "true()" else "false()"))::
474   ["processorURL", "'" ^ processorURL ^ "'" ;
475    "getterURL", "'" ^ getterURL ^ "'" ;
476    "draw_graphURL", "'http%3A//phd.cs.unibo.it%3A8083/'" ;
477    "uri_set_queueURL", "'http%3A//phd.cs.unibo.it%3A8084/'" ;
478    "UNICODEvsSYMBOL", "'symbol'" ;
479    "doctype-public", "'-//W3C//DTD%20XHTML%201.0%20Transitional//EN'" ;
480    "encoding", "'iso-8859-1'" ;
481    "media-type", "'text/html'" ;
482    "keys", "'d_c%2CC1%2CG%2CC2%2CL'" ;
483    "interfaceURL", "'http%3A//phd.cs.unibo.it/helm/html/cic/index.html'" ;
484    "naturalLanguage", "'yes'" ;
485    "annotations", "'no'" ;
486    "URLs_or_URIs", "'URIs'" ;
487    "topurl", "'http://phd.cs.unibo.it/helm'" ;
488    "CICURI", "'cic:/Coq/Init/Datatypes/bool_ind.con'" ]
489 ;;
490
491 let sequent_styles = [d_c ; c1 ; g ; c2 ; l];;
492 let sequent_args =
493  ["processorURL", "'" ^ processorURL ^ "'" ;
494   "getterURL", "'" ^ getterURL ^ "'" ;
495   "draw_graphURL", "'http%3A//phd.cs.unibo.it%3A8083/'" ;
496   "uri_set_queueURL", "'http%3A//phd.cs.unibo.it%3A8084/'" ;
497   "UNICODEvsSYMBOL", "'symbol'" ;
498   "doctype-public", "'-//W3C//DTD%20XHTML%201.0%20Transitional//EN'" ;
499   "encoding", "'iso-8859-1'" ;
500   "media-type", "'text/html'" ;
501   "keys", "'d_c%2CC1%2CG%2CC2%2CL'" ;
502   "interfaceURL", "'http%3A//phd.cs.unibo.it/helm/html/cic/index.html'" ;
503   "naturalLanguage", "'no'" ;
504   "annotations", "'no'" ;
505   "explodeall", "true()" ;
506   "URLs_or_URIs", "'URIs'" ;
507   "topurl", "'http://phd.cs.unibo.it/helm'" ;
508   "CICURI", "'cic:/Coq/Init/Datatypes/bool_ind.con'" ]
509 ;;
510
511 let parse_file filename =
512  let inch = open_in filename in
513   let rec read_lines () =
514    try
515     let line = input_line inch in
516      line ^ read_lines ()
517    with
518     End_of_file -> ""
519   in
520    read_lines ()
521 ;;
522
523 let applyStylesheets input styles args =
524  List.fold_left (fun i style -> Gdome_xslt.applyStylesheet i style args)
525   input styles
526 ;;
527
528 let
529  mml_of_cic_object ~explode_all uri annobj ids_to_inner_sorts ids_to_inner_types
530 =
531 (*CSC: ????????????????? *)
532  let xml, bodyxml =
533   Cic2Xml.print_object uri ~ids_to_inner_sorts annobj 
534  in
535  let xmlinnertypes =
536   Cic2Xml.print_inner_types uri ~ids_to_inner_sorts
537    ~ids_to_inner_types
538  in
539   let input =
540    match bodyxml with
541       None -> Xml2Gdome.document_of_xml domImpl xml
542     | Some bodyxml' ->
543        Xml.pp xml (Some constanttypefile) ;
544        Xml2Gdome.document_of_xml domImpl bodyxml'
545   in
546 (*CSC: We save the innertypes to disk so that we can retrieve them in the  *)
547 (*CSC: stylesheet. This DOES NOT work when UWOBO and/or the getter are not *)
548 (*CSC: local.                                                              *)
549    Xml.pp xmlinnertypes (Some innertypesfile) ;
550    let output = applyStylesheets input mml_styles (mml_args ~explode_all) in
551     output
552 ;;
553
554 let
555  save_object_to_disk uri annobj ids_to_inner_sorts ids_to_inner_types pathname
556 =
557  let name =
558   let struri = UriManager.string_of_uri uri in
559   let idx = (String.rindex struri '/') + 1 in
560    String.sub struri idx (String.length struri - idx)
561  in
562   let path = pathname ^ "/" ^ name in
563   let xml, bodyxml =
564    Cic2Xml.print_object uri ~ids_to_inner_sorts annobj 
565   in
566   let xmlinnertypes =
567    Cic2Xml.print_inner_types uri ~ids_to_inner_sorts
568     ~ids_to_inner_types
569   in
570    (* innertypes *)
571    let innertypesuri = UriManager.innertypesuri_of_uri uri in
572     Xml.pp ~quiet:true xmlinnertypes (Some (path ^ ".types.xml")) ;
573     Getter.register innertypesuri
574      (Configuration.annotations_url ^
575        Str.replace_first (Str.regexp "^cic:") ""
576         (UriManager.string_of_uri innertypesuri) ^ ".xml"
577      ) ;
578     (* constant type / variable / mutual inductive types definition *)
579     Xml.pp ~quiet:true xml (Some (path ^ ".xml")) ;
580     Getter.register uri
581      (Configuration.annotations_url ^
582        Str.replace_first (Str.regexp "^cic:") ""
583         (UriManager.string_of_uri uri) ^ ".xml"
584      ) ;
585     match bodyxml with
586        None -> ()
587      | Some bodyxml' ->
588         (* constant body *)
589         let bodyuri =
590          match UriManager.bodyuri_of_uri uri with
591             None -> assert false
592           | Some bodyuri -> bodyuri
593         in
594          Xml.pp ~quiet:true bodyxml' (Some (path ^ ".body.xml")) ;
595          Getter.register bodyuri
596           (Configuration.annotations_url ^
597             Str.replace_first (Str.regexp "^cic:") ""
598              (UriManager.string_of_uri bodyuri) ^ ".xml"
599           )
600 ;;
601
602
603 (* CALLBACKS *)
604
605 exception RefreshSequentException of exn;;
606 exception RefreshProofException of exn;;
607
608 let refresh_proof (output : GMathView.math_view) =
609  try
610   let uri,currentproof =
611    match !ProofEngine.proof with
612       None -> assert false
613     | Some (uri,metasenv,bo,ty) ->
614        !qed_set_sensitive (List.length metasenv = 0) ;
615        (*CSC: Wrong: [] is just plainly wrong *)
616        uri,(Cic.CurrentProof (UriManager.name_of_uri uri, metasenv, bo, ty, []))
617   in
618    let
619     (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
620      ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
621    =
622     Cic2acic.acic_object_of_cic_object currentproof
623    in
624     let mml =
625      mml_of_cic_object ~explode_all:true uri acic ids_to_inner_sorts
626       ids_to_inner_types
627     in
628      output#load_tree mml ;
629      current_cic_infos :=
630       Some (ids_to_terms,ids_to_father_ids,ids_to_conjectures,ids_to_hypotheses)
631  with
632   e ->
633  match !ProofEngine.proof with
634     None -> assert false
635   | Some (uri,metasenv,bo,ty) ->
636 prerr_endline ("Offending proof: " ^ CicPp.ppobj (Cic.CurrentProof ("questa",metasenv,bo,ty,[]))) ; flush stderr ;
637    raise (RefreshProofException e)
638 ;;
639
640 let refresh_sequent ?(empty_notebook=true) notebook =
641  try
642   match !ProofEngine.goal with
643      None ->
644       if empty_notebook then
645        begin 
646         notebook#remove_all_pages ~skip_switch_page_event:false ;
647         notebook#set_empty_page
648        end
649       else
650        notebook#proofw#unload
651    | Some metano ->
652       let metasenv =
653        match !ProofEngine.proof with
654           None -> assert false
655         | Some (_,metasenv,_,_) -> metasenv
656       in
657       let currentsequent = List.find (function (m,_,_) -> m=metano) metasenv in
658        let sequent_gdome,ids_to_terms,ids_to_father_ids,ids_to_hypotheses =
659         SequentPp.XmlPp.print_sequent metasenv currentsequent
660        in
661         let regenerate_notebook () = 
662          let skip_switch_page_event =
663           match metasenv with
664              (m,_,_)::_ when m = metano -> false
665            | _ -> true
666          in
667           notebook#remove_all_pages ~skip_switch_page_event ;
668           List.iter (function (m,_,_) -> notebook#add_page m) metasenv ;
669         in
670           if empty_notebook then
671            begin
672             regenerate_notebook () ;
673             notebook#set_current_page ~may_skip_switch_page_event:false metano
674            end
675           else
676            begin
677             let sequent_doc = Xml2Gdome.document_of_xml domImpl sequent_gdome in
678             let sequent_mml =
679              applyStylesheets sequent_doc sequent_styles sequent_args
680             in
681              notebook#set_current_page ~may_skip_switch_page_event:true metano;
682              notebook#proofw#load_tree ~dom:sequent_mml
683            end ;
684           current_goal_infos :=
685            Some (ids_to_terms,ids_to_father_ids,ids_to_hypotheses)
686  with
687   e ->
688 let metano =
689   match !ProofEngine.goal with
690      None -> assert false
691    | Some m -> m
692 in
693 let metasenv =
694  match !ProofEngine.proof with
695     None -> assert false
696   | Some (_,metasenv,_,_) -> metasenv
697 in
698 try
699 let currentsequent = List.find (function (m,_,_) -> m=metano) metasenv in
700 prerr_endline ("Offending sequent: " ^ SequentPp.TextualPp.print_sequent currentsequent) ; flush stderr ;
701    raise (RefreshSequentException e)
702 with Not_found -> prerr_endline ("Offending sequent " ^ string_of_int metano ^ " unkown."); raise (RefreshSequentException e)
703 ;;
704
705 (*
706 ignore(domImpl#saveDocumentToFile ~doc:sequent_doc
707  ~name:"/home/galata/miohelm/guruguru1" ~indent:true ()) ;
708 *)
709
710 let mml_of_cic_term metano term =
711  let metasenv =
712   match !ProofEngine.proof with
713      None -> []
714    | Some (_,metasenv,_,_) -> metasenv
715  in
716  let context =
717   match !ProofEngine.goal with
718      None -> []
719    | Some metano ->
720       let (_,canonical_context,_) =
721        List.find (function (m,_,_) -> m=metano) metasenv
722       in
723        canonical_context
724  in
725    let sequent_gdome,ids_to_terms,ids_to_father_ids,ids_to_hypotheses =
726     SequentPp.XmlPp.print_sequent metasenv (metano,context,term)
727    in
728     let sequent_doc =
729      Xml2Gdome.document_of_xml domImpl sequent_gdome
730     in
731      let res =
732       applyStylesheets sequent_doc sequent_styles sequent_args ;
733      in
734       current_scratch_infos :=
735        Some (term,ids_to_terms,ids_to_father_ids,ids_to_hypotheses) ;
736       res
737 ;;
738
739 exception OpenConjecturesStillThere;;
740 exception WrongProof;;
741
742 let pathname_of_annuri uristring =
743  Configuration.annotations_dir ^    
744   Str.replace_first (Str.regexp "^cic:") "" uristring
745 ;;
746
747 let make_dirs dirpath =
748  ignore (Unix.system ("mkdir -p " ^ dirpath))
749 ;;
750
751 let qed () =
752  match !ProofEngine.proof with
753     None -> assert false
754   | Some (uri,[],bo,ty) ->
755      if
756       CicReduction.are_convertible []
757        (CicTypeChecker.type_of_aux' [] [] bo) ty
758      then
759       begin
760        (*CSC: Wrong: [] is just plainly wrong *)
761        let proof = Cic.Constant (UriManager.name_of_uri uri,Some bo,ty,[]) in
762         let
763          (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
764           ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
765         =
766          Cic2acic.acic_object_of_cic_object proof
767         in
768          let mml =
769           mml_of_cic_object ~explode_all:false uri acic ids_to_inner_sorts
770            ids_to_inner_types
771          in
772           ((rendering_window ())#output : GMathView.math_view)#load_tree mml ;
773           !qed_set_sensitive false ;
774           (* let's save the theorem and register it to the getter *) 
775           let pathname = pathname_of_annuri (UriManager.buri_of_uri uri) in
776           make_dirs pathname ;
777           save_object_to_disk uri acic ids_to_inner_sorts ids_to_inner_types
778            pathname ;
779           current_cic_infos :=
780            Some
781             (ids_to_terms,ids_to_father_ids,ids_to_conjectures,
782              ids_to_hypotheses)
783       end
784      else
785       raise WrongProof
786   | _ -> raise OpenConjecturesStillThere
787 ;;
788
789 (*????
790 let dtdname = "http://www.cs.unibo.it/helm/dtd/cic.dtd";;
791 let dtdname = "/home/tassi/miohelm/helm/dtd/cic.dtd";;
792 *)
793 let dtdname = "/projects/helm/V7_mowgli/dtd/cic.dtd";;
794
795 let save () =
796  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
797   match !ProofEngine.proof with
798      None -> assert false
799    | Some (uri, metasenv, bo, ty) ->
800       let currentproof =
801        (*CSC: Wrong: [] is just plainly wrong *)
802        Cic.CurrentProof (UriManager.name_of_uri uri,metasenv,bo,ty,[])
803       in
804        let (acurrentproof,_,_,ids_to_inner_sorts,_,_,_) =
805         Cic2acic.acic_object_of_cic_object currentproof
806        in
807         let xml, bodyxml =
808          match Cic2Xml.print_object uri ~ids_to_inner_sorts acurrentproof with
809             xml,Some bodyxml -> xml,bodyxml
810           | _,None -> assert false
811         in
812          Xml.pp ~quiet:true xml (Some prooffiletype) ;
813          output_html outputhtml
814           ("<h1 color=\"Green\">Current proof type saved to " ^
815            prooffiletype ^ "</h1>") ;
816          Xml.pp ~quiet:true bodyxml (Some prooffile) ;
817          output_html outputhtml
818           ("<h1 color=\"Green\">Current proof body saved to " ^
819            prooffile ^ "</h1>")
820 ;;
821
822 (* Used to typecheck the loaded proofs *)
823 let typecheck_loaded_proof metasenv bo ty =
824  let module T = CicTypeChecker in
825   ignore (
826    List.fold_left
827     (fun metasenv ((_,context,ty) as conj) ->
828       ignore (T.type_of_aux' metasenv context ty) ;
829       metasenv @ [conj]
830     ) [] metasenv) ;
831   ignore (T.type_of_aux' metasenv [] ty) ;
832   ignore (T.type_of_aux' metasenv [] bo)
833 ;;
834
835 let load () =
836  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
837  let output = ((rendering_window ())#output : GMathView.math_view) in
838  let notebook = (rendering_window ())#notebook in
839   try
840    match 
841     GToolbox.input_string ~title:"Load Unfinished Proof" ~text:"/dummy.con"
842      "Choose an URI:"
843    with
844       None -> raise NoChoice
845     | Some uri0 ->
846        let uri = UriManager.uri_of_string ("cic:" ^ uri0) in
847         match CicParser.obj_of_xml prooffiletype (Some prooffile) with
848            Cic.CurrentProof (_,metasenv,bo,ty,_) ->
849             typecheck_loaded_proof metasenv bo ty ;
850             ProofEngine.proof :=
851              Some (uri, metasenv, bo, ty) ;
852             ProofEngine.goal :=
853              (match metasenv with
854                  [] -> None
855                | (metano,_,_)::_ -> Some metano
856              ) ;
857             refresh_proof output ;
858             refresh_sequent notebook ;
859              output_html outputhtml
860               ("<h1 color=\"Green\">Current proof type loaded from " ^
861                 prooffiletype ^ "</h1>") ;
862              output_html outputhtml
863               ("<h1 color=\"Green\">Current proof body loaded from " ^
864                 prooffile ^ "</h1>") ;
865             !save_set_sensitive true
866          | _ -> assert false
867   with
868      RefreshSequentException e ->
869       output_html outputhtml
870        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
871         "sequent: " ^ Printexc.to_string e ^ "</h1>")
872    | RefreshProofException e ->
873       output_html outputhtml
874        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
875         "proof: " ^ Printexc.to_string e ^ "</h1>")
876    | e ->
877       output_html outputhtml
878        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
879 ;;
880
881 let edit_aliases () =
882  let chosen = ref false in
883  let window =
884   GWindow.window
885    ~width:400 ~modal:true ~title:"Edit Aliases..." ~border_width:2 () in
886  let vbox =
887   GPack.vbox ~border_width:0 ~packing:window#add () in
888  let scrolled_window =
889   GBin.scrolled_window ~border_width:10
890    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
891  let input = GEdit.text ~editable:true ~width:400 ~height:100
892    ~packing:scrolled_window#add () in
893  let hbox =
894   GPack.hbox ~border_width:0
895    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
896  let okb =
897   GButton.button ~label:"Ok"
898    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
899  let cancelb =
900   GButton.button ~label:"Cancel"
901    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
902  ignore (window#connect#destroy GMain.Main.quit) ;
903  ignore (cancelb#connect#clicked window#destroy) ;
904  ignore
905   (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
906  let dom,resolve_id = !id_to_uris in
907   ignore
908    (input#insert_text ~pos:0
909     (String.concat "\n"
910       (List.map
911         (function v ->
912           let uri =
913            match resolve_id v with
914               None -> assert false
915             | Some uri -> uri
916           in
917            "alias " ^ v ^ " " ^
918              (string_of_cic_textual_parser_uri uri)
919         ) dom))) ;
920   window#show () ;
921   GMain.Main.main () ;
922   if !chosen then
923    let dom,resolve_id =
924     let inputtext = input#get_chars 0 input#length in
925     let regexpr =
926      let alfa = "[a-zA-Z_-]" in
927      let digit = "[0-9]" in
928      let ident = alfa ^ "\(" ^ alfa ^ "\|" ^ digit ^ "\)*" in
929      let blanks = "\( \|\t\|\n\)+" in
930      let nonblanks = "[^ \t\n]+" in
931      let uri = "/\(" ^ ident ^ "/\)*" ^ nonblanks in (* not very strict check *)
932       Str.regexp
933        ("alias" ^ blanks ^ "\(" ^ ident ^ "\)" ^ blanks ^ "\(" ^ uri ^ "\)")
934     in
935      let rec aux n =
936       try
937        let n' = Str.search_forward regexpr inputtext n in
938         let id = Str.matched_group 2 inputtext in
939         let uri =
940          cic_textual_parser_uri_of_string
941           ("cic:" ^ (Str.matched_group 5 inputtext))
942         in
943          let dom,resolve_id = aux (n' + 1) in
944           if List.mem id dom then
945            dom,resolve_id
946           else
947            id::dom,
948             (function id' -> if id = id' then Some uri else resolve_id id')
949       with
950        Not_found -> empty_id_to_uris
951      in
952       aux 0
953    in
954     id_to_uris := dom,resolve_id
955 ;;
956
957 let proveit () =
958  let module L = LogicalOperations in
959  let module G = Gdome in
960  let notebook = (rendering_window ())#notebook in
961  let output = (rendering_window ())#output in
962  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
963   match (rendering_window ())#output#get_selection with
964     Some node ->
965      let xpath =
966       ((node : Gdome.element)#getAttributeNS
967       (*CSC: OCAML DIVERGE
968       ((element : G.element)#getAttributeNS
969       *)
970         ~namespaceURI:helmns
971         ~localName:(G.domString "xref"))#to_string
972      in
973       if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
974       else
975        begin
976         try
977          match !current_cic_infos with
978             Some (ids_to_terms, ids_to_father_ids, _, _) ->
979              let id = xpath in
980               L.to_sequent id ids_to_terms ids_to_father_ids ;
981               refresh_proof output ;
982               refresh_sequent notebook
983           | None -> assert false (* "ERROR: No current term!!!" *)
984         with
985            RefreshSequentException e ->
986             output_html outputhtml
987              ("<h1 color=\"red\">Exception raised during the refresh of the " ^
988               "sequent: " ^ Printexc.to_string e ^ "</h1>")
989          | RefreshProofException e ->
990             output_html outputhtml
991              ("<h1 color=\"red\">Exception raised during the refresh of the " ^
992               "proof: " ^ Printexc.to_string e ^ "</h1>")
993          | e ->
994             output_html outputhtml
995              ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
996        end
997   | None -> assert false (* "ERROR: No selection!!!" *)
998 ;;
999
1000 let focus () =
1001  let module L = LogicalOperations in
1002  let module G = Gdome in
1003  let notebook = (rendering_window ())#notebook in
1004  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1005   match (rendering_window ())#output#get_selection with
1006     Some node ->
1007      let xpath =
1008       ((node : Gdome.element)#getAttributeNS
1009       (*CSC: OCAML DIVERGE
1010       ((element : G.element)#getAttributeNS
1011       *)
1012         ~namespaceURI:helmns
1013         ~localName:(G.domString "xref"))#to_string
1014      in
1015       if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
1016       else
1017        begin
1018         try
1019          match !current_cic_infos with
1020             Some (ids_to_terms, ids_to_father_ids, _, _) ->
1021              let id = xpath in
1022               L.focus id ids_to_terms ids_to_father_ids ;
1023               refresh_sequent notebook
1024           | None -> assert false (* "ERROR: No current term!!!" *)
1025         with
1026            RefreshSequentException e ->
1027             output_html outputhtml
1028              ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1029               "sequent: " ^ Printexc.to_string e ^ "</h1>")
1030          | RefreshProofException e ->
1031             output_html outputhtml
1032              ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1033               "proof: " ^ Printexc.to_string e ^ "</h1>")
1034          | e ->
1035             output_html outputhtml
1036              ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
1037        end
1038   | None -> assert false (* "ERROR: No selection!!!" *)
1039 ;;
1040
1041 exception NoPrevGoal;;
1042 exception NoNextGoal;;
1043
1044 let setgoal metano =
1045  let module L = LogicalOperations in
1046  let module G = Gdome in
1047  let notebook = (rendering_window ())#notebook in
1048  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1049   let metasenv =
1050    match !ProofEngine.proof with
1051       None -> assert false
1052     | Some (_,metasenv,_,_) -> metasenv
1053   in
1054    try
1055     refresh_sequent ~empty_notebook:false notebook
1056    with
1057       RefreshSequentException e ->
1058        output_html outputhtml
1059         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1060          "sequent: " ^ Printexc.to_string e ^ "</h1>")
1061     | e ->
1062        output_html outputhtml
1063         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
1064 ;;
1065
1066 let show_in_show_window, show_in_show_window_callback =
1067  let window =
1068   GWindow.window ~width:800 ~border_width:2 () in
1069  let scrolled_window =
1070   GBin.scrolled_window ~border_width:10 ~packing:window#add () in
1071  let mmlwidget =
1072   GMathView.math_view ~packing:scrolled_window#add ~width:600 ~height:400 () in
1073  let _ = window#event#connect#delete (fun _ -> window#misc#hide () ; true ) in
1074  let href = Gdome.domString "href" in
1075   let show_in_show_window uri =
1076    let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1077     try
1078      CicTypeChecker.typecheck uri ;
1079      let obj = CicEnvironment.get_cooked_obj uri in
1080       let
1081        (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
1082         ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
1083       =
1084        Cic2acic.acic_object_of_cic_object obj
1085       in
1086        let mml =
1087         mml_of_cic_object ~explode_all:false uri acic ids_to_inner_sorts
1088          ids_to_inner_types
1089        in
1090         window#set_title (UriManager.string_of_uri uri) ;
1091         window#misc#hide () ; window#show () ;
1092         mmlwidget#load_tree mml ;
1093     with
1094      e ->
1095       output_html outputhtml
1096        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1097   in
1098    let show_in_show_window_callback mmlwidget (n : Gdome.element) =
1099     if n#hasAttributeNS ~namespaceURI:xlinkns ~localName:href then
1100      let uri =
1101       (n#getAttributeNS ~namespaceURI:xlinkns ~localName:href)#to_string
1102      in 
1103       show_in_show_window (UriManager.uri_of_string uri)
1104     else
1105      if mmlwidget#get_action <> None then
1106       mmlwidget#action_toggle
1107    in
1108     let _ =
1109      mmlwidget#connect#clicked (show_in_show_window_callback mmlwidget)
1110     in
1111      show_in_show_window, show_in_show_window_callback
1112 ;;
1113
1114 exception NoObjectsLocated;;
1115
1116 let user_uri_choice ~title ~msg uris =
1117  let uri =
1118   match uris with
1119      [] -> raise NoObjectsLocated
1120    | [uri] -> uri
1121    | uris ->
1122       match
1123        interactive_user_uri_choice ~selection_mode:`SINGLE ~title ~msg uris
1124       with
1125          [uri] -> uri
1126        | _ -> assert false
1127  in
1128   String.sub uri 4 (String.length uri - 4)
1129 ;;
1130
1131 let locate_callback id =
1132  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1133  let result = MQueryGenerator.locate id in
1134  let uris =
1135   List.map
1136    (function uri,_ -> wrong_xpointer_format_from_wrong_xpointer_format' uri)
1137    result in
1138  let html =
1139   (" <h1>Locate Query: </h1><pre>" ^ get_last_query result ^ "</pre>")
1140  in
1141   output_html outputhtml html ;
1142   user_uri_choice ~title:"Ambiguous input."
1143    ~msg:
1144      ("Ambiguous input \"" ^ id ^
1145       "\". Please, choose one interpetation:")
1146    uris
1147 ;;
1148
1149 let locate () =
1150  let inputt = ((rendering_window ())#inputt : term_editor) in
1151  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1152    try
1153     match
1154      GToolbox.input_string ~title:"Locate" "Enter an identifier to locate:"
1155     with
1156        None -> raise NoChoice
1157      | Some input ->
1158         let uri = locate_callback input in
1159          inputt#set_term uri
1160    with
1161     e ->
1162      output_html outputhtml
1163       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
1164 ;;
1165
1166 let input_or_locate_uri ~title =
1167  let uri = ref None in
1168  let window =
1169   GWindow.window
1170    ~width:400 ~modal:true ~title ~border_width:2 () in
1171  let vbox = GPack.vbox ~packing:window#add () in
1172  let hbox1 =
1173   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1174  let _ =
1175   GMisc.label ~text:"Enter a valid URI:" ~packing:(hbox1#pack ~padding:5) () in
1176  let manual_input =
1177   GEdit.entry ~editable:true
1178    ~packing:(hbox1#pack ~expand:true ~fill:true ~padding:5) () in
1179  let checkb =
1180   GButton.button ~label:"Check"
1181    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1182  let _ = checkb#misc#set_sensitive false in
1183  let hbox2 =
1184   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1185  let _ =
1186   GMisc.label ~text:"You can also enter an indentifier to locate:"
1187    ~packing:(hbox2#pack ~padding:5) () in
1188  let locate_input =
1189   GEdit.entry ~editable:true
1190    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
1191  let locateb =
1192   GButton.button ~label:"Locate"
1193    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
1194  let _ = locateb#misc#set_sensitive false in
1195  let hbox3 =
1196   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1197  let okb =
1198   GButton.button ~label:"Ok"
1199    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
1200  let _ = okb#misc#set_sensitive false in
1201  let cancelb =
1202   GButton.button ~label:"Cancel"
1203    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) ()
1204  in
1205   ignore (window#connect#destroy GMain.Main.quit) ;
1206   ignore
1207    (cancelb#connect#clicked (function () -> uri := None ; window#destroy ())) ;
1208   let check_callback () =
1209    let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1210    let uri = "cic:" ^ manual_input#text in
1211     try
1212       ignore (Getter.resolve (UriManager.uri_of_string uri)) ;
1213       output_html outputhtml "<h1 color=\"Green\">OK</h1>" ;
1214       true
1215     with
1216        Getter.Unresolved ->
1217         output_html outputhtml
1218          ("<h1 color=\"Red\">URI " ^ uri ^
1219           " does not correspond to any object.</h1>") ;
1220         false
1221      | UriManager.IllFormedUri _ ->
1222         output_html outputhtml
1223          ("<h1 color=\"Red\">URI " ^ uri ^ " is not well-formed.</h1>") ;
1224         false
1225      | e ->
1226         output_html outputhtml
1227          ("<h1 color=\"Red\">" ^ Printexc.to_string e ^ "</h1>") ;
1228         false
1229   in
1230   ignore
1231    (okb#connect#clicked
1232      (function () ->
1233        if check_callback () then
1234         begin
1235          uri := Some manual_input#text ;
1236          window#destroy ()
1237         end
1238    )) ;
1239   ignore (checkb#connect#clicked (function () -> ignore (check_callback ()))) ;
1240   ignore
1241    (manual_input#connect#changed
1242      (fun _ ->
1243        if manual_input#text = "" then
1244         begin
1245          checkb#misc#set_sensitive false ;
1246          okb#misc#set_sensitive false
1247         end
1248        else
1249         begin
1250          checkb#misc#set_sensitive true ;
1251          okb#misc#set_sensitive true
1252         end));
1253   ignore
1254    (locate_input#connect#changed
1255      (fun _ -> locateb#misc#set_sensitive (locate_input#text <> ""))) ;
1256   ignore
1257    (locateb#connect#clicked
1258      (function () ->
1259        let id = locate_input#text in
1260         manual_input#set_text (locate_callback id) ;
1261         locate_input#delete_text 0 (String.length id)
1262    )) ;
1263   window#show () ;
1264   GMain.Main.main () ;
1265   match !uri with
1266      None -> raise NoChoice
1267    | Some uri -> UriManager.uri_of_string ("cic:" ^ uri)
1268 ;;
1269
1270 let locate_one_id id =
1271  let result = MQueryGenerator.locate id in
1272  let uris =
1273   List.map
1274    (function uri,_ ->
1275      wrong_xpointer_format_from_wrong_xpointer_format' uri
1276    ) result in
1277  let html= " <h1>Locate Query: </h1><pre>" ^ get_last_query result ^ "</pre>" in
1278   output_html (rendering_window ())#outputhtml html ;
1279   let uris' =
1280    match uris with
1281       [] ->
1282        [UriManager.string_of_uri
1283          (input_or_locate_uri ~title:("URI matching \"" ^ id ^ "\" unknown."))]
1284     | [uri] -> [uri]
1285     | _ ->
1286       interactive_user_uri_choice
1287        ~selection_mode:`EXTENDED
1288        ~ok:"Try every selection."
1289        ~title:"Ambiguous input."
1290        ~msg:
1291          ("Ambiguous input \"" ^ id ^
1292           "\". Please, choose one or more interpretations:")
1293        uris
1294   in
1295    List.map cic_textual_parser_uri_of_string uris'
1296 ;;
1297
1298 exception ThereDoesNotExistAnyWellTypedInterpretationOfTheInput;;
1299 exception AmbiguousInput;;
1300
1301 let disambiguate_input context metasenv dom mk_metasenv_and_expr =
1302  let known_ids,resolve_id = !id_to_uris in
1303  let dom' =
1304   let rec filter =
1305    function
1306       [] -> []
1307     | he::tl ->
1308        if List.mem he known_ids then filter tl else he::(filter tl)
1309   in
1310    filter dom
1311  in
1312   (* for each id in dom' we get the list of uris associated to it *)
1313   let list_of_uris = List.map locate_one_id dom' in
1314   (* and now we compute the list of all possible assignments from id to uris *)
1315   let resolve_ids =
1316    let rec aux ids list_of_uris =
1317     match ids,list_of_uris with
1318        [],[] -> [resolve_id]
1319      | id::idtl,uris::uristl ->
1320         let resolves = aux idtl uristl in
1321          List.concat
1322           (List.map
1323             (function uri ->
1324               List.map
1325                (function f ->
1326                  function id' -> if id = id' then Some uri else f id'
1327                ) resolves
1328             ) uris
1329           )
1330      | _,_ -> assert false
1331    in
1332     aux dom' list_of_uris
1333   in
1334    let tests_no = List.length resolve_ids in
1335     if tests_no > 1 then
1336      output_html (outputhtml ())
1337       ("<h1>Disambiguation phase started: " ^
1338         string_of_int (List.length resolve_ids) ^ " cases will be tried.") ;
1339    (* now we select only the ones that generates well-typed terms *)
1340    let resolve_ids' =
1341     let rec filter =
1342      function
1343         [] -> []
1344       | resolve::tl ->
1345          let metasenv',expr = mk_metasenv_and_expr resolve in
1346           try
1347 (*CSC: Bug here: we do not try to typecheck also the metasenv' *)
1348            ignore
1349             (CicTypeChecker.type_of_aux' metasenv context expr) ;
1350            resolve::(filter tl)
1351           with
1352            _ -> filter tl
1353     in
1354      filter resolve_ids
1355    in
1356     let resolve_id' =
1357      match resolve_ids' with
1358         [] -> raise ThereDoesNotExistAnyWellTypedInterpretationOfTheInput
1359       | [resolve_id] -> resolve_id
1360       | _ ->
1361         let choices =
1362          List.map
1363           (function resolve ->
1364             List.map
1365              (function id ->
1366                id,
1367                 match resolve id with
1368                    None -> assert false
1369                  | Some uri ->
1370                     match uri with
1371                        CicTextualParser0.ConUri uri
1372                      | CicTextualParser0.VarUri uri ->
1373                         UriManager.string_of_uri uri
1374                      | CicTextualParser0.IndTyUri (uri,tyno) ->
1375                         UriManager.string_of_uri uri ^ "#xpointer(1/" ^
1376                          string_of_int (tyno+1) ^ ")"
1377                      | CicTextualParser0.IndConUri (uri,tyno,consno) ->
1378                         UriManager.string_of_uri uri ^ "#xpointer(1/" ^
1379                          string_of_int (tyno+1) ^ "/" ^ string_of_int consno ^                           ")"
1380              ) dom
1381           ) resolve_ids'
1382         in
1383          let index = interactive_interpretation_choice choices in
1384           List.nth resolve_ids' index
1385     in
1386      id_to_uris := known_ids @ dom', resolve_id' ;
1387      mk_metasenv_and_expr resolve_id'
1388 ;;
1389
1390 exception UriAlreadyInUse;;
1391 exception NotAUriToAConstant;;
1392
1393 let new_proof () =
1394  let inputt = ((rendering_window ())#inputt : term_editor) in
1395  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1396  let output = ((rendering_window ())#output : GMathView.math_view) in
1397  let notebook = (rendering_window ())#notebook in
1398
1399  let chosen = ref false in
1400  let get_parsed = ref (function _ -> assert false) in
1401  let get_uri = ref (function _ -> assert false) in
1402  let non_empty_type = ref false in
1403  let window =
1404   GWindow.window
1405    ~width:600 ~modal:true ~title:"New Proof or Definition"
1406    ~border_width:2 () in
1407  let vbox = GPack.vbox ~packing:window#add () in
1408  let hbox =
1409   GPack.hbox ~border_width:0
1410    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1411  let _ =
1412   GMisc.label ~text:"Enter the URI for the new theorem or definition:"
1413    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1414  let uri_entry =
1415   GEdit.entry ~editable:true
1416    ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1417  let hbox1 =
1418   GPack.hbox ~border_width:0
1419    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1420  let _ =
1421   GMisc.label ~text:"Enter the theorem or definition type:"
1422    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1423  let scrolled_window =
1424   GBin.scrolled_window ~border_width:5
1425    ~packing:(vbox#pack ~expand:true ~padding:0) () in
1426  (* the content of the scrolled_window is moved below (see comment) *)
1427  let hbox =
1428   GPack.hbox ~border_width:0
1429    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1430  let okb =
1431   GButton.button ~label:"Ok"
1432    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1433  let _ = okb#misc#set_sensitive false in
1434  let cancelb =
1435   GButton.button ~label:"Cancel"
1436    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1437  (* moved here to have visibility of the ok button *)
1438  let newinputt =
1439   new term_editor ~width:400 ~height:100 ~packing:scrolled_window#add ()
1440    ~isnotempty_callback:
1441     (function b ->
1442       non_empty_type := b ;
1443       okb#misc#set_sensitive (b && uri_entry#text <> ""))
1444  in
1445  let _ =
1446   newinputt#set_term inputt#get_as_string ;
1447   inputt#reset in
1448  let _ =
1449   uri_entry#connect#changed
1450    (function () ->
1451      okb#misc#set_sensitive (!non_empty_type && uri_entry#text <> ""))
1452  in
1453  ignore (window#connect#destroy GMain.Main.quit) ;
1454  ignore (cancelb#connect#clicked window#destroy) ;
1455  ignore
1456   (okb#connect#clicked
1457     (function () ->
1458       chosen := true ;
1459       try
1460        let parsed = newinputt#get_term [] [] in
1461        let uristr = "cic:" ^ uri_entry#text in
1462        let uri = UriManager.uri_of_string uristr in
1463         if String.sub uristr (String.length uristr - 4) 4 <> ".con" then
1464          raise NotAUriToAConstant
1465         else
1466          begin
1467           try
1468            ignore (Getter.resolve uri) ;
1469            raise UriAlreadyInUse
1470           with
1471            Getter.Unresolved ->
1472             get_parsed := (function () -> parsed) ;
1473             get_uri := (function () -> uri) ; 
1474             window#destroy ()
1475          end
1476       with
1477        e ->
1478         output_html outputhtml
1479          ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1480   )) ;
1481  window#show () ;
1482  GMain.Main.main () ;
1483  if !chosen then
1484   try
1485    let dom,mk_metasenv_and_expr = !get_parsed () in
1486     let metasenv,expr =
1487      disambiguate_input [] [] dom mk_metasenv_and_expr
1488     in
1489      let _  = CicTypeChecker.type_of_aux' metasenv [] expr in
1490       ProofEngine.proof :=
1491        Some (!get_uri (), (1,[],expr)::metasenv, Cic.Meta (1,[]), expr) ;
1492       ProofEngine.goal := Some 1 ;
1493       refresh_sequent notebook ;
1494       refresh_proof output ;
1495       !save_set_sensitive true ;
1496       inputt#reset
1497   with
1498      RefreshSequentException e ->
1499       output_html outputhtml
1500        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1501         "sequent: " ^ Printexc.to_string e ^ "</h1>")
1502    | RefreshProofException e ->
1503       output_html outputhtml
1504        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1505         "proof: " ^ Printexc.to_string e ^ "</h1>")
1506    | e ->
1507       output_html outputhtml
1508        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1509 ;;
1510
1511 let check_term_in_scratch scratch_window metasenv context expr = 
1512  try
1513   let ty  = CicTypeChecker.type_of_aux' metasenv context expr in
1514    let mml = mml_of_cic_term 111 (Cic.Cast (expr,ty)) in
1515 prerr_endline ("### " ^ CicPp.ppterm expr ^ " ==> " ^ CicPp.ppterm ty) ;
1516     scratch_window#show () ;
1517     scratch_window#mmlwidget#load_tree ~dom:mml
1518  with
1519   e ->
1520    print_endline ("? " ^ CicPp.ppterm expr) ;
1521    raise e
1522 ;;
1523
1524 let check scratch_window () =
1525  let inputt = ((rendering_window ())#inputt : term_editor) in
1526  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1527   let metasenv =
1528    match !ProofEngine.proof with
1529       None -> []
1530     | Some (_,metasenv,_,_) -> metasenv
1531   in
1532   let context,names_context =
1533    let context =
1534     match !ProofEngine.goal with
1535        None -> []
1536      | Some metano ->
1537         let (_,canonical_context,_) =
1538          List.find (function (m,_,_) -> m=metano) metasenv
1539         in
1540          canonical_context
1541    in
1542     context,
1543     List.map
1544      (function
1545          Some (n,_) -> Some n
1546        | None -> None
1547      ) context
1548   in
1549    try
1550     let dom,mk_metasenv_and_expr = inputt#get_term names_context metasenv in
1551      let (metasenv',expr) =
1552       disambiguate_input context metasenv dom mk_metasenv_and_expr
1553      in
1554       check_term_in_scratch scratch_window metasenv' context expr
1555    with
1556     e ->
1557      output_html outputhtml
1558       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1559 ;;
1560
1561
1562 (***********************)
1563 (*       TACTICS       *)
1564 (***********************)
1565
1566 let call_tactic tactic () =
1567  let notebook = (rendering_window ())#notebook in
1568  let output = ((rendering_window ())#output : GMathView.math_view) in
1569  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1570  let savedproof = !ProofEngine.proof in
1571  let savedgoal  = !ProofEngine.goal in
1572   begin
1573    try
1574     tactic () ;
1575     refresh_sequent notebook ;
1576     refresh_proof output
1577    with
1578       RefreshSequentException e ->
1579        output_html outputhtml
1580         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1581          "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1582        ProofEngine.proof := savedproof ;
1583        ProofEngine.goal := savedgoal ;
1584        refresh_sequent notebook
1585     | RefreshProofException e ->
1586        output_html outputhtml
1587         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1588          "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1589        ProofEngine.proof := savedproof ;
1590        ProofEngine.goal := savedgoal ;
1591        refresh_sequent notebook ;
1592        refresh_proof output
1593     | e ->
1594        output_html outputhtml
1595         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1596        ProofEngine.proof := savedproof ;
1597        ProofEngine.goal := savedgoal ;
1598   end
1599 ;;
1600
1601 let call_tactic_with_input tactic () =
1602  let notebook = (rendering_window ())#notebook in
1603  let output = ((rendering_window ())#output : GMathView.math_view) in
1604  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1605  let inputt = ((rendering_window ())#inputt : term_editor) in
1606  let savedproof = !ProofEngine.proof in
1607  let savedgoal  = !ProofEngine.goal in
1608   let uri,metasenv,bo,ty =
1609    match !ProofEngine.proof with
1610       None -> assert false
1611     | Some (uri,metasenv,bo,ty) -> uri,metasenv,bo,ty
1612   in
1613    let canonical_context =
1614     match !ProofEngine.goal with
1615        None -> assert false
1616      | Some metano ->
1617         let (_,canonical_context,_) =
1618          List.find (function (m,_,_) -> m=metano) metasenv
1619         in
1620          canonical_context
1621    in
1622    let context =
1623     List.map
1624      (function
1625          Some (n,_) -> Some n
1626        | None -> None
1627      ) canonical_context
1628    in
1629     try
1630      let dom,mk_metasenv_and_expr = inputt#get_term context metasenv in
1631       let (metasenv',expr) =
1632        disambiguate_input canonical_context metasenv dom mk_metasenv_and_expr
1633       in
1634        ProofEngine.proof := Some (uri,metasenv',bo,ty) ;
1635        tactic expr ;
1636        refresh_sequent notebook ;
1637        refresh_proof output ;
1638        inputt#reset
1639     with
1640        RefreshSequentException e ->
1641         output_html outputhtml
1642          ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1643           "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1644         ProofEngine.proof := savedproof ;
1645         ProofEngine.goal := savedgoal ;
1646         refresh_sequent notebook
1647      | RefreshProofException e ->
1648         output_html outputhtml
1649          ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1650           "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1651         ProofEngine.proof := savedproof ;
1652         ProofEngine.goal := savedgoal ;
1653         refresh_sequent notebook ;
1654         refresh_proof output
1655      | e ->
1656         output_html outputhtml
1657          ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1658         ProofEngine.proof := savedproof ;
1659         ProofEngine.goal := savedgoal ;
1660 ;;
1661
1662 let call_tactic_with_goal_input tactic () =
1663  let module L = LogicalOperations in
1664  let module G = Gdome in
1665   let notebook = (rendering_window ())#notebook in
1666   let output = ((rendering_window ())#output : GMathView.math_view) in
1667   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1668   let savedproof = !ProofEngine.proof in
1669   let savedgoal  = !ProofEngine.goal in
1670    match notebook#proofw#get_selection with
1671      Some node ->
1672       let xpath =
1673        ((node : Gdome.element)#getAttributeNS
1674          ~namespaceURI:helmns
1675          ~localName:(G.domString "xref"))#to_string
1676       in
1677        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
1678        else
1679         begin
1680          try
1681           match !current_goal_infos with
1682              Some (ids_to_terms, ids_to_father_ids,_) ->
1683               let id = xpath in
1684                tactic (Hashtbl.find ids_to_terms id) ;
1685                refresh_sequent notebook ;
1686                refresh_proof output
1687            | None -> assert false (* "ERROR: No current term!!!" *)
1688          with
1689             RefreshSequentException e ->
1690              output_html outputhtml
1691               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1692                "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1693              ProofEngine.proof := savedproof ;
1694              ProofEngine.goal := savedgoal ;
1695              refresh_sequent notebook
1696           | RefreshProofException e ->
1697              output_html outputhtml
1698               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1699                "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1700              ProofEngine.proof := savedproof ;
1701              ProofEngine.goal := savedgoal ;
1702              refresh_sequent notebook ;
1703              refresh_proof output
1704           | e ->
1705              output_html outputhtml
1706               ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1707              ProofEngine.proof := savedproof ;
1708              ProofEngine.goal := savedgoal ;
1709         end
1710    | None ->
1711       output_html outputhtml
1712        ("<h1 color=\"red\">No term selected</h1>")
1713 ;;
1714
1715 let call_tactic_with_input_and_goal_input tactic () =
1716  let module L = LogicalOperations in
1717  let module G = Gdome in
1718   let notebook = (rendering_window ())#notebook in
1719   let output = ((rendering_window ())#output : GMathView.math_view) in
1720   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1721   let inputt = ((rendering_window ())#inputt : term_editor) in
1722   let savedproof = !ProofEngine.proof in
1723   let savedgoal  = !ProofEngine.goal in
1724    match notebook#proofw#get_selection with
1725      Some node ->
1726       let xpath =
1727        ((node : Gdome.element)#getAttributeNS
1728          ~namespaceURI:helmns
1729          ~localName:(G.domString "xref"))#to_string
1730       in
1731        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
1732        else
1733         begin
1734          try
1735           match !current_goal_infos with
1736              Some (ids_to_terms, ids_to_father_ids,_) ->
1737               let id = xpath in
1738                let uri,metasenv,bo,ty =
1739                 match !ProofEngine.proof with
1740                    None -> assert false
1741                  | Some (uri,metasenv,bo,ty) -> uri,metasenv,bo,ty
1742                in
1743                 let canonical_context =
1744                  match !ProofEngine.goal with
1745                     None -> assert false
1746                   | Some metano ->
1747                      let (_,canonical_context,_) =
1748                       List.find (function (m,_,_) -> m=metano) metasenv
1749                      in
1750                       canonical_context in
1751                 let context =
1752                  List.map
1753                   (function
1754                       Some (n,_) -> Some n
1755                     | None -> None
1756                   ) canonical_context
1757                 in
1758                  let dom,mk_metasenv_and_expr = inputt#get_term context metasenv
1759                  in
1760                   let (metasenv',expr) =
1761                    disambiguate_input canonical_context metasenv dom
1762                     mk_metasenv_and_expr
1763                   in
1764                    ProofEngine.proof := Some (uri,metasenv',bo,ty) ;
1765                    tactic ~goal_input:(Hashtbl.find ids_to_terms id)
1766                     ~input:expr ;
1767                    refresh_sequent notebook ;
1768                    refresh_proof output ;
1769                    inputt#reset
1770            | None -> assert false (* "ERROR: No current term!!!" *)
1771          with
1772             RefreshSequentException e ->
1773              output_html outputhtml
1774               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1775                "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1776              ProofEngine.proof := savedproof ;
1777              ProofEngine.goal := savedgoal ;
1778              refresh_sequent notebook
1779           | RefreshProofException e ->
1780              output_html outputhtml
1781               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1782                "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1783              ProofEngine.proof := savedproof ;
1784              ProofEngine.goal := savedgoal ;
1785              refresh_sequent notebook ;
1786              refresh_proof output
1787           | e ->
1788              output_html outputhtml
1789               ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1790              ProofEngine.proof := savedproof ;
1791              ProofEngine.goal := savedgoal ;
1792         end
1793    | None ->
1794       output_html outputhtml
1795        ("<h1 color=\"red\">No term selected</h1>")
1796 ;;
1797
1798 let call_tactic_with_goal_input_in_scratch tactic scratch_window () =
1799  let module L = LogicalOperations in
1800  let module G = Gdome in
1801   let mmlwidget = (scratch_window#mmlwidget : GMathView.math_view) in
1802   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1803   let savedproof = !ProofEngine.proof in
1804   let savedgoal  = !ProofEngine.goal in
1805    match mmlwidget#get_selection with
1806      Some node ->
1807       let xpath =
1808        ((node : Gdome.element)#getAttributeNS
1809          ~namespaceURI:helmns
1810          ~localName:(G.domString "xref"))#to_string
1811       in
1812        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
1813        else
1814         begin
1815          try
1816           match !current_scratch_infos with
1817              (* term is the whole goal in the scratch_area *)
1818              Some (term,ids_to_terms, ids_to_father_ids,_) ->
1819               let id = xpath in
1820                let expr = tactic term (Hashtbl.find ids_to_terms id) in
1821                 let mml = mml_of_cic_term 111 expr in
1822                  scratch_window#show () ;
1823                  scratch_window#mmlwidget#load_tree ~dom:mml
1824            | None -> assert false (* "ERROR: No current term!!!" *)
1825          with
1826           e ->
1827            output_html outputhtml
1828             ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
1829         end
1830    | None ->
1831       output_html outputhtml
1832        ("<h1 color=\"red\">No term selected</h1>")
1833 ;;
1834
1835 let call_tactic_with_hypothesis_input tactic () =
1836  let module L = LogicalOperations in
1837  let module G = Gdome in
1838   let notebook = (rendering_window ())#notebook in
1839   let output = ((rendering_window ())#output : GMathView.math_view) in
1840   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1841   let savedproof = !ProofEngine.proof in
1842   let savedgoal  = !ProofEngine.goal in
1843    match notebook#proofw#get_selection with
1844      Some node ->
1845       let xpath =
1846        ((node : Gdome.element)#getAttributeNS
1847          ~namespaceURI:helmns
1848          ~localName:(G.domString "xref"))#to_string
1849       in
1850        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
1851        else
1852         begin
1853          try
1854           match !current_goal_infos with
1855              Some (_,_,ids_to_hypotheses) ->
1856               let id = xpath in
1857                tactic (Hashtbl.find ids_to_hypotheses id) ;
1858                refresh_sequent notebook ;
1859                refresh_proof output
1860            | None -> assert false (* "ERROR: No current term!!!" *)
1861          with
1862             RefreshSequentException e ->
1863              output_html outputhtml
1864               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1865                "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1866              ProofEngine.proof := savedproof ;
1867              ProofEngine.goal := savedgoal ;
1868              refresh_sequent notebook
1869           | RefreshProofException e ->
1870              output_html outputhtml
1871               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1872                "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1873              ProofEngine.proof := savedproof ;
1874              ProofEngine.goal := savedgoal ;
1875              refresh_sequent notebook ;
1876              refresh_proof output
1877           | e ->
1878              output_html outputhtml
1879               ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1880              ProofEngine.proof := savedproof ;
1881              ProofEngine.goal := savedgoal ;
1882         end
1883    | None ->
1884       output_html outputhtml
1885        ("<h1 color=\"red\">No term selected</h1>")
1886 ;;
1887
1888
1889 let intros = call_tactic ProofEngine.intros;;
1890 let exact = call_tactic_with_input ProofEngine.exact;;
1891 let apply = call_tactic_with_input ProofEngine.apply;;
1892 let elimsimplintros = call_tactic_with_input ProofEngine.elim_simpl_intros;;
1893 let elimtype = call_tactic_with_input ProofEngine.elim_type;;
1894 let whd = call_tactic_with_goal_input ProofEngine.whd;;
1895 let reduce = call_tactic_with_goal_input ProofEngine.reduce;;
1896 let simpl = call_tactic_with_goal_input ProofEngine.simpl;;
1897 let fold = call_tactic_with_input ProofEngine.fold;;
1898 let cut = call_tactic_with_input ProofEngine.cut;;
1899 let change = call_tactic_with_input_and_goal_input ProofEngine.change;;
1900 let letin = call_tactic_with_input ProofEngine.letin;;
1901 let ring = call_tactic ProofEngine.ring;;
1902 let clearbody = call_tactic_with_hypothesis_input ProofEngine.clearbody;;
1903 let clear = call_tactic_with_hypothesis_input ProofEngine.clear;;
1904 let fourier = call_tactic ProofEngine.fourier;;
1905 let rewritesimpl = call_tactic_with_input ProofEngine.rewrite_simpl;;
1906 let reflexivity = call_tactic ProofEngine.reflexivity;;
1907 let symmetry = call_tactic ProofEngine.symmetry;;
1908 let transitivity = call_tactic_with_input ProofEngine.transitivity;;
1909 let left = call_tactic ProofEngine.left;;
1910 let right = call_tactic ProofEngine.right;;
1911 let assumption = call_tactic ProofEngine.assumption;;
1912
1913 let whd_in_scratch scratch_window =
1914  call_tactic_with_goal_input_in_scratch ProofEngine.whd_in_scratch
1915   scratch_window
1916 ;;
1917 let reduce_in_scratch scratch_window =
1918  call_tactic_with_goal_input_in_scratch ProofEngine.reduce_in_scratch
1919   scratch_window
1920 ;;
1921 let simpl_in_scratch scratch_window =
1922  call_tactic_with_goal_input_in_scratch ProofEngine.simpl_in_scratch
1923   scratch_window
1924 ;;
1925
1926
1927
1928 (**********************)
1929 (*   END OF TACTICS   *)
1930 (**********************)
1931
1932
1933 let show () =
1934  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1935   try
1936    show_in_show_window (input_or_locate_uri ~title:"Show")
1937   with
1938    e ->
1939     output_html outputhtml
1940      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1941 ;;
1942
1943 exception NotADefinition;;
1944
1945 let open_ () =
1946  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1947  let output = ((rendering_window ())#output : GMathView.math_view) in
1948  let notebook = (rendering_window ())#notebook in
1949    try
1950     let uri = input_or_locate_uri ~title:"Open" in
1951      CicTypeChecker.typecheck uri ;
1952      let metasenv,bo,ty =
1953       match CicEnvironment.get_cooked_obj uri with
1954          Cic.Constant (_,Some bo,ty,_) -> [],bo,ty
1955        | Cic.CurrentProof (_,metasenv,bo,ty,_) -> metasenv,bo,ty
1956        | Cic.Constant _
1957        | Cic.Variable _
1958        | Cic.InductiveDefinition _ -> raise NotADefinition
1959      in
1960       ProofEngine.proof :=
1961        Some (uri, metasenv, bo, ty) ;
1962       ProofEngine.goal := None ;
1963       refresh_sequent notebook ;
1964       refresh_proof output
1965    with
1966       RefreshSequentException e ->
1967        output_html outputhtml
1968         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1969          "sequent: " ^ Printexc.to_string e ^ "</h1>")
1970     | RefreshProofException e ->
1971        output_html outputhtml
1972         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1973          "proof: " ^ Printexc.to_string e ^ "</h1>")
1974     | e ->
1975        output_html outputhtml
1976         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1977 ;;
1978
1979
1980 let searchPattern () =
1981  let inputt = ((rendering_window ())#inputt : term_editor) in
1982  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1983   try
1984    let rec get_level ?(last_invalid=false) () =
1985     match
1986      GToolbox.input_string
1987       ~title:"Insert the strictness parameter for the query:"
1988       ((if last_invalid then
1989          "Invalid input (must be a non-negative natural number). Insert again "
1990         else
1991          "Insert "
1992        ) ^ "the strictness parameter for the query:")
1993     with
1994        None -> raise NoChoice
1995      | Some n ->
1996         try
1997          int_of_string n
1998         with
1999          _ -> get_level ~last_invalid:true ()
2000    in
2001     let level = get_level () in
2002     let metasenv =
2003      match !ProofEngine.proof with
2004         None -> assert false
2005       | Some (_,metasenv,_,_) -> metasenv
2006     in
2007      match !ProofEngine.goal with
2008         None -> ()
2009       | Some metano ->
2010          let (_, ey ,ty) = List.find (function (m,_,_) -> m=metano) metasenv in
2011           let result = MQueryGenerator.searchPattern metasenv ey ty level in
2012           let uris =
2013            List.map
2014             (function uri,_ ->
2015               wrong_xpointer_format_from_wrong_xpointer_format' uri
2016             ) result in
2017           let html =
2018            " <h1>Backward Query: </h1>" ^
2019            " <h2>Levels: </h2> " ^
2020            MQueryGenerator.string_of_levels
2021             (MQueryGenerator.levels_of_term metasenv ey ty) "<br>" ^
2022            " <pre>" ^ get_last_query result ^ "</pre>"
2023           in
2024            output_html outputhtml html ;
2025            let uris',exc =
2026             let rec filter_out =
2027              function
2028                 [] -> [],""
2029               | uri::tl ->
2030                  let tl',exc = filter_out tl in
2031                   try
2032                    if
2033                     ProofEngine.can_apply
2034                      (term_of_cic_textual_parser_uri
2035                       (cic_textual_parser_uri_of_string uri))
2036                    then
2037                     uri::tl',exc
2038                    else
2039                     tl',exc
2040                   with
2041                    e ->
2042                     let exc' =
2043                      "<h1 color=\"red\"> ^ Exception raised trying to apply " ^
2044                       uri ^ ": " ^ Printexc.to_string e ^ " </h1>" ^ exc
2045                     in
2046                      tl',exc'
2047             in
2048              filter_out uris
2049            in
2050             let html' =
2051              " <h1>Objects that can actually be applied: </h1> " ^
2052              String.concat "<br>" uris' ^ exc ^
2053              " <h1>Number of false matches: " ^
2054               string_of_int (List.length uris - List.length uris') ^ "</h1>" ^
2055              " <h1>Number of good matches: " ^
2056               string_of_int (List.length uris') ^ "</h1>"
2057             in
2058              output_html outputhtml html' ;
2059              let uri' =
2060               user_uri_choice ~title:"Ambiguous input."
2061               ~msg:
2062                 "Many lemmas can be successfully applied. Please, choose one:"
2063                uris'
2064              in
2065               inputt#set_term uri' ;
2066               apply ()
2067   with
2068    e -> 
2069     output_html outputhtml 
2070      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
2071 ;;
2072       
2073 let choose_selection
2074      (mmlwidget : GMathView.math_view) (element : Gdome.element option)
2075 =
2076  let module G = Gdome in
2077   let rec aux element =
2078    if element#hasAttributeNS
2079        ~namespaceURI:helmns
2080        ~localName:(G.domString "xref")
2081    then
2082      mmlwidget#set_selection (Some element)
2083    else
2084       match element#get_parentNode with
2085          None -> assert false
2086        (*CSC: OCAML DIVERGES!
2087        | Some p -> aux (new G.element_of_node p)
2088        *)
2089        | Some p -> aux (new Gdome.element_of_node p)
2090   in
2091    match element with
2092      Some x -> aux x
2093    | None   -> mmlwidget#set_selection None
2094 ;;
2095
2096 (* STUFF TO BUILD THE GTK INTERFACE *)
2097
2098 (* Stuff for the widget settings *)
2099
2100 let export_to_postscript (output : GMathView.math_view) =
2101  let lastdir = ref (Unix.getcwd ()) in
2102   function () ->
2103    match
2104     GToolbox.select_file ~title:"Export to PostScript"
2105      ~dir:lastdir ~filename:"screenshot.ps" ()
2106    with
2107       None -> ()
2108     | Some filename ->
2109        output#export_to_postscript ~filename:filename ();
2110 ;;
2111
2112 let activate_t1 (output : GMathView.math_view) button_set_anti_aliasing
2113  button_set_kerning button_set_transparency export_to_postscript_menu_item
2114  button_t1 ()
2115 =
2116  let is_set = button_t1#active in
2117   output#set_font_manager_type
2118    (if is_set then `font_manager_t1 else `font_manager_gtk) ;
2119   if is_set then
2120    begin
2121     button_set_anti_aliasing#misc#set_sensitive true ;
2122     button_set_kerning#misc#set_sensitive true ;
2123     button_set_transparency#misc#set_sensitive true ;
2124     export_to_postscript_menu_item#misc#set_sensitive true ;
2125    end
2126   else
2127    begin
2128     button_set_anti_aliasing#misc#set_sensitive false ;
2129     button_set_kerning#misc#set_sensitive false ;
2130     button_set_transparency#misc#set_sensitive false ;
2131     export_to_postscript_menu_item#misc#set_sensitive false ;
2132    end
2133 ;;
2134
2135 let set_anti_aliasing output button_set_anti_aliasing () =
2136  output#set_anti_aliasing button_set_anti_aliasing#active
2137 ;;
2138
2139 let set_kerning output button_set_kerning () =
2140  output#set_kerning button_set_kerning#active
2141 ;;
2142
2143 let set_transparency output button_set_transparency () =
2144  output#set_transparency button_set_transparency#active
2145 ;;
2146
2147 let changefont output font_size_spinb () =
2148  output#set_font_size font_size_spinb#value_as_int
2149 ;;
2150
2151 let set_log_verbosity output log_verbosity_spinb () =
2152  output#set_log_verbosity log_verbosity_spinb#value_as_int
2153 ;;
2154
2155 class settings_window (output : GMathView.math_view) sw
2156  export_to_postscript_menu_item selection_changed_callback
2157 =
2158  let settings_window = GWindow.window ~title:"GtkMathView settings" () in
2159  let vbox =
2160   GPack.vbox ~packing:settings_window#add () in
2161  let table =
2162   GPack.table
2163    ~rows:1 ~columns:3 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2164    ~border_width:5 ~packing:vbox#add () in
2165  let button_t1 =
2166   GButton.toggle_button ~label:"activate t1 fonts"
2167    ~packing:(table#attach ~left:0 ~top:0) () in
2168  let button_set_anti_aliasing =
2169   GButton.toggle_button ~label:"set_anti_aliasing"
2170    ~packing:(table#attach ~left:0 ~top:1) () in
2171  let button_set_kerning =
2172   GButton.toggle_button ~label:"set_kerning"
2173    ~packing:(table#attach ~left:1 ~top:1) () in
2174  let button_set_transparency =
2175   GButton.toggle_button ~label:"set_transparency"
2176    ~packing:(table#attach ~left:2 ~top:1) () in
2177  let table =
2178   GPack.table
2179    ~rows:2 ~columns:2 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2180    ~border_width:5 ~packing:vbox#add () in
2181  let font_size_label =
2182   GMisc.label ~text:"font size:"
2183    ~packing:(table#attach ~left:0 ~top:0 ~expand:`NONE) () in
2184  let font_size_spinb =
2185   let sadj =
2186    GData.adjustment ~value:14.0 ~lower:5.0 ~upper:50.0 ~step_incr:1.0 ()
2187   in
2188    GEdit.spin_button 
2189     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:0 ~fill:`NONE) () in
2190  let log_verbosity_label =
2191   GMisc.label ~text:"log verbosity:"
2192    ~packing:(table#attach ~left:0 ~top:1) () in
2193  let log_verbosity_spinb =
2194   let sadj =
2195    GData.adjustment ~value:0.0 ~lower:0.0 ~upper:3.0 ~step_incr:1.0 ()
2196   in
2197    GEdit.spin_button 
2198     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:1) () in
2199  let hbox =
2200   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2201  let closeb =
2202   GButton.button ~label:"Close"
2203    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2204 object(self)
2205  method show = settings_window#show
2206  initializer
2207   button_set_anti_aliasing#misc#set_sensitive false ;
2208   button_set_kerning#misc#set_sensitive false ;
2209   button_set_transparency#misc#set_sensitive false ;
2210   (* Signals connection *)
2211   ignore(button_t1#connect#clicked
2212    (activate_t1 output button_set_anti_aliasing button_set_kerning
2213     button_set_transparency export_to_postscript_menu_item button_t1)) ;
2214   ignore(font_size_spinb#connect#changed (changefont output font_size_spinb)) ;
2215   ignore(button_set_anti_aliasing#connect#toggled
2216    (set_anti_aliasing output button_set_anti_aliasing));
2217   ignore(button_set_kerning#connect#toggled
2218    (set_kerning output button_set_kerning)) ;
2219   ignore(button_set_transparency#connect#toggled
2220    (set_transparency output button_set_transparency)) ;
2221   ignore(log_verbosity_spinb#connect#changed
2222    (set_log_verbosity output log_verbosity_spinb)) ;
2223   ignore(closeb#connect#clicked settings_window#misc#hide)
2224 end;;
2225
2226 (* Scratch window *)
2227
2228 class scratch_window =
2229  let window =
2230   GWindow.window ~title:"MathML viewer" ~border_width:2 () in
2231  let vbox =
2232   GPack.vbox ~packing:window#add () in
2233  let hbox =
2234   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2235  let whdb =
2236   GButton.button ~label:"Whd"
2237    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2238  let reduceb =
2239   GButton.button ~label:"Reduce"
2240    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2241  let simplb =
2242   GButton.button ~label:"Simpl"
2243    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2244  let scrolled_window =
2245   GBin.scrolled_window ~border_width:10
2246    ~packing:(vbox#pack ~expand:true ~padding:5) () in
2247  let mmlwidget =
2248   GMathView.math_view
2249    ~packing:(scrolled_window#add) ~width:400 ~height:280 () in
2250 object(self)
2251  method mmlwidget = mmlwidget
2252  method show () = window#misc#hide () ; window#show ()
2253  initializer
2254   ignore(mmlwidget#connect#selection_changed (choose_selection mmlwidget)) ;
2255   ignore(window#event#connect#delete (fun _ -> window#misc#hide () ; true )) ;
2256   ignore(whdb#connect#clicked (whd_in_scratch self)) ;
2257   ignore(reduceb#connect#clicked (reduce_in_scratch self)) ;
2258   ignore(simplb#connect#clicked (simpl_in_scratch self))
2259 end;;
2260
2261 class page () =
2262  let vbox1 = GPack.vbox () in
2263 object(self)
2264  val mutable proofw_ref = None
2265  val mutable compute_ref = None
2266  method proofw =
2267   Lazy.force self#compute ;
2268   match proofw_ref with
2269      None -> assert false
2270    | Some proofw -> proofw
2271  method content = vbox1
2272  method compute =
2273   match compute_ref with
2274      None -> assert false
2275    | Some compute -> compute
2276  initializer
2277   compute_ref <-
2278    Some (lazy (
2279    let scrolled_window1 =
2280     GBin.scrolled_window ~border_width:10
2281      ~packing:(vbox1#pack ~expand:true ~padding:5) () in
2282    let proofw =
2283     GMathView.math_view ~width:400 ~height:275
2284      ~packing:(scrolled_window1#add) () in
2285    let _ = proofw_ref <- Some proofw in
2286    let hbox3 =
2287     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2288    let exactb =
2289     GButton.button ~label:"Exact"
2290      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2291    let introsb =
2292     GButton.button ~label:"Intros"
2293      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2294    let applyb =
2295     GButton.button ~label:"Apply"
2296      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2297    let elimsimplintrosb =
2298     GButton.button ~label:"ElimSimplIntros"
2299      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2300    let elimtypeb =
2301     GButton.button ~label:"ElimType"
2302      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2303    let whdb =
2304     GButton.button ~label:"Whd"
2305      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2306    let reduceb =
2307     GButton.button ~label:"Reduce"
2308      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2309    let simplb =
2310     GButton.button ~label:"Simpl"
2311      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2312    let foldb =
2313     GButton.button ~label:"Fold"
2314      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2315    let cutb =
2316     GButton.button ~label:"Cut"
2317      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2318    let hbox4 =
2319     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2320    let changeb =
2321     GButton.button ~label:"Change"
2322      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2323    let letinb =
2324     GButton.button ~label:"Let ... In"
2325      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2326    let ringb =
2327     GButton.button ~label:"Ring"
2328      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2329    let clearbodyb =
2330     GButton.button ~label:"ClearBody"
2331      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2332    let clearb =
2333     GButton.button ~label:"Clear"
2334      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2335    let fourierb =
2336     GButton.button ~label:"Fourier"
2337      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2338    let rewritesimplb =
2339     GButton.button ~label:"RewriteSimpl ->"
2340      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2341    let reflexivityb =
2342     GButton.button ~label:"Reflexivity"
2343      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2344    let hbox5 =
2345     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2346    let symmetryb =
2347     GButton.button ~label:"Symmetry"
2348      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2349    let transitivityb =
2350     GButton.button ~label:"Transitivity"
2351      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2352    let leftb =
2353     GButton.button ~label:"Left"
2354      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2355    let rightb =
2356     GButton.button ~label:"Right"
2357      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2358    let assumptionb =
2359     GButton.button ~label:"Assumption"
2360      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2361    let searchpatternb =
2362     GButton.button ~label:"SearchPattern_Apply"
2363      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2364    ignore(exactb#connect#clicked exact) ;
2365    ignore(applyb#connect#clicked apply) ;
2366    ignore(elimsimplintrosb#connect#clicked elimsimplintros) ;
2367    ignore(elimtypeb#connect#clicked elimtype) ;
2368    ignore(whdb#connect#clicked whd) ;
2369    ignore(reduceb#connect#clicked reduce) ;
2370    ignore(simplb#connect#clicked simpl) ;
2371    ignore(foldb#connect#clicked fold) ;
2372    ignore(cutb#connect#clicked cut) ;
2373    ignore(changeb#connect#clicked change) ;
2374    ignore(letinb#connect#clicked letin) ;
2375    ignore(ringb#connect#clicked ring) ;
2376    ignore(clearbodyb#connect#clicked clearbody) ;
2377    ignore(clearb#connect#clicked clear) ;
2378    ignore(fourierb#connect#clicked fourier) ;
2379    ignore(rewritesimplb#connect#clicked rewritesimpl) ;
2380    ignore(reflexivityb#connect#clicked reflexivity) ;
2381    ignore(symmetryb#connect#clicked symmetry) ;
2382    ignore(transitivityb#connect#clicked transitivity) ;
2383    ignore(leftb#connect#clicked left) ;
2384    ignore(rightb#connect#clicked right) ;
2385    ignore(assumptionb#connect#clicked assumption) ;
2386    ignore(introsb#connect#clicked intros) ;
2387    ignore(searchpatternb#connect#clicked searchPattern) ;
2388    ignore(proofw#connect#selection_changed (choose_selection proofw)) ;
2389   ))
2390 end
2391 ;;
2392
2393 class empty_page =
2394  let vbox1 = GPack.vbox () in
2395  let scrolled_window1 =
2396   GBin.scrolled_window ~border_width:10
2397    ~packing:(vbox1#pack ~expand:true ~padding:5) () in
2398  let proofw =
2399   GMathView.math_view ~width:400 ~height:275
2400    ~packing:(scrolled_window1#add) () in
2401 object(self)
2402  method proofw = (assert false : GMathView.math_view)
2403  method content = vbox1
2404  method compute = (assert false : unit)
2405 end
2406 ;;
2407
2408 let empty_page = new empty_page;;
2409
2410 class notebook =
2411 object(self)
2412  val notebook = GPack.notebook ()
2413  val pages = ref []
2414  val mutable skip_switch_page_event = false 
2415  val mutable empty = true
2416  method notebook = notebook
2417  method add_page n =
2418   let new_page = new page () in
2419    empty <- false ;
2420    pages := !pages @ [n,lazy (setgoal n),new_page] ;
2421    notebook#append_page
2422     ~tab_label:((GMisc.label ~text:("?" ^ string_of_int n) ())#coerce)
2423     new_page#content#coerce
2424  method remove_all_pages ~skip_switch_page_event:skip =
2425   if empty then
2426    notebook#remove_page 0 (* let's remove the empty page *)
2427   else
2428    List.iter (function _ -> notebook#remove_page 0) !pages ;
2429   pages := [] ;
2430   skip_switch_page_event <- skip
2431  method set_current_page ~may_skip_switch_page_event n =
2432   let (_,_,page) = List.find (function (m,_,_) -> m=n) !pages in
2433    let new_page = notebook#page_num page#content#coerce in
2434     if may_skip_switch_page_event && new_page <> notebook#current_page then
2435      skip_switch_page_event <- true ;
2436     notebook#goto_page new_page
2437  method set_empty_page =
2438   empty <- true ;
2439   pages := [] ;
2440   notebook#append_page
2441    ~tab_label:((GMisc.label ~text:"No proof in progress" ())#coerce)
2442    empty_page#content#coerce
2443  method proofw =
2444   let (_,_,page) = List.nth !pages notebook#current_page in
2445    page#proofw
2446  initializer
2447   ignore
2448    (notebook#connect#switch_page
2449     (function i ->
2450       let skip = skip_switch_page_event in
2451        skip_switch_page_event <- false ;
2452        if not skip then
2453         try
2454          let (metano,setgoal,page) = List.nth !pages i in
2455           ProofEngine.goal := Some metano ;
2456           Lazy.force (page#compute) ;
2457           Lazy.force setgoal
2458         with _ -> ()
2459     ))
2460 end
2461 ;;
2462
2463 (* Main window *)
2464
2465 class rendering_window output (notebook : notebook) =
2466  let scratch_window = new scratch_window in
2467  let window =
2468   GWindow.window ~title:"MathML viewer" ~border_width:0
2469    ~allow_shrink:false () in
2470  let vbox_for_menu = GPack.vbox ~packing:window#add () in
2471  (* menus *)
2472  let handle_box = GBin.handle_box ~border_width:2
2473   ~packing:(vbox_for_menu#pack ~padding:0) () in
2474  let menubar = GMenu.menu_bar ~packing:handle_box#add () in
2475  let factory0 = new GMenu.factory menubar in
2476  let accel_group = factory0#accel_group in
2477  (* file menu *)
2478  let file_menu = factory0#add_submenu "File" in
2479  let factory1 = new GMenu.factory file_menu ~accel_group in
2480  let export_to_postscript_menu_item =
2481   begin
2482    let _ =
2483     factory1#add_item "New Proof or Definition..." ~key:GdkKeysyms._N
2484      ~callback:new_proof
2485    in
2486    let reopen_menu_item =
2487     factory1#add_item "Reopen a Finished Proof..." ~key:GdkKeysyms._R
2488      ~callback:open_
2489    in
2490    let qed_menu_item =
2491     factory1#add_item "Qed" ~key:GdkKeysyms._E ~callback:qed in
2492    ignore (factory1#add_separator ()) ;
2493    ignore
2494     (factory1#add_item "Load Unfinished Proof..." ~key:GdkKeysyms._L
2495       ~callback:load) ;
2496    let save_menu_item =
2497     factory1#add_item "Save Unfinished Proof" ~key:GdkKeysyms._S ~callback:save
2498    in
2499    ignore
2500     (save_set_sensitive := function b -> save_menu_item#misc#set_sensitive b);
2501    ignore (!save_set_sensitive false);
2502    ignore (qed_set_sensitive:=function b -> qed_menu_item#misc#set_sensitive b);
2503    ignore (!qed_set_sensitive false);
2504    ignore (factory1#add_separator ()) ;
2505    let export_to_postscript_menu_item =
2506     factory1#add_item "Export to PostScript..."
2507      ~callback:(export_to_postscript output) in
2508    ignore (factory1#add_separator ()) ;
2509    ignore
2510     (factory1#add_item "Exit" ~key:GdkKeysyms._Q ~callback:GMain.Main.quit) ;
2511    export_to_postscript_menu_item
2512   end in
2513  (* edit menu *)
2514  let edit_menu = factory0#add_submenu "Edit Current Proof" in
2515  let factory2 = new GMenu.factory edit_menu ~accel_group in
2516  let focus_and_proveit_set_sensitive = ref (function _ -> assert false) in
2517  let proveit_menu_item =
2518   factory2#add_item "Prove It" ~key:GdkKeysyms._I
2519    ~callback:(function () -> proveit ();!focus_and_proveit_set_sensitive false)
2520  in
2521  let focus_menu_item =
2522   factory2#add_item "Focus" ~key:GdkKeysyms._F
2523    ~callback:(function () -> focus () ; !focus_and_proveit_set_sensitive false)
2524  in
2525  let _ =
2526   focus_and_proveit_set_sensitive :=
2527    function b ->
2528     proveit_menu_item#misc#set_sensitive b ;
2529     focus_menu_item#misc#set_sensitive b
2530  in
2531  let _ = !focus_and_proveit_set_sensitive false in
2532  (* edit term menu *)
2533  let edit_term_menu = factory0#add_submenu "Edit Term" in
2534  let factory5 = new GMenu.factory edit_term_menu ~accel_group in
2535  let check_menu_item =
2536   factory5#add_item "Check Term" ~key:GdkKeysyms._C
2537    ~callback:(check scratch_window) in
2538  let _ = check_menu_item#misc#set_sensitive false in
2539  (* search menu *)
2540  let settings_menu = factory0#add_submenu "Search" in
2541  let factory4 = new GMenu.factory settings_menu ~accel_group in
2542  let _ =
2543   factory4#add_item "Locate..." ~key:GdkKeysyms._T
2544    ~callback:locate in
2545  let show_menu_item =
2546   factory4#add_item "Show..." ~key:GdkKeysyms._H ~callback:show
2547  in
2548  (* settings menu *)
2549  let settings_menu = factory0#add_submenu "Settings" in
2550  let factory3 = new GMenu.factory settings_menu ~accel_group in
2551  let _ =
2552   factory3#add_item "Edit Aliases" ~key:GdkKeysyms._A
2553    ~callback:edit_aliases in
2554  let _ = factory3#add_separator () in
2555  let _ =
2556   factory3#add_item "MathML Widget Preferences..." ~key:GdkKeysyms._P
2557    ~callback:(function _ -> (settings_window ())#show ()) in
2558  (* accel group *)
2559  let _ = window#add_accel_group accel_group in
2560  (* end of menus *)
2561  let hbox0 =
2562   GPack.hbox
2563    ~packing:(vbox_for_menu#pack ~expand:true ~fill:true ~padding:5) () in
2564  let vbox =
2565   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
2566  let scrolled_window0 =
2567   GBin.scrolled_window ~border_width:10
2568    ~packing:(vbox#pack ~expand:true ~padding:5) () in
2569  let _ = scrolled_window0#add output#coerce in
2570  let frame =
2571   GBin.frame ~label:"Insert Term"
2572    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2573  let scrolled_window1 =
2574   GBin.scrolled_window ~border_width:5
2575    ~packing:frame#add () in
2576  let inputt =
2577   new term_editor ~width:400 ~height:100 ~packing:scrolled_window1#add ()
2578    ~isnotempty_callback:check_menu_item#misc#set_sensitive in
2579  let vboxl =
2580   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
2581  let _ =
2582   vboxl#pack ~expand:true ~fill:true ~padding:5 notebook#notebook#coerce in
2583  let frame =
2584   GBin.frame ~shadow_type:`IN ~packing:(vboxl#pack ~expand:true ~padding:5) ()
2585  in
2586  let outputhtml =
2587   GHtml.xmhtml
2588    ~source:"<html><body bgColor=\"white\"></body></html>"
2589    ~width:400 ~height: 100
2590    ~border_width:20
2591    ~packing:frame#add
2592    ~show:true () in
2593 object
2594  method outputhtml = outputhtml
2595  method inputt = inputt
2596  method output = (output : GMathView.math_view)
2597  method notebook = notebook
2598  method show = window#show
2599  initializer
2600   notebook#set_empty_page ;
2601   export_to_postscript_menu_item#misc#set_sensitive false ;
2602   check_term := (check_term_in_scratch scratch_window) ;
2603
2604   (* signal handlers here *)
2605   ignore(output#connect#selection_changed
2606    (function elem ->
2607      choose_selection output elem ;
2608      !focus_and_proveit_set_sensitive true
2609    )) ;
2610   ignore (output#connect#clicked (show_in_show_window_callback output)) ;
2611   let settings_window = new settings_window output scrolled_window0
2612    export_to_postscript_menu_item (choose_selection output) in
2613   set_settings_window settings_window ;
2614   set_outputhtml outputhtml ;
2615   ignore(window#event#connect#delete (fun _ -> GMain.Main.quit () ; true )) ;
2616   Logger.log_callback :=
2617    (Logger.log_to_html ~print_and_flush:(output_html outputhtml))
2618 end;;
2619
2620 (* MAIN *)
2621
2622 let initialize_everything () =
2623  let module U = Unix in
2624   let output = GMathView.math_view ~width:350 ~height:280 () in
2625   let notebook = new notebook in
2626    let rendering_window' = new rendering_window output notebook in
2627     set_rendering_window rendering_window' ;
2628     mml_of_cic_term_ref := mml_of_cic_term ;
2629     rendering_window'#show () ;
2630     GMain.Main.main ()
2631 ;;
2632
2633 let _ =
2634  if !usedb then
2635  Mqint.init "dbname=helm_mowgli" ; 
2636 (* Mqint.init "host=mowgli.cs.unibo.it dbname=helm_mowgli user=helm" ; *)
2637  ignore (GtkMain.Main.init ()) ;
2638  initialize_everything () ;
2639  if !usedb then Mqint.close ();
2640 ;;