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