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