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