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 all_disambiguation_passes = ref false
38 let gui_instance = ref None
40 class type browserWin =
41 (* this class exists only because GEdit.combo_box_entry is not supported by
42 * lablgladecc :-(((( *)
44 inherit MatitaGeneratedGui.browserWin
45 method browserUri: GEdit.entry
48 class console ~(buffer: GText.buffer) () =
50 val error_tag = buffer#create_tag [ `FOREGROUND "red" ]
51 val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
52 val message_tag = buffer#create_tag []
53 val debug_tag = buffer#create_tag [ `FOREGROUND "#888888" ]
54 method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
55 method error s = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
56 method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
57 method debug s = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
59 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
60 method log_callback (tag: HLog.log_tag) s =
61 let s = Pcre.replace ~pat:"
\e\\[0;3.m([^
\e]+)
\e\\[0m" ~templ:"$1" s in
63 | `Debug -> self#debug (s ^ "\n")
64 | `Error -> self#error (s ^ "\n")
65 | `Message -> self#message (s ^ "\n")
66 | `Warning -> self#warning (s ^ "\n")
69 let clean_current_baseuri grafite_status =
70 LibraryClean.clean_baseuris [grafite_status#baseuri]
72 let save_moo grafite_status =
73 let script = MatitaScript.current () in
74 let baseuri = grafite_status#baseuri in
75 match script#bos, script#eos with
78 GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
79 ~dependencies:grafite_status#dependencies grafite_status#dump
80 | _ -> clean_current_baseuri grafite_status
83 let ask_unsaved parent =
84 MatitaGtkMisc.ask_confirmation
85 ~parent ~title:"Unsaved work!"
86 ~message:("Your work is <b>unsaved</b>!\n\n"^
87 "<i>Do you want to save the script before continuing?</i>")
90 class interpErrorModel =
91 let cols = new GTree.column_list in
92 let id_col = cols#add Gobject.Data.string in
93 let dsc_col = cols#add Gobject.Data.string in
94 let interp_no_col = cols#add Gobject.Data.caml in
95 let tree_store = GTree.tree_store cols in
96 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
97 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
98 let id_view_col = GTree.view_column ~renderer:id_renderer () in
99 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
100 fun (tree_view: GTree.view) choices ->
103 tree_view#set_model (Some (tree_store :> GTree.model));
104 ignore (tree_view#append_column id_view_col);
105 ignore (tree_view#append_column dsc_view_col);
107 let idx1 = ref ~-1 in
112 if List.length choices = 1 then
115 (let loc_row = tree_store#append () in
118 [passes,envs_and_diffs,_,_] ->
119 tree_store#set ~row:loc_row ~column:id_col
120 ("Error location " ^ string_of_int (!idx1+1) ^
121 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
123 String.concat " " (List.map string_of_int passes) ^
125 tree_store#set ~row:loc_row ~column:interp_no_col
128 tree_store#set ~row:loc_row ~column:id_col
129 ("Error location " ^ string_of_int (!idx1+1));
130 tree_store#set ~row:loc_row ~column:interp_no_col
134 let idx2 = ref ~-1 in
136 (fun passes,envs_and_diffs,_,_ ->
139 if List.length lll = 1 then
142 let msg_row = tree_store#append ?parent:loc_row () in
143 (tree_store#set ~row:msg_row ~column:id_col
144 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
145 string_of_int (!idx2+1) ^
147 String.concat " " (List.map string_of_int passes) ^
149 tree_store#set ~row:msg_row ~column:interp_no_col
150 (!idx1,Some !idx2,None);
152 let idx3 = ref ~-1 in
154 (fun (passes,env,_) ->
157 match envs_and_diffs with
159 let interp_row = tree_store#append ?parent:msg_row () in
160 tree_store#set ~row:interp_row ~column:id_col
161 ("Interpretation " ^ string_of_int (!idx3+1) ^
163 String.concat " " (List.map string_of_int passes) ^
165 tree_store#set ~row:interp_row ~column:interp_no_col
166 (!idx1,Some !idx2,Some !idx3);
173 let row = tree_store#append ?parent:interp_row () in
174 tree_store#set ~row ~column:id_col id;
175 tree_store#set ~row ~column:dsc_col dsc;
176 tree_store#set ~row ~column:interp_no_col
177 (!idx1,Some !idx2,Some !idx3)
181 if List.length lll > 1 then
183 (fun p -> tree_view#expand_row (tree_store#get_path p))
187 method get_interp_no tree_path =
188 let iter = tree_store#get_iter tree_path in
189 tree_store#get ~row:iter ~column:interp_no_col
192 exception UseLibrary;;
194 let rec interactive_error_interp ~all_passes
195 (source_buffer:GSourceView2.source_buffer) notify_exn offset errorll filename
197 (* hook to save a script for each disambiguation error *)
200 source_buffer#get_text ~start:source_buffer#start_iter
201 ~stop:source_buffer#end_iter () in
202 let md5 = Digest.to_hex (Digest.string text) in
204 Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma" in
205 let ch = open_out filename in
206 output_string ch text;
209 assert (List.flatten errorll <> []);
211 let remove_non_significant =
212 List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
213 let annotated_errorll () =
216 (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
218 if all_passes then annotated_errorll () else
219 let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
220 (* We remove passes 1,2 and 5,6 *)
223 ::(3,remove_non_significant (safe_list_nth errorll 2))
224 ::(4,remove_non_significant (safe_list_nth errorll 3))
227 if List.flatten (List.map snd res) <> [] then res
229 (* all errors (if any) are not significant: we keep them *)
232 ::(3,(safe_list_nth errorll 2))
233 ::(4,(safe_list_nth errorll 3))
236 if List.flatten (List.map snd res) <> [] then
239 "All disambiguation errors are not significant. Showing them anyway." ;
245 "No errors in phases 2 and 3. Showing all errors in all phases" ;
249 let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
252 | [loffset,[_,envs_and_diffs,msg,significant]] ->
253 let _,env,diff = List.hd envs_and_diffs in
255 (MultiPassDisambiguator.DisambiguationError
256 (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
258 let dialog = new disambiguationErrors () in
259 dialog#check_widgets ();
261 dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
262 let model = new interpErrorModel dialog#treeview choices in
263 dialog#disambiguationErrors#set_title "Disambiguation error";
264 dialog#disambiguationErrorsLabel#set_label
265 "Click on an error to see the corresponding message:";
266 ignore (dialog#treeview#connect#cursor_changed
269 match fst (dialog#treeview#get_cursor ()) with
272 let idx1,idx2,idx3 = model#get_interp_no tree_path in
273 let loffset,lll = List.nth choices idx1 in
274 let _,envs_and_diffs,msg,significant =
276 Some idx2 -> List.nth lll idx2
278 [],[],lazy "Multiple error messages. Please select one.",true
282 Some idx3 -> List.nth envs_and_diffs idx3
283 | None -> [],[],[] (* dymmy value, used *) in
284 let script = MatitaScript.current () in
285 let error_tag = script#error_tag in
286 source_buffer#remove_tag error_tag
287 ~start:source_buffer#start_iter
288 ~stop:source_buffer#end_iter;
290 (MultiPassDisambiguator.DisambiguationError
291 (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
294 dialog#disambiguationErrors#destroy ();
297 let fail _ = return () in
298 ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
299 connect_button dialog#disambiguationErrorsOkButton
302 match fst (dialog#treeview#get_cursor ()) with
305 let idx1,idx2,idx3 = model#get_interp_no tree_path in
308 Some idx2, Some idx3 ->
309 let _,lll = List.nth choices idx1 in
310 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
311 let _,_,diff = List.nth envs_and_diffs idx3 in
313 | _,_ -> assert false
322 | DisambiguateTypes.Id id ->
323 GrafiteAst.Ident_alias (id, desc)
324 | DisambiguateTypes.Symbol (symb, i)->
325 GrafiteAst.Symbol_alias (symb, i, desc)
326 | DisambiguateTypes.Num i ->
327 GrafiteAst.Number_alias (i, desc)
329 GrafiteAstPp.pp_alias alias)
334 (source_buffer#get_iter_at_mark
335 (`NAME "beginning_of_statement")) newtxt ;
338 connect_button dialog#disambiguationErrorsMoreErrors
339 (fun _ -> return () ; raise UseLibrary);
340 connect_button dialog#disambiguationErrorsCancelButton fail;
341 dialog#disambiguationErrors#show ();
345 (** Selection handling
346 * Two clipboards are used: "clipboard" and "primary".
347 * "primary" is used by X, when you hit the middle button mouse is content is
348 * pasted between applications. In Matita this selection always contain the
349 * textual version of the selected term.
350 * "clipboard" is used inside Matita only and support ATM two different targets:
351 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
356 (* creation order _is_ relevant for windows placement *)
357 let main = new mainWin () in
358 let fileSel = new fileSelectionWin () in
359 let findRepl = new findReplWin () in
360 let keyBindingBoxes = (* event boxes which should receive global key events *)
361 [ main#mainWinEventBox ]
363 let console = new console ~buffer:main#logTextView#buffer () in
364 let (source_view: GSourceView2.source_view) =
365 GSourceView2.source_view
367 ~insert_spaces_instead_of_tabs:true ~tab_width:2
368 ~right_margin_position:80 ~show_right_margin:true
369 ~smart_home_end:`AFTER
370 ~packing:main#scriptScrolledWin#add
373 let default_font_size =
374 Helm_registry.get_opt_default Helm_registry.int
375 ~default:BuildTimeConf.default_font_size "matita.font_size"
377 let similarsymbols_tag_name = "similarsymbolos" in
378 let similarsymbols_tag = `NAME similarsymbols_tag_name in
379 let source_buffer = source_view#source_buffer in
381 val mutable chosen_file = None
382 val mutable _ok_not_exists = false
383 val mutable _only_directory = false
384 val mutable font_size = default_font_size
385 val mutable similarsymbols = []
386 val mutable similarsymbols_orig = []
387 val clipboard = GData.clipboard Gdk.Atom.clipboard
388 val primary = GData.clipboard Gdk.Atom.primary
390 method private reset_similarsymbols =
391 similarsymbols <- [];
392 similarsymbols_orig <- [];
393 try source_buffer#delete_mark similarsymbols_tag
394 with GText.No_such_mark _ -> ()
397 let s () = MatitaScript.current () in
398 (* glade's check widgets *)
399 List.iter (fun w -> w#check_widgets ())
400 (let c w = (w :> <check_widgets: unit -> unit>) in
401 [ c fileSel; c main; c findRepl]);
403 List.iter (* global key bindings *)
404 (fun (key, callback) -> self#addKeyBinding key callback)
407 toggle_win ~check:main#showProofMenuItem proof#proofWin;
409 toggle_win ~check:main#showCheckMenuItem check#checkWin;
413 let parse_txt_file file =
414 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
415 let l_rev = ref [] in
418 l_rev := input_line ch :: !l_rev;
427 ~authors:(parse_txt_file "AUTHORS")
428 (*~comments:"comments"*)
429 ~copyright:"Copyright (C) 2005, the HELM team"
430 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
431 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
433 ~version:BuildTimeConf.version
434 ~website:"http://matita.cs.unibo.it"
437 ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
438 connect_menu_item main#contentsMenuItem (fun () ->
439 if 0 = Sys.command "which gnome-help" then
441 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
443 ignore (Sys.command cmd)
445 MatitaGtkMisc.report_error ~title:"help system error"
447 "The program gnome-help is not installed\n\n"^
448 "To browse the user manal it is necessary to install "^
449 "the gnome help syste (also known as yelp)")
450 ~parent:main#toplevel ());
451 connect_menu_item main#aboutMenuItem about_dialog#present;
453 let show_find_Repl () =
454 findRepl#toplevel#misc#show ();
455 findRepl#toplevel#misc#grab_focus ()
457 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
459 let highlight start end_ =
460 source_buffer#move_mark `INSERT ~where:start;
461 source_buffer#move_mark `SEL_BOUND ~where:end_;
462 source_view#scroll_mark_onscreen `INSERT
464 let text = findRepl#findEntry#text in
465 let iter = source_buffer#get_iter `SEL_BOUND in
466 match iter#forward_search text with
468 (match source_buffer#start_iter#forward_search text with
470 | Some (start,end_) -> highlight start end_)
471 | Some (start,end_) -> highlight start end_
474 let text = findRepl#replaceEntry#text in
475 let ins = source_buffer#get_iter `INSERT in
476 let sel = source_buffer#get_iter `SEL_BOUND in
477 if ins#compare sel < 0 then
479 ignore(source_buffer#delete_selection ());
480 source_buffer#insert text
483 connect_button findRepl#findButton find_forward;
484 connect_button findRepl#findReplButton replace;
485 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
486 ignore(findRepl#toplevel#event#connect#delete
487 ~callback:(fun _ -> hide_find_Repl ();true));
490 (* phase 1: we save the actual status of the marks and we undo *)
491 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
492 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
493 let locked_iter_offset = locked_iter#offset in
496 (source_view#buffer#create_mark ~name:"lock_point"
497 ~left_gravity:true locked_iter) in
498 source_view#source_buffer#undo ();
499 (* phase 2: we save the cursor position and we redo, restoring
500 the previous status of all the marks *)
501 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
504 (source_view#buffer#create_mark ~name:"undo_point"
505 ~left_gravity:true cursor_iter)
507 source_view#source_buffer#redo ();
508 let mark_iter = source_view#buffer#get_iter_at_mark mark in
509 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
510 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
511 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
512 source_view#buffer#delete_mark mark;
513 source_view#buffer#delete_mark mark2;
514 (* phase 3: if after the undo the cursor was in the locked area,
515 then we move it there again and we perform a goto *)
516 if mark_iter#offset < locked_iter_offset then
518 source_view#buffer#move_mark `INSERT ~where:mark_iter;
519 (MatitaScript.current ())#goto `Cursor ();
521 (* phase 4: we perform again the undo. This time we are sure that
522 the text to undo is not locked *)
523 source_view#source_buffer#undo ();
524 source_view#misc#grab_focus () in
527 (* phase 1: we save the actual status of the marks, we redo and
529 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
530 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
531 let locked_iter_offset = locked_iter#offset in
534 (source_view#buffer#create_mark ~name:"lock_point"
535 ~left_gravity:true locked_iter) in
536 source_view#source_buffer#redo ();
537 source_view#source_buffer#undo ();
538 (* phase 2: we save the cursor position and we restore
539 the previous status of all the marks *)
540 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
543 (source_view#buffer#create_mark ~name:"undo_point"
544 ~left_gravity:true cursor_iter)
546 let mark_iter = source_view#buffer#get_iter_at_mark mark in
547 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
548 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
549 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
550 source_view#buffer#delete_mark mark;
551 source_view#buffer#delete_mark mark2;
552 (* phase 3: if after the undo the cursor is in the locked area,
553 then we move it there again and we perform a goto *)
554 if mark_iter#offset < locked_iter_offset then
556 source_view#buffer#move_mark `INSERT ~where:mark_iter;
557 (MatitaScript.current ())#goto `Cursor ();
559 (* phase 4: we perform again the redo. This time we are sure that
560 the text to redo is not locked *)
561 source_view#source_buffer#redo ();
562 source_view#misc#grab_focus ()
564 connect_menu_item main#undoMenuItem safe_undo;
566 ignore(source_view#source_buffer#connect#can_undo
567 ~callback:main#undoMenuItem#misc#set_sensitive);
568 *) main#undoMenuItem#misc#set_sensitive true;
569 connect_menu_item main#redoMenuItem safe_redo;
571 ignore(source_view#source_buffer#connect#can_redo
572 ~callback:main#redoMenuItem#misc#set_sensitive);
573 *) main#redoMenuItem#misc#set_sensitive true;
574 ignore(source_view#connect#after#populate_popup
575 ~callback:(fun pre_menu ->
576 let menu = new GMenu.menu pre_menu in
577 let menuItems = menu#children in
578 let undoMenuItem, redoMenuItem =
580 [undo;redo;sep1;cut;copy;paste;delete;sep2;
581 selectall;sep3;inputmethod;insertunicodecharacter] ->
582 List.iter menu#remove [ copy; cut; delete; paste ];
584 | _ -> assert false in
586 let i = ref 2 in (* last occupied position *)
587 fun ?label ?stock () ->
589 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
592 let copy = add_menu_item ~stock:`COPY () in
593 let cut = add_menu_item ~stock:`CUT () in
594 let delete = add_menu_item ~stock:`DELETE () in
595 let paste = add_menu_item ~stock:`PASTE () in
596 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
597 copy#misc#set_sensitive self#canCopy;
598 cut#misc#set_sensitive self#canCut;
599 delete#misc#set_sensitive self#canDelete;
600 paste#misc#set_sensitive self#canPaste;
601 paste_pattern#misc#set_sensitive self#canPastePattern;
602 connect_menu_item copy self#copy;
603 connect_menu_item cut self#cut;
604 connect_menu_item delete self#delete;
605 connect_menu_item paste self#paste;
606 connect_menu_item paste_pattern self#pastePattern;
607 let new_undoMenuItem =
608 GMenu.image_menu_item
609 ~image:(GMisc.image ~stock:`UNDO ())
612 ~packing:(menu#insert ~pos:0) () in
613 new_undoMenuItem#misc#set_sensitive
614 (undoMenuItem#misc#get_flag `SENSITIVE);
615 menu#remove (undoMenuItem :> GMenu.menu_item);
616 connect_menu_item new_undoMenuItem safe_undo;
617 let new_redoMenuItem =
618 GMenu.image_menu_item
619 ~image:(GMisc.image ~stock:`REDO ())
622 ~packing:(menu#insert ~pos:1) () in
623 new_redoMenuItem#misc#set_sensitive
624 (redoMenuItem#misc#get_flag `SENSITIVE);
625 menu#remove (redoMenuItem :> GMenu.menu_item);
626 connect_menu_item new_redoMenuItem safe_redo));
628 connect_menu_item main#editMenu (fun () ->
629 main#copyMenuItem#misc#set_sensitive self#canCopy;
630 main#cutMenuItem#misc#set_sensitive self#canCut;
631 main#deleteMenuItem#misc#set_sensitive self#canDelete;
632 main#pasteMenuItem#misc#set_sensitive self#canPaste;
633 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
634 connect_menu_item main#copyMenuItem self#copy;
635 connect_menu_item main#cutMenuItem self#cut;
636 connect_menu_item main#deleteMenuItem self#delete;
637 connect_menu_item main#pasteMenuItem self#paste;
638 connect_menu_item main#pastePatternMenuItem self#pastePattern;
639 connect_menu_item main#selectAllMenuItem (fun () ->
640 source_buffer#move_mark `INSERT source_buffer#start_iter;
641 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
642 connect_menu_item main#findReplMenuItem show_find_Repl;
643 connect_menu_item main#externalEditorMenuItem self#externalEditor;
644 connect_menu_item main#ligatureButton self#nextSimilarSymbol;
645 ignore(source_buffer#connect#after#insert_text
646 ~callback:(fun iter str ->
647 if main#menuitemAutoAltL#active && (str = " " || str = "\n") then
648 ignore(self#expand_virtual_if_any iter str)));
649 ignore (findRepl#findEntry#connect#activate find_forward);
650 (* interface lockers *)
652 main#buttonsToolbar#misc#set_sensitive false;
653 main#scriptMenu#misc#set_sensitive false;
654 source_view#set_editable false
657 main#buttonsToolbar#misc#set_sensitive true;
658 main#scriptMenu#misc#set_sensitive true;
659 source_view#set_editable true;
660 (*The next line seems sufficient to avoid some unknown race condition *)
661 GtkThread.sync (fun () -> ()) ()
663 let worker_thread = ref None in
665 let floc, msg = MatitaExcPp.to_string exn in
670 let (x, y) = HExtlib.loc_of_floc floc in
671 let script = MatitaScript.current () in
672 let locked_mark = script#locked_mark in
673 let error_tag = script#error_tag in
675 (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
676 let x' = baseoffset + x in
677 let y' = baseoffset + y in
678 let x_iter = source_buffer#get_iter (`OFFSET x') in
679 let y_iter = source_buffer#get_iter (`OFFSET y') in
680 source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
682 id := Some (source_buffer#connect#changed ~callback:(fun () ->
683 source_buffer#remove_tag error_tag
684 ~start:source_buffer#start_iter
685 ~stop:source_buffer#end_iter;
687 | None -> assert false (* a race condition occurred *)
689 (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
690 source_buffer#place_cursor
691 (source_buffer#get_iter (`OFFSET x'));
698 let saved_use_library= !MultiPassDisambiguator.use_library in
700 MultiPassDisambiguator.use_library := !all_disambiguation_passes;
702 MultiPassDisambiguator.use_library := saved_use_library;
705 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
707 interactive_error_interp
708 ~all_passes:!all_disambiguation_passes source_buffer
709 notify_exn offset errorll (s())#filename
712 MultiPassDisambiguator.use_library := true;
715 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
716 interactive_error_interp ~all_passes:true source_buffer
717 notify_exn offset errorll (s())#filename
720 | exc -> notify_exn exc);
721 MultiPassDisambiguator.use_library := saved_use_library;
724 (try notify_exn exc with Sys.Break as e -> notify_exn e);
728 worker_thread := Some (Thread.create thread_main ())
731 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
732 let interrupt = ref None in
733 let old_callback = ref (function _ -> ()) in
734 let force_interrupt n =
735 (* This function is called just before the thread's timeslice ends *)
737 if Some(Thread.id(Thread.self())) = !interrupt then
738 (interrupt := None; raise Sys.Break) in
740 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
741 Sys.Signal_handle f -> old_callback := f
743 | Sys.Signal_default -> assert false
746 match !worker_thread with
748 | Some t -> interrupt := Some (Thread.id t) in
752 f (); source_view#misc#grab_focus ()
754 exc -> source_view#misc#grab_focus (); raise exc in
756 (* file selection win *)
757 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
758 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
761 fileSel#fileSelectionWin#misc#hide ();
766 let fname = fileSel#fileSelectionWin#filename in
767 if Sys.file_exists fname then
769 if HExtlib.is_regular fname && not (_only_directory) then
771 else if _only_directory && HExtlib.is_dir fname then
776 if _ok_not_exists then
779 | `CANCEL -> return None
781 | `DELETE_EVENT -> return None));
783 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
785 let adj = main#logScrolledWin#vadjustment in
786 ignore (adj#connect#changed
787 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
788 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
789 (* natural deduction palette *)
790 main#tacticsButtonsHandlebox#misc#hide ();
791 MatitaGtkMisc.toggle_callback
793 if b then main#tacticsButtonsHandlebox#misc#show ()
794 else main#tacticsButtonsHandlebox#misc#hide ())
795 ~check:main#menuitemPalette;
796 connect_button main#butImpl_intro
797 (fun () -> source_buffer#insert "apply rule (⇒#i […] (…));\n");
798 connect_button main#butAnd_intro
799 (fun () -> source_buffer#insert
800 "apply rule (∧#i (…) (…));\n\t[\n\t|\n\t]\n");
801 connect_button main#butOr_intro_left
802 (fun () -> source_buffer#insert "apply rule (∨#i_l (…));\n");
803 connect_button main#butOr_intro_right
804 (fun () -> source_buffer#insert "apply rule (∨#i_r (…));\n");
805 connect_button main#butNot_intro
806 (fun () -> source_buffer#insert "apply rule (¬#i […] (…));\n");
807 connect_button main#butTop_intro
808 (fun () -> source_buffer#insert "apply rule (⊤#i);\n");
809 connect_button main#butImpl_elim
810 (fun () -> source_buffer#insert
811 "apply rule (⇒#e (…) (…));\n\t[\n\t|\n\t]\n");
812 connect_button main#butAnd_elim_left
813 (fun () -> source_buffer#insert "apply rule (∧#e_l (…));\n");
814 connect_button main#butAnd_elim_right
815 (fun () -> source_buffer#insert "apply rule (∧#e_r (…));\n");
816 connect_button main#butOr_elim
817 (fun () -> source_buffer#insert
818 "apply rule (∨#e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
819 connect_button main#butNot_elim
820 (fun () -> source_buffer#insert
821 "apply rule (¬#e (…) (…));\n\t[\n\t|\n\t]\n");
822 connect_button main#butBot_elim
823 (fun () -> source_buffer#insert "apply rule (⊥#e (…));\n");
824 connect_button main#butRAA
825 (fun () -> source_buffer#insert "apply rule (RAA […] (…));\n");
826 connect_button main#butUseLemma
827 (fun () -> source_buffer#insert "apply rule (lem #premises name …);\n");
828 connect_button main#butDischarge
829 (fun () -> source_buffer#insert "apply rule (discharge […]);\n");
831 connect_button main#butForall_intro
832 (fun () -> source_buffer#insert "apply rule (∀#i {…} (…));\n");
833 connect_button main#butForall_elim
834 (fun () -> source_buffer#insert "apply rule (∀#e {…} (…));\n");
835 connect_button main#butExists_intro
836 (fun () -> source_buffer#insert "apply rule (∃#i {…} (…));\n");
837 connect_button main#butExists_elim
838 (fun () -> source_buffer#insert
839 "apply rule (∃#e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
843 main#scriptNotebook#remove_page 1;
844 main#scriptNotebook#set_show_tabs false;
845 (* / TO BE REMOVED *)
846 let module Hr = Helm_registry in
847 MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
849 | true -> main#toplevel#fullscreen ()
850 | false -> main#toplevel#unfullscreen ());
851 main#fullscreenMenuItem#set_active false;
852 MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
853 ~callback:(function b ->
856 Interpretations.toggle_active_interpretations s#grafite_status b
858 assert false (* MATITA1.0 ???
859 s#set_grafite_status status*)
861 MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
862 ~callback:(fun enabled -> Interpretations.hide_coercions := enabled);
863 MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
864 ~callback:(fun enabled ->
865 Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
866 main#unicodeAsTexMenuItem#set_active
867 (Helm_registry.get_bool "matita.paste_unicode_as_tex");
869 HLog.set_log_callback self#console#log_callback;
870 GtkSignal.user_handler :=
872 | MatitaScript.ActionCancelled s -> HLog.error s
874 if not (Helm_registry.get_bool "matita.debug") then
879 source_buffer#set_language (Some MatitaGtkMisc.matita_lang);
880 source_buffer#set_highlight_syntax true
883 (s())#assignFileName None;
884 main#saveMenuItem#misc#set_sensitive false
886 let saveAsScript () =
888 match self#chooseFile ~ok_not_exists:true () with
891 script#assignFileName (Some f);
892 script#saveToFile ();
893 console#message ("'"^f^"' saved.\n");
899 if script#has_name then
900 (script#saveToFile ();
901 console#message ("'"^script#filename^"' saved.\n"))
904 let abandon_script () =
905 let grafite_status = (s ())#grafite_status in
906 if source_view#buffer#modified then
907 (match ask_unsaved main#toplevel with
908 | `YES -> saveScript ()
910 | `CANCEL -> raise MatitaTypes.Cancel);
911 save_moo grafite_status
916 match self#chooseFile () with
920 script#assignFileName (Some f);
921 source_view#source_buffer#begin_not_undoable_action ();
922 script#loadFromFile f;
923 source_view#source_buffer#end_not_undoable_action ();
924 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
925 source_view#buffer#place_cursor source_view#buffer#start_iter;
926 console#message ("'"^f^"' loaded.\n");
929 with MatitaTypes.Cancel -> ()
933 source_view#source_buffer#begin_not_undoable_action ();
936 source_view#source_buffer#end_not_undoable_action ();
938 (s ())#assignFileName None
941 source_buffer#place_cursor
942 (source_buffer#get_iter_at_mark (`NAME "locked")) in
943 let advance _ = (MatitaScript.current ())#advance (); cursor () in
944 let retract _ = (MatitaScript.current ())#retract (); cursor () in
945 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
946 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
947 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
948 let advance = locker (keep_focus advance) in
949 let retract = locker (keep_focus retract) in
950 let top = locker (keep_focus top) in
951 let bottom = locker (keep_focus bottom) in
952 let jump = locker (keep_focus jump) in
954 self#setQuitCallback (fun () ->
955 let script = MatitaScript.current () in
956 if source_view#buffer#modified then
957 match ask_unsaved main#toplevel with
960 save_moo script#grafite_status;
962 | `NO -> GMain.Main.quit ()
965 (save_moo script#grafite_status;
966 GMain.Main.quit ()));
967 connect_button main#scriptAdvanceButton advance;
968 connect_button main#scriptRetractButton retract;
969 connect_button main#scriptTopButton top;
970 connect_button main#scriptBottomButton bottom;
971 connect_button main#scriptJumpButton jump;
972 connect_button main#scriptAbortButton kill_worker;
973 connect_menu_item main#scriptAdvanceMenuItem advance;
974 connect_menu_item main#scriptRetractMenuItem retract;
975 connect_menu_item main#scriptTopMenuItem top;
976 connect_menu_item main#scriptBottomMenuItem bottom;
977 connect_menu_item main#scriptJumpMenuItem jump;
978 connect_menu_item main#openMenuItem loadScript;
979 connect_menu_item main#saveMenuItem saveScript;
980 connect_menu_item main#saveAsMenuItem saveAsScript;
981 connect_menu_item main#newMenuItem newScript;
982 connect_menu_item main#showCoercionsGraphMenuItem
984 let c = MatitaMathView.cicBrowser () in
985 c#load (`About `Coercions));
986 connect_menu_item main#showHintsDbMenuItem
988 let c = MatitaMathView.cicBrowser () in
989 c#load (`About `Hints));
990 connect_menu_item main#showTermGrammarMenuItem
992 let c = MatitaMathView.cicBrowser () in
993 c#load (`About `Grammar));
994 connect_menu_item main#showUnicodeTable
996 let c = MatitaMathView.cicBrowser () in
997 c#load (`About `TeX));
998 (* script monospace font stuff *)
999 self#updateFontSize ();
1001 main#debugMenu#misc#hide ();
1003 main#hintNotebook#misc#hide ();
1005 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1006 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1007 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1010 self#sourceView#misc#grab_focus ();
1011 (* main win dimension *)
1012 let width = Gdk.Screen.width ~screen:(Gdk.Screen.default ()) () in
1013 let height = Gdk.Screen.height ~screen:(Gdk.Screen.default ()) () in
1014 (* hack for xinerama, no proper support of monitors from lablgtk *)
1015 let width = if width > 1600 then width / 2 else width in
1016 let height = if height > 1200 then height / 2 else height in
1017 let main_w = width * 90 / 100 in
1018 let main_h = height * 80 / 100 in
1019 let script_w = main_w * 6 / 10 in
1020 main#toplevel#resize ~width:main_w ~height:main_h;
1021 main#hpaneScriptSequent#set_position script_w;
1023 ignore(source_view#connect#after#paste_clipboard
1024 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1025 (* clean_locked is set to true only "during" a PRIMARY paste
1026 operation (i.e. by clicking with the second mouse button) *)
1027 let clean_locked = ref false in
1028 ignore(source_view#event#connect#button_press
1031 if GdkEvent.Button.button button = 2 then
1032 clean_locked := true;
1035 ignore(source_view#event#connect#button_release
1036 ~callback:(fun button -> clean_locked := false; false));
1037 ignore(source_view#buffer#connect#after#apply_tag
1039 fun tag ~start:_ ~stop:_ ->
1041 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1044 clean_locked := false;
1045 (MatitaScript.current ())#clean_dirty_lock;
1046 clean_locked := true
1048 (* math view handling *)
1049 connect_menu_item main#newCicBrowserMenuItem (fun () ->
1050 ignore(MatitaMathView.cicBrowser ()));
1051 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1052 self#increaseFontSize ();
1053 MatitaMathView.increase_font_size ();
1054 MatitaMathView.update_font_sizes ());
1055 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1056 self#decreaseFontSize ();
1057 MatitaMathView.decrease_font_size ();
1058 MatitaMathView.update_font_sizes ());
1059 connect_menu_item main#normalFontSizeMenuItem (fun () ->
1060 self#resetFontSize ();
1061 MatitaMathView.reset_font_size ();
1062 MatitaMathView.update_font_sizes ());
1063 MatitaMathView.reset_font_size ();
1065 (** selections / clipboards handling *)
1067 method markupSelected = MatitaMathView.has_selection ()
1068 method private textSelected =
1069 (source_buffer#get_iter_at_mark `INSERT)#compare
1070 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1071 method private somethingSelected = self#markupSelected || self#textSelected
1072 method private markupStored = MatitaMathView.has_clipboard ()
1073 method private textStored = clipboard#text <> None
1074 method private somethingStored = self#markupStored || self#textStored
1076 method canCopy = self#somethingSelected
1077 method canCut = self#textSelected
1078 method canDelete = self#textSelected
1079 method canPaste = self#somethingStored
1080 method canPastePattern = self#markupStored
1083 if self#textSelected
1085 MatitaMathView.empty_clipboard ();
1086 source_view#buffer#copy_clipboard clipboard;
1088 MatitaMathView.copy_selection ()
1090 source_view#buffer#cut_clipboard clipboard;
1091 MatitaMathView.empty_clipboard ()
1092 method delete () = ignore (source_view#buffer#delete_selection ())
1094 if MatitaMathView.has_clipboard ()
1095 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1096 else source_view#buffer#paste_clipboard clipboard;
1097 (MatitaScript.current ())#clean_dirty_lock
1098 method pastePattern () =
1099 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1101 method private expand_virtual_if_any iter tok =
1103 let len = MatitaGtkMisc.utf8_string_length tok in
1105 let prev = iter#copy#backward_chars len in
1106 prev#get_slice ~stop:(prev#copy#backward_find_char
1107 (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
1109 let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
1110 self#reset_similarsymbols;
1111 let s = Glib.Utf8.from_unichar symb in
1112 assert(Glib.Utf8.validate s);
1113 source_buffer#delete ~start:iter
1114 ~stop:(iter#copy#backward_chars
1115 (MatitaGtkMisc.utf8_string_length inplaceof + len));
1116 source_buffer#insert ~iter
1117 (if inplaceof.[0] = '\\' then s else (s ^ tok));
1119 with Virtuals.Not_a_virtual -> false
1121 val similar_memory = Hashtbl.create 97
1122 val mutable old_used_memory = false
1124 method private nextSimilarSymbol () =
1125 let write_similarsymbol s =
1126 let s = Glib.Utf8.from_unichar s in
1127 let iter = source_buffer#get_iter_at_mark `INSERT in
1128 assert(Glib.Utf8.validate s);
1129 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
1130 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s;
1131 (try source_buffer#delete_mark similarsymbols_tag
1132 with GText.No_such_mark _ -> ());
1133 ignore(source_buffer#create_mark ~name:similarsymbols_tag_name
1134 (source_buffer#get_iter_at_mark `INSERT));
1136 let new_similarsymbol =
1138 let iter_ins = source_buffer#get_iter_at_mark `INSERT in
1139 let iter_lig = source_buffer#get_iter_at_mark similarsymbols_tag in
1140 not (iter_ins#equal iter_lig)
1141 with GText.No_such_mark _ -> true
1143 if new_similarsymbol then
1144 (if not(self#expand_virtual_if_any (source_buffer#get_iter_at_mark `INSERT) "")then
1146 let i = source_buffer#get_iter_at_mark `INSERT in
1147 Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
1149 (match Virtuals.similar_symbols last_symbol with
1152 similarsymbols_orig <- eqclass;
1154 try Hashtbl.find similar_memory similarsymbols_orig
1156 let is_used = List.map (fun x -> x,false) eqclass in
1157 Hashtbl.add similar_memory eqclass is_used;
1162 List.partition (fun s -> List.assoc s is_used) eqclass
1164 match used @ unused with a::b::c -> a,b,c | _ -> assert false
1167 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
1169 old_used_memory <- List.assoc hd is_used;
1171 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
1173 Hashtbl.replace similar_memory similarsymbols_orig is_used;
1174 write_similarsymbol hd;
1175 similarsymbols <- tl @ [ hd ]))
1177 match similarsymbols with
1180 let is_used = Hashtbl.find similar_memory similarsymbols_orig in
1181 let last = HExtlib.list_last tl in
1182 let old_used_for_last = old_used_memory in
1183 old_used_memory <- List.assoc hd is_used;
1185 (hd, true) :: (last,old_used_for_last) ::
1186 List.filter (fun (x,_) -> x <> last && x <> hd) is_used
1188 Hashtbl.replace similar_memory similarsymbols_orig is_used;
1189 similarsymbols <- tl @ [ hd ];
1190 write_similarsymbol hd
1192 method private externalEditor () =
1193 let cmd = Helm_registry.get "matita.external_editor" in
1194 (* ZACK uncomment to enable interactive ask of external editor command *)
1197 "External editor command:
1198 %f will be substitute for the script name,
1199 %p for the cursor position in bytes,
1200 %l for the execution point in bytes."
1202 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1203 ~default:(Helm_registry.get "matita.external_editor") ()
1205 let script = MatitaScript.current () in
1206 let fname = script#filename in
1208 source_buffer#start_iter#get_slice
1209 ~stop:(source_buffer#get_iter_at_mark mark)
1211 let locked = `MARK script#locked_mark in
1212 let string_pos mark = string_of_int (String.length (slice mark)) in
1213 let cursor_pos = string_pos `INSERT in
1214 let locked_pos = string_pos locked in
1216 Pcre.replace ~pat:"%f" ~templ:fname
1217 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1218 (Pcre.replace ~pat:"%l" ~templ:locked_pos
1221 let locked_before = slice locked in
1222 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1223 ignore (Unix.system cmd);
1224 source_buffer#set_text (HExtlib.input_file fname);
1225 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1226 source_buffer#move_mark locked locked_iter;
1227 source_buffer#apply_tag script#locked_tag
1228 ~start:source_buffer#start_iter ~stop:locked_iter;
1229 let locked_after = slice locked in
1233 for i = 0 to String.length locked_before - 1 do
1234 if locked_before.[i] <> locked_after.[i] then begin
1235 source_buffer#place_cursor
1236 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1237 script#goto `Cursor ();
1239 end else if locked_before.[i] = '\n' then begin
1246 | Invalid_argument _ -> script#goto `Bottom ()
1248 method loadScript file =
1249 let script = MatitaScript.current () in
1251 script#assignFileName (Some file);
1252 let file = script#filename in
1254 if Sys.file_exists file then file
1255 else BuildTimeConf.script_template
1257 source_view#source_buffer#begin_not_undoable_action ();
1258 script#loadFromFile content;
1259 source_view#source_buffer#end_not_undoable_action ();
1260 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1261 source_view#buffer#place_cursor source_view#buffer#start_iter;
1262 console#message ("'"^file^"' loaded.");
1263 self#_enableSaveTo file
1266 let s = MatitaScript.current () in
1267 let w = main#toplevel in
1268 let set x = w#set_title x in
1270 "Matita - " ^ Filename.basename s#filename ^
1271 (if b then "*" else "") ^
1272 " in " ^ s#buri_of_current_file
1276 method private _enableSaveTo file =
1277 self#main#saveMenuItem#misc#set_sensitive true
1279 method console = console
1280 method sourceView: GSourceView2.source_view =
1281 (source_view: GSourceView2.source_view)
1282 method fileSel = fileSel
1283 method findRepl = findRepl
1286 method newBrowserWin () =
1288 inherit browserWin ()
1289 val combo = GEdit.entry ()
1291 self#check_widgets ();
1292 let combo_widget = combo#coerce in
1293 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1294 combo#misc#grab_focus ()
1295 method browserUri = combo
1298 method newUriDialog () =
1299 let dialog = new uriChoiceDialog () in
1300 dialog#check_widgets ();
1303 method newConfirmationDialog () =
1304 let dialog = new confirmationDialog () in
1305 dialog#check_widgets ();
1308 method newEmptyDialog () =
1309 let dialog = new emptyDialog () in
1310 dialog#check_widgets ();
1313 method private addKeyBinding key callback =
1314 List.iter (fun evbox -> add_key_binding key callback evbox)
1317 method setQuitCallback callback =
1318 connect_menu_item main#quitMenuItem callback;
1319 ignore (main#toplevel#event#connect#delete
1320 (fun _ -> callback ();true));
1321 self#addKeyBinding GdkKeysyms._q callback
1323 method chooseFile ?(ok_not_exists = false) () =
1324 _ok_not_exists <- ok_not_exists;
1325 _only_directory <- false;
1326 fileSel#fileSelectionWin#show ();
1330 method private chooseDir ?(ok_not_exists = false) () =
1331 _ok_not_exists <- ok_not_exists;
1332 _only_directory <- true;
1333 fileSel#fileSelectionWin#show ();
1335 (* we should check that this is a directory *)
1338 method askText ?(title = "") ?(msg = "") () =
1339 let dialog = new textDialog () in
1340 dialog#textDialog#set_title title;
1341 dialog#textDialogLabel#set_label msg;
1342 let text = ref None in
1345 dialog#textDialog#destroy ();
1348 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1349 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1350 connect_button dialog#textDialogOkButton (fun _ ->
1351 let text = dialog#textDialogTextView#buffer#get_text () in
1352 return (Some text));
1353 dialog#textDialog#show ();
1357 method private updateFontSize () =
1358 self#sourceView#misc#modify_font_by_name
1359 (sprintf "%s %d" BuildTimeConf.script_font font_size)
1361 method increaseFontSize () =
1362 font_size <- font_size + 1;
1363 self#updateFontSize ()
1365 method decreaseFontSize () =
1366 font_size <- font_size - 1;
1367 self#updateFontSize ()
1369 method resetFontSize () =
1370 font_size <- default_font_size;
1371 self#updateFontSize ()
1376 let g = new gui () in
1377 gui_instance := Some g;
1378 MatitaMathView.set_gui g;
1381 let instance = singleton gui
1383 let non p x = not (p x)
1385 (* this is a shit and should be changed :-{ *)
1386 let interactive_uri_choice
1387 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1388 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1389 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1393 let gui = instance () in
1394 if (selection_mode <> `SINGLE) &&
1395 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1399 let dialog = gui#newUriDialog () in
1400 if hide_uri_entry then
1401 dialog#uriEntryHBox#misc#hide ();
1404 dialog#uriChoiceSelectedButton#misc#hide ();
1405 dialog#uriChoiceConstantsButton#misc#hide ();
1407 dialog#okLabel#set_label ok_label;
1408 dialog#uriChoiceTreeView#selection#set_mode
1409 (selection_mode :> Gtk.Tags.selection_mode);
1410 let model = new stringListModel dialog#uriChoiceTreeView in
1411 let choices = ref None in
1415 dialog#copyButton#misc#show ();
1416 connect_button dialog#copyButton
1418 match model#easy_selection () with
1421 dialog#uriChoiceDialog#set_title title;
1422 dialog#uriChoiceLabel#set_text msg;
1423 List.iter model#easy_append (List.map NReference.string_of_reference uris);
1424 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1427 dialog#uriChoiceDialog#destroy ();
1430 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1431 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1432 return (Some uris));
1433 if ok_action = `AUTO then
1434 connect_button dialog#uriChoiceAutoButton (fun _ ->
1435 Helm_registry.set_bool "matita.auto_disambiguation" true;
1438 connect_button dialog#uriChoiceAutoButton (fun _ ->
1439 match model#easy_selection () with
1441 | uris -> return (Some (List.map NReference.reference_of_string uris)));
1442 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1443 match model#easy_selection () with
1445 | uris -> return (Some (List.map NReference.reference_of_string uris)));
1446 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1447 dialog#uriChoiceDialog#show ();
1449 (match !choices with
1450 | None -> raise MatitaTypes.Cancel
1451 | Some uris -> uris)
1455 let cols = new GTree.column_list in
1456 let id_col = cols#add Gobject.Data.string in
1457 let dsc_col = cols#add Gobject.Data.string in
1458 let interp_no_col = cols#add Gobject.Data.int in
1459 let tree_store = GTree.tree_store cols in
1460 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1461 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1462 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1463 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1464 fun tree_view choices ->
1467 tree_view#set_model (Some (tree_store :> GTree.model));
1468 ignore (tree_view#append_column id_view_col);
1469 ignore (tree_view#append_column dsc_view_col);
1470 let name_of_interp =
1471 (* try to find a reasonable name for an interpretation *)
1475 List.assoc "0" interp
1477 incr idx; string_of_int !idx
1479 tree_store#clear ();
1480 let idx = ref ~-1 in
1484 let interp_row = tree_store#append () in
1485 tree_store#set ~row:interp_row ~column:id_col
1486 (name_of_interp interp);
1487 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1490 let row = tree_store#append ~parent:interp_row () in
1491 tree_store#set ~row ~column:id_col id;
1492 tree_store#set ~row ~column:dsc_col dsc;
1493 tree_store#set ~row ~column:interp_no_col !idx)
1497 method get_interp_no tree_path =
1498 let iter = tree_store#get_iter tree_path in
1499 tree_store#get ~row:iter ~column:interp_no_col
1503 let interactive_string_choice
1504 text prefix_len ?(title = "") ?(msg = "") () ~id locs uris
1506 let gui = instance () in
1507 let dialog = gui#newUriDialog () in
1508 dialog#uriEntryHBox#misc#hide ();
1509 dialog#uriChoiceSelectedButton#misc#hide ();
1510 dialog#uriChoiceAutoButton#misc#hide ();
1511 dialog#uriChoiceConstantsButton#misc#hide ();
1512 dialog#uriChoiceTreeView#selection#set_mode
1513 (`SINGLE :> Gtk.Tags.selection_mode);
1514 let model = new stringListModel dialog#uriChoiceTreeView in
1515 let choices = ref None in
1516 dialog#uriChoiceDialog#set_title title;
1517 let hack_len = MatitaGtkMisc.utf8_string_length text in
1518 let rec colorize acc_len = function
1520 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1521 escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1523 let start, stop = HExtlib.loc_of_floc he in
1524 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1525 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1526 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1527 escape_pango_markup str1 ^ "<b>" ^
1528 escape_pango_markup str2 ^ "</b>" ^
1531 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1532 Printf.eprintf "(%d,%d)" start stop) locs; *)
1536 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1539 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1540 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1541 Printf.eprintf "(%d,%d)" start stop) locs;
1542 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1543 dialog#uriChoiceLabel#set_use_markup true;
1544 let txt = colorize 0 locs in
1545 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1546 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1548 dialog#uriChoiceLabel#set_label txt;
1549 List.iter model#easy_append uris;
1552 dialog#uriChoiceDialog#destroy ();
1555 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1556 connect_button dialog#uriChoiceForwardButton (fun _ ->
1557 match model#easy_selection () with
1559 | uris -> return (Some uris));
1560 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1561 dialog#uriChoiceDialog#show ();
1563 (match !choices with
1564 | None -> raise MatitaTypes.Cancel
1565 | Some uris -> uris)
1567 let interactive_interp_choice () text prefix_len choices =
1568 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1569 let filter_choices filter =
1570 let rec is_compatible filter =
1573 | ([],_,_)::tl -> is_compatible filter tl
1574 | (loc::tlloc,id,dsc)::tl ->
1576 if List.assoc (loc,id) filter = dsc then
1577 is_compatible filter ((tlloc,id,dsc)::tl)
1583 List.filter (fun (_,interp) -> is_compatible filter interp)
1585 let rec get_choices loc id =
1590 List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1592 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1594 let example_interp =
1598 let ask_user id locs choices =
1599 interactive_string_choice
1601 ~title:"Ambiguous input"
1602 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1604 let rec classify ids filter partial_interpretations =
1606 [] -> List.map fst partial_interpretations
1607 | ([],_,_)::tl -> classify tl filter partial_interpretations
1608 | (loc::tlloc,id,dsc)::tl ->
1609 let choices = get_choices loc id partial_interpretations in
1612 [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1615 match ask_user id [loc] choices with
1619 let filter = ((loc,id),chosen_dsc)::filter in
1620 let compatible_interps = filter_choices filter partial_interpretations in
1621 classify ((tlloc,id,dsc)::tl) filter compatible_interps
1623 let enumerated_choices =
1624 let idx = ref ~-1 in
1625 List.map (fun interp -> incr idx; !idx,interp) choices
1627 classify example_interp [] enumerated_choices
1630 (* disambiguator callbacks *)
1631 Disambiguate.set_choose_uris_callback
1632 (fun ~selection_mode ?ok ?(enable_button_for_non_vars=false) ~title ~msg ->
1633 interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1634 Disambiguate.set_choose_interp_callback (interactive_interp_choice ());
1635 (* gtk initialization *)
1636 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1637 ignore (GMain.Main.init ())