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