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