]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/gTopLevel.ml
ebe26c3e350a915089f1dbe229547d1620bdee0d
[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 (* GLOBAL CONSTANTS *)
38
39 let helmns = Gdome.domString "http://www.cs.unibo.it/helm";;
40 let xlinkns = Gdome.domString "http://www.w3.org/1999/xlink";;
41
42 let htmlheader =
43  "<html>" ^
44  " <body bgColor=\"white\">"
45 ;;
46
47 let htmlfooter =
48  " </body>" ^
49  "</html>"
50 ;;
51
52 let prooffile =
53  try
54   Sys.getenv "GTOPLEVEL_PROOFFILE"
55  with
56   Not_found -> "/public/currentproof"
57 ;;
58
59 let prooffiletype =
60  try
61   Sys.getenv "GTOPLEVEL_PROOFFILETYPE"
62  with
63   Not_found -> "/public/currentprooftype"
64 ;;
65
66 (*CSC: the getter should handle the innertypes, not the FS *)
67
68 let innertypesfile =
69  try
70   Sys.getenv "GTOPLEVEL_INNERTYPESFILE"
71  with
72   Not_found -> "/public/innertypes"
73 ;;
74
75 let constanttypefile =
76  try
77   Sys.getenv "GTOPLEVEL_CONSTANTTYPEFILE"
78  with
79   Not_found -> "/public/constanttype"
80 ;;
81
82 let postgresqlconnectionstring =
83  try
84   Sys.getenv "POSTGRESQL_CONNECTION_STRING"
85  with
86   Not_found -> "host=mowgli.cs.unibo.it dbname=helm_mowgli_new_schema user=helm"
87 ;;
88
89 let empty_id_to_uris = ([],function _ -> None);;
90
91
92 (* GLOBAL REFERENCES (USED BY CALLBACKS) *)
93
94 let htmlheader_and_content = ref htmlheader;;
95
96 let current_cic_infos = ref None;;
97 let current_goal_infos = ref None;;
98 let current_scratch_infos = ref None;;
99
100 let id_to_uris = ref empty_id_to_uris;;
101
102 let check_term = ref (fun _ _ _ -> assert false);;
103 let mml_of_cic_term_ref = ref (fun _ _ -> assert false);;
104
105 exception RenderingWindowsNotInitialized;;
106
107 let set_rendering_window,rendering_window =
108  let rendering_window_ref = ref None in
109   (function rw -> rendering_window_ref := Some rw),
110   (function () ->
111     match !rendering_window_ref with
112        None -> raise RenderingWindowsNotInitialized
113      | Some rw -> rw
114   )
115 ;;
116
117 exception SettingsWindowsNotInitialized;;
118
119 let set_settings_window,settings_window =
120  let settings_window_ref = ref None in
121   (function rw -> settings_window_ref := Some rw),
122   (function () ->
123     match !settings_window_ref with
124        None -> raise SettingsWindowsNotInitialized
125      | Some rw -> rw
126   )
127 ;;
128
129 exception OutputHtmlNotInitialized;;
130
131 let set_outputhtml,outputhtml =
132  let outputhtml_ref = ref None in
133   (function rw -> outputhtml_ref := Some rw),
134   (function () ->
135     match !outputhtml_ref with
136        None -> raise OutputHtmlNotInitialized
137      | Some outputhtml -> outputhtml
138   )
139 ;;
140
141 exception QedSetSensitiveNotInitialized;;
142 let qed_set_sensitive =
143  ref (function _ -> raise QedSetSensitiveNotInitialized)
144 ;;
145
146 exception SaveSetSensitiveNotInitialized;;
147 let save_set_sensitive =
148  ref (function _ -> raise SaveSetSensitiveNotInitialized)
149 ;;
150
151 (* COMMAND LINE OPTIONS *)
152
153 let usedb = ref true
154
155 let argspec =
156   [
157     "-nodb", Arg.Clear usedb, "disable use of MathQL DB"
158   ]
159 in
160 Arg.parse argspec ignore ""
161
162 (* MISC FUNCTIONS *)
163
164 let term_of_cic_textual_parser_uri uri =
165  let module C = Cic in
166  let module CTP = CicTextualParser0 in
167   match uri with
168      CTP.ConUri uri -> C.Const (uri,[])
169    | CTP.VarUri uri -> C.Var (uri,[])
170    | CTP.IndTyUri (uri,tyno) -> C.MutInd (uri,tyno,[])
171    | CTP.IndConUri (uri,tyno,consno) -> C.MutConstruct (uri,tyno,consno,[])
172 ;;
173
174 let string_of_cic_textual_parser_uri uri =
175  let module C = Cic in
176  let module CTP = CicTextualParser0 in
177   let uri' =
178    match uri with
179       CTP.ConUri uri -> UriManager.string_of_uri uri
180     | CTP.VarUri uri -> UriManager.string_of_uri uri
181     | CTP.IndTyUri (uri,tyno) ->
182        UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1)
183     | CTP.IndConUri (uri,tyno,consno) ->
184        UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1) ^ "/" ^
185         string_of_int consno
186   in
187    (* 4 = String.length "cic:" *)
188    String.sub uri' 4 (String.length uri' - 4)
189 ;;
190
191 let output_html outputhtml msg =
192  htmlheader_and_content := !htmlheader_and_content ^ msg ;
193  outputhtml#source (!htmlheader_and_content ^ htmlfooter) ;
194  outputhtml#set_topline (-1)
195 ;;
196
197 (* UTILITY FUNCTIONS TO DISAMBIGUATE AN URI *)
198
199 (* Check window *)
200
201 let check_window outputhtml uris =
202  let window =
203   GWindow.window
204    ~width:800 ~modal:true ~title:"Check" ~border_width:2 () in
205  let notebook =
206   GPack.notebook ~scrollable:true ~packing:window#add () in
207  window#show () ;
208  let render_terms =
209   List.map
210    (function uri ->
211      let scrolled_window =
212       GBin.scrolled_window ~border_width:10
213        ~packing:
214          (notebook#append_page ~tab_label:((GMisc.label ~text:uri ())#coerce))
215        ()
216      in
217       lazy 
218        (let mmlwidget =
219          GMathView.math_view
220           ~packing:scrolled_window#add ~width:400 ~height:280 () in
221         let expr =
222          let term =
223           term_of_cic_textual_parser_uri
224            (Disambiguate.cic_textual_parser_uri_of_string uri)
225          in
226           (Cic.Cast (term, CicTypeChecker.type_of_aux' [] [] term))
227         in
228          try
229           let mml = !mml_of_cic_term_ref 111 expr in
230            mmlwidget#load_tree ~dom:mml
231          with
232           e ->
233            output_html outputhtml
234             ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
235        )
236    ) uris
237  in
238   ignore
239    (notebook#connect#switch_page
240      (function i -> Lazy.force (List.nth render_terms i)))
241 ;;
242
243 exception NoChoice;;
244
245 let
246  interactive_user_uri_choice ~(selection_mode:[`SINGLE|`EXTENDED]) ?(ok="Ok")
247   ?(enable_button_for_non_vars=false) ~title ~msg uris
248 =
249  let choices = ref [] in
250  let chosen = ref false in
251  let use_only_constants = ref false in
252  let window =
253   GWindow.dialog ~modal:true ~title ~width:600 () in
254  let lMessage =
255   GMisc.label ~text:msg
256    ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
257  let scrolled_window =
258   GBin.scrolled_window ~border_width:10
259    ~packing:(window#vbox#pack ~expand:true ~fill:true ~padding:5) () in
260  let clist =
261   let expected_height = 18 * List.length uris in
262    let height = if expected_height > 400 then 400 else expected_height in
263     GList.clist ~columns:1 ~packing:scrolled_window#add
264      ~height ~selection_mode:(selection_mode :> Gtk.Tags.selection_mode) () in
265  let _ = List.map (function x -> clist#append [x]) uris in
266  let hbox2 =
267   GPack.hbox ~border_width:0
268    ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
269  let explain_label =
270   GMisc.label ~text:"None of the above. Try this one:"
271    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
272  let manual_input =
273   GEdit.entry ~editable:true
274    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
275  let hbox =
276   GPack.hbox ~border_width:0 ~packing:window#action_area#add () in
277  let okb =
278   GButton.button ~label:ok
279    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
280  let _ = okb#misc#set_sensitive false in
281  let nonvarsb =
282   GButton.button
283    ~packing:
284     (function w ->
285       if enable_button_for_non_vars then
286        hbox#pack ~expand:false ~fill:false ~padding:5 w)
287    ~label:"Try constants only" () in
288  let checkb =
289   GButton.button ~label:"Check"
290    ~packing:(hbox#pack ~padding:5) () in
291  let _ = checkb#misc#set_sensitive false in
292  let cancelb =
293   GButton.button ~label:"Abort"
294    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
295  (* actions *)
296  let check_callback () =
297   assert (List.length !choices > 0) ;
298   check_window (outputhtml ()) !choices
299  in
300   ignore (window#connect#destroy GMain.Main.quit) ;
301   ignore (cancelb#connect#clicked window#destroy) ;
302   ignore
303    (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
304   ignore
305    (nonvarsb#connect#clicked
306      (function () ->
307        use_only_constants := true ;
308        chosen := true ;
309        window#destroy ()
310    )) ;
311   ignore (checkb#connect#clicked check_callback) ;
312   ignore
313    (clist#connect#select_row
314      (fun ~row ~column ~event ->
315        checkb#misc#set_sensitive true ;
316        okb#misc#set_sensitive true ;
317        choices := (List.nth uris row)::!choices)) ;
318   ignore
319    (clist#connect#unselect_row
320      (fun ~row ~column ~event ->
321        choices :=
322         List.filter (function uri -> uri != (List.nth uris row)) !choices)) ;
323   ignore
324    (manual_input#connect#changed
325      (fun _ ->
326        if manual_input#text = "" then
327         begin
328          choices := [] ;
329          checkb#misc#set_sensitive false ;
330          okb#misc#set_sensitive false ;
331          clist#misc#set_sensitive true
332         end
333        else
334         begin
335          choices := [manual_input#text] ;
336          clist#unselect_all () ;
337          checkb#misc#set_sensitive true ;
338          okb#misc#set_sensitive true ;
339          clist#misc#set_sensitive false
340         end));
341   window#set_position `CENTER ;
342   window#show () ;
343   GMain.Main.main () ;
344   if !chosen then
345    if !use_only_constants then
346     List.filter
347      (function uri -> not (String.sub uri (String.length uri - 4) 4 = ".var"))
348      uris
349    else
350     if List.length !choices > 0 then !choices else raise NoChoice
351   else
352    raise NoChoice
353 ;;
354
355 let interactive_interpretation_choice interpretations =
356  let chosen = ref None in
357  let window =
358   GWindow.window
359    ~modal:true ~title:"Ambiguous well-typed input." ~border_width:2 () in
360  let vbox = GPack.vbox ~packing:window#add () in
361  let lMessage =
362   GMisc.label
363    ~text:
364     ("Ambiguous input since there are many well-typed interpretations." ^
365      " Please, choose one of them.")
366    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
367  let notebook =
368   GPack.notebook ~scrollable:true
369    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
370  let _ =
371   List.map
372    (function interpretation ->
373      let clist =
374       let expected_height = 18 * List.length interpretation in
375        let height = if expected_height > 400 then 400 else expected_height in
376         GList.clist ~columns:2 ~packing:notebook#append_page ~height
377          ~titles:["id" ; "URI"] ()
378      in
379       ignore
380        (List.map
381          (function (id,uri) ->
382            let n = clist#append [id;uri] in
383             clist#set_row ~selectable:false n
384          ) interpretation
385        ) ;
386       clist#columns_autosize ()
387    ) interpretations in
388  let hbox =
389   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
390  let okb =
391   GButton.button ~label:"Ok"
392    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
393  let cancelb =
394   GButton.button ~label:"Abort"
395    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
396  (* actions *)
397  ignore (window#connect#destroy GMain.Main.quit) ;
398  ignore (cancelb#connect#clicked window#destroy) ;
399  ignore
400   (okb#connect#clicked
401     (function () -> chosen := Some notebook#current_page ; window#destroy ())) ;
402  window#set_position `CENTER ;
403  window#show () ;
404  GMain.Main.main () ;
405  match !chosen with
406     None -> raise NoChoice
407   | Some n -> n
408 ;;
409
410
411 (* MISC FUNCTIONS *)
412
413 (* CSC: IMPERATIVE AND NOT VERY CLEAN, TO GET THE LAST ISSUED QUERY *)
414 let get_last_query = 
415  let query = ref "" in
416   MQueryGenerator.set_confirm_query
417    (function q -> query := MQueryUtil.text_of_query q ; true) ;
418   function result -> !query ^ " <h1>Result:</h1> " ^ MQueryUtil.text_of_result result "<br>"
419 ;;
420
421 let domImpl = Gdome.domImplementation ();;
422
423 let parseStyle name =
424  let style =
425   domImpl#createDocumentFromURI
426 (*
427    ~uri:("http://phd.cs.unibo.it:8081/getxslt?uri=" ^ name) ?mode:None
428 *)
429    ~uri:("styles/" ^ name) ()
430  in
431   Gdome_xslt.processStylesheet style
432 ;;
433
434 let d_c = parseStyle "drop_coercions.xsl";;
435 let tc1 = parseStyle "objtheorycontent.xsl";;
436 let hc2 = parseStyle "content_to_html.xsl";;
437 let l   = parseStyle "link.xsl";;
438
439 let c1 = parseStyle "rootcontent.xsl";;
440 let g  = parseStyle "genmmlid.xsl";;
441 let c2 = parseStyle "annotatedpres.xsl";;
442
443
444 let getterURL = Configuration.getter_url;;
445 let processorURL = Configuration.processor_url;;
446
447 let mml_styles = [d_c ; c1 ; g ; c2 ; l];;
448 let mml_args ~explode_all =
449  ("explodeall",(if explode_all then "true()" else "false()"))::
450   ["processorURL", "'" ^ processorURL ^ "'" ;
451    "getterURL", "'" ^ getterURL ^ "'" ;
452    "draw_graphURL", "'http%3A//phd.cs.unibo.it%3A8083/'" ;
453    "uri_set_queueURL", "'http%3A//phd.cs.unibo.it%3A8084/'" ;
454    "UNICODEvsSYMBOL", "'symbol'" ;
455    "doctype-public", "'-//W3C//DTD%20XHTML%201.0%20Transitional//EN'" ;
456    "encoding", "'iso-8859-1'" ;
457    "media-type", "'text/html'" ;
458    "keys", "'d_c%2CC1%2CG%2CC2%2CL'" ;
459    "interfaceURL", "'http%3A//phd.cs.unibo.it/helm/html/cic/index.html'" ;
460    "naturalLanguage", "'yes'" ;
461    "annotations", "'no'" ;
462    "URLs_or_URIs", "'URIs'" ;
463    "topurl", "'http://phd.cs.unibo.it/helm'" ;
464    "CICURI", "'cic:/Coq/Init/Datatypes/bool_ind.con'" ]
465 ;;
466
467 let sequent_styles = [d_c ; c1 ; g ; c2 ; l];;
468 let sequent_args =
469  ["processorURL", "'" ^ processorURL ^ "'" ;
470   "getterURL", "'" ^ getterURL ^ "'" ;
471   "draw_graphURL", "'http%3A//phd.cs.unibo.it%3A8083/'" ;
472   "uri_set_queueURL", "'http%3A//phd.cs.unibo.it%3A8084/'" ;
473   "UNICODEvsSYMBOL", "'symbol'" ;
474   "doctype-public", "'-//W3C//DTD%20XHTML%201.0%20Transitional//EN'" ;
475   "encoding", "'iso-8859-1'" ;
476   "media-type", "'text/html'" ;
477   "keys", "'d_c%2CC1%2CG%2CC2%2CL'" ;
478   "interfaceURL", "'http%3A//phd.cs.unibo.it/helm/html/cic/index.html'" ;
479   "naturalLanguage", "'no'" ;
480   "annotations", "'no'" ;
481   "explodeall", "true()" ;
482   "URLs_or_URIs", "'URIs'" ;
483   "topurl", "'http://phd.cs.unibo.it/helm'" ;
484   "CICURI", "'cic:/Coq/Init/Datatypes/bool_ind.con'" ]
485 ;;
486
487 let parse_file filename =
488  let inch = open_in filename in
489   let rec read_lines () =
490    try
491     let line = input_line inch in
492      line ^ read_lines ()
493    with
494     End_of_file -> ""
495   in
496    read_lines ()
497 ;;
498
499 let applyStylesheets input styles args =
500  List.fold_left (fun i style -> Gdome_xslt.applyStylesheet i style args)
501   input styles
502 ;;
503
504 let
505  mml_of_cic_object ~explode_all uri annobj ids_to_inner_sorts ids_to_inner_types
506 =
507 (*CSC: ????????????????? *)
508  let xml, bodyxml =
509   Cic2Xml.print_object uri ~ids_to_inner_sorts ~ask_dtd_to_the_getter:true
510    annobj 
511  in
512  let xmlinnertypes =
513   Cic2Xml.print_inner_types uri ~ids_to_inner_sorts ~ids_to_inner_types
514    ~ask_dtd_to_the_getter:true
515  in
516   let input =
517    match bodyxml with
518       None -> Xml2Gdome.document_of_xml domImpl xml
519     | Some bodyxml' ->
520        Xml.pp xml (Some constanttypefile) ;
521        Xml2Gdome.document_of_xml domImpl bodyxml'
522   in
523 (*CSC: We save the innertypes to disk so that we can retrieve them in the  *)
524 (*CSC: stylesheet. This DOES NOT work when UWOBO and/or the getter are not *)
525 (*CSC: local.                                                              *)
526    Xml.pp xmlinnertypes (Some innertypesfile) ;
527    let output = applyStylesheets input mml_styles (mml_args ~explode_all) in
528     output
529 ;;
530
531 let
532  save_object_to_disk uri annobj ids_to_inner_sorts ids_to_inner_types pathname
533 =
534  let name =
535   let struri = UriManager.string_of_uri uri in
536   let idx = (String.rindex struri '/') + 1 in
537    String.sub struri idx (String.length struri - idx)
538  in
539   let path = pathname ^ "/" ^ name in
540   let xml, bodyxml =
541    Cic2Xml.print_object uri ~ids_to_inner_sorts ~ask_dtd_to_the_getter:false
542     annobj 
543   in
544   let xmlinnertypes =
545    Cic2Xml.print_inner_types uri ~ids_to_inner_sorts ~ids_to_inner_types
546     ~ask_dtd_to_the_getter:false
547   in
548    (* innertypes *)
549    let innertypesuri = UriManager.innertypesuri_of_uri uri in
550     Xml.pp ~quiet:true xmlinnertypes (Some (path ^ ".types.xml")) ;
551     Getter.register innertypesuri
552      (Configuration.annotations_url ^
553        Str.replace_first (Str.regexp "^cic:") ""
554         (UriManager.string_of_uri innertypesuri) ^ ".xml"
555      ) ;
556     (* constant type / variable / mutual inductive types definition *)
557     Xml.pp ~quiet:true xml (Some (path ^ ".xml")) ;
558     Getter.register uri
559      (Configuration.annotations_url ^
560        Str.replace_first (Str.regexp "^cic:") ""
561         (UriManager.string_of_uri uri) ^ ".xml"
562      ) ;
563     match bodyxml with
564        None -> ()
565      | Some bodyxml' ->
566         (* constant body *)
567         let bodyuri =
568          match UriManager.bodyuri_of_uri uri with
569             None -> assert false
570           | Some bodyuri -> bodyuri
571         in
572          Xml.pp ~quiet:true bodyxml' (Some (path ^ ".body.xml")) ;
573          Getter.register bodyuri
574           (Configuration.annotations_url ^
575             Str.replace_first (Str.regexp "^cic:") ""
576              (UriManager.string_of_uri bodyuri) ^ ".xml"
577           )
578 ;;
579
580
581 (* CALLBACKS *)
582
583 exception RefreshSequentException of exn;;
584 exception RefreshProofException of exn;;
585
586 let refresh_proof (output : GMathView.math_view) =
587  try
588   let uri,currentproof =
589    match !ProofEngine.proof with
590       None -> assert false
591     | Some (uri,metasenv,bo,ty) ->
592        !qed_set_sensitive (List.length metasenv = 0) ;
593        (*CSC: Wrong: [] is just plainly wrong *)
594        uri,(Cic.CurrentProof (UriManager.name_of_uri uri, metasenv, bo, ty, []))
595   in
596    let
597     (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
598      ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
599    =
600     Cic2acic.acic_object_of_cic_object currentproof
601    in
602     let mml =
603      mml_of_cic_object ~explode_all:true uri acic ids_to_inner_sorts
604       ids_to_inner_types
605     in
606      output#load_tree mml ;
607      current_cic_infos :=
608       Some (ids_to_terms,ids_to_father_ids,ids_to_conjectures,ids_to_hypotheses)
609  with
610   e ->
611  match !ProofEngine.proof with
612     None -> assert false
613   | Some (uri,metasenv,bo,ty) ->
614 prerr_endline ("Offending proof: " ^ CicPp.ppobj (Cic.CurrentProof ("questa",metasenv,bo,ty,[]))) ; flush stderr ;
615    raise (RefreshProofException e)
616 ;;
617
618 let refresh_sequent ?(empty_notebook=true) notebook =
619  try
620   match !ProofEngine.goal with
621      None ->
622       if empty_notebook then
623        begin 
624         notebook#remove_all_pages ~skip_switch_page_event:false ;
625         notebook#set_empty_page
626        end
627       else
628        notebook#proofw#unload
629    | Some metano ->
630       let metasenv =
631        match !ProofEngine.proof with
632           None -> assert false
633         | Some (_,metasenv,_,_) -> metasenv
634       in
635       let currentsequent = List.find (function (m,_,_) -> m=metano) metasenv in
636        let sequent_gdome,ids_to_terms,ids_to_father_ids,ids_to_hypotheses =
637         SequentPp.XmlPp.print_sequent metasenv currentsequent
638        in
639         let regenerate_notebook () = 
640          let skip_switch_page_event =
641           match metasenv with
642              (m,_,_)::_ when m = metano -> false
643            | _ -> true
644          in
645           notebook#remove_all_pages ~skip_switch_page_event ;
646           List.iter (function (m,_,_) -> notebook#add_page m) metasenv ;
647         in
648           if empty_notebook then
649            begin
650             regenerate_notebook () ;
651             notebook#set_current_page ~may_skip_switch_page_event:false metano
652            end
653           else
654            begin
655             let sequent_doc = Xml2Gdome.document_of_xml domImpl sequent_gdome in
656             let sequent_mml =
657              applyStylesheets sequent_doc sequent_styles sequent_args
658             in
659              notebook#set_current_page ~may_skip_switch_page_event:true metano;
660              notebook#proofw#load_tree ~dom:sequent_mml
661            end ;
662           current_goal_infos :=
663            Some (ids_to_terms,ids_to_father_ids,ids_to_hypotheses)
664  with
665   e ->
666 let metano =
667   match !ProofEngine.goal with
668      None -> assert false
669    | Some m -> m
670 in
671 let metasenv =
672  match !ProofEngine.proof with
673     None -> assert false
674   | Some (_,metasenv,_,_) -> metasenv
675 in
676 try
677 let currentsequent = List.find (function (m,_,_) -> m=metano) metasenv in
678 prerr_endline ("Offending sequent: " ^ SequentPp.TextualPp.print_sequent currentsequent) ; flush stderr ;
679    raise (RefreshSequentException e)
680 with Not_found -> prerr_endline ("Offending sequent " ^ string_of_int metano ^ " unkown."); raise (RefreshSequentException e)
681 ;;
682
683 (*
684 ignore(domImpl#saveDocumentToFile ~doc:sequent_doc
685  ~name:"/home/galata/miohelm/guruguru1" ~indent:true ()) ;
686 *)
687
688 let mml_of_cic_term metano term =
689  let metasenv =
690   match !ProofEngine.proof with
691      None -> []
692    | Some (_,metasenv,_,_) -> metasenv
693  in
694  let context =
695   match !ProofEngine.goal with
696      None -> []
697    | Some metano ->
698       let (_,canonical_context,_) =
699        List.find (function (m,_,_) -> m=metano) metasenv
700       in
701        canonical_context
702  in
703    let sequent_gdome,ids_to_terms,ids_to_father_ids,ids_to_hypotheses =
704     SequentPp.XmlPp.print_sequent metasenv (metano,context,term)
705    in
706     let sequent_doc =
707      Xml2Gdome.document_of_xml domImpl sequent_gdome
708     in
709      let res =
710       applyStylesheets sequent_doc sequent_styles sequent_args ;
711      in
712       current_scratch_infos :=
713        Some (term,ids_to_terms,ids_to_father_ids,ids_to_hypotheses) ;
714       res
715 ;;
716
717 exception OpenConjecturesStillThere;;
718 exception WrongProof;;
719
720 let pathname_of_annuri uristring =
721  Configuration.annotations_dir ^    
722   Str.replace_first (Str.regexp "^cic:") "" uristring
723 ;;
724
725 let make_dirs dirpath =
726  ignore (Unix.system ("mkdir -p " ^ dirpath))
727 ;;
728
729 let save_obj uri obj =
730  let
731   (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
732    ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
733  =
734   Cic2acic.acic_object_of_cic_object obj
735  in
736   (* let's save the theorem and register it to the getter *) 
737   let pathname = pathname_of_annuri (UriManager.buri_of_uri uri) in
738    make_dirs pathname ;
739    save_object_to_disk uri acic ids_to_inner_sorts ids_to_inner_types
740     pathname
741 ;;
742
743 let qed () =
744  match !ProofEngine.proof with
745     None -> assert false
746   | Some (uri,[],bo,ty) ->
747      if
748       CicReduction.are_convertible []
749        (CicTypeChecker.type_of_aux' [] [] bo) ty
750      then
751       begin
752        (*CSC: Wrong: [] is just plainly wrong *)
753        let proof = Cic.Constant (UriManager.name_of_uri uri,Some bo,ty,[]) in
754         let
755          (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
756           ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
757         =
758          Cic2acic.acic_object_of_cic_object proof
759         in
760          let mml =
761           mml_of_cic_object ~explode_all:false uri acic ids_to_inner_sorts
762            ids_to_inner_types
763          in
764           ((rendering_window ())#output : GMathView.math_view)#load_tree mml ;
765           !qed_set_sensitive false ;
766           (* let's save the theorem and register it to the getter *) 
767           let pathname = pathname_of_annuri (UriManager.buri_of_uri uri) in
768           make_dirs pathname ;
769           save_object_to_disk uri acic ids_to_inner_sorts ids_to_inner_types
770            pathname ;
771           current_cic_infos :=
772            Some
773             (ids_to_terms,ids_to_father_ids,ids_to_conjectures,
774              ids_to_hypotheses)
775       end
776      else
777       raise WrongProof
778   | _ -> raise OpenConjecturesStillThere
779 ;;
780
781 let save () =
782  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
783   match !ProofEngine.proof with
784      None -> assert false
785    | Some (uri, metasenv, bo, ty) ->
786       let currentproof =
787        (*CSC: Wrong: [] is just plainly wrong *)
788        Cic.CurrentProof (UriManager.name_of_uri uri,metasenv,bo,ty,[])
789       in
790        let (acurrentproof,_,_,ids_to_inner_sorts,_,_,_) =
791         Cic2acic.acic_object_of_cic_object currentproof
792        in
793         let xml, bodyxml =
794          match
795           Cic2Xml.print_object uri ~ids_to_inner_sorts
796            ~ask_dtd_to_the_getter:true acurrentproof
797          with
798             xml,Some bodyxml -> xml,bodyxml
799           | _,None -> assert false
800         in
801          Xml.pp ~quiet:true xml (Some prooffiletype) ;
802          output_html outputhtml
803           ("<h1 color=\"Green\">Current proof type saved to " ^
804            prooffiletype ^ "</h1>") ;
805          Xml.pp ~quiet:true bodyxml (Some prooffile) ;
806          output_html outputhtml
807           ("<h1 color=\"Green\">Current proof body saved to " ^
808            prooffile ^ "</h1>")
809 ;;
810
811 (* Used to typecheck the loaded proofs *)
812 let typecheck_loaded_proof metasenv bo ty =
813  let module T = CicTypeChecker in
814   ignore (
815    List.fold_left
816     (fun metasenv ((_,context,ty) as conj) ->
817       ignore (T.type_of_aux' metasenv context ty) ;
818       metasenv @ [conj]
819     ) [] metasenv) ;
820   ignore (T.type_of_aux' metasenv [] ty) ;
821   ignore (T.type_of_aux' metasenv [] bo)
822 ;;
823
824 let load () =
825  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
826  let output = ((rendering_window ())#output : GMathView.math_view) in
827  let notebook = (rendering_window ())#notebook in
828   try
829    match 
830     GToolbox.input_string ~title:"Load Unfinished Proof" ~text:"/dummy.con"
831      "Choose an URI:"
832    with
833       None -> raise NoChoice
834     | Some uri0 ->
835        let uri = UriManager.uri_of_string ("cic:" ^ uri0) in
836         match CicParser.obj_of_xml prooffiletype (Some prooffile) with
837            Cic.CurrentProof (_,metasenv,bo,ty,_) ->
838             typecheck_loaded_proof metasenv bo ty ;
839             ProofEngine.proof :=
840              Some (uri, metasenv, bo, ty) ;
841             ProofEngine.goal :=
842              (match metasenv with
843                  [] -> None
844                | (metano,_,_)::_ -> Some metano
845              ) ;
846             refresh_proof output ;
847             refresh_sequent notebook ;
848              output_html outputhtml
849               ("<h1 color=\"Green\">Current proof type loaded from " ^
850                 prooffiletype ^ "</h1>") ;
851              output_html outputhtml
852               ("<h1 color=\"Green\">Current proof body loaded from " ^
853                 prooffile ^ "</h1>") ;
854             !save_set_sensitive true
855          | _ -> assert false
856   with
857      RefreshSequentException e ->
858       output_html outputhtml
859        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
860         "sequent: " ^ Printexc.to_string e ^ "</h1>")
861    | RefreshProofException e ->
862       output_html outputhtml
863        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
864         "proof: " ^ Printexc.to_string e ^ "</h1>")
865    | e ->
866       output_html outputhtml
867        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
868 ;;
869
870 let edit_aliases () =
871  let chosen = ref false in
872  let window =
873   GWindow.window
874    ~width:400 ~modal:true ~title:"Edit Aliases..." ~border_width:2 () in
875  let vbox =
876   GPack.vbox ~border_width:0 ~packing:window#add () in
877  let scrolled_window =
878   GBin.scrolled_window ~border_width:10
879    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
880  let input = GEdit.text ~editable:true ~width:400 ~height:100
881    ~packing:scrolled_window#add () in
882  let hbox =
883   GPack.hbox ~border_width:0
884    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
885  let okb =
886   GButton.button ~label:"Ok"
887    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
888  let cancelb =
889   GButton.button ~label:"Cancel"
890    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
891  ignore (window#connect#destroy GMain.Main.quit) ;
892  ignore (cancelb#connect#clicked window#destroy) ;
893  ignore
894   (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
895  let dom,resolve_id = !id_to_uris in
896   ignore
897    (input#insert_text ~pos:0
898     (String.concat "\n"
899       (List.map
900         (function v ->
901           let uri =
902            match resolve_id v with
903               None -> assert false
904             | Some uri -> uri
905           in
906            "alias " ^ v ^ " " ^
907              (string_of_cic_textual_parser_uri uri)
908         ) dom))) ;
909   window#show () ;
910   GMain.Main.main () ;
911   if !chosen then
912    let dom,resolve_id =
913     let inputtext = input#get_chars 0 input#length in
914     let regexpr =
915      let alfa = "[a-zA-Z_-]" in
916      let digit = "[0-9]" in
917      let ident = alfa ^ "\(" ^ alfa ^ "\|" ^ digit ^ "\)*" in
918      let blanks = "\( \|\t\|\n\)+" in
919      let nonblanks = "[^ \t\n]+" in
920      let uri = "/\(" ^ ident ^ "/\)*" ^ nonblanks in (* not very strict check *)
921       Str.regexp
922        ("alias" ^ blanks ^ "\(" ^ ident ^ "\)" ^ blanks ^ "\(" ^ uri ^ "\)")
923     in
924      let rec aux n =
925       try
926        let n' = Str.search_forward regexpr inputtext n in
927         let id = Str.matched_group 2 inputtext in
928         let uri =
929          Disambiguate.cic_textual_parser_uri_of_string
930           ("cic:" ^ (Str.matched_group 5 inputtext))
931         in
932          let dom,resolve_id = aux (n' + 1) in
933           if List.mem id dom then
934            dom,resolve_id
935           else
936            id::dom,
937             (function id' -> if id = id' then Some uri else resolve_id id')
938       with
939        Not_found -> empty_id_to_uris
940      in
941       aux 0
942    in
943     id_to_uris := dom,resolve_id
944 ;;
945
946 let proveit () =
947  let module L = LogicalOperations in
948  let module G = Gdome in
949  let notebook = (rendering_window ())#notebook in
950  let output = (rendering_window ())#output in
951  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
952   match (rendering_window ())#output#get_selection with
953     Some node ->
954      let xpath =
955       ((node : Gdome.element)#getAttributeNS
956       (*CSC: OCAML DIVERGE
957       ((element : G.element)#getAttributeNS
958       *)
959         ~namespaceURI:helmns
960         ~localName:(G.domString "xref"))#to_string
961      in
962       if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
963       else
964        begin
965         try
966          match !current_cic_infos with
967             Some (ids_to_terms, ids_to_father_ids, _, _) ->
968              let id = xpath in
969               L.to_sequent id ids_to_terms ids_to_father_ids ;
970               refresh_proof output ;
971               refresh_sequent notebook
972           | None -> assert false (* "ERROR: No current term!!!" *)
973         with
974            RefreshSequentException e ->
975             output_html outputhtml
976              ("<h1 color=\"red\">Exception raised during the refresh of the " ^
977               "sequent: " ^ Printexc.to_string e ^ "</h1>")
978          | RefreshProofException e ->
979             output_html outputhtml
980              ("<h1 color=\"red\">Exception raised during the refresh of the " ^
981               "proof: " ^ Printexc.to_string e ^ "</h1>")
982          | e ->
983             output_html outputhtml
984              ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
985        end
986   | None -> assert false (* "ERROR: No selection!!!" *)
987 ;;
988
989 let focus () =
990  let module L = LogicalOperations in
991  let module G = Gdome in
992  let notebook = (rendering_window ())#notebook in
993  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
994   match (rendering_window ())#output#get_selection with
995     Some node ->
996      let xpath =
997       ((node : Gdome.element)#getAttributeNS
998       (*CSC: OCAML DIVERGE
999       ((element : G.element)#getAttributeNS
1000       *)
1001         ~namespaceURI:helmns
1002         ~localName:(G.domString "xref"))#to_string
1003      in
1004       if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
1005       else
1006        begin
1007         try
1008          match !current_cic_infos with
1009             Some (ids_to_terms, ids_to_father_ids, _, _) ->
1010              let id = xpath in
1011               L.focus id ids_to_terms ids_to_father_ids ;
1012               refresh_sequent notebook
1013           | None -> assert false (* "ERROR: No current term!!!" *)
1014         with
1015            RefreshSequentException e ->
1016             output_html outputhtml
1017              ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1018               "sequent: " ^ Printexc.to_string e ^ "</h1>")
1019          | RefreshProofException e ->
1020             output_html outputhtml
1021              ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1022               "proof: " ^ Printexc.to_string e ^ "</h1>")
1023          | e ->
1024             output_html outputhtml
1025              ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
1026        end
1027   | None -> assert false (* "ERROR: No selection!!!" *)
1028 ;;
1029
1030 exception NoPrevGoal;;
1031 exception NoNextGoal;;
1032
1033 let setgoal metano =
1034  let module L = LogicalOperations in
1035  let module G = Gdome in
1036  let notebook = (rendering_window ())#notebook in
1037  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1038   let metasenv =
1039    match !ProofEngine.proof with
1040       None -> assert false
1041     | Some (_,metasenv,_,_) -> metasenv
1042   in
1043    try
1044     refresh_sequent ~empty_notebook:false notebook
1045    with
1046       RefreshSequentException e ->
1047        output_html outputhtml
1048         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1049          "sequent: " ^ Printexc.to_string e ^ "</h1>")
1050     | e ->
1051        output_html outputhtml
1052         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
1053 ;;
1054
1055 let
1056  show_in_show_window_obj, show_in_show_window_uri, show_in_show_window_callback
1057 =
1058  let window =
1059   GWindow.window ~width:800 ~border_width:2 () in
1060  let scrolled_window =
1061   GBin.scrolled_window ~border_width:10 ~packing:window#add () in
1062  let mmlwidget =
1063   GMathView.math_view ~packing:scrolled_window#add ~width:600 ~height:400 () in
1064  let _ = window#event#connect#delete (fun _ -> window#misc#hide () ; true ) in
1065  let href = Gdome.domString "href" in
1066   let show_in_show_window_obj uri obj =
1067    let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1068     try
1069      let
1070       (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
1071        ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
1072      =
1073       Cic2acic.acic_object_of_cic_object obj
1074      in
1075       let mml =
1076        mml_of_cic_object ~explode_all:false uri acic ids_to_inner_sorts
1077         ids_to_inner_types
1078       in
1079        window#set_title (UriManager.string_of_uri uri) ;
1080        window#misc#hide () ; window#show () ;
1081        mmlwidget#load_tree mml ;
1082     with
1083      e ->
1084       output_html outputhtml
1085        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1086   in
1087   let show_in_show_window_uri uri =
1088    let obj = CicEnvironment.get_obj uri in
1089     show_in_show_window_obj uri obj
1090   in
1091    let show_in_show_window_callback mmlwidget (n : Gdome.element) =
1092     if n#hasAttributeNS ~namespaceURI:xlinkns ~localName:href then
1093      let uri =
1094       (n#getAttributeNS ~namespaceURI:xlinkns ~localName:href)#to_string
1095      in 
1096       show_in_show_window_uri (UriManager.uri_of_string uri)
1097     else
1098      if mmlwidget#get_action <> None then
1099       mmlwidget#action_toggle
1100    in
1101     let _ =
1102      mmlwidget#connect#clicked (show_in_show_window_callback mmlwidget)
1103     in
1104      show_in_show_window_obj, show_in_show_window_uri,
1105       show_in_show_window_callback
1106 ;;
1107
1108 exception NoObjectsLocated;;
1109
1110 let user_uri_choice ~title ~msg uris =
1111  let uri =
1112   match uris with
1113      [] -> raise NoObjectsLocated
1114    | [uri] -> uri
1115    | uris ->
1116       match
1117        interactive_user_uri_choice ~selection_mode:`SINGLE ~title ~msg uris
1118       with
1119          [uri] -> uri
1120        | _ -> assert false
1121  in
1122   String.sub uri 4 (String.length uri - 4)
1123 ;;
1124
1125 let locate_callback id =
1126  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1127  let result = MQueryGenerator.locate id in
1128  let uris =
1129   List.map
1130    (function uri,_ ->
1131      Disambiguate.wrong_xpointer_format_from_wrong_xpointer_format' uri)
1132    result in
1133  let html =
1134   (" <h1>Locate Query: </h1><pre>" ^ get_last_query result ^ "</pre>")
1135  in
1136   output_html outputhtml html ;
1137   user_uri_choice ~title:"Ambiguous input."
1138    ~msg:
1139      ("Ambiguous input \"" ^ id ^
1140       "\". Please, choose one interpetation:")
1141    uris
1142 ;;
1143
1144
1145 let input_or_locate_uri ~title =
1146  let uri = ref None in
1147  let window =
1148   GWindow.window
1149    ~width:400 ~modal:true ~title ~border_width:2 () in
1150  let vbox = GPack.vbox ~packing:window#add () in
1151  let hbox1 =
1152   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1153  let _ =
1154   GMisc.label ~text:"Enter a valid URI:" ~packing:(hbox1#pack ~padding:5) () in
1155  let manual_input =
1156   GEdit.entry ~editable:true
1157    ~packing:(hbox1#pack ~expand:true ~fill:true ~padding:5) () in
1158  let checkb =
1159   GButton.button ~label:"Check"
1160    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1161  let _ = checkb#misc#set_sensitive false in
1162  let hbox2 =
1163   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1164  let _ =
1165   GMisc.label ~text:"You can also enter an indentifier to locate:"
1166    ~packing:(hbox2#pack ~padding:5) () in
1167  let locate_input =
1168   GEdit.entry ~editable:true
1169    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
1170  let locateb =
1171   GButton.button ~label:"Locate"
1172    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
1173  let _ = locateb#misc#set_sensitive false in
1174  let hbox3 =
1175   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1176  let okb =
1177   GButton.button ~label:"Ok"
1178    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
1179  let _ = okb#misc#set_sensitive false in
1180  let cancelb =
1181   GButton.button ~label:"Cancel"
1182    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) ()
1183  in
1184   ignore (window#connect#destroy GMain.Main.quit) ;
1185   ignore
1186    (cancelb#connect#clicked (function () -> uri := None ; window#destroy ())) ;
1187   let check_callback () =
1188    let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1189    let uri = "cic:" ^ manual_input#text in
1190     try
1191       ignore (Getter.resolve (UriManager.uri_of_string uri)) ;
1192       output_html outputhtml "<h1 color=\"Green\">OK</h1>" ;
1193       true
1194     with
1195        Getter.Unresolved ->
1196         output_html outputhtml
1197          ("<h1 color=\"Red\">URI " ^ uri ^
1198           " does not correspond to any object.</h1>") ;
1199         false
1200      | UriManager.IllFormedUri _ ->
1201         output_html outputhtml
1202          ("<h1 color=\"Red\">URI " ^ uri ^ " is not well-formed.</h1>") ;
1203         false
1204      | e ->
1205         output_html outputhtml
1206          ("<h1 color=\"Red\">" ^ Printexc.to_string e ^ "</h1>") ;
1207         false
1208   in
1209   ignore
1210    (okb#connect#clicked
1211      (function () ->
1212        if check_callback () then
1213         begin
1214          uri := Some manual_input#text ;
1215          window#destroy ()
1216         end
1217    )) ;
1218   ignore (checkb#connect#clicked (function () -> ignore (check_callback ()))) ;
1219   ignore
1220    (manual_input#connect#changed
1221      (fun _ ->
1222        if manual_input#text = "" then
1223         begin
1224          checkb#misc#set_sensitive false ;
1225          okb#misc#set_sensitive false
1226         end
1227        else
1228         begin
1229          checkb#misc#set_sensitive true ;
1230          okb#misc#set_sensitive true
1231         end));
1232   ignore
1233    (locate_input#connect#changed
1234      (fun _ -> locateb#misc#set_sensitive (locate_input#text <> ""))) ;
1235   ignore
1236    (locateb#connect#clicked
1237      (function () ->
1238        let id = locate_input#text in
1239         manual_input#set_text (locate_callback id) ;
1240         locate_input#delete_text 0 (String.length id)
1241    )) ;
1242   window#show () ;
1243   GMain.Main.main () ;
1244   match !uri with
1245      None -> raise NoChoice
1246    | Some uri -> UriManager.uri_of_string ("cic:" ^ uri)
1247 ;;
1248
1249 exception AmbiguousInput;;
1250
1251 (* A WIDGET TO ENTER CIC TERMS *)
1252
1253 module Callbacks =
1254  struct
1255   let output_html msg = output_html (outputhtml ()) msg;;
1256   let interactive_user_uri_choice =
1257    fun ~selection_mode ?ok ?enable_button_for_non_vars ~title ~msg ~id ->
1258     interactive_user_uri_choice ~selection_mode ?ok
1259      ?enable_button_for_non_vars ~title ~msg;;
1260   let interactive_interpretation_choice = interactive_interpretation_choice;;
1261   let input_or_locate_uri = input_or_locate_uri;;
1262  end
1263 ;;
1264
1265 module Disambiguate' = Disambiguate.Make(Callbacks);;
1266
1267 class term_editor ?packing ?width ?height ?isnotempty_callback () =
1268  let input = GEdit.text ~editable:true ?width ?height ?packing () in
1269  let _ =
1270   match isnotempty_callback with
1271      None -> ()
1272    | Some callback ->
1273       ignore(input#connect#changed (function () -> callback (input#length > 0)))
1274  in
1275 object(self)
1276  method coerce = input#coerce
1277  method reset =
1278   input#delete_text 0 input#length
1279  (* CSC: txt is now a string, but should be of type Cic.term *)
1280  method set_term txt =
1281   self#reset ;
1282   ignore ((input#insert_text txt) ~pos:0)
1283  (* CSC: this method should disappear *)
1284  method get_as_string =
1285   input#get_chars 0 input#length
1286  method get_metasenv_and_term ~context ~metasenv =
1287   let name_context =
1288    List.map
1289     (function
1290         Some (n,_) -> Some n
1291       | None -> None
1292     ) context
1293   in
1294    let lexbuf = Lexing.from_string (input#get_chars 0 input#length) in
1295     let dom,mk_metasenv_and_expr =
1296      CicTextualParserContext.main
1297       ~context:name_context ~metasenv CicTextualLexer.token lexbuf
1298     in
1299      let id_to_uris',metasenv,expr =
1300       Disambiguate'.disambiguate_input context metasenv dom mk_metasenv_and_expr
1301        ~id_to_uris:!id_to_uris
1302      in
1303       id_to_uris := id_to_uris' ;
1304       metasenv,expr
1305 end
1306 ;;
1307
1308 (* OTHER FUNCTIONS *)
1309
1310 let locate () =
1311  let inputt = ((rendering_window ())#inputt : term_editor) in
1312  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1313    try
1314     match
1315      GToolbox.input_string ~title:"Locate" "Enter an identifier to locate:"
1316     with
1317        None -> raise NoChoice
1318      | Some input ->
1319         let uri = locate_callback input in
1320          inputt#set_term uri
1321    with
1322     e ->
1323      output_html outputhtml
1324       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
1325 ;;
1326
1327
1328 exception UriAlreadyInUse;;
1329 exception NotAUriToAConstant;;
1330
1331 let new_inductive () =
1332  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1333  let output = ((rendering_window ())#output : GMathView.math_view) in
1334  let notebook = (rendering_window ())#notebook in
1335
1336  let chosen = ref false in
1337  let inductive = ref true in
1338  let paramsno = ref 0 in
1339  let get_uri = ref (function _ -> assert false) in
1340  let get_base_uri = ref (function _ -> assert false) in
1341  let get_names = ref (function _ -> assert false) in
1342  let get_types_and_cons = ref (function _ -> assert false) in
1343  let get_context_and_subst = ref (function _ -> assert false) in 
1344  let window =
1345   GWindow.window
1346    ~width:600 ~modal:true ~position:`CENTER
1347    ~title:"New Block of Mutual (Co)Inductive Definitions"
1348    ~border_width:2 () in
1349  let vbox = GPack.vbox ~packing:window#add () in
1350  let hbox =
1351   GPack.hbox ~border_width:0
1352    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1353  let _ =
1354   GMisc.label ~text:"Enter the URI for the new block:"
1355    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1356  let uri_entry =
1357   GEdit.entry ~editable:true
1358    ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1359  let hbox0 =
1360   GPack.hbox ~border_width:0
1361    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1362  let _ =
1363   GMisc.label
1364    ~text:
1365      "Enter the number of left parameters in every arity and constructor type:"
1366    ~packing:(hbox0#pack ~expand:false ~fill:false ~padding:5) () in
1367  let paramsno_entry =
1368   GEdit.entry ~editable:true ~text:"0"
1369    ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
1370  let hbox1 =
1371   GPack.hbox ~border_width:0
1372    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1373  let _ =
1374   GMisc.label ~text:"Are the definitions inductive or coinductive?"
1375    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1376  let inductiveb =
1377   GButton.radio_button ~label:"Inductive"
1378    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1379  let coinductiveb =
1380   GButton.radio_button ~label:"Coinductive"
1381    ~group:inductiveb#group
1382    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1383  let hbox2 =
1384   GPack.hbox ~border_width:0
1385    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1386  let _ =
1387   GMisc.label ~text:"Enter the list of the names of the types:"
1388    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
1389  let names_entry =
1390   GEdit.entry ~editable:true
1391    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
1392  let hboxn =
1393   GPack.hbox ~border_width:0
1394    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1395  let okb =
1396   GButton.button ~label:"> Next"
1397    ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1398  let _ = okb#misc#set_sensitive true in
1399  let cancelb =
1400   GButton.button ~label:"Abort"
1401    ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1402  ignore (window#connect#destroy GMain.Main.quit) ;
1403  ignore (cancelb#connect#clicked window#destroy) ;
1404  (* First phase *)
1405  let rec phase1 () =
1406   ignore
1407    (okb#connect#clicked
1408      (function () ->
1409        try
1410         let uristr = "cic:" ^ uri_entry#text in
1411         let namesstr = names_entry#text in
1412         let paramsno' = int_of_string (paramsno_entry#text) in
1413          match Str.split (Str.regexp " +") namesstr with
1414             [] -> assert false
1415           | (he::tl) as names ->
1416              let uri = UriManager.uri_of_string (uristr ^ "/" ^ he ^ ".ind") in
1417               begin
1418                try
1419                 ignore (Getter.resolve uri) ;
1420                 raise UriAlreadyInUse
1421                with
1422                 Getter.Unresolved ->
1423                  get_uri := (function () -> uri) ; 
1424                  get_names := (function () -> names) ;
1425                  inductive := inductiveb#active ;
1426                  paramsno := paramsno' ;
1427                  phase2 ()
1428               end
1429        with
1430         e ->
1431          output_html outputhtml
1432           ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1433      ))
1434  (* Second phase *)
1435  and phase2 () =
1436   let type_widgets =
1437    List.map
1438     (function name ->
1439       let frame =
1440        GBin.frame ~label:name
1441         ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1442       let vbox = GPack.vbox ~packing:frame#add () in
1443       let hbox = GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false) () in
1444       let _ =
1445        GMisc.label ~text:("Enter its type:")
1446         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1447       let scrolled_window =
1448        GBin.scrolled_window ~border_width:5
1449         ~packing:(vbox#pack ~expand:true ~padding:0) () in
1450       let newinputt =
1451        new term_editor ~width:400 ~height:20 ~packing:scrolled_window#add ()
1452         ~isnotempty_callback:
1453          (function b ->
1454            (*non_empty_type := b ;*)
1455            okb#misc#set_sensitive true) (*(b && uri_entry#text <> ""))*)
1456       in
1457       let hbox =
1458        GPack.hbox ~border_width:0
1459         ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1460       let _ =
1461        GMisc.label ~text:("Enter the list of its constructors:")
1462         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1463       let cons_names_entry =
1464        GEdit.entry ~editable:true
1465         ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1466       (newinputt,cons_names_entry)
1467     ) (!get_names ())
1468   in
1469    vbox#remove hboxn#coerce ;
1470    let hboxn =
1471     GPack.hbox ~border_width:0
1472      ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1473    let okb =
1474     GButton.button ~label:"> Next"
1475      ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1476    let cancelb =
1477     GButton.button ~label:"Abort"
1478      ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1479    ignore (cancelb#connect#clicked window#destroy) ;
1480    ignore
1481     (okb#connect#clicked
1482       (function () ->
1483         try
1484          let names = !get_names () in
1485          let types_and_cons =
1486           List.map2
1487            (fun name (newinputt,cons_names_entry) ->
1488              let consnamesstr = cons_names_entry#text in
1489              let cons_names = Str.split (Str.regexp " +") consnamesstr in
1490              let metasenv,expr =
1491               newinputt#get_metasenv_and_term ~context:[] ~metasenv:[]
1492              in
1493               match metasenv with
1494                  [] -> expr,cons_names
1495                | _ -> raise AmbiguousInput
1496            ) names type_widgets
1497          in
1498           let uri = !get_uri () in
1499           let _ =
1500            (* Let's see if so far the definition is well-typed *)
1501            let params = [] in
1502            let paramsno = 0 in
1503            (* To test if the arities of the inductive types are well *)
1504            (* typed, we check the inductive block definition where   *)
1505            (* no constructor is given to each type.                  *)
1506            let tys =
1507             List.map2
1508              (fun name (ty,cons) -> (name, !inductive, ty, []))
1509              names types_and_cons
1510            in
1511             CicTypeChecker.typecheck_mutual_inductive_defs uri
1512              (tys,params,paramsno)
1513           in
1514            get_context_and_subst :=
1515             (function () ->
1516               let i = ref 0 in
1517                List.fold_left2
1518                 (fun (context,subst) name (ty,_) ->
1519                   let res =
1520                    (Some (Cic.Name name, Cic.Decl ty))::context,
1521                     (Cic.MutInd (uri,!i,[]))::subst
1522                   in
1523                    incr i ; res
1524                 ) ([],[]) names types_and_cons) ;
1525            let types_and_cons' =
1526             List.map2
1527              (fun name (ty,cons) -> (name, !inductive, ty, phase3 name cons))
1528              names types_and_cons
1529            in
1530             get_types_and_cons := (function () -> types_and_cons') ;
1531             chosen := true ;
1532             window#destroy ()
1533         with
1534          e ->
1535           output_html outputhtml
1536            ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1537       ))
1538  (* Third phase *)
1539  and phase3 name cons =
1540   let get_cons_types = ref (function () -> assert false) in
1541   let window2 =
1542    GWindow.window
1543     ~width:600 ~modal:true ~position:`CENTER
1544     ~title:(name ^ " Constructors")
1545     ~border_width:2 () in
1546   let vbox = GPack.vbox ~packing:window2#add () in
1547   let cons_type_widgets =
1548    List.map
1549     (function consname ->
1550       let hbox =
1551        GPack.hbox ~border_width:0
1552         ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1553       let _ =
1554        GMisc.label ~text:("Enter the type of " ^ consname ^ ":")
1555         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1556       let scrolled_window =
1557        GBin.scrolled_window ~border_width:5
1558         ~packing:(vbox#pack ~expand:true ~padding:0) () in
1559       let newinputt =
1560        new term_editor ~width:400 ~height:20 ~packing:scrolled_window#add ()
1561         ~isnotempty_callback:
1562          (function b ->
1563            (* (*non_empty_type := b ;*)
1564            okb#misc#set_sensitive true) (*(b && uri_entry#text <> ""))*) *)())
1565       in
1566        newinputt
1567     ) cons in
1568   let hboxn =
1569    GPack.hbox ~border_width:0
1570     ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1571   let okb =
1572    GButton.button ~label:"> Next"
1573     ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1574   let _ = okb#misc#set_sensitive true in
1575   let cancelb =
1576    GButton.button ~label:"Abort"
1577     ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1578   ignore (window2#connect#destroy GMain.Main.quit) ;
1579   ignore (cancelb#connect#clicked window2#destroy) ;
1580   ignore
1581    (okb#connect#clicked
1582      (function () ->
1583        try
1584         chosen := true ;
1585         let context,subst= !get_context_and_subst () in
1586         let cons_types =
1587          List.map2
1588           (fun name inputt ->
1589             let metasenv,expr =
1590              inputt#get_metasenv_and_term ~context ~metasenv:[]
1591             in
1592              match metasenv with
1593                 [] ->
1594                  let undebrujined_expr =
1595                   List.fold_left
1596                    (fun expr t -> CicSubstitution.subst t expr) expr subst
1597                  in
1598                   name, undebrujined_expr
1599               | _ -> raise AmbiguousInput
1600           ) cons cons_type_widgets
1601         in
1602          get_cons_types := (function () -> cons_types) ;
1603          window2#destroy ()
1604        with
1605         e ->
1606          output_html outputhtml
1607           ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1608      )) ;
1609   window2#show () ;
1610   GMain.Main.main () ;
1611   let okb_pressed = !chosen in
1612    chosen := false ;
1613    if (not okb_pressed) then
1614     begin
1615      window#destroy () ;
1616      assert false (* The control never reaches this point *)
1617     end
1618    else
1619     (!get_cons_types ())
1620  in
1621   phase1 () ;
1622   (* No more phases left or Abort pressed *) 
1623   window#show () ;
1624   GMain.Main.main () ;
1625   window#destroy () ;
1626   if !chosen then
1627    try
1628     let uri = !get_uri () in
1629 (*CSC: Da finire *)
1630     let params = [] in
1631     let tys = !get_types_and_cons () in
1632      let obj = Cic.InductiveDefinition tys params !paramsno in
1633       begin
1634        try
1635         prerr_endline (CicPp.ppobj obj) ;
1636         CicTypeChecker.typecheck_mutual_inductive_defs uri
1637          (tys,params,!paramsno) ;
1638         with
1639          e ->
1640           prerr_endline "Offending mutual (co)inductive type declaration:" ;
1641           prerr_endline (CicPp.ppobj obj) ;
1642       end ;
1643       (* We already know that obj is well-typed. We need to add it to the  *)
1644       (* environment in order to compute the inner-types without having to *)
1645       (* debrujin it or having to modify lots of other functions to avoid  *)
1646       (* asking the environment for the MUTINDs we are defining now.       *)
1647       CicEnvironment.put_inductive_definition uri obj ;
1648       save_obj uri obj ;
1649       show_in_show_window_obj uri obj
1650    with
1651     e ->
1652      output_html outputhtml
1653       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1654 ;;
1655
1656 let new_proof () =
1657  let inputt = ((rendering_window ())#inputt : term_editor) in
1658  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1659  let output = ((rendering_window ())#output : GMathView.math_view) in
1660  let notebook = (rendering_window ())#notebook in
1661
1662  let chosen = ref false in
1663  let get_metasenv_and_term = ref (function _ -> assert false) in
1664  let get_uri = ref (function _ -> assert false) in
1665  let non_empty_type = ref false in
1666  let window =
1667   GWindow.window
1668    ~width:600 ~modal:true ~title:"New Proof or Definition"
1669    ~border_width:2 () in
1670  let vbox = GPack.vbox ~packing:window#add () in
1671  let hbox =
1672   GPack.hbox ~border_width:0
1673    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1674  let _ =
1675   GMisc.label ~text:"Enter the URI for the new theorem or definition:"
1676    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1677  let uri_entry =
1678   GEdit.entry ~editable:true
1679    ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1680  let hbox1 =
1681   GPack.hbox ~border_width:0
1682    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1683  let _ =
1684   GMisc.label ~text:"Enter the theorem or definition type:"
1685    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1686  let scrolled_window =
1687   GBin.scrolled_window ~border_width:5
1688    ~packing:(vbox#pack ~expand:true ~padding:0) () in
1689  (* the content of the scrolled_window is moved below (see comment) *)
1690  let hbox =
1691   GPack.hbox ~border_width:0
1692    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1693  let okb =
1694   GButton.button ~label:"Ok"
1695    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1696  let _ = okb#misc#set_sensitive false in
1697  let cancelb =
1698   GButton.button ~label:"Cancel"
1699    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1700  (* moved here to have visibility of the ok button *)
1701  let newinputt =
1702   new term_editor ~width:400 ~height:100 ~packing:scrolled_window#add ()
1703    ~isnotempty_callback:
1704     (function b ->
1705       non_empty_type := b ;
1706       okb#misc#set_sensitive (b && uri_entry#text <> ""))
1707  in
1708  let _ =
1709   newinputt#set_term inputt#get_as_string ;
1710   inputt#reset in
1711  let _ =
1712   uri_entry#connect#changed
1713    (function () ->
1714      okb#misc#set_sensitive (!non_empty_type && uri_entry#text <> ""))
1715  in
1716  ignore (window#connect#destroy GMain.Main.quit) ;
1717  ignore (cancelb#connect#clicked window#destroy) ;
1718  ignore
1719   (okb#connect#clicked
1720     (function () ->
1721       chosen := true ;
1722       try
1723        let metasenv,parsed = newinputt#get_metasenv_and_term [] [] in
1724        let uristr = "cic:" ^ uri_entry#text in
1725        let uri = UriManager.uri_of_string uristr in
1726         if String.sub uristr (String.length uristr - 4) 4 <> ".con" then
1727          raise NotAUriToAConstant
1728         else
1729          begin
1730           try
1731            ignore (Getter.resolve uri) ;
1732            raise UriAlreadyInUse
1733           with
1734            Getter.Unresolved ->
1735             get_metasenv_and_term := (function () -> metasenv,parsed) ;
1736             get_uri := (function () -> uri) ; 
1737             window#destroy ()
1738          end
1739       with
1740        e ->
1741         output_html outputhtml
1742          ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1743   )) ;
1744  window#show () ;
1745  GMain.Main.main () ;
1746  if !chosen then
1747   try
1748    let metasenv,expr = !get_metasenv_and_term () in
1749     let _  = CicTypeChecker.type_of_aux' metasenv [] expr in
1750      ProofEngine.proof :=
1751       Some (!get_uri (), (1,[],expr)::metasenv, Cic.Meta (1,[]), expr) ;
1752      ProofEngine.goal := Some 1 ;
1753      refresh_sequent notebook ;
1754      refresh_proof output ;
1755      !save_set_sensitive true ;
1756      inputt#reset
1757   with
1758      RefreshSequentException e ->
1759       output_html outputhtml
1760        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1761         "sequent: " ^ Printexc.to_string e ^ "</h1>")
1762    | RefreshProofException e ->
1763       output_html outputhtml
1764        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1765         "proof: " ^ Printexc.to_string e ^ "</h1>")
1766    | e ->
1767       output_html outputhtml
1768        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1769 ;;
1770
1771 let check_term_in_scratch scratch_window metasenv context expr = 
1772  try
1773   let ty = CicTypeChecker.type_of_aux' metasenv context expr in
1774    let mml = mml_of_cic_term 111 (Cic.Cast (expr,ty)) in
1775     scratch_window#show () ;
1776     scratch_window#mmlwidget#load_tree ~dom:mml
1777  with
1778   e ->
1779    print_endline ("? " ^ CicPp.ppterm expr) ;
1780    raise e
1781 ;;
1782
1783 let check scratch_window () =
1784  let inputt = ((rendering_window ())#inputt : term_editor) in
1785  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1786   let metasenv =
1787    match !ProofEngine.proof with
1788       None -> []
1789     | Some (_,metasenv,_,_) -> metasenv
1790   in
1791   let context =
1792    match !ProofEngine.goal with
1793       None -> []
1794     | Some metano ->
1795        let (_,canonical_context,_) =
1796         List.find (function (m,_,_) -> m=metano) metasenv
1797        in
1798         canonical_context
1799   in
1800    try
1801     let metasenv',expr = inputt#get_metasenv_and_term context metasenv in
1802      check_term_in_scratch scratch_window metasenv' context expr
1803    with
1804     e ->
1805      output_html outputhtml
1806       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1807 ;;
1808
1809
1810 (***********************)
1811 (*       TACTICS       *)
1812 (***********************)
1813
1814 let call_tactic tactic () =
1815  let notebook = (rendering_window ())#notebook in
1816  let output = ((rendering_window ())#output : GMathView.math_view) in
1817  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1818  let savedproof = !ProofEngine.proof in
1819  let savedgoal  = !ProofEngine.goal in
1820   begin
1821    try
1822     tactic () ;
1823     refresh_sequent notebook ;
1824     refresh_proof output
1825    with
1826       RefreshSequentException e ->
1827        output_html outputhtml
1828         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1829          "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1830        ProofEngine.proof := savedproof ;
1831        ProofEngine.goal := savedgoal ;
1832        refresh_sequent notebook
1833     | RefreshProofException e ->
1834        output_html outputhtml
1835         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1836          "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1837        ProofEngine.proof := savedproof ;
1838        ProofEngine.goal := savedgoal ;
1839        refresh_sequent notebook ;
1840        refresh_proof output
1841     | e ->
1842        output_html outputhtml
1843         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1844        ProofEngine.proof := savedproof ;
1845        ProofEngine.goal := savedgoal ;
1846   end
1847 ;;
1848
1849 let call_tactic_with_input tactic () =
1850  let notebook = (rendering_window ())#notebook in
1851  let output = ((rendering_window ())#output : GMathView.math_view) in
1852  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1853  let inputt = ((rendering_window ())#inputt : term_editor) in
1854  let savedproof = !ProofEngine.proof in
1855  let savedgoal  = !ProofEngine.goal in
1856   let uri,metasenv,bo,ty =
1857    match !ProofEngine.proof with
1858       None -> assert false
1859     | Some (uri,metasenv,bo,ty) -> uri,metasenv,bo,ty
1860   in
1861    let canonical_context =
1862     match !ProofEngine.goal with
1863        None -> assert false
1864      | Some metano ->
1865         let (_,canonical_context,_) =
1866          List.find (function (m,_,_) -> m=metano) metasenv
1867         in
1868          canonical_context
1869    in
1870     try
1871      let metasenv',expr =
1872       inputt#get_metasenv_and_term canonical_context metasenv
1873      in
1874       ProofEngine.proof := Some (uri,metasenv',bo,ty) ;
1875       tactic expr ;
1876       refresh_sequent notebook ;
1877       refresh_proof output ;
1878       inputt#reset
1879     with
1880        RefreshSequentException e ->
1881         output_html outputhtml
1882          ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1883           "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1884         ProofEngine.proof := savedproof ;
1885         ProofEngine.goal := savedgoal ;
1886         refresh_sequent notebook
1887      | RefreshProofException e ->
1888         output_html outputhtml
1889          ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1890           "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1891         ProofEngine.proof := savedproof ;
1892         ProofEngine.goal := savedgoal ;
1893         refresh_sequent notebook ;
1894         refresh_proof output
1895      | e ->
1896         output_html outputhtml
1897          ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1898         ProofEngine.proof := savedproof ;
1899         ProofEngine.goal := savedgoal ;
1900 ;;
1901
1902 let call_tactic_with_goal_input tactic () =
1903  let module L = LogicalOperations in
1904  let module G = Gdome in
1905   let notebook = (rendering_window ())#notebook in
1906   let output = ((rendering_window ())#output : GMathView.math_view) in
1907   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1908   let savedproof = !ProofEngine.proof in
1909   let savedgoal  = !ProofEngine.goal in
1910    match notebook#proofw#get_selection with
1911      Some node ->
1912       let xpath =
1913        ((node : Gdome.element)#getAttributeNS
1914          ~namespaceURI:helmns
1915          ~localName:(G.domString "xref"))#to_string
1916       in
1917        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
1918        else
1919         begin
1920          try
1921           match !current_goal_infos with
1922              Some (ids_to_terms, ids_to_father_ids,_) ->
1923               let id = xpath in
1924                tactic (Hashtbl.find ids_to_terms id) ;
1925                refresh_sequent notebook ;
1926                refresh_proof output
1927            | None -> assert false (* "ERROR: No current term!!!" *)
1928          with
1929             RefreshSequentException e ->
1930              output_html outputhtml
1931               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1932                "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1933              ProofEngine.proof := savedproof ;
1934              ProofEngine.goal := savedgoal ;
1935              refresh_sequent notebook
1936           | RefreshProofException e ->
1937              output_html outputhtml
1938               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1939                "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1940              ProofEngine.proof := savedproof ;
1941              ProofEngine.goal := savedgoal ;
1942              refresh_sequent notebook ;
1943              refresh_proof output
1944           | e ->
1945              output_html outputhtml
1946               ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1947              ProofEngine.proof := savedproof ;
1948              ProofEngine.goal := savedgoal ;
1949         end
1950    | None ->
1951       output_html outputhtml
1952        ("<h1 color=\"red\">No term selected</h1>")
1953 ;;
1954
1955 let call_tactic_with_input_and_goal_input tactic () =
1956  let module L = LogicalOperations in
1957  let module G = Gdome in
1958   let notebook = (rendering_window ())#notebook in
1959   let output = ((rendering_window ())#output : GMathView.math_view) in
1960   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1961   let inputt = ((rendering_window ())#inputt : term_editor) in
1962   let savedproof = !ProofEngine.proof in
1963   let savedgoal  = !ProofEngine.goal in
1964    match notebook#proofw#get_selection with
1965      Some node ->
1966       let xpath =
1967        ((node : Gdome.element)#getAttributeNS
1968          ~namespaceURI:helmns
1969          ~localName:(G.domString "xref"))#to_string
1970       in
1971        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
1972        else
1973         begin
1974          try
1975           match !current_goal_infos with
1976              Some (ids_to_terms, ids_to_father_ids,_) ->
1977               let id = xpath in
1978                let uri,metasenv,bo,ty =
1979                 match !ProofEngine.proof with
1980                    None -> assert false
1981                  | Some (uri,metasenv,bo,ty) -> uri,metasenv,bo,ty
1982                in
1983                 let canonical_context =
1984                  match !ProofEngine.goal with
1985                     None -> assert false
1986                   | Some metano ->
1987                      let (_,canonical_context,_) =
1988                       List.find (function (m,_,_) -> m=metano) metasenv
1989                      in
1990                       canonical_context in
1991                 let (metasenv',expr) =
1992                  inputt#get_metasenv_and_term canonical_context metasenv
1993                 in
1994                  ProofEngine.proof := Some (uri,metasenv',bo,ty) ;
1995                  tactic ~goal_input:(Hashtbl.find ids_to_terms id)
1996                   ~input:expr ;
1997                  refresh_sequent notebook ;
1998                  refresh_proof output ;
1999                  inputt#reset
2000            | None -> assert false (* "ERROR: No current term!!!" *)
2001          with
2002             RefreshSequentException e ->
2003              output_html outputhtml
2004               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2005                "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
2006              ProofEngine.proof := savedproof ;
2007              ProofEngine.goal := savedgoal ;
2008              refresh_sequent notebook
2009           | RefreshProofException e ->
2010              output_html outputhtml
2011               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2012                "proof: " ^ Printexc.to_string e ^ "</h1>") ;
2013              ProofEngine.proof := savedproof ;
2014              ProofEngine.goal := savedgoal ;
2015              refresh_sequent notebook ;
2016              refresh_proof output
2017           | e ->
2018              output_html outputhtml
2019               ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2020              ProofEngine.proof := savedproof ;
2021              ProofEngine.goal := savedgoal ;
2022         end
2023    | None ->
2024       output_html outputhtml
2025        ("<h1 color=\"red\">No term selected</h1>")
2026 ;;
2027
2028 let call_tactic_with_goal_input_in_scratch tactic scratch_window () =
2029  let module L = LogicalOperations in
2030  let module G = Gdome in
2031   let mmlwidget = (scratch_window#mmlwidget : GMathView.math_view) in
2032   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2033   let savedproof = !ProofEngine.proof in
2034   let savedgoal  = !ProofEngine.goal in
2035    match mmlwidget#get_selection with
2036      Some node ->
2037       let xpath =
2038        ((node : Gdome.element)#getAttributeNS
2039          ~namespaceURI:helmns
2040          ~localName:(G.domString "xref"))#to_string
2041       in
2042        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
2043        else
2044         begin
2045          try
2046           match !current_scratch_infos with
2047              (* term is the whole goal in the scratch_area *)
2048              Some (term,ids_to_terms, ids_to_father_ids,_) ->
2049               let id = xpath in
2050                let expr = tactic term (Hashtbl.find ids_to_terms id) in
2051                 let mml = mml_of_cic_term 111 expr in
2052                  scratch_window#show () ;
2053                  scratch_window#mmlwidget#load_tree ~dom:mml
2054            | None -> assert false (* "ERROR: No current term!!!" *)
2055          with
2056           e ->
2057            output_html outputhtml
2058             ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
2059         end
2060    | None ->
2061       output_html outputhtml
2062        ("<h1 color=\"red\">No term selected</h1>")
2063 ;;
2064
2065 let call_tactic_with_hypothesis_input tactic () =
2066  let module L = LogicalOperations in
2067  let module G = Gdome in
2068   let notebook = (rendering_window ())#notebook in
2069   let output = ((rendering_window ())#output : GMathView.math_view) in
2070   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2071   let savedproof = !ProofEngine.proof in
2072   let savedgoal  = !ProofEngine.goal in
2073    match notebook#proofw#get_selection with
2074      Some node ->
2075       let xpath =
2076        ((node : Gdome.element)#getAttributeNS
2077          ~namespaceURI:helmns
2078          ~localName:(G.domString "xref"))#to_string
2079       in
2080        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
2081        else
2082         begin
2083          try
2084           match !current_goal_infos with
2085              Some (_,_,ids_to_hypotheses) ->
2086               let id = xpath in
2087                tactic (Hashtbl.find ids_to_hypotheses id) ;
2088                refresh_sequent notebook ;
2089                refresh_proof output
2090            | None -> assert false (* "ERROR: No current term!!!" *)
2091          with
2092             RefreshSequentException e ->
2093              output_html outputhtml
2094               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2095                "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
2096              ProofEngine.proof := savedproof ;
2097              ProofEngine.goal := savedgoal ;
2098              refresh_sequent notebook
2099           | RefreshProofException e ->
2100              output_html outputhtml
2101               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2102                "proof: " ^ Printexc.to_string e ^ "</h1>") ;
2103              ProofEngine.proof := savedproof ;
2104              ProofEngine.goal := savedgoal ;
2105              refresh_sequent notebook ;
2106              refresh_proof output
2107           | e ->
2108              output_html outputhtml
2109               ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2110              ProofEngine.proof := savedproof ;
2111              ProofEngine.goal := savedgoal ;
2112         end
2113    | None ->
2114       output_html outputhtml
2115        ("<h1 color=\"red\">No term selected</h1>")
2116 ;;
2117
2118
2119 let intros = call_tactic ProofEngine.intros;;
2120 let exact = call_tactic_with_input ProofEngine.exact;;
2121 let apply = call_tactic_with_input ProofEngine.apply;;
2122 let elimintrossimpl = call_tactic_with_input ProofEngine.elim_intros_simpl;;
2123 let elimtype = call_tactic_with_input ProofEngine.elim_type;;
2124 let whd = call_tactic_with_goal_input ProofEngine.whd;;
2125 let reduce = call_tactic_with_goal_input ProofEngine.reduce;;
2126 let simpl = call_tactic_with_goal_input ProofEngine.simpl;;
2127 let fold_whd = call_tactic_with_input ProofEngine.fold_whd;;
2128 let fold_reduce = call_tactic_with_input ProofEngine.fold_reduce;;
2129 let fold_simpl = call_tactic_with_input ProofEngine.fold_simpl;;
2130 let cut = call_tactic_with_input ProofEngine.cut;;
2131 let change = call_tactic_with_input_and_goal_input ProofEngine.change;;
2132 let letin = call_tactic_with_input ProofEngine.letin;;
2133 let ring = call_tactic ProofEngine.ring;;
2134 let clearbody = call_tactic_with_hypothesis_input ProofEngine.clearbody;;
2135 let clear = call_tactic_with_hypothesis_input ProofEngine.clear;;
2136 let fourier = call_tactic ProofEngine.fourier;;
2137 let rewritesimpl = call_tactic_with_input ProofEngine.rewrite_simpl;;
2138 let rewritebacksimpl = call_tactic_with_input ProofEngine.rewrite_back_simpl;;
2139 let replace = call_tactic_with_input_and_goal_input ProofEngine.replace;;
2140 let reflexivity = call_tactic ProofEngine.reflexivity;;
2141 let symmetry = call_tactic ProofEngine.symmetry;;
2142 let transitivity = call_tactic_with_input ProofEngine.transitivity;;
2143 let exists = call_tactic ProofEngine.exists;;
2144 let split = call_tactic ProofEngine.split;;
2145 let left = call_tactic ProofEngine.left;;
2146 let right = call_tactic ProofEngine.right;;
2147 let assumption = call_tactic ProofEngine.assumption;;
2148 let generalize = call_tactic_with_goal_input ProofEngine.generalize;;
2149 let absurd = call_tactic_with_input ProofEngine.absurd;;
2150 let contradiction = call_tactic ProofEngine.contradiction;;
2151 (* Galla chiede: come dare alla tattica la lista di termini da decomporre?
2152 let decompose = call_tactic_with_input_and_goal_input ProofEngine.decompose;;
2153 *)
2154
2155 let whd_in_scratch scratch_window =
2156  call_tactic_with_goal_input_in_scratch ProofEngine.whd_in_scratch
2157   scratch_window
2158 ;;
2159 let reduce_in_scratch scratch_window =
2160  call_tactic_with_goal_input_in_scratch ProofEngine.reduce_in_scratch
2161   scratch_window
2162 ;;
2163 let simpl_in_scratch scratch_window =
2164  call_tactic_with_goal_input_in_scratch ProofEngine.simpl_in_scratch
2165   scratch_window
2166 ;;
2167
2168
2169
2170 (**********************)
2171 (*   END OF TACTICS   *)
2172 (**********************)
2173
2174
2175 let show () =
2176  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2177   try
2178    show_in_show_window_uri (input_or_locate_uri ~title:"Show")
2179   with
2180    e ->
2181     output_html outputhtml
2182      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2183 ;;
2184
2185 exception NotADefinition;;
2186
2187 let open_ () =
2188  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2189  let output = ((rendering_window ())#output : GMathView.math_view) in
2190  let notebook = (rendering_window ())#notebook in
2191    try
2192     let uri = input_or_locate_uri ~title:"Open" in
2193      CicTypeChecker.typecheck uri ;
2194      let metasenv,bo,ty =
2195       match CicEnvironment.get_cooked_obj uri with
2196          Cic.Constant (_,Some bo,ty,_) -> [],bo,ty
2197        | Cic.CurrentProof (_,metasenv,bo,ty,_) -> metasenv,bo,ty
2198        | Cic.Constant _
2199        | Cic.Variable _
2200        | Cic.InductiveDefinition _ -> raise NotADefinition
2201      in
2202       ProofEngine.proof :=
2203        Some (uri, metasenv, bo, ty) ;
2204       ProofEngine.goal := None ;
2205       refresh_sequent notebook ;
2206       refresh_proof output
2207    with
2208       RefreshSequentException e ->
2209        output_html outputhtml
2210         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2211          "sequent: " ^ Printexc.to_string e ^ "</h1>")
2212     | RefreshProofException e ->
2213        output_html outputhtml
2214         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2215          "proof: " ^ Printexc.to_string e ^ "</h1>")
2216     | e ->
2217        output_html outputhtml
2218         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2219 ;;
2220
2221 let show_query_results results =
2222  let window =
2223   GWindow.window
2224    ~modal:false ~title:"Query results." ~border_width:2 () in
2225  let vbox = GPack.vbox ~packing:window#add () in
2226  let hbox =
2227   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2228  let lMessage =
2229   GMisc.label
2230    ~text:"Click on a URI to show that object"
2231    ~packing:hbox#add () in
2232  let scrolled_window =
2233   GBin.scrolled_window ~border_width:10 ~height:400 ~width:600
2234    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2235  let clist = GList.clist ~columns:1 ~packing:scrolled_window#add () in
2236   ignore
2237    (List.map
2238      (function (uri,_) ->
2239        let n =
2240         clist#append [uri]
2241        in
2242         clist#set_row ~selectable:false n
2243      ) results
2244    ) ;
2245   clist#columns_autosize () ;
2246   ignore
2247    (clist#connect#select_row
2248      (fun ~row ~column ~event ->
2249        let (uristr,_) = List.nth results row in
2250         match
2251          Disambiguate.cic_textual_parser_uri_of_string
2252           (Disambiguate.wrong_xpointer_format_from_wrong_xpointer_format'
2253             uristr)
2254         with
2255            CicTextualParser0.ConUri uri
2256          | CicTextualParser0.VarUri uri
2257          | CicTextualParser0.IndTyUri (uri,_)
2258          | CicTextualParser0.IndConUri (uri,_,_) ->
2259             show_in_show_window_uri uri
2260      )
2261    ) ;
2262   window#show ()
2263 ;;
2264
2265 let refine_constraints (must_obj,must_rel,must_sort) =
2266  let chosen = ref false in
2267  let use_only = ref false in
2268  let window =
2269   GWindow.window
2270    ~modal:true ~title:"Constraints refinement."
2271    ~width:800 ~border_width:2 () in
2272  let vbox = GPack.vbox ~packing:window#add () in
2273  let hbox =
2274   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2275  let lMessage =
2276   GMisc.label
2277    ~text: "\"Only\" constraints can be enforced or not."
2278    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2279  let onlyb =
2280   GButton.toggle_button ~label:"Enforce \"only\" constraints"
2281    ~active:false ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2282  in
2283   ignore
2284    (onlyb#connect#toggled (function () -> use_only := onlyb#active)) ;
2285  (* Notebook for the constraints choice *)
2286  let notebook =
2287   GPack.notebook ~scrollable:true
2288    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2289  (* Rel constraints *)
2290  let label =
2291   GMisc.label
2292    ~text: "Constraints on Rels" () in
2293  let vbox' =
2294   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
2295    () in
2296  let hbox =
2297   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
2298  let lMessage =
2299   GMisc.label
2300    ~text: "You can now specify the constraints on Rels."
2301    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2302  let expected_height = 25 * (List.length must_rel + 2) in
2303  let height = if expected_height > 400 then 400 else expected_height in
2304  let scrolled_window =
2305   GBin.scrolled_window ~border_width:10 ~height ~width:600
2306    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
2307  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
2308  let rel_constraints =
2309   List.map
2310    (function (position,depth) ->
2311      let hbox =
2312       GPack.hbox
2313        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
2314      let lMessage =
2315       GMisc.label
2316        ~text:position
2317        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2318      match depth with
2319         None -> position, ref None
2320       | Some depth' ->
2321          let mutable_ref = ref (Some depth') in
2322          let depthb =
2323           GButton.toggle_button
2324            ~label:("depth = " ^ string_of_int depth') ~active:true
2325            ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2326          in
2327           ignore
2328            (depthb#connect#toggled
2329              (function () ->
2330                let sel_depth = if depthb#active then Some depth' else None in
2331                 mutable_ref := sel_depth
2332             )) ;
2333           position, mutable_ref
2334    ) must_rel in
2335  (* Sort constraints *)
2336  let label =
2337   GMisc.label
2338    ~text: "Constraints on Sorts" () in
2339  let vbox' =
2340   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
2341    () in
2342  let hbox =
2343   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
2344  let lMessage =
2345   GMisc.label
2346    ~text: "You can now specify the constraints on Sorts."
2347    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2348  let expected_height = 25 * (List.length must_sort + 2) in
2349  let height = if expected_height > 400 then 400 else expected_height in
2350  let scrolled_window =
2351   GBin.scrolled_window ~border_width:10 ~height ~width:600
2352    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
2353  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
2354  let sort_constraints =
2355   List.map
2356    (function (position,depth,sort) ->
2357      let hbox =
2358       GPack.hbox
2359        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
2360      let lMessage =
2361       GMisc.label
2362        ~text:(sort ^ " " ^ position)
2363        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2364      match depth with
2365         None -> position, ref None, sort
2366       | Some depth' ->
2367          let mutable_ref = ref (Some depth') in
2368          let depthb =
2369           GButton.toggle_button ~label:("depth = " ^ string_of_int depth')
2370            ~active:true
2371            ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2372          in
2373           ignore
2374            (depthb#connect#toggled
2375              (function () ->
2376                let sel_depth = if depthb#active then Some depth' else None in
2377                 mutable_ref := sel_depth
2378             )) ;
2379           position, mutable_ref, sort
2380    ) must_sort in
2381  (* Obj constraints *)
2382  let label =
2383   GMisc.label
2384    ~text: "Constraints on constants" () in
2385  let vbox' =
2386   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
2387    () in
2388  let hbox =
2389   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
2390  let lMessage =
2391   GMisc.label
2392    ~text: "You can now specify the constraints on constants."
2393    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2394  let expected_height = 25 * (List.length must_obj + 2) in
2395  let height = if expected_height > 400 then 400 else expected_height in
2396  let scrolled_window =
2397   GBin.scrolled_window ~border_width:10 ~height ~width:600
2398    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
2399  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
2400  let obj_constraints =
2401   List.map
2402    (function (uri,position,depth) ->
2403      let hbox =
2404       GPack.hbox
2405        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
2406      let lMessage =
2407       GMisc.label
2408        ~text:(uri ^ " " ^ position)
2409        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2410      match depth with
2411         None -> uri, position, ref None
2412       | Some depth' ->
2413          let mutable_ref = ref (Some depth') in
2414          let depthb =
2415           GButton.toggle_button ~label:("depth = " ^ string_of_int depth')
2416            ~active:true
2417            ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2418          in
2419           ignore
2420            (depthb#connect#toggled
2421              (function () ->
2422                let sel_depth = if depthb#active then Some depth' else None in
2423                 mutable_ref := sel_depth
2424             )) ;
2425           uri, position, mutable_ref
2426    ) must_obj in
2427  (* Confirm/abort buttons *)
2428  let hbox =
2429   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2430  let okb =
2431   GButton.button ~label:"Ok"
2432    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2433  let cancelb =
2434   GButton.button ~label:"Abort"
2435    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2436  in
2437   ignore (window#connect#destroy GMain.Main.quit) ;
2438   ignore (cancelb#connect#clicked window#destroy) ;
2439   ignore
2440    (okb#connect#clicked (function () -> chosen := true ; window#destroy ()));
2441   window#set_position `CENTER ;
2442   window#show () ;
2443   GMain.Main.main () ;
2444   if !chosen then
2445    let chosen_must_rel =
2446     List.map
2447      (function (position,ref_depth) -> position,!ref_depth) rel_constraints in
2448    let chosen_must_sort =
2449     List.map
2450      (function (position,ref_depth,sort) -> position,!ref_depth,sort)
2451      sort_constraints
2452    in
2453    let chosen_must_obj =
2454     List.map
2455      (function (uri,position,ref_depth) -> uri,position,!ref_depth)
2456      obj_constraints
2457    in
2458     (chosen_must_obj,chosen_must_rel,chosen_must_sort),
2459      (if !use_only then
2460 (*CSC: ???????????????????????? I assume that must and only are the same... *)
2461        Some chosen_must_obj,Some chosen_must_rel,Some chosen_must_sort
2462       else
2463        None,None,None
2464      )
2465   else
2466    raise NoChoice
2467 ;;
2468
2469 let completeSearchPattern () =
2470  let inputt = ((rendering_window ())#inputt : term_editor) in
2471  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2472   try
2473    let metasenv,expr = inputt#get_metasenv_and_term ~context:[] ~metasenv:[] in
2474    let must = MQueryLevels2.get_constraints expr in
2475    let must',only = refine_constraints must in
2476    let results = MQueryGenerator.searchPattern must' only in 
2477     show_query_results results
2478   with
2479    e ->
2480     output_html outputhtml
2481      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2482 ;;
2483
2484 let insertQuery () =
2485  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2486   try
2487    let chosen = ref None in
2488    let window =
2489     GWindow.window
2490      ~modal:true ~title:"Insert Query (Experts Only)" ~border_width:2 () in
2491    let vbox = GPack.vbox ~packing:window#add () in
2492    let label =
2493     GMisc.label ~text:"Insert Query. For Experts Only."
2494      ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2495    let scrolled_window =
2496     GBin.scrolled_window ~border_width:10 ~height:400 ~width:600
2497      ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2498    let input = GEdit.text ~editable:true
2499     ~packing:scrolled_window#add () in
2500    let hbox =
2501     GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2502    let okb =
2503     GButton.button ~label:"Ok"
2504      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2505    let loadb =
2506     GButton.button ~label:"Load from file..."
2507      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2508    let cancelb =
2509     GButton.button ~label:"Abort"
2510      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2511    ignore (window#connect#destroy GMain.Main.quit) ;
2512    ignore (cancelb#connect#clicked window#destroy) ;
2513    ignore
2514     (okb#connect#clicked
2515       (function () ->
2516         chosen := Some (input#get_chars 0 input#length) ; window#destroy ())) ;
2517    ignore
2518     (loadb#connect#clicked
2519       (function () ->
2520         match
2521          GToolbox.select_file ~title:"Select Query File" ()
2522         with
2523            None -> ()
2524          | Some filename ->
2525             let inch = open_in filename in
2526              let rec read_file () =
2527               try
2528                let line = input_line inch in
2529                 line ^ "\n" ^ read_file ()
2530               with
2531                End_of_file -> ""
2532              in
2533               let text = read_file () in
2534                input#delete_text 0 input#length ;
2535                ignore (input#insert_text text ~pos:0))) ;
2536    window#set_position `CENTER ;
2537    window#show () ;
2538    GMain.Main.main () ;
2539    match !chosen with
2540       None -> ()
2541     | Some q ->
2542        let results =
2543         Mqint.execute (MQueryUtil.query_of_text (Lexing.from_string q))
2544        in
2545         show_query_results results
2546   with
2547    e ->
2548     output_html outputhtml
2549      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2550 ;;
2551
2552 let choose_must list_of_must only =
2553  let chosen = ref None in
2554  let user_constraints = ref [] in
2555  let window =
2556   GWindow.window
2557    ~modal:true ~title:"Query refinement." ~border_width:2 () in
2558  let vbox = GPack.vbox ~packing:window#add () in
2559  let hbox =
2560   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2561  let lMessage =
2562   GMisc.label
2563    ~text:
2564     ("You can now specify the genericity of the query. " ^
2565      "The more generic the slower.")
2566    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2567  let hbox =
2568   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2569  let lMessage =
2570   GMisc.label
2571    ~text:
2572     "Suggestion: start with faster queries before moving to more generic ones."
2573    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2574  let notebook =
2575   GPack.notebook ~scrollable:true
2576    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2577  let _ =
2578   let page = ref 0 in
2579   let last = List.length list_of_must in
2580   List.map
2581    (function must ->
2582      incr page ;
2583      let label =
2584       GMisc.label ~text:
2585        (if !page = 1 then "More generic" else
2586          if !page = last then "More precise" else "          ") () in
2587      let expected_height = 25 * (List.length must + 2) in
2588      let height = if expected_height > 400 then 400 else expected_height in
2589      let scrolled_window =
2590       GBin.scrolled_window ~border_width:10 ~height ~width:600
2591        ~packing:(notebook#append_page ~tab_label:label#coerce) () in
2592      let clist =
2593         GList.clist ~columns:2 ~packing:scrolled_window#add
2594          ~titles:["URI" ; "Position"] ()
2595      in
2596       ignore
2597        (List.map
2598          (function (uri,position) ->
2599            let n =
2600             clist#append 
2601              [uri; if position then "MainConclusion" else "Conclusion"]
2602            in
2603             clist#set_row ~selectable:false n
2604          ) must
2605        ) ;
2606       clist#columns_autosize ()
2607    ) list_of_must in
2608  let _ =
2609   let label = GMisc.label ~text:"User provided" () in
2610   let vbox =
2611    GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce) () in
2612   let hbox =
2613    GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2614   let lMessage =
2615    GMisc.label
2616    ~text:"Select the constraints that must be satisfied and press OK."
2617    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2618   let expected_height = 25 * (List.length only + 2) in
2619   let height = if expected_height > 400 then 400 else expected_height in
2620   let scrolled_window =
2621    GBin.scrolled_window ~border_width:10 ~height ~width:600
2622     ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2623   let clist =
2624    GList.clist ~columns:2 ~packing:scrolled_window#add
2625     ~selection_mode:`EXTENDED
2626     ~titles:["URI" ; "Position"] ()
2627   in
2628    ignore
2629     (List.map
2630       (function (uri,position) ->
2631         let n =
2632          clist#append 
2633           [uri; if position then "MainConclusion" else "Conclusion"]
2634         in
2635          clist#set_row ~selectable:true n
2636       ) only
2637     ) ;
2638    clist#columns_autosize () ;
2639    ignore
2640     (clist#connect#select_row
2641       (fun ~row ~column ~event ->
2642         user_constraints := (List.nth only row)::!user_constraints)) ;
2643    ignore
2644     (clist#connect#unselect_row
2645       (fun ~row ~column ~event ->
2646         user_constraints :=
2647          List.filter
2648           (function uri -> uri != (List.nth only row)) !user_constraints)) ;
2649  in
2650  let hbox =
2651   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2652  let okb =
2653   GButton.button ~label:"Ok"
2654    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2655  let cancelb =
2656   GButton.button ~label:"Abort"
2657    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2658  (* actions *)
2659  ignore (window#connect#destroy GMain.Main.quit) ;
2660  ignore (cancelb#connect#clicked window#destroy) ;
2661  ignore
2662   (okb#connect#clicked
2663     (function () -> chosen := Some notebook#current_page ; window#destroy ())) ;
2664  window#set_position `CENTER ;
2665  window#show () ;
2666  GMain.Main.main () ;
2667  match !chosen with
2668     None -> raise NoChoice
2669   | Some n ->
2670      if n = List.length list_of_must then
2671       (* user provided constraints *)
2672       !user_constraints
2673      else
2674       List.nth list_of_must n
2675 ;;
2676
2677 let searchPattern () =
2678  let inputt = ((rendering_window ())#inputt : term_editor) in
2679  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2680   try
2681     let metasenv =
2682      match !ProofEngine.proof with
2683         None -> assert false
2684       | Some (_,metasenv,_,_) -> metasenv
2685     in
2686      match !ProofEngine.goal with
2687         None -> ()
2688       | Some metano ->
2689          let (_, ey ,ty) = List.find (function (m,_,_) -> m=metano) metasenv in
2690           let list_of_must,only = MQueryLevels.out_restr metasenv ey ty in
2691           let must = choose_must list_of_must only in
2692           let torigth_restriction (u,b) =
2693            let p =
2694             if b then
2695              "http://www.cs.unibo.it/helm/schemas/schema-helm#MainConclusion" 
2696             else
2697              "http://www.cs.unibo.it/helm/schemas/schema-helm#InConclusion"
2698            in
2699             (u,p,None)
2700           in
2701           let rigth_must = List.map torigth_restriction must in
2702           let rigth_only = Some (List.map torigth_restriction only) in
2703           let result =
2704            MQueryGenerator.searchPattern
2705             (rigth_must,[],[]) (rigth_only,None,None) in 
2706           let uris =
2707            List.map
2708             (function uri,_ ->
2709               Disambiguate.wrong_xpointer_format_from_wrong_xpointer_format' uri
2710             ) result in
2711           let html =
2712            " <h1>Backward Query: </h1>" ^
2713            " <pre>" ^ get_last_query result ^ "</pre>"
2714           in
2715            output_html outputhtml html ;
2716            let uris',exc =
2717             let rec filter_out =
2718              function
2719                 [] -> [],""
2720               | uri::tl ->
2721                  let tl',exc = filter_out tl in
2722                   try
2723                    if
2724                     ProofEngine.can_apply
2725                      (term_of_cic_textual_parser_uri
2726                       (Disambiguate.cic_textual_parser_uri_of_string uri))
2727                    then
2728                     uri::tl',exc
2729                    else
2730                     tl',exc
2731                   with
2732                    e ->
2733                     let exc' =
2734                      "<h1 color=\"red\"> ^ Exception raised trying to apply " ^
2735                       uri ^ ": " ^ Printexc.to_string e ^ " </h1>" ^ exc
2736                     in
2737                      tl',exc'
2738             in
2739              filter_out uris
2740            in
2741             let html' =
2742              " <h1>Objects that can actually be applied: </h1> " ^
2743              String.concat "<br>" uris' ^ exc ^
2744              " <h1>Number of false matches: " ^
2745               string_of_int (List.length uris - List.length uris') ^ "</h1>" ^
2746              " <h1>Number of good matches: " ^
2747               string_of_int (List.length uris') ^ "</h1>"
2748             in
2749              output_html outputhtml html' ;
2750              let uri' =
2751               user_uri_choice ~title:"Ambiguous input."
2752               ~msg:
2753                 "Many lemmas can be successfully applied. Please, choose one:"
2754                uris'
2755              in
2756               inputt#set_term uri' ;
2757               apply ()
2758   with
2759    e -> 
2760     output_html outputhtml 
2761      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
2762 ;;
2763       
2764 let choose_selection
2765      (mmlwidget : GMathView.math_view) (element : Gdome.element option)
2766 =
2767  let module G = Gdome in
2768   let rec aux element =
2769    if element#hasAttributeNS
2770        ~namespaceURI:helmns
2771        ~localName:(G.domString "xref")
2772    then
2773      mmlwidget#set_selection (Some element)
2774    else
2775       match element#get_parentNode with
2776          None -> assert false
2777        (*CSC: OCAML DIVERGES!
2778        | Some p -> aux (new G.element_of_node p)
2779        *)
2780        | Some p -> aux (new Gdome.element_of_node p)
2781   in
2782    match element with
2783      Some x -> aux x
2784    | None   -> mmlwidget#set_selection None
2785 ;;
2786
2787 (* STUFF TO BUILD THE GTK INTERFACE *)
2788
2789 (* Stuff for the widget settings *)
2790
2791 let export_to_postscript (output : GMathView.math_view) =
2792  let lastdir = ref (Unix.getcwd ()) in
2793   function () ->
2794    match
2795     GToolbox.select_file ~title:"Export to PostScript"
2796      ~dir:lastdir ~filename:"screenshot.ps" ()
2797    with
2798       None -> ()
2799     | Some filename ->
2800        output#export_to_postscript ~filename:filename ();
2801 ;;
2802
2803 let activate_t1 (output : GMathView.math_view) button_set_anti_aliasing
2804  button_set_kerning button_set_transparency export_to_postscript_menu_item
2805  button_t1 ()
2806 =
2807  let is_set = button_t1#active in
2808   output#set_font_manager_type
2809    (if is_set then `font_manager_t1 else `font_manager_gtk) ;
2810   if is_set then
2811    begin
2812     button_set_anti_aliasing#misc#set_sensitive true ;
2813     button_set_kerning#misc#set_sensitive true ;
2814     button_set_transparency#misc#set_sensitive true ;
2815     export_to_postscript_menu_item#misc#set_sensitive true ;
2816    end
2817   else
2818    begin
2819     button_set_anti_aliasing#misc#set_sensitive false ;
2820     button_set_kerning#misc#set_sensitive false ;
2821     button_set_transparency#misc#set_sensitive false ;
2822     export_to_postscript_menu_item#misc#set_sensitive false ;
2823    end
2824 ;;
2825
2826 let set_anti_aliasing output button_set_anti_aliasing () =
2827  output#set_anti_aliasing button_set_anti_aliasing#active
2828 ;;
2829
2830 let set_kerning output button_set_kerning () =
2831  output#set_kerning button_set_kerning#active
2832 ;;
2833
2834 let set_transparency output button_set_transparency () =
2835  output#set_transparency button_set_transparency#active
2836 ;;
2837
2838 let changefont output font_size_spinb () =
2839  output#set_font_size font_size_spinb#value_as_int
2840 ;;
2841
2842 let set_log_verbosity output log_verbosity_spinb () =
2843  output#set_log_verbosity log_verbosity_spinb#value_as_int
2844 ;;
2845
2846 class settings_window (output : GMathView.math_view) sw
2847  export_to_postscript_menu_item selection_changed_callback
2848 =
2849  let settings_window = GWindow.window ~title:"GtkMathView settings" () in
2850  let vbox =
2851   GPack.vbox ~packing:settings_window#add () in
2852  let table =
2853   GPack.table
2854    ~rows:1 ~columns:3 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2855    ~border_width:5 ~packing:vbox#add () in
2856  let button_t1 =
2857   GButton.toggle_button ~label:"activate t1 fonts"
2858    ~packing:(table#attach ~left:0 ~top:0) () in
2859  let button_set_anti_aliasing =
2860   GButton.toggle_button ~label:"set_anti_aliasing"
2861    ~packing:(table#attach ~left:0 ~top:1) () in
2862  let button_set_kerning =
2863   GButton.toggle_button ~label:"set_kerning"
2864    ~packing:(table#attach ~left:1 ~top:1) () in
2865  let button_set_transparency =
2866   GButton.toggle_button ~label:"set_transparency"
2867    ~packing:(table#attach ~left:2 ~top:1) () in
2868  let table =
2869   GPack.table
2870    ~rows:2 ~columns:2 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2871    ~border_width:5 ~packing:vbox#add () in
2872  let font_size_label =
2873   GMisc.label ~text:"font size:"
2874    ~packing:(table#attach ~left:0 ~top:0 ~expand:`NONE) () in
2875  let font_size_spinb =
2876   let sadj =
2877    GData.adjustment ~value:14.0 ~lower:5.0 ~upper:50.0 ~step_incr:1.0 ()
2878   in
2879    GEdit.spin_button 
2880     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:0 ~fill:`NONE) () in
2881  let log_verbosity_label =
2882   GMisc.label ~text:"log verbosity:"
2883    ~packing:(table#attach ~left:0 ~top:1) () in
2884  let log_verbosity_spinb =
2885   let sadj =
2886    GData.adjustment ~value:0.0 ~lower:0.0 ~upper:3.0 ~step_incr:1.0 ()
2887   in
2888    GEdit.spin_button 
2889     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:1) () in
2890  let hbox =
2891   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2892  let closeb =
2893   GButton.button ~label:"Close"
2894    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2895 object(self)
2896  method show = settings_window#show
2897  initializer
2898   button_set_anti_aliasing#misc#set_sensitive false ;
2899   button_set_kerning#misc#set_sensitive false ;
2900   button_set_transparency#misc#set_sensitive false ;
2901   (* Signals connection *)
2902   ignore(button_t1#connect#clicked
2903    (activate_t1 output button_set_anti_aliasing button_set_kerning
2904     button_set_transparency export_to_postscript_menu_item button_t1)) ;
2905   ignore(font_size_spinb#connect#changed (changefont output font_size_spinb)) ;
2906   ignore(button_set_anti_aliasing#connect#toggled
2907    (set_anti_aliasing output button_set_anti_aliasing));
2908   ignore(button_set_kerning#connect#toggled
2909    (set_kerning output button_set_kerning)) ;
2910   ignore(button_set_transparency#connect#toggled
2911    (set_transparency output button_set_transparency)) ;
2912   ignore(log_verbosity_spinb#connect#changed
2913    (set_log_verbosity output log_verbosity_spinb)) ;
2914   ignore(closeb#connect#clicked settings_window#misc#hide)
2915 end;;
2916
2917 (* Scratch window *)
2918
2919 class scratch_window =
2920  let window =
2921   GWindow.window ~title:"MathML viewer" ~border_width:2 () in
2922  let vbox =
2923   GPack.vbox ~packing:window#add () in
2924  let hbox =
2925   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2926  let whdb =
2927   GButton.button ~label:"Whd"
2928    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2929  let reduceb =
2930   GButton.button ~label:"Reduce"
2931    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2932  let simplb =
2933   GButton.button ~label:"Simpl"
2934    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2935  let scrolled_window =
2936   GBin.scrolled_window ~border_width:10
2937    ~packing:(vbox#pack ~expand:true ~padding:5) () in
2938  let mmlwidget =
2939   GMathView.math_view
2940    ~packing:(scrolled_window#add) ~width:400 ~height:280 () in
2941 object(self)
2942  method mmlwidget = mmlwidget
2943  method show () = window#misc#hide () ; window#show ()
2944  initializer
2945   ignore(mmlwidget#connect#selection_changed (choose_selection mmlwidget)) ;
2946   ignore(window#event#connect#delete (fun _ -> window#misc#hide () ; true )) ;
2947   ignore(whdb#connect#clicked (whd_in_scratch self)) ;
2948   ignore(reduceb#connect#clicked (reduce_in_scratch self)) ;
2949   ignore(simplb#connect#clicked (simpl_in_scratch self))
2950 end;;
2951
2952 class page () =
2953  let vbox1 = GPack.vbox () in
2954 object(self)
2955  val mutable proofw_ref = None
2956  val mutable compute_ref = None
2957  method proofw =
2958   Lazy.force self#compute ;
2959   match proofw_ref with
2960      None -> assert false
2961    | Some proofw -> proofw
2962  method content = vbox1
2963  method compute =
2964   match compute_ref with
2965      None -> assert false
2966    | Some compute -> compute
2967  initializer
2968   compute_ref <-
2969    Some (lazy (
2970    let scrolled_window1 =
2971     GBin.scrolled_window ~border_width:10
2972      ~packing:(vbox1#pack ~expand:true ~padding:5) () in
2973    let proofw =
2974     GMathView.math_view ~width:400 ~height:275
2975      ~packing:(scrolled_window1#add) () in
2976    let _ = proofw_ref <- Some proofw in
2977    let hbox3 =
2978     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2979    let exactb =
2980     GButton.button ~label:"Exact"
2981      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2982    let introsb =
2983     GButton.button ~label:"Intros"
2984      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2985    let applyb =
2986     GButton.button ~label:"Apply"
2987      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2988    let elimintrossimplb =
2989     GButton.button ~label:"ElimIntrosSimpl"
2990      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2991    let elimtypeb =
2992     GButton.button ~label:"ElimType"
2993      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2994    let whdb =
2995     GButton.button ~label:"Whd"
2996      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2997    let reduceb =
2998     GButton.button ~label:"Reduce"
2999      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3000    let simplb =
3001     GButton.button ~label:"Simpl"
3002      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3003    let hbox4 =
3004     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
3005    let foldwhdb =
3006     GButton.button ~label:"Fold_whd"
3007      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3008    let foldreduceb =
3009     GButton.button ~label:"Fold_reduce"
3010      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3011    let foldsimplb =
3012     GButton.button ~label:"Fold_simpl"
3013      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3014    let cutb =
3015     GButton.button ~label:"Cut"
3016      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3017    let changeb =
3018     GButton.button ~label:"Change"
3019      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3020    let letinb =
3021     GButton.button ~label:"Let ... In"
3022      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3023    let ringb =
3024     GButton.button ~label:"Ring"
3025      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3026    let hbox5 =
3027     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
3028    let clearbodyb =
3029     GButton.button ~label:"ClearBody"
3030      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3031    let clearb =
3032     GButton.button ~label:"Clear"
3033      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3034    let fourierb =
3035     GButton.button ~label:"Fourier"
3036      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3037    let rewritesimplb =
3038     GButton.button ~label:"RewriteSimpl ->"
3039      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3040    let rewritebacksimplb =
3041     GButton.button ~label:"RewriteSimpl <-"
3042      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3043    let replaceb =
3044     GButton.button ~label:"Replace"
3045      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3046    let hbox6 =
3047     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
3048    let reflexivityb =
3049     GButton.button ~label:"Reflexivity"
3050      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3051    let symmetryb =
3052     GButton.button ~label:"Symmetry"
3053      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3054    let transitivityb =
3055     GButton.button ~label:"Transitivity"
3056      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3057    let existsb =
3058     GButton.button ~label:"Exists"
3059      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3060    let splitb =
3061     GButton.button ~label:"Split"
3062      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3063    let leftb =
3064     GButton.button ~label:"Left"
3065      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3066    let rightb =
3067     GButton.button ~label:"Right"
3068      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3069    let assumptionb =
3070     GButton.button ~label:"Assumption"
3071      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3072    let hbox7 =
3073     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
3074    let generalizeb =
3075     GButton.button ~label:"Generalize"
3076      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
3077    let absurdb =
3078     GButton.button ~label:"Absurd"
3079      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
3080    let contradictionb =
3081     GButton.button ~label:"Contradiction"
3082      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
3083    let searchpatternb =
3084     GButton.button ~label:"SearchPattern_Apply"
3085      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
3086
3087    ignore(exactb#connect#clicked exact) ;
3088    ignore(applyb#connect#clicked apply) ;
3089    ignore(elimintrossimplb#connect#clicked elimintrossimpl) ;
3090    ignore(elimtypeb#connect#clicked elimtype) ;
3091    ignore(whdb#connect#clicked whd) ;
3092    ignore(reduceb#connect#clicked reduce) ;
3093    ignore(simplb#connect#clicked simpl) ;
3094    ignore(foldwhdb#connect#clicked fold_whd) ;
3095    ignore(foldreduceb#connect#clicked fold_reduce) ;
3096    ignore(foldsimplb#connect#clicked fold_simpl) ;
3097    ignore(cutb#connect#clicked cut) ;
3098    ignore(changeb#connect#clicked change) ;
3099    ignore(letinb#connect#clicked letin) ;
3100    ignore(ringb#connect#clicked ring) ;
3101    ignore(clearbodyb#connect#clicked clearbody) ;
3102    ignore(clearb#connect#clicked clear) ;
3103    ignore(fourierb#connect#clicked fourier) ;
3104    ignore(rewritesimplb#connect#clicked rewritesimpl) ;
3105    ignore(rewritebacksimplb#connect#clicked rewritebacksimpl) ;
3106    ignore(replaceb#connect#clicked replace) ;
3107    ignore(reflexivityb#connect#clicked reflexivity) ;
3108    ignore(symmetryb#connect#clicked symmetry) ;
3109    ignore(transitivityb#connect#clicked transitivity) ;
3110    ignore(existsb#connect#clicked exists) ;
3111    ignore(splitb#connect#clicked split) ;
3112    ignore(leftb#connect#clicked left) ;
3113    ignore(rightb#connect#clicked right) ;
3114    ignore(assumptionb#connect#clicked assumption) ;
3115    ignore(generalizeb#connect#clicked generalize) ;
3116    ignore(absurdb#connect#clicked absurd) ;
3117    ignore(contradictionb#connect#clicked contradiction) ;
3118    ignore(introsb#connect#clicked intros) ;
3119    ignore(searchpatternb#connect#clicked searchPattern) ;
3120    ignore(proofw#connect#selection_changed (choose_selection proofw)) ;
3121   ))
3122 end
3123 ;;
3124
3125 class empty_page =
3126  let vbox1 = GPack.vbox () in
3127  let scrolled_window1 =
3128   GBin.scrolled_window ~border_width:10
3129    ~packing:(vbox1#pack ~expand:true ~padding:5) () in
3130  let proofw =
3131   GMathView.math_view ~width:400 ~height:275
3132    ~packing:(scrolled_window1#add) () in
3133 object(self)
3134  method proofw = (assert false : GMathView.math_view)
3135  method content = vbox1
3136  method compute = (assert false : unit)
3137 end
3138 ;;
3139
3140 let empty_page = new empty_page;;
3141
3142 class notebook =
3143 object(self)
3144  val notebook = GPack.notebook ()
3145  val pages = ref []
3146  val mutable skip_switch_page_event = false 
3147  val mutable empty = true
3148  method notebook = notebook
3149  method add_page n =
3150   let new_page = new page () in
3151    empty <- false ;
3152    pages := !pages @ [n,lazy (setgoal n),new_page] ;
3153    notebook#append_page
3154     ~tab_label:((GMisc.label ~text:("?" ^ string_of_int n) ())#coerce)
3155     new_page#content#coerce
3156  method remove_all_pages ~skip_switch_page_event:skip =
3157   if empty then
3158    notebook#remove_page 0 (* let's remove the empty page *)
3159   else
3160    List.iter (function _ -> notebook#remove_page 0) !pages ;
3161   pages := [] ;
3162   skip_switch_page_event <- skip
3163  method set_current_page ~may_skip_switch_page_event n =
3164   let (_,_,page) = List.find (function (m,_,_) -> m=n) !pages in
3165    let new_page = notebook#page_num page#content#coerce in
3166     if may_skip_switch_page_event && new_page <> notebook#current_page then
3167      skip_switch_page_event <- true ;
3168     notebook#goto_page new_page
3169  method set_empty_page =
3170   empty <- true ;
3171   pages := [] ;
3172   notebook#append_page
3173    ~tab_label:((GMisc.label ~text:"No proof in progress" ())#coerce)
3174    empty_page#content#coerce
3175  method proofw =
3176   let (_,_,page) = List.nth !pages notebook#current_page in
3177    page#proofw
3178  initializer
3179   ignore
3180    (notebook#connect#switch_page
3181     (function i ->
3182       let skip = skip_switch_page_event in
3183        skip_switch_page_event <- false ;
3184        if not skip then
3185         try
3186          let (metano,setgoal,page) = List.nth !pages i in
3187           ProofEngine.goal := Some metano ;
3188           Lazy.force (page#compute) ;
3189           Lazy.force setgoal
3190         with _ -> ()
3191     ))
3192 end
3193 ;;
3194
3195 (* Main window *)
3196
3197 class rendering_window output (notebook : notebook) =
3198  let scratch_window = new scratch_window in
3199  let window =
3200   GWindow.window ~title:"MathML viewer" ~border_width:0
3201    ~allow_shrink:false () in
3202  let vbox_for_menu = GPack.vbox ~packing:window#add () in
3203  (* menus *)
3204  let handle_box = GBin.handle_box ~border_width:2
3205   ~packing:(vbox_for_menu#pack ~padding:0) () in
3206  let menubar = GMenu.menu_bar ~packing:handle_box#add () in
3207  let factory0 = new GMenu.factory menubar in
3208  let accel_group = factory0#accel_group in
3209  (* file menu *)
3210  let file_menu = factory0#add_submenu "File" in
3211  let factory1 = new GMenu.factory file_menu ~accel_group in
3212  let export_to_postscript_menu_item =
3213   begin
3214    let _ =
3215     factory1#add_item "New Block of (Co)Inductive Definitions..."
3216      ~key:GdkKeysyms._B ~callback:new_inductive
3217    in
3218    let _ =
3219     factory1#add_item "New Proof or Definition..." ~key:GdkKeysyms._N
3220      ~callback:new_proof
3221    in
3222    let reopen_menu_item =
3223     factory1#add_item "Reopen a Finished Proof..." ~key:GdkKeysyms._R
3224      ~callback:open_
3225    in
3226    let qed_menu_item =
3227     factory1#add_item "Qed" ~key:GdkKeysyms._E ~callback:qed in
3228    ignore (factory1#add_separator ()) ;
3229    ignore
3230     (factory1#add_item "Load Unfinished Proof..." ~key:GdkKeysyms._L
3231       ~callback:load) ;
3232    let save_menu_item =
3233     factory1#add_item "Save Unfinished Proof" ~key:GdkKeysyms._S ~callback:save
3234    in
3235    ignore
3236     (save_set_sensitive := function b -> save_menu_item#misc#set_sensitive b);
3237    ignore (!save_set_sensitive false);
3238    ignore (qed_set_sensitive:=function b -> qed_menu_item#misc#set_sensitive b);
3239    ignore (!qed_set_sensitive false);
3240    ignore (factory1#add_separator ()) ;
3241    let export_to_postscript_menu_item =
3242     factory1#add_item "Export to PostScript..."
3243      ~callback:(export_to_postscript output) in
3244    ignore (factory1#add_separator ()) ;
3245    ignore
3246     (factory1#add_item "Exit" ~key:GdkKeysyms._Q ~callback:GMain.Main.quit) ;
3247    export_to_postscript_menu_item
3248   end in
3249  (* edit menu *)
3250  let edit_menu = factory0#add_submenu "Edit Current Proof" in
3251  let factory2 = new GMenu.factory edit_menu ~accel_group in
3252  let focus_and_proveit_set_sensitive = ref (function _ -> assert false) in
3253  let proveit_menu_item =
3254   factory2#add_item "Prove It" ~key:GdkKeysyms._I
3255    ~callback:(function () -> proveit ();!focus_and_proveit_set_sensitive false)
3256  in
3257  let focus_menu_item =
3258   factory2#add_item "Focus" ~key:GdkKeysyms._F
3259    ~callback:(function () -> focus () ; !focus_and_proveit_set_sensitive false)
3260  in
3261  let _ =
3262   focus_and_proveit_set_sensitive :=
3263    function b ->
3264     proveit_menu_item#misc#set_sensitive b ;
3265     focus_menu_item#misc#set_sensitive b
3266  in
3267  let _ = !focus_and_proveit_set_sensitive false in
3268  (* edit term menu *)
3269  let edit_term_menu = factory0#add_submenu "Edit Term" in
3270  let factory5 = new GMenu.factory edit_term_menu ~accel_group in
3271  let check_menu_item =
3272   factory5#add_item "Check Term" ~key:GdkKeysyms._C
3273    ~callback:(check scratch_window) in
3274  let _ = check_menu_item#misc#set_sensitive false in
3275  (* search menu *)
3276  let settings_menu = factory0#add_submenu "Search" in
3277  let factory4 = new GMenu.factory settings_menu ~accel_group in
3278  let _ =
3279   factory4#add_item "Locate..." ~key:GdkKeysyms._T
3280    ~callback:locate in
3281  let searchPattern_menu_item =
3282   factory4#add_item "SearchPattern..." ~key:GdkKeysyms._D
3283    ~callback:completeSearchPattern in
3284  let _ = searchPattern_menu_item#misc#set_sensitive false in
3285  let show_menu_item =
3286   factory4#add_item "Show..." ~key:GdkKeysyms._H ~callback:show
3287  in
3288  let insert_query_item =
3289   factory4#add_item "Insert Query (Experts Only)..." ~key:GdkKeysyms._U
3290    ~callback:insertQuery in
3291  (* settings menu *)
3292  let settings_menu = factory0#add_submenu "Settings" in
3293  let factory3 = new GMenu.factory settings_menu ~accel_group in
3294  let _ =
3295   factory3#add_item "Edit Aliases" ~key:GdkKeysyms._A
3296    ~callback:edit_aliases in
3297  let _ = factory3#add_separator () in
3298  let _ =
3299   factory3#add_item "MathML Widget Preferences..." ~key:GdkKeysyms._P
3300    ~callback:(function _ -> (settings_window ())#show ()) in
3301  (* accel group *)
3302  let _ = window#add_accel_group accel_group in
3303  (* end of menus *)
3304  let hbox0 =
3305   GPack.hbox
3306    ~packing:(vbox_for_menu#pack ~expand:true ~fill:true ~padding:5) () in
3307  let vbox =
3308   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
3309  let scrolled_window0 =
3310   GBin.scrolled_window ~border_width:10
3311    ~packing:(vbox#pack ~expand:true ~padding:5) () in
3312  let _ = scrolled_window0#add output#coerce in
3313  let frame =
3314   GBin.frame ~label:"Insert Term"
3315    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
3316  let scrolled_window1 =
3317   GBin.scrolled_window ~border_width:5
3318    ~packing:frame#add () in
3319  let inputt =
3320   new term_editor ~width:400 ~height:100 ~packing:scrolled_window1#add ()
3321    ~isnotempty_callback:
3322     (function b ->
3323       check_menu_item#misc#set_sensitive b ;
3324       searchPattern_menu_item#misc#set_sensitive b) in
3325  let vboxl =
3326   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
3327  let _ =
3328   vboxl#pack ~expand:true ~fill:true ~padding:5 notebook#notebook#coerce in
3329  let frame =
3330   GBin.frame ~shadow_type:`IN ~packing:(vboxl#pack ~expand:true ~padding:5) ()
3331  in
3332  let outputhtml =
3333   GHtml.xmhtml
3334    ~source:"<html><body bgColor=\"white\"></body></html>"
3335    ~width:400 ~height: 100
3336    ~border_width:20
3337    ~packing:frame#add
3338    ~show:true () in
3339 object
3340  method outputhtml = outputhtml
3341  method inputt = inputt
3342  method output = (output : GMathView.math_view)
3343  method notebook = notebook
3344  method show = window#show
3345  initializer
3346   notebook#set_empty_page ;
3347   export_to_postscript_menu_item#misc#set_sensitive false ;
3348   check_term := (check_term_in_scratch scratch_window) ;
3349
3350   (* signal handlers here *)
3351   ignore(output#connect#selection_changed
3352    (function elem ->
3353      choose_selection output elem ;
3354      !focus_and_proveit_set_sensitive true
3355    )) ;
3356   ignore (output#connect#clicked (show_in_show_window_callback output)) ;
3357   let settings_window = new settings_window output scrolled_window0
3358    export_to_postscript_menu_item (choose_selection output) in
3359   set_settings_window settings_window ;
3360   set_outputhtml outputhtml ;
3361   ignore(window#event#connect#delete (fun _ -> GMain.Main.quit () ; true )) ;
3362   Logger.log_callback :=
3363    (Logger.log_to_html ~print_and_flush:(output_html outputhtml))
3364 end;;
3365
3366 (* MAIN *)
3367
3368 let initialize_everything () =
3369  let module U = Unix in
3370   let output = GMathView.math_view ~width:350 ~height:280 () in
3371   let notebook = new notebook in
3372    let rendering_window' = new rendering_window output notebook in
3373     set_rendering_window rendering_window' ;
3374     mml_of_cic_term_ref := mml_of_cic_term ;
3375     rendering_window'#show () ;
3376     GMain.Main.main ()
3377 ;;
3378
3379 let _ =
3380  if !usedb then
3381   begin
3382    Mqint.set_database Mqint.postgres_db ;
3383    Mqint.init postgresqlconnectionstring ;
3384   end ;
3385  ignore (GtkMain.Main.init ()) ;
3386  initialize_everything () ;
3387  if !usedb then Mqint.close ();
3388 ;;