xref: /haiku/src/apps/icon-o-matic/shape/commands/AddPathsCommand.cpp (revision 21258e2674226d6aa732321b6f8494841895af5f)
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 <Catalog.h>
16 #include <Locale.h>
17 
18 #include "PathContainer.h"
19 #include "VectorPath.h"
20 
21 
22 #undef B_TRANSLATION_CONTEXT
23 #define B_TRANSLATION_CONTEXT "Icon-O-Matic-AddPathsCmd"
24 
25 
26 using std::nothrow;
27 
28 // constructor
29 AddPathsCommand::AddPathsCommand(PathContainer* container,
30 								 VectorPath** const paths,
31 								 int32 count,
32 								 bool ownsPaths,
33 								 int32 index)
34 	: Command(),
35 	  fContainer(container),
36 	  fPaths(paths && count > 0 ? new (nothrow) VectorPath*[count] : NULL),
37 	  fCount(count),
38 	  fOwnsPaths(ownsPaths),
39 	  fIndex(index),
40 	  fPathsAdded(false)
41 {
42 	if (!fContainer || !fPaths)
43 		return;
44 
45 	memcpy(fPaths, paths, sizeof(VectorPath*) * fCount);
46 
47 	if (!fOwnsPaths) {
48 		// Add references to paths
49 		for (int32 i = 0; i < fCount; i++) {
50 			if (fPaths[i] != NULL)
51 				fPaths[i]->AcquireReference();
52 		}
53 	}
54 }
55 
56 // destructor
57 AddPathsCommand::~AddPathsCommand()
58 {
59 	if (!fPathsAdded && fPaths) {
60 		for (int32 i = 0; i < fCount; i++) {
61 			if (fPaths[i] != NULL)
62 				fPaths[i]->ReleaseReference();
63 		}
64 	}
65 	delete[] fPaths;
66 }
67 
68 // InitCheck
69 status_t
70 AddPathsCommand::InitCheck()
71 {
72 	return fContainer && fPaths ? B_OK : B_NO_INIT;
73 }
74 
75 // Perform
76 status_t
77 AddPathsCommand::Perform()
78 {
79 	// add paths to container
80 	for (int32 i = 0; i < fCount; i++) {
81 		if (fPaths[i] && !fContainer->AddPath(fPaths[i], fIndex + i)) {
82 			// roll back
83 			for (int32 j = i - 1; j >= 0; j--)
84 				fContainer->RemovePath(fPaths[j]);
85 			return B_ERROR;
86 		}
87 	}
88 	fPathsAdded = true;
89 
90 	return B_OK;
91 }
92 
93 // Undo
94 status_t
95 AddPathsCommand::Undo()
96 {
97 	// remove paths from container
98 	for (int32 i = 0; i < fCount; i++) {
99 		fContainer->RemovePath(fPaths[i]);
100 	}
101 	fPathsAdded = false;
102 
103 	return B_OK;
104 }
105 
106 // GetName
107 void
108 AddPathsCommand::GetName(BString& name)
109 {
110 	if (fOwnsPaths) {
111 		if (fCount > 1)
112 			name << B_TRANSLATE("Add Paths");
113 		else
114 			name << B_TRANSLATE("Add Path");
115 	} else {
116 		if (fCount > 1)
117 			name << B_TRANSLATE("Assign Paths");
118 		else
119 			name << B_TRANSLATE("Assign Path");
120 	}
121 }
122