File: gui.ml

package info (click to toggle)
geneweb 6.08%2Bgit20181019%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 9,460 kB
  • sloc: ml: 75,564; sh: 1,282; makefile: 708; javascript: 485; perl: 27
file content (1455 lines) | stat: -rw-r--r-- 42,223 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
(* $Id: gui.ml,v 1.00 2011-12-25 15:36:35 flh Exp $ *)

open Printf;

type conf =
  { bases_dir : mutable string;
    port : mutable int;
    browser : mutable option string;
    log : mutable string;
    gui_arg : mutable list (string * string);
    gwd_arg : mutable list string;
    only_arg : mutable list string;
    server_running : mutable option int;
    waiting_pids : mutable list int }
;

value bin_dir = "/usr/bin";

value share_dir = "/usr/share/geneweb";

value home_dir =
  try Sys.getenv "HOME" with
  [ Not_found ->
    Sys.getcwd ()]
;

value assistant_default_bases_dir = home_dir;

value trace = ref False;

value default_lang =
  try Sys.getenv "LC_ALL" with
  [ Not_found ->
      try Sys.getenv "LC_MESSAGES" with
      [ Not_found -> try Sys.getenv "LANG" with [ Not_found -> "en" ] ] ]
;

value lang = ref default_lang;
value lexicon_mtime = ref 0.0;

value lexicon_file = Filename.concat share_dir "lang/gui_lex.txt";

value config_gui_file = Filename.concat home_dir ".geneweb-gui-config.txt";

(**/**) (* Gestion du dictionnaire des langues pour GUI. *)

value input_lexicon lang = do {
  let ht = Hashtbl.create 501 in
  Mutil.input_lexicon lang ht (fun () -> open_in lexicon_file);
  ht
};

value unfreeze_lexicon =
  let lexicon = ref None in
  fun lang ->
    if Sys.file_exists lexicon_file then do {
      let stbuf = Unix.stat lexicon_file in
      if stbuf.Unix.st_mtime > lexicon_mtime.val then do {
        lexicon.val := None;
        lexicon_mtime.val := stbuf.Unix.st_mtime;
      }
      else ();
      match lexicon.val with
      [ Some lex -> Some lex
      | None -> do {
          let lex = input_lexicon lang in
          lexicon.val := Some lex;
          Some lex
        } ]
    }
    else None
;

value transl w =
  match unfreeze_lexicon lang.val with
  [ Some lex -> try Hashtbl.find lex w with [ Not_found -> "[" ^ w ^ "]" ]
  | None -> w ]
;

value capitale w = String.capitalize w ;


(**/**) (* Fonctions utiles. *)


value channel_redirector channel callback = do {
  let (cout,cin) = Unix.pipe () in
  Unix.dup2 cin channel ;
  let chan = GMain.Io.channel_of_descr cout in
  let len = 80 in
  let buf = Bytes.create len in
  GMain.Io.add_watch chan ~prio:0 ~cond:[`IN; `HUP; `ERR] ~callback:
    do { fun cond ->
      try
        if List.mem `IN cond then do {
          (* On Windows, you must use Io.read *)
          let len = GMain.Io.read chan ~buf ~pos:0 ~len in
          len >= 1 && (callback (Bytes.sub buf 0 len))
        }
        else False
      with [ _ -> False ]
  }
};


value exec prog args out err =
  Unix.create_process prog (Array.of_list [prog :: args]) Unix.stdin out err
;

