Mise à jour terminée. Pour connaître les apports de la version 13.8.4 par rapport à notre ancienne version vous pouvez lire les "Release Notes" suivantes :
https://about.gitlab.com/releases/2021/02/11/security-release-gitlab-13-8-4-released/
https://about.gitlab.com/releases/2021/02/05/gitlab-13-8-3-released/

why3ide.ml 57.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
(*  Copyright 2010-2017   --   INRIA - CNRS - Paris-Sud University  *)
(*                                                                  *)
(*  This software is distributed under the terms of the GNU Lesser  *)
(*  General Public License version 2.1, with the special exception  *)
(*  on linking described in file LICENSE.                           *)
(*                                                                  *)
(********************************************************************)

12
open Why3
13
open Format
14
open Gconfig
15
open Stdlib
Sylvain Dailler's avatar
Sylvain Dailler committed
16 17
open Ide_utils
open History
18 19
open Itp_communication
open Itp_server
20

21 22
external reset_gc : unit -> unit = "ml_reset_gc"

23
let debug = Debug.lookup_flag "ide_info"
24
let debug_stack_trace = Debug.lookup_flag "stack_trace"
25

26 27 28 29 30
(***************************)
(* Debugging Json protocol *)
(***************************)


31
(* TODO remove print_request_json and print_notification_json *)
32 33 34 35 36
exception Badparsing

let print_request_json fmt (r: ide_request) =
  (try (
    let s = Pp.string_of Json_util.print_request r in
37
    let x = Json_util.parse_request s in
38 39 40 41 42 43 44
    if r = x then () else raise Badparsing)
  with
    _ -> Format.eprintf "Bad parsing@.");
  Json_util.print_request fmt r

let print_notification_json fmt (n: notification) =
  (try (
45
    let x = Json_util.parse_notification (Pp.string_of Json_util.print_notification n) in
46 47 48 49 50 51 52 53
    if n = x then () else raise Badparsing)
  with
    _ -> Format.eprintf "Bad parsing@.");
  Json_util.print_notification fmt n

let debug_json = Debug.register_flag "json_proto"
    ~desc:"Print@ json@ requests@ and@ notifications@"

Clément Fumex's avatar
Clément Fumex committed
54 55 56
(*******************)
(* server protocol *)
(*******************)
57

58
module Protocol_why3ide = struct
Clément Fumex's avatar
Clément Fumex committed
59 60

  let debug_proto = Debug.register_flag "ide_proto"
61
      ~desc:"Print@ debugging@ messages@ about@ Why3Ide@ protocol@"
Clément Fumex's avatar
Clément Fumex committed
62 63

  let print_request_debug r =
64
    Debug.dprintf debug_proto "[IDE proto] request %a@." print_request r;
65
    Debug.dprintf debug_json "%a@." print_request_json r
Clément Fumex's avatar
Clément Fumex committed
66

Sylvain Dailler's avatar
Sylvain Dailler committed
67
  let print_msg_debug m =
68
    Debug.dprintf debug_proto "[IDE proto] message %a@." print_msg m
Clément Fumex's avatar
Clément Fumex committed
69 70

  let print_notify_debug n =
71
    Debug.dprintf debug_proto "[IDE proto] handling notification %a@." print_notify n;
72
    Debug.dprintf debug_json "%a@." print_notification_json n
Clément Fumex's avatar
Clément Fumex committed
73 74 75 76

  let list_requests: ide_request list ref = ref []

  let get_requests () =
77 78
    let n = List.length !list_requests in
    if n > 0 then
79
      Debug.dprintf debug_proto "[IDE proto] got %d new requests@." n;
Clément Fumex's avatar
Clément Fumex committed
80 81 82 83 84
    let l = List.rev !list_requests in
    list_requests := [];
    l

  let send_request r =
85
    print_request_debug r;
Clément Fumex's avatar
Clément Fumex committed
86 87 88 89 90
    list_requests := r :: !list_requests

  let notification_list: notification list ref = ref []

  let notify n =
91
(* too early, print when handling notifications
Clément Fumex's avatar
Clément Fumex committed
92
    print_notify_debug n;
93
 *)    notification_list := n :: !notification_list
Clément Fumex's avatar
Clément Fumex committed
94 95

  let get_notified () =
96 97 98
    let n = List.length !notification_list in
    if n > 0 then
      Debug.dprintf debug_proto "[IDE proto] got %d new notifications@." n;
Clément Fumex's avatar
Clément Fumex committed
99 100 101
    let l = List.rev !notification_list in
    notification_list := [];
    l
Sylvain Dailler's avatar
Sylvain Dailler committed
102 103 104

end

105 106 107
(* True when session differs from the saved session *)
let session_needs_saving = ref false

Clément Fumex's avatar
Clément Fumex committed
108
let get_notified = Protocol_why3ide.get_notified
Sylvain Dailler's avatar
Sylvain Dailler committed
109

110 111 112 113 114
let send_request r =
  (* If request changes the session then session needs saving *)
  if modify_session r then
    session_needs_saving := true;
  Protocol_why3ide.send_request r
Sylvain Dailler's avatar
Sylvain Dailler committed
115

Clément Fumex's avatar
Clément Fumex committed
116 117 118
(****************************************)
(* server instance on the GTK scheduler *)
(****************************************)
119

120 121 122 123 124 125 126 127 128 129
(*
   The gtk scheduler is catching all exceptions avoiding the printing of the
   backtrace that is normally done by debug option stack_trace. To recover this
   behavior we catch exceptions ourselves. If "stack_trace" is on, we exit on
   first exception and print backtrace on standard output otherwise we raise
   the exception again (with information on error output).
*)
let backtrace_and_exit f () =
  try f () with
  | e ->
