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