]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaGui.ml
added icons to entries shown in cicbrowser so that directories are
[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 console ~(buffer: GText.buffer) () =
35   object (self)
36     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
37     val warning_tag = buffer#create_tag [ `FOREGROUND "yellow" ]
38     val message_tag = buffer#create_tag []
39     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
40     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
41     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
42     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
43     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
44     method clear () =
45       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
46     method log_callback (tag: MatitaLog.log_tag) s =
47       match tag with
48       | `Debug -> self#debug (s ^ "\n")
49       | `Error -> self#error (s ^ "\n")
50       | `Message -> self#message (s ^ "\n")
51       | `Warning -> self#warning (s ^ "\n")
52   end
53
54 class gui () =
55     (* creation order _is_ relevant for windows placement *)
56   let main = new mainWin () in
57   let about = new aboutWin () in
58   let fileSel = new fileSelectionWin () in
59   let keyBindingBoxes = (* event boxes which should receive global key events *)
60     [ main#mainWinEventBox ]
61   in
62   let console = new console ~buffer:main#logTextView#buffer () in
63   object (self)
64     val mutable chosen_file = None
65     val mutable _ok_not_exists = false
66     val mutable script_fname = None 
67    
68     initializer
69         (* glade's check widgets *)
70       List.iter (fun w -> w#check_widgets ())
71         (let c w = (w :> <check_widgets: unit -> unit>) in
72          [ c about; c fileSel; c main ]);
73         (* key bindings *)
74       List.iter (* global key bindings *)
75         (fun (key, callback) -> self#addKeyBinding key callback)
76 (*
77         [ GdkKeysyms._F3,
78             toggle_win ~check:main#showProofMenuItem proof#proofWin;
79           GdkKeysyms._F4,
80             toggle_win ~check:main#showCheckMenuItem check#checkWin;
81 *)
82         [ ];
83         (* about win *)
84       ignore (about#aboutWin#event#connect#delete (fun _ -> true));
85       ignore (main#aboutMenuItem#connect#activate (fun _ ->
86         about#aboutWin#show ()));
87       connect_button about#aboutDismissButton (fun _ ->
88         about#aboutWin#misc#hide ());
89       about#aboutLabel#set_label (Pcre.replace ~pat:"@VERSION@"
90         ~templ:BuildTimeConf.version about#aboutLabel#label);
91         (* file selection win *)
92       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
93       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
94         let return r =
95           chosen_file <- r;
96           fileSel#fileSelectionWin#misc#hide ();
97           GMain.Main.quit ()
98         in
99         match event with
100         | `OK ->
101             let fname = fileSel#fileSelectionWin#filename in
102             if Sys.file_exists fname then
103               (if is_regular fname then return (Some fname))
104             else
105               (if _ok_not_exists then return (Some fname))
106         | `CANCEL -> return None
107         | `HELP -> ()
108         | `DELETE_EVENT -> return None));
109         (* menus *)
110       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
111       main#helpMenu#set_right_justified true;
112         (* console *)
113       let adj = main#logScrolledWin#vadjustment in
114       ignore (adj#connect#changed
115                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
116       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
117         (* toolbar *)
118       let module A = TacticAst in
119       let hole = CicAst.UserInput in
120       let loc = CicAst.dummy_floc in
121       let tac ast _ =
122         if (MatitaScript.instance ())#onGoingProof () then
123           (MatitaScript.instance ())#advance
124             ~statement:("\n" ^ TacticAstPp.pp_tactical (A.Tactic (loc, ast))) ()
125       in
126       let tac_w_term ast _ =
127         if (MatitaScript.instance ())#onGoingProof () then
128           let (buf: GText.buffer) = self#main#scriptTextView#buffer in
129           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
130             ("\n" ^ TacticAstPp.pp_tactic ast)
131       in
132       let tbar = self#main in
133       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
134       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
135       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
136       connect_button tbar#elimButton (tac_w_term (A.Elim (loc, hole, None)));
137       connect_button tbar#elimTypeButton (tac_w_term (A.ElimType (loc, hole)));
138       connect_button tbar#splitButton (tac (A.Split loc));
139       connect_button tbar#leftButton (tac (A.Left loc));
140       connect_button tbar#rightButton (tac (A.Right loc));
141       connect_button tbar#existsButton (tac (A.Exists loc));
142       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
143       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
144       connect_button tbar#transitivityButton
145         (tac_w_term (A.Transitivity (loc, hole)));
146       connect_button tbar#assumptionButton (tac (A.Assumption loc));
147       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, hole)));
148       connect_button tbar#autoButton (tac (A.Auto (loc,None)));
149         (* quit *)
150       self#setQuitCallback (fun () -> exit 0);
151         (* log *)
152       MatitaLog.set_log_callback self#console#log_callback;
153       GtkSignal.user_handler :=
154         (fun exn ->
155            MatitaLog.error
156              (sprintf "Uncaught exception: %s" (Printexc.to_string exn)));
157         (* script *)
158       let s () = MatitaScript.instance () in
159       let disableSave () =
160         script_fname <- None;
161         self#main#saveMenuItem#misc#set_sensitive false
162       in
163       let loadScript () =
164         let script = s () in
165         match self#chooseFile () with
166         | Some f -> 
167               script#reset (); 
168               script#loadFrom f; 
169               console#message ("'"^f^"' loaded.");
170               self#_enableSaveTo f
171         | None -> ()
172       in
173       let saveAsScript () =
174         let script = s () in
175         match self#chooseFile ~ok_not_exists:true () with
176         | Some f -> 
177               script#saveTo f; 
178               console#message ("'"^f^"' saved.");
179               self#_enableSaveTo f
180         | None -> ()
181       in
182       let saveScript () =
183         match script_fname with
184         | None -> saveAsScript ()
185         | Some f -> 
186               (s ())#saveTo f;
187               console#message ("'"^f^"' saved.");
188       in
189       let newScript () = (s ())#reset (); disableSave () in
190       let cursor () =
191         let buf = self#main#scriptTextView#buffer in
192         buf#place_cursor (buf#get_iter_at_mark (`NAME "locked"))
193       in
194       let advance _ = (MatitaScript.instance ())#advance (); cursor () in
195       let retract _ = (MatitaScript.instance ())#retract (); cursor () in
196       let top _ = (MatitaScript.instance ())#goto `Top (); cursor () in
197       let bottom _ = (MatitaScript.instance ())#goto `Bottom (); cursor () in
198       let jump _ = (MatitaScript.instance ())#goto `Cursor (); cursor () in
199       let connect_key sym f =
200         connect_key self#main#mainWinEventBox#event
201           ~modifiers:[`CONTROL] ~stop:true sym f;
202         connect_key self#main#scriptTextView#event
203           ~modifiers:[`CONTROL] ~stop:true sym f
204       in
205       connect_button self#main#scriptAdvanceButton advance;
206       connect_button self#main#scriptRetractButton retract;
207       connect_button self#main#scriptTopButton top;
208       connect_button self#main#scriptBottomButton bottom;
209       connect_key GdkKeysyms._Down advance;
210       connect_key GdkKeysyms._Up retract;
211       connect_key GdkKeysyms._Home top;
212       connect_key GdkKeysyms._End bottom;
213       connect_button self#main#scriptJumpButton jump;
214       connect_menu_item self#main#openMenuItem   loadScript;
215       connect_menu_item self#main#saveMenuItem   saveScript;
216       connect_menu_item self#main#saveAsMenuItem saveAsScript;
217       connect_menu_item self#main#newMenuItem    newScript;
218       connect_key GdkKeysyms._period
219         (fun () ->
220            let buf = self#main#scriptTextView#buffer in
221            buf#insert ~iter:(buf#get_iter_at_mark `INSERT) ".\n";
222            advance ());
223       connect_key GdkKeysyms._Return
224         (fun () ->
225            let buf = self#main#scriptTextView#buffer in
226            buf#insert ~iter:(buf#get_iter_at_mark `INSERT) "\n";
227            advance ());
228          (* script monospace font stuff *)  
229       let font =
230         Helm_registry.get_opt_default Helm_registry.get
231           BuildTimeConf.default_script_font "matita.script_font"
232       in
233 (*       let monospace_tag = 
234         self#main#scriptTextView#buffer#create_tag [`FONT_DESC font] 
235       in *)
236       self#main#scriptTextView#misc#modify_font_by_name font;
237 (*       let _ = 
238         self#main#scriptTextView#buffer#connect#changed ~callback:(fun _ ->
239           let start, stop = self#main#scriptTextView#buffer#bounds in
240           self#main#scriptTextView#buffer#apply_tag monospace_tag start stop)
241       in *)
242         (* debug menu *)
243       self#main#debugMenu#misc#hide ();
244         (* status bar *)
245       self#main#hintLowImage#set_file (image_path "matita-bulb-low.png");
246       self#main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
247       self#main#hintHighImage#set_file (image_path "matita-bulb-high.png");
248         (* focus *)
249       self#main#scriptTextView#misc#grab_focus ();
250         (* main win dimension *)
251       let width = Gdk.Screen.width () in
252       let height = Gdk.Screen.height () in
253       let main_w = width * 90 / 100 in 
254       let main_h = height * 80 / 100 in
255       let script_w = main_w / 2 in
256       self#main#toplevel#resize ~width:main_w ~height:main_h;
257       self#main#hpaneScriptSequent#set_position script_w  
258     
259     method loadScript file =       
260       let script = MatitaScript.instance () in
261       script#reset (); 
262       script#loadFrom file; 
263       console#message ("'"^file^"' loaded.");
264       self#_enableSaveTo file
265         
266     method private _enableSaveTo file =
267       script_fname <- Some file;
268       self#main#saveMenuItem#misc#set_sensitive true
269         
270
271     method console = console
272
273     method about = about
274     method fileSel = fileSel
275     method main = main
276
277     method newBrowserWin () =
278       let win = new browserWin () in
279       win#check_widgets ();
280       win
281
282     method newUriDialog () =
283       let dialog = new uriChoiceDialog () in
284       dialog#check_widgets ();
285       dialog
286
287     method newInterpDialog () =
288       let dialog = new interpChoiceDialog () in
289       dialog#check_widgets ();
290       dialog
291
292     method newConfirmationDialog () =
293       let dialog = new confirmationDialog () in
294       dialog#check_widgets ();
295       dialog
296
297     method newEmptyDialog () =
298       let dialog = new emptyDialog () in
299       dialog#check_widgets ();
300       dialog
301
302     method private addKeyBinding key callback =
303       List.iter (fun evbox -> add_key_binding key callback evbox)
304         keyBindingBoxes
305
306     method setQuitCallback callback =
307       ignore (main#toplevel#connect#destroy callback);
308       ignore (main#quitMenuItem#connect#activate callback);
309       self#addKeyBinding GdkKeysyms._q callback
310
311     method chooseFile ?(ok_not_exists = false) () =
312       _ok_not_exists <- ok_not_exists;
313       fileSel#fileSelectionWin#show ();
314       GtkThread.main ();
315       chosen_file
316
317     method askText ?(title = "") ?(msg = "") () =
318       let dialog = new textDialog () in
319       dialog#textDialog#set_title title;
320       dialog#textDialogLabel#set_label msg;
321       let text = ref None in
322       let return v =
323         text := v;
324         dialog#textDialog#destroy ();
325         GMain.Main.quit ()
326       in
327       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
328       connect_button dialog#textDialogCancelButton (fun _ -> return None);
329       connect_button dialog#textDialogOkButton (fun _ ->
330         let text = dialog#textDialogTextView#buffer#get_text () in
331         return (Some text));
332       dialog#textDialog#show ();
333       GtkThread.main ();
334       !text
335
336   end
337
338 let gui () = 
339   let g = new gui () in
340   gui_instance := Some g;
341   g
342   
343 let instance = singleton gui
344
345 let non p x = not (p x)
346
347 let is_var_uri s =
348   try
349     String.sub s (String.length s - 4) 4 = ".var"
350   with Invalid_argument _ -> false
351
352 (* this is a shit and should be changed :-{ *)
353 let interactive_uri_choice
354   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
355   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
356   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
357   ?copy_cb ()
358   ~id uris
359 =
360   let gui = instance () in
361   let nonvars_uris = lazy (List.filter (non is_var_uri) uris) in
362   if (selection_mode <> `SINGLE) &&
363     (Helm_registry.get_bool "matita.auto_disambiguation")
364   then
365     Lazy.force nonvars_uris
366   else begin
367     let dialog = gui#newUriDialog () in
368     if hide_uri_entry then
369       dialog#uriEntryHBox#misc#hide ();
370     if hide_try then
371       begin
372       dialog#uriChoiceSelectedButton#misc#hide ();
373       dialog#uriChoiceConstantsButton#misc#hide ();
374       end;
375     dialog#okLabel#set_label ok_label;  
376     dialog#uriChoiceTreeView#selection#set_mode
377       (selection_mode :> Gtk.Tags.selection_mode);
378     let model = new stringListModel dialog#uriChoiceTreeView in
379     let choices = ref None in
380     let nonvars = ref false in
381     (match copy_cb with
382     | None -> ()
383     | Some cb ->
384         dialog#copyButton#misc#show ();
385         connect_button dialog#copyButton 
386         (fun _ ->
387           match model#easy_selection () with
388           | [u] -> (cb u)
389           | _ -> ()));
390     dialog#uriChoiceDialog#set_title title;
391     dialog#uriChoiceLabel#set_text msg;
392     List.iter model#easy_append uris;
393     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
394     let return v =
395       choices := v;
396       dialog#uriChoiceDialog#destroy ();
397       GMain.Main.quit ()
398     in
399     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
400     connect_button dialog#uriChoiceConstantsButton (fun _ ->
401       return (Some (Lazy.force nonvars_uris)));
402     if ok_action = `AUTO then
403       connect_button dialog#uriChoiceAutoButton (fun _ ->
404         Helm_registry.set_bool "matita.auto_disambiguation" true;
405         return (Some (Lazy.force nonvars_uris)))
406     else
407       connect_button dialog#uriChoiceAutoButton (fun _ ->
408         match model#easy_selection () with
409         | [] -> ()
410         | uris -> return (Some uris));
411     connect_button dialog#uriChoiceSelectedButton (fun _ ->
412       match model#easy_selection () with
413       | [] -> ()
414       | uris -> return (Some uris));
415     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
416     dialog#uriChoiceDialog#show ();
417     GtkThread.main ();
418     (match !choices with 
419     | None -> raise MatitaTypes.Cancel
420     | Some uris -> uris)
421   end
422
423 class interpModel =
424   let cols = new GTree.column_list in
425   let id_col = cols#add Gobject.Data.string in
426   let dsc_col = cols#add Gobject.Data.string in
427   let interp_no_col = cols#add Gobject.Data.int in
428   let tree_store = GTree.tree_store cols in
429   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
430   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
431   let id_view_col = GTree.view_column ~renderer:id_renderer () in
432   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
433   fun tree_view choices ->
434     object
435       initializer
436         tree_view#set_model (Some (tree_store :> GTree.model));
437         ignore (tree_view#append_column id_view_col);
438         ignore (tree_view#append_column dsc_view_col);
439         let name_of_interp =
440           (* try to find a reasonable name for an interpretation *)
441           let idx = ref 0 in
442           fun interp ->
443             try
444               List.assoc "0" interp
445             with Not_found ->
446               incr idx; string_of_int !idx
447         in
448         tree_store#clear ();
449         let idx = ref ~-1 in
450         List.iter
451           (fun interp ->
452             incr idx;
453             let interp_row = tree_store#append () in
454             tree_store#set ~row:interp_row ~column:id_col
455               (name_of_interp interp);
456             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
457             List.iter
458               (fun (id, dsc) ->
459                 let row = tree_store#append ~parent:interp_row () in
460                 tree_store#set ~row ~column:id_col id;
461                 tree_store#set ~row ~column:dsc_col dsc;
462                 tree_store#set ~row ~column:interp_no_col !idx)
463               interp)
464           choices
465
466       method get_interp_no tree_path =
467         let iter = tree_store#get_iter tree_path in
468         tree_store#get ~row:iter ~column:interp_no_col
469     end
470
471 let interactive_interp_choice () choices =
472   let gui = instance () in
473   assert (choices <> []);
474   let dialog = gui#newInterpDialog () in
475   let model = new interpModel dialog#interpChoiceTreeView choices in
476   let interp_len = List.length (List.hd choices) in
477   dialog#interpChoiceDialog#set_title "Interpretation choice";
478   dialog#interpChoiceDialogLabel#set_label "Choose an interpretation:";
479   let interp_no = ref None in
480   let return _ =
481     dialog#interpChoiceDialog#destroy ();
482     GMain.Main.quit ()
483   in
484   let fail _ = interp_no := None; return () in
485   ignore (dialog#interpChoiceDialog#event#connect#delete (fun _ -> true));
486   connect_button dialog#interpChoiceOkButton (fun _ ->
487     match !interp_no with None -> () | Some _ -> return ());
488   connect_button dialog#interpChoiceCancelButton fail;
489   ignore (dialog#interpChoiceTreeView#connect#row_activated (fun path _ ->
490     interp_no := Some (model#get_interp_no path);
491     return ()));
492   let selection = dialog#interpChoiceTreeView#selection in
493   ignore (selection#connect#changed (fun _ ->
494     match selection#get_selected_rows with
495     | [path] ->
496         MatitaLog.debug (sprintf "selection: %d" (model#get_interp_no path));
497         interp_no := Some (model#get_interp_no path)
498     | _ -> assert false));
499   dialog#interpChoiceDialog#show ();
500   GtkThread.main ();
501   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
502