]> matita.cs.unibo.it Git - helm.git/blob - matita/matitaGui.ml
the same utf8 bug as before
[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 = DependenciesParser.baseuri_of_script ~include_paths:[] fname in
74   let moo_fname = 
75     LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri ~writable:true in
76   let save () =
77     let metadata_fname =
78      LibraryMisc.metadata_file_of_baseuri 
79        ~must_exist:false ~baseuri ~writable:true in
80     let lexicon_fname =
81      LibraryMisc.lexicon_file_of_baseuri 
82        ~must_exist:false ~baseuri ~writable:true
83     in
84      GrafiteMarshal.save_moo moo_fname
85       grafite_status.GrafiteTypes.moo_content_rev;
86      LibraryNoDb.save_metadata metadata_fname
87       lexicon_status.LexiconEngine.metadata;
88      LexiconMarshal.save_lexicon lexicon_fname
89       lexicon_status.LexiconEngine.lexicon_content_rev
90   in
91   if (MatitaScript.current ())#eos &&
92      grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof
93   then
94     begin
95       let rc = 
96         MatitaGtkMisc.ask_confirmation
97         ~title:"A .moo can be generated"
98         ~message:(Printf.sprintf 
99           "%s can be generated for %s.\n<i>Should I generate it?</i>"
100           (Filename.basename moo_fname) (Filename.basename fname))
101         ~parent ()
102       in
103       let b = 
104         match rc with 
105         | `YES -> true 
106         | `NO -> false 
107         | `CANCEL -> raise MatitaTypes.Cancel 
108       in
109       if b then
110           save ()
111       else
112         clean_current_baseuri grafite_status
113     end
114   else
115     clean_current_baseuri grafite_status 
116     
117 let ask_unsaved parent =
118   MatitaGtkMisc.ask_confirmation 
119     ~parent ~title:"Unsaved work!" 
120     ~message:("Your work is <b>unsaved</b>!\n\n"^
121          "<i>Do you want to save the script before continuing?</i>")
122     ()
123
124 (** Selection handling
125  * Two clipboards are used: "clipboard" and "primary".
126  * "primary" is used by X, when you hit the middle button mouse is content is
127  *    pasted between applications. In Matita this selection always contain the
128  *    textual version of the selected term.
129  * "clipboard" is used inside Matita only and support ATM two different targets:
130  *    "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
131  *    be added
132  *)
133
134 class gui () =
135     (* creation order _is_ relevant for windows placement *)
136   let main = new mainWin () in
137   let fileSel = new fileSelectionWin () in
138   let findRepl = new findReplWin () in
139   let develList = new develListWin () in
140   let newDevel = new newDevelWin () in
141   let keyBindingBoxes = (* event boxes which should receive global key events *)
142     [ main#mainWinEventBox ]
143   in
144   let console = new console ~buffer:main#logTextView#buffer () in
145   let (source_view: GSourceView.source_view) =
146     GSourceView.source_view
147       ~auto_indent:true
148       ~insert_spaces_instead_of_tabs:true ~tabs_width:2
149       ~margin:80 ~show_margin:true
150       ~smart_home_end:true
151       ~packing:main#scriptScrolledWin#add
152       ()
153   in
154   let default_font_size =
155     Helm_registry.get_opt_default Helm_registry.int
156       ~default:BuildTimeConf.default_font_size "matita.font_size"
157   in
158   let source_buffer = source_view#source_buffer in
159   object (self)
160     val mutable chosen_file = None
161     val mutable _ok_not_exists = false
162     val mutable _only_directory = false
163     val mutable script_fname = None
164     val mutable font_size = default_font_size
165     val mutable next_devel_must_contain = None
166     val mutable next_ligatures = []
167     val clipboard = GData.clipboard Gdk.Atom.clipboard
168     val primary = GData.clipboard Gdk.Atom.primary
169    
170     initializer
171         (* glade's check widgets *)
172       List.iter (fun w -> w#check_widgets ())
173         (let c w = (w :> <check_widgets: unit -> unit>) in
174         [ c fileSel; c main; c findRepl]);
175         (* key bindings *)
176       List.iter (* global key bindings *)
177         (fun (key, callback) -> self#addKeyBinding key callback)
178 (*
179         [ GdkKeysyms._F3,
180             toggle_win ~check:main#showProofMenuItem proof#proofWin;
181           GdkKeysyms._F4,
182             toggle_win ~check:main#showCheckMenuItem check#checkWin;
183 *)
184         [ ];
185         (* about win *)
186       let parse_txt_file file =
187        let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
188        let l_rev = ref [] in
189        try
190         while true do
191          l_rev := input_line ch :: !l_rev;
192         done;
193         assert false
194        with
195         End_of_file ->
196          close_in ch;
197          List.rev !l_rev in 
198       let about_dialog =
199        GWindow.about_dialog
200         ~authors:(parse_txt_file "AUTHORS")
201         (*~comments:"comments"*)
202         ~copyright:"Copyright (C) 2005, the HELM team"
203         ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
204         ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
205         ~name:"Matita"
206         ~version:BuildTimeConf.version
207         ~website:"http://helm.cs.unibo.it"
208         ()
209       in
210       connect_menu_item main#contentsMenuItem (fun () ->
211         let cmd =
212           sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
213         in
214         ignore (Sys.command cmd));
215       connect_menu_item main#aboutMenuItem about_dialog#present;
216         (* findRepl win *)
217       let show_find_Repl () = 
218         findRepl#toplevel#misc#show ();
219         findRepl#toplevel#misc#grab_focus ()
220       in
221       let hide_find_Repl () = findRepl#toplevel#misc#hide () in
222       let find_forward _ = 
223           let highlight start end_ =
224             source_buffer#move_mark `INSERT ~where:start;
225             source_buffer#move_mark `SEL_BOUND ~where:end_;
226             source_view#scroll_mark_onscreen `INSERT
227           in
228           let text = findRepl#findEntry#text in
229           let iter = source_buffer#get_iter `SEL_BOUND in
230           match iter#forward_search text with
231           | None -> 
232               (match source_buffer#start_iter#forward_search text with
233               | None -> ()
234               | Some (start,end_) -> highlight start end_)
235           | Some (start,end_) -> highlight start end_ 
236       in
237       let replace _ =
238         let text = findRepl#replaceEntry#text in
239         let ins = source_buffer#get_iter `INSERT in
240         let sel = source_buffer#get_iter `SEL_BOUND in
241         if ins#compare sel < 0 then 
242           begin
243             ignore(source_buffer#delete_selection ());
244             source_buffer#insert text
245           end
246       in
247       connect_button findRepl#findButton find_forward;
248       connect_button findRepl#findReplButton replace;
249       connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
250       ignore(findRepl#toplevel#event#connect#delete 
251         ~callback:(fun _ -> hide_find_Repl ();true));
252       let safe_undo =
253        fun () ->
254         (* phase 1: we save the actual status of the marks and we undo *)
255         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
256         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
257         let locked_iter_offset = locked_iter#offset in
258         let mark2 =
259          `MARK
260            (source_view#buffer#create_mark ~name:"lock_point"
261              ~left_gravity:true locked_iter) in
262         source_view#source_buffer#undo ();
263         (* phase 2: we save the cursor position and we redo, restoring
264            the previous status of all the marks *)
265         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
266         let mark =
267          `MARK
268            (source_view#buffer#create_mark ~name:"undo_point"
269              ~left_gravity:true cursor_iter)
270         in
271          source_view#source_buffer#redo ();
272          let mark_iter = source_view#buffer#get_iter_at_mark mark in
273          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
274          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
275           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
276           source_view#buffer#delete_mark mark;
277           source_view#buffer#delete_mark mark2;
278           (* phase 3: if after the undo the cursor was in the locked area,
279              then we move it there again and we perform a goto *)
280           if mark_iter#offset < locked_iter_offset then
281            begin
282             source_view#buffer#move_mark `INSERT ~where:mark_iter;
283             (MatitaScript.current ())#goto `Cursor ();
284            end;
285           (* phase 4: we perform again the undo. This time we are sure that
286              the text to undo is not locked *)
287           source_view#source_buffer#undo ();
288           source_view#misc#grab_focus () in
289       let safe_redo =
290        fun () ->
291         (* phase 1: we save the actual status of the marks, we redo and
292            we undo *)
293         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
294         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
295         let locked_iter_offset = locked_iter#offset in
296         let mark2 =
297          `MARK
298            (source_view#buffer#create_mark ~name:"lock_point"
299              ~left_gravity:true locked_iter) in
300         source_view#source_buffer#redo ();
301         source_view#source_buffer#undo ();
302         (* phase 2: we save the cursor position and we restore
303            the previous status of all the marks *)
304         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
305         let mark =
306          `MARK
307            (source_view#buffer#create_mark ~name:"undo_point"
308              ~left_gravity:true cursor_iter)
309         in
310          let mark_iter = source_view#buffer#get_iter_at_mark mark in
311          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
312          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
313           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
314           source_view#buffer#delete_mark mark;
315           source_view#buffer#delete_mark mark2;
316           (* phase 3: if after the undo the cursor is in the locked area,
317              then we move it there again and we perform a goto *)
318           if mark_iter#offset < locked_iter_offset then
319            begin
320             source_view#buffer#move_mark `INSERT ~where:mark_iter;
321             (MatitaScript.current ())#goto `Cursor ();
322            end;
323           (* phase 4: we perform again the redo. This time we are sure that
324              the text to redo is not locked *)
325           source_view#source_buffer#redo ();
326           source_view#misc#grab_focus ()
327       in
328       connect_menu_item main#undoMenuItem safe_undo;
329       ignore(source_view#source_buffer#connect#can_undo
330         ~callback:main#undoMenuItem#misc#set_sensitive);
331       connect_menu_item main#redoMenuItem safe_redo;
332       ignore(source_view#source_buffer#connect#can_redo
333         ~callback:main#redoMenuItem#misc#set_sensitive);
334       ignore(source_view#connect#after#populate_popup
335        ~callback:(fun pre_menu ->
336          let menu = new GMenu.menu pre_menu in
337          let menuItems = menu#children in
338          let undoMenuItem, redoMenuItem =
339           match menuItems with
340              [undo;redo;sep1;cut;copy;paste;delete;sep2;
341               selectall;sep3;inputmethod;insertunicodecharacter] ->
342                 List.iter menu#remove [ copy; cut; delete; paste ];
343                 undo,redo
344            | _ -> assert false in
345          let add_menu_item =
346            let i = ref 2 in (* last occupied position *)
347            fun ?label ?stock () ->
348              incr i;
349              GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
350               ()
351          in
352          let copy = add_menu_item ~stock:`COPY () in
353          let cut = add_menu_item ~stock:`CUT () in
354          let delete = add_menu_item ~stock:`DELETE () in
355          let paste = add_menu_item ~stock:`PASTE () in
356          let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
357          copy#misc#set_sensitive self#canCopy;
358          cut#misc#set_sensitive self#canCut;
359          delete#misc#set_sensitive self#canDelete;
360          paste#misc#set_sensitive self#canPaste;
361          paste_pattern#misc#set_sensitive self#canPastePattern;
362          connect_menu_item copy self#copy;
363          connect_menu_item cut self#cut;
364          connect_menu_item delete self#delete;
365          connect_menu_item paste self#paste;
366          connect_menu_item paste_pattern self#pastePattern;
367          let new_undoMenuItem =
368           GMenu.image_menu_item
369            ~image:(GMisc.image ~stock:`UNDO ())
370            ~use_mnemonic:true
371            ~label:"_Undo"
372            ~packing:(menu#insert ~pos:0) () in
373          new_undoMenuItem#misc#set_sensitive
374           (undoMenuItem#misc#get_flag `SENSITIVE);
375          menu#remove (undoMenuItem :> GMenu.menu_item);
376          connect_menu_item new_undoMenuItem safe_undo;
377          let new_redoMenuItem =
378           GMenu.image_menu_item
379            ~image:(GMisc.image ~stock:`REDO ())
380            ~use_mnemonic:true
381            ~label:"_Redo"
382            ~packing:(menu#insert ~pos:1) () in
383          new_redoMenuItem#misc#set_sensitive
384           (redoMenuItem#misc#get_flag `SENSITIVE);
385           menu#remove (redoMenuItem :> GMenu.menu_item);
386           connect_menu_item new_redoMenuItem safe_redo));
387
388       connect_menu_item main#editMenu (fun () ->
389         main#copyMenuItem#misc#set_sensitive self#canCopy;
390         main#cutMenuItem#misc#set_sensitive self#canCut;
391         main#deleteMenuItem#misc#set_sensitive self#canDelete;
392         main#pasteMenuItem#misc#set_sensitive self#canPaste;
393         main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
394       connect_menu_item main#copyMenuItem self#copy;
395       connect_menu_item main#cutMenuItem self#cut;
396       connect_menu_item main#deleteMenuItem self#delete;
397       connect_menu_item main#pasteMenuItem self#paste;
398       connect_menu_item main#pastePatternMenuItem self#pastePattern;
399       connect_menu_item main#selectAllMenuItem (fun () ->
400         source_buffer#move_mark `INSERT source_buffer#start_iter;
401         source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
402       connect_menu_item main#findReplMenuItem show_find_Repl;
403       connect_menu_item main#externalEditorMenuItem self#externalEditor;
404       connect_menu_item main#ligatureButton self#nextLigature;
405       ignore (findRepl#findEntry#connect#activate find_forward);
406         (* interface lockers *)
407       let lock_world _ =
408         main#buttonsToolbar#misc#set_sensitive false;
409         develList#buttonsHbox#misc#set_sensitive false;
410         source_view#set_editable false
411       in
412       let unlock_world _ =
413         main#buttonsToolbar#misc#set_sensitive true;
414         develList#buttonsHbox#misc#set_sensitive true;
415         source_view#set_editable true
416       in
417       let locker f = 
418         fun () -> 
419           lock_world ();
420           try f ();unlock_world () with exc -> unlock_world (); raise exc in
421       let keep_focus f =
422         fun () ->
423          try
424           f (); source_view#misc#grab_focus ()
425          with
426           exc -> source_view#misc#grab_focus (); raise exc in
427         (* developments win *)
428       let model = 
429         new MatitaGtkMisc.multiStringListModel 
430           ~cols:2 develList#developmentsTreeview
431       in
432       let refresh_devels_win () =
433         model#list_store#clear ();
434         List.iter 
435           (fun (name, root) -> model#easy_mappend [name;root]) 
436           (MatitamakeLib.list_known_developments ())
437       in
438       let get_devel_selected () = 
439         match model#easy_mselection () with
440         | [[name;_]] -> MatitamakeLib.development_for_name name
441         | _ -> None
442       in
443       let refresh () = 
444         while Glib.Main.pending () do 
445           ignore(Glib.Main.iteration false); 
446         done
447       in
448       connect_button develList#newButton
449         (fun () -> 
450           next_devel_must_contain <- None;
451           newDevel#toplevel#misc#show());
452       connect_button develList#deleteButton
453         (locker (fun () -> 
454           (match get_devel_selected () with
455           | None -> ()
456           | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
457           refresh_devels_win ()));
458       connect_button develList#buildButton 
459         (locker (fun () -> 
460           match get_devel_selected () with
461           | None -> ()
462           | Some d -> 
463               let build = locker 
464                 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
465               in
466               ignore(build ())));
467       connect_button develList#cleanButton 
468         (locker (fun () -> 
469           match get_devel_selected () with
470           | None -> ()
471           | Some d -> 
472               let clean = locker 
473                 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
474               in
475               ignore(clean ())));
476       connect_button develList#publishButton 
477         (locker (fun () -> 
478           match get_devel_selected () with
479           | None -> ()
480           | Some d -> 
481               let clean = locker 
482                 (fun () -> MatitamakeLib.publish_development_in_bg refresh d)
483               in
484               ignore(clean ())));
485       connect_button develList#closeButton 
486         (fun () -> develList#toplevel#misc#hide());
487       ignore(develList#toplevel#event#connect#delete 
488         (fun _ -> develList#toplevel#misc#hide();true));
489       connect_menu_item main#developmentsMenuItem
490         (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
491       
492         (* add development win *)
493       let check_if_root_contains root =
494         match next_devel_must_contain with
495         | None -> true
496         | Some path -> 
497             let is_prefix_of d1 d2 =
498               let len1 = String.length d1 in
499               let len2 = String.length d2 in
500               if len2 < len1 then 
501                 false
502               else
503                 let pref = String.sub d2 0 len1 in
504                 pref = d1
505             in
506             is_prefix_of root path
507       in
508       connect_button newDevel#addButton 
509        (fun () -> 
510           let name = newDevel#nameEntry#text in
511           let root = newDevel#rootEntry#text in
512           if check_if_root_contains root then
513             begin
514               ignore (MatitamakeLib.initialize_development name root);
515               refresh_devels_win ();
516               newDevel#nameEntry#set_text "";
517               newDevel#rootEntry#set_text "";
518               newDevel#toplevel#misc#hide()
519             end
520           else
521             HLog.error ("The selected root does not contain " ^ 
522               match next_devel_must_contain with 
523               | Some x -> x 
524               | _ -> assert false));
525       connect_button newDevel#chooseRootButton 
526        (fun () ->
527          let path = self#chooseDir () in
528          match path with
529          | Some path -> newDevel#rootEntry#set_text path
530          | None -> ());
531       connect_button newDevel#cancelButton 
532        (fun () -> newDevel#toplevel#misc#hide ());
533       ignore(newDevel#toplevel#event#connect#delete 
534         (fun _ -> newDevel#toplevel#misc#hide();true));
535       
536         (* file selection win *)
537       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
538       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
539         let return r =
540           chosen_file <- r;
541           fileSel#fileSelectionWin#misc#hide ();
542           GMain.Main.quit ()
543         in
544         match event with
545         | `OK ->
546             let fname = fileSel#fileSelectionWin#filename in
547             if Sys.file_exists fname then
548               begin
549                 if HExtlib.is_regular fname && not (_only_directory) then 
550                   return (Some fname) 
551                 else if _only_directory && HExtlib.is_dir fname then 
552                   return (Some fname)
553               end
554             else
555               begin
556                 if _ok_not_exists then 
557                   return (Some fname)
558               end
559         | `CANCEL -> return None
560         | `HELP -> ()
561         | `DELETE_EVENT -> return None));
562         (* menus *)
563       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
564         (* console *)
565       let adj = main#logScrolledWin#vadjustment in
566         ignore (adj#connect#changed
567                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
568       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
569         (* toolbar *)
570       let module A = GrafiteAst in
571       let hole = CicNotationPt.UserInput in
572       let loc = HExtlib.dummy_floc in
573       let tac ast _ =
574         if (MatitaScript.current ())#onGoingProof () then
575           (MatitaScript.current ())#advance
576             ~statement:("\n"
577               ^ GrafiteAstPp.pp_tactical ~term_pp:CicNotationPp.pp_term
578                 ~lazy_term_pp:CicNotationPp.pp_term (A.Tactic (loc, ast)))
579             ()
580       in
581       let tac_w_term ast _ =
582         if (MatitaScript.current ())#onGoingProof () then
583           let buf = source_buffer in
584           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
585             ("\n"
586             ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
587               ~lazy_term_pp:CicNotationPp.pp_term ast)
588       in
589       let tbar = main in
590       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
591       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
592       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
593       connect_button tbar#elimButton (tac_w_term
594         (A.Elim (loc, hole, None, None, [])));
595       connect_button tbar#elimTypeButton (tac_w_term
596         (A.ElimType (loc, hole, None, None, [])));
597       connect_button tbar#splitButton (tac (A.Split loc));
598       connect_button tbar#leftButton (tac (A.Left loc));
599       connect_button tbar#rightButton (tac (A.Right loc));
600       connect_button tbar#existsButton (tac (A.Exists loc));
601       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
602       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
603       connect_button tbar#transitivityButton
604         (tac_w_term (A.Transitivity (loc, hole)));
605       connect_button tbar#assumptionButton (tac (A.Assumption loc));
606       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
607       connect_button tbar#autoButton (tac (A.Auto (loc,None,None,None,None)));
608       MatitaGtkMisc.toggle_widget_visibility
609        ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
610        ~check:main#tacticsBarMenuItem;
611       let module Hr = Helm_registry in
612       if
613         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
614       then 
615         main#tacticsBarMenuItem#set_active false;
616       MatitaGtkMisc.toggle_callback 
617         ~callback:(function 
618           | true -> main#toplevel#fullscreen () 
619           | false -> main#toplevel#unfullscreen ())
620         ~check:main#fullscreenMenuItem;
621       main#fullscreenMenuItem#set_active false;
622         (* log *)
623       HLog.set_log_callback self#console#log_callback;
624       GtkSignal.user_handler :=
625         (function 
626         | MatitaScript.ActionCancelled s -> HLog.error s
627         | exn ->
628           if not (Helm_registry.get_bool "matita.debug") then
629            let floc, msg = MatitaExcPp.to_string exn in
630             begin
631              match floc with
632                 None -> ()
633               | Some floc ->
634                  let (x, y) = HExtlib.loc_of_floc floc in
635                  let script = MatitaScript.current () in
636                  let locked_mark = script#locked_mark in
637                  let error_tag = script#error_tag in
638                  let baseoffset =
639                   (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
640                  let x' = baseoffset + x in
641                  let y' = baseoffset + y in
642                  let x_iter = source_buffer#get_iter (`OFFSET x') in
643                  let y_iter = source_buffer#get_iter (`OFFSET y') in
644                  source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
645                  let id = ref None in
646                  id := Some (source_buffer#connect#changed ~callback:(fun () ->
647                    source_buffer#remove_tag error_tag
648                      ~start:source_buffer#start_iter
649                      ~stop:source_buffer#end_iter;
650                    match !id with
651                    | None -> assert false (* a race condition occurred *)
652                    | Some id ->
653                        (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
654                  source_buffer#place_cursor
655                   (source_buffer#get_iter (`OFFSET x'));
656             end;
657             HLog.error msg
658           else raise exn);
659         (* script *)
660       ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
661       let _ =
662         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
663         | None ->
664             HLog.warn (sprintf "can't load language file %s"
665               BuildTimeConf.lang_file)
666         | Some matita_lang ->
667             source_buffer#set_language matita_lang;
668             source_buffer#set_highlight true
669       in
670       let s () = MatitaScript.current () in
671       let disableSave () =
672         script_fname <- None;
673         main#saveMenuItem#misc#set_sensitive false
674       in
675       let saveAsScript () =
676         let script = s () in
677         match self#chooseFile ~ok_not_exists:true () with
678         | Some f -> 
679               script#assignFileName f;
680               script#saveToFile (); 
681               console#message ("'"^f^"' saved.\n");
682               self#_enableSaveTo f
683         | None -> ()
684       in
685       let saveScript () =
686         match script_fname with
687         | None -> saveAsScript ()
688         | Some f -> 
689               (s ())#assignFileName f;
690               (s ())#saveToFile ();
691               console#message ("'"^f^"' saved.\n");
692       in
693       let abandon_script () =
694         let lexicon_status = (s ())#lexicon_status in
695         let grafite_status = (s ())#grafite_status in
696         if source_view#buffer#modified then
697           (match ask_unsaved main#toplevel with
698           | `YES -> saveScript ()
699           | `NO -> ()
700           | `CANCEL -> raise MatitaTypes.Cancel);
701         (match script_fname with
702         | None -> ()
703         | Some fname ->
704            ask_and_save_moo_if_needed main#toplevel fname
705             lexicon_status grafite_status);
706       in
707       let loadScript () =
708         let script = s () in 
709         try 
710           match self#chooseFile () with
711           | Some f -> 
712               abandon_script ();
713               script#reset (); 
714               script#assignFileName f;
715               source_view#source_buffer#begin_not_undoable_action ();
716               script#loadFromFile f; 
717               source_view#source_buffer#end_not_undoable_action ();
718               console#message ("'"^f^"' loaded.\n");
719               self#_enableSaveTo f
720           | None -> ()
721         with MatitaTypes.Cancel -> ()
722       in
723       let newScript () = 
724         abandon_script ();
725         source_view#source_buffer#begin_not_undoable_action ();
726         (s ())#reset (); 
727         (s ())#template (); 
728         source_view#source_buffer#end_not_undoable_action ();
729         disableSave ();
730         script_fname <- None
731       in
732       let cursor () =
733         source_buffer#place_cursor
734           (source_buffer#get_iter_at_mark (`NAME "locked")) in
735       let advance _ = (MatitaScript.current ())#advance (); cursor () in
736       let retract _ = (MatitaScript.current ())#retract (); cursor () in
737       let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
738       let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
739       let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
740       let advance = locker (keep_focus advance) in
741       let retract = locker (keep_focus retract) in
742       let top = locker (keep_focus top) in
743       let bottom = locker (keep_focus bottom) in
744       let jump = locker (keep_focus jump) in
745         (* quit *)
746       self#setQuitCallback (fun () -> 
747         let lexicon_status = (MatitaScript.current ())#lexicon_status in
748         let grafite_status = (MatitaScript.current ())#grafite_status in
749         if source_view#buffer#modified then
750           begin
751             let rc = ask_unsaved main#toplevel in 
752             try
753               match rc with
754               | `YES -> saveScript ();
755                         if not source_view#buffer#modified then
756                           begin
757                             (match script_fname with
758                             | None -> ()
759                             | Some fname -> 
760                                ask_and_save_moo_if_needed main#toplevel
761                                 fname lexicon_status grafite_status);
762                           GMain.Main.quit ()
763                           end
764               | `NO -> GMain.Main.quit ()
765               | `CANCEL -> raise MatitaTypes.Cancel
766             with MatitaTypes.Cancel -> ()
767           end 
768         else 
769           begin  
770             (match script_fname with
771             | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
772             | Some fname ->
773                 try
774                   ask_and_save_moo_if_needed main#toplevel fname lexicon_status
775                    grafite_status;
776                   GMain.Main.quit ()
777                 with MatitaTypes.Cancel -> ())
778           end);
779       connect_button main#scriptAdvanceButton advance;
780       connect_button main#scriptRetractButton retract;
781       connect_button main#scriptTopButton top;
782       connect_button main#scriptBottomButton bottom;
783       connect_button main#scriptJumpButton jump;
784       connect_menu_item main#scriptAdvanceMenuItem advance;
785       connect_menu_item main#scriptRetractMenuItem retract;
786       connect_menu_item main#scriptTopMenuItem top;
787       connect_menu_item main#scriptBottomMenuItem bottom;
788       connect_menu_item main#scriptJumpMenuItem jump;
789       connect_menu_item main#openMenuItem   loadScript;
790       connect_menu_item main#saveMenuItem   saveScript;
791       connect_menu_item main#saveAsMenuItem saveAsScript;
792       connect_menu_item main#newMenuItem    newScript;
793          (* script monospace font stuff *)  
794       self#updateFontSize ();
795         (* debug menu *)
796       main#debugMenu#misc#hide ();
797         (* status bar *)
798       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
799       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
800       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
801         (* focus *)
802       self#sourceView#misc#grab_focus ();
803         (* main win dimension *)
804       let width = Gdk.Screen.width () in
805       let height = Gdk.Screen.height () in
806       let main_w = width * 90 / 100 in 
807       let main_h = height * 80 / 100 in
808       let script_w = main_w * 6 / 10 in
809       main#toplevel#resize ~width:main_w ~height:main_h;
810       main#hpaneScriptSequent#set_position script_w;
811         (* source_view *)
812       ignore(source_view#connect#after#paste_clipboard 
813         ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
814       (* clean_locked is set to true only "during" a PRIMARY paste
815          operation (i.e. by clicking with the second mouse button) *)
816       let clean_locked = ref false in
817       ignore(source_view#event#connect#button_press
818         ~callback:
819           (fun button ->
820             if GdkEvent.Button.button button = 2 then
821              clean_locked := true;
822             false
823           ));
824       ignore(source_view#event#connect#button_release
825         ~callback:(fun button -> clean_locked := false; false));
826       ignore(source_view#buffer#connect#after#apply_tag
827        ~callback:(
828          fun tag ~start:_ ~stop:_ ->
829           if !clean_locked &&
830              tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
831           then
832            begin
833             clean_locked := false;
834             (MatitaScript.current ())#clean_dirty_lock;
835             clean_locked := true
836            end));
837       (* math view handling *)
838       connect_menu_item main#newCicBrowserMenuItem (fun () ->
839         ignore (MatitaMathView.cicBrowser ()));
840       connect_menu_item main#increaseFontSizeMenuItem (fun () ->
841         self#increaseFontSize ();
842         MatitaMathView.increase_font_size ();
843         MatitaMathView.update_font_sizes ());
844       connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
845         self#decreaseFontSize ();
846         MatitaMathView.decrease_font_size ();
847         MatitaMathView.update_font_sizes ());
848       connect_menu_item main#normalFontSizeMenuItem (fun () ->
849         self#resetFontSize ();
850         MatitaMathView.reset_font_size ();
851         MatitaMathView.update_font_sizes ());
852       MatitaMathView.reset_font_size ();
853
854       (** selections / clipboards handling *)
855
856     method markupSelected = MatitaMathView.has_selection ()
857     method private textSelected =
858       (source_buffer#get_iter_at_mark `INSERT)#compare
859         (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
860     method private somethingSelected = self#markupSelected || self#textSelected
861     method private markupStored = MatitaMathView.has_clipboard ()
862     method private textStored = clipboard#text <> None
863     method private somethingStored = self#markupStored || self#textStored
864
865     method canCopy = self#somethingSelected
866     method canCut = self#textSelected
867     method canDelete = self#textSelected
868     method canPaste = self#somethingStored
869     method canPastePattern = self#markupStored
870
871     method copy () =
872       if self#textSelected
873       then begin
874         MatitaMathView.empty_clipboard ();
875         source_view#buffer#copy_clipboard clipboard;
876       end else
877         MatitaMathView.copy_selection ()
878     method cut () =
879       source_view#buffer#cut_clipboard clipboard;
880       MatitaMathView.empty_clipboard ()
881     method delete () = ignore (source_view#buffer#delete_selection ())
882     method paste () =
883       if MatitaMathView.has_clipboard ()
884       then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
885       else source_view#buffer#paste_clipboard clipboard;
886       (MatitaScript.current ())#clean_dirty_lock
887     method pastePattern () =
888       source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
889     
890     method private nextLigature () =
891       let iter = source_buffer#get_iter_at_mark `INSERT in
892       let write_ligature len s =
893         assert(Glib.Utf8.validate s);
894         source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
895         source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
896       in
897       let get_ligature word =
898         let len = MatitaGtkMisc.utf8_string_length word in
899         let aux_tex () =
900           try
901             for i = len - 1 downto 0 do
902               if HExtlib.is_alpha word.[i] then ()
903               else
904                 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
905             done;
906             None
907           with Found i ->
908             if i = ~-1 then None else Some (String.sub word i (len - i))
909         in
910         let aux_ligature () =
911           try
912             for i = len - 1 downto 0 do
913               if CicNotationLexer.is_ligature_char word.[i] then ()
914               else raise (Found (i+1))
915             done;
916             raise (Found 0)
917           with
918           | Found i ->
919               (try
920                 Some (String.sub word i (len - i))
921               with Invalid_argument _ -> None)
922         in
923         match aux_tex () with
924         | Some macro -> macro
925         | None -> (match aux_ligature () with Some l -> l | None -> word)
926       in
927       (match next_ligatures with
928       | [] -> (* find ligatures and fill next_ligatures, then try again *)
929           let last_word =
930             iter#get_slice
931               ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
932           in
933           let ligature = get_ligature last_word in
934           (match CicNotationLexer.lookup_ligatures ligature with
935           | [] -> ()
936           | hd :: tl ->
937               write_ligature (MatitaGtkMisc.utf8_string_length ligature) hd;
938               next_ligatures <- tl @ [ hd ])
939       | hd :: tl ->
940           write_ligature 1 hd;
941           next_ligatures <- tl @ [ hd ])
942
943     method private externalEditor () =
944       let cmd = Helm_registry.get "matita.external_editor" in
945 (* ZACK uncomment to enable interactive ask of external editor command *)
946 (*      let cmd =
947          let msg =
948           "External editor command:
949 %f  will be substitute for the script name,
950 %p  for the cursor position in bytes,
951 %l  for the execution point in bytes."
952         in
953         ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
954           ~default:(Helm_registry.get "matita.external_editor") ()
955       in *)
956       let fname = (MatitaScript.current ())#filename in
957       let slice mark =
958         source_buffer#start_iter#get_slice
959           ~stop:(source_buffer#get_iter_at_mark mark)
960       in
961       let script = MatitaScript.current () in
962       let locked = `MARK script#locked_mark in
963       let string_pos mark = string_of_int (String.length (slice mark)) in
964       let cursor_pos = string_pos `INSERT in
965       let locked_pos = string_pos locked in
966       let cmd =
967         Pcre.replace ~pat:"%f" ~templ:fname
968           (Pcre.replace ~pat:"%p" ~templ:cursor_pos
969             (Pcre.replace ~pat:"%l" ~templ:locked_pos
970               cmd))
971       in
972       let locked_before = slice locked in
973       let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
974       ignore (Unix.system cmd);
975       source_buffer#set_text (HExtlib.input_file fname);
976       let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
977       source_buffer#move_mark locked locked_iter;
978       source_buffer#apply_tag script#locked_tag
979         ~start:source_buffer#start_iter ~stop:locked_iter;
980       let locked_after = slice locked in
981       let line = ref 0 in
982       let col = ref 0 in
983       try
984         for i = 0 to String.length locked_before - 1 do
985           if locked_before.[i] <> locked_after.[i] then begin
986             source_buffer#place_cursor
987               ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
988             script#goto `Cursor ();
989             raise Exit
990           end else if locked_before.[i] = '\n' then begin
991             incr line;
992             col := 0
993           end
994         done
995       with
996       | Exit -> ()
997       | Invalid_argument _ -> script#goto `Bottom ()
998
999     method loadScript file =       
1000       let script = MatitaScript.current () in
1001       script#reset (); 
1002       script#assignFileName file;
1003       let content =
1004        if Sys.file_exists file then file
1005        else BuildTimeConf.script_template
1006       in
1007        source_view#source_buffer#begin_not_undoable_action ();
1008        script#loadFromFile content;
1009        source_view#source_buffer#end_not_undoable_action ();
1010        console#message ("'"^file^"' loaded.");
1011        self#_enableSaveTo file
1012       
1013     method setStar name b =
1014       let l = main#scriptLabel in
1015       if b then
1016         l#set_text (name ^  " *")
1017       else
1018         l#set_text (name)
1019         
1020     method private _enableSaveTo file =
1021       script_fname <- Some file;
1022       self#main#saveMenuItem#misc#set_sensitive true
1023         
1024     method console = console
1025     method sourceView: GSourceView.source_view =
1026       (source_view: GSourceView.source_view)
1027     method fileSel = fileSel
1028     method findRepl = findRepl
1029     method main = main
1030     method develList = develList
1031     method newDevel = newDevel
1032
1033     method newBrowserWin () =
1034       object (self)
1035         inherit browserWin ()
1036         val combo = GEdit.combo_box_entry ()
1037         initializer
1038           self#check_widgets ();
1039           let combo_widget = combo#coerce in
1040           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1041           combo#entry#misc#grab_focus ()
1042         method browserUri = combo
1043       end
1044
1045     method newUriDialog () =
1046       let dialog = new uriChoiceDialog () in
1047       dialog#check_widgets ();
1048       dialog
1049
1050     method newRecordDialog () =
1051       let dialog = new recordChoiceDialog () in
1052       dialog#check_widgets ();
1053       dialog
1054
1055     method newConfirmationDialog () =
1056       let dialog = new confirmationDialog () in
1057       dialog#check_widgets ();
1058       dialog
1059
1060     method newEmptyDialog () =
1061       let dialog = new emptyDialog () in
1062       dialog#check_widgets ();
1063       dialog
1064
1065     method private addKeyBinding key callback =
1066       List.iter (fun evbox -> add_key_binding key callback evbox)
1067         keyBindingBoxes
1068
1069     method setQuitCallback callback =
1070       connect_menu_item main#quitMenuItem callback;
1071       ignore (main#toplevel#event#connect#delete 
1072         (fun _ -> callback ();true));
1073       self#addKeyBinding GdkKeysyms._q callback
1074
1075     method chooseFile ?(ok_not_exists = false) () =
1076       _ok_not_exists <- ok_not_exists;
1077       _only_directory <- false;
1078       fileSel#fileSelectionWin#show ();
1079       GtkThread.main ();
1080       chosen_file
1081
1082     method private chooseDir ?(ok_not_exists = false) () =
1083       _ok_not_exists <- ok_not_exists;
1084       _only_directory <- true;
1085       fileSel#fileSelectionWin#show ();
1086       GtkThread.main ();
1087       (* we should check that this is a directory *)
1088       chosen_file
1089   
1090     method createDevelopment ~containing =
1091       next_devel_must_contain <- containing;
1092       newDevel#toplevel#misc#show()
1093
1094     method askText ?(title = "") ?(msg = "") () =
1095       let dialog = new textDialog () in
1096       dialog#textDialog#set_title title;
1097       dialog#textDialogLabel#set_label msg;
1098       let text = ref None in
1099       let return v =
1100         text := v;
1101         dialog#textDialog#destroy ();
1102         GMain.Main.quit ()
1103       in
1104       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1105       connect_button dialog#textDialogCancelButton (fun _ -> return None);
1106       connect_button dialog#textDialogOkButton (fun _ ->
1107         let text = dialog#textDialogTextView#buffer#get_text () in
1108         return (Some text));
1109       dialog#textDialog#show ();
1110       GtkThread.main ();
1111       !text
1112
1113     method private updateFontSize () =
1114       self#sourceView#misc#modify_font_by_name
1115         (sprintf "%s %d" BuildTimeConf.script_font font_size)
1116
1117     method increaseFontSize () =
1118       font_size <- font_size + 1;
1119       self#updateFontSize ()
1120
1121     method decreaseFontSize () =
1122       font_size <- font_size - 1;
1123       self#updateFontSize ()
1124
1125     method resetFontSize () =
1126       font_size <- default_font_size;
1127       self#updateFontSize ()
1128
1129   end
1130
1131 let gui () = 
1132   let g = new gui () in
1133   gui_instance := Some g;
1134   MatitaMathView.set_gui g;
1135   g
1136   
1137 let instance = singleton gui
1138
1139 let non p x = not (p x)
1140
1141 (* this is a shit and should be changed :-{ *)
1142 let interactive_uri_choice
1143   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1144   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
1145   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
1146   ?copy_cb ()
1147   ~id uris
1148 =
1149   let gui = instance () in
1150   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1151   if (selection_mode <> `SINGLE) &&
1152     (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1153   then
1154     Lazy.force nonvars_uris
1155   else begin
1156     let dialog = gui#newUriDialog () in
1157     if hide_uri_entry then
1158       dialog#uriEntryHBox#misc#hide ();
1159     if hide_try then
1160       begin
1161       dialog#uriChoiceSelectedButton#misc#hide ();
1162       dialog#uriChoiceConstantsButton#misc#hide ();
1163       end;
1164     dialog#okLabel#set_label ok_label;  
1165     dialog#uriChoiceTreeView#selection#set_mode
1166       (selection_mode :> Gtk.Tags.selection_mode);
1167     let model = new stringListModel dialog#uriChoiceTreeView in
1168     let choices = ref None in
1169     (match copy_cb with
1170     | None -> ()
1171     | Some cb ->
1172         dialog#copyButton#misc#show ();
1173         connect_button dialog#copyButton 
1174         (fun _ ->
1175           match model#easy_selection () with
1176           | [u] -> (cb u)
1177           | _ -> ()));
1178     dialog#uriChoiceDialog#set_title title;
1179     dialog#uriChoiceLabel#set_text msg;
1180     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1181     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1182     let return v =
1183       choices := v;
1184       dialog#uriChoiceDialog#destroy ();
1185       GMain.Main.quit ()
1186     in
1187     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1188     connect_button dialog#uriChoiceConstantsButton (fun _ ->
1189       return (Some (Lazy.force nonvars_uris)));
1190     if ok_action = `AUTO then
1191       connect_button dialog#uriChoiceAutoButton (fun _ ->
1192         Helm_registry.set_bool "matita.auto_disambiguation" true;
1193         return (Some (Lazy.force nonvars_uris)))
1194     else
1195       connect_button dialog#uriChoiceAutoButton (fun _ ->
1196         match model#easy_selection () with
1197         | [] -> ()
1198         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1199     connect_button dialog#uriChoiceSelectedButton (fun _ ->
1200       match model#easy_selection () with
1201       | [] -> ()
1202       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1203     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1204     dialog#uriChoiceDialog#show ();
1205     GtkThread.main ();
1206     (match !choices with 
1207     | None -> raise MatitaTypes.Cancel
1208     | Some uris -> uris)
1209   end
1210
1211 class interpModel =
1212   let cols = new GTree.column_list in
1213   let id_col = cols#add Gobject.Data.string in
1214   let dsc_col = cols#add Gobject.Data.string in
1215   let interp_no_col = cols#add Gobject.Data.int in
1216   let tree_store = GTree.tree_store cols in
1217   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1218   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1219   let id_view_col = GTree.view_column ~renderer:id_renderer () in
1220   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1221   fun tree_view choices ->
1222     object
1223       initializer
1224         tree_view#set_model (Some (tree_store :> GTree.model));
1225         ignore (tree_view#append_column id_view_col);
1226         ignore (tree_view#append_column dsc_view_col);
1227         let name_of_interp =
1228           (* try to find a reasonable name for an interpretation *)
1229           let idx = ref 0 in
1230           fun interp ->
1231             try
1232               List.assoc "0" interp
1233             with Not_found ->
1234               incr idx; string_of_int !idx
1235         in
1236         tree_store#clear ();
1237         let idx = ref ~-1 in
1238         List.iter
1239           (fun interp ->
1240             incr idx;
1241             let interp_row = tree_store#append () in
1242             tree_store#set ~row:interp_row ~column:id_col
1243               (name_of_interp interp);
1244             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1245             List.iter
1246               (fun (id, dsc) ->
1247                 let row = tree_store#append ~parent:interp_row () in
1248                 tree_store#set ~row ~column:id_col id;
1249                 tree_store#set ~row ~column:dsc_col dsc;
1250                 tree_store#set ~row ~column:interp_no_col !idx)
1251               interp)
1252           choices
1253
1254       method get_interp_no tree_path =
1255         let iter = tree_store#get_iter tree_path in
1256         tree_store#get ~row:iter ~column:interp_no_col
1257     end
1258
1259 let interactive_interp_choice () choices =
1260   let gui = instance () in
1261   assert (choices <> []);
1262   let dialog = gui#newRecordDialog () in
1263   let model = new interpModel dialog#recordChoiceTreeView choices in
1264   dialog#recordChoiceDialog#set_title "Interpretation choice";
1265   dialog#recordChoiceDialogLabel#set_label "Choose an interpretation:";
1266   let interp_no = ref None in
1267   let return _ =
1268     dialog#recordChoiceDialog#destroy ();
1269     GMain.Main.quit ()
1270   in
1271   let fail _ = interp_no := None; return () in
1272   ignore (dialog#recordChoiceDialog#event#connect#delete (fun _ -> true));
1273   connect_button dialog#recordChoiceOkButton (fun _ ->
1274     match !interp_no with None -> () | Some _ -> return ());
1275   connect_button dialog#recordChoiceCancelButton fail;
1276   ignore (dialog#recordChoiceTreeView#connect#row_activated (fun path _ ->
1277     interp_no := Some (model#get_interp_no path);
1278     return ()));
1279   let selection = dialog#recordChoiceTreeView#selection in
1280   ignore (selection#connect#changed (fun _ ->
1281     match selection#get_selected_rows with
1282     | [path] -> interp_no := Some (model#get_interp_no path)
1283     | _ -> assert false));
1284   dialog#recordChoiceDialog#show ();
1285   GtkThread.main ();
1286   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
1287
1288 let _ =
1289   (* disambiguator callbacks *)
1290   GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1291   GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1292   (* gtk initialization *)
1293   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1294   GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1295   ignore (GMain.Main.init ())
1296