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