How to test if last line in TextView/TextBuffer is visible?

Is there any way to test if the last line in a TextView/TextBuffer is visible in the containing ScrollWindow?

I have a TextView which contains log lines for a process, and I am currently using scroll_to_mark( ) to keep the last line visible as I add lines. This works well, but I want to NOT scroll if the user has scrolled upward and is looking at earlier lines.

I’m working in Python, but comments about doing this in C would be helpful, too.

I think I need to test if the last line is visible, and if it is, then scroll when I add a new line. If the last line is not visible, then I won’t force the scrolling.

Ah-- this works:

def on_log_message(self, message):
    visible_rect = self.text_view.get_visible_rect()
    text_buffer_end_iter = self.text_buffer.get_end_iter()
    end_line_top, _end_line_height = self.text_view.get_line_yrange(text_buffer_end_iter)
    end_line_visible = visible_rect.y <= end_line_top <= visible_rect.y + visible_rect.height

    self.text_buffer.insert(text_buffer_end_iter, message)
    self.text_buffer.insert(text_buffer_end_iter, '\n')

    if end_line_visible:
        self.text_view.scroll_to_mark(self.text_mark_end, 0, False, 0, 0)