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