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