xref: /haiku/src/apps/mediaplayer/MainWin.cpp (revision b5a859ad6285b14769a5ede7b81e4261044faf7e)
1 /*
2  * MainWin.cpp - Media Player for the Haiku Operating System
3  *
4  * Copyright (C) 2006 Marcus Overhagen <marcus@overhagen.de>
5  * Copyright (C) 2007-2010 Stephan Aßmus <superstippi@gmx.de> (GPL->MIT ok)
6  * Copyright (C) 2007-2009 Fredrik Modéen <[FirstName]@[LastName].se> (MIT ok)
7  *
8  * Released under the terms of the MIT license.
9  */
10 
11 
12 #include "MainWin.h"
13 
14 #include <math.h>
15 #include <stdio.h>
16 #include <string.h>
17 
18 #include <Alert.h>
19 #include <Application.h>
20 #include <Autolock.h>
21 #include <Catalog.h>
22 #include <Debug.h>
23 #include <Directory.h>
24 #include <Drivers.h>
25 #include <fs_attr.h>
26 #include <LayoutBuilder.h>
27 #include <Language.h>
28 #include <Locale.h>
29 #include <MediaRoster.h>
30 #include <Menu.h>
31 #include <MenuBar.h>
32 #include <MenuItem.h>
33 #include <MessageRunner.h>
34 #include <Messenger.h>
35 #include <PopUpMenu.h>
36 #include <PropertyInfo.h>
37 #include <RecentItems.h>
38 #include <Roster.h>
39 #include <Screen.h>
40 #include <String.h>
41 #include <TypeConstants.h>
42 #include <View.h>
43 
44 #include "AudioProducer.h"
45 #include "ControllerObserver.h"
46 #include "DurationToString.h"
47 #include "FilePlaylistItem.h"
48 #include "MainApp.h"
49 #include "NetworkStreamWin.h"
50 #include "PeakView.h"
51 #include "PlaylistItem.h"
52 #include "PlaylistObserver.h"
53 #include "PlaylistWindow.h"
54 #include "Settings.h"
55 
56 
57 #undef B_TRANSLATION_CONTEXT
58 #define B_TRANSLATION_CONTEXT "MediaPlayer-Main"
59 #define MIN_WIDTH 250
60 
61 
62 int MainWin::sNoVideoWidth = MIN_WIDTH;
63 
64 
65 // XXX TODO: why is lround not defined?
66 #define lround(a) ((int)(0.99999 + (a)))
67 
68 enum {
69 	M_DUMMY = 0x100,
70 	M_FILE_OPEN = 0x1000,
71 	M_NETWORK_STREAM_OPEN,
72 	M_EJECT_DEVICE,
73 	M_FILE_INFO,
74 	M_FILE_PLAYLIST,
75 	M_FILE_CLOSE,
76 	M_FILE_QUIT,
77 	M_VIEW_SIZE,
78 	M_TOGGLE_FULLSCREEN,
79 	M_TOGGLE_ALWAYS_ON_TOP,
80 	M_TOGGLE_NO_INTERFACE,
81 	M_VOLUME_UP,
82 	M_VOLUME_DOWN,
83 	M_SKIP_NEXT,
84 	M_SKIP_PREV,
85 	M_WIND,
86 
87 	// The common display aspect ratios
88 	M_ASPECT_SAME_AS_SOURCE,
89 	M_ASPECT_NO_DISTORTION,
90 	M_ASPECT_4_3,
91 	M_ASPECT_16_9,
92 	M_ASPECT_83_50,
93 	M_ASPECT_7_4,
94 	M_ASPECT_37_20,
95 	M_ASPECT_47_20,
96 
97 	M_SELECT_AUDIO_TRACK			= 0x00000800,
98 	M_SELECT_AUDIO_TRACK_END		= 0x00000fff,
99 	M_SELECT_VIDEO_TRACK			= 0x00010000,
100 	M_SELECT_VIDEO_TRACK_END		= 0x00010fff,
101 	M_SELECT_SUB_TITLE_TRACK		= 0x00020000,
102 	M_SELECT_SUB_TITLE_TRACK_END	= 0x00020fff,
103 
104 	M_SET_RATING,
105 
106 	M_SET_PLAYLIST_POSITION,
107 
108 	M_FILE_DELETE,
109 
110 	M_SLIDE_CONTROLS,
111 	M_FINISH_SLIDING_CONTROLS
112 };
113 
114 
115 static property_info sPropertyInfo[] = {
116 	{ "Next", { B_EXECUTE_PROPERTY },
117 		{ B_DIRECT_SPECIFIER, 0 },
118 		"Skip to the next track.", 0
119 	},
120 	{ "Prev", { B_EXECUTE_PROPERTY },
121 		{ B_DIRECT_SPECIFIER, 0 },
122 		"Skip to the previous track.", 0
123 	},
124 	{ "Play", { B_EXECUTE_PROPERTY },
125 		{ B_DIRECT_SPECIFIER, 0 },
126 		"Start playing.", 0
127 	},
128 	{ "Stop", { B_EXECUTE_PROPERTY },
129 		{ B_DIRECT_SPECIFIER, 0 },
130 		"Stop playing.", 0
131 	},
132 	{ "Pause", { B_EXECUTE_PROPERTY },
133 		{ B_DIRECT_SPECIFIER, 0 },
134 		"Pause playback.", 0
135 	},
136 	{ "TogglePlaying", { B_EXECUTE_PROPERTY },
137 		{ B_DIRECT_SPECIFIER, 0 },
138 		"Toggle pause/play.", 0
139 	},
140 	{ "Mute", { B_EXECUTE_PROPERTY },
141 		{ B_DIRECT_SPECIFIER, 0 },
142 		"Toggle mute.", 0
143 	},
144 	{ "Volume", { B_GET_PROPERTY, B_SET_PROPERTY, 0 },
145 		{ B_DIRECT_SPECIFIER, 0 },
146 		"Gets/sets the volume (0.0-2.0).", 0,
147 		{ B_FLOAT_TYPE }
148 	},
149 	{ "URI", { B_GET_PROPERTY, 0 },
150 		{ B_DIRECT_SPECIFIER, 0 },
151 		"Gets the URI of the currently playing item.", 0,
152 		{ B_STRING_TYPE }
153 	},
154 	{ "TrackNumber", { B_GET_PROPERTY, 0 },
155 		{ B_DIRECT_SPECIFIER, 0 },
156 		"Gets the number of the current track playing.", 0,
157 		{ B_INT32_TYPE }
158 	},
159 	{ "ToggleFullscreen", { B_EXECUTE_PROPERTY },
160 		{ B_DIRECT_SPECIFIER, 0 },
161 		"Toggle fullscreen.", 0
162 	},
163 	{ "Duration", { B_GET_PROPERTY, 0 },
164 		{ B_DIRECT_SPECIFIER, 0 },
165 		"Gets the duration of the currently playing item "
166 			"in microseconds.", 0,
167 		{ B_INT64_TYPE }
168 	},
169 	{ "Position", { B_GET_PROPERTY, B_SET_PROPERTY, 0 },
170 		{ B_DIRECT_SPECIFIER, 0 },
171 		"Gets/sets the current playing position in microseconds.",
172 		0, { B_INT64_TYPE }
173 	},
174 	{ "Seek", { B_SET_PROPERTY },
175 		{ B_DIRECT_SPECIFIER, 0 },
176 		"Seek by the specified amounts of microseconds.", 0,
177 		{ B_INT64_TYPE }
178 	},
179 	{ "PlaylistTrackCount", { B_GET_PROPERTY, 0 },
180 		{ B_DIRECT_SPECIFIER, 0 },
181 		"Gets the number of tracks in Playlist.", 0,
182 		{ B_INT16_TYPE }
183 	},
184 	{ "PlaylistTrackTitle", { B_GET_PROPERTY, 0 },
185 		{ B_INDEX_SPECIFIER, 0 },
186 		"Gets the title of the nth track in Playlist.", 0,
187 		{ B_STRING_TYPE }
188 	},
189 
190 	{ 0 }
191 };
192 
193 
194 static const char* kRatingAttrName = "Media:Rating";
195 
196 static const char* kDisabledSeekMessage = B_TRANSLATE("Drop files to play");
197 
198 static const char* kApplicationName = B_TRANSLATE_SYSTEM_NAME(NAME);
199 
200 
201 MainWin::MainWin(bool isFirstWindow, BMessage* message)
202 	:
203 	BWindow(BRect(100, 100, 400, 300), kApplicationName, B_TITLED_WINDOW,
204  		B_ASYNCHRONOUS_CONTROLS),
205  	fCreationTime(system_time()),
206 	fInfoWin(NULL),
207 	fPlaylistWindow(NULL),
208 	fHasFile(false),
209 	fHasVideo(false),
210 	fHasAudio(false),
211 	fPlaylist(new Playlist),
212 	fPlaylistObserver(new PlaylistObserver(this)),
213 	fController(new Controller),
214 	fControllerObserver(new ControllerObserver(this,
215 		OBSERVE_FILE_CHANGES | OBSERVE_TRACK_CHANGES
216 			| OBSERVE_PLAYBACK_STATE_CHANGES | OBSERVE_POSITION_CHANGES
217 			| OBSERVE_VOLUME_CHANGES)),
218 	fIsFullscreen(false),
219 	fAlwaysOnTop(false),
220 	fNoInterface(false),
221 	fShowsFullscreenControls(false),
222 	fSourceWidth(-1),
223 	fSourceHeight(-1),
224 	fWidthAspect(0),
225 	fHeightAspect(0),
226 	fSavedFrame(),
227 	fNoVideoFrame(),
228 
229 	fMouseDownTracking(false),
230 	fLastMousePos(0, 0),
231 	fLastMouseMovedTime(system_time()),
232 	fMouseMoveDist(0),
233 
234 	fGlobalSettingsListener(this),
235 	fInitialSeekPosition(0),
236 	fAllowWinding(true)
237 {
238 	// Handle window position and size depending on whether this is the
239 	// first window or not. Use the window size from the window that was
240 	// last resized by the user.
241 	static int pos = 0;
242 	MoveBy(pos * 25, pos * 25);
243 	pos = (pos + 1) % 15;
244 
245 	BRect frame = Settings::Default()->AudioPlayerWindowFrame();
246 	if (frame.IsValid()) {
247 		if (isFirstWindow) {
248 			if (message == NULL) {
249 				MoveTo(frame.LeftTop());
250 				ResizeTo(frame.Width(), frame.Height());
251 			} else {
252 				// Delay moving to the initial position, since we don't
253 				// know if we will be playing audio at all.
254 				message->AddRect("window frame", frame);
255 			}
256 		}
257 		if (sNoVideoWidth == MIN_WIDTH)
258 			sNoVideoWidth = frame.IntegerWidth();
259 	} else if (sNoVideoWidth > MIN_WIDTH) {
260 		ResizeTo(sNoVideoWidth, Bounds().Height());
261 	}
262 	fNoVideoWidth = sNoVideoWidth;
263 
264 	BRect rect = Bounds();
265 
266 	// background
267 	fBackground = new BView(rect, "background", B_FOLLOW_ALL,
268 		B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE);
269 	fBackground->SetViewColor(0, 0, 0);
270 	AddChild(fBackground);
271 
272 	// menu
273 	fMenuBar = new BMenuBar(fBackground->Bounds(), "menu");
274 	_CreateMenu();
275 	fBackground->AddChild(fMenuBar);
276 	fMenuBar->SetResizingMode(B_FOLLOW_NONE);
277 	fMenuBar->ResizeToPreferred();
278 	fMenuBarWidth = (int)fMenuBar->Frame().Width() + 1;
279 	fMenuBarHeight = (int)fMenuBar->Frame().Height() + 1;
280 
281 	// video view
282 	rect = BRect(0, fMenuBarHeight, fBackground->Bounds().right,
283 		fMenuBarHeight + 10);
284 	fVideoView = new VideoView(rect, "video display", B_FOLLOW_NONE);
285 	fBackground->AddChild(fVideoView);
286 
287 	// controls
288 	rect = BRect(0, fMenuBarHeight + 11, fBackground->Bounds().right,
289 		fBackground->Bounds().bottom);
290 	fControls = new ControllerView(rect, fController, fPlaylist);
291 	fBackground->AddChild(fControls);
292 	fControls->ResizeToPreferred();
293 	fControlsHeight = (int)fControls->Frame().Height() + 1;
294 	fControlsWidth = (int)fControls->Frame().Width() + 1;
295 	fControls->SetResizingMode(B_FOLLOW_BOTTOM | B_FOLLOW_LEFT_RIGHT);
296 	fControls->SetDisabledString(kDisabledSeekMessage);
297 
298 	fPlaylist->AddListener(fPlaylistObserver);
299 	fController->SetVideoView(fVideoView);
300 	fController->AddListener(fControllerObserver);
301 	PeakView* peakView = fControls->GetPeakView();
302 	peakView->SetPeakNotificationWhat(MSG_PEAK_NOTIFICATION);
303 	fController->SetPeakListener(peakView);
304 
305 	_SetupWindow();
306 
307 	// setup the playlist window now, we need to have it
308 	// running for the undo/redo playlist editing
309 	fPlaylistWindow = new PlaylistWindow(BRect(150, 150, 500, 600), fPlaylist,
310 		fController);
311 	fPlaylistWindow->Hide();
312 	fPlaylistWindow->Show();
313 		// this makes sure the window thread is running without
314 		// showing the window just yet
315 
316 	Settings::Default()->AddListener(&fGlobalSettingsListener);
317 	_AdoptGlobalSettings();
318 
319 	AddShortcut('z', B_COMMAND_KEY, new BMessage(B_UNDO));
320 	AddShortcut('y', B_COMMAND_KEY, new BMessage(B_UNDO));
321 	AddShortcut('z', B_COMMAND_KEY | B_SHIFT_KEY, new BMessage(B_REDO));
322 	AddShortcut('y', B_COMMAND_KEY | B_SHIFT_KEY, new BMessage(B_REDO));
323 
324 	Hide();
325 	Show();
326 
327 	if (message != NULL)
328 		PostMessage(message);
329 
330 	BMediaRoster* roster = BMediaRoster::Roster();
331 	roster->StartWatching(BMessenger(this, this), B_MEDIA_SERVER_STARTED);
332 	roster->StartWatching(BMessenger(this, this),  B_MEDIA_SERVER_QUIT);
333 }
334 
335 
336 MainWin::~MainWin()
337 {
338 //	printf("MainWin::~MainWin\n");
339 
340 	BMediaRoster* roster = BMediaRoster::CurrentRoster();
341 	roster->StopWatching(BMessenger(this, this), B_MEDIA_SERVER_STARTED);
342 	roster->StopWatching(BMessenger(this, this), B_MEDIA_SERVER_QUIT);
343 
344 	Settings::Default()->RemoveListener(&fGlobalSettingsListener);
345 	fPlaylist->RemoveListener(fPlaylistObserver);
346 	fController->Lock();
347 	fController->RemoveListener(fControllerObserver);
348 	fController->SetPeakListener(NULL);
349 	fController->SetVideoTarget(NULL);
350 	fController->Unlock();
351 
352 	// give the views a chance to detach from any notifiers
353 	// before we delete them
354 	fBackground->RemoveSelf();
355 	delete fBackground;
356 
357 	if (fInfoWin && fInfoWin->Lock())
358 		fInfoWin->Quit();
359 
360 	if (fPlaylistWindow && fPlaylistWindow->Lock())
361 		fPlaylistWindow->Quit();
362 
363 	delete fPlaylist;
364 	fPlaylist = NULL;
365 
366 	// quit the Controller looper thread
367 	thread_id controllerThread = fController->Thread();
368 	fController->PostMessage(B_QUIT_REQUESTED);
369 	status_t exitValue;
370 	wait_for_thread(controllerThread, &exitValue);
371 }
372 
373 
374 // #pragma mark -
375 
376 
377 void
378 MainWin::FrameResized(float newWidth, float newHeight)
379 {
380 	if (newWidth != Bounds().Width() || newHeight != Bounds().Height()) {
381 		debugger("size wrong\n");
382 	}
383 
384 	bool noMenu = fNoInterface || fIsFullscreen;
385 	bool noControls = fNoInterface || fIsFullscreen;
386 
387 //	printf("FrameResized enter: newWidth %.0f, newHeight %.0f\n",
388 //		newWidth, newHeight);
389 
390 	if (!fHasVideo)
391 		sNoVideoWidth = fNoVideoWidth = (int)newWidth;
392 
393 	int maxVideoWidth  = int(newWidth) + 1;
394 	int maxVideoHeight = int(newHeight) + 1
395 		- (noMenu  ? 0 : fMenuBarHeight)
396 		- (noControls ? 0 : fControlsHeight);
397 
398 	ASSERT(maxVideoHeight >= 0);
399 
400 	int y = 0;
401 
402 	if (noMenu) {
403 		if (!fMenuBar->IsHidden(fMenuBar))
404 			fMenuBar->Hide();
405 	} else {
406 		fMenuBar->MoveTo(0, y);
407 		fMenuBar->ResizeTo(newWidth, fMenuBarHeight - 1);
408 		if (fMenuBar->IsHidden(fMenuBar))
409 			fMenuBar->Show();
410 		y += fMenuBarHeight;
411 	}
412 
413 	if (maxVideoHeight == 0) {
414 		if (!fVideoView->IsHidden(fVideoView))
415 			fVideoView->Hide();
416 	} else {
417 		_ResizeVideoView(0, y, maxVideoWidth, maxVideoHeight);
418 		if (fVideoView->IsHidden(fVideoView))
419 			fVideoView->Show();
420 		y += maxVideoHeight;
421 	}
422 
423 	if (noControls) {
424 		if (!fControls->IsHidden(fControls))
425 			fControls->Hide();
426 	} else {
427 		fControls->MoveTo(0, y);
428 		fControls->ResizeTo(newWidth, fControlsHeight - 1);
429 		if (fControls->IsHidden(fControls))
430 			fControls->Show();
431 //		y += fControlsHeight;
432 	}
433 
434 //	printf("FrameResized leave\n");
435 }
436 
437 
438 void
439 MainWin::Zoom(BPoint /*position*/, float /*width*/, float /*height*/)
440 {
441 	PostMessage(M_TOGGLE_FULLSCREEN);
442 }
443 
444 
445 void
446 MainWin::DispatchMessage(BMessage* msg, BHandler* handler)
447 {
448 	if ((msg->what == B_MOUSE_DOWN)
449 		&& (handler == fBackground || handler == fVideoView
450 			|| handler == fControls)) {
451 		_MouseDown(msg, dynamic_cast<BView*>(handler));
452 	}
453 
454 	if ((msg->what == B_MOUSE_MOVED)
455 		&& (handler == fBackground || handler == fVideoView
456 			|| handler == fControls)) {
457 		_MouseMoved(msg, dynamic_cast<BView*>(handler));
458 	}
459 
460 	if ((msg->what == B_MOUSE_UP)
461 		&& (handler == fBackground || handler == fVideoView)) {
462 		_MouseUp(msg);
463 	}
464 
465 	if ((msg->what == B_KEY_DOWN)
466 		&& (handler == fBackground || handler == fVideoView)) {
467 		// special case for PrintScreen key
468 		if (msg->FindInt32("key") == B_PRINT_KEY) {
469 			fVideoView->OverlayScreenshotPrepare();
470 			BWindow::DispatchMessage(msg, handler);
471 			fVideoView->OverlayScreenshotCleanup();
472 			return;
473 		}
474 
475 		// every other key gets dispatched to our _KeyDown first
476 		if (_KeyDown(msg)) {
477 			// it got handled, don't pass it on
478 			return;
479 		}
480 	}
481 
482 	BWindow::DispatchMessage(msg, handler);
483 }
484 
485 
486 void
487 MainWin::MessageReceived(BMessage* msg)
488 {
489 //	msg->PrintToStream();
490 	switch (msg->what) {
491 		case B_EXECUTE_PROPERTY:
492 		case B_GET_PROPERTY:
493 		case B_SET_PROPERTY:
494 		{
495 			BMessage reply(B_REPLY);
496 			status_t result = B_BAD_SCRIPT_SYNTAX;
497 			int32 index;
498 			BMessage specifier;
499 			int32 what;
500 			const char* property;
501 
502 			if (msg->GetCurrentSpecifier(&index, &specifier, &what,
503 					&property) != B_OK) {
504 				return BWindow::MessageReceived(msg);
505 			}
506 
507 			BPropertyInfo propertyInfo(sPropertyInfo);
508 			switch (propertyInfo.FindMatch(msg, index, &specifier, what,
509 					property)) {
510 				case 0:
511 					fControls->SkipForward();
512 					result = B_OK;
513 					break;
514 
515 				case 1:
516 					fControls->SkipBackward();
517 					result = B_OK;
518 					break;
519 
520 				case 2:
521 					fController->Play();
522 					result = B_OK;
523 					break;
524 
525 				case 3:
526 					fController->Stop();
527 					result = B_OK;
528 					break;
529 
530 				case 4:
531 					fController->Pause();
532 					result = B_OK;
533 					break;
534 
535 				case 5:
536 					fController->TogglePlaying();
537 					result = B_OK;
538 					break;
539 
540 				case 6:
541 					fController->ToggleMute();
542 					result = B_OK;
543 					break;
544 
545 				case 7:
546 				{
547 					if (msg->what == B_GET_PROPERTY) {
548 						result = reply.AddFloat("result",
549 							fController->Volume());
550 					} else if (msg->what == B_SET_PROPERTY) {
551 						float newVolume;
552 						result = msg->FindFloat("data", &newVolume);
553 						if (result == B_OK)
554 							fController->SetVolume(newVolume);
555 					}
556 					break;
557 				}
558 
559 				case 8:
560 				{
561 					if (msg->what == B_GET_PROPERTY) {
562 						BAutolock _(fPlaylist);
563 						const PlaylistItem* item = fController->Item();
564 						if (item == NULL) {
565 							result = B_NO_INIT;
566 							break;
567 						}
568 
569 						result = reply.AddString("result", item->LocationURI());
570 					}
571 					break;
572 				}
573 
574 				case 9:
575 				{
576 					if (msg->what == B_GET_PROPERTY) {
577 						BAutolock _(fPlaylist);
578 						const PlaylistItem* item = fController->Item();
579 						if (item == NULL) {
580 							result = B_NO_INIT;
581 							break;
582 						}
583 
584 						result = reply.AddInt32("result", item->TrackNumber());
585 					}
586 					break;
587 				}
588 
589 				case 10:
590 					PostMessage(M_TOGGLE_FULLSCREEN);
591 					break;
592 
593 				case 11:
594 					if (msg->what != B_GET_PROPERTY)
595 						break;
596 
597 					result = reply.AddInt64("result",
598 						fController->TimeDuration());
599 					break;
600 
601 				case 12:
602 				{
603 					if (msg->what == B_GET_PROPERTY) {
604 						result = reply.AddInt64("result",
605 							fController->TimePosition());
606 					} else if (msg->what == B_SET_PROPERTY) {
607 						int64 newTime;
608 						result = msg->FindInt64("data", &newTime);
609 						if (result == B_OK)
610 							fController->SetTimePosition(newTime);
611 					}
612 
613 					break;
614 				}
615 
616 				case 13:
617 				{
618 					if (msg->what != B_SET_PROPERTY)
619 						break;
620 
621 					bigtime_t seekBy;
622 					result = msg->FindInt64("data", &seekBy);
623 					if (result != B_OK)
624 						break;
625 
626 					_Wind(seekBy, 0);
627 					break;
628 				}
629 
630 				case 14:
631 					result = reply.AddInt16("result", fPlaylist->CountItems());
632 					break;
633 
634 				case 15:
635 				{
636 					int32 i = specifier.GetInt32("index", 0);
637 					if (i >= fPlaylist->CountItems()) {
638 						result = B_NO_INIT;
639 						break;
640 					}
641 
642 					BAutolock _(fPlaylist);
643 					const PlaylistItem* item = fPlaylist->ItemAt(i);
644 					result = item == NULL ? B_NO_INIT
645 						: reply.AddString("result", item->Title());
646 					break;
647 				}
648 
649 				default:
650 					return BWindow::MessageReceived(msg);
651 			}
652 
653 			if (result != B_OK) {
654 				reply.what = B_MESSAGE_NOT_UNDERSTOOD;
655 				reply.AddString("message", strerror(result));
656 				reply.AddInt32("error", result);
657 			}
658 
659 			msg->SendReply(&reply);
660 			break;
661 		}
662 
663 		case B_REFS_RECEIVED:
664 		case M_URL_RECEIVED:
665 			_RefsReceived(msg);
666 			break;
667 
668 		case B_SIMPLE_DATA:
669 			if (msg->HasRef("refs"))
670 				_RefsReceived(msg);
671 			break;
672 		case M_OPEN_PREVIOUS_PLAYLIST:
673 			OpenPlaylist(msg);
674 			break;
675 
676 		case B_UNDO:
677 		case B_REDO:
678 			fPlaylistWindow->PostMessage(msg);
679 			break;
680 
681 		case B_MEDIA_SERVER_STARTED:
682 		{
683 			printf("TODO: implement B_MEDIA_SERVER_STARTED\n");
684 //
685 //			BAutolock _(fPlaylist);
686 //			BMessage fakePlaylistMessage(MSG_PLAYLIST_CURRENT_ITEM_CHANGED);
687 //			fakePlaylistMessage.AddInt32("index",
688 //				fPlaylist->CurrentItemIndex());
689 //			PostMessage(&fakePlaylistMessage);
690 			break;
691 		}
692 
693 		case B_MEDIA_SERVER_QUIT:
694 			printf("TODO: implement B_MEDIA_SERVER_QUIT\n");
695 //			if (fController->Lock()) {
696 //				fController->CleanupNodes();
697 //				fController->Unlock();
698 //			}
699 			break;
700 
701 		// PlaylistObserver messages
702 		case MSG_PLAYLIST_ITEM_ADDED:
703 		{
704 			PlaylistItem* item;
705 			int32 index;
706 			if (msg->FindPointer("item", (void**)&item) == B_OK
707 				&& msg->FindInt32("index", &index) == B_OK) {
708 				_AddPlaylistItem(item, index);
709 			}
710 			break;
711 		}
712 		case MSG_PLAYLIST_ITEM_REMOVED:
713 		{
714 			int32 index;
715 			if (msg->FindInt32("index", &index) == B_OK)
716 				_RemovePlaylistItem(index);
717 			break;
718 		}
719 		case MSG_PLAYLIST_CURRENT_ITEM_CHANGED:
720 		{
721 			BAutolock _(fPlaylist);
722 
723 			int32 index;
724 			// if false, the message was meant to only update the GUI
725 			bool play;
726 			if (msg->FindBool("play", &play) < B_OK || !play)
727 				break;
728 			if (msg->FindInt32("index", &index) < B_OK
729 				|| index != fPlaylist->CurrentItemIndex())
730 				break;
731 			PlaylistItemRef item(fPlaylist->ItemAt(index));
732 			if (item.IsSet()) {
733 				printf("open playlist item: %s\n", item->Name().String());
734 				OpenPlaylistItem(item);
735 				_MarkPlaylistItem(index);
736 			}
737 			break;
738 		}
739 		case MSG_PLAYLIST_IMPORT_FAILED:
740 		{
741 			BAlert* alert = new BAlert(B_TRANSLATE("Nothing to Play"),
742 				B_TRANSLATE("None of the files you wanted to play appear "
743 				"to be media files."), B_TRANSLATE("OK"));
744 			alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
745 			alert->Go();
746 			fControls->SetDisabledString(kDisabledSeekMessage);
747 			break;
748 		}
749 
750 		// ControllerObserver messages
751 		case MSG_CONTROLLER_FILE_FINISHED:
752 		{
753 			BAutolock _(fPlaylist);
754 
755 			//The file is finished. Open at start next time.
756 			fController->SaveState(true);
757 
758 			bool hadNext = fPlaylist->SetCurrentItemIndex(
759 				fPlaylist->CurrentItemIndex() + 1);
760 			if (!hadNext) {
761 				// Reached end of playlist
762 				// Handle "quit when done" settings
763 				if ((fHasVideo && fCloseWhenDonePlayingMovie)
764 					|| (!fHasVideo && fCloseWhenDonePlayingSound))
765 					PostMessage(B_QUIT_REQUESTED);
766 				// Handle "loop by default" settings
767 				if ((fHasVideo && fLoopMovies)
768 					|| (!fHasVideo && fLoopSounds)) {
769 					if (fPlaylist->CountItems() > 1)
770 						fPlaylist->SetCurrentItemIndex(0);
771 					else
772 						fController->Play();
773 				}
774 			}
775 			break;
776 		}
777 		case MSG_CONTROLLER_FILE_CHANGED:
778 		{
779 			status_t result = B_ERROR;
780 			msg->FindInt32("result", &result);
781 			PlaylistItemRef itemRef;
782 			PlaylistItem* item;
783 			if (msg->FindPointer("item", (void**)&item) == B_OK) {
784 				itemRef.SetTo(item, true);
785 					// The reference was passed along with the message.
786 			} else {
787 				BAutolock _(fPlaylist);
788 				itemRef.SetTo(fPlaylist->ItemAt(
789 					fPlaylist->CurrentItemIndex()));
790 			}
791 			_PlaylistItemOpened(itemRef, result);
792 			break;
793 		}
794 		case MSG_CONTROLLER_VIDEO_TRACK_CHANGED:
795 		{
796 			int32 index;
797 			if (msg->FindInt32("index", &index) == B_OK) {
798 				int32 i = 0;
799 				while (BMenuItem* item = fVideoTrackMenu->ItemAt(i)) {
800 					item->SetMarked(i == index);
801 					i++;
802 				}
803 			}
804 			break;
805 		}
806 		case MSG_CONTROLLER_AUDIO_TRACK_CHANGED:
807 		{
808 			int32 index;
809 			if (msg->FindInt32("index", &index) == B_OK) {
810 				int32 i = 0;
811 				while (BMenuItem* item = fAudioTrackMenu->ItemAt(i)) {
812 					item->SetMarked(i == index);
813 					i++;
814 				}
815 				_UpdateAudioChannelCount(index);
816 			}
817 			break;
818 		}
819 		case MSG_CONTROLLER_SUB_TITLE_TRACK_CHANGED:
820 		{
821 			int32 index;
822 			if (msg->FindInt32("index", &index) == B_OK) {
823 				int32 i = 0;
824 				while (BMenuItem* item = fSubTitleTrackMenu->ItemAt(i)) {
825 					BMessage* message = item->Message();
826 					if (message != NULL) {
827 						item->SetMarked((int32)message->what
828 							- M_SELECT_SUB_TITLE_TRACK == index);
829 					}
830 					i++;
831 				}
832 			}
833 			break;
834 		}
835 		case MSG_CONTROLLER_PLAYBACK_STATE_CHANGED:
836 		{
837 			uint32 state;
838 			if (msg->FindInt32("state", (int32*)&state) == B_OK)
839 				fControls->SetPlaybackState(state);
840 			break;
841 		}
842 		case MSG_CONTROLLER_POSITION_CHANGED:
843 		{
844 			float position;
845 			if (msg->FindFloat("position", &position) == B_OK) {
846 				fControls->SetPosition(position, fController->TimePosition(),
847 					fController->TimeDuration());
848 				fAllowWinding = true;
849 			}
850 			break;
851 		}
852 		case MSG_CONTROLLER_SEEK_HANDLED:
853 			break;
854 
855 		case MSG_CONTROLLER_VOLUME_CHANGED:
856 		{
857 			float volume;
858 			if (msg->FindFloat("volume", &volume) == B_OK)
859 				fControls->SetVolume(volume);
860 			fController->SaveState();
861 			break;
862 		}
863 		case MSG_CONTROLLER_MUTED_CHANGED:
864 		{
865 			bool muted;
866 			if (msg->FindBool("muted", &muted) == B_OK)
867 				fControls->SetMuted(muted);
868 			break;
869 		}
870 
871 		// menu item messages
872 		case M_FILE_OPEN:
873 		{
874 			BMessenger target(this);
875 			BMessage result(B_REFS_RECEIVED);
876 			BMessage appMessage(M_SHOW_OPEN_PANEL);
877 			appMessage.AddMessenger("target", target);
878 			appMessage.AddMessage("message", &result);
879 			appMessage.AddString("title", B_TRANSLATE("Open clips"));
880 			appMessage.AddString("label", B_TRANSLATE("Open"));
881 			be_app->PostMessage(&appMessage);
882 			break;
883 		}
884 
885 		case M_NETWORK_STREAM_OPEN:
886 		{
887 			BMessenger target(this);
888 			NetworkStreamWin* win = new NetworkStreamWin(target);
889 			win->Show();
890 			break;
891 		}
892 
893 		case M_EJECT_DEVICE:
894 			Eject();
895 			break;
896 
897 		case M_FILE_INFO:
898 			ShowFileInfo();
899 			break;
900 		case M_FILE_PLAYLIST:
901 			ShowPlaylistWindow();
902 			break;
903 		case M_FILE_CLOSE:
904 			PostMessage(B_QUIT_REQUESTED);
905 			break;
906 		case M_FILE_QUIT:
907 			be_app->PostMessage(B_QUIT_REQUESTED);
908 			break;
909 
910 		case M_TOGGLE_FULLSCREEN:
911 			_ToggleFullscreen();
912 			break;
913 
914 		case M_TOGGLE_ALWAYS_ON_TOP:
915 			_ToggleAlwaysOnTop();
916 			break;
917 
918 		case M_TOGGLE_NO_INTERFACE:
919 			_ToggleNoInterface();
920 			break;
921 
922 		case M_VIEW_SIZE:
923 		{
924 			int32 size;
925 			if (msg->FindInt32("size", &size) == B_OK) {
926 				if (!fHasVideo)
927 					break;
928 				if (fIsFullscreen)
929 					_ToggleFullscreen();
930 				_ResizeWindow(size);
931 			}
932 			break;
933 		}
934 
935 /*
936 		case B_ACQUIRE_OVERLAY_LOCK:
937 			printf("B_ACQUIRE_OVERLAY_LOCK\n");
938 			fVideoView->OverlayLockAcquire();
939 			break;
940 
941 		case B_RELEASE_OVERLAY_LOCK:
942 			printf("B_RELEASE_OVERLAY_LOCK\n");
943 			fVideoView->OverlayLockRelease();
944 			break;
945 */
946 		case B_MOUSE_WHEEL_CHANGED:
947 		{
948 			float dx = msg->FindFloat("be:wheel_delta_x");
949 			float dy = msg->FindFloat("be:wheel_delta_y");
950 			bool inv = modifiers() & B_COMMAND_KEY;
951 			if (dx > 0.1)
952 				PostMessage(inv ? M_VOLUME_DOWN : M_SKIP_PREV);
953 			if (dx < -0.1)
954 				PostMessage(inv ? M_VOLUME_UP : M_SKIP_NEXT);
955 			if (dy > 0.1)
956 				PostMessage(inv ? M_SKIP_PREV : M_VOLUME_DOWN);
957 			if (dy < -0.1)
958 				PostMessage(inv ? M_SKIP_NEXT : M_VOLUME_UP);
959 			break;
960 		}
961 
962 		case M_SKIP_NEXT:
963 			fControls->SkipForward();
964 			break;
965 
966 		case M_SKIP_PREV:
967 			fControls->SkipBackward();
968 			break;
969 
970 		case M_WIND:
971 		{
972 			bigtime_t howMuch;
973 			int64 frames;
974 			if (msg->FindInt64("how much", &howMuch) != B_OK
975 				|| msg->FindInt64("frames", &frames) != B_OK) {
976 				break;
977 			}
978 
979 			_Wind(howMuch, frames);
980 			break;
981 		}
982 
983 		case M_VOLUME_UP:
984 			fController->VolumeUp();
985 			break;
986 
987 		case M_VOLUME_DOWN:
988 			fController->VolumeDown();
989 			break;
990 
991 		case M_ASPECT_SAME_AS_SOURCE:
992 			if (fHasVideo) {
993 				int width;
994 				int height;
995 				int widthAspect;
996 				int heightAspect;
997 				fController->GetSize(&width, &height,
998 					&widthAspect, &heightAspect);
999 				VideoFormatChange(width, height, widthAspect, heightAspect);
1000 			}
1001 			break;
1002 
1003 		case M_ASPECT_NO_DISTORTION:
1004 			if (fHasVideo) {
1005 				int width;
1006 				int height;
1007 				fController->GetSize(&width, &height);
1008 				VideoFormatChange(width, height, width, height);
1009 			}
1010 			break;
1011 
1012 		case M_ASPECT_4_3:
1013 			VideoAspectChange(4, 3);
1014 			break;
1015 
1016 		case M_ASPECT_16_9: // 1.77 : 1
1017 			VideoAspectChange(16, 9);
1018 			break;
1019 
1020 		case M_ASPECT_83_50: // 1.66 : 1
1021 			VideoAspectChange(83, 50);
1022 			break;
1023 
1024 		case M_ASPECT_7_4: // 1.75 : 1
1025 			VideoAspectChange(7, 4);
1026 			break;
1027 
1028 		case M_ASPECT_37_20: // 1.85 : 1
1029 			VideoAspectChange(37, 20);
1030 			break;
1031 
1032 		case M_ASPECT_47_20: // 2.35 : 1
1033 			VideoAspectChange(47, 20);
1034 			break;
1035 
1036 		case M_SET_PLAYLIST_POSITION:
1037 		{
1038 			BAutolock _(fPlaylist);
1039 
1040 			int32 index;
1041 			if (msg->FindInt32("index", &index) == B_OK)
1042 				fPlaylist->SetCurrentItemIndex(index);
1043 			break;
1044 		}
1045 
1046 		case MSG_OBJECT_CHANGED:
1047 			// received from fGlobalSettingsListener
1048 			// TODO: find out which object, if we ever watch more than
1049 			// the global settings instance...
1050 			_AdoptGlobalSettings();
1051 			break;
1052 
1053 		case M_SLIDE_CONTROLS:
1054 		{
1055 			float offset;
1056 			if (msg->FindFloat("offset", &offset) == B_OK) {
1057 				fControls->MoveBy(0, offset);
1058 				fVideoView->SetSubTitleMaxBottom(fControls->Frame().top - 1);
1059 				UpdateIfNeeded();
1060 				snooze(15000);
1061 			}
1062 			break;
1063 		}
1064 		case M_FINISH_SLIDING_CONTROLS:
1065 		{
1066 			float offset;
1067 			bool show;
1068 			if (msg->FindFloat("offset", &offset) == B_OK
1069 				&& msg->FindBool("show", &show) == B_OK) {
1070 				if (show) {
1071 					fControls->MoveTo(fControls->Frame().left, offset);
1072 					fVideoView->SetSubTitleMaxBottom(offset - 1);
1073 				} else {
1074 					fVideoView->SetSubTitleMaxBottom(
1075 						fVideoView->Bounds().bottom);
1076 					fControls->RemoveSelf();
1077 					fControls->MoveTo(fVideoView->Frame().left,
1078 						fVideoView->Frame().bottom + 1);
1079 					fBackground->AddChild(fControls);
1080 					fControls->SetSymbolScale(1.0f);
1081 					while (!fControls->IsHidden())
1082 						fControls->Hide();
1083 				}
1084 			}
1085 			break;
1086 		}
1087 		case M_HIDE_FULL_SCREEN_CONTROLS:
1088 			if (fIsFullscreen) {
1089 				BPoint videoViewWhere;
1090 				if (msg->FindPoint("where", &videoViewWhere) == B_OK) {
1091 					if (msg->FindBool("force")
1092 						|| !fControls->Frame().Contains(videoViewWhere)) {
1093 						_ShowFullscreenControls(false);
1094 						// hide the mouse cursor until the user moves it
1095 						be_app->ObscureCursor();
1096 					}
1097 				}
1098 			}
1099 			break;
1100 
1101 		case M_SET_RATING:
1102 		{
1103 			int32 rating;
1104 			if (msg->FindInt32("rating", &rating) == B_OK)
1105 				_SetRating(rating);
1106 			break;
1107 		}
1108 
1109 		default:
1110 			if (msg->what >= M_SELECT_AUDIO_TRACK
1111 				&& msg->what <= M_SELECT_AUDIO_TRACK_END) {
1112 				fController->SelectAudioTrack(msg->what - M_SELECT_AUDIO_TRACK);
1113 				break;
1114 			}
1115 			if (msg->what >= M_SELECT_VIDEO_TRACK
1116 				&& msg->what <= M_SELECT_VIDEO_TRACK_END) {
1117 				fController->SelectVideoTrack(msg->what - M_SELECT_VIDEO_TRACK);
1118 				break;
1119 			}
1120 			if ((int32)msg->what >= M_SELECT_SUB_TITLE_TRACK - 1
1121 				&& msg->what <= M_SELECT_SUB_TITLE_TRACK_END) {
1122 				fController->SelectSubTitleTrack((int32)msg->what
1123 					- M_SELECT_SUB_TITLE_TRACK);
1124 				break;
1125 			}
1126 			// let BWindow handle the rest
1127 			BWindow::MessageReceived(msg);
1128 	}
1129 }
1130 
1131 
1132 void
1133 MainWin::WindowActivated(bool active)
1134 {
1135 	fController->PlayerActivated(active);
1136 }
1137 
1138 
1139 bool
1140 MainWin::QuitRequested()
1141 {
1142 	fController->SaveState();
1143 	BMessage message(M_PLAYER_QUIT);
1144 	GetQuitMessage(&message);
1145 	be_app->PostMessage(&message);
1146 	return true;
1147 }
1148 
1149 
1150 void
1151 MainWin::MenusBeginning()
1152 {
1153 	_SetupVideoAspectItems(fVideoAspectMenu);
1154 }
1155 
1156 
1157 // #pragma mark -
1158 
1159 
1160 void
1161 MainWin::OpenPlaylist(const BMessage* playlistArchive)
1162 {
1163 	if (playlistArchive == NULL)
1164 		return;
1165 
1166 	BAutolock _(this);
1167 	BAutolock playlistLocker(fPlaylist);
1168 
1169 	if (fPlaylist->Unarchive(playlistArchive) != B_OK)
1170 		return;
1171 
1172 	int32 currentIndex;
1173 	if (playlistArchive->FindInt32("index", &currentIndex) != B_OK)
1174 		currentIndex = 0;
1175 	fPlaylist->SetCurrentItemIndex(currentIndex);
1176 
1177 	playlistLocker.Unlock();
1178 
1179 	if (currentIndex != -1) {
1180 		// Restore the current play position only if we have something to play
1181 		playlistArchive->FindInt64("position", (int64*)&fInitialSeekPosition);
1182 	}
1183 
1184 	if (IsHidden())
1185 		Show();
1186 }
1187 
1188 
1189 void
1190 MainWin::OpenPlaylistItem(const PlaylistItemRef& item)
1191 {
1192 	status_t ret = fController->SetToAsync(item);
1193 	if (ret != B_OK) {
1194 		fprintf(stderr, "MainWin::OpenPlaylistItem() - Failed to send message "
1195 			"to Controller.\n");
1196 		BString message = B_TRANSLATE("%app% encountered an internal error. "
1197 			"The file could not be opened.");
1198 		message.ReplaceFirst("%app%", kApplicationName);
1199 		BAlert* alert = new BAlert(kApplicationName, message.String(),
1200 			B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT);
1201 		alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
1202 		alert->Go();
1203 		_PlaylistItemOpened(item, ret);
1204 	} else {
1205 		BString string;
1206 		string.SetToFormat(B_TRANSLATE("Opening '%s'."), item->Name().String());
1207 		fControls->SetDisabledString(string.String());
1208 	}
1209 }
1210 
1211 
1212 static int
1213 FindCdPlayerDevice(const char* directory)
1214 {
1215 	BDirectory dir;
1216 	dir.SetTo(directory);
1217 	if (dir.InitCheck() != B_NO_ERROR)
1218 		return false;
1219 	dir.Rewind();
1220 	BEntry entry;
1221 	while (dir.GetNextEntry(&entry) >= 0) {
1222 		BPath path;
1223 		if (entry.GetPath(&path) != B_NO_ERROR)
1224 			continue;
1225 		const char* name = path.Path();
1226 		entry_ref e;
1227 		if (entry.GetRef(&e) != B_NO_ERROR)
1228 			continue;
1229 		if (entry.IsDirectory()) {
1230 			if (strcmp(e.name, "floppy") == 0)
1231 				continue; // ignore floppy
1232 			int deviceFD = FindCdPlayerDevice(name);
1233 			if (deviceFD >= 0)
1234 				return deviceFD;
1235 		} else {
1236 			if (strcmp(e.name, "raw") != 0)
1237 				continue;
1238 			int deviceFD = open(name, O_RDONLY);
1239 			if (deviceFD < 0)
1240 				continue;
1241 			device_geometry geometry;
1242 			if (ioctl(deviceFD, B_GET_GEOMETRY, &geometry, sizeof(geometry)) >= 0
1243 				&& geometry.device_type == B_CD)
1244 				return deviceFD;
1245 			close(deviceFD);
1246 		}
1247 	}
1248 	return B_ERROR;
1249 }
1250 
1251 
1252 void
1253 MainWin::Eject()
1254 {
1255 	status_t mediaStatus = B_DEV_NO_MEDIA;
1256 	// find the cd player device
1257 	fDevice = FindCdPlayerDevice("/dev/disk");
1258 	// get the status first
1259 	ioctl(fDevice, B_GET_MEDIA_STATUS, &mediaStatus, sizeof(mediaStatus));
1260 	// if door open, load the media, else eject the cd
1261 	status_t result = ioctl(fDevice,
1262 		mediaStatus == B_DEV_DOOR_OPEN ? B_LOAD_MEDIA : B_EJECT_DEVICE);
1263 	if (result != B_NO_ERROR)
1264 		printf("Error ejecting device");
1265 }
1266 
1267 
1268 void
1269 MainWin::ShowFileInfo()
1270 {
1271 	if (!fInfoWin)
1272 		fInfoWin = new InfoWin(Frame().LeftTop(), fController);
1273 
1274 	if (fInfoWin->Lock()) {
1275 		if (fInfoWin->IsHidden())
1276 			fInfoWin->Show();
1277 		else
1278 			fInfoWin->Activate();
1279 		fInfoWin->Unlock();
1280 	}
1281 }
1282 
1283 
1284 void
1285 MainWin::ShowPlaylistWindow()
1286 {
1287 	if (fPlaylistWindow->Lock()) {
1288 		// make sure the window shows on the same workspace as ourself
1289 		uint32 workspaces = Workspaces();
1290 		if (fPlaylistWindow->Workspaces() != workspaces)
1291 			fPlaylistWindow->SetWorkspaces(workspaces);
1292 
1293 		// show or activate
1294 		if (fPlaylistWindow->IsHidden())
1295 			fPlaylistWindow->Show();
1296 		else
1297 			fPlaylistWindow->Activate();
1298 
1299 		fPlaylistWindow->Unlock();
1300 	}
1301 }
1302 
1303 
1304 void
1305 MainWin::VideoAspectChange(int forcedWidth, int forcedHeight, float widthScale)
1306 {
1307 	// Force specific source size and pixel width scale.
1308 	if (fHasVideo) {
1309 		int width;
1310 		int height;
1311 		fController->GetSize(&width, &height);
1312 		VideoFormatChange(forcedWidth, forcedHeight,
1313 			lround(width * widthScale), height);
1314 	}
1315 }
1316 
1317 
1318 void
1319 MainWin::VideoAspectChange(float widthScale)
1320 {
1321 	// Called when video aspect ratio changes and the original
1322 	// width/height should be restored too, display aspect is not known,
1323 	// only pixel width scale.
1324 	if (fHasVideo) {
1325 		int width;
1326 		int height;
1327 		fController->GetSize(&width, &height);
1328 		VideoFormatChange(width, height, lround(width * widthScale), height);
1329 	}
1330 }
1331 
1332 
1333 void
1334 MainWin::VideoAspectChange(int widthAspect, int heightAspect)
1335 {
1336 	// Called when video aspect ratio changes and the original
1337 	// width/height should be restored too.
1338 	if (fHasVideo) {
1339 		int width;
1340 		int height;
1341 		fController->GetSize(&width, &height);
1342 		VideoFormatChange(width, height, widthAspect, heightAspect);
1343 	}
1344 }
1345 
1346 
1347 void
1348 MainWin::VideoFormatChange(int width, int height, int widthAspect,
1349 	int heightAspect)
1350 {
1351 	// Called when video format or aspect ratio changes.
1352 
1353 	printf("VideoFormatChange enter: width %d, height %d, "
1354 		"aspect ratio: %d:%d\n", width, height, widthAspect, heightAspect);
1355 
1356 	// remember current view scale
1357 	int percent = _CurrentVideoSizeInPercent();
1358 
1359  	fSourceWidth = width;
1360  	fSourceHeight = height;
1361  	fWidthAspect = widthAspect;
1362  	fHeightAspect = heightAspect;
1363 
1364 	if (percent == 100)
1365 		_ResizeWindow(100);
1366 	else
1367 	 	FrameResized(Bounds().Width(), Bounds().Height());
1368 
1369 	printf("VideoFormatChange leave\n");
1370 }
1371 
1372 
1373 void
1374 MainWin::GetQuitMessage(BMessage* message)
1375 {
1376 	message->AddPointer("instance", this);
1377 	message->AddRect("window frame", Frame());
1378 	message->AddBool("audio only", !fHasVideo);
1379 	message->AddInt64("creation time", fCreationTime);
1380 
1381 	if (!fHasVideo && fHasAudio) {
1382 		// store playlist, current index and position if this is audio
1383 		BMessage playlistArchive;
1384 
1385 		BAutolock controllerLocker(fController);
1386 		playlistArchive.AddInt64("position", fController->TimePosition());
1387 		controllerLocker.Unlock();
1388 
1389 		if (!fPlaylist)
1390 			return;
1391 
1392 		BAutolock playlistLocker(fPlaylist);
1393 		if (fPlaylist->Archive(&playlistArchive) != B_OK
1394 			|| playlistArchive.AddInt32("index",
1395 				fPlaylist->CurrentItemIndex()) != B_OK
1396 			|| message->AddMessage("playlist", &playlistArchive) != B_OK) {
1397 			fprintf(stderr, "Failed to store current playlist.\n");
1398 		}
1399 	}
1400 }
1401 
1402 
1403 BHandler*
1404 MainWin::ResolveSpecifier(BMessage* message, int32 index, BMessage* specifier,
1405 	int32 what, const char* property)
1406 {
1407 	BPropertyInfo propertyInfo(sPropertyInfo);
1408 	if (propertyInfo.FindMatch(message, index, specifier, what, property)
1409 			!= B_ERROR)
1410 		return this;
1411 
1412 	return BWindow::ResolveSpecifier(message, index, specifier, what, property);
1413 }
1414 
1415 
1416 status_t
1417 MainWin::GetSupportedSuites(BMessage* data)
1418 {
1419 	if (data == NULL)
1420 		return B_BAD_VALUE;
1421 
1422 	status_t status = data->AddString("suites", "suite/vnd.Haiku-MediaPlayer");
1423 	if (status != B_OK)
1424 		return status;
1425 
1426 	BPropertyInfo propertyInfo(sPropertyInfo);
1427 	status = data->AddFlat("messages", &propertyInfo);
1428 	if (status != B_OK)
1429 		return status;
1430 
1431 	return BWindow::GetSupportedSuites(data);
1432 }
1433 
1434 
1435 // #pragma mark -
1436 
1437 
1438 void
1439 MainWin::_RefsReceived(BMessage* message)
1440 {
1441 	// the playlist is replaced by dropped files
1442 	// or the dropped files are appended to the end
1443 	// of the existing playlist if <shift> is pressed
1444 	bool append = false;
1445 	if (message->FindBool("append to playlist", &append) != B_OK)
1446 		append = modifiers() & B_SHIFT_KEY;
1447 
1448 	BAutolock _(fPlaylist);
1449 	int32 appendIndex = append ? APPEND_INDEX_APPEND_LAST
1450 		: APPEND_INDEX_REPLACE_PLAYLIST;
1451 	message->AddInt32("append_index", appendIndex);
1452 
1453 	// forward the message to the playlist window,
1454 	// so that undo/redo is used for modifying the playlist
1455 	fPlaylistWindow->PostMessage(message);
1456 
1457 	if (message->FindRect("window frame", &fNoVideoFrame) != B_OK)
1458 		fNoVideoFrame = BRect();
1459 }
1460 
1461 
1462 void
1463 MainWin::_PlaylistItemOpened(const PlaylistItemRef& item, status_t result)
1464 {
1465 	if (result != B_OK) {
1466 		BAutolock _(fPlaylist);
1467 
1468 		item->SetPlaybackFailed();
1469 		bool allItemsFailed = true;
1470 		int32 count = fPlaylist->CountItems();
1471 		for (int32 i = 0; i < count; i++) {
1472 			if (!fPlaylist->ItemAtFast(i)->PlaybackFailed()) {
1473 				allItemsFailed = false;
1474 				break;
1475 			}
1476 		}
1477 
1478 		if (allItemsFailed) {
1479 			// Display error if all files failed to play.
1480 			BString message(B_TRANSLATE(
1481 				"The file '%filename' could not be opened.\n\n"));;
1482 			message.ReplaceAll("%filename", item->Name());
1483 
1484 			if (result == B_MEDIA_NO_HANDLER) {
1485 				// give a more detailed message for the most likely of all
1486 				// errors
1487 				message << B_TRANSLATE(
1488 					"There is no decoder installed to handle the "
1489 					"file format, or the decoder has trouble with the "
1490 					"specific version of the format.");
1491 			} else {
1492 				message << B_TRANSLATE("Error: ") << strerror(result);
1493 			}
1494 			BAlert* alert = new BAlert("error", message.String(),
1495 				B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT);
1496 			alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
1497 			alert->Go();
1498 			fControls->SetDisabledString(kDisabledSeekMessage);
1499 		} else {
1500 			// Just go to the next file and don't bother user (yet)
1501 			fPlaylist->SetCurrentItemIndex(fPlaylist->CurrentItemIndex() + 1);
1502 		}
1503 
1504 		fHasFile = false;
1505 		fHasVideo = false;
1506 		fHasAudio = false;
1507 		SetTitle(kApplicationName);
1508 	} else {
1509 		fHasFile = true;
1510 		fHasVideo = fController->VideoTrackCount() != 0;
1511 		fHasAudio = fController->AudioTrackCount() != 0;
1512 		SetTitle(item->Name().String());
1513 
1514 		if (fInitialSeekPosition < 0) {
1515 			fInitialSeekPosition
1516 				= fController->TimeDuration() + fInitialSeekPosition;
1517 		}
1518 		fController->SetTimePosition(fInitialSeekPosition);
1519 		fInitialSeekPosition = 0;
1520 
1521 		if (fPlaylist->CountItems() == 1)
1522 			fController->RestoreState();
1523 	}
1524 	_SetupWindow();
1525 
1526 	if (result == B_OK)
1527 		_UpdatePlaylistItemFile();
1528 }
1529 
1530 
1531 void
1532 MainWin::_SetupWindow()
1533 {
1534 //	printf("MainWin::_SetupWindow\n");
1535 	// Populate the track menus
1536 	_SetupTrackMenus(fAudioTrackMenu, fVideoTrackMenu, fSubTitleTrackMenu);
1537 	_UpdateAudioChannelCount(fController->CurrentAudioTrack());
1538 
1539 	fVideoMenu->SetEnabled(fHasVideo);
1540 	fAudioMenu->SetEnabled(fHasAudio);
1541 	int previousSourceWidth = fSourceWidth;
1542 	int previousSourceHeight = fSourceHeight;
1543 	int previousWidthAspect = fWidthAspect;
1544 	int previousHeightAspect = fHeightAspect;
1545 	if (fHasVideo) {
1546 		fController->GetSize(&fSourceWidth, &fSourceHeight,
1547 			&fWidthAspect, &fHeightAspect);
1548 	} else {
1549 		fSourceWidth = 0;
1550 		fSourceHeight = 0;
1551 		fWidthAspect = 1;
1552 		fHeightAspect = 1;
1553 	}
1554 	_UpdateControlsEnabledStatus();
1555 
1556 	// Adopt the size and window layout if necessary
1557 	if (previousSourceWidth != fSourceWidth
1558 		|| previousSourceHeight != fSourceHeight
1559 		|| previousWidthAspect != fWidthAspect
1560 		|| previousHeightAspect != fHeightAspect) {
1561 
1562 		_SetWindowSizeLimits();
1563 
1564 		if (!fIsFullscreen) {
1565 			// Resize to 100% but stay on screen
1566 			_ResizeWindow(100, !fHasVideo, true);
1567 		} else {
1568 			// Make sure we relayout the video view when in full screen mode
1569 			FrameResized(Frame().Width(), Frame().Height());
1570 		}
1571 	}
1572 
1573 	_ShowIfNeeded();
1574 
1575 	fVideoView->MakeFocus();
1576 }
1577 
1578 
1579 void
1580 MainWin::_CreateMenu()
1581 {
1582 	fFileMenu = new BMenu(kApplicationName);
1583 	fPlaylistMenu = new BMenu(B_TRANSLATE("Playlist" B_UTF8_ELLIPSIS));
1584 	fAudioMenu = new BMenu(B_TRANSLATE("Audio"));
1585 	fVideoMenu = new BMenu(B_TRANSLATE("Video"));
1586 	fVideoAspectMenu = new BMenu(B_TRANSLATE("Aspect ratio"));
1587 	fAudioTrackMenu = new BMenu(B_TRANSLATE_CONTEXT("Track",
1588 		"Audio Track Menu"));
1589 	fVideoTrackMenu = new BMenu(B_TRANSLATE_CONTEXT("Track",
1590 		"Video Track Menu"));
1591 	fSubTitleTrackMenu = new BMenu(B_TRANSLATE("Subtitles"));
1592 	fAttributesMenu = new BMenu(B_TRANSLATE("Attributes"));
1593 
1594 	fMenuBar->AddItem(fFileMenu);
1595 	fMenuBar->AddItem(fAudioMenu);
1596 	fMenuBar->AddItem(fVideoMenu);
1597 	fMenuBar->AddItem(fAttributesMenu);
1598 
1599 	BMenuItem* item = new BMenuItem(B_TRANSLATE("New player" B_UTF8_ELLIPSIS),
1600 		new BMessage(M_NEW_PLAYER), 'N');
1601 	fFileMenu->AddItem(item);
1602 	item->SetTarget(be_app);
1603 
1604 	// Add recent files to "Open File" entry as sub-menu.
1605 	BRecentFilesList recentFiles(10, false, NULL, kAppSig);
1606 	item = new BMenuItem(recentFiles.NewFileListMenu(
1607 		B_TRANSLATE("Open file" B_UTF8_ELLIPSIS), NULL, NULL, this, 10, true,
1608 		NULL, kAppSig), new BMessage(M_FILE_OPEN));
1609 	item->SetShortcut('O', 0);
1610 	fFileMenu->AddItem(item);
1611 
1612 	item = new BMenuItem(B_TRANSLATE("Open network stream"),
1613 		new BMessage(M_NETWORK_STREAM_OPEN));
1614 	fFileMenu->AddItem(item);
1615 
1616 	item = new BMenuItem(B_TRANSLATE("Eject Device"),
1617 		new BMessage(M_EJECT_DEVICE));
1618 	fFileMenu->AddItem(item);
1619 
1620 	fFileMenu->AddSeparatorItem();
1621 
1622 	fFileMenu->AddItem(new BMenuItem(B_TRANSLATE("File info" B_UTF8_ELLIPSIS),
1623 		new BMessage(M_FILE_INFO), 'I'));
1624 	fFileMenu->AddItem(fPlaylistMenu);
1625 	fPlaylistMenu->Superitem()->SetShortcut('P', B_COMMAND_KEY);
1626 	fPlaylistMenu->Superitem()->SetMessage(new BMessage(M_FILE_PLAYLIST));
1627 
1628 	fFileMenu->AddSeparatorItem();
1629 
1630 	fNoInterfaceMenuItem = new BMenuItem(B_TRANSLATE("Hide interface"),
1631 		new BMessage(M_TOGGLE_NO_INTERFACE), 'H');
1632 	fFileMenu->AddItem(fNoInterfaceMenuItem);
1633 	fFileMenu->AddItem(new BMenuItem(B_TRANSLATE("Always on top"),
1634 		new BMessage(M_TOGGLE_ALWAYS_ON_TOP), 'A'));
1635 
1636 	item = new BMenuItem(B_TRANSLATE("Settings" B_UTF8_ELLIPSIS),
1637 		new BMessage(M_SETTINGS), ',');
1638 	fFileMenu->AddItem(item);
1639 	item->SetTarget(be_app);
1640 
1641 	fFileMenu->AddSeparatorItem();
1642 
1643 	fFileMenu->AddItem(new BMenuItem(B_TRANSLATE("Close"),
1644 		new BMessage(M_FILE_CLOSE), 'W'));
1645 	fFileMenu->AddItem(new BMenuItem(B_TRANSLATE("Quit"),
1646 		new BMessage(M_FILE_QUIT), 'Q'));
1647 
1648 	fPlaylistMenu->SetRadioMode(true);
1649 
1650 	fAudioMenu->AddItem(fAudioTrackMenu);
1651 
1652 	fVideoMenu->AddItem(fVideoTrackMenu);
1653 	fVideoMenu->AddItem(fSubTitleTrackMenu);
1654 	fVideoMenu->AddSeparatorItem();
1655 	BMessage* resizeMessage = new BMessage(M_VIEW_SIZE);
1656 	resizeMessage->AddInt32("size", 50);
1657 	fVideoMenu->AddItem(new BMenuItem(
1658 		B_TRANSLATE("50% scale"), resizeMessage, '0'));
1659 
1660 	resizeMessage = new BMessage(M_VIEW_SIZE);
1661 	resizeMessage->AddInt32("size", 100);
1662 	fVideoMenu->AddItem(new BMenuItem(
1663 		B_TRANSLATE("100% scale"), resizeMessage, '1'));
1664 
1665 	resizeMessage = new BMessage(M_VIEW_SIZE);
1666 	resizeMessage->AddInt32("size", 200);
1667 	fVideoMenu->AddItem(new BMenuItem(
1668 		B_TRANSLATE("200% scale"), resizeMessage, '2'));
1669 
1670 	resizeMessage = new BMessage(M_VIEW_SIZE);
1671 	resizeMessage->AddInt32("size", 300);
1672 	fVideoMenu->AddItem(new BMenuItem(
1673 		B_TRANSLATE("300% scale"), resizeMessage, '3'));
1674 
1675 	resizeMessage = new BMessage(M_VIEW_SIZE);
1676 	resizeMessage->AddInt32("size", 400);
1677 	fVideoMenu->AddItem(new BMenuItem(
1678 		B_TRANSLATE("400% scale"), resizeMessage, '4'));
1679 
1680 	fVideoMenu->AddSeparatorItem();
1681 
1682 	fVideoMenu->AddItem(new BMenuItem(B_TRANSLATE("Full screen"),
1683 		new BMessage(M_TOGGLE_FULLSCREEN), B_ENTER));
1684 
1685 	fVideoMenu->AddSeparatorItem();
1686 
1687 	_SetupVideoAspectItems(fVideoAspectMenu);
1688 	fVideoMenu->AddItem(fVideoAspectMenu);
1689 
1690 	fRatingMenu = new BMenu(B_TRANSLATE("Rating"));
1691 	fAttributesMenu->AddItem(fRatingMenu);
1692 	for (int32 i = 1; i <= 10; i++) {
1693 		char label[16];
1694 		snprintf(label, sizeof(label), "%" B_PRId32, i);
1695 		BMessage* setRatingMsg = new BMessage(M_SET_RATING);
1696 		setRatingMsg->AddInt32("rating", i);
1697 		fRatingMenu->AddItem(new BMenuItem(label, setRatingMsg));
1698 	}
1699 }
1700 
1701 
1702 void
1703 MainWin::_SetupVideoAspectItems(BMenu* menu)
1704 {
1705 	BMenuItem* item;
1706 	while ((item = menu->RemoveItem((int32)0)) != NULL)
1707 		delete item;
1708 
1709 	int width;
1710 	int height;
1711 	int widthAspect;
1712 	int heightAspect;
1713 	fController->GetSize(&width, &height, &widthAspect, &heightAspect);
1714 		// We don't care if there is a video track at all. In that
1715 		// case we should end up not marking any item.
1716 
1717 	// NOTE: The item marking may end up marking for example both
1718 	// "Stream Settings" and "16 : 9" if the stream settings happen to
1719 	// be "16 : 9".
1720 
1721 	menu->AddItem(item = new BMenuItem(B_TRANSLATE("Stream settings"),
1722 		new BMessage(M_ASPECT_SAME_AS_SOURCE), '1', B_SHIFT_KEY));
1723 	item->SetMarked(widthAspect == fWidthAspect
1724 		&& heightAspect == fHeightAspect);
1725 
1726 	menu->AddItem(item = new BMenuItem(B_TRANSLATE("No aspect correction"),
1727 		new BMessage(M_ASPECT_NO_DISTORTION), '0', B_SHIFT_KEY));
1728 	item->SetMarked(width == fWidthAspect && height == fHeightAspect);
1729 
1730 	menu->AddSeparatorItem();
1731 
1732 	menu->AddItem(item = new BMenuItem("4 : 3",
1733 		new BMessage(M_ASPECT_4_3), 2, B_SHIFT_KEY));
1734 	item->SetMarked(fWidthAspect == 4 && fHeightAspect == 3);
1735 	menu->AddItem(item = new BMenuItem("16 : 9",
1736 		new BMessage(M_ASPECT_16_9), 3, B_SHIFT_KEY));
1737 	item->SetMarked(fWidthAspect == 16 && fHeightAspect == 9);
1738 
1739 	menu->AddSeparatorItem();
1740 
1741 	menu->AddItem(item = new BMenuItem("1.66 : 1",
1742 		new BMessage(M_ASPECT_83_50)));
1743 	item->SetMarked(fWidthAspect == 83 && fHeightAspect == 50);
1744 	menu->AddItem(item = new BMenuItem("1.75 : 1",
1745 		new BMessage(M_ASPECT_7_4)));
1746 	item->SetMarked(fWidthAspect == 7 && fHeightAspect == 4);
1747 	menu->AddItem(item = new BMenuItem(B_TRANSLATE("1.85 : 1 (American)"),
1748 		new BMessage(M_ASPECT_37_20)));
1749 	item->SetMarked(fWidthAspect == 37 && fHeightAspect == 20);
1750 	menu->AddItem(item = new BMenuItem(B_TRANSLATE("2.35 : 1 (Cinemascope)"),
1751 		new BMessage(M_ASPECT_47_20)));
1752 	item->SetMarked(fWidthAspect == 47 && fHeightAspect == 20);
1753 }
1754 
1755 
1756 void
1757 MainWin::_SetupTrackMenus(BMenu* audioTrackMenu, BMenu* videoTrackMenu,
1758 	BMenu* subTitleTrackMenu)
1759 {
1760 	audioTrackMenu->RemoveItems(0, audioTrackMenu->CountItems(), true);
1761 	videoTrackMenu->RemoveItems(0, videoTrackMenu->CountItems(), true);
1762 	subTitleTrackMenu->RemoveItems(0, subTitleTrackMenu->CountItems(), true);
1763 
1764 	char s[100];
1765 
1766 	int count = fController->AudioTrackCount();
1767 	int current = fController->CurrentAudioTrack();
1768 	for (int i = 0; i < count; i++) {
1769 		BMessage metaData;
1770 		const char* languageString = NULL;
1771 		if (fController->GetAudioMetaData(i, &metaData) == B_OK)
1772 			metaData.FindString("language", &languageString);
1773 		if (languageString != NULL) {
1774 			BLanguage language(languageString);
1775 			BString languageName;
1776 			if (language.GetName(languageName) == B_OK)
1777 				languageString = languageName.String();
1778 			snprintf(s, sizeof(s), "%s", languageString);
1779 		} else
1780 			snprintf(s, sizeof(s), B_TRANSLATE("Track %d"), i + 1);
1781 		BMenuItem* item = new BMenuItem(s,
1782 			new BMessage(M_SELECT_AUDIO_TRACK + i));
1783 		item->SetMarked(i == current);
1784 		audioTrackMenu->AddItem(item);
1785 	}
1786 	if (count == 0) {
1787 		audioTrackMenu->AddItem(new BMenuItem(B_TRANSLATE_CONTEXT("none",
1788 			"Audio track menu"), new BMessage(M_DUMMY)));
1789 		audioTrackMenu->ItemAt(0)->SetMarked(true);
1790 	}
1791 	audioTrackMenu->SetEnabled(count > 1);
1792 
1793 	count = fController->VideoTrackCount();
1794 	current = fController->CurrentVideoTrack();
1795 	for (int i = 0; i < count; i++) {
1796 		snprintf(s, sizeof(s), B_TRANSLATE("Track %d"), i + 1);
1797 		BMenuItem* item = new BMenuItem(s,
1798 			new BMessage(M_SELECT_VIDEO_TRACK + i));
1799 		item->SetMarked(i == current);
1800 		videoTrackMenu->AddItem(item);
1801 	}
1802 	if (count == 0) {
1803 		videoTrackMenu->AddItem(new BMenuItem(B_TRANSLATE("none"),
1804 			new BMessage(M_DUMMY)));
1805 		videoTrackMenu->ItemAt(0)->SetMarked(true);
1806 	}
1807 	videoTrackMenu->SetEnabled(count > 1);
1808 
1809 	count = fController->SubTitleTrackCount();
1810 	if (count > 0) {
1811 		current = fController->CurrentSubTitleTrack();
1812 		BMenuItem* item = new BMenuItem(
1813 			B_TRANSLATE_CONTEXT("Off", "Subtitles menu"),
1814 			new BMessage(M_SELECT_SUB_TITLE_TRACK - 1));
1815 		subTitleTrackMenu->AddItem(item);
1816 		item->SetMarked(current == -1);
1817 
1818 		subTitleTrackMenu->AddSeparatorItem();
1819 
1820 		for (int i = 0; i < count; i++) {
1821 			const char* name = fController->SubTitleTrackName(i);
1822 			if (name != NULL)
1823 				snprintf(s, sizeof(s), "%s", name);
1824 			else
1825 				snprintf(s, sizeof(s), B_TRANSLATE("Track %d"), i + 1);
1826 			item = new BMenuItem(s,
1827 				new BMessage(M_SELECT_SUB_TITLE_TRACK + i));
1828 			item->SetMarked(i == current);
1829 			subTitleTrackMenu->AddItem(item);
1830 		}
1831 	} else {
1832 		subTitleTrackMenu->AddItem(new BMenuItem(
1833 			B_TRANSLATE_CONTEXT("none", "Subtitles menu"),
1834 			new BMessage(M_DUMMY)));
1835 		subTitleTrackMenu->ItemAt(0)->SetMarked(true);
1836 	}
1837 	subTitleTrackMenu->SetEnabled(count > 0);
1838 }
1839 
1840 
1841 void
1842 MainWin::_UpdateAudioChannelCount(int32 audioTrackIndex)
1843 {
1844 	fControls->SetAudioChannelCount(fController->AudioTrackChannelCount());
1845 }
1846 
1847 
1848 void
1849 MainWin::_GetMinimumWindowSize(int& width, int& height) const
1850 {
1851 	width = MIN_WIDTH;
1852 	height = 0;
1853 	if (!fNoInterface) {
1854 		width = max_c(width, fMenuBarWidth);
1855 		width = max_c(width, fControlsWidth);
1856 		height = fMenuBarHeight + fControlsHeight;
1857 	}
1858 }
1859 
1860 
1861 void
1862 MainWin::_GetUnscaledVideoSize(int& videoWidth, int& videoHeight) const
1863 {
1864 	if (fWidthAspect != 0 && fHeightAspect != 0) {
1865 		videoWidth = fSourceHeight * fWidthAspect / fHeightAspect;
1866 		videoHeight = fSourceWidth * fHeightAspect / fWidthAspect;
1867 		// Use the scaling which produces an enlarged view.
1868 		if (videoWidth > fSourceWidth) {
1869 			// Enlarge width
1870 			videoHeight = fSourceHeight;
1871 		} else {
1872 			// Enlarge height
1873 			videoWidth = fSourceWidth;
1874 		}
1875 	} else {
1876 		videoWidth = fSourceWidth;
1877 		videoHeight = fSourceHeight;
1878 	}
1879 }
1880 
1881 
1882 void
1883 MainWin::_SetWindowSizeLimits()
1884 {
1885 	int minWidth;
1886 	int minHeight;
1887 	_GetMinimumWindowSize(minWidth, minHeight);
1888 	SetSizeLimits(minWidth - 1, 32000, minHeight - 1,
1889 		fHasVideo ? 32000 : minHeight - 1);
1890 }
1891 
1892 
1893 int
1894 MainWin::_CurrentVideoSizeInPercent() const
1895 {
1896 	if (!fHasVideo)
1897 		return 0;
1898 
1899 	int videoWidth;
1900 	int videoHeight;
1901 	_GetUnscaledVideoSize(videoWidth, videoHeight);
1902 
1903 	int viewWidth = fVideoView->Bounds().IntegerWidth() + 1;
1904 	int viewHeight = fVideoView->Bounds().IntegerHeight() + 1;
1905 
1906 	int widthPercent = viewWidth * 100 / videoWidth;
1907 	int heightPercent = viewHeight * 100 / videoHeight;
1908 
1909 	if (widthPercent > heightPercent)
1910 		return widthPercent;
1911 	return heightPercent;
1912 }
1913 
1914 
1915 void
1916 MainWin::_ZoomVideoView(int percentDiff)
1917 {
1918 	if (!fHasVideo)
1919 		return;
1920 
1921 	int percent = _CurrentVideoSizeInPercent();
1922 	int newSize = percent * (100 + percentDiff) / 100;
1923 
1924 	if (newSize < 25)
1925 		newSize = 25;
1926 	if (newSize > 400)
1927 		newSize = 400;
1928 	if (newSize != percent) {
1929 		BMessage message(M_VIEW_SIZE);
1930 		message.AddInt32("size", newSize);
1931 		PostMessage(&message);
1932 	}
1933 }
1934 
1935 
1936 void
1937 MainWin::_ResizeWindow(int percent, bool useNoVideoWidth, bool stayOnScreen)
1938 {
1939 	// Get required window size
1940 	int videoWidth;
1941 	int videoHeight;
1942 	_GetUnscaledVideoSize(videoWidth, videoHeight);
1943 
1944 	videoWidth = (videoWidth * percent) / 100;
1945 	videoHeight = (videoHeight * percent) / 100;
1946 
1947 	// Calculate and set the minimum window size
1948 	int width;
1949 	int height;
1950 	_GetMinimumWindowSize(width, height);
1951 
1952 	width = max_c(width, videoWidth) - 1;
1953 	if (useNoVideoWidth)
1954 		width = max_c(width, fNoVideoWidth);
1955 	height = height + videoHeight - 1;
1956 
1957 	if (stayOnScreen) {
1958 		BRect screenFrame(BScreen(this).Frame());
1959 		BRect frame(Frame());
1960 		BRect decoratorFrame(DecoratorFrame());
1961 
1962 		// Shrink the screen frame by the window border size
1963 		screenFrame.top += frame.top - decoratorFrame.top;
1964 		screenFrame.left += frame.left - decoratorFrame.left;
1965 		screenFrame.right += frame.right - decoratorFrame.right;
1966 		screenFrame.bottom += frame.bottom - decoratorFrame.bottom;
1967 
1968 		// Update frame to what the new size would be
1969 		frame.right = frame.left + width;
1970 		frame.bottom = frame.top + height;
1971 
1972 		if (!screenFrame.Contains(frame)) {
1973 			// Resize the window so it doesn't extend outside the current
1974 			// screen frame.
1975 			// We don't use BWindow::MoveOnScreen() in order to resize the
1976 			// window while keeping the same aspect ratio.
1977 			if (frame.Width() > screenFrame.Width()
1978 				|| frame.Height() > screenFrame.Height()) {
1979 				// too large
1980 				int widthDiff
1981 					= frame.IntegerWidth() - screenFrame.IntegerWidth();
1982 				int heightDiff
1983 					= frame.IntegerHeight() - screenFrame.IntegerHeight();
1984 
1985 				float shrinkScale;
1986 				if (widthDiff > heightDiff)
1987 					shrinkScale = (float)(width - widthDiff) / width;
1988 				else
1989 					shrinkScale = (float)(height - heightDiff) / height;
1990 
1991 				// Resize width/height and center window
1992 				width = lround(width * shrinkScale);
1993 				height = lround(height * shrinkScale);
1994 				MoveTo((screenFrame.left + screenFrame.right - width) / 2,
1995 					(screenFrame.top + screenFrame.bottom - height) / 2);
1996 			} else {
1997 				// just off-screen on one or more sides
1998 				int offsetX = 0;
1999 				int offsetY = 0;
2000 				if (frame.left < screenFrame.left)
2001 					offsetX = (int)(screenFrame.left - frame.left);
2002 				else if (frame.right > screenFrame.right)
2003 					offsetX = (int)(screenFrame.right - frame.right);
2004 				if (frame.top < screenFrame.top)
2005 					offsetY = (int)(screenFrame.top - frame.top);
2006 				else if (frame.bottom > screenFrame.bottom)
2007 					offsetY = (int)(screenFrame.bottom - frame.bottom);
2008 				MoveBy(offsetX, offsetY);
2009 			}
2010 		}
2011 	}
2012 
2013 	ResizeTo(width, height);
2014 }
2015 
2016 
2017 void
2018 MainWin::_ResizeVideoView(int x, int y, int width, int height)
2019 {
2020 	// Keep aspect ratio, place video view inside
2021 	// the background area (may create black bars).
2022 	int videoWidth;
2023 	int videoHeight;
2024 	_GetUnscaledVideoSize(videoWidth, videoHeight);
2025 	float scaledWidth  = videoWidth;
2026 	float scaledHeight = videoHeight;
2027 	float factor = min_c(width / scaledWidth, height / scaledHeight);
2028 	int renderWidth = lround(scaledWidth * factor);
2029 	int renderHeight = lround(scaledHeight * factor);
2030 	if (renderWidth > width)
2031 		renderWidth = width;
2032 	if (renderHeight > height)
2033 		renderHeight = height;
2034 
2035 	int xOffset = (width - renderWidth) / 2;
2036 	int yOffset = (height - renderHeight) / 2;
2037 
2038 	fVideoView->MoveTo(x, y);
2039 	fVideoView->ResizeTo(width - 1, height - 1);
2040 
2041 	BRect videoFrame(xOffset, yOffset,
2042 		xOffset + renderWidth - 1, yOffset + renderHeight - 1);
2043 
2044 	fVideoView->SetVideoFrame(videoFrame);
2045 	fVideoView->SetSubTitleMaxBottom(height - 1);
2046 }
2047 
2048 
2049 // #pragma mark -
2050 
2051 
2052 void
2053 MainWin::_MouseDown(BMessage* msg, BView* originalHandler)
2054 {
2055 	uint32 buttons = msg->FindInt32("buttons");
2056 
2057 	// On Zeta, only "screen_where" is reliable, "where" and "be:view_where"
2058 	// seem to be broken
2059 	BPoint screenWhere;
2060 	if (msg->FindPoint("screen_where", &screenWhere) != B_OK) {
2061 		// TODO: remove
2062 		// Workaround for BeOS R5, it has no "screen_where"
2063 		if (!originalHandler || msg->FindPoint("where", &screenWhere) < B_OK)
2064 			return;
2065 		originalHandler->ConvertToScreen(&screenWhere);
2066 	}
2067 
2068 	// double click handling
2069 
2070 	if (msg->FindInt32("clicks") % 2 == 0) {
2071 		BRect rect(screenWhere.x - 1, screenWhere.y - 1, screenWhere.x + 1,
2072 			screenWhere.y + 1);
2073 		if (rect.Contains(fMouseDownMousePos)) {
2074 			if (buttons == B_PRIMARY_MOUSE_BUTTON)
2075 				PostMessage(M_TOGGLE_FULLSCREEN);
2076 			else if (buttons == B_SECONDARY_MOUSE_BUTTON)
2077 				PostMessage(M_TOGGLE_NO_INTERFACE);
2078 
2079 			return;
2080 		}
2081 	}
2082 
2083 	fMouseDownMousePos = screenWhere;
2084 	fMouseDownWindowPos = Frame().LeftTop();
2085 
2086 	if (buttons == B_PRIMARY_MOUSE_BUTTON && !fIsFullscreen) {
2087 		// start mouse tracking
2088 		fVideoView->SetMouseEventMask(B_POINTER_EVENTS | B_NO_POINTER_HISTORY
2089 			/* | B_LOCK_WINDOW_FOCUS */);
2090 		fMouseDownTracking = true;
2091 	}
2092 
2093 	// pop up a context menu if right mouse button is down
2094 
2095 	if ((buttons & B_SECONDARY_MOUSE_BUTTON) != 0)
2096 		_ShowContextMenu(screenWhere);
2097 }
2098 
2099 
2100 void
2101 MainWin::_MouseMoved(BMessage* msg, BView* originalHandler)
2102 {
2103 //	msg->PrintToStream();
2104 
2105 	BPoint mousePos;
2106 	uint32 buttons = msg->FindInt32("buttons");
2107 	// On Zeta, only "screen_where" is reliable, "where"
2108 	// and "be:view_where" seem to be broken
2109 	if (msg->FindPoint("screen_where", &mousePos) != B_OK) {
2110 		// TODO: remove
2111 		// Workaround for BeOS R5, it has no "screen_where"
2112 		if (!originalHandler || msg->FindPoint("where", &mousePos) < B_OK)
2113 			return;
2114 		originalHandler->ConvertToScreen(&mousePos);
2115 	}
2116 
2117 	if (buttons == B_PRIMARY_MOUSE_BUTTON && fMouseDownTracking
2118 		&& !fIsFullscreen) {
2119 //		printf("screen where: %.0f, %.0f => ", mousePos.x, mousePos.y);
2120 		float delta_x = mousePos.x - fMouseDownMousePos.x;
2121 		float delta_y = mousePos.y - fMouseDownMousePos.y;
2122 		float x = fMouseDownWindowPos.x + delta_x;
2123 		float y = fMouseDownWindowPos.y + delta_y;
2124 //		printf("move window to %.0f, %.0f\n", x, y);
2125 		MoveTo(x, y);
2126 	}
2127 
2128 	bigtime_t eventTime;
2129 	if (msg->FindInt64("when", &eventTime) != B_OK)
2130 		eventTime = system_time();
2131 
2132 	if (buttons == 0 && fIsFullscreen) {
2133 		BPoint moveDelta = mousePos - fLastMousePos;
2134 		float moveDeltaDist
2135 			= sqrtf(moveDelta.x * moveDelta.x + moveDelta.y * moveDelta.y);
2136 		if (eventTime - fLastMouseMovedTime < 200000)
2137 			fMouseMoveDist += moveDeltaDist;
2138 		else
2139 			fMouseMoveDist = moveDeltaDist;
2140 		if (fMouseMoveDist > 5)
2141 			_ShowFullscreenControls(true);
2142 	}
2143 
2144 	fLastMousePos = mousePos;
2145 	fLastMouseMovedTime =eventTime;
2146 }
2147 
2148 
2149 void
2150 MainWin::_MouseUp(BMessage* msg)
2151 {
2152 	fMouseDownTracking = false;
2153 }
2154 
2155 
2156 void
2157 MainWin::_ShowContextMenu(const BPoint& screenPoint)
2158 {
2159 	printf("Show context menu\n");
2160 	BPopUpMenu* menu = new BPopUpMenu("context menu", false, false);
2161 	BMenuItem* item;
2162 	menu->AddItem(item = new BMenuItem(B_TRANSLATE("Full screen"),
2163 		new BMessage(M_TOGGLE_FULLSCREEN), B_ENTER));
2164 	item->SetMarked(fIsFullscreen);
2165 	item->SetEnabled(fHasVideo);
2166 
2167 	menu->AddItem(item = new BMenuItem(B_TRANSLATE("Hide interface"),
2168 		new BMessage(M_TOGGLE_NO_INTERFACE), 'H'));
2169 	item->SetMarked(fNoInterface);
2170 	item->SetEnabled(fHasVideo && !fIsFullscreen);
2171 
2172 	menu->AddItem(item = new BMenuItem(B_TRANSLATE("Always on top"),
2173 		new BMessage(M_TOGGLE_ALWAYS_ON_TOP), 'A'));
2174 	item->SetMarked(fAlwaysOnTop);
2175 	item->SetEnabled(fHasVideo);
2176 
2177 	BMenu* aspectSubMenu = new BMenu(B_TRANSLATE("Aspect ratio"));
2178 	_SetupVideoAspectItems(aspectSubMenu);
2179 	aspectSubMenu->SetTargetForItems(this);
2180 	menu->AddItem(item = new BMenuItem(aspectSubMenu));
2181 	item->SetEnabled(fHasVideo);
2182 
2183 	menu->AddSeparatorItem();
2184 
2185 	// Add track selector menus
2186 	BMenu* audioTrackMenu = new BMenu(B_TRANSLATE("Audio track"));
2187 	BMenu* videoTrackMenu = new BMenu(B_TRANSLATE("Video track"));
2188 	BMenu* subTitleTrackMenu = new BMenu(B_TRANSLATE("Subtitles"));
2189 	_SetupTrackMenus(audioTrackMenu, videoTrackMenu, subTitleTrackMenu);
2190 
2191 	audioTrackMenu->SetTargetForItems(this);
2192 	videoTrackMenu->SetTargetForItems(this);
2193 	subTitleTrackMenu->SetTargetForItems(this);
2194 
2195 	menu->AddItem(item = new BMenuItem(audioTrackMenu));
2196 	item->SetEnabled(fHasAudio);
2197 
2198 	menu->AddItem(item = new BMenuItem(videoTrackMenu));
2199 	item->SetEnabled(fHasVideo);
2200 
2201 	menu->AddItem(item = new BMenuItem(subTitleTrackMenu));
2202 	item->SetEnabled(fHasVideo);
2203 
2204 	menu->AddSeparatorItem();
2205 	menu->AddItem(new BMenuItem(B_TRANSLATE("Quit"), new BMessage(M_FILE_QUIT), 'Q'));
2206 
2207 	menu->SetTargetForItems(this);
2208 	BRect rect(screenPoint.x - 5, screenPoint.y - 5, screenPoint.x + 5,
2209 		screenPoint.y + 5);
2210 	menu->Go(screenPoint, true, true, rect, true);
2211 }
2212 
2213 
2214 /*!	Trap keys that are about to be send to background or renderer view.
2215 	Return true if it shouldn't be passed to the view.
2216 */
2217 bool
2218 MainWin::_KeyDown(BMessage* msg)
2219 {
2220 	uint32 key = msg->FindInt32("key");
2221 	uint32 rawChar = msg->FindInt32("raw_char");
2222 	uint32 modifier = msg->FindInt32("modifiers");
2223 
2224 //	printf("key 0x%lx, rawChar 0x%lx, modifiers 0x%lx\n", key, rawChar,
2225 //		modifier);
2226 
2227 	// ignore the system modifier namespace
2228 	if ((modifier & (B_CONTROL_KEY | B_COMMAND_KEY))
2229 			== (B_CONTROL_KEY | B_COMMAND_KEY))
2230 		return false;
2231 
2232 	switch (rawChar) {
2233 		case B_SPACE:
2234 			fController->TogglePlaying();
2235 			return true;
2236 
2237 		case 'm':
2238 			fController->ToggleMute();
2239 			return true;
2240 
2241 		case B_ESCAPE:
2242 			if (!fIsFullscreen)
2243 				break;
2244 
2245 			PostMessage(M_TOGGLE_FULLSCREEN);
2246 			return true;
2247 
2248 		case B_ENTER:		// Enter / Return
2249 			if ((modifier & B_COMMAND_KEY) != 0) {
2250 				PostMessage(M_TOGGLE_FULLSCREEN);
2251 				return true;
2252 			}
2253 			break;
2254 
2255 		case B_TAB:
2256 		case 'f':
2257 			if ((modifier & (B_COMMAND_KEY | B_CONTROL_KEY | B_OPTION_KEY
2258 					| B_MENU_KEY)) == 0) {
2259 				PostMessage(M_TOGGLE_FULLSCREEN);
2260 				return true;
2261 			}
2262 			break;
2263 
2264 		case B_UP_ARROW:
2265 			if ((modifier & B_COMMAND_KEY) != 0)
2266 				PostMessage(M_SKIP_NEXT);
2267 			else
2268 				PostMessage(M_VOLUME_UP);
2269 			return true;
2270 
2271 		case B_DOWN_ARROW:
2272 			if ((modifier & B_COMMAND_KEY) != 0)
2273 				PostMessage(M_SKIP_PREV);
2274 			else
2275 				PostMessage(M_VOLUME_DOWN);
2276 			return true;
2277 
2278 		case B_RIGHT_ARROW:
2279 			if ((modifier & B_COMMAND_KEY) != 0)
2280 				PostMessage(M_SKIP_NEXT);
2281 			else if (fAllowWinding) {
2282 				BMessage windMessage(M_WIND);
2283 				if ((modifier & B_SHIFT_KEY) != 0) {
2284 					windMessage.AddInt64("how much", 30000000LL);
2285 					windMessage.AddInt64("frames", 5);
2286 				} else {
2287 					windMessage.AddInt64("how much", 5000000LL);
2288 					windMessage.AddInt64("frames", 1);
2289 				}
2290 				PostMessage(&windMessage);
2291 			}
2292 			return true;
2293 
2294 		case B_LEFT_ARROW:
2295 			if ((modifier & B_COMMAND_KEY) != 0)
2296 				PostMessage(M_SKIP_PREV);
2297 			else if (fAllowWinding) {
2298 				BMessage windMessage(M_WIND);
2299 				if ((modifier & B_SHIFT_KEY) != 0) {
2300 					windMessage.AddInt64("how much", -30000000LL);
2301 					windMessage.AddInt64("frames", -5);
2302 				} else {
2303 					windMessage.AddInt64("how much", -5000000LL);
2304 					windMessage.AddInt64("frames", -1);
2305 				}
2306 				PostMessage(&windMessage);
2307 			}
2308 			return true;
2309 
2310 		case B_PAGE_UP:
2311 			PostMessage(M_SKIP_NEXT);
2312 			return true;
2313 
2314 		case B_PAGE_DOWN:
2315 			PostMessage(M_SKIP_PREV);
2316 			return true;
2317 
2318 		case '+':
2319 			if ((modifier & B_COMMAND_KEY) == 0) {
2320 				_ZoomVideoView(10);
2321 				return true;
2322 			}
2323 			break;
2324 
2325 		case '-':
2326 			if ((modifier & B_COMMAND_KEY) == 0) {
2327 				_ZoomVideoView(-10);
2328 				return true;
2329 			}
2330 			break;
2331 
2332 		case B_DELETE:
2333 		case 'd': 			// d for delete
2334 		case 't':			// t for Trash
2335 			if ((modifiers() & B_COMMAND_KEY) != 0) {
2336 				BAutolock _(fPlaylist);
2337 				BMessage removeMessage(M_PLAYLIST_MOVE_TO_TRASH);
2338 				removeMessage.AddInt32("playlist index",
2339 					fPlaylist->CurrentItemIndex());
2340 				fPlaylistWindow->PostMessage(&removeMessage);
2341 				return true;
2342 			}
2343 			break;
2344 	}
2345 
2346 	switch (key) {
2347 		case 0x3a:  		// numeric keypad +
2348 			if ((modifier & B_COMMAND_KEY) == 0) {
2349 				_ZoomVideoView(10);
2350 				return true;
2351 			}
2352 			break;
2353 
2354 		case 0x25:  		// numeric keypad -
2355 			if ((modifier & B_COMMAND_KEY) == 0) {
2356 				_ZoomVideoView(-10);
2357 				return true;
2358 			}
2359 			break;
2360 
2361 		case 0x38:			// numeric keypad up arrow
2362 			PostMessage(M_VOLUME_UP);
2363 			return true;
2364 
2365 		case 0x59:			// numeric keypad down arrow
2366 			PostMessage(M_VOLUME_DOWN);
2367 			return true;
2368 
2369 		case 0x39:			// numeric keypad page up
2370 		case 0x4a:			// numeric keypad right arrow
2371 			PostMessage(M_SKIP_NEXT);
2372 			return true;
2373 
2374 		case 0x5a:			// numeric keypad page down
2375 		case 0x48:			// numeric keypad left arrow
2376 			PostMessage(M_SKIP_PREV);
2377 			return true;
2378 
2379 		// Playback controls along the bottom of the keyboard:
2380 		// Z X C (V) B  for US International
2381 		case 0x4c:
2382 			PostMessage(M_SKIP_PREV);
2383 			return true;
2384 		case 0x4d:
2385 			fController->TogglePlaying();
2386 			return true;
2387 		case 0x4e:
2388 			fController->Pause();
2389 			return true;
2390 		case 0x4f:
2391 			fController->Stop();
2392 			return true;
2393 		case 0x50:
2394 			PostMessage(M_SKIP_NEXT);
2395 			return true;
2396 	}
2397 
2398 	return false;
2399 }
2400 
2401 
2402 // #pragma mark -
2403 
2404 
2405 void
2406 MainWin::_ToggleFullscreen()
2407 {
2408 	printf("_ToggleFullscreen enter\n");
2409 
2410 	if (!fHasVideo) {
2411 		printf("_ToggleFullscreen - ignoring, as we don't have a video\n");
2412 		return;
2413 	}
2414 
2415 	fIsFullscreen = !fIsFullscreen;
2416 
2417 	if (fIsFullscreen) {
2418 		// switch to fullscreen
2419 
2420 		fSavedFrame = Frame();
2421 		printf("saving current frame: %d %d %d %d\n", int(fSavedFrame.left),
2422 			int(fSavedFrame.top), int(fSavedFrame.right),
2423 			int(fSavedFrame.bottom));
2424 		BScreen screen(this);
2425 		BRect rect(screen.Frame());
2426 
2427 		Hide();
2428 		MoveTo(rect.left, rect.top);
2429 		ResizeTo(rect.Width(), rect.Height());
2430 		Show();
2431 
2432 	} else {
2433 		// switch back from full screen mode
2434 		_ShowFullscreenControls(false, false);
2435 
2436 		Hide();
2437 		MoveTo(fSavedFrame.left, fSavedFrame.top);
2438 		ResizeTo(fSavedFrame.Width(), fSavedFrame.Height());
2439 		Show();
2440 	}
2441 
2442 	fVideoView->SetFullscreen(fIsFullscreen);
2443 
2444 	_MarkItem(fFileMenu, M_TOGGLE_FULLSCREEN, fIsFullscreen);
2445 
2446 	printf("_ToggleFullscreen leave\n");
2447 }
2448 
2449 void
2450 MainWin::_ToggleAlwaysOnTop()
2451 {
2452 	fAlwaysOnTop = !fAlwaysOnTop;
2453 	SetFeel(fAlwaysOnTop ? B_FLOATING_ALL_WINDOW_FEEL : B_NORMAL_WINDOW_FEEL);
2454 
2455 	_MarkItem(fFileMenu, M_TOGGLE_ALWAYS_ON_TOP, fAlwaysOnTop);
2456 }
2457 
2458 
2459 void
2460 MainWin::_ToggleNoInterface()
2461 {
2462 	printf("_ToggleNoInterface enter\n");
2463 
2464 	if (fIsFullscreen || !fHasVideo) {
2465 		// Fullscreen playback is always without interface and
2466 		// audio playback is always with interface. So we ignore these
2467 		// two states here.
2468 		printf("_ToggleNoControls leave, doing nothing, we are fullscreen\n");
2469 		return;
2470 	}
2471 
2472 	fNoInterface = !fNoInterface;
2473 	_SetWindowSizeLimits();
2474 
2475 	if (fNoInterface) {
2476 		MoveBy(0, fMenuBarHeight);
2477 		ResizeBy(0, -(fControlsHeight + fMenuBarHeight));
2478 		SetLook(B_BORDERED_WINDOW_LOOK);
2479 	} else {
2480 		MoveBy(0, -fMenuBarHeight);
2481 		ResizeBy(0, fControlsHeight + fMenuBarHeight);
2482 		SetLook(B_TITLED_WINDOW_LOOK);
2483 	}
2484 
2485 	_MarkItem(fFileMenu, M_TOGGLE_NO_INTERFACE, fNoInterface);
2486 
2487 	printf("_ToggleNoInterface leave\n");
2488 }
2489 
2490 
2491 void
2492 MainWin::_ShowIfNeeded()
2493 {
2494 	// Only proceed if the window is already running
2495 	if (find_thread(NULL) != Thread())
2496 		return;
2497 
2498 	if (!fHasVideo && fNoVideoFrame.IsValid()) {
2499 		MoveTo(fNoVideoFrame.LeftTop());
2500 		ResizeTo(fNoVideoFrame.Width(), fNoVideoFrame.Height());
2501 		MoveOnScreen(B_MOVE_IF_PARTIALLY_OFFSCREEN);
2502 	} else if (fHasVideo && IsHidden())
2503 		CenterOnScreen();
2504 
2505 	fNoVideoFrame = BRect();
2506 
2507 	if (IsHidden()) {
2508 		Show();
2509 		UpdateIfNeeded();
2510 	}
2511 }
2512 
2513 
2514 void
2515 MainWin::_ShowFullscreenControls(bool show, bool animate)
2516 {
2517 	if (fShowsFullscreenControls == show)
2518 		return;
2519 
2520 	fShowsFullscreenControls = show;
2521 	fVideoView->SetFullscreenControlsVisible(show);
2522 
2523 	if (show) {
2524 		fControls->RemoveSelf();
2525 		fControls->MoveTo(fVideoView->Bounds().left,
2526 			fVideoView->Bounds().bottom + 1);
2527 		fVideoView->AddChild(fControls);
2528 		if (fScaleFullscreenControls)
2529 			fControls->SetSymbolScale(1.5f);
2530 
2531 		while (fControls->IsHidden())
2532 			fControls->Show();
2533 	}
2534 
2535 	if (animate) {
2536 		// Slide the controls into view. We need to do this with
2537 		// messages, otherwise we block the video playback for the
2538 		// time of the animation.
2539 		const float kAnimationOffsets[] = { 0.05, 0.2, 0.5, 0.2, 0.05 };
2540 		const int32 steps = sizeof(kAnimationOffsets) / sizeof(float);
2541 		float height = fControls->Bounds().Height();
2542 		float moveDist = show ? -height : height;
2543 		float originalY = fControls->Frame().top;
2544 		for (int32 i = 0; i < steps; i++) {
2545 			BMessage message(M_SLIDE_CONTROLS);
2546 			message.AddFloat("offset",
2547 				floorf(moveDist * kAnimationOffsets[i]));
2548 			PostMessage(&message, this);
2549 		}
2550 		BMessage finalMessage(M_FINISH_SLIDING_CONTROLS);
2551 		finalMessage.AddFloat("offset", originalY + moveDist);
2552 		finalMessage.AddBool("show", show);
2553 		PostMessage(&finalMessage, this);
2554 	} else if (!show) {
2555 		fControls->RemoveSelf();
2556 		fControls->MoveTo(fVideoView->Frame().left,
2557 			fVideoView->Frame().bottom + 1);
2558 		fBackground->AddChild(fControls);
2559 		fControls->SetSymbolScale(1.0f);
2560 
2561 		while (!fControls->IsHidden())
2562 			fControls->Hide();
2563 	}
2564 }
2565 
2566 
2567 // #pragma mark -
2568 
2569 
2570 void
2571 MainWin::_Wind(bigtime_t howMuch, int64 frames)
2572 {
2573 	if (!fAllowWinding || !fController->Lock())
2574 		return;
2575 
2576 	if (frames != 0 && fHasVideo && !fController->IsPlaying()) {
2577 		int64 newFrame = fController->CurrentFrame() + frames;
2578 		fController->SetFramePosition(newFrame);
2579 	} else {
2580 		bigtime_t seekTime = fController->TimePosition() + howMuch;
2581 		if (seekTime < 0) {
2582 			fInitialSeekPosition = seekTime;
2583 			PostMessage(M_SKIP_PREV);
2584 		} else if (seekTime > fController->TimeDuration()) {
2585 			fInitialSeekPosition = 0;
2586 			PostMessage(M_SKIP_NEXT);
2587 		} else
2588 			fController->SetTimePosition(seekTime);
2589 	}
2590 
2591 	fController->Unlock();
2592 	fAllowWinding = false;
2593 }
2594 
2595 
2596 // #pragma mark -
2597 
2598 
2599 void
2600 MainWin::_UpdatePlaylistItemFile()
2601 {
2602 	BAutolock locker(fPlaylist);
2603 	const FilePlaylistItem* item
2604 		= dynamic_cast<const FilePlaylistItem*>(fController->Item());
2605 	if (item == NULL)
2606 		return;
2607 
2608 	if (!fHasVideo && !fHasAudio)
2609 		return;
2610 
2611 	BNode node(&item->Ref());
2612 	if (node.InitCheck())
2613 		return;
2614 
2615 	locker.Unlock();
2616 
2617 	// Set some standard attributes of the currently played file.
2618 	// This should only be a temporary solution.
2619 
2620 	// Write duration
2621 	const char* kDurationAttrName = "Media:Length";
2622 	attr_info info;
2623 	status_t status = node.GetAttrInfo(kDurationAttrName, &info);
2624 	if (status != B_OK || info.size == 0) {
2625 		bigtime_t duration = fController->TimeDuration();
2626 		// TODO: Tracker does not seem to care about endian for scalar types
2627 		node.WriteAttr(kDurationAttrName, B_INT64_TYPE, 0, &duration,
2628 			sizeof(int64));
2629 	}
2630 
2631 	// Write audio bitrate
2632 	if (fHasAudio) {
2633 		status = node.GetAttrInfo("Audio:Bitrate", &info);
2634 		if (status != B_OK || info.size == 0) {
2635 			media_format format;
2636 			if (fController->GetEncodedAudioFormat(&format) == B_OK
2637 				&& format.type == B_MEDIA_ENCODED_AUDIO) {
2638 				int32 bitrate = (int32)(format.u.encoded_audio.bit_rate
2639 					/ 1000);
2640 				char text[256];
2641 				snprintf(text, sizeof(text), "%" B_PRId32 " kbit", bitrate);
2642 				node.WriteAttr("Audio:Bitrate", B_STRING_TYPE, 0, text,
2643 					strlen(text) + 1);
2644 			}
2645 		}
2646 	}
2647 
2648 	// Write video bitrate
2649 	if (fHasVideo) {
2650 		status = node.GetAttrInfo("Video:Bitrate", &info);
2651 		if (status != B_OK || info.size == 0) {
2652 			media_format format;
2653 			if (fController->GetEncodedVideoFormat(&format) == B_OK
2654 				&& format.type == B_MEDIA_ENCODED_VIDEO) {
2655 				int32 bitrate = (int32)(format.u.encoded_video.avg_bit_rate
2656 					/ 1000);
2657 				char text[256];
2658 				snprintf(text, sizeof(text), "%" B_PRId32 " kbit", bitrate);
2659 				node.WriteAttr("Video:Bitrate", B_STRING_TYPE, 0, text,
2660 					strlen(text) + 1);
2661 			}
2662 		}
2663 	}
2664 
2665 	_UpdateAttributesMenu(node);
2666 }
2667 
2668 
2669 void
2670 MainWin::_UpdateAttributesMenu(const BNode& node)
2671 {
2672 	int32 rating = -1;
2673 
2674 	attr_info info;
2675 	status_t status = node.GetAttrInfo(kRatingAttrName, &info);
2676 	if (status == B_OK && info.type == B_INT32_TYPE) {
2677 		// Node has the Rating attribute.
2678 		node.ReadAttr(kRatingAttrName, B_INT32_TYPE, 0, &rating,
2679 			sizeof(rating));
2680 	}
2681 
2682 	for (int32 i = 0; BMenuItem* item = fRatingMenu->ItemAt(i); i++)
2683 		item->SetMarked(i + 1 == rating);
2684 }
2685 
2686 
2687 void
2688 MainWin::_SetRating(int32 rating)
2689 {
2690 	BAutolock locker(fPlaylist);
2691 	const FilePlaylistItem* item
2692 		= dynamic_cast<const FilePlaylistItem*>(fController->Item());
2693 	if (item == NULL)
2694 		return;
2695 
2696 	BNode node(&item->Ref());
2697 	if (node.InitCheck())
2698 		return;
2699 
2700 	locker.Unlock();
2701 
2702 	node.WriteAttr(kRatingAttrName, B_INT32_TYPE, 0, &rating, sizeof(rating));
2703 
2704 	// TODO: The whole mechnism should work like this:
2705 	// * There is already an attribute API for PlaylistItem, flesh it out!
2706 	// * FilePlaylistItem node-monitors it's file somehow.
2707 	// * FilePlaylistItem keeps attributes in sync and sends notications.
2708 	// * MainWin updates the menu according to FilePlaylistItem notifications.
2709 	// * PlaylistWin shows columns with attribute and other info.
2710 	// * PlaylistWin updates also upon FilePlaylistItem notifications.
2711 	// * This keeps attributes in sync when another app changes them.
2712 
2713 	_UpdateAttributesMenu(node);
2714 }
2715 
2716 
2717 void
2718 MainWin::_UpdateControlsEnabledStatus()
2719 {
2720 	uint32 enabledButtons = 0;
2721 	if (fHasVideo || fHasAudio) {
2722 		enabledButtons |= PLAYBACK_ENABLED | SEEK_ENABLED
2723 			| SEEK_BACK_ENABLED | SEEK_FORWARD_ENABLED;
2724 	}
2725 	if (fHasAudio)
2726 		enabledButtons |= VOLUME_ENABLED;
2727 
2728 	BAutolock _(fPlaylist);
2729 	bool canSkipPrevious, canSkipNext;
2730 	fPlaylist->GetSkipInfo(&canSkipPrevious, &canSkipNext);
2731 	if (canSkipPrevious)
2732 		enabledButtons |= SKIP_BACK_ENABLED;
2733 	if (canSkipNext)
2734 		enabledButtons |= SKIP_FORWARD_ENABLED;
2735 
2736 	fControls->SetEnabled(enabledButtons);
2737 
2738 	fNoInterfaceMenuItem->SetEnabled(fHasVideo);
2739 	fAttributesMenu->SetEnabled(fHasAudio || fHasVideo);
2740 }
2741 
2742 
2743 void
2744 MainWin::_UpdatePlaylistMenu()
2745 {
2746 	if (!fPlaylist->Lock())
2747 		return;
2748 
2749 	fPlaylistMenu->RemoveItems(0, fPlaylistMenu->CountItems(), true);
2750 
2751 	int32 count = fPlaylist->CountItems();
2752 	for (int32 i = 0; i < count; i++) {
2753 		PlaylistItem* item = fPlaylist->ItemAtFast(i);
2754 		_AddPlaylistItem(item, i);
2755 	}
2756 	fPlaylistMenu->SetTargetForItems(this);
2757 
2758 	_MarkPlaylistItem(fPlaylist->CurrentItemIndex());
2759 
2760 	fPlaylist->Unlock();
2761 }
2762 
2763 
2764 void
2765 MainWin::_AddPlaylistItem(PlaylistItem* item, int32 index)
2766 {
2767 	BMessage* message = new BMessage(M_SET_PLAYLIST_POSITION);
2768 	message->AddInt32("index", index);
2769 	BMenuItem* menuItem = new BMenuItem(item->Name().String(), message);
2770 	fPlaylistMenu->AddItem(menuItem, index);
2771 }
2772 
2773 
2774 void
2775 MainWin::_RemovePlaylistItem(int32 index)
2776 {
2777 	delete fPlaylistMenu->RemoveItem(index);
2778 }
2779 
2780 
2781 void
2782 MainWin::_MarkPlaylistItem(int32 index)
2783 {
2784 	if (BMenuItem* item = fPlaylistMenu->ItemAt(index)) {
2785 		item->SetMarked(true);
2786 		// ... and in case the menu is currently on screen:
2787 		if (fPlaylistMenu->LockLooper()) {
2788 			fPlaylistMenu->Invalidate();
2789 			fPlaylistMenu->UnlockLooper();
2790 		}
2791 	}
2792 }
2793 
2794 
2795 void
2796 MainWin::_MarkItem(BMenu* menu, uint32 command, bool mark)
2797 {
2798 	if (BMenuItem* item = menu->FindItem(command))
2799 		item->SetMarked(mark);
2800 }
2801 
2802 
2803 void
2804 MainWin::_AdoptGlobalSettings()
2805 {
2806 	mpSettings settings;
2807 	Settings::Default()->Get(settings);
2808 
2809 	fCloseWhenDonePlayingMovie = settings.closeWhenDonePlayingMovie;
2810 	fCloseWhenDonePlayingSound = settings.closeWhenDonePlayingSound;
2811 	fLoopMovies = settings.loopMovie;
2812 	fLoopSounds = settings.loopSound;
2813 	fScaleFullscreenControls = settings.scaleFullscreenControls;
2814 }
2815