xref: /haiku/src/apps/icon-o-matic/shape/commands/AddTransformersCommand.cpp (revision 02354704729d38c3b078c696adc1bbbd33cbcf72)
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 "AddTransformersCommand.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 "ShapeContainer.h"
19 #include "Shape.h"
20 
21 
22 #undef B_TRANSLATION_CONTEXT
23 #define B_TRANSLATION_CONTEXT "Icon-O-Matic-AddTransformersCmd"
24 
25 
26 using std::nothrow;
27 
28 // constructor
29 AddTransformersCommand::AddTransformersCommand(Shape* container,
30 											   Transformer** const transformers,
31 											   int32 count,
32 											   int32 index)
33 	: Command(),
34 	  fContainer(container),
35 	  fTransformers(transformers && count > 0 ?
36 	  				new (nothrow) Transformer*[count] : NULL),
37 	  fCount(count),
38 	  fIndex(index),
39 	  fTransformersAdded(false)
40 {
41 	if (!fContainer || !fTransformers)
42 		return;
43 
44 	memcpy(fTransformers, transformers, sizeof(Transformer*) * fCount);
45 }
46 
47 // destructor
48 AddTransformersCommand::~AddTransformersCommand()
49 {
50 	if (!fTransformersAdded && fTransformers) {
51 		for (int32 i = 0; i < fCount; i++)
52 			delete fTransformers[i];
53 	}
54 	delete[] fTransformers;
55 }
56 
57 // InitCheck
58 status_t
59 AddTransformersCommand::InitCheck()
60 {
61 	return fContainer && fTransformers ? B_OK : B_NO_INIT;
62 }
63 
64 // Perform
65 status_t
66 AddTransformersCommand::Perform()
67 {
68 	status_t ret = B_OK;
69 
70 	// add transformers to container
71 	int32 index = fIndex;
72 	for (int32 i = 0; i < fCount; i++) {
73 		if (fTransformers[i]
74 			&& !fContainer->AddTransformer(fTransformers[i], index)) {
75 			ret = B_ERROR;
76 			// roll back
77 			for (int32 j = i - 1; j >= 0; j--)
78 				fContainer->RemoveTransformer(fTransformers[j]);
79 			break;
80 		}
81 		index++;
82 	}
83 	fTransformersAdded = true;
84 
85 	return ret;
86 }
87 
88 // Undo
89 status_t
90 AddTransformersCommand::Undo()
91 {
92 	status_t ret = B_OK;
93 
94 	// add shapes to container at remembered indices
95 	for (int32 i = 0; i < fCount; i++) {
96 		fContainer->RemoveTransformer(fTransformers[i]);
97 	}
98 	fTransformersAdded = false;
99 
100 	return ret;
101 }
102 
103 // GetName
104 void
105 AddTransformersCommand::GetName(BString& name)
106 {
107 	if (fCount > 1)
108 		name << B_TRANSLATE("Add Transformers");
109 	else
110 		name << B_TRANSLATE("Add Transformer");
111 }
112