tags:

views:

560

answers:

1

What is the best way to display constantly updated logging output using Cocoa Components? The output is line-based and generated by the application. Appending lines should be fast, and the view should automatically scroll to the bottom. All in all, it should work and look like basic standard out in a terminal.

My code is written in Python, using the PyObjC bridge. I'm looking for approaches/examples I can adapt, Objective-C code is welcome.

+1  A: 

It seems that there are two options: (1) use an NSTableView and (2) use an NSTextView. Console.app appears to use an NSTableView but an NSTextView is probably less code.

For (1), I would write an NSTableDataSource that returns the appropriate line (either from memory or from disk) for tableView_objectValueForTableColumn_rowIndex_ and the total number of log lines for numberOfRowsInTableView_. Set this data source as the dataSource for an NSTableView. You may need to call tableView.reloadData() to redisplay the data when a new log line comes in. Assuming the table view is embedded in an NSScrollView (the default if you create the table view in Interface Builder), you can scroll to the bottom with this method from the Apple Scroll View Programming Guide (easily translated to Python)

- (void)scrollToBottom:sender;
{
    NSPoint newScrollOrigin;

    // assume that the scrollview is an existing variable
    if ([[scrollview documentView] isFlipped]) {
        newScrollOrigin=NSMakePoint(0.0,NSMaxY([[scrollview documentView] frame])
                                       -NSHeight([[scrollview contentView] bounds]));
    } else {
        newScrollOrigin=NSMakePoint(0.0,0.0);
    }

    [[scrollview documentView] scrollPoint:newScrollOrigin];

}

Obviously, this code assumes that you've got an IBOutlet to the scroll view.

For (2), you can add a line to the end of the text view with textView.textStorage().appendString_(new_log + '\n') (assuming there isn't already a newline on the end). You can force the enclosing scroll view to scroll to the end (indirectoy) by calling textView.setSelectedRange_(NSMakeRange(textView.textStorage().length(),0))

Barry Wark