MARCHE Claude's avatar
MARCHE Claude committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143
     if Debug.test_flag debug_stack_trace then
       begin
         Printexc.print_backtrace stderr;
         Format.eprintf "exception '%a' was raised in a LablGtk callback.@."
                        Exn_printer.exn_printer e;
         exit 1
       end
     else
       begin
         Format.eprintf "exception '%a' was raised in a LablGtk callback.@."
                        Exn_printer.exn_printer e;
         Format.eprintf "This should not happen. Please report. @.";
         raise e
       end
144

145
module Scheduler = struct
146

147 148
    let blocking = false

149
    let multiplier = 3
150

Clément Fumex's avatar
Clément Fumex committed
151
    let idle ~prio f =
152
      let (_ : GMain.Idle.id) = GMain.Idle.add ~prio (backtrace_and_exit f) in ()
153

Clément Fumex's avatar
Clément Fumex committed
154
    let timeout ~ms f =
155 156
      let (_ : GMain.Timeout.id) =
        GMain.Timeout.add ~ms ~callback:(backtrace_and_exit f) in ()
Clément Fumex's avatar
Clément Fumex committed
157
end
158

159
module Server = Itp_server.Make (Scheduler) (Protocol_why3ide)
160

Clément Fumex's avatar
Clément Fumex committed
161 162 163
(************************)
(* parsing command line *)
(************************)
164

Clément Fumex's avatar
Clément Fumex committed
165 166 167 168 169 170 171 172
let files : string Queue.t = Queue.create ()
let opt_parser = ref None

let spec = Arg.align [
  "-F", Arg.String (fun s -> opt_parser := Some s),
      "<format> select input format (default: \"why\")";
  "--format", Arg.String (fun s -> opt_parser := Some s),
      " same as -F";
Sylvain Dailler's avatar
Sylvain Dailler committed
173
(*
Clément Fumex's avatar
Clément Fumex committed
174 175 176
  "-f",
   Arg.String (fun s -> input_files := s :: !input_files),
   "<file> add file to the project (ignored if it is already there)";
Sylvain Dailler's avatar
Sylvain Dailler committed
177
*)
Clément Fumex's avatar
Clément Fumex committed
178 179
  Termcode.arg_extra_expl_prefix
]
180

Clément Fumex's avatar
Clément Fumex committed
181 182 183
let usage_str = sprintf
  "Usage: %s [options] [<file.why>|<project directory>]..."
  (Filename.basename Sys.argv.(0))
MARCHE Claude's avatar
MARCHE Claude committed
184

185 186 187
let env, gconfig = try
  let config, base_config, env =
    Whyconf.Args.initialize spec (fun f -> Queue.add f files) usage_str in
Clément Fumex's avatar
Clément Fumex committed
188 189 190
    if Queue.is_empty files then
      Whyconf.Args.exit_with_usage spec usage_str;
    Gconfig.load_config config base_config;
191
    env, Gconfig.config ()
Clément Fumex's avatar
Clément Fumex committed
192 193 194 195 196

  with e when not (Debug.test_flag Debug.stack_trace) ->
    eprintf "%a@." Exn_printer.exn_printer e;
    exit 1

197
(* Initialization of config, provers, task_driver and controller in the server *)
198 199 200 201 202 203 204 205 206 207
let () =
  let dir =
    try
      Server_utils.get_session_dir ~allow_mkdir:true files
    with Invalid_argument s ->
      Format.eprintf "Error: %s@." s;
      Whyconf.Args.exit_with_usage spec usage_str
  in
  Server.init_server gconfig.config env dir;
  Queue.iter (fun f -> send_request (Add_file_req f)) files
208

Clément Fumex's avatar
Clément Fumex committed
209 210 211 212 213 214
let () =
  Debug.dprintf debug "[GUI] Init the GTK interface...@?";
  ignore (GtkMain.Main.init ());
  Debug.dprintf debug " done.@.";
  Gconfig.init ()

MARCHE Claude's avatar
MARCHE Claude committed
215

MARCHE Claude's avatar
MARCHE Claude committed
216 217 218 219
(********************************)
(* Source language highlighting *)
(********************************)

MARCHE Claude's avatar
MARCHE Claude committed
220

MARCHE Claude's avatar
MARCHE Claude committed
221
let (why_lang, any_lang) =
Clément Fumex's avatar
Clément Fumex committed
222 223
  let main = Whyconf.get_main gconfig.config in
  let load_path = Filename.concat (Whyconf.datadir main) "lang" in
