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