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