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