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