transmission/macosx/MessageWindowController.m

497 lines
18 KiB
Mathematica
Raw Normal View History

2007-09-16 01:02:06 +00:00
/******************************************************************************
* $Id$
*
* Copyright (c) 2006-2011 Transmission authors and contributors
2007-09-16 01:02:06 +00:00
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*****************************************************************************/
#import "MessageWindowController.h"
#import "NSApplicationAdditions.h"
#import "NSStringAdditions.h"
2007-09-16 01:02:06 +00:00
#import <transmission.h>
#import <utils.h>
2007-09-16 01:02:06 +00:00
#define LEVEL_ERROR 0
#define LEVEL_INFO 1
#define LEVEL_DEBUG 2
#define UPDATE_SECONDS 0.75
2007-09-16 01:02:06 +00:00
@interface MessageWindowController (Private)
- (void) resizeColumn;
- (BOOL) shouldIncludeMessageForFilter: (NSString *) filterString message: (NSDictionary *) message;
2007-09-16 01:02:06 +00:00
- (NSString *) stringForMessage: (NSDictionary *) message;
@end
@implementation MessageWindowController
- (id) init
2007-09-16 01:02:06 +00:00
{
2007-12-24 16:18:09 +00:00
return [super initWithWindowNibName: @"MessageWindow"];
2007-09-16 01:02:06 +00:00
}
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver: self];
2007-09-16 01:02:06 +00:00
[fTimer invalidate];
2009-11-28 21:01:27 +00:00
[fLock release];
2007-09-16 01:02:06 +00:00
[fMessages release];
[fDisplayedMessages release];
2007-09-16 01:02:06 +00:00
[fAttributes release];
2007-09-16 01:02:06 +00:00
[super dealloc];
}
- (void) awakeFromNib
{
NSWindow * window = [self window];
[window setFrameAutosaveName: @"MessageWindowFrame"];
[window setFrameUsingName: @"MessageWindowFrame"];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(resizeColumn)
name: @"NSTableViewColumnDidResizeNotification" object: fMessageTable];
[window setContentBorderThickness: NSMinY([[fMessageTable enclosingScrollView] frame]) forEdge: NSMinYEdge];
2008-03-15 20:18:44 +00:00
[[self window] setTitle: NSLocalizedString(@"Message Log", "Message window -> title")];
//set images and text for popup button items
[[fLevelButton itemAtIndex: LEVEL_ERROR] setTitle: NSLocalizedString(@"Error", "Message window -> level string")];
[[fLevelButton itemAtIndex: LEVEL_INFO] setTitle: NSLocalizedString(@"Info", "Message window -> level string")];
[[fLevelButton itemAtIndex: LEVEL_DEBUG] setTitle: NSLocalizedString(@"Debug", "Message window -> level string")];
const CGFloat levelButtonOldWidth = NSWidth([fLevelButton frame]);
[fLevelButton sizeToFit];
//set table column text
[[[fMessageTable tableColumnWithIdentifier: @"Date"] headerCell] setTitle: NSLocalizedString(@"Date",
"Message window -> table column")];
[[[fMessageTable tableColumnWithIdentifier: @"Name"] headerCell] setTitle: NSLocalizedString(@"Process",
"Message window -> table column")];
[[[fMessageTable tableColumnWithIdentifier: @"Message"] headerCell] setTitle: NSLocalizedString(@"Message",
"Message window -> table column")];
//set and size buttons
[fSaveButton setTitle: [NSLocalizedString(@"Save", "Message window -> save button") stringByAppendingEllipsis]];
[fSaveButton sizeToFit];
NSRect saveButtonFrame = [fSaveButton frame];
saveButtonFrame.size.width += 10.0;
saveButtonFrame.origin.x += NSWidth([fLevelButton frame]) - levelButtonOldWidth;
[fSaveButton setFrame: saveButtonFrame];
const CGFloat oldClearButtonWidth = [fClearButton frame].size.width;
[fClearButton setTitle: NSLocalizedString(@"Clear", "Message window -> save button")];
[fClearButton sizeToFit];
NSRect clearButtonFrame = [fClearButton frame];
clearButtonFrame.size.width = MAX(clearButtonFrame.size.width + 10.0, saveButtonFrame.size.width);
clearButtonFrame.origin.x -= NSWidth(clearButtonFrame) - oldClearButtonWidth;
[fClearButton setFrame: clearButtonFrame];
2007-09-16 01:02:06 +00:00
[[fFilterField cell] setPlaceholderString: NSLocalizedString(@"Filter", "Message window -> filter field")];
NSRect filterButtonFrame = [fFilterField frame];
filterButtonFrame.origin.x -= NSWidth(clearButtonFrame) - oldClearButtonWidth;
[fFilterField setFrame: filterButtonFrame];
fAttributes = [[[[[fMessageTable tableColumnWithIdentifier: @"Message"] dataCell] attributedStringValue]
attributesAtIndex: 0 effectiveRange: NULL] retain];
2007-09-16 01:02:06 +00:00
//select proper level in popup button
switch ([[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"])
2007-10-11 12:06:46 +00:00
{
case TR_MSG_ERR:
[fLevelButton selectItemAtIndex: LEVEL_ERROR];
break;
case TR_MSG_INF:
[fLevelButton selectItemAtIndex: LEVEL_INFO];
break;
case TR_MSG_DBG:
[fLevelButton selectItemAtIndex: LEVEL_DEBUG];
break;
default: //safety
[[NSUserDefaults standardUserDefaults] setInteger: TR_MSG_ERR forKey: @"MessageLevel"];
[fLevelButton selectItemAtIndex: LEVEL_ERROR];
2007-10-11 12:06:46 +00:00
}
2007-12-24 16:18:09 +00:00
fMessages = [[NSMutableArray alloc] init];
fDisplayedMessages = [[NSMutableArray alloc] init];
2009-11-28 21:01:27 +00:00
fLock = [[NSLock alloc] init];
}
- (void) windowDidBecomeKey: (NSNotification *) notification
{
if (!fTimer)
2009-12-11 04:01:47 +00:00
{
fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self
selector: @selector(updateLog:) userInfo: nil repeats: YES];
2009-12-11 04:01:47 +00:00
[self updateLog: nil];
}
2007-09-16 01:02:06 +00:00
}
- (void) windowWillClose: (id)sender
{
[fTimer invalidate];
fTimer = nil;
}
2007-09-16 01:02:06 +00:00
- (void) updateLog: (NSTimer *) timer
{
tr_msg_list * messages;
2007-09-16 01:02:06 +00:00
if ((messages = tr_getQueuedMessages()) == NULL)
return;
2009-11-28 21:01:27 +00:00
[fLock lock];
static NSUInteger currentIndex = 0;
NSScroller * scroller = [[fMessageTable enclosingScrollView] verticalScroller];
const BOOL shouldScroll = currentIndex == 0 || [scroller floatValue] == 1.0 || [scroller isHidden]
|| [scroller knobProportion] == 1.0;
const NSInteger maxLevel = [[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"];
NSString * filterString = [fFilterField stringValue];
BOOL changed = NO;
for (tr_msg_list * currentMessage = messages; currentMessage != NULL; currentMessage = currentMessage->next)
{
2008-03-16 15:26:53 +00:00
NSString * name = currentMessage->name != NULL ? [NSString stringWithUTF8String: currentMessage->name]
: [[NSProcessInfo processInfo] processName];
NSString * file = [[[NSString stringWithUTF8String: currentMessage->file] lastPathComponent] stringByAppendingFormat: @":%d",
currentMessage->line];
2008-03-16 15:26:53 +00:00
NSDictionary * message = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithUTF8String: currentMessage->message], @"Message",
[NSDate dateWithTimeIntervalSince1970: currentMessage->when], @"Date",
[NSNumber numberWithUnsignedInteger: currentIndex++], @"Index", //more accurate when sorting by date
[NSNumber numberWithInteger: currentMessage->level], @"Level",
2008-03-16 15:26:53 +00:00
name, @"Name",
file, @"File", nil];
[fMessages addObject: message];
if (currentMessage->level <= maxLevel && [self shouldIncludeMessageForFilter: filterString message: message])
{
[fDisplayedMessages addObject: message];
changed = YES;
}
}
2007-09-16 01:02:06 +00:00
if ([fMessages count] > TR_MAX_MSG_LOG)
{
const NSUInteger oldCount = [fDisplayedMessages count];
NSIndexSet * removeIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fMessages count]-TR_MAX_MSG_LOG)];
NSArray * itemsToRemove = [fMessages objectsAtIndexes: removeIndexes];
[fMessages removeObjectsAtIndexes: removeIndexes];
[fDisplayedMessages removeObjectsInArray: itemsToRemove];
changed |= oldCount > [fDisplayedMessages count];
}
if (changed)
{
[fDisplayedMessages sortUsingDescriptors: [fMessageTable sortDescriptors]];
[fMessageTable reloadData];
if (shouldScroll)
[fMessageTable scrollRowToVisible: [fMessageTable numberOfRows]-1];
}
2009-11-28 21:01:27 +00:00
[fLock unlock];
tr_freeMessageList(messages);
2007-09-16 01:02:06 +00:00
}
- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView
2007-09-16 01:02:06 +00:00
{
return [fDisplayedMessages count];
2007-09-16 01:02:06 +00:00
}
- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (NSInteger) row
2007-09-16 01:02:06 +00:00
{
NSString * ident = [column identifier];
NSDictionary * message = [fDisplayedMessages objectAtIndex: row];
2007-09-16 01:02:06 +00:00
if ([ident isEqualToString: @"Date"])
return [message objectForKey: @"Date"];
else if ([ident isEqualToString: @"Level"])
{
const NSInteger level = [[message objectForKey: @"Level"] integerValue];
switch (level)
2007-10-01 21:52:31 +00:00
{
case TR_MSG_ERR:
return [NSImage imageNamed: @"RedDot.png"];
2007-10-01 21:52:31 +00:00
case TR_MSG_INF:
return [NSImage imageNamed: @"YellowDot.png"];
2007-10-01 21:52:31 +00:00
case TR_MSG_DBG:
return [NSImage imageNamed: @"PurpleDot.png"];
2007-10-01 21:52:31 +00:00
default:
NSAssert1(NO, @"Unknown message log level: %d", level);
2007-10-01 21:52:31 +00:00
return nil;
}
2007-09-16 01:02:06 +00:00
}
else if ([ident isEqualToString: @"Name"])
return [message objectForKey: @"Name"];
2007-09-16 01:02:06 +00:00
else
return [message objectForKey: @"Message"];
}
#warning don't cut off end
- (CGFloat) tableView: (NSTableView *) tableView heightOfRow: (NSInteger) row
{
NSString * message = [[fDisplayedMessages objectAtIndex: row] objectForKey: @"Message"];
NSTableColumn * column = [tableView tableColumnWithIdentifier: @"Message"];
const CGFloat count = floorf([message sizeWithAttributes: fAttributes].width / [column width]);
return [tableView rowHeight] * (count + 1.0);
}
2007-09-16 01:02:06 +00:00
- (void) tableView: (NSTableView *) tableView sortDescriptorsDidChange: (NSArray *) oldDescriptors
{
[fDisplayedMessages sortUsingDescriptors: [fMessageTable sortDescriptors]];
2007-09-16 01:02:06 +00:00
[fMessageTable reloadData];
}
- (NSString *) tableView: (NSTableView *) tableView toolTipForCell: (NSCell *) cell rect: (NSRectPointer) rect
tableColumn: (NSTableColumn *) column row: (NSInteger) row mouseLocation: (NSPoint) mouseLocation
{
NSDictionary * message = [fDisplayedMessages objectAtIndex: row];
return [message objectForKey: @"File"];
}
2007-09-16 01:02:06 +00:00
- (void) copy: (id) sender
{
NSIndexSet * indexes = [fMessageTable selectedRowIndexes];
NSMutableArray * messageStrings = [NSMutableArray arrayWithCapacity: [indexes count]];
for (NSDictionary * message in [fDisplayedMessages objectsAtIndexes: indexes])
2007-10-12 11:33:26 +00:00
[messageStrings addObject: [self stringForMessage: message]];
2007-09-16 01:02:06 +00:00
NSString * messageString = [messageStrings componentsJoinedByString: @"\n"];
NSPasteboard * pb = [NSPasteboard generalPasteboard];
if ([NSApp isOnSnowLeopardOrBetter])
{
[pb clearContents];
[pb writeObjects: [NSArray arrayWithObject: messageString]];
}
else
{
[pb declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner: nil];
[pb setString: messageString forType: NSStringPboardType];
}
2007-09-16 01:02:06 +00:00
}
- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
{
SEL action = [menuItem action];
if (action == @selector(copy:))
return [fMessageTable numberOfSelectedRows] > 0;
return YES;
}
- (void) changeLevel: (id) sender
{
NSInteger level;
2007-10-01 21:52:31 +00:00
switch ([fLevelButton indexOfSelectedItem])
{
case LEVEL_ERROR:
level = TR_MSG_ERR;
break;
case LEVEL_INFO:
level = TR_MSG_INF;
break;
case LEVEL_DEBUG:
level = TR_MSG_DBG;
break;
default:
NSAssert1(NO, @"Unknown message log level: %d", [fLevelButton indexOfSelectedItem]);
2007-10-01 21:52:31 +00:00
}
2007-09-16 01:02:06 +00:00
if ([[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"] == level)
return;
2009-11-28 21:01:27 +00:00
[fLock lock];
2007-09-16 01:02:06 +00:00
[[NSUserDefaults standardUserDefaults] setInteger: level forKey: @"MessageLevel"];
NSString * filterString = [fFilterField stringValue];
[fDisplayedMessages removeAllObjects];
for (NSDictionary * message in fMessages)
if ([[message objectForKey: @"Level"] integerValue] <= level
&& [self shouldIncludeMessageForFilter: filterString message: message])
[fDisplayedMessages addObject: message];
[fDisplayedMessages sortUsingDescriptors: [fMessageTable sortDescriptors]];
[fMessageTable reloadData];
if ([fDisplayedMessages count] > 0)
{
[fMessageTable deselectAll: self];
[fMessageTable scrollRowToVisible: [fMessageTable numberOfRows]-1];
}
[fLock unlock];
}
- (void) changeFilter: (id) sender
{
[fLock lock];
const NSInteger level = [[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"];
NSString * filterString = [fFilterField stringValue];
[fDisplayedMessages removeAllObjects];
for (NSDictionary * message in fMessages)
if ([[message objectForKey: @"Level"] integerValue] <= level
&& [self shouldIncludeMessageForFilter: filterString message: message])
[fDisplayedMessages addObject: message];
[fDisplayedMessages sortUsingDescriptors: [fMessageTable sortDescriptors]];
[fMessageTable reloadData];
2009-11-28 21:01:27 +00:00
if ([fDisplayedMessages count] > 0)
{
[fMessageTable deselectAll: self];
[fMessageTable scrollRowToVisible: [fMessageTable numberOfRows]-1];
}
2009-11-28 21:01:27 +00:00
[fLock unlock];
2007-09-16 01:02:06 +00:00
}
- (void) clearLog: (id) sender
{
[fLock lock];
2007-09-16 01:02:06 +00:00
[fMessages removeAllObjects];
[fDisplayedMessages removeAllObjects];
2007-09-16 01:02:06 +00:00
[fMessageTable reloadData];
[fLock unlock];
2007-09-16 01:02:06 +00:00
}
- (void) writeToFile: (id) sender
{
//make the array sorted by date
NSSortDescriptor * descriptor = [[[NSSortDescriptor alloc] initWithKey: @"Index" ascending: YES] autorelease];
2007-09-16 01:02:06 +00:00
NSArray * descriptors = [[NSArray alloc] initWithObjects: descriptor, nil];
NSArray * sortedMessages = [[fDisplayedMessages sortedArrayUsingDescriptors: descriptors] retain];
2007-09-16 01:02:06 +00:00
[descriptors release];
NSSavePanel * panel = [NSSavePanel savePanel];
[panel setRequiredFileType: @"txt"];
[panel setCanSelectHiddenExtension: YES];
[panel beginSheetForDirectory: nil file: NSLocalizedString(@"untitled", "Save log panel -> default file name")
modalForWindow: [self window] modalDelegate: self
didEndSelector: @selector(writeToFileSheetClosed:returnCode:contextInfo:) contextInfo: sortedMessages];
2007-09-16 01:02:06 +00:00
}
- (void) writeToFileSheetClosed: (NSSavePanel *) panel returnCode: (NSInteger) code contextInfo: (NSArray *) messages
2007-09-16 01:02:06 +00:00
{
if (code == NSOKButton)
{
//create the text to output
NSMutableArray * messageStrings = [NSMutableArray arrayWithCapacity: [messages count]];
for (NSDictionary * message in messages)
[messageStrings addObject: [self stringForMessage: message]];
NSString * fileString = [messageStrings componentsJoinedByString: @"\n"];
if (![fileString writeToFile: [panel filename] atomically: YES encoding: NSUTF8StringEncoding error: nil])
2007-09-16 01:02:06 +00:00
{
NSAlert * alert = [[NSAlert alloc] init];
[alert addButtonWithTitle: NSLocalizedString(@"OK", "Save log alert panel -> button")];
[alert setMessageText: NSLocalizedString(@"Log Could Not Be Saved", "Save log alert panel -> title")];
[alert setInformativeText: [NSString stringWithFormat:
2007-09-16 01:02:06 +00:00
NSLocalizedString(@"There was a problem creating the file \"%@\".",
"Save log alert panel -> message"), [[panel filename] lastPathComponent]]];
2007-09-16 01:02:06 +00:00
[alert setAlertStyle: NSWarningAlertStyle];
[alert runModal];
[alert release];
}
}
[messages release];
2007-09-16 01:02:06 +00:00
}
@end
@implementation MessageWindowController (Private)
- (void) resizeColumn
{
[fMessageTable noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange:
NSMakeRange(0, [fMessageTable numberOfRows])]];
}
- (BOOL) shouldIncludeMessageForFilter: (NSString *) filterString message: (NSDictionary *) message
{
if ([filterString isEqualToString: @""])
return YES;
const NSStringCompareOptions searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
return [[message objectForKey: @"Name"] rangeOfString: filterString options: searchOptions].location != NSNotFound
|| [[message objectForKey: @"Message"] rangeOfString: filterString options: searchOptions].location != NSNotFound;
}
2007-09-16 01:02:06 +00:00
- (NSString *) stringForMessage: (NSDictionary *) message
{
NSString * levelString;
const NSInteger level = [[message objectForKey: @"Level"] integerValue];
switch (level)
2007-10-01 21:52:31 +00:00
{
case TR_MSG_ERR:
levelString = NSLocalizedString(@"Error", "Message window -> level");
2007-10-01 21:52:31 +00:00
break;
case TR_MSG_INF:
levelString = NSLocalizedString(@"Info", "Message window -> level");
2007-10-01 21:52:31 +00:00
break;
case TR_MSG_DBG:
levelString = NSLocalizedString(@"Debug", "Message window -> level");
2007-10-01 21:52:31 +00:00
break;
default:
NSAssert1(NO, @"Unknown message log level: %d", level);
2007-10-01 21:52:31 +00:00
}
2007-09-16 01:02:06 +00:00
return [NSString stringWithFormat: @"%@ %@ [%@] %@: %@", [message objectForKey: @"Date"],
[message objectForKey: @"File"], levelString,
[message objectForKey: @"Name"], [message objectForKey: @"Message"], nil];
2007-09-16 01:02:06 +00:00
}
@end