]> matita.cs.unibo.it Git - helm.git/blob - matita/matitaGui.ml
elim tactic: now takes a pattern instead of just a term
[helm.git] / matita / matitaGui.ml
1 (* Copyright (C) 2004-2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 open Printf
29
30 open MatitaGeneratedGui
31 open MatitaGtkMisc
32 open MatitaMisc
33
34 exception Found of int
35
36 let gui_instance = ref None
37
38 class type browserWin =
39   (* this class exists only because GEdit.combo_box_entry is not supported by
40    * lablgladecc :-(((( *)
41 object
42   inherit MatitaGeneratedGui.browserWin
43   method browserUri: GEdit.combo_box_entry
44 end
45
46 class console ~(buffer: GText.buffer) () =
47   object (self)
48     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
49     val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
50     val message_tag = buffer#create_tag []
51     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
52     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
53     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
54     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
55     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
56     method clear () =
57       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
58     method log_callback (tag: HLog.log_tag) s =
59       match tag with
60       | `Debug -> self#debug (s ^ "\n")
61       | `Error -> self#error (s ^ "\n")
62       | `Message -> self#message (s ^ "\n")
63       | `Warning -> self#warning (s ^ "\n")
64   end
65         
66 let clean_current_baseuri grafite_status = 
67     try  
68       let baseuri = GrafiteTypes.get_string_option grafite_status "baseuri" in
69       LibraryClean.clean_baseuris [baseuri]
70     with GrafiteTypes.Option_error _ -> ()
71
72 let ask_and_save_moo_if_needed parent fname lexicon_status grafite_status = 
73   let baseuri =
74    try Some (GrafiteTypes.get_string_option grafite_status "baseuri")
75    with GrafiteTypes.Option_error _ -> None
76   in
77   if (MatitaScript.current ())#eos &&
78      grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof &&
79      baseuri <> None
80   then
81    begin
82     let baseuri = match baseuri with Some b -> b | None -> assert false in
83     let moo_fname = 
84      LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri
85       ~writable:true in
86     let save () =
87       let metadata_fname =
88        LibraryMisc.metadata_file_of_baseuri 
89          ~must_exist:false ~baseuri ~writable:true in
90       let lexicon_fname =
91        LibraryMisc.lexicon_file_of_baseuri 
92          ~must_exist:false ~baseuri ~writable:true
93       in
94        GrafiteMarshal.save_moo moo_fname
95         grafite_status.GrafiteTypes.moo_content_rev;
96        LibraryNoDb.save_metadata metadata_fname
97         lexicon_status.LexiconEngine.metadata;
98        LexiconMarshal.save_lexicon lexicon_fname
99         lexicon_status.LexiconEngine.lexicon_content_rev
100     in
101      begin
102        let rc = 
103          MatitaGtkMisc.ask_confirmation
104          ~title:"A .moo can be generated"
105          ~message:(Printf.sprintf 
106            "%s can be generated for %s.\n<i>Should I generate it?</i>"
107            (Filename.basename moo_fname) (Filename.basename fname))
108          ~parent ()
109        in
110        let b = 
111          match rc with 
112          | `YES -> true 
113          | `NO -> false 
114          | `CANCEL -> raise MatitaTypes.Cancel 
115        in
116        if b then
117            save ()
118        else
119          clean_current_baseuri grafite_status
120      end
121    end
122   else
123     clean_current_baseuri grafite_status 
124     
125 let ask_unsaved parent =
126   MatitaGtkMisc.ask_confirmation 
127     ~parent ~title:"Unsaved work!" 
128     ~message:("Your work is <b>unsaved</b>!\n\n"^
129          "<i>Do you want to save the script before continuing?</i>")
130     ()
131
132 class interpErrorModel =
133   let cols = new GTree.column_list in
134   let id_col = cols#add Gobject.Data.string in
135   let dsc_col = cols#add Gobject.Data.string in
136   let interp_no_col = cols#add Gobject.Data.caml in
137   let tree_store = GTree.tree_store cols in
138   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
139   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
140   let id_view_col = GTree.view_column ~renderer:id_renderer () in
141   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
142   fun (tree_view: GTree.view) choices ->
143     object
144       initializer
145         tree_view#set_model (Some (tree_store :> GTree.model));
146         ignore (tree_view#append_column id_view_col);
147         ignore (tree_view#append_column dsc_view_col);
148         tree_store#clear ();
149         let idx1 = ref ~-1 in
150         List.iter
151           (fun _,lll ->
152             incr idx1;
153             let loc_row =
154              if List.length choices = 1 then
155               None
156              else
157               (let loc_row = tree_store#append () in
158                 begin
159                  match lll with
160                     [passes,envs_and_diffs,_,_] ->
161                       tree_store#set ~row:loc_row ~column:id_col
162                        ("Error location " ^ string_of_int (!idx1+1) ^
163                         ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
164                         " (in passes " ^
165                         String.concat " " (List.map string_of_int passes) ^
166                         ")");
167                       tree_store#set ~row:loc_row ~column:interp_no_col
168                        (!idx1,Some 0,None);
169                   | _ ->
170                     tree_store#set ~row:loc_row ~column:id_col
171                      ("Error location " ^ string_of_int (!idx1+1));
172                     tree_store#set ~row:loc_row ~column:interp_no_col
173                      (!idx1,None,None);
174                 end ;
175                 Some loc_row) in
176             let idx2 = ref ~-1 in
177              List.iter
178               (fun passes,envs_and_diffs,_,_ ->
179                 incr idx2;
180                 let msg_row =
181                  if List.length lll = 1 then
182                   loc_row
183                  else
184                   let msg_row = tree_store#append ?parent:loc_row () in
185                    (tree_store#set ~row:msg_row ~column:id_col
186                      ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
187                       string_of_int (!idx2+1) ^
188                       " (in passes " ^
189                       String.concat " " (List.map string_of_int passes) ^
190                       ")");
191                     tree_store#set ~row:msg_row ~column:interp_no_col
192                      (!idx1,Some !idx2,None);
193                     Some msg_row) in
194                 let idx3 = ref ~-1 in
195                 List.iter
196                  (fun (passes,env,_) ->
197                    incr idx3;
198                    let interp_row =
199                     match envs_and_diffs with
200                        _::_::_ ->
201                         let interp_row = tree_store#append ?parent:msg_row () in
202                         tree_store#set ~row:interp_row ~column:id_col
203                           ("Interpretation " ^ string_of_int (!idx3+1) ^
204                            " (in passes " ^
205                            String.concat " " (List.map string_of_int passes) ^
206                            ")");
207                         tree_store#set ~row:interp_row ~column:interp_no_col
208                          (!idx1,Some !idx2,Some !idx3);
209                         Some interp_row
210                      | [_] -> msg_row
211                      | [] -> assert false
212                    in
213                     List.iter
214                      (fun (_, id, dsc) ->
215                        let row = tree_store#append ?parent:interp_row () in
216                        tree_store#set ~row ~column:id_col id;
217                        tree_store#set ~row ~column:dsc_col dsc;
218                        tree_store#set ~row ~column:interp_no_col
219                         (!idx1,Some !idx2,Some !idx3)
220                      ) env
221                  ) envs_and_diffs
222               ) lll ;
223              if List.length lll > 1 then
224               HExtlib.iter_option
225                (fun p -> tree_view#expand_row (tree_store#get_path p))
226                loc_row
227           ) choices
228
229       method get_interp_no tree_path =
230         let iter = tree_store#get_iter tree_path in
231         tree_store#get ~row:iter ~column:interp_no_col
232     end
233
234
235 let rec interactive_error_interp ?(all_passes=false) (source_buffer:GSourceView.source_buffer) notify_exn offset errorll
236
237   assert (List.flatten errorll <> []);
238   let errorll' =
239    let remove_non_significant =
240      List.filter (fun (_env,_diff,_loc,_msg,significant) -> significant) in
241    if all_passes then errorll else
242      let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
243     (* We remove passes 1,2 and 5,6 *)
244      let res =
245       []::[]
246       ::(remove_non_significant (safe_list_nth errorll 2))
247       ::(remove_non_significant (safe_list_nth errorll 3))
248       ::[]::[]
249      in
250       if List.flatten res <> [] then res
251       else
252        (* all errors (if any) are not significant: we keep them *)
253        let res =
254         []::[]
255         ::(safe_list_nth errorll 2)
256         ::(safe_list_nth errorll 3)
257         ::[]::[]
258        in
259         if List.flatten res <> [] then
260          begin
261           HLog.warn
262            "All disambiguation errors are not significant. Showing them anyway." ;
263           res
264          end
265         else
266          begin
267           HLog.warn
268            "No errors in phases 2 and 3. Showing all errors in all phases" ;
269           errorll
270          end
271    in
272   let choices =
273    let pass = ref 0 in
274    List.flatten
275     (List.map
276       (fun l ->
277         incr pass;
278         List.map
279          (fun (env,diff,offset,msg,significant) ->
280            offset, [[!pass], [[!pass], env, diff], msg, significant]) l
281       ) errorll') in
282   (* Here we are doing a stable sort and list_uniq returns the latter
283      "equal" element. I.e. we are showing the error corresponding to the
284      most advanced disambiguation pass *)
285   let choices =
286    let choices_compare (o1,_) (o2,_) = compare o1 o2 in
287    let choices_compare_by_passes (p1,_,_,_) (p2,_,_,_) =
288     compare p1 p2 in
289    let rec uniq =
290     function
291        [] -> []
292      | h::[] -> [h]
293      | (o1,res1)::(o2,res2)::tl when o1 = o2 ->
294         let merge_by_name errors =
295          let merge_by_env errors =
296           let choices_compare_by_env (_,e1,_) (_,e2,_) = compare e1 e2 in
297           let choices_compare_by_passes (p1,_,_) (p2,_,_) =
298            compare p1 p2 in
299           let rec uniq_by_env =
300            function
301               [] -> []
302             | h::[] -> [h]
303             | (p1,e1,_)::(p2,e2,d2)::tl when e1 = e2 ->
304                 uniq_by_env ((p1@p2,e2,d2) :: tl) 
305             | h1::tl -> h1 :: uniq_by_env tl
306           in
307            List.sort choices_compare_by_passes
308             (uniq_by_env (List.stable_sort choices_compare_by_env errors))
309          in
310          let choices_compare_by_msg (_,_,m1,_) (_,_,m2,_) =
311           compare (Lazy.force m1) (Lazy.force m2) in
312          let rec uniq_by_msg =
313           function
314              [] -> []
315            | h::[] -> [h]
316            | (p1,i1,m1,s1)::(p2,i2,m2,s2)::tl
317              when Lazy.force m1 = Lazy.force m2 && s1 = s2 ->
318                uniq_by_msg ((p1@p2,merge_by_env (i1@i2),m2,s2) :: tl)
319            | h1::tl -> h1 :: uniq_by_msg tl
320          in
321           List.sort choices_compare_by_msg
322            (uniq_by_msg (List.stable_sort choices_compare_by_msg errors))
323         in
324          let res = merge_by_name (res1@res2) in
325           uniq ((o1,res) :: tl)
326      | h1::tl -> h1 :: uniq tl
327    in
328    (* Errors in phase 3 that are not also in phase 4 are filtered out *)
329    let filter_phase_3 choices =
330     if all_passes then choices
331     else
332      let filter =
333       HExtlib.filter_map
334        (function
335            (loffset,messages) ->
336               let filtered_messages =
337                HExtlib.filter_map
338                 (function
339                     [3],_,_,_ -> None
340                   | item -> Some item
341                 ) messages
342               in
343                if filtered_messages = [] then
344                 None
345                else
346                 Some (loffset,filtered_messages))
347      in
348       filter choices
349    in
350     filter_phase_3
351      (List.map (fun o,l -> o,List.sort choices_compare_by_passes l)
352        (uniq (List.stable_sort choices_compare choices)))
353   in
354    match choices with
355       [] -> assert false
356     | [loffset,[_,envs_and_diffs,msg,significant]] ->
357         let _,env,diff = List.hd envs_and_diffs in
358          notify_exn
359           (GrafiteDisambiguator.DisambiguationError
360             (offset,[[env,diff,loffset,msg,significant]]));
361     | _::_ ->
362        let dialog = new disambiguationErrors () in
363        dialog#check_widgets ();
364        if all_passes then
365         dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
366        let model = new interpErrorModel dialog#treeview choices in
367        dialog#disambiguationErrors#set_title "Disambiguation error";
368        dialog#disambiguationErrorsLabel#set_label
369         "Click on an error to see the corresponding message:";
370        ignore (dialog#treeview#connect#cursor_changed
371         (fun _ ->
372           let tree_path =
373            match fst (dialog#treeview#get_cursor ()) with
374               None -> assert false
375            | Some tp -> tp in
376           let idx1,idx2,idx3 = model#get_interp_no tree_path in
377           let loffset,lll = List.nth choices idx1 in
378           let _,envs_and_diffs,msg,significant =
379            match idx2 with
380               Some idx2 -> List.nth lll idx2
381             | None ->
382                 [],[],lazy "Multiple error messages. Please select one.",true
383           in
384           let _,env,diff =
385            match idx3 with
386               Some idx3 -> List.nth envs_and_diffs idx3
387             | None -> [],[],[] (* dymmy value, used *) in
388           let script = MatitaScript.current () in
389           let error_tag = script#error_tag in
390            source_buffer#remove_tag error_tag
391              ~start:source_buffer#start_iter
392              ~stop:source_buffer#end_iter;
393            notify_exn
394             (GrafiteDisambiguator.DisambiguationError
395               (offset,[[env,diff,loffset,msg,significant]]))
396            ));
397        let return _ =
398          dialog#disambiguationErrors#destroy ();
399          GMain.Main.quit ()
400        in
401        let fail _ = return () in
402        ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
403        connect_button dialog#disambiguationErrorsOkButton
404         (fun _ ->
405           let tree_path =
406            match fst (dialog#treeview#get_cursor ()) with
407               None -> assert false
408            | Some tp -> tp in
409           let idx1,idx2,idx3 = model#get_interp_no tree_path in
410           let diff =
411            match idx2,idx3 with
412               Some idx2, Some idx3 ->
413                let _,lll = List.nth choices idx1 in
414                let _,envs_and_diffs,_,_ = List.nth lll idx2 in
415                let _,_,diff = List.nth envs_and_diffs idx3 in
416                 diff
417             | _,_ -> assert false
418           in
419            let newtxt =
420             String.concat "\n"
421              ("" ::
422                List.map
423                 (fun k,value ->
424                   DisambiguatePp.pp_environment
425                    (DisambiguateTypes.Environment.add k value
426                      DisambiguateTypes.Environment.empty))
427                 diff) ^ "\n"
428            in
429             source_buffer#insert
430              ~iter:
431                (source_buffer#get_iter_at_mark
432                 (`NAME "beginning_of_statement")) newtxt ;
433             return ()
434         );
435        connect_button dialog#disambiguationErrorsMoreErrors
436         (fun _ -> return () ;
437           interactive_error_interp ~all_passes:true source_buffer notify_exn offset
438            errorll);
439        connect_button dialog#disambiguationErrorsCancelButton fail;
440        dialog#disambiguationErrors#show ();
441        GtkThread.main ()
442
443
444 (** Selection handling
445  * Two clipboards are used: "clipboard" and "primary".
446  * "primary" is used by X, when you hit the middle button mouse is content is
447  *    pasted between applications. In Matita this selection always contain the
448  *    textual version of the selected term.
449  * "clipboard" is used inside Matita only and support ATM two different targets:
450  *    "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
451  *    be added
452  *)
453
454 class gui () =
455     (* creation order _is_ relevant for windows placement *)
456   let main = new mainWin () in
457   let fileSel = new fileSelectionWin () in
458   let findRepl = new findReplWin () in
459   let develList = new develListWin () in
460   let newDevel = new newDevelWin () in
461   let keyBindingBoxes = (* event boxes which should receive global key events *)
462     [ main#mainWinEventBox ]
463   in
464   let console = new console ~buffer:main#logTextView#buffer () in
465   let (source_view: GSourceView.source_view) =
466     GSourceView.source_view
467       ~auto_indent:true
468       ~insert_spaces_instead_of_tabs:true ~tabs_width:2
469       ~margin:80 ~show_margin:true
470       ~smart_home_end:true
471       ~packing:main#scriptScrolledWin#add
472       ()
473   in
474   let default_font_size =
475     Helm_registry.get_opt_default Helm_registry.int
476       ~default:BuildTimeConf.default_font_size "matita.font_size"
477   in
478   let source_buffer = source_view#source_buffer in
479   object (self)
480     val mutable chosen_file = None
481     val mutable _ok_not_exists = false
482     val mutable _only_directory = false
483     val mutable script_fname = None
484     val mutable font_size = default_font_size
485     val mutable next_devel_must_contain = None
486     val mutable next_ligatures = []
487     val clipboard = GData.clipboard Gdk.Atom.clipboard
488     val primary = GData.clipboard Gdk.Atom.primary
489    
490     initializer
491         (* glade's check widgets *)
492       List.iter (fun w -> w#check_widgets ())
493         (let c w = (w :> <check_widgets: unit -> unit>) in
494         [ c fileSel; c main; c findRepl]);
495         (* key bindings *)
496       List.iter (* global key bindings *)
497         (fun (key, callback) -> self#addKeyBinding key callback)
498 (*
499         [ GdkKeysyms._F3,
500             toggle_win ~check:main#showProofMenuItem proof#proofWin;
501           GdkKeysyms._F4,
502             toggle_win ~check:main#showCheckMenuItem check#checkWin;
503 *)
504         [ ];
505         (* about win *)
506       let parse_txt_file file =
507        let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
508        let l_rev = ref [] in
509        try
510         while true do
511          l_rev := input_line ch :: !l_rev;
512         done;
513         assert false
514        with
515         End_of_file ->
516          close_in ch;
517          List.rev !l_rev in 
518       let about_dialog =
519        GWindow.about_dialog
520         ~authors:(parse_txt_file "AUTHORS")
521         (*~comments:"comments"*)
522         ~copyright:"Copyright (C) 2005, the HELM team"
523         ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
524         ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
525         ~name:"Matita"
526         ~version:BuildTimeConf.version
527         ~website:"http://helm.cs.unibo.it"
528         ()
529       in
530       connect_menu_item main#contentsMenuItem (fun () ->
531         let cmd =
532           sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
533         in
534         ignore (Sys.command cmd));
535       connect_menu_item main#aboutMenuItem about_dialog#present;
536         (* findRepl win *)
537       let show_find_Repl () = 
538         findRepl#toplevel#misc#show ();
539         findRepl#toplevel#misc#grab_focus ()
540       in
541       let hide_find_Repl () = findRepl#toplevel#misc#hide () in
542       let find_forward _ = 
543           let highlight start end_ =
544             source_buffer#move_mark `INSERT ~where:start;
545             source_buffer#move_mark `SEL_BOUND ~where:end_;
546             source_view#scroll_mark_onscreen `INSERT
547           in
548           let text = findRepl#findEntry#text in
549           let iter = source_buffer#get_iter `SEL_BOUND in
550           match iter#forward_search text with
551           | None -> 
552               (match source_buffer#start_iter#forward_search text with
553               | None -> ()
554               | Some (start,end_) -> highlight start end_)
555           | Some (start,end_) -> highlight start end_ 
556       in
557       let replace _ =
558         let text = findRepl#replaceEntry#text in
559         let ins = source_buffer#get_iter `INSERT in
560         let sel = source_buffer#get_iter `SEL_BOUND in
561         if ins#compare sel < 0 then 
562           begin
563             ignore(source_buffer#delete_selection ());
564             source_buffer#insert text
565           end
566       in
567       connect_button findRepl#findButton find_forward;
568       connect_button findRepl#findReplButton replace;
569       connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
570       ignore(findRepl#toplevel#event#connect#delete 
571         ~callback:(fun _ -> hide_find_Repl ();true));
572       let safe_undo =
573        fun () ->
574         (* phase 1: we save the actual status of the marks and we undo *)
575         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
576         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
577         let locked_iter_offset = locked_iter#offset in
578         let mark2 =
579          `MARK
580            (source_view#buffer#create_mark ~name:"lock_point"
581              ~left_gravity:true locked_iter) in
582         source_view#source_buffer#undo ();
583         (* phase 2: we save the cursor position and we redo, restoring
584            the previous status of all the marks *)
585         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
586         let mark =
587          `MARK
588            (source_view#buffer#create_mark ~name:"undo_point"
589              ~left_gravity:true cursor_iter)
590         in
591          source_view#source_buffer#redo ();
592          let mark_iter = source_view#buffer#get_iter_at_mark mark in
593          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
594          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
595           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
596           source_view#buffer#delete_mark mark;
597           source_view#buffer#delete_mark mark2;
598           (* phase 3: if after the undo the cursor was in the locked area,
599              then we move it there again and we perform a goto *)
600           if mark_iter#offset < locked_iter_offset then
601            begin
602             source_view#buffer#move_mark `INSERT ~where:mark_iter;
603             (MatitaScript.current ())#goto `Cursor ();
604            end;
605           (* phase 4: we perform again the undo. This time we are sure that
606              the text to undo is not locked *)
607           source_view#source_buffer#undo ();
608           source_view#misc#grab_focus () in
609       let safe_redo =
610        fun () ->
611         (* phase 1: we save the actual status of the marks, we redo and
612            we undo *)
613         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
614         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
615         let locked_iter_offset = locked_iter#offset in
616         let mark2 =
617          `MARK
618            (source_view#buffer#create_mark ~name:"lock_point"
619              ~left_gravity:true locked_iter) in
620         source_view#source_buffer#redo ();
621         source_view#source_buffer#undo ();
622         (* phase 2: we save the cursor position and we restore
623            the previous status of all the marks *)
624         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
625         let mark =
626          `MARK
627            (source_view#buffer#create_mark ~name:"undo_point"
628              ~left_gravity:true cursor_iter)
629         in
630          let mark_iter = source_view#buffer#get_iter_at_mark mark in
631          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
632          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
633           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
634           source_view#buffer#delete_mark mark;
635           source_view#buffer#delete_mark mark2;
636           (* phase 3: if after the undo the cursor is in the locked area,
637              then we move it there again and we perform a goto *)
638           if mark_iter#offset < locked_iter_offset then
639            begin
640             source_view#buffer#move_mark `INSERT ~where:mark_iter;
641             (MatitaScript.current ())#goto `Cursor ();
642            end;
643           (* phase 4: we perform again the redo. This time we are sure that
644              the text to redo is not locked *)
645           source_view#source_buffer#redo ();
646           source_view#misc#grab_focus ()
647       in
648       connect_menu_item main#undoMenuItem safe_undo;
649       ignore(source_view#source_buffer#connect#can_undo
650         ~callback:main#undoMenuItem#misc#set_sensitive);
651       connect_menu_item main#redoMenuItem safe_redo;
652       ignore(source_view#source_buffer#connect#can_redo
653         ~callback:main#redoMenuItem#misc#set_sensitive);
654       ignore(source_view#connect#after#populate_popup
655        ~callback:(fun pre_menu ->
656          let menu = new GMenu.menu pre_menu in
657          let menuItems = menu#children in
658          let undoMenuItem, redoMenuItem =
659           match menuItems with
660              [undo;redo;sep1;cut;copy;paste;delete;sep2;
661               selectall;sep3;inputmethod;insertunicodecharacter] ->
662                 List.iter menu#remove [ copy; cut; delete; paste ];
663                 undo,redo
664            | _ -> assert false in
665          let add_menu_item =
666            let i = ref 2 in (* last occupied position *)
667            fun ?label ?stock () ->
668              incr i;
669              GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
670               ()
671          in
672          let copy = add_menu_item ~stock:`COPY () in
673          let cut = add_menu_item ~stock:`CUT () in
674          let delete = add_menu_item ~stock:`DELETE () in
675          let paste = add_menu_item ~stock:`PASTE () in
676          let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
677          copy#misc#set_sensitive self#canCopy;
678          cut#misc#set_sensitive self#canCut;
679          delete#misc#set_sensitive self#canDelete;
680          paste#misc#set_sensitive self#canPaste;
681          paste_pattern#misc#set_sensitive self#canPastePattern;
682          connect_menu_item copy self#copy;
683          connect_menu_item cut self#cut;
684          connect_menu_item delete self#delete;
685          connect_menu_item paste self#paste;
686          connect_menu_item paste_pattern self#pastePattern;
687          let new_undoMenuItem =
688           GMenu.image_menu_item
689            ~image:(GMisc.image ~stock:`UNDO ())
690            ~use_mnemonic:true
691            ~label:"_Undo"
692            ~packing:(menu#insert ~pos:0) () in
693          new_undoMenuItem#misc#set_sensitive
694           (undoMenuItem#misc#get_flag `SENSITIVE);
695          menu#remove (undoMenuItem :> GMenu.menu_item);
696          connect_menu_item new_undoMenuItem safe_undo;
697          let new_redoMenuItem =
698           GMenu.image_menu_item
699            ~image:(GMisc.image ~stock:`REDO ())
700            ~use_mnemonic:true
701            ~label:"_Redo"
702            ~packing:(menu#insert ~pos:1) () in
703          new_redoMenuItem#misc#set_sensitive
704           (redoMenuItem#misc#get_flag `SENSITIVE);
705           menu#remove (redoMenuItem :> GMenu.menu_item);
706           connect_menu_item new_redoMenuItem safe_redo));
707
708       connect_menu_item main#editMenu (fun () ->
709         main#copyMenuItem#misc#set_sensitive self#canCopy;
710         main#cutMenuItem#misc#set_sensitive self#canCut;
711         main#deleteMenuItem#misc#set_sensitive self#canDelete;
712         main#pasteMenuItem#misc#set_sensitive self#canPaste;
713         main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
714       connect_menu_item main#copyMenuItem self#copy;
715       connect_menu_item main#cutMenuItem self#cut;
716       connect_menu_item main#deleteMenuItem self#delete;
717       connect_menu_item main#pasteMenuItem self#paste;
718       connect_menu_item main#pastePatternMenuItem self#pastePattern;
719       connect_menu_item main#selectAllMenuItem (fun () ->
720         source_buffer#move_mark `INSERT source_buffer#start_iter;
721         source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
722       connect_menu_item main#findReplMenuItem show_find_Repl;
723       connect_menu_item main#externalEditorMenuItem self#externalEditor;
724       connect_menu_item main#ligatureButton self#nextLigature;
725       ignore (findRepl#findEntry#connect#activate find_forward);
726         (* interface lockers *)
727       let lock_world _ =
728         main#buttonsToolbar#misc#set_sensitive false;
729         develList#buttonsHbox#misc#set_sensitive false;
730         main#scriptMenu#misc#set_sensitive false;
731         source_view#set_editable false
732       in
733       let unlock_world _ =
734         main#buttonsToolbar#misc#set_sensitive true;
735         develList#buttonsHbox#misc#set_sensitive true;
736         main#scriptMenu#misc#set_sensitive true;
737         source_view#set_editable true;
738         (*The next line seems sufficient to avoid some unknown race condition *)
739         GtkThread.sync (fun () -> ()) ()
740       in
741       let worker_thread = ref None in
742       let notify_exn exn =
743        let floc, msg = MatitaExcPp.to_string exn in
744         begin
745          match floc with
746             None -> ()
747           | Some floc ->
748              let (x, y) = HExtlib.loc_of_floc floc in
749              let script = MatitaScript.current () in
750              let locked_mark = script#locked_mark in
751              let error_tag = script#error_tag in
752              let baseoffset =
753               (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
754              let x' = baseoffset + x in
755              let y' = baseoffset + y in
756              let x_iter = source_buffer#get_iter (`OFFSET x') in
757              let y_iter = source_buffer#get_iter (`OFFSET y') in
758              source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
759              let id = ref None in
760              id := Some (source_buffer#connect#changed ~callback:(fun () ->
761                source_buffer#remove_tag error_tag
762                  ~start:source_buffer#start_iter
763                  ~stop:source_buffer#end_iter;
764                match !id with
765                | None -> assert false (* a race condition occurred *)
766                | Some id ->
767                    (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
768              source_buffer#place_cursor
769               (source_buffer#get_iter (`OFFSET x'));
770         end;
771         HLog.error msg in
772       let locker f () =
773        let thread_main =
774         fun () -> 
775           lock_world ();
776           try
777            f ();
778            unlock_world ()
779           with
780            | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
781               (try
782                 interactive_error_interp source_buffer notify_exn offset
783                  errorll
784                with
785                 exc -> notify_exn exc);
786               unlock_world ()
787            | exc ->
788               notify_exn exc;
789               unlock_world ()
790        in
791         worker_thread := Some (Thread.create thread_main ()) in
792       let kill_worker =
793        (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
794        let interrupt = ref None in
795        let old_callback = ref (function _ -> ()) in
796        let force_interrupt n =
797          (* This function is called just before the thread's timeslice ends *)
798          !old_callback n;
799          if Some(Thread.id(Thread.self())) = !interrupt then
800           (interrupt := None; raise Sys.Break) in
801        let _ =
802         match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
803            Sys.Signal_handle f -> old_callback := f
804          | Sys.Signal_ignore
805          | Sys.Signal_default -> assert false
806        in
807         fun () ->
808          match !worker_thread with
809             None -> assert false
810           | Some t -> interrupt := Some (Thread.id t) in
811       let keep_focus f =
812         fun () ->
813          try
814           f (); source_view#misc#grab_focus ()
815          with
816           exc -> source_view#misc#grab_focus (); raise exc in
817         (* developments win *)
818       let model = 
819         new MatitaGtkMisc.multiStringListModel 
820           ~cols:2 develList#developmentsTreeview
821       in
822       let refresh_devels_win () =
823         model#list_store#clear ();
824         List.iter 
825           (fun (name, root) -> model#easy_mappend [name;root]) 
826           (MatitamakeLib.list_known_developments ())
827       in
828       let get_devel_selected () = 
829         match model#easy_mselection () with
830         | [[name;_]] -> MatitamakeLib.development_for_name name
831         | _ -> None
832       in
833       let refresh () = 
834         while Glib.Main.pending () do 
835           ignore(Glib.Main.iteration false); 
836         done
837       in
838       connect_button develList#newButton
839         (fun () -> 
840           next_devel_must_contain <- None;
841           newDevel#toplevel#misc#show());
842       connect_button develList#deleteButton
843         (locker (fun () -> 
844           (match get_devel_selected () with
845           | None -> ()
846           | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
847           refresh_devels_win ()));
848       connect_button develList#buildButton 
849         (locker (fun () -> 
850           match get_devel_selected () with
851           | None -> ()
852           | Some d -> 
853               let build = locker 
854                 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
855               in
856               ignore(build ())));
857       connect_button develList#cleanButton 
858         (locker (fun () -> 
859           match get_devel_selected () with
860           | None -> ()
861           | Some d -> 
862               let clean = locker 
863                 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
864               in
865               ignore(clean ())));
866       connect_button develList#publishButton 
867         (locker (fun () -> 
868           match get_devel_selected () with
869           | None -> ()
870           | Some d -> 
871               let publish = locker (fun () ->
872                 MatitamakeLib.publish_development_in_bg refresh d) in
873               ignore(publish ())));
874       connect_button develList#graphButton (fun () -> 
875         match get_devel_selected () with
876         | None -> ()
877         | Some d ->
878             (match MatitamakeLib.dot_for_development d with
879             | None -> ()
880             | Some _ ->
881                 let browser = MatitaMathView.cicBrowser () in
882                 browser#load (`Development
883                   (MatitamakeLib.name_for_development d))));
884       connect_button develList#closeButton 
885         (fun () -> develList#toplevel#misc#hide());
886       ignore(develList#toplevel#event#connect#delete 
887         (fun _ -> develList#toplevel#misc#hide();true));
888       connect_menu_item main#developmentsMenuItem
889         (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
890       
891         (* add development win *)
892       let check_if_root_contains root =
893         match next_devel_must_contain with
894         | None -> true
895         | Some path -> 
896             let is_prefix_of d1 d2 =
897               let len1 = String.length d1 in
898               let len2 = String.length d2 in
899               if len2 < len1 then 
900                 false
901               else
902                 let pref = String.sub d2 0 len1 in
903                 pref = d1
904             in
905             is_prefix_of root path
906       in
907       connect_button newDevel#addButton 
908        (fun () -> 
909           let name = newDevel#nameEntry#text in
910           let root = newDevel#rootEntry#text in
911           if check_if_root_contains root then
912             begin
913               ignore (MatitamakeLib.initialize_development name root);
914               refresh_devels_win ();
915               newDevel#nameEntry#set_text "";
916               newDevel#rootEntry#set_text "";
917               newDevel#toplevel#misc#hide()
918             end
919           else
920             HLog.error ("The selected root does not contain " ^ 
921               match next_devel_must_contain with 
922               | Some x -> x 
923               | _ -> assert false));
924       connect_button newDevel#chooseRootButton 
925        (fun () ->
926          let path = self#chooseDir () in
927          match path with
928          | Some path -> newDevel#rootEntry#set_text path
929          | None -> ());
930       connect_button newDevel#cancelButton 
931        (fun () -> newDevel#toplevel#misc#hide ());
932       ignore(newDevel#toplevel#event#connect#delete 
933         (fun _ -> newDevel#toplevel#misc#hide();true));
934       
935         (* file selection win *)
936       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
937       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
938         let return r =
939           chosen_file <- r;
940           fileSel#fileSelectionWin#misc#hide ();
941           GMain.Main.quit ()
942         in
943         match event with
944         | `OK ->
945             let fname = fileSel#fileSelectionWin#filename in
946             if Sys.file_exists fname then
947               begin
948                 if HExtlib.is_regular fname && not (_only_directory) then 
949                   return (Some fname) 
950                 else if _only_directory && HExtlib.is_dir fname then 
951                   return (Some fname)
952               end
953             else
954               begin
955                 if _ok_not_exists then 
956                   return (Some fname)
957               end
958         | `CANCEL -> return None
959         | `HELP -> ()
960         | `DELETE_EVENT -> return None));
961         (* menus *)
962       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
963         (* console *)
964       let adj = main#logScrolledWin#vadjustment in
965         ignore (adj#connect#changed
966                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
967       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
968         (* toolbar *)
969       let module A = GrafiteAst in
970       let hole = CicNotationPt.UserInput in
971       let loc = HExtlib.dummy_floc in
972       let tac ast _ =
973         if (MatitaScript.current ())#onGoingProof () then
974           (MatitaScript.current ())#advance
975             ~statement:("\n"
976               ^ GrafiteAstPp.pp_tactical ~term_pp:CicNotationPp.pp_term
977                 ~lazy_term_pp:CicNotationPp.pp_term (A.Tactic (loc, ast)))
978             ()
979       in
980       let tac_w_term ast _ =
981         if (MatitaScript.current ())#onGoingProof () then
982           let buf = source_buffer in
983           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
984             ("\n"
985             ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
986               ~lazy_term_pp:CicNotationPp.pp_term ast)
987       in
988       let tbar = main in
989       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
990       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
991       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
992       connect_button tbar#elimButton (tac_w_term
993         (A.Elim (loc, (Some hole, [], Some CicNotationPt.UserInput), None, None, [])));
994       connect_button tbar#elimTypeButton (tac_w_term
995         (A.ElimType (loc, hole, None, None, [])));
996       connect_button tbar#splitButton (tac (A.Split loc));
997       connect_button tbar#leftButton (tac (A.Left loc));
998       connect_button tbar#rightButton (tac (A.Right loc));
999       connect_button tbar#existsButton (tac (A.Exists loc));
1000       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
1001       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
1002       connect_button tbar#transitivityButton
1003         (tac_w_term (A.Transitivity (loc, hole)));
1004       connect_button tbar#assumptionButton (tac (A.Assumption loc));
1005       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
1006       connect_button tbar#autoButton (tac (A.Auto (loc,[])));
1007       MatitaGtkMisc.toggle_widget_visibility
1008        ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
1009        ~check:main#tacticsBarMenuItem;
1010       let module Hr = Helm_registry in
1011       if
1012         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
1013       then 
1014         main#tacticsBarMenuItem#set_active false;
1015       MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
1016         ~callback:(function 
1017           | true -> main#toplevel#fullscreen () 
1018           | false -> main#toplevel#unfullscreen ());
1019       main#fullscreenMenuItem#set_active false;
1020       MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
1021         ~callback:(function
1022           | true ->
1023               CicNotation.set_active_notations
1024                 (List.map fst (CicNotation.get_all_notations ()))
1025           | false ->
1026               CicNotation.set_active_notations []);
1027       MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
1028         ~callback:(fun enabled -> Acic2content.hide_coercions := enabled);
1029       MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
1030         ~callback:(fun enabled ->
1031           Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
1032       if not (Helm_registry.has "matita.paste_unicode_as_tex") then
1033         Helm_registry.set_bool "matita.paste_unicode_as_tex" true;
1034       main#unicodeAsTexMenuItem#set_active
1035         (Helm_registry.get_bool "matita.paste_unicode_as_tex");
1036         (* log *)
1037       HLog.set_log_callback self#console#log_callback;
1038       GtkSignal.user_handler :=
1039         (function 
1040         | MatitaScript.ActionCancelled s -> HLog.error s
1041         | exn ->
1042           if not (Helm_registry.get_bool "matita.debug") then
1043            notify_exn exn
1044           else raise exn);
1045         (* script *)
1046       ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
1047       let _ =
1048         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
1049         | None ->
1050             HLog.warn (sprintf "can't load language file %s"
1051               BuildTimeConf.lang_file)
1052         | Some matita_lang ->
1053             source_buffer#set_language matita_lang;
1054             source_buffer#set_highlight true
1055       in
1056       let s () = MatitaScript.current () in
1057       let disableSave () =
1058         script_fname <- None;
1059         main#saveMenuItem#misc#set_sensitive false
1060       in
1061       let saveAsScript () =
1062         let script = s () in
1063         match self#chooseFile ~ok_not_exists:true () with
1064         | Some f -> 
1065               script#assignFileName f;
1066               script#saveToFile (); 
1067               console#message ("'"^f^"' saved.\n");
1068               self#_enableSaveTo f
1069         | None -> ()
1070       in
1071       let saveScript () =
1072         match script_fname with
1073         | None -> saveAsScript ()
1074         | Some f -> 
1075               (s ())#assignFileName f;
1076               (s ())#saveToFile ();
1077               console#message ("'"^f^"' saved.\n");
1078       in
1079       let abandon_script () =
1080         let lexicon_status = (s ())#lexicon_status in
1081         let grafite_status = (s ())#grafite_status in
1082         if source_view#buffer#modified then
1083           (match ask_unsaved main#toplevel with
1084           | `YES -> saveScript ()
1085           | `NO -> ()
1086           | `CANCEL -> raise MatitaTypes.Cancel);
1087         (match script_fname with
1088         | None -> ()
1089         | Some fname ->
1090            ask_and_save_moo_if_needed main#toplevel fname
1091             lexicon_status grafite_status);
1092       in
1093       let loadScript () =
1094         let script = s () in 
1095         try 
1096           match self#chooseFile () with
1097           | Some f -> 
1098               abandon_script ();
1099               script#reset (); 
1100               script#assignFileName f;
1101               source_view#source_buffer#begin_not_undoable_action ();
1102               script#loadFromFile f; 
1103               source_view#source_buffer#end_not_undoable_action ();
1104               console#message ("'"^f^"' loaded.\n");
1105               self#_enableSaveTo f
1106           | None -> ()
1107         with MatitaTypes.Cancel -> ()
1108       in
1109       let newScript () = 
1110         abandon_script ();
1111         source_view#source_buffer#begin_not_undoable_action ();
1112         (s ())#reset (); 
1113         (s ())#template (); 
1114         source_view#source_buffer#end_not_undoable_action ();
1115         disableSave ();
1116         script_fname <- None
1117       in
1118       let cursor () =
1119         source_buffer#place_cursor
1120           (source_buffer#get_iter_at_mark (`NAME "locked")) in
1121       let advance _ = (MatitaScript.current ())#advance (); cursor () in
1122       let retract _ = (MatitaScript.current ())#retract (); cursor () in
1123       let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
1124       let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
1125       let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
1126       let advance = locker (keep_focus advance) in
1127       let retract = locker (keep_focus retract) in
1128       let top = locker (keep_focus top) in
1129       let bottom = locker (keep_focus bottom) in
1130       let jump = locker (keep_focus jump) in
1131         (* quit *)
1132       self#setQuitCallback (fun () -> 
1133         let lexicon_status = (MatitaScript.current ())#lexicon_status in
1134         let grafite_status = (MatitaScript.current ())#grafite_status in
1135         if source_view#buffer#modified then
1136           begin
1137             let rc = ask_unsaved main#toplevel in 
1138             try
1139               match rc with
1140               | `YES -> saveScript ();
1141                         if not source_view#buffer#modified then
1142                           begin
1143                             (match script_fname with
1144                             | None -> ()
1145                             | Some fname -> 
1146                                ask_and_save_moo_if_needed main#toplevel
1147                                 fname lexicon_status grafite_status);
1148                           GMain.Main.quit ()
1149                           end
1150               | `NO -> GMain.Main.quit ()
1151               | `CANCEL -> raise MatitaTypes.Cancel
1152             with MatitaTypes.Cancel -> ()
1153           end 
1154         else 
1155           begin  
1156             (match script_fname with
1157             | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
1158             | Some fname ->
1159                 try
1160                   ask_and_save_moo_if_needed main#toplevel fname lexicon_status
1161                    grafite_status;
1162                   GMain.Main.quit ()
1163                 with MatitaTypes.Cancel -> ())
1164           end);
1165       connect_button main#scriptAdvanceButton advance;
1166       connect_button main#scriptRetractButton retract;
1167       connect_button main#scriptTopButton top;
1168       connect_button main#scriptBottomButton bottom;
1169       connect_button main#scriptJumpButton jump;
1170       connect_button main#scriptAbortButton kill_worker;
1171       connect_menu_item main#scriptAdvanceMenuItem advance;
1172       connect_menu_item main#scriptRetractMenuItem retract;
1173       connect_menu_item main#scriptTopMenuItem top;
1174       connect_menu_item main#scriptBottomMenuItem bottom;
1175       connect_menu_item main#scriptJumpMenuItem jump;
1176       connect_menu_item main#openMenuItem   loadScript;
1177       connect_menu_item main#saveMenuItem   saveScript;
1178       connect_menu_item main#saveAsMenuItem saveAsScript;
1179       connect_menu_item main#newMenuItem    newScript;
1180          (* script monospace font stuff *)  
1181       self#updateFontSize ();
1182         (* debug menu *)
1183       main#debugMenu#misc#hide ();
1184         (* status bar *)
1185       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1186       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1187       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1188         (* focus *)
1189       self#sourceView#misc#grab_focus ();
1190         (* main win dimension *)
1191       let width = Gdk.Screen.width () in
1192       let height = Gdk.Screen.height () in
1193       let main_w = width * 90 / 100 in 
1194       let main_h = height * 80 / 100 in
1195       let script_w = main_w * 6 / 10 in
1196       main#toplevel#resize ~width:main_w ~height:main_h;
1197       main#hpaneScriptSequent#set_position script_w;
1198         (* source_view *)
1199       ignore(source_view#connect#after#paste_clipboard 
1200         ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1201       (* clean_locked is set to true only "during" a PRIMARY paste
1202          operation (i.e. by clicking with the second mouse button) *)
1203       let clean_locked = ref false in
1204       ignore(source_view#event#connect#button_press
1205         ~callback:
1206           (fun button ->
1207             if GdkEvent.Button.button button = 2 then
1208              clean_locked := true;
1209             false
1210           ));
1211       ignore(source_view#event#connect#button_release
1212         ~callback:(fun button -> clean_locked := false; false));
1213       ignore(source_view#buffer#connect#after#apply_tag
1214        ~callback:(
1215          fun tag ~start:_ ~stop:_ ->
1216           if !clean_locked &&
1217              tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1218           then
1219            begin
1220             clean_locked := false;
1221             (MatitaScript.current ())#clean_dirty_lock;
1222             clean_locked := true
1223            end));
1224       (* math view handling *)
1225       connect_menu_item main#newCicBrowserMenuItem (fun () ->
1226         ignore (MatitaMathView.cicBrowser ()));
1227       connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1228         self#increaseFontSize ();
1229         MatitaMathView.increase_font_size ();
1230         MatitaMathView.update_font_sizes ());
1231       connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1232         self#decreaseFontSize ();
1233         MatitaMathView.decrease_font_size ();
1234         MatitaMathView.update_font_sizes ());
1235       connect_menu_item main#normalFontSizeMenuItem (fun () ->
1236         self#resetFontSize ();
1237         MatitaMathView.reset_font_size ();
1238         MatitaMathView.update_font_sizes ());
1239       MatitaMathView.reset_font_size ();
1240
1241       (** selections / clipboards handling *)
1242
1243     method markupSelected = MatitaMathView.has_selection ()
1244     method private textSelected =
1245       (source_buffer#get_iter_at_mark `INSERT)#compare
1246         (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1247     method private somethingSelected = self#markupSelected || self#textSelected
1248     method private markupStored = MatitaMathView.has_clipboard ()
1249     method private textStored = clipboard#text <> None
1250     method private somethingStored = self#markupStored || self#textStored
1251
1252     method canCopy = self#somethingSelected
1253     method canCut = self#textSelected
1254     method canDelete = self#textSelected
1255     method canPaste = self#somethingStored
1256     method canPastePattern = self#markupStored
1257
1258     method copy () =
1259       if self#textSelected
1260       then begin
1261         MatitaMathView.empty_clipboard ();
1262         source_view#buffer#copy_clipboard clipboard;
1263       end else
1264         MatitaMathView.copy_selection ()
1265     method cut () =
1266       source_view#buffer#cut_clipboard clipboard;
1267       MatitaMathView.empty_clipboard ()
1268     method delete () = ignore (source_view#buffer#delete_selection ())
1269     method paste () =
1270       if MatitaMathView.has_clipboard ()
1271       then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1272       else source_view#buffer#paste_clipboard clipboard;
1273       (MatitaScript.current ())#clean_dirty_lock
1274     method pastePattern () =
1275       source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1276     
1277     method private nextLigature () =
1278       let iter = source_buffer#get_iter_at_mark `INSERT in
1279       let write_ligature len s =
1280         assert(Glib.Utf8.validate s);
1281         source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
1282         source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
1283       in
1284       let get_ligature word =
1285         let len = String.length word in
1286         let aux_tex () =
1287           try
1288             for i = len - 1 downto 0 do
1289               if HExtlib.is_alpha word.[i] then ()
1290               else
1291                 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
1292             done;
1293             None
1294           with Found i ->
1295             if i = ~-1 then None else Some (String.sub word i (len - i))
1296         in
1297         let aux_ligature () =
1298           try
1299             for i = len - 1 downto 0 do
1300               if CicNotationLexer.is_ligature_char word.[i] then ()
1301               else raise (Found (i+1))
1302             done;
1303             raise (Found 0)
1304           with
1305           | Found i ->
1306               (try
1307                 Some (String.sub word i (len - i))
1308               with Invalid_argument _ -> None)
1309         in
1310         match aux_tex () with
1311         | Some macro -> macro
1312         | None -> (match aux_ligature () with Some l -> l | None -> word)
1313       in
1314       (match next_ligatures with
1315       | [] -> (* find ligatures and fill next_ligatures, then try again *)
1316           let last_word =
1317             iter#get_slice
1318               ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
1319           in
1320           let ligature = get_ligature last_word in
1321           (match CicNotationLexer.lookup_ligatures ligature with
1322           | [] -> ()
1323           | hd :: tl ->
1324               write_ligature (MatitaGtkMisc.utf8_string_length ligature) hd;
1325               next_ligatures <- tl @ [ hd ])
1326       | hd :: tl ->
1327           write_ligature 1 hd;
1328           next_ligatures <- tl @ [ hd ])
1329
1330     method private externalEditor () =
1331       let cmd = Helm_registry.get "matita.external_editor" in
1332 (* ZACK uncomment to enable interactive ask of external editor command *)
1333 (*      let cmd =
1334          let msg =
1335           "External editor command:
1336 %f  will be substitute for the script name,
1337 %p  for the cursor position in bytes,
1338 %l  for the execution point in bytes."
1339         in
1340         ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1341           ~default:(Helm_registry.get "matita.external_editor") ()
1342       in *)
1343       let fname = (MatitaScript.current ())#filename in
1344       let slice mark =
1345         source_buffer#start_iter#get_slice
1346           ~stop:(source_buffer#get_iter_at_mark mark)
1347       in
1348       let script = MatitaScript.current () in
1349       let locked = `MARK script#locked_mark in
1350       let string_pos mark = string_of_int (String.length (slice mark)) in
1351       let cursor_pos = string_pos `INSERT in
1352       let locked_pos = string_pos locked in
1353       let cmd =
1354         Pcre.replace ~pat:"%f" ~templ:fname
1355           (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1356             (Pcre.replace ~pat:"%l" ~templ:locked_pos
1357               cmd))
1358       in
1359       let locked_before = slice locked in
1360       let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1361       ignore (Unix.system cmd);
1362       source_buffer#set_text (HExtlib.input_file fname);
1363       let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1364       source_buffer#move_mark locked locked_iter;
1365       source_buffer#apply_tag script#locked_tag
1366         ~start:source_buffer#start_iter ~stop:locked_iter;
1367       let locked_after = slice locked in
1368       let line = ref 0 in
1369       let col = ref 0 in
1370       try
1371         for i = 0 to String.length locked_before - 1 do
1372           if locked_before.[i] <> locked_after.[i] then begin
1373             source_buffer#place_cursor
1374               ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1375             script#goto `Cursor ();
1376             raise Exit
1377           end else if locked_before.[i] = '\n' then begin
1378             incr line;
1379             col := 0
1380           end
1381         done
1382       with
1383       | Exit -> ()
1384       | Invalid_argument _ -> script#goto `Bottom ()
1385
1386     method loadScript file =       
1387       let script = MatitaScript.current () in
1388       script#reset (); 
1389       if Pcre.pmatch ~pat:"\\.p$" file then
1390         begin
1391           let tptppath = 
1392             Helm_registry.get_opt_default Helm_registry.string ~default:"./"
1393               "matita.tptppath"
1394           in
1395           let data = Matitaprover.p_to_ma ~filename:file ~tptppath () in
1396           let filename = Pcre.replace ~pat:"\\.p$" ~templ:".ma" file in
1397           script#assignFileName filename;
1398           source_view#source_buffer#begin_not_undoable_action ();
1399           script#loadFromString data;
1400           source_view#source_buffer#end_not_undoable_action ();
1401           console#message ("'"^filename^"' loaded.");
1402           self#_enableSaveTo filename
1403         end
1404       else
1405         begin
1406           script#assignFileName file;
1407           let content =
1408            if Sys.file_exists file then file
1409            else BuildTimeConf.script_template
1410           in
1411            source_view#source_buffer#begin_not_undoable_action ();
1412            script#loadFromFile content;
1413            source_view#source_buffer#end_not_undoable_action ();
1414            console#message ("'"^file^"' loaded.");
1415            self#_enableSaveTo file
1416         end
1417       
1418     method setStar name b =
1419       let l = main#scriptLabel in
1420       if b then
1421         l#set_text (name ^  " *")
1422       else
1423         l#set_text (name)
1424         
1425     method private _enableSaveTo file =
1426       script_fname <- Some file;
1427       self#main#saveMenuItem#misc#set_sensitive true
1428         
1429     method console = console
1430     method sourceView: GSourceView.source_view =
1431       (source_view: GSourceView.source_view)
1432     method fileSel = fileSel
1433     method findRepl = findRepl
1434     method main = main
1435     method develList = develList
1436     method newDevel = newDevel
1437
1438     method newBrowserWin () =
1439       object (self)
1440         inherit browserWin ()
1441         val combo = GEdit.combo_box_entry ()
1442         initializer
1443           self#check_widgets ();
1444           let combo_widget = combo#coerce in
1445           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1446           combo#entry#misc#grab_focus ()
1447         method browserUri = combo
1448       end
1449
1450     method newUriDialog () =
1451       let dialog = new uriChoiceDialog () in
1452       dialog#check_widgets ();
1453       dialog
1454
1455     method newConfirmationDialog () =
1456       let dialog = new confirmationDialog () in
1457       dialog#check_widgets ();
1458       dialog
1459
1460     method newEmptyDialog () =
1461       let dialog = new emptyDialog () in
1462       dialog#check_widgets ();
1463       dialog
1464
1465     method private addKeyBinding key callback =
1466       List.iter (fun evbox -> add_key_binding key callback evbox)
1467         keyBindingBoxes
1468
1469     method setQuitCallback callback =
1470       connect_menu_item main#quitMenuItem callback;
1471       ignore (main#toplevel#event#connect#delete 
1472         (fun _ -> callback ();true));
1473       self#addKeyBinding GdkKeysyms._q callback
1474
1475     method chooseFile ?(ok_not_exists = false) () =
1476       _ok_not_exists <- ok_not_exists;
1477       _only_directory <- false;
1478       fileSel#fileSelectionWin#show ();
1479       GtkThread.main ();
1480       chosen_file
1481
1482     method private chooseDir ?(ok_not_exists = false) () =
1483       _ok_not_exists <- ok_not_exists;
1484       _only_directory <- true;
1485       fileSel#fileSelectionWin#show ();
1486       GtkThread.main ();
1487       (* we should check that this is a directory *)
1488       chosen_file
1489   
1490     method createDevelopment ~containing =
1491       next_devel_must_contain <- containing;
1492       newDevel#toplevel#misc#show()
1493
1494     method askText ?(title = "") ?(msg = "") () =
1495       let dialog = new textDialog () in
1496       dialog#textDialog#set_title title;
1497       dialog#textDialogLabel#set_label msg;
1498       let text = ref None in
1499       let return v =
1500         text := v;
1501         dialog#textDialog#destroy ();
1502         GMain.Main.quit ()
1503       in
1504       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1505       connect_button dialog#textDialogCancelButton (fun _ -> return None);
1506       connect_button dialog#textDialogOkButton (fun _ ->
1507         let text = dialog#textDialogTextView#buffer#get_text () in
1508         return (Some text));
1509       dialog#textDialog#show ();
1510       GtkThread.main ();
1511       !text
1512
1513     method private updateFontSize () =
1514       self#sourceView#misc#modify_font_by_name
1515         (sprintf "%s %d" BuildTimeConf.script_font font_size)
1516
1517     method increaseFontSize () =
1518       font_size <- font_size + 1;
1519       self#updateFontSize ()
1520
1521     method decreaseFontSize () =
1522       font_size <- font_size - 1;
1523       self#updateFontSize ()
1524
1525     method resetFontSize () =
1526       font_size <- default_font_size;
1527       self#updateFontSize ()
1528
1529   end
1530
1531 let gui () = 
1532   let g = new gui () in
1533   gui_instance := Some g;
1534   MatitaMathView.set_gui g;
1535   g
1536   
1537 let instance = singleton gui
1538
1539 let non p x = not (p x)
1540
1541 (* this is a shit and should be changed :-{ *)
1542 let interactive_uri_choice
1543   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1544   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
1545   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
1546   ?copy_cb ()
1547   ~id uris
1548 =
1549   let gui = instance () in
1550   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1551   if (selection_mode <> `SINGLE) &&
1552     (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1553   then
1554     Lazy.force nonvars_uris
1555   else begin
1556     let dialog = gui#newUriDialog () in
1557     if hide_uri_entry then
1558       dialog#uriEntryHBox#misc#hide ();
1559     if hide_try then
1560       begin
1561       dialog#uriChoiceSelectedButton#misc#hide ();
1562       dialog#uriChoiceConstantsButton#misc#hide ();
1563       end;
1564     dialog#okLabel#set_label ok_label;  
1565     dialog#uriChoiceTreeView#selection#set_mode
1566       (selection_mode :> Gtk.Tags.selection_mode);
1567     let model = new stringListModel dialog#uriChoiceTreeView in
1568     let choices = ref None in
1569     (match copy_cb with
1570     | None -> ()
1571     | Some cb ->
1572         dialog#copyButton#misc#show ();
1573         connect_button dialog#copyButton 
1574         (fun _ ->
1575           match model#easy_selection () with
1576           | [u] -> (cb u)
1577           | _ -> ()));
1578     dialog#uriChoiceDialog#set_title title;
1579     dialog#uriChoiceLabel#set_text msg;
1580     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1581     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1582     let return v =
1583       choices := v;
1584       dialog#uriChoiceDialog#destroy ();
1585       GMain.Main.quit ()
1586     in
1587     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1588     connect_button dialog#uriChoiceConstantsButton (fun _ ->
1589       return (Some (Lazy.force nonvars_uris)));
1590     if ok_action = `AUTO then
1591       connect_button dialog#uriChoiceAutoButton (fun _ ->
1592         Helm_registry.set_bool "matita.auto_disambiguation" true;
1593         return (Some (Lazy.force nonvars_uris)))
1594     else
1595       connect_button dialog#uriChoiceAutoButton (fun _ ->
1596         match model#easy_selection () with
1597         | [] -> ()
1598         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1599     connect_button dialog#uriChoiceSelectedButton (fun _ ->
1600       match model#easy_selection () with
1601       | [] -> ()
1602       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1603     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1604     dialog#uriChoiceDialog#show ();
1605     GtkThread.main ();
1606     (match !choices with 
1607     | None -> raise MatitaTypes.Cancel
1608     | Some uris -> uris)
1609   end
1610
1611 class interpModel =
1612   let cols = new GTree.column_list in
1613   let id_col = cols#add Gobject.Data.string in
1614   let dsc_col = cols#add Gobject.Data.string in
1615   let interp_no_col = cols#add Gobject.Data.int in
1616   let tree_store = GTree.tree_store cols in
1617   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1618   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1619   let id_view_col = GTree.view_column ~renderer:id_renderer () in
1620   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1621   fun tree_view choices ->
1622     object
1623       initializer
1624         tree_view#set_model (Some (tree_store :> GTree.model));
1625         ignore (tree_view#append_column id_view_col);
1626         ignore (tree_view#append_column dsc_view_col);
1627         let name_of_interp =
1628           (* try to find a reasonable name for an interpretation *)
1629           let idx = ref 0 in
1630           fun interp ->
1631             try
1632               List.assoc "0" interp
1633             with Not_found ->
1634               incr idx; string_of_int !idx
1635         in
1636         tree_store#clear ();
1637         let idx = ref ~-1 in
1638         List.iter
1639           (fun interp ->
1640             incr idx;
1641             let interp_row = tree_store#append () in
1642             tree_store#set ~row:interp_row ~column:id_col
1643               (name_of_interp interp);
1644             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1645             List.iter
1646               (fun (id, dsc) ->
1647                 let row = tree_store#append ~parent:interp_row () in
1648                 tree_store#set ~row ~column:id_col id;
1649                 tree_store#set ~row ~column:dsc_col dsc;
1650                 tree_store#set ~row ~column:interp_no_col !idx)
1651               interp)
1652           choices
1653
1654       method get_interp_no tree_path =
1655         let iter = tree_store#get_iter tree_path in
1656         tree_store#get ~row:iter ~column:interp_no_col
1657     end
1658
1659 let interactive_string_choice 
1660   text prefix_len ?(title = "") ?(msg = "") () ~id locs uris 
1661 =
1662   let gui = instance () in
1663     let dialog = gui#newUriDialog () in
1664     dialog#uriEntryHBox#misc#hide ();
1665     dialog#uriChoiceSelectedButton#misc#hide ();
1666     dialog#uriChoiceAutoButton#misc#hide ();
1667     dialog#uriChoiceConstantsButton#misc#hide ();
1668     dialog#uriChoiceTreeView#selection#set_mode
1669       (`SINGLE :> Gtk.Tags.selection_mode);
1670     let model = new stringListModel dialog#uriChoiceTreeView in
1671     let choices = ref None in
1672     dialog#uriChoiceDialog#set_title title; 
1673     let hack_len = MatitaGtkMisc.utf8_string_length text in
1674     let rec colorize acc_len = function
1675       | [] -> 
1676           let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1677           fst(MatitaGtkMisc.utf8_parsed_text text floc)
1678       | he::tl -> 
1679           let start, stop =  HExtlib.loc_of_floc he in
1680           let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1681           let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1682           let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1683           str1 ^ "<b>" ^ str2 ^ "</b>" ^ colorize stop tl
1684     in
1685 (*     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1686                 Printf.eprintf "(%d,%d)" start stop) locs; *)
1687     let locs = 
1688       List.sort 
1689         (fun loc1 loc2 -> 
1690           fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2)) 
1691         locs 
1692     in
1693 (*     prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1694     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1695                 Printf.eprintf "(%d,%d)" start stop) locs;
1696     prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1697     dialog#uriChoiceLabel#set_use_markup true;
1698     let txt = colorize 0 locs in
1699     let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1700       (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1701     in
1702     dialog#uriChoiceLabel#set_label txt;
1703     List.iter model#easy_append uris;
1704     let return v =
1705       choices := v;
1706       dialog#uriChoiceDialog#destroy ();
1707       GMain.Main.quit ()
1708     in
1709     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1710     connect_button dialog#uriChoiceForwardButton (fun _ ->
1711       match model#easy_selection () with
1712       | [] -> ()
1713       | uris -> return (Some uris));
1714     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1715     dialog#uriChoiceDialog#show ();
1716     GtkThread.main ();
1717     (match !choices with 
1718     | None -> raise MatitaTypes.Cancel
1719     | Some uris -> uris)
1720
1721 let interactive_interp_choice () text prefix_len choices =
1722 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1723  let filter_choices filter =
1724   let rec is_compatible filter =
1725    function
1726       [] -> true
1727     | ([],_,_)::tl -> is_compatible filter tl
1728     | (loc::tlloc,id,dsc)::tl ->
1729        try
1730         if List.assoc (loc,id) filter = dsc then
1731          is_compatible filter ((tlloc,id,dsc)::tl)
1732         else
1733          false
1734        with
1735         Not_found -> true
1736   in
1737    List.filter (fun (_,interp) -> is_compatible filter interp)
1738  in
1739  let rec get_choices loc id =
1740   function
1741      [] -> []
1742    | (_,he)::tl ->
1743       let _,_,dsc =
1744        List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1745       in
1746        dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1747  in
1748  let example_interp =
1749   match choices with
1750      [] -> assert false
1751    | he::_ -> he in
1752  let ask_user id locs choices =
1753   interactive_string_choice
1754    text prefix_len
1755    ~title:"Ambiguous input"
1756    ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1757  in
1758  let rec classify ids filter partial_interpretations =
1759   match ids with
1760      [] -> List.map fst partial_interpretations
1761    | ([],_,_)::tl -> classify tl filter partial_interpretations
1762    | (loc::tlloc,id,dsc)::tl ->
1763       let choices = get_choices loc id partial_interpretations in
1764       let chosen_dsc =
1765        match choices with
1766           [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1767         | [dsc] -> dsc
1768         | _ ->
1769           match ask_user id [loc] choices with
1770              [x] -> x
1771            | _ -> assert false
1772       in
1773        let filter = ((loc,id),chosen_dsc)::filter in
1774        let compatible_interps = filter_choices filter partial_interpretations in
1775         classify ((tlloc,id,dsc)::tl) filter compatible_interps
1776  in
1777  let enumerated_choices =
1778   let idx = ref ~-1 in
1779   List.map (fun interp -> incr idx; !idx,interp) choices
1780  in
1781   classify example_interp [] enumerated_choices
1782
1783 let _ =
1784   (* disambiguator callbacks *)
1785   GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1786   GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1787   (* gtk initialization *)
1788   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1789   GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1790   ignore (GMain.Main.init ())
1791