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