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