1 (* Copyright (C) 2004-2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
30 open MatitaGeneratedGui
34 exception Found of int
36 let gui_instance = ref None
38 class type browserWin =
39 (* this class exists only because GEdit.combo_box_entry is not supported by
40 * lablgladecc :-(((( *)
42 inherit MatitaGeneratedGui.browserWin
43 method browserUri: GEdit.combo_box_entry
46 class console ~(buffer: GText.buffer) () =
48 val error_tag = buffer#create_tag [ `FOREGROUND "red" ]
49 val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
50 val message_tag = buffer#create_tag []
51 val debug_tag = buffer#create_tag [ `FOREGROUND "#888888" ]
52 method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
53 method error s = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
54 method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
55 method debug s = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
57 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
58 method log_callback (tag: HLog.log_tag) s =
60 | `Debug -> self#debug (s ^ "\n")
61 | `Error -> self#error (s ^ "\n")
62 | `Message -> self#message (s ^ "\n")
63 | `Warning -> self#warning (s ^ "\n")
66 let clean_current_baseuri grafite_status =
68 let baseuri = GrafiteTypes.get_string_option grafite_status "baseuri" in
69 LibraryClean.clean_baseuris [baseuri]
70 with GrafiteTypes.Option_error _ -> ()
72 let ask_and_save_moo_if_needed parent fname lexicon_status grafite_status =
73 let baseuri = DependenciesParser.baseuri_of_script ~include_paths:[] fname in
74 let moo_fname = LibraryMisc.obj_file_of_baseuri ~baseuri ~writable:true in
77 LibraryMisc.metadata_file_of_baseuri ~baseuri ~writable:true in
79 LibraryMisc.lexicon_file_of_baseuri ~baseuri ~writable:true
81 GrafiteMarshal.save_moo moo_fname
82 grafite_status.GrafiteTypes.moo_content_rev;
83 LibraryNoDb.save_metadata metadata_fname
84 lexicon_status.LexiconEngine.metadata;
85 LexiconMarshal.save_lexicon lexicon_fname
86 lexicon_status.LexiconEngine.lexicon_content_rev
88 if (MatitaScript.current ())#eos &&
89 grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof
93 MatitaGtkMisc.ask_confirmation
94 ~title:"A .moo can be generated"
95 ~message:(Printf.sprintf
96 "%s can be generated for %s.\n<i>Should I generate it?</i>"
97 (Filename.basename moo_fname) (Filename.basename fname))
104 | `CANCEL -> raise MatitaTypes.Cancel
109 clean_current_baseuri grafite_status
112 clean_current_baseuri grafite_status
114 let ask_unsaved parent =
115 MatitaGtkMisc.ask_confirmation
116 ~parent ~title:"Unsaved work!"
117 ~message:("Your work is <b>unsaved</b>!\n\n"^
118 "<i>Do you want to save the script before continuing?</i>")
121 (** Selection handling
122 * Two clipboards are used: "clipboard" and "primary".
123 * "primary" is used by X, when you hit the middle button mouse is content is
124 * pasted between applications. In Matita this selection always contain the
125 * textual version of the selected term.
126 * "clipboard" is used inside Matita only and support ATM two different targets:
127 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
132 (* creation order _is_ relevant for windows placement *)
133 let main = new mainWin () in
134 let fileSel = new fileSelectionWin () in
135 let findRepl = new findReplWin () in
136 let develList = new develListWin () in
137 let newDevel = new newDevelWin () in
138 let keyBindingBoxes = (* event boxes which should receive global key events *)
139 [ main#mainWinEventBox ]
141 let console = new console ~buffer:main#logTextView#buffer () in
142 let (source_view: GSourceView.source_view) =
143 GSourceView.source_view
145 ~insert_spaces_instead_of_tabs:true ~tabs_width:2
146 ~margin:80 ~show_margin:true
148 ~packing:main#scriptScrolledWin#add
151 let default_font_size =
152 Helm_registry.get_opt_default Helm_registry.int
153 ~default:BuildTimeConf.default_font_size "matita.font_size"
155 let source_buffer = source_view#source_buffer in
157 val mutable chosen_file = None
158 val mutable _ok_not_exists = false
159 val mutable _only_directory = false
160 val mutable script_fname = None
161 val mutable font_size = default_font_size
162 val mutable next_devel_must_contain = None
163 val mutable next_ligatures = []
164 val clipboard = GData.clipboard Gdk.Atom.clipboard
165 val primary = GData.clipboard Gdk.Atom.primary
168 (* glade's check widgets *)
169 List.iter (fun w -> w#check_widgets ())
170 (let c w = (w :> <check_widgets: unit -> unit>) in
171 [ c fileSel; c main; c findRepl]);
173 List.iter (* global key bindings *)
174 (fun (key, callback) -> self#addKeyBinding key callback)
177 toggle_win ~check:main#showProofMenuItem proof#proofWin;
179 toggle_win ~check:main#showCheckMenuItem check#checkWin;
183 let parse_txt_file file =
184 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
185 let l_rev = ref [] in
188 l_rev := input_line ch :: !l_rev;
197 ~authors:(parse_txt_file "AUTHORS")
198 (*~comments:"comments"*)
199 ~copyright:"Copyright (C) 2005, the HELM team"
200 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
201 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
203 ~version:BuildTimeConf.version
204 ~website:"http://helm.cs.unibo.it"
207 connect_menu_item main#contentsMenuItem (fun () ->
209 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
211 ignore (Sys.command cmd));
212 connect_menu_item main#aboutMenuItem about_dialog#present;
214 let show_find_Repl () =
215 findRepl#toplevel#misc#show ();
216 findRepl#toplevel#misc#grab_focus ()
218 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
220 let highlight start end_ =
221 source_buffer#move_mark `INSERT ~where:start;
222 source_buffer#move_mark `SEL_BOUND ~where:end_;
223 source_view#scroll_mark_onscreen `INSERT
225 let text = findRepl#findEntry#text in
226 let iter = source_buffer#get_iter `SEL_BOUND in
227 match iter#forward_search text with
229 (match source_buffer#start_iter#forward_search text with
231 | Some (start,end_) -> highlight start end_)
232 | Some (start,end_) -> highlight start end_
235 let text = findRepl#replaceEntry#text in
236 let ins = source_buffer#get_iter `INSERT in
237 let sel = source_buffer#get_iter `SEL_BOUND in
238 if ins#compare sel < 0 then
240 ignore(source_buffer#delete_selection ());
241 source_buffer#insert text
244 connect_button findRepl#findButton find_forward;
245 connect_button findRepl#findReplButton replace;
246 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
247 ignore(findRepl#toplevel#event#connect#delete
248 ~callback:(fun _ -> hide_find_Repl ();true));
251 (* phase 1: we save the actual status of the marks and we undo *)
252 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
253 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
254 let locked_iter_offset = locked_iter#offset in
257 (source_view#buffer#create_mark ~name:"lock_point"
258 ~left_gravity:true locked_iter) in
259 source_view#source_buffer#undo ();
260 (* phase 2: we save the cursor position and we redo, restoring
261 the previous status of all the marks *)
262 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
265 (source_view#buffer#create_mark ~name:"undo_point"
266 ~left_gravity:true cursor_iter)
268 source_view#source_buffer#redo ();
269 let mark_iter = source_view#buffer#get_iter_at_mark mark in
270 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
271 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
272 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
273 source_view#buffer#delete_mark mark;
274 source_view#buffer#delete_mark mark2;
275 (* phase 3: if after the undo the cursor was in the locked area,
276 then we move it there again and we perform a goto *)
277 if mark_iter#offset < locked_iter_offset then
279 source_view#buffer#move_mark `INSERT ~where:mark_iter;
280 (MatitaScript.current ())#goto `Cursor ();
282 (* phase 4: we perform again the undo. This time we are sure that
283 the text to undo is not locked *)
284 source_view#source_buffer#undo ();
285 source_view#misc#grab_focus () in
288 (* phase 1: we save the actual status of the marks, we redo and
290 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
291 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
292 let locked_iter_offset = locked_iter#offset in
295 (source_view#buffer#create_mark ~name:"lock_point"
296 ~left_gravity:true locked_iter) in
297 source_view#source_buffer#redo ();
298 source_view#source_buffer#undo ();
299 (* phase 2: we save the cursor position and we restore
300 the previous status of all the marks *)
301 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
304 (source_view#buffer#create_mark ~name:"undo_point"
305 ~left_gravity:true cursor_iter)
307 let mark_iter = source_view#buffer#get_iter_at_mark mark in
308 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
309 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
310 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
311 source_view#buffer#delete_mark mark;
312 source_view#buffer#delete_mark mark2;
313 (* phase 3: if after the undo the cursor is in the locked area,
314 then we move it there again and we perform a goto *)
315 if mark_iter#offset < locked_iter_offset then
317 source_view#buffer#move_mark `INSERT ~where:mark_iter;
318 (MatitaScript.current ())#goto `Cursor ();
320 (* phase 4: we perform again the redo. This time we are sure that
321 the text to redo is not locked *)
322 source_view#source_buffer#redo ();
323 source_view#misc#grab_focus ()
325 connect_menu_item main#undoMenuItem safe_undo;
326 ignore(source_view#source_buffer#connect#can_undo
327 ~callback:main#undoMenuItem#misc#set_sensitive);
328 connect_menu_item main#redoMenuItem safe_redo;
329 ignore(source_view#source_buffer#connect#can_redo
330 ~callback:main#redoMenuItem#misc#set_sensitive);
331 ignore(source_view#connect#after#populate_popup
332 ~callback:(fun pre_menu ->
333 let menu = new GMenu.menu pre_menu in
334 let menuItems = menu#children in
335 let undoMenuItem, redoMenuItem =
337 [undo;redo;sep1;cut;copy;paste;delete;sep2;
338 selectall;sep3;inputmethod;insertunicodecharacter] ->
339 List.iter menu#remove [ copy; cut; delete; paste ];
341 | _ -> assert false in
343 let i = ref 2 in (* last occupied position *)
344 fun ?label ?stock () ->
346 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
349 let copy = add_menu_item ~stock:`COPY () in
350 let cut = add_menu_item ~stock:`CUT () in
351 let delete = add_menu_item ~stock:`DELETE () in
352 let paste = add_menu_item ~stock:`PASTE () in
353 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
354 copy#misc#set_sensitive self#canCopy;
355 cut#misc#set_sensitive self#canCut;
356 delete#misc#set_sensitive self#canDelete;
357 paste#misc#set_sensitive self#canPaste;
358 paste_pattern#misc#set_sensitive self#canPastePattern;
359 connect_menu_item copy self#copy;
360 connect_menu_item cut self#cut;
361 connect_menu_item delete self#delete;
362 connect_menu_item paste self#paste;
363 connect_menu_item paste_pattern self#pastePattern;
364 let new_undoMenuItem =
365 GMenu.image_menu_item
366 ~image:(GMisc.image ~stock:`UNDO ())
369 ~packing:(menu#insert ~pos:0) () in
370 new_undoMenuItem#misc#set_sensitive
371 (undoMenuItem#misc#get_flag `SENSITIVE);
372 menu#remove (undoMenuItem :> GMenu.menu_item);
373 connect_menu_item new_undoMenuItem safe_undo;
374 let new_redoMenuItem =
375 GMenu.image_menu_item
376 ~image:(GMisc.image ~stock:`REDO ())
379 ~packing:(menu#insert ~pos:1) () in
380 new_redoMenuItem#misc#set_sensitive
381 (redoMenuItem#misc#get_flag `SENSITIVE);
382 menu#remove (redoMenuItem :> GMenu.menu_item);
383 connect_menu_item new_redoMenuItem safe_redo));
385 connect_menu_item main#editMenu (fun () ->
386 main#copyMenuItem#misc#set_sensitive self#canCopy;
387 main#cutMenuItem#misc#set_sensitive self#canCut;
388 main#deleteMenuItem#misc#set_sensitive self#canDelete;
389 main#pasteMenuItem#misc#set_sensitive self#canPaste;
390 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
391 connect_menu_item main#copyMenuItem self#copy;
392 connect_menu_item main#cutMenuItem self#cut;
393 connect_menu_item main#deleteMenuItem self#delete;
394 connect_menu_item main#pasteMenuItem self#paste;
395 connect_menu_item main#pastePatternMenuItem self#pastePattern;
396 connect_menu_item main#selectAllMenuItem (fun () ->
397 source_buffer#move_mark `INSERT source_buffer#start_iter;
398 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
399 connect_menu_item main#findReplMenuItem show_find_Repl;
400 connect_menu_item main#externalEditorMenuItem self#externalEditor;
401 connect_menu_item main#ligatureButton self#nextLigature;
402 ignore (findRepl#findEntry#connect#activate find_forward);
403 (* interface lockers *)
405 main#buttonsToolbar#misc#set_sensitive false;
406 develList#buttonsHbox#misc#set_sensitive false;
407 source_view#set_editable false
410 main#buttonsToolbar#misc#set_sensitive true;
411 develList#buttonsHbox#misc#set_sensitive true;
412 source_view#set_editable true
417 try f ();unlock_world () with exc -> unlock_world (); raise exc in
421 f (); source_view#misc#grab_focus ()
423 exc -> source_view#misc#grab_focus (); raise exc in
424 (* developments win *)
426 new MatitaGtkMisc.multiStringListModel
427 ~cols:2 develList#developmentsTreeview
429 let refresh_devels_win () =
430 model#list_store#clear ();
432 (fun (name, root) -> model#easy_mappend [name;root])
433 (MatitamakeLib.list_known_developments ())
435 let get_devel_selected () =
436 match model#easy_mselection () with
437 | [[name;_]] -> MatitamakeLib.development_for_name name
441 while Glib.Main.pending () do
442 ignore(Glib.Main.iteration false);
445 connect_button develList#newButton
447 next_devel_must_contain <- None;
448 newDevel#toplevel#misc#show());
449 connect_button develList#deleteButton
451 (match get_devel_selected () with
453 | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
454 refresh_devels_win ()));
455 connect_button develList#buildButton
457 match get_devel_selected () with
461 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
464 connect_button develList#cleanButton
466 match get_devel_selected () with
470 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
473 connect_button develList#publishButton
475 match get_devel_selected () with
479 (fun () -> MatitamakeLib.publish_development_in_bg refresh d)
482 connect_button develList#closeButton
483 (fun () -> develList#toplevel#misc#hide());
484 ignore(develList#toplevel#event#connect#delete
485 (fun _ -> develList#toplevel#misc#hide();true));
486 connect_menu_item main#developmentsMenuItem
487 (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
489 (* add development win *)
490 let check_if_root_contains root =
491 match next_devel_must_contain with
494 let is_prefix_of d1 d2 =
495 let len1 = String.length d1 in
496 let len2 = String.length d2 in
500 let pref = String.sub d2 0 len1 in
503 is_prefix_of root path
505 connect_button newDevel#addButton
507 let name = newDevel#nameEntry#text in
508 let root = newDevel#rootEntry#text in
509 if check_if_root_contains root then
511 ignore (MatitamakeLib.initialize_development name root);
512 refresh_devels_win ();
513 newDevel#nameEntry#set_text "";
514 newDevel#rootEntry#set_text "";
515 newDevel#toplevel#misc#hide()
518 HLog.error ("The selected root does not contain " ^
519 match next_devel_must_contain with
521 | _ -> assert false));
522 connect_button newDevel#chooseRootButton
524 let path = self#chooseDir () in
526 | Some path -> newDevel#rootEntry#set_text path
528 connect_button newDevel#cancelButton
529 (fun () -> newDevel#toplevel#misc#hide ());
530 ignore(newDevel#toplevel#event#connect#delete
531 (fun _ -> newDevel#toplevel#misc#hide();true));
533 (* file selection win *)
534 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
535 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
538 fileSel#fileSelectionWin#misc#hide ();
543 let fname = fileSel#fileSelectionWin#filename in
544 if Sys.file_exists fname then
546 if HExtlib.is_regular fname && not (_only_directory) then
548 else if _only_directory && HExtlib.is_dir fname then
553 if _ok_not_exists then
556 | `CANCEL -> return None
558 | `DELETE_EVENT -> return None));
560 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
562 let adj = main#logScrolledWin#vadjustment in
563 ignore (adj#connect#changed
564 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
565 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
567 let module A = GrafiteAst in
568 let hole = CicNotationPt.UserInput in
569 let loc = HExtlib.dummy_floc in
571 if (MatitaScript.current ())#onGoingProof () then
572 (MatitaScript.current ())#advance
574 ^ GrafiteAstPp.pp_tactical ~term_pp:CicNotationPp.pp_term
575 ~lazy_term_pp:CicNotationPp.pp_term (A.Tactic (loc, ast)))
578 let tac_w_term ast _ =
579 if (MatitaScript.current ())#onGoingProof () then
580 let buf = source_buffer in
581 buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
583 ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
584 ~lazy_term_pp:CicNotationPp.pp_term ast)
587 connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
588 connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
589 connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
590 connect_button tbar#elimButton (tac_w_term
591 (A.Elim (loc, hole, None, None, [])));
592 connect_button tbar#elimTypeButton (tac_w_term
593 (A.ElimType (loc, hole, None, None, [])));
594 connect_button tbar#splitButton (tac (A.Split loc));
595 connect_button tbar#leftButton (tac (A.Left loc));
596 connect_button tbar#rightButton (tac (A.Right loc));
597 connect_button tbar#existsButton (tac (A.Exists loc));
598 connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
599 connect_button tbar#symmetryButton (tac (A.Symmetry loc));
600 connect_button tbar#transitivityButton
601 (tac_w_term (A.Transitivity (loc, hole)));
602 connect_button tbar#assumptionButton (tac (A.Assumption loc));
603 connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
604 connect_button tbar#autoButton (tac (A.Auto (loc,None,None,None,None)));
605 MatitaGtkMisc.toggle_widget_visibility
606 ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
607 ~check:main#tacticsBarMenuItem;
608 let module Hr = Helm_registry in
610 not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
612 main#tacticsBarMenuItem#set_active false;
613 MatitaGtkMisc.toggle_callback
615 | true -> main#toplevel#fullscreen ()
616 | false -> main#toplevel#unfullscreen ())
617 ~check:main#fullscreenMenuItem;
618 main#fullscreenMenuItem#set_active false;
620 HLog.set_log_callback self#console#log_callback;
621 GtkSignal.user_handler :=
623 | MatitaScript.ActionCancelled s -> HLog.error s
625 if not (Helm_registry.get_bool "matita.debug") then
626 let floc, msg = MatitaExcPp.to_string exn in
631 let (x, y) = HExtlib.loc_of_floc floc in
632 let script = MatitaScript.current () in
633 let locked_mark = script#locked_mark in
634 let error_tag = script#error_tag in
636 (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
637 let x' = baseoffset + x in
638 let y' = baseoffset + y in
639 let x_iter = source_buffer#get_iter (`OFFSET x') in
640 let y_iter = source_buffer#get_iter (`OFFSET y') in
641 source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
643 id := Some (source_buffer#connect#changed ~callback:(fun () ->
644 source_buffer#remove_tag error_tag
645 ~start:source_buffer#start_iter
646 ~stop:source_buffer#end_iter;
648 | None -> assert false (* a race condition occurred *)
650 (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
651 source_buffer#place_cursor
652 (source_buffer#get_iter (`OFFSET x'));
657 ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
659 match GSourceView.source_language_from_file BuildTimeConf.lang_file with
661 HLog.warn (sprintf "can't load language file %s"
662 BuildTimeConf.lang_file)
663 | Some matita_lang ->
664 source_buffer#set_language matita_lang;
665 source_buffer#set_highlight true
667 let s () = MatitaScript.current () in
669 script_fname <- None;
670 main#saveMenuItem#misc#set_sensitive false
672 let saveAsScript () =
674 match self#chooseFile ~ok_not_exists:true () with
676 script#assignFileName f;
677 script#saveToFile ();
678 console#message ("'"^f^"' saved.\n");
683 match script_fname with
684 | None -> saveAsScript ()
686 (s ())#assignFileName f;
687 (s ())#saveToFile ();
688 console#message ("'"^f^"' saved.\n");
690 let abandon_script () =
691 let lexicon_status = (s ())#lexicon_status in
692 let grafite_status = (s ())#grafite_status in
693 if source_view#buffer#modified then
694 (match ask_unsaved main#toplevel with
695 | `YES -> saveScript ()
697 | `CANCEL -> raise MatitaTypes.Cancel);
698 (match script_fname with
701 ask_and_save_moo_if_needed main#toplevel fname
702 lexicon_status grafite_status);
707 match self#chooseFile () with
711 script#assignFileName f;
712 source_view#source_buffer#begin_not_undoable_action ();
713 script#loadFromFile f;
714 source_view#source_buffer#end_not_undoable_action ();
715 console#message ("'"^f^"' loaded.\n");
718 with MatitaTypes.Cancel -> ()
722 source_view#source_buffer#begin_not_undoable_action ();
725 source_view#source_buffer#end_not_undoable_action ();
730 source_buffer#place_cursor
731 (source_buffer#get_iter_at_mark (`NAME "locked")) in
732 let advance _ = (MatitaScript.current ())#advance (); cursor () in
733 let retract _ = (MatitaScript.current ())#retract (); cursor () in
734 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
735 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
736 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
737 let advance = locker (keep_focus advance) in
738 let retract = locker (keep_focus retract) in
739 let top = locker (keep_focus top) in
740 let bottom = locker (keep_focus bottom) in
741 let jump = locker (keep_focus jump) in
743 self#setQuitCallback (fun () ->
744 let lexicon_status = (MatitaScript.current ())#lexicon_status in
745 let grafite_status = (MatitaScript.current ())#grafite_status in
746 if source_view#buffer#modified then
748 let rc = ask_unsaved main#toplevel in
751 | `YES -> saveScript ();
752 if not source_view#buffer#modified then
754 (match script_fname with
757 ask_and_save_moo_if_needed main#toplevel
758 fname lexicon_status grafite_status);
761 | `NO -> GMain.Main.quit ()
762 | `CANCEL -> raise MatitaTypes.Cancel
763 with MatitaTypes.Cancel -> ()
767 (match script_fname with
768 | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
771 ask_and_save_moo_if_needed main#toplevel fname lexicon_status
774 with MatitaTypes.Cancel -> ())
776 connect_button main#scriptAdvanceButton advance;
777 connect_button main#scriptRetractButton retract;
778 connect_button main#scriptTopButton top;
779 connect_button main#scriptBottomButton bottom;
780 connect_button main#scriptJumpButton jump;
781 connect_menu_item main#scriptAdvanceMenuItem advance;
782 connect_menu_item main#scriptRetractMenuItem retract;
783 connect_menu_item main#scriptTopMenuItem top;
784 connect_menu_item main#scriptBottomMenuItem bottom;
785 connect_menu_item main#scriptJumpMenuItem jump;
786 connect_menu_item main#openMenuItem loadScript;
787 connect_menu_item main#saveMenuItem saveScript;
788 connect_menu_item main#saveAsMenuItem saveAsScript;
789 connect_menu_item main#newMenuItem newScript;
790 (* script monospace font stuff *)
791 self#updateFontSize ();
793 main#debugMenu#misc#hide ();
795 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
796 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
797 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
799 self#sourceView#misc#grab_focus ();
800 (* main win dimension *)
801 let width = Gdk.Screen.width () in
802 let height = Gdk.Screen.height () in
803 let main_w = width * 90 / 100 in
804 let main_h = height * 80 / 100 in
805 let script_w = main_w * 6 / 10 in
806 main#toplevel#resize ~width:main_w ~height:main_h;
807 main#hpaneScriptSequent#set_position script_w;
809 ignore(source_view#connect#after#paste_clipboard
810 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
811 (* clean_locked is set to true only "during" a PRIMARY paste
812 operation (i.e. by clicking with the second mouse button) *)
813 let clean_locked = ref false in
814 ignore(source_view#event#connect#button_press
817 if GdkEvent.Button.button button = 2 then
818 clean_locked := true;
821 ignore(source_view#event#connect#button_release
822 ~callback:(fun button -> clean_locked := false; false));
823 ignore(source_view#buffer#connect#after#apply_tag
825 fun tag ~start:_ ~stop:_ ->
827 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
830 clean_locked := false;
831 (MatitaScript.current ())#clean_dirty_lock;
834 (* math view handling *)
835 connect_menu_item main#newCicBrowserMenuItem (fun () ->
836 ignore (MatitaMathView.cicBrowser ()));
837 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
838 self#increaseFontSize ();
839 MatitaMathView.increase_font_size ();
840 MatitaMathView.update_font_sizes ());
841 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
842 self#decreaseFontSize ();
843 MatitaMathView.decrease_font_size ();
844 MatitaMathView.update_font_sizes ());
845 connect_menu_item main#normalFontSizeMenuItem (fun () ->
846 self#resetFontSize ();
847 MatitaMathView.reset_font_size ();
848 MatitaMathView.update_font_sizes ());
849 MatitaMathView.reset_font_size ();
851 (** selections / clipboards handling *)
853 method markupSelected = MatitaMathView.has_selection ()
854 method private textSelected =
855 (source_buffer#get_iter_at_mark `INSERT)#compare
856 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
857 method private somethingSelected = self#markupSelected || self#textSelected
858 method private markupStored = MatitaMathView.has_clipboard ()
859 method private textStored = clipboard#text <> None
860 method private somethingStored = self#markupStored || self#textStored
862 method canCopy = self#somethingSelected
863 method canCut = self#textSelected
864 method canDelete = self#textSelected
865 method canPaste = self#somethingStored
866 method canPastePattern = self#markupStored
871 MatitaMathView.empty_clipboard ();
872 source_view#buffer#copy_clipboard clipboard;
874 MatitaMathView.copy_selection ()
876 source_view#buffer#cut_clipboard clipboard;
877 MatitaMathView.empty_clipboard ()
878 method delete () = ignore (source_view#buffer#delete_selection ())
880 if MatitaMathView.has_clipboard ()
881 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
882 else source_view#buffer#paste_clipboard clipboard;
883 (MatitaScript.current ())#clean_dirty_lock
884 method pastePattern () =
885 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
887 method private nextLigature () =
888 let iter = source_buffer#get_iter_at_mark `INSERT in
889 let write_ligature len s =
890 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
891 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
893 let get_ligature word =
894 let len = String.length word in
897 for i = len - 1 downto 0 do
898 if HExtlib.is_alpha word.[i] then ()
900 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
904 if i = ~-1 then None else Some (String.sub word i (len - i))
906 let aux_ligature () =
908 for i = len - 1 downto 0 do
909 if CicNotationLexer.is_ligature_char word.[i] then ()
910 else raise (Found (i+1))
916 Some (String.sub word i (len - i))
917 with Invalid_argument _ -> None)
919 match aux_tex () with
920 | Some macro -> macro
921 | None -> (match aux_ligature () with Some l -> l | None -> word)
923 (match next_ligatures with
924 | [] -> (* find ligatures and fill next_ligatures, then try again *)
927 ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
929 let ligature = get_ligature last_word in
930 (match CicNotationLexer.lookup_ligatures ligature with
933 write_ligature (String.length ligature) hd;
934 next_ligatures <- tl @ [ hd ])
937 next_ligatures <- tl @ [ hd ])
939 method private externalEditor () =
940 let cmd = Helm_registry.get "matita.external_editor" in
941 (* ZACK uncomment to enable interactive ask of external editor command *)
944 "External editor command:
945 %f will be substitute for the script name,
946 %p for the cursor position in bytes,
947 %l for the execution point in bytes."
949 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
950 ~default:(Helm_registry.get "matita.external_editor") ()
952 let fname = (MatitaScript.current ())#filename in
954 source_buffer#start_iter#get_slice
955 ~stop:(source_buffer#get_iter_at_mark mark)
957 let script = MatitaScript.current () in
958 let locked = `MARK script#locked_mark in
959 let string_pos mark = string_of_int (String.length (slice mark)) in
960 let cursor_pos = string_pos `INSERT in
961 let locked_pos = string_pos locked in
963 Pcre.replace ~pat:"%f" ~templ:fname
964 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
965 (Pcre.replace ~pat:"%l" ~templ:locked_pos
968 let locked_before = slice locked in
969 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
970 ignore (Unix.system cmd);
971 source_buffer#set_text (HExtlib.input_file fname);
972 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
973 source_buffer#move_mark locked locked_iter;
974 source_buffer#apply_tag script#locked_tag
975 ~start:source_buffer#start_iter ~stop:locked_iter;
976 let locked_after = slice locked in
980 for i = 0 to String.length locked_before - 1 do
981 if locked_before.[i] <> locked_after.[i] then begin
982 source_buffer#place_cursor
983 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
984 script#goto `Cursor ();
986 end else if locked_before.[i] = '\n' then begin
993 | Invalid_argument _ -> script#goto `Bottom ()
995 method loadScript file =
996 let script = MatitaScript.current () in
998 script#assignFileName file;
1000 if Sys.file_exists file then file
1001 else BuildTimeConf.script_template
1003 source_view#source_buffer#begin_not_undoable_action ();
1004 script#loadFromFile content;
1005 source_view#source_buffer#end_not_undoable_action ();
1006 console#message ("'"^file^"' loaded.");
1007 self#_enableSaveTo file
1009 method setStar name b =
1010 let l = main#scriptLabel in
1012 l#set_text (name ^ " *")
1016 method private _enableSaveTo file =
1017 script_fname <- Some file;
1018 self#main#saveMenuItem#misc#set_sensitive true
1020 method console = console
1021 method sourceView: GSourceView.source_view =
1022 (source_view: GSourceView.source_view)
1023 method fileSel = fileSel
1024 method findRepl = findRepl
1026 method develList = develList
1027 method newDevel = newDevel
1029 method newBrowserWin () =
1031 inherit browserWin ()
1032 val combo = GEdit.combo_box_entry ()
1034 self#check_widgets ();
1035 let combo_widget = combo#coerce in
1036 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1037 combo#entry#misc#grab_focus ()
1038 method browserUri = combo
1041 method newUriDialog () =
1042 let dialog = new uriChoiceDialog () in
1043 dialog#check_widgets ();
1046 method newRecordDialog () =
1047 let dialog = new recordChoiceDialog () in
1048 dialog#check_widgets ();
1051 method newConfirmationDialog () =
1052 let dialog = new confirmationDialog () in
1053 dialog#check_widgets ();
1056 method newEmptyDialog () =
1057 let dialog = new emptyDialog () in
1058 dialog#check_widgets ();
1061 method private addKeyBinding key callback =
1062 List.iter (fun evbox -> add_key_binding key callback evbox)
1065 method setQuitCallback callback =
1066 connect_menu_item main#quitMenuItem callback;
1067 ignore (main#toplevel#event#connect#delete
1068 (fun _ -> callback ();true));
1069 self#addKeyBinding GdkKeysyms._q callback
1071 method chooseFile ?(ok_not_exists = false) () =
1072 _ok_not_exists <- ok_not_exists;
1073 _only_directory <- false;
1074 fileSel#fileSelectionWin#show ();
1078 method private chooseDir ?(ok_not_exists = false) () =
1079 _ok_not_exists <- ok_not_exists;
1080 _only_directory <- true;
1081 fileSel#fileSelectionWin#show ();
1083 (* we should check that this is a directory *)
1086 method createDevelopment ~containing =
1087 next_devel_must_contain <- containing;
1088 newDevel#toplevel#misc#show()
1090 method askText ?(title = "") ?(msg = "") () =
1091 let dialog = new textDialog () in
1092 dialog#textDialog#set_title title;
1093 dialog#textDialogLabel#set_label msg;
1094 let text = ref None in
1097 dialog#textDialog#destroy ();
1100 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1101 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1102 connect_button dialog#textDialogOkButton (fun _ ->
1103 let text = dialog#textDialogTextView#buffer#get_text () in
1104 return (Some text));
1105 dialog#textDialog#show ();
1109 method private updateFontSize () =
1110 self#sourceView#misc#modify_font_by_name
1111 (sprintf "%s %d" BuildTimeConf.script_font font_size)
1113 method increaseFontSize () =
1114 font_size <- font_size + 1;
1115 self#updateFontSize ()
1117 method decreaseFontSize () =
1118 font_size <- font_size - 1;
1119 self#updateFontSize ()
1121 method resetFontSize () =
1122 font_size <- default_font_size;
1123 self#updateFontSize ()
1128 let g = new gui () in
1129 gui_instance := Some g;
1130 MatitaMathView.set_gui g;
1133 let instance = singleton gui
1135 let non p x = not (p x)
1137 (* this is a shit and should be changed :-{ *)
1138 let interactive_uri_choice
1139 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1140 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1141 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1145 let gui = instance () in
1146 let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1147 if (selection_mode <> `SINGLE) &&
1148 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1150 Lazy.force nonvars_uris
1152 let dialog = gui#newUriDialog () in
1153 if hide_uri_entry then
1154 dialog#uriEntryHBox#misc#hide ();
1157 dialog#uriChoiceSelectedButton#misc#hide ();
1158 dialog#uriChoiceConstantsButton#misc#hide ();
1160 dialog#okLabel#set_label ok_label;
1161 dialog#uriChoiceTreeView#selection#set_mode
1162 (selection_mode :> Gtk.Tags.selection_mode);
1163 let model = new stringListModel dialog#uriChoiceTreeView in
1164 let choices = ref None in
1168 dialog#copyButton#misc#show ();
1169 connect_button dialog#copyButton
1171 match model#easy_selection () with
1174 dialog#uriChoiceDialog#set_title title;
1175 dialog#uriChoiceLabel#set_text msg;
1176 List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1177 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1180 dialog#uriChoiceDialog#destroy ();
1183 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1184 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1185 return (Some (Lazy.force nonvars_uris)));
1186 if ok_action = `AUTO then
1187 connect_button dialog#uriChoiceAutoButton (fun _ ->
1188 Helm_registry.set_bool "matita.auto_disambiguation" true;
1189 return (Some (Lazy.force nonvars_uris)))
1191 connect_button dialog#uriChoiceAutoButton (fun _ ->
1192 match model#easy_selection () with
1194 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1195 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1196 match model#easy_selection () with
1198 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1199 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1200 dialog#uriChoiceDialog#show ();
1202 (match !choices with
1203 | None -> raise MatitaTypes.Cancel
1204 | Some uris -> uris)
1208 let cols = new GTree.column_list in
1209 let id_col = cols#add Gobject.Data.string in
1210 let dsc_col = cols#add Gobject.Data.string in
1211 let interp_no_col = cols#add Gobject.Data.int in
1212 let tree_store = GTree.tree_store cols in
1213 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1214 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1215 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1216 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1217 fun tree_view choices ->
1220 tree_view#set_model (Some (tree_store :> GTree.model));
1221 ignore (tree_view#append_column id_view_col);
1222 ignore (tree_view#append_column dsc_view_col);
1223 let name_of_interp =
1224 (* try to find a reasonable name for an interpretation *)
1228 List.assoc "0" interp
1230 incr idx; string_of_int !idx
1232 tree_store#clear ();
1233 let idx = ref ~-1 in
1237 let interp_row = tree_store#append () in
1238 tree_store#set ~row:interp_row ~column:id_col
1239 (name_of_interp interp);
1240 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1243 let row = tree_store#append ~parent:interp_row () in
1244 tree_store#set ~row ~column:id_col id;
1245 tree_store#set ~row ~column:dsc_col dsc;
1246 tree_store#set ~row ~column:interp_no_col !idx)
1250 method get_interp_no tree_path =
1251 let iter = tree_store#get_iter tree_path in
1252 tree_store#get ~row:iter ~column:interp_no_col
1255 let interactive_interp_choice () choices =
1256 let gui = instance () in
1257 assert (choices <> []);
1258 let dialog = gui#newRecordDialog () in
1259 let model = new interpModel dialog#recordChoiceTreeView choices in
1260 dialog#recordChoiceDialog#set_title "Interpretation choice";
1261 dialog#recordChoiceDialogLabel#set_label "Choose an interpretation:";
1262 let interp_no = ref None in
1264 dialog#recordChoiceDialog#destroy ();
1267 let fail _ = interp_no := None; return () in
1268 ignore (dialog#recordChoiceDialog#event#connect#delete (fun _ -> true));
1269 connect_button dialog#recordChoiceOkButton (fun _ ->
1270 match !interp_no with None -> () | Some _ -> return ());
1271 connect_button dialog#recordChoiceCancelButton fail;
1272 ignore (dialog#recordChoiceTreeView#connect#row_activated (fun path _ ->
1273 interp_no := Some (model#get_interp_no path);
1275 let selection = dialog#recordChoiceTreeView#selection in
1276 ignore (selection#connect#changed (fun _ ->
1277 match selection#get_selected_rows with
1278 | [path] -> interp_no := Some (model#get_interp_no path)
1279 | _ -> assert false));
1280 dialog#recordChoiceDialog#show ();
1282 (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
1285 (* disambiguator callbacks *)
1286 GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1287 GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1288 (* gtk initialization *)
1289 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1290 GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1291 ignore (GMain.Main.init ())