001    package de.deepamehta.plugins.topicmaps.model;
002    
003    import de.deepamehta.core.model.ChildTopicsModel;
004    import de.deepamehta.core.model.TopicModel;
005    
006    import org.codehaus.jettison.json.JSONObject;
007    
008    
009    
010    /**
011     * A topic viewmodel as contained in a topicmap viewmodel.
012     * <p>
013     * That is a generic topic model enriched by view properties. Standard view properties are "dm4.topicmaps.x",
014     * "dm4.topicmaps.y", and "dm4.topicmaps.visibility". Additional view properties can be added by plugins (by
015     * implementing a Viewmodel Customizer).
016     */
017    public class TopicViewmodel extends TopicModel {
018    
019        // --- Instance Variables ---
020    
021        private ChildTopicsModel viewProps;
022    
023        // --- Constructors ---
024    
025        public TopicViewmodel(TopicModel topic, ChildTopicsModel viewProps) {
026            super(topic);
027            this.viewProps = viewProps;
028        }
029    
030        // --- Public Methods ---
031    
032        public ChildTopicsModel getViewProperties() {
033            return viewProps;
034        }
035    
036        // ---
037    
038        /**
039         * Convencience method to access the "dm4.topicmaps.x" standard view property.
040         */
041        public int getX() {
042            // Note: coordinates can be both: double (through JavaScript) and integer (programmatically placed).
043            // ### TODO: store coordinates always as integers
044            Object x = viewProps.getObject("dm4.topicmaps.x");
045            return x instanceof Double ? ((Double) x).intValue() : (Integer) x;
046        }
047    
048        /**
049         * Convencience method to access the "dm4.topicmaps.y" standard view property.
050         */
051        public int getY() {
052            // Note: coordinates can be both: double (through JavaScript) and integer (programmatically placed).
053            // ### TODO: store coordinates always as integers
054            Object y = viewProps.getObject("dm4.topicmaps.y");
055            return y instanceof Double ? ((Double) y).intValue() : (Integer) y;
056        }
057    
058        /**
059         * Convencience method to access the "dm4.topicmaps.visibility" standard view property.
060         */
061        public boolean getVisibility() {
062            return viewProps.getBoolean("dm4.topicmaps.visibility");
063        }
064    
065        // ---
066    
067        @Override
068        public JSONObject toJSON() {
069            try {
070                JSONObject o = super.toJSON();
071                o.put("view_props", viewProps.toJSON());
072                return o;
073            } catch (Exception e) {
074                throw new RuntimeException("Serialization failed (" + this + ")", e);
075            }
076        }
077    }