value exec_wait conf prog args =
  do {
    let wnd = GWindow.window
      ~title:(capitale (transl "Processing"))
      ~position:`CENTER
      ~resizable:True
      ~width:600 ~height:300 ()
    in
    ignore (wnd#connect#destroy ~callback:(fun _ -> ()));
    wnd#show();
    let vbox = GPack.vbox
      ~spacing:5
      ~packing:wnd#add ()
    in
    let scrolled_window = GBin.scrolled_window ~border_width: 10
      ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
      ~packing:vbox#add ()
    in
    let vvbox = GPack.hbox
      ~border_width: 10
      ~packing:scrolled_window#add_with_viewport ()
    in
    vvbox #focus#set_vadjustment (Some scrolled_window#vadjustment);
    let redirect channel =
      let buffer = GText.buffer () in
      let _text = GText.view ~buffer ~editable:False ~packing:vvbox#add () in
      channel_redirector channel
        (fun c -> do {buffer#insert (Bytes.to_string c); True})
    in
    ignore (redirect Unix.stderr);
    let pid = exec prog args Unix.stdout Unix.stderr in
    (* On voudrait bien attendre la fin du process
       mais sinon wnd ne s'affiche pas ...         *)
    let (_, _) = Unix.waitpid [] pid in
    ()
  }
;

value mkdir_p x =
  loop x where rec loop x =
    do  {
      let y = Filename.dirname x in
      if y <> x && String.length y < String.length x then loop y else ();
      try Unix.mkdir x 0o777 with [ Unix.Unix_error _ _ _ -> () ];
    }
;

value rmdir conf dir =
  (* Récupère tous les fichiers et dossier d'un dossier         *)
  (* et renvoie la liste des dossiers et la liste des fichiers. *)
  let read_files_folders fname =
    let list =
      List.map
        (fun file -> Filename.concat fname file)
        (Array.to_list (Sys.readdir fname))
    in
    List.partition Sys.is_directory list
  in
  (* Parcours récursif de tous les dossiers *)
  let rec loop l folders files =
    match l with
    [ [] -> (folders, files)
    | [x :: l] ->
        let (fd, fi) = read_files_folders x in
        let l = List.rev_append l fd in
        let folders = List.rev_append fd folders in
        let files = List.rev_append fi files in
        loop l folders files ]
  in
  (* Toute l'arborescence de dir *)
  let (folders, files) = loop [dir] [] [] in
  do {
    List.iter (fun f -> try Unix.unlink f with [ _ -> () ]) files;
    List.iter (fun f -> try Unix.rmdir f with [ _ -> () ]) folders;
    try Unix.rmdir dir with [ Unix.Unix_error _ _ _ -> () ]
  }
;

value rec cut_at_equal s =
  try
    let i = String.index s '=' in
    (String.sub s 0 i, String.sub s (succ i) (String.length s - succ i))
  with
  [ Not_found -> (s, "") ]
;

value read_base_env conf bname =
  let fname = Filename.concat conf.bases_dir (bname ^ ".gwf") in
  match try Some (open_in fname) with [ Sys_error _ -> None] with
  [ Some ic ->
      let env =
        loop [] where rec loop env =
          match try Some (input_line ic) with [End_of_file -> None] with
          [ Some s ->
              if s = "" || s.[0] = '#' then loop env
              else loop [cut_at_equal s :: env]
          | None -> List.rev env ]
      in
      do { close_in ic; env }
  | None -> [] ]
;

value write_base_env conf bname env =
  let fname = Filename.concat conf.bases_dir (bname ^ ".gwf") in
  match try Some (open_out fname) with [ Sys_error _ -> None] with
  [ Some oc ->
      do {
        List.iter (fun (k, v) -> fprintf oc "%s=%s\n" k v) env;
        close_out oc
      }
  | None -> () ]
;

value write_config_file conf = do {
  match try Some (open_out config_gui_file) with [ Sys_error _ -> None] with
  [ Some oc ->
      do {
        List.iter (fun (k, v) -> fprintf oc "%s=%s\n" k v) conf.gui_arg;
        close_out oc;
      }
  | None -> () ]
};

value read_config_file () =
  match try Some (open_in config_gui_file) with [ Sys_error _ -> None ] with
  [ Some ic ->
      loop [] where rec loop env =
        match try Some (input_line ic) with [ End_of_file -> None ] with
        [ Some line ->
            let len = String.length line in
            if len = 0 then loop env
            else if line.[0] = '#' then loop env
            else
              let bind =
                try
                  let i = String.index line '=' in
                  (String.sub line 0 i,
                   String.sub line (i + 1) (len - i - 1))
                with
                [ Not_found -> (line, "") ]
              in
              loop [bind :: env]
        | None -> do { close_in ic; env } ]
  | None -> [] ]
;

value config_browser () =
  let default_browsers =
    match Sys.os_type with
    [ "Win32" | "Cygwin" ->
        ["C:\\Program Files\\Mozilla Firefox\\firefox.exe";
         "C:\\Program Files\\Internet Explorer\\iexplore.exe"]
    | _ -> ["/usr/bin/x-www-browser"] ]
  in
  match List.filter Sys.file_exists default_browsers with
  [ [] -> None
  | [b :: l] -> Some b ]
;

value clean_waiting_pids conf =
  conf.waiting_pids :=
    List.filter
      (fun pid ->
         let (r, _) = Unix.waitpid [Unix.WNOHANG] pid in
         let _ =
           do {
             if r = pid then
               do { Printf.eprintf "--- pid ended %d\n" r; flush stderr }
             else ()
           }
         in
         r <> pid)
      conf.waiting_pids
;

value close_server conf =
  match conf.server_running with
  [ Some server_pid -> do {
      clean_waiting_pids conf;
      eprintf "Closing..."; flush stderr;
      (* Making a (empty) file STOP_SERVER to make the server stop. *)
      let (pid, ps) = Unix.waitpid [Unix.WNOHANG] server_pid in
      if pid=0 then
        let stop_server =
          List.fold_left Filename.concat conf.bases_dir ["cnt"; "STOP_SERVER"]
        in
        do {
          let oc = open_out stop_server in
          close_out oc;
          (* Send a phony connection to unblock it. *)
          let s = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
          try
            Unix.connect s (Unix.ADDR_INET Unix.inet_addr_loopback conf.port)
          with [ Unix.Unix_error _ _ _ -> () ];
          try Unix.close s with
            [ Unix.Unix_error _ _ _ -> () ];
          ignore (Unix.waitpid [] server_pid);
          try Sys.remove stop_server with [ Sys_error _ -> () ]
      } else ();
      conf.server_running := None;
      eprintf "\n"; flush stderr;
    }
  | None -> () ]
;


(**/**) (* Autres interfaces graphique ou utilitaires. *)

value select_dir parent initial_dir = do {
  let dialog = GWindow.file_chooser_dialog
    ~action:`SELECT_FOLDER
    ~parent () in
  dialog#add_button_stock `CANCEL `CANCEL ;
  dialog#add_select_button_stock `OPEN `OPEN ;
  let new_dir =
    if dialog#run () = `OPEN then
      match dialog#filename with
      [ Some dir -> dir
      | _ -> initial_dir ]
    else initial_dir
  in
  dialog#destroy ();
  new_dir
};

value select_file parent initial_file = do {
  let dialog = GWindow.file_chooser_dialog
    ~action:`OPEN
    ~parent () in
  dialog#add_button_stock `CANCEL `CANCEL ;
  dialog#add_select_button_stock `OPEN `OPEN ;
  let new_file =
    if dialog#run () = `OPEN then
      match dialog#filename with
      [ Some file -> file
      | _ -> initial_file ]
    else initial_file
  in
  dialog#destroy ();
  new_file
};

