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