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