source: trunk/macosx/MessageWindowController.m @ 13251

Last change on this file since 13251 was 13251, checked in by livings124, 9 years ago

reverse r13248-r13250, since ARC doesn't support 32-bit.

  • Property svn:keywords set to Date Rev Author Id
File size: 19.9 KB
Line 
1/******************************************************************************
2 * $Id: MessageWindowController.m 13251 2012-03-13 02:52:11Z livings124 $
3 *
4 * Copyright (c) 2006-2012 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 "NSMutableArrayAdditions.h"
28#import "NSStringAdditions.h"
29#import <transmission.h>
30#import <utils.h>
31
32#define LEVEL_ERROR 0
33#define LEVEL_INFO  1
34#define LEVEL_DEBUG 2
35
36#define UPDATE_SECONDS  0.75
37
38@interface MessageWindowController (Private)
39
40- (void) resizeColumn;
41- (BOOL) shouldIncludeMessageForFilter: (NSString *) filterString message: (NSDictionary *) message;
42- (void) updateListForFilter;
43- (NSString *) stringForMessage: (NSDictionary *) message;
44
45@end
46
47@implementation MessageWindowController
48
49- (id) init
50{
51    return [super initWithWindowNibName: @"MessageWindow"];
52}
53
54- (void) awakeFromNib
55{
56    NSWindow * window = [self window];
57    [window setFrameAutosaveName: @"MessageWindowFrame"];
58    [window setFrameUsingName: @"MessageWindowFrame"];
59   
60    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(resizeColumn)
61        name: @"NSTableViewColumnDidResizeNotification" object: fMessageTable];
62   
63    [window setContentBorderThickness: NSMinY([[fMessageTable enclosingScrollView] frame]) forEdge: NSMinYEdge];
64   
65    [[self window] setTitle: NSLocalizedString(@"Message Log", "Message window -> title")];
66   
67    //set images and text for popup button items
68    [[fLevelButton itemAtIndex: LEVEL_ERROR] setTitle: NSLocalizedString(@"Error", "Message window -> level string")];
69    [[fLevelButton itemAtIndex: LEVEL_INFO] setTitle: NSLocalizedString(@"Info", "Message window -> level string")];
70    [[fLevelButton itemAtIndex: LEVEL_DEBUG] setTitle: NSLocalizedString(@"Debug", "Message window -> level string")];
71   
72    const CGFloat levelButtonOldWidth = NSWidth([fLevelButton frame]);
73    [fLevelButton sizeToFit];
74   
75    //set table column text
76    [[[fMessageTable tableColumnWithIdentifier: @"Date"] headerCell] setTitle: NSLocalizedString(@"Date",
77        "Message window -> table column")];
78    [[[fMessageTable tableColumnWithIdentifier: @"Name"] headerCell] setTitle: NSLocalizedString(@"Process",
79        "Message window -> table column")];
80    [[[fMessageTable tableColumnWithIdentifier: @"Message"] headerCell] setTitle: NSLocalizedString(@"Message",
81        "Message window -> table column")];
82   
83    //set and size buttons
84    [fSaveButton setTitle: [NSLocalizedString(@"Save", "Message window -> save button") stringByAppendingEllipsis]];
85    [fSaveButton sizeToFit];
86   
87    NSRect saveButtonFrame = [fSaveButton frame];
88    saveButtonFrame.size.width += 10.0;
89    saveButtonFrame.origin.x += NSWidth([fLevelButton frame]) - levelButtonOldWidth;
90    [fSaveButton setFrame: saveButtonFrame];
91   
92    const CGFloat oldClearButtonWidth = [fClearButton frame].size.width;
93   
94    [fClearButton setTitle: NSLocalizedString(@"Clear", "Message window -> save button")];
95    [fClearButton sizeToFit];
96   
97    NSRect clearButtonFrame = [fClearButton frame];
98    clearButtonFrame.size.width = MAX(clearButtonFrame.size.width + 10.0, saveButtonFrame.size.width);
99    clearButtonFrame.origin.x -= NSWidth(clearButtonFrame) - oldClearButtonWidth;
100    [fClearButton setFrame: clearButtonFrame];
101   
102    [[fFilterField cell] setPlaceholderString: NSLocalizedString(@"Filter", "Message window -> filter field")];
103    NSRect filterButtonFrame = [fFilterField frame];
104    filterButtonFrame.origin.x -= NSWidth(clearButtonFrame) - oldClearButtonWidth;
105    [fFilterField setFrame: filterButtonFrame];
106   
107    fAttributes = [[[[[fMessageTable tableColumnWithIdentifier: @"Message"] dataCell] attributedStringValue]
108                    attributesAtIndex: 0 effectiveRange: NULL] retain];
109   
110    //select proper level in popup button
111    switch ([[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"])
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            break;
122        default: //safety
123            [[NSUserDefaults standardUserDefaults] setInteger: TR_MSG_ERR forKey: @"MessageLevel"];
124            [fLevelButton selectItemAtIndex: LEVEL_ERROR];
125    }
126   
127    fMessages = [[NSMutableArray alloc] init];
128    fDisplayedMessages = [[NSMutableArray alloc] init];
129   
130    fLock = [[NSLock alloc] init];
131}
132
133- (void) dealloc
134{
135    [[NSNotificationCenter defaultCenter] removeObserver: self];
136   
137    [fTimer invalidate];
138    [fLock release];
139   
140    [fMessages release];
141    [fDisplayedMessages release];
142   
143    [fAttributes release];
144   
145    [super dealloc];
146}
147
148- (void) windowDidBecomeKey: (NSNotification *) notification
149{
150    if (!fTimer)
151    {
152        fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self
153                    selector: @selector(updateLog:) userInfo: nil repeats: YES];
154        [self updateLog: nil];
155    }
156}
157
158- (void) windowWillClose: (id)sender
159{
160    [fTimer invalidate];
161    fTimer = nil;
162}
163
164- (void) updateLog: (NSTimer *) timer
165{
166    tr_msg_list * messages;
167    if ((messages = tr_getQueuedMessages()) == NULL)
168        return;
169   
170    [fLock lock];
171   
172    static NSUInteger currentIndex = 0;
173   
174    NSScroller * scroller = [[fMessageTable enclosingScrollView] verticalScroller];
175    const BOOL shouldScroll = currentIndex == 0 || [scroller floatValue] == 1.0 || [scroller isHidden]
176                                || [scroller knobProportion] == 1.0;
177   
178    const NSInteger maxLevel = [[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"];
179    NSString * filterString = [fFilterField stringValue];
180   
181    BOOL changed = NO;
182   
183    for (tr_msg_list * currentMessage = messages; currentMessage != NULL; currentMessage = currentMessage->next)
184    {
185        NSString * name = currentMessage->name != NULL ? [NSString stringWithUTF8String: currentMessage->name]
186                            : [[NSProcessInfo processInfo] processName];
187       
188        NSString * file = [[[NSString stringWithUTF8String: currentMessage->file] lastPathComponent] stringByAppendingFormat: @":%d",
189                            currentMessage->line];
190       
191        NSDictionary * message  = [NSDictionary dictionaryWithObjectsAndKeys:
192                                    [NSString stringWithUTF8String: currentMessage->message], @"Message",
193                                    [NSDate dateWithTimeIntervalSince1970: currentMessage->when], @"Date",
194                                    [NSNumber numberWithUnsignedInteger: currentIndex++], @"Index", //more accurate when sorting by date
195                                    [NSNumber numberWithInteger: currentMessage->level], @"Level",
196                                    name, @"Name",
197                                    file, @"File", nil];
198       
199        [fMessages addObject: message];
200       
201        if (currentMessage->level <= maxLevel && [self shouldIncludeMessageForFilter: filterString message: message])
202        {
203            [fDisplayedMessages addObject: message];
204            changed = YES;
205        }
206    }
207   
208    if ([fMessages count] > TR_MAX_MSG_LOG)
209    {
210        const NSUInteger oldCount = [fDisplayedMessages count];
211       
212        NSIndexSet * removeIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fMessages count]-TR_MAX_MSG_LOG)];
213        NSArray * itemsToRemove = [fMessages objectsAtIndexes: removeIndexes];
214       
215        [fMessages removeObjectsAtIndexes: removeIndexes];
216        [fDisplayedMessages removeObjectsInArray: itemsToRemove];
217       
218        changed |= oldCount > [fDisplayedMessages count];
219    }
220   
221    if (changed)
222    {
223        [fDisplayedMessages sortUsingDescriptors: [fMessageTable sortDescriptors]];
224       
225        [fMessageTable reloadData];
226        if (shouldScroll)
227            [fMessageTable scrollRowToVisible: [fMessageTable numberOfRows]-1];
228    }
229   
230    [fLock unlock];
231   
232    tr_freeMessageList(messages);
233}
234
235- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView
236{
237    return [fDisplayedMessages count];
238}
239
240- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (NSInteger) row
241{
242    NSString * ident = [column identifier];
243    NSDictionary * message = [fDisplayedMessages objectAtIndex: row];
244
245    if ([ident isEqualToString: @"Date"])
246        return [message objectForKey: @"Date"];
247    else if ([ident isEqualToString: @"Level"])
248    {
249        const NSInteger level = [[message objectForKey: @"Level"] integerValue];
250        switch (level)
251        {
252            case TR_MSG_ERR:
253                return [NSImage imageNamed: @"RedDot.png"];
254            case TR_MSG_INF:
255                return [NSImage imageNamed: @"YellowDot.png"];
256            case TR_MSG_DBG:
257                return [NSImage imageNamed: @"PurpleDot.png"];
258            default:
259                NSAssert1(NO, @"Unknown message log level: %d", level);
260                return nil;
261        }
262    }
263    else if ([ident isEqualToString: @"Name"])
264        return [message objectForKey: @"Name"];
265    else
266        return [message objectForKey: @"Message"];
267}
268
269#warning don't cut off end
270- (CGFloat) tableView: (NSTableView *) tableView heightOfRow: (NSInteger) row
271{
272    NSString * message = [[fDisplayedMessages objectAtIndex: row] objectForKey: @"Message"];
273   
274    NSTableColumn * column = [tableView tableColumnWithIdentifier: @"Message"];
275    const CGFloat count = floorf([message sizeWithAttributes: fAttributes].width / [column width]);
276    return [tableView rowHeight] * (count + 1.0);
277}
278
279- (void) tableView: (NSTableView *) tableView sortDescriptorsDidChange: (NSArray *) oldDescriptors
280{
281    [fDisplayedMessages sortUsingDescriptors: [fMessageTable sortDescriptors]];
282    [fMessageTable reloadData];
283}
284
285- (NSString *) tableView: (NSTableView *) tableView toolTipForCell: (NSCell *) cell rect: (NSRectPointer) rect
286                tableColumn: (NSTableColumn *) column row: (NSInteger) row mouseLocation: (NSPoint) mouseLocation
287{
288    NSDictionary * message = [fDisplayedMessages objectAtIndex: row];
289    return [message objectForKey: @"File"];
290}
291
292- (void) copy: (id) sender
293{
294    NSIndexSet * indexes = [fMessageTable selectedRowIndexes];
295    NSMutableArray * messageStrings = [NSMutableArray arrayWithCapacity: [indexes count]];
296   
297    for (NSDictionary * message in [fDisplayedMessages objectsAtIndexes: indexes])
298        [messageStrings addObject: [self stringForMessage: message]];
299   
300    NSString * messageString = [messageStrings componentsJoinedByString: @"\n"];
301   
302    NSPasteboard * pb = [NSPasteboard generalPasteboard];
303    [pb clearContents];
304    [pb writeObjects: [NSArray arrayWithObject: messageString]];
305}
306
307- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
308{
309    SEL action = [menuItem action];
310   
311    if (action == @selector(copy:))
312        return [fMessageTable numberOfSelectedRows] > 0;
313   
314    return YES;
315}
316
317- (void) changeLevel: (id) sender
318{
319    NSInteger level;
320    switch ([fLevelButton indexOfSelectedItem])
321    {
322        case LEVEL_ERROR:
323            level = TR_MSG_ERR;
324            break;
325        case LEVEL_INFO:
326            level = TR_MSG_INF;
327            break;
328        case LEVEL_DEBUG:
329            level = TR_MSG_DBG;
330            break;
331        default:
332            NSAssert1(NO, @"Unknown message log level: %d", [fLevelButton indexOfSelectedItem]);
333    }
334   
335    if ([[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"] == level)
336        return;
337   
338    [[NSUserDefaults standardUserDefaults] setInteger: level forKey: @"MessageLevel"];
339   
340    [fLock lock];
341   
342    [self updateListForFilter];
343   
344    [fLock unlock];
345}
346
347- (void) changeFilter: (id) sender
348{
349    [fLock lock];
350   
351    [self updateListForFilter];
352   
353    [fLock unlock];
354}
355
356- (void) clearLog: (id) sender
357{
358    [fLock lock];
359   
360    [fMessages removeAllObjects];
361   
362    const BOOL onLion = [NSApp isOnLionOrBetter];
363   
364    if (onLion)
365        [fMessageTable beginUpdates];
366   
367    if (onLion)
368        [fMessageTable removeRowsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedMessages count])] withAnimation: NSTableViewAnimationSlideLeft];
369    [fDisplayedMessages removeAllObjects];
370   
371    if (onLion)
372        [fMessageTable endUpdates];
373    else
374        [fMessageTable reloadData];
375   
376    [fLock unlock];
377}
378
379- (void) writeToFile: (id) sender
380{
381    NSSavePanel * panel = [NSSavePanel savePanel];
382    [panel setAllowedFileTypes: [NSArray arrayWithObject: @"txt"]];
383    [panel setCanSelectHiddenExtension: YES];
384   
385    [panel setNameFieldStringValue: NSLocalizedString(@"untitled", "Save log panel -> default file name")];
386   
387    [panel beginSheetModalForWindow: [self window] completionHandler: ^(NSInteger result) {
388        if (result == NSFileHandlingPanelOKButton)
389        {
390            //make the array sorted by date
391            NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey: @"Index" ascending: YES];
392            NSArray * descriptors = [[NSArray alloc] initWithObjects: descriptor, nil];
393            NSArray * sortedMessages = [fDisplayedMessages sortedArrayUsingDescriptors: descriptors];
394            [descriptors release];
395           
396            //create the text to output
397            NSMutableArray * messageStrings = [NSMutableArray arrayWithCapacity: [sortedMessages count]];
398            for (NSDictionary * message in sortedMessages)
399                [messageStrings addObject: [self stringForMessage: message]];
400           
401            NSString * fileString = [messageStrings componentsJoinedByString: @"\n"];
402           
403            if (![fileString writeToFile: [[panel URL] path] atomically: YES encoding: NSUTF8StringEncoding error: nil])
404            {
405                NSAlert * alert = [[NSAlert alloc] init];
406                [alert addButtonWithTitle: NSLocalizedString(@"OK", "Save log alert panel -> button")];
407                [alert setMessageText: NSLocalizedString(@"Log Could Not Be Saved", "Save log alert panel -> title")];
408                [alert setInformativeText: [NSString stringWithFormat:
409                                            NSLocalizedString(@"There was a problem creating the file \"%@\".",
410                                                              "Save log alert panel -> message"), [[[panel URL] path] lastPathComponent]]];
411                [alert setAlertStyle: NSWarningAlertStyle];
412               
413                [alert runModal];
414                [alert release];
415            }
416        }
417    }];
418}
419
420@end
421
422@implementation MessageWindowController (Private)
423
424- (void) resizeColumn
425{
426    [fMessageTable noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange:
427                    NSMakeRange(0, [fMessageTable numberOfRows])]];
428}
429
430- (BOOL) shouldIncludeMessageForFilter: (NSString *) filterString message: (NSDictionary *) message
431{
432    if ([filterString isEqualToString: @""])
433        return YES;
434   
435    const NSStringCompareOptions searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
436    return [[message objectForKey: @"Name"] rangeOfString: filterString options: searchOptions].location != NSNotFound
437            || [[message objectForKey: @"Message"] rangeOfString: filterString options: searchOptions].location != NSNotFound;
438}
439
440- (void) updateListForFilter
441{
442    const NSInteger level = [[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"];
443    NSString * filterString = [fFilterField stringValue];
444   
445    NSIndexSet * indexes = [fMessages indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^BOOL(id message, NSUInteger idx, BOOL * stop) {
446        return [[(NSDictionary *)message objectForKey: @"Level"] integerValue] <= level && [self shouldIncludeMessageForFilter: filterString message: message];
447    }];
448   
449    NSArray * tempMessages = [[fMessages objectsAtIndexes: indexes] sortedArrayUsingDescriptors: [fMessageTable sortDescriptors]];
450   
451    const BOOL onLion = [NSApp isOnLionOrBetter];
452   
453    if (onLion)
454        [fMessageTable beginUpdates];
455   
456    //figure out which rows were added/moved
457    NSUInteger currentIndex = 0, totalCount = 0;
458    NSMutableArray * itemsToAdd = [NSMutableArray array];
459    NSMutableIndexSet * itemsToAddIndexes = [NSMutableIndexSet indexSet];
460   
461    for (NSDictionary * message in tempMessages)
462    {
463        const NSUInteger previousIndex = [fDisplayedMessages indexOfObject: message inRange: NSMakeRange(currentIndex, [fDisplayedMessages count]-currentIndex)];
464        if (previousIndex == NSNotFound)
465        {
466            [itemsToAdd addObject: message];
467            [itemsToAddIndexes addIndex: totalCount];
468        }
469        else
470        {
471            if (previousIndex != currentIndex)
472            {
473                [fDisplayedMessages moveObjectAtIndex: previousIndex toIndex: currentIndex];
474                if (onLion)
475                    [fMessageTable moveRowAtIndex: previousIndex toIndex: currentIndex];
476            }
477            ++currentIndex;
478        }
479       
480        ++totalCount;
481    }
482   
483    //remove trailing items - those are the unused
484    if (currentIndex < [fDisplayedMessages count])
485    {
486        const NSRange removeRange = NSMakeRange(currentIndex, [fDisplayedMessages count]-currentIndex);
487        [fDisplayedMessages removeObjectsInRange: removeRange];
488        if (onLion)
489            [fMessageTable removeRowsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: removeRange] withAnimation: NSTableViewAnimationSlideDown];
490    }
491   
492    //add new items
493    [fDisplayedMessages insertObjects: itemsToAdd atIndexes: itemsToAddIndexes];
494    if (onLion)
495        [fMessageTable insertRowsAtIndexes: itemsToAddIndexes withAnimation: NSTableViewAnimationSlideUp];
496   
497    if (onLion)
498        [fMessageTable endUpdates];
499    else
500    {
501        [fMessageTable reloadData];
502       
503        if ([fDisplayedMessages count] > 0)
504            [fMessageTable deselectAll: self];
505    }
506   
507    NSAssert2([fDisplayedMessages isEqualToArray: tempMessages], @"Inconsistency between message arrays! %@ %@", fDisplayedMessages, tempMessages);
508}
509
510- (NSString *) stringForMessage: (NSDictionary *) message
511{
512    NSString * levelString;
513    const NSInteger level = [[message objectForKey: @"Level"] integerValue];
514    switch (level)
515    {
516        case TR_MSG_ERR:
517            levelString = NSLocalizedString(@"Error", "Message window -> level");
518            break;
519        case TR_MSG_INF:
520            levelString = NSLocalizedString(@"Info", "Message window -> level");
521            break;
522        case TR_MSG_DBG:
523            levelString = NSLocalizedString(@"Debug", "Message window -> level");
524            break;
525        default:
526            NSAssert1(NO, @"Unknown message log level: %d", level);
527    }
528   
529    return [NSString stringWithFormat: @"%@ %@ [%@] %@: %@", [message objectForKey: @"Date"],
530            [message objectForKey: @"File"], levelString,
531            [message objectForKey: @"Name"], [message objectForKey: @"Message"], nil];
532}
533
534@end
Note: See TracBrowser for help on using the repository browser.