]> matita.cs.unibo.it Git - helm.git/blob - matita/matitaGui.ml
The Abort button is now working properly. Cool.
[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         source_view#set_editable false
419       in
420       let unlock_world _ =
421         main#buttonsToolbar#misc#set_sensitive true;
422         develList#buttonsHbox#misc#set_sensitive true;
423         source_view#set_editable true
424       in
425       let worker_thread = ref None in
426       let locker f () =
427        let thread_main =
428         fun () -> 
429           lock_world ();
430           try f ();unlock_world () with exc -> unlock_world (); raise exc
431        in
432         worker_thread := Some (Thread.create thread_main ()) in
433       let kill_worker =
434        (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
435        let interrupt = ref None in
436        let old_callback = ref (function _ -> ()) in
437        let force_interrupt n =
438          (* This function is called just before the thread's timeslice ends *)
439          !old_callback n;
440          if Some(Thread.id(Thread.self())) = !interrupt then
441           (interrupt := None; raise Sys.Break) in
442        let _ =
443         match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
444            Sys.Signal_handle f -> old_callback := f
445          | Sys.Signal_ignore
446          | Sys.Signal_default -> assert false
447        in
448         fun () ->
449          match !worker_thread with
450             None -> assert false
451           | Some t -> interrupt := Some (Thread.id t) in
452       let keep_focus f =
453         fun () ->
454          try
455           f (); source_view#misc#grab_focus ()
456          with
457           exc -> source_view#misc#grab_focus (); raise exc in
458         (* developments win *)
459       let model = 
460         new MatitaGtkMisc.multiStringListModel 
461           ~cols:2 develList#developmentsTreeview
462       in
463       let refresh_devels_win () =
464         model#list_store#clear ();
465         List.iter 
466           (fun (name, root) -> model#easy_mappend [name;root]) 
467           (MatitamakeLib.list_known_developments ())
468       in
469       let get_devel_selected () = 
470         match model#easy_mselection () with
471         | [[name;_]] -> MatitamakeLib.development_for_name name
472         | _ -> None
473       in
474       let refresh () = 
475         while Glib.Main.pending () do 
476           ignore(Glib.Main.iteration false); 
477         done
478       in
479       connect_button develList#newButton
480         (fun () -> 
481           next_devel_must_contain <- None;
482           newDevel#toplevel#misc#show());
483       connect_button develList#deleteButton
484         (locker (fun () -> 
485           (match get_devel_selected () with
486           | None -> ()
487           | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
488           refresh_devels_win ()));
489       connect_button develList#buildButton 
490         (locker (fun () -> 
491           match get_devel_selected () with
492           | None -> ()
493           | Some d -> 
494               let build = locker 
495                 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
496               in
497               ignore(build ())));
498       connect_button develList#cleanButton 
499         (locker (fun () -> 
500           match get_devel_selected () with
501           | None -> ()
502           | Some d -> 
503               let clean = locker 
504                 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
505               in
506               ignore(clean ())));
507       connect_button develList#publishButton 
508         (locker (fun () -> 
509           match get_devel_selected () with
510           | None -> ()
511           | Some d -> 
512               let publish = locker (fun () ->
513                 MatitamakeLib.publish_development_in_bg refresh d) in
514               ignore(publish ())));
515       connect_button develList#graphButton (fun () -> 
516         match get_devel_selected () with
517         | None -> ()
518         | Some d ->
519             (match MatitamakeLib.dot_for_development d with
520             | None -> ()
521             | Some _ ->
522                 let browser = MatitaMathView.cicBrowser () in
523                 browser#load (`Development
524                   (MatitamakeLib.name_for_development d))));
525       connect_button develList#closeButton 
526         (fun () -> develList#toplevel#misc#hide());
527       ignore(develList#toplevel#event#connect#delete 
528         (fun _ -> develList#toplevel#misc#hide();true));
529       connect_menu_item main#developmentsMenuItem
530         (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
531       
532         (* add development win *)
533       let check_if_root_contains root =
534         match next_devel_must_contain with
535         | None -> true
536         | Some path -> 
537             let is_prefix_of d1 d2 =
538               let len1 = String.length d1 in
539               let len2 = String.length d2 in
540               if len2 < len1 then 
541                 false
542               else
543                 let pref = String.sub d2 0 len1 in
544                 pref = d1
545             in
546             is_prefix_of root path
547       in
548       connect_button newDevel#addButton 
549        (fun () -> 
550           let name = newDevel#nameEntry#text in
551           let root = newDevel#rootEntry#text in
552           if check_if_root_contains root then
553             begin
554               ignore (MatitamakeLib.initialize_development name root);
555               refresh_devels_win ();
556               newDevel#nameEntry#set_text "";
557               newDevel#rootEntry#set_text "";
558               newDevel#toplevel#misc#hide()
559             end
560           else
561             HLog.error ("The selected root does not contain " ^ 
562               match next_devel_must_contain with 
563               | Some x -> x 
564               | _ -> assert false));
565       connect_button newDevel#chooseRootButton 
566        (fun () ->
567          let path = self#chooseDir () in
568          match path with
569          | Some path -> newDevel#rootEntry#set_text path
570          | None -> ());
571       connect_button newDevel#cancelButton 
572        (fun () -> newDevel#toplevel#misc#hide ());
573       ignore(newDevel#toplevel#event#connect#delete 
574         (fun _ -> newDevel#toplevel#misc#hide();true));
575       
576         (* file selection win *)
577       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
578       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
579         let return r =
580           chosen_file <- r;
581           fileSel#fileSelectionWin#misc#hide ();
582           GMain.Main.quit ()
583         in
584         match event with
585         | `OK ->
586             let fname = fileSel#fileSelectionWin#filename in
587             if Sys.file_exists fname then
588               begin
589                 if HExtlib.is_regular fname && not (_only_directory) then 
590                   return (Some fname) 
591                 else if _only_directory && HExtlib.is_dir fname then 
592                   return (Some fname)
593               end
594             else
595               begin
596                 if _ok_not_exists then 
597                   return (Some fname)
598               end
599         | `CANCEL -> return None
600         | `HELP -> ()
601         | `DELETE_EVENT -> return None));
602         (* menus *)
603       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
604         (* console *)
605       let adj = main#logScrolledWin#vadjustment in
606         ignore (adj#connect#changed
607                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
608       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
609         (* toolbar *)
610       let module A = GrafiteAst in
611       let hole = CicNotationPt.UserInput in
612       let loc = HExtlib.dummy_floc in
613       let tac ast _ =
614         if (MatitaScript.current ())#onGoingProof () then
615           (MatitaScript.current ())#advance
616             ~statement:("\n"
617               ^ GrafiteAstPp.pp_tactical ~term_pp:CicNotationPp.pp_term
618                 ~lazy_term_pp:CicNotationPp.pp_term (A.Tactic (loc, ast)))
619             ()
620       in
621       let tac_w_term ast _ =
622         if (MatitaScript.current ())#onGoingProof () then
623           let buf = source_buffer in
624           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
625             ("\n"
626             ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
627               ~lazy_term_pp:CicNotationPp.pp_term ast)
628       in
629       let tbar = main in
630       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
631       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
632       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
633       connect_button tbar#elimButton (tac_w_term
634         (A.Elim (loc, hole, None, None, [])));
635       connect_button tbar#elimTypeButton (tac_w_term
636         (A.ElimType (loc, hole, None, None, [])));
637       connect_button tbar#splitButton (tac (A.Split loc));
638       connect_button tbar#leftButton (tac (A.Left loc));
639       connect_button tbar#rightButton (tac (A.Right loc));
640       connect_button tbar#existsButton (tac (A.Exists loc));
641       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
642       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
643       connect_button tbar#transitivityButton
644         (tac_w_term (A.Transitivity (loc, hole)));
645       connect_button tbar#assumptionButton (tac (A.Assumption loc));
646       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
647       connect_button tbar#autoButton (tac (A.Auto (loc,[])));
648       MatitaGtkMisc.toggle_widget_visibility
649        ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
650        ~check:main#tacticsBarMenuItem;
651       let module Hr = Helm_registry in
652       if
653         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
654       then 
655         main#tacticsBarMenuItem#set_active false;
656       MatitaGtkMisc.toggle_callback 
657         ~callback:(function 
658           | true -> main#toplevel#fullscreen () 
659           | false -> main#toplevel#unfullscreen ())
660         ~check:main#fullscreenMenuItem;
661       main#fullscreenMenuItem#set_active false;
662         (* log *)
663       HLog.set_log_callback self#console#log_callback;
664       GtkSignal.user_handler :=
665         (function 
666         | MatitaScript.ActionCancelled s -> HLog.error s
667         | exn ->
668           if not (Helm_registry.get_bool "matita.debug") then
669            let floc, msg = MatitaExcPp.to_string exn in
670             begin
671              match floc with
672                 None -> ()
673               | Some floc ->
674                  let (x, y) = HExtlib.loc_of_floc floc in
675                  let script = MatitaScript.current () in
676                  let locked_mark = script#locked_mark in
677                  let error_tag = script#error_tag in
678                  let baseoffset =
679                   (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
680                  let x' = baseoffset + x in
681                  let y' = baseoffset + y in
682                  let x_iter = source_buffer#get_iter (`OFFSET x') in
683                  let y_iter = source_buffer#get_iter (`OFFSET y') in
684                  source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
685                  let id = ref None in
686                  id := Some (source_buffer#connect#changed ~callback:(fun () ->
687                    source_buffer#remove_tag error_tag
688                      ~start:source_buffer#start_iter
689                      ~stop:source_buffer#end_iter;
690                    match !id with
691                    | None -> assert false (* a race condition occurred *)
692                    | Some id ->
693                        (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
694                  source_buffer#place_cursor
695                   (source_buffer#get_iter (`OFFSET x'));
696             end;
697             HLog.error msg
698           else raise exn);
699         (* script *)
700       ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
701       let _ =
702         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
703         | None ->
704             HLog.warn (sprintf "can't load language file %s"
705               BuildTimeConf.lang_file)
706         | Some matita_lang ->
707             source_buffer#set_language matita_lang;
708             source_buffer#set_highlight true
709       in
710       let s () = MatitaScript.current () in
711       let disableSave () =
712         script_fname <- None;
713         main#saveMenuItem#misc#set_sensitive false
714       in
715       let saveAsScript () =
716         let script = s () in
717         match self#chooseFile ~ok_not_exists:true () with
718         | Some f -> 
719               script#assignFileName f;
720               script#saveToFile (); 
721               console#message ("'"^f^"' saved.\n");
722               self#_enableSaveTo f
723         | None -> ()
724       in
725       let saveScript () =
726         match script_fname with
727         | None -> saveAsScript ()
728         | Some f -> 
729               (s ())#assignFileName f;
730               (s ())#saveToFile ();
731               console#message ("'"^f^"' saved.\n");
732       in
733       let abandon_script () =
734         let lexicon_status = (s ())#lexicon_status in
735         let grafite_status = (s ())#grafite_status in
736         if source_view#buffer#modified then
737           (match ask_unsaved main#toplevel with
738           | `YES -> saveScript ()
739           | `NO -> ()
740           | `CANCEL -> raise MatitaTypes.Cancel);
741         (match script_fname with
742         | None -> ()
743         | Some fname ->
744            ask_and_save_moo_if_needed main#toplevel fname
745             lexicon_status grafite_status);
746       in
747       let loadScript () =
748         let script = s () in 
749         try 
750           match self#chooseFile () with
751           | Some f -> 
752               abandon_script ();
753               script#reset (); 
754               script#assignFileName f;
755               source_view#source_buffer#begin_not_undoable_action ();
756               script#loadFromFile f; 
757               source_view#source_buffer#end_not_undoable_action ();
758               console#message ("'"^f^"' loaded.\n");
759               self#_enableSaveTo f
760           | None -> ()
761         with MatitaTypes.Cancel -> ()
762       in
763       let newScript () = 
764         abandon_script ();
765         source_view#source_buffer#begin_not_undoable_action ();
766         (s ())#reset (); 
767         (s ())#template (); 
768         source_view#source_buffer#end_not_undoable_action ();
769         disableSave ();
770         script_fname <- None
771       in
772       let cursor () =
773         source_buffer#place_cursor
774           (source_buffer#get_iter_at_mark (`NAME "locked")) in
775       let advance _ = (MatitaScript.current ())#advance (); cursor () in
776       let retract _ = (MatitaScript.current ())#retract (); cursor () in
777       let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
778       let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
779       let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
780       let advance = locker (keep_focus advance) in
781       let retract = locker (keep_focus retract) in
782       let top = locker (keep_focus top) in
783       let bottom = locker (keep_focus bottom) in
784       let jump = locker (keep_focus jump) in
785         (* quit *)
786       self#setQuitCallback (fun () -> 
787         let lexicon_status = (MatitaScript.current ())#lexicon_status in
788         let grafite_status = (MatitaScript.current ())#grafite_status in
789         if source_view#buffer#modified then
790           begin
791             let rc = ask_unsaved main#toplevel in 
792             try
793               match rc with
794               | `YES -> saveScript ();
795                         if not source_view#buffer#modified then
796                           begin
797                             (match script_fname with
798                             | None -> ()
799                             | Some fname -> 
800                                ask_and_save_moo_if_needed main#toplevel
801                                 fname lexicon_status grafite_status);
802                           GMain.Main.quit ()
803                           end
804               | `NO -> GMain.Main.quit ()
805               | `CANCEL -> raise MatitaTypes.Cancel
806             with MatitaTypes.Cancel -> ()
807           end 
808         else 
809           begin  
810             (match script_fname with
811             | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
812             | Some fname ->
813                 try
814                   ask_and_save_moo_if_needed main#toplevel fname lexicon_status
815                    grafite_status;
816                   GMain.Main.quit ()
817                 with MatitaTypes.Cancel -> ())
818           end);
819       connect_button main#scriptAdvanceButton advance;
820       connect_button main#scriptRetractButton retract;
821       connect_button main#scriptTopButton top;
822       connect_button main#scriptBottomButton bottom;
823       connect_button main#scriptJumpButton jump;
824       connect_button main#scriptAbortButton kill_worker;
825       connect_menu_item main#scriptAdvanceMenuItem advance;
826       connect_menu_item main#scriptRetractMenuItem retract;
827       connect_menu_item main#scriptTopMenuItem top;
828       connect_menu_item main#scriptBottomMenuItem bottom;
829       connect_menu_item main#scriptJumpMenuItem jump;
830       connect_menu_item main#openMenuItem   loadScript;
831       connect_menu_item main#saveMenuItem   saveScript;
832       connect_menu_item main#saveAsMenuItem saveAsScript;
833       connect_menu_item main#newMenuItem    newScript;
834          (* script monospace font stuff *)  
835       self#updateFontSize ();
836         (* debug menu *)
837       main#debugMenu#misc#hide ();
838         (* status bar *)
839       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
840       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
841       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
842         (* focus *)
843       self#sourceView#misc#grab_focus ();
844         (* main win dimension *)
845       let width = Gdk.Screen.width () in
846       let height = Gdk.Screen.height () in
847       let main_w = width * 90 / 100 in 
848       let main_h = height * 80 / 100 in
849       let script_w = main_w * 6 / 10 in
850       main#toplevel#resize ~width:main_w ~height:main_h;
851       main#hpaneScriptSequent#set_position script_w;
852         (* source_view *)
853       ignore(source_view#connect#after#paste_clipboard 
854         ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
855       (* clean_locked is set to true only "during" a PRIMARY paste
856          operation (i.e. by clicking with the second mouse button) *)
857       let clean_locked = ref false in
858       ignore(source_view#event#connect#button_press
859         ~callback:
860           (fun button ->
861             if GdkEvent.Button.button button = 2 then
862              clean_locked := true;
863             false
864           ));
865       ignore(source_view#event#connect#button_release
866         ~callback:(fun button -> clean_locked := false; false));
867       ignore(source_view#buffer#connect#after#apply_tag
868        ~callback:(
869          fun tag ~start:_ ~stop:_ ->
870           if !clean_locked &&
871              tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
872           then
873            begin
874             clean_locked := false;
875             (MatitaScript.current ())#clean_dirty_lock;
876             clean_locked := true
877            end));
878       (* math view handling *)
879       connect_menu_item main#newCicBrowserMenuItem (fun () ->
880         ignore (MatitaMathView.cicBrowser ()));
881       connect_menu_item main#increaseFontSizeMenuItem (fun () ->
882         self#increaseFontSize ();
883         MatitaMathView.increase_font_size ();
884         MatitaMathView.update_font_sizes ());
885       connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
886         self#decreaseFontSize ();
887         MatitaMathView.decrease_font_size ();
888         MatitaMathView.update_font_sizes ());
889       connect_menu_item main#normalFontSizeMenuItem (fun () ->
890         self#resetFontSize ();
891         MatitaMathView.reset_font_size ();
892         MatitaMathView.update_font_sizes ());
893       MatitaMathView.reset_font_size ();
894
895       (** selections / clipboards handling *)
896
897     method markupSelected = MatitaMathView.has_selection ()
898     method private textSelected =
899       (source_buffer#get_iter_at_mark `INSERT)#compare
900         (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
901     method private somethingSelected = self#markupSelected || self#textSelected
902     method private markupStored = MatitaMathView.has_clipboard ()
903     method private textStored = clipboard#text <> None
904     method private somethingStored = self#markupStored || self#textStored
905
906     method canCopy = self#somethingSelected
907     method canCut = self#textSelected
908     method canDelete = self#textSelected
909     method canPaste = self#somethingStored
910     method canPastePattern = self#markupStored
911
912     method copy () =
913       if self#textSelected
914       then begin
915         MatitaMathView.empty_clipboard ();
916         source_view#buffer#copy_clipboard clipboard;
917       end else
918         MatitaMathView.copy_selection ()
919     method cut () =
920       source_view#buffer#cut_clipboard clipboard;
921       MatitaMathView.empty_clipboard ()
922     method delete () = ignore (source_view#buffer#delete_selection ())
923     method paste () =
924       if MatitaMathView.has_clipboard ()
925       then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
926       else source_view#buffer#paste_clipboard clipboard;
927       (MatitaScript.current ())#clean_dirty_lock
928     method pastePattern () =
929       source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
930     
931     method private nextLigature () =
932       let iter = source_buffer#get_iter_at_mark `INSERT in
933       let write_ligature len s =
934         assert(Glib.Utf8.validate s);
935         source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
936         source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
937       in
938       let get_ligature word =
939         let len = String.length word in
940         let aux_tex () =
941           try
942             for i = len - 1 downto 0 do
943               if HExtlib.is_alpha word.[i] then ()
944               else
945                 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
946             done;
947             None
948           with Found i ->
949             if i = ~-1 then None else Some (String.sub word i (len - i))
950         in
951         let aux_ligature () =
952           try
953             for i = len - 1 downto 0 do
954               if CicNotationLexer.is_ligature_char word.[i] then ()
955               else raise (Found (i+1))
956             done;
957             raise (Found 0)
958           with
959           | Found i ->
960               (try
961                 Some (String.sub word i (len - i))
962               with Invalid_argument _ -> None)
963         in
964         match aux_tex () with
965         | Some macro -> macro
966         | None -> (match aux_ligature () with Some l -> l | None -> word)
967       in
968       (match next_ligatures with
969       | [] -> (* find ligatures and fill next_ligatures, then try again *)
970           let last_word =
971             iter#get_slice
972               ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
973           in
974           let ligature = get_ligature last_word in
975           (match CicNotationLexer.lookup_ligatures ligature with
976           | [] -> ()
977           | hd :: tl ->
978               write_ligature (MatitaGtkMisc.utf8_string_length ligature) hd;
979               next_ligatures <- tl @ [ hd ])
980       | hd :: tl ->
981           write_ligature 1 hd;
982           next_ligatures <- tl @ [ hd ])
983
984     method private externalEditor () =
985       let cmd = Helm_registry.get "matita.external_editor" in
986 (* ZACK uncomment to enable interactive ask of external editor command *)
987 (*      let cmd =
988          let msg =
989           "External editor command:
990 %f  will be substitute for the script name,
991 %p  for the cursor position in bytes,
992 %l  for the execution point in bytes."
993         in
994         ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
995           ~default:(Helm_registry.get "matita.external_editor") ()
996       in *)
997       let fname = (MatitaScript.current ())#filename in
998       let slice mark =
999         source_buffer#start_iter#get_slice
1000           ~stop:(source_buffer#get_iter_at_mark mark)
1001       in
1002       let script = MatitaScript.current () in
1003       let locked = `MARK script#locked_mark in
1004       let string_pos mark = string_of_int (String.length (slice mark)) in
1005       let cursor_pos = string_pos `INSERT in
1006       let locked_pos = string_pos locked in
1007       let cmd =
1008         Pcre.replace ~pat:"%f" ~templ:fname
1009           (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1010             (Pcre.replace ~pat:"%l" ~templ:locked_pos
1011               cmd))
1012       in
1013       let locked_before = slice locked in
1014       let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1015       ignore (Unix.system cmd);
1016       source_buffer#set_text (HExtlib.input_file fname);
1017       let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1018       source_buffer#move_mark locked locked_iter;
1019       source_buffer#apply_tag script#locked_tag
1020         ~start:source_buffer#start_iter ~stop:locked_iter;
1021       let locked_after = slice locked in
1022       let line = ref 0 in
1023       let col = ref 0 in
1024       try
1025         for i = 0 to String.length locked_before - 1 do
1026           if locked_before.[i] <> locked_after.[i] then begin
1027             source_buffer#place_cursor
1028               ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1029             script#goto `Cursor ();
1030             raise Exit
1031           end else if locked_before.[i] = '\n' then begin
1032             incr line;
1033             col := 0
1034           end
1035         done
1036       with
1037       | Exit -> ()
1038       | Invalid_argument _ -> script#goto `Bottom ()
1039
1040     method loadScript file =       
1041       let script = MatitaScript.current () in
1042       script#reset (); 
1043       if Pcre.pmatch ~pat:"\\.p$" file then
1044         begin
1045           let tptppath = 
1046             Helm_registry.get_opt_default Helm_registry.string ~default:"./"
1047               "matita.tptppath"
1048           in
1049           let data = Matitaprover.p_to_ma ~filename:file ~tptppath () in
1050           let filename = Pcre.replace ~pat:"\\.p$" ~templ:".ma" file in
1051           script#assignFileName filename;
1052           source_view#source_buffer#begin_not_undoable_action ();
1053           script#loadFromString data;
1054           source_view#source_buffer#end_not_undoable_action ();
1055           console#message ("'"^filename^"' loaded.");
1056           self#_enableSaveTo filename
1057         end
1058       else
1059         begin
1060           script#assignFileName file;
1061           let content =
1062            if Sys.file_exists file then file
1063            else BuildTimeConf.script_template
1064           in
1065            source_view#source_buffer#begin_not_undoable_action ();
1066            script#loadFromFile content;
1067            source_view#source_buffer#end_not_undoable_action ();
1068            console#message ("'"^file^"' loaded.");
1069            self#_enableSaveTo file
1070         end
1071       
1072     method setStar name b =
1073       let l = main#scriptLabel in
1074       if b then
1075         l#set_text (name ^  " *")
1076       else
1077         l#set_text (name)
1078         
1079     method private _enableSaveTo file =
1080       script_fname <- Some file;
1081       self#main#saveMenuItem#misc#set_sensitive true
1082         
1083     method console = console
1084     method sourceView: GSourceView.source_view =
1085       (source_view: GSourceView.source_view)
1086     method fileSel = fileSel
1087     method findRepl = findRepl
1088     method main = main
1089     method develList = develList
1090     method newDevel = newDevel
1091
1092     method newBrowserWin () =
1093       object (self)
1094         inherit browserWin ()
1095         val combo = GEdit.combo_box_entry ()
1096         initializer
1097           self#check_widgets ();
1098           let combo_widget = combo#coerce in
1099           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1100           combo#entry#misc#grab_focus ()
1101         method browserUri = combo
1102       end
1103
1104     method newUriDialog () =
1105       let dialog = new uriChoiceDialog () in
1106       dialog#check_widgets ();
1107       dialog
1108
1109     method newRecordDialog () =
1110       let dialog = new recordChoiceDialog () in
1111       dialog#check_widgets ();
1112       dialog
1113
1114     method newConfirmationDialog () =
1115       let dialog = new confirmationDialog () in
1116       dialog#check_widgets ();
1117       dialog
1118
1119     method newEmptyDialog () =
1120       let dialog = new emptyDialog () in
1121       dialog#check_widgets ();
1122       dialog
1123
1124     method private addKeyBinding key callback =
1125       List.iter (fun evbox -> add_key_binding key callback evbox)
1126         keyBindingBoxes
1127
1128     method setQuitCallback callback =
1129       connect_menu_item main#quitMenuItem callback;
1130       ignore (main#toplevel#event#connect#delete 
1131         (fun _ -> callback ();true));
1132       self#addKeyBinding GdkKeysyms._q callback
1133
1134     method chooseFile ?(ok_not_exists = false) () =
1135       _ok_not_exists <- ok_not_exists;
1136       _only_directory <- false;
1137       fileSel#fileSelectionWin#show ();
1138       GtkThread.main ();
1139       chosen_file
1140
1141     method private chooseDir ?(ok_not_exists = false) () =
1142       _ok_not_exists <- ok_not_exists;
1143       _only_directory <- true;
1144       fileSel#fileSelectionWin#show ();
1145       GtkThread.main ();
1146       (* we should check that this is a directory *)
1147       chosen_file
1148   
1149     method createDevelopment ~containing =
1150       next_devel_must_contain <- containing;
1151       newDevel#toplevel#misc#show()
1152
1153     method askText ?(title = "") ?(msg = "") () =
1154       let dialog = new textDialog () in
1155       dialog#textDialog#set_title title;
1156       dialog#textDialogLabel#set_label msg;
1157       let text = ref None in
1158       let return v =
1159         text := v;
1160         dialog#textDialog#destroy ();
1161         GMain.Main.quit ()
1162       in
1163       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1164       connect_button dialog#textDialogCancelButton (fun _ -> return None);
1165       connect_button dialog#textDialogOkButton (fun _ ->
1166         let text = dialog#textDialogTextView#buffer#get_text () in
1167         return (Some text));
1168       dialog#textDialog#show ();
1169       GtkThread.main ();
1170       !text
1171
1172     method private updateFontSize () =
1173       self#sourceView#misc#modify_font_by_name
1174         (sprintf "%s %d" BuildTimeConf.script_font font_size)
1175
1176     method increaseFontSize () =
1177       font_size <- font_size + 1;
1178       self#updateFontSize ()
1179
1180     method decreaseFontSize () =
1181       font_size <- font_size - 1;
1182       self#updateFontSize ()
1183
1184     method resetFontSize () =
1185       font_size <- default_font_size;
1186       self#updateFontSize ()
1187
1188   end
1189
1190 let gui () = 
1191   let g = new gui () in
1192   gui_instance := Some g;
1193   MatitaMathView.set_gui g;
1194   g
1195   
1196 let instance = singleton gui
1197
1198 let non p x = not (p x)
1199
1200 (* this is a shit and should be changed :-{ *)
1201 let interactive_uri_choice
1202   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1203   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
1204   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
1205   ?copy_cb ()
1206   ~id uris
1207 =
1208   let gui = instance () in
1209   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1210   if (selection_mode <> `SINGLE) &&
1211     (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1212   then
1213     Lazy.force nonvars_uris
1214   else begin
1215     let dialog = gui#newUriDialog () in
1216     if hide_uri_entry then
1217       dialog#uriEntryHBox#misc#hide ();
1218     if hide_try then
1219       begin
1220       dialog#uriChoiceSelectedButton#misc#hide ();
1221       dialog#uriChoiceConstantsButton#misc#hide ();
1222       end;
1223     dialog#okLabel#set_label ok_label;  
1224     dialog#uriChoiceTreeView#selection#set_mode
1225       (selection_mode :> Gtk.Tags.selection_mode);
1226     let model = new stringListModel dialog#uriChoiceTreeView in
1227     let choices = ref None in
1228     (match copy_cb with
1229     | None -> ()
1230     | Some cb ->
1231         dialog#copyButton#misc#show ();
1232         connect_button dialog#copyButton 
1233         (fun _ ->
1234           match model#easy_selection () with
1235           | [u] -> (cb u)
1236           | _ -> ()));
1237     dialog#uriChoiceDialog#set_title title;
1238     dialog#uriChoiceLabel#set_text msg;
1239     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1240     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1241     let return v =
1242       choices := v;
1243       dialog#uriChoiceDialog#destroy ();
1244       GMain.Main.quit ()
1245     in
1246     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1247     connect_button dialog#uriChoiceConstantsButton (fun _ ->
1248       return (Some (Lazy.force nonvars_uris)));
1249     if ok_action = `AUTO then
1250       connect_button dialog#uriChoiceAutoButton (fun _ ->
1251         Helm_registry.set_bool "matita.auto_disambiguation" true;
1252         return (Some (Lazy.force nonvars_uris)))
1253     else
1254       connect_button dialog#uriChoiceAutoButton (fun _ ->
1255         match model#easy_selection () with
1256         | [] -> ()
1257         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1258     connect_button dialog#uriChoiceSelectedButton (fun _ ->
1259       match model#easy_selection () with
1260       | [] -> ()
1261       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1262     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1263     dialog#uriChoiceDialog#show ();
1264     GtkThread.main ();
1265     (match !choices with 
1266     | None -> raise MatitaTypes.Cancel
1267     | Some uris -> uris)
1268   end
1269
1270 class interpModel =
1271   let cols = new GTree.column_list in
1272   let id_col = cols#add Gobject.Data.string in
1273   let dsc_col = cols#add Gobject.Data.string in
1274   let interp_no_col = cols#add Gobject.Data.int in
1275   let tree_store = GTree.tree_store cols in
1276   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1277   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1278   let id_view_col = GTree.view_column ~renderer:id_renderer () in
1279   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1280   fun tree_view choices ->
1281     object
1282       initializer
1283         tree_view#set_model (Some (tree_store :> GTree.model));
1284         ignore (tree_view#append_column id_view_col);
1285         ignore (tree_view#append_column dsc_view_col);
1286         let name_of_interp =
1287           (* try to find a reasonable name for an interpretation *)
1288           let idx = ref 0 in
1289           fun interp ->
1290             try
1291               List.assoc "0" interp
1292             with Not_found ->
1293               incr idx; string_of_int !idx
1294         in
1295         tree_store#clear ();
1296         let idx = ref ~-1 in
1297         List.iter
1298           (fun interp ->
1299             incr idx;
1300             let interp_row = tree_store#append () in
1301             tree_store#set ~row:interp_row ~column:id_col
1302               (name_of_interp interp);
1303             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1304             List.iter
1305               (fun (id, dsc) ->
1306                 let row = tree_store#append ~parent:interp_row () in
1307                 tree_store#set ~row ~column:id_col id;
1308                 tree_store#set ~row ~column:dsc_col dsc;
1309                 tree_store#set ~row ~column:interp_no_col !idx)
1310               interp)
1311           choices
1312
1313       method get_interp_no tree_path =
1314         let iter = tree_store#get_iter tree_path in
1315         tree_store#get ~row:iter ~column:interp_no_col
1316     end
1317
1318 let interactive_interp_choice () = 
1319   fun text prefix_len choices ->
1320   let gui = instance () in
1321   assert (choices <> []);
1322   let dialog = gui#newRecordDialog () in
1323   let model = new interpModel dialog#recordChoiceTreeView choices in
1324   dialog#recordChoiceDialog#set_title "Interpretation choice";
1325   dialog#recordChoiceDialogLabel#set_label "Choose an interpretation:";
1326   let interp_no = ref None in
1327   let return _ =
1328     dialog#recordChoiceDialog#destroy ();
1329     GMain.Main.quit ()
1330   in
1331   let fail _ = interp_no := None; return () in
1332   ignore (dialog#recordChoiceDialog#event#connect#delete (fun _ -> true));
1333   connect_button dialog#recordChoiceOkButton (fun _ ->
1334     match !interp_no with None -> () | Some _ -> return ());
1335   connect_button dialog#recordChoiceCancelButton fail;
1336   ignore (dialog#recordChoiceTreeView#connect#row_activated (fun path _ ->
1337     interp_no := Some (model#get_interp_no path);
1338     return ()));
1339   let selection = dialog#recordChoiceTreeView#selection in
1340   ignore (selection#connect#changed (fun _ ->
1341     match selection#get_selected_rows with
1342     | [path] -> interp_no := Some (model#get_interp_no path)
1343     | _ -> assert false));
1344   dialog#recordChoiceDialog#show ();
1345   GtkThread.main ();
1346   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
1347
1348 let interactive_string_choice 
1349   text prefix_len ?(title = "") ?(msg = "") () ~id locs uris 
1350 =
1351   let gui = instance () in
1352     let dialog = gui#newUriDialog () in
1353     dialog#uriEntryHBox#misc#hide ();
1354     dialog#uriChoiceSelectedButton#misc#hide ();
1355     dialog#uriChoiceAutoButton#misc#hide ();
1356     dialog#uriChoiceConstantsButton#misc#hide ();
1357     dialog#uriChoiceTreeView#selection#set_mode
1358       (`SINGLE :> Gtk.Tags.selection_mode);
1359     let model = new stringListModel dialog#uriChoiceTreeView in
1360     let choices = ref None in
1361     dialog#uriChoiceDialog#set_title title; 
1362     let hack_len = MatitaGtkMisc.utf8_string_length text in
1363     let rec colorize acc_len = function
1364       | [] -> 
1365           let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1366           fst(MatitaGtkMisc.utf8_parsed_text text floc)
1367       | he::tl -> 
1368           let start, stop =  HExtlib.loc_of_floc he in
1369           let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1370           let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1371           let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1372           str1 ^ "<b>" ^ str2 ^ "</b>" ^ colorize stop tl
1373     in
1374 (*     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1375                 Printf.eprintf "(%d,%d)" start stop) locs; *)
1376     let locs = 
1377       List.sort 
1378         (fun loc1 loc2 -> 
1379           fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2)) 
1380         locs 
1381     in
1382 (*     prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1383     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1384                 Printf.eprintf "(%d,%d)" start stop) locs;
1385     prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1386     dialog#uriChoiceLabel#set_use_markup true;
1387     let txt = colorize 0 locs in
1388     let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1389       (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1390     in
1391     dialog#uriChoiceLabel#set_label txt;
1392     List.iter model#easy_append uris;
1393     let return v =
1394       choices := v;
1395       dialog#uriChoiceDialog#destroy ();
1396       GMain.Main.quit ()
1397     in
1398     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1399     connect_button dialog#uriChoiceForwardButton (fun _ ->
1400       match model#easy_selection () with
1401       | [] -> ()
1402       | uris -> return (Some uris));
1403     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1404     dialog#uriChoiceDialog#show ();
1405     GtkThread.main ();
1406     (match !choices with 
1407     | None -> raise MatitaTypes.Cancel
1408     | Some uris -> uris)
1409
1410 let interactive_interp_choice () text prefix_len choices =
1411 (*  List.iter (fun (l,_,_) -> 
1412    List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1413    Printf.eprintf "(%d,%d)" start stop) l; prerr_endline "")
1414    ((List.hd choices)); *)
1415  let filter_choices filter =
1416   let rec is_compatible filter =
1417    function
1418       [] -> true
1419     | (_,id,dsc)::tl ->
1420        try
1421         if List.assoc id filter = dsc then
1422          is_compatible filter tl
1423         else
1424          false
1425        with
1426         Not_found -> true
1427   in
1428    List.filter (fun (_,interp) -> is_compatible filter interp)
1429  in
1430  let rec get_choices id =
1431   function
1432      [] -> []
1433    | (_,he)::tl ->
1434       let _,_,dsc = List.find (fun (_,id',_) -> id = id') he in
1435        dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices id tl))
1436  in
1437  let example_interp =
1438   match choices with
1439      [] -> assert false
1440    | he::_ -> he in
1441  let ask_user id locs choices =
1442   interactive_string_choice
1443    text prefix_len
1444    ~title:"Ambiguous input"
1445    ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1446  in
1447  let rec classify ids filter partial_interpretations =
1448   match ids with
1449      [] -> List.map fst partial_interpretations
1450    | (locs,id,_)::tl ->
1451       let choices = get_choices id partial_interpretations in
1452       let chosen_dsc =
1453        match choices with
1454           [dsc] -> dsc
1455         | _ ->
1456           match ask_user id locs choices with
1457              [x] -> x
1458            | _ -> assert false
1459       in
1460       let filter = (id,chosen_dsc)::filter in
1461       let compatible_interps = filter_choices filter partial_interpretations in
1462        classify tl filter compatible_interps in
1463  let enumerated_choices =
1464   let idx = ref ~-1 in
1465   List.map (fun interp -> incr idx; !idx,interp) choices
1466  in
1467   classify example_interp [] enumerated_choices
1468
1469 let _ =
1470   (* disambiguator callbacks *)
1471   GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1472   GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1473   (* gtk initialization *)
1474   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1475   GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1476   ignore (GMain.Main.init ())
1477