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