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