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