Fix for comments.
[librarian.git] / src / librarian / covers / widgets / background.py
index a6c7205..98adf05 100644 (file)
@@ -1,4 +1,8 @@
+# This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
+# Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
+#
 import io
 import io
+import time
 from urllib.request import urlopen
 import PIL.Image
 from .base import Widget
 from urllib.request import urlopen
 import PIL.Image
 from .base import Widget
@@ -7,7 +11,12 @@ from .base import Widget
 class Background(Widget):
     transparency = False
 
 class Background(Widget):
     transparency = False
 
+    def __init__(self, cover, crop_to_square=True):
+        self.crop_to_square = crop_to_square
+        super().__init__(cover)
+
     def setup(self):
     def setup(self):
+        self.img = None
         if self.cover.book_info.cover_url:
             while True:
                 try:
         if self.cover.book_info.cover_url:
             while True:
                 try:
@@ -19,23 +28,32 @@ class Background(Widget):
                 
             img = PIL.Image.open(data)
 
                 
             img = PIL.Image.open(data)
 
-            # crop top square.
-            if img.size[1] > img.size[0]:
-                img = img.crop((0, 0, img.size[0], img.size[0]))
-            else:
-                left = round((img.size[0] - img.size[1])/2)
-                img = img.crop((
-                    left,
-                    0,
-                    left + img.size[1],
-                    img.size[1]
-                ))
+            if self.crop_to_square:
+                # crop top square.
+                if img.size[1] > img.size[0]:
+                    img = img.crop((0, 0, img.size[0], img.size[0]))
+                else:
+                    left = round((img.size[0] - img.size[1])/2)
+                    img = img.crop((
+                        left,
+                        0,
+                        left + img.size[1],
+                        img.size[1]
+                    ))
             self.img = img
 
     def build(self, w, h):
             self.img = img
 
     def build(self, w, h):
-        kwadrat = round(max(w, h))
+        if not self.img:
+            return
         img = self.img
         img = self.img
-        img = self.img.resize((kwadrat, kwadrat))
+        scale = max(
+            w / img.size[0],
+            h / img.size[1]
+        )
+        img = self.img.resize((
+            round(scale * img.size[0]),
+            round(scale * img.size[1]),
+        ))
         img = img.crop((
             int((img.size[0] - w) / 2),
             0,
         img = img.crop((
             int((img.size[0] - w) / 2),
             0,