From d3efa1c748b52f4d542c68a17259296d9c83272f Mon Sep 17 00:00:00 2001
From: Vilem Duha <vilem.duha@gmail.com>
Date: Fri, 19 Nov 2021 13:33:02 +0100
Subject: [PATCH] BlenderKit: fix several minor UI issues

lock icons update was delayed
scroll buttons were not updated when number of rows changed
model dimension show also cm and mm when appropriate
design year is drawn without comma
prevent ui_bgl draw text error
correct pluralisation of ratings in tooltips.
---
 blenderkit/asset_bar_op.py | 36 +++++++++++++++++++++---------------
 blenderkit/ui.py           |  3 +++
 blenderkit/ui_bgl.py       |  2 ++
 blenderkit/ui_panels.py    | 17 +++++++++--------
 blenderkit/utils.py        | 15 +++++++++++++++
 5 files changed, 50 insertions(+), 23 deletions(-)

diff --git a/blenderkit/asset_bar_op.py b/blenderkit/asset_bar_op.py
index 4ad15285e..c48f4dcf3 100644
--- a/blenderkit/asset_bar_op.py
+++ b/blenderkit/asset_bar_op.py
@@ -26,6 +26,7 @@ from bpy.props import (
 
 active_area_pointer = 0
 
+
 def get_area_height(self):
     if type(self.context) != dict:
         if self.context is None:
@@ -297,15 +298,15 @@ class BlenderKitAssetBarOperator(BL_UI_OT_draw_operator):
         self.tooltip_widgets.append(gravatar_image)
 
         quality_star = BL_UI_Image(self.margin, self.tooltip_height - self.margin - self.asset_name_text_size,
-                                     1, 1)
+                                   1, 1)
         img_path = paths.get_addon_thumbnail_path('star_grey.png')
         quality_star.set_image(img_path)
         quality_star.set_image_size((self.asset_name_text_size, self.asset_name_text_size))
         quality_star.set_image_position((0, 0))
         # self.quality_star = quality_star
         self.tooltip_widgets.append(quality_star)
