Debian Codegraph @

ide/rocqide/rocqide.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Preferences
12 open Gtk_parsing
13 open Ideutils
14 open Session
15
16 (** Note concerning GtkTextBuffer
17
18 Be careful with gtk calls on text buffers, since many are non-atomic :
19 they emit a gtk signal and the handlers for this signal are run
20 immediately, before returning to the current function.
21 Here's a partial list of these signals and the methods that
22 trigger them (cf. documentation of GtkTextBuffer, signal section)
23
24 begin_user_action : #begin_user_action, #insert_interactive,
25 #insert_range_interactive, #delete_interactive, #delete_selection
26 end_user_action : #end_user_action, #insert_interactive,
27 #insert_range_interactive, #delete_interactive, #delete_selection
28
29 insert_text : #insert (and variants)
30 delete_range : #delete (and variants)
31
32 apply_tag : #apply_tag, (and some #insert)
33 remove_tag : #remove_tag
34
35 mark_deleted : #delete_mark
36 mark_set : #create_mark, #move_mark
37
38 changed : ... (whenever a buffer has changed)
39 modified_changed : #set_modified (and whenever the modified bit flips)
40
41 Caveat : when the buffer is modified, all iterators on it become
42 invalid and shouldn't be used (nasty errors otherwise). There are
43 some special cases : boundaries given to #insert and #delete are
44 revalidated by the default signal handler.
45 *)
46
47 (** {2 Some static elements } *)
48
49 (** The arguments that will be passed to rocqtop. No quoting here, since
50 no /bin/sh when using create_process instead of open_process. *)
51 let custom_project_file = ref None
52 let sup_args = ref []
53
54 let logfile = ref None
55
56 (** {2 Notebook of sessions } *)
57
58 (** The main element of rocqide is a notebook of session views *)
59
60 let notebook =
61 Wg_Notebook.create Session.build_layout Session.kill
62 ~border_width:2 ~show_border:false ~scrollable:true ()
63
64
65 (** {2 Callback functions for the user interface } *)
66
67 let on_current_term f =
68 let term = try Some notebook#current_term with Invalid_argument _ -> None in
69 match term with
70 | None -> ()
71 | Some t -> ignore (f t)
72
73 let cb_on_current_term f _ = on_current_term f
74
75 (** Nota: using && here has the advantage of working both under win32 and unix.
76 If someday we want the main command to be tried even if the "cd" has failed,
77 then we should use " ; " under unix but " & " under win32 (cf. #2363). *)
78
79 let local_cd file =
80 "cd " ^ Filename.quote (Filename.dirname file) ^ " && "
81
82 let pr_exit_status = function
83 | Unix.WEXITED 0 -> " succeeded"
84 | _ -> " failed"
85
86 let make_rocqtop_args fname =
87 let open CoqProject_file in
88 let base_args = match read_project#get with
89 | Ignore_args -> !sup_args
90 | Append_args -> !sup_args
91 | Subst_args -> [] in
92 let proj, args =
93 if read_project#get = Ignore_args then "", base_args
94 else
95 match !custom_project_file, fname with
96 | Some (d,proj), _ -> d, coqtop_args_from_project proj @ base_args
97 | None, None -> "", base_args
98 | None, Some the_file ->
99 match
100 CoqProject_file.find_project_file
101 ~from:(Filename.dirname the_file)
102 ~projfile_name:project_file_name#get
103 with
104 | None -> "", base_args
105 | Some proj ->
106 Minilib.log ("About to read project file " ^ proj);
107 let warning_fn x = Feedback.msg_warning Pp.(str x) in
108 proj, coqtop_args_from_project (read_project_file ~warning_fn proj) @ base_args
109 in
110 let args = match fname with
111 | None -> args
112 | Some fname ->
113 if List.exists (String.equal "-top") args then args
114 else
115 (* We basically copy the code of Names.check_valid since it is not exported *)
116 (* to rocqide. This is to prevent a possible failure of parsing "-topfile" *)
117 (* at initialization of rocqtop (see #10286) *)
118 (* If the file name is a valid identifier, use it as toplevel name; *)
119 (* otherwise the default “Top” will be used. *)
120 try
121 match Unicode.ident_refutation (Filename.chop_extension (Filename.basename fname)) with
122 | Some _ -> args
123 | None -> "-topfile"::fname::args
124 with Invalid_argument _ ->
125 failwith "RocqIDE cannot open files which do not have an extension in their filename."
126 in
127 proj, args
128
129 (** Setting drag & drop on widgets *)
130
131 let load_file_cb : (string -> unit) ref = ref ignore
132
133 let drop_received context ~x ~y data ~info ~time =
134 if data#format = 8 then begin
135 let files = Str.split (Str.regexp "\r?\n") data#data in
136 List.iter (fun f ->
137 let _, f = Glib.Convert.filename_from_uri f in
138 !load_file_cb f;
139 ) files;
140 context#finish ~success:true ~del:false ~time
141 end else context#finish ~success:false ~del:false ~time
142
143 let drop_targets = [
144 { Gtk.target = "text/uri-list"; Gtk.flags = []; Gtk.info = 0 }
145 ]
146
147 let set_drag (w : GObj.drag_ops) =
148 w#dest_set drop_targets ~actions:[`COPY;`MOVE];
149 w#connect#data_received ~callback:drop_received
150
151 (** Session management *)
152 let clear_db_highlight ?(retn=false) sn () =
153 (match sn.debug_stop_pt with
154 | Some (osn,bp,ep) ->
155 if List.mem osn notebook#pages then (* in case destroyed *)
156 osn.script#clear_debugging_highlight bp ep;
157 if retn then
158 notebook#goto_term sn;
159 | None -> ()
160 )
161
162 let find_secondary_sn sn =
163 let rec find = function
164 | [] -> sn
165 | hd :: tl ->
166 (match hd.debug_stop_pt with
167 | Some (osn,_,_) -> osn
168 | None -> find tl)
169 in find notebook#pages
170
171 let db_cmd sn cmd =
172 ignore @@ RocqDriver.try_grab ~db:true sn.rocqtop
173 (sn.rocqops#process_db_cmd cmd ~next:(function | _ -> RocqDriver.return ()))
174 (fun () -> Minilib.log "Rocq busy, discarding db_cmd")
175
176 let forward_db_stack = ref ((fun _ -> failwith "forward_db_stack")
177 : session -> unit -> unit)
178 let forward_db_vars = ref ((fun _ -> failwith "forward_db_vars")
179 : session -> int -> unit)
180 let forward_highlight_code = ref ((fun _ -> failwith "forward_highlight_code")
181 : session -> string * int * int -> unit)
182 let forward_restore_bpts = ref ((fun _ -> failwith "forward_restore_bpts")
183 : session -> unit)
184 let forward_init_db = ref ((fun _ -> failwith "forward_init_db")
185 : session -> unit)
186
187 let create_session f =
188 let project_file, args = make_rocqtop_args f in
189 if project_file <> "" then
190 flash_info (Printf.sprintf "Reading options from %s" project_file);
191 let sn = Session.create f args in
192 sn.debugger#set_forward_get_basename (fun _ -> sn.basename);
193 RocqDriver.set_restore_bpts sn.rocqtop (fun _ -> !forward_restore_bpts sn);
194 (sn.messages#route 0)#set_forward_send_db_cmd (db_cmd sn);
195 (sn.messages#route 0)#set_forward_send_db_stack (!forward_db_stack sn);
196 sn.debugger#set_forward_highlight_code (!forward_highlight_code sn);
197 sn.debugger#set_forward_clear_db_highlight (clear_db_highlight sn);
198 sn.debugger#set_forward_db_vars (!forward_db_vars sn);
199 sn.rocqops#set_forward_clear_db_highlight (clear_db_highlight ~retn:true sn);
200 sn.rocqops#set_forward_set_goals_of_dbg_session
201 (fun msg ->
202 sn.rocqops#set_debug_goal msg;
203 sn.last_db_goals <- msg;
204 let osn = (find_secondary_sn sn) in
205 osn.rocqops#set_debug_goal msg;
206 osn.last_db_goals <- msg);
207 sn.rocqops#set_forward_init_db (fun () -> !forward_init_db sn);
208 let _ = set_drag sn.script#drag in
209 sn
210
211
212 let db_upd_bpts ?(next=RocqDriver.return) updates sn =
213 if updates <> [] then
214 ignore @@ RocqDriver.try_grab ~db:true sn.rocqtop
215 (sn.rocqops#process_db_upd_bpts updates ~next:(function | _ -> next ()))
216 (fun () -> Minilib.log "Rocq busy, discarding db_upd_bpts")
217
218 let get_updates sn =
219 (* breakpoints in this buffer *)
220 let upds = List.map (fun bp ->
221 let start = sn.buffer#get_iter_at_mark (`NAME bp.mark_id) in
222 let stop = start#forward_char in
223 sn.buffer#apply_tag Tags.Script.breakpoint ~start ~stop; (* restore highlight for init *)
224 (("ToplevelInput", bp.prev_byte_offset), true)
225 ) sn.breakpoints
226 in
227 (* plus breakpoints in other buffers *)
228 List.fold_left (fun upds osn ->
229 match osn.abs_file_name with
230 | _ when osn == sn -> upds
231 | None -> upds
232 | Some file ->
233 (List.map (fun bp -> ((file, bp.prev_byte_offset), true)) osn.breakpoints) @ upds
234 ) upds notebook#pages
235
236 (* init breakpoints for new session or re-init after reset *)
237 let init_bpts sn =
238 RocqDriver.add_do_when_ready sn.rocqtop (fun _ ->
239 let upds = get_updates sn in
240 db_upd_bpts upds sn)
241
242 (* todo: shouldn't be so hard to chain operations *)
243 let () = forward_init_db := fun sn ->
244 let updates = get_updates sn in
245 let send_configd () =
246 ignore @@ RocqDriver.try_grab ~db:true sn.rocqtop
247 (sn.rocqops#process_db_configd () ~next:(function | _ -> RocqDriver.return ()))
248 (fun () -> Minilib.log "Rocq busy, discarding db_configd")
249 in
250 if updates = [] then
251 send_configd ()
252 else
253 db_upd_bpts updates sn ~next:(fun () -> send_configd (); RocqDriver.return ())
254
255 let restore_bpts sn =
256 init_bpts sn;
257 sn.debugger#set_stack [];
258 sn.debugger#set_vars []
259
260 let _ = forward_restore_bpts := restore_bpts
261
262 (** Auxiliary functions for the File operations *)
263
264 module FileAux = struct
265
266 let load_file ?(maycreate=false) f =
267 let f = CUnix.correct_path f (Sys.getcwd ()) in
268 try
269 Minilib.log "Loading file starts";
270 let is_f = CUnix.same_file f in
271 let rec search_f i = function
272 | [] -> false
273 | sn :: sessions ->
274 match sn.fileops#filename with
275 | Some fn when is_f fn -> notebook#goto_page i; true
276 | _ -> search_f (i+1) sessions
277 in
278 if not (search_f 0 notebook#pages) then begin
279 Minilib.log "Loading: get raw content";
280 let b = Buffer.create 1024 in
281 if Sys.file_exists f then Ideutils.read_file f b
282 else if not maycreate then flash_info ("Load failed: no such file");
283 Minilib.log "Loading: convert content";
284 let s = do_convert (Buffer.contents b) in
285 Minilib.log "Loading: create view";
286 let session = create_session (Some f) in
287 let index = notebook#append_term session in
288 notebook#goto_page index;
289 Minilib.log "Loading: stats";
290 session.fileops#update_stats;
291 let input_buffer = session.buffer in
292 Minilib.log "Loading: fill buffer";
293 input_buffer#set_text s;
294 input_buffer#set_modified false;
295 input_buffer#place_cursor ~where:input_buffer#start_iter;
296 Sentence.tag_all input_buffer;
297 session.script#clear_undo ();
298 Minilib.log "Loading: success";
299 end
300 with e -> flash_info ("Load failed: "^(Printexc.to_string e))
301
302 let confirm_save ok =
303 if ok then flash_info "Saved" else warning "Save Failed"
304
305 let select_and_save ?parent ~saveas ?filename sn =
306 let do_save = if saveas then sn.fileops#saveas ?parent else sn.fileops#save in
307 let title = if saveas then "Save file as" else "Save file" in
308 match select_file_for_save ~title ?parent ?filename () with
309 |None -> false
310 |Some f ->
311 let ok = do_save f in
312 confirm_save ok;
313 if ok then begin
314 sn.tab_label#set_text (Filename.remove_extension (Filename.basename f));
315 sn.abs_file_name <- Some (Session.to_abs_file_name f);
316 (* copying local breakpoints to other sessions seems pointless
317 for a "save as" because the saved file needs to be compiled
318 and other sessions restarted to use the new filename in
319 breakpoints *)
320 end;
321 ok
322
323 let check_save ?parent ~saveas sn =
324 try match sn.fileops#filename with
325 |None -> select_and_save ?parent ~saveas sn
326 |Some f ->
327 let ok = sn.fileops#save f in
328 confirm_save ok;
329 ok
330 with _ -> warning "Save Failed"; false
331
332 exception DontQuit
333
334 (* avoid getting 3 dialogs from ^C^C^C on the console. You can still get 2 :-( *)
335 let in_quit_dialog = ref false
336
337 let check_quit ?parent saveall =
338 in_quit_dialog := true;
339 (try save_pref ()
340 with e -> flash_info ("Cannot save preferences (" ^ Printexc.to_string e ^ ")"));
341 let is_modified sn = sn.buffer#modified in
342 if List.exists is_modified notebook#pages then begin
343 let answ = Ui_dialogs.question_box ~title:"Quit"
344 ~buttons:[ButtonWithLabel "Save named buffers and quit";
345 ButtonWithLabel "Quit without saving";
346 ButtonWithLabel "Don't quit"]
347 ~default:0
348 ~icon:(warn_image ())#coerce
349 ?parent
350 "There are unsaved buffers."
351 in
352 match answ with
353 | 1 -> saveall ()
354 | 2 -> ()
355 | _ -> in_quit_dialog := false; raise DontQuit
356 end;
357 List.iter (fun sn -> RocqDriver.close_rocqtop sn.rocqtop) notebook#pages
358
359 (* For MacOS, just to be sure, we close all rocqtops (again?) *)
360 let close_and_quit () =
361 List.iter (fun sn -> RocqDriver.close_rocqtop sn.rocqtop) notebook#pages;
362 exit 0
363
364 (* Work around a deadlock due to OCaml exit cleanup. The standard [exit]
365 function calls [flush_all], which can block if one of the opened channels is
366 not valid anymore. We do not register [at_exit] functions in RocqIDE, so
367 instead of flushing we simply die as gracefully as possible in the function
368 below. *)
369 external sys_exit : int -> 'a = "caml_sys_exit"
370
371 let crash_save exitcode =
372 Minilib.log "Starting emergency save of buffers in .crashrocqide files";
373 let idx =
374 let r = ref 0 in
375 fun () -> incr r; string_of_int !r
376 in
377 let save_session sn =
378 let filename = match sn.fileops#filename with
379 | None -> "Unnamed_rocqscript_" ^ idx () ^ ".crashrocqide"
380 | Some f -> f^".crashrocqide"
381 in
382 try
383 if try_export filename (sn.buffer#get_text ()) then
384 Minilib.log ("Saved "^filename)
385 else Minilib.log ("Could not save "^filename)
386 with _ -> Minilib.log ("Could not save "^filename)
387 in
388 List.iter save_session notebook#pages;
389 Minilib.log "End emergency save";
390 sys_exit exitcode
391
392 end
393
394 let () = load_file_cb := (fun s -> FileAux.load_file s)
395
396 let clear_all_bpts sn =
397 sn.breakpoints <- [];
398 init_bpts sn
399
400 (** Callbacks for the File menu *)
401
402 module File = struct
403
404 let newfile _ =
405 let sn = create_session None in
406 let index = notebook#append_term sn in
407 notebook#goto_page index;
408 init_bpts sn
409
410 let load ?parent _ =
411 let filename =
412 try notebook#current_term.fileops#filename
413 with Invalid_argument _ -> None in
414 let filenames = select_file_for_open ~title:"Load file" ~multiple:true ?parent ?filename () in
415 List.iter FileAux.load_file filenames;
416 on_current_term (fun sn -> init_bpts sn)
417
418 let save ?parent _ = on_current_term (FileAux.check_save ?parent ~saveas:false)
419
420 let saveas ?parent sn =
421 try
422 let filename = sn.fileops#filename in
423 ignore (FileAux.select_and_save ?parent ~saveas:true ?filename sn);
424 (* if a new file, adds breakpoints from other files into this session *)
425 init_bpts sn
426 with _ -> warning "Save Failed"
427
428 let saveas ?parent = cb_on_current_term (saveas ?parent)
429
430 let saveall _ =
431 List.iter
432 (fun sn -> match sn.fileops#filename with
433 | None -> ()
434 | Some f -> ignore (sn.fileops#save f))
435 notebook#pages
436
437 let () = RocqDriver.save_all := saveall
438
439 let reload_all ?parent _ =
440 List.iter
441 (fun sn -> if sn.fileops#changed_on_disk then begin
442 clear_all_bpts sn;
443 sn.fileops#reload ?parent ()
444 end)
445 notebook#pages
446
447 let win_interrupt = ref false
448
449 let quit ?parent _ =
450 if !win_interrupt then
451 win_interrupt := false
452 else if not !FileAux.in_quit_dialog then
453 try FileAux.check_quit ?parent saveall; exit 0
454 with FileAux.DontQuit -> ()
455
456 let close_buffer ?parent sn =
457 let do_remove () =
458 notebook#remove_page notebook#current_page;
459 (* remove breakpoints in this buffer from other sessions *)
460 if sn.breakpoints <> [] then
461 match sn.abs_file_name with
462 | None -> ()
463 | Some file ->
464 List.iter (fun osn ->
465 if sn != osn then begin
466 let upds = List.fold_left (fun upds bp ->
467 ((file, bp.prev_byte_offset), false) :: upds)
468 [] sn.breakpoints in
469 RocqDriver.add_do_when_ready osn.rocqtop (fun _ -> db_upd_bpts upds osn)
470 end
471 ) notebook#pages
472 in
473 if not sn.buffer#modified then do_remove ()
474 else
475 let answ = Ui_dialogs.question_box ~title:"Close"
476 ~buttons:[ButtonWithLabel "Save buffer and close";
477 ButtonWithLabel "Close without saving";
478 ButtonWithLabel "Don't close"]
479 ~default:0
480 ~icon:(warn_image ())#coerce
481 ?parent
482 "This buffer has unsaved modifications"
483 in
484 match answ with
485 | 1 when FileAux.check_save ?parent ~saveas:true sn -> do_remove ()
486 | 2 -> do_remove ()
487 | _ -> ()
488
489 let close_buffer ?parent = cb_on_current_term (close_buffer ?parent)
490
491 let export kind sn =
492 match sn.fileops#filename with
493 |None -> flash_info "Cannot print: this buffer has no name"
494 |Some f ->
495 let basef = Filename.basename f in
496 let output =
497 let basef_we = try Filename.chop_extension basef with _ -> basef in
498 match kind with
499 | "latex" -> basef_we ^ ".tex"
500 | "dvi" | "ps" | "pdf" | "html" -> basef_we ^ "." ^ kind
501 | _ -> assert false
502 in
503 let cmd =
504 local_cd f ^ cmd_rocqdoc#get ^ " --" ^ kind ^ " -o " ^
505 (Filename.quote output) ^ " " ^ (Filename.quote basef) ^ " 2>&1"
506 in
507 sn.messages#default_route#set (Pp.str ("Running: "^cmd));
508 let finally st = flash_info (cmd ^ pr_exit_status st)
509 in
510 run_command (fun msg -> sn.messages#default_route#add_string msg) finally cmd
511
512 let export kind = cb_on_current_term (export kind)
513
514 let print sn =
515 match sn.fileops#filename with
516 |None -> flash_info "Cannot print: this buffer has no name"
517 |Some f_name ->
518 let cmd =
519 local_cd f_name ^ cmd_rocqdoc#get ^ " -ps " ^
520 Filename.quote (Filename.basename f_name) ^ " | " ^ cmd_print#get
521 in
522 let w = GWindow.window ~title:"Print" ~modal:true
523 ~position:`CENTER ~wmclass:("RocqIDE","RocqIDE") ()
524 in
525 let v = GPack.vbox ~spacing:10 ~border_width:10 ~packing:w#add ()
526 in
527 let _ = GMisc.label ~text:"Print using the following command:"
528 ~justify:`LEFT ~packing:v#add ()
529 in
530 let e = GEdit.entry ~text:cmd ~editable:true ~width_chars:80
531 ~packing:v#add ()
532 in
533 let h = GPack.hbox ~spacing:10 ~packing:v#add ()
534 in
535 let ko = GButton.button ~stock:`CANCEL ~label:"Cancel" ~packing:h#add ()
536 in
537 let ok = GButton.button ~stock:`PRINT ~label:"Print" ~packing:h#add ()
538 in
539 let callback_print () =
540 w#destroy ();
541 let cmd = e#text in
542 let finally st = flash_info (cmd ^ pr_exit_status st) in
543 run_command ignore finally cmd
544 in
545 let _ = ko#connect#clicked ~callback:w#destroy in
546 let _ = ok#connect#clicked ~callback:callback_print in
547 w#misc#show ()
548
549 let print = cb_on_current_term print
550
551 let highlight sn =
552 Sentence.tag_all sn.buffer;
553 sn.script#recenter_insert
554
555 let highlight = cb_on_current_term highlight
556
557 end
558
559 (** Timers *)
560
561 let reset_reload_timer () =
562 FileOps.reload_timer.kill ();
563 if global_auto_reload#get then
564 FileOps.reload_timer.run
565 ~ms:global_auto_reload_delay#get
566 ~callback:(fun () -> File.reload_all (); true)
567
568 let reset_autosave_timer () =
569 let autosave sn = try sn.fileops#auto_save with _ -> () in
570 let autosave_all () = List.iter autosave notebook#pages; true in
571 FileOps.autosave_timer.kill ();
572 if auto_save#get then
573 FileOps.autosave_timer.run ~ms:auto_save_delay#get ~callback:autosave_all
574
575 (** Export of functions used in [rocqide_main] : *)
576
577 let close_and_quit = FileAux.close_and_quit
578 let crash_save = FileAux.crash_save
579 let do_load f = FileAux.load_file f
580
581 (** Callbacks for external commands *)
582
583 module External = struct
584
585 let rocq_makefile sn =
586 match sn.fileops#filename with
587 |None -> flash_info "Cannot make makefile: this buffer has no name"
588 |Some f ->
589 let cmd = local_cd f ^ cmd_rocqmakefile#get in
590 let finally st = flash_info (cmd_rocqmakefile#get ^ pr_exit_status st)
591 in
592 run_command ignore finally cmd
593
594 let rocq_makefile = cb_on_current_term rocq_makefile
595
596 let editor ?parent sn =
597 match sn.fileops#filename with
598 |None -> warning "Call to external editor available only on named files"
599 |Some f ->
600 File.save ();
601 let f = Filename.quote f in
602 let cmd = Util.subst_command_placeholder cmd_editor#get f in
603 run_command ignore (fun _ -> sn.fileops#reload ?parent ()) cmd
604
605 let editor ?parent = cb_on_current_term (editor ?parent)
606
607 let compile sn =
608 File.save ();
609 match sn.fileops#filename with
610 |None -> flash_info "Active buffer has no name"
611 |Some f ->
612 let args = RocqDriver.get_arguments sn.rocqtop in
613 let cmd = cmd_rocqc#get
614 ^ " " ^ String.concat " " (List.map Filename.quote args)
615 ^ " " ^ (Filename.quote f) ^ " 2>&1"
616 in
617 let buf = Buffer.create 1024 in
618 sn.messages#default_route#set (Pp.str ("Running: "^cmd));
619 let display s =
620 sn.messages#default_route#add_string s;
621 Buffer.add_string buf s
622 in
623 let finally st =
624 if st = Unix.WEXITED 0 then
625 flash_info (f ^ " successfully compiled")
626 else begin
627 flash_info (f ^ " failed to compile");
628 sn.messages#default_route#set (Pp.str ("Compilation output:\n" ^ cmd ^ "\n"));
629 sn.messages#default_route#add (Pp.str (Buffer.contents buf));
630 end
631 in
632 run_command display finally cmd
633
634 let compile = cb_on_current_term compile
635
636 (** [last_make_buf] contains the output of the last make compilation.
637 [last_make] is the same, but as a string, refreshed only when searching
638 the next error. *)
639
640 let last_make_buf = Buffer.create 1024
641 let last_make = ref ""
642 let last_make_index = ref 0
643 let last_make_dir = ref ""
644
645 let make sn =
646 match sn.fileops#filename with
647 |None -> flash_info "Cannot make: this buffer has no name"
648 |Some f ->
649 File.saveall ();
650 let cmd = local_cd f ^ cmd_make#get ^ " 2>&1" in
651 sn.messages#default_route#set (Pp.str "Compilation output:\n");
652 Buffer.reset last_make_buf;
653 last_make := "";
654 last_make_index := 0;
655 last_make_dir := Filename.dirname f;
656 let display s =
657 sn.messages#default_route#add_string s;
658 Buffer.add_string last_make_buf s
659 in
660 let finally st = flash_info (cmd_make#get ^ pr_exit_status st)
661 in
662 run_command display finally cmd
663
664 let make = cb_on_current_term make
665
666 let search_compile_error_regexp =
667 Str.regexp
668 "File \"\\([^\"]+\\)\", line \\([0-9]+\\), characters \\([0-9]+\\)-\\([0-9]+\\)"
669
670 let search_next_error () =
671 if String.length !last_make <> Buffer.length last_make_buf
672 then last_make := Buffer.contents last_make_buf;
673 let _ =
674 Str.search_forward search_compile_error_regexp !last_make !last_make_index
675 in
676 let f = Str.matched_group 1 !last_make
677 and l = int_of_string (Str.matched_group 2 !last_make)
678 and b = int_of_string (Str.matched_group 3 !last_make)
679 and e = int_of_string (Str.matched_group 4 !last_make)
680 and msg_index = Str.match_beginning ()
681 in
682 last_make_index := Str.group_end 4;
683 (Filename.concat !last_make_dir f, l, b, e,
684 String.sub !last_make msg_index (String.length !last_make - msg_index))
685
686 let next_error sn =
687 try
688 let file,line,start,stop,error_msg = search_next_error () in
689 FileAux.load_file file;
690 let b = sn.buffer in
691 let starti = Ideutils.get_iter_at_byte b ~line:(line-1) start in
692 let stopi = Ideutils.get_iter_at_byte b ~line:(line-1) stop in
693 b#apply_tag Tags.Script.error ~start:starti ~stop:stopi;
694 b#place_cursor ~where:starti;
695 sn.messages#default_route#set (Pp.str error_msg);
696 sn.script#misc#grab_focus ()
697 with Not_found ->
698 last_make_index := 0;
699 sn.messages#default_route#set (Pp.str "No more errors.\n")
700
701 let next_error = cb_on_current_term next_error
702
703 end
704
705 (** Callbacks for the Navigation menu *)
706
707 let update_status sn =
708 let display msg = pop_info (); push_info msg in
709 let next = function
710 | Interface.Fail x -> sn.rocqops#handle_failure x
711 | Interface.Good status ->
712 let path = match status.Interface.status_path with
713 | [] | _ :: [] -> "" (* Drop the topmost level, usually "Top" *)
714 | _ :: l -> " in " ^ String.concat "." l
715 in
716 let name = match status.Interface.status_proofname with
717 | None -> ""
718 | Some n -> ", proving " ^ n
719 in
720 display ("Ready"^ (if microPG#get then ", [μPG]" else "") ^ path ^ name);
721 RocqDriver.return ()
722 in
723 RocqDriver.bind (RocqDriver.status false) next
724
725 let find_next_occurrence ~backward sn =
726 (* go to the next occurrence of the current word, forward or backward *)
727 let b = sn.buffer in
728 let start = find_word_start (b#get_iter_at_mark `INSERT) in
729 let stop = find_word_end start in
730 let text = b#get_text ~start ~stop () in
731 let search = if backward then start#backward_search else stop#forward_search
732 in
733 match search text with
734 |None -> ()
735 |Some(where, _) -> b#place_cursor ~where; sn.script#recenter_insert
736
737 let send_to_rocq_aux f sn =
738 let info () = Minilib.log "Rocq busy, discarding query" in
739 let f = RocqDriver.seq (f sn) (update_status sn) in
740 ignore @@ RocqDriver.try_grab sn.rocqtop f info
741
742 let send_to_rocq f = on_current_term (send_to_rocq_aux f)
743
744 let db_continue opt sn =
745 RocqDriver.try_grab ~db:true sn.rocqtop (sn.rocqops#process_db_continue opt
746 ~next:(function | _ -> RocqDriver.return ()))
747 (fun () -> Minilib.log "Rocq busy, discarding db_continue")
748
749 (* find the session identified by sid. If not specified and the current term
750 is the stopping point for another session, direct actions to that term *)
751 let find_db_sn ?sid () =
752 let cur = notebook#current_term in
753 let f = match sid with
754 | Some sid -> fun term -> term.sid == sid
755 | None -> fun term ->
756 match term.debug_stop_pt with
757 | Some (osn,_,_) -> osn == cur
758 | None -> false
759 in
760 let res = List.filter f notebook#pages in
761 if res = [] then cur else List.hd res
762
763 let resume_debugger ?sid opt =
764 let term = try Some (find_db_sn ?sid ()) with Invalid_argument _ -> None in
765 match term with
766 | None -> false
767 | Some t ->
768 if RocqDriver.is_stopped_in_debugger t.rocqtop && db_continue opt t then begin
769 RocqDriver.set_stopped_in_debugger t.rocqtop false;
770 clear_db_highlight t ();
771 t.debugger#set_stack [];
772 t.debugger#set_vars [];
773 t.messages#default_route#set_editable2 false;
774 t.messages#default_route#push Feedback.Notice (Pp.mt ());
775 (* Ideutils.push_info "Rocq is computing"; todo: needs to be per-session *)
776 true
777 end else false
778
779 (* figure out which breakpoint locations have changed because the script was edited *)
780 let calculate_bpt_updates () =
781 let fn = "ToplevelInput" in
782 let rec update_bpts sn upd bpts_res = function
783 | bp :: tl ->
784 let iter = sn.buffer#get_iter_at_mark (`NAME bp.mark_id) in
785 let has_tag = iter#has_tag Tags.Script.breakpoint in
786 let prev_byte_offset = bp.prev_byte_offset in
787 if not has_tag then begin
788 sn.buffer#delete_mark (`NAME bp.mark_id); (* remove *)
789 update_bpts sn (((fn, prev_byte_offset), false) :: upd) bpts_res tl
790 end else if iter#offset <> bp.prev_uni_offset then begin
791 bp.prev_uni_offset <- iter#offset; (* move *)
792 let byte_offset = Ideutils.buffer_off_to_byte_off sn.buffer iter#offset in
793 bp.prev_byte_offset <- byte_offset;
794 update_bpts sn (((fn, byte_offset), true)
795 :: ((fn, prev_byte_offset), false) :: upd)
796 (bp :: bpts_res) tl (* move *)
797 end else
798 update_bpts sn upd (bp :: bpts_res) tl (* no change, keep *)
799 | [] -> (List.rev upd, List.rev bpts_res) (* order matters *)
800 in
801 let upds = List.map (fun sn -> update_bpts sn [] [] sn.breakpoints) notebook#pages in
802 upds
803
804 let maybe_update_breakpoints () =
805 let upds = calculate_bpt_updates () in
806 List.iter2 (fun sn (_, bpts) ->
807 sn.breakpoints <- bpts;
808 let sn_upds = List.concat (List.mapi (fun n sn2 ->
809 let (upd, _) = List.nth upds n in
810 match sn2.abs_file_name with
811 | _ when sn == sn2 -> upd (* as TopLevelInput *)
812 | Some fn ->
813 List.map (fun ((_, off), set) -> ((fn, off), set)) upd
814 | None -> []
815 ) notebook#pages) in
816 if sn_upds <> [] then
817 RocqDriver.add_do_when_ready sn.rocqtop (fun _ -> db_upd_bpts sn_upds sn)
818 ) notebook#pages upds
819
820 module Nav = struct
821 let forward_one_sid ?sid _ =
822 maybe_update_breakpoints ();
823 if not (resume_debugger ?sid Interface.StepOver) then
824 send_to_rocq (fun sn -> sn.rocqops#process_next_phrase)
825 let forward_one x = forward_one_sid x
826 let continue ?sid _ = maybe_update_breakpoints ();
827 if not (resume_debugger ?sid Interface.Continue) then
828 send_to_rocq (fun sn -> sn.rocqops#process_until_end_or_error)
829 let step_in ?sid _ = maybe_update_breakpoints ();
830 if not (resume_debugger ?sid Interface.StepIn) then
831 send_to_rocq (fun sn -> sn.rocqops#process_next_phrase)
832 let step_out ?sid _ = maybe_update_breakpoints ();
833 if not (resume_debugger ?sid Interface.StepOut) then
834 send_to_rocq (fun sn -> sn.rocqops#process_next_phrase)
835 let backward_one _ = maybe_update_breakpoints ();
836 send_to_rocq (fun sn -> init_bpts sn; sn.rocqops#backtrack_last_phrase)
837 let run_to_cursor _ = maybe_update_breakpoints ();
838 send_to_rocq (fun sn -> sn.rocqops#go_to_insert)
839 let run_to_end _ = maybe_update_breakpoints ();
840 send_to_rocq (fun sn -> sn.rocqops#process_until_end_or_error)
841 let previous_occ = cb_on_current_term (find_next_occurrence ~backward:true)
842 let next_occ = cb_on_current_term (find_next_occurrence ~backward:false)
843 let restart _ =
844 Minilib.log "Reset Initial";
845 maybe_update_breakpoints ();
846 if notebook#pages <> [] then begin
847 let sn = notebook#current_term in
848 RocqDriver.reset_rocqtop sn.rocqtop (* calls init_bpts *)
849 end
850 let interrupt _ = (* terminate computation *)
851 if Sys.os_type = "Win32" then File.win_interrupt := true;
852 Minilib.log "User interrupt received";
853 if not (resume_debugger Interface.Interrupt) && notebook#pages <> [] then begin
854 let osn = (find_db_sn ()) in
855 RocqDriver.interrupt_rocqtop osn.rocqtop CString.(Set.elements (Map.domain osn.jobpage#data))
856 end
857 let break ?sid _ = (* stop at the next possible stopping point *)
858 if notebook#pages <> [] then begin
859 let orocqtop = (find_db_sn ?sid ()).rocqtop in
860 if not (RocqDriver.is_stopped_in_debugger orocqtop) then
861 RocqDriver.send_break orocqtop
862 end
863 let show_debugger _ =
864 on_current_term (fun sn -> sn.debugger#show ())
865 let join_document _ = send_to_rocq (fun sn -> sn.rocqops#join_document)
866 end
867
868 let f9 = GtkData.AccelGroup.parse "F9"
869 let f10 = GtkData.AccelGroup.parse "F10"
870 let f11 = GtkData.AccelGroup.parse "F11"
871 let shft_f10 = GtkData.AccelGroup.parse "<Shift>F10"
872 let ctl_up = GtkData.AccelGroup.parse "<Ctrl>Up"
873 let ctl_down = GtkData.AccelGroup.parse "<Ctrl>Down"
874
875 (* handle certain function keys from detached Messages panel
876 functions are directed to the specified session or the
877 current session, not the Messages session (debatable) *)
878 let forward_keystroke key sid =
879 if key = f9 then (Nav.continue ~sid (); true)
880 else if key = f10 then (Nav.step_in ~sid (); true)
881 else if key = f11 then (Nav.break ~sid (); true)
882 else if key = shft_f10 then (Nav.step_out ~sid (); true)
883 else if key = ctl_up then (Nav.backward_one (*~sid*) (); true)
884 else if key = ctl_down then (Nav.forward_one_sid ~sid (); true)
885 else false
886
887 let _ = Wg_MessageView.forward_keystroke := forward_keystroke
888 let _ = Wg_Debugger.forward_keystroke := forward_keystroke
889
890 let printopts_callback opts v =
891 let b = v#get_active in
892 let () = List.iter (fun o -> RocqDriver.PrintOpt.set o b) opts in
893 send_to_rocq (fun sn -> sn.rocqops#show_goals)
894
895 (** Templates menu *)
896
897 let get_current_word term =
898 (* First look to find if autocompleting *)
899 match term.script#proposal with
900 | Some p -> p
901 | None ->
902 (* Then look at the current selected word *)
903 let buf1 = term.script#buffer in
904 let buf2 = term.proof#buffer in
905 if buf1#has_selection then
906 let (start, stop) = buf1#selection_bounds in
907 buf1#get_text ~slice:true ~start ~stop ()
908 else if buf2#has_selection then
909 let (start, stop) = buf2#selection_bounds in
910 buf2#get_text ~slice:true ~start ~stop ()
911 else if term.messages#has_selection then
912 term.messages#get_selected_text
913 (* Otherwise try to find the word around the cursor *)
914 else
915 let it = term.script#buffer#get_iter_at_mark `INSERT in
916 let start = find_word_start it in
917 let stop = find_word_end start in
918 term.script#buffer#get_text ~slice:true ~start ~stop ()
919
920 let print_branch c l =
921 Format.fprintf c " | @[<hov 1>%a@]=> _@\n"
922 (Minilib.print_list (fun c s -> Format.fprintf c "%s@ " s)) l
923
924 let print_branches c cases =
925 Format.fprintf c "@[match var with@\n%aend@]@."
926 (Minilib.print_list print_branch) cases
927
928 let display_match sn = function
929 |Interface.Fail _ ->
930 flash_info "Not an inductive type"; RocqDriver.return ()
931 |Interface.Good cases ->
932 let text =
933 let buf = Buffer.create 1024 in
934 let () = print_branches (Format.formatter_of_buffer buf) cases in
935 Buffer.contents buf
936 in
937 Minilib.log ("match template :\n" ^ text);
938 let b = sn.buffer in
939 let _ = b#delete_selection () in
940 let m = b#create_mark (b#get_iter_at_mark `INSERT) in
941 if b#insert_interactive text then begin
942 let i = b#get_iter (`MARK m) in
943 let _ = i#nocopy#forward_chars 9 in
944 let _ = b#place_cursor ~where:i in
945 b#move_mark ~where:(i#backward_chars 3) `SEL_BOUND
946 end;
947 b#delete_mark (`MARK m);
948 RocqDriver.return ()
949
950 let match_callback sn =
951 let w = get_current_word sn in
952 let rocqtop = sn.rocqtop in
953 let query = RocqDriver.bind (RocqDriver.mkcases w) (display_match sn) in
954 ignore @@ RocqDriver.try_grab rocqtop query
955 (fun () -> Minilib.log "Rocq busy, discarding mkcases")
956
957 let match_callback = cb_on_current_term match_callback
958
959 (** Queries *)
960
961 module Query = struct
962
963 let doquery query sn =
964 sn.messages#default_route#clear;
965 ignore @@ RocqDriver.try_grab sn.rocqtop (sn.rocqops#raw_rocq_query query ~route_id:0
966 ~next:(function
967 | Interface.Fail (_, _, err) ->
968 let err = Ideutils.validate err in
969 sn.messages#default_route#add err;
970 RocqDriver.return ()
971 | Interface.Good () -> RocqDriver.return ()))
972 (fun () -> Minilib.log "Rocq busy, discarding raw_rocq_query")
973
974 let queryif command sn =
975 Option.iter (fun query -> doquery (query ^ ".") sn)
976 begin try
977 let i = CString.string_index_from command 0 "..." in
978 let word = get_current_word sn in
979 if word = "" then None
980 else Some (CString.sub command 0 i ^ " " ^ word)
981 with Not_found -> Some command end
982
983 let query command _ = cb_on_current_term (queryif command) ()
984
985 end
986
987 (** Misc *)
988
989 module MiscMenu = struct
990
991 let detach_view sn = sn.control#detach ()
992
993 let detach_view = cb_on_current_term detach_view
994
995 let log_file_message () =
996 if !Minilib.debug then
997 let file = match !logfile with None -> "stderr" | Some f -> f in
998 "\nDebug mode is on, log file is "^file
999 else ""
1000
1001 let initial_about () =
1002 let initial_string =
1003 "Welcome to RocqIDE, an Integrated Development Environment for Rocq"
1004 in
1005 let rocq_version = RocqDriver.short_version () in
1006 let version_info =
1007 if Glib.Utf8.validate rocq_version then
1008 "\nYou are running " ^ rocq_version
1009 else ""
1010 in
1011 let msg = initial_string ^ version_info ^ log_file_message () in
1012 on_current_term (fun term -> term.messages#default_route#add_string msg)
1013
1014 let rocq_icon () =
1015 (* May raise Nof_found *)
1016 let name = "coq.png" in
1017 let chk d = Sys.file_exists (Filename.concat d name) in
1018 let dir = List.find chk (Minilib.rocqide_data_dirs ()) in
1019 Filename.concat dir name
1020
1021 let show_proof_diff where sn =
1022 sn.messages#default_route#clear;
1023 ignore @@ RocqDriver.try_grab sn.rocqtop (sn.rocqops#proof_diff where
1024 ~next:(function
1025 | Interface.Fail (_, _, err) ->
1026 let err = if (Pp.string_of_ppcmds err) <> "No proofs to diff." then err else
1027 Pp.str "Put the cursor over proven lines for \"Show Proof\" diffs"
1028 in
1029 let err = Ideutils.validate err in
1030 sn.messages#default_route#add err;
1031 RocqDriver.return ()
1032 | Interface.Good diff ->
1033 sn.messages#default_route#add diff;
1034 RocqDriver.return ()))
1035 (fun () -> Minilib.log "Rocq busy, discarding raw_rocq_query")
1036
1037 let show_proof_diffs _ = cb_on_current_term (show_proof_diff `INSERT) ()
1038
1039 let highlight_code sn loc =
1040 let (file, bp, ep) = loc in
1041 let highlight () =
1042 clear_db_highlight sn ();
1043 notebook#current_term.script#set_debugging_highlight bp ep;
1044 sn.debug_stop_pt <- Some (notebook#current_term, bp, ep);
1045 (* also show goal in secondary script goal panel *)
1046 notebook#current_term.rocqops#set_debug_goal sn.last_db_goals
1047 in
1048 if file = "ToplevelInput" then begin
1049 notebook#goto_term sn;
1050 highlight ()
1051 end else if CString.is_suffix ".v" file then begin
1052 try let _ = Unix.stat file in
1053 FileAux.load_file file;
1054 highlight ()
1055 with Unix.Unix_error (Unix.ENOENT,_,_) ->
1056 (* or just show in messages panel? *)
1057 let title = "Warning" in
1058 let icon = (warn_image ())#coerce in
1059 let buttons = ["OK"] in
1060 let msg = Printf.sprintf "Can't find: %s" file in
1061 let _ = GToolbox.question_box ~title ~buttons ~icon msg in
1062 ()
1063 end
1064
1065 let _ = forward_highlight_code := highlight_code
1066
1067 let db_stack sn _ =
1068 RocqDriver.add_do_when_ready sn.rocqtop (fun _ ->
1069 ignore @@ RocqDriver.try_grab ~db:true sn.rocqtop (sn.rocqops#process_db_stack
1070 ~next:(function
1071 | Interface.Good stack ->
1072 sn.debugger#set_stack stack;
1073 RocqDriver.return ()
1074 | Interface.Fail _ ->
1075 RocqDriver.return ()
1076 ))
1077 (fun () -> Minilib.log "Rocq busy, discarding db_stack")
1078 )
1079
1080 let _ = forward_db_stack := db_stack
1081
1082 let db_vars sn line =
1083 RocqDriver.add_do_when_ready sn.rocqtop (fun _ ->
1084 ignore @@ RocqDriver.try_grab ~db:true sn.rocqtop (sn.rocqops#process_db_vars line
1085 ~next:(function
1086 | Interface.Good vars ->
1087 sn.debugger#set_vars vars;
1088 RocqDriver.return ()
1089 | Interface.Fail _ ->
1090 RocqDriver.return ()
1091 ))
1092 (fun () -> Minilib.log "Rocq busy, discarding db_vars")
1093 )
1094
1095 let _ = forward_db_vars := db_vars
1096
1097 let next_bpt = ref 0
1098
1099 let compute_toggle sn =
1100 let start = sn.buffer#get_iter_at_mark `INSERT in
1101 let stop = start#forward_char in
1102 let file = "ToplevelInput" in
1103 let prev_uni_offset = start#offset in
1104 let prev_byte_offset = Ideutils.buffer_off_to_byte_off sn.buffer prev_uni_offset in
1105 let rec update_bpts = function
1106 | bp :: tl ->
1107 let iter = sn.buffer#get_iter_at_mark (`NAME bp.mark_id) in
1108 if iter#offset = prev_uni_offset then begin
1109 sn.buffer#remove_tag Tags.Script.breakpoint ~start ~stop;
1110 sn.buffer#delete_mark (`NAME bp.mark_id);
1111 [((file, prev_byte_offset), false)],
1112 List.filter (fun x ->
1113 x.mark_id <> bp.mark_id
1114 ) sn.breakpoints
1115 end else
1116 update_bpts tl
1117 | [] ->
1118 sn.buffer#apply_tag Tags.Script.breakpoint ~start ~stop;
1119 incr next_bpt;
1120 let mark_id = "bp" ^ (string_of_int !next_bpt) in
1121 let _ = sn.buffer#create_mark ~name:mark_id start in
1122 ([((file, prev_byte_offset), true)], ({ mark_id; prev_byte_offset; prev_uni_offset }
1123 :: sn.breakpoints))
1124 in
1125 let upd, bpts_res = update_bpts sn.breakpoints in
1126 sn.breakpoints <- List.rev bpts_res;
1127 upd
1128
1129 let toggle_breakpoint_i sn =
1130 maybe_update_breakpoints ();
1131 let upd = compute_toggle sn in
1132 db_upd_bpts upd sn;
1133 (* if this session has an associated file, toggle bp in all other sessions *)
1134 match sn.abs_file_name with
1135 | Some fname ->
1136 let upd2 = List.map (fun bp ->
1137 let ((_, off), toggle) = bp in
1138 ((fname, off), toggle)
1139 ) upd in
1140 List.iter (fun osn ->
1141 if osn != sn then
1142 RocqDriver.add_do_when_ready osn.rocqtop (fun _ -> db_upd_bpts upd2 osn)
1143 ) notebook#pages
1144 | None -> ()
1145
1146 let all_sessions_ready _ =
1147 List.fold_left (fun rdy sn -> rdy && RocqDriver.is_ready_or_stopped_in_debugger sn.rocqtop)
1148 true notebook#pages
1149
1150 let toggle_breakpoint _ =
1151 if all_sessions_ready () then
1152 on_current_term toggle_breakpoint_i
1153
1154 let about _ =
1155 let dialog = GWindow.about_dialog () in
1156 let _ = dialog#connect#response ~callback:(fun _ -> dialog#destroy ()) in
1157 let _ =
1158 try dialog#set_logo (GdkPixbuf.from_file (rocq_icon ()))
1159 with _ -> ()
1160 in
1161 let copyright =
1162 "Rocq is developed by the Rocq Development Team\n\
1163 (INRIA - CNRS - LIX - LRI - PPS)"
1164 in
1165 let authors = [
1166 "Benjamin Monate";
1167 "Jean-Christophe Filliâtre";
1168 "Pierre Letouzey";
1169 "Claude Marché";
1170 "Bruno Barras";
1171 "Pierre Corbineau";
1172 "Julien Narboux";
1173 "Hugo Herbelin";
1174 "Enrico Tassi";
1175 ]
1176 in
1177 dialog#set_name "RocqIDE";
1178 dialog#set_comments "The Rocq Integrated Development Environment";
1179 dialog#set_website Coq_config.wwwcoq;
1180 dialog#set_version Coq_config.version;
1181 dialog#set_copyright copyright;
1182 dialog#set_authors authors;
1183 dialog#show ()
1184
1185 let apply_unicode_binding =
1186 cb_on_current_term (fun t ->
1187 t.script#apply_unicode_binding())
1188
1189 let rocqtop_arguments sn =
1190 init_bpts sn;
1191 let dialog = GWindow.dialog ~title:"Coqtop arguments" () in
1192 let rocqtop = sn.rocqtop in
1193 (* Text entry *)
1194 let text = Ideutils.encode_string_list (RocqDriver.get_arguments rocqtop) in
1195 let entry = GEdit.entry ~text ~packing:dialog#vbox#add () in
1196 (* Buttons *)
1197 let box = dialog#action_area in
1198 let ok = GButton.button ~stock:`OK ~packing:box#add () in
1199 let fail s =
1200 let msg = Printf.sprintf "Invalid arguments: %s" s in
1201 let () = sn.messages#default_route#clear in
1202 sn.messages#default_route#push Feedback.Error (Pp.str msg) in
1203 let ok_cb () =
1204 let ntext = entry#text in
1205 if ntext <> text then
1206 match try Util.Inr (Ideutils.decode_string_list ntext) with Failure s -> Util.Inl s with
1207 | Util.Inl s -> fail s
1208 | Util.Inr nargs ->
1209 let failed = RocqDriver.filter_rocq_opts nargs in
1210 match failed with
1211 | [] ->
1212 let () = RocqDriver.set_arguments rocqtop nargs in
1213 dialog#destroy ()
1214 | args ->
1215 fail (String.concat " " args)
1216 else dialog#destroy ()
1217 in
1218 let _ = entry#connect#activate ~callback:ok_cb in
1219 let _ = ok#connect#clicked ~callback:ok_cb in
1220 let cancel = GButton.button ~stock:`CANCEL ~packing:box#add () in
1221 let cancel_cb () = dialog#destroy () in
1222 let _ = cancel#connect#clicked ~callback:cancel_cb in
1223 dialog#show ()
1224
1225 let rocqtop_arguments = cb_on_current_term rocqtop_arguments
1226
1227 let show_hide_query_pane sn =
1228 let ccw = sn.command in
1229 if ccw#visible then ccw#hide else ccw#show
1230
1231 let zoom_fit sn =
1232 let script = sn.script in
1233 let space = script#misc#allocation.Gtk.width in
1234 let cols = script#right_margin_position in
1235 let pango_ctx = script#misc#pango_context in
1236 let layout = pango_ctx#create_layout#as_layout in
1237 Pango.Layout.set_text layout (String.make cols 'X');
1238 let tlen = fst (Pango.Layout.get_pixel_size layout) in
1239 let ft = Pango.Font.from_string text_font#get in
1240 let fsize = Pango.Font.get_size ft in
1241 Pango.Font.set_size ft (fsize * space / tlen / Pango.scale * Pango.scale);
1242 text_font#set (Pango.Font.to_string ft);
1243 save_pref ()
1244
1245 end
1246
1247 (** Refresh functions *)
1248
1249 let refresh_notebook_pos () =
1250 let pos = match document_tabs_pos#get with
1251 | "left" -> `LEFT
1252 | "right" -> `RIGHT
1253 | "bottom" -> `BOTTOM
1254 | _ -> `TOP
1255 in
1256 notebook#set_tab_pos pos
1257
1258 (** Wrappers around GAction functions for creating menus *)
1259
1260 let menu = GAction.add_actions
1261 let item = GAction.add_action
1262 let radio = GAction.add_radio_action
1263
1264 (** Toggle items in menus for printing options *)
1265
1266 let toggle_item = GAction.add_toggle_action
1267
1268 (** Search the first '_' in a label string and return the following
1269 character as shortcut, plus the string without the '_' *)
1270
1271 let get_shortcut s =
1272 try
1273 let n = String.length s in
1274 let i = String.index s '_' in
1275 let k = String.make 1 s.[i+1] in
1276 let s' = (String.sub s 0 i) ^ (String.sub s (i+1) (n-i-1)) in
1277 Some k, s'
1278 with _ -> None,s
1279
1280 module Opt = RocqDriver.PrintOpt
1281
1282 let printopts_items menu_name l =
1283 let f Opt.{ label; init; opts } =
1284 let k, name = get_shortcut label in
1285 let accel = Option.map ((^) modifier_for_display#get) k in
1286 printopts_item_names := name :: !printopts_item_names;
1287 toggle_item name ~label ?accel ~active:init
1288 ~callback:(printopts_callback opts)
1289 menu_name
1290 in
1291 List.iter f l
1292
1293 let no_under = Util.String.map (fun x -> if x = '_' then '-' else x)
1294
1295 (** Create alphabetical menu items with elements in sub-items.
1296 [l] is a list of lists, one per initial letter *)
1297
1298 let alpha_items menu_name item_name l =
1299 let mk_item text =
1300 let text' =
1301 let len = String.length text in
1302 let buf = Buffer.create (len + 1) in
1303 let escaped = ref false in
1304 String.iter (fun c ->
1305 if !escaped then
1306 let () = Buffer.add_char buf c in
1307 escaped := false
1308 else if c = '_' then escaped := true
1309 else Buffer.add_char buf c
1310 ) text;
1311 if text.[len - 1] = '.'
1312 then Buffer.add_char buf '\n'
1313 else Buffer.add_char buf ' ';
1314 Buffer.contents buf
1315 in
1316 let callback _ =
1317 on_current_term (fun sn -> sn.buffer#insert_interactive text')
1318 in
1319 item (item_name^" "^(no_under text)) ~label:text ~callback menu_name
1320 in
1321 let mk_items = function
1322 | [] -> ()
1323 | [s] -> mk_item s
1324 | s::_ as ll ->
1325 let name = Printf.sprintf "%s %c" item_name s.[0] in
1326 let label = Printf.sprintf "_%c..." s.[0] in
1327 item name ~label menu_name;
1328 List.iter mk_item ll
1329 in
1330 List.iter mk_items l
1331
1332 (** Create a menu item that will insert a given text,
1333 and select the zone given by (offset,len).
1334 The first word in the text is used as item keyword.
1335 Caveat: the offset is now from the start of the text. *)
1336
1337 let template_item (text, offset, len, key) =
1338 let modifier = modifier_for_templates#get in
1339 let idx = String.index text ' ' in
1340 let name = String.sub text 0 idx in
1341 let label = "_"^name^" __" in
1342 let negoffset = String.length text - offset - len in
1343 let callback sn =
1344 let b = sn.buffer in
1345 if b#insert_interactive text then begin
1346 let iter = b#get_iter_at_mark `INSERT in
1347 ignore (iter#nocopy#backward_chars negoffset);
1348 b#move_mark `INSERT ~where:iter;
1349 ignore (iter#nocopy#backward_chars len);
1350 b#move_mark `SEL_BOUND ~where:iter;
1351 end
1352 in
1353 item name ~label ~callback:(cb_on_current_term callback) ~accel:(modifier^key)
1354
1355 (** Create menu items for pairs (query, shortcut key). *)
1356 let user_queries_items menu_name item_name l =
1357 let mk_item (query, key) =
1358 let callback = Query.query query in
1359 let accel = if not (CString.is_empty key) then
1360 Some (modifier_for_queries#get^key) else None in
1361 item (item_name^" "^(no_under query)) ~label:query ?accel ~callback menu_name
1362 in
1363 List.iter mk_item l
1364
1365 let emit_to_focus window sgn =
1366 let focussed_widget = GtkWindow.Window.get_focus window#as_window in
1367 let obj = Gobject.unsafe_cast focussed_widget in
1368 try GtkSignal.emit_unit obj ~sgn with _ -> ()
1369
1370 (** {2 Creation of the main rocqide window } *)
1371
1372 let build_ui () =
1373 (* issue 12779 *)
1374 GtkData.StyleContext.add_provider_for_screen
1375 (Gdk.Screen.default ())
1376 begin
1377 let provider = GObj.css_provider () in
1378 provider#load_from_data "button { box-shadow: none }";
1379 provider#as_css_provider
1380 end
1381 GtkData.StyleContext.ProviderPriority.application;
1382
1383 let w = GWindow.window
1384 ~wmclass:("RocqIDE","RocqIDE")
1385 ~width:window_width#get ~height:window_height#get
1386 ~title:"RocqIDE" ()
1387 in
1388 let () =
1389 try w#set_icon (Some (GdkPixbuf.from_file (MiscMenu.rocq_icon ())))
1390 with _ -> ()
1391 in
1392 let _ = w#event#connect#delete ~callback:(fun _ -> File.quit ~parent:w (); true) in
1393 let _ = w#misc#connect#size_allocate
1394 ~callback:(fun rect -> window_size := (rect.Gtk.width, rect.Gtk.height)) in
1395 let _ = set_drag w#drag in
1396
1397 let vbox = GPack.vbox ~homogeneous:false ~packing:w#add () in
1398
1399 let file_menu = GAction.action_group ~name:"File" () in
1400 let edit_menu = GAction.action_group ~name:"Edit" () in
1401 let view_menu = GAction.action_group ~name:"View" () in
1402 let export_menu = GAction.action_group ~name:"Export" () in
1403 let navigation_menu = GAction.action_group ~name:"Navigation" () in
1404 let templates_menu = GAction.action_group ~name:"Templates" () in
1405 let tools_menu = GAction.action_group ~name:"Tools" () in
1406 let queries_menu = GAction.action_group ~name:"Queries" () in
1407 let compile_menu = GAction.action_group ~name:"Compile" () in
1408 let debug_menu = GAction.action_group ~name:"Debug" () in
1409 let windows_menu = GAction.action_group ~name:"Windows" () in
1410 let help_menu = GAction.action_group ~name:"Help" () in
1411 let all_menus = [
1412 file_menu; edit_menu; view_menu; export_menu; navigation_menu;
1413 templates_menu; tools_menu; queries_menu; compile_menu; debug_menu; windows_menu;
1414 help_menu; ] in
1415
1416 menu file_menu [
1417 item "File" ~label:"_File";
1418 item "New" ~callback:File.newfile ~stock:`NEW;
1419 item "Open" ~callback:(File.load ~parent:w) ~stock:`OPEN ~tooltip:"Open file";
1420 item "Save" ~callback:(File.save ~parent:w) ~stock:`SAVE ~tooltip:"Save current buffer";
1421 item "Save as" ~stock:`SAVE_AS ~callback:(File.saveas ~parent:w);
1422 item "Save all" ~label:"Sa_ve all" ~callback:File.saveall;
1423 item "Close buffer" ~label:"_Close buffer" ~stock:`CLOSE
1424 ~callback:(File.close_buffer ~parent:w) ~tooltip:"Close current buffer";
1425 item "Print..." ~label:"_Print..." ~accel:"<Primary>p"
1426 ~callback:File.print ~stock:`PRINT;
1427 item "Rehighlight" ~label:"Re_highlight" ~accel:"<Primary>l"
1428 ~callback:File.highlight ~stock:`REFRESH;
1429 item "Quit" ~stock:`QUIT ~callback:(File.quit ~parent:w);
1430 ];
1431
1432 menu export_menu [
1433 item "Export to" ~label:"E_xport to";
1434 item "Html" ~label:"_HTML" ~callback:(File.export "html");
1435 item "Latex" ~label:"_LaTeX" ~callback:(File.export "latex");
1436 item "Dvi" ~label:"_DVI" ~callback:(File.export "dvi");
1437 item "Pdf" ~label:"_PDF" ~callback:(File.export "pdf");
1438 item "Ps" ~label:"P_ostScript" ~callback:(File.export "ps");
1439 ];
1440
1441 menu edit_menu [
1442 item "Edit" ~label:"_Edit";
1443 item "Undo" ~accel:"<Primary>z" ~stock:`UNDO
1444 ~callback:(cb_on_current_term (fun t -> t.script#undo ()));
1445 item "Redo" ~accel:"<Primary><Shift>z" ~stock:`REDO
1446 ~callback:(cb_on_current_term (fun t -> t.script#redo ()));
1447 item "Select All" ~accel:"<Primary>a" ~stock:`SELECT_ALL
1448 ~callback:(cb_on_current_term (fun t ->
1449 t.script#select_all ();
1450 t.proof#select_all ();
1451 t.messages#select_all ();
1452 t.debugger#select_all ()));
1453 item "Cut" ~stock:`CUT
1454 ~callback:(fun _ -> emit_to_focus w GtkText.View.S.cut_clipboard);
1455 item "Copy" ~stock:`COPY
1456 ~callback:(fun _ -> emit_to_focus w GtkText.View.S.copy_clipboard);
1457 item "Paste" ~stock:`PASTE
1458 ~callback:(fun _ -> emit_to_focus w GtkText.View.S.paste_clipboard);
1459 item "Find" ~stock:`FIND ~label:"Find / Replace"
1460 ~callback:(cb_on_current_term (fun t -> t.finder#show ()));
1461 item "Find Next" ~label:"Find _Next" ~stock:`GO_DOWN ~accel:"F3"
1462 ~callback:(cb_on_current_term (fun t -> t.finder#find_forward ()));
1463 item "Find Previous" ~label:"Find _Previous" ~stock:`GO_UP
1464 ~accel:"<Shift>F3"
1465 ~callback:(cb_on_current_term (fun t -> t.finder#find_backward ()));
1466 item "External editor" ~label:"External editor" ~stock:`EDIT
1467 ~callback:(External.editor ~parent:w);
1468 item "Preferences" ~accel:"<Primary>comma" ~stock:`PREFERENCES
1469 ~callback:(fun _ ->
1470 begin
1471 try Preferences_ui.configure ~apply:refresh_notebook_pos w
1472 with e ->
1473 flash_info ("Editing preferences failed (" ^ Printexc.to_string e ^ ")")
1474 end;
1475 reset_reload_timer ());
1476 ];
1477
1478 menu view_menu [
1479 item "View" ~label:"_View";
1480 item "Previous tab" ~label:"_Previous tab" ~accel:"<Primary>Page_Up"
1481 ~stock:`GO_BACK
1482 ~callback:(fun _ -> notebook#previous_page ());
1483 item "Next tab" ~label:"_Next tab" ~accel:"<Primary>Page_Down"
1484 ~stock:`GO_FORWARD
1485 ~callback:(fun _ -> notebook#next_page ());
1486 item "Zoom in" ~accel:("<Primary>plus")
1487 ~stock:`ZOOM_IN ~callback:(fun _ ->
1488 let ft = Pango.Font.from_string text_font#get in
1489 Pango.Font.set_size ft (Pango.Font.get_size ft + Pango.scale);
1490 text_font#set (Pango.Font.to_string ft);
1491 save_pref ());
1492 item "Zoom out" ~accel:("<Primary>minus")
1493 ~stock:`ZOOM_OUT ~callback:(fun _ ->
1494 let ft = Pango.Font.from_string text_font#get in
1495 Pango.Font.set_size ft (Pango.Font.get_size ft - Pango.scale);
1496 text_font#set (Pango.Font.to_string ft);
1497 save_pref ());
1498 item "Zoom fit" ~accel:("<Primary>0")
1499 ~stock:`ZOOM_FIT ~callback:(cb_on_current_term MiscMenu.zoom_fit);
1500 toggle_item "Show Toolbar" ~label:"Show _Toolbar"
1501 ~active:(show_toolbar#get)
1502 ~callback:(fun _ -> show_toolbar#set (not show_toolbar#get));
1503 item "Query Pane" ~label:"_Query Pane" ~accel:"F2"
1504 ~callback:(cb_on_current_term MiscMenu.show_hide_query_pane);
1505 GAction.group_radio_actions
1506 ~init_value:(
1507 let v = diffs#get in
1508 List.iter (fun o -> Opt.set o v) Opt.diff_item.Opt.opts;
1509 match v with "on" -> 1 | "removed" -> 2 | _ -> 0)
1510 ~callback:begin fun n ->
1511 (match n with
1512 | 0 -> List.iter (fun o -> Opt.set o "off"; diffs#set "off") Opt.diff_item.Opt.opts
1513 | 1 -> List.iter (fun o -> Opt.set o "on"; diffs#set "on") Opt.diff_item.Opt.opts
1514 | 2 -> List.iter (fun o -> Opt.set o "removed"; diffs#set "removed") Opt.diff_item.Opt.opts
1515 | _ -> assert false);
1516 send_to_rocq (fun sn -> sn.rocqops#show_goals)
1517 end
1518 [
1519 radio "Unset diff" 0 ~label:"_Don't show diffs";
1520 radio "Set diff" 1 ~label:"Show diffs: only _added";
1521 radio "Set removed diff" 2 ~label:"Show diffs: added and _removed";
1522 ];
1523 item "Show Proof Diffs" ~label:"_Show Proof (with diffs, if set)" ~accel:"<Shift>F2"
1524 ~callback:MiscMenu.show_proof_diffs;
1525 ];
1526 printopts_items view_menu RocqDriver.PrintOpt.bool_items;
1527
1528 let navitem (text, label, stock, callback, tooltip, accel) =
1529 let accel = modifier_for_navigation#get ^ accel in
1530 item text ~label ~stock ~callback ~tooltip ~accel
1531 in
1532 menu navigation_menu begin
1533 [
1534 (fun e -> item "Navigation" ~label:"_Navigation" e);
1535 ] @ List.map navitem [
1536 ("Forward", "_Forward", `GO_DOWN, Nav.forward_one, "Forward one command", "Down");
1537 ("Backward", "_Backward", `GO_UP, Nav.backward_one, "Backward one command", "Up");
1538 ("Run to cursor", "Run to _cursor", `JUMP_TO, Nav.run_to_cursor, "Run to cursor", "Right");
1539 ("Reset", "_Reset", `GOTO_TOP, Nav.restart, "Reset Rocq", "Home");
1540 ("Run to end", "_Run to end", `GOTO_BOTTOM, Nav.run_to_end, "Run to end", "End");
1541 ("Fully check", "_Fully check", `EXECUTE, Nav.join_document, "Fully check the document", "Return");
1542 ("Interrupt", "_Interrupt", `STOP, Nav.interrupt, "Interrupt computations", "Break");
1543 (* wait for this available in GtkSourceView !
1544 ("Hide", "_Hide", `MISSING_IMAGE,
1545 ~callback:(fun _ -> let sess = notebook#current_term in
1546 toggle_proof_visibility sess.buffer sess.analyzed_view#get_insert), "Hide proof", "h"); *)
1547 ("Previous", "_Previous occurrence", `GO_BACK, Nav.previous_occ,
1548 "Previous occurrence of word under cursor", "less");
1549 ("Next", "_Next occurrence", `GO_FORWARD, Nav.next_occ,
1550 "Next occurrence of word under cursor", "greater");
1551 ] end;
1552
1553 menu templates_menu [
1554 item "Templates" ~label:"Te_mplates";
1555 template_item ("Lemma new_lemma : .\nProof.\n\nQed.\n", 6,9, "J");
1556 template_item ("Theorem new_theorem : .\nProof.\n\nQed.\n", 8,11, "T");
1557 template_item ("Definition ident := .\n", 11,5, "E");
1558 template_item ("Inductive ident : :=\n | : .\n", 10,5, "I");
1559 template_item ("Fixpoint ident (_ : _) {struct _} : _ :=\n.\n", 9,5, "F");
1560 template_item ("Scheme new_scheme := Induction for _ Sort _\n" ^
1561 "with _ := Induction for _ Sort _.\n", 7,10, "S");
1562 item "match" ~label:"match ..." ~accel:(modifier_for_templates#get^"M")
1563 ~callback:match_callback
1564 ];
1565 alpha_items templates_menu "Template" Rocq_commands.commands;
1566
1567 let qitem s sc =
1568 let query = s ^ "..." in
1569 item s ~label:("_"^s)
1570 ~accel:(modifier_for_queries#get^sc)
1571 ~callback:(Query.query query)
1572 in
1573 menu queries_menu [
1574 item "Queries" ~label:"_Queries";
1575 qitem "Search" "K";
1576 qitem "Check" "C";
1577 qitem "Print" "P";
1578 qitem "About" "A";
1579 qitem "Locate" "L";
1580 qitem "Print Assumptions" "N";
1581 ];
1582 user_queries_items queries_menu "User-Query" user_queries#get;
1583
1584 menu tools_menu [
1585 item "Tools" ~label:"_Tools";
1586 item "Comment" ~label:"_Comment" ~accel:"<Primary>D"
1587 ~callback:(cb_on_current_term (fun t -> t.script#comment ()));
1588 item "Uncomment" ~label:"_Uncomment" ~accel:"<Primary><Shift>D"
1589 ~callback:(cb_on_current_term (fun t -> t.script#uncomment ()));
1590 item "Coqtop arguments" ~label:"Coqtop _arguments"
1591 ~callback:MiscMenu.rocqtop_arguments;
1592 item "LaTeX-to-unicode" ~label:"_LaTeX-to-unicode" ~accel:"<Shift>space"
1593 ~callback:MiscMenu.apply_unicode_binding;
1594 ];
1595
1596 menu compile_menu [
1597 item "Compile" ~label:"_Compile";
1598 item "Compile buffer" ~label:"_Compile buffer" ~callback:External.compile;
1599 item "Make" ~label:"_Make" ~accel:"F6"
1600 ~callback:External.make;
1601 item "Next error" ~label:"_Next error" ~accel:"F7"
1602 ~callback:External.next_error;
1603 item "Make makefile" ~label:"Make makefile" ~callback:External.rocq_makefile;
1604 ];
1605
1606 menu debug_menu [
1607 item "Debug" ~label:"_Debug";
1608 item "Toggle breakpoint" ~label:"_Toggle breakpoint" ~accel:"F8" ~stock:`MEDIA_RECORD
1609 ~callback:MiscMenu.toggle_breakpoint;
1610 item "Continue" ~label:"_Continue" ~accel:"F9" ~stock:`MEDIA_NEXT ~callback:Nav.continue;
1611 item "Step in" ~label:"Step in" ~accel:"F10" ~stock:`MEDIA_PLAY ~callback:Nav.step_in;
1612 item "Step out" ~label:"Step out" ~accel:"<Shift>F10" ~stock:`MEDIA_FORWARD ~callback:Nav.step_out;
1613 (* todo: consider other names for Break and Interrupt to be clearer to users *)
1614 item "Break" ~label:"Break" ~accel:"F11" ~stock:`MEDIA_PAUSE ~callback:Nav.break;
1615 item "Show debug panel" ~label:"Show debug panel" ~callback:Nav.show_debugger;
1616 ];
1617
1618 menu windows_menu [
1619 item "Windows" ~label:"_Windows";
1620 item "Detach Proof" ~label:"Detach _Proof" ~callback:MiscMenu.detach_view
1621 ];
1622
1623 menu help_menu [
1624 item "Help" ~label:"_Help";
1625 item "Browse Coq Manual" ~label:"Browse Coq _Manual" ~accel:"<Shift>F1" ~stock:`HELP
1626 ~callback:(fun _ ->
1627 browse notebook#current_term.messages#default_route#add_string Coq_config.wwwrefman);
1628 item "Browse Coq Library" ~label:"Browse Coq _Library" ~accel:"<Primary><Shift>F1" ~stock:`HELP
1629 ~callback:(fun _ ->
1630 browse notebook#current_term.messages#default_route#add_string Coq_config.wwwstdlib);
1631 item "Help for keyword" ~label:"Help for _keyword" ~accel:"F1"
1632 ~callback:(fun _ -> on_current_term (fun sn ->
1633 browse_keyword sn.messages#default_route#add_string (get_current_word sn)));
1634 item "Help for μPG mode" ~label:"Help for μPG mode"
1635 ~callback:(fun _ -> on_current_term (fun sn ->
1636 sn.messages#default_route#clear;
1637 sn.messages#default_route#add_string (MicroPG.get_documentation ())));
1638 item "About Coq" ~label:"_About" ~stock:`ABOUT
1639 ~callback:MiscMenu.about
1640 ];
1641
1642 Rocqide_ui.init ();
1643 Rocqide_ui.ui_m#insert_action_group file_menu 0;
1644 Rocqide_ui.ui_m#insert_action_group export_menu 0;
1645 Rocqide_ui.ui_m#insert_action_group edit_menu 0;
1646 Rocqide_ui.ui_m#insert_action_group view_menu 0;
1647 Rocqide_ui.ui_m#insert_action_group navigation_menu 0;
1648 Rocqide_ui.ui_m#insert_action_group templates_menu 0;
1649 Rocqide_ui.ui_m#insert_action_group tools_menu 0;
1650 Rocqide_ui.ui_m#insert_action_group queries_menu 0;
1651 Rocqide_ui.ui_m#insert_action_group compile_menu 0;
1652 Rocqide_ui.ui_m#insert_action_group debug_menu 0;
1653 Rocqide_ui.ui_m#insert_action_group windows_menu 0;
1654 Rocqide_ui.ui_m#insert_action_group help_menu 0;
1655 w#add_accel_group Rocqide_ui.ui_m#get_accel_group ;
1656 GtkMain.Rc.parse_string "gtk-can-change-accels = 1";
1657 if Config.gtk_platform <> `QUARTZ
1658 then vbox#pack (Rocqide_ui.ui_m#get_widget "/RocqIDE MenuBar");
1659
1660 (* Connect some specific actions *)
1661 let unicode = Rocqide_ui.ui_m#get_action "ui/RocqIDE MenuBar/Tools/LaTeX-to-unicode" in
1662 let callback b = unicode#set_sensitive b in
1663 let () = callback unicode_binding#get in
1664 let _ = unicode_binding#connect#changed ~callback in
1665
1666 (* Toolbar *)
1667 let tbar = GtkButton.Toolbar.cast
1668 ((Rocqide_ui.ui_m#get_widget "/RocqIDE ToolBar")#as_widget)
1669 in
1670 let () = GtkButton.Toolbar.set
1671 ~orientation:`HORIZONTAL ~style:`ICONS tbar
1672 in
1673 let toolbar = new GButton.toolbar tbar in
1674 let () = vbox#pack toolbar#coerce in
1675
1676 (* Emacs/PG mode *)
1677 MicroPG.init w notebook all_menus;
1678
1679 (* On tab switch, reset, update location *)
1680 let _ = notebook#connect#switch_page ~callback:(fun n ->
1681 let _ = if reset_on_tab_switch#get then Nav.restart () in
1682 try
1683 let session = notebook#get_nth_term n in
1684 let ins = session.buffer#get_iter_at_mark `INSERT in
1685 Ideutils.display_location ins
1686 with _ -> ())
1687 in
1688
1689 (* Vertical Separator between Scripts and Goals *)
1690 let () = vbox#pack ~expand:true notebook#coerce in
1691 let () = refresh_notebook_pos () in
1692 let lower_hbox = GPack.hbox ~homogeneous:false ~packing:vbox#pack () in
1693 let () = lower_hbox#pack ~expand:true status#coerce in
1694
1695 (* Location display *)
1696 let l = GMisc.label
1697 ~text:"Line: 1 Char: 1 Offset: 0"
1698 ~packing:lower_hbox#pack ()
1699 in
1700 let () = l#coerce#misc#set_name "location" in
1701 let () = set_location := l#set_text in
1702
1703 (* Progress Bar *)
1704 let pbar = GRange.progress_bar ~pulse_step:0.1 () in
1705 let () = lower_hbox#pack pbar#coerce in
1706 let ready () = pbar#set_fraction 0.0 in
1707 let pulse sn =
1708 if RocqDriver.is_stopped_in_debugger sn.rocqtop then
1709 (pbar#set_pulse_step 0.0; pbar#pulse ()) (* stops slider at left end, not ideal *)
1710 else if RocqDriver.is_computing sn.rocqtop then
1711 (pbar#set_pulse_step 0.1; pbar#pulse ())
1712 else ready () in
1713 let callback () = on_current_term pulse; true in
1714 let _ = Glib.Timeout.add ~ms:300 ~callback in
1715
1716 (* Pending proofs. It should be with a GtkSpinner... not bound *)
1717 let slaveinfo = GMisc.label ~xalign:0.5 ~width:50 () in
1718 let () = lower_hbox#pack slaveinfo#coerce in
1719 let () = slaveinfo#misc#set_has_tooltip true in
1720 let () = slaveinfo#misc#set_tooltip_markup
1721 "Proofs to be checked / Errors" in
1722 let update sn =
1723 let processed, to_process, jobs = sn.rocqops#get_slaves_status in
1724 let missing = to_process - processed in
1725 let n_err = sn.rocqops#get_n_errors in
1726 if n_err > 0 then
1727 slaveinfo#set_text (Printf.sprintf
1728 "%d / <span foreground=\"#FF0000\">%d</span>" missing n_err)
1729 else
1730 slaveinfo#set_text (Printf.sprintf "%d / %d" missing n_err);
1731 slaveinfo#set_use_markup true;
1732 sn.warnpage#update sn.rocqops#get_warnings;
1733 sn.errpage#update sn.rocqops#get_errors;
1734 sn.jobpage#update (Util.pi3 sn.rocqops#get_slaves_status) in
1735 let callback () = on_current_term update; true in
1736 let _ = Glib.Timeout.add ~ms:300 ~callback in
1737
1738 (* Initializing hooks *)
1739 let refresh_style style =
1740 let style = style_manager#style_scheme style in
1741 let iter_session v =
1742 v.script#source_buffer#set_style_scheme style;
1743 v.proof#source_buffer#set_style_scheme style;
1744 v.messages#default_route#source_buffer#set_style_scheme style in
1745 List.iter iter_session notebook#pages
1746 in
1747 let refresh_language lang =
1748 let lang = lang_manager#language lang in
1749 let iter_session v = v.script#source_buffer#set_language lang in
1750 List.iter iter_session notebook#pages
1751 in
1752 let refresh_toolbar b =
1753 if b then toolbar#misc#show () else toolbar#misc#hide ()
1754 in
1755 stick show_toolbar toolbar refresh_toolbar;
1756 let _ = source_style#connect#changed ~callback:refresh_style in
1757 let _ = source_language#connect#changed ~callback:refresh_language in
1758
1759 (* Showtime ! *)
1760 w#show ();
1761 w
1762
1763
1764 (** {2 Rocqide main function } *)
1765
1766 let make_file_buffer f =
1767 let f = if Filename.check_suffix f ".v" then f else f^".v" in
1768 FileAux.load_file ~maycreate:true f
1769
1770 let make_scratch_buffer () =
1771 let session = create_session None in
1772 let _ = notebook#append_term session in
1773 ()
1774
1775 let main files =
1776 let w = build_ui () in
1777 reset_reload_timer ();
1778 reset_autosave_timer ();
1779 (match files with
1780 | [] -> make_scratch_buffer ()
1781 | _ -> List.iter make_file_buffer files);
1782 notebook#goto_page 0;
1783 MiscMenu.initial_about ();
1784 on_current_term (fun t -> t.script#misc#grab_focus ());
1785 Minilib.log "End of Rocqide.main";
1786 w
1787
1788 (** {2 Argument parsing } *)
1789
1790 (** By default, the rocqtop we try to launch is exactly the current rocqide
1791 full name, with the last occurrence of "rocqide" replaced by "coqtop".
1792 This should correctly handle the ".opt", ".byte", ".exe" situations.
1793 If the replacement fails, we default to "coqtop", hoping it's somewhere
1794 in the path. Note that the -coqtop option to rocqide overrides
1795 this default coqtop path *)
1796
1797 let rocqide_specific_usage = Boot.Usage.{
1798 executable_name = "rocqide";
1799 extra_args = "";
1800 extra_options = "\n\
1801 RocqIDE specific options:\
1802 \n -f _CoqProjectFile set _CoqProject file to _CoqProjectFile\
1803 \n -unicode-bindings f1 .. f2 load files f1..f2 with extra unicode bindings\
1804 \n -coqtop dir look for rocqidetop in dir\
1805 \n -coqtop-flags extra flags for the rocqtop subprocess\
1806 \n -debug enable debug mode\
1807 \n -xml-debug enable debug mode and print XML messages to/from RocqIDE\
1808 \n"
1809 }
1810
1811 let read_rocqide_args argv =
1812 let set_debug () =
1813 CDebug.set_debug_all true;
1814 (* CDebug.(set_flag misc false)*)
1815 Minilib.debug := true;
1816 in
1817 let rec filter_rocqtop rocqtop project_files bindings_files out = function
1818 |"-unicode-bindings" :: sfilenames :: args ->
1819 let filenames = Str.split (Str.regexp ",") sfilenames in
1820 filter_rocqtop rocqtop project_files (filenames @ bindings_files) out args
1821 |"-coqtop" :: prog :: args ->
1822 if rocqtop = None then filter_rocqtop (Some prog) project_files bindings_files out args
1823 else (output_string stderr "Error: multiple -coqtop options"; exit 1)
1824 |"-coqtop" :: [] ->
1825 output_string stderr "Error: missing argument after -coqtop"; exit 1
1826 |"-f" :: file :: args ->
1827 if project_files <> None then
1828 (output_string stderr "Error: multiple -f options"; exit 1);
1829 let d = CUnix.canonical_path_name (Filename.dirname file) in
1830 let warning_fn x = Format.eprintf "%s@\n%!" x in
1831 let p = CoqProject_file.read_project_file ~warning_fn file in
1832 filter_rocqtop rocqtop (Some (d,p)) bindings_files out args
1833 |"-f" :: [] ->
1834 output_string stderr "Error: missing project file name"; exit 1
1835 |"-debug"::args ->
1836 set_debug ();
1837 filter_rocqtop rocqtop project_files bindings_files out args
1838 |"-xml-debug"::args ->
1839 set_debug ();
1840 (* xml_debug ref only exists in coqidetop *)
1841 filter_rocqtop rocqtop project_files bindings_files ("-xml-debug"::out) args
1842 |"-coqtop-flags" :: flags :: args->
1843 RocqDriver.ideslave_rocqtop_flags := Some flags;
1844 filter_rocqtop rocqtop project_files bindings_files out args
1845 | ("-v" | "--version") :: _ ->
1846 (* This does the same thing as Usage.version () but printed differently *)
1847 Printf.printf "RocqIDE, version %s\n" Coq_config.version;
1848 (* Unlike rocqtop we don't accumulate queries so we exit immediately *)
1849 exit 0
1850 | ("-h"|"-H"|"-?"|"-help"|"--help") :: _ ->
1851 Boot.Usage.print_usage stderr rocqide_specific_usage;
1852 exit 0
1853 | arg::args when out = [] && CString.is_prefix "-psn_" arg ->
1854 (* argument added by MacOS during .app launch *)
1855 filter_rocqtop rocqtop project_files bindings_files out args
1856 | arg::args -> filter_rocqtop rocqtop project_files bindings_files (arg::out) args
1857 |[] -> (rocqtop,project_files,bindings_files,List.rev out)
1858 in
1859 let rocqtop,project_files,bindings_files,argv = filter_rocqtop None None [] [] argv in
1860 Ideutils.custom_rocqtop := rocqtop;
1861 custom_project_file := project_files;
1862 Unicode_bindings.load_files bindings_files;
1863 argv
1864
1865
1866 (** {2 Signal handling } *)
1867
1868 (** The Ctrl-C (sigint) is handled as a interactive quit.
1869 For most of the other catchable signals we launch
1870 an emergency save of opened files and then exit. *)
1871
1872 let signals_to_crash =
1873 [Sys.sigabrt; Sys.sigalrm; Sys.sigfpe; Sys.sighup;
1874 Sys.sigill; Sys.sigpipe; Sys.sigquit; Sys.sigusr2]
1875
1876 let set_signal_handlers ?parent () =
1877 try
1878 Sys.set_signal Sys.sigint (Sys.Signal_handle (File.quit ?parent));
1879 List.iter
1880 (fun i -> Sys.set_signal i (Sys.Signal_handle FileAux.crash_save))
1881 signals_to_crash
1882 with _ -> Minilib.log "Signal ignored (normal if Win32)"