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