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

    Author:        Jan Wielemaker and Anjo Anjewierden
    E-mail:        jan@swi-prolog.org
    WWW:           https://www.swi-prolog.org/projects/xpce/
    Copyright (c)  1997-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(draw_config,
          [
          ]).
:- use_module(library(pce)).
:- use_module(library(pce_config)).
:- require([ absolute_file_name/3
           , broadcast_request/1
           , file_directory_name/2
           ]).

:- pce_global(@draw_default_arrow, new(arrow)).

                 /*******************************
                 *      CHECK ENVIRONMENT       *
                 *******************************/

has_printer_class :-
    get(@pce, convert, win_printer, class, _).

                 /*******************************
                 *         CONFIG STUFF         *
                 *******************************/

config(Path, Attributes) :-
    broadcast_request(config(draw_config:Path, Attributes)).

config(config/file,
       [ default('PceDraw')
       ]).
config(config/application,
       [ default('PceDraw')
       ]).

config(edit/auto_align,
       [ type(bool),
         comment(['Startup default for `Settings/Auto Align'': ',
                  'Automatically align new and modified objects']),
         default(true),
         icon('16x16/valign.png')
       ]).
config(resources/default_font,
       [ type(font),
         comment('Default font for text objects'),
         default(normal)
       ]).
config(resources/colour_palette,
       [ type(setof(colour)),
         comment('Set of colours available in attribute viewer'),
         default([red, green, blue, yellow, black, white])
       ]).
config(resources/fill_palette,
       [ type(setof(colour)),
         comment('Colours used for filling'),
         default([red, green, blue, yellow, black, white
                 ])
       ]).
config(resources/arrows,
       [ type(setof(arrow)),
         comment('Arrow heads for lines'),
         default([ @draw_default_arrow
                 ])
       ]).
%config(print/printer,
%       [ type(name),
%         comment('Name of the default printer.  May be $VARIABLE'),
%         default(DefPrinter)
%       ]) :-
%    (   get(@pce, environment_variable, 'PRINTER', _DefPrinter)
%    ->  DefPrinter = '$PRINTER'
%    ;   DefPrinter = 'PostScript'
%    ).
config(file/save_prototypes,
       [ type(bool),
         comment('Save user prototypes with drawing.'),
         default(true)
       ]).
config(file/save_pdf_on_save,
       [ type(bool),
         comment(['Automatically save drawing as PDF after ',
                  'saving as PceDraw .pd file'
                 ]),
         default(false)
       ]).
config(file/pdf_file_extension,
       [ type(name),
         comment(['Extension for PDF files.']),
         default('pdf')
       ]).
config(history/recent_files,
       [ type(setof(file)),
         comment('Recently visited files'),
         editable(false)
       ]).
config(history/geometry/main_window,
       [ type(geometry),
         comment('(X-)geometry specification of main window'),
         editable(false),
         default('600x600')
       ]).
config(history/geometry/attributes,
       [ type(point),
         comment('X,Y offset of attribute editor relative to main window'),
         editable(false)
       ]).

resource(arrows,        image, image('16x16/arrows.png')).
resource(fillpattern,   image, image('16x16/fillpattern.png')).

:- register_config_type(arrow,          [ editor(arrow_item),
                                          term([ length,
                                                 wing,
                                                 style,
                                                 fill_pattern
                                               ]+pen+colour),
                                          icon(arrows)
                                        ]).
:- register_config_type(setof(arrow),   [ editor(arrow_set_item),
                                          icon(arrows)
                                        ]).
:- register_config_type(setof(image),   [ editor(image_set_item),
                                          icon(fillpattern)
                                        ]).

:- register_config(config).

                 /*******************************
                 *            CLASSES           *
                 *******************************/

:- pce_autoload(arrow_item,        library(pce_arrow_item)).
:- pce_autoload(image_item,        library(pce_image_item)).
:- pce_autoload(set_item,          library(pce_set_item)).
:- pce_autoload(graphical_browser, library(pce_graphical_browser)).

:- pce_begin_class(arrow_set_item, set_item,
                   "Editor for a set of arrows").

initialise(ASI, Name:[name], Default:[chain], Msg:[code]*) :->
    new(B, graphical_browser(@default, @default,
                             ?(@prolog, make_arrow_line, @arg1),
                             @arg1?second_arrow)),
    send(B, single_column, @on),
    send(ASI, send_super, initialise, new(arrow_item), Name, Msg, B),
    (   Default \== @default
    ->  send(ASI, selection, Default)
    ;   true
    ).

make_arrow_line(Arrow, Line) :-
    new(Line, line(0, 0, 50, 0)),
    send(Line, second_arrow, Arrow).

:- pce_end_class.


:- pce_begin_class(image_set_item, set_item,
                   "Editor for a set of images").

initialise(ASI, Name:[name], Default:[chain], Msg:[code]*) :->
    new(B, graphical_browser(@default, @default,
                             create(bitmap, @arg1),
                             @arg1?image)),
    send(ASI, send_super, initialise, new(II, image_item), Name, Msg, B),
    (   absolute_file_name(pce('bitmaps/patterns'),
                           [ file_type(directory),
                             access(read),
                             file_errors(fail)
                           ], PatternDir)
    ->  send(II, directory, PatternDir)
    ;   true
    ),
    (   Default \== @default
    ->  good_patterns(Default, Patterns),
        send(ASI, selection, Patterns)
    ;   true
    ).

good_patterns(ChainIn, ChainOut) :-
    chain_list(ChainIn, ListIn),
    realise_patterns(ListIn, ListOut),
    chain_list(ChainOut, ListOut).

realise_patterns([], []).
realise_patterns([Image|T0], [Image|T]) :-
    object(Image),
    send(Image, instance_of, image),
    !,
    realise_patterns(T0, T).
realise_patterns([Name|T0], [Image|T]) :-
    pce_catch_error(_Error, new(Image, image(Name))),
    !,
    realise_patterns(T0, T).
realise_patterns([_|T0], T) :-
    realise_patterns(T0, T).

selection(ASI, Sel:chain) :<-
    get(ASI, get_super, selection, Sel0),
    get(Sel0, map, ?(@prolog, map_selected_image, @arg1), Sel).

map_selected_image(@Named, @Named) :-
    atom(Named),
    !.
map_selected_image(Image, Named) :-
    get(Image, name, @nil),
    get(Image, file, File),
    get(Image, path, SearchPath),
    local_name(SearchPath, File, Name),
    !,
    new(Named, image(Name)).
map_selected_image(Image, Image).

local_name(SearchPath, File, Name) :-
    get(File, absolute_path, FileName),
    base_name(FileName, Name),
    new(F, file(Name)),
    pce_catch_error(cannot_find_file, send(F, find, SearchPath, read)),
    send(F, same, File),
    !.

base_name(FileName, Name) :-
    file_directory_name(FileName, Dir),
    base_name(FileName, Dir, Name).

base_name(FileName, Dir0, Local) :-
    get(Dir0, ensure_suffix, /, Dir),
    atom_concat(Dir, Local, FileName).
base_name(_, /, _) :-
    !,
    fail.
base_name(_, '', _) :-
    !,
    fail.
base_name(FileName, Dir, Local) :-
    file_directory_name(Dir, Super),
    base_name(FileName, Super, Local).

:- pce_end_class.

