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