xref: /haiku/src/apps/mediaplayer/playlist/CopyPLItemsCommand.cpp (revision b9a5b9a6ee494261f2882bfc0ee9fde92282bef6)
1 /*
2  * Copyright 2007, Haiku. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Stephan Aßmus <superstippi@gmx.de>
7  */
8 
9 #include "CopyPLItemsCommand.h"
10 
11 #include <new>
12 #include <stdio.h>
13 
14 #include <Autolock.h>
15 
16 #include "Playlist.h"
17 
18 
19 using std::nothrow;
20 
21 
22 CopyPLItemsCommand::CopyPLItemsCommand(Playlist* playlist,
23 		 const int32* indices, int32 count, int32 toIndex)
24 	: Command()
25 	, fPlaylist(playlist)
26 	, fRefs(count > 0 ? new (nothrow) entry_ref[count] : NULL)
27 	, fToIndex(toIndex)
28 	, fCount(count)
29 {
30 	if (!indices || !fPlaylist || !fRefs) {
31 		// indicate a bad object state
32 		delete[] fRefs;
33 		fRefs = NULL;
34 		return;
35 	}
36 
37 	// init original entries and
38 	for (int32 i = 0; i < fCount; i++) {
39 		if (fPlaylist->GetRefAt(indices[i], &fRefs[i]) < B_OK) {
40 			delete[] fRefs;
41 			fRefs = NULL;
42 			return;
43 		}
44 	}
45 }
46 
47 
48 CopyPLItemsCommand::~CopyPLItemsCommand()
49 {
50 	delete[] fRefs;
51 }
52 
53 
54 status_t
55 CopyPLItemsCommand::InitCheck()
56 {
57 	if (!fPlaylist || !fRefs)
58 		return B_NO_INIT;
59 	return B_OK;
60 }
61 
62 
63 status_t
64 CopyPLItemsCommand::Perform()
65 {
66 	BAutolock _(fPlaylist);
67 
68 	status_t ret = B_OK;
69 
70 	// add refs to playlist at the insertion index
71 	int32 index = fToIndex;
72 	for (int32 i = 0; i < fCount; i++) {
73 		if (!fPlaylist->AddRef(fRefs[i], index++)) {
74 			ret = B_NO_MEMORY;
75 			break;
76 		}
77 	}
78 	if (ret < B_OK)
79 		return ret;
80 
81 	return B_OK;
82 }
83 
84 
85 status_t
86 CopyPLItemsCommand::Undo()
87 {
88 	BAutolock _(fPlaylist);
89 
90 	// remember currently playling ref in case we copy items over it
91 	entry_ref currentRef;
92 	bool adjustCurrentRef = fPlaylist->GetRefAt(fPlaylist->CurrentRefIndex(),
93 		&currentRef) == B_OK;
94 
95 	// remove refs from playlist
96 	int32 index = fToIndex;
97 	for (int32 i = 0; i < fCount; i++) {
98 		fPlaylist->RemoveRef(index++, false);
99 	}
100 
101 	// take care about currently played ref
102 	if (adjustCurrentRef)
103 		fPlaylist->SetCurrentRefIndex(fPlaylist->IndexOf(currentRef));
104 
105 	return B_OK;
106 }
107 
108 
109 void
110 CopyPLItemsCommand::GetName(BString& name)
111 {
112 	if (fCount > 1)
113 		name << "Copy Entries";
114 	else
115 		name << "Copy Entry";
116 }
117