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