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