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