value error_popup msg = do {
  let wnd = GWindow.window
    ~title:(capitale (transl "error"))
    ~position:`CENTER
    ~resizable:True ()
  in
  ignore (wnd#connect#destroy ~callback:(fun _ -> ()));
  let vbox = GPack.vbox
    ~spacing:5
    ~packing:wnd#add ()
  in
  let _label = GMisc.label
    ~text:msg
    ~packing:vbox#pack ()
  in
  let bbox = GPack.button_box `HORIZONTAL
    ~border_width: 5
    ~layout: `SPREAD
    ~packing: vbox#pack ()
  in
  let btn_ok = GButton.button
    ~label:(transl "OK")
    ~packing:bbox#pack ()
  in
  ignore (btn_ok#connect#clicked (fun () -> wnd#destroy ()));
  wnd#show ();
};

value display_log conf = do {
  let wnd = GWindow.window
    ~title:(capitale (transl "log"))
    ~position:`CENTER
    ~resizable:True
    ~width:600 ~height:300 ()
  in
  ignore (wnd#connect#destroy ~callback:(fun _ -> ()));
  let vbox = GPack.vbox
    ~spacing:5
    ~packing:wnd#add ()
  in
  let scrolled_window = GBin.scrolled_window ~border_width: 10
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~packing:vbox#add ()
  in
  let vvbox = GPack.hbox
    ~border_width: 10
    ~packing:scrolled_window#add_with_viewport ()
  in
  vvbox #focus#set_vadjustment (Some scrolled_window#vadjustment);
  match try Some (open_in conf.log) with [Sys_error _ -> None] with
  [ Some ic ->
      do {
        let len = in_channel_length ic in
        (* TODO ! *)
        if len > 0 then
          do {
            let buf = Buffer.create len in
            Buffer.add_channel buf ic len;
            let text = GText.view ~packing:vvbox#add () in
            text#buffer#set_text (Buffer.contents buf)
          }
        else ();
        close_in ic;
      }
  | None -> () ];
  let bbox = GPack.button_box `HORIZONTAL
    ~border_width: 5
    ~layout: `EDGE
    ~packing: vbox#pack ()
  in
  let btn_ok = GButton.button
    ~label:(transl "OK")
    ~packing:bbox#pack ()
  in
  ignore (btn_ok#connect#clicked (fun () -> wnd#destroy ()));
  wnd#show();
};

value delete_base conf bname = do {
  let wnd = GWindow.window
    ~title:(capitale (transl "Confirm"))
    ~position:`CENTER
    ~resizable:True
    ~width:300 ~height:50 ()
  in
  let vbox = GPack.vbox
    ~spacing:5
    ~packing:wnd#add ()
  in
  let bbox = GPack.button_box `HORIZONTAL
    ~border_width: 5
    ~layout: `SPREAD
    ~packing: vbox#pack ()
  in
  let btn_cancel = GButton.button
    ~label:(capitale (transl "cancel"))
    ~packing:bbox#pack ()
  in
  ignore (btn_cancel#connect#clicked (fun () -> wnd#destroy ()));
  let btn_ok = GButton.button
    ~label:(transl "OK")
    ~packing:bbox#pack ()
  in
  ignore
    (btn_ok#connect#clicked
      (fun () ->
        do {
          let base = Filename.concat conf.bases_dir (bname ^ ".gwb") in
          rmdir conf base;
          wnd#destroy ();
          (* TODO : revenir sur l'accueil *)
        }));
  wnd#show ();
};


(**/**) (* Autres binaires. *)

value read_error_cmd conf =
  match try Some (open_in conf.log) with [ Sys_error _ -> None ] with
  [ Some ic ->
      loop "" where rec loop msg =
        match try Some (input_line ic) with [ End_of_file -> None ] with
        [ Some line -> loop (msg ^ " " ^ line)
        | None -> do { close_in ic; msg } ]
  | None -> "error reading error_file" ]
;

value browse conf url = do {
  let pid =
    match conf.browser with
    [ Some browser -> exec browser [url] Unix.stdout Unix.stderr
    | None -> -1 ]
  in
  if pid = -1 then error_popup (transl "open url in your favorite browser")
  else conf.waiting_pids := [pid :: conf.waiting_pids];
  clean_waiting_pids conf;
};


(**/**) (* Binaires GeneWeb. *)
(*
   NB: Windows :
   let base = Filename.concat conf.bases_dir bname in
   Plante car il n'interprète pas les chemins avec espaces. On se place
   donc toujours dans le répertoire des bases dans launch_server.
*)

value gwc1 conf bname fname =
  (* Hack Windows, pas de Filename.concat mais juste bname *)
  let prog = Filename.concat bin_dir "gwc1" in
  let args = ["-v"; "-nc"; "-o"; bname] in
  let args = if fname <> "" then [fname :: args] else args in
  exec_wait conf prog args
;

value gwc2 conf bname fname =
  let prog = Filename.concat bin_dir "gwc2" in
  let args = ["-v"; "-nc"; "-o"; bname] in
  let args = if fname <> "" then [fname :: args] else args in
  exec_wait conf prog args
;

value ged2gwb conf bname fname =
  let prog = Filename.concat bin_dir "ged2gwb" in
  let args = ["-nc"; "-o"; bname] in
  let args = if fname <> "" then [fname :: args] else args in
  exec_wait conf prog args
;

value ged2gwb2 conf bname fname =
  let prog = Filename.concat bin_dir "ged2gwb2" in
  let args = ["-nc"; "-o"; bname] in
  let args = if fname <> "" then [fname :: args] else args in
  exec_wait conf prog args
;

value gwb2ged conf bname fname =
  let fname = fname ^ ".ged" in
  let prog = Filename.concat bin_dir "gwb2ged" in
  let args = [bname; "-o"; fname] in
  exec_wait conf prog args
;

value gwu conf bname fname =
  let fname = fname ^ ".gw" in
  let prog = Filename.concat bin_dir "gwu" in
  let args = [bname; "-o"; fname] in
  exec_wait conf prog args
;

value consang conf bname =
  let prog = Filename.concat bin_dir "consang" in
  let args = ["-i"; bname] in
  exec_wait conf prog args
;

value update_nldb conf bname =
  let prog = Filename.concat bin_dir "update_nldb" in
  let args = [bname] in
  (* TODO il faut effacer le fichier avant de le re-créer *)
  (* rm bname/notes_links *)
  exec_wait conf prog args
;

value check_base conf bname =
  let prog = Filename.concat bin_dir "check_base" in
  let args = [bname] in
  exec_wait conf prog args
;


(**/**) (* Fonctions utilies pour les binaires GeneWeb. *)

value print_default_gwf_file conf bname =
  let gwf =
    [ ("# File generated by GeneWeb", "");
      ("access_by_key", "yes");
      ("disable_forum", "yes");
      ("hide_private_names", "no");
      ("use_restrict", "no");
      ("show_consang", "yes");
      ("display_sosa", "yes");
      ("place_surname_link_to_ind", "yes");
      ("max_anc_level", "8");
      ("max_anc_tree", "7");
      ("max_desc_level", "12");
      ("max_desc_tree", "4");
      ("max_cousins", "2000");
      ("max_cousins_level", "5");
      ("latest_event", "20");
      ("template", "*");
      ("long_date", "no");
      ("counter", "no");
      ("full_siblings", "yes");
      ("hide_advanced_request", "no") ]
  in
  let fname = Filename.concat conf.bases_dir (bname ^ ".gwf") in
  if Sys.file_exists fname then ()
  else write_base_env conf bname gwf
;

value create_base conf bname src_file =
  if bname = "" then ()
  else do {
    if src_file = "" then gwc2 conf bname src_file
    else
      let fname = String.lowercase src_file in
      if Filename.check_suffix fname ".gw" then
        gwc2 conf bname src_file
      else if Filename.check_suffix fname ".ged" then
        ged2gwb2 conf bname src_file
      else error_popup (transl "Unknown file");
    let gwf_file = Filename.concat conf.bases_dir (bname ^ ".gwf") in
    if Sys.file_exists gwf_file then ()
    else print_default_gwf_file conf bname
};

value rename_base conf bname new_name =
  let databases =
    List.sort compare
      (List.filter (fun fn -> Filename.check_suffix fn ".gwb")
         (Array.to_list (Sys.readdir conf.bases_dir)))
  in
  let databases = List.map Filename.chop_extension databases in
  if List.mem new_name databases then
    error_popup (capitale (transl "database already exists"))
  else
    let old_base = Filename.concat conf.bases_dir (bname ^ ".gwb") in
    let new_base = Filename.concat conf.bases_dir (new_name ^ ".gwb") in
    try Sys.rename old_base new_base with [ _ -> error_popup "error rename" ]
;

value clean_database conf bname = do {
  gwu conf bname (bname ^ "_save");
  rename_base conf bname (bname ^ "_old");
  let fname = Filename.concat conf.bases_dir (bname ^ "_save.gw") in
  gwc2 conf bname fname;
  consang conf bname;
  update_nldb conf bname;
};

value merge conf bnames bname parameters = do {
  (* TODO : même méthode que clean *)
  List.iter
    (fun bname ->
      let bname = Filename.concat conf.bases_dir (bname ^ ".gwb") in
      let c =
        Filename.concat bin_dir "gwu " ^ bname ^ " -o " ^ bname ^ ".gw"
      in
      let rc = Sys.command c in
      if rc > 1 then error_popup c
      else ())
    bnames;
  let old_bases =
    List.fold_left
      (fun accu bname -> accu ^ " -sep " ^ bname ^ ".gw")
      "" bnames
  in
  let bname = Filename.concat conf.bases_dir bname in
  let c =
    Filename.concat bin_dir "gwc " ^ old_bases ^ " -f -o " ^ bname
  in
  let rc = Sys.command c in
  if rc > 1 then error_popup c
  else ();
};

(* fonctions pour faciliter le transport des bases suite à une mise à jour. *)
(* exporte toutes les bases au formet GW: base_name_date_today.gw *)
(* on copie toutes les base dans le nouveau dossier bases *)
(* on cherche tous les fichiers GW, et on les importe base_name *)
value export_all_bases conf =
  let databases =
    List.sort compare
      (List.filter (fun fn -> Filename.check_suffix fn ".gwb")
         (Array.to_list (Sys.readdir conf.bases_dir)))
  in
  let today = "05_10_2012" in
  List.iter
    (fun s -> gwu conf s (s ^ "_" ^ today))
    databases
;

value import_all_bases conf = ()
;

(**/**) (* UI pratique *)
value tmp_wnd conf bname f = do {
  let wnd = GWindow.window
    ~title:(capitale (transl "confirm"))
    ~position:`CENTER
    ~resizable:True ()
  in
  ignore (wnd#connect#destroy ~callback:(fun _ -> ()));
  let vbox = GPack.vbox
    ~spacing:5
    ~packing:wnd#add ()
  in
  let hbox = GPack.hbox
    ~spacing:5
    ~packing:vbox#pack ()
  in
  let _label = GMisc.label
    ~text:(transl "enter a name")
    ~packing:hbox#pack ()
  in
  let fname = ref "" in
  let entry = GEdit.entry
    ~text:""
    ~packing:(hbox#pack ~expand:False ~fill:False ~padding:5) ()
  in
  ignore (entry#connect#changed (fun () -> fname.val := entry#text));
  let bbox = GPack.button_box `HORIZONTAL
    ~border_width: 5
    ~layout: `SPREAD
    ~packing: vbox#pack ()
  in
  let btn_cancel = GButton.button
    ~label:(capitale (transl "cancel"))
    ~packing:bbox#pack ()
  in
  ignore (btn_cancel#connect#clicked (fun () -> wnd#destroy ()));
  let btn_ok = GButton.button
    ~label:(transl "OK")
    ~packing:bbox#pack ()
  in
  ignore (btn_ok#connect#clicked (fun () -> do {
    wnd#destroy ();
    let fname = if fname.val = "" then "a" else fname.val in
    f conf bname fname }));
  wnd#show ();
};


(**/**) (* Interface graphique. *)

value main_window = do {
  ignore (GMain.init ());
  let wnd = GWindow.window
    ~title:("GeneWeb - " ^ Version.txt)
    ~position:`CENTER
    ~resizable:True
    ~width:640 ~height:480 ()
  in
  (* TODO : faire un close_server *)
  ignore (wnd#connect#destroy ~callback:GMain.quit);
  wnd
};

value rec show_main conf = do {
  ignore
    (main_window#connect#destroy
       ~callback:(fun () -> do {close_server conf; GMain.quit ()}));
  main_window#show ();
  clean_waiting_pids conf;
  let databases =
    List.sort compare
      (List.filter (fun fn -> Filename.check_suffix fn ".gwb")
         (Array.to_list (Sys.readdir conf.bases_dir)))
  in
  let vbox = GPack.vbox
    ~spacing:5
    ~packing:main_window#add ()
  in
  let toolbar = GButton.toolbar
    ~orientation:`HORIZONTAL
    ~style:`BOTH
    ~packing:vbox#pack ()
  in
  let icon name =
    let file =
      List.fold_left Filename.concat share_dir ["images"; name]
    in
    let info = GDraw.pixmap_from_xpm ~file:file () in
    (GMisc.pixmap info ())#coerce
  in
  let inser_toolbar text tooltip icon_file callback =
    toolbar#insert_button
      ~text:text
      ~tooltip:tooltip
      ~tooltip_private:"Private"
      ~icon:(icon icon_file)
      ~callback:callback ()
  in
  ignore
    (inser_toolbar
       (capitale (transl "create")) (capitale (transl "create a database"))
       "gui_create.png" (fun () -> do { vbox#destroy (); new_database conf; }));
  toolbar#insert_space ();
  ignore
    (inser_toolbar
       (capitale (transl "log")) (capitale (transl "view log")) "gui_log.png"
       (fun () -> display_log conf) );
  toolbar#insert_space ();
  ignore
    (inser_toolbar
       (capitale (transl "doc")) (capitale (transl "view doc")) "gui_doc.png"
       (fun () ->
         let url = "http://geneweb.tuxfamily.org/wiki/GeneWeb" in
         ignore (browse conf url)) );
  toolbar#insert_space ();
(* TOTO : gérer le restart
  ignore
    (inser_toolbar
       (capitale (transl "setup")) (capitale (transl "setup GeneWeb"))
       "gui_setup.png" (fun () -> do { vbox#destroy (); setup_gui conf }));
  toolbar#insert_space ();
*)
(*
  inser_toolbar
    (capitale (transl "restart")) (capitale (transl "restart GeneWeb"))
    "gtk.xpm"
    (fun () -> do { vbox#destroy (); close_server conf; launch_server conf });
  toolbar#insert_space ();
*)
  ignore
    (inser_toolbar
       (capitale (transl "quit")) (capitale (transl "quit GeneWeb"))
       "gui_quit.png"
       (fun () -> do { vbox#destroy (); close_server conf; GMain.quit () }));
  if databases = [] then
    ignore
      (GMisc.label
         ~text:(capitale (transl "no databases."))
         ~packing:vbox#pack ())
  else do {
    let _label = GMisc.label
      ~text:((capitale (transl "available databases")) ^
              " (" ^ (string_of_int (List.length databases) ^ "):"))
      ~packing:vbox#pack ()
    in
    let scrolled_window = GBin.scrolled_window ~border_width: 10
      ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
      ~packing:vbox#add () in
    let vvbox = GPack.vbox ~border_width: 10
      ~packing:scrolled_window#add_with_viewport () in
    vvbox #focus#set_vadjustment (Some scrolled_window#vadjustment);
    let table = GPack.table
      ~rows:3
      ~columns:3
      ~row_spacings: 5
      ~col_spacings: 5
      ~packing:vvbox#pack ()
    in
    loop 0 databases where rec loop i =
      fun
      [ [] -> ()
      | [bname :: l] -> do {
           let bn = Filename.chop_extension bname in
           let _label = GMisc.label
             ~text:bn
             ~packing:(table#attach ~left:0 ~top:i) ()
           in
           let bbut = GButton.button
             ~label:(capitale (transl "browse"))
             ~packing:(table#attach ~left:1 ~top:i) ()
           in
           ignore
             (bbut#connect#clicked
               (fun () ->
                 let url =
                   Printf.sprintf "http://localhost:%d/%s" conf.port bn
                 in
                 ignore (browse conf url)));
           let bbut = GButton.button
             ~label:(capitale (transl "tools"))
             ~packing:(table#attach ~left:2 ~top:i) ()
           in
           ignore
             (bbut#connect#clicked
               (fun () -> do { vbox#destroy (); tools conf bn }));
           loop (i+1) l }]
  }
}

and new_database conf = do {
  let vbox = GPack.box `VERTICAL
    ~spacing:5
    ~packing:main_window#add ()
  in
  let table = GPack.table
    ~rows:2
    ~columns:2
    ~row_spacings: 5
    ~col_spacings: 5
    ~packing:vbox#pack ()
  in
  let _label = GMisc.label
    ~text:(capitale (transl "name of the database:"))
    ~packing:(table#attach ~left:0 ~top:0) ()
  in
  let entry = GEdit.entry
    ~text:""
    ~packing:(table#attach ~left:1 ~top:0) ()
  in
  let _label= GMisc.label
    ~text:(capitale (transl "select a file"))
    ~packing:(table#attach ~left:0 ~top:1) ()
  in
  let bbox = GPack.button_box `HORIZONTAL
    ~border_width: 5
    ~layout: `SPREAD
    ~packing: (table#attach ~left:1 ~top:1) ()
  in
  let select = GButton.button
    ~stock:`OPEN
    ~packing:bbox#pack ()
  in
  let file = ref "" in
  ignore
    (select#connect#clicked
       (fun () -> file.val := select_file main_window ""));
  let bbox = GPack.button_box `HORIZONTAL
    ~border_width: 5
    ~layout: `SPREAD
    ~packing: vbox#pack ()
  in
  let btn_cancel = GButton.button
    ~label:(capitale (transl "cancel"))
    ~packing:bbox#pack ()
  in
  ignore
    (btn_cancel#connect#clicked
      (fun () -> do { vbox#destroy (); show_main conf } ) );
  let btn_ok = GButton.button
    ~label:(transl "OK")
    ~packing:bbox#pack ()
  in
  ignore
    (btn_ok#connect#clicked
      (fun () ->
        do {
          create_base conf entry#text file.val;
          vbox#destroy ();
          show_main conf;
        }))
}

and setup_gui conf = do {
  let old_conf =
    { bases_dir = conf.bases_dir; port = conf.port;
      browser = conf.browser; log = conf.log; gui_arg = [];
      gwd_arg = [] ; only_arg = [];
      server_running = conf.server_running;
      waiting_pids = conf.waiting_pids }
  in
  let vbox = GPack.vbox
    ~spacing:5
    ~packing:main_window#add ()
  in
  let _label = GMisc.label
    ~text:(transl "setup GeneWeb")
    ~packing:vbox#pack ()
  in
  let hbox = GPack.hbox
    ~spacing:5
    ~packing:vbox#pack ()
  in
  let _label = GMisc.label
    ~text:("Bases dir : " ^ conf.bases_dir)
    ~packing:hbox#pack ()
  in
  let select = GButton.button
    ~stock:`OPEN
    ~packing:(hbox#pack ~expand:False) ()
  in
  ignore
    (select#connect#clicked
       (fun () -> conf.bases_dir := select_dir main_window conf.bases_dir)) ;
  let hbox = GPack.hbox
    ~spacing:5
    ~packing:vbox#pack ()
  in
  let _label = GMisc.label
    ~text:"Port :"
    ~packing:(hbox#pack ~expand:False ~fill:False ~padding:5) ()
  in
  let entry = GEdit.entry
    ~text:(string_of_int conf.port)
    ~packing:(hbox#pack ~expand:False ~fill:False ~padding:5) ()
  in
  ignore
    (entry#connect#changed
       (fun () -> conf.port := int_of_string entry#text));
  let browser =
    match conf.browser with
    [ Some browser -> browser
    | None -> "" ]
  in
  let hbox = GPack.hbox
    ~spacing:5
    ~packing:vbox#pack ()
  in
  let _label = GMisc.label
    ~text:("Browser : " ^ browser)
    ~packing:hbox#pack ()
  in
  let select = GButton.button
    ~stock:`OPEN
    ~packing:(hbox#pack ~expand:False) ()
  in
  ignore
    (select#connect#clicked
       (fun () ->
         let browser = select_file main_window bin_dir in
         let browser = if browser = "" then None else Some browser in
         conf.browser := browser)) ;
  let bbox = GPack.button_box `HORIZONTAL
    ~border_width: 5
    ~layout: `SPREAD
    ~packing: vbox#pack ()
  in
  let btn_cancel = GButton.button
    ~label:(transl "Cancel")
    ~packing:bbox#pack ()
  in
  ignore
    (btn_cancel#connect#clicked
       (fun () -> do { vbox#destroy (); show_main old_conf } ) ) ;
  let btn_ok = GButton.button
    ~label:(transl "OK")
    ~packing:bbox#pack ()
  in
  ignore
    (btn_ok#connect#clicked
      (fun () -> do {
        vbox#destroy ();
        let browser =
          match conf.browser with
          [ Some b -> b
          | None -> "" ]
        in
        let gui_arg =
          [("bd", conf.bases_dir); ("port", string_of_int conf.port);
           ("browser", browser)]
        in
        let conf = {(conf) with gui_arg = gui_arg} in
        write_config_file conf;
        close_server conf;
        launch_server conf }));
}

and config_gwf conf bname = do {
  let vbox = GPack.vbox
    ~spacing:5
    ~packing:main_window#add ()
  in
  let _label = GMisc.label
    ~text:(transl "Configuration gwf file of " ^ bname)
    ~packing:vbox#pack ()
  in
  let scrolled_window = GBin.scrolled_window ~border_width: 10
      ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
      ~packing:vbox#add () in
  let vvbox = GPack.vbox ~border_width: 10
      ~packing:scrolled_window#add_with_viewport () in
  vvbox #focus#set_vadjustment (Some scrolled_window#vadjustment);
  let hbox = GPack.hbox
    ~spacing:5
    ~packing:vvbox#pack ()
  in
  let vbox_list = GPack.vbox
    ~spacing:5
    ~packing:hbox#pack ()
  in
  let benv = read_base_env conf bname in
  let benv_new = ref (List.map (fun (k, v) -> (k, ref v)) benv) in
  List.iter
    (fun (k, v) ->
      do {
        let hbox = GPack.hbox
          ~spacing:5
          ~packing:vbox_list#pack ()
        in
        let _label = GMisc.label
          ~text: (k ^ " : ")
          ~width: 200
          ~packing:hbox#pack ()
        in
        (*
          TODO :
          si la valeur vaut "yes" ou "no", on ajoute un bouton radio
          sinon on ajoute un champ texte
          if v.val =
        *)
        let entry =
          GEdit.entry
            ~text: v.val
            ~packing:(hbox#pack ~expand:False ~fill:False ~padding:5) ()
        in
        ignore (entry#connect#changed (fun () -> v.val := entry#text))
      } )
    benv_new.val;
  let bbox = GPack.button_box `HORIZONTAL
    ~border_width: 5
    ~layout: `SPREAD
    ~packing: vbox#pack ()
  in
  let btn_cancel = GButton.button
    ~label:(transl "Cancel")
    ~packing:bbox#pack ()
  in
  ignore
    (btn_cancel#connect#clicked
       (fun () -> do { vbox#destroy (); show_main conf } ) );
  let btn_ok = GButton.button
    ~label:(transl "OK")
    ~packing:bbox#pack ()
  in
  ignore
    (btn_ok#connect#clicked
       (fun () -> do {
         let new_benv = List.map (fun (k, v) -> (k, v.val)) benv_new.val in
         write_base_env conf bname new_benv;
         vbox#destroy ();
         show_main conf } ) )
}

and tools conf bname = do {
  let vbox = GPack.vbox
    ~spacing:5
    ~packing:main_window#add ()
  in
  let _label = GMisc.label
    ~text:(transl "toolbox" ^ " " ^ bname)
    ~packing:vbox#pack ()
  in
  let scrolled_window = GBin.scrolled_window ~border_width: 10
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~packing:vbox#add () in
  let vvbox = GPack.hbox ~border_width: 10
    ~packing:scrolled_window#add_with_viewport () in
  vvbox #focus#set_vadjustment (Some scrolled_window#vadjustment);
  let table = GPack.table
    ~rows:2
    ~columns:2
    ~row_spacings: 5
    ~col_spacings: 5
    ~packing:vvbox#pack ()
  in
  let _label = GMisc.label
    ~text:(transl "extract gw file")
    ~packing:(table#attach ~left:0 ~top:0) ()
  in
  let bbut = GButton.button
    ~label:(transl "Extract GW")
    ~packing:(table#attach ~left:1 ~top:0) ()
  in
  ignore (bbut#connect#clicked (fun () -> tmp_wnd conf bname gwu));
  let _label = GMisc.label
    ~text:(transl "extract ged file")
    ~packing:(table#attach ~left:0 ~top:1) ()
  in
  let bbut = GButton.button
    ~label:(transl "Extract GED")
    ~packing:(table#attach ~left:1 ~top:1) ()
  in
  ignore (bbut#connect#clicked (fun () -> tmp_wnd conf bname gwb2ged));
  let _label = GMisc.label
    ~text:(transl "setup base options")
    ~packing:(table#attach ~left:0 ~top:2) ()
  in
  let bbut = GButton.button
    ~label:(transl "setup gwf file")
    ~packing:(table#attach ~left:1 ~top:2) ()
  in
  ignore
    (bbut#connect#clicked
      (fun () -> do { vbox#destroy (); config_gwf conf bname })) ;
  let _label = GMisc.label
    ~text:(transl "Clean database")
    ~packing:(table#attach ~left:0 ~top:3) ()
  in
  let bbut = GButton.button
    ~label:(transl "Clean")
    ~packing:(table#attach ~left:1 ~top:3) ()
  in
  ignore (bbut#connect#clicked (fun () -> clean_database conf bname));
  let _label = GMisc.label
    ~text:(transl "Rename")
    ~packing:(table#attach ~left:0 ~top:4) ()
  in
  let bbut = GButton.button
    ~label:(transl "Rename")
    ~packing:(table#attach ~left:1 ~top:4) ()
  in
  ignore
    (bbut#connect#clicked
       (fun () -> do {
         tmp_wnd conf bname rename_base;
         vbox#destroy ();
         show_main conf}));
  let _label = GMisc.label
    ~text:(transl "Delete")
    ~packing:(table#attach ~left:0 ~top:5) ()
  in
  let bbut = GButton.button
    ~label:(transl "Delete")
    ~packing:(table#attach ~left:1 ~top:5) ()
  in
  ignore (bbut#connect#clicked (fun () -> delete_base conf bname));
(* TODO
  GMisc.label
    ~text:"merge"
    ~packing:(table#attach ~left:0 ~top:0) ();
  let bbut = GButton.button
    ~label:(transl "Merge")
    ~packing:(table#attach ~left:1 ~top:0) ()
  in
  ignore
    (bbut#connect#clicked
      (fun () -> ()));
*)
  let _label = GMisc.label
    ~text:(transl "Consang")
    ~packing:(table#attach ~left:0 ~top:6) ()
  in
  let bbut = GButton.button
    ~label:(transl "Consang")
    ~packing:(table#attach ~left:1 ~top:6) ()
  in
  ignore (bbut#connect#clicked (fun () -> consang conf bname));
  let _label = GMisc.label
    ~text:(transl "Update_nldb")
    ~packing:(table#attach ~left:0 ~top:7) ()
  in
  let bbut = GButton.button
    ~label:(transl "Update_nldb")
    ~packing:(table#attach ~left:1 ~top:7) ()
  in
  ignore (bbut#connect#clicked (fun () -> update_nldb conf bname));
  let bbox = GPack.button_box `HORIZONTAL
    ~border_width: 5
    ~layout: `EDGE
    ~packing: vbox#pack ()
  in
  let btn_cancel = GButton.button
    ~label:(transl "Home")
    ~packing:bbox#pack ()
  in
  ignore
    (btn_cancel#connect#clicked
       (fun () -> do { vbox#destroy (); show_main conf } ) );
}

and launch_server conf = do {
  (* On se place dans le répertoire des bases (obligatoire pour Windows). *)
  Sys.chdir conf.bases_dir;
  clean_waiting_pids conf;
  (* TODO *)
(*
  let cmd_log =
    Unix.openfile conf.log [Unix.O_WRONLY; Unix.O_CREAT; Unix.O_TRUNC] 0o666
  in
*)
  let gwd_log =
    if trace.val then Unix.stdout
    else
      let fname = Filename.concat conf.bases_dir "gwd.log" in
      Unix.openfile fname [Unix.O_WRONLY; Unix.O_CREAT; Unix.O_TRUNC] 0o666
  in
  let stop_server =
    List.fold_left Filename.concat conf.bases_dir ["cnt"; "STOP_SERVER"]
  in
  try Sys.remove stop_server with [ Sys_error _ -> () ];
  let prog = Filename.concat bin_dir "gwd" in
  let args =
    ["-hd"; share_dir; "-bd"; conf.bases_dir; "-lang"; lang.val; "-p"; sprintf "%d" conf.port]
  in
  let server_pid = exec prog args gwd_log gwd_log in
  let (pid, ps) = Unix.waitpid [Unix.WNOHANG] server_pid in
  if pid = 0 then ()
  else do {
    eprintf "Cannot launch the server:";
    eprintf " perhaps another server is running.\n";
    eprintf "You must close it, if you want to try again.\n";
    flush stderr;
    exit 2;
  };
  conf.server_running := Some server_pid;
  show_main conf;
};

value launch_config () =
  if Sys.file_exists config_gui_file then
    let gui_arg = read_config_file () in
    let bases_dir = List.assoc "bd" gui_arg in
    let port = int_of_string (List.assoc "port" gui_arg) in
    let browser = Some (List.assoc "browser" gui_arg) in
    let log = Filename.concat bases_dir "comm.log" in
    let conf =
      { bases_dir = bases_dir;
        port = port; browser = browser; log = log;
        gui_arg = gui_arg; gwd_arg = []; only_arg = [];
        server_running = None; waiting_pids = [] }
    in
    launch_server conf
  else do {
    let assistant = GAssistant.assistant () in
    assistant#misc#set_size_request ~width:450 ~height:300 ();
    assistant#set_title (transl "Setup GeneWeb");
    let page_0 = GMisc.label
      ~text:(transl "This assistant will help you to setup GeneWeb") ()
    in
    let page_0b = GMisc.label
      ~text:(transl "Unlike geneweb and gwsetup, geneweb-gui is designed to work with bases stored in your home folder." ^ "\n\n" ^
             transl "It is not recommended to use the bases stored in /var/lib/geneweb with geneweb-gui." ^ "\n\n" ^
             transl "It is also not recommended to use ports 2316 or 2317 that are already used by the geneweb and gwsetup daemons." )
      ~line_wrap:True ()
    in
    let bases_dir = ref assistant_default_bases_dir in
    let page_1 = GPack.hbox ~spacing:5 () in
    let _label = GMisc.label
      ~text:(transl "select bases directory")
      ~packing:(page_1#pack ~expand:False ~fill:False ~padding:5) ()
    in
    let bbox = GPack.button_box `HORIZONTAL
      ~border_width: 5
      ~layout: `SPREAD
      ~packing:(page_1#pack ~expand:False ~fill:False ~padding:5) ()
    in
    let select = GButton.button
      ~stock:`OPEN
      ~packing:(bbox#pack ~expand:False ~fill:False ~padding:5) ()
    in
    ignore
      (select#connect#clicked
         (fun () -> do {
           bases_dir.val := select_dir assistant bases_dir.val;
           let num = assistant#current_page in
           let page = assistant#nth_page num in
           assistant#set_page_complete page (bases_dir.val <> "") }));
    let port = ref 2315 in (*to avoid conflicts with port 2317*)
    let page_2 = GPack.hbox ~homogeneous:False ~spacing:5 () in
    let _label = GMisc.label
      ~text:(transl "enter port")
      ~packing:(page_2#pack ~expand:False ~fill:False ~padding:5) ()
    in
    let entry = GEdit.entry
      ~text:(string_of_int port.val)
      ~packing:(page_2#pack ~expand:False ~fill:False ~padding:5) ()
    in
    ignore
      (entry#connect#changed
         (fun () -> do {
           let txt = entry#text in
           port.val := int_of_string txt;
           let num = assistant#current_page in
           let page = assistant#nth_page num in
           assistant#set_page_complete page (String.length txt > 0) }));
    let browser = ref "" in
    let page_3 = GPack.hbox ~homogeneous:False ~spacing:5 () in
    let _label = GMisc.label
      ~text:(transl "select browser")
      ~packing:(page_3#pack ~expand:False ~fill:False ~padding:5) ()
    in
    let bbox = GPack.button_box `HORIZONTAL
      ~border_width: 5
      ~layout: `SPREAD
      ~packing:(page_3#pack ~expand:False ~fill:False ~padding:5) ()
    in
    let select = GButton.button
      ~stock:`OPEN
      ~packing:(bbox#pack ~expand:False ~fill:False ~padding:5) ()
    in
    ignore
      (select#connect#clicked
         (fun () -> do {
           browser.val := select_file assistant browser.val;
           let num = assistant#current_page in
           let page = assistant#nth_page num in
           assistant#set_page_complete page (browser.val <> "") }));
    match config_browser () with
    [ Some b ->
        let btn = GButton.check_button
          ~label:b
          ~packing:(page_3#pack ~expand:False ~fill:False ~padding:5) ()
        in
        ignore
          (btn#connect#toggled
             ~callback:(fun () -> do {
               browser.val := b;
               let num = assistant#current_page in
               let page = assistant#nth_page num in
               assistant#set_page_complete page btn#active }))
    | None -> () ];
    let page_4 = GMisc.label
      ~text:(transl "Your configuration file is:" ^ "\n" ^ config_gui_file)
      ~line_wrap:True ()
    in
    ignore
      (assistant#append_page
         ~title:(transl "Introduction")
         ~page_type:`INTRO
         ~complete:True
         page_0#as_widget);
    ignore
      (assistant#append_page
         ~title:(transl "About geneweb-gui")
         ~page_type:`CONTENT
         ~complete:True
         page_0b#as_widget);
    ignore
      (assistant#append_page
         ~title:(transl "Setup bases directory")
         ~page_type:`CONTENT
         page_1#as_widget);
    ignore
      (assistant#append_page
         ~title:(transl "Setup port")
         ~page_type:`CONTENT
         ~complete:True
         page_2#as_widget);
    ignore
      (assistant#append_page
         ~title:(transl "Setup browser")
         ~page_type:`CONTENT
         page_3#as_widget);
    ignore
      (assistant#append_page
         ~title:(transl "Completed")
         ~page_type: `CONFIRM
         ~complete:True
         page_4#as_widget);
    let save_config () = do {
      let gui_arg =
        [("bd", bases_dir.val); ("port", string_of_int port.val);
         ("browser", browser.val)]
      in
      let conf =
        { bases_dir = bases_dir.val;
          port = port.val; browser = Some browser.val;
          log = Filename.concat bases_dir.val "comm.log";
          gui_arg = gui_arg; gwd_arg = []; only_arg = [];
          server_running = None; waiting_pids = [] }
      in
      (* TODO : On en a besoin avant ... *)
      (* mkdir_p conf.bases_dir; *)
      write_config_file conf;
      assistant#destroy ();
      launch_server conf }
    in
    ignore (assistant#connect#cancel ~callback:GMain.quit);
    ignore (assistant#connect#close ~callback:save_config);
    assistant#show ();
};


(**/**) (* main *)

value speclist = [("-trace", Arg.Set trace, " Trace server")];
value anon_fun s = raise (Arg.Bad (sprintf "Don't know what to do with %s" s));
value usage_msg = "Usage: gui [option]";

value main () = do {
  Arg.parse (Arg.align speclist) anon_fun usage_msg;
  launch_config ();
  let () = GMain.main () in
  Sys.catch_break True;
  eprintf "Bye\n"; flush stderr;
};

Printexc.print main ();