3 This file is part of the HandBrake source code.
4 Homepage: <http://handbrake.fr/>.
5 It may be used under the terms of the GNU General Public License. */
7 #import "HBQueueController.h"
9 #import "HBImageAndTextCell.h"
11 #define HB_ROW_HEIGHT_TITLE_ONLY 17.0
12 #define HB_ROW_HEIGHT_FULL_DESCRIPTION 200.0
13 // Pasteboard type for or drag operations
14 #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
16 //------------------------------------------------------------------------------------
18 //------------------------------------------------------------------------------------
20 //------------------------------------------------------------------------------------
21 // NSMutableAttributedString (HBAdditions)
22 //------------------------------------------------------------------------------------
24 @interface NSMutableAttributedString (HBAdditions)
25 - (void) appendString: (NSString*)aString withAttributes: (NSDictionary *)aDictionary;
28 @implementation NSMutableAttributedString (HBAdditions)
29 - (void) appendString: (NSString*)aString withAttributes: (NSDictionary *)aDictionary
31 NSAttributedString * s = [[[NSAttributedString alloc]
32 initWithString: aString
33 attributes: aDictionary] autorelease];
34 [self appendAttributedString: s];
39 @implementation HBQueueOutlineView
41 - (void)viewDidEndLiveResize
43 // Since we disabled calculating row heights during a live resize, force them to
45 [self noteHeightOfRowsWithIndexesChanged:
46 [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [self numberOfRows])]];
47 [super viewDidEndLiveResize];
52 /* This should be for dragging, we take this info from the presets right now */
53 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
57 // By default, NSTableView only drags an image of the first column. Change this to
58 // drag an image of the queue's icon and desc and action columns.
59 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"desc"], [self tableColumnWithIdentifier:@"icon"],[self tableColumnWithIdentifier:@"action"], nil];
60 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
65 - (void) mouseDown:(NSEvent *)theEvent
67 [super mouseDown:theEvent];
82 #pragma mark Toolbar Identifiers
83 // Toolbar identifiers
84 static NSString* HBQueueToolbar = @"HBQueueToolbar1";
85 static NSString* HBQueueStartCancelToolbarIdentifier = @"HBQueueStartCancelToolbarIdentifier";
86 static NSString* HBQueuePauseResumeToolbarIdentifier = @"HBQueuePauseResumeToolbarIdentifier";
90 @implementation HBQueueController
92 //------------------------------------------------------------------------------------
94 //------------------------------------------------------------------------------------
97 if (self = [super initWithWindowNibName:@"Queue"])
99 // NSWindowController likes to lazily load its window nib. Since this
100 // controller tries to touch the outlets before accessing the window, we
101 // need to force it to load immadiately by invoking its accessor.
103 // If/when we switch to using bindings, this can probably go away.
107 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
108 @"NO", @"QueueWindowIsOpen",
109 @"NO", @"QueueShowsDetail",
110 @"YES", @"QueueShowsJobsAsGroups",
113 fJobGroups = [[NSMutableArray arrayWithCapacity:0] retain];
118 - (void)setQueueArray: (NSMutableArray *)QueueFileArray
120 [fJobGroups setArray:QueueFileArray];
122 /* First stop any timer working now */
123 [self stopAnimatingCurrentJobGroupInQueue];
124 [fOutlineView reloadData];
128 /* lets get the stats on the status of the queue array */
130 fEncodingQueueItem = 0;
136 /* We use a number system to set the encode status of the queue item
138 * 0 == already encoded
139 * 1 == is being encoded
140 * 2 == is yet to be encoded
145 NSEnumerator *enumerator = [fJobGroups objectEnumerator];
147 while (tempObject = [enumerator nextObject])
149 NSDictionary *thisQueueDict = tempObject;
150 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
154 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
157 fEncodingQueueItem = i;
159 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
163 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
170 /* We should fire up the encoding timer here based on fWorkingCount */
172 if (fWorkingCount > 0)
174 /* we have an encoding job so, lets start the animation timer */
175 [self startAnimatingCurrentWorkingEncodeInQueue];
178 /* Set the queue status field in the queue window */
179 NSMutableString * string;
180 if (fPendingCount == 1)
182 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending", @"" ), fPendingCount];
186 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending", @"" ), fPendingCount];
188 [fQueueCountField setStringValue:string];
191 /* This method sets the status string in the queue window
192 * and is called from Controller.mm (fHBController)
193 * instead of running another timer here polling libhb
194 * for encoding status
196 - (void)setQueueStatusString: (NSString *)statusString
198 [fProgressTextField setStringValue:statusString];
201 //------------------------------------------------------------------------------------
203 //------------------------------------------------------------------------------------
206 // clear the delegate so that windowWillClose is not attempted
207 if( [[self window] delegate] == self )
208 [[self window] setDelegate:nil];
210 [fJobGroups release];
212 [fSavedExpandedItems release];
213 [fSavedSelectedItems release];
215 [[NSNotificationCenter defaultCenter] removeObserver:self];
220 //------------------------------------------------------------------------------------
222 //------------------------------------------------------------------------------------
223 - (void)setHandle: (hb_handle_t *)handle
225 fQueueEncodeLibhb = handle;
228 //------------------------------------------------------------------------------------
229 // Receive HBController
230 //------------------------------------------------------------------------------------
231 - (void)setHBController: (HBController *)controller
233 fHBController = controller;
238 //------------------------------------------------------------------------------------
239 // Displays and brings the queue window to the front
240 //------------------------------------------------------------------------------------
241 - (IBAction) showQueueWindow: (id)sender
243 [self showWindow:sender];
244 [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"QueueWindowIsOpen"];
249 //------------------------------------------------------------------------------------
251 //------------------------------------------------------------------------------------
256 if( ![[self window] setFrameUsingName:@"Queue"] )
257 [[self window] center];
258 [self setWindowFrameAutosaveName:@"Queue"];
259 [[self window] setExcludedFromWindowsMenu:YES];
261 /* lets setup our queue list outline view for drag and drop here */
262 [fOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
263 [fOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
264 [fOutlineView setVerticalMotionCanBeginDrag: YES];
267 // Don't allow autoresizing of main column, else the "delete" column will get
268 // pushed out of view.
269 [fOutlineView setAutoresizesOutlineColumn: NO];
271 #if HB_OUTLINE_METRIC_CONTROLS
272 [fIndentation setHidden: NO];
273 [fSpacing setHidden: NO];
274 [fIndentation setIntegerValue:[fOutlineView indentationPerLevel]]; // debug
275 [fSpacing setIntegerValue:3]; // debug
278 // Show/hide UI elements
279 fCurrentJobPaneShown = NO; // it's shown in the nib
280 //[self showCurrentJobPane:NO];
282 //[self updateQueueCountField];
286 //------------------------------------------------------------------------------------
288 //------------------------------------------------------------------------------------
289 - (void)windowWillClose:(NSNotification *)aNotification
291 [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"QueueWindowIsOpen"];
296 //------------------------------------------------------------------------------------
298 //------------------------------------------------------------------------------------
301 // Create a new toolbar instance, and attach it to our window
302 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: HBQueueToolbar] autorelease];
304 // Set up toolbar properties: Allow customization, give a default display mode, and remember state in user defaults
305 [toolbar setAllowsUserCustomization: YES];
306 [toolbar setAutosavesConfiguration: YES];
307 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
309 // We are the delegate
310 [toolbar setDelegate: self];
312 // Attach the toolbar to our window
313 [[self window] setToolbar:toolbar];
316 //------------------------------------------------------------------------------------
317 // toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:
318 //------------------------------------------------------------------------------------
319 - (NSToolbarItem *)toolbar:(NSToolbar *)toolbar
320 itemForItemIdentifier:(NSString *)itemIdentifier
321 willBeInsertedIntoToolbar:(BOOL)flag
323 // Required delegate method: Given an item identifier, this method returns an item.
324 // The toolbar will use this method to obtain toolbar items that can be displayed
325 // in the customization sheet, or in the toolbar itself.
327 NSToolbarItem *toolbarItem = nil;
329 if ([itemIdentifier isEqual: HBQueueStartCancelToolbarIdentifier])
331 toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
333 // Set the text label to be displayed in the toolbar and customization palette
334 [toolbarItem setLabel: @"Start"];
335 [toolbarItem setPaletteLabel: @"Start/Cancel"];
337 // Set up a reasonable tooltip, and image
338 [toolbarItem setToolTip: @"Start Encoding"];
339 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
341 // Tell the item what message to send when it is clicked
342 [toolbarItem setTarget: self];
343 [toolbarItem setAction: @selector(toggleStartCancel:)];
346 if ([itemIdentifier isEqual: HBQueuePauseResumeToolbarIdentifier])
348 toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
350 // Set the text label to be displayed in the toolbar and customization palette
351 [toolbarItem setLabel: @"Pause"];
352 [toolbarItem setPaletteLabel: @"Pause/Resume"];
354 // Set up a reasonable tooltip, and image
355 [toolbarItem setToolTip: @"Pause Encoding"];
356 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
358 // Tell the item what message to send when it is clicked
359 [toolbarItem setTarget: self];
360 [toolbarItem setAction: @selector(togglePauseResume:)];
366 //------------------------------------------------------------------------------------
367 // toolbarDefaultItemIdentifiers:
368 //------------------------------------------------------------------------------------
369 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
371 // Required delegate method: Returns the ordered list of items to be shown in the
372 // toolbar by default.
374 return [NSArray arrayWithObjects:
375 HBQueueStartCancelToolbarIdentifier,
376 HBQueuePauseResumeToolbarIdentifier,
380 //------------------------------------------------------------------------------------
381 // toolbarAllowedItemIdentifiers:
382 //------------------------------------------------------------------------------------
383 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
385 // Required delegate method: Returns the list of all allowed items by identifier.
386 // By default, the toolbar does not assume any items are allowed, even the
387 // separator. So, every allowed item must be explicitly listed.
389 return [NSArray arrayWithObjects:
390 HBQueueStartCancelToolbarIdentifier,
391 HBQueuePauseResumeToolbarIdentifier,
392 NSToolbarCustomizeToolbarItemIdentifier,
393 NSToolbarFlexibleSpaceItemIdentifier,
394 NSToolbarSpaceItemIdentifier,
395 NSToolbarSeparatorItemIdentifier,
399 //------------------------------------------------------------------------------------
400 // validateToolbarItem:
401 //------------------------------------------------------------------------------------
402 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
404 // Optional method: This message is sent to us since we are the target of some
405 // toolbar item actions.
407 if (!fQueueEncodeLibhb) return NO;
412 hb_get_state2 (fQueueEncodeLibhb, &s);
414 if ([[toolbarItem itemIdentifier] isEqual: HBQueueStartCancelToolbarIdentifier])
416 if ((s.state == HB_STATE_PAUSED) || (s.state == HB_STATE_WORKING) || (s.state == HB_STATE_MUXING))
419 [toolbarItem setImage:[NSImage imageNamed: @"Stop"]];
420 [toolbarItem setLabel: @"Stop"];
421 [toolbarItem setToolTip: @"Stop Encoding"];
424 else if (fPendingCount > 0)
427 [toolbarItem setImage:[NSImage imageNamed: @"Play"]];
428 [toolbarItem setLabel: @"Start"];
429 [toolbarItem setToolTip: @"Start Encoding"];
435 [toolbarItem setImage:[NSImage imageNamed: @"Play"]];
436 [toolbarItem setLabel: @"Start"];
437 [toolbarItem setToolTip: @"Start Encoding"];
441 if ([[toolbarItem itemIdentifier] isEqual: HBQueuePauseResumeToolbarIdentifier])
443 if (s.state == HB_STATE_PAUSED)
446 [toolbarItem setImage:[NSImage imageNamed: @"Play"]];
447 [toolbarItem setLabel: @"Resume"];
448 [toolbarItem setToolTip: @"Resume Encoding"];
451 else if ((s.state == HB_STATE_WORKING) || (s.state == HB_STATE_MUXING))
454 [toolbarItem setImage:[NSImage imageNamed: @"Pause"]];
455 [toolbarItem setLabel: @"Pause"];
456 [toolbarItem setToolTip: @"Pause Encoding"];
461 [toolbarItem setImage:[NSImage imageNamed: @"Pause"]];
462 [toolbarItem setLabel: @"Pause"];
463 [toolbarItem setToolTip: @"Pause Encoding"];
473 #pragma mark Queue Item Controls
474 //------------------------------------------------------------------------------------
475 // Delete encodes from the queue window and accompanying array
476 // Also handling first cancelling the encode if in fact its currently encoding.
477 //------------------------------------------------------------------------------------
478 - (IBAction)removeSelectedQueueItem: (id)sender
480 NSIndexSet * selectedRows = [fOutlineView selectedRowIndexes];
481 int row = [selectedRows firstIndex];
482 /* if this is a currently encoding job, we need to be sure to alert the user,
483 * to let them decide to cancel it first, then if they do, we can come back and
486 if ([[[fJobGroups objectAtIndex:row] objectForKey:@"Status"] intValue] == 1)
488 /* We pause the encode here so that it doesn't finish right after and then
489 * screw up the sync while the window is open
491 [fHBController Pause:NULL];
492 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"Stop This Encode and Remove It ?", nil)];
493 // Which window to attach the sheet to?
494 NSWindow * docWindow;
495 if ([sender respondsToSelector: @selector(window)])
496 docWindow = [sender window];
499 NSBeginCriticalAlertSheet(
501 NSLocalizedString(@"Keep Encoding", nil),
503 NSLocalizedString(@"Stop Encoding and Delete", nil),
505 nil, @selector(didDimissCancelCurrentJob:returnCode:contextInfo:), nil,
506 NSLocalizedString(@"Your movie will be lost if you don't continue encoding.", nil));
508 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
512 /* since we are not a currently encoding item, we can just be cancelled */
513 [fHBController removeQueueFileItem:row];
517 - (void) didDimissCancelCurrentJob: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
519 /* We resume encoding and perform the appropriate actions
520 * Note: Pause: is a toggle type method based on hb's current
521 * state, if it paused, it will resume encoding and vice versa.
522 * In this case, we are paused from the calling window, so calling
523 * [fHBController Pause:NULL]; Again will resume encoding
525 [fHBController Pause:NULL];
526 if (returnCode == NSAlertOtherReturn)
528 /* We need to save the currently encoding item number first */
529 int encodingItemToRemove = fEncodingQueueItem;
530 /* Since we are encoding, we need to let fHBController Cancel this job
531 * upon which it will move to the next one if there is one
533 [fHBController doCancelCurrentJob];
534 /* Now, we can go ahead and remove the job we just cancelled since
535 * we have its item number from above
537 [fHBController removeQueueFileItem:encodingItemToRemove];
542 //------------------------------------------------------------------------------------
543 // Show the finished encode in the finder
544 //------------------------------------------------------------------------------------
545 - (IBAction)revealSelectedQueueItem: (id)sender
547 NSIndexSet * selectedRows = [fOutlineView selectedRowIndexes];
548 NSInteger row = [selectedRows firstIndex];
549 if (row != NSNotFound)
551 while (row != NSNotFound)
553 NSMutableDictionary *queueItemToOpen = [fOutlineView itemAtRow: row];
554 [[NSWorkspace sharedWorkspace] selectFile:[queueItemToOpen objectForKey:@"DestinationPath"] inFileViewerRootedAtPath:nil];
556 row = [selectedRows indexGreaterThanIndex: row];
562 //------------------------------------------------------------------------------------
563 // Starts or cancels the processing of jobs depending on the current state
564 //------------------------------------------------------------------------------------
565 - (IBAction)toggleStartCancel: (id)sender
567 if (!fQueueEncodeLibhb) return;
570 hb_get_state2 (fQueueEncodeLibhb, &s);
572 if ((s.state == HB_STATE_PAUSED) || (s.state == HB_STATE_WORKING) || (s.state == HB_STATE_MUXING))
573 [fHBController Cancel: fQueuePane]; // sender == fQueuePane so that warning alert shows up on queue window
575 else if (fPendingCount > 0)
576 [fHBController Rip: NULL];
579 //------------------------------------------------------------------------------------
580 // Toggles the pause/resume state of libhb
581 //------------------------------------------------------------------------------------
582 - (IBAction)togglePauseResume: (id)sender
584 if (!fQueueEncodeLibhb) return;
587 hb_get_state2 (fQueueEncodeLibhb, &s);
589 if (s.state == HB_STATE_PAUSED)
590 hb_resume (fQueueEncodeLibhb);
591 else if ((s.state == HB_STATE_WORKING) || (s.state == HB_STATE_MUXING))
592 hb_pause (fQueueEncodeLibhb);
598 #pragma mark Animate Endcoding Item
603 //------------------------------------------------------------------------------------
604 // Starts animating the job icon of the currently processing job in the queue outline
606 //------------------------------------------------------------------------------------
607 - (void) startAnimatingCurrentWorkingEncodeInQueue
609 if (!fAnimationTimer)
610 fAnimationTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0/12.0 // 1/12 because there are 6 images in the animation cycle
612 selector:@selector(animateWorkingEncodeInQueue:)
614 repeats:YES] retain];
617 //------------------------------------------------------------------------------------
618 // If a job is currently processing, its job icon in the queue outline view is
619 // animated to its next state.
620 //------------------------------------------------------------------------------------
621 - (void) animateWorkingEncodeInQueue:(NSTimer*)theTimer
623 if (fWorkingCount > 0)
626 fAnimationIndex %= 6; // there are 6 animation images; see outlineView:objectValueForTableColumn:byItem: below.
627 [self animateWorkingEncodeIconInQueue];
632 - (void) animateWorkingEncodeIconInQueue
634 NSInteger row = fEncodingQueueItem; /// need to set to fEncodingQueueItem
635 NSInteger col = [fOutlineView columnWithIdentifier: @"icon"];
636 if (row != -1 && col != -1)
638 NSRect frame = [fOutlineView frameOfCellAtColumn:col row:row];
639 [fOutlineView setNeedsDisplayInRect: frame];
643 //------------------------------------------------------------------------------------
644 // Stops animating the job icon of the currently processing job in the queue outline
646 //------------------------------------------------------------------------------------
647 - (void) stopAnimatingCurrentJobGroupInQueue
649 if (fAnimationTimer && [fAnimationTimer isValid])
651 [fAnimationTimer invalidate];
652 [fAnimationTimer release];
653 fAnimationTimer = nil;
660 - (void)moveObjectsInArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
662 NSUInteger index = [indexSet lastIndex];
663 NSUInteger aboveInsertIndexCount = 0;
665 while (index != NSNotFound)
667 NSUInteger removeIndex;
669 if (index >= insertIndex)
671 removeIndex = index + aboveInsertIndexCount;
672 aboveInsertIndexCount++;
680 id object = [[array objectAtIndex:removeIndex] retain];
681 [array removeObjectAtIndex:removeIndex];
682 [array insertObject:object atIndex:insertIndex];
685 index = [indexSet indexLessThanIndex:index];
691 #pragma mark NSOutlineView delegate
694 - (id)outlineView:(NSOutlineView *)fOutlineView child:(NSInteger)index ofItem:(id)item
697 return [fJobGroups objectAtIndex:index];
699 // We are only one level deep, so we can't be asked about children
700 NSAssert (NO, @"HBQueueController outlineView:child:ofItem: can't handle nested items.");
704 - (BOOL)outlineView:(NSOutlineView *)fOutlineView isItemExpandable:(id)item
706 // Our outline view has no levels, but we can still expand every item. Doing so
707 // just makes the row taller. See heightOfRowByItem below.
711 - (BOOL)outlineView:(NSOutlineView *)fOutlineView shouldExpandItem:(id)item
713 // Our outline view has no levels, but we can still expand every item. Doing so
714 // just makes the row taller. See heightOfRowByItem below.
716 // Don't autoexpand while dragging, since we can't drop into the items
717 // return ![(HBQueueOutlineView*)fOutlineView isDragging];
719 return YES; //<-- Needs to be YES to allow expanding
723 - (NSInteger)outlineView:(NSOutlineView *)fOutlineView numberOfChildrenOfItem:(id)item
725 // Our outline view has no levels, so number of children will be zero for all
728 return [fJobGroups count];
733 - (void)outlineViewItemDidCollapse:(NSNotification *)notification
735 id item = [[notification userInfo] objectForKey:@"NSObject"];
736 NSInteger row = [fOutlineView rowForItem:item];
737 [fOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(row,1)]];
740 - (void)outlineViewItemDidExpand:(NSNotification *)notification
742 id item = [[notification userInfo] objectForKey:@"NSObject"];
743 NSInteger row = [fOutlineView rowForItem:item];
744 [fOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(row,1)]];
747 - (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item
749 if ([outlineView isItemExpanded: item])
751 // Short-circuit here if in a live resize primarily to fix a bug but also to
752 // increase resposivness during a resize. There's a bug in NSTableView that
753 // causes row heights to get messed up if you try to change them during a live
754 // resize. So if in a live resize, simply return the previously calculated
755 // height. The row heights will get fixed up after the resize because we have
756 // implemented viewDidEndLiveResize to force all of them to be recalculated.
757 // if ([outlineView inLiveResize] && [item lastDescriptionHeight] > 0)
758 // return [item lastDescriptionHeight];
760 // CGFloat width = [[outlineView tableColumnWithIdentifier: @"desc"] width];
761 // Column width is NOT what is ultimately used. I can't quite figure out what
762 // width to use for calculating text metrics. No matter how I tweak this value,
763 // there are a few conditions in which the drawn text extends below the bounds
764 // of the row cell. In previous versions, which ran under Tiger, I was
765 // reducing width by 47 pixles.
766 // width -= 2; // (?) for intercell spacing
768 // CGFloat height = [item heightOfDescriptionForWidth: width];
771 return HB_ROW_HEIGHT_FULL_DESCRIPTION;
774 return HB_ROW_HEIGHT_TITLE_ONLY;
777 - (CGFloat) heightOfDescriptionForWidth:(CGFloat)width
779 // Try to return the cached value if no changes have happened since the last time
780 //if ((width == fLastDescriptionWidth) && (fLastDescriptionHeight != 0) && !fNeedsDescription)
781 // return fLastDescriptionHeight;
783 //if (fNeedsDescription)
784 // [self updateDescription];
786 // Calculate the height
787 //NSRect bounds = [fDescription boundingRectWithSize:NSMakeSize(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin];
788 //fLastDescriptionHeight = bounds.size.height + 6.0; // add some border to bottom
789 //fLastDescriptionWidth = width;
790 return HB_ROW_HEIGHT_FULL_DESCRIPTION;
792 /* supposedly another way to do this, in case boundingRectWithSize isn't working
793 NSTextView* tmpView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, width, 1)];
794 [[tmpView textStorage] setAttributedString:aString];
795 [tmpView setHorizontallyResizable:NO];
796 [tmpView setVerticallyResizable:YES];
797 // [[tmpView textContainer] setHeightTracksTextView: YES];
798 // [[tmpView textContainer] setContainerSize: NSMakeSize(width, 10000)];
800 float height = [tmpView frame].size.height;
806 - (CGFloat) lastDescriptionHeight
808 return HB_ROW_HEIGHT_FULL_DESCRIPTION;
811 - (id)outlineView:(NSOutlineView *)fOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
813 // nb: The "desc" column is currently an HBImageAndTextCell. However, we are longer
814 // using the image portion of the cell so we could switch back to a regular NSTextFieldCell.
816 if ([[tableColumn identifier] isEqualToString:@"desc"])
818 /* This should have caused the description we wanted to show*/
819 //return [item objectForKey:@"SourceName"];
821 /* code to build the description as per old queue */
822 //return [self formatEncodeItemDescription:item];
824 /* Below should be put into a separate method but I am way too f'ing lazy right now */
825 NSMutableAttributedString * finalString = [[[NSMutableAttributedString alloc] initWithString: @""] autorelease];
827 NSMutableParagraphStyle * ps = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] retain];
828 [ps setHeadIndent: 40.0];
829 [ps setParagraphSpacing: 1.0];
830 [ps setTabStops:[NSArray array]]; // clear all tabs
831 [ps addTabStop: [[[NSTextTab alloc] initWithType: NSLeftTabStopType location: 20.0] autorelease]];
834 NSDictionary* detailAttr = [NSDictionary dictionaryWithObjectsAndKeys:
835 [NSFont systemFontOfSize:10.0], NSFontAttributeName,
836 ps, NSParagraphStyleAttributeName,
839 NSDictionary* detailBoldAttr = [NSDictionary dictionaryWithObjectsAndKeys:
840 [NSFont boldSystemFontOfSize:10.0], NSFontAttributeName,
841 ps, NSParagraphStyleAttributeName,
844 NSDictionary* titleAttr = [NSDictionary dictionaryWithObjectsAndKeys:
845 [NSFont systemFontOfSize:[NSFont systemFontSize]], NSFontAttributeName,
846 ps, NSParagraphStyleAttributeName,
849 NSDictionary* shortHeightAttr = [NSDictionary dictionaryWithObjectsAndKeys:
850 [NSFont systemFontOfSize:2.0], NSFontAttributeName,
853 /* First line, we should strip the destination path and just show the file name and add the title num and chapters (if any) */
854 //finalDescription = [finalDescription stringByAppendingString:[NSString stringWithFormat:@"Source: %@ Output: %@\n", [item objectForKey:@"SourceName"],[item objectForKey:@"DestinationPath"]]];
855 NSString * summaryInfo;
857 NSString * titleString = [NSString stringWithFormat:@"Title %d", [[item objectForKey:@"TitleNumber"] intValue]];
859 NSString * chapterString = ([[item objectForKey:@"ChapterStart"] intValue] == [[item objectForKey:@"ChapterEnd"] intValue]) ?
860 [NSString stringWithFormat:@"Chapter %d", [[item objectForKey:@"ChapterStart"] intValue]] :
861 [NSString stringWithFormat:@"Chapters %d through %d", [[item objectForKey:@"ChapterStart"] intValue], [[item objectForKey:@"ChapterEnd"] intValue]];
863 NSString * passesString;
864 if ([[item objectForKey:@"VideoTwoPass"] intValue] == 0)
866 passesString = [NSString stringWithFormat:@"1 Video Pass"];
870 if ([[item objectForKey:@"VideoTurboTwoPass"] intValue] == 1)
872 passesString = [NSString stringWithFormat:@"2 Video Passes Turbo"];
876 passesString = [NSString stringWithFormat:@"2 Video Passes"];
880 [finalString appendString:[NSString stringWithFormat:@"%@", [item objectForKey:@"SourceName"]] withAttributes:titleAttr];
882 summaryInfo = [NSString stringWithFormat: @" (%@, %@, %@)", titleString, chapterString, passesString];
884 [finalString appendString:[NSString stringWithFormat:@"%@\n", summaryInfo] withAttributes:detailAttr];
886 // Insert a short-in-height line to put some white space after the title
887 [finalString appendString:@"\n" withAttributes:shortHeightAttr];
888 // End of Title Stuff
890 /* Second Line (Preset Name)*/
891 [finalString appendString: @"Preset: " withAttributes:detailBoldAttr];
892 [finalString appendString:[NSString stringWithFormat:@"%@\n", [item objectForKey:@"PresetName"]] withAttributes:detailAttr];
894 /* Third Line (Format Summary) */
895 NSString * audioCodecSummary = @"";
896 /* Lets also get our audio track detail since we are going through the logic for use later */
897 NSString * audioDetail1 = @"None";
898 NSString * audioDetail2 = @"None";
899 NSString * audioDetail3 = @"None";
900 NSString * audioDetail4 = @"None";
901 if ([[item objectForKey:@"Audio1Track"] intValue] > 0)
903 audioCodecSummary = [NSString stringWithFormat:@"%@", [item objectForKey:@"Audio1Encoder"]];
904 audioDetail1 = [NSString stringWithFormat:@"%@ Encoder: %@ Mixdown: %@ SampleRate: %@(khz) Bitrate: %@(kbps)",
905 [item objectForKey:@"Audio1TrackDescription"] ,
906 [item objectForKey:@"Audio1Encoder"],
907 [item objectForKey:@"Audio1Mixdown"] ,
908 [item objectForKey:@"Audio1Samplerate"],
909 [item objectForKey:@"Audio1Bitrate"]];
912 if ([[item objectForKey:@"Audio2Track"] intValue] > 0)
914 audioCodecSummary = [NSString stringWithFormat:@"%@, %@",audioCodecSummary ,[item objectForKey:@"Audio2Encoder"]];
915 audioDetail2 = [NSString stringWithFormat:@"%@ Encoder: %@ Mixdown: %@ SampleRate: %@(khz) Bitrate: %@(kbps)",
916 [item objectForKey:@"Audio2TrackDescription"] ,
917 [item objectForKey:@"Audio2Encoder"],
918 [item objectForKey:@"Audio2Mixdown"] ,
919 [item objectForKey:@"Audio2Samplerate"],
920 [item objectForKey:@"Audio2Bitrate"]];
923 if ([[item objectForKey:@"Audio3Track"] intValue] > 0)
925 audioCodecSummary = [NSString stringWithFormat:@"%@, %@",audioCodecSummary ,[item objectForKey:@"Audio3Encoder"]];
926 audioDetail3 = [NSString stringWithFormat:@"%@ Encoder: %@ Mixdown: %@ SampleRate: %@(khz) Bitrate: %@(kbps)",
927 [item objectForKey:@"Audio3TrackDescription"] ,
928 [item objectForKey:@"Audio3Encoder"],
929 [item objectForKey:@"Audio3Mixdown"] ,
930 [item objectForKey:@"Audio3Samplerate"],
931 [item objectForKey:@"Audio3Bitrate"]];
933 if ([[item objectForKey:@"Audio4Track"] intValue] > 0)
935 audioCodecSummary = [NSString stringWithFormat:@"%@, %@",audioCodecSummary ,[item objectForKey:@"Audio3Encoder"]];
936 audioDetail4 = [NSString stringWithFormat:@"%@ Encoder: %@ Mixdown: %@ SampleRate: %@(khz) Bitrate: %@(kbps)",
937 [item objectForKey:@"Audio4TrackDescription"] ,
938 [item objectForKey:@"Audio4Encoder"],
939 [item objectForKey:@"Audio4Mixdown"] ,
940 [item objectForKey:@"Audio4Samplerate"],
941 [item objectForKey:@"Audio4Bitrate"]];
944 NSString * jobFormatInfo;
945 if ([[item objectForKey:@"ChapterMarkers"] intValue] == 1)
946 jobFormatInfo = [NSString stringWithFormat:@"%@ Container, %@ Video %@ Audio, Chapter Markers\n", [item objectForKey:@"FileFormat"], [item objectForKey:@"VideoEncoder"], audioCodecSummary];
948 jobFormatInfo = [NSString stringWithFormat:@"%@ Container, %@ Video %@ Audio\n", [item objectForKey:@"FileFormat"], [item objectForKey:@"VideoEncoder"], audioCodecSummary];
951 [finalString appendString: @"Format: " withAttributes:detailBoldAttr];
952 [finalString appendString: jobFormatInfo withAttributes:detailAttr];
954 /* Optional String for mp4 options */
955 if ([[item objectForKey:@"FileFormat"] isEqualToString: @"MP4 file"])
957 NSString * MP4Opts = @"";
958 BOOL mp4OptsPresent = NO;
959 if( [[item objectForKey:@"Mp4LargeFile"] intValue] == 1)
961 mp4OptsPresent = YES;
962 MP4Opts = [MP4Opts stringByAppendingString:@" - 64 Bit"];
964 if( [[item objectForKey:@"Mp4HttpOptimize"] intValue] == 1)
966 mp4OptsPresent = YES;
967 MP4Opts = [MP4Opts stringByAppendingString:@" - Http Optimized"];
970 if( [[item objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
972 mp4OptsPresent = YES;
973 MP4Opts = [MP4Opts stringByAppendingString:@" - iPod Atom "];
975 if (mp4OptsPresent == YES)
977 [finalString appendString: @"MP4 Options: " withAttributes:detailBoldAttr];
978 [finalString appendString: MP4Opts withAttributes:detailAttr];
979 [finalString appendString:@"\n" withAttributes:detailAttr];
983 /* Fourth Line (Destination Path)*/
984 [finalString appendString: @"Destination: " withAttributes:detailBoldAttr];
985 [finalString appendString: [item objectForKey:@"DestinationPath"] withAttributes:detailAttr];
986 [finalString appendString:@"\n" withAttributes:detailAttr];
987 /* Fifth Line Picture Details*/
988 NSString * pictureInfo;
989 pictureInfo = [NSString stringWithFormat:@"%@", [item objectForKey:@"PictureSizingSummary"]];
990 if ([[item objectForKey:@"PictureKeepRatio"] intValue] == 1)
992 pictureInfo = [pictureInfo stringByAppendingString:@" Keep Aspect Ratio"];
994 if ([[item objectForKey:@"VideoGrayScale"] intValue] == 1)
996 pictureInfo = [pictureInfo stringByAppendingString:@", Grayscale"];
999 [finalString appendString: @"Picture: " withAttributes:detailBoldAttr];
1000 [finalString appendString: pictureInfo withAttributes:detailAttr];
1001 [finalString appendString:@"\n" withAttributes:detailAttr];
1003 /* Optional String for Picture Filters */
1005 NSString * pictureFilters = @"";
1006 BOOL pictureFiltersPresent = NO;
1007 if( [[item objectForKey:@"VFR"] intValue] == 1)
1009 pictureFiltersPresent = YES;
1010 pictureFilters = [pictureFilters stringByAppendingString:@" - VFR"];
1012 if( [[item objectForKey:@"PictureDetelecine"] intValue] == 1 )
1014 pictureFiltersPresent = YES;
1015 pictureFilters = [pictureFilters stringByAppendingString:@" - Detelecine"];
1018 if( [[item objectForKey:@"PictureDecomb"] intValue] == 1)
1020 pictureFiltersPresent = YES;
1021 pictureFilters = [pictureFilters stringByAppendingString:@" - Decomb "];
1024 if ([[item objectForKey:@"PictureDeinterlace"] intValue] != 0)
1026 pictureFiltersPresent = YES;
1027 if ([[item objectForKey:@"PictureDeinterlace"] intValue] == 1)
1029 pictureFilters = [pictureFilters stringByAppendingString:@" - Decomb: Fast "];
1031 else if ([[item objectForKey:@"PictureDeinterlace"] intValue] == 2)
1033 pictureFilters = [pictureFilters stringByAppendingString:@" - Decomb: Slow "];
1035 else if ([[item objectForKey:@"PictureDeinterlace"] intValue] == 3)
1037 pictureFilters = [pictureFilters stringByAppendingString:@" - Decomb: Slower "];
1041 if ([[item objectForKey:@"PictureDenoise"] intValue] != 0)
1043 pictureFiltersPresent = YES;
1044 if ([[item objectForKey:@"PictureDenoise"] intValue] == 1)
1046 pictureFilters = [pictureFilters stringByAppendingString:@" - Denoise: Weak "];
1048 else if ([[item objectForKey:@"PictureDenoise"] intValue] == 2)
1050 pictureFilters = [pictureFilters stringByAppendingString:@" - Denoise: Medium "];
1052 else if ([[item objectForKey:@"PictureDenoise"] intValue] == 3)
1054 pictureFilters = [pictureFilters stringByAppendingString:@" - Denoise: Strong "];
1058 if ([[item objectForKey:@"PictureDeblock"] intValue] != 0)
1060 pictureFiltersPresent = YES;
1061 pictureFilters = [pictureFilters stringByAppendingString: [NSString stringWithFormat:@" - Deblock (pp7) (%d) ",[[item objectForKey:@"PictureDeblock"] intValue]]];
1063 if (pictureFiltersPresent == YES)
1065 [finalString appendString: @"Filters: " withAttributes:detailBoldAttr];
1066 [finalString appendString: pictureFilters withAttributes:detailAttr];
1067 [finalString appendString:@"\n" withAttributes:detailAttr];
1070 /* Sixth Line Video Details*/
1071 NSString * videoInfo;
1072 videoInfo = [NSString stringWithFormat:@"Encoder: %@", [item objectForKey:@"VideoEncoder"]];
1073 videoInfo = [NSString stringWithFormat:@"%@ Framerate: %@", videoInfo ,[item objectForKey:@"VideoFramerate"]];
1075 if ([[item objectForKey:@"VideoQualityType"] intValue] == 0)// Target Size MB
1077 videoInfo = [NSString stringWithFormat:@"%@ Target Size: %@(MB)", videoInfo ,[item objectForKey:@"VideoTargetSize"]];
1079 else if ([[item objectForKey:@"VideoQualityType"] intValue] == 1) // ABR
1081 videoInfo = [NSString stringWithFormat:@"%@ Bitrate: %d(kbps)", videoInfo ,[[item objectForKey:@"VideoAvgBitrate"] intValue]];
1085 videoInfo = [NSString stringWithFormat:@"%@ Constant Quality: %.0f %%", videoInfo ,[[item objectForKey:@"VideoQualitySlider"] floatValue] * 100];
1088 [finalString appendString: @"Video: " withAttributes:detailBoldAttr];
1089 [finalString appendString: videoInfo withAttributes:detailAttr];
1090 [finalString appendString:@"\n" withAttributes:detailAttr];
1092 if ([[item objectForKey:@"VideoEncoder"] isEqualToString: @"H.264 (x264)"])
1094 [finalString appendString: @"x264 Options: " withAttributes:detailBoldAttr];
1095 [finalString appendString: [item objectForKey:@"x264Option"] withAttributes:detailAttr];
1096 [finalString appendString:@"\n" withAttributes:detailAttr];
1100 /* Seventh Line Audio Details*/
1101 [finalString appendString: @"Audio Track 1: " withAttributes:detailBoldAttr];
1102 [finalString appendString: audioDetail1 withAttributes:detailAttr];
1103 [finalString appendString:@"\n" withAttributes:detailAttr];
1105 [finalString appendString: @"Audio Track 2: " withAttributes:detailBoldAttr];
1106 [finalString appendString: audioDetail2 withAttributes:detailAttr];
1107 [finalString appendString:@"\n" withAttributes:detailAttr];
1109 [finalString appendString: @"Audio Track 3: " withAttributes:detailBoldAttr];
1110 [finalString appendString: audioDetail3 withAttributes:detailAttr];
1111 [finalString appendString:@"\n" withAttributes:detailAttr];
1113 [finalString appendString: @"Audio Track 4: " withAttributes:detailBoldAttr];
1114 [finalString appendString: audioDetail4 withAttributes:detailAttr];
1118 else if ([[tableColumn identifier] isEqualToString:@"icon"])
1120 if ([[item objectForKey:@"Status"] intValue] == 0)
1122 return [NSImage imageNamed:@"EncodeComplete"];
1124 else if ([[item objectForKey:@"Status"] intValue] == 1)
1126 return [NSImage imageNamed: [NSString stringWithFormat: @"EncodeWorking%d", fAnimationIndex]];
1128 else if ([[item objectForKey:@"Status"] intValue] == 3)
1130 return [NSImage imageNamed:@"EncodeCanceled"];
1134 return [NSImage imageNamed:@"JobSmall"];
1144 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
1146 if ([[tableColumn identifier] isEqualToString:@"desc"])
1150 // nb: The "desc" column is currently an HBImageAndTextCell. However, we are longer
1151 // using the image portion of the cell so we could switch back to a regular NSTextFieldCell.
1153 // Set the image here since the value returned from outlineView:objectValueForTableColumn: didn't specify the image part
1154 [cell setImage:nil];
1156 else if ([[tableColumn identifier] isEqualToString:@"action"])
1158 [cell setEnabled: YES];
1159 BOOL highlighted = [outlineView isRowSelected:[outlineView rowForItem: item]] && [[outlineView window] isKeyWindow] && ([[outlineView window] firstResponder] == outlineView);
1160 if ([[item objectForKey:@"Status"] intValue] == 0)
1162 [cell setAction: @selector(revealSelectedQueueItem:)];
1165 [cell setImage:[NSImage imageNamed:@"RevealHighlight"]];
1166 [cell setAlternateImage:[NSImage imageNamed:@"RevealHighlightPressed"]];
1169 [cell setImage:[NSImage imageNamed:@"Reveal"]];
1173 [cell setAction: @selector(removeSelectedQueueItem:)];
1176 [cell setImage:[NSImage imageNamed:@"DeleteHighlight"]];
1177 [cell setAlternateImage:[NSImage imageNamed:@"DeleteHighlightPressed"]];
1180 [cell setImage:[NSImage imageNamed:@"Delete"]];
1185 - (void)outlineView:(NSOutlineView *)outlineView willDisplayOutlineCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
1187 // By default, the discolsure image gets centered vertically in the cell. We want
1188 // always at the top.
1189 if ([outlineView isItemExpanded: item])
1190 [cell setImagePosition: NSImageAbove];
1192 [cell setImagePosition: NSImageOnly];
1196 #pragma mark NSOutlineView delegate (dragging related)
1198 //------------------------------------------------------------------------------------
1199 // NSTableView delegate
1200 //------------------------------------------------------------------------------------
1203 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
1205 // Dragging is only allowed of the pending items.
1206 if ([[[fJobGroups objectAtIndex:[outlineView selectedRow]] objectForKey:@"Status"] intValue] != 2) // 2 is pending
1211 // Don't retain since this is just holding temporaral drag information, and it is
1212 //only used during a drag! We could put this in the pboard actually.
1213 fDraggedNodes = items;
1215 // Provide data for our custom type, and simple NSStrings.
1216 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
1218 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
1219 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
1225 /* This method is used to validate the drops. */
1226 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
1228 // Don't allow dropping ONTO an item since they can't really contain any children.
1229 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
1230 if (isOnDropTypeProposal)
1231 return NSDragOperationNone;
1233 // Don't allow dropping INTO an item since they can't really contain any children.
1236 index = [fOutlineView rowForItem: item] + 1;
1240 // NOTE: Should we allow dropping a pending job *above* the
1241 // finished or already encoded jobs ?
1242 // We do not let the user drop a pending job before or *above*
1243 // already finished or currently encoding jobs.
1244 if (index <= fEncodingQueueItem)
1246 return NSDragOperationNone;
1247 index = MAX (index, fEncodingQueueItem);
1251 [outlineView setDropItem:item dropChildIndex:index];
1252 return NSDragOperationGeneric;
1257 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
1259 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
1262 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
1263 while (obj = [enumerator nextObject])
1265 [moveItems addIndex:[fJobGroups indexOfObject:obj]];
1268 // Successful drop, we use moveObjectsInQueueArray:... in fHBController
1269 // to properly rearrange the queue array, save it to plist and then send it back here.
1270 // since Controller.mm is handling all queue array manipulation.
1271 // We *could do this here, but I think we are better served keeping that code together.
1272 [fHBController moveObjectsInQueueArray:fJobGroups fromIndexes:moveItems toIndex: index];
1275 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(unsigned)insertIndex
1277 unsigned index = [indexSet lastIndex];
1278 unsigned aboveInsertIndexCount = 0;
1280 while (index != NSNotFound)
1282 unsigned removeIndex;
1284 if (index >= insertIndex)
1286 removeIndex = index + aboveInsertIndexCount;
1287 aboveInsertIndexCount++;
1291 removeIndex = index;
1295 id object = [[array objectAtIndex:removeIndex] retain];
1296 [array removeObjectAtIndex:removeIndex];
1297 [array insertObject:object atIndex:insertIndex];
1300 index = [indexSet indexLessThanIndex:index];