hterm: fix mouse events to adjust for screen padding

Bug introduced when padding was added in crrev.com/c/2143311.

We clamp to the nearest value when click is in padding.

Bug: 267654
Change-Id: I82744a84a375bac165ff590ea35262e78f7a8ba6
Reviewed-on: https://chromium-review.googlesource.com/c/apps/libapps/+/2172936
Reviewed-by: Mike Frysinger <vapier@chromium.org>
Tested-by: kokoro <noreply+kokoro@google.com>
diff --git a/hterm/js/hterm_terminal.js b/hterm/js/hterm_terminal.js
index 13ca6b4..3a3a94a 100644
--- a/hterm/js/hterm_terminal.js
+++ b/hterm/js/hterm_terminal.js
@@ -597,7 +597,6 @@
         console.error(`Invalid screen padding size: ${v}`);
         return;
       }
-      terminal.setCssVar('screen-padding-size', `${v}px`);
       terminal.setScreenPaddingSize(v);
     },
 
@@ -1172,6 +1171,7 @@
  * @param {number} size
  */
 hterm.Terminal.prototype.setScreenPaddingSize = function(size) {
+  this.setCssVar('screen-padding-size', `${size}px`);
   this.scrollPort_.setScreenPaddingSize(size);
 };
 
@@ -3818,14 +3818,19 @@
   }
 
   // One based row/column stored on the mouse event.
+  const padding = this.scrollPort_.screenPaddingSize;
   e.terminalRow = Math.floor(
-      (e.clientY - this.scrollPort_.visibleRowTopMargin) /
+      (e.clientY - this.scrollPort_.visibleRowTopMargin - padding) /
       this.scrollPort_.characterSize.height) + 1;
   e.terminalColumn = Math.floor(
-      e.clientX / this.scrollPort_.characterSize.width) + 1;
+      (e.clientX - padding) / this.scrollPort_.characterSize.width) + 1;
 
-  if (e.type == 'mousedown' && e.terminalColumn > this.screenSize.width) {
-    // Mousedown in the scrollbar area.
+  // Clamp row and column.
+  e.terminalRow = lib.f.clamp(e.terminalRow, 1, this.screenSize.height);
+  e.terminalColumn = lib.f.clamp(e.terminalColumn, 1, this.screenSize.width);
+
+  // Ignore mousedown in the scrollbar area.
+  if (e.type == 'mousedown' && e.clientX >= this.scrollPort_.getScrollbarX()) {
     return;
   }