OSDN Git Service

Change minimum vobsub time from 3sec to 2sec, been meaning to do this for a while.
[handbrake-jp/handbrake-jp-git.git] / macosx / HBQueueController.mm
1 /* HBQueueController
2
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. */
6
7 #import "HBQueueController.h"
8 #import "Controller.h"
9 #import "HBImageAndTextCell.h"
10
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"
15
16 //------------------------------------------------------------------------------------
17 #pragma mark -
18 //------------------------------------------------------------------------------------
19
20 //------------------------------------------------------------------------------------
21 // NSMutableAttributedString (HBAdditions)
22 //------------------------------------------------------------------------------------
23
24 @interface NSMutableAttributedString (HBAdditions)
25 - (void) appendString: (NSString*)aString withAttributes: (NSDictionary *)aDictionary;
26 @end
27
28 @implementation NSMutableAttributedString (HBAdditions)
29 - (void) appendString: (NSString*)aString withAttributes: (NSDictionary *)aDictionary
30 {
31     NSAttributedString * s = [[[NSAttributedString alloc]
32         initWithString: aString
33         attributes: aDictionary] autorelease];
34     [self appendAttributedString: s];
35 }
36 @end
37
38
39 @implementation HBQueueOutlineView
40
41 - (void)viewDidEndLiveResize
42 {
43     // Since we disabled calculating row heights during a live resize, force them to
44     // recalculate now.
45     [self noteHeightOfRowsWithIndexesChanged:
46             [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [self numberOfRows])]];
47     [super viewDidEndLiveResize];
48 }
49
50
51
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
54 {
55     fIsDragging = YES;
56
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];
61 }
62
63
64
65 - (void) mouseDown:(NSEvent *)theEvent
66 {
67     [super mouseDown:theEvent];
68         fIsDragging = NO;
69 }
70
71
72
73 - (BOOL) isDragging;
74 {
75     return fIsDragging;
76 }
77
78
79
80 @end
81
82 #pragma mark Toolbar Identifiers
83 // Toolbar identifiers
84 static NSString*    HBQueueToolbar                            = @"HBQueueToolbar1";
85 static NSString*    HBQueueStartCancelToolbarIdentifier       = @"HBQueueStartCancelToolbarIdentifier";
86 static NSString*    HBQueuePauseResumeToolbarIdentifier       = @"HBQueuePauseResumeToolbarIdentifier";
87
88 #pragma mark -
89
90 @implementation HBQueueController
91
92 //------------------------------------------------------------------------------------
93 // init
94 //------------------------------------------------------------------------------------
95 - (id)init
96 {
97     if (self = [super initWithWindowNibName:@"Queue"])
98     {
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.
102         //
103         // If/when we switch to using bindings, this can probably go away.
104         [self window];
105
106         // Our defaults
107         [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
108             @"NO",      @"QueueWindowIsOpen",
109             @"NO",      @"QueueShowsDetail",
110             @"YES",     @"QueueShowsJobsAsGroups",
111             nil]];
112
113         fJobGroups = [[NSMutableArray arrayWithCapacity:0] retain];
114        } 
115         return self;
116 }
117
118 - (void)setQueueArray: (NSMutableArray *)QueueFileArray
119 {
120     [fJobGroups setArray:QueueFileArray];
121     fIsDragging = NO; 
122     /* First stop any timer working now */
123     [self stopAnimatingCurrentJobGroupInQueue];
124     [fOutlineView reloadData];
125     
126     
127     
128     /* lets get the stats on the status of the queue array */
129     
130     fEncodingQueueItem = 0;
131     fPendingCount = 0;
132     fCompletedCount = 0;
133     fCanceledCount = 0;
134     fWorkingCount = 0;
135     
136     /* We use a number system to set the encode status of the queue item
137      * in controller.mm
138      * 0 == already encoded
139      * 1 == is being encoded
140      * 2 == is yet to be encoded
141      * 3 == cancelled
142      */
143     
144         int i = 0;
145         for(id tempObject in fJobGroups)
146         {
147                 NSDictionary *thisQueueDict = tempObject;
148                 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
149                 {
150                         fCompletedCount++;      
151                 }
152                 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
153                 {
154                         fWorkingCount++;
155             fEncodingQueueItem = i;     
156                 }
157         if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending          
158         {
159                         fPendingCount++;
160                 }
161         if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled                
162         {
163                         fCanceledCount++;
164                 }
165                 i++;
166         }
167     
168     /* We should fire up the encoding timer here based on fWorkingCount */
169     
170     if (fWorkingCount > 0)
171     {
172         /* we have an encoding job so, lets start the animation timer */
173         [self startAnimatingCurrentWorkingEncodeInQueue];
174     }
175     
176     /* Set the queue status field in the queue window */
177     NSMutableString * string;
178     if (fPendingCount == 1)
179     {
180         string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending", @"" ), fPendingCount];
181     }
182     else
183     {
184         string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending", @"" ), fPendingCount];
185     }
186     [fQueueCountField setStringValue:string];
187     
188 }
189 /* This method sets the status string in the queue window
190  * and is called from Controller.mm (fHBController)
191  * instead of running another timer here polling libhb
192  * for encoding status
193  */
194 - (void)setQueueStatusString: (NSString *)statusString
195 {
196 [fProgressTextField setStringValue:statusString];
197 }
198
199 //------------------------------------------------------------------------------------
200 // dealloc
201 //------------------------------------------------------------------------------------
202 - (void)dealloc
203 {
204     // clear the delegate so that windowWillClose is not attempted
205     if( [[self window] delegate] == self )
206         [[self window] setDelegate:nil];
207
208     [fJobGroups release];
209
210     [fSavedExpandedItems release];
211     [fSavedSelectedItems release];
212
213     [[NSNotificationCenter defaultCenter] removeObserver:self];
214
215     [super dealloc];
216 }
217
218 //------------------------------------------------------------------------------------
219 // Receive HB handle
220 //------------------------------------------------------------------------------------
221 - (void)setHandle: (hb_handle_t *)handle
222 {
223     fQueueEncodeLibhb = handle;
224 }
225
226 //------------------------------------------------------------------------------------
227 // Receive HBController
228 //------------------------------------------------------------------------------------
229 - (void)setHBController: (HBController *)controller
230 {
231     fHBController = controller;
232 }
233
234 #pragma mark -
235
236 //------------------------------------------------------------------------------------
237 // Displays and brings the queue window to the front
238 //------------------------------------------------------------------------------------
239 - (IBAction) showQueueWindow: (id)sender
240 {
241     [self showWindow:sender];
242     [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"QueueWindowIsOpen"];
243 }
244
245
246
247 //------------------------------------------------------------------------------------
248 // awakeFromNib
249 //------------------------------------------------------------------------------------
250 - (void)awakeFromNib
251 {
252     [self setupToolbar];
253
254     if( ![[self window] setFrameUsingName:@"Queue"] )
255         [[self window] center];
256     [self setWindowFrameAutosaveName:@"Queue"];
257     [[self window] setExcludedFromWindowsMenu:YES];
258
259     /* lets setup our queue list outline view for drag and drop here */
260     [fOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
261     [fOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
262     [fOutlineView setVerticalMotionCanBeginDrag: YES];
263
264
265     // Don't allow autoresizing of main column, else the "delete" column will get
266     // pushed out of view.
267     [fOutlineView setAutoresizesOutlineColumn: NO];
268
269 #if HB_OUTLINE_METRIC_CONTROLS
270     [fIndentation setHidden: NO];
271     [fSpacing setHidden: NO];
272     [fIndentation setIntegerValue:[fOutlineView indentationPerLevel]];  // debug
273     [fSpacing setIntegerValue:3];       // debug
274 #endif
275
276     // Show/hide UI elements
277     fCurrentJobPaneShown = NO;     // it's shown in the nib
278     //[self showCurrentJobPane:NO];
279
280     //[self updateQueueCountField];
281 }
282
283
284 //------------------------------------------------------------------------------------
285 // windowWillClose
286 //------------------------------------------------------------------------------------
287 - (void)windowWillClose:(NSNotification *)aNotification
288 {
289     [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"QueueWindowIsOpen"];
290 }
291
292 #pragma mark Toolbar
293
294 //------------------------------------------------------------------------------------
295 // setupToolbar
296 //------------------------------------------------------------------------------------
297 - (void)setupToolbar
298 {
299     // Create a new toolbar instance, and attach it to our window
300     NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: HBQueueToolbar] autorelease];
301
302     // Set up toolbar properties: Allow customization, give a default display mode, and remember state in user defaults
303     [toolbar setAllowsUserCustomization: YES];
304     [toolbar setAutosavesConfiguration: YES];
305     [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
306
307     // We are the delegate
308     [toolbar setDelegate: self];
309
310     // Attach the toolbar to our window
311     [[self window] setToolbar:toolbar];
312 }
313
314 //------------------------------------------------------------------------------------
315 // toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:
316 //------------------------------------------------------------------------------------
317 - (NSToolbarItem *)toolbar:(NSToolbar *)toolbar
318         itemForItemIdentifier:(NSString *)itemIdentifier
319         willBeInsertedIntoToolbar:(BOOL)flag
320 {
321     // Required delegate method: Given an item identifier, this method returns an item.
322     // The toolbar will use this method to obtain toolbar items that can be displayed
323     // in the customization sheet, or in the toolbar itself.
324
325     NSToolbarItem *toolbarItem = nil;
326
327     if ([itemIdentifier isEqual: HBQueueStartCancelToolbarIdentifier])
328     {
329         toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
330
331         // Set the text label to be displayed in the toolbar and customization palette
332         [toolbarItem setLabel: @"Start"];
333         [toolbarItem setPaletteLabel: @"Start/Cancel"];
334
335         // Set up a reasonable tooltip, and image
336         [toolbarItem setToolTip: @"Start Encoding"];
337         [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
338
339         // Tell the item what message to send when it is clicked
340         [toolbarItem setTarget: self];
341         [toolbarItem setAction: @selector(toggleStartCancel:)];
342     }
343
344     if ([itemIdentifier isEqual: HBQueuePauseResumeToolbarIdentifier])
345     {
346         toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
347
348         // Set the text label to be displayed in the toolbar and customization palette
349         [toolbarItem setLabel: @"Pause"];
350         [toolbarItem setPaletteLabel: @"Pause/Resume"];
351
352         // Set up a reasonable tooltip, and image
353         [toolbarItem setToolTip: @"Pause Encoding"];
354         [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
355
356         // Tell the item what message to send when it is clicked
357         [toolbarItem setTarget: self];
358         [toolbarItem setAction: @selector(togglePauseResume:)];
359     }
360
361     return toolbarItem;
362 }
363
364 //------------------------------------------------------------------------------------
365 // toolbarDefaultItemIdentifiers:
366 //------------------------------------------------------------------------------------
367 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
368 {
369     // Required delegate method: Returns the ordered list of items to be shown in the
370     // toolbar by default.
371
372     return [NSArray arrayWithObjects:
373         HBQueueStartCancelToolbarIdentifier,
374         HBQueuePauseResumeToolbarIdentifier,
375         nil];
376 }
377
378 //------------------------------------------------------------------------------------
379 // toolbarAllowedItemIdentifiers:
380 //------------------------------------------------------------------------------------
381 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
382 {
383     // Required delegate method: Returns the list of all allowed items by identifier.
384     // By default, the toolbar does not assume any items are allowed, even the
385     // separator. So, every allowed item must be explicitly listed.
386
387     return [NSArray arrayWithObjects:
388         HBQueueStartCancelToolbarIdentifier,
389         HBQueuePauseResumeToolbarIdentifier,
390         NSToolbarCustomizeToolbarItemIdentifier,
391         NSToolbarFlexibleSpaceItemIdentifier,
392         NSToolbarSpaceItemIdentifier,
393         NSToolbarSeparatorItemIdentifier,
394         nil];
395 }
396
397 //------------------------------------------------------------------------------------
398 // validateToolbarItem:
399 //------------------------------------------------------------------------------------
400 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
401 {
402     // Optional method: This message is sent to us since we are the target of some
403     // toolbar item actions.
404
405     if (!fQueueEncodeLibhb) return NO;
406
407     BOOL enable = NO;
408
409     hb_state_t s;
410     hb_get_state2 (fQueueEncodeLibhb, &s);
411
412     if ([[toolbarItem itemIdentifier] isEqual: HBQueueStartCancelToolbarIdentifier])
413     {
414         if ((s.state == HB_STATE_PAUSED) || (s.state == HB_STATE_WORKING) || (s.state == HB_STATE_MUXING))
415         {
416             enable = YES;
417             [toolbarItem setImage:[NSImage imageNamed: @"Stop"]];
418             [toolbarItem setLabel: @"Stop"];
419             [toolbarItem setToolTip: @"Stop Encoding"];
420         }
421
422         else if (fPendingCount > 0)
423         {
424             enable = YES;
425             [toolbarItem setImage:[NSImage imageNamed: @"Play"]];
426             [toolbarItem setLabel: @"Start"];
427             [toolbarItem setToolTip: @"Start Encoding"];
428         }
429
430         else
431         {
432             enable = NO;
433             [toolbarItem setImage:[NSImage imageNamed: @"Play"]];
434             [toolbarItem setLabel: @"Start"];
435             [toolbarItem setToolTip: @"Start Encoding"];
436         }
437     }
438
439     if ([[toolbarItem itemIdentifier] isEqual: HBQueuePauseResumeToolbarIdentifier])
440     {
441         if (s.state == HB_STATE_PAUSED)
442         {
443             enable = YES;
444             [toolbarItem setImage:[NSImage imageNamed: @"Play"]];
445             [toolbarItem setLabel: @"Resume"];
446             [toolbarItem setToolTip: @"Resume Encoding"];
447        }
448
449         else if ((s.state == HB_STATE_WORKING) || (s.state == HB_STATE_MUXING))
450         {
451             enable = YES;
452             [toolbarItem setImage:[NSImage imageNamed: @"Pause"]];
453             [toolbarItem setLabel: @"Pause"];
454             [toolbarItem setToolTip: @"Pause Encoding"];
455         }
456         else
457         {
458             enable = NO;
459             [toolbarItem setImage:[NSImage imageNamed: @"Pause"]];
460             [toolbarItem setLabel: @"Pause"];
461             [toolbarItem setToolTip: @"Pause Encoding"];
462         }
463     }
464
465     return enable;
466 }
467
468 #pragma mark -
469
470
471 #pragma mark Queue Item Controls
472 //------------------------------------------------------------------------------------
473 // Delete encodes from the queue window and accompanying array
474 // Also handling first cancelling the encode if in fact its currently encoding.
475 //------------------------------------------------------------------------------------
476 - (IBAction)removeSelectedQueueItem: (id)sender
477 {
478     NSIndexSet * selectedRows = [fOutlineView selectedRowIndexes];
479     NSUInteger row = [selectedRows firstIndex];
480     if( row == NSNotFound )
481         return;
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
484      * remove it */
485     
486     if ([[[fJobGroups objectAtIndex:row] objectForKey:@"Status"] integerValue] == 1)
487     {
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
490         */
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 = nil;
495         if ([sender respondsToSelector: @selector(window)])
496             docWindow = [sender window];
497         
498         
499         NSBeginCriticalAlertSheet(
500                                   alertTitle,
501                                   NSLocalizedString(@"Keep Encoding", nil),
502                                   nil,
503                                   NSLocalizedString(@"Stop Encoding and Delete", nil),
504                                   docWindow, self,
505                                   nil, @selector(didDimissCancelCurrentJob:returnCode:contextInfo:), nil,
506                                   NSLocalizedString(@"Your movie will be lost if you don't continue encoding.", nil));
507         
508         // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
509     }
510     else
511     { 
512     /* since we are not a currently encoding item, we can just be cancelled */
513             [fHBController removeQueueFileItem:row];
514     }
515 }
516
517 - (void) didDimissCancelCurrentJob: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
518 {
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
524      */
525        [fHBController Pause:NULL];
526     if (returnCode == NSAlertOtherReturn)
527     {
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
532      */
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
536      */
537     [fHBController removeQueueFileItem:encodingItemToRemove];
538     }
539     
540 }
541
542 //------------------------------------------------------------------------------------
543 // Show the finished encode in the finder
544 //------------------------------------------------------------------------------------
545 - (IBAction)revealSelectedQueueItem: (id)sender
546 {
547     NSIndexSet * selectedRows = [fOutlineView selectedRowIndexes];
548     NSInteger row = [selectedRows firstIndex];
549     if (row != NSNotFound)
550     {
551         while (row != NSNotFound)
552         {
553            NSMutableDictionary *queueItemToOpen = [fOutlineView itemAtRow: row];
554          [[NSWorkspace sharedWorkspace] selectFile:[queueItemToOpen objectForKey:@"DestinationPath"] inFileViewerRootedAtPath:nil];
555
556             row = [selectedRows indexGreaterThanIndex: row];
557         }
558     }
559 }
560
561
562 //------------------------------------------------------------------------------------
563 // Starts or cancels the processing of jobs depending on the current state
564 //------------------------------------------------------------------------------------
565 - (IBAction)toggleStartCancel: (id)sender
566 {
567     if (!fQueueEncodeLibhb) return;
568
569     hb_state_t s;
570     hb_get_state2 (fQueueEncodeLibhb, &s);
571
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
574
575     else if (fPendingCount > 0)
576         [fHBController Rip: NULL];
577 }
578
579 //------------------------------------------------------------------------------------
580 // Toggles the pause/resume state of libhb
581 //------------------------------------------------------------------------------------
582 - (IBAction)togglePauseResume: (id)sender
583 {
584     if (!fQueueEncodeLibhb) return;
585     
586     hb_state_t s;
587     hb_get_state2 (fQueueEncodeLibhb, &s);
588     
589     if (s.state == HB_STATE_PAUSED)
590     {
591         hb_resume (fQueueEncodeLibhb);
592         [self startAnimatingCurrentWorkingEncodeInQueue];
593     }
594     else if ((s.state == HB_STATE_WORKING) || (s.state == HB_STATE_MUXING))
595     {
596         hb_pause (fQueueEncodeLibhb);
597         [self stopAnimatingCurrentJobGroupInQueue];
598     }
599 }
600
601 #pragma mark -
602
603
604 #pragma mark Animate Endcoding Item
605
606
607
608
609 //------------------------------------------------------------------------------------
610 // Starts animating the job icon of the currently processing job in the queue outline
611 // view.
612 //------------------------------------------------------------------------------------
613 - (void) startAnimatingCurrentWorkingEncodeInQueue
614 {
615     if (!fAnimationTimer)
616         fAnimationTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0/12.0     // 1/12 because there are 6 images in the animation cycle
617                 target:self
618                 selector:@selector(animateWorkingEncodeInQueue:)
619                 userInfo:nil
620                 repeats:YES] retain];
621 }
622
623 //------------------------------------------------------------------------------------
624 // If a job is currently processing, its job icon in the queue outline view is
625 // animated to its next state.
626 //------------------------------------------------------------------------------------
627 - (void) animateWorkingEncodeInQueue:(NSTimer*)theTimer
628 {
629     if (fWorkingCount > 0)
630     {
631         fAnimationIndex++;
632         fAnimationIndex %= 6;   // there are 6 animation images; see outlineView:objectValueForTableColumn:byItem: below.
633         [self animateWorkingEncodeIconInQueue];
634     }
635 }
636
637
638 - (void) animateWorkingEncodeIconInQueue
639 {
640     NSInteger row = fEncodingQueueItem; /// need to set to fEncodingQueueItem
641     NSInteger col = [fOutlineView columnWithIdentifier: @"icon"];
642     if (row != -1 && col != -1)
643     {
644         NSRect frame = [fOutlineView frameOfCellAtColumn:col row:row];
645         [fOutlineView setNeedsDisplayInRect: frame];
646     }
647 }
648
649 //------------------------------------------------------------------------------------
650 // Stops animating the job icon of the currently processing job in the queue outline
651 // view.
652 //------------------------------------------------------------------------------------
653 - (void) stopAnimatingCurrentJobGroupInQueue
654 {
655     if (fAnimationTimer && [fAnimationTimer isValid])
656     {
657         [fAnimationTimer invalidate];
658         [fAnimationTimer release];
659         fAnimationTimer = nil;
660     }
661 }
662
663
664 #pragma mark -
665
666 - (void)moveObjectsInArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
667 {
668     NSUInteger index = [indexSet lastIndex];
669     NSUInteger aboveInsertIndexCount = 0;
670
671     while (index != NSNotFound)
672     {
673         NSUInteger removeIndex;
674
675         if (index >= insertIndex)
676         {
677             removeIndex = index + aboveInsertIndexCount;
678             aboveInsertIndexCount++;
679         }
680         else
681         {
682             removeIndex = index;
683             insertIndex--;
684         }
685
686         id object = [[array objectAtIndex:removeIndex] retain];
687         [array removeObjectAtIndex:removeIndex];
688         [array insertObject:object atIndex:insertIndex];
689         [object release];
690
691         index = [indexSet indexLessThanIndex:index];
692     }
693 }
694
695
696 #pragma mark -
697 #pragma mark NSOutlineView delegate
698
699
700 - (id)outlineView:(NSOutlineView *)fOutlineView child:(NSInteger)index ofItem:(id)item
701 {
702     if (item == nil)
703         return [fJobGroups objectAtIndex:index];
704
705     // We are only one level deep, so we can't be asked about children
706     NSAssert (NO, @"HBQueueController outlineView:child:ofItem: can't handle nested items.");
707     return nil;
708 }
709
710 - (BOOL)outlineView:(NSOutlineView *)fOutlineView isItemExpandable:(id)item
711 {
712     // Our outline view has no levels, but we can still expand every item. Doing so
713     // just makes the row taller. See heightOfRowByItem below.
714     return YES;
715 }
716
717 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
718 {
719     // Our outline view has no levels, but we can still expand every item. Doing so
720     // just makes the row taller. See heightOfRowByItem below.
721 return ![(HBQueueOutlineView*)outlineView isDragging];
722 }
723
724 - (NSInteger)outlineView:(NSOutlineView *)fOutlineView numberOfChildrenOfItem:(id)item
725 {
726     // Our outline view has no levels, so number of children will be zero for all
727     // top-level items.
728     if (item == nil)
729         return [fJobGroups count];
730     else
731         return 0;
732 }
733
734 - (void)outlineViewItemDidCollapse:(NSNotification *)notification
735 {
736     id item = [[notification userInfo] objectForKey:@"NSObject"];
737     NSInteger row = [fOutlineView rowForItem:item];
738     [fOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(row,1)]];
739 }
740
741 - (void)outlineViewItemDidExpand:(NSNotification *)notification
742 {
743     id item = [[notification userInfo] objectForKey:@"NSObject"];
744     NSInteger row = [fOutlineView rowForItem:item];
745     [fOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(row,1)]];
746 }
747
748 - (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item
749 {
750     if ([outlineView isItemExpanded: item])
751     {
752         // Short-circuit here if in a live resize primarily to fix a bug but also to
753         // increase resposivness during a resize. There's a bug in NSTableView that
754         // causes row heights to get messed up if you try to change them during a live
755         // resize. So if in a live resize, simply return the previously calculated
756         // height. The row heights will get fixed up after the resize because we have
757         // implemented viewDidEndLiveResize to force all of them to be recalculated.
758         // if ([outlineView inLiveResize] && [item lastDescriptionHeight] > 0)
759          //   return [item lastDescriptionHeight];
760
761         // CGFloat width = [[outlineView tableColumnWithIdentifier: @"desc"] width];
762         // Column width is NOT what is ultimately used. I can't quite figure out what
763         // width to use for calculating text metrics. No matter how I tweak this value,
764         // there are a few conditions in which the drawn text extends below the bounds
765         // of the row cell. In previous versions, which ran under Tiger, I was
766         // reducing width by 47 pixles.
767         // width -= 2;     // (?) for intercell spacing
768
769         // CGFloat height = [item heightOfDescriptionForWidth: width];
770         // return height;
771         
772         return HB_ROW_HEIGHT_FULL_DESCRIPTION;
773     }
774     else
775         return HB_ROW_HEIGHT_TITLE_ONLY;
776 }
777
778 - (CGFloat) heightOfDescriptionForWidth:(CGFloat)width
779 {
780     // Try to return the cached value if no changes have happened since the last time
781     //if ((width == fLastDescriptionWidth) && (fLastDescriptionHeight != 0) && !fNeedsDescription)
782        // return fLastDescriptionHeight;
783
784     //if (fNeedsDescription)
785     //    [self updateDescription];
786
787     // Calculate the height
788     //NSRect bounds = [fDescription boundingRectWithSize:NSMakeSize(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin];
789     //fLastDescriptionHeight = bounds.size.height + 6.0; // add some border to bottom
790     //fLastDescriptionWidth = width;
791     return HB_ROW_HEIGHT_FULL_DESCRIPTION;
792
793 /* supposedly another way to do this, in case boundingRectWithSize isn't working
794     NSTextView* tmpView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, width, 1)];
795     [[tmpView textStorage] setAttributedString:aString];
796     [tmpView setHorizontallyResizable:NO];
797     [tmpView setVerticallyResizable:YES];
798 //    [[tmpView textContainer] setHeightTracksTextView: YES];
799 //    [[tmpView textContainer] setContainerSize: NSMakeSize(width, 10000)];
800     [tmpView sizeToFit];
801     float height = [tmpView frame].size.height;
802     [tmpView release];
803     return height;
804 */
805 }
806
807 - (CGFloat) lastDescriptionHeight
808 {
809     return HB_ROW_HEIGHT_FULL_DESCRIPTION;
810 }
811
812 - (id)outlineView:(NSOutlineView *)fOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
813 {
814     // nb: The "desc" column is currently an HBImageAndTextCell. However, we are longer
815     // using the image portion of the cell so we could switch back to a regular NSTextFieldCell.
816     
817     if ([[tableColumn identifier] isEqualToString:@"desc"])
818     {
819         /* This should have caused the description we wanted to show*/
820         //return [item objectForKey:@"SourceName"];
821         
822         /* code to build the description as per old queue */
823         //return [self formatEncodeItemDescription:item];
824         
825         /* Below should be put into a separate method but I am way too f'ing lazy right now */
826         NSMutableAttributedString * finalString = [[[NSMutableAttributedString alloc] initWithString: @""] autorelease];
827         // Attributes
828         NSMutableParagraphStyle * ps = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] retain];
829         [ps setHeadIndent: 40.0];
830         [ps setParagraphSpacing: 1.0];
831         [ps setTabStops:[NSArray array]];    // clear all tabs
832         [ps addTabStop: [[[NSTextTab alloc] initWithType: NSLeftTabStopType location: 20.0] autorelease]];
833         
834         
835         NSDictionary* detailAttr = [NSDictionary dictionaryWithObjectsAndKeys:
836                                     [NSFont systemFontOfSize:10.0], NSFontAttributeName,
837                                     ps, NSParagraphStyleAttributeName,
838                                     nil];
839         
840         NSDictionary* detailBoldAttr = [NSDictionary dictionaryWithObjectsAndKeys:
841                                         [NSFont boldSystemFontOfSize:10.0], NSFontAttributeName,
842                                         ps, NSParagraphStyleAttributeName,
843                                         nil];
844         
845         NSDictionary* titleAttr = [NSDictionary dictionaryWithObjectsAndKeys:
846                                    [NSFont systemFontOfSize:[NSFont systemFontSize]], NSFontAttributeName,
847                                    ps, NSParagraphStyleAttributeName,
848                                    nil];
849         
850         NSDictionary* shortHeightAttr = [NSDictionary dictionaryWithObjectsAndKeys:
851                                          [NSFont systemFontOfSize:2.0], NSFontAttributeName,
852                                          nil];
853         
854         /* First line, we should strip the destination path and just show the file name and add the title num and chapters (if any) */
855         //finalDescription = [finalDescription stringByAppendingString:[NSString stringWithFormat:@"Source: %@ Output: %@\n", [item objectForKey:@"SourceName"],[item objectForKey:@"DestinationPath"]]];
856         NSString * summaryInfo;
857         
858         NSString * titleString = [NSString stringWithFormat:@"Title %d", [[item objectForKey:@"TitleNumber"] intValue]];
859         
860         NSString * chapterString = ([[item objectForKey:@"ChapterStart"] intValue] == [[item objectForKey:@"ChapterEnd"] intValue]) ?
861         [NSString stringWithFormat:@"Chapter %d", [[item objectForKey:@"ChapterStart"] intValue]] :
862         [NSString stringWithFormat:@"Chapters %d through %d", [[item objectForKey:@"ChapterStart"] intValue], [[item objectForKey:@"ChapterEnd"] intValue]];
863         
864         NSString * passesString;
865         if ([[item objectForKey:@"VideoTwoPass"] intValue] == 0)
866         {
867             passesString = [NSString stringWithFormat:@"1 Video Pass"];
868         }
869         else
870         {
871             if ([[item objectForKey:@"VideoTurboTwoPass"] intValue] == 1)
872             {
873                 passesString = [NSString stringWithFormat:@"2 Video Passes Turbo"];
874             }
875             else
876             {
877                 passesString = [NSString stringWithFormat:@"2 Video Passes"];
878             }
879         }
880         
881         [finalString appendString:[NSString stringWithFormat:@"%@", [item objectForKey:@"SourceName"]] withAttributes:titleAttr];
882         
883         /* lets add the output file name to the title string here */
884         NSString * outputFilenameString = [[item objectForKey:@"DestinationPath"] lastPathComponent];
885         
886         summaryInfo = [NSString stringWithFormat: @" (%@, %@, %@) -> %@", titleString, chapterString, passesString, outputFilenameString];
887         
888         [finalString appendString:[NSString stringWithFormat:@"%@\n", summaryInfo] withAttributes:detailAttr];  
889         
890         // Insert a short-in-height line to put some white space after the title
891         [finalString appendString:@"\n" withAttributes:shortHeightAttr];
892         // End of Title Stuff
893         
894         /* Second Line  (Preset Name)*/
895         [finalString appendString: @"Preset: " withAttributes:detailBoldAttr];
896         [finalString appendString:[NSString stringWithFormat:@"%@\n", [item objectForKey:@"PresetName"]] withAttributes:detailAttr];
897         
898         /* Third Line  (Format Summary) */
899         NSString * audioCodecSummary = @"";
900         /* Lets also get our audio track detail since we are going through the logic for use later */
901         NSString * audioDetail1 = @"None";
902         NSString * audioDetail2 = @"None";
903         NSString * audioDetail3 = @"None";
904         NSString * audioDetail4 = @"None";
905         if ([[item objectForKey:@"Audio1Track"] intValue] > 0)
906         {
907             audioCodecSummary = [NSString stringWithFormat:@"%@", [item objectForKey:@"Audio1Encoder"]];
908             audioDetail1 = [NSString stringWithFormat:@"%@ Encoder: %@ Mixdown: %@ SampleRate: %@(khz) Bitrate: %@(kbps)",
909                             [item objectForKey:@"Audio1TrackDescription"] ,
910                             [item objectForKey:@"Audio1Encoder"],
911                             [item objectForKey:@"Audio1Mixdown"] ,
912                             [item objectForKey:@"Audio1Samplerate"],
913                             [item objectForKey:@"Audio1Bitrate"]];
914             
915             if ([[item objectForKey:@"Audio1TrackDRCSlider"] floatValue] > 1.00)
916             {
917                 audioDetail1 = [NSString stringWithFormat:@"%@, DRC: %@",audioDetail1,[item objectForKey:@"Audio1TrackDRCSlider"]];
918             }
919             else
920             {
921                 audioDetail1 = [NSString stringWithFormat:@"%@, DRC: Off",audioDetail1];
922             }
923         }
924         
925         if ([[item objectForKey:@"Audio2Track"] intValue] > 0)
926         {
927             audioCodecSummary = [NSString stringWithFormat:@"%@, %@",audioCodecSummary ,[item objectForKey:@"Audio2Encoder"]];
928             audioDetail2 = [NSString stringWithFormat:@"%@ Encoder: %@ Mixdown: %@ SampleRate: %@(khz) Bitrate: %@(kbps)",
929                             [item objectForKey:@"Audio2TrackDescription"] ,
930                             [item objectForKey:@"Audio2Encoder"],
931                             [item objectForKey:@"Audio2Mixdown"] ,
932                             [item objectForKey:@"Audio2Samplerate"],
933                             [item objectForKey:@"Audio2Bitrate"]];
934             
935             if ([[item objectForKey:@"Audio2TrackDRCSlider"] floatValue] > 1.00)
936             {
937                 audioDetail2 = [NSString stringWithFormat:@"%@, DRC: %@",audioDetail2,[item objectForKey:@"Audio2TrackDRCSlider"]];
938             }
939             else
940             {
941                 audioDetail2 = [NSString stringWithFormat:@"%@, DRC: Off",audioDetail2];
942             }
943         }
944         
945         if ([[item objectForKey:@"Audio3Track"] intValue] > 0)
946         {
947             audioCodecSummary = [NSString stringWithFormat:@"%@, %@",audioCodecSummary ,[item objectForKey:@"Audio3Encoder"]];
948             audioDetail3 = [NSString stringWithFormat:@"%@ Encoder: %@ Mixdown: %@ SampleRate: %@(khz) Bitrate: %@(kbps)",
949                             [item objectForKey:@"Audio3TrackDescription"] ,
950                             [item objectForKey:@"Audio3Encoder"],
951                             [item objectForKey:@"Audio3Mixdown"] ,
952                             [item objectForKey:@"Audio3Samplerate"],
953                             [item objectForKey:@"Audio3Bitrate"]];
954             
955             if ([[item objectForKey:@"Audio3TrackDRCSlider"] floatValue] > 1.00)
956             {
957                 audioDetail3 = [NSString stringWithFormat:@"%@, DRC: %@",audioDetail3,[item objectForKey:@"Audio3TrackDRCSlider"]];
958             }
959             else
960             {
961                 audioDetail3 = [NSString stringWithFormat:@"%@, DRC: Off",audioDetail3];
962             }
963         }
964         
965         if ([[item objectForKey:@"Audio4Track"] intValue] > 0)
966         {
967             audioCodecSummary = [NSString stringWithFormat:@"%@, %@",audioCodecSummary ,[item objectForKey:@"Audio3Encoder"]];
968             audioDetail4 = [NSString stringWithFormat:@"%@ Encoder: %@ Mixdown: %@ SampleRate: %@(khz) Bitrate: %@(kbps)",
969                             [item objectForKey:@"Audio4TrackDescription"] ,
970                             [item objectForKey:@"Audio4Encoder"],
971                             [item objectForKey:@"Audio4Mixdown"] ,
972                             [item objectForKey:@"Audio4Samplerate"],
973                             [item objectForKey:@"Audio4Bitrate"]];
974             
975             if ([[item objectForKey:@"Audio4TrackDRCSlider"] floatValue] > 1.00)
976             {
977                 audioDetail4 = [NSString stringWithFormat:@"%@, DRC: %@",audioDetail4,[item objectForKey:@"Audio4TrackDRCSlider"]];
978             }
979             else
980             {
981                 audioDetail4 = [NSString stringWithFormat:@"%@, DRC: Off",audioDetail4];
982             }
983         }
984         
985         NSString * jobFormatInfo;
986         if ([[item objectForKey:@"ChapterMarkers"] intValue] == 1)
987             jobFormatInfo = [NSString stringWithFormat:@"%@ Container, %@ Video  %@ Audio, Chapter Markers\n", [item objectForKey:@"FileFormat"], [item objectForKey:@"VideoEncoder"], audioCodecSummary];
988         else
989             jobFormatInfo = [NSString stringWithFormat:@"%@ Container, %@ Video  %@ Audio\n", [item objectForKey:@"FileFormat"], [item objectForKey:@"VideoEncoder"], audioCodecSummary];
990         
991         
992         [finalString appendString: @"Format: " withAttributes:detailBoldAttr];
993         [finalString appendString: jobFormatInfo withAttributes:detailAttr];
994         
995         /* Optional String for mp4 options */
996         if ([[item objectForKey:@"FileFormat"] isEqualToString: @"MP4 file"])
997         {
998             NSString * MP4Opts = @"";
999             BOOL mp4OptsPresent = NO;
1000             if( [[item objectForKey:@"Mp4LargeFile"] intValue] == 1)
1001             {
1002                 mp4OptsPresent = YES;
1003                 MP4Opts = [MP4Opts stringByAppendingString:@" - Large file size"];
1004             }
1005             if( [[item objectForKey:@"Mp4HttpOptimize"] intValue] == 1)
1006             {
1007                 mp4OptsPresent = YES;
1008                 MP4Opts = [MP4Opts stringByAppendingString:@" - Web optimized"];
1009             }
1010             
1011             if( [[item objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
1012             {
1013                 mp4OptsPresent = YES;
1014                 MP4Opts = [MP4Opts stringByAppendingString:@" - iPod 5G support "];
1015             }
1016             if (mp4OptsPresent == YES)
1017             {
1018                 [finalString appendString: @"MP4 Options: " withAttributes:detailBoldAttr];
1019                 [finalString appendString: MP4Opts withAttributes:detailAttr];
1020                 [finalString appendString:@"\n" withAttributes:detailAttr];
1021             }
1022         }
1023         
1024         /* Fourth Line (Destination Path)*/
1025         [finalString appendString: @"Destination: " withAttributes:detailBoldAttr];
1026         [finalString appendString: [item objectForKey:@"DestinationPath"] withAttributes:detailAttr];
1027         [finalString appendString:@"\n" withAttributes:detailAttr];
1028         /* Fifth Line Picture Details*/
1029         NSString * pictureInfo;
1030         pictureInfo = [NSString stringWithFormat:@"%@", [item objectForKey:@"PictureSizingSummary"]];
1031         if ([[item objectForKey:@"PictureKeepRatio"] intValue] == 1)
1032         {
1033             pictureInfo = [pictureInfo stringByAppendingString:@" Keep Aspect Ratio"];
1034         }
1035         if ([[item objectForKey:@"VideoGrayScale"] intValue] == 1)
1036         {
1037             pictureInfo = [pictureInfo stringByAppendingString:@", Grayscale"];
1038         }
1039         
1040         [finalString appendString: @"Picture: " withAttributes:detailBoldAttr];
1041         [finalString appendString: pictureInfo withAttributes:detailAttr];
1042         [finalString appendString:@"\n" withAttributes:detailAttr];
1043         
1044         /* Optional String for Picture Filters */
1045         
1046         NSString * pictureFilters = @"";
1047         BOOL pictureFiltersPresent = NO;
1048         
1049         if( [[item objectForKey:@"PictureDetelecine"] intValue] == 1)
1050         {
1051             pictureFiltersPresent = YES;
1052             pictureFilters = [pictureFilters stringByAppendingString:@" - Detelecine (Default)"];
1053         }
1054         else if( [[item objectForKey:@"PictureDetelecine"] intValue] == 2)
1055         {
1056             pictureFiltersPresent = YES;
1057             pictureFilters = [pictureFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[item objectForKey:@"PictureDetelecineCustom"]]];
1058         }
1059         
1060         if( [[item objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
1061         {
1062             if ([[item objectForKey:@"PictureDecomb"] intValue] != 0)
1063             {
1064                 pictureFiltersPresent = YES;
1065                 if( [[item objectForKey:@"PictureDecomb"] intValue] == 1)
1066                 {
1067                     pictureFiltersPresent = YES;
1068                     pictureFilters = [pictureFilters stringByAppendingString:@" - Decomb (Default)"];
1069                 }
1070                 if( [[item objectForKey:@"PictureDecomb"] intValue] == 2)
1071                 {
1072                     pictureFiltersPresent = YES;
1073                     pictureFilters = [pictureFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[item objectForKey:@"PictureDecombCustom"]]];
1074                 }
1075             }
1076         }
1077         else
1078         {
1079             if ([[item objectForKey:@"PictureDeinterlace"] intValue] != 0)
1080             {
1081                 pictureFiltersPresent = YES;
1082                 if ([[item objectForKey:@"PictureDeinterlace"] intValue] == 1)
1083                 {
1084                     pictureFilters = [pictureFilters stringByAppendingString:@" - Deinterlace (Fast)"];
1085                 }
1086                 else if ([[item objectForKey:@"PictureDeinterlace"] intValue] == 2)
1087                 {
1088                     pictureFilters = [pictureFilters stringByAppendingString:@" - Deinterlace (Slow)"];           
1089                 }
1090                 else if ([[item objectForKey:@"PictureDeinterlace"] intValue] == 3)
1091                 {
1092                     pictureFilters = [pictureFilters stringByAppendingString:@" - Deinterlace (Slower)"];            
1093                 }
1094                 else if ([[item objectForKey:@"PictureDeinterlace"] intValue] == 4)
1095                 {
1096                     pictureFilters = [pictureFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[item objectForKey:@"PictureDeinterlaceCustom"]]];            
1097                 }
1098                 
1099             }
1100         }
1101         if ([[item objectForKey:@"PictureDenoise"] intValue] != 0)
1102         {
1103             pictureFiltersPresent = YES;
1104             if ([[item objectForKey:@"PictureDenoise"] intValue] == 1)
1105             {
1106                 pictureFilters = [pictureFilters stringByAppendingString:@" - Denoise (Weak)"];
1107             }
1108             else if ([[item objectForKey:@"PictureDenoise"] intValue] == 2)
1109             {
1110                 pictureFilters = [pictureFilters stringByAppendingString:@" - Denoise (Medium)"];           
1111             }
1112             else if ([[item objectForKey:@"PictureDenoise"] intValue] == 3)
1113             {
1114                 pictureFilters = [pictureFilters stringByAppendingString:@" - Denoise (Strong)"];            
1115             }
1116             else if ([[item objectForKey:@"PictureDenoise"] intValue] == 4)
1117             {
1118                 pictureFilters = [pictureFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[item objectForKey:@"PictureDenoiseCustom"]]];            
1119             }
1120             
1121         }
1122         if ([[item objectForKey:@"PictureDeblock"] intValue] != 0)
1123         {
1124             pictureFiltersPresent = YES;
1125             pictureFilters = [pictureFilters stringByAppendingString: [NSString stringWithFormat:@" - Deblock (pp7) (%d)",[[item objectForKey:@"PictureDeblock"] intValue]]];
1126         }
1127         
1128         if ([[item objectForKey:@"VideoGrayScale"] intValue] == 1)
1129         {
1130             pictureFiltersPresent = YES;
1131             pictureFilters = [pictureFilters stringByAppendingString:@" - Grayscale"];
1132         }
1133         
1134         if (pictureFiltersPresent == YES)
1135         {
1136             [finalString appendString: @"Filters: " withAttributes:detailBoldAttr];
1137             [finalString appendString: pictureFilters withAttributes:detailAttr];
1138             [finalString appendString:@"\n" withAttributes:detailAttr];
1139         }
1140         
1141         /* Sixth Line Video Details*/
1142         NSString * videoInfo;
1143         videoInfo = [NSString stringWithFormat:@"Encoder: %@", [item objectForKey:@"VideoEncoder"]];
1144         
1145         /* for framerate look to see if we are using vfr detelecine */
1146         if ([[item objectForKey:@"JobIndexVideoFramerate"] intValue] == 0)
1147         {
1148             if ([[item objectForKey:@"PictureDetelecine"] intValue] == 1)
1149             {
1150                 /* we are using same as source with vfr detelecine */
1151                 videoInfo = [NSString stringWithFormat:@"%@ Framerate: Same as source (vfr detelecine)", videoInfo];
1152             }
1153             else
1154             {
1155                 /* we are using a variable framerate without dropping frames */
1156                 videoInfo = [NSString stringWithFormat:@"%@ Framerate: Same as source (variable)", videoInfo];
1157             }
1158         }
1159         else
1160         {
1161             /* we have a specified, constant framerate */
1162             videoInfo = [NSString stringWithFormat:@"%@ Framerate: %@ (constant framerate)", videoInfo ,[item objectForKey:@"VideoFramerate"]];
1163         }
1164         
1165         if ([[item objectForKey:@"VideoQualityType"] intValue] == 0)// Target Size MB
1166         {
1167             videoInfo = [NSString stringWithFormat:@"%@ Target Size: %@(MB) (%d(kbps) abr)", videoInfo ,[item objectForKey:@"VideoTargetSize"],[[item objectForKey:@"VideoAvgBitrate"] intValue]];
1168         }
1169         else if ([[item objectForKey:@"VideoQualityType"] intValue] == 1) // ABR
1170         {
1171             videoInfo = [NSString stringWithFormat:@"%@ Bitrate: %d(kbps)", videoInfo ,[[item objectForKey:@"VideoAvgBitrate"] intValue]];
1172         }
1173         else // CRF
1174         {
1175             videoInfo = [NSString stringWithFormat:@"%@ Constant Quality: %.2f", videoInfo ,[[item objectForKey:@"VideoQualitySlider"] floatValue]];
1176         }
1177         
1178         [finalString appendString: @"Video: " withAttributes:detailBoldAttr];
1179         [finalString appendString: videoInfo withAttributes:detailAttr];
1180         [finalString appendString:@"\n" withAttributes:detailAttr];
1181         
1182         if ([[item objectForKey:@"VideoEncoder"] isEqualToString: @"H.264 (x264)"])
1183         {
1184             [finalString appendString: @"x264 Options: " withAttributes:detailBoldAttr];
1185             [finalString appendString: [item objectForKey:@"x264Option"] withAttributes:detailAttr];
1186             [finalString appendString:@"\n" withAttributes:detailAttr];
1187         }
1188         
1189         
1190         /* Seventh Line Audio Details*/
1191         [finalString appendString: @"Audio Track 1: " withAttributes:detailBoldAttr];
1192         [finalString appendString: audioDetail1 withAttributes:detailAttr];
1193         [finalString appendString:@"\n" withAttributes:detailAttr];
1194         
1195         [finalString appendString: @"Audio Track 2: " withAttributes:detailBoldAttr];
1196         [finalString appendString: audioDetail2 withAttributes:detailAttr];
1197         [finalString appendString:@"\n" withAttributes:detailAttr];
1198         
1199         [finalString appendString: @"Audio Track 3: " withAttributes:detailBoldAttr];
1200         [finalString appendString: audioDetail3 withAttributes:detailAttr];
1201         [finalString appendString:@"\n" withAttributes:detailAttr];
1202         
1203         [finalString appendString: @"Audio Track 4: " withAttributes:detailBoldAttr];
1204         [finalString appendString: audioDetail4 withAttributes:detailAttr];
1205         
1206         return finalString;
1207     }
1208     else if ([[tableColumn identifier] isEqualToString:@"icon"])
1209     {
1210         if ([[item objectForKey:@"Status"] intValue] == 0)
1211         {
1212             return [NSImage imageNamed:@"EncodeComplete"];
1213         }
1214         else if ([[item objectForKey:@"Status"] intValue] == 1)
1215         {
1216             return [NSImage imageNamed: [NSString stringWithFormat: @"EncodeWorking%d", fAnimationIndex]];
1217         }
1218         else if ([[item objectForKey:@"Status"] intValue] == 3)
1219         {
1220             return [NSImage imageNamed:@"EncodeCanceled"];
1221         }
1222         else
1223         {
1224             return [NSImage imageNamed:@"JobSmall"];
1225         }
1226         
1227     }
1228     else
1229     {
1230         return @"";
1231     }
1232 }
1233
1234 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
1235 {
1236     if ([[tableColumn identifier] isEqualToString:@"desc"])
1237     {
1238
1239
1240         // nb: The "desc" column is currently an HBImageAndTextCell. However, we are longer
1241         // using the image portion of the cell so we could switch back to a regular NSTextFieldCell.
1242
1243         // Set the image here since the value returned from outlineView:objectValueForTableColumn: didn't specify the image part
1244         [cell setImage:nil];
1245     }
1246     else if ([[tableColumn identifier] isEqualToString:@"action"])
1247     {
1248         [cell setEnabled: YES];
1249         BOOL highlighted = [outlineView isRowSelected:[outlineView rowForItem: item]] && [[outlineView window] isKeyWindow] && ([[outlineView window] firstResponder] == outlineView);
1250         if ([[item objectForKey:@"Status"] intValue] == 0)
1251         {
1252             [cell setAction: @selector(revealSelectedQueueItem:)];
1253             if (highlighted)
1254             {
1255                 [cell setImage:[NSImage imageNamed:@"RevealHighlight"]];
1256                 [cell setAlternateImage:[NSImage imageNamed:@"RevealHighlightPressed"]];
1257             }
1258             else
1259                 [cell setImage:[NSImage imageNamed:@"Reveal"]];
1260         }
1261         else
1262         {
1263             [cell setAction: @selector(removeSelectedQueueItem:)];
1264             if (highlighted)
1265             {
1266                 [cell setImage:[NSImage imageNamed:@"DeleteHighlight"]];
1267                 [cell setAlternateImage:[NSImage imageNamed:@"DeleteHighlightPressed"]];
1268             }
1269             else
1270                 [cell setImage:[NSImage imageNamed:@"Delete"]];
1271         }
1272     }
1273 }
1274
1275 - (void)outlineView:(NSOutlineView *)outlineView willDisplayOutlineCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
1276 {
1277     // By default, the discolsure image gets centered vertically in the cell. We want
1278     // always at the top.
1279     if ([outlineView isItemExpanded: item])
1280         [cell setImagePosition: NSImageAbove];
1281     else
1282         [cell setImagePosition: NSImageOnly];
1283 }
1284
1285 #pragma mark -
1286 #pragma mark NSOutlineView delegate (dragging related)
1287
1288 //------------------------------------------------------------------------------------
1289 // NSTableView delegate
1290 //------------------------------------------------------------------------------------
1291
1292
1293 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
1294 {
1295     // Dragging is only allowed of the pending items.
1296     if ([[[items objectAtIndex:0] objectForKey:@"Status"] integerValue] != 2) // 2 is pending
1297     {
1298         return NO;
1299     }
1300     
1301     // Don't retain since this is just holding temporaral drag information, and it is
1302     //only used during a drag!  We could put this in the pboard actually.
1303     fDraggedNodes = items;
1304     
1305     // Provide data for our custom type, and simple NSStrings.
1306     [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
1307     
1308     // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
1309     [pboard setData:[NSData data] forType:DragDropSimplePboardType];
1310     
1311     return YES;
1312 }
1313
1314
1315 /* This method is used to validate the drops. */
1316 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
1317 {
1318     // Don't allow dropping ONTO an item since they can't really contain any children.
1319     BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
1320     if (isOnDropTypeProposal)
1321     {
1322         return NSDragOperationNone;
1323     }
1324     
1325     // Don't allow dropping INTO an item since they can't really contain any children.
1326     if (item != nil)
1327     {
1328         index = [fOutlineView rowForItem: item] + 1;
1329         item = nil;
1330     }
1331     
1332     // NOTE: Should we allow dropping a pending job *above* the
1333     // finished or already encoded jobs ?
1334     // We do not let the user drop a pending job before or *above*
1335     // already finished or currently encoding jobs.
1336     if (index <= fEncodingQueueItem)
1337     {
1338         return NSDragOperationNone;
1339         index = MAX (index, fEncodingQueueItem);
1340         }
1341     
1342     [outlineView setDropItem:item dropChildIndex:index];
1343     return NSDragOperationGeneric;
1344 }
1345
1346 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
1347 {
1348     NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
1349
1350     for( id obj in fDraggedNodes )
1351         [moveItems addIndex:[fJobGroups indexOfObject:obj]];
1352
1353     // Successful drop, we use moveObjectsInQueueArray:... in fHBController
1354     // to properly rearrange the queue array, save it to plist and then send it back here.
1355     // since Controller.mm is handling all queue array manipulation.
1356     // We *could do this here, but I think we are better served keeping that code together.
1357     [fHBController moveObjectsInQueueArray:fJobGroups fromIndexes:moveItems toIndex: index];
1358     return YES;
1359 }
1360
1361
1362 @end