forked from ViennaRSS/vienna-rss
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ArticleListView.m
1963 lines (1748 loc) · 64.1 KB
/
ArticleListView.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ArticleListView.m
// Vienna
//
// Created by Steve on 8/27/05.
// Copyright (c) 2004-2005 Steve Palmer. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "ArticleListView.h"
#import "Preferences.h"
#import "Constants.h"
#import "AppController.h"
#import "ArticleController.h"
#import "SplitViewExtensions.h"
#import "MessageListView.h"
#import "ArticleView.h"
#import "FoldersTree.h"
#import "CalendarExtensions.h"
#import "StringExtensions.h"
#import "HelperFunctions.h"
#import "ArticleRef.h"
#import "ArticleFilter.h"
#import "XMLParser.h"
#import "Field.h"
#import <WebKit/WebKit.h>
#import "PopupButton.h"
#import "BrowserPane.h"
#import "ProgressTextCell.h"
// Private functions
@interface ArticleListView (Private)
-(void)initTableView;
-(BOOL)copyTableSelection:(NSArray *)rows toPasteboard:(NSPasteboard *)pboard;
-(void)setTableViewFont;
-(void)showSortDirection;
-(void)selectArticleAfterReload;
-(void)handleReadingPaneChange:(NSNotificationCenter *)nc;
-(BOOL)scrollToArticle:(NSString *)guid;
-(void)selectFirstUnreadInFolder;
-(BOOL)viewNextUnreadInCurrentFolder:(int)currentRow;
-(void)loadMinimumFontSize;
-(void)markCurrentRead:(NSTimer *)aTimer;
-(void)refreshImmediatelyArticleAtCurrentRow;
-(void)refreshArticleAtCurrentRow;
-(void)makeRowSelectedAndVisible:(int)rowIndex;
-(void)updateArticleListRowHeight;
-(void)setOrientation:(int)newLayout;
-(void)loadSplitSettingsForLayout;
-(void)saveSplitSettingsForLayout;
-(void)showEnclosureView;
-(void)hideEnclosureView;
-(void)printDocument;
-(void)setError:(NSError *)newError;
-(void)handleError:(NSError *)error withDataSource:(WebDataSource *)dataSource;
-(void)endMainFrameLoad;
@end
static const CGFloat MA_Minimum_ArticleList_Pane_Width = 80;
static const CGFloat MA_Minimum_Article_Pane_Width = 80;
@implementation ArticleListView
/* initWithFrame
* Initialise our view.
*/
-(id)initWithFrame:(NSRect)frame
{
if (([super initWithFrame:frame]) != nil)
{
isChangingOrientation = NO;
isInTableInit = NO;
blockSelectionHandler = NO;
blockMarkRead = NO;
guidOfArticleToSelect = nil;
markReadTimer = nil;
lastError = nil;
isCurrentPageFullHTML = NO;
isLoadingHTMLArticle = NO;
currentURL = nil;
}
return self;
}
/* awakeFromNib
* Do things that only make sense once the NIB is loaded.
*/
-(void)awakeFromNib
{
// Register for notification
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(handleArticleListFontChange:) name:@"MA_Notify_ArticleListFontChange" object:nil];
[nc addObserver:self selector:@selector(handleReadingPaneChange:) name:@"MA_Notify_ReadingPaneChange" object:nil];
[nc addObserver:self selector:@selector(handleLoadFullHTMLChange:) name:@"MA_Notify_LoadFullHTMLChange" object:nil];
[nc addObserver:self selector:@selector(handleArticleListStateChange:) name:@"MA_Notify_ArticleListStateChange" object:nil];
// Make us the frame load and UI delegate for the web view
[articleText setUIDelegate:self];
[articleText setFrameLoadDelegate:self];
[articleText setOpenLinksInNewBrowser:YES];
[articleText setController:controller];
// Make web preferences 16pt Arial to match Safari
[[articleText preferences] setStandardFontFamily:@"Arial"];
[[articleText preferences] setDefaultFontSize:16];
// Disable caching
[articleText setMaintainsBackForwardList:NO];
[[articleText backForwardList] setPageCacheSize:0];
}
/* initialiseArticleView
* Do the things to initialise the article view from the database. This is the
* only point during initialisation where the database is guaranteed to be
* ready for use.
*/
-(void)initialiseArticleView
{
Preferences * prefs = [Preferences standardPreferences];
// Mark the start of the init phase
isAppInitialising = YES;
// Create report and condensed view attribute dictionaries
NSMutableParagraphStyle * style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByTruncatingTail];
reportCellDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, nil];
unreadReportCellDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, nil];
selectionDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, [NSColor whiteColor], NSForegroundColorAttributeName, nil];
unreadTopLineDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, [NSColor blackColor], NSForegroundColorAttributeName, nil];
topLineDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, [NSColor blackColor], NSForegroundColorAttributeName, nil];
unreadTopLineSelectionDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, [NSColor whiteColor], NSForegroundColorAttributeName, nil];
middleLineDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, [NSColor blueColor], NSForegroundColorAttributeName, nil];
linkLineDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, [NSColor blueColor], NSForegroundColorAttributeName, nil];
bottomLineDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, [NSColor grayColor], NSForegroundColorAttributeName, nil];
[style release];
// Set the reading pane orientation
[self setOrientation:[prefs layout]];
[splitView2 setDelegate:self];
// Initialise the article list view
[self initTableView];
// Make sure we skip the column filter button in the Tab order
[articleList setNextKeyView:articleText];
// Done initialising
isAppInitialising = NO;
}
/* constrainMinCoordinate
* Make sure the article pane width isn't shrunk beyond a minimum width. Otherwise it looks
* untidy.
*/
-(CGFloat)splitView:(NSSplitView *)sender constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)offset
{
return (sender == splitView2 && offset == 0) ? MA_Minimum_ArticleList_Pane_Width : proposedMin;
}
/* constrainMaxCoordinate
* Make sure that the article pane isn't shrunk beyond a minimum size otherwise the splitview
* or controls within it start resizing odd.
*/
-(CGFloat)splitView:(NSSplitView *)sender constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)offset
{
if (sender == splitView2 && offset == 0)
{
NSRect mainFrame = [[splitView2 superview] frame];
return (tableLayout == MA_Layout_Condensed) ?
mainFrame.size.width - MA_Minimum_Article_Pane_Width :
mainFrame.size.height - MA_Minimum_Article_Pane_Width;
}
return proposedMax;
}
/* resizeSubviewsWithOldSize
* Constrain the article list pane to a fixed width.
*/
-(void)splitView:(NSSplitView *)sender resizeSubviewsWithOldSize:(NSSize)oldSize
{
CGFloat dividerThickness = [sender dividerThickness];
id sv1 = [[sender subviews] objectAtIndex:0];
id sv2 = [[sender subviews] objectAtIndex:1];
NSRect leftFrame = [sv1 frame];
NSRect rightFrame = [sv2 frame];
NSRect newFrame = [sender frame];
if (sender == splitView2)
{
if (isChangingOrientation)
[splitView2 adjustSubviews];
else
{
leftFrame.origin = NSMakePoint(0, 0);
if (tableLayout == MA_Layout_Condensed)
{
leftFrame.size.height = newFrame.size.height;
rightFrame.size.width = newFrame.size.width - leftFrame.size.width - dividerThickness;
rightFrame.size.height = newFrame.size.height;
rightFrame.origin.x = leftFrame.size.width + dividerThickness;
}
else
{
leftFrame.size.width = newFrame.size.width;
rightFrame.size.height = newFrame.size.height - leftFrame.size.height - dividerThickness;
rightFrame.size.width = newFrame.size.width;
rightFrame.origin.y = leftFrame.size.height + dividerThickness;
}
[sv1 setFrame:leftFrame];
[sv2 setFrame:rightFrame];
}
}
}
/* createWebViewWithRequest
* Called when the browser wants to create a new window. The request is opened in a new tab.
*/
-(WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request
{
[controller openURL:[request URL] inPreferredBrowser:YES];
// Change this to handle modifier key?
// Is this covered by the webView policy?
return nil;
}
/* runJavaScriptAlertPanelWithMessage
* Called when the browser wants to display a JavaScript alert panel containing the specified message.
*/
- (void)webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
NSRunInformationalAlertPanel(NSLocalizedString(@"JavaScript", @""), // title
message, // message
NSLocalizedString(@"OK", @""), // default button
nil, // alt button
nil); // other button
}
/* runJavaScriptConfirmPanelWithMessage
* Called when the browser wants to display a JavaScript confirmation panel with the specified message.
*/
- (BOOL)webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
NSInteger result = NSRunInformationalAlertPanel(NSLocalizedString(@"JavaScript", @""), // title
message, // message
NSLocalizedString(@"OK", @""), // default button
NSLocalizedString(@"Cancel", @""), // alt button
nil);
return NSAlertDefaultReturn == result;
}
/* setStatusText
* Called from the webview when some JavaScript writes status text. Echo this to
* our status bar.
*/
-(void)webView:(WebView *)sender setStatusText:(NSString *)text
{
if ([[controller browserView] activeTabItemView] == self)
[controller setStatusMessage:text persist:NO];
}
/* mouseDidMoveOverElement
* Called from the webview when the user positions the mouse over an element. If it's a link
* then echo the URL to the status bar like Safari does.
*/
-(void)webView:(WebView *)sender mouseDidMoveOverElement:(NSDictionary *)elementInformation modifierFlags:(NSUInteger )modifierFlags
{
NSURL * url = [elementInformation valueForKey:@"WebElementLinkURL"];
[controller setStatusMessage:(url ? [url absoluteString] : @"") persist:NO];
}
/* contextMenuItemsForElement
* Creates a new context menu for our article's web view.
*/
-(NSArray *)webView:(WebView *)sender contextMenuItemsForElement:(NSDictionary *)element defaultMenuItems:(NSArray *)defaultMenuItems
{
// If this is an URL link, do the link-specific items.
NSURL * urlLink = [element valueForKey:WebElementLinkURLKey];
if (urlLink != nil)
return [controller contextMenuItemsForElement:element defaultMenuItems:defaultMenuItems];
// If we have a full HTML page then do the additional web-page specific items.
if (isCurrentPageFullHTML)
{
WebFrame * frameKey = [element valueForKey:WebElementFrameKey];
if (frameKey != nil)
return [controller contextMenuItemsForElement:element defaultMenuItems:defaultMenuItems];
}
// Remove the reload menu item if we don't have a full HTML page.
if (!isCurrentPageFullHTML)
{
NSMutableArray * newDefaultMenu = [[NSMutableArray alloc] init];
int count = [defaultMenuItems count];
int index;
// Copy over everything but the reload menu item, which we can't handle if
// this is not a full HTML page since we don't have an URL.
for (index = 0; index < count; index++)
{
NSMenuItem * menuItem = [defaultMenuItems objectAtIndex:index];
if ([menuItem tag] != WebMenuItemTagReload)
[newDefaultMenu addObject:menuItem];
}
// If we still have some menu items then use that for the new default menu, otherwise
// set the default items to nil as we may have removed all the items.
if ([newDefaultMenu count] > 0)
defaultMenuItems = [newDefaultMenu autorelease];
else
{
defaultMenuItems = nil;
[newDefaultMenu release];
}
}
// Return the default menu items.
return defaultMenuItems;
}
/* initTableView
* Do all the initialization for the article list table view control
*/
-(void)initTableView
{
Preferences * prefs = [Preferences standardPreferences];
// Variable initialization here
currentSelectedRow = -1;
articleListFont = nil;
articleListUnreadFont = nil;
// Initialize the article columns from saved data
NSArray * dataArray = [prefs arrayForKey:MAPref_ArticleListColumns];
Database * db = [Database sharedDatabase];
Field * field;
NSUInteger index;
for (index = 0; index < [dataArray count];)
{
NSString * name;
int width = 100;
BOOL visible = NO;
name = [dataArray objectAtIndex:index++];
if (index < [dataArray count])
visible = [[dataArray objectAtIndex:index++] intValue] == YES;
if (index < [dataArray count])
width = [[dataArray objectAtIndex:index++] intValue];
field = [db fieldByName:name];
[field setVisible:visible];
[field setWidth:width];
}
// Set the default fonts
[self setTableViewFont];
// In condensed mode, the summary field takes up the whole space.
[articleList setColumnAutoresizingStyle:NSTableViewUniformColumnAutoresizingStyle];
// Get the default list of visible columns
[self updateVisibleColumns];
// Dynamically create the popup menu. This is one less thing to
// explicitly localise in the NIB file.
NSMenu * articleListMenu = [[NSMenu alloc] init];
[articleListMenu addItem:copyOfMenuItemWithAction(@selector(markRead:))];
[articleListMenu addItem:copyOfMenuItemWithAction(@selector(markFlagged:))];
[articleListMenu addItem:copyOfMenuItemWithAction(@selector(deleteMessage:))];
[articleListMenu addItem:copyOfMenuItemWithAction(@selector(restoreMessage:))];
[articleListMenu addItem:copyOfMenuItemWithAction(@selector(downloadEnclosure:))];
[articleListMenu addItem:[NSMenuItem separatorItem]];
[articleListMenu addItem:copyOfMenuItemWithAction(@selector(viewSourceHomePage:))];
NSMenuItem * alternateItem = copyOfMenuItemWithAction(@selector(viewSourceHomePageInAlternateBrowser:));
[alternateItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
[alternateItem setAlternate:YES];
[articleListMenu addItem:alternateItem];
[articleListMenu addItem:copyOfMenuItemWithAction(@selector(viewArticlePages:))];
alternateItem = copyOfMenuItemWithAction(@selector(viewArticlePagesInAlternateBrowser:));
[alternateItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
[alternateItem setAlternate:YES];
[articleListMenu addItem:alternateItem];
[articleList setMenu:articleListMenu];
[articleListMenu release];
// Set the target for double-click actions
[articleList setDoubleAction:@selector(doubleClickRow:)];
[articleList setAction:@selector(singleClickRow:)];
[articleList setDelegate:self];
[articleList setDataSource:self];
[articleList setTarget:self];
}
/* singleClickRow
* Handle a single click action. If the click was in the read or flagged column then
* treat it as an action to mark the article read/unread or flagged/unflagged. Later
* trap the comments column and expand/collapse. If the click lands on the enclosure
* colum, download the associated enclosure.
*/
-(IBAction)singleClickRow:(id)sender
{
int row = [articleList clickedRow];
int column = [articleList clickedColumn];
NSArray * allArticles = [articleController allArticles];
if (row >= 0 && row < (int)[allArticles count])
{
NSArray * columns = [articleList tableColumns];
if (column >= 0 && column < (int)[columns count])
{
Article * theArticle = [allArticles objectAtIndex:row];
NSString * columnName = [(NSTableColumn *)[columns objectAtIndex:column] identifier];
if ([columnName isEqualToString:MA_Field_Read])
{
[articleController markReadByArray:[NSArray arrayWithObject:theArticle] readFlag:![theArticle isRead]];
return;
}
if ([columnName isEqualToString:MA_Field_Flagged])
{
[articleController markFlaggedByArray:[NSArray arrayWithObject:theArticle] flagged:![theArticle isFlagged]];
return;
}
if ([columnName isEqualToString:MA_Field_HasEnclosure])
{
// TODO: Do interesting stuff with the enclosure here.
}
}
}
}
/* doubleClickRow
* Handle double-click on the selected article. Open the original feed item in
* the default browser.
*/
-(IBAction)doubleClickRow:(id)sender
{
if (currentSelectedRow != -1 && [articleList clickedRow] != -1)
{
Article * theArticle = [[articleController allArticles] objectAtIndex:currentSelectedRow];
[controller openURLFromString:[theArticle link] inPreferredBrowser:YES];
}
}
/* updateAlternateMenuTitle
* Sets the approprate title for the alternate item in the contextual menu
* when user changes preference for opening pages in external browser
*/
-(void)updateAlternateMenuTitle
{
NSMenuItem * mainMenuItem;
NSMenuItem * contextualMenuItem;
int index;
NSMenu * articleListMenu = [articleList menu];
if (articleListMenu == nil)
return;
mainMenuItem = menuItemWithAction(@selector(viewSourceHomePageInAlternateBrowser:));
if (mainMenuItem != nil)
{
index = [articleListMenu indexOfItemWithTarget:nil andAction:@selector(viewSourceHomePageInAlternateBrowser:)];
if (index >= 0)
{
contextualMenuItem = [articleListMenu itemAtIndex:index];
[contextualMenuItem setTitle:[mainMenuItem title]];
}
}
mainMenuItem = menuItemWithAction(@selector(viewArticlePagesInAlternateBrowser:));
if (mainMenuItem != nil)
{
index = [articleListMenu indexOfItemWithTarget:nil andAction:@selector(viewArticlePagesInAlternateBrowser:)];
if (index >= 0)
{
contextualMenuItem = [articleListMenu itemAtIndex:index];
[contextualMenuItem setTitle:[mainMenuItem title]];
}
}
}
/* ensureSelectedArticle
* Ensure that there is a selected article and that it is visible.
*/
-(void)ensureSelectedArticle:(BOOL)singleSelection
{
if (singleSelection)
{
int nextRow = [[articleList selectedRowIndexes] firstIndex];
int articlesCount = [[articleController allArticles] count];
currentSelectedRow = -1;
if (nextRow < 0 || nextRow >= articlesCount)
nextRow = articlesCount - 1;
[self makeRowSelectedAndVisible:nextRow];
}
else
{
if ([articleList selectedRow] == -1)
[self makeRowSelectedAndVisible:0];
else
[articleList scrollRowToVisible:[articleList selectedRow]];
}
}
/* updateVisibleColumns
* Iterates through the array of visible columns and makes them
* visible or invisible as needed.
*/
-(void)updateVisibleColumns
{
NSArray * fields = [[Database sharedDatabase] arrayOfFields];
int count = [fields count];
int index;
// Save current selection
NSIndexSet * selArray = [articleList selectedRowIndexes];
// Mark we're doing an update of the tableview
isInTableInit = YES;
// Remove old columns
NSTableColumn * lastColumn;
while ((lastColumn = [[articleList tableColumns] lastObject]))
[articleList removeTableColumn:lastColumn];
[self updateArticleListRowHeight];
// Create the new columns
for (index = 0; index < count; ++index)
{
Field * field = [fields objectAtIndex:index];
NSString * identifier = [field name];
int tag = [field tag];
BOOL showField;
// Handle condensed layout vs. table layout
if (tableLayout == MA_Layout_Report)
showField = [field visible] && tag != MA_FieldID_Headlines && tag != MA_FieldID_Comments;
else
{
showField = NO;
if (tag == MA_FieldID_Read || tag == MA_FieldID_Flagged || tag == MA_FieldID_HasEnclosure)
showField = [field visible];
if (tag == MA_FieldID_Headlines)
showField = YES;
}
// Add to the end only those columns that are visible
if (showField)
{
NSTableColumn * column = [[NSTableColumn alloc] initWithIdentifier:identifier];
// Fix for bug where tableviews with alternating background rows lose their "colour".
// Only text cells are affected.
if ([[column dataCell] isKindOfClass:[NSTextFieldCell class]])
{
[[column dataCell] setDrawsBackground:NO];
[[column dataCell] setWraps:YES];
}
// Replace the normal text field cell with a progress text cell so we can
// display a progress indicator when loading HTML pages. NOTE: This is handled
// in willDisplayCell:forTableColumn:row: where it sets the inProgress flag.
// We need to use a different column for condensed layout vs. table layout.
BOOL isProgressColumn = NO;
if (tableLayout == MA_Layout_Report && [[column identifier] isEqualToString:MA_Field_Subject])
isProgressColumn = YES;
else if (tableLayout == MA_Layout_Condensed && [[column identifier] isEqualToString:MA_Field_Headlines])
isProgressColumn = YES;
if (isProgressColumn)
{
ProgressTextCell * progressCell;
progressCell = [[[ProgressTextCell alloc] init] autorelease];
[column setDataCell:progressCell];
}
// Set the header attributes.
NSTableHeaderCell * headerCell = [column headerCell];
BOOL isResizable = (tag != MA_FieldID_Read && tag != MA_FieldID_Flagged && tag != MA_FieldID_Comments && tag != MA_FieldID_HasEnclosure);
[headerCell setTitle:[field displayName]];
// Set the other column atributes.
[column setEditable:NO];
[column setResizingMask:(isResizable ? (NSTableColumnAutoresizingMask | NSTableColumnUserResizingMask) : NSTableColumnNoResizing)];
[column setMinWidth:10];
[column setMaxWidth:1000];
[column setWidth:[field width]];
[articleList addTableColumn:column];
[column release];
}
}
// Set the images for specific header columns
[articleList setHeaderImage:MA_Field_Read imageName:@"unread_header.tiff"];
[articleList setHeaderImage:MA_Field_Flagged imageName:@"flagged_header.tiff"];
[articleList setHeaderImage:MA_Field_HasEnclosure imageName:@"enclosure_header.tiff"];
// Initialise the sort direction
[self showSortDirection];
// Put the selection back
[articleList selectRowIndexes:selArray byExtendingSelection:NO];
// Done
isInTableInit = NO;
}
/* saveTableSettings
* Save the table column settings, specifically the visibility and width.
*/
-(void)saveTableSettings
{
Preferences * prefs = [Preferences standardPreferences];
// Remember the current folder and article
NSString * guid = (currentSelectedRow >= 0) ? [[[articleController allArticles] objectAtIndex:currentSelectedRow] guid] : @"";
[prefs setInteger:[articleController currentFolderId] forKey:MAPref_CachedFolderID];
[prefs setString:guid forKey:MAPref_CachedArticleGUID];
// An array we need for the settings
NSMutableArray * dataArray = [[NSMutableArray alloc] init];
// Create the new columns
for (Field * field in [[Database sharedDatabase] arrayOfFields])
{
[dataArray addObject:[field name]];
[dataArray addObject:[NSNumber numberWithBool:[field visible]]];
[dataArray addObject:[NSNumber numberWithInt:[field width]]];
}
// Save these to the preferences
[prefs setObject:dataArray forKey:MAPref_ArticleListColumns];
// Save the split bar position
[self saveSplitSettingsForLayout];
// We're done
[dataArray release];
}
/* setTableViewFont
* Gets the font for the article list and adjusts the table view
* row height to properly display that font.
*/
-(void)setTableViewFont
{
[articleListFont release];
[articleListUnreadFont release];
Preferences * prefs = [Preferences standardPreferences];
articleListFont = [[NSFont fontWithName:[prefs articleListFont] size:[prefs articleListFontSize]] retain];
articleListUnreadFont = [prefs boolForKey:MAPref_ShowUnreadArticlesInBold] ? [[NSFontManager sharedFontManager] convertWeight:YES ofFont:articleListFont] : articleListFont;
[articleListUnreadFont retain];
[reportCellDict setObject:articleListFont forKey:NSFontAttributeName];
[unreadReportCellDict setObject:articleListUnreadFont forKey:NSFontAttributeName];
[topLineDict setObject:articleListFont forKey:NSFontAttributeName];
[unreadTopLineDict setObject:articleListUnreadFont forKey:NSFontAttributeName];
[middleLineDict setObject:articleListFont forKey:NSFontAttributeName];
[linkLineDict setObject:articleListFont forKey:NSFontAttributeName];
[bottomLineDict setObject:articleListFont forKey:NSFontAttributeName];
[selectionDict setObject:articleListFont forKey:NSFontAttributeName];
[unreadTopLineSelectionDict setObject:articleListUnreadFont forKey:NSFontAttributeName];
[self updateArticleListRowHeight];
}
/* updateArticleListRowHeight
* Compute the number of rows that the current view requires. For table layout, there's just
* one line. For condensed layout, the number of lines depends on which fields are visible but
* there's always a minimum of one line anyway.
*/
-(void)updateArticleListRowHeight
{
Database * db = [Database sharedDatabase];
float height = [[[NSApp delegate] layoutManager] defaultLineHeightForFont:articleListFont];
int numberOfRowsInCell;
if (tableLayout == MA_Layout_Report)
numberOfRowsInCell = 1;
else
{
numberOfRowsInCell = 0;
if ([[db fieldByName:MA_Field_Subject] visible])
++numberOfRowsInCell;
if ([[db fieldByName:MA_Field_Folder] visible] || [[db fieldByName:MA_Field_Date] visible] || [[db fieldByName:MA_Field_Author] visible])
++numberOfRowsInCell;
if ([[db fieldByName:MA_Field_Link] visible])
++numberOfRowsInCell;
if ([[db fieldByName:MA_Field_Summary] visible])
++numberOfRowsInCell;
if (numberOfRowsInCell == 0)
++numberOfRowsInCell;
}
[articleList setRowHeight:(height + 2.0f) * (float)numberOfRowsInCell];
}
/* showSortDirection
* Shows the current sort column and direction in the table.
*/
-(void)showSortDirection
{
NSString * sortColumnIdentifier = [articleController sortColumnIdentifier];
for (NSTableColumn * column in [articleList tableColumns])
{
if ([[column identifier] isEqualToString:sortColumnIdentifier])
{
NSString * imageName = ([[[[Preferences standardPreferences] articleSortDescriptors] objectAtIndex:0] ascending]) ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator";
[articleList setHighlightedTableColumn:column];
[articleList setIndicatorImage:[NSImage imageNamed:imageName] inTableColumn:column];
}
else
{
// Remove any existing image in the column header.
[articleList setIndicatorImage:nil inTableColumn:column];
}
}
}
/* scrollToArticle
* Moves the selection to the specified article. Returns YES if we found the
* article, NO otherwise.
*/
-(BOOL)scrollToArticle:(NSString *)guid
{
int rowIndex = 0;
BOOL found = NO;
for (Article * thisArticle in [articleController allArticles])
{
if ([[thisArticle guid] isEqualToString:guid])
{
[self makeRowSelectedAndVisible:rowIndex];
found = YES;
break;
}
++rowIndex;
}
return found;
}
/* mainView
* Return the primary view of this view.
*/
-(NSView *)mainView
{
return articleList;
}
/* webView
* Returns the webview used to display the articles
*/
-(WebView *)webView
{
return articleText;
}
/* canDeleteMessageAtRow
* Returns YES if the message at the specified row can be deleted, otherwise NO.
*/
-(BOOL)canDeleteMessageAtRow:(int)row
{
if ((row >= 0) && (row < [[articleController allArticles] count]))
{
Article * article = [[articleController allArticles] objectAtIndex:row];
return (article != nil) && ![[Database sharedDatabase] readOnly] && [[articleList window] isVisible];
}
return NO;
}
/* canGoForward
* Return TRUE if we can go forward in the backtrack queue.
*/
-(BOOL)canGoForward
{
return [articleController canGoForward];
}
/* canGoBack
* Return TRUE if we can go backward in the backtrack queue.
*/
-(BOOL)canGoBack
{
return [articleController canGoBack];
}
/* handleGoForward
* Move forward through the backtrack queue.
*/
-(IBAction)handleGoForward:(id)sender
{
[articleController goForward];
[[NSApp mainWindow] makeFirstResponder:([self selectedArticle] != nil) ? articleList : [foldersTree mainView]];
}
/* handleGoBack
* Move backward through the backtrack queue.
*/
-(IBAction)handleGoBack:(id)sender
{
[articleController goBack];
[[NSApp mainWindow] makeFirstResponder:([self selectedArticle] != nil) ? articleList : [foldersTree mainView]];
}
/* handleKeyDown [delegate]
* Support special key codes. If we handle the key, return YES otherwise
* return NO to allow the framework to pass it on for default processing.
*/
-(BOOL)handleKeyDown:(unichar)keyChar withFlags:(NSUInteger )flags
{
return [controller handleKeyDown:keyChar withFlags:flags];
}
/* selectedArticle
* Returns the selected article, or nil if no article is selected.
*/
-(Article *)selectedArticle
{
return (currentSelectedRow >= 0) ? [[articleController allArticles] objectAtIndex:currentSelectedRow] : nil;
}
/* printDocument
* Print the active article.
*/
-(void)printDocument:(id)sender
{
[articleText printDocument:sender];
}
/* setError
* Save the most recent error instance.
*/
-(void)setError:(NSError *)newError
{
[newError retain];
[lastError release];
lastError = newError;
}
/* handleArticleListFontChange
* Called when the user changes the article list font and/or size in the Preferences
*/
-(void)handleArticleListFontChange:(NSNotification *)note
{
[self setTableViewFont];
if (self == [articleController mainArticleView])
{
[articleList reloadData];
}
}
-(void)handleArticleListStateChange:(NSNotification *)note
{
if (self == [articleController mainArticleView])
{
[articleList reloadData];
}
}
/* handleLoadFullHTMLChange
* Called when the user changes the folder setting to load the article in full HTML.
*/
-(void)handleLoadFullHTMLChange:(NSNotification *)note
{
if (self == [articleController mainArticleView])
[self refreshArticlePane];
}
/* handleReadingPaneChange
* Respond to the change to the reading pane orientation.
*/
-(void)handleReadingPaneChange:(NSNotificationCenter *)nc
{
if (self == [articleController mainArticleView])
{
[self saveSplitSettingsForLayout];
[self setOrientation:[[Preferences standardPreferences] layout]];
[self updateVisibleColumns];
[articleList reloadData];
}
}
/* loadSplitSettingsForLayout
* Set the splitview position for the current layout from the preferences.
*/
-(void)loadSplitSettingsForLayout
{
NSString * splitPrefsName = (tableLayout == MA_Layout_Report) ? @"SplitView2ReportLayout" : @"SplitView2CondensedLayout";
[splitView2 setLayout:[[Preferences standardPreferences] objectForKey:splitPrefsName]];
}
/* saveSplitSettingsForLayout
* Save the splitview position for the current layout to the preferences.
*/
-(void)saveSplitSettingsForLayout
{
NSString * splitPrefsName = (tableLayout == MA_Layout_Report) ? @"SplitView2ReportLayout" : @"SplitView2CondensedLayout";
[[Preferences standardPreferences] setObject:[splitView2 layout] forKey:splitPrefsName];
}
/* setOrientation
* Adjusts the article view orientation and updates the article list row
* height to accommodate the summary view
*/
-(void)setOrientation:(int)newLayout
{
isChangingOrientation = YES;
tableLayout = newLayout;
[splitView2 setVertical:(newLayout == MA_Layout_Condensed)];
[self loadSplitSettingsForLayout];
[splitView2 display];
isChangingOrientation = NO;
}
/* tableLayout
* Returns the active table layout.
*/
-(int)tableLayout
{
return tableLayout;
}
/* makeRowSelectedAndVisible
* Selects the specified row in the table and makes it visible by
* scrolling it to the center of the table.
*/
-(void)makeRowSelectedAndVisible:(int)rowIndex
{
if ([[articleController allArticles] count] == 0u)
{
currentSelectedRow = -1;
[articleList deselectAll:self];
}
else if (rowIndex == currentSelectedRow)
[self refreshArticleAtCurrentRow];
else
{
[articleList selectRowIndexes:[NSIndexSet indexSetWithIndex:rowIndex] byExtendingSelection:NO];
if (currentSelectedRow == -1 || blockSelectionHandler)
{
currentSelectedRow = rowIndex;
[self refreshImmediatelyArticleAtCurrentRow];
}
int pageSize = [articleList rowsInRect:[articleList visibleRect]].length;
int lastRow = [articleList numberOfRows] - 1;
int visibleRow = currentSelectedRow + (pageSize / 2);
if (visibleRow > lastRow)
visibleRow = lastRow;
[articleList scrollRowToVisible:currentSelectedRow];
[articleList scrollRowToVisible:visibleRow];
}
}
/* displayFirstUnread
* Locate the first unread article.
*/
-(void)displayFirstUnread
{
// Mark the current article read.
[self markCurrentRead:nil];
// If there are any unread articles then select the first one in the
// first folder.
if ([[Database sharedDatabase] countOfUnread] > 0)
{
guidOfArticleToSelect = nil;
// Get the first folder with unread articles.
int firstFolderWithUnread = [foldersTree firstFolderWithUnread];
// Select the folder in the tree view.
[foldersTree selectFolder:firstFolderWithUnread];
// Now select the first unread article.
[self selectFirstUnreadInFolder];
}
}
/* displayNextUnread
* Locate the next unread article from the current article onward.
*/
-(void)displayNextUnread