BoundsFactory.groovy
01 /*
02  * Copyright 2008-2016 the original author or authors.
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *     http://www.apache.org/licenses/LICENSE-2.0
09  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package griffon.builder.pivot.factory
17 
18 import org.apache.pivot.wtk.Bounds
19 import org.apache.pivot.wtk.Dimensions
20 import org.apache.pivot.wtk.Point
21 
22 /**
23  @author Andres Almiray
24  */
25 class BoundsFactory extends AbstractFactory {
26     boolean isLeaf() {
27         return true
28     }
29 
30     Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributesthrows InstantiationException, IllegalAccessException {
31         if (FactoryBuilderSupport.checkValueIsTypeNotString(value, name, Bounds)) {
32             return value
33         }
34         if (value != null && value instanceof Bounds) {
35             return value
36         else ifvalue != null) {
37             throw new IllegalArgumentException("In $name value must be of type ${Bounds.class.name}")
38         }
39 
40         if (attributes.containsKey('origin') || attributes.containsKey('size')) {
41             Point origin = attributes.remove('origin') ?: new Point(0i, 0i)
42             Dimensions size = attributes.remove('size') ?: new Dimensions(0i, 0i)
43             return new Bounds(origin, size)
44         }
45 
46         return new Bounds(
47                 toInteger(attributes.remove('x'?: 0i),
48                 toInteger(attributes.remove('y'?: 0i),
49                 toInteger(attributes.remove('width') ?: 0i),
50                 toInteger(attributes.remove('height') ?: 0i)
51         )
52     }
53 
54     private int toInteger(value) {
55         if (value instanceof Numberreturn value.intValue()
56         return Double.valueOf(value.toString()).intValue()
57     }
58 }