📄 project.java
字号:
/** * Copyright 2004 Carlos Silva A. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package jgantt.model;import java.util.Date;import java.util.Iterator;import java.util.Stack;import java.util.Vector;import jgantt.Messages;import jgantt.cmds.Command;import jgantt.cmds.TaskCommand;import com.csa.lib.xml.dom.Node;/** * Proyecto representa un proyecto para una carta gantt. * <p>Cada proyecto tiene una tarea principal (invisible) de la cual * se incluye todo el resto.</p> * <p>La fecha de inicio del proyecto se lleva al campo not before * de la tarea principal.</p> * <p>Las opciones de UNDO, REDO son manejadas por este objeto, pero * talvez sea mejor mover esta funcionalidad a ViewModel</p> * * TODO: agregar una tarea que ya tiene referencias hijas (eliminar constraints). * * @version $Header: /cvs/java/App_JGantt/source/jgantt/model/Project.java,v 1.36 2005/08/19 15:50:42 csilva Exp $ * @author Carlos Silva */public class Project { // SOPORTE A UNDO/REDO transient private Stack undoStack = new Stack(); transient private Stack redoStack = new Stack(); transient private boolean insideRedo = false; transient private boolean insideUndo = false; /** * Desrealiza el ultimo comando realizado. * Cuando una accion es deshecha, esta pasa a * lista de comandos por rehacer. */ public void undo() { if (undoStack.isEmpty()) return; insideUndo = true; TaskCommand cmd = (TaskCommand) undoStack.pop(); redoStack.push(cmd); cmd.undo(); insideUndo = false; } /** * Realiza nuevamente una actividad que ha sido deshecha. */ public void redo() { if (redoStack.isEmpty()) return; insideRedo = true; Command cmd = (Command) redoStack.pop(); cmd.execute(); insideRedo = false; } /** * Registra una accion deshacible. Normalmente es * llamado por los setters de las tareas. */ public void registerCommand(Command cmd) { if (!insideUndo) { undoStack.push(cmd); if (!insideRedo) redoStack.clear(); } } /** * Limpia las areas de las acciones de undo y redo. */ public void clearUndoRedo() { undoStack.clear(); redoStack.clear(); } /** * Pregunta si hay acciones en el area de undo * @return */ public boolean isUndoEmpty() { return undoStack.isEmpty(); } /** * Pregunta si hay acciones en el area de redo * @return */ public boolean isRedoEmpty() { return redoStack.isEmpty(); } /// Tarea principal Task mainTask; /// Fecha de inicio Date startDate; /// Nombre del proyecto String name; /// Juez para realizar consultas frecuentemente Referee referee = null; /// Organizador de fechas DateOrganizer dOrg = new DateOrganizer(); /// formato grafico ViewOptions viewOptions = null; /// Colores para graficos GraphColors graphColors = null; /// Colores para la tabla TaskTreeOptions treeColors; /// Lista de snapshots Vector snapshots = new Vector(); /** * Recursos asociados al proyecto * Contiene elementos de tipo Resource */ protected Vector resources = new Vector(); //transient transient Vector taskList = new Vector(); // constructor public Project(DateOrganizer dorg) { mainTask = new Task(this); mainTask.setName(Messages.getString("prj.mainTaskName")); //$NON-NLS-1$ taskList.addElement(mainTask); mainTask.setId(0); setDateOrganizer(dorg); } public Task createTask(String name) { return new Task(this, name); } public Task createTask(String name, int length) { return new Task(this, name, length); } public Resource createResource( int id, String name, String alias, String initials) { Resource person = new Resource(this); person.setId(id); person.setName(name); person.setAlias(alias); person.setInitials(initials); return person; } public void taskMoved(Task t) { taskList.clear(); rebuildIds(getMainTask(), 0); sendChange(new ProjectChange(ProjectChange.STRUCTURE, t)); } /** * Cuando se agrega una nueva tarea se debe recalcular todos los Id de las tareas. * @param child */ public void childInserted(Task child) { taskList.clear(); rebuildIds(getMainTask(), 0); sendChange(new ProjectChange(ProjectChange.TASK_ADDED, child)); } /** * Remueve a una tarea de la lista de tareas * esta funcion es gatillada por la funcion remove de la tarea. */ void removeTask(Task child) { taskList.clear(); rebuildIds(getMainTask(), 0); // Avisa a los escuchadores despues de eliminar la tarea. sendChange(new ProjectChange(ProjectChange.TASK_REMOVED, child)); } /** * Fuerza el recalculo completo. * Esto se requiere cuando hay cambios globales (como el calendario) */ public void forceRecalc() { for (int i = 0; i < taskList.size(); i++) { Task t = (Task) taskList.get(i); t.setDirty(); } sendChange(new ProjectChange(ProjectChange.FORCED_CHANGE, mainTask)); } /** * Regenera los Ids de las tareas y la lista de tareas taskList * @param t * @param id * @return */ int rebuildIds(Task t, int id) { int oid = id; t.setId(id++); taskList.add(t); for (Iterator i = t.getChildTasks().iterator(); i.hasNext();) { Task c = (Task) i.next(); id = rebuildIds(c, id); } if (oid == 0) rebuildVIds(); return id; } int vtCount = 0; void rebuildVIds() { vtCount = 0; //System.out.println("Project.rebuildVIds()"); for (int i = 0; i < taskList.size(); i++) { Task t = (Task) taskList.get(i); if (t.isVisible()) t.visibleIndex = vtCount++; else t.visibleIndex = -1; //System.out.println(" task "+t.getId()+" "+ t.getName()+" visibleIndex="+t.visibleIndex); } vtCount--; // mainTask no se cuenta } /** * * @return cantidad de tareas visibles sin inlcuir mainTask */ public int getVisibleTaskCount() { return vtCount; } /** * Obtiene la tarea iesima * @param n id de la tarea 0..visibleTaskCount * @return Tarea en la posicion n-esima */ public Task getVisibleTask(int n) { n++; for (int i = 0; i < taskList.size(); i++) { Task t = (Task) taskList.get(i); if (t.getVisibleIndex() == n) return t; } //System.out.println("Project.getVisibleTask()" + n + " not found"); return null; } /** * Al contrario de la funcion removeTask(Task), esta funcion puede * ser llamada por la interfaz para eliminar una cierta tarea * Para borrar una tarea de la cual se tiene la referencia se debe * usar task.remove(). */ public void removeTask(int id) { Task child = (Task) taskList.elementAt(id); child.remove(); } public int getTaskCount() { return taskList.size() - 1; } public Task getTask(int i) { return (Task) taskList.elementAt(i + 1); } void allDirty(){ for (int i = 0; i < taskList.size(); i++) { Task t = (Task) taskList.get(i); t.dirty=true; } } public void setDateOrganizer(DateOrganizer d) { dOrg = d; } public DateOrganizer getDateOrganizer() { return dOrg; } public Task getMainTask() { return mainTask; } public Date getStartDate() { return startDate; } public void setStartDate(Date newStartDate) { if (dOrg == null) { throw new RuntimeException(Messages.getString("prj.error.noCalendar")); //$NON-NLS-1$ } // cambia la hora de inicio de la jornada startDate = dOrg.getNormalizedStartDate(newStartDate); for (Iterator i = taskList.iterator(); i.hasNext();) { Task t = (Task) i.next(); t.setDirty(); } sendChange(new ProjectChange(ProjectChange.START_DATE, null)); } public String getName() { return name; } public void setName(String newName) { name = newName; } /** * agrega un nuevo recurso y le asigna un id. * @param r */ protected void addResource(Resource r) { resources.add(r); r.setId(resources.size()); } /** * Retorna la lista de recursos asociados al proyecto. * @return */ public Vector getResources() { return resources; } /** * Retorna una lista con los recursos y la cantidad de horas hombre total de cada uno. * Las unidades de asignation estan en minutos habiles. * * @return Vector donde cada elemento es de tipo Asignation */ public Vector getTotalAsignations() { Vector v = new Vector(); for (Iterator i = resources.iterator(); i.hasNext();) { Resource r = (Resource) i.next(); int units = mainTask.getTotalResourceUnits(r); Asignation a = new Asignation(r, units); v.add(a); } return v; } public Vector getWorkedAsignations() { Vector v = new Vector(); for (Iterator i = resources.iterator(); i.hasNext();) { Resource r = (Resource) i.next(); int units = mainTask.getWorkedResourceUnits(r); Asignation a = new Asignation(r, units); v.add(a); } return v; } protected boolean decide(Decision d) { if (referee == null) referee = new Referee(); return referee.decide(d); } /** * Transformar este objet en un nodo de XML * retorna un Elemento XML (no lo agrega al arbol) * @return Element */ public Node toXMLElement() { return XMLModel.toXML(this); } /** * Equivalente de llamar a {@link resource.remove}. * Quita al recurso de la lista de recursos y de las tareas que lo tienen con asignacion. * @param i */ public void removeResource(int id) { Resource r = (Resource) resources.remove(id - 1); for (int j = 0; j < taskList.size(); j++) { Task t = (Task) taskList.get(j); t.removeResource(r); } // reajustar ids for (int j = 0; j < resources.size(); j++) { r = (Resource) resources.get(j); r.setId(j + 1); } } /** * Retorna los colores generales del grafico de la gantt. * @return */ public GraphColors getGraphColors() { if (graphColors == null) { graphColors = new GraphColors(true); } return graphColors; } public void setGraphColors(GraphColors gc) { graphColors = gc; } /** * Retorna las caracteristicas visuales del proyecto. * @return */ public ViewOptions getViewOptions() { if (viewOptions == null) { viewOptions = new ViewOptions(this); } return viewOptions; } public TaskTreeOptions getTreeColors() { if (treeColors == null) { treeColors = new TaskTreeOptions(); } return treeColors; } /** * Guarda informacion de las tareas existentes sus fechas de inicio y termino * y su estado de completitud. Asocia a cada tarea un resumen con su informacion * particular llamando a la funcion {@link Task#takeSnapshot} de cada subtarea.</p> * <p>Cada snapshot tiene asociada una fecha de generacion y un nombre. * La llave de los snapshots es la fecha en que se toma el snapshot.</p> * * @param name nombre del snapshot */ public void takeSnapshot(String name) { Date date = new Date(); for (int i = 0; i < taskList.size(); i++) { Task t = (Task) taskList.get(i); t.takeSnapshot(date); } SnapShot ss = new SnapShot(date, name); snapshots.add(ss); sendChange(new ProjectChange(ProjectChange.SNAPSHOT_ADDED, ss)); } public static class SnapShot { public Date date; public String name; public SnapShot(Date d, String n) { date = d; name = n; } public String toString() { return XMLModel.sdf.format(date) + ": " + name; } } /** * Recupera una tabla de hashing con los snapshots. * donde la llave es la fecha... * @return */ public Vector getSnapshots() { return snapshots; } /** * Remueve este snapshot de todos los hijos * @param d */ public void removeSnapshot(Date date) { SnapShot ss = null; for (int i = 0; i < snapshots.size(); i++) { ss = (SnapShot) snapshots.get(i); if (ss.date.equals(date)) { snapshots.remove(ss); for (int j = 0; j < taskList.size(); j++) { Task t = (Task) taskList.get(j); t.removeSnapshot(date); } break; } } sendChange(new ProjectChange(ProjectChange.SNAPSHOT_REMOVED, ss)); } // Soporte a eventos /** * Objeto para administrar listeners */ protected ChangeSupport changeSupport = new ChangeSupport() { protected void notifyListener(Object listener, Change change) { ((ProjectListener) listener).projectChanged((ProjectChange) change); } }; /** * Agrega un listener a los suscritos * @param o */ public void addListener(ProjectListener listener) { changeSupport.addListener(listener); } /** * Remueve un listener de los suscritos * @param listener */ public void removeListener(ProjectListener listener) { changeSupport.removeListener(listener); } /** * Comienza una bloque de cambios que deben despacharse todos * juntos al final. * <p>El ultimo mensaje del bloque se envia con la marca:<code>isLast</code>.</p> */ public void beginBlockChanges() { changeSupport.beginBlockChanges(); } /** * Envia en bloque todos los cambios recibidos y que estan en la cola. * <p>El ultimo mensaje del bloque se envia con la marca:<code>isLast</code>.</p> */ public void commitBlockChanges() { changeSupport.commitBlockChanges(); } /** * Envia una cambio a todos los escuchadores * @param change ProjectChange */ public void sendChange(ProjectChange change) { changeSupport.sendChange(change); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -