source: trunk/macosx/MessageWindowController.m @ 9542

Last change on this file since 9542 was 9542, checked in by livings124, 13 years ago

in the message window code, create the processed file name/line number right away, to avoid having to store an extra number

  • Property svn:keywords set to Date Rev Author Id
File size: 14.6 KB
Line 
1/******************************************************************************
2 * $Id: MessageWindowController.m 9542 2009-11-22 03:40:19Z livings124 $
3 *
4 * Copyright (c) 2006-2009 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import "MessageWindowController.h"
26#import "NSApplicationAdditions.h"
27#import "NSStringAdditions.h"
28#import <transmission.h>
29
30#define LEVEL_ERROR 0
31#define LEVEL_INFO  1
32#define LEVEL_DEBUG 2
33
34#define UPDATE_SECONDS  0.6
35#define MAX_MESSAGES    8000
36
37@interface MessageWindowController (Private)
38
39- (void) resizeColumn;
40- (NSString *) stringForMessage: (NSDictionary *) message;
41
42@end
43
44@implementation MessageWindowController
45
46- (id) init
47{
48    return [super initWithWindowNibName: @"MessageWindow"];
49}
50
51- (void) dealloc
52{
53    [fTimer invalidate];
54    [fMessages release];
55   
56    [fAttributes release];
57   
58    [super dealloc];
59}
60
61- (void) awakeFromNib
62{
63    NSWindow * window = [self window];
64    [window setFrameAutosaveName: @"MessageWindowFrame"];
65    [window setFrameUsingName: @"MessageWindowFrame"];
66   
67    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(resizeColumn)
68        name: @"NSTableViewColumnDidResizeNotification" object: fMessageTable];
69   
70    [window setContentBorderThickness: [[fMessageTable enclosingScrollView] frame].origin.y forEdge: NSMinYEdge];
71   
72    //initially sort peer table by date
73    if ([[fMessageTable sortDescriptors] count] == 0)
74        [fMessageTable setSortDescriptors: [NSArray arrayWithObject: [[fMessageTable tableColumnWithIdentifier: @"Date"]
75                                            sortDescriptorPrototype]]];
76   
77    [[self window] setTitle: NSLocalizedString(@"Message Log", "Message window -> title")];
78   
79    //set images and text for popup button items
80    [[fLevelButton itemAtIndex: LEVEL_ERROR] setTitle: NSLocalizedString(@"Error", "Message window -> level string")];
81    [[fLevelButton itemAtIndex: LEVEL_INFO] setTitle: NSLocalizedString(@"Info", "Message window -> level string")];
82    [[fLevelButton itemAtIndex: LEVEL_DEBUG] setTitle: NSLocalizedString(@"Debug", "Message window -> level string")];
83   
84    //set table column text
85    [[[fMessageTable tableColumnWithIdentifier: @"Date"] headerCell] setTitle: NSLocalizedString(@"Date",
86        "Message window -> table column")];
87    [[[fMessageTable tableColumnWithIdentifier: @"Name"] headerCell] setTitle: NSLocalizedString(@"Process",
88        "Message window -> table column")];
89    [[[fMessageTable tableColumnWithIdentifier: @"Message"] headerCell] setTitle: NSLocalizedString(@"Message",
90        "Message window -> table column")];
91   
92    //set and size buttons
93    [fSaveButton setTitle: [NSLocalizedString(@"Save", "Message window -> save button") stringByAppendingEllipsis]];
94    [fSaveButton sizeToFit];
95   
96    NSRect saveButtonFrame = [fSaveButton frame];
97    saveButtonFrame.size.width += 10.0;
98    [fSaveButton setFrame: saveButtonFrame];
99   
100    const CGFloat oldClearButtonWidth = [fClearButton frame].size.width;
101   
102    [fClearButton setTitle: NSLocalizedString(@"Clear", "Message window -> save button")];
103    [fClearButton sizeToFit];
104   
105    NSRect clearButtonFrame = [fClearButton frame];
106    clearButtonFrame.size.width = MAX(clearButtonFrame.size.width + 10.0, saveButtonFrame.size.width);
107    clearButtonFrame.origin.x -= clearButtonFrame.size.width - oldClearButtonWidth;
108    [fClearButton setFrame: clearButtonFrame];
109   
110    //select proper level in popup button
111    switch (tr_getMessageLevel())
112    {
113        case TR_MSG_ERR:
114            [fLevelButton selectItemAtIndex: LEVEL_ERROR];
115            break;
116        case TR_MSG_INF:
117            [fLevelButton selectItemAtIndex: LEVEL_INFO];
118            break;
119        case TR_MSG_DBG:
120            [fLevelButton selectItemAtIndex: LEVEL_DEBUG];
121    }
122   
123    fMessages = [[NSMutableArray alloc] init];
124}
125
126- (void) windowDidBecomeKey: (NSNotification *) notification
127{
128    if (!fTimer)
129        fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self
130                    selector: @selector(updateLog:) userInfo: nil repeats: YES];
131    [self updateLog: nil];
132}
133
134- (void) windowWillClose: (id)sender
135{
136    [fTimer invalidate];
137    fTimer = nil;
138}
139
140- (void) updateLog: (NSTimer *) timer
141{
142    tr_msg_list * messages;
143    if ((messages = tr_getQueuedMessages()) == NULL)
144        return;
145   
146    static NSUInteger currentIndex = 0;
147   
148    NSScroller * scroller = [[fMessageTable enclosingScrollView] verticalScroller];
149    const BOOL shouldScroll = currentIndex == 0 || [scroller floatValue] == 1.0 || [scroller isHidden]
150                                || [scroller knobProportion] == 1.0;
151   
152    for (tr_msg_list * currentMessage = messages; currentMessage != NULL; currentMessage = currentMessage->next)
153    {
154        NSString * name = currentMessage->name != NULL ? [NSString stringWithUTF8String: currentMessage->name]
155                            : [[NSProcessInfo processInfo] processName];
156       
157        NSString * file = [NSString stringWithFormat: @"%@:%d", [[NSString stringWithUTF8String: currentMessage->file] lastPathComponent],
158                            currentMessage->line];
159       
160        NSDictionary * message  = [NSDictionary dictionaryWithObjectsAndKeys:
161                                    [NSString stringWithUTF8String: currentMessage->message], @"Message",
162                                    [NSDate dateWithTimeIntervalSince1970: currentMessage->when], @"Date",
163                                    [NSNumber numberWithUnsignedInteger: currentIndex++], @"Index", //more accurate when sorting by date
164                                    [NSNumber numberWithInteger: currentMessage->level], @"Level",
165                                    name, @"Name",
166                                    file, @"File", nil];
167       
168        [fMessages addObject: message];
169    }
170   
171    tr_freeMessageList(messages);
172   
173    NSUInteger total = [fMessages count];
174    if (total > MAX_MESSAGES)
175    {
176        //remove the oldest - move oldest to end for (assumedly) most efficient removal
177        NSSortDescriptor * descriptor = [[[NSSortDescriptor alloc] initWithKey: @"Index" ascending: NO] autorelease];
178        [fMessages sortUsingDescriptors: [NSArray arrayWithObject: descriptor]];
179       
180        [fMessages removeObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(MAX_MESSAGES, total-MAX_MESSAGES)]];
181       
182        [fMessageTable noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, MAX_MESSAGES)]];
183        total = MAX_MESSAGES;
184    }
185   
186    [fMessages sortUsingDescriptors: [fMessageTable sortDescriptors]];
187   
188    [fMessageTable reloadData];
189    if (shouldScroll)
190        [fMessageTable scrollRowToVisible: total-1];
191}
192
193- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView
194{
195    return [fMessages count];
196}
197
198- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (NSInteger) row
199{
200    NSString * ident = [column identifier];
201    NSDictionary * message = [fMessages objectAtIndex: row];
202
203    if ([ident isEqualToString: @"Date"])
204        return [message objectForKey: @"Date"];
205    else if ([ident isEqualToString: @"Level"])
206    {
207        const NSInteger level = [[message objectForKey: @"Level"] integerValue];
208        switch (level)
209        {
210            case TR_MSG_ERR:
211                return [NSImage imageNamed: @"RedDot.png"];
212            case TR_MSG_INF:
213                return [NSImage imageNamed: @"YellowDot.png"];
214            case TR_MSG_DBG:
215                return [NSImage imageNamed: @"PurpleDot.png"];
216            default:
217                NSAssert1(NO, @"Unknown message log level: %d", level);
218                return nil;
219        }
220    }
221    else if ([ident isEqualToString: @"Name"])
222        return [message objectForKey: @"Name"];
223    else
224        return [message objectForKey: @"Message"];
225}
226
227#warning don't cut off end
228- (CGFloat) tableView: (NSTableView *) tableView heightOfRow: (NSInteger) row
229{
230    NSTableColumn * column = [tableView tableColumnWithIdentifier: @"Message"];
231   
232    if (!fAttributes)
233        fAttributes = [[[[column dataCell] attributedStringValue] attributesAtIndex: 0 effectiveRange: NULL] retain];
234   
235    const CGFloat count = floorf([[[fMessages objectAtIndex: row] objectForKey: @"Message"] sizeWithAttributes: fAttributes].width
236                                / [column width]);
237    return [tableView rowHeight] * (count + 1.0);
238}
239
240- (void) tableView: (NSTableView *) tableView sortDescriptorsDidChange: (NSArray *) oldDescriptors
241{
242    [fMessages sortUsingDescriptors: [fMessageTable sortDescriptors]];
243    [fMessageTable reloadData];
244}
245
246- (NSString *) tableView: (NSTableView *) tableView toolTipForCell: (NSCell *) cell rect: (NSRectPointer) rect
247                tableColumn: (NSTableColumn *) column row: (NSInteger) row mouseLocation: (NSPoint) mouseLocation
248{
249    NSDictionary * message = [fMessages objectAtIndex: row];
250    return [message objectForKey: @"File"];
251}
252
253- (void) copy: (id) sender
254{
255    NSIndexSet * indexes = [fMessageTable selectedRowIndexes];
256    NSMutableArray * messageStrings = [NSMutableArray arrayWithCapacity: [indexes count]];
257   
258    for (NSDictionary * message in [fMessages objectsAtIndexes: indexes])
259        [messageStrings addObject: [self stringForMessage: message]];
260   
261    NSString * messageString = [messageStrings componentsJoinedByString: @"\n"];
262   
263    NSPasteboard * pb = [NSPasteboard generalPasteboard];
264    if ([NSApp isOnSnowLeopardOrBetter])
265    {
266        [pb clearContents];
267        [pb writeObjects: [NSArray arrayWithObject: messageString]];
268    }
269    else
270    {
271        [pb declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner: nil];
272        [pb setString: messageString forType: NSStringPboardType];
273    }
274}
275
276- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
277{
278    SEL action = [menuItem action];
279   
280    if (action == @selector(copy:))
281        return [fMessageTable numberOfSelectedRows] > 0;
282   
283    return YES;
284}
285
286- (void) changeLevel: (id) sender
287{
288    [self updateLog: nil];
289   
290    NSInteger level;
291    switch ([fLevelButton indexOfSelectedItem])
292    {
293        case LEVEL_ERROR:
294            level = TR_MSG_ERR;
295            break;
296        case LEVEL_INFO:
297            level = TR_MSG_INF;
298            break;
299        case LEVEL_DEBUG:
300            level = TR_MSG_DBG;
301            break;
302    }
303   
304    tr_setMessageLevel(level);
305    [[NSUserDefaults standardUserDefaults] setInteger: level forKey: @"MessageLevel"];
306}
307
308- (void) clearLog: (id) sender
309{
310    [fMessages removeAllObjects];
311    [fMessageTable reloadData];
312}
313
314- (void) writeToFile: (id) sender
315{
316    //make the array sorted by date
317    NSSortDescriptor * descriptor = [[[NSSortDescriptor alloc] initWithKey: @"Index" ascending: YES] autorelease];
318    NSArray * descriptors = [[NSArray alloc] initWithObjects: descriptor, nil];
319    NSArray * sortedMessages = [[fMessages sortedArrayUsingDescriptors: descriptors] retain];
320    [descriptors release];
321   
322    NSSavePanel * panel = [NSSavePanel savePanel];
323    [panel setRequiredFileType: @"txt"];
324    [panel setCanSelectHiddenExtension: YES];
325   
326    [panel beginSheetForDirectory: nil file: NSLocalizedString(@"untitled", "Save log panel -> default file name")
327            modalForWindow: [self window] modalDelegate: self
328            didEndSelector: @selector(writeToFileSheetClosed:returnCode:contextInfo:) contextInfo: sortedMessages];
329}
330
331- (void) writeToFileSheetClosed: (NSSavePanel *) panel returnCode: (NSInteger) code contextInfo: (NSArray *) messages
332{
333    if (code == NSOKButton)
334    {
335        //create the text to output
336        NSMutableArray * messageStrings = [NSMutableArray arrayWithCapacity: [messages count]];
337        for (NSDictionary * message in messages)
338            [messageStrings addObject: [self stringForMessage: message]];
339   
340        NSString * fileString = [messageStrings componentsJoinedByString: @"\n"];
341       
342        if (![fileString writeToFile: [panel filename] atomically: YES encoding: NSUTF8StringEncoding error: nil])
343        {
344            NSAlert * alert = [[NSAlert alloc] init];
345            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Save log alert panel -> button")];
346            [alert setMessageText: NSLocalizedString(@"Log Could Not Be Saved", "Save log alert panel -> title")];
347            [alert setInformativeText: [NSString stringWithFormat:
348                    NSLocalizedString(@"There was a problem creating the file \"%@\".",
349                    "Save log alert panel -> message"), [[panel filename] lastPathComponent]]];
350            [alert setAlertStyle: NSWarningAlertStyle];
351           
352            [alert runModal];
353            [alert release];
354        }
355    }
356   
357    [messages release];
358}
359
360@end
361
362@implementation MessageWindowController (Private)
363
364- (void) resizeColumn
365{
366    [fMessageTable noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange:
367                    NSMakeRange(0, [fMessageTable numberOfRows])]];
368}
369
370- (NSString *) stringForMessage: (NSDictionary *) message
371{
372    NSString * level;
373    switch ([[message objectForKey: @"Level"] integerValue])
374    {
375        case TR_MSG_ERR:
376            level = NSLocalizedString(@"Error", "Message window -> level");
377            break;
378        case TR_MSG_INF:
379            level = NSLocalizedString(@"Info", "Message window -> level");
380            break;
381        case TR_MSG_DBG:
382            level = NSLocalizedString(@"Debug", "Message window -> level");
383            break;
384        default:
385            level = @"";
386    }
387   
388    return [NSString stringWithFormat: @"%@ %@ [%@] %@: %@", [message objectForKey: @"Date"],
389            [message objectForKey: @"File"], level,
390            [message objectForKey: @"Name"], [message objectForKey: @"Message"], nil];
391}
392
393@end
Note: See TracBrowser for help on using the repository browser.