]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/gTopLevel.ml
Optional callbacks have been added to tactics that need to introduce
[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          GMathViewAux.single_selection_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_doc ~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 : GMathViewAux.single_selection_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_doc ~dom: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_doc ~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 : GMathViewAux.single_selection_math_view)#load_doc 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 : GMathViewAux.single_selection_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   GMathViewAux.single_selection_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_doc 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        prerr_endline
1099         "'get_action' and 'action_toggle' not yet implemented in lablgtkmathview 0.3.99"
1100 (* TODO commented out because not yet implemented in lablgtkmathview 0.3.99 *)
1101 (*
1102      if mmlwidget#get_action <> None then
1103       mmlwidget#action_toggle
1104 *)
1105    in
1106     let _ =
1107      mmlwidget#connect#click (show_in_show_window_callback mmlwidget)
1108     in
1109      show_in_show_window_obj, show_in_show_window_uri,
1110       show_in_show_window_callback
1111 ;;
1112
1113 exception NoObjectsLocated;;
1114
1115 let user_uri_choice ~title ~msg uris =
1116  let uri =
1117   match uris with
1118      [] -> raise NoObjectsLocated
1119    | [uri] -> uri
1120    | uris ->
1121       match
1122        interactive_user_uri_choice ~selection_mode:`SINGLE ~title ~msg uris
1123       with
1124          [uri] -> uri
1125        | _ -> assert false
1126  in
1127   String.sub uri 4 (String.length uri - 4)
1128 ;;
1129
1130 let locate_callback id =
1131  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1132  let result = MQueryGenerator.locate id in
1133  let uris =
1134   List.map
1135    (function uri,_ ->
1136      Disambiguate.wrong_xpointer_format_from_wrong_xpointer_format' uri)
1137    result in
1138  let html =
1139   (" <h1>Locate Query: </h1><pre>" ^ get_last_query result ^ "</pre>")
1140  in
1141   output_html outputhtml html ;
1142   user_uri_choice ~title:"Ambiguous input."
1143    ~msg:
1144      ("Ambiguous input \"" ^ id ^
1145       "\". Please, choose one interpetation:")
1146    uris
1147 ;;
1148
1149
1150 let input_or_locate_uri ~title =
1151  let uri = ref None in
1152  let window =
1153   GWindow.window
1154    ~width:400 ~modal:true ~title ~border_width:2 () in
1155  let vbox = GPack.vbox ~packing:window#add () in
1156  let hbox1 =
1157   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1158  let _ =
1159   GMisc.label ~text:"Enter a valid URI:" ~packing:(hbox1#pack ~padding:5) () in
1160  let manual_input =
1161   GEdit.entry ~editable:true
1162    ~packing:(hbox1#pack ~expand:true ~fill:true ~padding:5) () in
1163  let checkb =
1164   GButton.button ~label:"Check"
1165    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1166  let _ = checkb#misc#set_sensitive false in
1167  let hbox2 =
1168   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1169  let _ =
1170   GMisc.label ~text:"You can also enter an indentifier to locate:"
1171    ~packing:(hbox2#pack ~padding:5) () in
1172  let locate_input =
1173   GEdit.entry ~editable:true
1174    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
1175  let locateb =
1176   GButton.button ~label:"Locate"
1177    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
1178  let _ = locateb#misc#set_sensitive false in
1179  let hbox3 =
1180   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1181  let okb =
1182   GButton.button ~label:"Ok"
1183    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
1184  let _ = okb#misc#set_sensitive false in
1185  let cancelb =
1186   GButton.button ~label:"Cancel"
1187    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) ()
1188  in
1189   ignore (window#connect#destroy GMain.Main.quit) ;
1190   ignore
1191    (cancelb#connect#clicked (function () -> uri := None ; window#destroy ())) ;
1192   let check_callback () =
1193    let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1194    let uri = "cic:" ^ manual_input#text in
1195     try
1196       ignore (Getter.resolve (UriManager.uri_of_string uri)) ;
1197       output_html outputhtml "<h1 color=\"Green\">OK</h1>" ;
1198       true
1199     with
1200        Getter.Unresolved ->
1201         output_html outputhtml
1202          ("<h1 color=\"Red\">URI " ^ uri ^
1203           " does not correspond to any object.</h1>") ;
1204         false
1205      | UriManager.IllFormedUri _ ->
1206         output_html outputhtml
1207          ("<h1 color=\"Red\">URI " ^ uri ^ " is not well-formed.</h1>") ;
1208         false
1209      | e ->
1210         output_html outputhtml
1211          ("<h1 color=\"Red\">" ^ Printexc.to_string e ^ "</h1>") ;
1212         false
1213   in
1214   ignore
1215    (okb#connect#clicked
1216      (function () ->
1217        if check_callback () then
1218         begin
1219          uri := Some manual_input#text ;
1220          window#destroy ()
1221         end
1222    )) ;
1223   ignore (checkb#connect#clicked (function () -> ignore (check_callback ()))) ;
1224   ignore
1225    (manual_input#connect#changed
1226      (fun _ ->
1227        if manual_input#text = "" then
1228         begin
1229          checkb#misc#set_sensitive false ;
1230          okb#misc#set_sensitive false
1231         end
1232        else
1233         begin
1234          checkb#misc#set_sensitive true ;
1235          okb#misc#set_sensitive true
1236         end));
1237   ignore
1238    (locate_input#connect#changed
1239      (fun _ -> locateb#misc#set_sensitive (locate_input#text <> ""))) ;
1240   ignore
1241    (locateb#connect#clicked
1242      (function () ->
1243        let id = locate_input#text in
1244         manual_input#set_text (locate_callback id) ;
1245         locate_input#delete_text 0 (String.length id)
1246    )) ;
1247   window#show () ;
1248   GMain.Main.main () ;
1249   match !uri with
1250      None -> raise NoChoice
1251    | Some uri -> UriManager.uri_of_string ("cic:" ^ uri)
1252 ;;
1253
1254 exception AmbiguousInput;;
1255
1256 (* A WIDGET TO ENTER CIC TERMS *)
1257
1258 module Callbacks =
1259  struct
1260   let output_html msg = output_html (outputhtml ()) msg;;
1261   let interactive_user_uri_choice =
1262    fun ~selection_mode ?ok ?enable_button_for_non_vars ~title ~msg ~id ->
1263     interactive_user_uri_choice ~selection_mode ?ok
1264      ?enable_button_for_non_vars ~title ~msg;;
1265   let interactive_interpretation_choice = interactive_interpretation_choice;;
1266   let input_or_locate_uri = input_or_locate_uri;;
1267  end
1268 ;;
1269
1270 module Disambiguate' = Disambiguate.Make(Callbacks);;
1271
1272 class term_editor ?packing ?width ?height ?isnotempty_callback () =
1273  let input = GEdit.text ~editable:true ?width ?height ?packing () in
1274  let _ =
1275   match isnotempty_callback with
1276      None -> ()
1277    | Some callback ->
1278       ignore(input#connect#changed (function () -> callback (input#length > 0)))
1279  in
1280 object(self)
1281  method coerce = input#coerce
1282  method reset =
1283   input#delete_text 0 input#length
1284  (* CSC: txt is now a string, but should be of type Cic.term *)
1285  method set_term txt =
1286   self#reset ;
1287   ignore ((input#insert_text txt) ~pos:0)
1288  (* CSC: this method should disappear *)
1289  method get_as_string =
1290   input#get_chars 0 input#length
1291  method get_metasenv_and_term ~context ~metasenv =
1292   let name_context =
1293    List.map
1294     (function
1295         Some (n,_) -> Some n
1296       | None -> None
1297     ) context
1298   in
1299    let lexbuf = Lexing.from_string (input#get_chars 0 input#length) in
1300     let dom,mk_metasenv_and_expr =
1301      CicTextualParserContext.main
1302       ~context:name_context ~metasenv CicTextualLexer.token lexbuf
1303     in
1304      let id_to_uris',metasenv,expr =
1305       Disambiguate'.disambiguate_input context metasenv dom mk_metasenv_and_expr
1306        ~id_to_uris:!id_to_uris
1307      in
1308       id_to_uris := id_to_uris' ;
1309       metasenv,expr
1310 end
1311 ;;
1312
1313 (* OTHER FUNCTIONS *)
1314
1315 let locate () =
1316  let inputt = ((rendering_window ())#inputt : term_editor) in
1317  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1318    try
1319     match
1320      GToolbox.input_string ~title:"Locate" "Enter an identifier to locate:"
1321     with
1322        None -> raise NoChoice
1323      | Some input ->
1324         let uri = locate_callback input in
1325          inputt#set_term uri
1326    with
1327     e ->
1328      output_html outputhtml
1329       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
1330 ;;
1331
1332
1333 exception UriAlreadyInUse;;
1334 exception NotAUriToAConstant;;
1335
1336 let new_inductive () =
1337  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1338  let output = ((rendering_window ())#output : GMathViewAux.single_selection_math_view) in
1339  let notebook = (rendering_window ())#notebook in
1340
1341  let chosen = ref false in
1342  let inductive = ref true in
1343  let paramsno = ref 0 in
1344  let get_uri = ref (function _ -> assert false) in
1345  let get_base_uri = ref (function _ -> assert false) in
1346  let get_names = ref (function _ -> assert false) in
1347  let get_types_and_cons = ref (function _ -> assert false) in
1348  let get_context_and_subst = ref (function _ -> assert false) in 
1349  let window =
1350   GWindow.window
1351    ~width:600 ~modal:true ~position:`CENTER
1352    ~title:"New Block of Mutual (Co)Inductive Definitions"
1353    ~border_width:2 () in
1354  let vbox = GPack.vbox ~packing:window#add () in
1355  let hbox =
1356   GPack.hbox ~border_width:0
1357    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1358  let _ =
1359   GMisc.label ~text:"Enter the URI for the new block:"
1360    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1361  let uri_entry =
1362   GEdit.entry ~editable:true
1363    ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1364  let hbox0 =
1365   GPack.hbox ~border_width:0
1366    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1367  let _ =
1368   GMisc.label
1369    ~text:
1370      "Enter the number of left parameters in every arity and constructor type:"
1371    ~packing:(hbox0#pack ~expand:false ~fill:false ~padding:5) () in
1372  let paramsno_entry =
1373   GEdit.entry ~editable:true ~text:"0"
1374    ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
1375  let hbox1 =
1376   GPack.hbox ~border_width:0
1377    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1378  let _ =
1379   GMisc.label ~text:"Are the definitions inductive or coinductive?"
1380    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1381  let inductiveb =
1382   GButton.radio_button ~label:"Inductive"
1383    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1384  let coinductiveb =
1385   GButton.radio_button ~label:"Coinductive"
1386    ~group:inductiveb#group
1387    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1388  let hbox2 =
1389   GPack.hbox ~border_width:0
1390    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1391  let _ =
1392   GMisc.label ~text:"Enter the list of the names of the types:"
1393    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
1394  let names_entry =
1395   GEdit.entry ~editable:true
1396    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
1397  let hboxn =
1398   GPack.hbox ~border_width:0
1399    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1400  let okb =
1401   GButton.button ~label:"> Next"
1402    ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1403  let _ = okb#misc#set_sensitive true in
1404  let cancelb =
1405   GButton.button ~label:"Abort"
1406    ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1407  ignore (window#connect#destroy GMain.Main.quit) ;
1408  ignore (cancelb#connect#clicked window#destroy) ;
1409  (* First phase *)
1410  let rec phase1 () =
1411   ignore
1412    (okb#connect#clicked
1413      (function () ->
1414        try
1415         let uristr = "cic:" ^ uri_entry#text in
1416         let namesstr = names_entry#text in
1417         let paramsno' = int_of_string (paramsno_entry#text) in
1418          match Str.split (Str.regexp " +") namesstr with
1419             [] -> assert false
1420           | (he::tl) as names ->
1421              let uri = UriManager.uri_of_string (uristr ^ "/" ^ he ^ ".ind") in
1422               begin
1423                try
1424                 ignore (Getter.resolve uri) ;
1425                 raise UriAlreadyInUse
1426                with
1427                 Getter.Unresolved ->
1428                  get_uri := (function () -> uri) ; 
1429                  get_names := (function () -> names) ;
1430                  inductive := inductiveb#active ;
1431                  paramsno := paramsno' ;
1432                  phase2 ()
1433               end
1434        with
1435         e ->
1436          output_html outputhtml
1437           ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1438      ))
1439  (* Second phase *)
1440  and phase2 () =
1441   let type_widgets =
1442    List.map
1443     (function name ->
1444       let frame =
1445        GBin.frame ~label:name
1446         ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1447       let vbox = GPack.vbox ~packing:frame#add () in
1448       let hbox = GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false) () in
1449       let _ =
1450        GMisc.label ~text:("Enter its type:")
1451         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1452       let scrolled_window =
1453        GBin.scrolled_window ~border_width:5
1454         ~packing:(vbox#pack ~expand:true ~padding:0) () in
1455       let newinputt =
1456        new term_editor ~width:400 ~height:20 ~packing:scrolled_window#add ()
1457         ~isnotempty_callback:
1458          (function b ->
1459            (*non_empty_type := b ;*)
1460            okb#misc#set_sensitive true) (*(b && uri_entry#text <> ""))*)
1461       in
1462       let hbox =
1463        GPack.hbox ~border_width:0
1464         ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1465       let _ =
1466        GMisc.label ~text:("Enter the list of its constructors:")
1467         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1468       let cons_names_entry =
1469        GEdit.entry ~editable:true
1470         ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1471       (newinputt,cons_names_entry)
1472     ) (!get_names ())
1473   in
1474    vbox#remove hboxn#coerce ;
1475    let hboxn =
1476     GPack.hbox ~border_width:0
1477      ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1478    let okb =
1479     GButton.button ~label:"> Next"
1480      ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1481    let cancelb =
1482     GButton.button ~label:"Abort"
1483      ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1484    ignore (cancelb#connect#clicked window#destroy) ;
1485    ignore
1486     (okb#connect#clicked
1487       (function () ->
1488         try
1489          let names = !get_names () in
1490          let types_and_cons =
1491           List.map2
1492            (fun name (newinputt,cons_names_entry) ->
1493              let consnamesstr = cons_names_entry#text in
1494              let cons_names = Str.split (Str.regexp " +") consnamesstr in
1495              let metasenv,expr =
1496               newinputt#get_metasenv_and_term ~context:[] ~metasenv:[]
1497              in
1498               match metasenv with
1499                  [] -> expr,cons_names
1500                | _ -> raise AmbiguousInput
1501            ) names type_widgets
1502          in
1503           let uri = !get_uri () in
1504           let _ =
1505            (* Let's see if so far the definition is well-typed *)
1506            let params = [] in
1507            let paramsno = 0 in
1508            (* To test if the arities of the inductive types are well *)
1509            (* typed, we check the inductive block definition where   *)
1510            (* no constructor is given to each type.                  *)
1511            let tys =
1512             List.map2
1513              (fun name (ty,cons) -> (name, !inductive, ty, []))
1514              names types_and_cons
1515            in
1516             CicTypeChecker.typecheck_mutual_inductive_defs uri
1517              (tys,params,paramsno)
1518           in
1519            get_context_and_subst :=
1520             (function () ->
1521               let i = ref 0 in
1522                List.fold_left2
1523                 (fun (context,subst) name (ty,_) ->
1524                   let res =
1525                    (Some (Cic.Name name, Cic.Decl ty))::context,
1526                     (Cic.MutInd (uri,!i,[]))::subst
1527                   in
1528                    incr i ; res
1529                 ) ([],[]) names types_and_cons) ;
1530            let types_and_cons' =
1531             List.map2
1532              (fun name (ty,cons) -> (name, !inductive, ty, phase3 name cons))
1533              names types_and_cons
1534            in
1535             get_types_and_cons := (function () -> types_and_cons') ;
1536             chosen := true ;
1537             window#destroy ()
1538         with
1539          e ->
1540           output_html outputhtml
1541            ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1542       ))
1543  (* Third phase *)
1544  and phase3 name cons =
1545   let get_cons_types = ref (function () -> assert false) in
1546   let window2 =
1547    GWindow.window
1548     ~width:600 ~modal:true ~position:`CENTER
1549     ~title:(name ^ " Constructors")
1550     ~border_width:2 () in
1551   let vbox = GPack.vbox ~packing:window2#add () in
1552   let cons_type_widgets =
1553    List.map
1554     (function consname ->
1555       let hbox =
1556        GPack.hbox ~border_width:0
1557         ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1558       let _ =
1559        GMisc.label ~text:("Enter the type of " ^ consname ^ ":")
1560         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1561       let scrolled_window =
1562        GBin.scrolled_window ~border_width:5
1563         ~packing:(vbox#pack ~expand:true ~padding:0) () in
1564       let newinputt =
1565        new term_editor ~width:400 ~height:20 ~packing:scrolled_window#add ()
1566         ~isnotempty_callback:
1567          (function b ->
1568            (* (*non_empty_type := b ;*)
1569            okb#misc#set_sensitive true) (*(b && uri_entry#text <> ""))*) *)())
1570       in
1571        newinputt
1572     ) cons in
1573   let hboxn =
1574    GPack.hbox ~border_width:0
1575     ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1576   let okb =
1577    GButton.button ~label:"> Next"
1578     ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1579   let _ = okb#misc#set_sensitive true in
1580   let cancelb =
1581    GButton.button ~label:"Abort"
1582     ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1583   ignore (window2#connect#destroy GMain.Main.quit) ;
1584   ignore (cancelb#connect#clicked window2#destroy) ;
1585   ignore
1586    (okb#connect#clicked
1587      (function () ->
1588        try
1589         chosen := true ;
1590         let context,subst= !get_context_and_subst () in
1591         let cons_types =
1592          List.map2
1593           (fun name inputt ->
1594             let metasenv,expr =
1595              inputt#get_metasenv_and_term ~context ~metasenv:[]
1596             in
1597              match metasenv with
1598                 [] ->
1599                  let undebrujined_expr =
1600                   List.fold_left
1601                    (fun expr t -> CicSubstitution.subst t expr) expr subst
1602                  in
1603                   name, undebrujined_expr
1604               | _ -> raise AmbiguousInput
1605           ) cons cons_type_widgets
1606         in
1607          get_cons_types := (function () -> cons_types) ;
1608          window2#destroy ()
1609        with
1610         e ->
1611          output_html outputhtml
1612           ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1613      )) ;
1614   window2#show () ;
1615   GMain.Main.main () ;
1616   let okb_pressed = !chosen in
1617    chosen := false ;
1618    if (not okb_pressed) then
1619     begin
1620      window#destroy () ;
1621      assert false (* The control never reaches this point *)
1622     end
1623    else
1624     (!get_cons_types ())
1625  in
1626   phase1 () ;
1627   (* No more phases left or Abort pressed *) 
1628   window#show () ;
1629   GMain.Main.main () ;
1630   window#destroy () ;
1631   if !chosen then
1632    try
1633     let uri = !get_uri () in
1634 (*CSC: Da finire *)
1635     let params = [] in
1636     let tys = !get_types_and_cons () in
1637      let obj = Cic.InductiveDefinition tys params !paramsno in
1638       begin
1639        try
1640         prerr_endline (CicPp.ppobj obj) ;
1641         CicTypeChecker.typecheck_mutual_inductive_defs uri
1642          (tys,params,!paramsno) ;
1643         with
1644          e ->
1645           prerr_endline "Offending mutual (co)inductive type declaration:" ;
1646           prerr_endline (CicPp.ppobj obj) ;
1647       end ;
1648       (* We already know that obj is well-typed. We need to add it to the  *)
1649       (* environment in order to compute the inner-types without having to *)
1650       (* debrujin it or having to modify lots of other functions to avoid  *)
1651       (* asking the environment for the MUTINDs we are defining now.       *)
1652       CicEnvironment.put_inductive_definition uri obj ;
1653       save_obj uri obj ;
1654       show_in_show_window_obj uri obj
1655    with
1656     e ->
1657      output_html outputhtml
1658       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1659 ;;
1660
1661 let mk_fresh_name_callback context name ~typ =
1662  let fresh_name =
1663   match ProofEngineHelpers.mk_fresh_name context name ~typ with
1664      Cic.Name fresh_name -> fresh_name
1665    | Cic.Anonymous -> assert false
1666  in
1667   match
1668    GToolbox.input_string ~title:"Enter a fresh hypothesis name" ~text:fresh_name
1669     ("Enter a fresh name for the hypothesis " ^
1670       CicPp.pp typ
1671        (List.map (function None -> None | Some (n,_) -> Some n) context))
1672   with
1673      Some fresh_name' -> Cic.Name fresh_name'
1674    | None -> raise NoChoice
1675 ;;
1676
1677 let new_proof () =
1678  let inputt = ((rendering_window ())#inputt : term_editor) in
1679  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1680  let output = ((rendering_window ())#output : GMathViewAux.single_selection_math_view) in
1681  let notebook = (rendering_window ())#notebook in
1682
1683  let chosen = ref false in
1684  let get_metasenv_and_term = ref (function _ -> assert false) in
1685  let get_uri = ref (function _ -> assert false) in
1686  let non_empty_type = ref false in
1687  let window =
1688   GWindow.window
1689    ~width:600 ~modal:true ~title:"New Proof or Definition"
1690    ~border_width:2 () in
1691  let vbox = GPack.vbox ~packing:window#add () in
1692  let hbox =
1693   GPack.hbox ~border_width:0
1694    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1695  let _ =
1696   GMisc.label ~text:"Enter the URI for the new theorem or definition:"
1697    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1698  let uri_entry =
1699   GEdit.entry ~editable:true
1700    ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1701  let hbox1 =
1702   GPack.hbox ~border_width:0
1703    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1704  let _ =
1705   GMisc.label ~text:"Enter the theorem or definition type:"
1706    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1707  let scrolled_window =
1708   GBin.scrolled_window ~border_width:5
1709    ~packing:(vbox#pack ~expand:true ~padding:0) () in
1710  (* the content of the scrolled_window is moved below (see comment) *)
1711  let hbox =
1712   GPack.hbox ~border_width:0
1713    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1714  let okb =
1715   GButton.button ~label:"Ok"
1716    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1717  let _ = okb#misc#set_sensitive false in
1718  let cancelb =
1719   GButton.button ~label:"Cancel"
1720    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1721  (* moved here to have visibility of the ok button *)
1722  let newinputt =
1723   new term_editor ~width:400 ~height:100 ~packing:scrolled_window#add ()
1724    ~isnotempty_callback:
1725     (function b ->
1726       non_empty_type := b ;
1727       okb#misc#set_sensitive (b && uri_entry#text <> ""))
1728  in
1729  let _ =
1730   newinputt#set_term inputt#get_as_string ;
1731   inputt#reset in
1732  let _ =
1733   uri_entry#connect#changed
1734    (function () ->
1735      okb#misc#set_sensitive (!non_empty_type && uri_entry#text <> ""))
1736  in
1737  ignore (window#connect#destroy GMain.Main.quit) ;
1738  ignore (cancelb#connect#clicked window#destroy) ;
1739  ignore
1740   (okb#connect#clicked
1741     (function () ->
1742       chosen := true ;
1743       try
1744        let metasenv,parsed = newinputt#get_metasenv_and_term [] [] in
1745        let uristr = "cic:" ^ uri_entry#text in
1746        let uri = UriManager.uri_of_string uristr in
1747         if String.sub uristr (String.length uristr - 4) 4 <> ".con" then
1748          raise NotAUriToAConstant
1749         else
1750          begin
1751           try
1752            ignore (Getter.resolve uri) ;
1753            raise UriAlreadyInUse
1754           with
1755            Getter.Unresolved ->
1756             get_metasenv_and_term := (function () -> metasenv,parsed) ;
1757             get_uri := (function () -> uri) ; 
1758             window#destroy ()
1759          end
1760       with
1761        e ->
1762         output_html outputhtml
1763          ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1764   )) ;
1765  window#show () ;
1766  GMain.Main.main () ;
1767  if !chosen then
1768   try
1769    let metasenv,expr = !get_metasenv_and_term () in
1770     let _  = CicTypeChecker.type_of_aux' metasenv [] expr in
1771      ProofEngine.proof :=
1772       Some (!get_uri (), (1,[],expr)::metasenv, Cic.Meta (1,[]), expr) ;
1773      ProofEngine.goal := Some 1 ;
1774      refresh_sequent notebook ;
1775      refresh_proof output ;
1776      !save_set_sensitive true ;
1777      inputt#reset ;
1778      ProofEngine.intros ~mk_fresh_name_callback () ;
1779      refresh_sequent notebook ;
1780      refresh_proof output
1781   with
1782      RefreshSequentException e ->
1783       output_html outputhtml
1784        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1785         "sequent: " ^ Printexc.to_string e ^ "</h1>")
1786    | RefreshProofException e ->
1787       output_html outputhtml
1788        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1789         "proof: " ^ Printexc.to_string e ^ "</h1>")
1790    | e ->
1791       output_html outputhtml
1792        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1793 ;;
1794
1795 let check_term_in_scratch scratch_window metasenv context expr = 
1796  try
1797   let ty = CicTypeChecker.type_of_aux' metasenv context expr in
1798    let mml = mml_of_cic_term 111 (Cic.Cast (expr,ty)) in
1799     scratch_window#show () ;
1800     scratch_window#mmlwidget#load_doc ~dom:mml
1801  with
1802   e ->
1803    print_endline ("? " ^ CicPp.ppterm expr) ;
1804    raise e
1805 ;;
1806
1807 let check scratch_window () =
1808  let inputt = ((rendering_window ())#inputt : term_editor) in
1809  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1810   let metasenv =
1811    match !ProofEngine.proof with
1812       None -> []
1813     | Some (_,metasenv,_,_) -> metasenv
1814   in
1815   let context =
1816    match !ProofEngine.goal with
1817       None -> []
1818     | Some metano ->
1819        let (_,canonical_context,_) =
1820         List.find (function (m,_,_) -> m=metano) metasenv
1821        in
1822         canonical_context
1823   in
1824    try
1825     let metasenv',expr = inputt#get_metasenv_and_term context metasenv in
1826      check_term_in_scratch scratch_window metasenv' context expr
1827    with
1828     e ->
1829      output_html outputhtml
1830       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1831 ;;
1832
1833 let decompose_uris_choice_callback uris = 
1834 (* N.B.: in questo passaggio perdo l'informazione su exp_named_subst !!!! *)
1835   let module U = UriManager in 
1836    List.map 
1837     (function uri ->
1838       match Disambiguate.cic_textual_parser_uri_of_string uri with
1839          CicTextualParser0.IndTyUri (uri,typeno) -> (uri,typeno,[])
1840        | _ -> assert false)
1841     (interactive_user_uri_choice 
1842       ~selection_mode:`EXTENDED ~ok:"Ok" ~enable_button_for_non_vars:false 
1843       ~title:"Decompose" ~msg:"Please, select the Inductive Types to decompose" 
1844       (List.map 
1845         (function (uri,typeno,_) ->
1846           U.string_of_uri uri ^ "#1/" ^ string_of_int (typeno+1)
1847         ) uris)
1848     ) 
1849 ;;
1850
1851 (***********************)
1852 (*       TACTICS       *)
1853 (***********************)
1854
1855 let call_tactic tactic () =
1856  let notebook = (rendering_window ())#notebook in
1857  let output = ((rendering_window ())#output : GMathViewAux.single_selection_math_view) in
1858  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1859  let savedproof = !ProofEngine.proof in
1860  let savedgoal  = !ProofEngine.goal in
1861   begin
1862    try
1863     tactic () ;
1864     refresh_sequent notebook ;
1865     refresh_proof output
1866    with
1867       RefreshSequentException e ->
1868        output_html outputhtml
1869         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1870          "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1871        ProofEngine.proof := savedproof ;
1872        ProofEngine.goal := savedgoal ;
1873        refresh_sequent notebook
1874     | RefreshProofException e ->
1875        output_html outputhtml
1876         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1877          "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1878        ProofEngine.proof := savedproof ;
1879        ProofEngine.goal := savedgoal ;
1880        refresh_sequent notebook ;
1881        refresh_proof output
1882     | e ->
1883        output_html outputhtml
1884         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1885        ProofEngine.proof := savedproof ;
1886        ProofEngine.goal := savedgoal ;
1887   end
1888 ;;
1889
1890 let call_tactic_with_input tactic () =
1891  let notebook = (rendering_window ())#notebook in
1892  let output = ((rendering_window ())#output : GMathViewAux.single_selection_math_view) in
1893  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1894  let inputt = ((rendering_window ())#inputt : term_editor) in
1895  let savedproof = !ProofEngine.proof in
1896  let savedgoal  = !ProofEngine.goal in
1897   let uri,metasenv,bo,ty =
1898    match !ProofEngine.proof with
1899       None -> assert false
1900     | Some (uri,metasenv,bo,ty) -> uri,metasenv,bo,ty
1901   in
1902    let canonical_context =
1903     match !ProofEngine.goal with
1904        None -> assert false
1905      | Some metano ->
1906         let (_,canonical_context,_) =
1907          List.find (function (m,_,_) -> m=metano) metasenv
1908         in
1909          canonical_context
1910    in
1911     try
1912      let metasenv',expr =
1913       inputt#get_metasenv_and_term canonical_context metasenv
1914      in
1915       ProofEngine.proof := Some (uri,metasenv',bo,ty) ;
1916       tactic expr ;
1917       refresh_sequent notebook ;
1918       refresh_proof output ;
1919       inputt#reset
1920     with
1921        RefreshSequentException e ->
1922         output_html outputhtml
1923          ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1924           "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1925         ProofEngine.proof := savedproof ;
1926         ProofEngine.goal := savedgoal ;
1927         refresh_sequent notebook
1928      | RefreshProofException e ->
1929         output_html outputhtml
1930          ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1931           "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1932         ProofEngine.proof := savedproof ;
1933         ProofEngine.goal := savedgoal ;
1934         refresh_sequent notebook ;
1935         refresh_proof output
1936      | e ->
1937         output_html outputhtml
1938          ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1939         ProofEngine.proof := savedproof ;
1940         ProofEngine.goal := savedgoal ;
1941 ;;
1942
1943 let call_tactic_with_goal_input tactic () =
1944  let module L = LogicalOperations in
1945  let module G = Gdome in
1946   let notebook = (rendering_window ())#notebook in
1947   let output = ((rendering_window ())#output : GMathViewAux.single_selection_math_view) in
1948   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1949   let savedproof = !ProofEngine.proof in
1950   let savedgoal  = !ProofEngine.goal in
1951    match notebook#proofw#get_selection with
1952      Some node ->
1953       let xpath =
1954        ((node : Gdome.element)#getAttributeNS
1955          ~namespaceURI:helmns
1956          ~localName:(G.domString "xref"))#to_string
1957       in
1958        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
1959        else
1960         begin
1961          try
1962           match !current_goal_infos with
1963              Some (ids_to_terms, ids_to_father_ids,_) ->
1964               let id = xpath in
1965                tactic (Hashtbl.find ids_to_terms id) ;
1966                refresh_sequent notebook ;
1967                refresh_proof output
1968            | None -> assert false (* "ERROR: No current term!!!" *)
1969          with
1970             RefreshSequentException e ->
1971              output_html outputhtml
1972               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1973                "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
1974              ProofEngine.proof := savedproof ;
1975              ProofEngine.goal := savedgoal ;
1976              refresh_sequent notebook
1977           | RefreshProofException e ->
1978              output_html outputhtml
1979               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1980                "proof: " ^ Printexc.to_string e ^ "</h1>") ;
1981              ProofEngine.proof := savedproof ;
1982              ProofEngine.goal := savedgoal ;
1983              refresh_sequent notebook ;
1984              refresh_proof output
1985           | e ->
1986              output_html outputhtml
1987               ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1988              ProofEngine.proof := savedproof ;
1989              ProofEngine.goal := savedgoal ;
1990         end
1991    | None ->
1992       output_html outputhtml
1993        ("<h1 color=\"red\">No term selected</h1>")
1994 ;;
1995
1996 let call_tactic_with_input_and_goal_input tactic () =
1997  let module L = LogicalOperations in
1998  let module G = Gdome in
1999   let notebook = (rendering_window ())#notebook in
2000   let output = ((rendering_window ())#output : GMathViewAux.single_selection_math_view) in
2001   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2002   let inputt = ((rendering_window ())#inputt : term_editor) in
2003   let savedproof = !ProofEngine.proof in
2004   let savedgoal  = !ProofEngine.goal in
2005    match notebook#proofw#get_selection with
2006      Some node ->
2007       let xpath =
2008        ((node : Gdome.element)#getAttributeNS
2009          ~namespaceURI:helmns
2010          ~localName:(G.domString "xref"))#to_string
2011       in
2012        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
2013        else
2014         begin
2015          try
2016           match !current_goal_infos with
2017              Some (ids_to_terms, ids_to_father_ids,_) ->
2018               let id = xpath in
2019                let uri,metasenv,bo,ty =
2020                 match !ProofEngine.proof with
2021                    None -> assert false
2022                  | Some (uri,metasenv,bo,ty) -> uri,metasenv,bo,ty
2023                in
2024                 let canonical_context =
2025                  match !ProofEngine.goal with
2026                     None -> assert false
2027                   | Some metano ->
2028                      let (_,canonical_context,_) =
2029                       List.find (function (m,_,_) -> m=metano) metasenv
2030                      in
2031                       canonical_context in
2032                 let (metasenv',expr) =
2033                  inputt#get_metasenv_and_term canonical_context metasenv
2034                 in
2035                  ProofEngine.proof := Some (uri,metasenv',bo,ty) ;
2036                  tactic ~goal_input:(Hashtbl.find ids_to_terms id)
2037                   ~input:expr ;
2038                  refresh_sequent notebook ;
2039                  refresh_proof output ;
2040                  inputt#reset
2041            | None -> assert false (* "ERROR: No current term!!!" *)
2042          with
2043             RefreshSequentException e ->
2044              output_html outputhtml
2045               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2046                "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
2047              ProofEngine.proof := savedproof ;
2048              ProofEngine.goal := savedgoal ;
2049              refresh_sequent notebook
2050           | RefreshProofException e ->
2051              output_html outputhtml
2052               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2053                "proof: " ^ Printexc.to_string e ^ "</h1>") ;
2054              ProofEngine.proof := savedproof ;
2055              ProofEngine.goal := savedgoal ;
2056              refresh_sequent notebook ;
2057              refresh_proof output
2058           | e ->
2059              output_html outputhtml
2060               ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2061              ProofEngine.proof := savedproof ;
2062              ProofEngine.goal := savedgoal ;
2063         end
2064    | None ->
2065       output_html outputhtml
2066        ("<h1 color=\"red\">No term selected</h1>")
2067 ;;
2068
2069 let call_tactic_with_goal_input_in_scratch tactic scratch_window () =
2070  let module L = LogicalOperations in
2071  let module G = Gdome in
2072   let mmlwidget = (scratch_window#mmlwidget : GMathViewAux.single_selection_math_view) in
2073   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2074   let savedproof = !ProofEngine.proof in
2075   let savedgoal  = !ProofEngine.goal in
2076    match mmlwidget#get_selection with
2077      Some node ->
2078       let xpath =
2079        ((node : Gdome.element)#getAttributeNS
2080          ~namespaceURI:helmns
2081          ~localName:(G.domString "xref"))#to_string
2082       in
2083        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
2084        else
2085         begin
2086          try
2087           match !current_scratch_infos with
2088              (* term is the whole goal in the scratch_area *)
2089              Some (term,ids_to_terms, ids_to_father_ids,_) ->
2090               let id = xpath in
2091                let expr = tactic term (Hashtbl.find ids_to_terms id) in
2092                 let mml = mml_of_cic_term 111 expr in
2093                  scratch_window#show () ;
2094                  scratch_window#mmlwidget#load_doc ~dom:mml
2095            | None -> assert false (* "ERROR: No current term!!!" *)
2096          with
2097           e ->
2098            output_html outputhtml
2099             ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
2100         end
2101    | None ->
2102       output_html outputhtml
2103        ("<h1 color=\"red\">No term selected</h1>")
2104 ;;
2105
2106 let call_tactic_with_hypothesis_input tactic () =
2107  let module L = LogicalOperations in
2108  let module G = Gdome in
2109   let notebook = (rendering_window ())#notebook in
2110   let output = ((rendering_window ())#output : GMathViewAux.single_selection_math_view) in
2111   let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2112   let savedproof = !ProofEngine.proof in
2113   let savedgoal  = !ProofEngine.goal in
2114    match notebook#proofw#get_selection with
2115      Some node ->
2116       let xpath =
2117        ((node : Gdome.element)#getAttributeNS
2118          ~namespaceURI:helmns
2119          ~localName:(G.domString "xref"))#to_string
2120       in
2121        if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
2122        else
2123         begin
2124          try
2125           match !current_goal_infos with
2126              Some (_,_,ids_to_hypotheses) ->
2127               let id = xpath in
2128                tactic (Hashtbl.find ids_to_hypotheses id) ;
2129                refresh_sequent notebook ;
2130                refresh_proof output
2131            | None -> assert false (* "ERROR: No current term!!!" *)
2132          with
2133             RefreshSequentException e ->
2134              output_html outputhtml
2135               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2136                "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
2137              ProofEngine.proof := savedproof ;
2138              ProofEngine.goal := savedgoal ;
2139              refresh_sequent notebook
2140           | RefreshProofException e ->
2141              output_html outputhtml
2142               ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2143                "proof: " ^ Printexc.to_string e ^ "</h1>") ;
2144              ProofEngine.proof := savedproof ;
2145              ProofEngine.goal := savedgoal ;
2146              refresh_sequent notebook ;
2147              refresh_proof output
2148           | e ->
2149              output_html outputhtml
2150               ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2151              ProofEngine.proof := savedproof ;
2152              ProofEngine.goal := savedgoal ;
2153         end
2154    | None ->
2155       output_html outputhtml
2156        ("<h1 color=\"red\">No term selected</h1>")
2157 ;;
2158
2159
2160 let intros = call_tactic (ProofEngine.intros ~mk_fresh_name_callback);;
2161 let exact = call_tactic_with_input ProofEngine.exact;;
2162 let apply = call_tactic_with_input ProofEngine.apply;;
2163 let elimintrossimpl = call_tactic_with_input ProofEngine.elim_intros_simpl;;
2164 let elimtype = call_tactic_with_input ProofEngine.elim_type;;
2165 let whd = call_tactic_with_goal_input ProofEngine.whd;;
2166 let reduce = call_tactic_with_goal_input ProofEngine.reduce;;
2167 let simpl = call_tactic_with_goal_input ProofEngine.simpl;;
2168 let fold_whd = call_tactic_with_input ProofEngine.fold_whd;;
2169 let fold_reduce = call_tactic_with_input ProofEngine.fold_reduce;;
2170 let fold_simpl = call_tactic_with_input ProofEngine.fold_simpl;;
2171 let cut = call_tactic_with_input (ProofEngine.cut ~mk_fresh_name_callback);;
2172 let change = call_tactic_with_input_and_goal_input ProofEngine.change;;
2173 let letin = call_tactic_with_input (ProofEngine.letin ~mk_fresh_name_callback);;
2174 let ring = call_tactic ProofEngine.ring;;
2175 let clearbody = call_tactic_with_hypothesis_input ProofEngine.clearbody;;
2176 let clear = call_tactic_with_hypothesis_input ProofEngine.clear;;
2177 let fourier = call_tactic ProofEngine.fourier;;
2178 let rewritesimpl = call_tactic_with_input ProofEngine.rewrite_simpl;;
2179 let rewritebacksimpl = call_tactic_with_input ProofEngine.rewrite_back_simpl;;
2180 let replace = call_tactic_with_input_and_goal_input ProofEngine.replace;;
2181 let reflexivity = call_tactic ProofEngine.reflexivity;;
2182 let symmetry = call_tactic ProofEngine.symmetry;;
2183 let transitivity = call_tactic_with_input ProofEngine.transitivity;;
2184 let exists = call_tactic ProofEngine.exists;;
2185 let split = call_tactic ProofEngine.split;;
2186 let left = call_tactic ProofEngine.left;;
2187 let right = call_tactic ProofEngine.right;;
2188 let assumption = call_tactic ProofEngine.assumption;;
2189 let generalize = call_tactic_with_goal_input ProofEngine.generalize;;
2190 let absurd = call_tactic_with_input ProofEngine.absurd;;
2191 let contradiction = call_tactic ProofEngine.contradiction;;
2192 let decompose =
2193  call_tactic_with_input
2194   (ProofEngine.decompose ~uris_choice_callback:decompose_uris_choice_callback);;
2195
2196 let whd_in_scratch scratch_window =
2197  call_tactic_with_goal_input_in_scratch ProofEngine.whd_in_scratch
2198   scratch_window
2199 ;;
2200 let reduce_in_scratch scratch_window =
2201  call_tactic_with_goal_input_in_scratch ProofEngine.reduce_in_scratch
2202   scratch_window
2203 ;;
2204 let simpl_in_scratch scratch_window =
2205  call_tactic_with_goal_input_in_scratch ProofEngine.simpl_in_scratch
2206   scratch_window
2207 ;;
2208
2209
2210
2211 (**********************)
2212 (*   END OF TACTICS   *)
2213 (**********************)
2214
2215
2216 let show () =
2217  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2218   try
2219    show_in_show_window_uri (input_or_locate_uri ~title:"Show")
2220   with
2221    e ->
2222     output_html outputhtml
2223      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2224 ;;
2225
2226 exception NotADefinition;;
2227
2228 let open_ () =
2229  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2230  let output = ((rendering_window ())#output : GMathViewAux.single_selection_math_view) in
2231  let notebook = (rendering_window ())#notebook in
2232    try
2233     let uri = input_or_locate_uri ~title:"Open" in
2234      CicTypeChecker.typecheck uri ;
2235      let metasenv,bo,ty =
2236       match CicEnvironment.get_cooked_obj uri with
2237          Cic.Constant (_,Some bo,ty,_) -> [],bo,ty
2238        | Cic.CurrentProof (_,metasenv,bo,ty,_) -> metasenv,bo,ty
2239        | Cic.Constant _
2240        | Cic.Variable _
2241        | Cic.InductiveDefinition _ -> raise NotADefinition
2242      in
2243       ProofEngine.proof :=
2244        Some (uri, metasenv, bo, ty) ;
2245       ProofEngine.goal := None ;
2246       refresh_sequent notebook ;
2247       refresh_proof output
2248    with
2249       RefreshSequentException e ->
2250        output_html outputhtml
2251         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2252          "sequent: " ^ Printexc.to_string e ^ "</h1>")
2253     | RefreshProofException e ->
2254        output_html outputhtml
2255         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
2256          "proof: " ^ Printexc.to_string e ^ "</h1>")
2257     | e ->
2258        output_html outputhtml
2259         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2260 ;;
2261
2262 let show_query_results results =
2263  let window =
2264   GWindow.window
2265    ~modal:false ~title:"Query results." ~border_width:2 () in
2266  let vbox = GPack.vbox ~packing:window#add () in
2267  let hbox =
2268   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2269  let lMessage =
2270   GMisc.label
2271    ~text:"Click on a URI to show that object"
2272    ~packing:hbox#add () in
2273  let scrolled_window =
2274   GBin.scrolled_window ~border_width:10 ~height:400 ~width:600
2275    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2276  let clist = GList.clist ~columns:1 ~packing:scrolled_window#add () in
2277   ignore
2278    (List.map
2279      (function (uri,_) ->
2280        let n =
2281         clist#append [uri]
2282        in
2283         clist#set_row ~selectable:false n
2284      ) results
2285    ) ;
2286   clist#columns_autosize () ;
2287   ignore
2288    (clist#connect#select_row
2289      (fun ~row ~column ~event ->
2290        let (uristr,_) = List.nth results row in
2291         match
2292          Disambiguate.cic_textual_parser_uri_of_string
2293           (Disambiguate.wrong_xpointer_format_from_wrong_xpointer_format'
2294             uristr)
2295         with
2296            CicTextualParser0.ConUri uri
2297          | CicTextualParser0.VarUri uri
2298          | CicTextualParser0.IndTyUri (uri,_)
2299          | CicTextualParser0.IndConUri (uri,_,_) ->
2300             show_in_show_window_uri uri
2301      )
2302    ) ;
2303   window#show ()
2304 ;;
2305
2306 let refine_constraints (must_obj,must_rel,must_sort) =
2307  let chosen = ref false in
2308  let use_only = ref false in
2309  let window =
2310   GWindow.window
2311    ~modal:true ~title:"Constraints refinement."
2312    ~width:800 ~border_width:2 () in
2313  let vbox = GPack.vbox ~packing:window#add () in
2314  let hbox =
2315   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2316  let lMessage =
2317   GMisc.label
2318    ~text: "\"Only\" constraints can be enforced or not."
2319    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2320  let onlyb =
2321   GButton.toggle_button ~label:"Enforce \"only\" constraints"
2322    ~active:false ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2323  in
2324   ignore
2325    (onlyb#connect#toggled (function () -> use_only := onlyb#active)) ;
2326  (* Notebook for the constraints choice *)
2327  let notebook =
2328   GPack.notebook ~scrollable:true
2329    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2330  (* Rel constraints *)
2331  let label =
2332   GMisc.label
2333    ~text: "Constraints on Rels" () in
2334  let vbox' =
2335   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
2336    () in
2337  let hbox =
2338   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
2339  let lMessage =
2340   GMisc.label
2341    ~text: "You can now specify the constraints on Rels."
2342    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2343  let expected_height = 25 * (List.length must_rel + 2) in
2344  let height = if expected_height > 400 then 400 else expected_height in
2345  let scrolled_window =
2346   GBin.scrolled_window ~border_width:10 ~height ~width:600
2347    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
2348  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
2349  let rel_constraints =
2350   List.map
2351    (function (position,depth) ->
2352      let hbox =
2353       GPack.hbox
2354        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
2355      let lMessage =
2356       GMisc.label
2357        ~text:position
2358        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2359      match depth with
2360         None -> position, ref None
2361       | Some depth' ->
2362          let mutable_ref = ref (Some depth') in
2363          let depthb =
2364           GButton.toggle_button
2365            ~label:("depth = " ^ string_of_int depth') ~active:true
2366            ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2367          in
2368           ignore
2369            (depthb#connect#toggled
2370              (function () ->
2371                let sel_depth = if depthb#active then Some depth' else None in
2372                 mutable_ref := sel_depth
2373             )) ;
2374           position, mutable_ref
2375    ) must_rel in
2376  (* Sort constraints *)
2377  let label =
2378   GMisc.label
2379    ~text: "Constraints on Sorts" () in
2380  let vbox' =
2381   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
2382    () in
2383  let hbox =
2384   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
2385  let lMessage =
2386   GMisc.label
2387    ~text: "You can now specify the constraints on Sorts."
2388    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2389  let expected_height = 25 * (List.length must_sort + 2) in
2390  let height = if expected_height > 400 then 400 else expected_height in
2391  let scrolled_window =
2392   GBin.scrolled_window ~border_width:10 ~height ~width:600
2393    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
2394  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
2395  let sort_constraints =
2396   List.map
2397    (function (position,depth,sort) ->
2398      let hbox =
2399       GPack.hbox
2400        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
2401      let lMessage =
2402       GMisc.label
2403        ~text:(sort ^ " " ^ position)
2404        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2405      match depth with
2406         None -> position, ref None, sort
2407       | Some depth' ->
2408          let mutable_ref = ref (Some depth') in
2409          let depthb =
2410           GButton.toggle_button ~label:("depth = " ^ string_of_int depth')
2411            ~active:true
2412            ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2413          in
2414           ignore
2415            (depthb#connect#toggled
2416              (function () ->
2417                let sel_depth = if depthb#active then Some depth' else None in
2418                 mutable_ref := sel_depth
2419             )) ;
2420           position, mutable_ref, sort
2421    ) must_sort in
2422  (* Obj constraints *)
2423  let label =
2424   GMisc.label
2425    ~text: "Constraints on constants" () in
2426  let vbox' =
2427   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
2428    () in
2429  let hbox =
2430   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
2431  let lMessage =
2432   GMisc.label
2433    ~text: "You can now specify the constraints on constants."
2434    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2435  let expected_height = 25 * (List.length must_obj + 2) in
2436  let height = if expected_height > 400 then 400 else expected_height in
2437  let scrolled_window =
2438   GBin.scrolled_window ~border_width:10 ~height ~width:600
2439    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
2440  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
2441  let obj_constraints =
2442   List.map
2443    (function (uri,position,depth) ->
2444      let hbox =
2445       GPack.hbox
2446        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
2447      let lMessage =
2448       GMisc.label
2449        ~text:(uri ^ " " ^ position)
2450        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2451      match depth with
2452         None -> uri, position, ref None
2453       | Some depth' ->
2454          let mutable_ref = ref (Some depth') in
2455          let depthb =
2456           GButton.toggle_button ~label:("depth = " ^ string_of_int depth')
2457            ~active:true
2458            ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2459          in
2460           ignore
2461            (depthb#connect#toggled
2462              (function () ->
2463                let sel_depth = if depthb#active then Some depth' else None in
2464                 mutable_ref := sel_depth
2465             )) ;
2466           uri, position, mutable_ref
2467    ) must_obj in
2468  (* Confirm/abort buttons *)
2469  let hbox =
2470   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2471  let okb =
2472   GButton.button ~label:"Ok"
2473    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2474  let cancelb =
2475   GButton.button ~label:"Abort"
2476    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
2477  in
2478   ignore (window#connect#destroy GMain.Main.quit) ;
2479   ignore (cancelb#connect#clicked window#destroy) ;
2480   ignore
2481    (okb#connect#clicked (function () -> chosen := true ; window#destroy ()));
2482   window#set_position `CENTER ;
2483   window#show () ;
2484   GMain.Main.main () ;
2485   if !chosen then
2486    let chosen_must_rel =
2487     List.map
2488      (function (position,ref_depth) -> position,!ref_depth) rel_constraints in
2489    let chosen_must_sort =
2490     List.map
2491      (function (position,ref_depth,sort) -> position,!ref_depth,sort)
2492      sort_constraints
2493    in
2494    let chosen_must_obj =
2495     List.map
2496      (function (uri,position,ref_depth) -> uri,position,!ref_depth)
2497      obj_constraints
2498    in
2499     (chosen_must_obj,chosen_must_rel,chosen_must_sort),
2500      (if !use_only then
2501 (*CSC: ???????????????????????? I assume that must and only are the same... *)
2502        Some chosen_must_obj,Some chosen_must_rel,Some chosen_must_sort
2503       else
2504        None,None,None
2505      )
2506   else
2507    raise NoChoice
2508 ;;
2509
2510 let completeSearchPattern () =
2511  let inputt = ((rendering_window ())#inputt : term_editor) in
2512  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2513   try
2514    let metasenv,expr = inputt#get_metasenv_and_term ~context:[] ~metasenv:[] in
2515    let must = MQueryLevels2.get_constraints expr in
2516    let must',only = refine_constraints must in
2517    let results = MQueryGenerator.searchPattern must' only in 
2518     show_query_results results
2519   with
2520    e ->
2521     output_html outputhtml
2522      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2523 ;;
2524
2525 let insertQuery () =
2526  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2527   try
2528    let chosen = ref None in
2529    let window =
2530     GWindow.window
2531      ~modal:true ~title:"Insert Query (Experts Only)" ~border_width:2 () in
2532    let vbox = GPack.vbox ~packing:window#add () in
2533    let label =
2534     GMisc.label ~text:"Insert Query. For Experts Only."
2535      ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2536    let scrolled_window =
2537     GBin.scrolled_window ~border_width:10 ~height:400 ~width:600
2538      ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2539    let input = GEdit.text ~editable:true
2540     ~packing:scrolled_window#add () in
2541    let hbox =
2542     GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2543    let okb =
2544     GButton.button ~label:"Ok"
2545      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2546    let loadb =
2547     GButton.button ~label:"Load from file..."
2548      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2549    let cancelb =
2550     GButton.button ~label:"Abort"
2551      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2552    ignore (window#connect#destroy GMain.Main.quit) ;
2553    ignore (cancelb#connect#clicked window#destroy) ;
2554    ignore
2555     (okb#connect#clicked
2556       (function () ->
2557         chosen := Some (input#get_chars 0 input#length) ; window#destroy ())) ;
2558    ignore
2559     (loadb#connect#clicked
2560       (function () ->
2561         match
2562          GToolbox.select_file ~title:"Select Query File" ()
2563         with
2564            None -> ()
2565          | Some filename ->
2566             let inch = open_in filename in
2567              let rec read_file () =
2568               try
2569                let line = input_line inch in
2570                 line ^ "\n" ^ read_file ()
2571               with
2572                End_of_file -> ""
2573              in
2574               let text = read_file () in
2575                input#delete_text 0 input#length ;
2576                ignore (input#insert_text text ~pos:0))) ;
2577    window#set_position `CENTER ;
2578    window#show () ;
2579    GMain.Main.main () ;
2580    match !chosen with
2581       None -> ()
2582     | Some q ->
2583        let results =
2584         Mqint.execute (MQueryUtil.query_of_text (Lexing.from_string q))
2585        in
2586         show_query_results results
2587   with
2588    e ->
2589     output_html outputhtml
2590      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2591 ;;
2592
2593 let choose_must list_of_must only =
2594  let chosen = ref None in
2595  let user_constraints = ref [] in
2596  let window =
2597   GWindow.window
2598    ~modal:true ~title:"Query refinement." ~border_width:2 () in
2599  let vbox = GPack.vbox ~packing:window#add () in
2600  let hbox =
2601   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2602  let lMessage =
2603   GMisc.label
2604    ~text:
2605     ("You can now specify the genericity of the query. " ^
2606      "The more generic the slower.")
2607    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2608  let hbox =
2609   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2610  let lMessage =
2611   GMisc.label
2612    ~text:
2613     "Suggestion: start with faster queries before moving to more generic ones."
2614    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2615  let notebook =
2616   GPack.notebook ~scrollable:true
2617    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2618  let _ =
2619   let page = ref 0 in
2620   let last = List.length list_of_must in
2621   List.map
2622    (function must ->
2623      incr page ;
2624      let label =
2625       GMisc.label ~text:
2626        (if !page = 1 then "More generic" else
2627          if !page = last then "More precise" else "          ") () in
2628      let expected_height = 25 * (List.length must + 2) in
2629      let height = if expected_height > 400 then 400 else expected_height in
2630      let scrolled_window =
2631       GBin.scrolled_window ~border_width:10 ~height ~width:600
2632        ~packing:(notebook#append_page ~tab_label:label#coerce) () in
2633      let clist =
2634         GList.clist ~columns:2 ~packing:scrolled_window#add
2635          ~titles:["URI" ; "Position"] ()
2636      in
2637       ignore
2638        (List.map
2639          (function (uri,position) ->
2640            let n =
2641             clist#append 
2642              [uri; if position then "MainConclusion" else "Conclusion"]
2643            in
2644             clist#set_row ~selectable:false n
2645          ) must
2646        ) ;
2647       clist#columns_autosize ()
2648    ) list_of_must in
2649  let _ =
2650   let label = GMisc.label ~text:"User provided" () in
2651   let vbox =
2652    GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce) () in
2653   let hbox =
2654    GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2655   let lMessage =
2656    GMisc.label
2657    ~text:"Select the constraints that must be satisfied and press OK."
2658    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2659   let expected_height = 25 * (List.length only + 2) in
2660   let height = if expected_height > 400 then 400 else expected_height in
2661   let scrolled_window =
2662    GBin.scrolled_window ~border_width:10 ~height ~width:600
2663     ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2664   let clist =
2665    GList.clist ~columns:2 ~packing:scrolled_window#add
2666     ~selection_mode:`EXTENDED
2667     ~titles:["URI" ; "Position"] ()
2668   in
2669    ignore
2670     (List.map
2671       (function (uri,position) ->
2672         let n =
2673          clist#append 
2674           [uri; if position then "MainConclusion" else "Conclusion"]
2675         in
2676          clist#set_row ~selectable:true n
2677       ) only
2678     ) ;
2679    clist#columns_autosize () ;
2680    ignore
2681     (clist#connect#select_row
2682       (fun ~row ~column ~event ->
2683         user_constraints := (List.nth only row)::!user_constraints)) ;
2684    ignore
2685     (clist#connect#unselect_row
2686       (fun ~row ~column ~event ->
2687         user_constraints :=
2688          List.filter
2689           (function uri -> uri != (List.nth only row)) !user_constraints)) ;
2690  in
2691  let hbox =
2692   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2693  let okb =
2694   GButton.button ~label:"Ok"
2695    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2696  let cancelb =
2697   GButton.button ~label:"Abort"
2698    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2699  (* actions *)
2700  ignore (window#connect#destroy GMain.Main.quit) ;
2701  ignore (cancelb#connect#clicked window#destroy) ;
2702  ignore
2703   (okb#connect#clicked
2704     (function () -> chosen := Some notebook#current_page ; window#destroy ())) ;
2705  window#set_position `CENTER ;
2706  window#show () ;
2707  GMain.Main.main () ;
2708  match !chosen with
2709     None -> raise NoChoice
2710   | Some n ->
2711      if n = List.length list_of_must then
2712       (* user provided constraints *)
2713       !user_constraints
2714      else
2715       List.nth list_of_must n
2716 ;;
2717
2718 let searchPattern () =
2719  let inputt = ((rendering_window ())#inputt : term_editor) in
2720  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2721   try
2722     let metasenv =
2723      match !ProofEngine.proof with
2724         None -> assert false
2725       | Some (_,metasenv,_,_) -> metasenv
2726     in
2727      match !ProofEngine.goal with
2728         None -> ()
2729       | Some metano ->
2730          let (_, ey ,ty) = List.find (function (m,_,_) -> m=metano) metasenv in
2731           let list_of_must,only = MQueryLevels.out_restr metasenv ey ty in
2732           let must = choose_must list_of_must only in
2733           let torigth_restriction (u,b) =
2734            let p =
2735             if b then
2736              "http://www.cs.unibo.it/helm/schemas/schema-helm#MainConclusion" 
2737             else
2738              "http://www.cs.unibo.it/helm/schemas/schema-helm#InConclusion"
2739            in
2740             (u,p,None)
2741           in
2742           let rigth_must = List.map torigth_restriction must in
2743           let rigth_only = Some (List.map torigth_restriction only) in
2744           let result =
2745            MQueryGenerator.searchPattern
2746             (rigth_must,[],[]) (rigth_only,None,None) in 
2747           let uris =
2748            List.map
2749             (function uri,_ ->
2750               Disambiguate.wrong_xpointer_format_from_wrong_xpointer_format' uri
2751             ) result in
2752           let html =
2753            " <h1>Backward Query: </h1>" ^
2754            " <pre>" ^ get_last_query result ^ "</pre>"
2755           in
2756            output_html outputhtml html ;
2757            let uris',exc =
2758             let rec filter_out =
2759              function
2760                 [] -> [],""
2761               | uri::tl ->
2762                  let tl',exc = filter_out tl in
2763                   try
2764                    if
2765                     ProofEngine.can_apply
2766                      (term_of_cic_textual_parser_uri
2767                       (Disambiguate.cic_textual_parser_uri_of_string uri))
2768                    then
2769                     uri::tl',exc
2770                    else
2771                     tl',exc
2772                   with
2773                    e ->
2774                     let exc' =
2775                      "<h1 color=\"red\"> ^ Exception raised trying to apply " ^
2776                       uri ^ ": " ^ Printexc.to_string e ^ " </h1>" ^ exc
2777                     in
2778                      tl',exc'
2779             in
2780              filter_out uris
2781            in
2782             let html' =
2783              " <h1>Objects that can actually be applied: </h1> " ^
2784              String.concat "<br>" uris' ^ exc ^
2785              " <h1>Number of false matches: " ^
2786               string_of_int (List.length uris - List.length uris') ^ "</h1>" ^
2787              " <h1>Number of good matches: " ^
2788               string_of_int (List.length uris') ^ "</h1>"
2789             in
2790              output_html outputhtml html' ;
2791              let uri' =
2792               user_uri_choice ~title:"Ambiguous input."
2793               ~msg:
2794                 "Many lemmas can be successfully applied. Please, choose one:"
2795                uris'
2796              in
2797               inputt#set_term uri' ;
2798               apply ()
2799   with
2800    e -> 
2801     output_html outputhtml 
2802      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
2803 ;;
2804       
2805 let choose_selection
2806      (mmlwidget : GMathViewAux.single_selection_math_view) (element : Gdome.element option)
2807 =
2808  let module G = Gdome in
2809   let rec aux element =
2810    if element#hasAttributeNS
2811        ~namespaceURI:helmns
2812        ~localName:(G.domString "xref")
2813    then
2814      mmlwidget#set_selection (Some element)
2815    else
2816     try
2817       match element#get_parentNode with
2818          None -> assert false
2819        (*CSC: OCAML DIVERGES!
2820        | Some p -> aux (new G.element_of_node p)
2821        *)
2822        | Some p -> aux (new Gdome.element_of_node p)
2823     with
2824        GdomeInit.DOMCastException _ ->
2825         Printf.printf "******* trying to select above the document root ********\n" ; flush stdout
2826         
2827   in
2828    match element with
2829      Some x -> aux x
2830    | None   -> mmlwidget#set_selection None
2831 ;;
2832
2833 (* STUFF TO BUILD THE GTK INTERFACE *)
2834
2835 (* Stuff for the widget settings *)
2836
2837 let export_to_postscript (output : GMathViewAux.single_selection_math_view) =
2838  let lastdir = ref (Unix.getcwd ()) in
2839   function () ->
2840    match
2841     GToolbox.select_file ~title:"Export to PostScript"
2842      ~dir:lastdir ~filename:"screenshot.ps" ()
2843    with
2844       None -> ()
2845     | Some filename ->
2846        output#export_to_postscript ~filename:filename ();
2847 ;;
2848
2849 let activate_t1 (output : GMathViewAux.single_selection_math_view) button_set_anti_aliasing
2850  button_set_transparency export_to_postscript_menu_item
2851  button_t1 ()
2852 =
2853  let is_set = button_t1#active in
2854   output#set_font_manager_type
2855    (if is_set then `font_manager_t1 else `font_manager_gtk) ;
2856   if is_set then
2857    begin
2858     button_set_anti_aliasing#misc#set_sensitive true ;
2859     button_set_transparency#misc#set_sensitive true ;
2860     export_to_postscript_menu_item#misc#set_sensitive true ;
2861    end
2862   else
2863    begin
2864     button_set_anti_aliasing#misc#set_sensitive false ;
2865     button_set_transparency#misc#set_sensitive false ;
2866     export_to_postscript_menu_item#misc#set_sensitive false ;
2867    end
2868 ;;
2869
2870 let set_anti_aliasing output button_set_anti_aliasing () =
2871  output#set_anti_aliasing button_set_anti_aliasing#active
2872 ;;
2873
2874 let set_transparency output button_set_transparency () =
2875  output#set_transparency button_set_transparency#active
2876 ;;
2877
2878 let changefont output font_size_spinb () =
2879  output#set_font_size font_size_spinb#value_as_int
2880 ;;
2881
2882 let set_log_verbosity output log_verbosity_spinb () =
2883  output#set_log_verbosity log_verbosity_spinb#value_as_int
2884 ;;
2885
2886 class settings_window (output : GMathViewAux.single_selection_math_view) sw
2887  export_to_postscript_menu_item selection_changed_callback
2888 =
2889  let settings_window = GWindow.window ~title:"GtkMathView settings" () in
2890  let vbox =
2891   GPack.vbox ~packing:settings_window#add () in
2892  let table =
2893   GPack.table
2894    ~rows:1 ~columns:3 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2895    ~border_width:5 ~packing:vbox#add () in
2896  let button_t1 =
2897   GButton.toggle_button ~label:"activate t1 fonts"
2898    ~packing:(table#attach ~left:0 ~top:0) () in
2899  let button_set_anti_aliasing =
2900   GButton.toggle_button ~label:"set_anti_aliasing"
2901    ~packing:(table#attach ~left:0 ~top:1) () in
2902  let button_set_transparency =
2903   GButton.toggle_button ~label:"set_transparency"
2904    ~packing:(table#attach ~left:2 ~top:1) () in
2905  let table =
2906   GPack.table
2907    ~rows:2 ~columns:2 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2908    ~border_width:5 ~packing:vbox#add () in
2909  let font_size_label =
2910   GMisc.label ~text:"font size:"
2911    ~packing:(table#attach ~left:0 ~top:0 ~expand:`NONE) () in
2912  let font_size_spinb =
2913   let sadj =
2914    GData.adjustment ~value:14.0 ~lower:5.0 ~upper:50.0 ~step_incr:1.0 ()
2915   in
2916    GEdit.spin_button 
2917     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:0 ~fill:`NONE) () in
2918  let log_verbosity_label =
2919   GMisc.label ~text:"log verbosity:"
2920    ~packing:(table#attach ~left:0 ~top:1) () in
2921  let log_verbosity_spinb =
2922   let sadj =
2923    GData.adjustment ~value:0.0 ~lower:0.0 ~upper:3.0 ~step_incr:1.0 ()
2924   in
2925    GEdit.spin_button 
2926     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:1) () in
2927  let hbox =
2928   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2929  let closeb =
2930   GButton.button ~label:"Close"
2931    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2932 object(self)
2933  method show = settings_window#show
2934  initializer
2935   button_set_anti_aliasing#misc#set_sensitive false ;
2936   button_set_transparency#misc#set_sensitive false ;
2937   (* Signals connection *)
2938   ignore(button_t1#connect#clicked
2939    (activate_t1 output button_set_anti_aliasing
2940     button_set_transparency export_to_postscript_menu_item button_t1)) ;
2941   ignore(font_size_spinb#connect#changed (changefont output font_size_spinb)) ;
2942   ignore(button_set_anti_aliasing#connect#toggled
2943    (set_anti_aliasing output button_set_anti_aliasing));
2944   ignore(button_set_transparency#connect#toggled
2945    (set_transparency output button_set_transparency)) ;
2946   ignore(log_verbosity_spinb#connect#changed
2947    (set_log_verbosity output log_verbosity_spinb)) ;
2948   ignore(closeb#connect#clicked settings_window#misc#hide)
2949 end;;
2950
2951 (* Scratch window *)
2952
2953 class scratch_window =
2954  let window =
2955   GWindow.window ~title:"MathML viewer" ~border_width:2 () in
2956  let vbox =
2957   GPack.vbox ~packing:window#add () in
2958  let hbox =
2959   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2960  let whdb =
2961   GButton.button ~label:"Whd"
2962    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2963  let reduceb =
2964   GButton.button ~label:"Reduce"
2965    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2966  let simplb =
2967   GButton.button ~label:"Simpl"
2968    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2969  let scrolled_window =
2970   GBin.scrolled_window ~border_width:10
2971    ~packing:(vbox#pack ~expand:true ~padding:5) () in
2972  let mmlwidget =
2973   GMathViewAux.single_selection_math_view
2974    ~packing:(scrolled_window#add) ~width:400 ~height:280 () in
2975 object(self)
2976  method mmlwidget = mmlwidget
2977  method show () = window#misc#hide () ; window#show ()
2978  initializer
2979   ignore(mmlwidget#connect#selection_changed (choose_selection mmlwidget)) ;
2980   ignore(window#event#connect#delete (fun _ -> window#misc#hide () ; true )) ;
2981   ignore(whdb#connect#clicked (whd_in_scratch self)) ;
2982   ignore(reduceb#connect#clicked (reduce_in_scratch self)) ;
2983   ignore(simplb#connect#clicked (simpl_in_scratch self))
2984 end;;
2985
2986 class page () =
2987  let vbox1 = GPack.vbox () in
2988 object(self)
2989  val mutable proofw_ref = None
2990  val mutable compute_ref = None
2991  method proofw =
2992   Lazy.force self#compute ;
2993   match proofw_ref with
2994      None -> assert false
2995    | Some proofw -> proofw
2996  method content = vbox1
2997  method compute =
2998   match compute_ref with
2999      None -> assert false
3000    | Some compute -> compute
3001  initializer
3002   compute_ref <-
3003    Some (lazy (
3004    let scrolled_window1 =
3005     GBin.scrolled_window ~border_width:10
3006      ~packing:(vbox1#pack ~expand:true ~padding:5) () in
3007    let proofw =
3008     GMathViewAux.single_selection_math_view ~width:400 ~height:275
3009      ~packing:(scrolled_window1#add) () in
3010    let _ = proofw_ref <- Some proofw in
3011    let hbox3 =
3012     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
3013    let exactb =
3014     GButton.button ~label:"Exact"
3015      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3016    let introsb =
3017     GButton.button ~label:"Intros"
3018      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3019    let applyb =
3020     GButton.button ~label:"Apply"
3021      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3022    let elimintrossimplb =
3023     GButton.button ~label:"ElimIntrosSimpl"
3024      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3025    let elimtypeb =
3026     GButton.button ~label:"ElimType"
3027      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3028    let whdb =
3029     GButton.button ~label:"Whd"
3030      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3031    let reduceb =
3032     GButton.button ~label:"Reduce"
3033      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3034    let simplb =
3035     GButton.button ~label:"Simpl"
3036      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
3037    let hbox4 =
3038     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
3039    let foldwhdb =
3040     GButton.button ~label:"Fold_whd"
3041      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3042    let foldreduceb =
3043     GButton.button ~label:"Fold_reduce"
3044      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3045    let foldsimplb =
3046     GButton.button ~label:"Fold_simpl"
3047      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3048    let cutb =
3049     GButton.button ~label:"Cut"
3050      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3051    let changeb =
3052     GButton.button ~label:"Change"
3053      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3054    let letinb =
3055     GButton.button ~label:"Let ... In"
3056      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3057    let ringb =
3058     GButton.button ~label:"Ring"
3059      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
3060    let hbox5 =
3061     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
3062    let clearbodyb =
3063     GButton.button ~label:"ClearBody"
3064      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3065    let clearb =
3066     GButton.button ~label:"Clear"
3067      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3068    let fourierb =
3069     GButton.button ~label:"Fourier"
3070      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3071    let rewritesimplb =
3072     GButton.button ~label:"RewriteSimpl ->"
3073      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3074    let rewritebacksimplb =
3075     GButton.button ~label:"RewriteSimpl <-"
3076      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3077    let replaceb =
3078     GButton.button ~label:"Replace"
3079      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
3080    let hbox6 =
3081     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
3082    let reflexivityb =
3083     GButton.button ~label:"Reflexivity"
3084      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3085    let symmetryb =
3086     GButton.button ~label:"Symmetry"
3087      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3088    let transitivityb =
3089     GButton.button ~label:"Transitivity"
3090      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3091    let existsb =
3092     GButton.button ~label:"Exists"
3093      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3094    let splitb =
3095     GButton.button ~label:"Split"
3096      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3097    let leftb =
3098     GButton.button ~label:"Left"
3099      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3100    let rightb =
3101     GButton.button ~label:"Right"
3102      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3103    let assumptionb =
3104     GButton.button ~label:"Assumption"
3105      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
3106    let hbox7 =
3107     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
3108    let generalizeb =
3109     GButton.button ~label:"Generalize"
3110      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
3111    let absurdb =
3112     GButton.button ~label:"Absurd"
3113      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
3114    let contradictionb =
3115     GButton.button ~label:"Contradiction"
3116      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
3117    let searchpatternb =
3118     GButton.button ~label:"SearchPattern_Apply"
3119      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
3120    let decomposeb =
3121     GButton.button ~label:"Decompose"
3122      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
3123
3124    ignore(exactb#connect#clicked exact) ;
3125    ignore(applyb#connect#clicked apply) ;
3126    ignore(elimintrossimplb#connect#clicked elimintrossimpl) ;
3127    ignore(elimtypeb#connect#clicked elimtype) ;
3128    ignore(whdb#connect#clicked whd) ;
3129    ignore(reduceb#connect#clicked reduce) ;
3130    ignore(simplb#connect#clicked simpl) ;
3131    ignore(foldwhdb#connect#clicked fold_whd) ;
3132    ignore(foldreduceb#connect#clicked fold_reduce) ;
3133    ignore(foldsimplb#connect#clicked fold_simpl) ;
3134    ignore(cutb#connect#clicked cut) ;
3135    ignore(changeb#connect#clicked change) ;
3136    ignore(letinb#connect#clicked letin) ;
3137    ignore(ringb#connect#clicked ring) ;
3138    ignore(clearbodyb#connect#clicked clearbody) ;
3139    ignore(clearb#connect#clicked clear) ;
3140    ignore(fourierb#connect#clicked fourier) ;
3141    ignore(rewritesimplb#connect#clicked rewritesimpl) ;
3142    ignore(rewritebacksimplb#connect#clicked rewritebacksimpl) ;
3143    ignore(replaceb#connect#clicked replace) ;
3144    ignore(reflexivityb#connect#clicked reflexivity) ;
3145    ignore(symmetryb#connect#clicked symmetry) ;
3146    ignore(transitivityb#connect#clicked transitivity) ;
3147    ignore(existsb#connect#clicked exists) ;
3148    ignore(splitb#connect#clicked split) ;
3149    ignore(leftb#connect#clicked left) ;
3150    ignore(rightb#connect#clicked right) ;
3151    ignore(assumptionb#connect#clicked assumption) ;
3152    ignore(generalizeb#connect#clicked generalize) ;
3153    ignore(absurdb#connect#clicked absurd) ;
3154    ignore(contradictionb#connect#clicked contradiction) ;
3155    ignore(introsb#connect#clicked intros) ;
3156    ignore(searchpatternb#connect#clicked searchPattern) ;
3157    ignore(proofw#connect#selection_changed (choose_selection proofw)) ;
3158    ignore(decomposeb#connect#clicked decompose) ;
3159   ))
3160 end
3161 ;;
3162
3163 class empty_page =
3164  let vbox1 = GPack.vbox () in
3165  let scrolled_window1 =
3166   GBin.scrolled_window ~border_width:10
3167    ~packing:(vbox1#pack ~expand:true ~padding:5) () in
3168  let proofw =
3169   GMathViewAux.single_selection_math_view ~width:400 ~height:275
3170    ~packing:(scrolled_window1#add) () in
3171 object(self)
3172  method proofw = (assert false : GMathViewAux.single_selection_math_view)
3173  method content = vbox1
3174  method compute = (assert false : unit)
3175 end
3176 ;;
3177
3178 let empty_page = new empty_page;;
3179
3180 class notebook =
3181 object(self)
3182  val notebook = GPack.notebook ()
3183  val pages = ref []
3184  val mutable skip_switch_page_event = false 
3185  val mutable empty = true
3186  method notebook = notebook
3187  method add_page n =
3188   let new_page = new page () in
3189    empty <- false ;
3190    pages := !pages @ [n,lazy (setgoal n),new_page] ;
3191    notebook#append_page
3192     ~tab_label:((GMisc.label ~text:("?" ^ string_of_int n) ())#coerce)
3193     new_page#content#coerce
3194  method remove_all_pages ~skip_switch_page_event:skip =
3195   if empty then
3196    notebook#remove_page 0 (* let's remove the empty page *)
3197   else
3198    List.iter (function _ -> notebook#remove_page 0) !pages ;
3199   pages := [] ;
3200   skip_switch_page_event <- skip
3201  method set_current_page ~may_skip_switch_page_event n =
3202   let (_,_,page) = List.find (function (m,_,_) -> m=n) !pages in
3203    let new_page = notebook#page_num page#content#coerce in
3204     if may_skip_switch_page_event && new_page <> notebook#current_page then
3205      skip_switch_page_event <- true ;
3206     notebook#goto_page new_page
3207  method set_empty_page =
3208   empty <- true ;
3209   pages := [] ;
3210   notebook#append_page
3211    ~tab_label:((GMisc.label ~text:"No proof in progress" ())#coerce)
3212    empty_page#content#coerce
3213  method proofw =
3214   let (_,_,page) = List.nth !pages notebook#current_page in
3215    page#proofw
3216  initializer
3217   ignore
3218    (notebook#connect#switch_page
3219     (function i ->
3220       let skip = skip_switch_page_event in
3221        skip_switch_page_event <- false ;
3222        if not skip then
3223         try
3224          let (metano,setgoal,page) = List.nth !pages i in
3225           ProofEngine.goal := Some metano ;
3226           Lazy.force (page#compute) ;
3227           Lazy.force setgoal
3228         with _ -> ()
3229     ))
3230 end
3231 ;;
3232
3233 (* Main window *)
3234
3235 class rendering_window output (notebook : notebook) =
3236  let scratch_window = new scratch_window in
3237  let window =
3238   GWindow.window ~title:"MathML viewer" ~border_width:0
3239    ~allow_shrink:false () in
3240  let vbox_for_menu = GPack.vbox ~packing:window#add () in
3241  (* menus *)
3242  let handle_box = GBin.handle_box ~border_width:2
3243   ~packing:(vbox_for_menu#pack ~padding:0) () in
3244  let menubar = GMenu.menu_bar ~packing:handle_box#add () in
3245  let factory0 = new GMenu.factory menubar in
3246  let accel_group = factory0#accel_group in
3247  (* file menu *)
3248  let file_menu = factory0#add_submenu "File" in
3249  let factory1 = new GMenu.factory file_menu ~accel_group in
3250  let export_to_postscript_menu_item =
3251   begin
3252    let _ =
3253     factory1#add_item "New Block of (Co)Inductive Definitions..."
3254      ~key:GdkKeysyms._B ~callback:new_inductive
3255    in
3256    let _ =
3257     factory1#add_item "New Proof or Definition..." ~key:GdkKeysyms._N
3258      ~callback:new_proof
3259    in
3260    let reopen_menu_item =
3261     factory1#add_item "Reopen a Finished Proof..." ~key:GdkKeysyms._R
3262      ~callback:open_
3263    in
3264    let qed_menu_item =
3265     factory1#add_item "Qed" ~key:GdkKeysyms._E ~callback:qed in
3266    ignore (factory1#add_separator ()) ;
3267    ignore
3268     (factory1#add_item "Load Unfinished Proof..." ~key:GdkKeysyms._L
3269       ~callback:load) ;
3270    let save_menu_item =
3271     factory1#add_item "Save Unfinished Proof" ~key:GdkKeysyms._S ~callback:save
3272    in
3273    ignore
3274     (save_set_sensitive := function b -> save_menu_item#misc#set_sensitive b);
3275    ignore (!save_set_sensitive false);
3276    ignore (qed_set_sensitive:=function b -> qed_menu_item#misc#set_sensitive b);
3277    ignore (!qed_set_sensitive false);
3278    ignore (factory1#add_separator ()) ;
3279    let export_to_postscript_menu_item =
3280     factory1#add_item "Export to PostScript..."
3281      ~callback:(export_to_postscript output) in
3282    ignore (factory1#add_separator ()) ;
3283    ignore
3284     (factory1#add_item "Exit" ~key:GdkKeysyms._Q ~callback:GMain.Main.quit) ;
3285    export_to_postscript_menu_item
3286   end in
3287  (* edit menu *)
3288  let edit_menu = factory0#add_submenu "Edit Current Proof" in
3289  let factory2 = new GMenu.factory edit_menu ~accel_group in
3290  let focus_and_proveit_set_sensitive = ref (function _ -> assert false) in
3291  let proveit_menu_item =
3292   factory2#add_item "Prove It" ~key:GdkKeysyms._I
3293    ~callback:(function () -> proveit ();!focus_and_proveit_set_sensitive false)
3294  in
3295  let focus_menu_item =
3296   factory2#add_item "Focus" ~key:GdkKeysyms._F
3297    ~callback:(function () -> focus () ; !focus_and_proveit_set_sensitive false)
3298  in
3299  let _ =
3300   focus_and_proveit_set_sensitive :=
3301    function b ->
3302     proveit_menu_item#misc#set_sensitive b ;
3303     focus_menu_item#misc#set_sensitive b
3304  in
3305  let _ = !focus_and_proveit_set_sensitive false in
3306  (* edit term menu *)
3307  let edit_term_menu = factory0#add_submenu "Edit Term" in
3308  let factory5 = new GMenu.factory edit_term_menu ~accel_group in
3309  let check_menu_item =
3310   factory5#add_item "Check Term" ~key:GdkKeysyms._C
3311    ~callback:(check scratch_window) in
3312  let _ = check_menu_item#misc#set_sensitive false in
3313  (* search menu *)
3314  let settings_menu = factory0#add_submenu "Search" in
3315  let factory4 = new GMenu.factory settings_menu ~accel_group in
3316  let _ =
3317   factory4#add_item "Locate..." ~key:GdkKeysyms._T
3318    ~callback:locate in
3319  let searchPattern_menu_item =
3320   factory4#add_item "SearchPattern..." ~key:GdkKeysyms._D
3321    ~callback:completeSearchPattern in
3322  let _ = searchPattern_menu_item#misc#set_sensitive false in
3323  let show_menu_item =
3324   factory4#add_item "Show..." ~key:GdkKeysyms._H ~callback:show
3325  in
3326  let insert_query_item =
3327   factory4#add_item "Insert Query (Experts Only)..." ~key:GdkKeysyms._U
3328    ~callback:insertQuery in
3329  (* settings menu *)
3330  let settings_menu = factory0#add_submenu "Settings" in
3331  let factory3 = new GMenu.factory settings_menu ~accel_group in
3332  let _ =
3333   factory3#add_item "Edit Aliases" ~key:GdkKeysyms._A
3334    ~callback:edit_aliases in
3335  let _ = factory3#add_separator () in
3336  let _ =
3337   factory3#add_item "MathML Widget Preferences..." ~key:GdkKeysyms._P
3338    ~callback:(function _ -> (settings_window ())#show ()) in
3339  (* accel group *)
3340  let _ = window#add_accel_group accel_group in
3341  (* end of menus *)
3342  let hbox0 =
3343   GPack.hbox
3344    ~packing:(vbox_for_menu#pack ~expand:true ~fill:true ~padding:5) () in
3345  let vbox =
3346   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
3347  let scrolled_window0 =
3348   GBin.scrolled_window ~border_width:10
3349    ~packing:(vbox#pack ~expand:true ~padding:5) () in
3350  let _ = scrolled_window0#add output#coerce in
3351  let frame =
3352   GBin.frame ~label:"Insert Term"
3353    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
3354  let scrolled_window1 =
3355   GBin.scrolled_window ~border_width:5
3356    ~packing:frame#add () in
3357  let inputt =
3358   new term_editor ~width:400 ~height:100 ~packing:scrolled_window1#add ()
3359    ~isnotempty_callback:
3360     (function b ->
3361       check_menu_item#misc#set_sensitive b ;
3362       searchPattern_menu_item#misc#set_sensitive b) in
3363  let vboxl =
3364   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
3365  let _ =
3366   vboxl#pack ~expand:true ~fill:true ~padding:5 notebook#notebook#coerce in
3367  let frame =
3368   GBin.frame ~shadow_type:`IN ~packing:(vboxl#pack ~expand:true ~padding:5) ()
3369  in
3370  let outputhtml =
3371   GHtml.xmhtml
3372    ~source:"<html><body bgColor=\"white\"></body></html>"
3373    ~width:400 ~height: 100
3374    ~border_width:20
3375    ~packing:frame#add
3376    ~show:true () in
3377 object
3378  method outputhtml = outputhtml
3379  method inputt = inputt
3380  method output = (output : GMathViewAux.single_selection_math_view)
3381  method notebook = notebook
3382  method show = window#show
3383  initializer
3384   notebook#set_empty_page ;
3385   export_to_postscript_menu_item#misc#set_sensitive false ;
3386   check_term := (check_term_in_scratch scratch_window) ;
3387
3388   (* signal handlers here *)
3389   ignore(output#connect#selection_changed
3390    (function elem ->
3391      choose_selection output elem ;
3392      !focus_and_proveit_set_sensitive true
3393    )) ;
3394   ignore (output#connect#click (show_in_show_window_callback output)) ;
3395   let settings_window = new settings_window output scrolled_window0
3396    export_to_postscript_menu_item (choose_selection output) in
3397   set_settings_window settings_window ;
3398   set_outputhtml outputhtml ;
3399   ignore(window#event#connect#delete (fun _ -> GMain.Main.quit () ; true )) ;
3400   Logger.log_callback :=
3401    (Logger.log_to_html ~print_and_flush:(output_html outputhtml))
3402 end;;
3403
3404 (* MAIN *)
3405
3406 let initialize_everything () =
3407  let module U = Unix in
3408   let output = GMathViewAux.single_selection_math_view ~width:350 ~height:280 () in
3409   let notebook = new notebook in
3410    let rendering_window' = new rendering_window output notebook in
3411     set_rendering_window rendering_window' ;
3412     mml_of_cic_term_ref := mml_of_cic_term ;
3413     rendering_window'#show () ;
3414     GMain.Main.main ()
3415 ;;
3416
3417 let _ =
3418  if !usedb then
3419   begin
3420    Mqint.set_database Mqint.postgres_db ;
3421    Mqint.init postgresqlconnectionstring ;
3422   end ;
3423  ignore (GtkMain.Main.init ()) ;
3424  initialize_everything () ;
3425  if !usedb then Mqint.close ();
3426 ;;