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