-        label = self.new_text('', 2*self.margin+self.asset_name_text_size,
-                              self.tooltip_height - int(self.asset_name_text_size+ self.margin * .5),
+        label = self.new_text('', 2 * self.margin + self.asset_name_text_size,
+                              self.tooltip_height - int(self.asset_name_text_size + self.margin * .5),
                               text_size=self.asset_name_text_size)
         self.tooltip_widgets.append(label)
         self.quality_label = label
@@ -443,19 +444,19 @@ class BlenderKitAssetBarOperator(BL_UI_OT_draw_operator):
             ui_props.reports_y = region.height - self.bar_y - 600
             self.reports_x = self.bar_x
             ui_props.reports_x = self.bar_x
-        else:#ui.bar_y - ui.bar_height - 100
+        else:  # ui.bar_y - ui.bar_height - 100
 
             self.reports_y = region.height - self.bar_y - self.bar_height - 50
-            ui_props.reports_y =region.height -  self.bar_y - self.bar_height- 50
+            ui_props.reports_y = region.height - self.bar_y - self.bar_height - 50
             self.reports_x = self.bar_x
             ui_props.reports_x = self.bar_x
             # print(self.bar_y, self.bar_height, region.height)
 
     def update_layout(self, context, event):
         # restarting asset_bar completely since the widgets are too hard to get working with updates.
-        self.scroll_update()
 
         self.position_and_hide_buttons()
+        self.scroll_update()
 
         self.button_close.set_location(self.bar_width - self.other_button_size, -self.other_button_size)
         if hasattr(self, 'button_notifications'):
@@ -479,7 +480,6 @@ class BlenderKitAssetBarOperator(BL_UI_OT_draw_operator):
 
         # to hide arrows accordingly
 
-
     def asset_button_init(self, asset_x, asset_y, button_idx):
         ui_scale = bpy.context.preferences.view.ui_scale
 
@@ -582,25 +582,25 @@ class BlenderKitAssetBarOperator(BL_UI_OT_draw_operator):
 
         self.widgets_panel.append(self.button_close)
 
-        scroll_width = 30
-        self.button_scroll_down = BL_UI_Button(-scroll_width, 0, scroll_width, self.bar_height)
+        self.scroll_width = 30
+        self.button_scroll_down = BL_UI_Button(-self.scroll_width, 0, self.scroll_width, self.bar_height)
         self.button_scroll_down.bg_color = button_bg_color
         self.button_scroll_down.hover_bg_color = button_hover_color
         self.button_scroll_down.text = ""
         self.button_scroll_down.set_image(paths.get_addon_thumbnail_path('arrow_left.png'))
-        self.button_scroll_down.set_image_size((scroll_width, self.button_size))
+        self.button_scroll_down.set_image_size((self.scroll_width, self.button_size))
         self.button_scroll_down.set_image_position((0, int((self.bar_height - self.button_size) / 2)))
 
         self.button_scroll_down.set_mouse_down(self.scroll_down)
 
         self.widgets_panel.append(self.button_scroll_down)
 
-        self.button_scroll_up = BL_UI_Button(self.bar_width, 0, scroll_width, self.bar_height)
+        self.button_scroll_up = BL_UI_Button(self.bar_width, 0, self.scroll_width, self.bar_height)
         self.button_scroll_up.bg_color = button_bg_color
         self.button_scroll_up.hover_bg_color = button_hover_color
         self.button_scroll_up.text = ""
         self.button_scroll_up.set_image(paths.get_addon_thumbnail_path('arrow_right.png'))
-        self.button_scroll_up.set_image_size((scroll_width, self.button_size))
+        self.button_scroll_up.set_image_size((self.scroll_width, self.button_size))
         self.button_scroll_up.set_image_position((0, int((self.bar_height - self.button_size) / 2)))
 
         self.button_scroll_up.set_mouse_down(self.scroll_up)
@@ -661,6 +661,11 @@ class BlenderKitAssetBarOperator(BL_UI_OT_draw_operator):
             button.validation_icon.visible = False
             button.progress_bar.visible = False
 
+        self.button_scroll_down.height = self.bar_height
+        self.button_scroll_down.set_image_position((0, int((self.bar_height - self.button_size) / 2)))
+        self.button_scroll_down.height = self.bar_height
+        self.button_scroll_down.set_image_position((0, int((self.bar_height - self.button_size) / 2)))
+
     def __init__(self):
         super().__init__()
 
@@ -808,8 +813,8 @@ class BlenderKitAssetBarOperator(BL_UI_OT_draw_operator):
             get_tooltip_data(asset_data)
             an = asset_data['name']
             max_name_length = 30
-            if len(an)>max_name_length+3:
-                an = an[:30]+'...'
+            if len(an) > max_name_length + 3:
+                an = an[:30] + '...'
             self.asset_name.text = an
             self.authors_name.text = asset_data['tooltip_data']['author_text']
             self.quality_label.text = asset_data['tooltip_data']['quality']
@@ -912,7 +917,8 @@ class BlenderKitAssetBarOperator(BL_UI_OT_draw_operator):
                     asset_button.visible = True
 
                     asset_data = sr[asset_button.asset_index]
-
+                    if asset_data is None:
+                        continue
                     iname = blenderkit.utils.previmg_name(asset_button.asset_index)
                     # show indices for debug purposes
                     # asset_button.text = str(asset_button.asset_index)
diff --git a/blenderkit/ui.py b/blenderkit/ui.py
index 41c4feeeb..0844121bf 100644
--- a/blenderkit/ui.py
+++ b/blenderkit/ui.py
@@ -1737,6 +1737,9 @@ class AssetDragOperator(bpy.types.Operator):
             self.handlers_remove()
             bpy.context.window.cursor_set("DEFAULT")
             ui_props.dragging = False
+            bpy.ops.view3d.blenderkit_asset_bar_widget('INVOKE_REGION_WIN',
+                                                       do_search=False)
+
             return {'CANCELLED'}
 
         sprops = bpy.context.window_manager.blenderkit_models
diff --git a/blenderkit/ui_bgl.py b/blenderkit/ui_bgl.py
index 339f59838..07362b550 100644
--- a/blenderkit/ui_bgl.py
+++ b/blenderkit/ui_bgl.py
@@ -137,6 +137,8 @@ def draw_image(x, y, width, height, image, transparency, crop=(0, 0, 1, 1), batc
 def draw_text(text, x, y, size, color=(1, 1, 1, 0.5), halign = 'LEFT', valign = 'TOP'):
     font_id = 1
     # bgl.glColor4f(*color)
+    if type(text) != str:
+        text = str(text)
     blf.color(font_id, color[0], color[1], color[2], color[3])
     blf.size(font_id, size, 72)
     if halign != 'LEFT':
diff --git a/blenderkit/ui_panels.py b/blenderkit/ui_panels.py
index d976fbdd3..c3734554e 100644
--- a/blenderkit/ui_panels.py
+++ b/blenderkit/ui_panels.py
@@ -1744,12 +1744,15 @@ class AssetPopupCard(bpy.types.Operator, ratings_utils.RatingsProperties):
             op.url = url
             op.tooltip = tooltip
 
-    def draw_asset_parameter(self, layout, key='', pretext='', do_search=False):
+    def draw_asset_parameter(self, layout, key='', pretext='', do_search=False, decimal = True):
         parameter = utils.get_param(self.asset_data, key)
         if parameter == None:
             return
         if type(parameter) == int:
-            parameter = f"{parameter:,d}"
+            if decimal:
+                parameter = f"{parameter:,d}"
+            else:
+                parameter = f"{parameter}"
         elif type(parameter) == float:
             parameter = f"{parameter:,.1f}"
         if do_search:
@@ -1866,7 +1869,7 @@ class AssetPopupCard(bpy.types.Operator, ratings_utils.RatingsProperties):
                                   do_search=True)
         self.draw_asset_parameter(box, key='designCollection', pretext='Collection', do_search=True)
         self.draw_asset_parameter(box, key='designVariant', pretext='Variant')
-        self.draw_asset_parameter(box, key='designYear', pretext='Design year')
+        self.draw_asset_parameter(box, key='designYear', pretext='Design year', decimal = False)
 
         self.draw_asset_parameter(box, key='faceCount', pretext='Face count')
         # self.draw_asset_parameter(box, key='thumbnailScale', pretext='Preview scale')
@@ -1878,9 +1881,7 @@ class AssetPopupCard(bpy.types.Operator, ratings_utils.RatingsProperties):
             self.draw_asset_parameter(box, key='modelStyle', pretext='Style')
 
         if utils.get_param(self.asset_data, 'dimensionX'):
-            t = '%s×%s×%s m' % (utils.fmt_length(mparams['dimensionX']),
-                                utils.fmt_length(mparams['dimensionY']),
-                                utils.fmt_length(mparams['dimensionZ']))
+            t = utils.fmt_dimensions(mparams)
             self.draw_property(box, 'Size', t)
         if self.asset_data.get('filesSize'):
             fs = self.asset_data['filesSize']
@@ -2065,12 +2066,12 @@ class AssetPopupCard(bpy.types.Operator, ratings_utils.RatingsProperties):
 
             tooltip_extension = f'.\n\nRatings results are shown for assets with more than {show_rating_threshold} ratings'
             op = row.operator('wm.blenderkit_tooltip', text=str(q), icon='SOLO_ON')
-            op.tooltip = f"Quality, average from {rc['quality']} ratings" \
+            op.tooltip = f"Quality, average from {rc['quality']} rating{'' if rc['quality'] == 1 else 's'}" \
                          f"{tooltip_extension if rcount <= show_rating_threshold else ''}"
             row.label(text='   ')
 
             op = row.operator('wm.blenderkit_tooltip', text=str(c), icon_value=pcoll['dumbbell'].icon_id)
-            op.tooltip = f"Complexity, median from {rc['workingHours']} ratings" \
+            op.tooltip = f"Complexity, median from {rc['workingHours']} rating{'' if rc['workingHours'] == 1 else 's'}" \
                          f"{tooltip_extension if rcount <= show_rating_threshold else ''}"
 
             if rcount <= show_rating_prompt_threshold:
diff --git a/blenderkit/utils.py b/blenderkit/utils.py
index 5bdace75f..952219ad7 100644
--- a/blenderkit/utils.py
+++ b/blenderkit/utils.py
@@ -741,6 +741,21 @@ def name_update(props):
         # Here we actually rename assets datablocks, but don't do that with HDR's and possibly with others
         asset.name = fname
 
+def fmt_dimensions(p):
+    '''formats dimensions to correct string'''
+    dims = [p['dimensionX'],p['dimensionY'],p['dimensionZ']]
+    maxl = max(dims)
+    if maxl>1:
+        unit = 'm'
+        unitscale = 1
+    elif maxl>.01:
+        unit = 'cm'
+        unitscale = 100
+    else:
+        unit = 'mm'
+        unitscale = 1000
+    s = f'{fmt_length(dims[0]*unitscale)}×{fmt_length(dims[1]*unitscale)}×{fmt_length(dims[2]*unitscale)} {unit}'
+    return s
 
 def fmt_length(prop):
     prop = str(round(prop, 2))
-- 
GitLab