From 203680ff58ad1e56b232df7463f72034fa8d7a97 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Lorenz=20H=C3=BCbschle-Schneider?=
 <lorenz-dev@lgh-alumni.de>
Date: Fri, 7 Mar 2014 17:07:05 +0000
Subject: [PATCH] Try to fetch all unread lines if that is a reasonable amount

Partially fixes #139 in that it tries to accomplish this, but until we can request
only non-filtered lines from WeeChat, the best thing we can do is guessing.
---
 js/glowingbear.js | 19 +++++++++++++++----
 js/models.js      |  4 +++-
 2 files changed, 18 insertions(+), 5 deletions(-)

diff --git a/js/glowingbear.js b/js/glowingbear.js
index 1414105..a2cbde7 100644
--- a/js/glowingbear.js
+++ b/js/glowingbear.js
@@ -645,12 +645,20 @@ weechat.controller('WeechatCtrl', ['$rootScope', '$scope', '$store', '$timeout',
         }
     };
 
-    $rootScope.$on('activeBufferChanged', function() {
+
+    $rootScope.$on('activeBufferChanged', function(event, unreadSum) {
         var ab = models.getActiveBuffer();
 
         if (ab.requestedLines < $scope.lines) {
             // buffer has not been loaded, but some lines may already be present if they arrived after we connected
-            $scope.fetchMoreLines($scope.lines);
+            // try to determine how many lines to fetch
+            var numLines = $scope.lines;  // that's a screenful plus 10 lines
+            unreadSum += 10;  // let's just add a 10 line safety margin here again
+            if (unreadSum > numLines) {
+                // request up to 4*(screenful + 10 lines)
+                numLines = Math.min(4*numLines, unreadSum);
+            }
+            $scope.fetchMoreLines(numLines);
         }
         $rootScope.updateTitle(ab);
 
@@ -847,8 +855,11 @@ weechat.controller('WeechatCtrl', ['$rootScope', '$scope', '$store', '$timeout',
 
 
     $rootScope.loadingLines = false;
-    $scope.fetchMoreLines = function() {
-        connection.fetchMoreLines($scope.lines);
+    $scope.fetchMoreLines = function(numLines) {
+        if (!numLines) {
+            numLines = $scope.lines;
+        }
+        connection.fetchMoreLines(numLines);
     };
 
     $rootScope.scrollWithBuffer = function(nonIncremental) {
diff --git a/js/models.js b/js/models.js
index 67e8345..92d65ad 100644
--- a/js/models.js
+++ b/js/models.js
@@ -419,11 +419,13 @@ models.service('models', ['$rootScope', '$filter', function($rootScope, $filter)
             previousBuffer.lastSeen = previousBuffer.lines.length-1;
         }
 
+        var unreadSum = activeBuffer.unread + activeBuffer.notification;
+
         activeBuffer.active = true;
         activeBuffer.unread = 0;
         activeBuffer.notification = 0;
 
-        $rootScope.$emit('activeBufferChanged');
+        $rootScope.$emit('activeBufferChanged', unreadSum);
         $rootScope.$emit('notificationChanged');
         return true;
     };