/*  Part of XPCE --- The SWI-Prolog GUI toolkit

    Author:        Jan Wielemaker and Anjo Anjewierden
    E-mail:        jan@swi.psy.uva.nl
    WWW:           http://www.swi.psy.uva.nl/projects/xpce/
    Copyright (c)  2002-2011, University of Amsterdam
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in
       the documentation and/or other materials provided with the
       distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

:- module('Xserver',
          [ ensure_x_server/2           % +Display, +Depth
          ]).
:- use_module(library(pce)).


%!  ensure_x_server(+Display, +Depth)
%
%   Ensure the existence of a graphics environment for XPCE.  This
%   library uses the `head-less' server Xvfb if there is no X-server
%   in the environment.
%
%   Currently this library deals with Windows (where no explicit
%   server is required) and Xfree using the Xfree socket naming
%   conventions.  Please send platform-specific code to
%   info@swi-prolog.org

ensure_x_server(_Display, _) :-
    current_prolog_flag(windows, true),
    !. % we have a display
ensure_x_server(_Display, _) :-
    getenv('DISPLAY', _),
    !.               % Existing X11 display
ensure_x_server(Display, _) :-
    atom_concat('/tmp/.X11-unix/X', Display, Socket),
    catch(open(Socket, read, In), _, fail),
    close(In),
    export_environment(Display).
ensure_x_server(Display, Depth) :-
    print_message(informational, pce(xserver(start_Xvfb(Display, Depth)))),
    xauthority(Display, Auth),
    xlog(Display, Log),
    mcookie(Cookie),
    ignore(catch(delete_file(Auth), _, true)),
    sformat(Cmd1, '/usr/bin/X11/xauth -f ~w add :~w . ~s > ~w 2>&1',
            [ Auth, Display, Cookie, Log ]),
    shell(Cmd1),
    sformat(Cmd2, 'nohup /usr/bin/X11/Xvfb :~w -auth ~w -screen 0 640x480x~w >> ~w &',
            [ Display, Auth, Depth, Log ]),
    shell(Cmd2),
    sleep(5),
    export_environment(Display).

xauthority(Display, Auth) :-
    atomic_list_concat(['/tmp/.X', Display, 'Authority'], Auth).
xlog(Display, Log) :-
    atomic_list_concat(['/tmp/.X', Display, 'Log'], Log).

mcookie(Cookie) :-
    open(pipe(mcookie), read, Stream),
    read_line_to_codes(Stream, Cookie).

export_environment(Display) :-
    xauthority(Display, Auth),
    atom_concat(':', Display, Address),
    setenv('DISPLAY', Address),
    setenv('XAUTHORITY', Auth).

                 /*******************************
                 *            MESSAGES          *
                 *******************************/
:- multifile
    prolog:message/3.

%       Catch messages.  sgml/4 is generated by the SGML2PL binding.

prolog:message(pce(xserver(start_Xvfb(Display, Depth)))) -->
    [ 'XPCE: Starting Xvfb on display ~w using depth ~w'-[Display, Depth]
    ].
