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 =
74 try Some (GrafiteTypes.get_string_option grafite_status "baseuri")
75 with GrafiteTypes.Option_error _ -> None
77 if (MatitaScript.current ())#eos &&
78 grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof &&
82 let baseuri = match baseuri with Some b -> b | None -> assert false in
84 LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri
88 LibraryMisc.metadata_file_of_baseuri
89 ~must_exist:false ~baseuri ~writable:true in
91 LibraryMisc.lexicon_file_of_baseuri
92 ~must_exist:false ~baseuri ~writable:true
94 GrafiteMarshal.save_moo moo_fname
95 grafite_status.GrafiteTypes.moo_content_rev;
96 LibraryNoDb.save_metadata metadata_fname
97 lexicon_status.LexiconEngine.metadata;
98 LexiconMarshal.save_lexicon lexicon_fname
99 lexicon_status.LexiconEngine.lexicon_content_rev
103 MatitaGtkMisc.ask_confirmation
104 ~title:"A .moo can be generated"
105 ~message:(Printf.sprintf
106 "%s can be generated for %s.\n<i>Should I generate it?</i>"
107 (Filename.basename moo_fname) (Filename.basename fname))
114 | `CANCEL -> raise MatitaTypes.Cancel
119 clean_current_baseuri grafite_status
123 clean_current_baseuri grafite_status
125 let ask_unsaved parent =
126 MatitaGtkMisc.ask_confirmation
127 ~parent ~title:"Unsaved work!"
128 ~message:("Your work is <b>unsaved</b>!\n\n"^
129 "<i>Do you want to save the script before continuing?</i>")
132 class interpErrorModel =
133 let cols = new GTree.column_list in
134 let id_col = cols#add Gobject.Data.string in
135 let dsc_col = cols#add Gobject.Data.string in
136 let interp_no_col = cols#add Gobject.Data.caml in
137 let tree_store = GTree.tree_store cols in
138 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
139 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
140 let id_view_col = GTree.view_column ~renderer:id_renderer () in
141 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
142 fun (tree_view: GTree.view) choices ->
145 tree_view#set_model (Some (tree_store :> GTree.model));
146 ignore (tree_view#append_column id_view_col);
147 ignore (tree_view#append_column dsc_view_col);
149 let idx1 = ref ~-1 in
154 if List.length choices = 1 then
157 (let loc_row = tree_store#append () in
160 [passes,envs_and_diffs,_,_] ->
161 tree_store#set ~row:loc_row ~column:id_col
162 ("Error location " ^ string_of_int (!idx1+1) ^
163 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
165 String.concat " " (List.map string_of_int passes) ^
167 tree_store#set ~row:loc_row ~column:interp_no_col
170 tree_store#set ~row:loc_row ~column:id_col
171 ("Error location " ^ string_of_int (!idx1+1));
172 tree_store#set ~row:loc_row ~column:interp_no_col
176 let idx2 = ref ~-1 in
178 (fun passes,envs_and_diffs,_,_ ->
181 if List.length lll = 1 then
184 let msg_row = tree_store#append ?parent:loc_row () in
185 (tree_store#set ~row:msg_row ~column:id_col
186 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
187 string_of_int (!idx2+1) ^
189 String.concat " " (List.map string_of_int passes) ^
191 tree_store#set ~row:msg_row ~column:interp_no_col
192 (!idx1,Some !idx2,None);
194 let idx3 = ref ~-1 in
196 (fun (passes,env,_) ->
199 match envs_and_diffs with
201 let interp_row = tree_store#append ?parent:msg_row () in
202 tree_store#set ~row:interp_row ~column:id_col
203 ("Interpretation " ^ string_of_int (!idx3+1) ^
205 String.concat " " (List.map string_of_int passes) ^
207 tree_store#set ~row:interp_row ~column:interp_no_col
208 (!idx1,Some !idx2,Some !idx3);
215 let row = tree_store#append ?parent:interp_row () in
216 tree_store#set ~row ~column:id_col id;
217 tree_store#set ~row ~column:dsc_col dsc;
218 tree_store#set ~row ~column:interp_no_col
219 (!idx1,Some !idx2,Some !idx3)
223 if List.length lll > 1 then
225 (fun p -> tree_view#expand_row (tree_store#get_path p))
229 method get_interp_no tree_path =
230 let iter = tree_store#get_iter tree_path in
231 tree_store#get ~row:iter ~column:interp_no_col
235 let rec interactive_error_interp ?(all_passes=false) (source_buffer:GSourceView.source_buffer) notify_exn offset errorll
238 let remove_non_significant =
239 List.filter (fun (_env,_diff,_loc,_msg,significant) -> significant) in
240 if all_passes then errorll else
241 (* We remove passes 1,2 and 5,6 *)
243 ::(remove_non_significant (List.nth errorll 2))
244 ::(remove_non_significant (List.nth errorll 3))
253 (fun (env,diff,offset,msg,significant) ->
254 offset, [[!pass], [[!pass], env, diff], msg, significant]) l
256 (* Here we are doing a stable sort and list_uniq returns the latter
257 "equal" element. I.e. we are showing the error corresponding to the
258 most advanced disambiguation pass *)
260 let choices_compare (o1,_) (o2,_) = compare o1 o2 in
261 let choices_compare_by_passes (p1,_,_,_) (p2,_,_,_) =
267 | (o1,res1)::(o2,res2)::tl when o1 = o2 ->
268 let merge_by_name errors =
269 let merge_by_env errors =
270 let choices_compare_by_env (_,e1,_) (_,e2,_) = compare e1 e2 in
271 let choices_compare_by_passes (p1,_,_) (p2,_,_) =
273 let rec uniq_by_env =
277 | (p1,e1,_)::(p2,e2,d2)::tl when e1 = e2 ->
278 uniq_by_env ((p1@p2,e2,d2) :: tl)
279 | h1::tl -> h1 :: uniq_by_env tl
281 List.sort choices_compare_by_passes
282 (uniq_by_env (List.stable_sort choices_compare_by_env errors))
284 let choices_compare_by_msg (_,_,m1,_) (_,_,m2,_) =
285 compare (Lazy.force m1) (Lazy.force m2) in
286 let rec uniq_by_msg =
290 | (p1,i1,m1,s1)::(p2,i2,m2,s2)::tl
291 when Lazy.force m1 = Lazy.force m2 && s1 = s2 ->
292 uniq_by_msg ((p1@p2,merge_by_env (i1@i2),m2,s2) :: tl)
293 | h1::tl -> h1 :: uniq_by_msg tl
295 List.sort choices_compare_by_msg
296 (uniq_by_msg (List.stable_sort choices_compare_by_msg errors))
298 let res = merge_by_name (res1@res2) in
299 uniq ((o1,res) :: tl)
300 | h1::tl -> h1 :: uniq tl
302 List.map (fun o,l -> o,List.sort choices_compare_by_passes l)
303 (uniq (List.stable_sort choices_compare choices))
307 | [loffset,[_,envs_and_diffs,msg,significant]] ->
308 let _,env,diff = List.hd envs_and_diffs in
310 (GrafiteDisambiguator.DisambiguationError
311 (offset,[[env,diff,loffset,msg,significant]]));
313 let dialog = new disambiguationErrors () in
314 dialog#check_widgets ();
316 dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
317 let model = new interpErrorModel dialog#treeview choices in
318 dialog#disambiguationErrors#set_title "Disambiguation error";
319 dialog#disambiguationErrorsLabel#set_label
320 "Click on an error to see the corresponding message:";
321 ignore (dialog#treeview#connect#cursor_changed
324 match fst (dialog#treeview#get_cursor ()) with
327 let idx1,idx2,idx3 = model#get_interp_no tree_path in
328 let loffset,lll = List.nth choices idx1 in
329 let _,envs_and_diffs,msg,significant =
331 Some idx2 -> List.nth lll idx2
333 [],[],lazy "Multiple error messages. Please select one.",true
337 Some idx3 -> List.nth envs_and_diffs idx3
338 | None -> [],[],[] (* dymmy value, used *) in
339 let script = MatitaScript.current () in
340 let error_tag = script#error_tag in
341 source_buffer#remove_tag error_tag
342 ~start:source_buffer#start_iter
343 ~stop:source_buffer#end_iter;
345 (GrafiteDisambiguator.DisambiguationError
346 (offset,[[env,diff,loffset,msg,significant]]))
349 dialog#disambiguationErrors#destroy ();
352 let fail _ = return () in
353 ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
354 connect_button dialog#disambiguationErrorsOkButton
357 match fst (dialog#treeview#get_cursor ()) with
360 let idx1,idx2,idx3 = model#get_interp_no tree_path in
363 Some idx2, Some idx3 ->
364 let _,lll = List.nth choices idx1 in
365 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
366 let _,_,diff = List.nth envs_and_diffs idx3 in
368 | _,_ -> assert false
375 DisambiguatePp.pp_environment
376 (DisambiguateTypes.Environment.add k value
377 DisambiguateTypes.Environment.empty))
382 (source_buffer#get_iter_at_mark
383 (`NAME "beginning_of_statement")) newtxt ;
386 connect_button dialog#disambiguationErrorsMoreErrors
387 (fun _ -> return () ;
388 interactive_error_interp ~all_passes:true source_buffer notify_exn offset
390 connect_button dialog#disambiguationErrorsCancelButton fail;
391 dialog#disambiguationErrors#show ();
395 (** Selection handling
396 * Two clipboards are used: "clipboard" and "primary".
397 * "primary" is used by X, when you hit the middle button mouse is content is
398 * pasted between applications. In Matita this selection always contain the
399 * textual version of the selected term.
400 * "clipboard" is used inside Matita only and support ATM two different targets:
401 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
406 (* creation order _is_ relevant for windows placement *)
407 let main = new mainWin () in
408 let fileSel = new fileSelectionWin () in
409 let findRepl = new findReplWin () in
410 let develList = new develListWin () in
411 let newDevel = new newDevelWin () in
412 let keyBindingBoxes = (* event boxes which should receive global key events *)
413 [ main#mainWinEventBox ]
415 let console = new console ~buffer:main#logTextView#buffer () in
416 let (source_view: GSourceView.source_view) =
417 GSourceView.source_view
419 ~insert_spaces_instead_of_tabs:true ~tabs_width:2
420 ~margin:80 ~show_margin:true
422 ~packing:main#scriptScrolledWin#add
425 let default_font_size =
426 Helm_registry.get_opt_default Helm_registry.int
427 ~default:BuildTimeConf.default_font_size "matita.font_size"
429 let source_buffer = source_view#source_buffer in
431 val mutable chosen_file = None
432 val mutable _ok_not_exists = false
433 val mutable _only_directory = false
434 val mutable script_fname = None
435 val mutable font_size = default_font_size
436 val mutable next_devel_must_contain = None
437 val mutable next_ligatures = []
438 val clipboard = GData.clipboard Gdk.Atom.clipboard
439 val primary = GData.clipboard Gdk.Atom.primary
442 (* glade's check widgets *)
443 List.iter (fun w -> w#check_widgets ())
444 (let c w = (w :> <check_widgets: unit -> unit>) in
445 [ c fileSel; c main; c findRepl]);
447 List.iter (* global key bindings *)
448 (fun (key, callback) -> self#addKeyBinding key callback)
451 toggle_win ~check:main#showProofMenuItem proof#proofWin;
453 toggle_win ~check:main#showCheckMenuItem check#checkWin;
457 let parse_txt_file file =
458 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
459 let l_rev = ref [] in
462 l_rev := input_line ch :: !l_rev;
471 ~authors:(parse_txt_file "AUTHORS")
472 (*~comments:"comments"*)
473 ~copyright:"Copyright (C) 2005, the HELM team"
474 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
475 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
477 ~version:BuildTimeConf.version
478 ~website:"http://helm.cs.unibo.it"
481 connect_menu_item main#contentsMenuItem (fun () ->
483 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
485 ignore (Sys.command cmd));
486 connect_menu_item main#aboutMenuItem about_dialog#present;
488 let show_find_Repl () =
489 findRepl#toplevel#misc#show ();
490 findRepl#toplevel#misc#grab_focus ()
492 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
494 let highlight start end_ =
495 source_buffer#move_mark `INSERT ~where:start;
496 source_buffer#move_mark `SEL_BOUND ~where:end_;
497 source_view#scroll_mark_onscreen `INSERT
499 let text = findRepl#findEntry#text in
500 let iter = source_buffer#get_iter `SEL_BOUND in
501 match iter#forward_search text with
503 (match source_buffer#start_iter#forward_search text with
505 | Some (start,end_) -> highlight start end_)
506 | Some (start,end_) -> highlight start end_
509 let text = findRepl#replaceEntry#text in
510 let ins = source_buffer#get_iter `INSERT in
511 let sel = source_buffer#get_iter `SEL_BOUND in
512 if ins#compare sel < 0 then
514 ignore(source_buffer#delete_selection ());
515 source_buffer#insert text
518 connect_button findRepl#findButton find_forward;
519 connect_button findRepl#findReplButton replace;
520 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
521 ignore(findRepl#toplevel#event#connect#delete
522 ~callback:(fun _ -> hide_find_Repl ();true));
525 (* phase 1: we save the actual status of the marks and we undo *)
526 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
527 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
528 let locked_iter_offset = locked_iter#offset in
531 (source_view#buffer#create_mark ~name:"lock_point"
532 ~left_gravity:true locked_iter) in
533 source_view#source_buffer#undo ();
534 (* phase 2: we save the cursor position and we redo, restoring
535 the previous status of all the marks *)
536 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
539 (source_view#buffer#create_mark ~name:"undo_point"
540 ~left_gravity:true cursor_iter)
542 source_view#source_buffer#redo ();
543 let mark_iter = source_view#buffer#get_iter_at_mark mark in
544 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
545 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
546 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
547 source_view#buffer#delete_mark mark;
548 source_view#buffer#delete_mark mark2;
549 (* phase 3: if after the undo the cursor was in the locked area,
550 then we move it there again and we perform a goto *)
551 if mark_iter#offset < locked_iter_offset then
553 source_view#buffer#move_mark `INSERT ~where:mark_iter;
554 (MatitaScript.current ())#goto `Cursor ();
556 (* phase 4: we perform again the undo. This time we are sure that
557 the text to undo is not locked *)
558 source_view#source_buffer#undo ();
559 source_view#misc#grab_focus () in
562 (* phase 1: we save the actual status of the marks, we redo and
564 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
565 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
566 let locked_iter_offset = locked_iter#offset in
569 (source_view#buffer#create_mark ~name:"lock_point"
570 ~left_gravity:true locked_iter) in
571 source_view#source_buffer#redo ();
572 source_view#source_buffer#undo ();
573 (* phase 2: we save the cursor position and we restore
574 the previous status of all the marks *)
575 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
578 (source_view#buffer#create_mark ~name:"undo_point"
579 ~left_gravity:true cursor_iter)
581 let mark_iter = source_view#buffer#get_iter_at_mark mark in
582 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
583 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
584 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
585 source_view#buffer#delete_mark mark;
586 source_view#buffer#delete_mark mark2;
587 (* phase 3: if after the undo the cursor is in the locked area,
588 then we move it there again and we perform a goto *)
589 if mark_iter#offset < locked_iter_offset then
591 source_view#buffer#move_mark `INSERT ~where:mark_iter;
592 (MatitaScript.current ())#goto `Cursor ();
594 (* phase 4: we perform again the redo. This time we are sure that
595 the text to redo is not locked *)
596 source_view#source_buffer#redo ();
597 source_view#misc#grab_focus ()
599 connect_menu_item main#undoMenuItem safe_undo;
600 ignore(source_view#source_buffer#connect#can_undo
601 ~callback:main#undoMenuItem#misc#set_sensitive);
602 connect_menu_item main#redoMenuItem safe_redo;
603 ignore(source_view#source_buffer#connect#can_redo
604 ~callback:main#redoMenuItem#misc#set_sensitive);
605 ignore(source_view#connect#after#populate_popup
606 ~callback:(fun pre_menu ->
607 let menu = new GMenu.menu pre_menu in
608 let menuItems = menu#children in
609 let undoMenuItem, redoMenuItem =
611 [undo;redo;sep1;cut;copy;paste;delete;sep2;
612 selectall;sep3;inputmethod;insertunicodecharacter] ->
613 List.iter menu#remove [ copy; cut; delete; paste ];
615 | _ -> assert false in
617 let i = ref 2 in (* last occupied position *)
618 fun ?label ?stock () ->
620 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
623 let copy = add_menu_item ~stock:`COPY () in
624 let cut = add_menu_item ~stock:`CUT () in
625 let delete = add_menu_item ~stock:`DELETE () in
626 let paste = add_menu_item ~stock:`PASTE () in
627 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
628 copy#misc#set_sensitive self#canCopy;
629 cut#misc#set_sensitive self#canCut;
630 delete#misc#set_sensitive self#canDelete;
631 paste#misc#set_sensitive self#canPaste;
632 paste_pattern#misc#set_sensitive self#canPastePattern;
633 connect_menu_item copy self#copy;
634 connect_menu_item cut self#cut;
635 connect_menu_item delete self#delete;
636 connect_menu_item paste self#paste;
637 connect_menu_item paste_pattern self#pastePattern;
638 let new_undoMenuItem =
639 GMenu.image_menu_item
640 ~image:(GMisc.image ~stock:`UNDO ())
643 ~packing:(menu#insert ~pos:0) () in
644 new_undoMenuItem#misc#set_sensitive
645 (undoMenuItem#misc#get_flag `SENSITIVE);
646 menu#remove (undoMenuItem :> GMenu.menu_item);
647 connect_menu_item new_undoMenuItem safe_undo;
648 let new_redoMenuItem =
649 GMenu.image_menu_item
650 ~image:(GMisc.image ~stock:`REDO ())
653 ~packing:(menu#insert ~pos:1) () in
654 new_redoMenuItem#misc#set_sensitive
655 (redoMenuItem#misc#get_flag `SENSITIVE);
656 menu#remove (redoMenuItem :> GMenu.menu_item);
657 connect_menu_item new_redoMenuItem safe_redo));
659 connect_menu_item main#editMenu (fun () ->
660 main#copyMenuItem#misc#set_sensitive self#canCopy;
661 main#cutMenuItem#misc#set_sensitive self#canCut;
662 main#deleteMenuItem#misc#set_sensitive self#canDelete;
663 main#pasteMenuItem#misc#set_sensitive self#canPaste;
664 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
665 connect_menu_item main#copyMenuItem self#copy;
666 connect_menu_item main#cutMenuItem self#cut;
667 connect_menu_item main#deleteMenuItem self#delete;
668 connect_menu_item main#pasteMenuItem self#paste;
669 connect_menu_item main#pastePatternMenuItem self#pastePattern;
670 connect_menu_item main#selectAllMenuItem (fun () ->
671 source_buffer#move_mark `INSERT source_buffer#start_iter;
672 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
673 connect_menu_item main#findReplMenuItem show_find_Repl;
674 connect_menu_item main#externalEditorMenuItem self#externalEditor;
675 connect_menu_item main#ligatureButton self#nextLigature;
676 ignore (findRepl#findEntry#connect#activate find_forward);
677 (* interface lockers *)
679 main#buttonsToolbar#misc#set_sensitive false;
680 develList#buttonsHbox#misc#set_sensitive false;
681 main#scriptMenu#misc#set_sensitive false;
682 source_view#set_editable false
685 main#buttonsToolbar#misc#set_sensitive true;
686 develList#buttonsHbox#misc#set_sensitive true;
687 main#scriptMenu#misc#set_sensitive true;
688 source_view#set_editable true;
689 (*The next line seems sufficient to avoid some unknown race condition *)
690 GtkThread.sync (fun () -> ()) ()
692 let worker_thread = ref None in
694 let floc, msg = MatitaExcPp.to_string exn in
699 let (x, y) = HExtlib.loc_of_floc floc in
700 let script = MatitaScript.current () in
701 let locked_mark = script#locked_mark in
702 let error_tag = script#error_tag in
704 (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
705 let x' = baseoffset + x in
706 let y' = baseoffset + y in
707 let x_iter = source_buffer#get_iter (`OFFSET x') in
708 let y_iter = source_buffer#get_iter (`OFFSET y') in
709 source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
711 id := Some (source_buffer#connect#changed ~callback:(fun () ->
712 source_buffer#remove_tag error_tag
713 ~start:source_buffer#start_iter
714 ~stop:source_buffer#end_iter;
716 | None -> assert false (* a race condition occurred *)
718 (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
719 source_buffer#place_cursor
720 (source_buffer#get_iter (`OFFSET x'));
731 | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
732 interactive_error_interp source_buffer notify_exn offset errorll ;
738 worker_thread := Some (Thread.create thread_main ()) in
740 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
741 let interrupt = ref None in
742 let old_callback = ref (function _ -> ()) in
743 let force_interrupt n =
744 (* This function is called just before the thread's timeslice ends *)
746 if Some(Thread.id(Thread.self())) = !interrupt then
747 (interrupt := None; raise Sys.Break) in
749 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
750 Sys.Signal_handle f -> old_callback := f
752 | Sys.Signal_default -> assert false
755 match !worker_thread with
757 | Some t -> interrupt := Some (Thread.id t) in
761 f (); source_view#misc#grab_focus ()
763 exc -> source_view#misc#grab_focus (); raise exc in
764 (* developments win *)
766 new MatitaGtkMisc.multiStringListModel
767 ~cols:2 develList#developmentsTreeview
769 let refresh_devels_win () =
770 model#list_store#clear ();
772 (fun (name, root) -> model#easy_mappend [name;root])
773 (MatitamakeLib.list_known_developments ())
775 let get_devel_selected () =
776 match model#easy_mselection () with
777 | [[name;_]] -> MatitamakeLib.development_for_name name
781 while Glib.Main.pending () do
782 ignore(Glib.Main.iteration false);
785 connect_button develList#newButton
787 next_devel_must_contain <- None;
788 newDevel#toplevel#misc#show());
789 connect_button develList#deleteButton
791 (match get_devel_selected () with
793 | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
794 refresh_devels_win ()));
795 connect_button develList#buildButton
797 match get_devel_selected () with
801 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
804 connect_button develList#cleanButton
806 match get_devel_selected () with
810 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
813 connect_button develList#publishButton
815 match get_devel_selected () with
818 let publish = locker (fun () ->
819 MatitamakeLib.publish_development_in_bg refresh d) in
820 ignore(publish ())));
821 connect_button develList#graphButton (fun () ->
822 match get_devel_selected () with
825 (match MatitamakeLib.dot_for_development d with
828 let browser = MatitaMathView.cicBrowser () in
829 browser#load (`Development
830 (MatitamakeLib.name_for_development d))));
831 connect_button develList#closeButton
832 (fun () -> develList#toplevel#misc#hide());
833 ignore(develList#toplevel#event#connect#delete
834 (fun _ -> develList#toplevel#misc#hide();true));
835 connect_menu_item main#developmentsMenuItem
836 (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
838 (* add development win *)
839 let check_if_root_contains root =
840 match next_devel_must_contain with
843 let is_prefix_of d1 d2 =
844 let len1 = String.length d1 in
845 let len2 = String.length d2 in
849 let pref = String.sub d2 0 len1 in
852 is_prefix_of root path
854 connect_button newDevel#addButton
856 let name = newDevel#nameEntry#text in
857 let root = newDevel#rootEntry#text in
858 if check_if_root_contains root then
860 ignore (MatitamakeLib.initialize_development name root);
861 refresh_devels_win ();
862 newDevel#nameEntry#set_text "";
863 newDevel#rootEntry#set_text "";
864 newDevel#toplevel#misc#hide()
867 HLog.error ("The selected root does not contain " ^
868 match next_devel_must_contain with
870 | _ -> assert false));
871 connect_button newDevel#chooseRootButton
873 let path = self#chooseDir () in
875 | Some path -> newDevel#rootEntry#set_text path
877 connect_button newDevel#cancelButton
878 (fun () -> newDevel#toplevel#misc#hide ());
879 ignore(newDevel#toplevel#event#connect#delete
880 (fun _ -> newDevel#toplevel#misc#hide();true));
882 (* file selection win *)
883 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
884 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
887 fileSel#fileSelectionWin#misc#hide ();
892 let fname = fileSel#fileSelectionWin#filename in
893 if Sys.file_exists fname then
895 if HExtlib.is_regular fname && not (_only_directory) then
897 else if _only_directory && HExtlib.is_dir fname then
902 if _ok_not_exists then
905 | `CANCEL -> return None
907 | `DELETE_EVENT -> return None));
909 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
911 let adj = main#logScrolledWin#vadjustment in
912 ignore (adj#connect#changed
913 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
914 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
916 let module A = GrafiteAst in
917 let hole = CicNotationPt.UserInput in
918 let loc = HExtlib.dummy_floc in
920 if (MatitaScript.current ())#onGoingProof () then
921 (MatitaScript.current ())#advance
923 ^ GrafiteAstPp.pp_tactical ~term_pp:CicNotationPp.pp_term
924 ~lazy_term_pp:CicNotationPp.pp_term (A.Tactic (loc, ast)))
927 let tac_w_term ast _ =
928 if (MatitaScript.current ())#onGoingProof () then
929 let buf = source_buffer in
930 buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
932 ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
933 ~lazy_term_pp:CicNotationPp.pp_term ast)
936 connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
937 connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
938 connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
939 connect_button tbar#elimButton (tac_w_term
940 (A.Elim (loc, hole, None, None, [])));
941 connect_button tbar#elimTypeButton (tac_w_term
942 (A.ElimType (loc, hole, None, None, [])));
943 connect_button tbar#splitButton (tac (A.Split loc));
944 connect_button tbar#leftButton (tac (A.Left loc));
945 connect_button tbar#rightButton (tac (A.Right loc));
946 connect_button tbar#existsButton (tac (A.Exists loc));
947 connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
948 connect_button tbar#symmetryButton (tac (A.Symmetry loc));
949 connect_button tbar#transitivityButton
950 (tac_w_term (A.Transitivity (loc, hole)));
951 connect_button tbar#assumptionButton (tac (A.Assumption loc));
952 connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
953 connect_button tbar#autoButton (tac (A.Auto (loc,[])));
954 MatitaGtkMisc.toggle_widget_visibility
955 ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
956 ~check:main#tacticsBarMenuItem;
957 let module Hr = Helm_registry in
959 not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
961 main#tacticsBarMenuItem#set_active false;
962 MatitaGtkMisc.toggle_callback
964 | true -> main#toplevel#fullscreen ()
965 | false -> main#toplevel#unfullscreen ())
966 ~check:main#fullscreenMenuItem;
967 main#fullscreenMenuItem#set_active false;
969 HLog.set_log_callback self#console#log_callback;
970 GtkSignal.user_handler :=
972 | MatitaScript.ActionCancelled s -> HLog.error s
974 if not (Helm_registry.get_bool "matita.debug") then
978 ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
980 match GSourceView.source_language_from_file BuildTimeConf.lang_file with
982 HLog.warn (sprintf "can't load language file %s"
983 BuildTimeConf.lang_file)
984 | Some matita_lang ->
985 source_buffer#set_language matita_lang;
986 source_buffer#set_highlight true
988 let s () = MatitaScript.current () in
990 script_fname <- None;
991 main#saveMenuItem#misc#set_sensitive false
993 let saveAsScript () =
995 match self#chooseFile ~ok_not_exists:true () with
997 script#assignFileName f;
998 script#saveToFile ();
999 console#message ("'"^f^"' saved.\n");
1000 self#_enableSaveTo f
1004 match script_fname with
1005 | None -> saveAsScript ()
1007 (s ())#assignFileName f;
1008 (s ())#saveToFile ();
1009 console#message ("'"^f^"' saved.\n");
1011 let abandon_script () =
1012 let lexicon_status = (s ())#lexicon_status in
1013 let grafite_status = (s ())#grafite_status in
1014 if source_view#buffer#modified then
1015 (match ask_unsaved main#toplevel with
1016 | `YES -> saveScript ()
1018 | `CANCEL -> raise MatitaTypes.Cancel);
1019 (match script_fname with
1022 ask_and_save_moo_if_needed main#toplevel fname
1023 lexicon_status grafite_status);
1026 let script = s () in
1028 match self#chooseFile () with
1032 script#assignFileName f;
1033 source_view#source_buffer#begin_not_undoable_action ();
1034 script#loadFromFile f;
1035 source_view#source_buffer#end_not_undoable_action ();
1036 console#message ("'"^f^"' loaded.\n");
1037 self#_enableSaveTo f
1039 with MatitaTypes.Cancel -> ()
1043 source_view#source_buffer#begin_not_undoable_action ();
1046 source_view#source_buffer#end_not_undoable_action ();
1048 script_fname <- None
1051 source_buffer#place_cursor
1052 (source_buffer#get_iter_at_mark (`NAME "locked")) in
1053 let advance _ = (MatitaScript.current ())#advance (); cursor () in
1054 let retract _ = (MatitaScript.current ())#retract (); cursor () in
1055 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
1056 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
1057 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
1058 let advance = locker (keep_focus advance) in
1059 let retract = locker (keep_focus retract) in
1060 let top = locker (keep_focus top) in
1061 let bottom = locker (keep_focus bottom) in
1062 let jump = locker (keep_focus jump) in
1064 self#setQuitCallback (fun () ->
1065 let lexicon_status = (MatitaScript.current ())#lexicon_status in
1066 let grafite_status = (MatitaScript.current ())#grafite_status in
1067 if source_view#buffer#modified then
1069 let rc = ask_unsaved main#toplevel in
1072 | `YES -> saveScript ();
1073 if not source_view#buffer#modified then
1075 (match script_fname with
1078 ask_and_save_moo_if_needed main#toplevel
1079 fname lexicon_status grafite_status);
1082 | `NO -> GMain.Main.quit ()
1083 | `CANCEL -> raise MatitaTypes.Cancel
1084 with MatitaTypes.Cancel -> ()
1088 (match script_fname with
1089 | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
1092 ask_and_save_moo_if_needed main#toplevel fname lexicon_status
1095 with MatitaTypes.Cancel -> ())
1097 connect_button main#scriptAdvanceButton advance;
1098 connect_button main#scriptRetractButton retract;
1099 connect_button main#scriptTopButton top;
1100 connect_button main#scriptBottomButton bottom;
1101 connect_button main#scriptJumpButton jump;
1102 connect_button main#scriptAbortButton kill_worker;
1103 connect_menu_item main#scriptAdvanceMenuItem advance;
1104 connect_menu_item main#scriptRetractMenuItem retract;
1105 connect_menu_item main#scriptTopMenuItem top;
1106 connect_menu_item main#scriptBottomMenuItem bottom;
1107 connect_menu_item main#scriptJumpMenuItem jump;
1108 connect_menu_item main#openMenuItem loadScript;
1109 connect_menu_item main#saveMenuItem saveScript;
1110 connect_menu_item main#saveAsMenuItem saveAsScript;
1111 connect_menu_item main#newMenuItem newScript;
1112 (* script monospace font stuff *)
1113 self#updateFontSize ();
1115 main#debugMenu#misc#hide ();
1117 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1118 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1119 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1121 self#sourceView#misc#grab_focus ();
1122 (* main win dimension *)
1123 let width = Gdk.Screen.width () in
1124 let height = Gdk.Screen.height () in
1125 let main_w = width * 90 / 100 in
1126 let main_h = height * 80 / 100 in
1127 let script_w = main_w * 6 / 10 in
1128 main#toplevel#resize ~width:main_w ~height:main_h;
1129 main#hpaneScriptSequent#set_position script_w;
1131 ignore(source_view#connect#after#paste_clipboard
1132 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1133 (* clean_locked is set to true only "during" a PRIMARY paste
1134 operation (i.e. by clicking with the second mouse button) *)
1135 let clean_locked = ref false in
1136 ignore(source_view#event#connect#button_press
1139 if GdkEvent.Button.button button = 2 then
1140 clean_locked := true;
1143 ignore(source_view#event#connect#button_release
1144 ~callback:(fun button -> clean_locked := false; false));
1145 ignore(source_view#buffer#connect#after#apply_tag
1147 fun tag ~start:_ ~stop:_ ->
1149 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1152 clean_locked := false;
1153 (MatitaScript.current ())#clean_dirty_lock;
1154 clean_locked := true
1156 (* math view handling *)
1157 connect_menu_item main#newCicBrowserMenuItem (fun () ->
1158 ignore (MatitaMathView.cicBrowser ()));
1159 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1160 self#increaseFontSize ();
1161 MatitaMathView.increase_font_size ();
1162 MatitaMathView.update_font_sizes ());
1163 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1164 self#decreaseFontSize ();
1165 MatitaMathView.decrease_font_size ();
1166 MatitaMathView.update_font_sizes ());
1167 connect_menu_item main#normalFontSizeMenuItem (fun () ->
1168 self#resetFontSize ();
1169 MatitaMathView.reset_font_size ();
1170 MatitaMathView.update_font_sizes ());
1171 MatitaMathView.reset_font_size ();
1173 (** selections / clipboards handling *)
1175 method markupSelected = MatitaMathView.has_selection ()
1176 method private textSelected =
1177 (source_buffer#get_iter_at_mark `INSERT)#compare
1178 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1179 method private somethingSelected = self#markupSelected || self#textSelected
1180 method private markupStored = MatitaMathView.has_clipboard ()
1181 method private textStored = clipboard#text <> None
1182 method private somethingStored = self#markupStored || self#textStored
1184 method canCopy = self#somethingSelected
1185 method canCut = self#textSelected
1186 method canDelete = self#textSelected
1187 method canPaste = self#somethingStored
1188 method canPastePattern = self#markupStored
1191 if self#textSelected
1193 MatitaMathView.empty_clipboard ();
1194 source_view#buffer#copy_clipboard clipboard;
1196 MatitaMathView.copy_selection ()
1198 source_view#buffer#cut_clipboard clipboard;
1199 MatitaMathView.empty_clipboard ()
1200 method delete () = ignore (source_view#buffer#delete_selection ())
1202 if MatitaMathView.has_clipboard ()
1203 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1204 else source_view#buffer#paste_clipboard clipboard;
1205 (MatitaScript.current ())#clean_dirty_lock
1206 method pastePattern () =
1207 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1209 method private nextLigature () =
1210 let iter = source_buffer#get_iter_at_mark `INSERT in
1211 let write_ligature len s =
1212 assert(Glib.Utf8.validate s);
1213 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
1214 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
1216 let get_ligature word =
1217 let len = String.length word in
1220 for i = len - 1 downto 0 do
1221 if HExtlib.is_alpha word.[i] then ()
1223 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
1227 if i = ~-1 then None else Some (String.sub word i (len - i))
1229 let aux_ligature () =
1231 for i = len - 1 downto 0 do
1232 if CicNotationLexer.is_ligature_char word.[i] then ()
1233 else raise (Found (i+1))
1239 Some (String.sub word i (len - i))
1240 with Invalid_argument _ -> None)
1242 match aux_tex () with
1243 | Some macro -> macro
1244 | None -> (match aux_ligature () with Some l -> l | None -> word)
1246 (match next_ligatures with
1247 | [] -> (* find ligatures and fill next_ligatures, then try again *)
1250 ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
1252 let ligature = get_ligature last_word in
1253 (match CicNotationLexer.lookup_ligatures ligature with
1256 write_ligature (MatitaGtkMisc.utf8_string_length ligature) hd;
1257 next_ligatures <- tl @ [ hd ])
1259 write_ligature 1 hd;
1260 next_ligatures <- tl @ [ hd ])
1262 method private externalEditor () =
1263 let cmd = Helm_registry.get "matita.external_editor" in
1264 (* ZACK uncomment to enable interactive ask of external editor command *)
1267 "External editor command:
1268 %f will be substitute for the script name,
1269 %p for the cursor position in bytes,
1270 %l for the execution point in bytes."
1272 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1273 ~default:(Helm_registry.get "matita.external_editor") ()
1275 let fname = (MatitaScript.current ())#filename in
1277 source_buffer#start_iter#get_slice
1278 ~stop:(source_buffer#get_iter_at_mark mark)
1280 let script = MatitaScript.current () in
1281 let locked = `MARK script#locked_mark in
1282 let string_pos mark = string_of_int (String.length (slice mark)) in
1283 let cursor_pos = string_pos `INSERT in
1284 let locked_pos = string_pos locked in
1286 Pcre.replace ~pat:"%f" ~templ:fname
1287 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1288 (Pcre.replace ~pat:"%l" ~templ:locked_pos
1291 let locked_before = slice locked in
1292 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1293 ignore (Unix.system cmd);
1294 source_buffer#set_text (HExtlib.input_file fname);
1295 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1296 source_buffer#move_mark locked locked_iter;
1297 source_buffer#apply_tag script#locked_tag
1298 ~start:source_buffer#start_iter ~stop:locked_iter;
1299 let locked_after = slice locked in
1303 for i = 0 to String.length locked_before - 1 do
1304 if locked_before.[i] <> locked_after.[i] then begin
1305 source_buffer#place_cursor
1306 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1307 script#goto `Cursor ();
1309 end else if locked_before.[i] = '\n' then begin
1316 | Invalid_argument _ -> script#goto `Bottom ()
1318 method loadScript file =
1319 let script = MatitaScript.current () in
1321 if Pcre.pmatch ~pat:"\\.p$" file then
1324 Helm_registry.get_opt_default Helm_registry.string ~default:"./"
1327 let data = Matitaprover.p_to_ma ~filename:file ~tptppath () in
1328 let filename = Pcre.replace ~pat:"\\.p$" ~templ:".ma" file in
1329 script#assignFileName filename;
1330 source_view#source_buffer#begin_not_undoable_action ();
1331 script#loadFromString data;
1332 source_view#source_buffer#end_not_undoable_action ();
1333 console#message ("'"^filename^"' loaded.");
1334 self#_enableSaveTo filename
1338 script#assignFileName file;
1340 if Sys.file_exists file then file
1341 else BuildTimeConf.script_template
1343 source_view#source_buffer#begin_not_undoable_action ();
1344 script#loadFromFile content;
1345 source_view#source_buffer#end_not_undoable_action ();
1346 console#message ("'"^file^"' loaded.");
1347 self#_enableSaveTo file
1350 method setStar name b =
1351 let l = main#scriptLabel in
1353 l#set_text (name ^ " *")
1357 method private _enableSaveTo file =
1358 script_fname <- Some file;
1359 self#main#saveMenuItem#misc#set_sensitive true
1361 method console = console
1362 method sourceView: GSourceView.source_view =
1363 (source_view: GSourceView.source_view)
1364 method fileSel = fileSel
1365 method findRepl = findRepl
1367 method develList = develList
1368 method newDevel = newDevel
1370 method newBrowserWin () =
1372 inherit browserWin ()
1373 val combo = GEdit.combo_box_entry ()
1375 self#check_widgets ();
1376 let combo_widget = combo#coerce in
1377 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1378 combo#entry#misc#grab_focus ()
1379 method browserUri = combo
1382 method newUriDialog () =
1383 let dialog = new uriChoiceDialog () in
1384 dialog#check_widgets ();
1387 method newConfirmationDialog () =
1388 let dialog = new confirmationDialog () in
1389 dialog#check_widgets ();
1392 method newEmptyDialog () =
1393 let dialog = new emptyDialog () in
1394 dialog#check_widgets ();
1397 method private addKeyBinding key callback =
1398 List.iter (fun evbox -> add_key_binding key callback evbox)
1401 method setQuitCallback callback =
1402 connect_menu_item main#quitMenuItem callback;
1403 ignore (main#toplevel#event#connect#delete
1404 (fun _ -> callback ();true));
1405 self#addKeyBinding GdkKeysyms._q callback
1407 method chooseFile ?(ok_not_exists = false) () =
1408 _ok_not_exists <- ok_not_exists;
1409 _only_directory <- false;
1410 fileSel#fileSelectionWin#show ();
1414 method private chooseDir ?(ok_not_exists = false) () =
1415 _ok_not_exists <- ok_not_exists;
1416 _only_directory <- true;
1417 fileSel#fileSelectionWin#show ();
1419 (* we should check that this is a directory *)
1422 method createDevelopment ~containing =
1423 next_devel_must_contain <- containing;
1424 newDevel#toplevel#misc#show()
1426 method askText ?(title = "") ?(msg = "") () =
1427 let dialog = new textDialog () in
1428 dialog#textDialog#set_title title;
1429 dialog#textDialogLabel#set_label msg;
1430 let text = ref None in
1433 dialog#textDialog#destroy ();
1436 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1437 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1438 connect_button dialog#textDialogOkButton (fun _ ->
1439 let text = dialog#textDialogTextView#buffer#get_text () in
1440 return (Some text));
1441 dialog#textDialog#show ();
1445 method private updateFontSize () =
1446 self#sourceView#misc#modify_font_by_name
1447 (sprintf "%s %d" BuildTimeConf.script_font font_size)
1449 method increaseFontSize () =
1450 font_size <- font_size + 1;
1451 self#updateFontSize ()
1453 method decreaseFontSize () =
1454 font_size <- font_size - 1;
1455 self#updateFontSize ()
1457 method resetFontSize () =
1458 font_size <- default_font_size;
1459 self#updateFontSize ()
1464 let g = new gui () in
1465 gui_instance := Some g;
1466 MatitaMathView.set_gui g;
1469 let instance = singleton gui
1471 let non p x = not (p x)
1473 (* this is a shit and should be changed :-{ *)
1474 let interactive_uri_choice
1475 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1476 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1477 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1481 let gui = instance () in
1482 let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1483 if (selection_mode <> `SINGLE) &&
1484 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1486 Lazy.force nonvars_uris
1488 let dialog = gui#newUriDialog () in
1489 if hide_uri_entry then
1490 dialog#uriEntryHBox#misc#hide ();
1493 dialog#uriChoiceSelectedButton#misc#hide ();
1494 dialog#uriChoiceConstantsButton#misc#hide ();
1496 dialog#okLabel#set_label ok_label;
1497 dialog#uriChoiceTreeView#selection#set_mode
1498 (selection_mode :> Gtk.Tags.selection_mode);
1499 let model = new stringListModel dialog#uriChoiceTreeView in
1500 let choices = ref None in
1504 dialog#copyButton#misc#show ();
1505 connect_button dialog#copyButton
1507 match model#easy_selection () with
1510 dialog#uriChoiceDialog#set_title title;
1511 dialog#uriChoiceLabel#set_text msg;
1512 List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1513 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1516 dialog#uriChoiceDialog#destroy ();
1519 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1520 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1521 return (Some (Lazy.force nonvars_uris)));
1522 if ok_action = `AUTO then
1523 connect_button dialog#uriChoiceAutoButton (fun _ ->
1524 Helm_registry.set_bool "matita.auto_disambiguation" true;
1525 return (Some (Lazy.force nonvars_uris)))
1527 connect_button dialog#uriChoiceAutoButton (fun _ ->
1528 match model#easy_selection () with
1530 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1531 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1532 match model#easy_selection () with
1534 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1535 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1536 dialog#uriChoiceDialog#show ();
1538 (match !choices with
1539 | None -> raise MatitaTypes.Cancel
1540 | Some uris -> uris)
1544 let cols = new GTree.column_list in
1545 let id_col = cols#add Gobject.Data.string in
1546 let dsc_col = cols#add Gobject.Data.string in
1547 let interp_no_col = cols#add Gobject.Data.int in
1548 let tree_store = GTree.tree_store cols in
1549 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1550 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1551 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1552 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1553 fun tree_view choices ->
1556 tree_view#set_model (Some (tree_store :> GTree.model));
1557 ignore (tree_view#append_column id_view_col);
1558 ignore (tree_view#append_column dsc_view_col);
1559 let name_of_interp =
1560 (* try to find a reasonable name for an interpretation *)
1564 List.assoc "0" interp
1566 incr idx; string_of_int !idx
1568 tree_store#clear ();
1569 let idx = ref ~-1 in
1573 let interp_row = tree_store#append () in
1574 tree_store#set ~row:interp_row ~column:id_col
1575 (name_of_interp interp);
1576 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1579 let row = tree_store#append ~parent:interp_row () in
1580 tree_store#set ~row ~column:id_col id;
1581 tree_store#set ~row ~column:dsc_col dsc;
1582 tree_store#set ~row ~column:interp_no_col !idx)
1586 method get_interp_no tree_path =
1587 let iter = tree_store#get_iter tree_path in
1588 tree_store#get ~row:iter ~column:interp_no_col
1591 let interactive_string_choice
1592 text prefix_len ?(title = "") ?(msg = "") () ~id locs uris
1594 let gui = instance () in
1595 let dialog = gui#newUriDialog () in
1596 dialog#uriEntryHBox#misc#hide ();
1597 dialog#uriChoiceSelectedButton#misc#hide ();
1598 dialog#uriChoiceAutoButton#misc#hide ();
1599 dialog#uriChoiceConstantsButton#misc#hide ();
1600 dialog#uriChoiceTreeView#selection#set_mode
1601 (`SINGLE :> Gtk.Tags.selection_mode);
1602 let model = new stringListModel dialog#uriChoiceTreeView in
1603 let choices = ref None in
1604 dialog#uriChoiceDialog#set_title title;
1605 let hack_len = MatitaGtkMisc.utf8_string_length text in
1606 let rec colorize acc_len = function
1608 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1609 fst(MatitaGtkMisc.utf8_parsed_text text floc)
1611 let start, stop = HExtlib.loc_of_floc he in
1612 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1613 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1614 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1615 str1 ^ "<b>" ^ str2 ^ "</b>" ^ colorize stop tl
1617 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1618 Printf.eprintf "(%d,%d)" start stop) locs; *)
1622 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1625 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1626 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1627 Printf.eprintf "(%d,%d)" start stop) locs;
1628 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1629 dialog#uriChoiceLabel#set_use_markup true;
1630 let txt = colorize 0 locs in
1631 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1632 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1634 dialog#uriChoiceLabel#set_label txt;
1635 List.iter model#easy_append uris;
1638 dialog#uriChoiceDialog#destroy ();
1641 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1642 connect_button dialog#uriChoiceForwardButton (fun _ ->
1643 match model#easy_selection () with
1645 | uris -> return (Some uris));
1646 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1647 dialog#uriChoiceDialog#show ();
1649 (match !choices with
1650 | None -> raise MatitaTypes.Cancel
1651 | Some uris -> uris)
1653 let interactive_interp_choice () text prefix_len choices =
1654 (* List.iter (fun (l,_,_) ->
1655 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1656 Printf.eprintf "(%d,%d)" start stop) l; prerr_endline "")
1657 ((List.hd choices)); *)
1658 let filter_choices filter =
1659 let rec is_compatible filter =
1664 if List.assoc id filter = dsc then
1665 is_compatible filter tl
1671 List.filter (fun (_,interp) -> is_compatible filter interp)
1673 let rec get_choices id =
1677 let _,_,dsc = List.find (fun (_,id',_) -> id = id') he in
1678 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices id tl))
1680 let example_interp =
1684 let ask_user id locs choices =
1685 interactive_string_choice
1687 ~title:"Ambiguous input"
1688 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1690 let rec classify ids filter partial_interpretations =
1692 [] -> List.map fst partial_interpretations
1693 | (locs,id,_)::tl ->
1694 let choices = get_choices id partial_interpretations in
1699 match ask_user id locs choices with
1703 let filter = (id,chosen_dsc)::filter in
1704 let compatible_interps = filter_choices filter partial_interpretations in
1705 classify tl filter compatible_interps in
1706 let enumerated_choices =
1707 let idx = ref ~-1 in
1708 List.map (fun interp -> incr idx; !idx,interp) choices
1710 classify example_interp [] enumerated_choices
1713 (* disambiguator callbacks *)
1714 GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1715 GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1716 (* gtk initialization *)
1717 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1718 GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1719 ignore (GMain.Main.init ())