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