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