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