MARCHE Claude's avatar
MARCHE Claude committed
224 225 226 227 228 229 230 231
  let languages_manager =
    GSourceView2.source_language_manager ~default:true
  in
  languages_manager#set_search_path
    (load_path :: languages_manager#search_path);
  let why_lang =
    match languages_manager#language "why3" with
    | None ->
Clément Fumex's avatar
Clément Fumex committed
232
        eprintf "language file for 'why3' not found in directory %s@."
MARCHE Claude's avatar
MARCHE Claude committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
          load_path;
        exit 1
    | Some _ as l -> l in
  let any_lang filename =
    match languages_manager#guess_language ~filename () with
    | None -> why_lang
    | Some _ as l -> l in
  (why_lang, any_lang)

(* Borrowed from Frama-C src/gui/source_manager.ml:
Try to convert a source file either as UTF-8 or as locale. *)
let try_convert s =
  try
    if Glib.Utf8.validate s then s else Glib.Convert.locale_to_utf8 s
  with Glib.Convert.Error _ ->
    try
      Glib.Convert.convert_with_fallback
        ~fallback:"#neither UTF-8 nor locale nor ISO-8859-15#"
        ~to_codeset:"UTF-8"
        ~from_codeset:"ISO_8859-15"
        s
    with Glib.Convert.Error _ as e -> Printexc.to_string e

MARCHE Claude's avatar
MARCHE Claude committed
256

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
(****************************)
(* Color handling in source *)
(****************************)

(* For each view, we have to recreate the tags *)
let create_colors v =
  let premise_tag (v: GSourceView2.source_view) = v#buffer#create_tag
      ~name:"premise_tag" [`BACKGROUND gconfig.premise_color] in

  let neg_premise_tag (v: GSourceView2.source_view) = v#buffer#create_tag
      ~name:"neg_premise_tag" [`BACKGROUND gconfig.neg_premise_color] in

  let goal_tag (v: GSourceView2.source_view) = v#buffer#create_tag
      ~name:"goal_tag" [`BACKGROUND gconfig.goal_color] in

  let error_tag (v: GSourceView2.source_view) = v#buffer#create_tag
      ~name:"error_tag" [`BACKGROUND gconfig.error_color] in
  let _ : GText.tag = premise_tag v in
  let _ : GText.tag = neg_premise_tag v in
  let _ : GText.tag = goal_tag v in
  let _ : GText.tag = error_tag v in
  ()

(* Erase all the source location tags in a source file *)
let erase_color_loc (v:GSourceView2.source_view) =
  let buf = v#buffer in
  buf#remove_tag_by_name "premise_tag" ~start:buf#start_iter ~stop:buf#end_iter;
  buf#remove_tag_by_name "neg_premise_tag" ~start:buf#start_iter ~stop:buf#end_iter;
  buf#remove_tag_by_name "goal_tag" ~start:buf#start_iter ~stop:buf#end_iter;
  buf#remove_tag_by_name "error_tag" ~start:buf#start_iter ~stop:buf#end_iter


MARCHE Claude's avatar
MARCHE Claude committed
289

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
(*******************)
(* Graphical tools *)
(*******************)

(* Elements needed for usage of graphical elements *)

(* [quit_on_saved] set to true by exit function to delay quiting after Saved
   notification is received *)
let quit_on_saved = ref false

(* Exit brutally without asking anything *)
let exit_function_unsafe () =
  send_request Exit_req;
  GMain.quit ()

(* Contains a quadruplets (tab page, source_view, file_has_been_modified, label_of_tab):
   - tab_page is a unique number for each pages of the notebook
   - source_view is the graphical element inside a tab
   - has_been_modified is a reference to a boolean stating if the current tab
     source has been modified
   - label_of_tab is the mutable title of the tab
*)
let source_view_table : (int * GSourceView2.source_view * bool ref * GMisc.label) Hstr.t =
  Hstr.create 14

315 316 317
(* The corresponding file does not have a source view *)
exception Nosourceview of string

318 319 320 321 322
let get_source_view_table (file:string) =
  match Hstr.find source_view_table file with
  | v -> v
  | exception Not_found -> raise (Nosourceview file)

323 324 325 326 327 328
(* This returns the source_view of a file *)
let get_source_view (file: string) : GSourceView2.source_view =
  match Hstr.find source_view_table file with
  | (_, v, _, _) -> v
  | exception Not_found -> raise (Nosourceview file)

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
(* Saving function for sources *)
let save_sources () =
  Hstr.iter
    (fun k (_n, (s: GSourceView2.source_view), b, _l) ->
      if !b then
        let text_to_save = s#source_buffer#get_text () in
        send_request (Save_file_req (k, text_to_save))
    )
    source_view_table

(* True if there exist a file which needs saving *)
let files_need_saving () =
  Hstr.fold (fun _k (_, _, b, _) acc -> !b || acc) source_view_table false

(* Ask if the user wants to save session before exit. Exit is then delayed until
   the [Saved] notification is received *)
let exit_function_safe () =
  if not !session_needs_saving && not (files_need_saving ()) then
    exit_function_unsafe ()
  else
    let answer =
      GToolbox.question_box
        ~title:"Why3 saving session and files"
        ~buttons:["Yes"; "No"; "Cancel"]
        "Do you want to save the session and unsaved files?"
    in
    begin
      match answer with
      | 1 -> save_sources(); send_request Save_req; quit_on_saved := true
      | 2 -> exit_function_unsafe ()
      | _ -> ()
    end

(* Update name of the tab when the label changes so that it has a * as prefix *)
let update_label_change (label: GMisc.label) =
  let s = label#text in
  if not (Strings.has_prefix "*" s) then
    label#set_text ("*" ^ s)

(* Update name of the tab when the label is saved. Removes * prefix *)
let update_label_saved (label: GMisc.label) =
  let s = label#text in
  if (Strings.has_prefix "*" s) then
    label#set_text (String.sub s 1 (String.length s - 1))

MARCHE Claude's avatar
MARCHE Claude committed
374

375 376 377
(**********************)
(* Graphical elements *)
(**********************)
378

MARCHE Claude's avatar
MARCHE Claude committed
379

380
let main_window : GWindow.window =
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  let w = GWindow.window
            ~allow_grow:true ~allow_shrink:true
            ~width:gconfig.window_width
            ~height:gconfig.window_height
            ~title:"Why3 Interactive Proof Session" ()
  in
  (* callback to record the new size of the main window when changed, so
   that on restart the window size is the same as the last session *)
  let (_ : GtkSignal.id) =
    w#misc#connect#size_allocate
      ~callback:
      (fun {Gtk.width=w;Gtk.height=h} ->
       gconfig.window_height <- h;
       gconfig.window_width <- w)
  in w

(* the main window contains a vertical box, containing:
398 399
   1. the menu [menubar]
   2. an horizontal box [hb]
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
 *)

let vbox = GPack.vbox ~packing:main_window#add ()

let menubar = GMenu.menu_bar
  ~packing:(vbox#pack ?from:None ?expand:None ?fill:None ?padding:None)
  ()

let hb = GPack.hbox ~packing:vbox#add ()

(* 1. Menu *)

let factory = new GMenu.factory menubar

let accel_group = factory#accel_group

MARCHE Claude's avatar
MARCHE Claude committed
416 417 418 419 420 421 422 423 424 425
let create_menu_item (factory:GMenu.menu GMenu.factory)
                     ?key label tooltip =
  let i = factory#add_item ?key label in
  i#misc#set_tooltip_markup tooltip;
  i

let connect_menu_item i ~callback =
  let (_ : GtkSignal.id) = i#connect#activate ~callback in ()

(* 1.1 "File" menu items *)
MARCHE Claude's avatar
MARCHE Claude committed
426

427 428
let file_menu = factory#add_submenu "_File"
let file_factory = new GMenu.factory file_menu ~accel_group
MARCHE Claude's avatar
MARCHE Claude committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
let menu_add_file =
  create_menu_item file_factory "_Add file to session"
                   "Insert another file in the current session"
let menu_preferences =
  create_menu_item file_factory "_Preferences"
                   "Open Preferences Window"
let menu_refresh =
  create_menu_item file_factory ~key:GdkKeysyms._R "_Refresh session"
                   "Refresh the proof session with updated source files."
let menu_save_session =
  create_menu_item file_factory "_Save session"
                   "Save the current proof session on disk"
let menu_quit =
  create_menu_item file_factory ~key:GdkKeysyms._Q "_Quit"
                   "Quit the interface. See the Preferences for setting the policy on automatic file saving at exit."

(* 1.2 "Tools" menu items *)

let tools_menu = factory#add_submenu "_Tools"
let tools_factory = new GMenu.factory tools_menu ~accel_group

Sylvain Dailler's avatar
Sylvain Dailler committed
450

451 452 453 454 455
let strategies_factory =
  let tools_submenu_strategies = tools_factory#add_submenu "Strategies" in
  let ( _ : GMenu.menu_item) = tools_factory#add_separator () in
  new GMenu.factory tools_submenu_strategies

456 457 458 459
let provers_factory =
  let tools_submenu_provers = tools_factory#add_submenu "Provers" in
  let ( _ : GMenu.menu_item) = tools_factory#add_separator () in
  new GMenu.factory tools_submenu_provers
MARCHE Claude's avatar
MARCHE Claude committed
460

461 462


MARCHE Claude's avatar
MARCHE Claude committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
(* 1.3 "View" menu items *)



(****************************)
(* actions of the interface *)
(****************************)









(***********************************)
(* connection of actions to signals *)
(***********************************)

(* File menu signals *)

let () =
  let callback () =
    Gconfig.preferences gconfig;
    (* TODO:
      begin
        match !current_env_session with
          | None -> ()
          | Some e ->
              Session.update_env_session_config e gconfig.config;
              Session.unload_provers e
      end;
      recreate_gui ();
(*
      Mprover.iter
        (fun p pi ->
          Debug.dprintf debug "editor for %a : %s@." Whyconf.print_prover p
            pi.editor)
        (Whyconf.get_provers gconfig.config);
     *)
     *)
    let nb = gconfig.session_nb_processes in
    send_request (Set_max_tasks_req nb)
  in
  connect_menu_item menu_preferences ~callback

let () =
  connect_menu_item
    menu_save_session
    ~callback:(fun () -> send_request Save_req)
514

MARCHE Claude's avatar
MARCHE Claude committed
515 516 517 518
let () =
  connect_menu_item
    menu_quit
    ~callback:exit_function_safe
519

MARCHE Claude's avatar
MARCHE Claude committed
520 521 522 523 524 525 526
let (_ : GtkSignal.id) =
  main_window#connect#destroy
    ~callback:exit_function_safe

let (_ : GtkSignal.id) =
  main_window#event#connect#delete
    ~callback:(fun _ -> exit_function_safe (); true)
527

528 529
(* 2. horizontal box contains:
   2.1 TODO: a tool box ?
530 531 532
   2.2 a horizontal paned [hp] containing:
     2.2.1 a scrolled window to hold the tree view of the session [scrolledview]
     2.2.2 a vertical paned containing [vpan222]
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
*)

let hp = GPack.paned `HORIZONTAL ~packing:hb#add ()

let scrollview =
  let sv =
    GBin.scrolled_window
      ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
      ~width:gconfig.tree_width ~shadow_type:`ETCHED_OUT
      ~packing:hp#add ()
  in
  let (_ : GtkSignal.id) =
    sv#misc#connect#size_allocate
      ~callback:
      (fun {Gtk.width=w;Gtk.height=_h} ->
       gconfig.tree_width <- w)
  in sv

551
(** {2 view for the session tree} *)
MARCHE Claude's avatar
MARCHE Claude committed
552 553 554 555
let scrolled_session_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT
MARCHE Claude's avatar
MARCHE Claude committed
556
    ~packing:scrollview#add_with_viewport
MARCHE Claude's avatar
MARCHE Claude committed
557 558
    ()

559 560 561 562 563 564 565
(* Vertical pan *)
let vpan222 = GPack.paned `VERTICAL ~packing:hp#add ()

(*  the scrolled window 2.2.1 [scrolled_session_view] contains a GTK tree

*)

566 567
(** {3 the model for tree view} *)

568
let cols = new GTree.column_list
569
(* first column: unique id of the object *)
Clément Fumex's avatar
Clément Fumex committed
570
let node_id_column = cols#add Gobject.Data.int
571 572 573 574 575
(* second column: an icon identifying the object: file,theory, goal, transformation *)
let icon_column = cols#add Gobject.Data.gobject
(* third column: name of the object *)
let name_column = cols#add Gobject.Data.string
(* fourth column: icon status for the object: proved/unproved, unknown, timeout, etc. *)
576
let status_column = cols#add Gobject.Data.gobject
577
(* fifth column: extra status info: time, obsolete status, limits *)
578
let time_column = cols#add Gobject.Data.string
MARCHE Claude's avatar
MARCHE Claude committed
579

580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
(* first view column: icon and name *)
let view_name_column =
  let v = GTree.view_column ~title:"Theories/Goals" () in
  (* icon attribute *)
  let icon_renderer = GTree.cell_renderer_pixbuf [ ] in
  v#pack icon_renderer ;
  v#add_attribute icon_renderer "pixbuf" icon_column;
  let name_renderer = GTree.cell_renderer_text [`XALIGN 0.] in
  v#pack name_renderer;
  v#add_attribute name_renderer "text" name_column;
(*  v#set_sizing `AUTOSIZE; *)
  v#set_resizable true;
  v#set_max_width 500;
  v

(* second view column: status *)
let view_status_column =
  let status_renderer = GTree.cell_renderer_pixbuf [ ] in
  let v = GTree.view_column ~title:"Status"
                            ~renderer:(status_renderer, ["pixbuf", status_column])
                            ()
  in
  v#set_resizable false;
  v#set_visible true;
  v
605 606 607

let view_time_column =
  let renderer = GTree.cell_renderer_text [`XALIGN 0.] in
608 609 610 611 612 613
  let v = GTree.view_column ~title:"Time"
                            ~renderer:(renderer, ["text", time_column]) ()
  in
  v#set_resizable false;
  v#set_visible true;
  v
614

615 616 617 618 619
let goals_model,goals_view =
  Debug.dprintf debug "[GUI] Creating tree model...@?";
  let model = GTree.tree_store cols in
  let view = GTree.view ~model ~packing:scrolled_session_view#add () in
  let () = view#selection#set_mode (* `SINGLE *) `MULTIPLE in
620
(*
621
  let () = view#set_rules_hint true in
622 623
*)
  let () = view#set_enable_search false in
624 625 626
  let _: int = view#append_column view_name_column in
  let _: int = view#append_column view_status_column in
  let _: int = view#append_column view_time_column in
627
  Debug.dprintf debug "[GTK IDE] done@.";
628
  model,view
629

630 631 632 633 634 635 636 637 638 639 640 641

(***********************************)
(* Mapping session to the GTK tree *)
(***********************************)

type pa_status = Controller_itp.proof_attempt_status
      * bool   (* obsolete or not *) (* TODO *)
      * Call_provers.resource_limit

let node_id_type : node_type Hint.t = Hint.create 17
let node_id_proved : bool Hint.t = Hint.create 17
let node_id_pa : pa_status Hint.t = Hint.create 17
642
let node_id_detached : bool Hint.t = Hint.create 17
643 644

let get_node_type id = Hint.find node_id_type id
645 646 647 648 649

let get_node_proved id =
  try Hint.find node_id_proved id
  with Not_found -> false

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
let get_node_id_pa id = Hint.find node_id_pa id

let get_obs (pa_st: pa_status) = match pa_st with
| _, b, _ -> b

let get_proof_attempt (pa_st: pa_status) = match pa_st with
| pa, _, _ -> pa

let get_limit (pa_st: pa_status) = match pa_st with
| _, _, l -> l

let get_node_obs id = get_obs (get_node_id_pa id)
let get_node_proof_attempt id = get_proof_attempt (get_node_id_pa id)
let get_node_limit id = get_limit (get_node_id_pa id)

let get_node_id iter = goals_model#get ~row:iter ~column:node_id_column

(* To each node we have the corresponding row_reference *)
let node_id_to_gtree : GTree.row_reference Hint.t = Hint.create 42
(* TODO exception for those: *)
let get_node_row id = Hint.find node_id_to_gtree id

672 673 674
let get_node_detached id =
  Hint.find node_id_detached id

675 676 677 678 679 680 681 682 683 684 685 686 687 688
(******************************)
(* Initialization of the tree *)
(******************************)

let remove_tree goals_model =
  Hint.iter (fun _x i ->
    try ignore(goals_model#remove (i#iter)) with _ -> ())
    node_id_to_gtree

let clear_tree_and_table goals_model =
  remove_tree goals_model;
  Hint.clear node_id_to_gtree;
  Hint.clear node_id_type;
  Hint.clear node_id_proved;
689 690
  Hint.clear node_id_pa;
  Hint.clear node_id_detached
691 692 693 694 695


(**************)
(* Menu items *)
(**************)
696

697

698 699 700 701 702 703 704
let reload_unsafe () =
  (* Clearing the tree *)
  clear_tree_and_table goals_model;
  send_request Reload_req

(* Same as reload_safe but propose to save edited sources before reload *)
let reload_safe () =
705
  if files_need_saving () then
706 707 708 709
    let answer =
      GToolbox.question_box
        ~title:"Why3 saving source files"
        ~buttons:["Yes"; "No"; "Cancel"]
MARCHE Claude's avatar
MARCHE Claude committed
710
        "Do you want to save modified source files before refresh?\nBeware that unsaved modifications will be discarded."
711 712 713 714 715
    in
    match answer with
    | 1 -> save_sources (); reload_unsafe ()
    | 2 -> reload_unsafe ()
    | _ -> ()
716 717
  else
    reload_unsafe ()
718

MARCHE Claude's avatar
MARCHE Claude committed
719
let () = connect_menu_item menu_refresh ~callback:reload_safe
720

721

Clément Fumex's avatar
Clément Fumex committed
722
(* vpan222 contains:
723
   2.2.2.1 a notebook containing view of the current task, source code etc
724
   2.2.2.2 a vertical pan which contains [vbox2222]
Clément Fumex's avatar
Clément Fumex committed
725
     2.2.2.2.1 the input field to type commands
726
     2.2.2.2.2 a scrolled window to hold the output of the commands
727 728
 *)

729 730 731
(***********************************)
(*    notebook on the top 2.2.2.1  *)
(***********************************)
732

733
(* notebook is composed of a Task page and several source files pages *)
734 735
let notebook = GPack.notebook ~packing:vpan222#add ()

736 737 738
(********************************)
(* Task view (part of notebook) *)
(********************************)
739 740 741 742 743
let task_page,scrolled_task_view =
  let label = GMisc.label ~text:"Task" () in
  0, GPack.vbox ~homogeneous:false ~packing:
    (fun w -> ignore(notebook#append_page ~tab_label:label#coerce w)) ()

744 745 746 747
let scrolled_task_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT
748
    ~packing:scrolled_task_view#add ()
749

750
(* Showing current task *)
751 752 753
let task_view =
  GSourceView2.source_view
    ~editable:false
Clément Fumex's avatar
Clément Fumex committed
754
    ~cursor_visible:false
755 756 757 758
    ~show_line_numbers:true
    ~packing:scrolled_task_view#add
    ()

759
(* Creating a page for source code view *)
760
let create_source_view =
761
  (* Counter for pages *)
762
  let n = ref 2 in
763 764
  (* Create a page with tabname [f] and buffer equal to [content] in the
     notebook. Also add a corresponding page in source_view_table. *)
765 766 767
  let create_source_view f content =
    if not (Hstr.mem source_view_table f) then
      begin
768
        let label = GMisc.label ~text:f () in
769 770
        let source_page, scrolled_source_view =
          !n, GPack.vbox ~homogeneous:false ~packing:
771 772
            (fun w -> ignore(notebook#append_page ~tab_label:label#coerce w)) ()
        in
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
        let scrolled_source_view =
          GBin.scrolled_window
            ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
            ~shadow_type:`ETCHED_OUT
            ~packing:scrolled_source_view#add () in
        let source_view =
          GSourceView2.source_view
            ~auto_indent:true
            ~insert_spaces_instead_of_tabs:true ~tab_width:2
            ~show_line_numbers:true
            ~right_margin_position:80 ~show_right_margin:true
            (* ~smart_home_end:true *)
            ~editable:true
            ~packing:scrolled_source_view#add
            () in
788 789
        let has_changed = ref false in
        Hstr.add source_view_table f (source_page, source_view, has_changed, label);
790 791
        n := !n + 1;
        source_view#source_buffer#set_text content;
792 793 794 795 796 797 798 799 800 801 802
        (* At initialization, file has not changed. When it changes, changes the
           name of the tab and update has_changed boolean. *)
        let (_: GtkSignal.id) = source_view#source_buffer#connect#changed
          ~callback:(fun () ->
            try
              let _source_page, _source_view, has_changed, label =
                Hstr.find source_view_table f in
              update_label_change label;
              has_changed := true;
              ()
            with Not_found -> () ) in
803 804
        Gconfig.add_modifiable_mono_font_view source_view#misc;
        source_view#source_buffer#set_language why_lang;
805 806 807
        (* We have to create the tags for background colors for each view.
           They are not reusable from the other views.  *)
        create_colors source_view;
808 809 810 811 812
        Gconfig.set_fonts ()
      end in
  create_source_view
(* End of notebook *)

813 814 815 816 817
(*
  2.2.2.2 a vertical pan which contains [vbox2222]
    2.2.2.2.1 the input field to type commands [hbox22221]
    2.2.2.2.2 a scrolled window to hold the output of the commands [message_zone]
*)
Clément Fumex's avatar
Clément Fumex committed
818
let vbox2222 = GPack.vbox ~packing:vpan222#add  ()
819

820 821 822 823
(* 2.2.2.2.1 Horizontal box [hbox22221]
     [monitor] number of scheduled/running provers
     [command_entry] Commands to run on the session
*)
824 825 826 827 828 829
let hbox22221 =
  GPack.hbox
    ~packing:(vbox2222#pack ?from:None ?expand:None ?fill:None ?padding:None) ()

let monitor =
  GMisc.label
MARCHE Claude's avatar
MARCHE Claude committed
830
    ~text:"  0/0/0"
831
    ~width:100
MARCHE Claude's avatar
MARCHE Claude committed
832
    ~xalign:0.0
833
    ~packing:(hbox22221#pack ?from:None ?expand:None ?fill:None ?padding:None) ()
834

MARCHE Claude's avatar
MARCHE Claude committed
835 836
let command_entry = GEdit.entry ~packing:hbox22221#add ()

837
(* Part 2.2.2.2.2 contains message returned by the IDE/server *)
MARCHE Claude's avatar
MARCHE Claude committed
838
let message_zone =
839 840 841 842
  let sv = GBin.scrolled_window
      ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
      ~shadow_type:`ETCHED_OUT ~packing:vbox2222#add ()
  in
MARCHE Claude's avatar
MARCHE Claude committed
843
  GText.view ~editable:false ~cursor_visible:false
844 845
    ~packing:sv#add ()

846 847 848 849
(* Create a tag for errors in the message zone. *)
let message_zone_error_tag = message_zone#buffer#create_tag
  ~name:"error" [`BACKGROUND gconfig.neg_premise_color]

850 851 852
(**** Message-zone printing functions *****)

(* Function used to print stuff on the message_zone *)
MARCHE Claude's avatar
MARCHE Claude committed
853
let print_message fmt =
854 855 856 857 858 859
  Format.kfprintf
    (fun _ -> let s = flush_str_formatter () in
              message_zone#buffer#set_text s)
    str_formatter
    fmt

860 861 862 863 864
let add_to_msg_zone s =
  let s = message_zone#buffer#get_text () ^ "\n" ^ s in
  message_zone#buffer#set_text s;
  message_zone#scroll_to_mark `INSERT

865
(**** Monitor *****)
Clément Fumex's avatar
Clément Fumex committed
866

867 868 869 870 871 872 873 874 875 876 877 878 879
let fan n =
  match n mod 4 with
    | 0 -> "|"
    | 1 | -3 -> "\\"
    | 2 | -2 -> "-"
    | 3 | -1 -> "/"
    | _ -> assert false

let update_monitor =
  let c = ref 0 in
  fun t s r ->
  reset_gc ();
  incr c;
MARCHE Claude's avatar
MARCHE Claude committed
880 881 882
  let f = if r=0 then "  " else fan (!c / 2) ^ " " in
  monitor#set_text
    (f ^ (string_of_int t) ^ "/" ^ (string_of_int s) ^ "/" ^ (string_of_int r))
Clément Fumex's avatar
Clément Fumex committed
883

MARCHE Claude's avatar
MARCHE Claude committed
884

885 886 887



888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
(****************************)
(* command entry completion *)
(****************************)

let completion_cols = new GTree.column_list
let completion_col = completion_cols#add Gobject.Data.string
let completion_model = GTree.tree_store completion_cols

let command_entry_completion : GEdit.entry_completion =
  GEdit.entry_completion ~model:completion_model ~minimum_key_length:1 ~entry:command_entry ()

let add_completion_entry s =
  let row = completion_model#append () in
  completion_model#set ~row ~column:completion_col s

903 904 905 906 907 908 909
let match_function s iter =
  let candidate = completion_model#get ~row:iter ~column:completion_col in
  try
    ignore (Str.search_forward (Str.regexp s) candidate 0);
    true
  with Not_found -> false

910
(* see also init_compeltion below *)
911

Sylvain Dailler's avatar
Sylvain Dailler committed
912
(*********************)
913
(* Terminal history  *)
Sylvain Dailler's avatar
Sylvain Dailler committed
914 915
(*********************)

916
let list_commands = create_history()
Sylvain Dailler's avatar
Sylvain Dailler committed
917 918 919

let _ =
  command_entry#event#connect#key_press
920 921 922
    ~callback:(fun (ev: 'a Gdk.event) ->
      match GdkEvent.Key.keyval ev with
      | k when k = GdkKeysyms._Up -> (* Arrow up *)
923 924 925 926 927
          let s = print_next_command list_commands in
          (match s with
          | None -> true
          | Some s ->
              (command_entry#set_text s; true))
928
      | k when k = GdkKeysyms._Down -> (* Arrow down *)
929 930 931 932 933
          let s = print_prev_command list_commands in
          (match s with
          | None -> true
          | Some s ->
              (command_entry#set_text s; true))
Sylvain Dailler's avatar
Sylvain Dailler committed
934 935 936
      | _ -> false
      )

Clément Fumex's avatar
Clément Fumex committed
937 938 939
let () =
  let n = gconfig.session_nb_processes in
  Debug.dprintf debug "[IDE] setting max proof tasks to %d@." n;
940
  send_request (Set_max_tasks_req n)
941

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
(********************)
(* Locations colors *)
(********************)

(* This apply a background [color] on a location given by its file view [v] line
   [l] beginning char [b] and end char [e]. *)
let color_loc (v:GSourceView2.source_view) ~color l b e =
  let buf = v#buffer in
  let top = buf#start_iter in
  let start = top#forward_lines (l-1) in
  let start = start#forward_chars b in
  let stop = start#forward_chars (e-b) in
  buf#apply_tag_by_name ~start ~stop color

let convert_color (color: color): string =
  match color with
  | Neg_premise_color -> "neg_premise_tag"
  | Premise_color -> "premise_tag"
  | Goal_color -> "goal_tag"

962
let move_to_line ~yalign (v : GSourceView2.source_view) line =
963
  let line = max 0 (line - 1) in
964 965 966 967 968 969 970 971 972 973
  let line = min line v#buffer#line_count in
  let it = v#buffer#get_iter (`LINE line) in
  v#buffer#place_cursor ~where:it;
  let mark = `MARK (v#buffer#create_mark it) in
  v#scroll_to_mark ~use_align:true ~yalign mark

(* TODO Do we want an option to choose if we aggressivily switch to the correct
   source location each time we receive locations with task or not *)
let always_scroll = false

974 975 976 977 978
(* Add a color tag on the right locations on the correct file.
   If the file was not open yet, nothing is done *)
let color_loc ~color loc =
  let f, l, b, e = Loc.get loc in
  try
979 980 981 982 983 984 985
    let (n, v, _, _) = get_source_view_table f in
    if color = Goal_color then
      begin
        if always_scroll then
          notebook#goto_page n;
        move_to_line ~yalign:0.0 v l;
      end;
986 987 988 989 990 991 992 993 994 995 996 997 998 999
    let color = convert_color color in
    color_loc ~color v l b e
  with
  | Nosourceview _ ->
      (* If the file is not present do nothing *)
      ()

(* Erase the colors and apply the colors given by l (which come from the task)
   to appropriate source files *)
let apply_loc_on_source (l: (Loc.position * color) list) =
  Hstr.iter (fun _ (_, v, _, _) -> erase_color_loc v) source_view_table;
  List.iter (fun (loc, color) ->
    color_loc ~color loc) l

1000

1001 1002 1003
(*******************)
(* The "View" menu *)
(*******************)
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016

let view_menu = factory#add_submenu "_View"
let view_factory = new GMenu.factory view_menu ~accel_group

(* goals view is not yet multi-selectable
let (_ : GMenu.image_menu_item) =
  view_factory#add_image_item ~key:GdkKeysyms._A
    ~label:"Select all"
    ~callback:(fun () -> goals_view#selection#select_all ()) ()
 *)

let (_ : GMenu.menu_item) =
  view_factory#add_item ~key:GdkKeysyms._plus
Clément Fumex's avatar
Clément Fumex committed
1017
    ~callback:enlarge_fonts "Enlarge font"
1018 1019 1020

let (_ : GMenu.menu_item) =
    view_factory#add_item ~key:GdkKeysyms._minus
Clément Fumex's avatar
Clément Fumex committed
1021
      ~callback:reduce_fonts "Reduce font"
1022 1023 1024 1025 1026

let (_ : GMenu.image_menu_item) =
  view_factory#add_image_item ~key:GdkKeysyms._E
    ~label:"Expand all" ~callback:(fun () -> goals_view#expand_all ()) ()

1027
let collapse_iter iter =
1028 1029 1030
  let path = goals_model#get_path iter in
  goals_view#collapse_row path

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
let rec collapse_proven_goals_from_iter iter =
  let node_id = get_node_id iter in
  let is_proved = get_node_proved node_id in
  if is_proved then
    collapse_iter iter
  else
    let n = goals_model#iter_n_children (Some iter) in
    for i = 0 to (n - 1) do
      collapse_proven_goals_from_iter (goals_model#iter_children ?nth:(Some i) (Some iter))
    done
1041 1042 1043 1044 1045 1046 1047 1048

let collapse_proven_goals () =
  match goals_model#get_iter_first with
  | None -> ()
  | Some root_iter -> collapse_proven_goals_from_iter root_iter

let (_ : GMenu.image_menu_item) =
  view_factory#add_image_item ~key:GdkKeysyms._C
1049
    ~label:"Collapse proven goals" ~callback:(fun () -> collapse_proven_goals ()) ()
1050 1051 1052 1053 1054 1055 1056

let () =
  Gconfig.add_modifiable_sans_font_view goals_view#misc;
  Gconfig.add_modifiable_mono_font_view monitor#misc;
  Gconfig.add_modifiable_mono_font_view task_view#misc;
  Gconfig.add_modifiable_mono_font_view command_entry#misc;
  Gconfig.add_modifiable_mono_font_view message_zone#misc;
MARCHE Claude's avatar
MARCHE Claude committed
1057
  task_view#source_buffer#set_language why_lang;
Clément Fumex's avatar
Clément Fumex committed
1058
  Gconfig.set_fonts ()
1059

MARCHE Claude's avatar
MARCHE Claude committed
1060 1061 1062



1063 1064 1065 1066
(******************)
(*    actions     *)
(******************)

Clément Fumex's avatar
Clément Fumex committed
1067 1068 1069 1070
let get_selected_row_references () =
  List.map
    (fun path -> goals_model#get_row_reference path)
    goals_view#selection#get_selected_rows
1071

1072
(* unused
1073
let rec update_status_column_from_iter cont iter =
Clément Fumex's avatar
Clément Fumex committed
1074
  set_status_column iter;
1075
  match goals_model#iter_parent iter with
1076
  | Some p -> update_status_column_from_iter cont p
1077
  | None -> ()
1078
*)
1079

1080
(* TODO Unused functions. Map these to a key or remove it *)
1081 1082
let move_current_row_selection_up () =
  let current_view = List.hd (goals_view#selection#get_selected_rows) in
1083 1084 1085
  ignore (GTree.Path.up current_view);
  let row_up = goals_model#get_row_reference current_view in
  goals_view#selection#select_iter row_up#iter
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098

let move_current_row_selection_down () =
  let current_iter =
    try
      let current_view = List.hd (goals_view#selection#get_selected_rows) in
      let current_row = goals_model#get_row_reference current_view in
      Some current_row#iter
    with Not_found ->
      None
  in
  let child = goals_model#iter_children current_iter in
  goals_view#selection#select_iter child

1099
let clear_command_entry () = command_entry#set_text ""
MARCHE Claude's avatar
MARCHE Claude committed
1100 1101

let interp cmd =
Clément Fumex's avatar
Clément Fumex committed
1102 1103
  (* TODO: do some preprocessing for queries, or leave everything to server ? *)
  let rows = get_selected_row_references () in
1104 1105 1106 1107
  let ids =
    match rows with
      | [] -> [root_node]
      | _ -> List.map (fun n -> get_node_id n#iter) rows
Clément Fumex's avatar
Clément Fumex committed
1108
  in
1109
  List.iter (fun id -> send_request (Command_req (id, cmd))) ids;
1110
  clear_command_entry ()
MARCHE Claude's avatar
MARCHE Claude committed
1111 1112 1113

let (_ : GtkSignal.id) =
  command_entry#connect#activate
1114 1115
    ~callback:(fun () -> add_command list_commands command_entry#text;
      interp command_entry#text)
1116

1117 1118
let on_selected_row r =
  try
Clément Fumex's avatar
Clément Fumex committed
1119 1120 1121 1122
    let id = get_node_id r#iter in
    let typ = get_node_type id in
    match typ with
    | NGoal ->
1123 1124 1125 1126
      let detached = get_node_detached id in
      if detached then
        task_view#source_buffer#set_text ""
      else
1127
        let b = gconfig.intro_premises in
1128
        send_request (Get_task(id,b, true))
1129 1130 1131 1132 1133
    | NProofAttempt ->
      let (pa, _obs, _l) = Hint.find node_id_pa id in
      (match pa with
      | Controller_itp.Done pr ->
          task_view#source_buffer#set_text pr.Call_provers.pr_output
1134 1135
      | Controller_itp.Detached ->
          task_view#source_buffer#set_text "Detached"
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
      | Controller_itp.Interrupted ->
          task_view#source_buffer#set_text "Interrupted"
      | Controller_itp.Scheduled ->
          task_view#source_buffer#set_text "Scheduled"
      | Controller_itp.Running ->
          task_view#source_buffer#set_text "Running"
      | Controller_itp.InternalFailure _e ->
          task_view#source_buffer#set_text "Internal failure"
      | Controller_itp.Uninstalled _p ->
          task_view#source_buffer#set_text "Uninstalled")
1146 1147
    | _ ->
       let b = gconfig.intro_premises in
1148
       send_request (Get_task(id,b,true))
1149 1150
  with
    | Not_found -> task_view#source_buffer#set_text ""
Clément Fumex's avatar
Clément Fumex committed
1151

1152

1153 1154 1155
let (_ : GtkSignal.id) =
  goals_view#selection#connect#after#changed ~callback:
    (fun () ->
1156
     Debug.dprintf debug "[IDE INFO] running callback of goals_view#selection#connect#after#changed@.";
MARCHE Claude's avatar
MARCHE Claude committed
1157 1158
     begin
       match get_selected_row_references () with
1159
       | [r] -> on_selected_row r;
MARCHE Claude's avatar
MARCHE Claude committed
1160 1161
       | _ -> ()
     end (* ;
1162
     command_entry#misc#grab_focus () *))
1163

1164
let (_ : GtkSignal.id) =
1165
  let callback ev =
1166
    Debug.dprintf debug "[IDE INFO] running callback of goals_view#event#connect#button_press@.";
1167 1168
    let n = GdkEvent.Button.button ev in
    begin
MARCHE Claude's avatar