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