xref: /haiku/src/apps/icon-o-matic/shape/commands/AddPathsCommand.cpp (revision 2c704682c473cd9e0f4b10d91c072f200e740cd8)
1 /*
2  * Copyright 2006, Haiku.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Stephan Aßmus <superstippi@gmx.de>
7  */
8 
9 #include "AddPathsCommand.h"
10 
11 #include <new>
12 #include <stdio.h>
13 #include <string.h>
14 
15 #include "PathContainer.h"
16 #include "VectorPath.h"
17 
18 using std::nothrow;
19 
20 // constructor
21 AddPathsCommand::AddPathsCommand(PathContainer* container,
22 								 VectorPath** const paths,
23 								 int32 count,
24 								 bool ownsPaths,
25 								 int32 index)
26 	: Command(),
27 	  fContainer(container),
28 	  fPaths(paths && count > 0 ? new (nothrow) VectorPath*[count] : NULL),
29 	  fCount(count),
30 	  fOwnsPaths(ownsPaths),
31 	  fIndex(index),
32 	  fPathsAdded(false)
33 {
34 	if (!fContainer || !fPaths)
35 		return;
36 
37 	memcpy(fPaths, paths, sizeof(VectorPath*) * fCount);
38 
39 	if (!fOwnsPaths) {
40 		// Add references to paths
41 		for (int32 i = 0; i < fCount; i++) {
42 			if (fPaths[i] != NULL)
43 				fPaths[i]->Acquire();
44 		}
45 	}
46 }
47 
48 // destructor
49 AddPathsCommand::~AddPathsCommand()
50 {
51 	if (!fPathsAdded && fPaths) {
52 		for (int32 i = 0; i < fCount; i++) {
53 			if (fPaths[i] != NULL)
54 				fPaths[i]->Release();
55 		}
56 	}
57 	delete[] fPaths;
58 }
59 
60 // InitCheck
61 status_t
62 AddPathsCommand::InitCheck()
63 {
64 	return fContainer && fPaths ? B_OK : B_NO_INIT;
65 }
66 
67 // Perform
68 status_t
69 AddPathsCommand::Perform()
70 {
71 	// add paths to container
72 	for (int32 i = 0; i < fCount; i++) {
73 		if (fPaths[i] && !fContainer->AddPath(fPaths[i], fIndex + i)) {
74 			// roll back
75 			for (int32 j = i - 1; j >= 0; j--)
76 				fContainer->RemovePath(fPaths[j]);
77 			return B_ERROR;
78 		}
79 	}
80 	fPathsAdded = true;
81 
82 	return B_OK;
83 }
84 
85 // Undo
86 status_t
87 AddPathsCommand::Undo()
88 {
89 	// remove paths from container
90 	for (int32 i = 0; i < fCount; i++) {
91 		fContainer->RemovePath(fPaths[i]);
92 	}
93 	fPathsAdded = false;
94 
95 	return B_OK;
96 }
97 
98 // GetName
99 void
100 AddPathsCommand::GetName(BString& name)
101 {
102 	if (fOwnsPaths) {
103 		if (fCount > 1)
104 			name << "Add Paths";
105 		else
106 			name << "Add Path";
107 	} else {
108 		if (fCount > 1)
109 			name << "Assign Paths";
110 		else
111 			name << "Assign Path";
112 	}
113 }
114