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