# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Mobius Forensic Toolkit
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024 Eduardo Aguiar
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
from gi.repository import GdkPixbuf

from gtk_image_buffer import GTKImageBuffer


# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief UI engine for GTK library
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class GTKEngine(object):

    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    # @brief create image buffer from image file
    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def new_image_buffer_from_file(self, filename, width=-1, height=-1):
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(filename, width, height)
        return GTKImageBuffer(pixbuf)

    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    # @brief create image buffer from data
    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def new_image_buffer_from_data(self, data, width=-1, height=-1):
        loader = GdkPixbuf.PixbufLoader()

        # if both sizes are given, set_size instead of scaling
        if width != -1 and height != -1:
            loader.set_size(width, height)

        loader.write(data)
        loader.close()
        pixbuf = loader.get_pixbuf()

        # scale, if necessary
        if width == -1 or height == -1:

            if width != -1 and height == -1:
                yscale = float(width) / float(pixbuf.get_width() or 1)
                height = int(yscale * float(pixbuf.get_height()))

            elif width == -1 and height != -1:
                xscale = float(height) / float(pixbuf.get_height() or 1)
                width = int(xscale * float(pixbuf.get_width()))

            pixbuf = pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)

        # return GTKImageBuffer object
        return GTKImageBuffer(pixbuf)
