]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaGui.ml
added support for expansion of ligatures ALT-L will trigger it
[helm.git] / helm / 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 open Printf
27
28 open MatitaGeneratedGui
29 open MatitaGtkMisc
30 open MatitaMisc
31
32 let gui_instance = ref None
33
34 class type browserWin =
35   (* this class exists only because GEdit.combo_box_entry is not supported by
36    * lablgladecc :-(((( *)
37 object
38   inherit MatitaGeneratedGui.browserWin
39   method browserUri: GEdit.combo_box_entry
40 end
41
42 class console ~(buffer: GText.buffer) () =
43   object (self)
44     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
45     val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
46     val message_tag = buffer#create_tag []
47     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
48     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
49     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
50     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
51     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
52     method clear () =
53       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
54     method log_callback (tag: MatitaLog.log_tag) s =
55       match tag with
56       | `Debug -> self#debug (s ^ "\n")
57       | `Error -> self#error (s ^ "\n")
58       | `Message -> self#message (s ^ "\n")
59       | `Warning -> self#warning (s ^ "\n")
60   end
61         
62 let clean_current_baseuri status = 
63     try  
64       let baseuri = MatitaTypes.get_string_option status "baseuri" in
65       MatitacleanLib.clean_baseuris [baseuri]
66     with MatitaTypes.Option_error _ -> ()
67
68 let ask_and_save_moo_if_needed parent fname status = 
69   let save () =
70     let moo_fname = MatitacleanLib.obj_file_of_script fname in
71     MatitaMoo.save_moo moo_fname status.MatitaTypes.moo_content_rev in
72   if (MatitaScript.current ())#eos &&
73      status.MatitaTypes.proof_status = MatitaTypes.No_proof
74   then
75     begin
76       let mooname = 
77         MatitacleanLib.obj_file_of_script fname
78       in
79       let rc = 
80         MatitaGtkMisc.ask_confirmation
81         ~title:"A .moo can be generated"
82         ~message:(Printf.sprintf 
83           "%s can be generated for %s.\n<i>Should I generate it?</i>"
84           (Filename.basename mooname) (Filename.basename fname))
85         ~parent ()
86       in
87       let b = 
88         match rc with 
89         | `YES -> true 
90         | `NO -> false 
91         | `CANCEL -> raise MatitaTypes.Cancel 
92       in
93       if b then
94         save ()
95       else
96         clean_current_baseuri status
97     end
98   else
99     clean_current_baseuri status 
100     
101 let ask_unsaved parent =
102   MatitaGtkMisc.ask_confirmation 
103     ~parent ~title:"Unsaved work!" 
104     ~message:("Your work is <b>unsaved</b>!\n\n"^
105          "<i>Do you want to save the script before continuing?</i>")
106     ()
107
108 class gui () =
109     (* creation order _is_ relevant for windows placement *)
110   let main = new mainWin () in
111   let fileSel = new fileSelectionWin () in
112   let findRepl = new findReplWin () in
113   let develList = new develListWin () in
114   let newDevel = new newDevelWin () in
115   let keyBindingBoxes = (* event boxes which should receive global key events *)
116     [ main#mainWinEventBox ]
117   in
118   let console = new console ~buffer:main#logTextView#buffer () in
119   let (source_view: GSourceView.source_view) =
120     GSourceView.source_view
121       ~auto_indent:true
122       ~insert_spaces_instead_of_tabs:true ~tabs_width:2
123       ~margin:80 ~show_margin:true
124       ~smart_home_end:true
125       ~packing:main#scriptScrolledWin#add
126       ()
127   in
128   let default_font_size =
129     Helm_registry.get_opt_default Helm_registry.int
130       ~default:BuildTimeConf.default_font_size "matita.font_size"
131   in
132   let source_buffer = source_view#source_buffer in
133   object (self)
134     val mutable chosen_file = None
135     val mutable _ok_not_exists = false
136     val mutable _only_directory = false
137     val mutable script_fname = None
138     val mutable font_size = default_font_size
139     val mutable next_devel_must_contain = None
140     val mutable next_ligatures = []
141    
142     initializer
143         (* glade's check widgets *)
144       List.iter (fun w -> w#check_widgets ())
145         (let c w = (w :> <check_widgets: unit -> unit>) in
146         [ c fileSel; c main; c findRepl]);
147         (* key bindings *)
148       List.iter (* global key bindings *)
149         (fun (key, callback) -> self#addKeyBinding key callback)
150 (*
151         [ GdkKeysyms._F3,
152             toggle_win ~check:main#showProofMenuItem proof#proofWin;
153           GdkKeysyms._F4,
154             toggle_win ~check:main#showCheckMenuItem check#checkWin;
155 *)
156         [ ];
157         (* about win *)
158       let parse_txt_file file =
159        let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
160        let l_rev = ref [] in
161        try
162         while true do
163          l_rev := input_line ch :: !l_rev;
164         done;
165         assert false
166        with
167         End_of_file ->
168          close_in ch;
169          List.rev !l_rev in 
170       let about_dialog =
171        GWindow.about_dialog
172         ~authors:(parse_txt_file "AUTHORS")
173         (*~comments:"comments"*)
174         ~copyright:"Copyright (C) 2005, the HELM team"
175         ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
176         ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
177         ~name:"Matita"
178         ~version:BuildTimeConf.version
179         ~website:"http://helm.cs.unibo.it"
180         ()
181       in
182       connect_menu_item main#aboutMenuItem about_dialog#present;
183         (* findRepl win *)
184       let show_find_Repl () = 
185         findRepl#toplevel#misc#show ();
186         findRepl#toplevel#misc#grab_focus ()
187       in
188       let hide_find_Repl () = findRepl#toplevel#misc#hide () in
189       let find_forward _ = 
190           let highlight start end_ =
191             source_buffer#move_mark `INSERT ~where:start;
192             source_buffer#move_mark `SEL_BOUND ~where:end_;
193             source_view#scroll_mark_onscreen `INSERT
194           in
195           let text = findRepl#findEntry#text in
196           let iter = source_buffer#get_iter `SEL_BOUND in
197           match iter#forward_search text with
198           | None -> 
199               (match source_buffer#start_iter#forward_search text with
200               | None -> ()
201               | Some (start,end_) -> highlight start end_)
202           | Some (start,end_) -> highlight start end_ 
203       in
204       let replace _ =
205         let text = findRepl#replaceEntry#text in
206         let ins = source_buffer#get_iter `INSERT in
207         let sel = source_buffer#get_iter `SEL_BOUND in
208         if ins#compare sel < 0 then 
209           begin
210             ignore(source_buffer#delete_selection ());
211             source_buffer#insert text
212           end
213       in
214       connect_button findRepl#findButton find_forward;
215       connect_button findRepl#findReplButton replace;
216       connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
217       ignore(findRepl#toplevel#event#connect#delete 
218         ~callback:(fun _ -> hide_find_Repl ();true));
219       let safe_undo =
220        fun () ->
221         (* phase 1: we save the actual status of the marks and we undo *)
222         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
223         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
224         let locked_iter_offset = locked_iter#offset in
225         let mark2 =
226          `MARK
227            (source_view#buffer#create_mark ~name:"lock_point"
228              ~left_gravity:true locked_iter) in
229         source_view#source_buffer#undo ();
230         (* phase 2: we save the cursor position and we redo, restoring
231            the previous status of all the marks *)
232         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
233         let mark =
234          `MARK
235            (source_view#buffer#create_mark ~name:"undo_point"
236              ~left_gravity:true cursor_iter)
237         in
238          source_view#source_buffer#redo ();
239          let mark_iter = source_view#buffer#get_iter_at_mark mark in
240          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
241          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
242           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
243           source_view#buffer#delete_mark mark;
244           source_view#buffer#delete_mark mark2;
245           (* phase 3: if after the undo the cursor was in the locked area,
246              then we move it there again and we perform a goto *)
247           if mark_iter#offset < locked_iter_offset then
248            begin
249             source_view#buffer#move_mark `INSERT ~where:mark_iter;
250             (MatitaScript.current ())#goto `Cursor ();
251            end;
252           (* phase 4: we perform again the undo. This time we are sure that
253              the text to undo is not locked *)
254           source_view#source_buffer#undo ();
255           source_view#misc#grab_focus () in
256       let safe_redo =
257        fun () ->
258         (* phase 1: we save the actual status of the marks, we redo and
259            we undo *)
260         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
261         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
262         let locked_iter_offset = locked_iter#offset in
263         let mark2 =
264          `MARK
265            (source_view#buffer#create_mark ~name:"lock_point"
266              ~left_gravity:true locked_iter) in
267         source_view#source_buffer#redo ();
268         source_view#source_buffer#undo ();
269         (* phase 2: we save the cursor position and we restore
270            the previous status of all the marks *)
271         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
272         let mark =
273          `MARK
274            (source_view#buffer#create_mark ~name:"undo_point"
275              ~left_gravity:true cursor_iter)
276         in
277          let mark_iter = source_view#buffer#get_iter_at_mark mark in
278          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
279          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
280           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
281           source_view#buffer#delete_mark mark;
282           source_view#buffer#delete_mark mark2;
283           (* phase 3: if after the undo the cursor is in the locked area,
284              then we move it there again and we perform a goto *)
285           if mark_iter#offset < locked_iter_offset then
286            begin
287             source_view#buffer#move_mark `INSERT ~where:mark_iter;
288             (MatitaScript.current ())#goto `Cursor ();
289            end;
290           (* phase 4: we perform again the redo. This time we are sure that
291              the text to redo is not locked *)
292           source_view#source_buffer#redo ();
293           source_view#misc#grab_focus ()
294       in
295       connect_menu_item main#undoMenuItem safe_undo;
296       ignore(source_view#source_buffer#connect#can_undo
297         ~callback:main#undoMenuItem#misc#set_sensitive);
298       connect_menu_item main#redoMenuItem safe_redo;
299       ignore(source_view#source_buffer#connect#can_redo
300         ~callback:main#redoMenuItem#misc#set_sensitive);
301       ignore(source_view#connect#after#populate_popup
302        ~callback:(fun pre_menu ->
303          let menu = new GMenu.menu pre_menu in
304          let menuItems = menu#children in
305          let undoMenuItem, redoMenuItem =
306           match menuItems with
307              [undo;redo;sep1;cut;copy;paste;delete;sep2;
308               selectall;sep3;inputmethod;insertunicodecharacter] -> undo,redo
309            | _ -> assert false in
310          let new_undoMenuItem =
311           GMenu.image_menu_item
312            ~image:(GMisc.image ~stock:`UNDO ())
313            ~use_mnemonic:true
314            ~label:"_Undo"
315            ~packing:(menu#insert ~pos:0) () in
316          new_undoMenuItem#misc#set_sensitive
317           (undoMenuItem#misc#get_flag `SENSITIVE);
318          menu#remove (undoMenuItem :> GMenu.menu_item);
319          connect_menu_item new_undoMenuItem safe_undo;
320          let new_redoMenuItem =
321           GMenu.image_menu_item
322            ~image:(GMisc.image ~stock:`REDO ())
323            ~use_mnemonic:true
324            ~label:"_Redo"
325            ~packing:(menu#insert ~pos:1) () in
326          new_redoMenuItem#misc#set_sensitive
327           (redoMenuItem#misc#get_flag `SENSITIVE);
328           menu#remove (redoMenuItem :> GMenu.menu_item);
329           connect_menu_item new_redoMenuItem safe_redo));
330       let clipboard = GData.clipboard Gdk.Atom.clipboard in
331       let text_selected () =
332         (source_buffer#get_iter_at_mark `INSERT)#compare
333           (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
334       in
335       let markup_selected () = MatitaMathView.get_selections () <> None in
336       connect_menu_item main#editMenu (fun () ->
337         let text_selected = text_selected () in
338         let markup_selected = markup_selected () in
339         let something_selected = text_selected || markup_selected in
340         main#cutMenuItem#misc#set_sensitive text_selected;
341         main#copyMenuItem#misc#set_sensitive something_selected;
342         main#deleteMenuItem#misc#set_sensitive text_selected;
343         main#pasteMenuItem#misc#set_sensitive (clipboard#text <> None));
344       connect_menu_item main#cutMenuItem (fun () ->
345         source_view#buffer#cut_clipboard clipboard);
346       connect_menu_item main#copyMenuItem (fun () ->
347         if text_selected () then
348           source_view#buffer#copy_clipboard clipboard
349         else if markup_selected () then
350           match MatitaMathView.get_selections () with
351           | None
352           | Some [] -> ()
353           | Some (s :: _) -> clipboard#set_text s);
354       connect_menu_item main#pasteMenuItem (fun () ->
355         source_view#buffer#paste_clipboard clipboard;
356         (MatitaScript.current ())#clean_dirty_lock);
357       connect_menu_item main#deleteMenuItem (fun () ->
358         ignore (source_view#buffer#delete_selection ()));
359       connect_menu_item main#selectAllMenuItem (fun () ->
360         source_buffer#move_mark `INSERT source_buffer#start_iter;
361         source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
362       connect_menu_item main#findReplMenuItem show_find_Repl;
363       connect_menu_item main#externalEditorMenuItem self#externalEditor;
364       connect_menu_item main#ligatureButton self#nextLigature;
365       ignore (findRepl#findEntry#connect#activate find_forward);
366         (* interface lockers *)
367       let lock_world _ =
368         main#buttonsToolbar#misc#set_sensitive false;
369         develList#buttonsHbox#misc#set_sensitive false;
370         source_view#set_editable false
371       in
372       let unlock_world _ =
373         main#buttonsToolbar#misc#set_sensitive true;
374         develList#buttonsHbox#misc#set_sensitive true;
375         source_view#set_editable true
376       in
377       let locker f = 
378         fun () -> 
379           lock_world ();
380           try f ();unlock_world () with exc -> unlock_world (); raise exc in
381       let keep_focus f =
382         fun () ->
383          try
384           f (); source_view#misc#grab_focus ()
385          with
386           exc -> source_view#misc#grab_focus (); raise exc in
387         (* developments win *)
388       let model = 
389         new MatitaGtkMisc.multiStringListModel 
390           ~cols:2 develList#developmentsTreeview
391       in
392       let refresh_devels_win () =
393         model#list_store#clear ();
394         List.iter 
395           (fun (name, root) -> model#easy_mappend [name;root]) 
396           (MatitamakeLib.list_known_developments ())
397       in
398       let get_devel_selected () = 
399         match model#easy_mselection () with
400         | [[name;_]] -> MatitamakeLib.development_for_name name
401         | _ -> None
402       in
403       let refresh () = 
404         while Glib.Main.pending () do 
405           ignore(Glib.Main.iteration false); 
406         done
407       in
408       connect_button develList#newButton
409         (fun () -> 
410           next_devel_must_contain <- None;
411           newDevel#toplevel#misc#show());
412       connect_button develList#deleteButton
413         (locker (fun () -> 
414           (match get_devel_selected () with
415           | None -> ()
416           | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
417           refresh_devels_win ()));
418       connect_button develList#buildButton 
419         (locker (fun () -> 
420           match get_devel_selected () with
421           | None -> ()
422           | Some d -> 
423               let build = locker 
424                 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
425               in
426               ignore(build ())));
427       connect_button develList#cleanButton 
428         (locker (fun () -> 
429           match get_devel_selected () with
430           | None -> ()
431           | Some d -> 
432               let clean = locker 
433                 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
434               in
435               ignore(clean ())));
436       connect_button develList#closeButton 
437         (fun () -> develList#toplevel#misc#hide());
438       ignore(develList#toplevel#event#connect#delete 
439         (fun _ -> develList#toplevel#misc#hide();true));
440       let selected_devel = ref None in
441       connect_menu_item main#developmentsMenuItem
442         (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
443       
444         (* add development win *)
445       let check_if_root_contains root =
446         match next_devel_must_contain with
447         | None -> true
448         | Some path -> 
449             let is_prefix_of d1 d2 =
450               let len1 = String.length d1 in
451               let len2 = String.length d2 in
452               if len2 < len1 then 
453                 false
454               else
455                 let pref = String.sub d2 0 len1 in
456                 pref = d1
457             in
458             is_prefix_of root path
459       in
460       connect_button newDevel#addButton 
461        (fun () -> 
462           let name = newDevel#nameEntry#text in
463           let root = newDevel#rootEntry#text in
464           if check_if_root_contains root then
465             begin
466               ignore (MatitamakeLib.initialize_development name root);
467               refresh_devels_win ();
468               newDevel#nameEntry#set_text "";
469               newDevel#rootEntry#set_text "";
470               newDevel#toplevel#misc#hide()
471             end
472           else
473             MatitaLog.error ("The selected root does not contain " ^ 
474               match next_devel_must_contain with 
475               | Some x -> x 
476               | _ -> assert false));
477       connect_button newDevel#chooseRootButton 
478        (fun () ->
479          let path = self#chooseDir () in
480          match path with
481          | Some path -> newDevel#rootEntry#set_text path
482          | None -> ());
483       connect_button newDevel#cancelButton 
484        (fun () -> newDevel#toplevel#misc#hide ());
485       ignore(newDevel#toplevel#event#connect#delete 
486         (fun _ -> newDevel#toplevel#misc#hide();true));
487       
488         (* file selection win *)
489       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
490       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
491         let return r =
492           chosen_file <- r;
493           fileSel#fileSelectionWin#misc#hide ();
494           GMain.Main.quit ()
495         in
496         match event with
497         | `OK ->
498             let fname = fileSel#fileSelectionWin#filename in
499             if Sys.file_exists fname then
500               begin
501                 if HExtlib.is_regular fname && not (_only_directory) then 
502                   return (Some fname) 
503                 else if _only_directory && HExtlib.is_dir fname then 
504                   return (Some fname)
505               end
506             else
507               begin
508                 if _ok_not_exists then 
509                   return (Some fname)
510               end
511         | `CANCEL -> return None
512         | `HELP -> ()
513         | `DELETE_EVENT -> return None));
514         (* menus *)
515       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
516         (* console *)
517       let adj = main#logScrolledWin#vadjustment in
518         ignore (adj#connect#changed
519                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
520       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
521         (* toolbar *)
522       let module A = GrafiteAst in
523       let hole = CicNotationPt.UserInput in
524       let loc = DisambiguateTypes.dummy_floc in
525       let tac ast _ =
526         if (MatitaScript.current ())#onGoingProof () then
527           (MatitaScript.current ())#advance
528             ~statement:("\n" ^ GrafiteAstPp.pp_tactical (A.Tactic (loc, ast)))
529             ()
530       in
531       let tac_w_term ast _ =
532         if (MatitaScript.current ())#onGoingProof () then
533           let buf = source_buffer in
534           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
535             ("\n" ^ GrafiteAstPp.pp_tactic ast)
536       in
537       let tbar = main in
538       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
539       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
540       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
541       connect_button tbar#elimButton (tac_w_term
542         (A.Elim (loc, hole, None, None, [])));
543       connect_button tbar#elimTypeButton (tac_w_term
544         (A.ElimType (loc, hole, None, None, [])));
545       connect_button tbar#splitButton (tac (A.Split loc));
546       connect_button tbar#leftButton (tac (A.Left loc));
547       connect_button tbar#rightButton (tac (A.Right loc));
548       connect_button tbar#existsButton (tac (A.Exists loc));
549       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
550       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
551       connect_button tbar#transitivityButton
552         (tac_w_term (A.Transitivity (loc, hole)));
553       connect_button tbar#assumptionButton (tac (A.Assumption loc));
554       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
555       connect_button tbar#autoButton (tac (A.Auto (loc,None,None,None,None)));
556       MatitaGtkMisc.toggle_widget_visibility
557        ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
558        ~check:main#tacticsBarMenuItem;
559       let module Hr = Helm_registry in
560       if
561         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
562       then 
563         main#tacticsBarMenuItem#set_active false;
564       MatitaGtkMisc.toggle_callback 
565         ~callback:(function 
566           | true -> main#toplevel#fullscreen () 
567           | false -> main#toplevel#unfullscreen ())
568         ~check:main#fullscreenMenuItem;
569       main#fullscreenMenuItem#set_active false;
570         (* log *)
571       MatitaLog.set_log_callback self#console#log_callback;
572       GtkSignal.user_handler :=
573         (fun exn ->
574           if not (Helm_registry.get_bool "matita.debug") then
575             MatitaLog.error (MatitaExcPp.to_string exn)
576           else raise exn);
577         (* script *)
578       let _ = source_buffer#connect#changed (fun _ -> next_ligatures <- []) in
579       let _ =
580         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
581         | None ->
582             MatitaLog.warn (sprintf "can't load language file %s"
583               BuildTimeConf.lang_file)
584         | Some matita_lang ->
585             source_buffer#set_language matita_lang;
586             source_buffer#set_highlight true
587       in
588       let s () = MatitaScript.current () in
589       let disableSave () =
590         script_fname <- None;
591         main#saveMenuItem#misc#set_sensitive false
592       in
593       let saveAsScript () =
594         let script = s () in
595         match self#chooseFile ~ok_not_exists:true () with
596         | Some f -> 
597               script#assignFileName f;
598               script#saveToFile (); 
599               console#message ("'"^f^"' saved.\n");
600               self#_enableSaveTo f
601         | None -> ()
602       in
603       let saveScript () =
604         match script_fname with
605         | None -> saveAsScript ()
606         | Some f -> 
607               (s ())#assignFileName f;
608               (s ())#saveToFile ();
609               console#message ("'"^f^"' saved.\n");
610       in
611       let abandon_script () =
612         let status = (s ())#status in
613         if source_view#buffer#modified then
614           (match ask_unsaved main#toplevel with
615           | `YES -> saveScript ()
616           | `NO -> ()
617           | `CANCEL -> raise MatitaTypes.Cancel);
618         (match script_fname with
619         | None -> ()
620         | Some fname -> ask_and_save_moo_if_needed main#toplevel fname status);
621       in
622       let loadScript () =
623         let script = s () in 
624         let status = script#status in
625         try 
626           match self#chooseFile () with
627           | Some f -> 
628               abandon_script ();
629               script#reset (); 
630               script#assignFileName f;
631               source_view#source_buffer#begin_not_undoable_action ();
632               script#loadFromFile f; 
633               source_view#source_buffer#end_not_undoable_action ();
634               console#message ("'"^f^"' loaded.\n");
635               self#_enableSaveTo f
636           | None -> ()
637         with MatitaTypes.Cancel -> ()
638       in
639       let newScript () = 
640         abandon_script ();
641         source_view#source_buffer#begin_not_undoable_action ();
642         (s ())#reset (); 
643         (s ())#template (); 
644         source_view#source_buffer#end_not_undoable_action ();
645         disableSave ();
646         script_fname <- None
647       in
648       let cursor () =
649         source_buffer#place_cursor
650           (source_buffer#get_iter_at_mark (`NAME "locked")) in
651       let advance _ = (MatitaScript.current ())#advance (); cursor () in
652       let retract _ = (MatitaScript.current ())#retract (); cursor () in
653       let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
654       let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
655       let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
656       let advance = locker (keep_focus advance) in
657       let retract = locker (keep_focus retract) in
658       let top = locker (keep_focus top) in
659       let bottom = locker (keep_focus bottom) in
660       let jump = locker (keep_focus jump) in
661       let connect_key sym f =
662         connect_key main#mainWinEventBox#event
663           ~modifiers:[`CONTROL] ~stop:true sym f;
664         connect_key self#sourceView#event
665           ~modifiers:[`CONTROL] ~stop:true sym f
666       in
667         (* quit *)
668       self#setQuitCallback (fun () -> 
669         let status = (MatitaScript.current ())#status in
670         if source_view#buffer#modified then
671           begin
672             let rc = ask_unsaved main#toplevel in 
673             try
674               match rc with
675               | `YES -> saveScript ();
676                         if not source_view#buffer#modified then
677                           begin
678                             (match script_fname with
679                             | None -> ()
680                             | Some fname -> 
681                                ask_and_save_moo_if_needed 
682                                  main#toplevel fname status);
683                           GMain.Main.quit ()
684                           end
685               | `NO -> GMain.Main.quit ()
686               | `CANCEL -> raise MatitaTypes.Cancel
687             with MatitaTypes.Cancel -> ()
688           end 
689         else 
690           begin  
691             (match script_fname with
692             | None -> clean_current_baseuri status; GMain.Main.quit ()
693             | Some fname ->
694                 try
695                   ask_and_save_moo_if_needed main#toplevel fname status;
696                   GMain.Main.quit ()
697                 with MatitaTypes.Cancel -> ())
698           end);
699       connect_button main#scriptAdvanceButton advance;
700       connect_button main#scriptRetractButton retract;
701       connect_button main#scriptTopButton top;
702       connect_button main#scriptBottomButton bottom;
703       connect_key GdkKeysyms._Down advance;
704       connect_key GdkKeysyms._Up retract;
705       connect_key GdkKeysyms._Home top;
706       connect_key GdkKeysyms._End bottom;
707       connect_button main#scriptJumpButton jump;
708       connect_menu_item main#openMenuItem   loadScript;
709       connect_menu_item main#saveMenuItem   saveScript;
710       connect_menu_item main#saveAsMenuItem saveAsScript;
711       connect_menu_item main#newMenuItem    newScript;
712       connect_key GdkKeysyms._period
713         (fun () ->
714           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
715             ".\n";
716           advance ());
717       connect_key GdkKeysyms._Return
718         (fun () ->
719           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
720             "\n";
721           advance ());
722          (* script monospace font stuff *)  
723       self#updateFontSize ();
724         (* debug menu *)
725       main#debugMenu#misc#hide ();
726         (* status bar *)
727       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
728       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
729       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
730         (* focus *)
731       self#sourceView#misc#grab_focus ();
732         (* main win dimension *)
733       let width = Gdk.Screen.width () in
734       let height = Gdk.Screen.height () in
735       let main_w = width * 90 / 100 in 
736       let main_h = height * 80 / 100 in
737       let script_w = main_w * 6 / 10 in
738       main#toplevel#resize ~width:main_w ~height:main_h;
739       main#hpaneScriptSequent#set_position script_w;
740         (* source_view *)
741       ignore(source_view#connect#after#paste_clipboard 
742         ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
743       (* clean_locked is set to true only "during" a PRIMARY paste
744          operation (i.e. by clicking with the second mouse button) *)
745       let clean_locked = ref false in
746       ignore(source_view#event#connect#button_press
747         ~callback:
748           (fun button ->
749             if GdkEvent.Button.button button = 2 then
750              clean_locked := true;
751             false
752           ));
753       ignore(source_view#event#connect#button_release
754         ~callback:(fun button -> clean_locked := false; false));
755       ignore(source_view#buffer#connect#after#apply_tag
756        ~callback:(
757          fun tag ~start:_ ~stop:_ ->
758           if !clean_locked &&
759              tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
760           then
761            begin
762             clean_locked := false;
763             (MatitaScript.current ())#clean_dirty_lock;
764             clean_locked := true
765            end));
766       (* math view handling *)
767       connect_menu_item main#newCicBrowserMenuItem (fun () ->
768         ignore (MatitaMathView.cicBrowser ()));
769       connect_menu_item main#increaseFontSizeMenuItem (fun () ->
770         self#increaseFontSize ();
771         MatitaMathView.increase_font_size ();
772         MatitaMathView.update_font_sizes ());
773       connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
774         self#decreaseFontSize ();
775         MatitaMathView.decrease_font_size ();
776         MatitaMathView.update_font_sizes ());
777       connect_menu_item main#normalFontSizeMenuItem (fun () ->
778         self#resetFontSize ();
779         MatitaMathView.reset_font_size ();
780         MatitaMathView.update_font_sizes ());
781       MatitaMathView.reset_font_size ();
782     
783     method private nextLigature () =
784       let iter = source_buffer#get_iter_at_mark `INSERT in
785       let write_ligature len s =
786         source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
787         source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
788       in
789       (match next_ligatures with
790       | [] -> (* find ligatures and fill next_ligatures, then try again *)
791           let last_word = iter#get_slice ~stop:iter#copy#backward_word_start in
792           let len = String.length last_word in
793           let i = ref (len - 1) in
794           while !i >= 0 && CicNotationLexer.is_ligature_char last_word.[!i] do
795             decr i
796           done;
797           let ligature = String.sub last_word (!i + 1) (len - (!i + 1)) in
798           (match CicNotationLexer.lookup_ligatures ligature with
799           | [] -> ()
800           | hd :: tl ->
801               write_ligature (String.length ligature) hd;
802               next_ligatures <- tl @ [ hd ])
803       | hd :: tl ->
804           write_ligature 1 hd;
805           next_ligatures <- tl @ [ hd ])
806
807     method private externalEditor () =
808       let cmd = Helm_registry.get "matita.external_editor" in
809 (* ZACK uncomment to enable interactive ask of external editor command *)
810 (*      let cmd =
811          let msg =
812           "External editor command:
813 %f  will be substitute for the script name,
814 %p  for the cursor position in bytes,
815 %l  for the execution point in bytes."
816         in
817         ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
818           ~default:(Helm_registry.get "matita.external_editor") ()
819       in *)
820       let fname = (MatitaScript.current ())#filename in
821       let slice mark =
822         source_buffer#start_iter#get_slice
823           ~stop:(source_buffer#get_iter_at_mark mark)
824       in
825       let script = MatitaScript.current () in
826       let locked = `MARK script#locked_mark in
827       let string_pos mark = string_of_int (String.length (slice mark)) in
828       let cursor_pos = string_pos `INSERT in
829       let locked_pos = string_pos locked in
830       let cmd =
831         Pcre.replace ~pat:"%f" ~templ:fname
832           (Pcre.replace ~pat:"%p" ~templ:cursor_pos
833             (Pcre.replace ~pat:"%l" ~templ:locked_pos
834               cmd))
835       in
836       let locked_before = slice locked in
837       let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
838       ignore (Unix.system cmd);
839       source_buffer#set_text (HExtlib.input_file fname);
840       let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
841       source_buffer#move_mark locked locked_iter;
842       source_buffer#apply_tag script#locked_tag
843         ~start:source_buffer#start_iter ~stop:locked_iter;
844       let locked_after = slice locked in
845       let line = ref 0 in
846       let col = ref 0 in
847       try
848         for i = 0 to String.length locked_before - 1 do
849           if locked_before.[i] <> locked_after.[i] then begin
850             source_buffer#place_cursor
851               ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
852             script#goto `Cursor ();
853             raise Exit
854           end else if locked_before.[i] = '\n' then begin
855             incr line;
856             col := 0
857           end
858         done
859       with
860       | Exit -> ()
861       | Invalid_argument _ -> script#goto `Bottom ()
862
863     method loadScript file =       
864       let script = MatitaScript.current () in
865       script#reset (); 
866       script#assignFileName file;
867       let content =
868        if Sys.file_exists file then file
869        else BuildTimeConf.script_template
870       in
871        source_view#source_buffer#begin_not_undoable_action ();
872        script#loadFromFile content;
873        source_view#source_buffer#end_not_undoable_action ();
874        console#message ("'"^file^"' loaded.");
875        self#_enableSaveTo file
876       
877     method setStar name b =
878       let l = main#scriptLabel in
879       if b then
880         l#set_text (name ^  " *")
881       else
882         l#set_text (name)
883         
884     method private _enableSaveTo file =
885       script_fname <- Some file;
886       self#main#saveMenuItem#misc#set_sensitive true
887         
888     method console = console
889     method sourceView: GSourceView.source_view =
890       (source_view: GSourceView.source_view)
891     method fileSel = fileSel
892     method findRepl = findRepl
893     method main = main
894     method develList = develList
895     method newDevel = newDevel
896
897     method newBrowserWin () =
898       object (self)
899         inherit browserWin ()
900         val combo = GEdit.combo_box_entry ()
901         initializer
902           self#check_widgets ();
903           let combo_widget = combo#coerce in
904           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
905           combo#entry#misc#grab_focus ()
906         method browserUri = combo
907       end
908
909     method newUriDialog () =
910       let dialog = new uriChoiceDialog () in
911       dialog#check_widgets ();
912       dialog
913
914     method newRecordDialog () =
915       let dialog = new recordChoiceDialog () in
916       dialog#check_widgets ();
917       dialog
918
919     method newConfirmationDialog () =
920       let dialog = new confirmationDialog () in
921       dialog#check_widgets ();
922       dialog
923
924     method newEmptyDialog () =
925       let dialog = new emptyDialog () in
926       dialog#check_widgets ();
927       dialog
928
929     method private addKeyBinding key callback =
930       List.iter (fun evbox -> add_key_binding key callback evbox)
931         keyBindingBoxes
932
933     method setQuitCallback callback =
934       connect_menu_item main#quitMenuItem callback;
935       ignore (main#toplevel#event#connect#delete 
936         (fun _ -> callback ();true));
937       self#addKeyBinding GdkKeysyms._q callback
938
939     method chooseFile ?(ok_not_exists = false) () =
940       _ok_not_exists <- ok_not_exists;
941       _only_directory <- false;
942       fileSel#fileSelectionWin#show ();
943       GtkThread.main ();
944       chosen_file
945
946     method private chooseDir ?(ok_not_exists = false) () =
947       _ok_not_exists <- ok_not_exists;
948       _only_directory <- true;
949       fileSel#fileSelectionWin#show ();
950       GtkThread.main ();
951       (* we should check that this is a directory *)
952       chosen_file
953   
954     method createDevelopment ~containing =
955       next_devel_must_contain <- containing;
956       newDevel#toplevel#misc#show()
957
958     method askText ?(title = "") ?(msg = "") () =
959       let dialog = new textDialog () in
960       dialog#textDialog#set_title title;
961       dialog#textDialogLabel#set_label msg;
962       let text = ref None in
963       let return v =
964         text := v;
965         dialog#textDialog#destroy ();
966         GMain.Main.quit ()
967       in
968       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
969       connect_button dialog#textDialogCancelButton (fun _ -> return None);
970       connect_button dialog#textDialogOkButton (fun _ ->
971         let text = dialog#textDialogTextView#buffer#get_text () in
972         return (Some text));
973       dialog#textDialog#show ();
974       GtkThread.main ();
975       !text
976
977     method private updateFontSize () =
978       self#sourceView#misc#modify_font_by_name
979         (sprintf "%s %d" BuildTimeConf.script_font font_size)
980
981     method increaseFontSize () =
982       font_size <- font_size + 1;
983       self#updateFontSize ()
984
985     method decreaseFontSize () =
986       font_size <- font_size - 1;
987       self#updateFontSize ()
988
989     method resetFontSize () =
990       font_size <- default_font_size;
991       self#updateFontSize ()
992
993   end
994
995 let gui () = 
996   let g = new gui () in
997   gui_instance := Some g;
998   MatitaMathView.set_gui g;
999   g
1000   
1001 let instance = singleton gui
1002
1003 let non p x = not (p x)
1004
1005 (* this is a shit and should be changed :-{ *)
1006 let interactive_uri_choice
1007   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1008   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
1009   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
1010   ?copy_cb ()
1011   ~id uris
1012 =
1013   let gui = instance () in
1014   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1015   if (selection_mode <> `SINGLE) &&
1016     (Helm_registry.get_bool "matita.auto_disambiguation")
1017   then
1018     Lazy.force nonvars_uris
1019   else begin
1020     let dialog = gui#newUriDialog () in
1021     if hide_uri_entry then
1022       dialog#uriEntryHBox#misc#hide ();
1023     if hide_try then
1024       begin
1025       dialog#uriChoiceSelectedButton#misc#hide ();
1026       dialog#uriChoiceConstantsButton#misc#hide ();
1027       end;
1028     dialog#okLabel#set_label ok_label;  
1029     dialog#uriChoiceTreeView#selection#set_mode
1030       (selection_mode :> Gtk.Tags.selection_mode);
1031     let model = new stringListModel dialog#uriChoiceTreeView in
1032     let choices = ref None in
1033     let nonvars = ref false in
1034     (match copy_cb with
1035     | None -> ()
1036     | Some cb ->
1037         dialog#copyButton#misc#show ();
1038         connect_button dialog#copyButton 
1039         (fun _ ->
1040           match model#easy_selection () with
1041           | [u] -> (cb u)
1042           | _ -> ()));
1043     dialog#uriChoiceDialog#set_title title;
1044     dialog#uriChoiceLabel#set_text msg;
1045     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1046     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1047     let return v =
1048       choices := v;
1049       dialog#uriChoiceDialog#destroy ();
1050       GMain.Main.quit ()
1051     in
1052     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1053     connect_button dialog#uriChoiceConstantsButton (fun _ ->
1054       return (Some (Lazy.force nonvars_uris)));
1055     if ok_action = `AUTO then
1056       connect_button dialog#uriChoiceAutoButton (fun _ ->
1057         Helm_registry.set_bool "matita.auto_disambiguation" true;
1058         return (Some (Lazy.force nonvars_uris)))
1059     else
1060       connect_button dialog#uriChoiceAutoButton (fun _ ->
1061         match model#easy_selection () with
1062         | [] -> ()
1063         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1064     connect_button dialog#uriChoiceSelectedButton (fun _ ->
1065       match model#easy_selection () with
1066       | [] -> ()
1067       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1068     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1069     dialog#uriChoiceDialog#show ();
1070     GtkThread.main ();
1071     (match !choices with 
1072     | None -> raise MatitaTypes.Cancel
1073     | Some uris -> uris)
1074   end
1075
1076 class interpModel =
1077   let cols = new GTree.column_list in
1078   let id_col = cols#add Gobject.Data.string in
1079   let dsc_col = cols#add Gobject.Data.string in
1080   let interp_no_col = cols#add Gobject.Data.int in
1081   let tree_store = GTree.tree_store cols in
1082   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1083   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1084   let id_view_col = GTree.view_column ~renderer:id_renderer () in
1085   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1086   fun tree_view choices ->
1087     object
1088       initializer
1089         tree_view#set_model (Some (tree_store :> GTree.model));
1090         ignore (tree_view#append_column id_view_col);
1091         ignore (tree_view#append_column dsc_view_col);
1092         let name_of_interp =
1093           (* try to find a reasonable name for an interpretation *)
1094           let idx = ref 0 in
1095           fun interp ->
1096             try
1097               List.assoc "0" interp
1098             with Not_found ->
1099               incr idx; string_of_int !idx
1100         in
1101         tree_store#clear ();
1102         let idx = ref ~-1 in
1103         List.iter
1104           (fun interp ->
1105             incr idx;
1106             let interp_row = tree_store#append () in
1107             tree_store#set ~row:interp_row ~column:id_col
1108               (name_of_interp interp);
1109             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1110             List.iter
1111               (fun (id, dsc) ->
1112                 let row = tree_store#append ~parent:interp_row () in
1113                 tree_store#set ~row ~column:id_col id;
1114                 tree_store#set ~row ~column:dsc_col dsc;
1115                 tree_store#set ~row ~column:interp_no_col !idx)
1116               interp)
1117           choices
1118
1119       method get_interp_no tree_path =
1120         let iter = tree_store#get_iter tree_path in
1121         tree_store#get ~row:iter ~column:interp_no_col
1122     end
1123
1124 let interactive_interp_choice () choices =
1125   let gui = instance () in
1126   assert (choices <> []);
1127   let dialog = gui#newRecordDialog () in
1128   let model = new interpModel dialog#recordChoiceTreeView choices in
1129   let interp_len = List.length (List.hd choices) in
1130   dialog#recordChoiceDialog#set_title "Interpretation choice";
1131   dialog#recordChoiceDialogLabel#set_label "Choose an interpretation:";
1132   let interp_no = ref None in
1133   let return _ =
1134     dialog#recordChoiceDialog#destroy ();
1135     GMain.Main.quit ()
1136   in
1137   let fail _ = interp_no := None; return () in
1138   ignore (dialog#recordChoiceDialog#event#connect#delete (fun _ -> true));
1139   connect_button dialog#recordChoiceOkButton (fun _ ->
1140     match !interp_no with None -> () | Some _ -> return ());
1141   connect_button dialog#recordChoiceCancelButton fail;
1142   ignore (dialog#recordChoiceTreeView#connect#row_activated (fun path _ ->
1143     interp_no := Some (model#get_interp_no path);
1144     return ()));
1145   let selection = dialog#recordChoiceTreeView#selection in
1146   ignore (selection#connect#changed (fun _ ->
1147     match selection#get_selected_rows with
1148     | [path] -> interp_no := Some (model#get_interp_no path)
1149     | _ -> assert false));
1150   dialog#recordChoiceDialog#show ();
1151   GtkThread.main ();
1152   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
1153
1154 let _ =
1155   (* disambiguator callbacks *)
1156   MatitaDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1157   MatitaDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1158   (* gtk initialization *)
1159   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1160   GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1161   ignore (GMain.Main.init ())
1162