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 let basedir = Helm_registry.get "matita.basedir" in
70 LibraryClean.clean_baseuris ~basedir [baseuri]
71 with GrafiteTypes.Option_error _ -> ()
73 let ask_and_save_moo_if_needed parent fname lexicon_status grafite_status =
74 let basedir = Helm_registry.get "matita.basedir" in
75 let baseuri = DependenciesParser.baseuri_of_script ~include_paths:[] fname in
76 let moo_fname = LibraryMisc.obj_file_of_baseuri ~basedir ~baseuri in
78 let metadata_fname= LibraryMisc.metadata_file_of_baseuri ~basedir ~baseuri in
79 GrafiteMarshal.save_moo moo_fname
80 grafite_status.GrafiteTypes.moo_content_rev;
81 LibraryNoDb.save_metadata metadata_fname
82 lexicon_status.LexiconEngine.metadata
84 if (MatitaScript.current ())#eos &&
85 grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof
89 MatitaGtkMisc.ask_confirmation
90 ~title:"A .moo can be generated"
91 ~message:(Printf.sprintf
92 "%s can be generated for %s.\n<i>Should I generate it?</i>"
93 (Filename.basename moo_fname) (Filename.basename fname))
100 | `CANCEL -> raise MatitaTypes.Cancel
105 clean_current_baseuri grafite_status
108 clean_current_baseuri grafite_status
110 let ask_unsaved parent =
111 MatitaGtkMisc.ask_confirmation
112 ~parent ~title:"Unsaved work!"
113 ~message:("Your work is <b>unsaved</b>!\n\n"^
114 "<i>Do you want to save the script before continuing?</i>")
117 (** Selection handling
118 * Two clipboards are used: "clipboard" and "primary".
119 * "primary" is used by X, when you hit the middle button mouse is content is
120 * pasted between applications. In Matita this selection always contain the
121 * textual version of the selected term.
122 * "clipboard" is used inside Matita only and support ATM two different targets:
123 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
128 (* creation order _is_ relevant for windows placement *)
129 let main = new mainWin () in
130 let fileSel = new fileSelectionWin () in
131 let findRepl = new findReplWin () in
132 let develList = new develListWin () in
133 let newDevel = new newDevelWin () in
134 let keyBindingBoxes = (* event boxes which should receive global key events *)
135 [ main#mainWinEventBox ]
137 let console = new console ~buffer:main#logTextView#buffer () in
138 let (source_view: GSourceView.source_view) =
139 GSourceView.source_view
141 ~insert_spaces_instead_of_tabs:true ~tabs_width:2
142 ~margin:80 ~show_margin:true
144 ~packing:main#scriptScrolledWin#add
147 let default_font_size =
148 Helm_registry.get_opt_default Helm_registry.int
149 ~default:BuildTimeConf.default_font_size "matita.font_size"
151 let source_buffer = source_view#source_buffer in
153 val mutable chosen_file = None
154 val mutable _ok_not_exists = false
155 val mutable _only_directory = false
156 val mutable script_fname = None
157 val mutable font_size = default_font_size
158 val mutable next_devel_must_contain = None
159 val mutable next_ligatures = []
160 val clipboard = GData.clipboard Gdk.Atom.clipboard
161 val primary = GData.clipboard Gdk.Atom.primary
164 (* glade's check widgets *)
165 List.iter (fun w -> w#check_widgets ())
166 (let c w = (w :> <check_widgets: unit -> unit>) in
167 [ c fileSel; c main; c findRepl]);
169 List.iter (* global key bindings *)
170 (fun (key, callback) -> self#addKeyBinding key callback)
173 toggle_win ~check:main#showProofMenuItem proof#proofWin;
175 toggle_win ~check:main#showCheckMenuItem check#checkWin;
179 let parse_txt_file file =
180 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
181 let l_rev = ref [] in
184 l_rev := input_line ch :: !l_rev;
193 ~authors:(parse_txt_file "AUTHORS")
194 (*~comments:"comments"*)
195 ~copyright:"Copyright (C) 2005, the HELM team"
196 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
197 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
199 ~version:BuildTimeConf.version
200 ~website:"http://helm.cs.unibo.it"
203 connect_menu_item main#aboutMenuItem about_dialog#present;
205 let show_find_Repl () =
206 findRepl#toplevel#misc#show ();
207 findRepl#toplevel#misc#grab_focus ()
209 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
211 let highlight start end_ =
212 source_buffer#move_mark `INSERT ~where:start;
213 source_buffer#move_mark `SEL_BOUND ~where:end_;
214 source_view#scroll_mark_onscreen `INSERT
216 let text = findRepl#findEntry#text in
217 let iter = source_buffer#get_iter `SEL_BOUND in
218 match iter#forward_search text with
220 (match source_buffer#start_iter#forward_search text with
222 | Some (start,end_) -> highlight start end_)
223 | Some (start,end_) -> highlight start end_
226 let text = findRepl#replaceEntry#text in
227 let ins = source_buffer#get_iter `INSERT in
228 let sel = source_buffer#get_iter `SEL_BOUND in
229 if ins#compare sel < 0 then
231 ignore(source_buffer#delete_selection ());
232 source_buffer#insert text
235 connect_button findRepl#findButton find_forward;
236 connect_button findRepl#findReplButton replace;
237 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
238 ignore(findRepl#toplevel#event#connect#delete
239 ~callback:(fun _ -> hide_find_Repl ();true));
242 (* phase 1: we save the actual status of the marks and we undo *)
243 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
244 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
245 let locked_iter_offset = locked_iter#offset in
248 (source_view#buffer#create_mark ~name:"lock_point"
249 ~left_gravity:true locked_iter) in
250 source_view#source_buffer#undo ();
251 (* phase 2: we save the cursor position and we redo, restoring
252 the previous status of all the marks *)
253 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
256 (source_view#buffer#create_mark ~name:"undo_point"
257 ~left_gravity:true cursor_iter)
259 source_view#source_buffer#redo ();
260 let mark_iter = source_view#buffer#get_iter_at_mark mark in
261 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
262 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
263 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
264 source_view#buffer#delete_mark mark;
265 source_view#buffer#delete_mark mark2;
266 (* phase 3: if after the undo the cursor was in the locked area,
267 then we move it there again and we perform a goto *)
268 if mark_iter#offset < locked_iter_offset then
270 source_view#buffer#move_mark `INSERT ~where:mark_iter;
271 (MatitaScript.current ())#goto `Cursor ();
273 (* phase 4: we perform again the undo. This time we are sure that
274 the text to undo is not locked *)
275 source_view#source_buffer#undo ();
276 source_view#misc#grab_focus () in
279 (* phase 1: we save the actual status of the marks, we redo and
281 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
282 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
283 let locked_iter_offset = locked_iter#offset in
286 (source_view#buffer#create_mark ~name:"lock_point"
287 ~left_gravity:true locked_iter) in
288 source_view#source_buffer#redo ();
289 source_view#source_buffer#undo ();
290 (* phase 2: we save the cursor position and we restore
291 the previous status of all the marks *)
292 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
295 (source_view#buffer#create_mark ~name:"undo_point"
296 ~left_gravity:true cursor_iter)
298 let mark_iter = source_view#buffer#get_iter_at_mark mark in
299 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
300 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
301 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
302 source_view#buffer#delete_mark mark;
303 source_view#buffer#delete_mark mark2;
304 (* phase 3: if after the undo the cursor is in the locked area,
305 then we move it there again and we perform a goto *)
306 if mark_iter#offset < locked_iter_offset then
308 source_view#buffer#move_mark `INSERT ~where:mark_iter;
309 (MatitaScript.current ())#goto `Cursor ();
311 (* phase 4: we perform again the redo. This time we are sure that
312 the text to redo is not locked *)
313 source_view#source_buffer#redo ();
314 source_view#misc#grab_focus ()
316 connect_menu_item main#undoMenuItem safe_undo;
317 ignore(source_view#source_buffer#connect#can_undo
318 ~callback:main#undoMenuItem#misc#set_sensitive);
319 connect_menu_item main#redoMenuItem safe_redo;
320 ignore(source_view#source_buffer#connect#can_redo
321 ~callback:main#redoMenuItem#misc#set_sensitive);
322 ignore(source_view#connect#after#populate_popup
323 ~callback:(fun pre_menu ->
324 let menu = new GMenu.menu pre_menu in
325 let menuItems = menu#children in
326 let undoMenuItem, redoMenuItem =
328 [undo;redo;sep1;cut;copy;paste;delete;sep2;
329 selectall;sep3;inputmethod;insertunicodecharacter] ->
330 List.iter menu#remove [ copy; cut; delete; paste ];
332 | _ -> assert false in
334 let i = ref 2 in (* last occupied position *)
335 fun ?label ?stock () ->
337 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
340 let copy = add_menu_item ~stock:`COPY () in
341 let cut = add_menu_item ~stock:`CUT () in
342 let delete = add_menu_item ~stock:`DELETE () in
343 let paste = add_menu_item ~stock:`PASTE () in
344 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
345 copy#misc#set_sensitive self#canCopy;
346 cut#misc#set_sensitive self#canCut;
347 delete#misc#set_sensitive self#canDelete;
348 paste#misc#set_sensitive self#canPaste;
349 paste_pattern#misc#set_sensitive self#canPastePattern;
350 connect_menu_item copy self#copy;
351 connect_menu_item cut self#cut;
352 connect_menu_item delete self#delete;
353 connect_menu_item paste self#paste;
354 connect_menu_item paste_pattern self#pastePattern;
355 let new_undoMenuItem =
356 GMenu.image_menu_item
357 ~image:(GMisc.image ~stock:`UNDO ())
360 ~packing:(menu#insert ~pos:0) () in
361 new_undoMenuItem#misc#set_sensitive
362 (undoMenuItem#misc#get_flag `SENSITIVE);
363 menu#remove (undoMenuItem :> GMenu.menu_item);
364 connect_menu_item new_undoMenuItem safe_undo;
365 let new_redoMenuItem =
366 GMenu.image_menu_item
367 ~image:(GMisc.image ~stock:`REDO ())
370 ~packing:(menu#insert ~pos:1) () in
371 new_redoMenuItem#misc#set_sensitive
372 (redoMenuItem#misc#get_flag `SENSITIVE);
373 menu#remove (redoMenuItem :> GMenu.menu_item);
374 connect_menu_item new_redoMenuItem safe_redo));
376 connect_menu_item main#editMenu (fun () ->
377 main#copyMenuItem#misc#set_sensitive self#canCopy;
378 main#cutMenuItem#misc#set_sensitive self#canCut;
379 main#deleteMenuItem#misc#set_sensitive self#canDelete;
380 main#pasteMenuItem#misc#set_sensitive self#canPaste;
381 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
382 connect_menu_item main#copyMenuItem self#copy;
383 connect_menu_item main#cutMenuItem self#cut;
384 connect_menu_item main#deleteMenuItem self#delete;
385 connect_menu_item main#pasteMenuItem self#paste;
386 connect_menu_item main#pastePatternMenuItem self#pastePattern;
387 connect_menu_item main#selectAllMenuItem (fun () ->
388 source_buffer#move_mark `INSERT source_buffer#start_iter;
389 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
390 connect_menu_item main#findReplMenuItem show_find_Repl;
391 connect_menu_item main#externalEditorMenuItem self#externalEditor;
392 connect_menu_item main#ligatureButton self#nextLigature;
393 ignore (findRepl#findEntry#connect#activate find_forward);
394 (* interface lockers *)
396 main#buttonsToolbar#misc#set_sensitive false;
397 develList#buttonsHbox#misc#set_sensitive false;
398 source_view#set_editable false
401 main#buttonsToolbar#misc#set_sensitive true;
402 develList#buttonsHbox#misc#set_sensitive true;
403 source_view#set_editable true
408 try f ();unlock_world () with exc -> unlock_world (); raise exc in
412 f (); source_view#misc#grab_focus ()
414 exc -> source_view#misc#grab_focus (); raise exc in
415 (* developments win *)
417 new MatitaGtkMisc.multiStringListModel
418 ~cols:2 develList#developmentsTreeview
420 let refresh_devels_win () =
421 model#list_store#clear ();
423 (fun (name, root) -> model#easy_mappend [name;root])
424 (MatitamakeLib.list_known_developments ())
426 let get_devel_selected () =
427 match model#easy_mselection () with
428 | [[name;_]] -> MatitamakeLib.development_for_name name
432 while Glib.Main.pending () do
433 ignore(Glib.Main.iteration false);
436 connect_button develList#newButton
438 next_devel_must_contain <- None;
439 newDevel#toplevel#misc#show());
440 connect_button develList#deleteButton
442 (match get_devel_selected () with
444 | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
445 refresh_devels_win ()));
446 connect_button develList#buildButton
448 match get_devel_selected () with
452 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
455 connect_button develList#cleanButton
457 match get_devel_selected () with
461 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
464 connect_button develList#closeButton
465 (fun () -> develList#toplevel#misc#hide());
466 ignore(develList#toplevel#event#connect#delete
467 (fun _ -> develList#toplevel#misc#hide();true));
468 connect_menu_item main#developmentsMenuItem
469 (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
471 (* add development win *)
472 let check_if_root_contains root =
473 match next_devel_must_contain with
476 let is_prefix_of d1 d2 =
477 let len1 = String.length d1 in
478 let len2 = String.length d2 in
482 let pref = String.sub d2 0 len1 in
485 is_prefix_of root path
487 connect_button newDevel#addButton
489 let name = newDevel#nameEntry#text in
490 let root = newDevel#rootEntry#text in
491 if check_if_root_contains root then
493 ignore (MatitamakeLib.initialize_development name root);
494 refresh_devels_win ();
495 newDevel#nameEntry#set_text "";
496 newDevel#rootEntry#set_text "";
497 newDevel#toplevel#misc#hide()
500 HLog.error ("The selected root does not contain " ^
501 match next_devel_must_contain with
503 | _ -> assert false));
504 connect_button newDevel#chooseRootButton
506 let path = self#chooseDir () in
508 | Some path -> newDevel#rootEntry#set_text path
510 connect_button newDevel#cancelButton
511 (fun () -> newDevel#toplevel#misc#hide ());
512 ignore(newDevel#toplevel#event#connect#delete
513 (fun _ -> newDevel#toplevel#misc#hide();true));
515 (* file selection win *)
516 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
517 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
520 fileSel#fileSelectionWin#misc#hide ();
525 let fname = fileSel#fileSelectionWin#filename in
526 if Sys.file_exists fname then
528 if HExtlib.is_regular fname && not (_only_directory) then
530 else if _only_directory && HExtlib.is_dir fname then
535 if _ok_not_exists then
538 | `CANCEL -> return None
540 | `DELETE_EVENT -> return None));
542 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
544 let adj = main#logScrolledWin#vadjustment in
545 ignore (adj#connect#changed
546 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
547 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
549 let module A = GrafiteAst in
550 let hole = CicNotationPt.UserInput in
551 let loc = HExtlib.dummy_floc in
553 if (MatitaScript.current ())#onGoingProof () then
554 (MatitaScript.current ())#advance
556 ^ GrafiteAstPp.pp_tactical ~term_pp:CicNotationPp.pp_term
557 ~lazy_term_pp:CicNotationPp.pp_term (A.Tactic (loc, ast)))
560 let tac_w_term ast _ =
561 if (MatitaScript.current ())#onGoingProof () then
562 let buf = source_buffer in
563 buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
565 ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
566 ~lazy_term_pp:CicNotationPp.pp_term ast)
569 connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
570 connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
571 connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
572 connect_button tbar#elimButton (tac_w_term
573 (A.Elim (loc, hole, None, None, [])));
574 connect_button tbar#elimTypeButton (tac_w_term
575 (A.ElimType (loc, hole, None, None, [])));
576 connect_button tbar#splitButton (tac (A.Split loc));
577 connect_button tbar#leftButton (tac (A.Left loc));
578 connect_button tbar#rightButton (tac (A.Right loc));
579 connect_button tbar#existsButton (tac (A.Exists loc));
580 connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
581 connect_button tbar#symmetryButton (tac (A.Symmetry loc));
582 connect_button tbar#transitivityButton
583 (tac_w_term (A.Transitivity (loc, hole)));
584 connect_button tbar#assumptionButton (tac (A.Assumption loc));
585 connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
586 connect_button tbar#autoButton (tac (A.Auto (loc,None,None,None,None)));
587 MatitaGtkMisc.toggle_widget_visibility
588 ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
589 ~check:main#tacticsBarMenuItem;
590 let module Hr = Helm_registry in
592 not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
594 main#tacticsBarMenuItem#set_active false;
595 MatitaGtkMisc.toggle_callback
597 | true -> main#toplevel#fullscreen ()
598 | false -> main#toplevel#unfullscreen ())
599 ~check:main#fullscreenMenuItem;
600 main#fullscreenMenuItem#set_active false;
602 HLog.set_log_callback self#console#log_callback;
603 GtkSignal.user_handler :=
605 if not (Helm_registry.get_bool "matita.debug") then
606 let floc, msg = MatitaExcPp.to_string exn in
611 let (x, y) = HExtlib.loc_of_floc floc in
612 let script = MatitaScript.current () in
613 let locked_mark = script#locked_mark in
614 let error_tag = script#error_tag in
616 (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
617 let x' = baseoffset + x in
618 let y' = baseoffset + y in
619 let x_iter = source_buffer#get_iter (`OFFSET x') in
620 let y_iter = source_buffer#get_iter (`OFFSET y') in
621 source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
623 id := Some (source_buffer#connect#changed ~callback:(fun () ->
624 source_buffer#remove_tag error_tag
625 ~start:source_buffer#start_iter
626 ~stop:source_buffer#end_iter;
628 | None -> assert false (* a race condition occurred *)
630 (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
631 source_buffer#place_cursor
632 (source_buffer#get_iter (`OFFSET x'));
637 ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
639 match GSourceView.source_language_from_file BuildTimeConf.lang_file with
641 HLog.warn (sprintf "can't load language file %s"
642 BuildTimeConf.lang_file)
643 | Some matita_lang ->
644 source_buffer#set_language matita_lang;
645 source_buffer#set_highlight true
647 let s () = MatitaScript.current () in
649 script_fname <- None;
650 main#saveMenuItem#misc#set_sensitive false
652 let saveAsScript () =
654 match self#chooseFile ~ok_not_exists:true () with
656 script#assignFileName f;
657 script#saveToFile ();
658 console#message ("'"^f^"' saved.\n");
663 match script_fname with
664 | None -> saveAsScript ()
666 (s ())#assignFileName f;
667 (s ())#saveToFile ();
668 console#message ("'"^f^"' saved.\n");
670 let abandon_script () =
671 let lexicon_status = (s ())#lexicon_status in
672 let grafite_status = (s ())#grafite_status in
673 if source_view#buffer#modified then
674 (match ask_unsaved main#toplevel with
675 | `YES -> saveScript ()
677 | `CANCEL -> raise MatitaTypes.Cancel);
678 (match script_fname with
681 ask_and_save_moo_if_needed main#toplevel fname
682 lexicon_status grafite_status);
687 match self#chooseFile () with
691 script#assignFileName f;
692 source_view#source_buffer#begin_not_undoable_action ();
693 script#loadFromFile f;
694 source_view#source_buffer#end_not_undoable_action ();
695 console#message ("'"^f^"' loaded.\n");
698 with MatitaTypes.Cancel -> ()
702 source_view#source_buffer#begin_not_undoable_action ();
705 source_view#source_buffer#end_not_undoable_action ();
710 source_buffer#place_cursor
711 (source_buffer#get_iter_at_mark (`NAME "locked")) in
712 let advance _ = (MatitaScript.current ())#advance (); cursor () in
713 let retract _ = (MatitaScript.current ())#retract (); cursor () in
714 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
715 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
716 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
717 let advance = locker (keep_focus advance) in
718 let retract = locker (keep_focus retract) in
719 let top = locker (keep_focus top) in
720 let bottom = locker (keep_focus bottom) in
721 let jump = locker (keep_focus jump) in
722 let connect_key sym f =
723 connect_key main#mainWinEventBox#event
724 ~modifiers:[`CONTROL] ~stop:true sym f;
725 connect_key self#sourceView#event
726 ~modifiers:[`CONTROL] ~stop:true sym f
729 self#setQuitCallback (fun () ->
730 let lexicon_status = (MatitaScript.current ())#lexicon_status in
731 let grafite_status = (MatitaScript.current ())#grafite_status in
732 if source_view#buffer#modified then
734 let rc = ask_unsaved main#toplevel in
737 | `YES -> saveScript ();
738 if not source_view#buffer#modified then
740 (match script_fname with
743 ask_and_save_moo_if_needed main#toplevel
744 fname lexicon_status grafite_status);
747 | `NO -> GMain.Main.quit ()
748 | `CANCEL -> raise MatitaTypes.Cancel
749 with MatitaTypes.Cancel -> ()
753 (match script_fname with
754 | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
757 ask_and_save_moo_if_needed main#toplevel fname lexicon_status
760 with MatitaTypes.Cancel -> ())
762 connect_button main#scriptAdvanceButton advance;
763 connect_button main#scriptRetractButton retract;
764 connect_button main#scriptTopButton top;
765 connect_button main#scriptBottomButton bottom;
766 connect_button main#scriptJumpButton jump;
767 connect_menu_item main#scriptAdvanceMenuItem advance;
768 connect_menu_item main#scriptRetractMenuItem retract;
769 connect_menu_item main#scriptTopMenuItem top;
770 connect_menu_item main#scriptBottomMenuItem bottom;
771 connect_menu_item main#scriptJumpMenuItem jump;
772 connect_menu_item main#openMenuItem loadScript;
773 connect_menu_item main#saveMenuItem saveScript;
774 connect_menu_item main#saveAsMenuItem saveAsScript;
775 connect_menu_item main#newMenuItem newScript;
776 (* script monospace font stuff *)
777 self#updateFontSize ();
779 main#debugMenu#misc#hide ();
781 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
782 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
783 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
785 self#sourceView#misc#grab_focus ();
786 (* main win dimension *)
787 let width = Gdk.Screen.width () in
788 let height = Gdk.Screen.height () in
789 let main_w = width * 90 / 100 in
790 let main_h = height * 80 / 100 in
791 let script_w = main_w * 6 / 10 in
792 main#toplevel#resize ~width:main_w ~height:main_h;
793 main#hpaneScriptSequent#set_position script_w;
795 ignore(source_view#connect#after#paste_clipboard
796 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
797 (* clean_locked is set to true only "during" a PRIMARY paste
798 operation (i.e. by clicking with the second mouse button) *)
799 let clean_locked = ref false in
800 ignore(source_view#event#connect#button_press
803 if GdkEvent.Button.button button = 2 then
804 clean_locked := true;
807 ignore(source_view#event#connect#button_release
808 ~callback:(fun button -> clean_locked := false; false));
809 ignore(source_view#buffer#connect#after#apply_tag
811 fun tag ~start:_ ~stop:_ ->
813 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
816 clean_locked := false;
817 (MatitaScript.current ())#clean_dirty_lock;
820 (* math view handling *)
821 connect_menu_item main#newCicBrowserMenuItem (fun () ->
822 ignore (MatitaMathView.cicBrowser ()));
823 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
824 self#increaseFontSize ();
825 MatitaMathView.increase_font_size ();
826 MatitaMathView.update_font_sizes ());
827 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
828 self#decreaseFontSize ();
829 MatitaMathView.decrease_font_size ();
830 MatitaMathView.update_font_sizes ());
831 connect_menu_item main#normalFontSizeMenuItem (fun () ->
832 self#resetFontSize ();
833 MatitaMathView.reset_font_size ();
834 MatitaMathView.update_font_sizes ());
835 MatitaMathView.reset_font_size ();
837 (** selections / clipboards handling *)
839 method markupSelected = MatitaMathView.has_selection ()
840 method private textSelected =
841 (source_buffer#get_iter_at_mark `INSERT)#compare
842 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
843 method private somethingSelected = self#markupSelected || self#textSelected
844 method private markupStored = MatitaMathView.has_clipboard ()
845 method private textStored = clipboard#text <> None
846 method private somethingStored = self#markupStored || self#textStored
848 method canCopy = self#somethingSelected
849 method canCut = self#textSelected
850 method canDelete = self#textSelected
851 method canPaste = self#somethingStored
852 method canPastePattern = self#markupStored
857 MatitaMathView.empty_clipboard ();
858 source_view#buffer#copy_clipboard clipboard;
860 MatitaMathView.copy_selection ()
862 source_view#buffer#cut_clipboard clipboard;
863 MatitaMathView.empty_clipboard ()
864 method delete () = ignore (source_view#buffer#delete_selection ())
866 if MatitaMathView.has_clipboard ()
867 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
868 else source_view#buffer#paste_clipboard clipboard;
869 (MatitaScript.current ())#clean_dirty_lock
870 method pastePattern () =
871 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
873 method private nextLigature () =
874 let iter = source_buffer#get_iter_at_mark `INSERT in
875 let write_ligature len s =
876 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
877 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
879 let get_ligature word =
880 let len = String.length word in
883 for i = len - 1 downto 0 do
884 if HExtlib.is_alpha word.[i] then ()
886 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
890 if i = ~-1 then None else Some (String.sub word i (len - i))
892 let aux_ligature () =
894 for i = len - 1 downto 0 do
895 if CicNotationLexer.is_ligature_char word.[i] then ()
896 else raise (Found (i+1))
902 Some (String.sub word i (len - i))
903 with Invalid_argument _ -> None)
905 match aux_tex () with
906 | Some macro -> macro
907 | None -> (match aux_ligature () with Some l -> l | None -> word)
909 (match next_ligatures with
910 | [] -> (* find ligatures and fill next_ligatures, then try again *)
913 ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
915 let ligature = get_ligature last_word in
916 (match CicNotationLexer.lookup_ligatures ligature with
919 write_ligature (String.length ligature) hd;
920 next_ligatures <- tl @ [ hd ])
923 next_ligatures <- tl @ [ hd ])
925 method private externalEditor () =
926 let cmd = Helm_registry.get "matita.external_editor" in
927 (* ZACK uncomment to enable interactive ask of external editor command *)
930 "External editor command:
931 %f will be substitute for the script name,
932 %p for the cursor position in bytes,
933 %l for the execution point in bytes."
935 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
936 ~default:(Helm_registry.get "matita.external_editor") ()
938 let fname = (MatitaScript.current ())#filename in
940 source_buffer#start_iter#get_slice
941 ~stop:(source_buffer#get_iter_at_mark mark)
943 let script = MatitaScript.current () in
944 let locked = `MARK script#locked_mark in
945 let string_pos mark = string_of_int (String.length (slice mark)) in
946 let cursor_pos = string_pos `INSERT in
947 let locked_pos = string_pos locked in
949 Pcre.replace ~pat:"%f" ~templ:fname
950 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
951 (Pcre.replace ~pat:"%l" ~templ:locked_pos
954 let locked_before = slice locked in
955 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
956 ignore (Unix.system cmd);
957 source_buffer#set_text (HExtlib.input_file fname);
958 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
959 source_buffer#move_mark locked locked_iter;
960 source_buffer#apply_tag script#locked_tag
961 ~start:source_buffer#start_iter ~stop:locked_iter;
962 let locked_after = slice locked in
966 for i = 0 to String.length locked_before - 1 do
967 if locked_before.[i] <> locked_after.[i] then begin
968 source_buffer#place_cursor
969 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
970 script#goto `Cursor ();
972 end else if locked_before.[i] = '\n' then begin
979 | Invalid_argument _ -> script#goto `Bottom ()
981 method loadScript file =
982 let script = MatitaScript.current () in
984 script#assignFileName file;
986 if Sys.file_exists file then file
987 else BuildTimeConf.script_template
989 source_view#source_buffer#begin_not_undoable_action ();
990 script#loadFromFile content;
991 source_view#source_buffer#end_not_undoable_action ();
992 console#message ("'"^file^"' loaded.");
993 self#_enableSaveTo file
995 method setStar name b =
996 let l = main#scriptLabel in
998 l#set_text (name ^ " *")
1002 method private _enableSaveTo file =
1003 script_fname <- Some file;
1004 self#main#saveMenuItem#misc#set_sensitive true
1006 method console = console
1007 method sourceView: GSourceView.source_view =
1008 (source_view: GSourceView.source_view)
1009 method fileSel = fileSel
1010 method findRepl = findRepl
1012 method develList = develList
1013 method newDevel = newDevel
1015 method newBrowserWin () =
1017 inherit browserWin ()
1018 val combo = GEdit.combo_box_entry ()
1020 self#check_widgets ();
1021 let combo_widget = combo#coerce in
1022 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1023 combo#entry#misc#grab_focus ()
1024 method browserUri = combo
1027 method newUriDialog () =
1028 let dialog = new uriChoiceDialog () in
1029 dialog#check_widgets ();
1032 method newRecordDialog () =
1033 let dialog = new recordChoiceDialog () in
1034 dialog#check_widgets ();
1037 method newConfirmationDialog () =
1038 let dialog = new confirmationDialog () in
1039 dialog#check_widgets ();
1042 method newEmptyDialog () =
1043 let dialog = new emptyDialog () in
1044 dialog#check_widgets ();
1047 method private addKeyBinding key callback =
1048 List.iter (fun evbox -> add_key_binding key callback evbox)
1051 method setQuitCallback callback =
1052 connect_menu_item main#quitMenuItem callback;
1053 ignore (main#toplevel#event#connect#delete
1054 (fun _ -> callback ();true));
1055 self#addKeyBinding GdkKeysyms._q callback
1057 method chooseFile ?(ok_not_exists = false) () =
1058 _ok_not_exists <- ok_not_exists;
1059 _only_directory <- false;
1060 fileSel#fileSelectionWin#show ();
1064 method private chooseDir ?(ok_not_exists = false) () =
1065 _ok_not_exists <- ok_not_exists;
1066 _only_directory <- true;
1067 fileSel#fileSelectionWin#show ();
1069 (* we should check that this is a directory *)
1072 method createDevelopment ~containing =
1073 next_devel_must_contain <- containing;
1074 newDevel#toplevel#misc#show()
1076 method askText ?(title = "") ?(msg = "") () =
1077 let dialog = new textDialog () in
1078 dialog#textDialog#set_title title;
1079 dialog#textDialogLabel#set_label msg;
1080 let text = ref None in
1083 dialog#textDialog#destroy ();
1086 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1087 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1088 connect_button dialog#textDialogOkButton (fun _ ->
1089 let text = dialog#textDialogTextView#buffer#get_text () in
1090 return (Some text));
1091 dialog#textDialog#show ();
1095 method private updateFontSize () =
1096 self#sourceView#misc#modify_font_by_name
1097 (sprintf "%s %d" BuildTimeConf.script_font font_size)
1099 method increaseFontSize () =
1100 font_size <- font_size + 1;
1101 self#updateFontSize ()
1103 method decreaseFontSize () =
1104 font_size <- font_size - 1;
1105 self#updateFontSize ()
1107 method resetFontSize () =
1108 font_size <- default_font_size;
1109 self#updateFontSize ()
1114 let g = new gui () in
1115 gui_instance := Some g;
1116 MatitaMathView.set_gui g;
1119 let instance = singleton gui
1121 let non p x = not (p x)
1123 (* this is a shit and should be changed :-{ *)
1124 let interactive_uri_choice
1125 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1126 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1127 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1131 let gui = instance () in
1132 let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1133 if (selection_mode <> `SINGLE) &&
1134 (Helm_registry.get_bool "matita.auto_disambiguation")
1136 Lazy.force nonvars_uris
1138 let dialog = gui#newUriDialog () in
1139 if hide_uri_entry then
1140 dialog#uriEntryHBox#misc#hide ();
1143 dialog#uriChoiceSelectedButton#misc#hide ();
1144 dialog#uriChoiceConstantsButton#misc#hide ();
1146 dialog#okLabel#set_label ok_label;
1147 dialog#uriChoiceTreeView#selection#set_mode
1148 (selection_mode :> Gtk.Tags.selection_mode);
1149 let model = new stringListModel dialog#uriChoiceTreeView in
1150 let choices = ref None in
1154 dialog#copyButton#misc#show ();
1155 connect_button dialog#copyButton
1157 match model#easy_selection () with
1160 dialog#uriChoiceDialog#set_title title;
1161 dialog#uriChoiceLabel#set_text msg;
1162 List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1163 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1166 dialog#uriChoiceDialog#destroy ();
1169 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1170 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1171 return (Some (Lazy.force nonvars_uris)));
1172 if ok_action = `AUTO then
1173 connect_button dialog#uriChoiceAutoButton (fun _ ->
1174 Helm_registry.set_bool "matita.auto_disambiguation" true;
1175 return (Some (Lazy.force nonvars_uris)))
1177 connect_button dialog#uriChoiceAutoButton (fun _ ->
1178 match model#easy_selection () with
1180 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1181 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1182 match model#easy_selection () with
1184 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1185 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1186 dialog#uriChoiceDialog#show ();
1188 (match !choices with
1189 | None -> raise MatitaTypes.Cancel
1190 | Some uris -> uris)
1194 let cols = new GTree.column_list in
1195 let id_col = cols#add Gobject.Data.string in
1196 let dsc_col = cols#add Gobject.Data.string in
1197 let interp_no_col = cols#add Gobject.Data.int in
1198 let tree_store = GTree.tree_store cols in
1199 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1200 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1201 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1202 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1203 fun tree_view choices ->
1206 tree_view#set_model (Some (tree_store :> GTree.model));
1207 ignore (tree_view#append_column id_view_col);
1208 ignore (tree_view#append_column dsc_view_col);
1209 let name_of_interp =
1210 (* try to find a reasonable name for an interpretation *)
1214 List.assoc "0" interp
1216 incr idx; string_of_int !idx
1218 tree_store#clear ();
1219 let idx = ref ~-1 in
1223 let interp_row = tree_store#append () in
1224 tree_store#set ~row:interp_row ~column:id_col
1225 (name_of_interp interp);
1226 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1229 let row = tree_store#append ~parent:interp_row () in
1230 tree_store#set ~row ~column:id_col id;
1231 tree_store#set ~row ~column:dsc_col dsc;
1232 tree_store#set ~row ~column:interp_no_col !idx)
1236 method get_interp_no tree_path =
1237 let iter = tree_store#get_iter tree_path in
1238 tree_store#get ~row:iter ~column:interp_no_col
1241 let interactive_interp_choice () choices =
1242 let gui = instance () in
1243 assert (choices <> []);
1244 let dialog = gui#newRecordDialog () in
1245 let model = new interpModel dialog#recordChoiceTreeView choices in
1246 dialog#recordChoiceDialog#set_title "Interpretation choice";
1247 dialog#recordChoiceDialogLabel#set_label "Choose an interpretation:";
1248 let interp_no = ref None in
1250 dialog#recordChoiceDialog#destroy ();
1253 let fail _ = interp_no := None; return () in
1254 ignore (dialog#recordChoiceDialog#event#connect#delete (fun _ -> true));
1255 connect_button dialog#recordChoiceOkButton (fun _ ->
1256 match !interp_no with None -> () | Some _ -> return ());
1257 connect_button dialog#recordChoiceCancelButton fail;
1258 ignore (dialog#recordChoiceTreeView#connect#row_activated (fun path _ ->
1259 interp_no := Some (model#get_interp_no path);
1261 let selection = dialog#recordChoiceTreeView#selection in
1262 ignore (selection#connect#changed (fun _ ->
1263 match selection#get_selected_rows with
1264 | [path] -> interp_no := Some (model#get_interp_no path)
1265 | _ -> assert false));
1266 dialog#recordChoiceDialog#show ();
1268 (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
1271 (* disambiguator callbacks *)
1272 GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1273 GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1274 (* gtk initialization *)
1275 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1276 GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1277 ignore (GMain.Main.init ())