]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/gTopLevel.ml
The disambiguation now returns a list of interpretations.
[helm.git] / helm / gTopLevel / gTopLevel.ml
1 (* Copyright (C) 2000-2004, 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://helm.cs.unibo.it/
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 let debug_level = ref 1
37 let debug_print ?(level = 1) s = if !debug_level >= level then prerr_endline s
38 let error s = prerr_endline ("E: " ^ s)
39 let warning s = prerr_endline ("W: " ^ s)
40
41 open Printf
42
43 (* DEBUGGING *)
44
45 module MQI  = MQueryInterpreter
46 module MQIC = MQIConn
47 module MQGT = MQGTypes
48 module MQGU = MQGUtil
49 module MQG  = MQueryGenerator
50
51
52 (* first of all let's initialize the Helm_registry *)
53 let _ =
54  let configuration_file = "gTopLevel.conf.xml" in
55   if not (Sys.file_exists configuration_file) then begin
56     eprintf "E: Can't find configuration file '%s'\n" configuration_file;
57     exit 2
58   end;
59  Helm_registry.load_from configuration_file
60 ;;
61
62 (* GLOBAL CONSTANTS *)
63
64 let mqi_debug_fun s = debug_print ~level:2 s
65 let mqi_handle = MQIC.init ~log:mqi_debug_fun ()
66
67 let xlinkns = Gdome.domString "http://www.w3.org/1999/xlink";;
68
69 let restore_environment_on_boot = true ;;
70 let notify_hbugs_on_goal_change = false ;;
71
72 let auto_disambiguation = ref true ;;
73
74 (* GLOBAL REFERENCES (USED BY CALLBACKS) *)
75
76 let check_term = ref (fun _ _ _ -> assert false);;
77
78 exception RenderingWindowsNotInitialized;;
79
80 let set_rendering_window,rendering_window =
81  let rendering_window_ref = ref None in
82   (function rw -> rendering_window_ref := Some rw),
83   (function () ->
84     match !rendering_window_ref with
85        None -> raise RenderingWindowsNotInitialized
86      | Some rw -> rw
87   )
88 ;;
89
90 exception SettingsWindowsNotInitialized;;
91
92 let set_settings_window,settings_window =
93  let settings_window_ref = ref None in
94   (function rw -> settings_window_ref := Some rw),
95   (function () ->
96     match !settings_window_ref with
97        None -> raise SettingsWindowsNotInitialized
98      | Some rw -> rw
99   )
100 ;;
101
102 exception QedSetSensitiveNotInitialized;;
103 let qed_set_sensitive =
104  ref (function _ -> raise QedSetSensitiveNotInitialized)
105 ;;
106
107 exception SaveSetSensitiveNotInitialized;;
108 let save_set_sensitive =
109  ref (function _ -> raise SaveSetSensitiveNotInitialized)
110 ;;
111
112 (* COMMAND LINE OPTIONS *)
113
114 let usedb = ref true
115
116 let argspec =
117   [
118     "-nodb", Arg.Clear usedb, "disable use of MathQL DB"
119   ]
120 in
121 Arg.parse argspec ignore ""
122
123 (* MISC FUNCTIONS *)
124
125 let term_of_cic_textual_parser_uri uri =
126  let module C = Cic in
127  let module CTP = CicTextualParser0 in
128   match uri with
129      CTP.ConUri uri -> C.Const (uri,[])
130    | CTP.VarUri uri -> C.Var (uri,[])
131    | CTP.IndTyUri (uri,tyno) -> C.MutInd (uri,tyno,[])
132    | CTP.IndConUri (uri,tyno,consno) -> C.MutConstruct (uri,tyno,consno,[])
133 ;;
134
135 let string_of_cic_textual_parser_uri uri =
136  let module C = Cic in
137  let module CTP = CicTextualParser0 in
138   let uri' =
139    match uri with
140       CTP.ConUri uri -> UriManager.string_of_uri uri
141     | CTP.VarUri uri -> UriManager.string_of_uri uri
142     | CTP.IndTyUri (uri,tyno) ->
143        UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1)
144     | CTP.IndConUri (uri,tyno,consno) ->
145        UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1) ^ "/" ^
146         string_of_int consno
147   in
148    (* 4 = String.length "cic:" *)
149    String.sub uri' 4 (String.length uri' - 4)
150 ;;
151
152 (* UTILITY FUNCTIONS TO DISAMBIGUATE AN URI *)
153
154 (* Check window *)
155
156 let check_window uris =
157  let window =
158   GWindow.window
159    ~width:800 ~modal:true ~title:"Check" ~border_width:2 () in
160  let notebook =
161   GPack.notebook ~scrollable:true ~packing:window#add () in
162  window#show () ;
163  let render_terms =
164   List.map
165    (function uri ->
166      let scrolled_window =
167       GBin.scrolled_window ~border_width:10
168        ~packing:
169          (notebook#append_page ~tab_label:((GMisc.label ~text:uri ())#coerce))
170        ()
171      in
172       lazy 
173        (let mmlwidget =
174          TermViewer.sequent_viewer
175           ~packing:scrolled_window#add ~width:400 ~height:280 () in
176         let expr =
177          let term =
178           term_of_cic_textual_parser_uri
179            (MQueryMisc.cic_textual_parser_uri_of_string uri)
180          in
181           (Cic.Cast (term, CicTypeChecker.type_of_aux' [] [] term))
182         in
183          try
184           mmlwidget#load_sequent [] (111,[],expr)
185          with
186           e ->
187            HelmLogger.log (`Error (`T (Printexc.to_string e)))
188        )
189    ) uris
190  in
191   ignore
192    (notebook#connect#switch_page
193      (function i ->
194        Lazy.force (List.nth render_terms i)))
195 ;;
196
197 exception NoChoice;;
198
199 let
200  interactive_user_uri_choice ~(selection_mode:[`MULTIPLE|`SINGLE]) ?(ok="Ok")
201   ?(enable_button_for_non_vars=false) ~title ~msg uris
202 =
203  let only_constant_choices =
204    lazy
205      (List.filter
206       (fun uri -> not (String.sub uri (String.length uri - 4) 4 = ".var"))
207       uris)
208  in
209  if selection_mode <> `SINGLE && !auto_disambiguation then
210   Lazy.force only_constant_choices
211  else begin
212    let choices = ref [] in
213    let chosen = ref false in
214    let use_only_constants = ref false in
215    let window =
216     GWindow.dialog ~modal:true ~title ~width:600 () in
217    let lMessage =
218     GMisc.label ~text:msg
219      ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
220    let scrolled_window =
221     GBin.scrolled_window ~border_width:10
222      ~packing:(window#vbox#pack ~expand:true ~fill:true ~padding:5) () in
223    let clist =
224     let expected_height = 18 * List.length uris in
225      let height = if expected_height > 400 then 400 else expected_height in
226       GList.clist ~columns:1 ~packing:scrolled_window#add
227        ~height ~selection_mode:(selection_mode :> Gtk.Tags.selection_mode) () in
228    let _ = List.map (function x -> clist#append [x]) uris in
229    let hbox2 =
230     GPack.hbox ~border_width:0
231      ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
232    let explain_label =
233     GMisc.label ~text:"None of the above. Try this one:"
234      ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
235    let manual_input =
236     GEdit.entry ~editable:true
237      ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
238    let hbox =
239     GPack.hbox ~border_width:0 ~packing:window#action_area#add () in
240    let okb =
241     GButton.button ~label:ok
242      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
243    let _ = okb#misc#set_sensitive false in
244    let nonvarsb =
245     GButton.button
246      ~packing:
247       (function w ->
248         if enable_button_for_non_vars then
249          hbox#pack ~expand:false ~fill:false ~padding:5 w)
250      ~label:"Try constants only" () in
251    let autob =
252     GButton.button
253      ~packing:
254       (fun w ->
255         if enable_button_for_non_vars then
256          hbox#pack ~expand:false ~fill:false ~padding:5 w)
257      ~label:"Auto" () in
258    let checkb =
259     GButton.button ~label:"Check"
260      ~packing:(hbox#pack ~padding:5) () in
261    let _ = checkb#misc#set_sensitive false in
262    let cancelb =
263     GButton.button ~label:"Abort"
264      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
265    (* actions *)
266    let check_callback () =
267     assert (List.length !choices > 0) ;
268     check_window !choices
269    in
270     ignore (window#connect#destroy GMain.Main.quit) ;
271     ignore (cancelb#connect#clicked window#destroy) ;
272     ignore
273      (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
274     ignore
275      (nonvarsb#connect#clicked
276        (function () ->
277          use_only_constants := true ;
278          chosen := true ;
279          window#destroy ()
280      )) ;
281     ignore (autob#connect#clicked (fun () ->
282       auto_disambiguation := true;
283       (rendering_window ())#set_auto_disambiguation true;
284       use_only_constants := true ;
285       chosen := true;
286       window#destroy ()));
287     ignore (checkb#connect#clicked check_callback) ;
288     ignore
289      (clist#connect#select_row
290        (fun ~row ~column ~event ->
291          checkb#misc#set_sensitive true ;
292          okb#misc#set_sensitive true ;
293          choices := (List.nth uris row)::!choices)) ;
294     ignore
295      (clist#connect#unselect_row
296        (fun ~row ~column ~event ->
297          choices :=
298           List.filter (function uri -> uri != (List.nth uris row)) !choices)) ;
299     ignore
300      (manual_input#connect#changed
301        (fun _ ->
302          if manual_input#text = "" then
303           begin
304            choices := [] ;
305            checkb#misc#set_sensitive false ;
306            okb#misc#set_sensitive false ;
307            clist#misc#set_sensitive true
308           end
309          else
310           begin
311            choices := [manual_input#text] ;
312            clist#unselect_all () ;
313            checkb#misc#set_sensitive true ;
314            okb#misc#set_sensitive true ;
315            clist#misc#set_sensitive false
316           end));
317     window#set_position `CENTER ;
318     window#show () ;
319     GtkThread.main ();
320     if !chosen then
321      if !use_only_constants then
322        Lazy.force only_constant_choices
323      else
324       if List.length !choices > 0 then !choices else raise NoChoice
325     else
326      raise NoChoice
327  end
328 ;;
329
330 let interactive_interpretation_choice interpretations =
331  let chosen = ref None in
332  let window =
333   GWindow.window
334    ~modal:true ~title:"Ambiguous well-typed input." ~border_width:2 () in
335  let vbox = GPack.vbox ~packing:window#add () in
336  let lMessage =
337   GMisc.label
338    ~text:
339     ("Ambiguous input since there are many well-typed interpretations." ^
340      " Please, choose one of them.")
341    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
342  let notebook =
343   GPack.notebook ~scrollable:true
344    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
345  let _ =
346   List.map
347    (function interpretation ->
348      let clist =
349       let expected_height = 18 * List.length interpretation in
350        let height = if expected_height > 400 then 400 else expected_height in
351         GList.clist ~columns:2 ~packing:notebook#append_page ~height
352          ~titles:["id" ; "URI"] ()
353      in
354       ignore
355        (List.map
356          (function (id,uri) ->
357            let n = clist#append [id;uri] in
358             clist#set_row ~selectable:false n
359          ) interpretation
360        ) ;
361       clist#columns_autosize ()
362    ) interpretations in
363  let hbox =
364   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
365  let okb =
366   GButton.button ~label:"Ok"
367    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
368  let cancelb =
369   GButton.button ~label:"Abort"
370    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
371  (* actions *)
372  ignore (window#connect#destroy GMain.Main.quit) ;
373  ignore (cancelb#connect#clicked window#destroy) ;
374  ignore
375   (okb#connect#clicked
376     (function () -> chosen := Some notebook#current_page ; window#destroy ())) ;
377  window#set_position `CENTER ;
378  window#show () ;
379  GtkThread.main ();
380  match !chosen with
381     None -> raise NoChoice
382   | Some n -> [n]
383 ;;
384
385
386 (* MISC FUNCTIONS *)
387
388 let
389  save_object_to_disk uri annobj ids_to_inner_sorts ids_to_inner_types pathname
390 =
391  let name =
392   let struri = UriManager.string_of_uri uri in
393   let idx = (String.rindex struri '/') + 1 in
394    String.sub struri idx (String.length struri - idx)
395  in
396   let path = pathname ^ "/" ^ name in
397   let xml, bodyxml =
398    Cic2Xml.print_object uri ~ids_to_inner_sorts ~ask_dtd_to_the_getter:false
399     annobj 
400   in
401   let xmlinnertypes =
402    Cic2Xml.print_inner_types uri ~ids_to_inner_sorts ~ids_to_inner_types
403     ~ask_dtd_to_the_getter:false
404   in
405    (* innertypes *)
406    let innertypesuri = UriManager.innertypesuri_of_uri uri in
407     Xml.pp ~quiet:true xmlinnertypes (Some (path ^ ".types.xml")) ;
408     Http_getter.register' innertypesuri
409      (Helm_registry.get "local_library.url" ^
410        Str.replace_first (Str.regexp "^cic:") ""
411         (UriManager.string_of_uri innertypesuri) ^ ".xml"
412      ) ;
413     (* constant type / variable / mutual inductive types definition *)
414     Xml.pp ~quiet:true xml (Some (path ^ ".xml")) ;
415     Http_getter.register' uri
416      (Helm_registry.get "local_library.url" ^
417        Str.replace_first (Str.regexp "^cic:") ""
418         (UriManager.string_of_uri uri) ^ ".xml"
419      ) ;
420     match bodyxml with
421        None -> ()
422      | Some bodyxml' ->
423         (* constant body *)
424         let bodyuri =
425          match UriManager.bodyuri_of_uri uri with
426             None -> assert false
427           | Some bodyuri -> bodyuri
428         in
429          Xml.pp ~quiet:true bodyxml' (Some (path ^ ".body.xml")) ;
430          Http_getter.register' bodyuri
431           (Helm_registry.get "local_library.url" ^
432             Str.replace_first (Str.regexp "^cic:") ""
433              (UriManager.string_of_uri bodyuri) ^ ".xml"
434           )
435 ;;
436
437
438 (* CALLBACKS *)
439
440 exception OpenConjecturesStillThere;;
441 exception WrongProof;;
442
443 let pathname_of_annuri uristring =
444  Helm_registry.get "local_library.dir" ^    
445   Str.replace_first (Str.regexp "^cic:") "" uristring
446 ;;
447
448 let make_dirs dirpath =
449  ignore (Unix.system ("mkdir -p " ^ dirpath))
450 ;;
451
452 let save_obj uri obj =
453  let
454   (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
455    ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
456  =
457   Cic2acic.acic_object_of_cic_object ~eta_fix:false obj
458  in
459   (* let's save the theorem and register it to the getter *) 
460   let pathname = pathname_of_annuri (UriManager.buri_of_uri uri) in
461    make_dirs pathname ;
462    save_object_to_disk uri acic ids_to_inner_sorts ids_to_inner_types
463     pathname
464 ;;
465
466 let qed () =
467  match ProofEngine.get_proof () with
468     None -> assert false
469   | Some (uri,[],bo,ty) ->
470      if
471       CicReduction.are_convertible []
472        (CicTypeChecker.type_of_aux' [] [] bo) ty
473      then
474       begin
475        (*CSC: Wrong: [] is just plainly wrong *)
476        let proof = Cic.Constant (UriManager.name_of_uri uri,Some bo,ty,[]) in
477        let (acic,ids_to_inner_types,ids_to_inner_sorts) =
478         (rendering_window ())#output#load_proof uri proof
479        in
480         !qed_set_sensitive false ;
481         (* let's save the theorem and register it to the getter *) 
482         let pathname = pathname_of_annuri (UriManager.buri_of_uri uri) in
483          make_dirs pathname ;
484          save_object_to_disk uri acic ids_to_inner_sorts ids_to_inner_types
485           pathname
486       end
487      else
488       raise WrongProof
489   | _ -> raise OpenConjecturesStillThere
490 ;;
491
492   (** save an unfinished proof on the filesystem *)
493 let save_unfinished_proof () =
494  let (xml, bodyxml) = ProofEngine.get_current_status_as_xml () in
495  let proof_file_type = Helm_registry.get "gtoplevel.proof_file_type" in
496  let proof_file = Helm_registry.get "gtoplevel.proof_file" in
497  Xml.pp ~quiet:true xml (Some proof_file_type) ;
498  HelmLogger.log
499   (`Msg (`T ("Current proof type saved to " ^ proof_file_type))) ;
500  Xml.pp ~quiet:true bodyxml (Some proof_file) ;
501  HelmLogger.log
502   (`Msg (`T ("Current proof body saved to " ^ proof_file)))
503 ;;
504
505 (* Used to typecheck the loaded proofs *)
506 let typecheck_loaded_proof metasenv bo ty =
507  let module T = CicTypeChecker in
508   ignore (
509    List.fold_left
510     (fun metasenv ((_,context,ty) as conj) ->
511       ignore (T.type_of_aux' metasenv context ty) ;
512       metasenv @ [conj]
513     ) [] metasenv) ;
514   ignore (T.type_of_aux' metasenv [] ty) ;
515   ignore (T.type_of_aux' metasenv [] bo)
516 ;;
517
518 let decompose_uris_choice_callback uris = 
519 (* N.B.: in questo passaggio perdo l'informazione su exp_named_subst !!!! *)
520   let module U = UriManager in 
521    List.map 
522     (function uri ->
523       match MQueryMisc.cic_textual_parser_uri_of_string uri with
524          CicTextualParser0.IndTyUri (uri,typeno) -> (uri,typeno,[])
525        | _ -> assert false)
526     (interactive_user_uri_choice 
527       ~selection_mode:`MULTIPLE ~ok:"Ok" ~enable_button_for_non_vars:false 
528       ~title:"Decompose" ~msg:"Please, select the Inductive Types to decompose" 
529       (List.map 
530         (function (uri,typeno,_) ->
531           U.string_of_uri uri ^ "#1/" ^ string_of_int (typeno+1)
532         ) uris)
533     ) 
534 ;;
535
536 let mk_fresh_name_callback metasenv context name ~typ =
537  let fresh_name =
538   match FreshNamesGenerator.mk_fresh_name metasenv context name ~typ with
539      Cic.Name fresh_name -> fresh_name
540    | Cic.Anonymous -> assert false
541  in
542   match
543    GToolbox.input_string ~title:"Enter a fresh hypothesis name" ~text:fresh_name
544     ("Enter a fresh name for the hypothesis " ^
545       CicPp.pp typ
546        (List.map (function None -> None | Some (n,_) -> Some n) context))
547   with
548      Some fresh_name' -> Cic.Name fresh_name'
549    | None -> raise NoChoice
550 ;;
551
552 let refresh_proof (output : TermViewer.proof_viewer) =
553  try
554   let uri,currentproof =
555    match ProofEngine.get_proof () with
556       None -> assert false
557     | Some (uri,metasenv,bo,ty) ->
558        ProofEngine.set_proof (Some (uri,metasenv,bo,ty)) ;
559        if List.length metasenv = 0 then
560         begin
561          !qed_set_sensitive true ;
562          Hbugs.clear ()
563         end
564        else
565         Hbugs.notify () ;
566        (*CSC: Wrong: [] is just plainly wrong *)
567        uri,
568         (Cic.CurrentProof (UriManager.name_of_uri uri, metasenv, bo, ty, []))
569   in
570    ignore (output#load_proof uri currentproof)
571  with
572   e ->
573  match ProofEngine.get_proof () with
574     None -> assert false
575   | Some (uri,metasenv,bo,ty) ->
576       debug_print ("Offending proof: " ^ CicPp.ppobj (Cic.CurrentProof ("questa",metasenv,bo,ty,[])));
577       raise (InvokeTactics.RefreshProofException e)
578
579 let set_proof_engine_goal g =
580  ProofEngine.goal := g
581 ;;
582
583 let refresh_goals ?(empty_notebook=true) notebook =
584  try
585   match !ProofEngine.goal with
586      None ->
587       if empty_notebook then
588        begin 
589         notebook#remove_all_pages ~skip_switch_page_event:false ;
590         notebook#set_empty_page
591        end
592       else
593        notebook#proofw#unload
594    | Some metano ->
595       let metasenv =
596        match ProofEngine.get_proof () with
597           None -> assert false
598         | Some (_,metasenv,_,_) -> metasenv
599       in
600       let currentsequent =
601        List.find (function (m,_,_) -> m=metano) metasenv
602       in
603         let regenerate_notebook () = 
604          let skip_switch_page_event =
605           match metasenv with
606              (m,_,_)::_ when m = metano -> false
607            | _ -> true
608          in
609           notebook#remove_all_pages ~skip_switch_page_event ;
610           List.iter (function (m,_,_) -> notebook#add_page m) metasenv ;
611         in
612          if empty_notebook then
613           begin
614            regenerate_notebook () ;
615            notebook#set_current_page
616             ~may_skip_switch_page_event:false metano
617           end
618          else
619           begin
620            notebook#set_current_page
621             ~may_skip_switch_page_event:true metano ;
622            notebook#proofw#load_sequent metasenv currentsequent
623           end
624  with
625   e ->
626 let metano =
627   match !ProofEngine.goal with
628      None -> assert false
629    | Some m -> m
630 in
631 let metasenv =
632  match ProofEngine.get_proof () with
633     None -> assert false
634   | Some (_,metasenv,_,_) -> metasenv
635 in
636 try
637   let currentsequent = List.find (function (m,_,_) -> m=metano) metasenv in
638   debug_print
639     ("Offending sequent: " ^ SequentPp.TextualPp.print_sequent currentsequent);
640   raise (InvokeTactics.RefreshSequentException e)
641 with Not_found ->
642   debug_print ("Offending sequent " ^ string_of_int metano ^ " unknown.");
643   raise (InvokeTactics.RefreshSequentException e)
644
645 module InvokeTacticsCallbacks =
646  struct
647   let sequent_viewer () = (rendering_window ())#notebook#proofw
648   let term_editor () = (rendering_window ())#inputt
649   let scratch_window () = (rendering_window ())#scratch_window
650
651   let refresh_proof () =
652    let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
653     refresh_proof output
654
655   let refresh_goals () =
656    let notebook = (rendering_window ())#notebook in
657     refresh_goals notebook
658
659   let decompose_uris_choice_callback = decompose_uris_choice_callback
660   let mk_fresh_name_callback = mk_fresh_name_callback
661  end
662 ;;
663 module InvokeTactics' = InvokeTactics.Make (InvokeTacticsCallbacks);;
664 (*
665 (* Just to initialize the Hbugs module *)
666 module Ignore = Hbugs.Initialize (InvokeTactics');;
667 Hbugs.set_describe_hint_callback (fun hint ->
668   match hint with
669   | Hbugs_types.Use_apply_Luke term -> check_window [term]
670   | _ -> ())
671 ;;
672 *)
673 let dummy_uri = "/dummy.con"
674
675   (** load an unfinished proof from filesystem *)
676 let load_unfinished_proof () =
677  let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
678  let notebook = (rendering_window ())#notebook in
679   try
680    match 
681     GToolbox.input_string ~title:"Load Unfinished Proof" ~text:dummy_uri
682      "Choose an URI:"
683    with
684       None -> raise NoChoice
685     | Some uri0 ->
686        let uri = UriManager.uri_of_string ("cic:" ^ uri0) in
687        let proof_file_type = Helm_registry.get "gtoplevel.proof_file_type" in
688        let proof_file = Helm_registry.get "gtoplevel.proof_file" in
689         match CicParser.obj_of_xml proof_file_type (Some proof_file) with
690            Cic.CurrentProof (_,metasenv,bo,ty,_) ->
691             typecheck_loaded_proof metasenv bo ty ;
692             ProofEngine.set_proof (Some (uri, metasenv, bo, ty)) ;
693             refresh_proof output ;
694             set_proof_engine_goal
695              (match metasenv with
696                  [] -> None
697                | (metano,_,_)::_ -> Some metano
698              ) ;
699             refresh_goals notebook ;
700              HelmLogger.log
701               (`Msg (`T ("Current proof type loaded from " ^ proof_file_type)));
702              HelmLogger.log
703               (`Msg (`T ("Current proof body loaded from " ^ proof_file))) ;
704             !save_set_sensitive true;
705          | _ -> assert false
706   with
707      InvokeTactics.RefreshSequentException e ->
708       HelmLogger.log
709        (`Error (`T ("Exception raised during the refresh of the " ^
710         "sequent: " ^ Printexc.to_string e)))
711    | InvokeTactics.RefreshProofException e ->
712       HelmLogger.log
713        (`Error (`T ("Exception raised during the refresh of the " ^
714         "proof: " ^ Printexc.to_string e)))
715    | e ->
716       HelmLogger.log
717        (`Error (`T (Printexc.to_string e)))
718 ;;
719
720 let clear_aliases () =
721   let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
722   inputt#environment :=
723     DisambiguatingParser.EnvironmentP3.of_string
724       DisambiguatingParser.EnvironmentP3.empty
725 ;;
726
727 let edit_aliases () =
728  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
729  let disambiguation_env = inputt#environment in
730  let chosen_aliases = ref None in
731  let window =
732   GWindow.window
733    ~width:400 ~modal:true ~title:"Edit Aliases..." ~border_width:2 () in
734  let vbox =
735   GPack.vbox ~border_width:0 ~packing:window#add () in
736  let scrolled_window =
737   GBin.scrolled_window ~border_width:10
738    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
739  let input = GText.view ~editable:true ~width:400 ~height:100
740    ~packing:scrolled_window#add () in
741  let hbox =
742   GPack.hbox ~border_width:0
743    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
744  let okb =
745   GButton.button ~label:"Ok"
746    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
747  let clearb =
748   GButton.button ~label:"Clear"
749    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
750  let cancelb =
751   GButton.button ~label:"Cancel"
752    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
753  ignore (window#connect#destroy GMain.Main.quit) ;
754  ignore (cancelb#connect#clicked window#destroy) ;
755  ignore (clearb#connect#clicked (fun () ->
756   input#buffer#set_text DisambiguatingParser.EnvironmentP3.empty)) ;
757  ignore (okb#connect#clicked (fun () ->
758     chosen_aliases := Some (input#buffer#get_text ());
759     window#destroy ()));
760   ignore
761    (input#buffer#insert ~iter:(input#buffer#get_iter_at_char 0)
762      (DisambiguatingParser.EnvironmentP3.to_string !disambiguation_env ^ "\n"));
763   window#show () ;
764   GtkThread.main ();
765   match !chosen_aliases with
766   | None -> ()
767   | Some raw_aliases ->
768       let new_disambiguation_env =
769         (try
770           DisambiguatingParser.EnvironmentP3.of_string raw_aliases
771         with e ->
772           HelmLogger.log
773             (`Error (`T
774               ("Error while parsing aliases: " ^ Printexc.to_string e)));
775           !disambiguation_env)
776       in
777       disambiguation_env := new_disambiguation_env
778 ;;
779
780 let proveit () =
781  let module L = LogicalOperations in
782  let module G = Gdome in
783  let notebook = (rendering_window ())#notebook in
784  let output = (rendering_window ())#output in
785   try
786    output#make_sequent_of_selected_term ;
787    refresh_proof output ;
788    refresh_goals notebook
789   with
790      InvokeTactics.RefreshSequentException e ->
791       HelmLogger.log
792        (`Error (`T ("Exception raised during the refresh of the " ^
793         "sequent: " ^ Printexc.to_string e)))
794    | InvokeTactics.RefreshProofException e ->
795       HelmLogger.log
796        (`Error (`T ("Exception raised during the refresh of the " ^
797         "proof: " ^ Printexc.to_string e)))
798    | e ->
799       HelmLogger.log
800        (`Error (`T (Printexc.to_string e)))
801 ;;
802
803 let focus () =
804  let module L = LogicalOperations in
805  let module G = Gdome in
806  let notebook = (rendering_window ())#notebook in
807  let output = (rendering_window ())#output in
808   try
809    output#focus_sequent_of_selected_term ;
810    refresh_goals notebook
811   with
812      InvokeTactics.RefreshSequentException e ->
813       HelmLogger.log
814        (`Error (`T ("Exception raised during the refresh of the " ^
815         "sequent: " ^ Printexc.to_string e)))
816    | InvokeTactics.RefreshProofException e ->
817       HelmLogger.log
818        (`Error (`T ("Exception raised during the refresh of the " ^
819         "proof: " ^ Printexc.to_string e)))
820    | e ->
821       HelmLogger.log
822        (`Error (`T (Printexc.to_string e)))
823 ;;
824
825 exception NoPrevGoal;;
826 exception NoNextGoal;;
827
828 let setgoal metano =
829  let module L = LogicalOperations in
830  let module G = Gdome in
831  let notebook = (rendering_window ())#notebook in
832  let output = (rendering_window ())#output in
833   let metasenv =
834    match ProofEngine.get_proof () with
835       None -> assert false
836     | Some (_,metasenv,_,_) -> metasenv
837   in
838    try
839     refresh_goals ~empty_notebook:false notebook
840    with
841       InvokeTactics.RefreshSequentException e ->
842        HelmLogger.log
843         (`Error (`T ("Exception raised during the refresh of the " ^
844          "sequent: " ^ Printexc.to_string e)))
845     | e ->
846        HelmLogger.log
847         (`Error (`T (Printexc.to_string e)))
848 ;;
849
850 let
851  show_in_show_window_obj, show_in_show_window_uri, show_in_show_window_callback
852 =
853  let window =
854   GWindow.window ~width:800 ~border_width:2 () in
855  let scrolled_window =
856   GBin.scrolled_window ~border_width:10 ~packing:window#add () in
857  let mmlwidget =
858   GMathViewAux.single_selection_math_view
859     ~packing:scrolled_window#add ~width:600 ~height:400 ()
860  in
861  let _ = window#event#connect#delete (fun _ -> window#misc#hide () ; true ) in
862  let href = Gdome.domString "href" in
863   let show_in_show_window_obj uri obj =
864     try
865      let
866       (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
867        ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
868      =
869       Cic2acic.acic_object_of_cic_object obj
870      in
871       let mml =
872        ChosenTransformer.mml_of_cic_object
873         ~explode_all:false uri acic ids_to_inner_sorts ids_to_inner_types
874       in
875        window#set_title (UriManager.string_of_uri uri) ;
876        window#misc#hide () ; window#show () ;
877        mmlwidget#load_doc mml ;
878     with
879      e ->
880       HelmLogger.log
881        (`Error (`T (Printexc.to_string e)))
882   in
883   let show_in_show_window_uri uri =
884    let obj = CicEnvironment.get_obj uri in
885     show_in_show_window_obj uri obj
886   in
887    let show_in_show_window_callback mmlwidget (n : Gdome.element option) _ =
888     match n with
889        None -> ()
890      | Some n' ->
891         if n'#hasAttributeNS ~namespaceURI:xlinkns ~localName:href then
892          let uri =
893           (n'#getAttributeNS ~namespaceURI:xlinkns ~localName:href)#to_string
894          in 
895           show_in_show_window_uri (UriManager.uri_of_string uri)
896         else
897          ignore (mmlwidget#action_toggle n')
898    in
899     let _ =
900      mmlwidget#connect#click (show_in_show_window_callback mmlwidget)
901     in
902      show_in_show_window_obj, show_in_show_window_uri,
903       show_in_show_window_callback
904 ;;
905
906 exception NoObjectsLocated;;
907
908 let user_uri_choice ~title ~msg uris =
909  let uri =
910   match uris with
911      [] -> raise NoObjectsLocated
912    | [uri] -> uri
913    | uris ->
914       match
915        interactive_user_uri_choice ~selection_mode:`SINGLE ~title ~msg uris
916       with
917          [uri] -> uri
918        | _ -> assert false
919  in
920   String.sub uri 4 (String.length uri - 4)
921 ;;
922
923 let locate_callback id =
924  let query = MQG.locate id in
925  let result = MQI.execute mqi_handle query in
926  let uris =
927   List.map
928    (function uri,_ ->
929      MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri)
930    result in
931   HelmLogger.log (`Msg (`T "Locate Query:")) ;
932   MQueryUtil.text_of_query (fun m -> HelmLogger.log (`Msg (`T m))) "" query; 
933   HelmLogger.log (`Msg (`T "Result:")) ;
934   MQueryUtil.text_of_result (fun m -> HelmLogger.log (`Msg (`T m))) "" result;
935   user_uri_choice ~title:"Ambiguous input."
936    ~msg:
937      ("Ambiguous input \"" ^ id ^
938       "\". Please, choose one interpetation:")
939    uris
940 ;;
941
942
943 let input_or_locate_uri ~title =
944  let uri = ref None in
945  let window =
946   GWindow.window
947    ~width:400 ~modal:true ~title ~border_width:2 () in
948  let vbox = GPack.vbox ~packing:window#add () in
949  let hbox1 =
950   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
951  let _ =
952   GMisc.label ~text:"Enter a valid URI:" ~packing:(hbox1#pack ~padding:5) () in
953  let manual_input =
954   GEdit.entry ~editable:true
955    ~packing:(hbox1#pack ~expand:true ~fill:true ~padding:5) () in
956  let checkb =
957   GButton.button ~label:"Check"
958    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
959  let _ = checkb#misc#set_sensitive false in
960  let hbox2 =
961   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
962  let _ =
963   GMisc.label ~text:"You can also enter an indentifier to locate:"
964    ~packing:(hbox2#pack ~padding:5) () in
965  let locate_input =
966   GEdit.entry ~editable:true
967    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
968  let locateb =
969   GButton.button ~label:"Locate"
970    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
971  let _ = locateb#misc#set_sensitive false in
972  let hbox3 =
973   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
974  let okb =
975   GButton.button ~label:"Ok"
976    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
977  let _ = okb#misc#set_sensitive false in
978  let cancelb =
979   GButton.button ~label:"Cancel"
980    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) ()
981  in
982   ignore (window#connect#destroy GMain.Main.quit) ;
983   ignore
984    (cancelb#connect#clicked (function () -> uri := None ; window#destroy ())) ;
985   let check_callback () =
986    let uri = "cic:" ^ manual_input#text in
987     try
988       ignore (Http_getter.resolve' (UriManager.uri_of_string uri)) ;
989       HelmLogger.log (`Msg (`T "OK")) ;
990       true
991     with
992        Http_getter_types.Unresolvable_URI _ ->
993         HelmLogger.log
994          (`Error (`T ("URI " ^ uri ^
995           " does not correspond to any object."))) ;
996         false
997      | UriManager.IllFormedUri _ ->
998         HelmLogger.log
999          (`Error (`T ("URI " ^ uri ^ " is not well-formed."))) ;
1000         false
1001      | e ->
1002         HelmLogger.log
1003          (`Error (`T (Printexc.to_string e))) ;
1004         false
1005   in
1006   ignore
1007    (okb#connect#clicked
1008      (function () ->
1009        if check_callback () then
1010         begin
1011          uri := Some manual_input#text ;
1012          window#destroy ()
1013         end
1014    )) ;
1015   ignore (checkb#connect#clicked (function () -> ignore (check_callback ()))) ;
1016   ignore
1017    (manual_input#connect#changed
1018      (fun _ ->
1019        if manual_input#text = "" then
1020         begin
1021          checkb#misc#set_sensitive false ;
1022          okb#misc#set_sensitive false
1023         end
1024        else
1025         begin
1026          checkb#misc#set_sensitive true ;
1027          okb#misc#set_sensitive true
1028         end));
1029   ignore
1030    (locate_input#connect#changed
1031      (fun _ -> locateb#misc#set_sensitive (locate_input#text <> ""))) ;
1032   ignore
1033    (locateb#connect#clicked
1034      (function () ->
1035        let id = locate_input#text in
1036         manual_input#set_text (locate_callback id) ;
1037         locate_input#delete_text 0 (String.length id)
1038    )) ;
1039   window#show () ;
1040   GtkThread.main ();
1041   match !uri with
1042      None -> raise NoChoice
1043    | Some uri -> UriManager.uri_of_string ("cic:" ^ uri)
1044 ;;
1045
1046 exception AmbiguousInput;;
1047
1048 (* A WIDGET TO ENTER CIC TERMS *)
1049
1050 module DisambiguateCallbacks =
1051  struct
1052   let interactive_user_uri_choice =
1053    fun ~selection_mode ?ok ?enable_button_for_non_vars ~title ~msg ~id ->
1054     interactive_user_uri_choice ~selection_mode ?ok
1055      ?enable_button_for_non_vars ~title ~msg
1056   let interactive_interpretation_choice = interactive_interpretation_choice
1057   let input_or_locate_uri = input_or_locate_uri
1058  end
1059 ;;
1060
1061 module TermEditor' = ChosenTermEditor.Make (DisambiguateCallbacks);;
1062
1063 (* OTHER FUNCTIONS *)
1064
1065 let locate () =
1066  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1067    try
1068     match
1069      GToolbox.input_string ~title:"Locate" "Enter an identifier to locate:"
1070     with
1071        None -> raise NoChoice
1072      | Some input ->
1073         let uri = locate_callback input in
1074          inputt#set_term uri
1075    with
1076     e ->
1077      HelmLogger.log
1078       (`Error (`T (Printexc.to_string e)))
1079 ;;
1080
1081
1082 exception UriAlreadyInUse;;
1083 exception NotAUriToAConstant;;
1084
1085 let new_inductive () =
1086  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1087  let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
1088  let notebook = (rendering_window ())#notebook in
1089
1090  let chosen = ref false in
1091  let inductive = ref true in
1092  let paramsno = ref 0 in
1093  let get_uri = ref (function _ -> assert false) in
1094  let get_base_uri = ref (function _ -> assert false) in
1095  let get_names = ref (function _ -> assert false) in
1096  let get_types_and_cons = ref (function _ -> assert false) in
1097  let get_context_and_subst = ref (function _ -> assert false) in 
1098  let window =
1099   GWindow.window
1100    ~width:600 ~modal:true ~position:`CENTER
1101    ~title:"New Block of Mutual (Co)Inductive Definitions"
1102    ~border_width:2 () in
1103  let vbox = GPack.vbox ~packing:window#add () in
1104  let hbox =
1105   GPack.hbox ~border_width:0
1106    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1107  let _ =
1108   GMisc.label ~text:"Enter the URI for the new block:"
1109    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1110  let uri_entry =
1111   GEdit.entry ~editable:true
1112    ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1113  let hbox0 =
1114   GPack.hbox ~border_width:0
1115    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1116  let _ =
1117   GMisc.label
1118    ~text:
1119      "Enter the number of left parameters in every arity and constructor type:"
1120    ~packing:(hbox0#pack ~expand:false ~fill:false ~padding:5) () in
1121  let paramsno_entry =
1122   GEdit.entry ~editable:true ~text:"0"
1123    ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
1124  let hbox1 =
1125   GPack.hbox ~border_width:0
1126    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1127  let _ =
1128   GMisc.label ~text:"Are the definitions inductive or coinductive?"
1129    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1130  let inductiveb =
1131   GButton.radio_button ~label:"Inductive"
1132    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1133  let coinductiveb =
1134   GButton.radio_button ~label:"Coinductive"
1135    ~group:inductiveb#group
1136    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1137  let hbox2 =
1138   GPack.hbox ~border_width:0
1139    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1140  let _ =
1141   GMisc.label ~text:"Enter the list of the names of the types:"
1142    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
1143  let names_entry =
1144   GEdit.entry ~editable:true
1145    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
1146  let hboxn =
1147   GPack.hbox ~border_width:0
1148    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1149  let okb =
1150   GButton.button ~label:"> Next"
1151    ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1152  let _ = okb#misc#set_sensitive true in
1153  let cancelb =
1154   GButton.button ~label:"Abort"
1155    ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1156  ignore (window#connect#destroy GMain.Main.quit) ;
1157  ignore (cancelb#connect#clicked window#destroy) ;
1158  (* First phase *)
1159  let rec phase1 () =
1160   ignore
1161    (okb#connect#clicked
1162      (function () ->
1163        try
1164         let uristr = "cic:" ^ uri_entry#text in
1165         let namesstr = names_entry#text in
1166         let paramsno' = int_of_string (paramsno_entry#text) in
1167          match Str.split (Str.regexp " +") namesstr with
1168             [] -> assert false
1169           | (he::tl) as names ->
1170              let uri = UriManager.uri_of_string (uristr ^ "/" ^ he ^ ".ind") in
1171               begin
1172                try
1173                 ignore (Http_getter.resolve' uri) ;
1174                 raise UriAlreadyInUse
1175                with Http_getter_types.Unresolvable_URI _ ->
1176                  get_uri := (function () -> uri) ; 
1177                  get_names := (function () -> names) ;
1178                  inductive := inductiveb#active ;
1179                  paramsno := paramsno' ;
1180                  phase2 ()
1181               end
1182        with
1183         e ->
1184          HelmLogger.log
1185           (`Error (`T (Printexc.to_string e)))
1186      ))
1187  (* Second phase *)
1188  and phase2 () =
1189   let type_widgets =
1190    List.map
1191     (function name ->
1192       let frame =
1193        GBin.frame ~label:name
1194         ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1195       let vbox = GPack.vbox ~packing:frame#add () in
1196       let hbox = GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false) () in
1197       let _ =
1198        GMisc.label ~text:("Enter its type:")
1199         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1200       let scrolled_window =
1201        GBin.scrolled_window ~border_width:5
1202         ~packing:(vbox#pack ~expand:true ~padding:0) () in
1203       let newinputt =
1204        TermEditor'.term_editor
1205         mqi_handle
1206         ~width:400 ~height:20 ~packing:scrolled_window#add 
1207         ~share_environment_with:inputt ()
1208         ~isnotempty_callback:
1209          (function b ->
1210            (*non_empty_type := b ;*)
1211            okb#misc#set_sensitive true) (*(b && uri_entry#text <> ""))*)
1212       in
1213       let hbox =
1214        GPack.hbox ~border_width:0
1215         ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1216       let _ =
1217        GMisc.label ~text:("Enter the list of its constructors:")
1218         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1219       let cons_names_entry =
1220        GEdit.entry ~editable:true
1221         ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1222       (newinputt,cons_names_entry)
1223     ) (!get_names ())
1224   in
1225    vbox#remove hboxn#coerce ;
1226    let hboxn =
1227     GPack.hbox ~border_width:0
1228      ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1229    let okb =
1230     GButton.button ~label:"> Next"
1231      ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1232    let cancelb =
1233     GButton.button ~label:"Abort"
1234      ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1235    ignore (cancelb#connect#clicked window#destroy) ;
1236    ignore
1237     (okb#connect#clicked
1238       (function () ->
1239         try
1240          let names = !get_names () in
1241          let types_and_cons =
1242           List.map2
1243            (fun name (newinputt,cons_names_entry) ->
1244              let consnamesstr = cons_names_entry#text in
1245              let cons_names = Str.split (Str.regexp " +") consnamesstr in
1246              let metasenv,expr =
1247               newinputt#get_metasenv_and_term ~context:[] ~metasenv:[]
1248              in
1249               match metasenv with
1250                  [] -> expr,cons_names
1251                | _ -> raise AmbiguousInput
1252            ) names type_widgets
1253          in
1254           let uri = !get_uri () in
1255           let _ =
1256            (* Let's see if so far the definition is well-typed *)
1257            let params = [] in
1258            let paramsno = 0 in
1259            (* To test if the arities of the inductive types are well *)
1260            (* typed, we check the inductive block definition where   *)
1261            (* no constructor is given to each type.                  *)
1262            let tys =
1263             List.map2
1264              (fun name (ty,cons) -> (name, !inductive, ty, []))
1265              names types_and_cons
1266            in
1267             CicTypeChecker.typecheck_mutual_inductive_defs uri
1268              (tys,params,paramsno)
1269           in
1270            get_context_and_subst :=
1271             (function () ->
1272               let i = ref 0 in
1273                List.fold_left2
1274                 (fun (context,subst) name (ty,_) ->
1275                   let res =
1276                    (Some (Cic.Name name, Cic.Decl ty))::context,
1277                     (Cic.MutInd (uri,!i,[]))::subst
1278                   in
1279                    incr i ; res
1280                 ) ([],[]) names types_and_cons) ;
1281            let types_and_cons' =
1282             List.map2
1283              (fun name (ty,cons) -> (name, !inductive, ty, phase3 name cons))
1284              names types_and_cons
1285            in
1286             get_types_and_cons := (function () -> types_and_cons') ;
1287             chosen := true ;
1288             window#destroy ()
1289         with
1290          e ->
1291           HelmLogger.log
1292            (`Error (`T (Printexc.to_string e)))
1293       ))
1294  (* Third phase *)
1295  and phase3 name cons =
1296   let get_cons_types = ref (function () -> assert false) in
1297   let window2 =
1298    GWindow.window
1299     ~width:600 ~modal:true ~position:`CENTER
1300     ~title:(name ^ " Constructors")
1301     ~border_width:2 () in
1302   let vbox = GPack.vbox ~packing:window2#add () in
1303   let cons_type_widgets =
1304    List.map
1305     (function consname ->
1306       let hbox =
1307        GPack.hbox ~border_width:0
1308         ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1309       let _ =
1310        GMisc.label ~text:("Enter the type of " ^ consname ^ ":")
1311         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1312       let scrolled_window =
1313        GBin.scrolled_window ~border_width:5
1314         ~packing:(vbox#pack ~expand:true ~padding:0) () in
1315       let newinputt =
1316        TermEditor'.term_editor
1317         mqi_handle
1318         ~width:400 ~height:20 ~packing:scrolled_window#add
1319         ~share_environment_with:inputt ()
1320         ~isnotempty_callback:
1321          (function b ->
1322            (* (*non_empty_type := b ;*)
1323            okb#misc#set_sensitive true) (*(b && uri_entry#text <> ""))*) *)())
1324       in
1325        newinputt
1326     ) cons in
1327   let hboxn =
1328    GPack.hbox ~border_width:0
1329     ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1330   let okb =
1331    GButton.button ~label:"> Next"
1332     ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1333   let _ = okb#misc#set_sensitive true in
1334   let cancelb =
1335    GButton.button ~label:"Abort"
1336     ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1337   ignore (window2#connect#destroy GMain.Main.quit) ;
1338   ignore (cancelb#connect#clicked window2#destroy) ;
1339   ignore
1340    (okb#connect#clicked
1341      (function () ->
1342        try
1343         chosen := true ;
1344         let context,subst= !get_context_and_subst () in
1345         let cons_types =
1346          List.map2
1347           (fun name inputt ->
1348             let metasenv,expr =
1349              inputt#get_metasenv_and_term ~context ~metasenv:[]
1350             in
1351              match metasenv with
1352                 [] ->
1353                  let undebrujined_expr =
1354                   List.fold_left
1355                    (fun expr t -> CicSubstitution.subst t expr) expr subst
1356                  in
1357                   name, undebrujined_expr
1358               | _ -> raise AmbiguousInput
1359           ) cons cons_type_widgets
1360         in
1361          get_cons_types := (function () -> cons_types) ;
1362          window2#destroy ()
1363        with
1364         e ->
1365          HelmLogger.log
1366           (`Error (`T (Printexc.to_string e)))
1367      )) ;
1368   window2#show () ;
1369   GtkThread.main ();
1370   let okb_pressed = !chosen in
1371    chosen := false ;
1372    if (not okb_pressed) then
1373     begin
1374      window#destroy () ;
1375      assert false (* The control never reaches this point *)
1376     end
1377    else
1378     (!get_cons_types ())
1379  in
1380   phase1 () ;
1381   (* No more phases left or Abort pressed *) 
1382   window#show () ;
1383   GtkThread.main ();
1384   window#destroy () ;
1385   if !chosen then
1386    try
1387     let uri = !get_uri () in
1388 (*CSC: Da finire *)
1389     let params = [] in
1390     let tys = !get_types_and_cons () in
1391      let obj = Cic.InductiveDefinition(tys,params,!paramsno) in
1392       begin
1393        try
1394         debug_print (CicPp.ppobj obj);
1395         CicTypeChecker.typecheck_mutual_inductive_defs uri
1396          (tys,params,!paramsno) ;
1397         with
1398          e ->
1399           debug_print "Offending mutual (co)inductive type declaration:" ;
1400           debug_print (CicPp.ppobj obj) ;
1401       end ;
1402       (* We already know that obj is well-typed. We need to add it to the  *)
1403       (* environment in order to compute the inner-types without having to *)
1404       (* debrujin it or having to modify lots of other functions to avoid  *)
1405       (* asking the environment for the MUTINDs we are defining now.       *)
1406       CicEnvironment.put_inductive_definition uri obj ;
1407       save_obj uri obj ;
1408       show_in_show_window_obj uri obj
1409    with
1410     e ->
1411      HelmLogger.log
1412       (`Error (`T (Printexc.to_string e)))
1413 ;;
1414
1415 let new_proof () =
1416  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1417  let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
1418  let notebook = (rendering_window ())#notebook in
1419
1420  let chosen = ref false in
1421  let get_metasenv_and_term = ref (function _ -> assert false) in
1422  let get_uri = ref (function _ -> assert false) in
1423  let non_empty_type = ref false in
1424  let window =
1425   GWindow.window
1426    ~width:600 ~modal:true ~title:"New Proof or Definition"
1427    ~border_width:2 () in
1428  let vbox = GPack.vbox ~packing:window#add () in
1429  let hbox =
1430   GPack.hbox ~border_width:0
1431    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1432  let _ =
1433   GMisc.label ~text:"Enter the URI for the new theorem or definition:"
1434    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1435  let uri_entry =
1436   GEdit.entry ~editable:true
1437    ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1438  uri_entry#set_text dummy_uri;
1439  uri_entry#select_region ~start:1 ~stop:(String.length dummy_uri);
1440  let hbox1 =
1441   GPack.hbox ~border_width:0
1442    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1443  let _ =
1444   GMisc.label ~text:"Enter the theorem or definition type:"
1445    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1446  let scrolled_window =
1447   GBin.scrolled_window ~border_width:5
1448    ~packing:(vbox#pack ~expand:true ~padding:0) () in
1449  (* the content of the scrolled_window is moved below (see comment) *)
1450  let hbox =
1451   GPack.hbox ~border_width:0
1452    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1453  let okb =
1454   GButton.button ~label:"Ok"
1455    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1456  let _ = okb#misc#set_sensitive false in
1457  let cancelb =
1458   GButton.button ~label:"Cancel"
1459    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1460  (* moved here to have visibility of the ok button *)
1461  let newinputt =
1462   TermEditor'.term_editor
1463    mqi_handle
1464    ~width:400 ~height:100 ~packing:scrolled_window#add
1465    ~share_environment_with:inputt ()
1466    ~isnotempty_callback:
1467     (function b ->
1468       non_empty_type := b ;
1469       okb#misc#set_sensitive (b && uri_entry#text <> ""))
1470  in
1471  let _ =
1472   newinputt#set_term inputt#get_as_string  ;
1473   inputt#reset in
1474  let _ =
1475   uri_entry#connect#changed
1476    (function () ->
1477      okb#misc#set_sensitive (!non_empty_type && uri_entry#text <> ""))
1478  in
1479  ignore (window#connect#destroy GMain.Main.quit) ;
1480  ignore (cancelb#connect#clicked window#destroy) ;
1481  ignore
1482   (okb#connect#clicked
1483     (function () ->
1484       chosen := true ;
1485       try
1486        let metasenv,parsed = newinputt#get_metasenv_and_term [] [] in
1487        let uristr = "cic:" ^ uri_entry#text in
1488        let uri = UriManager.uri_of_string uristr in
1489         if String.sub uristr (String.length uristr - 4) 4 <> ".con" then
1490          raise NotAUriToAConstant
1491         else
1492          begin
1493           try
1494            ignore (Http_getter.resolve' uri) ;
1495            raise UriAlreadyInUse
1496           with Http_getter_types.Unresolvable_URI _ ->
1497             get_metasenv_and_term := (function () -> metasenv,parsed) ;
1498             get_uri := (function () -> uri) ; 
1499             window#destroy ()
1500          end
1501       with
1502        e ->
1503         HelmLogger.log
1504          (`Error (`T (Printexc.to_string e)))
1505   )) ;
1506  window#show () ;
1507  GtkThread.main ();
1508  if !chosen then
1509   try
1510    let metasenv,expr = !get_metasenv_and_term () in
1511     let _  = CicTypeChecker.type_of_aux' metasenv [] expr in
1512      ProofEngine.set_proof
1513       (Some (!get_uri (), (1,[],expr)::metasenv, Cic.Meta (1,[]), expr)) ;
1514      set_proof_engine_goal (Some 1) ;
1515      refresh_goals notebook ;
1516      refresh_proof output ;
1517      !save_set_sensitive true ;
1518      inputt#reset ;
1519      ProofEngine.intros ~mk_fresh_name_callback () ;
1520      refresh_goals notebook ;
1521      refresh_proof output
1522   with
1523      InvokeTactics.RefreshSequentException e ->
1524       HelmLogger.log
1525        (`Error (`T ("Exception raised during the refresh of the " ^
1526         "sequent: " ^ Printexc.to_string e)))
1527    | InvokeTactics.RefreshProofException e ->
1528       HelmLogger.log
1529        (`Error (`T ("Exception raised during the refresh of the " ^
1530         "proof: " ^ Printexc.to_string e)))
1531    | e ->
1532       HelmLogger.log
1533        (`Error (`T (Printexc.to_string e)))
1534 ;;
1535
1536 let check_term_in_scratch scratch_window metasenv context expr = 
1537  try
1538   let ty = CicTypeChecker.type_of_aux' metasenv context expr in
1539   let expr = Cic.Cast (expr,ty) in
1540    scratch_window#show () ;
1541    scratch_window#set_term expr ;
1542    scratch_window#set_context context ;
1543    scratch_window#set_metasenv metasenv ;
1544    scratch_window#sequent_viewer#load_sequent metasenv (111,context,expr)
1545  with
1546   e ->
1547    print_endline ("? " ^ CicPp.ppterm expr) ;
1548    raise e
1549 ;;
1550
1551 let check scratch_window () =
1552  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1553   let metasenv =
1554    match ProofEngine.get_proof () with
1555       None -> []
1556     | Some (_,metasenv,_,_) -> metasenv
1557   in
1558   let context =
1559    match !ProofEngine.goal with
1560       None -> []
1561     | Some metano ->
1562        let (_,canonical_context,_) =
1563         List.find (function (m,_,_) -> m=metano) metasenv
1564        in
1565         canonical_context
1566   in
1567    try
1568     let metasenv',expr = inputt#get_metasenv_and_term context metasenv in
1569      check_term_in_scratch scratch_window metasenv' context expr
1570    with
1571     e ->
1572      HelmLogger.log
1573       (`Error (`T (Printexc.to_string e)))
1574 ;;
1575
1576 let show () =
1577   try
1578    show_in_show_window_uri (input_or_locate_uri ~title:"Show")
1579   with
1580    e ->
1581     HelmLogger.log
1582      (`Error (`T (Printexc.to_string e)))
1583 ;;
1584
1585 exception NotADefinition;;
1586
1587 let open_ () =
1588  let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
1589  let notebook = (rendering_window ())#notebook in
1590    try
1591     let uri = input_or_locate_uri ~title:"Open" in
1592      CicTypeChecker.typecheck uri ;
1593      let metasenv,bo,ty =
1594       match CicEnvironment.get_cooked_obj uri with
1595          Cic.Constant (_,Some bo,ty,_) -> [],bo,ty
1596        | Cic.CurrentProof (_,metasenv,bo,ty,_) -> metasenv,bo,ty
1597        | Cic.Constant _
1598        | Cic.Variable _
1599        | Cic.InductiveDefinition _ -> raise NotADefinition
1600      in
1601       ProofEngine.set_proof (Some (uri, metasenv, bo, ty)) ;
1602       set_proof_engine_goal None ;
1603       refresh_goals notebook ;
1604       refresh_proof output ;
1605       !save_set_sensitive true
1606    with
1607       InvokeTactics.RefreshSequentException e ->
1608        HelmLogger.log
1609         (`Error (`T ("Exception raised during the refresh of the " ^
1610          "sequent: " ^ Printexc.to_string e)))
1611     | InvokeTactics.RefreshProofException e ->
1612        HelmLogger.log
1613         (`Error (`T ("Exception raised during the refresh of the " ^
1614          "proof: " ^ Printexc.to_string e)))
1615     | e ->
1616        HelmLogger.log
1617         (`Error (`T (Printexc.to_string e)))
1618 ;;
1619
1620 let show_query_results results =
1621  let window =
1622   GWindow.window
1623    ~modal:false ~title:"Query results." ~border_width:2 () in
1624  let vbox = GPack.vbox ~packing:window#add () in
1625  let hbox =
1626   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1627  let lMessage =
1628   GMisc.label
1629    ~text:"Click on a URI to show that object"
1630    ~packing:hbox#add () in
1631  let scrolled_window =
1632   GBin.scrolled_window ~border_width:10 ~height:400 ~width:600
1633    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1634  let clist = GList.clist ~columns:1 ~packing:scrolled_window#add () in
1635   ignore
1636    (List.map
1637      (function (uri,_) ->
1638        let n =
1639         clist#append [uri]
1640        in
1641         clist#set_row ~selectable:false n
1642      ) results
1643    ) ;
1644   clist#columns_autosize () ;
1645   ignore
1646    (clist#connect#select_row
1647      (fun ~row ~column ~event ->
1648        let (uristr,_) = List.nth results row in
1649         match
1650          MQueryMisc.cic_textual_parser_uri_of_string
1651           (MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format'
1652             uristr)
1653         with
1654            CicTextualParser0.ConUri uri
1655          | CicTextualParser0.VarUri uri
1656          | CicTextualParser0.IndTyUri (uri,_)
1657          | CicTextualParser0.IndConUri (uri,_,_) ->
1658             show_in_show_window_uri uri
1659      )
1660    ) ;
1661   window#show ()
1662 ;;
1663
1664 let refine_constraints (must_obj,must_rel,must_sort) =
1665  let chosen = ref false in
1666  let use_only = ref false in
1667  let window =
1668   GWindow.window
1669    ~modal:true ~title:"Constraints refinement."
1670    ~width:800 ~border_width:2 () in
1671  let vbox = GPack.vbox ~packing:window#add () in
1672  let hbox =
1673   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1674  let lMessage =
1675   GMisc.label
1676    ~text: "\"Only\" constraints can be enforced or not."
1677    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1678  let onlyb =
1679   GButton.toggle_button ~label:"Enforce \"only\" constraints"
1680    ~active:false ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
1681  in
1682   ignore
1683    (onlyb#connect#toggled (function () -> use_only := onlyb#active)) ;
1684  (* Notebook for the constraints choice *)
1685  let notebook =
1686   GPack.notebook ~scrollable:true
1687    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1688  (* Rel constraints *)
1689  let label =
1690   GMisc.label
1691    ~text: "Constraints on Rels" () in
1692  let vbox' =
1693   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
1694    () in
1695  let hbox =
1696   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
1697  let lMessage =
1698   GMisc.label
1699    ~text: "You can now specify the constraints on Rels."
1700    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1701  let expected_height = 25 * (List.length must_rel + 2) in
1702  let height = if expected_height > 400 then 400 else expected_height in
1703  let scrolled_window =
1704   GBin.scrolled_window ~border_width:10 ~height ~width:600
1705    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
1706  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
1707  let mk_depth_button (hbox:GPack.box) d =
1708     let mutable_ref = ref (Some d) in
1709     let depthb =
1710      GButton.toggle_button
1711       ~label:("depth = " ^ string_of_int d) 
1712       ~active:true
1713       ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
1714     in
1715      ignore
1716       (depthb#connect#toggled
1717        (function () ->
1718         let sel_depth = if depthb#active then Some d else None in
1719          mutable_ref := sel_depth
1720        )) ; mutable_ref
1721  in
1722  let rel_constraints =
1723   List.map
1724    (function p ->
1725      let hbox =
1726       GPack.hbox
1727        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
1728      let lMessage =
1729       GMisc.label
1730        ~text:(MQGU.text_of_position (p:>MQGT.full_position))
1731        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1732      match p with
1733       | `MainHypothesis None 
1734       | `MainConclusion None -> p, ref None
1735       | `MainHypothesis (Some depth') 
1736       | `MainConclusion (Some depth') -> p, mk_depth_button hbox depth'
1737    ) must_rel in
1738  (* Sort constraints *)
1739  let label =
1740   GMisc.label
1741    ~text: "Constraints on Sorts" () in
1742  let vbox' =
1743   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
1744    () in
1745  let hbox =
1746   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
1747  let lMessage =
1748   GMisc.label
1749    ~text: "You can now specify the constraints on Sorts."
1750    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1751  let expected_height = 25 * (List.length must_sort + 2) in
1752  let height = if expected_height > 400 then 400 else expected_height in
1753  let scrolled_window =
1754   GBin.scrolled_window ~border_width:10 ~height ~width:600
1755    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
1756  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
1757  let sort_constraints =
1758   List.map
1759    (function (p, sort) ->
1760      let hbox =
1761       GPack.hbox
1762        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
1763      let lMessage =
1764       GMisc.label
1765        ~text:(MQGU.text_of_sort sort ^ " " ^ MQGU.text_of_position (p:>MQGT.full_position))
1766        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1767      match p with
1768       | `MainHypothesis None 
1769       | `MainConclusion None -> p, ref None, sort
1770       | `MainHypothesis (Some depth') 
1771       | `MainConclusion (Some depth') -> p, mk_depth_button hbox depth', sort
1772    ) must_sort in
1773  (* Obj constraints *)
1774  let label =
1775   GMisc.label
1776    ~text: "Constraints on constants" () in
1777  let vbox' =
1778   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
1779    () in
1780  let hbox =
1781   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
1782  let lMessage =
1783   GMisc.label
1784    ~text: "You can now specify the constraints on constants."
1785    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1786  let expected_height = 25 * (List.length must_obj + 2) in
1787  let height = if expected_height > 400 then 400 else expected_height in
1788  let scrolled_window =
1789   GBin.scrolled_window ~border_width:10 ~height ~width:600
1790    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
1791  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
1792  let obj_constraints =
1793   List.map
1794    (function (p, uri) ->
1795      let hbox =
1796       GPack.hbox
1797        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
1798      let lMessage =
1799       GMisc.label
1800        ~text:(uri ^ " " ^ (MQGU.text_of_position p))
1801        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1802      match p with
1803       | `InBody
1804       | `InHypothesis 
1805       | `InConclusion 
1806       | `MainHypothesis None 
1807       | `MainConclusion None -> p, ref None, uri
1808       | `MainHypothesis (Some depth') 
1809       | `MainConclusion (Some depth') -> p, mk_depth_button hbox depth', uri
1810    ) must_obj in
1811  (* Confirm/abort buttons *)
1812  let hbox =
1813   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1814  let okb =
1815   GButton.button ~label:"Ok"
1816    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1817  let cancelb =
1818   GButton.button ~label:"Abort"
1819    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
1820  in
1821   ignore (window#connect#destroy GMain.Main.quit) ;
1822   ignore (cancelb#connect#clicked window#destroy) ;
1823   ignore
1824    (okb#connect#clicked (function () -> chosen := true ; window#destroy ()));
1825   window#set_position `CENTER ;
1826   window#show () ;
1827   GtkThread.main ();
1828   if !chosen then
1829    let chosen_must_rel =
1830     List.map
1831      (function (position, ref_depth) -> MQGU.set_main_position position !ref_depth)
1832      rel_constraints
1833    in
1834    let chosen_must_sort =
1835     List.map
1836      (function (position, ref_depth, sort) -> 
1837       MQGU.set_main_position position !ref_depth,sort)
1838      sort_constraints
1839    in
1840    let chosen_must_obj =
1841     List.map
1842      (function (position, ref_depth, uri) -> MQGU.set_full_position position !ref_depth, uri)
1843      obj_constraints
1844    in
1845     (chosen_must_obj,chosen_must_rel,chosen_must_sort),
1846      (if !use_only then
1847 (*CSC: ???????????????????????? I assume that must and only are the same... *)
1848        Some chosen_must_obj,Some chosen_must_rel,Some chosen_must_sort
1849       else
1850        None,None,None
1851      )
1852   else
1853    raise NoChoice
1854 ;;
1855
1856 let completeSearchPattern () =
1857  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1858   try
1859    let metasenv,expr = inputt#get_metasenv_and_term ~context:[] ~metasenv:[] in
1860    let must = CGSearchPattern.get_constraints expr in
1861    let must',only = refine_constraints must in
1862    let query =
1863     MQG.query_of_constraints (Some CGSearchPattern.universe) must' only
1864    in
1865    let results = MQI.execute mqi_handle query in 
1866     show_query_results results
1867   with
1868    e ->
1869     HelmLogger.log
1870      (`Error (`T (Printexc.to_string e)))
1871 ;;
1872
1873 let insertQuery () =
1874   try
1875    let chosen = ref None in
1876    let window =
1877     GWindow.window
1878      ~modal:true ~title:"Insert Query (Experts Only)" ~border_width:2 () in
1879    let vbox = GPack.vbox ~packing:window#add () in
1880    let label =
1881     GMisc.label ~text:"Insert Query. For Experts Only."
1882      ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1883    let scrolled_window =
1884     GBin.scrolled_window ~border_width:10 ~height:400 ~width:600
1885      ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1886    let input = GText.view ~editable:true
1887     ~packing:scrolled_window#add () in
1888    let hbox =
1889     GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1890    let okb =
1891     GButton.button ~label:"Ok"
1892      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1893    let loadb =
1894     GButton.button ~label:"Load from file..."
1895      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1896    let cancelb =
1897     GButton.button ~label:"Abort"
1898      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1899    ignore (window#connect#destroy GMain.Main.quit) ;
1900    ignore (cancelb#connect#clicked window#destroy) ;
1901    ignore
1902     (okb#connect#clicked
1903       (function () ->
1904         chosen := Some (input#buffer#get_text ()) ; window#destroy ())) ;
1905    ignore
1906     (loadb#connect#clicked
1907       (function () ->
1908         match
1909          GToolbox.select_file ~title:"Select Query File" ()
1910         with
1911            None -> ()
1912          | Some filename ->
1913             let inch = open_in filename in
1914              let rec read_file () =
1915               try
1916                let line = input_line inch in
1917                 line ^ "\n" ^ read_file ()
1918               with
1919                End_of_file -> ""
1920              in
1921               let text = read_file () in
1922                input#buffer#delete input#buffer#start_iter input#buffer#end_iter ;
1923                ignore (input#buffer#insert text))) ;
1924    window#set_position `CENTER ;
1925    window#show () ;
1926    GtkThread.main ();
1927    match !chosen with
1928       None -> ()
1929     | Some q ->
1930        let results =
1931         MQI.execute mqi_handle (MQueryUtil.query_of_text (Lexing.from_string q))
1932        in
1933         show_query_results results
1934   with
1935    e ->
1936     HelmLogger.log
1937      (`Error (`T (Printexc.to_string e)))
1938 ;;
1939
1940 let choose_must list_of_must only =
1941  let chosen = ref None in
1942  let user_constraints = ref [] in
1943  let window =
1944   GWindow.window
1945    ~modal:true ~title:"Query refinement." ~border_width:2 () in
1946  let vbox = GPack.vbox ~packing:window#add () in
1947  let hbox =
1948   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1949  let lMessage =
1950   GMisc.label
1951    ~text:
1952     ("You can now specify the genericity of the query. " ^
1953      "The more generic the slower.")
1954    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1955  let hbox =
1956   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1957  let lMessage =
1958   GMisc.label
1959    ~text:
1960     "Suggestion: start with faster queries before moving to more generic ones."
1961    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1962  let notebook =
1963   GPack.notebook ~scrollable:true
1964    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1965  let _ =
1966   let page = ref 0 in
1967   let last = List.length list_of_must in
1968   List.map
1969    (function must ->
1970      incr page ;
1971      let label =
1972       GMisc.label ~text:
1973        (if !page = 1 then "More generic" else
1974          if !page = last then "More precise" else "          ") () in
1975      let expected_height = 25 * (List.length must + 2) in
1976      let height = if expected_height > 400 then 400 else expected_height in
1977      let scrolled_window =
1978       GBin.scrolled_window ~border_width:10 ~height ~width:600
1979        ~packing:(notebook#append_page ~tab_label:label#coerce) () in
1980      let clist =
1981         GList.clist ~columns:2 ~packing:scrolled_window#add
1982          ~titles:["URI" ; "Position"] ()
1983      in
1984       ignore
1985        (List.map
1986          (function (position, uri) ->
1987            let n =
1988             clist#append 
1989              [uri; MQGUtil.text_of_position position]
1990            in
1991             clist#set_row ~selectable:false n
1992          ) must
1993        ) ;
1994       clist#columns_autosize ()
1995    ) list_of_must in
1996  let _ =
1997   let label = GMisc.label ~text:"User provided" () in
1998   let vbox =
1999    GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce) () in
2000   let hbox =
2001    GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2002   let lMessage =
2003    GMisc.label
2004    ~text:"Select the constraints that must be satisfied and press OK."
2005    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2006   let expected_height = 25 * (List.length only + 2) in
2007   let height = if expected_height > 400 then 400 else expected_height in
2008   let scrolled_window =
2009    GBin.scrolled_window ~border_width:10 ~height ~width:600
2010     ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2011   let clist =
2012    GList.clist ~columns:2 ~packing:scrolled_window#add
2013     ~selection_mode:`MULTIPLE
2014     ~titles:["URI" ; "Position"] ()
2015   in
2016    ignore
2017     (List.map
2018       (function (position, uri) ->
2019         let n =
2020          clist#append 
2021           [uri; MQGUtil.text_of_position position]
2022         in
2023          clist#set_row ~selectable:true n
2024       ) only
2025     ) ;
2026    clist#columns_autosize () ;
2027    ignore
2028     (clist#connect#select_row
2029       (fun ~row ~column ~event ->
2030         user_constraints := (List.nth only row)::!user_constraints)) ;
2031    ignore
2032     (clist#connect#unselect_row
2033       (fun ~row ~column ~event ->
2034         user_constraints :=
2035          List.filter
2036           (function uri -> uri != (List.nth only row)) !user_constraints)) ;
2037  in
2038  let hbox =
2039   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2040  let okb =
2041   GButton.button ~label:"Ok"
2042    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2043  let cancelb =
2044   GButton.button ~label:"Abort"
2045    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2046  (* actions *)
2047  ignore (window#connect#destroy GMain.Main.quit) ;
2048  ignore (cancelb#connect#clicked window#destroy) ;
2049  ignore
2050   (okb#connect#clicked
2051     (function () -> chosen := Some notebook#current_page ; window#destroy ())) ;
2052  window#set_position `CENTER ;
2053  window#show () ;
2054  GtkThread.main ();
2055  match !chosen with
2056     None -> raise NoChoice
2057   | Some n ->
2058      if n = List.length list_of_must then
2059       (* user provided constraints *)
2060       !user_constraints
2061      else
2062       List.nth list_of_must n
2063 ;;
2064
2065 let searchPattern () =
2066  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
2067   try
2068     let proof =
2069      match ProofEngine.get_proof () with
2070         None -> assert false
2071       | Some proof -> proof
2072     in
2073      match !ProofEngine.goal with
2074       | None -> ()
2075       | Some metano ->
2076          let uris' =
2077            TacticChaser.matchConclusion mqi_handle
2078             ~choose_must () ~status:(proof, metano)
2079          in
2080          let uri' =
2081           user_uri_choice ~title:"Ambiguous input."
2082           ~msg: "Many lemmas can be successfully applied. Please, choose one:"
2083            uris'
2084          in
2085           inputt#set_term uri' ;
2086           InvokeTactics'.apply ()
2087   with
2088    e -> 
2089     HelmLogger.log 
2090      (`Error (`T (Printexc.to_string e)))
2091 ;;
2092       
2093 let choose_selection mmlwidget (element : Gdome.element option) =
2094  let module G = Gdome in
2095   let rec aux element =
2096    if element#hasAttributeNS
2097        ~namespaceURI:Misc.helmns
2098        ~localName:(G.domString "xref")
2099    then
2100      mmlwidget#set_selection (Some element)
2101    else
2102     try
2103       match element#get_parentNode with
2104          None -> assert false
2105        (*CSC: OCAML DIVERGES!
2106        | Some p -> aux (new G.element_of_node p)
2107        *)
2108        | Some p -> aux (new Gdome.element_of_node p)
2109     with
2110        GdomeInit.DOMCastException _ ->
2111         debug_print
2112          "******* trying to select above the document root ********"
2113   in
2114    match element with
2115      Some x -> aux x
2116    | None   -> mmlwidget#set_selection None
2117 ;;
2118
2119 (* STUFF TO BUILD THE GTK INTERFACE *)
2120
2121 (* Stuff for the widget settings *)
2122
2123 (*
2124 let export_to_postscript output =
2125  let lastdir = ref (Unix.getcwd ()) in
2126   function () ->
2127    match
2128     GToolbox.select_file ~title:"Export to PostScript"
2129      ~dir:lastdir ~filename:"screenshot.ps" ()
2130    with
2131       None -> ()
2132     | Some filename ->
2133        (output :> GMathView.math_view)#export_to_postscript
2134          ~filename:filename ();
2135 ;;
2136 *)
2137
2138 (*
2139 let activate_t1 output button_set_anti_aliasing
2140  button_set_transparency export_to_postscript_menu_item
2141  button_t1 ()
2142 =
2143  let is_set = button_t1#active in
2144   output#set_font_manager_type
2145    ~fm_type:(if is_set then `font_manager_t1 else `font_manager_gtk) ;
2146   if is_set then
2147    begin
2148     button_set_anti_aliasing#misc#set_sensitive true ;
2149     button_set_transparency#misc#set_sensitive true ;
2150     export_to_postscript_menu_item#misc#set_sensitive true ;
2151    end
2152   else
2153    begin
2154     button_set_anti_aliasing#misc#set_sensitive false ;
2155     button_set_transparency#misc#set_sensitive false ;
2156     export_to_postscript_menu_item#misc#set_sensitive false ;
2157    end
2158 ;;
2159
2160 let set_anti_aliasing output button_set_anti_aliasing () =
2161  output#set_anti_aliasing button_set_anti_aliasing#active
2162 ;;
2163
2164 let set_transparency output button_set_transparency () =
2165  output#set_transparency button_set_transparency#active
2166 ;;
2167 *)
2168
2169 let changefont output font_size_spinb () =
2170  output#set_font_size font_size_spinb#value_as_int
2171 ;;
2172
2173 let set_log_verbosity output log_verbosity_spinb () =
2174  output#set_log_verbosity log_verbosity_spinb#value_as_int
2175 ;;
2176
2177 class settings_window output sw
2178  export_to_postscript_menu_item selection_changed_callback
2179 =
2180  let settings_window = GWindow.window ~title:"GtkMathView settings" () in
2181  let vbox =
2182   GPack.vbox ~packing:settings_window#add () in
2183  let table =
2184   GPack.table
2185    ~rows:1 ~columns:3 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2186    ~border_width:5 ~packing:vbox#add () in
2187  let button_t1 =
2188   GButton.toggle_button ~label:"activate t1 fonts"
2189    ~packing:(table#attach ~left:0 ~top:0) () in
2190  let button_set_anti_aliasing =
2191   GButton.toggle_button ~label:"set_anti_aliasing"
2192    ~packing:(table#attach ~left:0 ~top:1) () in
2193  let button_set_transparency =
2194   GButton.toggle_button ~label:"set_transparency"
2195    ~packing:(table#attach ~left:2 ~top:1) () in
2196  let table =
2197   GPack.table
2198    ~rows:2 ~columns:2 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2199    ~border_width:5 ~packing:vbox#add () in
2200  let font_size_label =
2201   GMisc.label ~text:"font size:"
2202    ~packing:(table#attach ~left:0 ~top:0 ~expand:`NONE) () in
2203  let font_size_spinb =
2204   let sadj =
2205    GData.adjustment ~value:(float_of_int output#get_font_size)
2206     ~lower:5.0 ~upper:50.0 ~step_incr:1.0 ()
2207   in
2208    GEdit.spin_button 
2209     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:0 ~fill:`NONE) () in
2210  let log_verbosity_label =
2211   GMisc.label ~text:"log verbosity:"
2212    ~packing:(table#attach ~left:0 ~top:1) () in
2213  let log_verbosity_spinb =
2214   let sadj =
2215    GData.adjustment ~value:0.0 ~lower:0.0 ~upper:3.0 ~step_incr:1.0 ()
2216   in
2217    GEdit.spin_button 
2218     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:1) () in
2219  let hbox =
2220   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2221  let closeb =
2222   GButton.button ~label:"Close"
2223    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2224 object(self)
2225  method show = settings_window#show
2226  initializer
2227   button_set_anti_aliasing#misc#set_sensitive false ;
2228   button_set_transparency#misc#set_sensitive false ;
2229   (* Signals connection *)
2230   (*
2231   ignore(button_t1#connect#clicked
2232    (activate_t1 output button_set_anti_aliasing
2233     button_set_transparency export_to_postscript_menu_item button_t1)) ;
2234   *)
2235   ignore(font_size_spinb#connect#changed (changefont output font_size_spinb)) ;
2236   (*
2237   ignore(button_set_anti_aliasing#connect#toggled
2238    (set_anti_aliasing output button_set_anti_aliasing));
2239   ignore(button_set_transparency#connect#toggled
2240    (set_transparency output button_set_transparency)) ;
2241   *)
2242   ignore(log_verbosity_spinb#connect#changed
2243    (set_log_verbosity output log_verbosity_spinb)) ;
2244   ignore(closeb#connect#clicked settings_window#misc#hide)
2245 end;;
2246
2247 (* Scratch window *)
2248
2249 class scratch_window =
2250  let window =
2251   GWindow.window
2252     ~title:"MathML viewer"
2253     ~border_width:2 () in
2254  let vbox =
2255   GPack.vbox ~packing:window#add () in
2256  let hbox =
2257   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2258  let whdb =
2259   GButton.button ~label:"Whd"
2260    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2261  let reduceb =
2262   GButton.button ~label:"Reduce"
2263    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2264  let simplb =
2265   GButton.button ~label:"Simpl"
2266    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2267  let scrolled_window =
2268   GBin.scrolled_window ~border_width:10
2269    ~packing:(vbox#pack ~expand:true ~padding:5) () in
2270  let sequent_viewer =
2271   TermViewer.sequent_viewer
2272    ~packing:(scrolled_window#add) ~width:400 ~height:280 () in
2273 object(self)
2274  val mutable term = Cic.Rel 1                 (* dummy value *)
2275  val mutable context = ([] : Cic.context)     (* dummy value *)
2276  val mutable metasenv = ([] : Cic.metasenv)   (* dummy value *)
2277  method sequent_viewer = sequent_viewer
2278  method show () = window#misc#hide () ; window#show ()
2279  method term = term
2280  method set_term t = term <- t
2281  method context = context
2282  method set_context t = context <- t
2283  method metasenv = metasenv
2284  method set_metasenv t = metasenv <- t
2285  initializer
2286   ignore
2287    (sequent_viewer#connect#selection_changed (choose_selection sequent_viewer));
2288   ignore(window#event#connect#delete (fun _ -> window#misc#hide () ; true )) ;
2289   ignore(whdb#connect#clicked InvokeTactics'.whd_in_scratch) ;
2290   ignore(reduceb#connect#clicked InvokeTactics'.reduce_in_scratch) ;
2291   ignore(simplb#connect#clicked InvokeTactics'.simpl_in_scratch)
2292 end;;
2293
2294 let open_contextual_menu_for_selected_terms mmlwidget infos =
2295  let button = GdkEvent.Button.button infos in 
2296  let terms_selected = List.length mmlwidget#get_selections > 0 in
2297   if button = 3 then
2298    begin
2299     let time = GdkEvent.Button.time infos in
2300     let menu = GMenu.menu () in
2301     let f = new GMenu.factory menu in
2302     let whd_menu_item =
2303      f#add_item "Whd" ~key:GdkKeysyms._W ~callback:InvokeTactics'.whd in
2304     let reduce_menu_item =
2305      f#add_item "Reduce" ~key:GdkKeysyms._R ~callback:InvokeTactics'.reduce in
2306     let simpl_menu_item =
2307      f#add_item "Simpl" ~key:GdkKeysyms._S ~callback:InvokeTactics'.simpl in
2308     let _ = f#add_separator () in
2309     let generalize_menu_item =
2310      f#add_item "Generalize"
2311       ~key:GdkKeysyms._G ~callback:InvokeTactics'.generalize in
2312     let _ = f#add_separator () in
2313     let clear_menu_item =
2314      f#add_item "Clear" ~key:GdkKeysyms._C ~callback:InvokeTactics'.clear in
2315     let clearbody_menu_item =
2316      f#add_item "ClearBody"
2317       ~key:GdkKeysyms._B ~callback:InvokeTactics'.clearbody
2318     in
2319      whd_menu_item#misc#set_sensitive terms_selected ; 
2320      reduce_menu_item#misc#set_sensitive terms_selected ; 
2321      simpl_menu_item#misc#set_sensitive terms_selected ;
2322      generalize_menu_item#misc#set_sensitive terms_selected ;
2323      clear_menu_item#misc#set_sensitive terms_selected ;
2324      clearbody_menu_item#misc#set_sensitive terms_selected ;
2325      menu#popup ~button ~time
2326    end ;
2327   true
2328 ;;
2329
2330 class page () =
2331  let vbox1 = GPack.vbox () in
2332 object(self)
2333  val mutable proofw_ref = None
2334  val mutable compute_ref = None
2335  method proofw =
2336   Lazy.force self#compute ;
2337   match proofw_ref with
2338      None -> assert false
2339    | Some proofw -> proofw
2340  method content = vbox1
2341  method compute =
2342   match compute_ref with
2343      None -> assert false
2344    | Some compute -> compute
2345  initializer
2346   compute_ref <-
2347    Some (lazy (
2348    let scrolled_window1 =
2349     GBin.scrolled_window ~border_width:10
2350      ~packing:(vbox1#pack ~expand:true ~padding:5) () in
2351    let proofw =
2352     TermViewer.sequent_viewer ~width:400 ~height:275
2353      ~packing:(scrolled_window1#add) () in
2354    let _ = proofw_ref <- Some proofw in
2355    let hbox3 =
2356     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2357    let ringb =
2358     GButton.button ~label:"Ring"
2359      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2360    let fourierb =
2361     GButton.button ~label:"Fourier"
2362      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2363    let reflexivityb =
2364     GButton.button ~label:"Reflexivity"
2365      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2366    let symmetryb =
2367     GButton.button ~label:"Symmetry"
2368      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2369    let assumptionb =
2370     GButton.button ~label:"Assumption"
2371      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2372    let contradictionb =
2373     GButton.button ~label:"Contradiction"
2374      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2375    let hbox4 =
2376     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2377    let existsb =
2378     GButton.button ~label:"Exists"
2379      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2380    let splitb =
2381     GButton.button ~label:"Split"
2382      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2383    let leftb =
2384     GButton.button ~label:"Left"
2385      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2386    let rightb =
2387     GButton.button ~label:"Right"
2388      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2389    let searchpatternb =
2390     GButton.button ~label:"SearchPattern_Apply"
2391      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2392    let hbox5 =
2393     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2394    let exactb =
2395     GButton.button ~label:"Exact"
2396      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2397    let introsb =
2398     GButton.button ~label:"Intros"
2399      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2400    let applyb =
2401     GButton.button ~label:"Apply"
2402      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2403    let elimintrossimplb =
2404     GButton.button ~label:"ElimIntrosSimpl"
2405      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2406    let elimtypeb =
2407     GButton.button ~label:"ElimType"
2408      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2409    let foldwhdb =
2410     GButton.button ~label:"Fold_whd"
2411      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2412    let foldreduceb =
2413     GButton.button ~label:"Fold_reduce"
2414      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2415    let hbox6 =
2416     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2417    let foldsimplb =
2418     GButton.button ~label:"Fold_simpl"
2419      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2420    let cutb =
2421     GButton.button ~label:"Cut"
2422      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2423    let changeb =
2424     GButton.button ~label:"Change"
2425      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2426    let letinb =
2427     GButton.button ~label:"Let ... In"
2428      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2429    let rewritesimplb =
2430     GButton.button ~label:"RewriteSimpl ->"
2431      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2432    let rewritebacksimplb =
2433     GButton.button ~label:"RewriteSimpl <-"
2434      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2435    let hbox7 =
2436     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2437    let absurdb =
2438     GButton.button ~label:"Absurd"
2439      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2440    let decomposeb =
2441     GButton.button ~label:"Decompose"
2442      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2443    let transitivityb =
2444     GButton.button ~label:"Transitivity"
2445      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2446    let replaceb =
2447     GButton.button ~label:"Replace"
2448      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2449    let injectionb =
2450     GButton.button ~label:"Injection"
2451      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2452    let discriminateb =
2453     GButton.button ~label:"Discriminate"
2454      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2455 (* Zack: spostare in una toolbar
2456    let generalizeb =
2457     GButton.button ~label:"Generalize"
2458      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2459    let clearbodyb =
2460     GButton.button ~label:"ClearBody"
2461      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2462    let clearb =
2463     GButton.button ~label:"Clear"
2464      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2465    let whdb =
2466     GButton.button ~label:"Whd"
2467      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2468    let reduceb =
2469     GButton.button ~label:"Reduce"
2470      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2471    let simplb =
2472     GButton.button ~label:"Simpl"
2473      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2474 *)
2475
2476    ignore(exactb#connect#clicked InvokeTactics'.exact) ;
2477    ignore(applyb#connect#clicked InvokeTactics'.apply) ;
2478    ignore(elimintrossimplb#connect#clicked InvokeTactics'.elimintrossimpl) ;
2479    ignore(elimtypeb#connect#clicked InvokeTactics'.elimtype) ;
2480    ignore(foldwhdb#connect#clicked InvokeTactics'.fold_whd) ;
2481    ignore(foldreduceb#connect#clicked InvokeTactics'.fold_reduce) ;
2482    ignore(foldsimplb#connect#clicked InvokeTactics'.fold_simpl) ;
2483    ignore(cutb#connect#clicked InvokeTactics'.cut) ;
2484    ignore(changeb#connect#clicked InvokeTactics'.change) ;
2485    ignore(letinb#connect#clicked InvokeTactics'.letin) ;
2486    ignore(ringb#connect#clicked InvokeTactics'.ring) ;
2487    ignore(fourierb#connect#clicked InvokeTactics'.fourier) ;
2488    ignore(rewritesimplb#connect#clicked InvokeTactics'.rewritesimpl) ;
2489    ignore(rewritebacksimplb#connect#clicked InvokeTactics'.rewritebacksimpl) ;
2490    ignore(replaceb#connect#clicked InvokeTactics'.replace) ;
2491    ignore(reflexivityb#connect#clicked InvokeTactics'.reflexivity) ;
2492    ignore(symmetryb#connect#clicked InvokeTactics'.symmetry) ;
2493    ignore(transitivityb#connect#clicked InvokeTactics'.transitivity) ;
2494    ignore(existsb#connect#clicked InvokeTactics'.exists) ;
2495    ignore(splitb#connect#clicked InvokeTactics'.split) ;
2496    ignore(leftb#connect#clicked InvokeTactics'.left) ;
2497    ignore(rightb#connect#clicked InvokeTactics'.right) ;
2498    ignore(assumptionb#connect#clicked InvokeTactics'.assumption) ;
2499    ignore(absurdb#connect#clicked InvokeTactics'.absurd) ;
2500    ignore(contradictionb#connect#clicked InvokeTactics'.contradiction) ;
2501    ignore(introsb#connect#clicked InvokeTactics'.intros) ;
2502    ignore(decomposeb#connect#clicked InvokeTactics'.decompose) ;
2503    ignore(searchpatternb#connect#clicked searchPattern) ;
2504    ignore(injectionb#connect#clicked InvokeTactics'.injection) ;
2505    ignore(discriminateb#connect#clicked InvokeTactics'.discriminate) ;
2506 (* Zack: spostare in una toolbar
2507    ignore(whdb#connect#clicked whd) ;
2508    ignore(reduceb#connect#clicked reduce) ;
2509    ignore(simplb#connect#clicked simpl) ;
2510    ignore(clearbodyb#connect#clicked clearbody) ;
2511    ignore(clearb#connect#clicked clear) ;
2512    ignore(generalizeb#connect#clicked generalize) ;
2513 *)
2514    ignore(proofw#connect#selection_changed (choose_selection proofw)) ;
2515    ignore
2516      ((new GObj.event_ops proofw#as_widget)#connect#button_press
2517         (open_contextual_menu_for_selected_terms proofw)) ;
2518   ))
2519 end
2520 ;;
2521
2522 class empty_page =
2523  let vbox1 = GPack.vbox () in
2524  let scrolled_window1 =
2525   GBin.scrolled_window ~border_width:10
2526    ~packing:(vbox1#pack ~expand:true ~padding:5) () in
2527  let proofw =
2528   TermViewer.sequent_viewer ~width:400 ~height:275
2529    ~packing:(scrolled_window1#add) () in
2530 object(self)
2531  method proofw = (assert false : TermViewer.sequent_viewer)
2532  method content = vbox1
2533  method compute = (assert false : unit)
2534 end
2535 ;;
2536
2537 let empty_page = new empty_page;;
2538
2539 class notebook =
2540 object(self)
2541  val notebook = GPack.notebook ()
2542  val pages = ref []
2543  val mutable skip_switch_page_event = false 
2544  val mutable empty = true
2545  method notebook = notebook
2546  method add_page n =
2547   let new_page = new page () in
2548    empty <- false ;
2549    pages := !pages @ [n,lazy (setgoal n),new_page] ;
2550    notebook#append_page
2551     ~tab_label:((GMisc.label ~text:("?" ^ string_of_int n) ())#coerce)
2552     new_page#content#coerce
2553  method remove_all_pages ~skip_switch_page_event:skip =
2554   if empty then
2555    notebook#remove_page 0 (* let's remove the empty page *)
2556   else
2557    List.iter (function _ -> notebook#remove_page 0) !pages ;
2558   pages := [] ;
2559   skip_switch_page_event <- skip
2560  method set_current_page ~may_skip_switch_page_event n =
2561   let (_,_,page) = List.find (function (m,_,_) -> m=n) !pages in
2562    let new_page = notebook#page_num page#content#coerce in
2563     if may_skip_switch_page_event && new_page <> notebook#current_page then
2564      skip_switch_page_event <- true ;
2565     notebook#goto_page new_page
2566  method set_empty_page =
2567   empty <- true ;
2568   pages := [] ;
2569   notebook#append_page
2570    ~tab_label:((GMisc.label ~text:"No proof in progress" ())#coerce)
2571    empty_page#content#coerce
2572  method proofw =
2573   let (_,_,page) = List.nth !pages notebook#current_page in
2574    page#proofw
2575  initializer
2576   ignore
2577    (notebook#connect#switch_page
2578     (function i ->
2579       let skip = skip_switch_page_event in
2580        skip_switch_page_event <- false ;
2581        if not skip then
2582         try
2583          let (metano,setgoal,page) = List.nth !pages i in
2584           set_proof_engine_goal (Some metano) ;
2585           Lazy.force (page#compute) ;
2586           Lazy.force setgoal;
2587           if notify_hbugs_on_goal_change then
2588             Hbugs.notify ()
2589         with _ -> ()
2590     ))
2591 end
2592 ;;
2593
2594 let dump_environment () =
2595   try
2596     let oc = open_out (Helm_registry.get "gtoplevel.environment_file") in
2597     HelmLogger.log (`Msg (`T "Dumping environment ..."));
2598     CicEnvironment.dump_to_channel oc;
2599     HelmLogger.log (`Msg (`T "... done!")) ;
2600     close_out oc
2601   with exc ->
2602     HelmLogger.log
2603       (`Error (`T (Printf.sprintf "Dump failure, uncaught exception:%s"
2604         (Printexc.to_string exc))))
2605 ;;
2606 let restore_environment () =
2607   try
2608     let ic = open_in (Helm_registry.get "gtoplevel.environment_file") in
2609     HelmLogger.log (`Msg (`T "Restoring environment ... "));
2610     CicEnvironment.restore_from_channel ic;
2611     HelmLogger.log (`Msg (`T "... done!"));
2612     close_in ic
2613   with exc ->
2614     HelmLogger.log
2615       (`Error (`T (Printf.sprintf "Restore failure, uncaught exception:%s"
2616         (Printexc.to_string exc))))
2617 ;;
2618
2619 (* Main window *)
2620
2621 class rendering_window output (notebook : notebook) =
2622  let scratch_window = new scratch_window in
2623  let window =
2624   GWindow.window
2625    ~title:"gTopLevel - Helm's Proof Assistant"
2626    ~border_width:0 ~allow_shrink:false () in
2627  let vbox_for_menu = GPack.vbox ~packing:window#add () in
2628  (* menus *)
2629  let handle_box = GBin.handle_box ~border_width:2
2630   ~packing:(vbox_for_menu#pack ~padding:0) () in
2631  let menubar = GMenu.menu_bar ~packing:handle_box#add () in
2632  let factory0 = new GMenu.factory menubar in
2633  let accel_group = factory0#accel_group in
2634  (* file menu *)
2635  let file_menu = factory0#add_submenu "File" in
2636  let factory1 = new GMenu.factory file_menu ~accel_group in
2637  (* let export_to_postscript_menu_item = *)
2638  let _ =
2639   begin
2640    let _ =
2641     factory1#add_item "New Block of (Co)Inductive Definitions..."
2642      ~key:GdkKeysyms._B ~callback:new_inductive
2643    in
2644    let _ =
2645     factory1#add_item "New Proof or Definition..." ~key:GdkKeysyms._N
2646      ~callback:new_proof
2647    in
2648    let reopen_menu_item =
2649     factory1#add_item "Reopen a Finished Proof..." ~key:GdkKeysyms._R
2650      ~callback:open_
2651    in
2652    let qed_menu_item =
2653     factory1#add_item "Qed" ~key:GdkKeysyms._E ~callback:qed in
2654    ignore (factory1#add_separator ()) ;
2655    ignore
2656     (factory1#add_item "Load Unfinished Proof..." ~key:GdkKeysyms._L
2657       ~callback:load_unfinished_proof) ;
2658    let save_menu_item =
2659     factory1#add_item "Save Unfinished Proof" ~key:GdkKeysyms._S
2660       ~callback:save_unfinished_proof
2661    in
2662    ignore (factory1#add_separator ()) ;
2663    ignore (factory1#add_item "Clear Environment" ~callback:CicEnvironment.empty);
2664    ignore (factory1#add_item "Dump Environment" ~callback:dump_environment);
2665    ignore
2666     (factory1#add_item "Restore Environment" ~callback:restore_environment);
2667    ignore
2668     (save_set_sensitive := function b -> save_menu_item#misc#set_sensitive b);
2669    ignore (!save_set_sensitive false);
2670    ignore (qed_set_sensitive:=function b -> qed_menu_item#misc#set_sensitive b);
2671    ignore (!qed_set_sensitive false);
2672    ignore (factory1#add_separator ()) ;
2673    (*
2674    let export_to_postscript_menu_item =
2675     factory1#add_item "Export to PostScript..."
2676      ~callback:(export_to_postscript output) in
2677    *)
2678    ignore (factory1#add_separator ()) ;
2679    ignore
2680     (factory1#add_item "Exit" ~key:GdkKeysyms._Q ~callback:GMain.Main.quit) (*;
2681    export_to_postscript_menu_item *)
2682   end in
2683  (* edit menu *)
2684  let edit_menu = factory0#add_submenu "Edit Current Proof" in
2685  let factory2 = new GMenu.factory edit_menu ~accel_group in
2686  let focus_and_proveit_set_sensitive = ref (function _ -> assert false) in
2687  let proveit_menu_item =
2688   factory2#add_item "Prove It" ~key:GdkKeysyms._I
2689    ~callback:(function () -> proveit ();!focus_and_proveit_set_sensitive false)
2690  in
2691  let focus_menu_item =
2692   factory2#add_item "Focus" ~key:GdkKeysyms._F
2693    ~callback:(function () -> focus () ; !focus_and_proveit_set_sensitive false)
2694  in
2695  let _ =
2696   focus_and_proveit_set_sensitive :=
2697    function b ->
2698     proveit_menu_item#misc#set_sensitive b ;
2699     focus_menu_item#misc#set_sensitive b
2700  in
2701  let _ = !focus_and_proveit_set_sensitive false in
2702  (* edit term menu *)
2703  let edit_term_menu = factory0#add_submenu "Edit Term" in
2704  let factory5 = new GMenu.factory edit_term_menu ~accel_group in
2705  let check_menu_item =
2706   factory5#add_item "Check Term" ~key:GdkKeysyms._C
2707    ~callback:(check scratch_window) in
2708  let _ = check_menu_item#misc#set_sensitive false in
2709  (* search menu *)
2710  let search_menu = factory0#add_submenu "Search" in
2711  let factory4 = new GMenu.factory search_menu ~accel_group in
2712  let _ =
2713   factory4#add_item "Locate..." ~key:GdkKeysyms._T
2714    ~callback:locate in
2715  let searchPattern_menu_item =
2716   factory4#add_item "SearchPattern..." ~key:GdkKeysyms._D
2717    ~callback:completeSearchPattern in
2718  let _ = searchPattern_menu_item#misc#set_sensitive false in
2719  let show_menu_item =
2720   factory4#add_item "Show..." ~key:GdkKeysyms._H ~callback:show
2721  in
2722  let insert_query_item =
2723   factory4#add_item "Insert Query (Experts Only)..." ~key:GdkKeysyms._Y
2724    ~callback:insertQuery in
2725  (* hbugs menu *)
2726  let hbugs_menu = factory0#add_submenu "HBugs" in
2727  let factory6 = new GMenu.factory hbugs_menu ~accel_group in
2728  let _ =
2729   factory6#add_check_item
2730     ~active:false ~key:GdkKeysyms._F5 ~callback:Hbugs.toggle "HBugs enabled"
2731  in
2732  let _ =
2733   factory6#add_item ~key:GdkKeysyms._Return ~callback:Hbugs.notify
2734    "(Re)Submit status!"
2735  in
2736  let _ = factory6#add_separator () in
2737  let _ =
2738   factory6#add_item ~callback:Hbugs.start_web_services "Start Web Services"
2739  in
2740  let _ =
2741   factory6#add_item ~callback:Hbugs.stop_web_services "Stop Web Services"
2742  in
2743  (* settings menu *)
2744  let settings_menu = factory0#add_submenu "Settings" in
2745  let factory3 = new GMenu.factory settings_menu ~accel_group in
2746  let _ =
2747   factory3#add_item "Edit Aliases..." ~key:GdkKeysyms._A
2748    ~callback:edit_aliases in
2749  let _ =
2750   factory3#add_item "Clear Aliases" ~key:GdkKeysyms._K
2751    ~callback:clear_aliases in
2752  let autoitem =
2753   factory3#add_check_item "Auto disambiguation"
2754    ~callback:(fun checked -> auto_disambiguation := checked) in
2755  let _ = factory3#add_separator () in
2756  let _ =
2757   factory3#add_item "MathML Widget Preferences..." ~key:GdkKeysyms._P
2758    ~callback:(function _ -> (settings_window ())#show ()) in
2759  let _ = factory3#add_separator () in
2760  let _ =
2761   factory3#add_item "Reload Stylesheets"
2762    ~callback:
2763      (function _ ->
2764        ChosenTransformer.reload_stylesheets () ;
2765        if ProofEngine.get_proof () <> None then
2766         try
2767          refresh_goals notebook ;
2768          refresh_proof output
2769         with
2770            InvokeTactics.RefreshSequentException e ->
2771             HelmLogger.log
2772              (`Error (`T ("An error occurred while refreshing the " ^
2773                "sequent: " ^ Printexc.to_string e))) ;
2774            (*notebook#remove_all_pages ~skip_switch_page_event:false ;*)
2775            notebook#set_empty_page
2776          | InvokeTactics.RefreshProofException e ->
2777             HelmLogger.log
2778              (`Error (`T ("An error occurred while refreshing the proof: "               ^ Printexc.to_string e))) ;
2779             output#unload
2780      ) in
2781  (* accel group *)
2782  let _ = window#add_accel_group accel_group in
2783  (* end of menus *)
2784  let hbox0 =
2785   GPack.hbox
2786    ~packing:(vbox_for_menu#pack ~expand:true ~fill:true ~padding:5) () in
2787  let vbox =
2788   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
2789  let scrolled_window0 =
2790   GBin.scrolled_window ~border_width:10
2791    ~packing:(vbox#pack ~expand:true ~padding:5) () in
2792  let _ = scrolled_window0#add output#coerce in
2793  let frame =
2794   GBin.frame ~label:"Insert Term"
2795    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2796  let scrolled_window1 =
2797   GBin.scrolled_window ~border_width:5
2798    ~packing:frame#add () in
2799  let inputt =
2800   TermEditor'.term_editor
2801    mqi_handle
2802    ~width:400 ~height:100 ~packing:scrolled_window1#add ()
2803    ~isnotempty_callback:
2804     (function b ->
2805       check_menu_item#misc#set_sensitive b ;
2806       searchPattern_menu_item#misc#set_sensitive b) in
2807  let vboxl =
2808   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
2809  let _ =
2810   vboxl#pack ~expand:true ~fill:true ~padding:5 notebook#notebook#coerce in
2811  let frame =
2812   GBin.frame ~shadow_type:`IN ~packing:(vboxl#pack ~expand:true ~padding:5) ()
2813  in
2814  let _ =
2815    new HelmGtkLogger.html_logger
2816     ~width:400 ~height: 100 ~show:true ~packing:frame#add ()
2817  in
2818 object
2819  method inputt = inputt
2820  method output = (output : TermViewer.proof_viewer)
2821  method scratch_window = scratch_window
2822  method notebook = notebook
2823  method show = window#show
2824  method set_auto_disambiguation set = autoitem#set_active set
2825  initializer
2826   notebook#set_empty_page ;
2827   (*export_to_postscript_menu_item#misc#set_sensitive false ;*)
2828   check_term := (check_term_in_scratch scratch_window) ;
2829
2830   (* signal handlers here *)
2831   ignore(output#connect#selection_changed
2832    (function elem ->
2833      choose_selection output elem ;
2834      !focus_and_proveit_set_sensitive true
2835    )) ;
2836   ignore (output#connect#click (show_in_show_window_callback output)) ;
2837   let settings_window = new settings_window output scrolled_window0
2838    (*export_to_postscript_menu_item*)() (choose_selection output) in
2839   set_settings_window settings_window ;
2840   ignore(window#event#connect#delete (fun _ -> GMain.Main.quit () ; true ))
2841 end
2842
2843 (* MAIN *)
2844
2845 let initialize_everything () =
2846   let output = TermViewer.proof_viewer ~width:350 ~height:280 () in
2847   let notebook = new notebook in
2848   let rendering_window' = new rendering_window output notebook in
2849   rendering_window'#set_auto_disambiguation !auto_disambiguation;
2850   set_rendering_window rendering_window';
2851   let print_error_as_html prefix msg =
2852     HelmLogger.log (`Error (`T (prefix ^ msg)))
2853   in
2854   Gdome_xslt.setErrorCallback (Some (print_error_as_html "XSLT Error: "));
2855   Gdome_xslt.setDebugCallback
2856     (Some (print_error_as_html "XSLT Debug Message: "));
2857   rendering_window'#show () ;
2858   if restore_environment_on_boot &&
2859     Sys.file_exists (Helm_registry.get "gtoplevel.environment_file")
2860   then
2861     restore_environment ();
2862   GtkThread.main ()
2863 ;;
2864
2865 let main () =
2866  ignore (GtkMain.Main.init ()) ;
2867  initialize_everything () ;
2868  MQIC.close mqi_handle;
2869  Hbugs.quit ()
2870 ;;
2871
2872 try
2873   Sys.catch_break true;
2874   main ();
2875 with Sys.Break -> ()  (* exit nicely, invoking at_exit functions *)
2876