UNIVERSIDADE FEDERAL DE SANTA CATARINA
Desenvolvimento de um Sistema de planejamento e
acompanhamento técnico e financeiro de projetos
Luis Henrique Spoladore Amaral
2
UNIVERSIDADE FEDERAL DE SANTA CATARINA DEPARTAMENTO DE INFORMÁTICA E ESTATÍSTICA CURSO DE SISTEMAS DE INFORMAÇÃO
TÍTULO: Desenvolvimento de um Sistema de planejamento e acompanhamento técnico e econômico de projetos AUTOR: Luis Henrique Spoladore Amaral ORIENTADOR: José Eduardo De Lucca BANCA EXAMINADORA: Delson de Valois Santos ; Rafael Savi Florianópolis, 26 de fevereiro de 2007.
3
Resumo
Este trabalho descreve Desenvolvimento de um Sistema de planejamento e
acompanhamento técnico e financeiro de projetos.
Foram estudados os sistemas de gestão de projetos já existentes e dentre eles,
destacou-se o software livre GanttProject, que atendia parcialmente os requisitos
desejados. O sistema desenvolvido é então uma adaptação do sistema GanttProject,
que implementa os requisitos estabelecidos para o projeto.
Dentre as principais funcionalidades do sistema, destacam-se a possibilidade
de definir tarefas, cronogramas, e alocação de recursos e também a excelente
usabilidade da interface.
A gerência de projetos é ainda hoje uma área considerada de menor
importância em ambientes de laboratórios de pesquisa e pequenas empresas, que
concentram seus esforços na área operacional. Espera-se que o sistema
desenvolvido possa auxiliar tais laboratórios na gestão de projetos.
O trabalho relata também a experiência no desenvolvimento de novas
funcionalidades de um software mantido pela comunidade de software livre
SourceForge.
Palavras-chave: Gestão de projetos, GanttProject, Software Livre
4
Abstract
This work describes the Development of a technical and financial, planning and
accompaniment System.
Existing Management Systems have been studied and GanttProject have been
distinguished amongst them, supporting partially the desired requirements. So, the
developed system is an adaptation of GanttProject that implements the established
project requirements.
Amongst the main system functionalities, distinguishes the possibility of tasks
definig, schedules, resources allocation and the excellent interface usability.
The project management area still is considered of lesser importance at
research laboratories and small companies, wich concentrate its efforts on
operational areas. Its expected that the developed system could help those
laboratories to manage their projects.
This work also reports the experience in development of new features on a
software maintened by SourceForge, a free software community.
Keywords: Project Management, GanttProject, Free Software
5
Sumário
Resumo ...................................................................................................................... 3 Abstract ...................................................................................................................... 4 Lista de Figuras .......................................................................................................... 6 Lista de Tabelas ......................................................................................................... 7 1. Introdução .......................................................................................................... 8 2. Objetivos ............................................................................................................ 9 1.1 Objetivo Geral ................................................................................................ 9 1.2 Objetivos Específicos..................................................................................... 9 1.3 Limites............................................................................................................ 9 1.4 Estrutura ........................................................................................................ 9
3. Conceitos: ........................................................................................................ 11 3.1 Projeto.......................................................................................................... 11 3.2 Gerência de projetos.................................................................................... 12 3.3 Gráfico de Gantt........................................................................................... 13 3.4 PERT (Program Evaluation and Review Technique) ................................... 14 3.5 Método Caminho crítico (CPM).................................................................... 14 3.6 Work Breakdown Structure (WBS)............................................................... 15
4 Levantamento de requisitos para um sistema de Gestão de Projetos ............. 16 4.1 Requisitos Funcionais: ................................................................................. 17 4.2 Requisitos Não Funcionais: ......................................................................... 18
5 Avaliação de ferramentas de Gestão de Projetos ............................................ 19 5.1 Open Workbench ......................................................................................... 19 5.2 GanttProject ................................................................................................. 20 5.3 dotProject..................................................................................................... 21
6 Proposta de solução para uma ferramenta de gestão de projetos................... 23 6.1 GanttProject ................................................................................................. 24
6.1.1 Estado Atual..........................................................................................24 6.1.2 Novas Funcionalidades.........................................................................31
7 Caso de uso da ferramenta.............................................................................. 36 8 Conclusões ...................................................................................................... 49 Trabalhos Futuros .................................................................................................... 50 Glossário .................................................................................................................. 51 Referências Bibliográficas ........................................................................................ 54 Bibliografia................................................................................................................ 56 Apêndices................................................................................................................. 57 Classes e arquivos alterados ................................................................................ 57 Classes e Arquivos criados................................................................................... 58 Código Fonte ........................................................................................................ 60
6
Lista de FigurasFigura 1 - Exemplo de Gráfico PERT .......................................................................... 14 Figura 2 - Exemplo de WBS ......................................................................................... 15 Figura 3 - Tela Inicial - Tarefas .................................................................................... 24 Figura 4 - Tela principal de Recursos ......................................................................... 25 Figura 5 - Tela de propriedades gerais de Recurso .................................................. 26 Figura 6 - Tela de propriedades ferias de Recurso ................................................... 26 Figura 7 - Tela ilustrando a exibição de conflitos entre alocação de Recursos ...... 27 Figura 8 - Tela de propriedades gerais de Tarefa...................................................... 28 Figura 9 - Tela de notas da Tarefa .............................................................................. 28 Figura 10 - Tela de colunas customizadas da Tarefa................................................ 29 Figura 11 - Tela de recursos da Tarefa....................................................................... 29 Figura 12 - Tela de dependências da Tarefa.............................................................. 30 Figura 13 - Tela importação de projeto de servidor WebDAV .................................. 30 Figura 14 - Tela de propriedades gerais de Tarefa, agora com campo orçamento33 Figura 15 - Nova Tela de custos de Tarefa ................................................................ 33 Figura 16 - Nova Tela para execução de relatórios ................................................... 34 Figura 17 - Relatório de Custos por Atividade............................................................ 34 Figura 18 - Relatório Financeiro .................................................................................. 35 Figura 19 - Definindo Projeto ...................................................................................... 37 Figura 20 - Definindo dias de folga.............................................................................. 37 Figura 21 - Definindo Tarefa ........................................................................................ 39 Figura 22 - Definindo relações de tarefas ................................................................... 39 Figura 23 - Definindo custos de tarefa ........................................................................ 40 Figura 24 - Visualização do Gráfico Gantt .................................................................. 40 Figura 25 - Associando tarefas utilizando recurso de interface................................ 41 Figura 26 - Associando recursos à Tarefa.................................................................. 42 Figura 27 - Visualização de Gráfico de Alocação de Recursos................................ 42 Figura 28 - Visualização de comparação de estados de projeto.............................. 43 Figura 29 - Visualização do caminho crítico ............................................................... 44 Figura 30 - Gráfico de PERT........................................................................................ 44 Figura 31 - Relatório de Custos por Atividade............................................................ 45 Figura 32 - Relatório de Resumo de custos ............................................................... 46 Figura 33 - Configurando Servidor FTP ...................................................................... 46 Figura 34 - Relatório Web Gráfico de Gantt ............................................................... 47 Figura 35 - Relatório Web - Recursos ......................................................................... 47
7
Lista de TabelasTabela 1: Requisitos no software Open Benchwork ................................................. 19 Tabela 2: Requisitos no software GanttProject .......................................................... 21 Tabela 3: Requisitos no software dotProject .............................................................. 22
8
1. Introdução
A organização da sociedade capitalista foi profundamente alterada pela Revolução
Industrial. Diversas transformações iniciaram, tornando o processo de controle das
organizações cada vez mais complexo. Ao fim do século XIX, surge a administração,
propiciando conhecimento científico ao gerenciamento das novas estruturas
produtivas. Observa-se neste contexto, um empregado que diferencia-se dos demais
quanto ao nível de autoridade. Identificado como gestor, suas atribuições e
atividades executadas são objeto de estudo de diversas teorias da administração.
FAYOL (1970) foi o responsável pela Teoria Clássica da Administração.
Preocupado na organização da empresa como um todo, sistematizou os grupos
necessários à atividade administrativa: planejar, organizar, comandar, coordenar e
controlar. TAYLOR (1971) propôs a utilização de métodos científicos na
administração de empresas, dando inicio à Administração Científica. Nela, foram
identificados os princípios de planejamento, preparação dos trabalhadores, controle
e execução. Ambas teorias preocupavam-se em atingir os objetivos de maior
produtividade no trabalho e eficiência nas organizações.
Desde então, diversas teorias e metodologias foram criadas no âmbito da
gerência de projetos. Apesar da proposta de Fayol servir ainda a base para as
práticas de gestão, estudos mais recentes ressaltam a natureza incerta dos projetos
inserida em um ambiente mutável, em que dificilmente o projeto se mantém dentro
do planejado, como afirmam REED (1989) e MINTZBERG (1990).
Atualmente, a referencia na área de gestão de projetos é o PMI ( Project
Management Institute. Este instituto é responsável pela publicação do PMBOK -
Project Management Body of Knowledge – que é um conjunto de conhecimentos
para gerenciamento de projeto. Este trabalho esta baseado nos conceitos
apresentados por este instituto.
9
2. Objetivos
1.1 Objetivo Geral
O objetivo deste trabalho é desenvolver um software livre para planejamento
e acompanhamento técnico e financeiro de projetos que sirva como alternativa aos
softwares proprietários. Espera-se que o mesmo possa auxiliar e incentivar
laboratórios de pesquisa a planejar e gerenciar seus projetos.
1.2 Objetivos Específicos
1.2.1 Estudar os princípios de gerenciamento de projetos, de acordo com as
entidades de referência da área.
1.2.2 Levantar as necessidades de gerenciamento de projetos em ambiente
acadêmico/universitário.
1.2.3 Criar uma ferramenta livre que incorpore os conceitos básicos de
gerenciamento de projetos aplicados ao ambiente acadêmico.
1.3 Limites
O trabalho está voltado ao desenvolvimento de uma ferramenta para auxiliar
laboratórios de pesquisa a planejar e acompanhar seus projetos, o que não impede
que pequenas empresas e usuários domésticos utilizem a ferramenta, dadas as
características genéricas de gerência de projeto suportadas.
1.4 Estrutura
Este trabalho esta estrutura em 8 capítulos. O primeiro capítulo apresenta
uma introdução à gerência de projetos. O segundo descreve o trabalho em geral,
apresentado seus objetivos gerais e específicos, limitações e estrutura.
O terceiro aborda os conceitos relacionados à gerência de projetos, enquanto
que o quarto capítulo busca identificar requisitos de software que possibilite a gestão
de projetos em laboratórios de pesquisa.
10
Tendo definidos os requisitos, no quinto capítulo é descrita a avaliação de
algumas ferramentas de gestão existentes atualmente. O sexto capítulo apresenta o
software proposto e o seu desenvolvimento.
Posteriormente, é exibido no sétimo capítulo um exemplo de caso de uso da
ferramenta. No último capitulo são apresentadas as conclusões, resultados
alcançados e sugestões para trabalhos futuros.
11
3. Conceitos:
Neste capítulo serão apresentados os principais conceitos de gestão de
projetos, utilizando como principal referência o PMBOK.
3.1 Projeto
Projeto é um conjunto fechado de atividades ou tarefas, com prazos e custos
bem definidos. Um temporário empreendido para criar um produto, serviço ou
resultado exclusivo. [PMB04]
1 - Temporário
Temporário significa que todos os projetos possuem um início e um final
definidos. O final é alcançado quando os objetivos do projeto tiverem sido atingidos,
quando se tornar claro que os objetivos do projeto não serão ou não poderão ser
atingidos ou quando não existir mais a necessidade do projeto e ele for encerrado.
Temporário não significa necessariamente de curta duração; muitos projetos duram
vários anos. Em todos os casos, no entanto, a duração de um projeto é finita.
Projetos não são esforços contínuos.
Além disso, geralmente o termo temporário não se aplica ao produto, serviço
ou resultado criado pelo projeto. A maioria dos projetos é realizada para criar um
resultado duradouro. Por exemplo, um projeto para erguer um monumento nacional
criará um resultado que deve durar séculos. Os projetos também podem com
freqüência ter impactos sociais, econômicos e ambientais, intencionais ou não, com
duração muito mais longa que a dos próprios projetos.
A natureza temporária dos projetos pode também ser aplicada a outros
aspectos do esforço:
- A oportunidade ou janela do mercado geralmente é temporária—alguns
projetos têm um prazo limitado durante o qual seu produto ou serviço deve ser
gerado.
- A equipe do projeto, como uma unidade de trabalho, dificilmente continuará a
mesma após o projeto—uma equipe criada com o único objetivo de realizar o projeto
realizará esse projeto e, em seguida, será desfeita e seus membros serão
realocados quando o projeto for concluído.
12
2 - Produtos, serviços ou resultados exclusivos.
Um projeto cria entregas exclusivas, que são produtos, serviços ou resultados.
Os projetos podem criar:
- Um produto ou objeto produzido, quantificável e que pode ser um item final ou
um item componente.
- Uma capacidade de realizar um serviço, como funções de negócios que dão
suporte à produção ou à distribuição.
- Um resultado, como resultados finais ou documentos. Por exemplo, um
projeto de pesquisa desenvolve um conhecimento que pode ser usado para
determinar se uma tendência está presente ou não ou se um novo processo irá
beneficiar a sociedade.
A singularidade é uma característica importante das entregas do projeto. Por
exemplo, muitos milhares de prédios de escritórios foram construídos, mas cada
prédio em particular é único—tem proprietário diferente, projeto diferente, local
diferente, construtora diferente, etc. A presença de elementos repetitivos não muda
a singularidade fundamental do trabalho do projeto.
3 – Elaboração Progressiva
A elaboração progressiva é uma característica de projetos que integra os
conceitos de temporário e exclusivo. Elaboração progressiva significa desenvolver
em etapas e continuar por incrementos. Por exemplo, o escopo do projeto será
descrito de maneira geral no início do projeto e se tornará mais explícito e detalhado
conforme a equipe do projeto desenvolve um entendimento mais completo dos
objetivos e das entregas.
3.2 Gerência de projetos
O gerenciamento de projetos é a aplicação de conhecimento, habilidades, ferramentas
e técnicas às atividades do projeto a fim de atender aos seus requisitos. O gerenciamento
de projetos é realizado através da aplicação e da integração dos seguintes processos de
gerenciamento de projetos: iniciação, planejamento, execução, monitoramento e controle, e
encerramento. O gerente de projetos é a pessoa responsável pela realização dos objetivos
do projeto. As funções da gerencia de projetos são [KLE98]:
13
• Liderança: para inspirar os participantes a atingir as metas e objetivos em um nível
que atenda ou exceda suas expectativas. Esta é a única função de gerência de projetos que
ocorre simultaneamente com as demais funções. O gerente de projeto pode utilizar a
liderança para executar o projeto com eficiência e eficácia.
• Definição: para determinar a visão global, metas, objetivos, escopo,
responsabilidades e distribuições de recursos de um projeto. Uma maneira comum de
capturar esta informação é através de um documento que delineia o projeto e é assinado
por todas as partes interessadas
• Planejamento: para determinar os passos necessários para executar o projeto,
indicando as pessoas que irão executá-los e identificando as datas iniciais e finais.
• Organização: para gerenciar os recursos eficazmente para a execução do plano. A
organização envolve atividades como formar um time, alocar recursos, calcular custos,
avaliar riscos, preparar a documentação do projeto e assegurar um bom canal de
comunicação.
• Controle: para avaliar o quanto o projeto atinge suas metas e objetivos. O controle
envolve a coleta e avaliação de relatórios, controlar mudanças nas linhas de base, e
responder a circunstancias que possam afetar negativamente os participantes do projeto
• Finalização: para concluir um projeto com eficiência e eficácia. Finalizar um projeto
envolve compilar estatísticas, liberar o pessoal e preparar um documento com os
conhecimentos adquiridos.
3.3 Gráfico de Gantt
Uma representação gráfica de informações relacionadas ao cronograma. Em
um gráfico de barras típico, as atividades do cronograma ou os componentes da
estrutura analítica do projeto são listados verticalmente no lado esquerdo do gráfico,
as datas são mostradas horizontalmente na parte superior e as durações das
atividades são exibidas como barras horizontais posicionadas de acordo com as
datas [PMB04].
Foi desenvolvido em 1910 por Henry L. Gantt. Em sua forma inicial, ele exibe
as atividades dispostas verticalmente e o tempo horizontalmente. É possível mostrar
também a composição de tarefas e sub-tarefas. Atualmente, novos dados foram
adicionados, de modo que é possível exibir não só a duração como também a
dependência entre tarefas, porcentagem concluída e recursos alocados [WIK06a]..
14
3.4 PERT (Program Evaluation and Review Technique)
PERT, também conhecido como a técnica de estimativa dos três pontos, utiliza
três estimativas de tempo para que uma tarefa seja completada. As três estimativas
são: a mais provável, a mais pessimista e a mais otimista. A mais provável é o
esforço (em dias, horas) para completar uma tarefa em condições normais. A mais
pessimista é o esforço para completar uma tarefa nas piores circunstâncias. A mais
otimista considera o esforço para completar a tarefa nas melhores condições. Esta
técnica utiliza o método do caminho crítico para determinar a média ponderada de
duração das tarefas [KLE98].
Foi em resposta a este problema que o PERT foi desenvolvido em 1957 em ação
conjunta da Marinha dos EUA e a empresa de consultoria de Booz, Allen e Hamilton.
O conceito foi originalmente aplicado ao projeto do submarino Polaris. O sistema
PERT esta baseado na idéia de que estimativas são incertas, consequentemente é
relevante utilizar escalas de durações e probabilidades de a duração de uma
atividade estar nesta escala, do que assumir que uma tarefa será completada em
uma quantidade de tempo fixa [LEW99].
Pode ser representado graficamente através de uma rede onde as atividades do
projeto são apresentados na forma de um grafo direcional. Os eventos são
representados pelos vértices e as arestas apresentam o peso das suas durações.
Figura 1 - Exemplo de Gráfico PERT
3.5 Método Caminho crítico (CPM)
O caminho crítico é a seqüência mais longa de tarefas partindo do inicio até o fim do
projeto. É importante identificar o caminho critico por o atraso em uma tarefa desse caminho
implica no atraso de todo o projeto [KNU91]. Dessa forma, é possível identificar quais
tarefas merecem maior atenção.
15
3.6 Work Breakdown Structure (WBS)
Uma decomposição hierárquica orientada à entrega do trabalho a ser
executado pela equipe do projeto Ela organiza e define o escopo total do projeto.
Cada nível descendente representa uma definição cada vez mais detalhada do
trabalho do projeto [PMB04]. Sua tradução em português é Estrutura Analítica de
Projetos. A WBS serve como base para a maior parte do planejamento de projeto.
Figura 2 - Exemplo de WBS
16
4 Levantamento de requisitos para um sistema de Gestão de Projetos
Será apresentado neste capítulo o levantamento de requisitos para um sistema
de gerência de projetos. Tais requisitos foram identificados através de entrevistas
informais e através da convivência com as pessoas responsáveis pela gerencia de
projetos no laboratório GeNESS [GEN07].
Requisitos são uma descrição das necessidades ou desejos para um produto. O
Objetivo básico da fase de requisitos é identificar e documentar o que é realmente
necessário, em uma forma que comunica claramente essa informação ao cliente e
aos membros da equipe de desenvolvimento [LAR00].
Requisitos de software podem ser classificados como funcionais ou não
funcionais. Requisitos funcionais (RF) são as funções que o usuário esperam que o
software faça. O termo função é uma operação genérica a ser realizada pelo
sistema, através de comandos dos usuários ou eventos do sistema. Já os requisitos
não funcionais (RNF) são as qualidades do software, como usabilidade,
desempenho, tecnologia. Podem ser classificados também quanto ao seu grau de
importância, em essencial, importante e desejável.
Essencial é um requisito imprescindível, que deve ser implementado. Sem
ele o sistema não entra em funcionamento.
Importante é um requisito que, caso não seja implementado, permite que o
sistema funcione, porém, de forma não satisfatória.
Desejável é um requisito que não compromete o funcionamento satisfatório
do sistema. Caso não haja tempo para implementa-lo, pode ser deixado para
próximas versões.
A seguir, uma descrição informal dos requisitos identificados:
• Um software de gerência de projetos deve fornecer meios para, no
mínimo, descrever o projeto, definir tarefas, indicar interdependência das
tarefas, alocar recursos, definir cronograma e custos associados.
• Deve ter boa usabilidade para proporcionar agilidade ao usuário planejar e
re-planejar as tarefas constantemente.
17
• Deve rodar em rede ou, ao menos, permitir a publicação de relatórios na
web, possibilitando que o cronograma e demais informações necessárias
para a execução sejam acessadas convenientemente por todos os
envolvidos no projeto.
• Também deve ter interface para que os usuários alimentem o sistema
informando o andamento de cada atividade e quais delas já foram
concluídas, dados essenciais para o gerente monitorar o andamento dos
projetos.
• É necessário que seja um software livre, eliminando assim os gastos com
licenças. É interessante também que o sistema seja multiplataforma, ou
seja, que possa ser executado em diferentes sistemas operacionais, como
Windows e Linux.
• Os dados deverão ser salvos, preferencialmente, em banco de dados livre
ou em arquivos formato XML, possibilitando futuras integrações. É
interessante também que a instalação e configuração da ferramenta seja
simples, não exigindo conhecimentos avançados de informática.
Serão levantados requisitos detalhados que a ferramenta de gerência de
projetos deve contemplar.
4.1 Requisitos Funcionais:
• RF01: Definição de descrição dos projetos (Essencial);
• RF02: Definição de tarefas (descrição e prazos) e suas interdependências
(Essencial);
• RF03: Definição e alocação de recursos para as tarefas (Essencial);
• RF04: Definição de custos para as tarefas (Essencial);
• RF05: Acompanhamento do andamento do projeto, permitindo a visualização
e manutenção dos estados das tarefas, seus prazos e custos (Essencial);
• RF06: Visualização de Gantt Chart (Importante);
• RF07: Visualização de Pert Chart (Desejável);
• RF08: Visualização do caminho crítico (Desejável);
• RF09: Suporte a WBS - Work Breakdown Structure (Desejável) ;
18
• RF10: Geração de relatório das atividades (Importante);
• RF11: Geração de relatório de custos (Importante);
4.2 Requisitos Não Funcionais:
• RNF01: Deve executar localmente (offline) (Importante);
• RNF02: Deve permitir execução em rede ou publicar relatórios web (
Importante);
• RNF03: Deve ser uma ferramenta intuitiva para demandar o menor custo (de
horas) possível no aprendizado de sua utilização (Importante);
• RNF04: Deve ter boa usabilidade de forma que a atividade de gerência tome
o menor tempo possível das pessoas para que não seja abandonada em prol
de atividades de produção (Desejável);
• RNF05: Deve ser implementado como software livre, disponibilizando o
código fonte. (Essencial);
• RNF06: Deve permitir a execução em nos sistemas operacionais Linux e
Windows. (Importante);
• RNF07: Os dados deverão ser armazenados em banco de dados livre ou em
arquivos XML (Essencial);
• RNF08: Suporte a língua portuguesa (Importante).
• RNF09: Instalação simples (Desejável).
Tendo definidos os requisitos para uma ferramenta de Gestão de Projetos,
iniciou-se uma pesquisa dos softwares existentes atualmente. Os softwares, Open
Workbench, GanttProject e dotProject, foram pesquisados verificando se os mesmos
atendiam os requisitos especificados.
19
5 Avaliação de ferramentas de Gestão de Projetos
5.1 Open Workbench
O software Open Workbench [OPE07], na versão 1.1.4, é uma ferramenta
para desktop, desenvolvido utilizando as linguagens C++ e Java, voltado apenas
para plataforma Windows. Foi desenvolvido pela empresa Niku e a partir de 2004
seu código fonte foi liberado. Hoje a empresa responsável pelo sistema é a
Computer Associates. Seu código fonte está disponível em Sourceforge, sob a
licença da proprietária e também através da licença pública Mozilla (MPL 1.1). Para
trabalhar com os fontes, é necessário possuir uma licença de utilização do software
Microsoft Visual Studio 2003 ou superior.
Os dados dos projetos são armazenados em sistema de arquivos
proprietários. Existe a opção de exportar e importar arquivos XML, porém, na última
versão testada, essa funcionalidade possuía alguns bugs. É uma ferramenta que
atende praticamente todas as atividades de gestão de projetos, incluindo seu
planejamento e controle. Infelizmente sua interface não é intuitiva, exigindo um
tempo dedicado ao aprendizado da ferramenta através de sua documentação.
O sistema possui traduções para línguas as línguas inglesa, francesa e
alemã, porém não suporta a língua portuguesa. Até o dia 12/01/2007, 176.383
downloads foram efetuados.
Tabela 1: Requisitos no software Open Benchwork
Requisito Atende Observações
RF01 Sim Permite a definição de descrição dos projetos. RF02 Sim Permite a definição de tarefas e suas interdependências. RF03 Sim Permite a definição e alocação de recursos para as tarefas. RF04 Sim Permite a definição de custos para as tarefas, através dos
custos dos recursos a ela associados. RF05 Sim Permite o acompanhamento do andamento do projeto, a
visualização e manutenção dos estados das tarefas, seus prazos e custos.
RF06 Sim Permite a visualização de Gantt Chart. RF07 Sim Permite a visualização de Pert Chart. RF08 Sim Permite a visualização do caminho crítico. RF09 Sim Possui suporte a WBS - Work Breakdown Structure. RF10 Não Não gera relatório de atividades.
20
RF11 Não Não gera relatório de custos. RNF01 Sim O sistema é executado localmente. RNF02 Não Não permite execução em rede nem publica relatórios web. RNF03 Não A interface não é intuitiva, exigindo esforços para o
aprendizado. RNF04 Sim Após o estudo e compreensão da interface, o usuário
consegue executar a maioria das operações com bastante agilidade.
RNF05 Sim O código fonte é disponibilizado, porem em linguagem proprietária.
RNF06 Não O sistema é executado apenas na plataforma Windows. RNF07 Não Os dados são armazenados em arquivos proprietários e a
opção para salvar em XML, na versão testada, não funcionava.
RNF08 Não Não possui tradução para a língua portuguesa. RNF09 Sim A instalação é simples, guiado através de um wizard.
5.2 GanttProject
O software GanttProject [GAN05] foi desenvolvido inicialmente por Alexandre
Thomas e Dmitry Barashev, através de seus estudos na universidade de Marne- la-
Vallee na França em Dezembro de 2002. É um software livre, sob a licença GPL
(General Public License), desenvolvido em Java e com código fonte disponível em
Sourceforge. Recentemente, um departamento do governo francês desejando
melhorar o sistema, contratou a empresa Actimage, para refinar o software e
incorporar novas funcionalidades.
Possui tradução em 13 idiomas, incluído o português. Até 12/01/2007,
699.943 downloads (incluindo versões anteriores) foram efetuados. A sua principal
característica é a excelente usabilidade, através de uma interface amigável e
intuitiva, proporcionando agilidade ao usuário. Permite alterar as tarefas
manipulando diretamente os gráficos, com recursos do tipo arrastar e soltar. Atente
grande parte das atividades relacionadas a gestão, porém não possuiu recursos
para gerenciar custos.
O Sistema é executado localmente e permite gerar relatórios em formato de
páginas web. Permite, com algumas limitações, trabalhar em rede, através de um
21
servidor WebDAV. Os projetos são salvos em arquivos XML..A versão testada foi a
2.0-pre1.
Tabela 2: Requisitos no software GanttProject
Requisito Atende Observações
RF01 Sim Permite a definição de descrição dos projetos. RF02 Sim Permite a definição de tarefas e suas interdependências. RF03 Sim Permite a definição e alocação de recursos para as tarefas. RF04 Não Não permite a definição de custos para as tarefas. RF05 Sim Permite o acompanhamento do andamento do projeto, a
visualização e manutenção dos estados das tarefas, seus prazos e custos.
RF06 Sim Permite a visualização de Gantt Chart. RF07 Sim Permite a visualização de Pert Chart. RF08 Sim Permite a visualização do caminho crítico. RF09 Nao Não possui suporte a WBS - Work Breakdown Structure. RF10 Sim Permite gerar relatório de atividades, através de arquivos
HTML, porem nao muito satisfatório. RF11 Não Não permite gerar relatório de custos. RNF01 Sim O sistema é executado localmente. RNF02 Sim Permite execução em rede através de um servidor WebDAV.
Permite exportar relatórios em formato de paginas web. RNF03 Sim A interface é bem intuitiva, não exigindo esforços para o
aprendizado. RNF04 Sim Tem excelente usabilidade a interface so sistema. RNF05 Sim O código fonte é disponibilizado, em linguagem Java. RNF06 Sim O sistema é executado em plataforma Windows e Linux. RNF07 Sim Os dados são armazenados em arquivos XML. RNF08 Sim Possui tradução para a língua portuguesa. RNF09 Sim A instalação é simples, guiado através de um wizard ou
executado diretamente sem instalação.
5.3 dotProject
O sistema dotProject [DOT07], iniciado em 2000, é desenvolvido e mantido
por voluntários, sem auxílio de nenhuma companhia. Até 12/01/2007, 423.702
downloads foram efetuados. A versão estável atual é a 2.0.4. É um software livre,
sob as licenças BSD e GPL (General Public License), desenvolvido em PHP e seu
código fonte esta disponível em Sourceforge. Possui traduções em mais de 20
22
idiomas, sendo português uma delas. Utiliza o conceito de modularidade, permitindo
que novas funcionalidades sejam desenvolvidas e facilmente acopladas ao sistema.
É um sistema para ser utilizado em rede, através de um browser web,
permitindo a interação simultânea de vários usuários e essa é sua principal
característica. Apesar disso, pode ser utilizado localmente. É executado em um
servidor web Apache e seus dados são armazenados em uma base de dados
MySQL. Atende todas as atividades de gestão de projetos. Seu ponto fraco é a
interface com pouca usabilidade, característica de sistemas em ambiente web. Sua
instalação também não é simples, exigindo instalar previamente o servidor web
Apache e a base de dados MySQL.
Tabela 3: Requisitos no software dotProject
Requisito Atende Observações
RF01 Sim Permite a definição de descrição dos projetos. RF02 Sim Permite a definição de tarefas e suas interdependências. RF03 Sim Permite a definição e alocação de recursos para as tarefas. RF04 Sim Permite a definição de custos para as tarefas, através dos
custos dos recursos a ela associados. RF05 Sim Permite o acompanhamento do andamento do projeto, a
visualização e manutenção dos estados das tarefas, seus prazos e custos.
RF06 Sim Permite a visualização de Gantt Chart. RF07 Sim Permite a visualização de Pert Chart. RF08 Sim Permite a visualização do caminho crítico. RF09 Nao Não possui suporte a WBS - Work Breakdown Structure. RF10 Sim Permite gerar relatório de atividades, entre outros. RF11 Não Não permite gerar relatório de custos. RNF01 Sim O sistema é executado localmente. RNF02 Sim Permite execução em rede através de ambiente web, esse é o
seu foco. RNF03 Sim A interface é bem intuitiva, não exigindo esforços para o
aprendizado. RNF04 Não Não apresenta usabilidade na interface, característica comum
em ambiente web. RNF05 Sim O código fonte é disponibilizado, em linguagem PHP. RNF06 Sim O sistema é executado em plataforma Windows e Linux,
utilizando um servidor Apache. RNF07 Sim Os dados são armazenados na base de dados MySQL. RNF08 Sim Possui tradução para a língua portuguesa. RNF09 Não A instalação não é simples, exigindo a instalação do servidor
web Apache e base de dados MySQL..
23
6 Proposta de solução para uma ferramenta de gestão de projetos
As três ferramentas avaliadas atendem bem as atividades de gestão de
projetos, cada uma com as suas particularidades. O desenvolvimento de uma
ferramenta que atenda tais requisitos exigiria muito tempo e recursos, extrapolando
o objetivo de um trabalho de graduação. A alternativa proposta foi o
desenvolvimento de novas funcionalidades em um dos softwares avaliados. Esta
opção apresenta a vantagem de desenvolver a partir de um código que
provavelmente foi testado, diminuindo as chances de erros de programação. Dentre
eles, o sistema GanttProject foi o que mais atendeu aos requisitos exigidos. Faltava
porem a atribuição de custos às tarefas e relatórios relacionados, bem como o
suporte ao WBS.
A seguir, é apresentada uma descrição mais detalhada do software
GanttProject, explorando um pouco mais suas funcionalidades.
24
6.1 GanttProject
6.1.1 Estado Atual
O software GanttProject destaca-se pela usabilidade de sua interface,
requisito importante para uma ferramenta de gestão de projeto. As principais
funcionalidades estão dispostas em uma barra horizontal superior. Na tela principal,
ao lado esquerdo, existem duas abas: Gantt, utilizada para estruturar e manejar
projetos e suas fases; e Recursos, utilizada para controle de recursos. No lado
direito está a área do gráfico de Gantt, que exibe as tarefas, suas relações e outras
informações. Todas as informações visíveis, tanto na área de abas, quanto na área
do gráfico, podem ser customizadas, permitindo ao usuário escolher quais campos
devem exibidos.
Figura 3 - Tela Inicial - Tarefas
25
A área Recursos é utilizada para o controle do pessoal envolvido no projeto.
Nome, telefone, e-mail, função no projeto e período de férias são algumas das
informações que podem ser cadastradas aos recursos. Um gráfico Gantt informa na
linha do tempo o período em que os recursos estão alocados para cada tarefa.
A função de uma pessoa é escolhida dentro de uma lista de funções, que
pode ser alimentada pelo ou usuário, ou carregada previamente durante a fase
inicial de criação do projeto selecionando alguma lista já disponível. Um exemplo
desse recurso é, o conjunto de funções para projetos de Desenvolvimento de
Software que inclui, entre outras, as funções de desenvolvedor, analista, designer
gráfico.
O conceito de recurso neste sistema aqui pode ser aplicado também para
recursos não humanos, como materiais e salas de reuniões.
Figura 4 - Tela principal de Recursos
26
Figura 5 - Tela de propriedades gerais de Recurso
Figura 6 - Tela de propriedades ferias de Recurso
27
A representação gráfica da utilização dos recursos permite a identificação de
conflitos entre alocação de tarefas. Caso o mesmo recurso tenha sido alocado para
tarefas que ocorram ao mesmo tempo, o conflito será exibido no gráfico como uma
barra vermelha. As férias são exibidas em uma barra amarela.
Figura 7 - Tela ilustrando a exibição de conflitos entre alocação de Recursos
28
Na área de tarefas, ativada através da aba Gantt, são exibidas as tarefas e
relações e outras informações. Dentre os atributos de uma tarefa, pode-se citar:
nome, prioridade, duração, porcentagem concluída, data de início e de fim. Tais
atributos podem ser definidos na tela de propriedades da tarefa. Nas demais abas
desta janela, é possível definir os recursos associados a tarefa, dependências, notas
e também colunas customizadas. As colunas customizadas são úteis para adicionar
informações às tarefas, como exemplo, um campo “Exige consultoria” do tipo
booleano. É possível também, ao associar um recurso, definir a sua função nesta
tarefa e também a sua porcentagem de alocação.
Figura 8 - Tela de propriedades gerais de Tarefa
Figura 9 - Tela de notas da Tarefa
29
Figura 10 - Tela de colunas customizadas da Tarefa
Figura 11 - Tela de recursos da Tarefa
As dependências entre tarefas podem ser criadas diretamente no gráfico,
especificando que o início de uma tarefa depende do final de outra. Existem distintos
tipos de dependências: Final-início (a tarefa só inicia após o final de outra tarefa) ,
Início-Fim (a tarefa termina antes do início de outra tarefa), Final-Final (a tarefa
termina junto com outra tarefa), Início-Início (a tarefa inicia junto com outra tarefa).
30
Figura 12 - Tela de dependências da Tarefa
O software permite geração de relatórios de um projeto em diversos formatos
, que incluem PDF, arquivo separado por vírgula, imagens JPG, PNG ou ainda em
páginas HTML.
O compartilhamento do projeto entre diversos usuários é possível através de
utilização de um servidor WebDAV [DAV06]. O servidor WebDAV é semelhante ao
um servidor de arquivos FTP, com a vantagem do recurso de bloqueio, que não
permite a edição simultânea de um arquivo por mais de um usuário. O software
suporta a utilização desse servidor, possibilitando importar e exportar arquivos.
Outra alternativa para o compartilhamento de informação é a exportação das
páginas HTML diretamente a um servidor FTP, permitindo o acompanhamento do
projeto por outros usuários.
Figura 13 - Tela importação de projeto de servidor WebDAV
31
Além das funcionalidades citadas, a ferramenta possui também recursos para
exportar e importar projetos em formato de arquivos separado por vírgulas e também
de arquivos Microsoft Project, proporcionando maior interoperabilidade. Outro
recurso interessante é a possibilidade de salvar estados do projeto e fazer
comparações entre estes estados, permitindo ao usuário avaliar as mudanças
ocorridas no cronograma.
6.1.2 Novas Funcionalidades
Como citado anteriormente, para a ferramenta de gestão proposta, faltavam
ainda os requisitos de definição de custos às tarefas, geração de relatório financeiro
e suporte ao WBS. Este último, requisito classificado como desejável, não será
implementado neste trabalho.
Para atender os requisitos, foram definidas as seguintes funcionalidades:
• Definição de um orçamento para uma tarefa
• Definição de custos para uma tarefa
Atributos de custo: data, valor, descrição.
• Manipulação de custos para uma tarefa: inclusão, exclusão.
• Exibição do total de custos para uma tarefa;
• Criação de um relatório exibindo o resumo de custos por tarefas;
• Criação de um relatório exibindo o detalhamento de custos por tarefas;
Quando se pretende adicionar novas funcionalidades a um sistema, modificando
o seu código, deve-se realizar um estudo prévio da sua documentação que pode
conter diagramas de seqüência, diagramas de classe ou casos de uso , textos
descritivos e outros. Neste caso, tais documentos não estavam disponíveis restando
apenas o código-fonte.
Uma alternativa para a falta de documentação quando se pretende trabalhar
em código fonte já existente é a engenharia reversa. “Engenharia reversa é o
processo de análise de um sistema para criar representações do sistema em um
nível mais elevado de abstração” [CHI90]. Considerando o ciclo de desenvolvimento
32
de software, esse processo pode ser visto como “voltar atrás no ciclo de
desenvolvimento” [WAR92].
Foi utilizado o software Enterprise Architect [ENT05] na tentativa de gerar
diagramas de classe a partir do código fonte. O resultado não foi satisfatório pois os
diagramas gerados eram muito complexos impossibilitando a sua compreensão. Ao
todo, são 527 classes distribuídas em 66 pacotes.
A solução para implementar as novas funcionalidades foi um amplo estudo do
código fonte. O código estava bem organizado, seguindo os padrões de
nomenclatura da linguagem Java, além de possuir comentários, características que
auxiliaram a compreensão do código.
O desenvolvimento das novas funcionalidades implicou na alteração de 19
classes e na inclusão de mais 35 arquivos, entre classes, arquivos de relatório e
bibliotecas.
Conforme os requisitos levantados, identificou-se a necessidade de relatórios
que permitissem o acompanhamento financeiro. Foram desenvolvidos dois
relatórios: um que exibisse o detalhamento dos custos das tarefas, apresentando...,
e outro que relata síntese financeira, exibindo o orçamento, os custos e o montante
disponível para cada tarefa.
Tais relatórios foram desenvolvidos utilizando as ferramentas JasperReports
[JAS05] e iReport [IRE05]. JasperReports é uma ferramenta de código aberto,em
Java, que permite a elaboração de relatórios e exportação dos mesmos em diversos
formatos como PDF, HTML, XML, entre outros. iReport também é uma ferramenta
de código aberto em Java, utilizada para projetar e construir, visualmente, relatórios
JasperReports. Ambas as ferramentas possuíam fácil adaptabilidade ao projeto por
serem desenvolvidas em Java. As bibliotecas dessas ferramentas foram adicionadas
ao código, logo, as mesmas não precisam ser instaladas para que os novos
relatórios sejam executados.
A seguir, serão apresentadas as interfaces com as novas funcionalidades.
33
Figura 14 - Tela de propriedades gerais de Tarefa, agora com campo orçamento
Figura 15 - Nova Tela de custos de Tarefa
34
Figura 16 - Nova Tela para execução de relatórios
Figura 17 - Relatório de Custos por Atividade
35
Figura 18 - Relatório Financeiro
36
7 Caso de uso da ferramenta
Neste capítulo, será apresentado um caso de uso da ferramenta. O cenário,
laboratório e recursos utilizados neste exemplo são fictícios.
Projeto Inclusão Digital Consciente
O objetivo do projeto é desenvolver uma ferramenta que sirva como um tutorial
passo a passo de utilização de ferramentas básicas do computador como:
• Editor de textos
• Planilhas
• Apresentações
• Navegadores web
• Busca de informações na web
• Utilização de e-mail
O publico alvo são alunos do ensino médio de colégios da rede pública,
previamente selecionados. Será desenvolvido por bolsistas da universidade, que
serão responsáveis também pelo treinamento dos professores dos colégios e pelas
aulas introdutórias.
37
Figura 19 - Definindo Projeto
Em seguida, foi definido o calendário, considerando sábado e domingo como
dias de folga.
Figura 20 - Definindo dias de folga
38
As seguintes tarefas foram definidas e agrupadas em módulos. Foram
definidos também seus orçamentos e custos:
Preparação
• Captação de recursos em empresas privadas e órgãos do governo
Início: 18/10/2006 Fim:
20/12/2006
• Seleção de bolsistas Início: 21/11/2006 Fim:
20/12/2006
• Seleção de colégios beneficiados Início: 22/11/2006 Fim:
20/12/2006
Módulo 1
• Busca de referências bibliográficas Início: 20/12/2006 Fim:
27/01/2007
• Levantamento de requisitos para a ferramenta Início: 29/01/2007 Fim:
17/02/2007
• Avaliação de ferramentas similares Início: 19/02/2007 Fim:
03/03/2007
Módulo 2
• Desenvolvimento da Ferramenta Início: 05/03/2007 Fim:
14/04/2007
Módulo 3
• Instalação da ferramenta nos colégios Início: 16/04/2007 Fim:
21/04/2007
• Treinamento dos professores Início: 23/04/2007 Fim:
05/05/2007
• Aulas introdutórias da nos colégios Início: 07/05/2007 Fim:
16/06/2007
39
Módulo 4
• Avaliação dos resultados obtidos nos colégios Início: 18/06/2007 Fim:
23/06/2007
• Elaboração e submissão de artigo na Semana da Extensão UFSC
Início: 25/06/2007 Fim:
14/07/2007
Figura 21 - Definindo Tarefa
Figura 22 - Definindo relações de tarefas
40
Figura 23 - Definindo custos de tarefa
Figura 24 - Visualização do Gráfico Gantt
41
Foram definidas as relações entre tarefas, utilizando o recurso de interface
arrastar-soltar.
Figura 25 - Associando tarefas utilizando recurso de interface
Foram definidos os seguintes recursos:
● Paulo Duarte. Função: Gerente de Projeto
● Júlio César Função Programador
● Ademir Macedo Função Programador
● Carla Florinda Função Instrutora
42
Estes recursos foram associados às tarefas.
Figura 26 - Associando recursos à Tarefa
Figura 27 - Visualização de Gráfico de Alocação de Recursos
43
O estado atual do projeto foi salvo. Para ilustrar este recurso, a tarefa inicial
de captação de recursos teve seu término adiado para 06/01/2007, utilizando para
isso o recurso de interface arrastar-e-soltar. Em conseqüência, todas as tarefas
seguintes foram igualmente adiadas. O gráfico ilustra a diferença entre os estados,
exibindo em vermelho a situação inicial. Esse recurso é extremamente interessante
pois permite ao usuário acompanhar as diferenças entre o planejamento e a
execução do projeto.
Figura 28 - Visualização de comparação de estados de projeto
44
A seguir, os gráficos do caminho crítico, ilustrado no gráfico pela cor vermelha
e barras em negrito.
Figura 29 - Visualização do caminho crítico
Figura 30 - Gráfico de PERT
45
Através do novo recurso de emissão de relatórios financeiros, foram gerados
os relatórios de Custo por Atividade e Resumo de Custos.
Figura 31 - Relatório de Custos por Atividade
46
Figura 32 - Relatório de Resumo de custos
Foram também publicados relatório web em um servidor FTP.
Figura 33 - Configurando Servidor FTP
47
Figura 34 - Relatório Web Gráfico de Gantt
Figura 35 - Relatório Web - Recursos
48
Dessa maneira, foi exemplificado um caso de uso da ferramenta, já com as
novas funcionalidades implementadas.
Figura 36 - Relatório Web - Tarefas
49
8 Conclusões
Uma ferramenta que permita planejar e acompanhar projetos foi proposta
neste trabalho. Os principais conceitos da gestão de projetos foram abordados,
servindo de base para o levantamento de requisitos para tal ferramenta.
Softwares livres, já existentes foram avaliados, confrontando-os com os
requisitos estabelecidos. Dentre eles, destacou-se o sistema GanttProject, com sua
excelente usabilidade, porem sem suporte ao controle financeiro. Tal carência foi
suprida mediante o desenvolvimento de novas funcionalidades.
Para o desenvolvimento das novas funcionalidades, foi necessário grande
esforço na tarefa de engenharia reversa, interpretando o código fonte, sendo este o
único recurso disponível. Posteriormente foi demonstrado um caso de uso da
ferramenta com as novas funcionalidades incorporadas
Com este trabalho, foi demonstrado que é possível desenvolver à partir do
código de um software livre existente, adaptando-o para atender às necessidades
desejadas. Os objetivos propostos foram atingidos com satisfação, resultando como
contribuição à comunidade de software livre, uma ferramenta gratuita, de código
livre, para a gestão de projetos, que pode ser utilizada por laboratórios de pesquisa,
pequenas empresas e usuários domésticos.
50
Trabalhos Futuros
O requisito proposto ao suporte ao WBS não foi implementado neste trabalho,
podendo ser implementado futuramente. É interessante também um estudo mais
aprofundado de outras ferramentas de engenharia reversa, visando a obtenção de
diagramas que facilitem o entendimento do código do sistema.
Identificou-se também durante a fase de testes, a necessidade de
detalhamento orçamentário. Atualmente, o orçamento é definido apenas em um
campo e seria interessante decompô-lo, permitindo fazer comparações entre o os
custos planejados no orçamento e os custos durante a execução. Identificou-se
também a necessidade de definir custos aos recursos, como o salário por exemplo.
Dessa maneira, o sistema poderia calcular automaticamente os custos totais no
projeto de acordo com o tempo de utilização dos recursos.
As funcionalidades desenvolvidas neste trabalho foram implementadas
diretamente no código do sistema. Como conseqüência, novas versões lançadas
pelos desenvolvedores do GanttProject não conterão tais recursos, sendo
necessário um novo estudo do código para implementá-las. Recomenda-se então,
estudar uma maneira de desenvolver o recurso como um plugin, que seja
desacoplado do código central, permitindo a facilmente adaptação a novas versões.
Essas alterações efetuadas no código foram enviadas para os líderes do projeto
GanttProject, existindo a possibilidade de as mesmas serem incorporadas às novas
versões.
51
Glossário Bug : é um erro no funcionamento comum de um software, também chamado de falha na
lógica programacional de um programa de computador, que pode causar falhas no objetivo
de uma ação na utilização de um programa de computador [WIK07i].
FTP : significa File Transfer Protocol (Protocolo de Transferência de Arquivos), e é uma
forma bastante rápida e versátil de transferir arquivos (também conhecidos como ficheiros),
sendo uma das mais usadas na internet [WIK06c].
GPL (General Public License) : é a designação da licença para software livre idealizada
por Richard Stallman no final da década de 1980, no âmbito do projecto GNU da Free
Software Foundation. A GPL é a licença com maior utilização por parte de projetos de
software livre, em grande parte devido à sua adoção para o Linux [WIK07h].
HTML : deriva da expressão Hyper Text Markup Language. Trata-se de uma linguagem de
marcação utilizada para produzir páginas na Internet. Esses códigos podem ser
interpretados pelos browsers para exibir as páginas da World Wide Web [WIK06b].
Licença BSD : representa uma família de licenças de software livre, de domínio público. O
original foi usado pela Distribuição de Software de Berkeley, um sistema operacional Unix,
para o qual a licença foi nomeada. A licença BSD tem sido referenciada como copycenter,
em comparação com o padrão copyrigth e copyleft de software livre: “Leve ao copycenter e
faça quantas cópias você quiser” [WIK07g].
Offline : empregado na área da informática, significa que o cliente não esta conectado a
uma rede.
Request For Comments : documentos que definem normas e protocolos para a Internet e
onde se fazem as discussões de nível técnico para a definição de novos protocolos [UFB98].
SourceForge : é um software de controle de desenvolvimento colaborativo. O sistema é
administrado pela VA Software. Ele prove uma interface para um diversificado serviço do
ciclo de vida no desenvolvimento de softwares e integra com um grande número de
aplicações de código aberto (como PostgreSQL e CVS). SourceForge.net é um localizador
centralizado de desenvolvedores de software para controlar e manter o desenvolvimento de
52
open sources, e atua como um repositório de código fonte. Um grande número de projetos
open source estão hospedados no site (ele atingiu 110.000 projetos e 1,2 milhões de
usuários registrados), embora contenha um grande número de projetos dormentes ele é de
longe o maior portal de código aberto [WIK07j].
Web (World Wide Web) : é uma rede de computadores na Internet que fornece informação
em forma de hipermídia, como vídeos, sons, hipertextos e figuras. Para ver a informação,
pode-se usar um software chamado navegador (browser) para descarregar informações
(chamadas "documentos" ou "páginas") de servidores de internet (ou "sites") e mostrá-los na
tela do usuário. O usuário pode então seguir os links na página para outros documentos ou
mesmo enviar informações de volta para o servidor para interagir com ele. O ato de seguir
links é comumente chamado de "navegar" ou "surfar" na Web [WIK07f].
WebDAV : ou Web-based Distributed Authoring and Versioning é um conjunto de extensões
para o HTTP (Hypertext Transfer Protocol) que permite que os usuários editem e gerenciam
cooperativamente arquivos em servidores Web remotos. Foi definido pelo IETF (Internet
Engineering Task Force) na RFC 2518.
Suas principais funcionalidades são:
- Controle de concorrência: previne que dois ou mais colaboradores escrevam no
mesmo recurso sem antes avaliar as mudanças. Para isso são utilizados permissões de
escrita compartidas e exclusividades de longa duração. Por se tratar de uma ferramenta de
internet, em que as conexões podem ser interrompidas arbitrariamente e também para
economizar recursos de rede, a duração das permissões é independente da conexão de
rede. Ou seja, é possível manter o bloqueio a um recurso mesmo não estando conectado ao
servidor.
- Propriedades: um arquivo XML permite o armazenamento de propriedade como por
exemplo a lista de autores dos recursos Web. Essas propriedades podem ser incluídas,
excluídas e procuradas utilizando o protocolo DASL (DAV Searching and Locating),
permitindo buscas de recursos Web baseadas em propriedades.
- Manipulação de namespace: o protocolo permite que os recursos sejam copiados
ou movidos. Coleções, que são similares a diretórios de arquivos, podem ser criados e
listados [DAV06].
Wizard : em português, Assistente, é um utilitário interativo existente em muitos softwares,
sua função é assessorar passo-a-passo o usuário à realizar uma tarefa.
53
XML : é um subtipo de SGML (Standard Generalized Markup Language - Linguagem
Padronizada de Marcação Genérica) capaz de descrever diversos tipos de dados. Seu
propósito principal é a facilidade de compartilhamento de informações através da Internet
[WIK06d].
54
Referências Bibliográficas
[KLE98] KLEIM, R & IRWIN, S.: Project Management Practitioner's Handbook. AMACOM Books, 1998.
[PMB04] PMI: Um Guia do Conjunto de Conhecimentos em Gerenciamento de Projetos (Guia PMBOK®). Project Management Institute, Terceira Edição, 2004.
[LEW99] LEWIS, P.: The Project Manager's Desk Reference A Comprehensive Guide to Project Planning, Scheduling, Evaluation, and Systems. McGraw-Hill, Segunda Edição, 1999.
[LAR00] LARMAN, C.: Utilizando UML e padrões: uma introdução à analise e ao projeto orientados a objetos. Trad. Luiz A. Meirelles Salgado - Porto Alegre, Bookman, 2000.
[KNU91] KNUDSON, J. & Bitz I.: Project Management. AMACOM Books, 1991.
[CHI90] CHIKOFSKY,J.: Reverse Engineering and Design Recovery: A Taxonomy in IEEE Software, IEEE Computer Society, 1990, pg 13–17.
[WAR92] WARDEN, R.: Software Reuse and Reverse Engineering in Practice. Londres, Chapman & Hall, 1992, pg 283–305
[GEN07]. GENESS. Disponível em: <http://www.geness.ufsc.br/> Acesso em: 10 jan 2007.
[GAN05] GANTTPROJECT. Disponível em: <http://sourceforge.net/projects/ganttproject/> Acesso em: 10 set 2005. [OPE07] OPEN Workbench. Disponível em: <http://www.openworkbench.org/>
Acesso em 10 jan 2007.
[DOT07] DOTPROJECT. Disponível em: <http://www.dotproject.net>
Acesso em: 10 jan 2007.
[JAS05] JASPER Reports. Disponível em: <http://jasperreports.sourceforge.net>
Acesso em: 11 nov 2005.
[IRE05] IREPORT. Disponível em: <http://www.jasperforge.org/sf/projects/ireport>
Acesso em: 11 nov 2005.
55
[ENT05] ENTERPRISE Architect. Disponível em:
<http://www.sparxsystems.com/products/ea.html> Acesso em: 09 out 2005.
Referências utilizadas no glossário:
[DAV06] WEBDAV. In: WebDAV Resources: Disponível em: <http://www.webdav.org/> Acesso em: 18 abr 2006.
[UFB98] REQUEST For Comments. In: Glossário LABCOMP – UFBA. Disponível em: <http://www.fis.ufba.br/labcomp/glossario.htm> Acesso em: 20 abr 2006.
[WIK06a] GANTT. In: Wikipédia: a enciclopédia livre. Disponível em: <http://pt.wikipedia.org/wiki/Gantt> Acesso em: 19 abr 2006.
[WIK06b] HTML. In: Wikipédia: a enciclopédia livre. Disponível em: <http://pt.wikipedia.org/wiki/HTML> Acesso em: 19 abr 2006.
[WIK06c] FTP. In: Wikipédia: a enciclopédia livre. Disponível em: <http://pt.wikipedia.org/wiki/FTP> Acesso em: 19 abr 2006.
[WIK06d] XML. In: Wikipédia: a enciclopédia livre. Disponível em: <http://pt.wikipedia.org/wiki/XML> Acesso em: 19 abr 2006.
[WIK07f] WEB. In: Wikipédia: a enciclopédia livre. Disponível em: <http://pt.wikipedia.org/wiki/Web> Acesso em: 16 jan 2007.
[WIK07g] BSD License. In: Wikipédia: a enciclopédia livre. Disponível em: <http://en.wikipedia.org/wiki/BSD_license> Acesso em: 16 jan 2007.
[WIK07h] GNU General Public License. In: Wikipédia: a enciclopédia livre. Disponível em: <http://pt.wikipedia.org/wiki/GNU_General_Public_License> Acesso em: 16 jan 2007.
[WIK07i] BUG. In: Wikipédia: a enciclopédia livre. Disponível em: <http://pt.wikipedia.org/wiki/Bug > Acesso em: 16 jan 2007.
[WIK07j] SOURCEFORGE. In: Wikipédia: a enciclopédia livre. Disponível em: <http://pt.wikipedia.org/wiki/SourceForge> Acesso em: 16 jan 2007.
56
Bibliografia
DUNCAN, W.: A Guide To The Project Management Body Of Knowledge. Charlotte, 1996.
pg67-70
FAYOL, H.: Administração industrial e geral, 8. ed. São Paulo: Atlas, 1970.
TAYLOR, F.: Princípios de administração científica. 7.ed. São Paulo: Atlas, 1971 MINTZBERG, H.: “The manager’s job: folklore and fact”. Harvard Business Review, p.163-176, Mar./Abr. 1990. REED, M.: The sociology of management. London: Harvester Wheatsheaf, 1989. CHARVAT, J.: “Project Management Methodologies: Selecting, Implementing, and Supporting Methodologies and Processes for Projects”. Canada, John Wiley & Sons, Ltd., 2003 MARTIN, P. & TATE, K.: Getting Started in Project Management, Canada, John Wiley & Sons, Ltd., 2001 BARBOSA, J. & TEIXEIRA R.: Gestão Estratégica nas empresas de pequeno e médio porte. Caderno de Pesquisas em Administração, São Paulo, v. 10, nº 3, p. 31-42, julho/setembro 2003. Disponivel em: <http://www.ead.fea.usp.br/cad-pesq/arquivos/v10n3art3.pdf>. Acesso em: 3 Jan 2006.
57
Apêndices
Classes e arquivos alterados
- 17 classes e 2 arquivos i18n
net.sourceforge.ganttproject.gui.GanttDialogProperties
net.sourceforge.ganttproject.gui.GanttTaskPropertiesBean
net.sourceforge.ganttproject.gui.taskproperties.CommonPanel
net.sourceforge.ganttproject.task.Task
net.sourceforge.ganttproject.task.TaskImpl
net.sourceforge.ganttproject.task.TaskNode
net.sourceforge.ganttproject.task.MutableTask
net.sourceforge.ganttproject.task.TaskProperties
net.sourceforge.ganttproject.GanttTreeTable
net.sourceforge.ganttproject.GanttTreeTableModel
net.sourceforge.ganttproject.Mediator
net.sourceforge.ganttproject.GanttProject
net.sourceforge.ganttproject.parser.TaskTagHandler
net.sourceforge.ganttproject.document.ProxyDocument
net.sourceforge.ganttproject.io.CSVOptions
net.sourceforge.ganttproject.io.GanttCSVExport
net.sourceforge.ganttproject.io.GanttXMLSaver
Arquivos i18n:
i18n.properties
i18n_pt_BR.properties
58
Classes e Arquivos criados
- 19 classes, 4 arquivos iReport, e 8 bibliotecas adicionadas
net.sourceforge.ganttproject.task.Cost
net.sourceforge.ganttproject.task.CostException
net.sourceforge.ganttproject.task.CostImpl
net.sourceforge.ganttproject.task.CostMutator
net.sourceforge.ganttproject.parser.CostTagHandler
net.sourceforge.ganttproject.task.CostsTaskCollection > inner MutableCostsTaskCollection
__ CostMutatorImpl
__ MutationCostInfo
net.sourceforge.ganttproject.task.CostsTaskCollectionImpl
net.sourceforge.ganttproject.gui.taskproperties.CostsPanel
net.sourceforge.ganttproject.gui.CostsTableModel
net.sourceforge.ganttproject.gui.GanttDialogCost
net.sourceforge.ganttproject.gui.report.ReportDialog
net.sourceforge.ganttproject.gui.report.ReportPanel
edu.ufsc.ganttproject.report.ReportCostDataSource
edu.ufsc.ganttproject.report.ReportCostResumeDataSource
edu.ufsc.ganttproject.report.CostsResumeReport
edu.ufsc.ganttproject.report.CostsTaskReport
Arquivos IReport:
edu.ufsc.ganttproject.report.CostsResumeReport.jrxml
edu.ufsc.ganttproject.report.CostsResumeReport.jasper
edu.ufsc.ganttproject.report.CostsTaskReport.jrxml
edu.ufsc.ganttproject.report.CostsTaskReport.jasper
Bibliotecas adicionadas para iReport:
commons-beanutils-1.5.jar
59
commons-collections-2.1.jar
commons-digester-1.7.jar
iReport.jar
itext-1.3.1.jar
jasperreports-1.1.0.jar
jdt-compiler.jar xml-apis.jar
60
Código Fonte
Classes e arquivos criados
net.sourceforge.ganttproject.task. Cost
package net.sourceforge.ganttproject.task;
import java.util.Date;
/**
* This class describes a cost.
* @author Luis Amaral Oct 24, 2005
*
*/
/**
* @author luisamaral
* Oct 24, 2005
*/
public interface Cost {
//String getId();
//void setId(String newId);
String getDescription();
void setDescription(String description);
Date getDate();
void setDate(Date date);
double getValue();
void setValue(double value);
String toString();
}
net.sourceforge.ganttproject.task. CostException
package net.sourceforge.ganttproject.task;
/**
* Exception to be thrown in several cases : A custom column already exists (and
* someone tries to add a nex one with the same name) A custom column does not
* exists (and someone tried to get it) A class mismatch.
*
* @author LH (Luis Amaral) Oct 24, 2005
*/
public class CostException extends Exception {
public static final int ALREADY_EXIST = 0;
public static final int DO_NOT_EXIST = 1;
public static final int CLASS_MISMATCH = 2;
/**
* Exception type.
*/
private int type = -1;
public CostException(int type, String message) {
super(message);
this.type = type;
}
public int getType() {
return type;
}
}
net.sourceforge.ganttproject.task CostImpl
package net.sourceforge.ganttproject.task;
import java.util.Date;
/**
* This class describes a ost.
* @author Luis Amaral Oct 24, 2005
*
*/
61
/**
* @author luisamaral
* Oct 24, 2005
*/
public class CostImpl implements Cost{
//private String id = null;
/**
* The column date.
*/
private Date date = null;
private double value = 0;
private String description = null;
/**
* Creates an instance of CustomColmn.
*/
public CostImpl() {
//this.id = id;
}
/**
* Creates an instance of CustomColmn with a name, a type (class) and a
* default value.
*
* @param colName
* The column name.
* @param colType
* The colmun type.
* @param colDefaultValue
* The default value.
*/
public CostImpl(Date date, String description, double value) {
this.date = date;
this.description = description;
this.value = value;
}
/*
public String getId() {
return id;
}
public void setId(String newId) {
id = newId;
}
*/
/**
* Returns the default value.
*
* @return The defautl value.
*/
public String getDescription() {
return description;
}
/**
* Sets the default value.
*
* @param defaultValue
* The default value to be set.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Returns the column name.
*
* @return The column name.
*/
public Date getDate() {
return date;
}
/**
* Sets the column name.
*
* @param name
* The column name to be set.
*/
public void setDate(Date date) {
this.date = date;
}
/**
* Returns the column type.
*
62
* @return The column type.
*/
public double getValue() {
return value;
}
/**
* Sets the column type.
*
* @param type
* The column type to be set.
*/
public void setValue(double value) {
this.value = value;
}
/**
* Returns a string representation of the CustomColumn.
*
* @return A string representation of the CustomColumn.
*/
public String toString() {
return this.date + " [" + this.description + "] <" + this.value + ">";
}
}
net.sourceforge.ganttproject.task. CostMutator
package net.sourceforge.ganttproject.task;
public interface CostMutator extends
MutableCostsTaskCollection {
void commit();
}
net.sourceforge.ganttproject.parser.CostTagHandler package net.sourceforge.ganttproject.parser;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttTaskRelationship;
import net.sourceforge.ganttproject.task.Cost;
import net.sourceforge.ganttproject.task.CostImpl;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskManager;
import net.sourceforge.ganttproject.task.dependency.TaskDependency;
import net.sourceforge.ganttproject.task.dependency.TaskDependencyException;
import net.sourceforge.ganttproject.task.dependency.constraint.FinishStartConstraintImpl;
import org.xml.sax.Attributes;
public class CostTagHandler implements TagHandler, ParsingListener {
private final TaskManager myTaskManager;
public CostTagHandler(ParsingContext context, TaskManager taskManager) {
myContext = context;
myTaskManager = taskManager;
}
/**
* @see net.sourceforge.ganttproject.parser.TagHandler#endElement(String,
* String, String)
*/
public void endElement(String namespaceURI, String sName, String qName) {
/*
* if ("dependencies".equals (qName)) { myDependenciesSectionStarted =
* false; }
*/
}
/**
* @see net.sourceforge.ganttproject.parser.TagHandler#startElement(String,
* String, String, Attributes)
*/
public void startElement(String namespaceURI, String sName, String qName,
Attributes attrs) {
/*
63
* if ("dependencies".equals (qName)) { myDependenciesSectionStarted =
* true; }
*/
if ("cost".equals(qName)) {
/*
* if (!myDependenciesSectionStarted) { throw new
* RuntimeException("Invalid file format. Found 'dependency' tag
* without prior 'dependencies' tag"); } else {
*/
loadCost(attrs);
}
}
public void parsingStarted() {
}
public void parsingFinished() {
for (int i = 0; i < getCosts().size(); i++) {
GanttCostStructure gcs = (GanttCostStructure) getCosts().get(i);
myTaskManager.getTask(gcs.taskID).getCostsTaskCollection().addCost(gcs.cost);
//System.out.println("Custo adicionado " + cost.getDescription() + " " + myTaskManager.getTask(getContext().getTaskID()).getName() );
}
}
protected void loadCost(Attributes attrs) {
if (attrs != null) {
Cost cost = new CostImpl();
String dateAsString = attrs.getValue("date");
String valueAsString = attrs.getValue("value");
try {
double value = Double.parseDouble(valueAsString);
cost.setValue(value);
} catch (NumberFormatException e) {
System.out.println("Erro no valor" + e.getMessage());
}
try {
Date date = new Date(Long.parseLong(dateAsString));
cost.setDate(date);
} catch (Exception e) {
System.out.println("Erro na data" + e.getMessage());
}
cost.setDescription(attrs.getValue("description"));
GanttCostStructure gcs = new GanttCostStructure(getContext().getTaskID(),cost);
getCosts().add(gcs);
}
}
private List getCosts() {
return myCosts;
}
private ParsingContext getContext() {
return myContext;
}
private List myCosts = new ArrayList();
private ParsingContext myContext;
private class GanttCostStructure {
public int taskID;
public Cost cost = null;
public GanttCostStructure(int taskID, Cost cost) {
this.taskID = taskID;
this.cost = cost;
}
}
}
net.sourceforge.ganttproject.task. CostsTaskCollection
package net.sourceforge.ganttproject.task;
import net.sourceforge.ganttproject.resource.ProjectResource;
import java.util.Collection;
/**
* @author lh
*/
64
public interface CostsTaskCollection extends MutableCostsTaskCollection {
Cost[] getCosts();
Collection getCollection();
double getTotalCosts();
Cost getCost(String costId);
CostMutator createMutator();
void clear();
}
interface MutableCostsTaskCollection {
void addCost(Cost cost);
void deleteCost(Cost cost);
//Cost[] getCachedCosts();
}
net.sourceforge.ganttproject.task. CostsTaskCollectionImpl
package net.sourceforge.ganttproject.task;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.ganttproject.resource.ProjectResource;
import net.sourceforge.ganttproject.resource.ResourceManager;
import net.sourceforge.ganttproject.roles.Role;
class CostsTaskCollectionImpl implements CostsTaskCollection {
private final Map myCosts = new HashMap();
private final TaskImpl myTask;
//private ResourceManager myResourceManager;
public CostsTaskCollectionImpl(TaskImpl task) {
myTask = task;
//myResourceManager = resourceManager;
}
private CostsTaskCollectionImpl(
CostsTaskCollectionImpl collection) {
myTask = collection.myTask;
Cost[] costs = collection.getCosts();
for (int i = 0; i < costs.length; i++) {
Cost next = costs[i];
Cost copy = new CostImpl();
copy.setDate(next.getDate());
copy.setDescription(next.getDescription());
copy.setValue(next.getValue());
addCost(copy);
}
}
public void clear() {
Cost[] costs = getCosts();
for (int i = 0; i < costs.length; i++) {
costs[i] = null;
}
}
public Cost[] getCosts() {
return (Cost[]) myCosts.values().toArray(
new Cost[myCosts.size()]);
}
public double getTotalCosts() {
double total = 0;
Cost[] costs = this.getCosts();
for (int i = 0; i < costs.length; i++) {
total+=costs[i].getValue();
}
return total;
}
public Collection getCollection() {
return myCosts.values();
}
65
public Cost getCost(String costId) {
return (Cost) myCosts.get(costId);
}
public CostMutator createMutator() {
return new CostMutatorImpl();
}
CostsTaskCollectionImpl copy() {
return new CostsTaskCollectionImpl(this);
}
public void deleteCost(Cost cost) {
myCosts.remove(cost.toString());
}
public void addCost(Cost cost) {
myCosts.put(cost.toString(), cost);
}
private Task getTask() {
return myTask;
}
private class CostMutatorImpl implements
CostMutator {
private Map myQueue = new HashMap();
public void addCost(Cost cost) {
myQueue.put(cost.toString(), new MutationCostInfo(cost, MutationCostInfo.ADD));
}
public void deleteCost(Cost cost) {
MutationCostInfo info = (MutationCostInfo) myQueue.get(cost);
if (info == null) {
myQueue.put(cost.toString(), new MutationCostInfo(cost,
MutationCostInfo.DELETE));
} else if (info.myOperation == MutationCostInfo.ADD) {
myQueue.remove(cost.toString());
}
}
public void commit() {
List mutations = new ArrayList(myQueue.values());
Collections.sort(mutations);
for (int i = 0; i < mutations.size(); i++) {
MutationCostInfo next = (MutationCostInfo) mutations.get(i);
switch (next.myOperation) {
case MutationCostInfo.DELETE: {
myCosts.remove(next.myCost.toString());
break;
}
case MutationCostInfo.ADD: {
//Cost result = next.myCost;
myCosts.put(next.myCost.toString(),next.myCost);
//Talvez seja necessário criar outro objeto
/*
* ResourceAssignment result = auxAddAssignment(next.myResource);
result.setLoad(next.myAssignment.getLoad());
result.setCoordinator(next.myAssignment.isCoordinator());
result.setRoleForAssignment(next.myAssignment
.getRoleForAssignment());
*/
}
default:
break;
}
}
}
}
private static class MutationCostInfo implements Comparable {
static final int ADD = 0;
static final int DELETE = 1;
private final Cost myCost;
private final int myOrder;
66
private static int ourOrder;
private int myOperation;
public MutationCostInfo(Cost cost, int operation) {
myCost = cost;
myOrder = ourOrder++;
myOperation = operation;
}
public boolean equals(Object o) {
boolean result = o instanceof MutationCostInfo;
if (result) {
result = myCost.equals(
((MutationCostInfo) o).myCost);
}
return result;
}
public int compareTo(Object o) {
if (!(o instanceof MutationCostInfo)) {
throw new IllegalArgumentException();
}
return myOrder - ((MutationCostInfo) o).myOrder;
}
}
}
net.sourceforge.ganttproject.gui. taskproperties.CostsPanel package net.sourceforge.ganttproject.gui.taskproperties;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Vector;
import java.text.NumberFormat;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JFormattedTextField;
import net.sourceforge.ganttproject.GanttProject;
import net.sourceforge.ganttproject.Mediator;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.CostsTaskCollection;
import net.sourceforge.ganttproject.gui.CostsTableModel;
import net.sourceforge.ganttproject.gui.GanttDialogCost;
import net.sourceforge.ganttproject.gui.ResourcesTableModel;
import net.sourceforge.ganttproject.gui.TestGanttRolloverButton;
import net.sourceforge.ganttproject.task.CostImpl;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.Cost;
import net.sourceforge.ganttproject.task.CostImpl;
import org.jdesktop.jdnc.JNTable;
import org.jdesktop.swing.JXTable;
import org.jdesktop.swing.decorator.AlternateRowHighlighter;
import org.jdesktop.swing.decorator.Highlighter;
import org.jdesktop.swing.decorator.HighlighterPipeline;
/**
* @author bbaranne Mar 4, 2005
*/
public class CostsPanel extends CommonPanel {
private static GanttLanguage language = GanttLanguage.getInstance();
private JPanel costsPanel;
private JXTable costsTable;
private JScrollPane costsScrollPane;
67
//private JTextField totalCostField = null;
private JFormattedTextField totalCostField = null;
private NumberFormat costFormat;
private JLabel totalCostLabel = null;
private CostsTableModel myCostTableModel = null;
//private Task myTask = null;
public CostsPanel(Task task) {
super(task);
//myTask = task;
//this.initComponents();
}
public JPanel getComponent() {
if (costsPanel == null) {
constructCostsPanel();
}
return costsPanel;
}
private void constructCostsPanel() {
CostsTaskCollection costs = getTask().getCostsTaskCollection();
costsPanel = new JPanel(new GridBagLayout());
myCostTableModel = new CostsTableModel(costs);
costsTable = new JXTable(myCostTableModel);
//setUpResourcesComboColumn(resourcesTable); // set column editor
//setUpCoordinatorBooleanColumn(resourcesTable);
//setUpRolesComboColumn(resourcesTable);
costsTable.setRowHeight(23);
costsTable.getColumnModel().getColumn(0).setPreferredWidth(80);
costsTable.getColumnModel().getColumn(1).setPreferredWidth(130);
costsTable.getColumnModel().getColumn(2).setPreferredWidth(310);
//costsTable.getColumnModel().getColumn(3).setPreferredWidth(200);
costsTable.setHighlighters(new HighlighterPipeline(
new Highlighter[] { new Highlighter(
new Color(0xFF, 0xFF, 0xFF), null) }));
costsScrollPane = new JScrollPane(costsTable);
costsScrollPane.setPreferredSize(new Dimension(520, 130));
JPanel secondResourcesScrollPane = new JPanel();
secondResourcesScrollPane.setBorder(new TitledBorder(
//new EtchedBorder(), GanttProject.correctLabel(getLanguage()
// .getText("human"))));
new EtchedBorder(), language.getText("costs")));
secondResourcesScrollPane.add(costsScrollPane);
JButton bremove = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/delete_16.gif")));
//bremove.setToolTipText(GanttProject.getToolTip(getLanguage().getText(
// "removeResources")));
bremove.setToolTipText(language.getText("deleteCost"));
bremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int[] selectedRow = costsTable.getSelectedRows();
for (int i = 0; i < selectedRow.length; ++i) {
if (costsTable.getModel().getValueAt(selectedRow[i],1) != null) {
try {
sumTotalCost(false,(NumberFormat.getCurrencyInstance().parse((String)costsTable.getModel().getValueAt(selectedRow[i],1))).doubleValue());
} catch (Exception e) {
System.out.println("Erro CostsPanel : " + e.getMessage());
}
costsTable.getModel().setValueAt(null, selectedRow[i],1);
}
}
}
});
secondResourcesScrollPane.add(bremove);
68
JButton buttonAdd = new JButton(language.getText("add"));
buttonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cost cost = new CostImpl();
GanttDialogCost d = new GanttDialogCost(Mediator
.getGanttProjectSingleton(), cost, getTableModel());
d.setVisible(true);
sumTotalCost(true,d.getValue());
}
});
secondResourcesScrollPane.add(buttonAdd);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.insets.right = 15;
gbc.insets.left = 10;
gbc.insets.top = 10;
gbc.weighty = 0;
JPanel commonFields = setupCommonFields(true);
addUsingGBL(costsPanel, commonFields, gbc, 0, 0, 1, 1);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 8;
gbc.gridheight = 1;
gbc.weighty = 1;
costsPanel.add(secondResourcesScrollPane, gbc);
//totalCostField = new JTextField();
costFormat = NumberFormat.getCurrencyInstance();
totalCostField = new JFormattedTextField(costFormat);
totalCostField.setColumns(15);
totalCostField.setEditable(false);
totalCostLabel = new JLabel();
totalCostLabel.setText(language.getText("total"));
showTotalCost();
JPanel totalCostPane = new JPanel();
totalCostPane.add(totalCostLabel);
totalCostPane.add(totalCostField);
gbc.gridx = 0;
gbc.gridy = 2;
costsPanel.add(totalCostPane, gbc);
}
public CostsTableModel getTableModel() {
return myCostTableModel;
}
private void sumTotalCost(boolean sum, double value) {
double actValue = ((Number)totalCostField.getValue()).doubleValue();
if (sum)
actValue+= value;
else
actValue-=value;
totalCostField.setValue(new Double(actValue));
}
private void showTotalCost() {
Cost[] costs = getTask().getCostsTaskCollection().getCosts();
double totalCosts = 0;
for (int i=0;i <costs.length;i++) {
totalCosts+=costs[i].getValue();
}
totalCostField.setValue(new Double(totalCosts));
}
}
net.sourceforge.ganttproject.gui. CostsTableModel
package net.sourceforge.ganttproject.gui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Date;
import java.util.Vector;
import java.text.NumberFormat;
import javax.swing.table.AbstractTableModel;
69
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.resource.HumanResource;
import net.sourceforge.ganttproject.resource.ProjectResource;
import net.sourceforge.ganttproject.roles.Role;
import net.sourceforge.ganttproject.task.Cost;
import net.sourceforge.ganttproject.task.CostsTaskCollection;
import net.sourceforge.ganttproject.task.CostMutator;;
public class CostsTableModel extends AbstractTableModel {
private static GanttLanguage language = GanttLanguage.getInstance();
final String[] columnNames = {language.getText("date"),
language.getText("value"),
language.getText("description"),
language.getText("id")};
//private final CostsTaskCollection myCostsTaskCollection;
private final List myCosts;
//private static final int MAX_ROW_COUNT = 100;
private final CostMutator myMutator;
private boolean isChanged = false;
public CostsTableModel(CostsTaskCollection costsTaskCollection) {
//myCostsTaskCollection = costsTaskCollection;
myCosts = new ArrayList(Arrays.asList(costsTaskCollection
.getCosts()));
myMutator = costsTaskCollection.createMutator();
}
/**
* Return the number of colums
*/
public int getColumnCount() {
return columnNames.length - 1;
}
/**
* Return the number of rows
*/
public int getRowCount() {
return myCosts.size() + 1;
}
/**
* Return the name of the column at col index
*/
public String getColumnName(int col) {
return columnNames[col];
}
/**
* Return the object a specify cell
*/
public Object getValueAt(int row, int col) {
Object result = null;
if (row >= 0) {
if (row < myCosts.size()) {
Cost cost = (Cost) myCosts
.get(row);
switch (col) {
case 3:
result = cost.toString();
break;
case 0:
result = new GanttCalendar(cost.getDate());
break;
case 1:
//result = new Double(cost.getValue());
result = NumberFormat.getCurrencyInstance().format(cost.getValue());
break;
case 2:
result = cost.getDescription();
break;
default:
result = "";
}
} else {
result = null;
}
} else {
throw new IllegalArgumentException("I can't return data in row="
70
+ row);
}
return result;
}
/*
* JTable uses this method to determine the default renderer/ editor for
* each cell. If we didn't implement this method, then the last column would
* contain text ("true"/"false"), rather than a check box.
*/
public Class getColumnClass(int c) {
switch (c) {
case 3:
case 0:
return Date.class;
case 1:
//return Double.class;
return String.class;
case 2:
return String.class;
default:
return String.class;
}
}
public boolean isCellEditable(int row, int col) {
return false;
}
/*
* Don't need to implement this method unless your table's data can change.
*/
public void setValueAt(Object value, int row, int col) {
if (value == null)
deleteCost(row);
else
createCost(value);
isChanged = true;
// fireTableCellUpdated(row, col);
}
private void deleteCost(int row) {
String costString = (String) getValueAt(row,3);
Iterator it = myCosts.iterator();
Cost cost = null;
while (it.hasNext() && cost == null){
cost = (Cost) it.next();
if (cost.toString().equals(costString))
it.remove();
else
cost = null;
}
myMutator.deleteCost(cost);
fireTableRowsDeleted(row,row);
}
private void createCost(Object value) {
if (value instanceof Cost) {
Cost newCost = (Cost) value;
myMutator.addCost(newCost);
myCosts.add(newCost);
fireTableRowsInserted(myCosts.size(), myCosts.size());
}
}
public List getCosts() {
return myCosts;
}
void commit() {
myMutator.commit();
}
public boolean isChanged() {
return isChanged;
}
}
net.sourceforge.ganttproject.gui. GanttDialogCost package net.sourceforge.ganttproject.gui;
import java.awt.BorderLayout;
import java.awt.CardLayout;
71
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.NumberFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.Mediator;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.Cost;
/**
* Dialog opened to create a new cost.
*
* @author lh Oct 24, 2005
*/
public class GanttDialogCost extends JDialog {
private static GanttLanguage language = GanttLanguage.getInstance();
/**
* Created Cost.
*/
private Cost cost = null;
private JPanel panelText = null;
private JTextArea textArea = null;
private JLabel labelDate = null;
private JButton buttonDate = null;
private JLabel labelName = null;
private JLabel labelValue = null;
private JTextField fieldValue = null;
private JLabel labelDescription = null;
private JButton buttonOK = null;
private JButton buttonCancel = null;
private GanttCalendar date = null;
private CostsTableModel myCostTableModel = null;
public GanttDialogCost(Frame parent, Cost cost, CostsTableModel myCostTableModel) {
super(parent, language.getText("newCost"), true);
this.cost = cost;
initComponents();
DialogAligner.center(this, parent);
this.myCostTableModel = myCostTableModel;
}
private void initComponents() {
GridBagConstraints constraints = new GridBagConstraints();
labelName = new JLabel(language.getText("date") + ": ");
labelValue = new JLabel(language.getText("value") + ": ");
labelDescription = new JLabel(language.getText("shortDescription") + ": ");
fieldValue = new JTextField();
fieldValue.setColumns(10);
// Text
textArea = new JTextArea();
72
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setColumns(25);
textArea.setRows(5);
JScrollPane jsp = new JScrollPane(textArea);
//panelText = new JPanel(new BorderLayout());
//panelText.add(jsp, BorderLayout.CENTER);
// Date
ImageIcon icon = new ImageIcon(getClass().getResource(
"/icons/calendar_16.gif"));
date = new GanttCalendar(new Date());
final GanttDialogDate dd = new GanttDialogDate(this, date, false);
labelDate = new JLabel(date.toString());
buttonDate = new JButton(icon);
buttonDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dd.show();
date = dd.getDate();
labelDate.setText(date.toString());
}
});
date = dd.getDate();
labelDate.setText(date.toString());
//comboTypes = new JComboBox(CostStorage.availableTypes);
buttonOK = new JButton();
buttonOK.setHorizontalTextPosition(SwingConstants.CENTER);
buttonOK.setText(language.getText("ok"));
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
ok();
}
});
getRootPane().setDefaultButton(buttonOK);
buttonCancel = new JButton();
buttonCancel.setHorizontalAlignment(SwingConstants.CENTER);
buttonCancel.setText(language.getText("cancel"));
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
cancel();
}
});
setResizable(false);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
closeDialog();
}
});
constraints.fill = GridBagConstraints.HORIZONTAL;
JPanel panelMain = new JPanel(new GridBagLayout());
// name
constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.insets = new Insets(5, 5, 10, 10);
panelMain.add(labelName, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
//constraints.gridwidth = 5;
//constraints.ipadx = 100;
panelMain.add(labelDate, constraints);
constraints.gridx = 2;
constraints.gridy = 0;
//constraints.gridwidth = 10;
//constraints.ipadx = 100;
//constraints.insets = new Insets(0, 5, 0, 5);
panelMain.add(buttonDate, constraints);
// type
constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 1;
constraints.insets = new Insets(5, 5, 10, 10);
panelMain.add(labelValue, constraints);
constraints.gridx = 1;
constraints.gridy = 1;
//constraints.gridwidth = 5;
73
panelMain.add(fieldValue, constraints);
// panelDefaultValue
constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 2;
constraints.insets = new Insets(5, 5, 10, 10);
panelMain.add(labelDescription, constraints);
constraints.gridx = 1;
constraints.gridy = 2;
//constraints.gridwidth = 5;
//panelMain.add(panelText, constraints);
panelMain.add(jsp, constraints);
// buttonOK
constraints = new GridBagConstraints();
constraints.gridx = 3;
constraints.gridy = 3;
constraints.anchor = java.awt.GridBagConstraints.EAST;
constraints.insets = new Insets(10, 10, 10, 10);
panelMain.add(buttonOK, constraints);
// buttonCancel
constraints = new java.awt.GridBagConstraints();
constraints.gridx = 4;
constraints.gridy = 3;
constraints.anchor = java.awt.GridBagConstraints.EAST;
constraints.insets = new Insets(10, 10, 10, 10);
panelMain.add(buttonCancel, constraints);
// All
getContentPane().setLayout(new GridBagLayout());
constraints = new java.awt.GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 5;
constraints.gridheight = 5;
constraints.fill = java.awt.GridBagConstraints.BOTH;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
getContentPane().add(panelMain, constraints);
pack();
} // TODO change the default value for custom columns.
private void ok() {
Mediator.getGanttProjectSingleton().setAskForSave(true);
try {
double value = (NumberFormat.getNumberInstance().parse(fieldValue.getText())).doubleValue();
if (fieldValue.getText().length() != 0) {
if (cost != null) {
cost.setDate(date.getTime());
cost.setValue(value);
cost.setDescription(textArea.getText());
myCostTableModel.setValueAt(cost,0,0);
}
closeDialog();
} else
fieldValue.requestFocus();
} catch (Exception e) {
fieldValue.requestFocus();
}
}
public double getValue() {
if (fieldValue.getText().length() == 0)
return 0;
else
return Double.parseDouble(fieldValue.getText());
}
private void cancel() {
fieldValue.setText(""); //its important to the CostPanel -> totalCosts
closeDialog();
}
private void closeDialog() {
setVisible(false);
dispose();
}
}
net.sourceforge.ganttproject.gui. report.ReportDialog
package net.sourceforge.ganttproject.gui.report;
import javax.swing.Box;
74
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import net.sourceforge.ganttproject.GanttProject;
import net.sourceforge.ganttproject.gui.GeneralDialog;
import net.sourceforge.ganttproject.gui.about.AboutAuthorPanel;
import net.sourceforge.ganttproject.gui.about.AboutJavaInfosPanel;
import net.sourceforge.ganttproject.gui.about.AboutLibraryPanel;
import net.sourceforge.ganttproject.gui.about.AboutLicensePanel;
import net.sourceforge.ganttproject.gui.about.AboutPanel;
import net.sourceforge.ganttproject.gui.options.TopPanel;
import net.sourceforge.ganttproject.language.GanttLanguage;
/**
* @author Luis Henrique
*/
public class ReportDialog extends GeneralDialog {
/** Constructor. */
public ReportDialog(GanttProject parent) {
super(parent, GanttProject.correctLabel(GanttLanguage.getInstance()
.getText("report"))
+ " - Ganttproject", false, new ReportPanel(parent));
// hide the cancel button
cancelButton.hide();
}
/** Callback for the tree selection event. */
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) (e.getPath()
.getLastPathComponent());
String sNode = (String) (node.getUserObject());
// - ask the settingPanel if parameters are changed
// boolean bHasChange = settingPanel.applyChanges(true); //no change to
// do on this panel
// - remove the settingPanel
mainPanel2.remove(0);
// - Create the new panel
if (sNode.equals(language.getText("report")))
settingPanel = new ReportPanel(appli);
//else if (sNode.equals(GanttProject.correctLabel(language.getText("about"))))
// settingPanel = new AboutPanel(appli);
Box vb = Box.createVerticalBox();
vb.add(new TopPanel(" " + settingPanel.getTitle(), settingPanel
.getComment()));
vb.add(settingPanel);
settingPanel.initialize();
// - add the settingPanel into the main Panel
mainPanel2.add(vb, 0);
mainPanel2.repaint();
mainPanel2.validate(); // valide the changes
}
/** Coonstruct the menu settings. */
public void constructSections() {
DefaultMutableTreeNode reportNode = addObject(language
.getText("report"), null);
//DefaultMutableTreeNode aboutNode = addObject(GanttProject
// .correctLabel(language.getText("about")), null);
}
}
net.sourceforge.ganttproject.gui. report.ReportPanel
package net.sourceforge.ganttproject.gui.report;
import edu.ufsc.ganttproject.report.ReportCostDataSource;
import edu.ufsc.ganttproject.report.ReportCostResumeDataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.IOException;
import java.awt.event.ActionEvent;
75
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.sourceforge.ganttproject.GanttProject;
import net.sourceforge.ganttproject.GanttSplash;
import net.sourceforge.ganttproject.gui.GanttDialogInfo;
import net.sourceforge.ganttproject.gui.options.GeneralOptionPanel;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskManager;
import net.sourceforge.ganttproject.util.BrowserControl;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
/**
* @author athomas The About panel.
*/
public class ReportPanel extends GeneralOptionPanel {
private static final String rel1 = "/edu/ufsc/ganttproject/report/TaskReport.jasper";
private static final String rel2 = "edu/ufsc/ganttproject/report/CostsTaskReport.jasper";
private static final String costResumeRel = "/edu/ufsc/ganttproject/report/CostsResumeReport.jasper";
private GanttProject gp = null;
/** Constructor. */
public ReportPanel(GanttProject parent) {
super(GanttProject.correctLabel(GanttLanguage.getInstance().getText(
"report")), GanttLanguage.getInstance().getText("settingsReport")
, parent);
gp = parent;
vb.add(new JPanel());
JButton bViewReport = new JButton(GanttProject.correctLabel(language
.getText("reportTaskCost")), new ImageIcon(getClass().getResource(
"/icons/settings_16.gif")));
bViewReport.setToolTipText(GanttProject.getToolTip(language
.getText("reportTaskCost"))); // add a simple tool tip
// text :)
bViewReport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showTaskCostReport();
}
});
vb.add(bViewReport);
JButton bViewCostResumeReport = new JButton(GanttProject.correctLabel(language
.getText("reportCostResume")), new ImageIcon(getClass().getResource(
"/icons/settings_16.gif")));
bViewCostResumeReport.setToolTipText(GanttProject.getToolTip(language
.getText("reportCostResume"))); // add a simple tool tip
// text :)
bViewCostResumeReport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCostResumeReport();
}
});
vb.add(bViewCostResumeReport);
applyComponentOrientation(language.getComponentOrientation());
}
private void createTaskCollection(Task task, int depth, ArrayList arrayList) {
Task[] nestedTasks = task.getManager().getTaskHierarchy()
.getNestedTasks(task);
76
for (int i = 0; i < nestedTasks.length; i++) {
Task next = nestedTasks[i];
//String nextSerialized = serializeTask(next, depth);
//out.append(nextSerialized);
arrayList.add(next);
createTaskCollection(next, depth + 1, arrayList);
}
}
private void showTaskCostReport() {
if (!gp.getTaskManager().getTasksCollection().isEmpty()) {
ArrayList alTasks = new ArrayList(gp.getTaskManager().getTasksCollection().size());
createTaskCollection(gp.getTaskManager().getRootTask(), 0, alTasks);
//ReportCostDataSource ds = new ReportCostDataSource(gp.getTaskManager().getTasksCollection());
ReportCostDataSource ds = new ReportCostDataSource(alTasks);
// Parametros do relatorio
Map parametros = new HashMap();
parametros.put("pathSubRel",rel2);
JasperViewer viewer = null;
try {
JasperPrint impressao = JasperFillManager.fillReport(getClass().getResourceAsStream(rel1), parametros, ds);
//exibe o relatório
viewer = new JasperViewer(impressao, false);
viewer.show();
} catch (JRException jre) {
System.out.println("Erro: " + jre.getMessage());
}
} else {
GanttDialogInfo gdi = new GanttDialogInfo(null,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION,
language.getText("msg21"), language.getText("error"));
gdi.show();
}
}
private void showCostResumeReport() {
if (!gp.getTaskManager().getTasksCollection().isEmpty()) {
ArrayList alTasks = new ArrayList(gp.getTaskManager().getTasksCollection().size());
createTaskCollection(gp.getTaskManager().getRootTask(), 0, alTasks);
//ReportCostDataSource ds = new ReportCostDataSource(gp.getTaskManager().getTasksCollection());
ReportCostResumeDataSource ds = new ReportCostResumeDataSource(alTasks);
// Parametros do relatorio
//Map parametros = new HashMap();
//parametros.put("pathSubRel",rel2);
JasperViewer viewer = null;
try {
JasperPrint impressao = JasperFillManager.fillReport(getClass().getResourceAsStream(costResumeRel), null, ds);
//exibe o relatório
viewer = new JasperViewer(impressao, false);
viewer.show();
} catch (JRException jre) {
System.out.println("Erro: " + jre.getMessage());
}
} else {
77
GanttDialogInfo gdi = new GanttDialogInfo(null,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION,
language.getText("msg21"), language.getText("error"));
gdi.show();
}
}
/** This method check if the value has changed, and assk for commit changes. */
public boolean applyChanges(boolean askForApply) {
// nothing to do :)
return bHasChange = false;
}
/** Initialize the component. */
public void initialize() {
// nothing to do :)
}
}
edu.ufsc.ganttproject.report. ReportCostDataSource
package edu.ufsc.ganttproject.report;
import java.util.Iterator;
import java.util.List;
import java.util.Collection;
import net.sourceforge.ganttproject.task.Task;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
public class ReportCostDataSource implements JRDataSource {
private Iterator itrTasks;
private Object valorAtual;
private boolean irParaProximoAluno = true;
/**
* @param campos
* @param itr
*/
public ReportCostDataSource(Collection lista) {
super();
this.itrTasks = lista.iterator();
}
/*
* (non-Javadoc)
*
* @see net.sf.jasperreports.engine.JRDataSource#next()
*/
public boolean next() throws JRException {
valorAtual = itrTasks.hasNext() ? itrTasks.next() : null;
irParaProximoAluno = (valorAtual != null);
return irParaProximoAluno;
}
/*
* (non-Javadoc)
*
* @see net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf.jasperreports.engine.JRField)
*/
public Object getFieldValue(JRField campo) throws JRException {
Object valor = null;
Task task = (Task) valorAtual;
//teste
if ("name".equals(campo.getName())) {
valor = task.getName();
} else if ("CostsList".equals(campo.getName())) {
valor = new JRBeanCollectionDataSource(task.getCostsTaskCollection().getCollection());
} else if ("start".equals(campo.getName())) {
valor = task.getStart().getTime();
} else if ("end".equals(campo.getName())) {
valor = task.getEnd().getTime();
} else if ("budget".equals(campo.getName())) {
valor = new Double(task.getBudget());
} else if ("totalCosts".equals(campo.getName())) {
valor = new Double(task.getCostsTaskCollection().getTotalCosts());
} else if ("remain".equals(campo.getName())) {
valor = new Double(task.getBudget() - task.getCostsTaskCollection().getTotalCosts());
78
}
return valor;
}
}
edu.ufsc.ganttproject.report. ReportCostResumeDataSource
package edu.ufsc.ganttproject.report;
import java.util.Iterator;
import java.util.Collection;
import net.sourceforge.ganttproject.task.Task;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
public class ReportCostResumeDataSource implements JRDataSource {
private Iterator itrTasks;
private Object valorAtual;
private boolean irParaProximoAluno = true;
/**
* @param campos
* @param itr
*/
public ReportCostResumeDataSource(Collection lista) {
super();
this.itrTasks = lista.iterator();
}
/*
* (non-Javadoc)
*
* @see net.sf.jasperreports.engine.JRDataSource#next()
*/
public boolean next() throws JRException {
valorAtual = itrTasks.hasNext() ? itrTasks.next() : null;
irParaProximoAluno = (valorAtual != null);
return irParaProximoAluno;
}
/*
* (non-Javadoc)
*
* @see net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf.jasperreports.engine.JRField)
*/
public Object getFieldValue(JRField campo) throws JRException {
Object valor = null;
Task task = (Task) valorAtual;
if ("name".equals(campo.getName())) {
valor = task.getName();
} else if ("start".equals(campo.getName())) {
valor = task.getStart().getTime();
} else if ("end".equals(campo.getName())) {
valor = task.getEnd().getTime();
} else if ("budget".equals(campo.getName())) {
valor = new Double(task.getBudget());
} else if ("totalCosts".equals(campo.getName())) {
valor = new Double(task.getCostsTaskCollection().getTotalCosts());
} else if ("remain".equals(campo.getName())) {
valor = new Double(task.getBudget() - task.getCostsTaskCollection().getTotalCosts());
}
return valor;
}
}
edu.ufsc.ganttproject.report. CostsResumeReport
package edu.ufsc.ganttproject.report;
/*
* Generated by JasperReports - 03/02/06 17:39
*/
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.fill.*;
import java.util.*;
import java.math.*;
import java.text.*;
import java.io.*;
import java.net.*;
import java.util.*;
79
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.*;
/**
*
*/
public class CostsResumeReport extends JREvaluator
{
/**
*
*/
private JRFillParameter parameter_REPORT_RESOURCE_BUNDLE = null;
private JRFillParameter parameter_REPORT_CONNECTION = null;
private JRFillParameter parameter_REPORT_PARAMETERS_MAP = null;
private JRFillParameter parameter_IS_IGNORE_PAGINATION = null;
private JRFillParameter parameter_REPORT_CLASS_LOADER = null;
private JRFillParameter parameter_REPORT_VIRTUALIZER = null;
private JRFillParameter parameter_REPORT_LOCALE = null;
private JRFillParameter parameter_REPORT_DATA_SOURCE = null;
private JRFillParameter parameter_REPORT_SCRIPTLET = null;
private JRFillParameter parameter_REPORT_MAX_COUNT = null;
private JRFillField field_totalCosts = null;
private JRFillField field_start = null;
private JRFillField field_end = null;
private JRFillField field_budget = null;
private JRFillField field_remain = null;
private JRFillField field_name = null;
private JRFillVariable variable_PAGE_NUMBER = null;
private JRFillVariable variable_COLUMN_NUMBER = null;
private JRFillVariable variable_REPORT_COUNT = null;
private JRFillVariable variable_PAGE_COUNT = null;
private JRFillVariable variable_COLUMN_COUNT = null;
/**
*
*/
public void customizedInit(
Map pm,
Map fm,
Map vm
)
{
initParams(pm);
initFields(fm);
initVars(vm);
}
/**
*
*/
private void initParams(Map pm)
{
parameter_REPORT_RESOURCE_BUNDLE = (JRFillParameter)pm.get("REPORT_RESOURCE_BUNDLE");
parameter_REPORT_CONNECTION = (JRFillParameter)pm.get("REPORT_CONNECTION");
parameter_REPORT_PARAMETERS_MAP = (JRFillParameter)pm.get("REPORT_PARAMETERS_MAP");
parameter_IS_IGNORE_PAGINATION = (JRFillParameter)pm.get("IS_IGNORE_PAGINATION");
parameter_REPORT_CLASS_LOADER = (JRFillParameter)pm.get("REPORT_CLASS_LOADER");
parameter_REPORT_VIRTUALIZER = (JRFillParameter)pm.get("REPORT_VIRTUALIZER");
parameter_REPORT_LOCALE = (JRFillParameter)pm.get("REPORT_LOCALE");
parameter_REPORT_DATA_SOURCE = (JRFillParameter)pm.get("REPORT_DATA_SOURCE");
parameter_REPORT_SCRIPTLET = (JRFillParameter)pm.get("REPORT_SCRIPTLET");
parameter_REPORT_MAX_COUNT = (JRFillParameter)pm.get("REPORT_MAX_COUNT");
}
/**
*
*/
private void initFields(Map fm)
{
field_totalCosts = (JRFillField)fm.get("totalCosts");
field_start = (JRFillField)fm.get("start");
field_end = (JRFillField)fm.get("end");
field_budget = (JRFillField)fm.get("budget");
field_remain = (JRFillField)fm.get("remain");
80
field_name = (JRFillField)fm.get("name");
}
/**
*
*/
private void initVars(Map vm)
{
variable_PAGE_NUMBER = (JRFillVariable)vm.get("PAGE_NUMBER");
variable_COLUMN_NUMBER = (JRFillVariable)vm.get("COLUMN_NUMBER");
variable_REPORT_COUNT = (JRFillVariable)vm.get("REPORT_COUNT");
variable_PAGE_COUNT = (JRFillVariable)vm.get("PAGE_COUNT");
variable_COLUMN_COUNT = (JRFillVariable)vm.get("COLUMN_COUNT");
}
/**
*
*/
public Object evaluate(int id) throws Throwable
{
Object value = null;
switch (id)
{
case 0 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 1 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 2 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 3 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 4 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 5 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 6 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 7 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 8 :
{
value = (java.lang.String)(((java.lang.String)field_name.getValue()));
break;
}
case 9 :
{
value = (java.util.Date)(((java.util.Date)field_start.getValue()));
break;
}
case 10 :
{
value = (java.lang.Double)(((java.lang.Double)field_budget.getValue()));
break;
}
case 11 :
{
value = (java.util.Date)(((java.util.Date)field_end.getValue()));
break;
}
case 12 :
81
{
value = (java.lang.Double)(((java.lang.Double)field_remain.getValue()));
break;
}
case 13 :
{
value = (java.lang.Double)(((java.lang.Double)field_totalCosts.getValue()));
break;
}
default :
{
}
}
return value;
}
/**
*
*/
public Object evaluateOld(int id) throws Throwable
{
Object value = null;
switch (id)
{
case 0 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 1 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 2 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 3 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 4 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 5 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 6 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 7 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 8 :
{
value = (java.lang.String)(((java.lang.String)field_name.getOldValue()));
break;
}
case 9 :
{
value = (java.util.Date)(((java.util.Date)field_start.getOldValue()));
break;
}
case 10 :
{
value = (java.lang.Double)(((java.lang.Double)field_budget.getOldValue()));
break;
}
case 11 :
{
value = (java.util.Date)(((java.util.Date)field_end.getOldValue()));
break;
}
82
case 12 :
{
value = (java.lang.Double)(((java.lang.Double)field_remain.getOldValue()));
break;
}
case 13 :
{
value = (java.lang.Double)(((java.lang.Double)field_totalCosts.getOldValue()));
break;
}
default :
{
}
}
return value;
}
/**
*
*/
public Object evaluateEstimated(int id) throws Throwable
{
Object value = null;
switch (id)
{
case 0 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 1 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 2 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 3 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 4 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 5 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 6 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 7 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 8 :
{
value = (java.lang.String)(((java.lang.String)field_name.getValue()));
break;
}
case 9 :
{
value = (java.util.Date)(((java.util.Date)field_start.getValue()));
break;
}
case 10 :
{
value = (java.lang.Double)(((java.lang.Double)field_budget.getValue()));
break;
}
case 11 :
{
value = (java.util.Date)(((java.util.Date)field_end.getValue()));
break;
}
83
case 12 :
{
value = (java.lang.Double)(((java.lang.Double)field_remain.getValue()));
break;
}
case 13 :
{
value = (java.lang.Double)(((java.lang.Double)field_totalCosts.getValue()));
break;
}
default :
{
}
}
return value;
}
}
edu.ufsc.ganttproject.report.CostsTaskReport
package edu.ufsc.ganttproject.report;
/*
* Generated by JasperReports - 03/02/06 15:43
*/
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.fill.*;
import java.util.*;
import java.math.*;
import java.text.*;
import java.io.*;
import java.net.*;
import java.util.*;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.*;
/**
*
*/
public class CostsTaskReport extends JREvaluator
{
/**
*
*/
private JRFillParameter parameter_REPORT_RESOURCE_BUNDLE = null;
private JRFillParameter parameter_REPORT_CONNECTION = null;
private JRFillParameter parameter_REPORT_PARAMETERS_MAP = null;
private JRFillParameter parameter_IS_IGNORE_PAGINATION = null;
private JRFillParameter parameter_REPORT_CLASS_LOADER = null;
private JRFillParameter parameter_REPORT_VIRTUALIZER = null;
private JRFillParameter parameter_REPORT_LOCALE = null;
private JRFillParameter parameter_REPORT_DATA_SOURCE = null;
private JRFillParameter parameter_REPORT_SCRIPTLET = null;
private JRFillParameter parameter_REPORT_MAX_COUNT = null;
private JRFillField field_value = null;
private JRFillField field_description = null;
private JRFillField field_date = null;
private JRFillVariable variable_PAGE_NUMBER = null;
private JRFillVariable variable_COLUMN_NUMBER = null;
private JRFillVariable variable_REPORT_COUNT = null;
private JRFillVariable variable_PAGE_COUNT = null;
private JRFillVariable variable_COLUMN_COUNT = null;
/**
*
*/
public void customizedInit(
Map pm,
Map fm,
Map vm
)
{
initParams(pm);
initFields(fm);
initVars(vm);
}
84
/**
*
*/
private void initParams(Map pm)
{
parameter_REPORT_RESOURCE_BUNDLE = (JRFillParameter)pm.get("REPORT_RESOURCE_BUNDLE");
parameter_REPORT_CONNECTION = (JRFillParameter)pm.get("REPORT_CONNECTION");
parameter_REPORT_PARAMETERS_MAP = (JRFillParameter)pm.get("REPORT_PARAMETERS_MAP");
parameter_IS_IGNORE_PAGINATION = (JRFillParameter)pm.get("IS_IGNORE_PAGINATION");
parameter_REPORT_CLASS_LOADER = (JRFillParameter)pm.get("REPORT_CLASS_LOADER");
parameter_REPORT_VIRTUALIZER = (JRFillParameter)pm.get("REPORT_VIRTUALIZER");
parameter_REPORT_LOCALE = (JRFillParameter)pm.get("REPORT_LOCALE");
parameter_REPORT_DATA_SOURCE = (JRFillParameter)pm.get("REPORT_DATA_SOURCE");
parameter_REPORT_SCRIPTLET = (JRFillParameter)pm.get("REPORT_SCRIPTLET");
parameter_REPORT_MAX_COUNT = (JRFillParameter)pm.get("REPORT_MAX_COUNT");
}
/**
*
*/
private void initFields(Map fm)
{
field_value = (JRFillField)fm.get("value");
field_description = (JRFillField)fm.get("description");
field_date = (JRFillField)fm.get("date");
}
/**
*
*/
private void initVars(Map vm)
{
variable_PAGE_NUMBER = (JRFillVariable)vm.get("PAGE_NUMBER");
variable_COLUMN_NUMBER = (JRFillVariable)vm.get("COLUMN_NUMBER");
variable_REPORT_COUNT = (JRFillVariable)vm.get("REPORT_COUNT");
variable_PAGE_COUNT = (JRFillVariable)vm.get("PAGE_COUNT");
variable_COLUMN_COUNT = (JRFillVariable)vm.get("COLUMN_COUNT");
}
/**
*
*/
public Object evaluate(int id) throws Throwable
{
Object value = null;
switch (id)
{
case 0 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 1 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 2 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 3 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 4 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 5 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 6 :
85
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 7 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 8 :
{
value = (java.util.Date)(((java.util.Date)field_date.getValue()));
break;
}
case 9 :
{
value = (java.lang.String)(((java.lang.String)field_description.getValue()));
break;
}
case 10 :
{
value = (java.lang.Double)(((java.lang.Double)field_value.getValue()));
break;
}
default :
{
}
}
return value;
}
/**
*
*/
public Object evaluateOld(int id) throws Throwable
{
Object value = null;
switch (id)
{
case 0 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 1 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 2 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 3 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 4 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 5 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 6 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 7 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 8 :
{
value = (java.util.Date)(((java.util.Date)field_date.getOldValue()));
break;
}
case 9 :
{
86
value = (java.lang.String)(((java.lang.String)field_description.getOldValue()));
break;
}
case 10 :
{
value = (java.lang.Double)(((java.lang.Double)field_value.getOldValue()));
break;
}
default :
{
}
}
return value;
}
/**
*
*/
public Object evaluateEstimated(int id) throws Throwable
{
Object value = null;
switch (id)
{
case 0 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 1 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 2 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 3 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 4 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 5 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 6 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 7 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 8 :
{
value = (java.util.Date)(((java.util.Date)field_date.getValue()));
break;
}
case 9 :
{
value = (java.lang.String)(((java.lang.String)field_description.getValue()));
break;
}
case 10 :
{
value = (java.lang.Double)(((java.lang.Double)field_value.getValue()));
break;
}
default :
{
}
}
return value;
}
87
}
edu.ufsc.ganttproject.report. CostsResumeReport.jrxml
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Created with iReport - A designer for JasperReports -->
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport
name="CostsResumeReport"
columnCount="1"
printOrder="Vertical"
orientation="Portrait"
pageWidth="595"
pageHeight="842"
columnWidth="535"
columnSpacing="0"
leftMargin="30"
rightMargin="30"
topMargin="20"
bottomMargin="20"
whenNoDataType="NoPages"
isTitleNewPage="false"
isSummaryNewPage="false">
<property name="ireport.scriptlethandling" value="0" />
<property name="ireport.encoding" value="UTF-8" />
<import value="java.util.*" />
<import value="net.sf.jasperreports.engine.*" />
<import value="net.sf.jasperreports.engine.data.*" />
<field name="name" class="java.lang.String"/>
<field name="start" class="java.util.Date"/>
<field name="end" class="java.util.Date"/>
<field name="budget" class="java.lang.Double"/>
<field name="totalCosts" class="java.lang.Double"/>
<field name="remain" class="java.lang.Double"/>
<background>
<band height="0" isSplitAllowed="true" >
</band>
</background>
<title>
<band height="0" isSplitAllowed="true" >
</band>
</title>
<pageHeader>
<band height="0" isSplitAllowed="true" >
</band>
</pageHeader>
<columnHeader>
<band height="44" isSplitAllowed="true" >
<rectangle radius="0" >
<reportElement
mode="Opaque"
x="2"
y="2"
width="530"
height="21"
forecolor="#000000"
backcolor="#CC0033"
key="rectangle-1"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<graphicElement stretchType="NoStretch" pen="None" fill="Solid" />
</rectangle>
<staticText>
<reportElement
mode="Opaque"
x="206"
y="5"
width="145"
height="16"
forecolor="#FFFFFF"
backcolor="#CC0033"
key="staticText-1"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Top" rotation="None" lineSpacing="Single">
<font fontName="Verdana" pdfFontName="Helvetica" size="11" isBold="true" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
88
</textElement>
<text><![CDATA[Relatório Financeiro]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="6"
y="24"
width="55"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText-2"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<text><![CDATA[Atividade]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="397"
y="24"
width="63"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText-3"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<text><![CDATA[Orçamento]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="196"
y="24"
width="33"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText-5"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<text><![CDATA[Início]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="261"
y="24"
width="27"
height="18"
forecolor="#000000"
89
backcolor="#FFFFFF"
key="staticText-6"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<text><![CDATA[Fim]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="473"
y="24"
width="59"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText-7"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<text><![CDATA[Disponível]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="355"
y="24"
width="34"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="staticText-9"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<text><![CDATA[Gasto]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="25" isSplitAllowed="true" >
<textField isStretchWithOverflow="false" pattern="" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="9"
y="1"
width="182"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-3"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
90
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{name}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="dd/MM/yyyy" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="196"
y="1"
width="64"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-4"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.util.Date"><![CDATA[$F{start}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="#,##0.00" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="394"
y="1"
width="64"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-7"
stretchType="NoStretch"
positionType="Float"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.lang.Double"><![CDATA[$F{budget}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="dd/MM/yyyy" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="262"
y="1"
width="63"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-5"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000"
91
rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.util.Date"><![CDATA[$F{end}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="#,##0.00" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="467"
y="1"
width="64"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-8"
stretchType="NoStretch"
positionType="Float"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.lang.Double"><![CDATA[$F{remain}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="#,##0.00" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="333"
y="1"
width="56"
height="18"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-9"
stretchType="NoStretch"
positionType="Float"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Bottom" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="12" isBold="false" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.lang.Double"><![CDATA[$F{totalCosts}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height="8" isSplitAllowed="true" >
</band>
</columnFooter>
<pageFooter>
<band height="0" isSplitAllowed="true" >
</band>
</pageFooter>
<summary>
<band height="11" isSplitAllowed="true" >
</band>
</summary>
</jasperReport>
edu.ufsc.ganttproject.report. CostsTaskReport.jrxml
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Created with iReport - A designer for JasperReports -->
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport
92
name="CostsTaskReport"
columnCount="1"
printOrder="Vertical"
orientation="Portrait"
pageWidth="536"
pageHeight="842"
columnWidth="535"
columnSpacing="0"
leftMargin="0"
rightMargin="0"
topMargin="0"
bottomMargin="0"
whenNoDataType="NoPages"
isTitleNewPage="false"
isSummaryNewPage="false">
<property name="ireport.scriptlethandling" value="0" />
<property name="ireport.encoding" value="UTF-8" />
<import value="java.util.*" />
<import value="net.sf.jasperreports.engine.*" />
<import value="net.sf.jasperreports.engine.data.*" />
<field name="description" class="java.lang.String"/>
<field name="date" class="java.util.Date"/>
<field name="value" class="java.lang.Double"/>
<background>
<band height="0" isSplitAllowed="true" >
</band>
</background>
<title>
<band height="0" isSplitAllowed="true" >
</band>
</title>
<pageHeader>
<band height="1" isSplitAllowed="true" >
</band>
</pageHeader>
<columnHeader>
<band height="0" isSplitAllowed="true" >
</band>
</columnHeader>
<detail>
<band height="25" isSplitAllowed="true" >
<textField isStretchWithOverflow="false" pattern="dd/MM/yyyy" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="5"
y="5"
width="67"
height="17"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-1"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Top" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="10" isBold="true" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.util.Date"><![CDATA[$F{date}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="76"
y="5"
width="237"
height="17"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-2"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Left" verticalAlignment="Top" rotation="None" lineSpacing="Single">
93
<font fontName="Arial" pdfFontName="Helvetica" size="10" isBold="true" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{description}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="false" pattern="#,##0.00" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="318"
y="4"
width="63"
height="17"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-3"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
<textElement textAlignment="Right" verticalAlignment="Top" rotation="None" lineSpacing="Single">
<font fontName="Arial" pdfFontName="Helvetica" size="10" isBold="true" isItalic="false" isUnderline="false" isPdfEmbedded ="false" pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
<textFieldExpression class="java.lang.Double"><![CDATA[$F{value}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height="0" isSplitAllowed="true" >
</band>
</columnFooter>
<pageFooter>
<band height="1" isSplitAllowed="true" >
</band>
</pageFooter>
<summary>
<band height="0" isSplitAllowed="true" >
</band>
</summary>
</jasperReport>
Classes e arquivos alterados
net.sourceforge.ganttproject.gui. GanttDialogProperties
package net.sourceforge.ganttproject.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.tree.DefaultMutableTreeNode;
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttGraphicArea;
import net.sourceforge.ganttproject.GanttTask;
import net.sourceforge.ganttproject.GanttTree2;
import net.sourceforge.ganttproject.Mediator;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskManager;
/**
* Dialog to edit the properties of a task
94
*/
public class GanttDialogProperties
extends JDialog
implements ActionListener {
/** JTextField for the name of task */
private JTextField jtfname;
/** JConboBox for the mother task */
private JComboBox jcbfather;
/** JTextField for the begining of the task */
private JTextField jtfbegin;
/** JTextField for duration of task */
private JTextField jtflength;
/** JList for depends of task */
// private JList jldepend;
/** JSlider for advent state of task */
private JSlider spercent;
/** JPanel for advancement label */
private JLabel advancementLabel;
/** JCheckBox . Is is a meetin point??? */
private JCheckBox jcbbilan;
/** Boolean to say if the task has child */
boolean haschild = false;
/** The GanttTree of the application. */
private GanttTree2 ttree;
/** GanttTask to edit */
private Task ttask;
/** GanttGraphicArea of the application. */
private GanttGraphicArea aarea;
/** Button to choose the date */
private JButton button;
/** Store old percent state value */
int percentValue;
/** The language */
private GanttLanguage lang = GanttLanguage.getInstance();
JFrame prj;
int saveDuration;
//LH
double saveCost;
Color saveColor;
/** true if the ok button was pressed */
public boolean change = false;
/** Color chooser dialog */
protected static JColorChooser colorChooser = new JColorChooser();
// By CL
private GanttTaskPropertiesBean taskPropertiesBean;
private Task task;
private GanttTask[] tasks;
95
private GanttTree2 tree;
private GanttGraphicArea area;
private JFrame parent;
/** Constructor */
public GanttDialogProperties(JFrame parent, GanttTree2 tree,
Hashtable managerHash, GanttTask[] tasks, GanttGraphicArea area,
String tasksNames) {
super(parent, GanttLanguage.getInstance().getText("propertiesFor")
+ " '" + tasksNames + "'", true);
this.tree = tree;
this.tasks = tasks;
// this.task = tasks [0];
saveDuration = tasks[0].getLength();
//LH
saveCost = tasks[0].getBudget();
this.area = area;
this.parent = parent;
// tree.forwardScheduling();
taskPropertiesBean = new GanttTaskPropertiesBean(this, tasks, tree,
managerHash);
Container cp = getContentPane();
taskPropertiesBean.addActionListener(this);
cp.add(taskPropertiesBean, BorderLayout.CENTER);
// this.setSize(600, 350);
this.pack();
setResizable(false);
DialogAligner.center(this, getParent());
applyComponentOrientation(lang.getComponentOrientation());
// GanttTask returnTask = taskPropertiesBean.getReturnTask();
// set the ok button as default action for enter
if (getRootPane() != null)
getRootPane().setDefaultButton(taskPropertiesBean.okButton);
}
/** Search a string on an array */
private int findTheIndex(Object s, String[] lot) {
for (int i = 0; i < lot.length; i++) {
if (s.toString() == lot[i]) {
return i;
}
}
return 0;
}
/** When click on date button, it open the dialog to select date. */
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof TestGanttRolloverButton) {
TestGanttRolloverButton button = (TestGanttRolloverButton) evt
.getSource();
if (button.getName().equals("start")) {
GanttCalendar date = taskPropertiesBean.getStart();
GanttDialogDate dd = new GanttDialogDate(this, date, true);
dd.show();
96
taskPropertiesBean.setStart(dd.getDate(), false);
}
else if (button.getName().equals("finish")) {
GanttCalendar date = taskPropertiesBean.getFinish();
GanttDialogDate dd = new GanttDialogDate(this, date, true);
dd.show();
taskPropertiesBean.setEnd(dd.getDate(), false);
} else if (button.getName().equals("third")) {
GanttCalendar date = taskPropertiesBean.getThird();
GanttDialogDate dd = new GanttDialogDate(this, date);
dd.show();
taskPropertiesBean.setThird(dd.getDate(), false);
}
}
else if (evt.getSource() instanceof JButton) {
JButton button = (JButton) evt.getSource();
if (button.getName().equals("ok")) {
this.setVisible(false);
dispose();
Mediator.getUndoManager().undoableEdit("Properties changed",
new Runnable() {
public void run() {
Task[] returnTask = taskPropertiesBean
.getReturnTask();
// System.err.println("[GanttDialogProperties]
// returnTask="+returnTask);
// returnTask.setTaskID(this.task.getTaskID());
// getTaskManager().setTask(returnTask);
DefaultMutableTreeNode father;
for (int i = 0; i < returnTask.length; i++) {
tree.getNode(tasks[i].getTaskID())
.setUserObject(returnTask[i]);
// Refresh all father
father = tree.getFatherNode(tree
.getNode(tasks[i].getTaskID()));
while (father != null) {
tree.forwardScheduling();
father = tree.getFatherNode(father);
}
}
}
});
tree.getJTree().repaint();
tree.getJTree().updateUI();
tree.getTable().setRowHeight(20);
area.repaint();
change = true;
}
else if (button.getName().equals("cancel")) {
this.setVisible(false);
dispose();
}
}
97
else if (evt.getSource() instanceof JTextField) {
JTextField textfield = (JTextField) evt.getSource();
if (textfield.getName().equals("length")) {
try {
int duration = Integer.parseInt(textfield.getText().trim());
taskPropertiesBean.changeLength(duration);
saveDuration = duration;
} catch (Exception e) {
textfield.setText(saveDuration + "");
GanttDialogInfo gdiError = new GanttDialogInfo(parent,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION,
lang.getText("msg16"), lang.getText("error"));
gdiError.show();
taskPropertiesBean.changeLength(saveDuration);
}
}//LH
else if (textfield.getName().equals("cost")) {
try {
double cost = Double.parseDouble(textfield.getText().trim());
taskPropertiesBean.changeBudget(cost);
saveCost = cost;
} catch (Exception e) {
textfield.setText(saveCost + "");
// TODO change the error message
GanttDialogInfo gdiError = new GanttDialogInfo(parent,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION,
lang.getText("msg16"), lang.getText("error"));
gdiError.show();
taskPropertiesBean.changeBudget(saveCost);
}
}
// Change the name of task
else if (textfield.getName().equals("name_of_task")) {
taskPropertiesBean.changeNameOfTask();
}
} else if (evt.getSource() instanceof JComboBox) {
JComboBox comboBox = (JComboBox) evt.getSource();
if (comboBox.getName().equals("third")) {
if (taskPropertiesBean.getThird() != null)
taskPropertiesBean.setThird(taskPropertiesBean.getThird(),
false);
else
taskPropertiesBean.setThird(taskPropertiesBean.getStart()
.newAdd(0), false);
}
}
}
private TaskManager getTaskManager() {
return this.task.getManager();
}
}
net.sourceforge.ganttproject.gui. GanttTaskPropertiesBean
package net.sourceforge.ganttproject.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.Hashtable;
import java.util.Vector;
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.ImageIcon;
import javax.swing.JButton;
98
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultMutableTreeNode;
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttGraphicArea;
import net.sourceforge.ganttproject.GanttProject;
import net.sourceforge.ganttproject.GanttTask;
import net.sourceforge.ganttproject.GanttTree2;
import net.sourceforge.ganttproject.Mediator;
import net.sourceforge.ganttproject.gui.taskproperties.CustomColumnsPanel;
import net.sourceforge.ganttproject.gui.taskproperties.CostsPanel;
import net.sourceforge.ganttproject.gui.taskproperties.TaskAllocationsPanel;
import net.sourceforge.ganttproject.gui.taskproperties.TaskDependenciesPanel;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.resource.HumanResourceManager;
import net.sourceforge.ganttproject.roles.RoleManager;
import net.sourceforge.ganttproject.shape.JPaintCombo;
import net.sourceforge.ganttproject.shape.ShapeConstants;
import net.sourceforge.ganttproject.shape.ShapePaint;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskImpl;
import net.sourceforge.ganttproject.task.TaskMutator;
import net.sourceforge.ganttproject.util.BrowserControl;
/**
* Real panel for editing task properties
*/
public class GanttTaskPropertiesBean
extends JPanel {
// Input attributes
// protected GanttTask selectedTask; //Task whose properties will be shown
protected GanttTask[] selectedTasks;
protected Vector savePredecessors;
private GanttTree2 tree; // GanttTree that contain all the tasks information
private GanttLanguage language = GanttLanguage.getInstance(); // language
// the panel
// will
// display
private JDialog parent;
// Output attributes: you can find the definition is GanttTask
// private String name;
private int length;
private int percentComplete;
private int priority;
//LH
private double budget;
private GanttCalendar start;
private GanttCalendar end;
private GanttCalendar third;
private boolean bilan;
99
private boolean isProjectTask;
private String notes;
// private GanttTask selectedTaskClone;
// private Hashtable managerHash;
//
// private Hashtable assignedResources = new Hashtable();
// private attributes for internal use
GridBagConstraints gbc = new GridBagConstraints();
FlowLayout flowL = new FlowLayout(FlowLayout.LEFT, 10, 10);
JTabbedPane tabbedPane; // TabbedPane that include the following four items
JPanel generalPanel;
JPanel predecessorsPanel;
JPanel resourcesPanel;
JPanel notesPanel;
//LH
JPanel costsPanel;
// Components on general pannel
JPanel firstRowPanel1; // components in first row
JTextField nameField1;
JTextField durationField1;
//LH
//JTextField budgetField1;
JFormattedTextField budgetField1;
JLabel nameLabel1;
JLabel durationLabel1;
//LH
JLabel budgetLabel1;
JLabel lblWebLink;
JTextField tfWebLink;
JButton bWebLink;
JPanel secondRowPanel1; // components in second row
JSpinner percentCompleteSlider;
JLabel percentCompleteLabel1;
JLabel priorityLabel1;
JComboBox priorityComboBox;
JPanel thirdRowPanel1; // componets in third row
JTextField startDateField1;
JTextField finishDateField1;
JTextField thirdDateField1;
JLabel startDateLabel1;
JLabel finishDateLabel1;
JComboBox thirdDateComboBox;
JButton startDateButton1;
JButton finishDateButton1;
JButton thirdDateButton1;
JPanel lastRowPanel1; // components in last row
JPanel webLinkPanel; // components in web link panel
JLabel mileStoneLabel1;
100
JCheckBox mileStoneCheckBox1;
JCheckBox projectTaskCheckBox1;
JButton colorButton;
boolean isColorChanged;
JButton colorSpace;
JPanel colorPanel;
/** Shape chooser combo Box */
JPaintCombo shapeComboBox;
// Components on predecessors pannel
JLabel nameLabel2; // first row, here the textfield is un-editable
JLabel durationLabel2;
JTextField nameField2;
JPanel firstRowPanel2;
JScrollPane predecessorsScrollPane; // second row, a table
JLabel nameLabelNotes;
JLabel durationLabelNotes;
//LH
JLabel budgetLabelNotes;
JTextField nameFieldNotes;
JTextField durationFieldNotes;
//LH
//JTextField budgetFieldNotes;
JFormattedTextField budgetFieldNotes;
JScrollPane scrollPaneNotes;
JTextArea noteAreaNotes;
JPanel firstRowPanelNotes;
JPanel secondRowPanelNotes;
// Component on the SOUTH ok CANCEL buttons
public JButton okButton;
JButton cancelButton;
JPanel southPanel;
private boolean onlyOneTask = false;
private String taskWebLink;
private boolean taskIsMilestone;
private GanttCalendar taskStartDate;
private GanttCalendar taskEndDate;
private GanttCalendar taskThirdDate;
private int taskThirdDateConstraint;
private boolean taskIsProjectTask;
private int taskLength;
private String taskNotes;
private int taskCompletionPercentage;
private int taskPriority;
//LH
private double taskBudget;
private boolean taskIsStartFixed;
private boolean taskIsFinishFixed;
private Color taskColor;
private ShapePaint taskShape;
101
private CustomColumnsPanel myCustomColumnPanel = null;
// private ResourcesTableModel myResourcesTableModel;
private TaskDependenciesPanel myDependenciesPanel;
private TaskAllocationsPanel[] myAllocationsPanel;
private CostsPanel myCostsPanel = null;;
private boolean isStartFixed;
// private boolean isFinishFixed;
private final HumanResourceManager myHumanResourceManager;
private final RoleManager myRoleManager;
private Task myUnpluggedClone;
/** add a component to container by using GridBagConstraints. */
private void addUsingGBL(Container container, Component component,
GridBagConstraints gbc, int x,
int y, int w, int h) {
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
gbc.weighty = 0;
container.add(component, gbc);
}
/** set the first row in all the tabbed pane. thus give them a common look */
private void setFirstRow(Container container, GridBagConstraints gbc,
JLabel nameLabel, JTextField nameField, JLabel durationLabel,
JTextField durationField, JLabel budgetLabel, JTextField budgetField) {
container.setLayout(new GridBagLayout());
gbc.weightx = 0;
gbc.weighty = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets.right = 15;
gbc.insets.left = 10;
gbc.insets.top = 10;
addUsingGBL(container, nameLabel, gbc, 0, 0, 1, 1);
addUsingGBL(container, nameField, gbc, 1, 0, 1, 1);
addUsingGBL(container, durationLabel, gbc, 2, 0, 1, 1);
gbc.weightx = 1;
addUsingGBL(container, durationField, gbc, 3, 0, 1, 1);
//LH
addUsingGBL(container, budgetLabel, gbc, 4, 0, 1, 1);
addUsingGBL(container, budgetField, gbc, 5, 0, 1, 1);
}
/** Construct the general panel */
private void constructGeneralPanel() {
generalPanel = new JPanel(new GridBagLayout());
// first row
nameLabel1 = new JLabel(language.getText("name") + ":");
nameField1 = new JTextField(20);
nameField1.setName("name_of_task");
if (!onlyOneTask) {
nameLabel1.setVisible(false);
nameField1.setVisible(false);
}
durationLabel1 = new JLabel(language.getText("length") + ":");
durationField1 = new JTextField(8);
durationField1.setName("length");
firstRowPanel1 = new JPanel(flowL);
//LH
budgetLabel1 = new JLabel(language.getText("budget") + ":");
//budgetField1 = new JTextField(8);
NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
102
budgetField1 = new JFormattedTextField(format);
budgetField1.setColumns(8);
budgetField1.setName("budget");
setFirstRow(firstRowPanel1, gbc, nameLabel1, nameField1,
durationLabel1, durationField1, budgetLabel1, budgetField1);
// second row
percentCompleteLabel1 = new JLabel(language.getText("advancement")); // Progress
SpinnerNumberModel spinnerModel = new SpinnerNumberModel(0, 0, 100, 1);
percentCompleteSlider = new JSpinner(spinnerModel);
secondRowPanel1 = new JPanel(flowL);
secondRowPanel1.add(percentCompleteLabel1);
// secondRowPanel1.add(percentCompleteField1);
secondRowPanel1.add(percentCompleteSlider);
priorityLabel1 = new JLabel(language.getText("priority"));
secondRowPanel1.add(priorityLabel1);
priorityComboBox = new JComboBox();
priorityComboBox.addItem(language.getText("low"));
priorityComboBox.addItem(language.getText("normal"));
priorityComboBox.addItem(language.getText("hight"));
priorityComboBox.setEditable(false);
secondRowPanel1.add(priorityComboBox);
// third row
startDateLabel1 = new JLabel(language.getText("dateOfBegining") + ":");
startDateField1 = new JTextField(12);
startDateField1.setEditable(false);
finishDateLabel1 = new JLabel(language.getText("dateOfEnd") + ":");
finishDateField1 = new JTextField(12);
finishDateField1.setEditable(false);
thirdDateComboBox = new JComboBox();
thirdDateComboBox.addItem("");
thirdDateComboBox.addItem(language.getText("earliestBegin"));
thirdDateComboBox.setName("third");
thirdDateComboBox.setSelectedIndex(selectedTasks[0]
.getThirdDateConstraint());
thirdDateField1 = new JTextField(12);
thirdDateField1.setEditable(false);
ImageIcon icon = new ImageIcon(getClass().getResource(
"/icons/calendar_16.gif"));
startDateButton1 = new TestGanttRolloverButton(icon);
startDateButton1.setName("start");
startDateButton1.setToolTipText(GanttProject.getToolTip(language
.getText("chooseDate")));
finishDateButton1 = new TestGanttRolloverButton(icon);
finishDateButton1.setName("finish");
finishDateButton1.setToolTipText(GanttProject.getToolTip(language
.getText("chooseDate")));
thirdDateButton1 = new TestGanttRolloverButton(icon);
thirdDateButton1.setName("third");
thirdDateButton1.setToolTipText(GanttProject.getToolTip(language
.getText("chooseDate")));
if (selectedTasks[0].getThirdDateConstraint() == 0)
thirdDateButton1.setEnabled(false);
GridBagLayout thirdRowPanel1Layout = new GridBagLayout();
// TODO put the date
thirdRowPanel1 = new JPanel(flowL);
thirdRowPanel1.setBorder(new TitledBorder(new EtchedBorder(), language
.getText("date")));
JPanel startDatePanel = new JPanel(
new FlowLayout(FlowLayout.LEFT, 5, 0));
startDatePanel.add(startDateLabel1);
startDatePanel.add(startDateField1);
startDatePanel.add(startDateButton1);
JPanel finishDatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5,
0));
finishDatePanel.add(finishDateLabel1);
finishDatePanel.add(finishDateField1);
103
finishDatePanel.add(finishDateButton1);
JPanel thirdDatePanel = new JPanel(
new FlowLayout(FlowLayout.LEFT, 5, 0));
thirdDatePanel.add(thirdDateComboBox);
thirdDatePanel.add(thirdDateField1);
thirdDatePanel.add(thirdDateButton1);
// thirdRowPanel1.add(startDatePanel);
// thirdRowPanel1.add(finishDatePanel);
// thirdRowPanel1.add(thirdDatePanel);
addUsingGBL(thirdRowPanel1, startDatePanel, gbc, 0, 0, 1, 1);
addUsingGBL(thirdRowPanel1, finishDatePanel, gbc, 0, 1, 1, 1);
addUsingGBL(thirdRowPanel1, thirdDatePanel, gbc, 0, 2, 1, 1);
// fourth row
JCheckBox checkBox = constructCheckBox ();
lastRowPanel1 = new JPanel(flowL);
if (checkBox != null)
lastRowPanel1.add(checkBox);
JPanel shapePanel = new JPanel();
shapePanel.setLayout(new BorderLayout());
JLabel lshape = new JLabel(" " + language.getText("shape") + " ");
shapeComboBox = new JPaintCombo(ShapeConstants.PATTERN_LIST);
shapePanel.add(lshape, BorderLayout.WEST);
shapePanel.add(shapeComboBox, BorderLayout.CENTER);
colorButton = new JButton(language.getText("colorButton"));
colorButton.setBackground(selectedTasks[0].getColor());
final String colorChooserTitle = language.getText("selectColor");
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog dialog;
dialog = JColorChooser.createDialog(parent, colorChooserTitle,
true, GanttDialogProperties.colorChooser,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorButton
.setBackground(GanttDialogProperties.colorChooser
.getColor());
isColorChanged = true;
}
}
, new ActionListener() {
public void actionPerformed(ActionEvent e) {
// nothing to do for "Cancel"
}
});
/*
* AbstractColorChooserPanel[] panels =
* GanttDialogProperties.colorChooser.getChooserPanels();
* GanttDialogProperties.colorChooser.removeChooserPanel(panels[0]);
* GanttDialogProperties.colorChooser.addChooserPanel(panels[0]);
*/
GanttDialogProperties.colorChooser.setColor(colorButton
.getBackground());
dialog.show();
}
});
colorSpace = new JButton(language.getText("defaultColor"));
colorSpace.setBackground(GanttGraphicArea.taskDefaultColor);
colorSpace.setToolTipText(GanttProject.getToolTip(language
.getText("resetColor")));
colorSpace.addActionListener(new ActionListener() {
104
public void actionPerformed(ActionEvent e) {
colorButton.setBackground(GanttGraphicArea.taskDefaultColor);
isColorChanged = true;
}
});
colorPanel = new JPanel();
colorPanel.setLayout(new BorderLayout());
colorPanel.add(colorButton, "West");
colorPanel.add(colorSpace, "Center");
colorPanel.add(shapePanel, BorderLayout.EAST);
lastRowPanel1.add(colorPanel);
// ---Set GridBagConstraints constant
gbc.anchor = GridBagConstraints.WEST;
gbc.insets.right = 15;
gbc.insets.left = 10;
gbc.insets.top = 10;
addUsingGBL(generalPanel, firstRowPanel1, gbc, 0, 0, 1, 1);
addUsingGBL(generalPanel, secondRowPanel1, gbc, 0, 1, 1, 1);
addUsingGBL(generalPanel, thirdRowPanel1, gbc, 0, 2, 1, 1);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
gbc.gridheight = GridBagConstraints.RELATIVE;
gbc.anchor = GridBagConstraints.WEST;
gbc.weighty = 1;
generalPanel.add(lastRowPanel1, gbc);
// The panel for the web link
webLinkPanel = new JPanel(flowL);
lblWebLink = new JLabel(language.getText("webLink"));
webLinkPanel.add(lblWebLink);
tfWebLink = new JTextField(30);
webLinkPanel.add(tfWebLink);
bWebLink = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/web_16.gif")));
bWebLink.setToolTipText(GanttProject.getToolTip(language
.getText("openWebLink")));
webLinkPanel.add(bWebLink);
bWebLink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// link to open the web link
try {
if (!BrowserControl.displayURL(tfWebLink.getText())) {
GanttDialogInfo gdi = new GanttDialogInfo(null,
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION, language
.getText("msg4"), language
.getText("error"));
gdi.show();
}
} catch (Exception ex) {
}
}
});
gbc.gridy = 4;
generalPanel.add(webLinkPanel, gbc);
}
/** Add the differents action listener on the differents widgets */
public void addActionListener(ActionListener l) {
nameField1.addActionListener(l);
startDateButton1.addActionListener(l);
finishDateButton1.addActionListener(l);
thirdDateButton1.addActionListener(l);
thirdDateComboBox.addActionListener(l);
okButton.addActionListener(l);
cancelButton.addActionListener(l);
durationField1.addActionListener(l);
105
budgetField1.addActionListener(l);
}
/** Change the name of the task on all textfiled of task name */
public void changeNameOfTask() {
if (nameField1 != null && nameFieldNotes != null) {
String nameOfTask = nameField1.getText().trim();
nameField1.setText(nameOfTask);
if (onlyOneTask)
myDependenciesPanel.nameChanged(nameOfTask);
myAllocationsPanel[0].nameChanged(nameOfTask);
nameFieldNotes.setText(nameOfTask);
}
}
private void constructCustomColumnPanel() {
myCustomColumnPanel = new CustomColumnsPanel(Mediator
.getCustomColumnsStorage());
}
/** Construct the predecessors tabbed pane */
private void constructPredecessorsPanel() {
myDependenciesPanel = new TaskDependenciesPanel(selectedTasks[0]);
predecessorsPanel = myDependenciesPanel.getComponent();
}
/** Construct the resources panel */
private void constructResourcesPanel() {
myAllocationsPanel = new TaskAllocationsPanel[selectedTasks.length];
for (int i = 0; i < myAllocationsPanel.length; i++) {
myAllocationsPanel[i] = new TaskAllocationsPanel(selectedTasks[i],
myHumanResourceManager, myRoleManager, onlyOneTask);
if (i != 0)
myAllocationsPanel[i].getComponent();
}
resourcesPanel = myAllocationsPanel[0].getComponent();
}
/** construct the notes pannel */
private void constructNotesPanel() {
notesPanel = new JPanel(new GridBagLayout());
// first row
nameLabelNotes = new JLabel(language.getText("name") + ":");
nameFieldNotes = new JTextField(20);
if (!onlyOneTask) {
nameLabelNotes.setVisible(false);
nameFieldNotes.setVisible(false);
}
durationLabelNotes = new JLabel(language.getText("length") + ":");
//LH
// TODO put string in properties
budgetLabelNotes = new JLabel(language.getText("budget") + ":");
durationFieldNotes = new JTextField(8);
//LH
//budgetFieldNotes = new JTextField(8);
budgetFieldNotes = new JFormattedTextField(NumberFormat.getCurrencyInstance());
budgetFieldNotes.setColumns(8);
nameFieldNotes.setEditable(false);
durationFieldNotes.setEditable(false);
budgetFieldNotes.setEditable(false);
firstRowPanelNotes = new JPanel();
setFirstRow(firstRowPanelNotes, gbc, nameLabelNotes, nameFieldNotes,
106
durationLabelNotes, durationFieldNotes, budgetLabelNotes, budgetFieldNotes);
secondRowPanelNotes = new JPanel();
secondRowPanelNotes.setBorder(new TitledBorder(new EtchedBorder(),
language.getText("notesTask") + ":"));
noteAreaNotes = new JTextArea(8, 40);
noteAreaNotes.setLineWrap(true);
noteAreaNotes.setWrapStyleWord(true);
noteAreaNotes.setBackground(new Color(1.0f, 1.0f, 1.0f));
scrollPaneNotes = new JScrollPane(noteAreaNotes);
secondRowPanelNotes.add(scrollPaneNotes);
JButton bdate = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/clock_16.gif")));
bdate.setToolTipText(GanttProject.getToolTip(language
.getText("putDate")));
bdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
noteAreaNotes.append("\n" + GanttCalendar.getDateAndTime()
+ "\n");
}
});
secondRowPanelNotes.add(bdate);
gbc.anchor = GridBagConstraints.WEST;
gbc.insets.right = 15;
gbc.insets.left = 10;
gbc.insets.top = 10;
gbc.weighty = 0;
addUsingGBL(notesPanel, firstRowPanelNotes, gbc, 0, 0, 1, 1);
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 1;
notesPanel.add(secondRowPanelNotes, gbc);
}
//LH
/** construct the costs pannel */
private void constructCostsPanel() {
//costsPanel = new CostsPanel(selectedTasks[0], Mediator
// .getCostStorage());
myCostsPanel = new CostsPanel(selectedTasks[0]);
costsPanel = myCostsPanel.getComponent();
}
/** Construct the south panel */
private void constructSouthPanel() {
okButton = new JButton(language.getText("ok"));
okButton.setName("ok");
if (getRootPane() != null)
getRootPane().setDefaultButton(okButton); // set ok the defuault
// button when press
// "enter" --> check
// because
// getRootPane()==null
// !!!
cancelButton = new JButton(language.getText("cancel"));
cancelButton.setName("cancel");
107
southPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 50, 10));
southPanel.add(okButton);
southPanel.add(cancelButton);
}
/** Constructor */
public GanttTaskPropertiesBean(JDialog parent, GanttTask[] selectedTasks,
GanttTree2 tree, Hashtable managerHash) {
this.parent = parent;
this.onlyOneTask = false;
if (selectedTasks.length == 1)
this.onlyOneTask = true;
this.selectedTasks = selectedTasks;
setInitialValues(selectedTasks[0]);
savePredecessors = selectedTasks[0].getPredecessorsOld();
myHumanResourceManager = (HumanResourceManager) managerHash
.get(GanttProject.HUMAN_RESOURCE_MANAGER_ID);
myRoleManager = (RoleManager) managerHash
.get(GanttProject.ROLE_MANAGER_ID);
setTree(tree);
init();
// this.managerHash = managerHash;
setSelectedTask();
// set predecessor comboBox
// setUpPredecessorComboColumn(predecessorsTable.getColumnModel().getColumn(1),
// predecessorsTable); //set column editor
// setUpTypeComboColumn(predecessorsTable.getColumnModel().getColumn(2));
// //set column editor
// set resources comboBox
/*
* setUpResourcesComboColumn(((ResourceManager)managerHash.get("HUMAN_RESOURCE")).getResources(),
* resourcesTable.getColumnModel().getColumn(0)); //set column editor
*/
/*
* tabbedPane = new JTabbedPane(); constructGeneralPanel();
* tabbedPane.add("General", generalPanel);
* constructPredecessorsPanel(); tabbedPane.add("Predecessors",
* predecessorsPanel); constructResourcesPanel();
* tabbedPane.add("Resources", resourcesPanel); constructNotesPanel();
* tabbedPane.add("Notes", notesPanel); add(tabbedPane);
*/
}
/** Init the widgets */
public void init() {
tabbedPane = new JTabbedPane();
tabbedPane.getModel().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
changeNameOfTask();
fireDurationChanged();
fireBudgetChanged();
}
});
constructGeneralPanel();
tabbedPane.addTab(language.getText("general"), new ImageIcon(getClass()
.getResource("/icons/properties_16.gif")), generalPanel);
if (onlyOneTask) {
constructPredecessorsPanel();
tabbedPane.addTab(language.getText("predecessors"), new ImageIcon(
108
getClass().getResource("/icons/relashion.gif")),
predecessorsPanel);
}
constructResourcesPanel();
tabbedPane.addTab(GanttProject.correctLabel(language.getText("human")),
new ImageIcon(getClass().getResource("/icons/res_16.gif")),
resourcesPanel);
constructNotesPanel();
tabbedPane.addTab(language.getText("notesTask"), new ImageIcon(
getClass().getResource("/icons/note_16.gif")), notesPanel);
setLayout(new BorderLayout());
add(tabbedPane, BorderLayout.CENTER);
constructSouthPanel();
add(southPanel, BorderLayout.SOUTH);
constructCustomColumnPanel();
tabbedPane.addTab(language.getText("customColumns"), new ImageIcon(
getClass().getResource("/icons/custom.gif")),
myCustomColumnPanel);
//LH
if (onlyOneTask) {
constructCostsPanel();
tabbedPane.addTab(language.getText("costs"), new ImageIcon(
getClass().getResource("/icons/custom.gif")),
costsPanel);
}
}
// Input methods
/**
* as the name indicated, it will not replace the original GanttTask in the
* Tree.
*/
public Task[] getReturnTask() {
GanttTask[] returnTask = new GanttTask[selectedTasks.length];
for (int i = 0; i < selectedTasks.length; i++) {
if (myAllocationsPanel[0].getTableModel().isChanged()) {
if (i != 0)
copyValues(myAllocationsPanel[0].getTableModel(),
myAllocationsPanel[i].getTableModel());
}
myAllocationsPanel[i].getTableModel().commit();
returnTask[i] = selectedTasks[i];
// returnTask.setTaskID(selectedTask.getTaskID());
TaskMutator mutator = returnTask[i].createMutator();
if (onlyOneTask) {
mutator.setName(getTaskName()); // getName()
mutator.setProjectTask (false);
}
if (this.taskWebLink != null && !this.taskWebLink.equals(getWebLink()))
returnTask[i].setWebLink(getWebLink()); // getName()
if (mileStoneCheckBox1 != null) {
if (this.taskIsMilestone != isBilan())
mutator.setMilestone(isBilan());
returnTask[i].setChecked(false);
}
else if (projectTaskCheckBox1 != null) {
if (this.taskIsProjectTask != isProjectTask())
mutator.setProjectTask(isProjectTask());
}
if (!this.taskStartDate.equals(getStart()))
109
mutator.setStart(getStart());
if (((this.taskThirdDate == null) && (getThird() != null))
|| ((this.taskThirdDate != null) && (getThird() == null))
|| ((this.taskThirdDate != null) && (!this.taskThirdDate
.equals(getThird()))))
mutator.setThird(getThird(), getThirdDateConstraint());
if (getLength() > 0) {
if (this.taskLength != getLength())
mutator.setDuration(returnTask[i].getManager()
.createLength(getLength()));
}
if (!this.taskNotes.equals(getNotes()))
returnTask[i].setNotes(getNotes());
if (this.taskCompletionPercentage != getPercentComplete())
mutator.setCompletionPercentage(getPercentComplete());
if (this.taskPriority != getPriority())
returnTask[i].setPriority(getPriority());
//LH
if (this.taskBudget != getBudget())
returnTask[i].setBudget(getBudget());
if (this.taskIsStartFixed != isStartFixed)
returnTask[i].setStartFixed(isStartFixed);
//LH
if (onlyOneTask)
myCostsPanel.getTableModel().commit();
// if (this.taskIsFinishFixed != isFinishFixed)
// returnTask[i].setFinishFixed(isFinishFixed);
if (isColorChanged)
returnTask[i].setColor(colorButton.getBackground());
if ((((this.taskShape == null) && (shapeComboBox.getSelectedIndex() != 0)))
|| ((this.taskShape != null) && (!this.taskShape
.equals((ShapePaint) shapeComboBox
.getSelectedPaint()))))
returnTask[i].setShape(new ShapePaint(
(ShapePaint) shapeComboBox.getSelectedPaint(),
Color.white, returnTask[i].getColor()));
if (returnTask[i].getShape() != null)
returnTask[i].setShape(new ShapePaint(returnTask[i].getShape(),
Color.white, returnTask[i].getColor()));
mutator.commit();
if (onlyOneTask) {
myDependenciesPanel.getTableModel().commit();
}
returnTask[i].applyThirdDateConstraint();
}
return returnTask;
}
/** as the name indicated */
public void setSelectedTask() {
// this.selectedTask = selectedTask;
nameField1.setText(selectedTasks[0].getName());
// nameField2.setText(selectedTask.toString());
nameFieldNotes.setText(selectedTasks[0].toString());
setName(selectedTasks[0].toString());
durationField1.setText(selectedTasks[0].getLength() + "");
// durationField2.setText(selectedTask.getLength() + "");
durationFieldNotes.setText(selectedTasks[0].getLength() + "");
110
//LH
//budgetField1.setText(selectedTasks[0].getBudget() + "");
budgetField1.setValue(new Double(selectedTasks[0].getBudget()));
//budgetFieldNotes.setText(selectedTasks[0].getBudget() + "");
budgetFieldNotes.setValue(new Double(selectedTasks[0].getBudget()));
percentCompleteSlider.setValue(new Integer(selectedTasks[0]
.getCompletionPercentage()));
percentCompleteLabel1.setText(language.getText("advancement"));
priorityComboBox.setSelectedIndex(selectedTasks[0].getPriority());
startDateField1.setText(selectedTasks[0].getStart().toString());
finishDateField1.setText(selectedTasks[0].getEnd().toString());
if (selectedTasks[0].getThird() != null) {
thirdDateField1.setText(selectedTasks[0].getThird().toString());
setThird(selectedTasks[0].getThird().Clone(), true);
}
setStart(selectedTasks[0].getStart().Clone(), true);
setEnd(selectedTasks[0].getEnd().Clone(), true);
bilan = selectedTasks[0].isMilestone();
isProjectTask = selectedTasks[0].isProjectTask();
if (mileStoneCheckBox1 != null)
mileStoneCheckBox1.setSelected(bilan);
else if (projectTaskCheckBox1 != null)
projectTaskCheckBox1.setSelected(isProjectTask);
tfWebLink.setText(selectedTasks[0].getWebLink());
if (selectedTasks[0].shapeDefined()) {
for (int j = 0; j < ShapeConstants.PATTERN_LIST.length; j++) {
if (selectedTasks[0].getShape().equals(
ShapeConstants.PATTERN_LIST[j])) {
shapeComboBox.setSelectedIndex(j);
break;
}
}
}
noteAreaNotes.setText(selectedTasks[0].getNotes());
setStartFixed(selectedTasks[0].isStartFixed());
// setFinishFixed(selectedTasks[0].isFinishFixed());
myUnpluggedClone = selectedTasks[0].unpluggedClone();
}
/** as the name indicated */
public void setTree(GanttTree2 tree) {
this.tree = tree;
}
// Output methods
/** as the name indicated */
public boolean isBilan() {
bilan = mileStoneCheckBox1.isSelected();
return bilan;
}
public boolean isProjectTask() {
isProjectTask = projectTaskCheckBox1.isSelected();
return isProjectTask;
}
111
/** as the name indicated */
// public GanttCalendar getEnd() {
//
// return end;
//
// }
/** as the name indicated */
public GanttCalendar getThird() {
return third;
}
public int getThirdDateConstraint() {
return thirdDateComboBox.getSelectedIndex();
}
/** as the name indicated */
public int getLength() {
length = Integer.parseInt(durationField1.getText().trim());
return length;
}
//LH
public double getBudget() {
//budget = Double.parseDouble(budgetField1.getText().trim());
budget = ((Number)budgetField1.getValue()).doubleValue();
return budget;
}
public void fireDurationChanged() {
String value = durationField1.getText();
try {
int duration = Integer.parseInt(value);
changeLength(duration);
} catch (NumberFormatException e) {
}
}
public void fireBudgetChanged() {
//String value = budgetField1.getText();
if (budgetField1.getValue() != null)
try {
//double budget = Double.parseDouble(value);
//double budget = ((Number)budgetField1.getValue()).doubleValue();
double budget = ((Number)NumberFormat.getNumberInstance().parse(budgetField1.getText())).doubleValue();
changeBudget(budget);
} catch (Exception e) {
System.out.println("Budget Error:" + e.getMessage());
}
}
/** Set the duration of the task */
public void changeLength(int _length) {
if (_length <= 0) {
_length = 1;
}
durationField1.setText(_length + "");
if (onlyOneTask)
myDependenciesPanel.durationChanged(_length);
myAllocationsPanel[0].durationChanged(_length);
durationFieldNotes.setText(_length + "");
length = _length;
// change the end date
GanttCalendar _end = start.newAdd(length);
this.end = _end;
finishDateField1.setText(_end.toString());
}
/** Change the budget of the task on all textfiled of task budget */
public void changeBudget(double _budget) {
//budgetField1.setText(_budget + "");
112
budgetField1.setValue(new Double(_budget));
if (onlyOneTask)
myDependenciesPanel.budgetChanged(_budget);
myAllocationsPanel[0].budgetChanged(_budget);
myCostsPanel.budgetChanged(_budget);
//budgetFieldNotes.setText(_budget + "");
budgetFieldNotes.setValue(new Double(_budget));
budget = _budget;
}
/** as the name indicated */
public String getNotes() {
notes = noteAreaNotes.getText();
return notes;
}
/** Return the name of the task */
public String getTaskName() {
String text = nameField1.getText();
return text == null ? "" : text.trim();
}
/** @return the web link of the task. */
public String getWebLink() {
String text = tfWebLink.getText();
return text == null ? "" : text.trim();
}
/** as the name indicated */
public int getPercentComplete() {
percentComplete = ((Integer) percentCompleteSlider.getValue())
.hashCode();
return percentComplete;
}
/** Return the priority level of the task */
public int getPriority() {
priority = priorityComboBox.getSelectedIndex();
return priority;
}
public void setStartFixed(boolean startFixed) {
isStartFixed = startFixed;
startDateField1.setForeground(isStartFixed ? Color.BLACK : Color.GRAY);
}
// public void setFinishFixed(boolean startFixed) {
// isFinishFixed = startFixed;
// finishDateField1
// .setForeground(isFinishFixed ? Color.BLACK : Color.GRAY);
// }
/** Return the start date of the task */
public GanttCalendar getStart() {
start.setFixed(isStartFixed);
return start;
}
public GanttCalendar getFinish() {
// end.setFixed(isFinishFixed);
return end;
}
/** Change the start date of the task */
public void setStart(GanttCalendar dstart, boolean test) {
if (test == true) {
startDateField1.setText(dstart.toString());
this.start = dstart;
return;
}
startDateField1.setText(dstart.toString());
this.start = dstart;
this.setStartFixed(dstart.isFixed());
if (this.start.compareTo(this.end) < 0) {
adjustLength();
} else {
113
GanttCalendar _end = start.newAdd(length);
this.end = _end;
finishDateField1.setText(_end.toString());
}
}
/** Change the end date of the task */
public void setEnd(GanttCalendar dend, boolean test) {
if (test == true) {
finishDateField1.setText(dend.toString());
this.end = dend;
return;
}
finishDateField1.setText(dend.toString());
this.end = dend;
// this.setFinishFixed(dend.isFixed());
if (this.start.compareTo(this.end) < 0) {
adjustLength();
} else {
GanttCalendar _start = this.end.newAdd(-length);
this.start = _start;
startDateField1.setText(_start.toString());
}
}
/** Change the third date of the task */
public void setThird(GanttCalendar dthird, boolean test) {
if (test) {
thirdDateField1.setText(dthird.toString());
this.third = dthird;
return;
}
switch (thirdDateComboBox.getSelectedIndex()) {
case TaskImpl.EARLIESTBEGIN:
thirdDateButton1.setEnabled(true);
thirdDateField1.setText(dthird.toString());
this.third = dthird;
break;
case TaskImpl.NONE:
thirdDateButton1.setEnabled(false);
thirdDateField1.setText("");
this.third = null;
break;
}
}
private void adjustLength() {
myUnpluggedClone.setStart(this.start);
myUnpluggedClone.setEnd(this.end);
length = (int) myUnpluggedClone.getDuration().getLength();
durationField1.setText("" + length);
// durationField2.setText(""+length);
myAllocationsPanel[0].durationChanged(length);
durationFieldNotes.setText("" + length);
}
private void setInitialValues(GanttTask task) {
this.taskWebLink = task.getWebLink();
this.taskIsMilestone = task.isMilestone();
this.taskStartDate = task.getStart();
this.taskEndDate = task.getEnd();
this.taskLength = task.getLength();
this.taskNotes = task.getNotes();
this.taskCompletionPercentage = task.getCompletionPercentage();
this.taskPriority = task.getPriority();
//LH
this.taskBudget = task.getBudget();
this.taskIsStartFixed = task.isStartFixed();
// this.taskIsFinishFixed = task.isFinishFixed();
this.taskColor = task.getColor();
this.taskShape = task.getShape();
this.taskThirdDate = task.getThird();
this.taskThirdDateConstraint = task.getThirdDateConstraint();
this.taskIsProjectTask = task.isProjectTask();
}
private void copyValues(ResourcesTableModel original,
ResourcesTableModel clone) {
for (int i = 0; i < clone.getRowCount(); i++)
clone.setValueAt(null, i, 1);
for (int j = 0; j < original.getRowCount(); j++)
for (int k = 0; k < original.getColumnCount(); k++)
clone.setValueAt(original.getValueAt(j, k), j, k);
}
114
private JCheckBox constructCheckBox () {
boolean hasAParentOrDescendantProjectTask = true;
boolean isASuperTask = false;
for (int i = 0 ; i < selectedTasks.length ; i++) {
DefaultMutableTreeNode node = ((GanttTree2)tree).getNode (selectedTasks[i].getTaskID());
if (node.getChildCount() != 0)
isASuperTask = true;
//check if the task has a projectTask descendant or parent
if (((GanttTree2)tree).haveParentOrDescendantProjectTask(node)) {
hasAParentOrDescendantProjectTask = false;
}
}
if (hasAParentOrDescendantProjectTask)
projectTaskCheckBox1 = new JCheckBox (language.getText("projectTask"));
if (projectTaskCheckBox1 == null && (!isASuperTask)) {
mileStoneCheckBox1 = new JCheckBox(language.getText("meetingPoint")); // Milestone
return mileStoneCheckBox1;
}
return projectTaskCheckBox1;
}
}
net.sourceforge.ganttproject.gui. taskproperties.CommonPanel
package net.sourceforge.ganttproject.gui.taskproperties;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Locale;
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.Task;
/**
* Created by IntelliJ IDEA. User: bard
*/
abstract class CommonPanel implements InternalStateListener {
private final GanttLanguage language;
private JLabel nameLabel3;
private JLabel durationLabel3;
private JTextField nameField3;
private JTextField durationField3;
private JPanel firstRowPanel3;
private FlowLayout flowL = new FlowLayout(FlowLayout.LEFT, 10, 10);
private GridBagConstraints gbc = new GridBagConstraints();
private final Task myTask;
//LH
private JLabel budgetLabel3;
//private JTextField budgetField3;
private JFormattedTextField budgetField3;
public CommonPanel(Task task) {
language = GanttLanguage.getInstance();
myTask = task;
}
protected void addUsingGBL(Container container, Component component,
GridBagConstraints gbc, int x,
int y, int w, int h) {
115
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
gbc.weighty = 0;
container.add(component, gbc);
container.applyComponentOrientation(ComponentOrientation
.getOrientation(Locale.getDefault()));
}
/** set the first row in all the tabbed pane. thus give them a common look */
protected void setFirstRow(Container container, GridBagConstraints gbc,
JLabel nameLabel, JTextField nameField, JLabel durationLabel,
JTextField durationField, JLabel budgetLabel, JTextField budgetField) {
container.setLayout(new GridBagLayout());
gbc.weightx = 0;
gbc.weighty = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets.right = 15;
gbc.insets.left = 10;
gbc.insets.top = 10;
addUsingGBL(container, nameLabel, gbc, 0, 0, 1, 1);
addUsingGBL(container, nameField, gbc, 1, 0, 1, 1);
addUsingGBL(container, durationLabel, gbc, 2, 0, 1, 1);
gbc.weightx = 1;
addUsingGBL(container, durationField, gbc, 3, 0, 1, 1);
addUsingGBL(container, budgetLabel, gbc, 4, 0, 1, 1);
addUsingGBL(container, budgetField, gbc, 5, 0, 1, 1);
}
public void nameChanged(String newName) {
nameField3.setText(newName);
}
public void durationChanged(int newDuration) {
durationField3.setText("" + newDuration);
}
//LH
public void budgetChanged(double newBudget) {
//budgetField3.setText("" + newBudget);
budgetField3.setValue(new Double(newBudget));
}
protected JPanel setupCommonFields(boolean onlyOneTask) {
nameLabel3 = new JLabel(getLanguage().getText("name") + ":");
nameField3 = new JTextField(20);
nameField3.setText(getTask().getName());
durationLabel3 = new JLabel(getLanguage().getText("length") + ":");
durationField3 = new JTextField(8);
durationField3.setText("" + getTask().getDuration().getLength());
nameField3.setEditable(false);
durationField3.setEditable(false);
firstRowPanel3 = new JPanel(flowL);
//Lh
budgetLabel3 = new JLabel(getLanguage().getText("budget") + ":");
//budgetField3 = new JTextField(8);
budgetField3 = new JFormattedTextField(NumberFormat.getCurrencyInstance());
//budgetField3.setText("" + getTask().getBudget());
budgetField3.setValue(new Double(getTask().getBudget()));
budgetField3.setColumns(8);
budgetField3.setEditable(false);
setFirstRow(firstRowPanel3, gbc, nameLabel3, nameField3,
durationLabel3, durationField3, budgetLabel3, budgetField3);
if (!onlyOneTask) {
nameLabel3.setVisible(false);
nameField3.setVisible(false);
}
return firstRowPanel3;
}
protected GanttLanguage getLanguage() {
return language;
}
protected Task getTask() {
return myTask;
}
}
116
net.sourceforge.ganttproject.task. Task
package net.sourceforge.ganttproject.task;
import java.awt.Color;
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttTaskRelationship;
import net.sourceforge.ganttproject.shape.ShapePaint;
import net.sourceforge.ganttproject.task.dependency.TaskDependencySlice;
/**
* Created by IntelliJ IDEA.
*
* @author bard Date: 27.01.2004
*/
public interface Task extends MutableTask {
TaskMutator createMutator();
// main properties
int getTaskID();
String getName();
boolean isMilestone();
int getPriority();
TaskActivity[] getActivities();
GanttCalendar getStart();
GanttCalendar getEnd();
TaskLength getDuration();
TaskLength translateDuration(TaskLength duration);
int getCompletionPercentage();
boolean isStartFixed();
// boolean isFinishFixed();
ShapePaint getShape();
Color getColor();
String getNotes();
boolean getExpand();
//
// relationships with other entities
GanttTaskRelationship[] getPredecessors();
GanttTaskRelationship[] getSuccessors();
// HumanResource[] getAssignedHumanResources();
ResourceAssignment[] getAssignments();
TaskDependencySlice getDependencies();
TaskDependencySlice getDependenciesAsDependant();
TaskDependencySlice getDependenciesAsDependee();
ResourceAssignmentCollection getAssignmentCollection();
//LH
CostsTaskCollection getCostsTaskCollection();
Cost[] getCosts();
//
Task getSupertask();
Task[] getNestedTasks();
void move(Task targetSupertask);
void delete();
TaskManager getManager();
Task unpluggedClone();
// Color DEFAULT_COLOR = new Color( 140, 182, 206); not used
117
CustomColumnsValues getCustomValues();
boolean isCritical();
GanttCalendar getThird();
void applyThirdDateConstraint();
int getThirdDateConstraint();
void setThirdDate(GanttCalendar thirdDate);
void setThirdDateConstraint(int dateConstraint);
TaskInfo getTaskInfo();
boolean isProjectTask ();
//LH
double getBudget();
}
net.sourceforge.ganttproject.task. TaskImpl
package net.sourceforge.ganttproject.task;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttTaskRelationship;
import net.sourceforge.ganttproject.calendar.AlwaysWorkingTimeCalendarImpl;
import net.sourceforge.ganttproject.calendar.GPCalendar;
import net.sourceforge.ganttproject.calendar.GPCalendarActivity;
import net.sourceforge.ganttproject.shape.ShapePaint;
import net.sourceforge.ganttproject.task.dependency.TaskDependencySlice;
import net.sourceforge.ganttproject.task.dependency.TaskDependencySliceAsDependant;
import net.sourceforge.ganttproject.task.dependency.TaskDependencySliceAsDependee;
import net.sourceforge.ganttproject.task.dependency.TaskDependencySliceImpl;
import net.sourceforge.ganttproject.task.hierarchy.TaskHierarchyItem;
import net.sourceforge.ganttproject.time.TimeUnit;
/**
* Created by IntelliJ IDEA.
*
* @author bard Date: 31.01.2004
*/
public class TaskImpl implements Task {
private int myID;
private final TaskManagerImpl myManager;
private String myName;
private String myWebLink = new String("http://");
private boolean isMilestone;
boolean isProjectTask;
private int myPriority;
private GanttCalendar myStart;
private GanttCalendar myEnd;
private GanttCalendar myThird;
private int myThirdDateConstraint;
private int myCompletionPercentage;
private TaskLength myLength;
private List myActivities = new ArrayList();
private boolean isStartFixed;
118
// private boolean isFinishFixed;
private boolean bExpand;
// private final TaskDependencyCollection myDependencies = new
// TaskDependencyCollectionImpl();
private ResourceAssignmentCollectionImpl myAssignments;
//LH
private CostsTaskCollectionImpl myCosts;
private TaskDependencySlice myDependencySlice;
private TaskDependencySlice myDependencySliceAsDependant;
private TaskDependencySlice myDependencySliceAsDependee;
private boolean myEventsEnabled;
private final TaskHierarchyItem myTaskHierarchyItem;
private ShapePaint myShape;
private Color myColor;
private String myNotes;
private MutatorImpl myMutator;
private CustomColumnsValues customValues = null;
private boolean critical;
public final static int NONE = 0;
public final static int EARLIESTBEGIN = 1;
//LH
private double myBudget;
protected TaskImpl(TaskManager taskManager, int taskID) {
myManager = (TaskManagerImpl) taskManager;
if (taskID == -1) {
myID = myManager.getMaxID();
myManager.increaseMaxID();
} else {
if (myManager.getTask(taskID) != null) {
throw new IllegalArgumentException("There is a task with ID="
+ taskID + " already");
}
myID = taskID;
}
//LH
myCosts = new CostsTaskCollectionImpl(this);
myAssignments = new ResourceAssignmentCollectionImpl(this, myManager
.getConfig().getResourceManager());
myDependencySlice = new TaskDependencySliceImpl(this, myManager
.getDependencyCollection());
myDependencySliceAsDependant = new TaskDependencySliceAsDependant(this,
myManager.getDependencyCollection());
myDependencySliceAsDependee = new TaskDependencySliceAsDependee(this,
myManager.getDependencyCollection());
myPriority = 1;
myTaskHierarchyItem = myManager.getHierarchyManager().createItem(this);
isStartFixed = false;
// isFinishFixed = false;
myNotes = "";
bExpand = true;
myColor = null;
customValues = new CustomColumnsValues();
}
protected TaskImpl(TaskImpl copy, boolean isUnplugged) {
myManager = copy.myManager;
if (!isUnplugged) {
myTaskHierarchyItem = myManager.getHierarchyManager().createItem(
this);
} else {
myTaskHierarchyItem = null;
}
importData(copy);
}
//TODO implementar importação de custos
119
protected void importData(TaskImpl copy) {
myAssignments = new ResourceAssignmentCollectionImpl(this, myManager
.getConfig().getResourceManager());
myAssignments.importData(copy.getAssignmentCollection());
myID = copy.myID;
myName = copy.myName;
myWebLink = copy.myWebLink;
isMilestone = copy.isMilestone;
isProjectTask = copy.isProjectTask;
myPriority = copy.myPriority;
myStart = copy.myStart;
myEnd = copy.myEnd;
myThird = copy.myThird;
myThirdDateConstraint = copy.myThirdDateConstraint;
myCompletionPercentage = copy.myCompletionPercentage;
myLength = copy.myLength;
isStartFixed = copy.isStartFixed;
// isFinishFixed = copy.isFinishFixed;
myShape = copy.myShape;
myColor = copy.myColor;
myNotes = copy.myNotes;
bExpand = copy.bExpand;
//
myDependencySlice = new TaskDependencySliceImpl(this, myManager
.getDependencyCollection());
myDependencySliceAsDependant = new TaskDependencySliceAsDependant(this,
myManager.getDependencyCollection());
myDependencySliceAsDependee = new TaskDependencySliceAsDependee(this,
myManager.getDependencyCollection());
customValues = (CustomColumnsValues) copy.getCustomValues().clone();
recalculateActivities();
}
public Task unpluggedClone() {
TaskImpl result = new TaskImpl(this, true);
return result;
}
public TaskMutator createMutator() {
if (myMutator != null) {
throw new RuntimeException("Two mutators have been requested",
myException);
}
myMutator = new MutatorImpl();
myException = new Exception();
return myMutator;
}
private Exception myException;
// main properties
public int getTaskID() {
return myID;
}
public String getName() {
return myName;
}
public String getWebLink() {
return myWebLink;
}
public boolean isMilestone() {
return isMilestone;
}
public int getPriority() {
return myPriority;
}
public GanttCalendar getStart() {
if (myMutator != null
&& myMutator.myIsolationLevel == TaskMutator.READ_UNCOMMITED) {
return myMutator.getStart();
} else {
return myStart;
}
}
public GanttCalendar getEnd() {
if (myMutator != null
&& myMutator.myIsolationLevel == TaskMutator.READ_UNCOMMITED) {
return myMutator.getEnd();
120
} else {
if (myEnd == null) {
myEnd = getStart().Clone();
myEnd.add((int) getDuration().getLength());
}
return myEnd;
}
}
public GanttCalendar getThird() {
if (myMutator != null
&& myMutator.myIsolationLevel == TaskMutator.READ_UNCOMMITED) {
return myMutator.getThird();
} else {
return myThird;
}
}
public int getThirdDateConstraint() {
return myThirdDateConstraint;
}
public TaskActivity[] getActivities() {
List activities = myMutator == null ? null : myMutator.getActivities();
if (activities == null) {
activities = myActivities;
}
return (TaskActivity[]) activities.toArray(new TaskActivity[activities
.size()]);
}
public TaskLength getDuration() {
return (myMutator != null && myMutator.myIsolationLevel == TaskMutator.READ_UNCOMMITED) ? myMutator
.getDuration()
: myLength;
}
public int getCompletionPercentage() {
return (myMutator != null && myMutator.myIsolationLevel == TaskMutator.READ_UNCOMMITED) ? myMutator
.getCompletionPercentage()
: myCompletionPercentage;
}
public boolean isStartFixed() {
return isStartFixed;
}
// public boolean isFinishFixed() {
// return isFinishFixed;
// }
public boolean getExpand() {
return bExpand;
}
public ShapePaint getShape() {
return myShape;
}
public Color getColor() {
Color result = myColor;
if (result == null) {
if (isMilestone() || getNestedTasks().length > 0) {
result = Color.BLACK;
} else {
result = myManager.getConfig().getDefaultColor();
}
}
return result;
}
public String getNotes() {
return myNotes;
}
public GanttTaskRelationship[] getPredecessors() {
return new GanttTaskRelationship[0]; // To change body of implemented
// methods use Options | File
// Templates.
}
public GanttTaskRelationship[] getSuccessors() {
return new GanttTaskRelationship[0]; // To change body of implemented
// methods use Options | File
// Templates.
}
public ResourceAssignment[] getAssignments() {
121
return myAssignments.getAssignments();
}
public ResourceAssignmentCollection getAssignmentCollection() {
return myAssignments;
}
public Cost[] getCosts() {
return myCosts.getCosts();
}
public CostsTaskCollection getCostsTaskCollection() {
return myCosts;
}
//
public Task getSupertask() {
TaskHierarchyItem container = myTaskHierarchyItem.getContainerItem();
return container.getTask();
}
public Task[] getNestedTasks() {
TaskHierarchyItem[] nestedItems = myTaskHierarchyItem.getNestedItems();
Task[] result = new Task[nestedItems.length];
for (int i = 0; i < nestedItems.length; i++) {
result[i] = nestedItems[i].getTask();
}
return result;
}
public void move(Task targetSupertask) {
TaskImpl supertaskImpl = (TaskImpl) targetSupertask;
TaskHierarchyItem targetItem = supertaskImpl.myTaskHierarchyItem;
myTaskHierarchyItem.delete();
targetItem.addNestedItem(myTaskHierarchyItem);
}
public void delete() {
getDependencies().clear();
getAssignmentCollection().clear();
}
public TaskDependencySlice getDependencies() {
return myDependencySlice;
}
public TaskDependencySlice getDependenciesAsDependant() {
return myDependencySliceAsDependant;
}
public TaskDependencySlice getDependenciesAsDependee() {
return myDependencySliceAsDependee;
}
public TaskManager getManager() {
return myManager;
}
// TODO: remove this hack. ID must never be changed
protected void setTaskIDHack(int taskID) {
myID = taskID;
}
private static interface EventSender {
void enable();
void fireEvent();
}
private class ProgressEventSender implements EventSender {
private boolean myEnabled;
public void fireEvent() {
if (myEnabled) {
myManager.fireTaskProgressChanged(TaskImpl.this);
}
myEnabled = false;
}
public void enable() {
myEnabled = true;
}
}
private class PropertiesEventSender implements EventSender {
private boolean myEnabled;
122
public void fireEvent() {
if (myEnabled) {
myManager.fireTaskPropertiesChanged(TaskImpl.this);
}
myEnabled = false;
}
public void enable() {
myEnabled = true;
}
}
private static class FieldChange {
String myFieldName;
Object myFieldValue;
EventSender myEventSender;
void setValue(Object newValue) {
myFieldValue = newValue;
myEventSender.enable();
}
}
private static class DurationChange extends FieldChange {
Date getCachedDate(int length) {
if (myDates == null) {
return null;
}
int index = length - myMinLength;
if (index < 0 || index >= myDates.size()) {
return null;
}
return (Date) myDates.get(index);
}
void cacheDate(Date date, int length) {
if (myDates == null) {
myDates = new ArrayList();
}
int index = length - myMinLength;
while (index <= -1) {
myDates.add(0, null);
index++;
}
while (index > myDates.size()) {
myDates.add(null);
}
if (index == -1) {
myDates.add(0, date);
} else if (index == myDates.size()) {
myDates.add(date);
} else {
myDates.set(index, date);
}
}
private int myMinLength = 0;
private List myDates;
}
private class MutatorImpl implements TaskMutator {
private EventSender myPropertiesEventSender = new PropertiesEventSender();
private EventSender myProgressEventSender = new ProgressEventSender();
private FieldChange myCompletionPercentageChange;
private FieldChange myStartChange;
private FieldChange myEndChange;
private FieldChange myThirdChange;
private DurationChange myDurationChange;
private List myActivities;
private final List myCommands = new ArrayList();
private int myIsolationLevel;
public void commit() {
try {
boolean fireChanges = false;
if (myStartChange != null) {
123
GanttCalendar start = getStart();
TaskImpl.this.setStart(start);
}
if (myDurationChange != null) {
TaskLength duration = getDuration();
TaskImpl.this.setDuration(duration);
myEndChange = null;
}
if (myCompletionPercentageChange != null) {
int newValue = getCompletionPercentage();
TaskImpl.this.setCompletionPercentage(newValue);
}
if (myEndChange != null) {
GanttCalendar end = getEnd();
TaskImpl.this.setEnd(end);
}
if (myThirdChange != null) {
GanttCalendar third = getThird();
TaskImpl.this.setThirdDate(third);
}
for (int i = 0; i < myCommands.size(); i++) {
Runnable next = (Runnable) myCommands.get(i);
next.run();
}
myCommands.clear();
myPropertiesEventSender.fireEvent();
myProgressEventSender.fireEvent();
} finally {
TaskImpl.this.myMutator = null;
}
}
public GanttCalendar getThird() {
return myThirdChange == null ? TaskImpl.this.myThird
: (GanttCalendar) myThirdChange.myFieldValue;
}
public List getActivities() {
if (myActivities == null && (myStartChange != null)
|| (myDurationChange != null)) {
myActivities = new ArrayList();
TaskImpl.this.recalculateActivities(myActivities, getStart()
.getTime(), getEnd().getTime());
}
return myActivities;
}
public void setName(final String name) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setName(name);
}
});
}
public void setProjectTask(final boolean projectTask) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setProjectTask(projectTask);
}
});
}
public void setMilestone(final boolean milestone) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setMilestone(milestone);
}
});
}
public void setPriority(final int priority) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setPriority(priority);
}
});
}
public void setStart(final GanttCalendar start) {
if (myStartChange == null) {
myStartChange = new FieldChange();
myStartChange.myEventSender = myPropertiesEventSender;
}
myStartChange.setValue(start);
myActivities = null;
}
public void setEnd(final GanttCalendar end) {
if (myEndChange == null) {
124
myEndChange = new FieldChange();
myEndChange.myEventSender = myPropertiesEventSender;
}
myEndChange.setValue(end);
myActivities = null;
}
public void setThird(final GanttCalendar third,
final int thirdDateConstraint) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setThirdDateConstraint(thirdDateConstraint);
}
});
if (myThirdChange == null) {
myThirdChange = new FieldChange();
myThirdChange.myEventSender = myPropertiesEventSender;
}
myThirdChange.setValue(third);
myActivities = null;
}
public void setDuration(final TaskLength length) {
if (myDurationChange == null) {
myDurationChange = new DurationChange();
myDurationChange.myEventSender = myPropertiesEventSender;
myDurationChange.setValue(length);
} else {
TaskLength currentLength = (TaskLength) myDurationChange.myFieldValue;
if (currentLength.getLength() - length.getLength() == 0) {
return;
}
}
TaskLength prevLength = (TaskLength) myDurationChange.myFieldValue;
// System.err.println("new duration="+length+"
// previous="+prevLength);
// Date prevEnd =
// myDurationChange.getCachedDate((int)prevLength.getLength());
Date prevEnd = null;
// System.err.println("previously cached shift="+prevEnd);
myDurationChange.setValue(length);
GanttCalendar newEnd;
Date shifted;
if (prevEnd == null) {
// System.err.println("no prev, length="+length.getLength());
shifted = TaskImpl.this.shiftDate(getStart().getTime(), length
.getTimeUnit(), length.getLength());
} else {
// System.err.println("yes prev,
// length="+(length.getLength()-prevLength.getLength()));
shifted = TaskImpl.this.shiftDate(prevEnd,
length.getTimeUnit(), length.getLength()
- prevLength.getLength());
}
// System.err.println("caching shift="+shifted+" for
// duration="+length);
// myDurationChange.cacheDate(shifted, (int)length.getLength());
newEnd = new GanttCalendar(shifted);
setEnd(newEnd);
myActivities = null;
}
public void setExpand(final boolean expand) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setExpand(expand);
}
});
}
public void setCompletionPercentage(final int percentage) {
if (myCompletionPercentageChange == null) {
myCompletionPercentageChange = new FieldChange();
myCompletionPercentageChange.myEventSender = myProgressEventSender;
}
myCompletionPercentageChange.setValue(new Integer(percentage));
}
public void setStartFixed(final boolean isFixed) {
myCommands.add(new Runnable() {
125
public void run() {
TaskImpl.this.setStartFixed(isFixed);
}
});
}
// public void setFinishFixed(final boolean isFixed) {
// myCommands.add(new Runnable() {
// public void run() {
// TaskImpl.this.setFinishFixed(isFixed);
// }
// });
//
// }
public void setCritical(final boolean critical) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setCritical(critical);
}
});
}
public void setShape(final ShapePaint shape) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setShape(shape);
}
});
}
public void setColor(final Color color) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setColor(color);
}
});
}
public void setNotes(final String notes) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setNotes(notes);
}
});
}
public void addNotes(final String notes) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.addNotes(notes);
}
});
}
public int getCompletionPercentage() {
return myCompletionPercentageChange == null ? TaskImpl.this.myCompletionPercentage
: ((Integer) myCompletionPercentageChange.myFieldValue)
.intValue();
}
GanttCalendar getStart() {
return myStartChange == null ? TaskImpl.this.myStart
: (GanttCalendar) myStartChange.myFieldValue;
}
GanttCalendar getEnd() {
return myEndChange == null ? TaskImpl.this.myEnd
: (GanttCalendar) myEndChange.myFieldValue;
}
TaskLength getDuration() {
return myDurationChange == null ? TaskImpl.this.myLength
: (TaskLength) myDurationChange.myFieldValue;
}
public void shift(float unitCount) {
Task result = getPrecomputedShift(unitCount);
if (result == null) {
result = TaskImpl.this.shift(unitCount);
cachePrecomputedShift(result, unitCount);
}
// System.err.println("[MutatorImpl] shift(): result="+result);
setStart(result.getStart());
setDuration(result.getDuration());
setEnd(result.getEnd());
}
public void shift(TaskLength shift) {
126
TaskImpl.this.shift(shift);
}
public void setIsolationLevel(int level) {
myIsolationLevel = level;
}
private void cachePrecomputedShift(Task result, float unitCount) {
}
private Task getPrecomputedShift(float unitCount) {
return null;
}
private TaskInfo myTaskInfo;
public TaskInfo getTaskInfo() {
return myTaskInfo;
}
public void setTaskInfo(TaskInfo taskInfo) {
myTaskInfo = taskInfo;
}
//LH
public void setBudget(final double cost) {
myCommands.add(new Runnable() {
public void run() {
TaskImpl.this.setBudget(cost);
}
});
}
}
public void setName(String name) {
myName = name;
}
public void setWebLink(String webLink) {
myWebLink = webLink;
}
public void setMilestone(boolean milestone) {
isMilestone = milestone;
}
public void setPriority(int priority) {
myPriority = priority;
}
public void setStart(GanttCalendar start) {
Date closestWorkingStart = myManager.findClosestWorkingTime(start
.getTime());
start.setTime(closestWorkingStart);
GanttCalendar oldStart = myStart == null ? null : myStart.Clone();
myStart = start;
if (areEventsEnabled()) {
myManager.fireTaskScheduleChanged(this, oldStart, getEnd());
}
recalculateActivities();
}
public void setEnd(GanttCalendar end) {
GanttCalendar oldFinish = myEnd == null ? null : myEnd.Clone();
myEnd = end;
recalculateActivities();
// System.err.println("we have "+myActivities.size()+" activities");
if (areEventsEnabled()) {
myManager.fireTaskScheduleChanged(this, myStart.Clone(), oldFinish);
}
}
public void setThirdDate(GanttCalendar third) {
GanttCalendar oldThird = myThird == null ? null : myThird.Clone();
myThird = third;
// recalculateActivities();
// if (areEventsEnabled()) {
// myManager.fireTaskScheduleChanged(this, myThird.Clone(), oldThird);
// }
}
127
public void setThirdDateConstraint(int thirdDateConstraint) {
myThirdDateConstraint = thirdDateConstraint;
}
public void shift(TaskLength shift) {
float unitCount = shift.getLength(myLength.getTimeUnit());
if (unitCount != 0f) {
Task resultTask = shift(unitCount);
GanttCalendar oldStart = myStart;
GanttCalendar oldEnd = myEnd;
myStart = resultTask.getStart();
myLength = resultTask.getDuration();
myEnd = resultTask.getEnd();
if (areEventsEnabled()) {
myManager.fireTaskScheduleChanged(this, oldStart, oldEnd);
}
recalculateActivities();
}
}
public Task shift(float unitCount) {
Task clone = unpluggedClone();
if (unitCount > 0) {
TaskLength length = myManager.createLength(myLength.getTimeUnit(),
unitCount);
// clone.setDuration(length);
Date shiftedDate = shiftDate(myStart.getTime(), length
.getTimeUnit(), length.getLength(), RESTLESS_CALENDAR);
clone.setStart(new GanttCalendar(shiftedDate));
clone.setDuration(myLength);
} else {
// TODO: hack assuming unit=day
// clone.setStart(clone.getStart().newAdd((int)unitCount));
Date newStart = shiftDate(clone.getStart().getTime(), clone
.getDuration().getTimeUnit(), (long) unitCount);
clone.setStart(new GanttCalendar(newStart));
clone.setDuration(myLength);
}
return clone;
}
public void setDuration(TaskLength length) {
GanttCalendar oldFinish = myEnd == null ? null : myEnd.Clone();
myLength = length;
Date newEndDate = shiftDate(myStart.getTime(),
length.getTimeUnit(), length.getLength());
myEnd = new GanttCalendar(newEndDate);
// myEnd = myStart.newAdd((int) length.getLength());
recalculateActivities();
if (areEventsEnabled()) {
myManager.fireTaskScheduleChanged(this, myStart.Clone(),
oldFinish);
}
}
private Date shiftDate(Date input, TimeUnit timeUnit, long length) {
return shiftDate(input, timeUnit, length, myManager.getConfig()
.getCalendar());
}
private Date shiftDate(Date input, TimeUnit timeUnit, long length,
GPCalendar calendar) {
List activities = calendar.getActivities(input, timeUnit, length);
if (activities.isEmpty()) {
throw new RuntimeException("Can't set length=" + length + " start="
+ input);
}
Date result;
if (length >= 0) {
GPCalendarActivity lastActivity = (GPCalendarActivity) activities
.get(activities.size() - 1);
result = lastActivity.getEnd();
} else {
GPCalendarActivity firstActivity = (GPCalendarActivity) activities
.get(0);
result = firstActivity.getStart();
}
return result;
}
128
public TaskLength translateDuration(TaskLength duration) {
return myManager.createLength(myLength.getTimeUnit(),
translateDurationValue(duration));
}
private float translateDurationValue(TaskLength duration) {
if (myLength.getTimeUnit().equals(duration.getTimeUnit())) {
return duration.getValue();
}
if (myLength.getTimeUnit().isConstructedFrom(duration.getTimeUnit())) {
return duration.getValue()
/ myLength.getTimeUnit().getAtomCount(
duration.getTimeUnit());
}
if (duration.getTimeUnit().isConstructedFrom(myLength.getTimeUnit())) {
return duration.getValue()
* duration.getTimeUnit().getAtomCount(
myLength.getTimeUnit());
}
throw new RuntimeException("Can't transalte duration=" + duration
+ " into units=" + myLength.getTimeUnit());
}
private void recalculateActivities() {
if (myEnd == null || myManager == null) {
return;
}
recalculateActivities(myActivities, myStart.getTime(), myEnd.getTime());
int length = 0;
for (int i = 0; i < myActivities.size(); i++) {
TaskActivity next = (TaskActivity) myActivities.get(i);
if (next.getIntensity() > 0) {
length += next.getDuration().getLength(
getDuration().getTimeUnit());
}
}
myLength = getManager().createLength(myLength.getTimeUnit(), length);
}
private void recalculateActivities(List output, Date startDate, Date endDate) {
GPCalendar calendar = myManager.getConfig().getCalendar();
List activities = calendar.getActivities(startDate, endDate);
output.clear();
for (int i = 0; i < activities.size(); i++) {
GPCalendarActivity nextCalendarActivity = (GPCalendarActivity) activities
.get(i);
TaskActivityImpl nextTaskActivity;
if (nextCalendarActivity.isWorkingTime()) {
nextTaskActivity = new TaskActivityImpl(this,
nextCalendarActivity.getStart(), nextCalendarActivity
.getEnd());
} else if (i > 0 && i + 1 < activities.size()) {
nextTaskActivity = new TaskActivityImpl(this,
nextCalendarActivity.getStart(), nextCalendarActivity
.getEnd(), 0);
} else {
continue;
}
output.add(nextTaskActivity);
}
}
public void setCompletionPercentage(int percentage) {
int oldPercentage = myCompletionPercentage;
myCompletionPercentage = percentage;
if (oldPercentage != myCompletionPercentage) {
EventSender progressEventSender = new ProgressEventSender();
progressEventSender.enable();
progressEventSender.fireEvent();
}
}
public void setStartFixed(boolean isFixed) {
isStartFixed = isFixed;
}
// public void setFinishFixed(boolean isFixed) {
// isFinishFixed = isFixed;
// }
public void setShape(ShapePaint shape) {
myShape = shape;
}
129
public void setColor(Color color) {
myColor = color;
}
public void setNotes(String notes) {
myNotes = notes;
}
public void setExpand(boolean expand) {
bExpand = expand;
}
public void addNotes(String notes) {
myNotes += notes;
}
protected void enableEvents(boolean enabled) {
myEventsEnabled = enabled;
}
protected boolean areEventsEnabled() {
return myEventsEnabled;
}
/**
* Allows to determine, if a special shape is defined for this task.
*
* @return true, if this task has its own shape defined.
*/
public boolean shapeDefined() {
return (myShape != null);
}
/**
* Allows to determine, if a special color is defined for this task.
*
* @return true, if this task has its own color defined.
*/
public boolean colorDefined() {
return (myColor != null);
}
public String toString() {
return myName + ": " + myStart.getTime() + "-" + myLength;
}
public boolean isUnplugged() {
return myTaskHierarchyItem == null;
}
/**
* Returns the CustomColumnValues.
*
* @return The CustomColumnValues.
*/
public CustomColumnsValues getCustomValues() {
return customValues;
}
/**
* @inheritDoc
*/
public void setCritical(boolean critical) {
this.critical = critical;
}
/**
* @inheritDoc
*/
public boolean isCritical() {
return this.critical;
}
// TODO: implementation of this method has no correlation with algorithms
// recalculating schedules,
// doesn't affect subtasks and supertasks. It is necessary to call this
// method explicitly from other
// parts of code to be sure that constraint fulfils
//
// Method GanttCalendar.newAdd() assumes that time unit is day
public void applyThirdDateConstraint() {
TaskLength length = getDuration();
if (getThird() != null)
switch (getThirdDateConstraint()) {
case EARLIESTBEGIN:
130
// TODO: TIME UNIT (assumption about days)
if (getThird().after(getStart())) {
int difference = getThird().diff(getStart());
GanttCalendar _start = getStart().newAdd(difference);
GanttCalendar _end = getEnd().newAdd(difference);
setEnd(_end);
setStart(_start);
setDuration(length);
}
break;
}
}
private TaskInfo myTaskInfo;
public TaskInfo getTaskInfo() {
return myTaskInfo;
}
public void setTaskInfo(TaskInfo taskInfo) {
myTaskInfo = taskInfo;
}
public boolean isProjectTask() {
return isProjectTask;
}
public void setProjectTask(boolean projectTask) {
isProjectTask = projectTask;
}
private static final GPCalendar RESTLESS_CALENDAR = new AlwaysWorkingTimeCalendarImpl();
//LH
public double getBudget() {
return myBudget;
}
//LH
public void setBudget(double cost) {
myBudget = cost;
}
}
net.sourceforge.ganttproject.task. TaskNode
package net.sourceforge.ganttproject.task;
import javax.swing.tree.DefaultMutableTreeNode;
import net.sourceforge.ganttproject.GanttCalendar;
/**
* This class is the class to use to discribe the tasks hierarchy.
*
* @author bbaranne (Benoit Baranne)
*/
public class TaskNode extends DefaultMutableTreeNode {
/**
* The reference task
*/
private final Task task;
/**
* Creates an instance of TaskNode with the given task as reference.
*
* @param t
* Task of reference.
*/
public TaskNode(Task t) {
super(t);
task = t;
}
/**
* Sets the priority of the task.
*
* @param priority
* The priority to be set.
*/
public void setPriority(int priority) {
task.setPriority(priority);
}
/**
* Returns the priority of the task.
*
* @return The priority of the task.
131
*/
public int getPriority() {
return task.getPriority();
}
/**
* Sets the name of the task.
*
* @param newName
* The name to be set.
*/
public void setName(String newName) {
task.setName(newName);
}
/**
* Returns the name of the task.
*
* @return The name of the task.
*/
public String getName() {
return task.getName();
}
/**
* Sets the start date of the task.
*
* @param startDate
* The start date of the task to be set.
*/
public void setStart(GanttCalendar startDate) {
task.setStart(startDate);
}
/**
* Returns the start date of the task.
*
* @return The start date of the task.
*/
public GanttCalendar getStart() {
return task.getStart();
}
/**
* Sets the end date of the task.
*
* @param endDate
* The end date of the task to be set.
*/
public void setEnd(GanttCalendar endDate) {
task.setEnd(endDate);
}
/**
* Returns the end date of the task.
*
* @return The end date of the task.
*/
public GanttCalendar getEnd() {
return task.getEnd();
}
/**
* Sets the duration of the task.
*
* @param length
* The duration to be set.
*/
public void setDuration(TaskLength length) {
task.setDuration(length);
}
/**
* Returns the duration of the task.
*
* @return The duration of the task.
*/
public int getDuration() {
return (int) task.getDuration().getValue();
}
/**
* Sets the completion percentage of the task.
*
* @param percentage
* The percentage to be set.
*/
public void setCompletionPercentage(int percentage) {
task.setCompletionPercentage(percentage);
}
/**
132
* Returns the completion percentage of the task.
*
* @return The completion percentage of the task.
*/
public int getCompletionPercentage() {
return task.getCompletionPercentage();
}
public void setTaskInfo(TaskInfo info) {
task.setTaskInfo(info);
}
public TaskInfo getTaskInfo() {
return task.getTaskInfo();
}
/**
* @inheritDoc
*/
public String toString() {
return task.getName();
}
/**
* @inheritDoc
*/
public Object getUserObject() {
return task;
}
public void applyThirdDateConstraint() {
if (task.getThird() != null)
switch (task.getThirdDateConstraint()) {
case TaskImpl.EARLIESTBEGIN:
if (task.getThird().after(getStart())) {
task.setStart(task.getThird().newAdd(0));
}
}
}
/**
* Sets the budget of the task.
*
* @param budget
* The budget to be set.
*/
public void setBudget(double budget) {
task.setBudget(budget);
}
/**
* Returns the budget of the task.
*
* @return The budget of the task.
*/
public double getBudget() {
return task.getBudget();
}
}
net.sourceforge.ganttproject.task. MutableTask
package net.sourceforge.ganttproject.task;
import java.awt.Color;
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.shape.ShapePaint;
/**
* Created by IntelliJ IDEA.
*
* @author bard Date: 06.02.2004
*/
public interface MutableTask {
void setName(String name);
void setMilestone(boolean isMilestone);
void setPriority(int priority);
void setStart(GanttCalendar start);
void setEnd(GanttCalendar end);
void setDuration(TaskLength length);
void shift(TaskLength shift);
133
void setCompletionPercentage(int percentage);
void setStartFixed(boolean isFixed);
// void setFinishFixed(boolean isFixed);
void setShape(ShapePaint shape);
void setColor(Color color);
void setNotes(String notes);
void addNotes(String notes);
void setExpand(boolean expand);
//LH
void setBudget(double budget);
/**
* Sets the task as critical or not. The method is used be TaskManager after
* having run a CriticalPathAlgorithm to set the critical tasks. When
* painted, the tasks are rendered as critical using Task.isCritical(). So,
* a task is set as critical only if critical path is displayed.
*
* @param critical
* <code>true</code> if this is critical, <code>false</code>
* otherwise.
*/
void setCritical(boolean critical);
void setTaskInfo(TaskInfo taskInfo);
void setProjectTask (boolean projectTask);
}
net.sourceforge.ganttproject.task. TaskProperties
package net.sourceforge.ganttproject.task;
import java.text.NumberFormat;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.dependency.TaskDependency;
/**
* Class with which one can get any properties (even custom) from any task.
*
* @author bbaranne
*
*/
public class TaskProperties {
public static final String ID_TASK_DATES = "taskDates";
public static final String ID_TASK_NAME = "name";
public static final String ID_TASK_LENGTH = "length";
//LH
public static final String ID_TASK_BUDGET = "budget";
public static final String ID_TASK_ADVANCEMENT = "advancement";
public static final String ID_TASK_COORDINATOR = "coordinator";
public static final String ID_TASK_RESOURCES = "resources";
public static final String ID_TASK_ID = "id";
public static final String ID_TASK_PREDECESSORS = "predecessors";
/**
* Returns the task property specified by <code>propertyID</code>.
*
* @param task
* The task from which we want the property.
* @param propertyID
* The property ID which could be <code>ID_TASK_DATES</code>,
* <code>ID_TASK_NAME</code>, ... or a custom column name.
* @return the task property specified by <code>propertyID</code>. The
134
* result may be <code>null</code>.
*/
public static Object getProperty(Task task, String propertyID) {
Object res = null;
StringBuffer sb = new StringBuffer();
if (propertyID != null) {
if (propertyID.equals(ID_TASK_DATES)) {
sb.append(" [ ");
sb.append(task.getStart() + " - " + task.getEnd());
sb.append(" ] ");
res = sb.toString();
} else if (propertyID.equals(ID_TASK_NAME)) {
sb.append(" " + task.getName() + " ");
res = sb.toString();
} else if (propertyID.equals(ID_TASK_LENGTH)) {
sb.append(" [ ");
sb.append((int) task.getDuration().getLength() + " "
+ GanttLanguage.getInstance().getText("days"));
sb.append(" ] ");
res = sb.toString();
} else if (propertyID.equals(ID_TASK_BUDGET)) { //LH
sb.append(" [ ");
//LH
//sb.append((double) task.getBudget() + " $");
sb.append(NumberFormat.getCurrencyInstance().format(task.getBudget()));
sb.append(" ] ");
res = sb.toString();
} else if (propertyID.equals(ID_TASK_ADVANCEMENT)) {
sb.append(" [ ");
sb.append(task.getCompletionPercentage() + "%");
sb.append(" ] ");
res = sb.toString();
} else if (propertyID.equals(ID_TASK_COORDINATOR)) {
ResourceAssignment[] assignments = task.getAssignments();
if (assignments.length > 0) {
boolean first = true;
boolean close = false;
int j = 0;
for (int i = 0; i < assignments.length; i++) {
if (assignments[i].isCoordinator()) {
j++;
if (first) {
close = true;
first = false;
sb.append("{");
}
if (j > 1) {
sb.append(", ");
}
sb.append(assignments[i].getResource().getName());
}
}
if (close)
sb.append("}");
}
res = sb.toString();
} else if (propertyID.equals(ID_TASK_RESOURCES)) {
ResourceAssignment[] assignments = task.getAssignments();
if (assignments.length > 0) {
sb.append(" ");
for (int i = 0; i < assignments.length; i++) {
sb.append(assignments[i].getResource().getName());
if (i < assignments.length - 1) {
sb.append(",");
}
}
sb.append(" ");
}
res = sb.toString();
} else if (propertyID.equals(ID_TASK_ID)) {
sb.append("# ").append(task.getTaskID());
res = sb.toString();
} else if (propertyID.equals(ID_TASK_PREDECESSORS)) {
TaskDependency[] dep = task.getDependenciesAsDependant().toArray();
int i = 0;
if (dep != null && dep.length > 0) {
for (i = 0; i < dep.length - 1; i++)
sb.append(dep[i].getDependee().getTaskID() + ", ");
sb.append(dep[i].getDependee().getTaskID());
}
res = sb.toString();
} else {
res = task.getCustomValues().getValue(propertyID);
}
135
}
return res;
}
}
net.sourceforge.ganttproject. GanttTreeTable
package net.sourceforge.ganttproject;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.Action;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import net.sourceforge.ganttproject.delay.Delay;
import net.sourceforge.ganttproject.gui.GanttDialogCustomColumn;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.CustomColumn;
import net.sourceforge.ganttproject.task.CustomColumnsException;
import net.sourceforge.ganttproject.task.CustomColumnsManager;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskContainmentHierarchyFacade;
import net.sourceforge.ganttproject.task.TaskNode;
import net.sourceforge.ganttproject.util.DateUtils;
import org.jdesktop.jdnc.JNTreeTable;
import org.jdesktop.swing.decorator.AlternateRowHighlighter;
import org.jdesktop.swing.decorator.HierarchicalColumnHighlighter;
import org.jdesktop.swing.decorator.Highlighter;
import org.jdesktop.swing.decorator.HighlighterPipeline;
import org.jdesktop.swing.table.TableColumnExt;
import org.jdesktop.swing.treetable.TreeTableModel;
/**
* Treetable used to displayed tabular data and hierarchical data.
*
* @author bbaranne
* @version 1.0 (20050301) (yyyymmdd)
*/
public class GanttTreeTable extends JNTreeTable {
136
/**
* Unique instance of GanttLanguage.
*/
private static GanttLanguage language = GanttLanguage.getInstance();
/**
* PopupMenu showed on right click (window, linux) on the table header.
*/
private JPopupMenu popupMenu;
/**
* Map ColumnName -> MenuItem
*/
private Map mapColNameMenuItem;
/**
* Point where the user has just right clicked on the table header.
*/
private Point clickPoint = null;
/**
* model of the treetable.
*/
private GanttTreeTableModel ttModel;
/**
* stores the tableColum associated with there ColumnKeeper. it is used to
* retore the column at the same index it has been removed.
*/
private Map mapTableColumnColumnKeeper = null;
/**
* Menu item to delete columns.
*/
private JMenuItem jmiDeleteColumn;
DisplayedColumnsList listDisplayedColumns = null;
/**
* Creates an instance of GanttTreeTable with the given TreeTableModel.
*
* @param model
* TreeTableModel.
*/
public GanttTreeTable(TreeTableModel model) {
super(model);
initTreeTable();
}
public void setAction(Action action) {
InputMap inputMap = new InputMap();
inputMap.put((KeyStroke) action.getValue(Action.ACCELERATOR_KEY),
action.getValue(Action.NAME));
inputMap.setParent(getTreeTable().getInputMap(JComponent.WHEN_FOCUSED));
getTreeTable().setInputMap(JComponent.WHEN_FOCUSED, inputMap);
// Add the action to the component
getTreeTable().getActionMap().put(action.getValue(Action.NAME), action);
}
private void updateDisplayedColumnsOrder() {
Iterator it = this.listDisplayedColumns.iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
if (dc.isDisplayed()) {
String id = dc.getID();
String name = getNameForId(id);
int viewIndex = getTable().convertColumnIndexToView(
getColumn(name).getModelIndex());
dc.setOrder(viewIndex);
dc.setWidth(getColumn(name).getPreferredWidth());
}
}
}
public DisplayedColumnsList getDisplayColumns() {
updateDisplayedColumnsOrder();
return this.listDisplayedColumns;
}
public void setDisplayedColumns(DisplayedColumnsList displayedColumns) {
137
DisplayedColumnsList l = (DisplayedColumnsList) displayedColumns
.clone();
if (displayedColumns.size() != 0) {
this.listDisplayedColumns = displayedColumns;
displayAllColumns();
hideAllColumns();
this.listDisplayedColumns = l;
}
Collections.sort(this.listDisplayedColumns);
Iterator it = this.listDisplayedColumns.iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
String id = dc.getID();
String name = getNameForId(id);
if (dc.displayed)
displayColumn(name);
else
hideColumn(name);
}
}
/**
* Initialize the treetable. Addition of various listeners, tree's icons,
*/
public void initTreeTable() {
clickPoint = null;
if(Mediator.getCustomColumnsManager() == null)
Mediator.registerCustomColumnsManager(new CustomColumnsManager(this));
mapColNameMenuItem = new HashMap();
mapTableColumnColumnKeeper = new HashMap();
ttModel = (GanttTreeTableModel) this.getTreeTableModel();
Enumeration enumeration = getTable().getColumnModel().getColumns();
Collection lToDel = new ArrayList();
while (enumeration.hasMoreElements()) {
TableColumnExt tc = (TableColumnExt) enumeration.nextElement();
// System.out.println(tc.getTitle());
// if (!ttModel.titles.contains(tc.getTitle()))
lToDel.add(tc);
}
Iterator it = lToDel.iterator();
while (it.hasNext())
getTable().removeColumn((TableColumn) it.next());
getTable().setAutoCreateColumnsFromModel(false);
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
TableColumnExt tce1 = new TableColumnExt(0);
tce1.setTitle(GanttTreeTableModel.strColType);
TableColumnExt tce2 = new TableColumnExt(1);
tce2.setTitle(GanttTreeTableModel.strColPriority);
TableColumnExt tce3 = new TableColumnExt(2);
tce3.setTitle(GanttTreeTableModel.strColInfo);
TableColumnExt tce4 = new TableColumnExt(3);
tce4.setTitle(GanttTreeTableModel.strColName);
TableColumnExt tce5 = new TableColumnExt(4);
tce5.setTitle(GanttTreeTableModel.strColBegDate);
TableColumnExt tce6 = new TableColumnExt(5);
tce6.setTitle(GanttTreeTableModel.strColEndDate);
TableColumnExt tce7 = new TableColumnExt(6);
tce7.setTitle(GanttTreeTableModel.strColDuration);
TableColumnExt tce8 = new TableColumnExt(7);
tce8.setTitle(GanttTreeTableModel.strColCompletion);
TableColumnExt tce9 = new TableColumnExt(8);
tce9.setTitle(GanttTreeTableModel.strColCoordinator);
TableColumnExt tce10 = new TableColumnExt(9);
tce10.setTitle(GanttTreeTableModel.strColPredecessors);
TableColumnExt tce11 = new TableColumnExt(10);
tce11.setTitle(GanttTreeTableModel.strColID);
//LH
TableColumnExt tce12 = new TableColumnExt(11);
tce12.setTitle(GanttTreeTableModel.strColBudget);
this.addColumn(tce1);
this.addColumn(tce2);
this.addColumn(tce3);
this.addColumn(tce4);
this.addColumn(tce5);
this.addColumn(tce6);
this.addColumn(tce7);
this.addColumn(tce8);
this.addColumn(tce9);
this.addColumn(tce10);
138
this.addColumn(tce11);
this.addColumn(tce12);
listDisplayedColumns = new DisplayedColumnsList();
// Type
DisplayedColumn dc1 = new DisplayedColumn(getIdForName(tce1.getTitle()));
dc1.setDisplayed(false);
dc1.setOrder(this.getTable().convertColumnIndexToView(
tce1.getModelIndex()));
dc1.setWidth(tce1.getPreferredWidth());
listDisplayedColumns.add(dc1);
// Priority
DisplayedColumn dc2 = new DisplayedColumn(getIdForName(tce2.getTitle()));
dc2.setDisplayed(false);
dc2.setOrder(this.getTable().convertColumnIndexToView(
tce2.getModelIndex()));
dc2.setWidth(tce2.getPreferredWidth());
listDisplayedColumns.add(dc2);
// Info
DisplayedColumn dc3 = new DisplayedColumn(getIdForName(tce3.getTitle()));
dc3.setDisplayed(false);
dc3.setOrder(this.getTable().convertColumnIndexToView(
tce3.getModelIndex()));
dc3.setWidth(tce3.getPreferredWidth());
listDisplayedColumns.add(dc3);
// Name
DisplayedColumn dc4 = new DisplayedColumn(getIdForName(tce4.getTitle()));
dc4.setDisplayed(true);
dc4.setOrder(this.getTable().convertColumnIndexToView(
tce4.getModelIndex()));
dc4.setWidth(tce4.getPreferredWidth());
listDisplayedColumns.add(dc4);
// Begin date
DisplayedColumn dc5 = new DisplayedColumn(getIdForName(tce5.getTitle()));
dc5.setDisplayed(true);
dc5.setOrder(this.getTable().convertColumnIndexToView(
tce5.getModelIndex()));
dc5.setWidth(tce5.getPreferredWidth());
listDisplayedColumns.add(dc5);
// End date
DisplayedColumn dc6 = new DisplayedColumn(getIdForName(tce6.getTitle()));
dc6.setDisplayed(true);
dc6.setOrder(this.getTable().convertColumnIndexToView(
tce6.getModelIndex()));
dc6.setWidth(tce6.getPreferredWidth());
listDisplayedColumns.add(dc6);
// Duration
DisplayedColumn dc7 = new DisplayedColumn(getIdForName(tce7.getTitle()));
dc7.setDisplayed(false);
dc7.setOrder(this.getTable().convertColumnIndexToView(
tce7.getModelIndex()));
dc7.setWidth(tce7.getPreferredWidth());
listDisplayedColumns.add(dc7);
// Completion
DisplayedColumn dc8 = new DisplayedColumn(getIdForName(tce8.getTitle()));
dc8.setDisplayed(false);
dc8.setOrder(this.getTable().convertColumnIndexToView(
tce8.getModelIndex()));
dc8.setWidth(tce8.getPreferredWidth());
listDisplayedColumns.add(dc8);
// Coordinator
DisplayedColumn dc9 = new DisplayedColumn(getIdForName(tce9.getTitle()));
dc9.setDisplayed(false);
dc9.setOrder(this.getTable().convertColumnIndexToView(
tce9.getModelIndex()));
dc9.setWidth(tce9.getPreferredWidth());
listDisplayedColumns.add(dc9);
// Predecessors
DisplayedColumn dc10 = new DisplayedColumn(getIdForName(tce10
.getTitle()));
dc10.setDisplayed(false);
dc10.setOrder(this.getTable().convertColumnIndexToView(
tce10.getModelIndex()));
dc10.setWidth(tce10.getPreferredWidth());
listDisplayedColumns.add(dc10);
// ID
DisplayedColumn dc11 = new DisplayedColumn(getIdForName(tce11
.getTitle()));
dc11.setDisplayed(false);
dc11.setOrder(this.getTable().convertColumnIndexToView(
tce11.getModelIndex()));
dc11.setWidth(tce11.getPreferredWidth());
139
listDisplayedColumns.add(dc11);
// LH
// BUDGET
DisplayedColumn dc12 = new DisplayedColumn(getIdForName(tce12
.getTitle()));
dc12.setDisplayed(false);
dc12.setOrder(this.getTable().convertColumnIndexToView(
tce12.getModelIndex()));
dc12.setWidth(tce12.getPreferredWidth());
listDisplayedColumns.add(dc12);
this.setDisplayedColumns(listDisplayedColumns);
this.mapTableColumnColumnKeeper.put(tce1, null);
this.mapTableColumnColumnKeeper.put(tce2, null);
this.mapTableColumnColumnKeeper.put(tce3, null);
this.mapTableColumnColumnKeeper.put(tce4, null);
this.mapTableColumnColumnKeeper.put(tce5, null);
this.mapTableColumnColumnKeeper.put(tce6, null);
this.mapTableColumnColumnKeeper.put(tce7, null);
this.mapTableColumnColumnKeeper.put(tce8, null);
this.mapTableColumnColumnKeeper.put(tce9, null);
this.mapTableColumnColumnKeeper.put(tce10, null);
this.mapTableColumnColumnKeeper.put(tce11, null);
//LH
this.mapTableColumnColumnKeeper.put(tce12, null);
// the model must implement TableColumnModelListener
getTable().getColumnModel().addColumnModelListener(
(TableColumnModelListener) this.getTreeTableModel());
getTable().getModel().addTableModelListener(new ModelListener());
getTable().getTableHeader().addMouseListener(new HeaderMouseListener());
// The following is used to store the new index of a moved column in
// order
// to restore it properly.
getTable().getColumnModel().addColumnModelListener(
new TableColumnModelListener() {
public void columnAdded(TableColumnModelEvent e) {
// nothing to do
}
public void columnRemoved(TableColumnModelEvent e) {
// nothing to do
}
public void columnMoved(TableColumnModelEvent e) {
DefaultTableColumnModel o = (DefaultTableColumnModel) e
.getSource();
TableColumn tc = o.getColumn(e.getFromIndex());
ColumnKeeper ck = ((ColumnKeeper) mapTableColumnColumnKeeper
.get(tc));
if (ck != null)
ck.setInitIndex(e.getToIndex());
if (Mediator.getGanttProjectSingleton() != null)
Mediator.getGanttProjectSingleton().setAskForSave(
true);
updateDisplayedColumnsOrder();
}
public void columnMarginChanged(ChangeEvent e) {
// nothing to do
}
public void columnSelectionChanged(ListSelectionEvent e) {
// nothing to do
}
});
initColumnsAlignements();
// Highlighters to ease the reading of the table.
setHighlighters(new HighlighterPipeline(new Highlighter[] {
AlternateRowHighlighter.quickSilver,
new HierarchicalColumnHighlighter() }));
// set the CellEditor for the dates.
getTable().getColumnExt(GanttTreeTableModel.strColBegDate)
.setCellEditor(new DateCellEditor(new JTextField()));
getTable().getColumnExt(GanttTreeTableModel.strColEndDate)
.setCellEditor(new DateCellEditor(new JTextField()));
140
getTable().getColumnExt(GanttTreeTableModel.strColName).setCellEditor(
new NameCellEditor());
setShowHorizontalLines(true);
ImageIcon icon = new ImageIcon(getClass().getResource(
"/icons/simple_task.gif"));
setOpenIcon(null);
setClosedIcon(null);
setCollapsedIcon(new ImageIcon(getClass()
.getResource("/icons/plus.gif")));
setExpandedIcon(new ImageIcon(getClass()
.getResource("/icons/minus.gif")));
setLeafIcon(null);
createPopupMenu();
this.setHasColumnControl(false);
// this.getTable().moveColumn(0,2);
// List l = new ArrayList();
// DisplayedColumn dc1 = new DisplayedColumn("tpd3");
// DisplayedColumn dc2 = new DisplayedColumn("tpd8");
// dc1.setDisplayed(true);
// dc2.setDisplayed(true);
// l.add(dc1);
// l.add(dc2);
// this.setDisplayedColumns(l);
// // hideColumn("Name");
if (listDisplayedColumns != null)
this.setDisplayedColumns(listDisplayedColumns);
else
this.displayAllColumns();
Thread t = new Thread() {
public void run() {
calculateWidth();
revalidate();
}
};
SwingUtilities.invokeLater(t);
this.getTreeTable().getParent().setBackground(Color.WHITE);
EventListener listeners[] = this.getTreeTable().getParent()
.getListeners(MouseListener.class);
for (int i = 0; i < listeners.length; i++)
this.getTreeTable().getParent().removeMouseListener(
(MouseListener) listeners[i]);
this.getTreeTable().getParent().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
e.consume();
if (e.getClickCount() == 1)
Mediator.getGanttProjectSingleton().getTree()
.selectTreeRow(-1);
else if (e.getClickCount() == 2
&& e.getButton() == MouseEvent.BUTTON1) {
Mediator.getGanttProjectSingleton().getUndoManager()
.undoableEdit("New Task by click", new Runnable() {
public void run() {
Mediator.getGanttProjectSingleton()
.newTask();
}
});
}
}
});
}
void addScrollPaneMouseListener(MouseListener ml) {
this.getTreeTable().getParent().addMouseListener(ml);
}
private void initColumnsAlignements() {
// set the columns horizontal aligment. It also associate an
// appropiate renderer according to the column class.
setColumnHorizontalAlignment(GanttTreeTableModel.strColType,
SwingConstants.CENTER);
setColumnHorizontalAlignment(GanttTreeTableModel.strColPriority,
SwingConstants.CENTER);
setColumnHorizontalAlignment(GanttTreeTableModel.strColInfo,
SwingConstants.CENTER);
// setColumnHorizontalAlignment(GanttTreeTableModel.strColName,
141
// SwingConstants.LEFT);
setColumnHorizontalAlignment(GanttTreeTableModel.strColBegDate,
SwingConstants.RIGHT);
setColumnHorizontalAlignment(GanttTreeTableModel.strColEndDate,
SwingConstants.RIGHT);
setColumnHorizontalAlignment(GanttTreeTableModel.strColDuration,
SwingConstants.CENTER);
setColumnHorizontalAlignment(GanttTreeTableModel.strColCompletion,
SwingConstants.CENTER);
setColumnHorizontalAlignment(GanttTreeTableModel.strColCoordinator,
SwingConstants.CENTER);
setColumnHorizontalAlignment(GanttTreeTableModel.strColPredecessors,
SwingConstants.RIGHT);
setColumnHorizontalAlignment(GanttTreeTableModel.strColID,
SwingConstants.CENTER);
//LH
setColumnHorizontalAlignment(GanttTreeTableModel.strColBudget,
SwingConstants.CENTER);
// Set the columns widths
getTable().getColumnExt(GanttTreeTableModel.strColID)
.setPreferredWidth(32);
//LH
getTable().getColumnExt(GanttTreeTableModel.strColBudget)
.setPreferredWidth(32);
getTable().getColumnExt(GanttTreeTableModel.strColType)
.setPreferredWidth(32);
getTable().getColumnExt(GanttTreeTableModel.strColPriority)
.setPreferredWidth(42);
getTable().getColumnExt(GanttTreeTableModel.strColInfo)
.setPreferredWidth(32);
getTable().getColumnExt(GanttTreeTableModel.strColName)
.setPreferredWidth(120);
getTable().getColumnExt(GanttTreeTableModel.strColDuration)
.setPreferredWidth(50);
// getTable().getColumnExt(GanttTreeTableModel.strColType).setMaxWidth(32);
// getTable().getColumnExt(GanttTreeTableModel.strColPriority).setMaxWidth(42);
// getTable().getColumnExt(GanttTreeTableModel.strColInfo).setMaxWidth(32);
// getTable().getColumnExt(GanttTreeTableModel.strColName).setMaxWidth(800);
// getTable().getColumnExt(GanttTreeTableModel.strColBegDate).setMaxWidth(300);
// getTable().getColumnExt(GanttTreeTableModel.strColEndDate).setMaxWidth(300);
// getTable().getColumnExt(GanttTreeTableModel.strColDuration).setMaxWidth(300);
// getTable().getColumnExt(GanttTreeTableModel.strColCompletion).setMaxWidth(300);
// getTable().getColumnExt(GanttTreeTableModel.strColCoordinator).setMaxWidth(300);
}
void calculateWidth() {
int width = 0;
int nbCol = getTable().getColumnCount();
for (int i = 0; i < nbCol; i++) {
TableColumnExt tce = getTable().getColumnExt(i);
if (tce.isVisible())
width += tce.getPreferredWidth();
}
getTable().setPreferredScrollableViewportSize(new Dimension(width, 0));
}
/**
* Creates the popupMenu used to hide/show columns and to add customs
* columns. It will associate each tablecolumn with an ColumnKeeper in
* charge of adding and removing the tablecolumn.
*/
private void createPopupMenu() {
142
Iterator it = mapTableColumnColumnKeeper.keySet().iterator();
mapColNameMenuItem.clear();
popupMenu = new JPopupMenu();
TableColumnModel tcModel = this.getTable().getColumnModel();
// int nbCol = tcModel.getColumnCount();
int nbCol = mapTableColumnColumnKeeper.keySet().size();
for (int i = 0; i < nbCol; i++) {
// TableColumn column = tcModel.getColumn(i);
TableColumn column = (TableColumn) it.next();
JCheckBoxMenuItem jcbmi = new JCheckBoxMenuItem(column
.getHeaderValue().toString());
ColumnKeeper ck = (ColumnKeeper) mapTableColumnColumnKeeper
.get(column);
if (ck == null)
ck = new ColumnKeeper(column);
jcbmi.setSelected(ck.isShown);
jcbmi.addActionListener(ck);
mapTableColumnColumnKeeper.put(column, ck);
mapColNameMenuItem.put(column.getHeaderValue().toString(), jcbmi);
popupMenu.add(jcbmi);
}
popupMenu.addSeparator();
JMenuItem jmiAddColumn = new JMenuItem(language
.getText("addCustomColumn"));
jmiAddColumn.setIcon(new ImageIcon(getClass().getResource(
"/icons/addCol_16.gif")));
jmiAddColumn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Mediator.getGanttProjectSingleton().getUndoManager()
.undoableEdit("PopUpNewColumn", new Runnable() {
public void run() {
Mediator.getCustomColumnsManager()
.addNewCustomColumn(null);
}
});
}
});
JMenuItem jmiDisplayAll = new JMenuItem(language.getText("displayAll"));
jmiDisplayAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Mediator.getGanttProjectSingleton().getUndoManager()
.undoableEdit("displayAllColumns", new Runnable() {
public void run() {
displayAllColumns();
}
});
}
});
/*
* To delete a custom column the user has to right click on the column
* header. If the colum header match with a custom column the menu item
* will be enable. Otherwise it is disable.
*/
jmiDeleteColumn = new JMenuItem(language.getText("deleteCustomColumn"));
jmiDeleteColumn.setIcon(new ImageIcon(getClass().getResource(
"/icons/removeCol_16.gif")));
jmiDeleteColumn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Mediator.getGanttProjectSingleton().getUndoManager()
.undoableEdit("deleteCustomColumn", new Runnable() {
public void run() {
// deleteCustomColumn(getTable().getColumnName(getTable().columnAtPoint(clickPoint)));
int ind = getTable().columnAtPoint(clickPoint);
if(ind >=0){
Mediator
.getCustomColumnsManager()
.deleteCustomColumn(getTable().getColumnName(ind));
jmiDeleteColumn.setEnabled(false);
}
143
}
});
}
});
jmiDeleteColumn.setEnabled(false);
popupMenu.add(jmiDisplayAll);
popupMenu.addSeparator();
popupMenu.add(jmiAddColumn);
popupMenu.add(jmiDeleteColumn);
}
private void reorderPopuMenu() {
int total = popupMenu.getComponentCount() - 5;
int last = popupMenu.getComponentCount() - 5;
for (int i = 0; i < total; i++)
popupMenu.remove(0);
Collections.sort(listDisplayedColumns);
Collections.reverse(listDisplayedColumns);
Iterator it = listDisplayedColumns.iterator();
boolean disable = false;
while (it.hasNext()) {
last = popupMenu.getComponentCount() - 5;
DisplayedColumn dc = (DisplayedColumn) it.next();
JMenuItem jmi = null;
int pos = 0;
if (dc.isDisplayed())
jmi = (JMenuItem) mapColNameMenuItem.get(getNameForId(dc.id));
else {
jmi = (JMenuItem) mapColNameMenuItem.get(getNameForId(dc.id));
pos = last;
}
popupMenu.add(jmi, pos);
}
Component comp[] = popupMenu.getComponents();
JCheckBoxMenuItem jcbmi = null;
for (int i = 0; i < comp.length; i++) {
if (comp[i] instanceof JCheckBoxMenuItem)
if (jcbmi == null) {
jcbmi = (JCheckBoxMenuItem) comp[i];
if (jcbmi.isSelected())
jcbmi.setEnabled(false);
else
jcbmi = null;
} else if (((JCheckBoxMenuItem) comp[i]).isSelected())
jcbmi.setEnabled(true);
}
Collection col = mapColNameMenuItem.keySet();
Iterator it2 = col.iterator();
while (it2.hasNext()) {
String s = (String) it2.next();
int o = listDisplayedColumns.getOrderForName(s);
if (o == -1)
popupMenu.add((JMenuItem) mapColNameMenuItem.get(s), last);
last = popupMenu.getComponentCount() - 5;
}
}
/**
* Rename the MenuItem named <code>oldName</code> intor
* <code>newName</code>.
*
* @param oldName
* MenuItem old name.
* @param newName
* MenuItem new name.
*/
private void renameMenuItem(String oldName, String newName) {
Component[] t = popupMenu.getComponents();
JCheckBoxMenuItem jcbmi = null;
for (int i = 0; i < t.length; i++) {
if (t[i] instanceof JCheckBoxMenuItem) {
jcbmi = (JCheckBoxMenuItem) t[i];
if (jcbmi.getText().equals(oldName)) {
jcbmi.setText(newName);
break;
}
}
}
if (jcbmi != null) {
mapColNameMenuItem.remove(oldName);
mapColNameMenuItem.put(newName, jcbmi);
}
}
/**
* Displays all the table columns.
144
*/
private void displayAllColumns() {
Iterator it = mapTableColumnColumnKeeper.values().iterator();
while (it.hasNext()) {
ColumnKeeper ck = (ColumnKeeper) it.next();
if (!ck.isShown)
ck.show();
}
createPopupMenu();
}
/**
* Displays all the table columns.
*/
private void hideAllColumns() {
Iterator it = mapTableColumnColumnKeeper.values().iterator();
while (it.hasNext()) {
ColumnKeeper ck = (ColumnKeeper) it.next();
if (ck.isShown)
ck.hide();
}
createPopupMenu();
}
/**
* Display the column whose name is given in parameter.
*
* @param name
* Name of the column to display.
*/
private void displayColumn(String name) {
int indexView = -1;
int width = -1;
Iterator itDc = this.listDisplayedColumns.iterator();
while (itDc.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) itDc.next();
if (getNameForId(dc.getID()).equals(name)) {
indexView = dc.getOrder();
width = dc.getWidth();
}
}
Iterator it = mapTableColumnColumnKeeper.keySet().iterator();
while (it.hasNext()) {
TableColumn c = (TableColumn) it.next();
String n = (String) c.getHeaderValue();
if (n.equals(name)) {
ColumnKeeper ck = (ColumnKeeper) mapTableColumnColumnKeeper
.get(c);
if (indexView != -1)
ck.index = indexView;
if (!ck.isShown)
ck.show();
break;
}
}
getTable().getColumnExt(name).setPreferredWidth(width);
createPopupMenu();
}
private void hideColumn(String name) {
Iterator it = mapTableColumnColumnKeeper.keySet().iterator();
while (it.hasNext()) {
TableColumn c = (TableColumn) it.next();
String n = (String) c.getHeaderValue();
if (n.equals(name)) {
ColumnKeeper ck = (ColumnKeeper) mapTableColumnColumnKeeper
.get(c);
if (ck.isShown)
ck.hide();
break;
}
}
createPopupMenu();
}
/**
* Adds a new custom column. The custom column will affect all tasks and
* future tasks. Several types are available for the custom columns (string,
* date, integer, double, boolean). A default value is also set.
*/
public void addNewCustomColumn(CustomColumn customColumn) {
if (customColumn == null) {
customColumn = new CustomColumn();
145
GanttDialogCustomColumn d = new GanttDialogCustomColumn(Mediator
.getGanttProjectSingleton(), customColumn);
d.setVisible(true);
}
if (customColumn.getName() != null) // if something has been entered
{
GanttTreeTableModel treeTableModel = (GanttTreeTableModel) getTreeTableModel();
int nbCol = treeTableModel.getColumnCountTotal(); // +
// treeTableModel.getCustomColumnCount();
String newName = customColumn.getName();
((GanttTreeTableModel) ttModel).addCustomColumn(newName);
try {
Mediator.getCustomColumnsStorage()
.addCustomColumn(customColumn);
} catch (CustomColumnsException ex) {
if (ex.getType() == CustomColumnsException.ALREADY_EXIST)
addNewCustomColumn(null);
return;
}
TaskContainmentHierarchyFacade tchf = Mediator
.getGanttProjectSingleton().getTaskManager()
.getTaskHierarchy();
setCustomColumnValueToAllNestedTask(tchf, tchf.getRootTask(),
customColumn.getName(), customColumn.getDefaultValue());
TableColumnExt t = new TableColumnExt(nbCol);
t.setMaxWidth(500);
t.setHeaderValue(newName);
getTable().getColumnModel().addColumn(t);
try {
if (clickPoint != null)
getTable().getColumnModel().moveColumn(
getTable().getColumnCount() - 1,
getTable().columnAtPoint(clickPoint));
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
int align = SwingConstants.CENTER;
if (customColumn.getType().equals(GregorianCalendar.class))
align = SwingConstants.RIGHT;
setColumnHorizontalAlignment(newName, align);
DisplayedColumn dc = new DisplayedColumn(Mediator
.getCustomColumnsStorage().getIdFromName(newName));
dc.setDisplayed(true);
dc.setOrder(getTable().convertColumnIndexToView(
getColumn(newName).getModelIndex()));
dc.setWidth(getColumn(newName).getPreferredWidth());
this.listDisplayedColumns.add(dc);
if (GregorianCalendar.class
.isAssignableFrom(customColumn.getType()))
getTable().getColumnExt(newName).setCellEditor(
new DateCellEditor(new JTextField()));
//
JCheckBoxMenuItem jcbmi = new JCheckBoxMenuItem(newName);
jcbmi.setSelected(true);
ColumnKeeper ck = new ColumnKeeper(t);
jcbmi.addActionListener(ck);
mapColNameMenuItem.put(newName, jcbmi);
mapTableColumnColumnKeeper.put(t, ck);
popupMenu.insert(jcbmi, popupMenu.getSubElements().length - 3);
//
Mediator.getGanttProjectSingleton().setAskForSave(true);
}
Thread t = new Thread() {
public void run() {
calculateWidth();
revalidate();
}
};
SwingUtilities.invokeLater(t);
}
/**
* Delete permanently a custom column.
146
*
* @param name
* Name of the column to delete.
*/
public void deleteCustomColumn(String name) {
try {
Mediator.getCustomColumnsStorage().getCustomColumn(name);
} catch (CustomColumnsException e) {
// e.printStackTrace();
return;
}
// the column has to be displayed to be removed.
this.displayColumn(name);
// DisplayedColumns
DisplayedColumn toDel = null;
Iterator it = listDisplayedColumns.iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
if (getNameForId(dc.getID()).equals(name))
toDel = dc;
}
if (toDel != null)
listDisplayedColumns.remove(toDel);
int index = getTable().getColumnModel().getColumnIndex(name);
int modelIndex = getTable().convertColumnIndexToModel(index);
TableColumnModelEvent tcme = new TableColumnModelEvent(getTable()
.getColumnModel(), modelIndex, modelIndex);
getTable().removeColumn(getTable().getColumnExt(name));
getTable().columnRemoved(tcme);
/*
* TODO There is a problem here : I don't remove the custom column from
* the treetablemodel. If I remove it there will be a problem when
* deleting a custom column if it isn't the last created.
*/
// TreeTableModel
ttModel.deleteCustomColumn(name);
// CustomColumnsStorage level
Mediator.getCustomColumnsStorage().removeCustomColumn(name);
// Every tasks
TaskContainmentHierarchyFacade tchf = Mediator
.getGanttProjectSingleton().getTaskManager().getTaskHierarchy();
tchf.getRootTask().getCustomValues().removeCustomColumn(name);
removeCustomColumnToAllNestedTask(tchf, tchf.getRootTask(), name);
// MenuItem
popupMenu.remove(popupMenu
.getComponentIndex((Component) mapColNameMenuItem.get(name)));
mapColNameMenuItem.remove(name);
// newBB
Iterator it2 = mapTableColumnColumnKeeper.keySet().iterator();
while (it2.hasNext()) {
TableColumn c = (TableColumn) it2.next();
String n = (String) c.getHeaderValue();
if (n.equals(name)) {
mapTableColumnColumnKeeper.remove(c);
break;
}
}
Mediator.getGanttProjectSingleton().setAskForSave(true);
}
public void renameCustomcolumn(String name, String newName) {
Mediator.getGanttProjectSingleton().setAskForSave(true);
this.displayColumn(name);
TableColumnExt tc = (TableColumnExt) getTable().getColumn(name);
tc.setTitle(newName);
Mediator.getGanttProjectSingleton().repaint();
renameMenuItem(name, newName);
TaskContainmentHierarchyFacade tchf = Mediator
147
.getGanttProjectSingleton().getTaskManager().getTaskHierarchy();
tchf.getRootTask().getCustomValues().renameCustomColumn(name, newName);
renameCustomColumnForAllNestedTask(tchf, tchf.getRootTask(), name,
newName);
ttModel.renameCustomColumn(name, newName);
// newBB
Iterator it = mapTableColumnColumnKeeper.keySet().iterator();
while (it.hasNext()) {
TableColumn c = (TableColumn) it.next();
String n = (String) c.getHeaderValue();
if (n.equals(name)) {
ColumnKeeper ck = (ColumnKeeper) mapTableColumnColumnKeeper
.get(c);
((TableColumnExt) c).setTitle(newName);
break;
}
}
}
// public void changeDefaultValue(String name, Object newDefaultValue)
// {
// // this.displayColumn(name);
// }
/**
* @param facade
* TaskContainmentHierarchyFacade ot retrive nested tasks.
* @param root
* Root task to start with.
* @param colName
* Name of the new custom column to add to the tasks.
* @param value
* Value for this new custom column.
*/
private void setCustomColumnValueToAllNestedTask(
TaskContainmentHierarchyFacade facade, Task root, String colName,
Object value) {
try {
root.getCustomValues().setValue(colName, value);
} catch (CustomColumnsException e) {
e.printStackTrace();
}
Task[] tt = facade.getNestedTasks(root);
for (int i = 0; i < tt.length; i++) {
try {
tt[i].getCustomValues().setValue(colName, value);
} catch (CustomColumnsException e1) {
e1.printStackTrace();
}
setCustomColumnValueToAllNestedTask(facade, tt[i], colName, value);
}
}
/**
* Remove permanetly the custom column for the task <code>root</code> and
* all its children.
*
* @param facade
* TaskContainmentHierarchyFacade ot retrive nested tasks.
* @param root
* Root task to start with.
* @param colName
* Name of the custom column to remove.
*/
private void removeCustomColumnToAllNestedTask(
TaskContainmentHierarchyFacade facade, Task root, String colName) {
// root.getCustomValues().removeCustomColumn(colName);
Task[] tt = facade.getNestedTasks(root);
for (int i = 0; i < tt.length; i++) {
tt[i].getCustomValues().removeCustomColumn(colName);
removeCustomColumnToAllNestedTask(facade, tt[i], colName);
}
}
private void renameCustomColumnForAllNestedTask(
TaskContainmentHierarchyFacade facade, Task root, String oldName,
String newName) {
148
// root.getCustomValues().renameCustomColumn(oldName,newName);
Task[] tt = facade.getNestedTasks(root);
for (int i = 0; i < tt.length; i++) {
tt[i].getCustomValues().renameCustomColumn(oldName, newName);
renameCustomColumnForAllNestedTask(facade, tt[i], oldName, newName);
}
}
/**
* Changes the language. The table headers change and also the menu items.
* For the moment when the user changes the language every columns are
* redisplayed (even if they were hidden).
*
* @param ganttLanguage
*/
public void changeLanguage(GanttLanguage ganttLanguage) {
/*
* The following is ugly but it seems to work. I've had some problems
* when changing the language. the solution I've implemented is to get
* the TableColum and set the new header name.
*/
TableColumnModel tcm = this.getTable().getColumnModel();
List listTableColumnToHide = new ArrayList();
Iterator it = mapTableColumnColumnKeeper.keySet().iterator();
while (it.hasNext()) {
TableColumn tc = (TableColumn) it.next();
ColumnKeeper ck = (ColumnKeeper) mapTableColumnColumnKeeper.get(tc);
if (!ck.isShown) {
listTableColumnToHide.add(tc);
// listColIndexToHide.add(new Integer(ck.getInitIndex()));
ck.show();
}
}
int iColType = tcm.getColumnIndex(GanttTreeTableModel.strColType);
int iColPriority = tcm
.getColumnIndex(GanttTreeTableModel.strColPriority);
int iColInfo = tcm.getColumnIndex(GanttTreeTableModel.strColInfo);
int iColName = tcm.getColumnIndex(GanttTreeTableModel.strColName);
int iColBegDate = tcm.getColumnIndex(GanttTreeTableModel.strColBegDate);
int iColEndDate = tcm.getColumnIndex(GanttTreeTableModel.strColEndDate);
int iColDuration = tcm
.getColumnIndex(GanttTreeTableModel.strColDuration);
int iColCompletion = tcm
.getColumnIndex(GanttTreeTableModel.strColCompletion);
int iColCoordinator = tcm
.getColumnIndex(GanttTreeTableModel.strColCoordinator);
int iColPredecessor = tcm
.getColumnIndex(GanttTreeTableModel.strColPredecessors);
int iColID = tcm.getColumnIndex(GanttTreeTableModel.strColID);
//LH
int iColBudget = tcm.getColumnIndex(GanttTreeTableModel.strColBudget);
((GanttTreeTableModel) this.ttModel).changeLanguage(ganttLanguage);
tcm.getColumn(iColType).setHeaderValue(GanttTreeTableModel.strColType);
tcm.getColumn(iColPriority).setHeaderValue(
GanttTreeTableModel.strColPriority);
tcm.getColumn(iColInfo).setHeaderValue(GanttTreeTableModel.strColInfo);
tcm.getColumn(iColName).setHeaderValue(GanttTreeTableModel.strColName);
tcm.getColumn(iColBegDate).setHeaderValue(
GanttTreeTableModel.strColBegDate);
tcm.getColumn(iColEndDate).setHeaderValue(
GanttTreeTableModel.strColEndDate);
tcm.getColumn(iColDuration).setHeaderValue(
GanttTreeTableModel.strColDuration);
tcm.getColumn(iColCompletion).setHeaderValue(
GanttTreeTableModel.strColCompletion);
149
tcm.getColumn(iColCoordinator).setHeaderValue(
GanttTreeTableModel.strColCoordinator);
tcm.getColumn(iColPredecessor).setHeaderValue(
GanttTreeTableModel.strColPredecessors);
tcm.getColumn(iColID).setHeaderValue(GanttTreeTableModel.strColID);
//LH
tcm.getColumn(iColBudget).setHeaderValue(GanttTreeTableModel.strColBudget);
this.createPopupMenu();
/*
* Presently when the language is modified, every columns are
* redisplayed even those which were hidden.
*/
// Collections.sort(listColIndexToHide);
// Collections.reverse(listColIndexToHide);
// System.out.println(listColIndexToHide);
it = listTableColumnToHide.iterator();
while (it.hasNext()) {
// int i = ((Integer) it.next()).intValue();
// System.out.println(i +" pour " + tcm.getColumnCount() + ", model
// : " +
// i);
((ColumnKeeper) mapTableColumnColumnKeeper.get(it.next())).hide();
// TableColumnModelEvent tcme = new TableColumnModelEvent(tcm,i,i);
// getTable().columnRemoved(tcme);
}
Component tcomp[] = popupMenu.getComponents();
for (int i = 0; i < tcomp.length; i++) {
if (tcomp[i] instanceof JCheckBoxMenuItem) {
JCheckBoxMenuItem c = (JCheckBoxMenuItem) tcomp[i];
// The following isn't well done...
// catching an exception to set the menu slected or not is
// ugly...
// TODO make this more beautiful
try {
c
.setSelected(((ColumnKeeper) mapTableColumnColumnKeeper
.get(tcm.getColumn(tcm.getColumnIndex(c
.getText())))).isShown);
} catch (IllegalArgumentException e) {
c.setSelected(false);
}
}
}
}
String getIdForName(String colName) {
String id = null;
if (colName.equals(GanttTreeTableModel.strColType))
id = "tpd0";
else if (colName.equals(GanttTreeTableModel.strColPriority))
id = "tpd1";
else if (colName.equals(GanttTreeTableModel.strColInfo))
id = "tpd2";
else if (colName.equals(GanttTreeTableModel.strColName))
id = "tpd3";
else if (colName.equals(GanttTreeTableModel.strColBegDate))
id = "tpd4";
else if (colName.equals(GanttTreeTableModel.strColEndDate))
id = "tpd5";
else if (colName.equals(GanttTreeTableModel.strColDuration))
id = "tpd6";
else if (colName.equals(GanttTreeTableModel.strColCompletion))
id = "tpd7";
else if (colName.equals(GanttTreeTableModel.strColCoordinator))
id = "tpd8";
else if (colName.equals(GanttTreeTableModel.strColPredecessors))
id = "tpd9";
else if (colName.equals(GanttTreeTableModel.strColID))
id = "tpd10";
//LH
else if (colName.equals(GanttTreeTableModel.strColBudget))
id = "tpd11";
else
150
id = Mediator.getCustomColumnsStorage().getIdFromName(colName);
return id;
}
private String getNameForId(String id) {
String name = null;
if (id.equals("tpd0"))
name = GanttTreeTableModel.strColType;
else if (id.equals("tpd1"))
name = GanttTreeTableModel.strColPriority;
else if (id.equals("tpd2"))
name = GanttTreeTableModel.strColInfo;
else if (id.equals("tpd3"))
name = GanttTreeTableModel.strColName;
else if (id.equals("tpd4"))
name = GanttTreeTableModel.strColBegDate;
else if (id.equals("tpd5"))
name = GanttTreeTableModel.strColEndDate;
else if (id.equals("tpd6"))
name = GanttTreeTableModel.strColDuration;
else if (id.equals("tpd7"))
name = GanttTreeTableModel.strColCompletion;
else if (id.equals("tpd8"))
name = GanttTreeTableModel.strColCoordinator;
else if (id.equals("tpd9"))
name = GanttTreeTableModel.strColPredecessors;
else if (id.equals("tpd10"))
name = GanttTreeTableModel.strColID;
//LH
else if (id.equals("tpd11"))
name = GanttTreeTableModel.strColBudget;
else
name = Mediator.getCustomColumnsStorage().getNameFromId(id);
return name;
}
/**
* Returns the JTree used in the treetable.
*
* @return The JTree used in the treetable.
*/
public JTree getTree() {
return this.getTreeTable().getTree();
}
/**
* Returns the vertical scrollbar.
*
* @return The vertical scrollbar.
*/
public JScrollBar getVerticalScrollBar() {
return scrollPane.getVerticalScrollBar();
}
public JScrollPane getScrollPane() {
return scrollPane;
}
/**
*
* @inheritDoc
*/
public void requestFocus() {
if (getDisplayColumns().isDisplayed(GanttTreeTableModel.strColName)) {
int c = getTable().convertColumnIndexToView(
getColumn(GanttTreeTableModel.strColName).getModelIndex());
NameCellEditor ed = (NameCellEditor) getTable()
.getCellEditor(-1, c);
ed.requestFocus();
}
}
public void centerViewOnSelectedCell() {
int row = getTable().getSelectedRow();
int col = getTable().getEditingColumn();
if (col == -1)
col = getTable().getSelectedColumn();
Rectangle rect = getTable().getCellRect(row, col, true);
scrollPane.getHorizontalScrollBar().scrollRectToVisible(rect);
scrollPane.getViewport().scrollRectToVisible(rect);
}
public void addMouseListener(MouseListener mouseListener) {
super.addMouseListener(mouseListener);
getTable().addMouseListener(mouseListener);
151
getTree().addMouseListener(mouseListener);
this.getTreeTable().getParent().addMouseListener(mouseListener);
}
/**
* Adds the key listener to the Table, the tree and this.
*/
public void addKeyListener(KeyListener keyListener) {
super.addKeyListener(keyListener);
getTable().addKeyListener(keyListener);
getTree().addKeyListener(keyListener);
}
void setDelay(TaskNode taskNode, Delay delay) {
try {
int indexInfo = getTable().getColumnModel().getColumnIndex(
GanttTreeTableModel.strColInfo);
indexInfo = getTable().convertColumnIndexToModel(indexInfo);
ttModel.setValueAt(delay, taskNode, indexInfo);
} catch (IllegalArgumentException e) {
}
}
/*
* ----- INNER CLASSES -----
*/
public class DisplayedColumnsList extends ArrayList {
public DisplayedColumnsList() {
super();
}
/**
* Returns <code>true</code> if the column name <code>name</code>
* is displayed, <code>false</code> otherwise.
*
* @param name
* Name of the column to check the display.
* @return <code>true</code> if the column name <code>name</code> is
* displayed, <code>false</code> otherwise.
*/
public boolean isDisplayed(String name) {
Iterator it = this.iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
if (getNameForId(dc.getID()).equals(name))
return dc.isDisplayed();
}
return false;
}
public int getOrderForName(String name) {
Iterator it = this.iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
if (getNameForId(dc.getID()).equals(name))
return dc.getOrder();
}
return -1;
}
public String getNameForOrder(int order) {
Iterator it = this.iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
if (dc.getOrder() == order)
return getNameForId(dc.getID());
}
return null;
}
public boolean add(Object o) {
if (o instanceof DisplayedColumn) {
DisplayedColumn dc1 = (DisplayedColumn) o;
Iterator it = this.iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
if (dc.getID().equals(dc1.getID())) {
this.remove(dc);
return super.add(dc1);
}
}
return super.add(dc1);
}
return false;
}
152
public Object clone() {
DisplayedColumnsList l = new DisplayedColumnsList();
Iterator it = this.iterator();
while (it.hasNext())
l.add(((DisplayedColumn) it.next()).clone());
return l;
}
}
public class DisplayedColumn implements Comparable {
private String id = null;
private boolean displayed = false;
private int order = -1;
private int width = 0;
public DisplayedColumn(String id) {
this.id = id;
}
public void setID(String id) {
this.id = id;
}
public void setDisplayed(boolean disp) {
this.displayed = disp;
}
public boolean isDisplayed() {
return this.displayed;
}
public String getID() {
return this.id;
}
public void setOrder(int order) {
this.order = order;
}
public int getOrder() {
return this.order;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public Object clone() {
DisplayedColumn dc = new DisplayedColumn(this.id);
dc.setDisplayed(this.isDisplayed());
dc.setOrder(this.getOrder());
dc.setWidth(this.getWidth());
return dc;
}
public String toString() {
return "[ID = " + id + ", displayed = " + displayed + ", order = "
+ order + "]";
}
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object o) {
if (o == null)
return 0;
if (o instanceof DisplayedColumn) {
DisplayedColumn dc = (DisplayedColumn) o;
if (this.order != dc.order)
return this.order - dc.order;
return this.id.compareTo(dc.id);
}
return 0;
}
}
/**
* This actionListener manages the column to be hiden or displayed. It has a
* TableColumn and hide it or display it
153
*
* @author bbaranne Mar 1, 2005
*/
class ColumnKeeper implements ActionListener {
/**
* the initial index of the table column.
*/
private int index;
/**
* True if the table column is displayed, false otherwise.
*/
private boolean isShown = true;
/**
* The managed table column.
*/
protected TableColumn column;
/**
* Creates a new ColumnKeeper for the given TableColumn.
*
* @param tc
* TableColumn to manage.
*/
public ColumnKeeper(TableColumn tc) {
column = tc;
index = column.getModelIndex();
}
/**
* Set the initial index of the table column.
*
* @param initIndex
* The initial index of the table column.
*/
public void setInitIndex(int initIndex) {
index = initIndex;
}
/**
* Returns the initial index of the table column.
*
* @return The initial index of the table column.
*/
public int getInitIndex() {
return index;
}
/**
* Hides the table column.
*/
void hide() {
getTable().getColumnModel().removeColumn(column);
isShown = false;
String name = (String) column.getHeaderValue();
String id = getIdForName(name);
Iterator it = listDisplayedColumns.iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
if (dc.getID().equals(id))
dc.setDisplayed(false);
}
// Thread t = new Thread(){
// public void run(){
calculateWidth();
revalidate();
// }
// };
// SwingUtilities.invokeLater(t);
}
/**
* Shows the table column.
*/
void show() {
boolean reloadInfo = false;
getTable().getColumnModel().addColumn(column);
try {
int columnViewIndexOld = index;
int columnModelIndexActual = column.getModelIndex();
if (column.getIdentifier().equals(
GanttTreeTableModel.strColInfo))
reloadInfo = true;
int columnViewIndexActual = getTable()
.convertColumnIndexToView(columnModelIndexActual);
getTable()
154
.moveColumn(columnViewIndexActual, columnViewIndexOld);
} catch (IllegalArgumentException e) {
index = getTable().getModel().getColumnCount() - 1;
}
isShown = true;
String name = (String) column.getHeaderValue();
String id = getIdForName(name);
boolean found = false;
Iterator it = listDisplayedColumns.iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
if (dc.getID().equals(id)) {
dc.setDisplayed(true);
found = true;
}
}
if (!found && id != null) {
DisplayedColumn dc = new DisplayedColumn(id);
dc.setDisplayed(true);
listDisplayedColumns.add(dc);
}
if (reloadInfo)
if (Mediator.getDelayManager() != null)
Mediator.getDelayManager().fireDelayObservation();
// Thread t = new Thread(){
// public void run(){
calculateWidth();
revalidate();
// }
// };
// SwingUtilities.invokeLater(t);
}
public void actionPerformed(ActionEvent e) {
Mediator.getGanttProjectSingleton().getUndoManager().undoableEdit(
"HIDE OR SHOW A COLUMN", new Runnable() {
public void run() {
if (!isShown)
show();
else
hide();
getTable().repaint();
}
});
}
}
/**
* This class handles the mouse actions on the treetable header.
*
* @author bbaranne Mar 1, 2005
* @version 1.0 Show the popupMenu when popup is triggered.
*/
class HeaderMouseListener extends MouseAdapter {
/**
* Creates a new HeaderMouseListener
*/
public HeaderMouseListener() {
super();
}
/*
* Something ugly !! TODO find a means to display the popupmenu with the
* right UI.
*/
boolean first = false;
/**
* @inheritDoc Shows the popupMenu to hide/show columns and to add
* custom columns.
*/
public void mouseClicked(MouseEvent e) {
if (!first) {
createPopupMenu();
first = true;
}
// On windows e.isPopupTrigger doesn't work, strange...
if (e.getButton() == MouseEvent.BUTTON3 || e.isPopupTrigger()) {
Component c = (Component) e.getSource();
reorderPopuMenu();
popupMenu.show(c, e.getX(), e.getY());
clickPoint = e.getPoint();//popupMenu.getLocationOnScreen();
155
CustomColumn cc = null;
try {
cc = Mediator.getCustomColumnsStorage().getCustomColumn(
getTable().getColumnName(
getTable().columnAtPoint(e.getPoint())));
} catch (CustomColumnsException e1) {
// TODO Auto-generated catch block
// e1.printStackTrace();
}
if (cc != null)
jmiDeleteColumn.setEnabled(true);
else
jmiDeleteColumn.setEnabled(false);
}
}
}
/**
* CellEditor that uses DateUtils.parseDate to parse the given date.
*
* @author bbaranne Mar 1, 2005
*/
class DateCellEditor extends DefaultCellEditor {
// textfield used for editing.
JTextField field = null;
// normal textfield background color
private Color colorNormal = null;
// error textfield background color (when the date isn't correct
private final Color colorError = new Color(255, 125, 125);
// the returned date
private Date date = null;
/**
* Creates a new DateCellEditor.
*
* @param field
* JTextField used to edit the date.
*/
public DateCellEditor(JTextField field) {
super(field);
this.field = field;
}
/**
* @inheritDoc
*/
public Object getCellEditorValue() {
return new GanttCalendar(date == null ? new Date() : date);
}
/**
* @inheritDoc If the date is not correct, the textfield's background
* goes red until the user enters a correct date.
*/
public boolean stopCellEditing() {
boolean res = true;
try {
date = DateUtils.parseDate(field.getText(), language
.getLocale());
field.setBackground(colorNormal);
super.fireEditingStopped();
} catch (ParseException e) {
Toolkit.getDefaultToolkit().beep();
field.setBackground(colorError);
res = false;
}
return res;
}
}
/**
* The class replaces the cell editor used in the hierarchical column of
* the tree table.
*
* @author bbaranne (Benoit Baranne)
*/
class NameCellEditor extends DefaultCellEditor {
private JTextField field = null;
public NameCellEditor() {
super(new JTextField());
field = (JTextField) this.editorComponent;
}
156
public void requestFocus() {
this.field.requestFocusInWindow();
this.field.selectAll();
}
public boolean stopCellEditing() {
if (field.getText().trim().length() != 0)
super.stopCellEditing();
else {
Mediator.getGanttProjectSingleton().deleteTasks(false);
super.fireEditingCanceled();
}
return super.stopCellEditing();
}
// public void cancelCellEditing()
// {
// super.cancelCellEditing();
// }
}
/**
* This class repaints the GraphicArea and the table every time the table
* model has been modified. TODO Add the refresh functionnality when
* available.
*
* @author Benoit Baranne
*/
class ModelListener implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// Mediator.getGanttProjectSingleton().getArea().repaint();
// getTable().repaint();
Mediator.getGanttProjectSingleton().repaint();
}
}
}
net.sourceforge.ganttproject. GanttTreeTableModel
package net.sourceforge.ganttproject;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Vector;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
import net.sourceforge.ganttproject.delay.Delay;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.CustomColumnsException;
import net.sourceforge.ganttproject.task.ResourceAssignment;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskContainmentHierarchyFacade;
import net.sourceforge.ganttproject.task.TaskInfo;
import net.sourceforge.ganttproject.task.TaskLength;
import net.sourceforge.ganttproject.task.TaskLengthImpl;
import net.sourceforge.ganttproject.task.TaskNode;
import net.sourceforge.ganttproject.task.dependency.TaskDependency;
import org.jdesktop.swing.treetable.DefaultTreeTableModel;
/**
* This class is the model for GanttTreeTable to display tasks.
*
* @author bbaranne (Benoit Baranne)
*/
public class GanttTreeTableModel extends DefaultTreeTableModel implements
TableColumnModelListener, TaskContainmentHierarchyFacade {
private static GanttLanguage language = GanttLanguage.getInstance();
public static String strColType = null;
public static String strColPriority = null;
157
public static String strColInfo = null;
public static String strColName = null;
public static String strColBegDate = null;
public static String strColEndDate = null;
public static String strColDuration = null;
//LH
public static String strColBudget = null;
public static String strColCompletion = null;
public static String strColCoordinator = null;
public static String strColPredecessors = null;
public static String strColID = null;
/** The colums titles */
public List titles = null;
/**
* Custom columns list.
*/
private Vector customColumns = null;
/**
* Number of columns (presently in the model)
*/
private int nbCol = 12;
//LH : private int nbCol = 11;
/**
* Number of columns (at all, even hiden)
*/
private int nbColTot = nbCol;
/**
* Creates an instance of GanttTreeTableModel with a root.
*
* @param root
* The root.
*/
public GanttTreeTableModel(TreeNode root) {
super(root);
titles = new ArrayList();
customColumns = new Vector();
changeLanguage(language);
}
/**
* Changes the language.
*
* @param ganttLanguage
* New language to use.
*/
public void changeLanguage(GanttLanguage ganttLanguage) {
strColType = language.getText("tableColType");
strColPriority = language.getText("tableColPriority");
strColInfo = language.getText("tableColInfo");
strColName = language.getText("tableColName");
strColBegDate = language.getText("tableColBegDate");
strColEndDate = language.getText("tableColEndDate");
strColDuration = language.getText("tableColDuration");
//LH
//TODO put string in properties
strColBudget = language.getText("budget");
strColCompletion = language.getText("tableColCompletion");
strColCoordinator = language.getText("tableColCoordinator");
strColPredecessors = language.getText("tableColPredecessors");
strColID = language.getText("tableColID");
titles.clear();
//LH
String[] cols = new String[] { strColType, strColPriority, strColInfo,
strColName, strColBegDate, strColEndDate, strColDuration,
strColCompletion, strColCoordinator, strColPredecessors,
strColID, strColBudget };
for (int i = 0; i < cols.length; i++)
titles.add(new String(cols[i]));
}
/**
158
* Invoked this to insert newChild at location index in parents children.
* This will then message nodesWereInserted to create the appropriate event.
* This is the preferred way to add children as it will create the
* appropriate event.
*/
public void insertNodeInto(MutableTreeNode newChild,
MutableTreeNode parent, int index) {
parent.insert(newChild, index);
int[] newIndexs = new int[1];
newIndexs[0] = index;
nodesWereInserted(parent, newIndexs);
}
/**
* Message this to remove node from its parent. This will message
* nodesWereRemoved to create the appropriate event. This is the preferred
* way to remove a node as it handles the event creation for you.
*/
public void removeNodeFromParent(MutableTreeNode node) {
MutableTreeNode parent = (MutableTreeNode) node.getParent();
if (parent == null)
throw new IllegalArgumentException("node does not have a parent.");
int[] childIndex = new int[1];
Object[] removedArray = new Object[1];
childIndex[0] = parent.getIndex(node);
parent.remove(childIndex[0]);
removedArray[0] = node;
nodesWereRemoved(parent, childIndex, removedArray);
}
/**
* Add a custom column to the model.
*
* @param title
*/
public void addCustomColumn(String title) {
customColumns.add(title);
nbColTot++;
}
/**
* Delete a custom column.
*
* @param title
*/
public void deleteCustomColumn(String title) {
customColumns.remove(title);
this.columnRemoved(null);
nbColTot--;
}
public void renameCustomColumn(String oldName, String newName) {
customColumns.set(customColumns.indexOf(oldName), newName);
}
// /**
// * Returns the number of custom columns.
// * @return
// */
// public int getCustomColumnCount()
// {
// return customColumns.size();
// }
public int getColumnCount() {
return nbCol;
}
public int getColumnCountTotal() {
return nbColTot;
}
/**
* {@inheritDoc}
*/
public Class getColumnClass(int column) {
switch (column) {
case 0:
case 1:
case 2:
return Icon.class;
159
case 3:
return hierarchicalColumnClass;
case 4:
case 5:
return GregorianCalendar.class;
case 6:
case 7:
return Integer.class;
case 8:
return String.class;
case 9:
return String.class;
case 10:
return Integer.class;
//LH
case 11:
//return Double.class;
return String.class;
default: {
TaskNode tn = (TaskNode) this.getRoot();
// tn = (TaskNode)tn.children().nextElement();
Object o = this.getValueAt(tn, column);
if (o == null) {
o = "erreur";
System.err.println("!!!!!!!!!!!!!!!!!");
}
return o.getClass();
}
}
}
public String getColumnName(int column) {
if (column < titles.size())
return (String) titles.get(column);
try {
return (String) customColumns.get(column - titles.size());
} catch (IndexOutOfBoundsException e) {
return (String) customColumns.get(column - titles.size() - 1);
}
}
/**
* @inheritDoc
*/
public boolean isCellEditable(Object node, int column) {
if (node instanceof TaskNode)
return column != 8 && column != 9 && column != 10 && column !=2 && column !=11;
return false;
}
// public Object getChild(Object parent, int index)
// {
//
// }
//
// public int getChildCount(Object parent)
// {
//
// }
/**
* @inheritDoc
*/
public Object getValueAt(Object node, int column) {
Object res = null;
if (!(node instanceof TaskNode))
return null;
TaskNode tn = (TaskNode) node;
Task t = (Task) tn.getUserObject();
// if(tn.getParent()!=null){
switch (column) {
case 0:
if (((Task) tn.getUserObject()).isProjectTask()) {
res = new ImageIcon(getClass().getResource(
"/icons/mproject.gif"));
} else if (!tn.isLeaf())
res = new ImageIcon(getClass().getResource("/icons/mtask.gif"));
else if (t.isMilestone())
res = new ImageIcon(getClass()
.getResource("/icons/meeting.gif"));
else
res = new ImageIcon(getClass().getResource("/icons/tasks2.png"));
break;
160
case 1:
Task task = (Task) tn.getUserObject();
String path = (task.getPriority() == 0 ? "/icons/task1.gif" : task
.getPriority() == 1 ? "/icons/task.gif"
: "/icons/task2.gif");
res = new ImageIcon(getClass().getResource(path));
break;
case 2: // info
TaskInfo info = t.getTaskInfo();
if (info != null) {
if (info instanceof Delay) {
int type = ((Delay) info).getType();
if (type == Delay.NORMAL)
res = new ImageIcon(getClass().getResource(
"/icons/alert1_16.gif"));
else if (type == Delay.CRITICAL)
res = new ImageIcon(getClass().getResource(
"/icons/alert2_16.gif"));
}
}
break;
case 3:
res = tn.getName();
break;
case 4:
res = tn.getStart();
break;
case 5:
res = tn.getEnd();
break;
case 6:
res = new Integer(tn.getDuration());
break;
case 7:
res = new Integer(tn.getCompletionPercentage());
break;
case 8: {
ResourceAssignment[] tAssign = t.getAssignments();
StringBuffer sb = new StringBuffer();
int nb = 0;
for (int i = 0; i < tAssign.length; i++) {
ResourceAssignment resAss = tAssign[i];
if (resAss.isCoordinator())
sb.append(nb++ == 0 ? "" : ", ").append(
resAss.getResource().getName());
}
// res = "Not implemented";
res = sb.toString();
break;
}
case 9: {
String resStr = "";
TaskDependency[] dep = t.getDependenciesAsDependant().toArray();
int i = 0;
if (dep != null && dep.length > 0) {
for (i = 0; i < dep.length - 1; i++)
resStr += dep[i].getDependee().getTaskID() + ", ";
resStr += dep[i].getDependee().getTaskID() + "";
}
res = resStr;
break;
}
case 10:
res = new Integer(t.getTaskID());
break;
//LH
case 11:
res = new Double(t.getBudget());
break;
default:
String colName = this.getColumnName(column);
// System.out.println(" -> "+colName);
// System.out.println(t+" : "+t.getCustomValues());
res = t.getCustomValues().getValue(colName);
break;
}
// }
// else
// res ="";
return res;
161
}
/**
* @inheritDoc
*/
public void setValueAt(final Object value, final Object node,
final int column) {
if (isCellEditable(node, column)) {
// System.out.println("undoable colonne: " + column);
Mediator.getGanttProjectSingleton().getUndoManager().undoableEdit(
"Change properties column", new Runnable() {
public void run() {
setValue(value, node, column);
}
});
} else {
// System.out.println("NOT undoable colonne: " + column);
setValue(value, node, column);
}
// System.out.println("node : " + node);
// System.out.println("valeur : " + value);
Mediator.getGanttProjectSingleton().repaint();
Mediator.getGanttProjectSingleton().setAskForSave(true);
}
/**
* Set value in left pane cell
* @param value
* @param node
* @param column
*/
private void setValue(final Object value, final Object node,
final int column) {
switch (column) {
case 0:
case 1:
case 2: // info
((TaskNode) node).setTaskInfo((TaskInfo) value);
case 8:
break;
case 3:
((TaskNode) node).setName(value.toString());
break;
case 4:
((TaskNode) node).setStart((GanttCalendar) value);
((TaskNode) node).applyThirdDateConstraint();
break;
case 5:
((TaskNode) node).setEnd((GanttCalendar) value);
break;
case 6:
TaskLength tl = ((Task) ((TaskNode) node).getUserObject())
.getDuration();
tl.getTimeUnit();
((TaskNode) node).setDuration(new TaskLengthImpl(tl.getTimeUnit(),
((Integer) value).intValue()));
break;
case 7:
((TaskNode) node).setCompletionPercentage(((Integer) value)
.intValue());
break;
//LH
case 11:
((TaskNode) node).setBudget(((Double) value).doubleValue());
break;
default: // custom colums
try {
((Task) ((TaskNode) node).getUserObject()).getCustomValues()
.setValue(this.getColumnName(column), value);
} catch (CustomColumnsException e) {
e.printStackTrace();
}
}
}
/**
* @inheritDoc
*/
public void columnAdded(TableColumnModelEvent arg0) {
162
nbCol++;
}
/**
* @inheritDoc
*/
public void columnRemoved(TableColumnModelEvent arg0) {
nbCol--;
}
/**
* @inheritDoc
*/
public void columnMoved(TableColumnModelEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @inheritDoc
*/
public void columnMarginChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @inheritDoc
*/
public void columnSelectionChanged(ListSelectionEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @inheritDoc
*/
public Task[] getNestedTasks(Task container) {
TaskNode r = (TaskNode) root;
Enumeration e = r.children();
Vector v = new Vector();
while (e.hasMoreElements())
v.add((TaskNode) e.nextElement());
Task[] res = new Task[v.size()];
v.toArray(res);
return res;
}
/**
* Purpose: Should return true if this Tasks has any nested subtasks.
*/
public boolean hasNestedTasks(Task container) {
TaskNode r = (TaskNode) root;
if (r.getChildCount() > 0) {
return true;
} else {
return false;
}
}
/**
* @inheritDoc
*/
public Task getRootTask() {
return (Task) ((TaskNode) this.getRoot()).getUserObject();
}
/**
* Returns the corresponding task node according to the given task.
*
* @param task
* The task whom tasknode we want to get.
* @return The corresponding task node according to the given task.
*/
public TaskNode getTaskNodeForTask(Task task) {
Enumeration enumeration = ((TaskNode) getRoot()).preorderEnumeration();
while (enumeration.hasMoreElements()) {
Object next = enumeration.nextElement();
if (!(next instanceof TaskNode))
continue;
TaskNode tn = (TaskNode) next;
Task t = (Task) tn.getUserObject();
if (t.equals(task))
return tn;
}
return null;
}
163
/**
* @inheritDoc
*/
public Task getContainer(Task nestedTask) {
// TODO Auto-generated method stub
return null;
}
/**
* @inheritDoc
*/
public void move(Task whatMove, Task whereMove) {
// TODO Auto-generated method stub
}
/**
* @inheritDoc
*/
public boolean areUnrelated(Task dependant, Task dependee) {
// TODO Auto-generated method stub
return false;
}
public int getDepth(Task task) {
// TODO Auto-generated method stub
return 0;
}
}
net.sourceforge.ganttproject. Mediator
package net.sourceforge.ganttproject;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.ganttproject.delay.DelayManager;
import net.sourceforge.ganttproject.gui.options.model.ChangeValueDispatcher;
import net.sourceforge.ganttproject.plugins.PluginManager;
import net.sourceforge.ganttproject.roles.RoleManager;
import net.sourceforge.ganttproject.task.CustomColumnsManager;
import net.sourceforge.ganttproject.task.CustomColumnsStorage;
import net.sourceforge.ganttproject.task.TaskManager;
import net.sourceforge.ganttproject.task.TaskSelectionManager;
import net.sourceforge.ganttproject.undo.GPUndoManager;
/**
* This class allow the developer to get some useful references. - GanttProject
* reference; - CustomColumnManager reference; - CustomColumnStorage reference.
*
* @author bbaranne Mar 2, 2005
*/
public class Mediator {
/**
* The unique GanttProject instance.
*/
private static GanttProject ganttprojectSingleton = null;
/**
* The unique CustomColumnsManager instance.
*/
private static CustomColumnsManager customColumnsManager = null;
private static CustomColumnsStorage customColumnsStorage = null;
private static TaskSelectionManager taskSelectionManager = null;
private static RoleManager roleManager = null;
private static TaskManager taskManager = null;
private static GPUndoManager undoManager = null;
private static DelayManager delayManager = null;
private static PluginManager pluginManager = new PluginManager();
private static List changeValueDispatchers = new ArrayList();
/**
* Regsiters the unique GanttProject instance.
*
164
* @param gp
* The unique GanttProject instance.
*/
public static void registerGanttProject(GanttProject gp) {
ganttprojectSingleton = gp;
}
/**
* Regsiters the unique CustomColumnsManager instance.
*
* @param managerThe
* unique CustomColumnsManager instance.
*/
public static void registerCustomColumnsManager(CustomColumnsManager manager) {
customColumnsManager = manager;
}
public static void registerCustomColumnsStorage(CustomColumnsStorage storage) {
customColumnsStorage = storage;
}
public static void registerTaskSelectionManager(
TaskSelectionManager taskSelection) {
taskSelectionManager = taskSelection;
}
public static void registerRoleManager(RoleManager roleMgr) {
roleManager = roleMgr;
}
public static void registerTaskManager(TaskManager taskMgr) {
taskManager = taskMgr;
}
public static void registerUndoManager(GPUndoManager undoMgr) {
undoManager = undoMgr;
}
public static void registerDelayManager(DelayManager delayMgr) {
delayManager = delayMgr;
}
public static void addChangeValueDispatcher(ChangeValueDispatcher dispatcher){
changeValueDispatchers.add(dispatcher);
}
/**
* Returns the unique GanttProject instance.
*
* @return The unique GanttProject instance.
*/
public static GanttProject getGanttProjectSingleton() {
return ganttprojectSingleton;
}
/**
* Returns the unique CustomColumnsStorage instance.
*
* @return The unique CustomColumnsStorage instance.
*/
public static CustomColumnsStorage getCustomColumnsStorage() {
return customColumnsStorage;
}
/**
* Returns the unique CustomColumnsManager instance.
*
* @return The unique CustomColumnsManager instance.
*/
public static CustomColumnsManager getCustomColumnsManager() {
return customColumnsManager;
}
public static TaskSelectionManager getTaskSelectionManager() {
return taskSelectionManager;
}
public static RoleManager getRoleManager() {
return roleManager;
}
public static TaskManager getTaskManager() {
return taskManager;
}
165
public static GPUndoManager getUndoManager() {
return undoManager;
}
public static DelayManager getDelayManager() {
return delayManager;
}
public static PluginManager getPluginManager() {
return pluginManager;
}
public static List getChangeValueDispatchers(){
return changeValueDispatchers;
}
}
net.sourceforge.ganttproject. GanttProject
package net.sourceforge.ganttproject;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import net.sourceforge.ganttproject.GanttGraphicArea.MouseSupport;
import net.sourceforge.ganttproject.action.CalculateCriticalPathAction;
166
import net.sourceforge.ganttproject.action.CopyAction;
import net.sourceforge.ganttproject.action.CutAction;
import net.sourceforge.ganttproject.action.DeleteAssignmentAction;
import net.sourceforge.ganttproject.action.DeleteHumanAction;
import net.sourceforge.ganttproject.action.GPAction;
import net.sourceforge.ganttproject.action.ImportResources;
import net.sourceforge.ganttproject.action.NewArtefactAction;
import net.sourceforge.ganttproject.action.NewHumanAction;
import net.sourceforge.ganttproject.action.NewTaskAction;
import net.sourceforge.ganttproject.action.PasteAction;
import net.sourceforge.ganttproject.action.RedoAction;
import net.sourceforge.ganttproject.action.RefreshViewAction;
import net.sourceforge.ganttproject.action.ResourceActionSet;
import net.sourceforge.ganttproject.action.RolloverAction;
import net.sourceforge.ganttproject.action.ScrollGanttChartLeftAction;
import net.sourceforge.ganttproject.action.ScrollGanttChartRightAction;
import net.sourceforge.ganttproject.action.SwitchViewAction;
import net.sourceforge.ganttproject.action.UndoAction;
import net.sourceforge.ganttproject.action.ZoomInAction;
import net.sourceforge.ganttproject.action.ZoomOutAction;
import net.sourceforge.ganttproject.calendar.GPCalendar;
import net.sourceforge.ganttproject.calendar.WeekendCalendarImpl;
import net.sourceforge.ganttproject.chart.Chart;
import net.sourceforge.ganttproject.chart.ChartViewState;
import net.sourceforge.ganttproject.chart.ToggleChartAction;
import net.sourceforge.ganttproject.delay.DelayManager;
import net.sourceforge.ganttproject.document.AbstractURLDocument;
import net.sourceforge.ganttproject.document.Document;
import net.sourceforge.ganttproject.document.DocumentCreator;
import net.sourceforge.ganttproject.document.DocumentManager;
import net.sourceforge.ganttproject.document.DocumentsMRU;
import net.sourceforge.ganttproject.document.FileDocument;
import net.sourceforge.ganttproject.document.HttpDocument;
import net.sourceforge.ganttproject.document.OpenDocumentAction;
import net.sourceforge.ganttproject.export.ExportFileAction;
import net.sourceforge.ganttproject.export.ExportFileWizardImpl;
import net.sourceforge.ganttproject.filter.GanttCSVFilter;
import net.sourceforge.ganttproject.filter.GanttHTMLFileFilter;
import net.sourceforge.ganttproject.filter.GanttJPGFileFilter;
import net.sourceforge.ganttproject.filter.GanttMSProjectLFileFilter;
import net.sourceforge.ganttproject.filter.GanttPDFFileFilter;
import net.sourceforge.ganttproject.filter.GanttPNGFileFilter;
import net.sourceforge.ganttproject.filter.GanttXFIGFileFilter;
import net.sourceforge.ganttproject.filter.GanttXMLFileFilter;
import net.sourceforge.ganttproject.gui.GanttDialogCalendar;
import net.sourceforge.ganttproject.gui.GanttDialogInfo;
import net.sourceforge.ganttproject.gui.GanttDialogPerson;
import net.sourceforge.ganttproject.gui.GanttDialogProperties;
import net.sourceforge.ganttproject.gui.GanttLookAndFeelInfo;
import net.sourceforge.ganttproject.gui.GanttLookAndFeels;
import net.sourceforge.ganttproject.gui.GanttStatusBar;
import net.sourceforge.ganttproject.gui.GanttURLChooser;
import net.sourceforge.ganttproject.gui.TestGanttRolloverButton;
import net.sourceforge.ganttproject.gui.TipsDialog;
import net.sourceforge.ganttproject.gui.UIConfiguration;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.gui.about.AboutDialog;
import net.sourceforge.ganttproject.gui.report.ReportDialog;
import net.sourceforge.ganttproject.gui.options.SettingsDialog;
import net.sourceforge.ganttproject.gui.previousState.GanttDialogCompareToPreviousState;
import net.sourceforge.ganttproject.gui.previousState.GanttDialogSaveAsPreviousState;
import net.sourceforge.ganttproject.gui.projectwizard.NewProjectWizard;
import net.sourceforge.ganttproject.gui.scrolling.ScrollingManager;
import net.sourceforge.ganttproject.gui.scrolling.ScrollingManagerImpl;
import net.sourceforge.ganttproject.gui.zoom.ZoomManager;
import net.sourceforge.ganttproject.importer.ImportFileAction;
import net.sourceforge.ganttproject.importer.ImportFileWizardImpl;
import net.sourceforge.ganttproject.io.GPSaver;
import net.sourceforge.ganttproject.io.GanttXMLOpen;
import net.sourceforge.ganttproject.io.GanttXMLSaver;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.parser.AllocationTagHandler;
import net.sourceforge.ganttproject.parser.BlankLineTagHandler;
import net.sourceforge.ganttproject.parser.CustomPropertiesTagHandler;
import net.sourceforge.ganttproject.parser.DefaultWeekTagHandler;
167
import net.sourceforge.ganttproject.parser.DependencyTagHandler;
import net.sourceforge.ganttproject.parser.CostTagHandler;
import net.sourceforge.ganttproject.parser.GPParser;
import net.sourceforge.ganttproject.parser.HolidayTagHandler;
import net.sourceforge.ganttproject.parser.ParserFactory;
import net.sourceforge.ganttproject.parser.PreviousStateTasksTagHandler;
import net.sourceforge.ganttproject.parser.ResourceTagHandler;
import net.sourceforge.ganttproject.parser.RoleTagHandler;
import net.sourceforge.ganttproject.parser.TaskDisplayColumnsTagHandler;
import net.sourceforge.ganttproject.parser.TaskPropertiesTagHandler;
import net.sourceforge.ganttproject.parser.TaskTagHandler;
import net.sourceforge.ganttproject.parser.VacationTagHandler;
import net.sourceforge.ganttproject.parser.ViewTagHandler;
import net.sourceforge.ganttproject.print.PrintManager;
import net.sourceforge.ganttproject.print.PrintPreview;
import net.sourceforge.ganttproject.resource.AssignmentContext;
import net.sourceforge.ganttproject.resource.HumanResource;
import net.sourceforge.ganttproject.resource.HumanResourceManager;
import net.sourceforge.ganttproject.resource.ProjectResource;
import net.sourceforge.ganttproject.resource.ResourceContext;
import net.sourceforge.ganttproject.resource.ResourceEvent;
import net.sourceforge.ganttproject.resource.ResourceManager;
import net.sourceforge.ganttproject.resource.ResourceView;
import net.sourceforge.ganttproject.roles.RoleManager;
import net.sourceforge.ganttproject.task.BlankLineNode;
import net.sourceforge.ganttproject.task.CustomColumnsStorage;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskContainmentHierarchyFacade;
import net.sourceforge.ganttproject.task.TaskManager;
import net.sourceforge.ganttproject.task.TaskManagerConfig;
import net.sourceforge.ganttproject.task.TaskNode;
import net.sourceforge.ganttproject.task.TaskSelectionManager;
import net.sourceforge.ganttproject.task.algorithm.AdjustTaskBoundsAlgorithm;
import net.sourceforge.ganttproject.task.algorithm.RecalculateTaskCompletionPercentageAlgorithm;
import net.sourceforge.ganttproject.task.dependency.TaskDependencyException;
import net.sourceforge.ganttproject.task.dependency.constraint.FinishStartConstraintImpl;
import net.sourceforge.ganttproject.time.TimeUnitStack;
import net.sourceforge.ganttproject.time.gregorian.GPTimeUnitStack;
import net.sourceforge.ganttproject.undo.GPUndoManager;
import net.sourceforge.ganttproject.undo.UndoManagerImpl;
import net.sourceforge.ganttproject.util.BrowserControl;
/**
* Main frame of the project
*/
public class GanttProject extends GanttProjectBase implements ActionListener,
IGanttProject, ResourceView, KeyListener, UIFacade {
/** The current version of ganttproject */
public static final String version = "2.0-pre1";
/* List of calendar for the project */
private ArrayList listOfCalendar = new ArrayList();
/** Command line creation or gui creation */
public static boolean byCommandLine = false;
/** The language use */
private GanttLanguage language = GanttLanguage.getInstance();
/** The JTree part. */
private GanttTree2 tree;
/** GanttGraphicArea for the calendar with Gantt */
private GanttGraphicArea area;
/** GanttPeoplePanel to edit person that work on the project */
private GanttResourcePanel resp;
//LH
/** The differents menus */
public JMenu mProject, mMRU, mEdit, mTask, mHuman, mHelp, mServer, mReport,
mCalendar;
// public JMenu mView;
168
//LH
/** The differetns menuitem */
public JMenuItem miNew, miOpen, miOpenURL, miSave, miSaveAs, miSaveAsURL,
miPublishToWeb, /* miOpenDB,miSaveAsDB, */
miPrint, miPreview, miQuit, miCut, miCopy, miPaste, miOptions,
miDeleteTask, miPropertiesTask, miUp, miDown, miDelHuman,
miPropHuman, miSendMailHuman, miEditCalendar, miPrjCal, miWebPage,
miTips, miReport, miAbout, miManual, miRefresh, miChartOptions;
public JMenuItem miUndo, miRedo;
private static final int maxSizeMRU = 5;
private DocumentsMRU documentsMRU = new DocumentsMRU(maxSizeMRU);
/** The differents button of toolbar */
private TestGanttRolloverButton bExit, bNew, bOpen, bSave, bSaveAs,
bExport, bImport, bPrint, bPreviewPrint, bCopy, bCut, bPaste,
bNewTask, bDelete, bProperties, bUnlink, bLink, bInd, bUnind, bUp,
bDown, bPrev, bScrollCenter, bNext, bZoomFit, bAbout;
private TestGanttRolloverButton bShowHiddens;
private JPopupMenu menu = new JPopupMenu();;
TestGanttRolloverButton bZoomIn, bZoomOut;
private TestGanttRolloverButton bUndo, bRedo;
private TestGanttRolloverButton bCritical;
private TestGanttRolloverButton bSaveCurrent, bComparePrev;
private TestGanttRolloverButton bRefresh;
/** The project filename */
public Document projectDocument = null;
/** Informations for the current project. */
public PrjInfos prjInfos = new PrjInfos();
/** Boolean to know if the file has been modify */
public boolean askForSave = false;
/** The info for the look'n'feel */
public GanttLookAndFeelInfo lookAndFeel;
/** Is the application only for viewer. */
public boolean isOnlyViewer;
/** The list of all managers installed in this project */
private Hashtable managerHash = new Hashtable();
private ResourceActionSet myResourceActions;
private boolean isApplet;
/** Frame for the help Viewer */
private JFrame helpFrame = null;
private final TaskManager myTaskManager;
private FacadeInvalidator myFacadeInvalidator;
private UIConfiguration myUIConfiguration;
private static class TaskContainmentHierarchyFacadeImpl implements
TaskContainmentHierarchyFacade {
private Map myTask2treeNode = new HashMap();
private Task myRootTask;
private List myPathBuffer = new ArrayList();
private GanttTree2 myTree;
public TaskContainmentHierarchyFacadeImpl(GanttTree2 tree) {
ArrayList allTasks = ((GanttTree2) tree).getAllTasks();
// comboBox.addItem("no set");
// for (int i = 0; i < allTasks.size(); i++) {
// DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)
// allTasks.get(i);
for (Iterator it = allTasks.iterator(); it.hasNext();) {
169
TaskNode treeNode = (TaskNode) it.next();
Task task = (Task) treeNode.getUserObject();
if (treeNode.isRoot()) {
myRootTask = task;
}
myTask2treeNode.put(task, treeNode);
}
myTree = tree;
}
public Task[] getNestedTasks(Task container) {
Task[] result = null;
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) myTask2treeNode
.get(container);
if (treeNode != null) {
ArrayList list = new ArrayList();
for (Enumeration children = treeNode.children(); children
.hasMoreElements();) {
DefaultMutableTreeNode next = (DefaultMutableTreeNode) children
.nextElement();
if (next instanceof TaskNode)
list.add(next.getUserObject());
}
result = (Task[]) list.toArray(new Task[0]);
}
return result == null ? new Task[0] : result;
}
/**
* Purpose: Returns true if the container Task has any nested tasks.
* This should be a quicker check than using getNestedTasks().
*
* @param container
* The Task on which to check for children.
*/
public boolean hasNestedTasks(Task container) {
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) myTask2treeNode
.get(container);
if (treeNode != null) {
if (treeNode.children().hasMoreElements()) {
return true;
}
}
return false;
}
public Task getRootTask() {
return myRootTask;
}
public Task getContainer(Task nestedTask) {
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) myTask2treeNode
.get(nestedTask);
if (treeNode == null) {
return null;
}
DefaultMutableTreeNode containerNode = (DefaultMutableTreeNode) treeNode
.getParent();
return containerNode == null ? null : (Task) containerNode
.getUserObject();
}
public boolean areUnrelated(Task first, Task second) {
myPathBuffer.clear();
for (Task container = getContainer(first); container != null; container = getContainer(container)) {
myPathBuffer.add(container);
}
if (myPathBuffer.contains(second)) {
return false;
}
myPathBuffer.clear();
for (Task container = getContainer(second); container != null; container = getContainer(container)) {
myPathBuffer.add(container);
}
if (myPathBuffer.contains(first)) {
return false;
}
return true;
}
public void move(Task whatMove, Task whereMove) {
DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode) myTask2treeNode
.get(whereMove);
170
DefaultMutableTreeNode movedNode = (DefaultMutableTreeNode) myTask2treeNode
.get(whatMove);
if (movedNode != null) {
TreePath movedPath = new TreePath(movedNode.getPath());
boolean wasSelected = (myTree.getJTree().getSelectionModel()
.isPathSelected(movedPath));
if (wasSelected) {
myTree.getJTree().getSelectionModel().removeSelectionPath(
movedPath);
}
myTree.getModel().removeNodeFromParent(movedNode);
myTree.getModel().insertNodeInto(movedNode, targetNode,
targetNode.getChildCount());
if (wasSelected) {
movedPath = new TreePath(movedNode.getPath());
myTree.getJTree().getSelectionModel().addSelectionPath(
movedPath);
}
} else {
myTree.addObjectWithExpand(whatMove, targetNode);
}
}
public int getDepth(Task task) {
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) myTask2treeNode
.get(task);
return treeNode.getLevel();
}
}
private static class FacadeInvalidator implements TreeModelListener {
private boolean isValid;
public FacadeInvalidator(TreeModel treeModel) {
isValid = false;
treeModel.addTreeModelListener(this);
}
boolean isValid() {
return isValid;
}
void reset() {
isValid = true;
}
public void treeNodesChanged(TreeModelEvent e) {
isValid = false;
}
public void treeNodesInserted(TreeModelEvent e) {
isValid = false;
}
public void treeNodesRemoved(TreeModelEvent e) {
isValid = false;
}
public void treeStructureChanged(TreeModelEvent e) {
isValid = false;
}
}
private final GanttOptions options;
private JMenuBar bar;
// ! Toolbar of ui
private JToolBar toolBar;
private DefaultListModel iconList = new DefaultListModel();
private JList list = new JList(iconList);
private DefaultListModel deletedIconList = new DefaultListModel();
private JList deletedList = new JList(deletedIconList);
// list.setName("list");
171
// ! a status bar on the main frame
private GanttStatusBar statusBar;
private NewTaskAction myNewTaskAction;
private NewHumanAction myNewHumanAction;
private NewArtefactAction myNewArtefactAction;
private CopyAction myCopyAction;
private PasteAction myPasteAction;
private CutAction myCutAction;
private RefreshViewAction myRefreshAction;
private DeleteHumanAction myDeleteHumanAction;
private DeleteAssignmentAction myDeleteAssignmentAction;
private TaskContainmentHierarchyFacadeImpl myCachedFacade;
private List myRolloverActions = new ArrayList();
private ArrayList myPreviousStates = new ArrayList();
private MouseListener myStopEditingMouseListener = null;
private DelayManager myDelayManager;
// private boolean bQuickSave;//to know if gantt has to quicksave the
// project
// private int currentQuickSave;
// private ArrayList aQuick;//List of all the quicksaves
// private int lastQuickSave;
// private int firstQuickSave;
// private int undoNumber;
private JSplitPane mySplitPane;
private Chart[] myCharts = null;
public TaskContainmentHierarchyFacade getTaskContainment() {
if (!myFacadeInvalidator.isValid() || myCachedFacade == null) {
myCachedFacade = new TaskContainmentHierarchyFacadeImpl(tree);
myFacadeInvalidator.reset();
}
return myCachedFacade;
}
/** Constructor */
public GanttProject(boolean isOnlyViewer, String filename, boolean isApplet) {
ToolTipManager.sharedInstance().setInitialDelay(200);
ToolTipManager.sharedInstance().setDismissDelay(60000);
Mediator.registerRoleManager(getRoleManager());
CustomColumnsStorage customColumnsStorage = new CustomColumnsStorage();
Mediator.registerCustomColumnsStorage(customColumnsStorage);
TaskSelectionManager taskSelectionManager = new TaskSelectionManager();
Mediator.registerTaskSelectionManager(taskSelectionManager);
this.isOnlyViewer = isOnlyViewer;
if (!isOnlyViewer)
setTitle(language.getText("appliTitle"));
else
setTitle("GanttViewer");
setFocusable(true);
lookAndFeel = GanttLookAndFeels.getGanttLookAndFeels().getDefaultInfo();
options = new GanttOptions(getRoleManager(), isOnlyViewer);
// Color color = GanttGraphicArea.taskDefaultColor;
options.setUIConfiguration(myUIConfiguration);
options.setDocumentsMRU(documentsMRU);
options.setLookAndFeel(lookAndFeel);
if (options.load()) {
language = options.getLanguage();
GanttGraphicArea.taskDefaultColor = options.getDefaultColor();
lookAndFeel = options.getLnfInfos();
HttpDocument.setLockDAVMinutes(options.getLockDAVMinutes());
}
myUIConfiguration = options.getUIConfiguration();
172
class TaskManagerConfigImpl implements TaskManagerConfig {
public Color getDefaultColor() {
return myUIConfiguration.getTaskColor();
}
public GPCalendar getCalendar() {
return GanttProject.this.getActiveCalendar();
}
public TimeUnitStack getTimeUnitStack() {
return GanttProject.this.getTimeUnitStack();
}
public ResourceManager getResourceManager() {
return GanttProject.this.getHumanResourceManager();
}
}
TaskManagerConfig taskConfig = new TaskManagerConfigImpl();
myTimeUnitStack = new GPTimeUnitStack(getLanguage());
myTaskManager = TaskManager.Access.newInstance(
new TaskContainmentHierarchyFacade.Factory() {
public TaskContainmentHierarchyFacade createFacede() {
return GanttProject.this.getTaskContainment();
}
}, taskConfig);
Mediator.registerTaskManager(myTaskManager);
this.isApplet = isApplet;
myZoomManager = new ZoomManager(this);
ImageIcon icon = new ImageIcon(getClass().getResource(
"/icons/ganttproject.png"));
setIconImage(icon.getImage());
// Create each objects
tree = new GanttTree2(this, myTaskManager, getUIFacade());
myFacadeInvalidator = new FacadeInvalidator(tree.getJTree().getModel());
area = new GanttGraphicArea(this, tree, getTaskManager(),
getZoomManager(), getUndoManager(), myUIConfiguration);
area.getMyChartModel().addOptionChangeListener(
new RowHeightAligner(tree, area.getMyChartModel()));
GanttImagePanel but = new GanttImagePanel("big.png", "tasks.png", 300,
42);
tree.setGraphicArea(area);
//
miChartOptions = new JMenuItem(area.getOptionsDialogAction());
getZoomManager().addZoomListener(area.getZoomListener());
myCopyAction = new CopyAction((GanttTree2) getTree(), options
.getIconSize());
myPasteAction = new PasteAction((GanttTree2) getTree(), options
.getIconSize());
myCutAction = new CutAction((GanttTree2) getTree(), options
.getIconSize());
myRefreshAction = new RefreshViewAction(getUIFacade(), options);
myRolloverActions.add(myCopyAction);
myRolloverActions.add(myPasteAction);
myRolloverActions.add(myCutAction);
myRolloverActions.add(myRefreshAction);
tree.setActions();
// Create the menus
bar = new JMenuBar();
if (!isOnlyViewer)
setJMenuBar(bar);
// Allocation of the menus
mProject = new JMenu();
mMRU = new JMenu();
mMRU.setIcon(new ImageIcon(getClass().getResource(
"/icons/recent_16.gif")));
mEdit = new JMenu();
// mView = new JMenu ();
mTask = new JMenu();
mHuman = new JMenu();
mHelp = new JMenu();
//LH
mReport = new JMenu();
mCalendar = new JMenu();
mServer = new JMenu();
mServer.setIcon(new ImageIcon(getClass().getResource(
173
"/icons/server_16.gif")));
miUndo = new JMenuItem(new UndoAction(getUndoManager(), "16"));
mEdit.add(miUndo);
// miUndo.setEnabled(false);
miRedo = new JMenuItem(new RedoAction(getUndoManager(), "16"));
mEdit.add(miRedo);
// miRedo.setEnabled(false);
mEdit.addSeparator();
createProjectMenu();
miRefresh = new JMenuItem(myRefreshAction);
// miRefresh.setAccelerator((KeyStroke)myRefreshAction.getValue(Action.ACCELERATOR_KEY));
mEdit.add(miRefresh);
mEdit.addSeparator();
miCut = new JMenuItem(myCutAction);
mEdit.add(miCut);
miCopy = new JMenuItem(myCopyAction);
mEdit.add(miCopy);
miPaste = new JMenuItem(myPasteAction);
mEdit.add(miPaste);
mEdit.addSeparator();
miOptions = createNewItem("/icons/settings_16.gif");
mEdit.add(miOptions);
myNewTaskAction = new NewTaskAction((IGanttProject) this);
mTask.add(myNewTaskAction);
miDeleteTask = createNewItem("/icons/delete_16.gif");
mTask.add(miDeleteTask);
miPropertiesTask = createNewItem("/icons/properties_16.gif");
mTask.add(miPropertiesTask);
//
//
myNewHumanAction = new NewHumanAction(getHumanResourceManager(),
getRoleManager(), this, this) {
public void actionPerformed(ActionEvent event) {
super.actionPerformed(event);
getTabs().setSelectedIndex(UIFacade.RESOURCES_INDEX);
}
};
myDeleteAssignmentAction = new DeleteAssignmentAction(
getHumanResourceManager(),
(AssignmentContext) getResourcePanel(), this);
mHuman.add(myNewHumanAction);
myDeleteHumanAction = new DeleteHumanAction(getHumanResourceManager(),
(ResourceContext) getResourcePanel(), this);
miDelHuman = new JMenuItem(myDeleteHumanAction);
mHuman.add(miDelHuman);
miPropHuman = createNewItem("/icons/properties_16.gif");
mHuman.add(miPropHuman);
miSendMailHuman = createNewItem("/icons/send_mail_16.gif");
mHuman.add(miSendMailHuman);
mHuman.add(new ImportResources(getHumanResourceManager(),
getTaskManager(), getRoleManager(), this));
//LH
miReport = createNewItem("/icons/help_16.gif");
mReport.add(miReport);
miEditCalendar = createNewItem("/icons/clock_16.gif");
mCalendar.add(miEditCalendar);
miPrjCal = createNewItem("/icons/default_calendar_16.gif");
mCalendar.add(miPrjCal);
miWebPage = createNewItem("/icons/home_16.gif");
mHelp.add(miWebPage);
miManual = createNewItem("/icons/help_16.gif");
try { // See if helpgui library is on the classpath
Class.forName("net.sourceforge.helpgui.HelpGui");
mHelp.add(miManual);
miManual.setAccelerator(KeyStroke.getKeyStroke("F1"));
} catch (Exception ex) {
// Not add the help button on the ui
}
miTips = createNewItem("/icons/about_16.gif");
mHelp.add(miTips);
miAbout = createNewItem("/icons/manual_16.gif");
mHelp.add(miAbout);
if (!isApplet) {
bar.add(mProject); // for a applet veiwer, Project menu is not
// neccessary By CL
174
}
bar.add(mEdit);
JMenu viewMenu = createViewMenu();
if (viewMenu != null)
bar.add(viewMenu);
// bar.add (mView);
bar.add(mTask);
bar.add(mHuman);
// bar.add(mCalendar);
//LH
bar.add(mReport);
bar.add(mHelp);
setMemonic();
// to create a default project
// createDefaultTree(tree);
JPanel left = new JPanel(new BorderLayout());
left.add(but, BorderLayout.NORTH);
left.add(tree, BorderLayout.CENTER);
left.setPreferredSize(new Dimension(315, 600));
left.setBackground(Color.white);
// A splitpane is use
mySplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
if (language.getComponentOrientation() == ComponentOrientation.LEFT_TO_RIGHT) {
mySplitPane.setLeftComponent(left);
mySplitPane.setRightComponent(area);
mySplitPane
.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
} else {
mySplitPane.setRightComponent(left);
mySplitPane.setLeftComponent(area);
mySplitPane.setDividerLocation((int) (Toolkit.getDefaultToolkit()
.getScreenSize().getWidth() - left.getPreferredSize()
.getWidth()));
mySplitPane
.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
mySplitPane.setOneTouchExpandable(true);
mySplitPane.setPreferredSize(new Dimension(800, 500));
// Add Gantt Panel, Human resource pannel and RESOURCE panel
getTabs().addTab(language.getText("gantt"),
new ImageIcon(getClass().getResource("/icons/tasks_16.gif")),
mySplitPane, area);
getTabs().addTab(language.getText("human"),
new ImageIcon(getClass().getResource("/icons/res_16.gif")),
getResourcePanel(), getResourcePanel().area);
// pert area
getTabs().setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
getTabs().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
bUnlink
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bLink
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bInd
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bUnind
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bCut
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bCopy
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bPaste
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bCritical
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bScrollCenter
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bComparePrev
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
175
bSaveCurrent
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX);
bNewTask
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX
|| getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX);
bDelete
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX
|| getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX);
bProperties
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX
|| getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX);
bDown
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX
|| getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX);
bUp
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX
|| getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX);
bZoomIn
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX
|| getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX);
bZoomOut
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX
|| getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX);
bPrev
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX
|| getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX);
bNext
.setEnabled(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX
|| getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX);
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) { // Gantt
// Chart
bNewTask.setToolTipText(getToolTip(correctLabel(language
.getText("createTask"))));
bDelete.setToolTipText(getToolTip(correctLabel(language
.getText("deleteTask"))));
bProperties.setToolTipText(getToolTip(correctLabel(language
.getText("propertiesTask"))));
if (options.getButtonShow() != GanttOptions.ICONS) {
bNewTask.setText(correctLabel(language
.getText("createTask")));
bDelete.setText(correctLabel(language
.getText("deleteTask")));
bProperties.setText(correctLabel(language
.getText("propertiesTask")));
}
} else if (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) { // Resources
// Chart
bNewTask.setToolTipText(getToolTip(correctLabel(language
176
.getText("newHuman"))));
bDelete.setToolTipText(getToolTip(correctLabel(language
.getText("deleteHuman"))));
bProperties.setToolTipText(getToolTip(correctLabel(language
.getText("propertiesHuman"))));
if (options.getButtonShow() != GanttOptions.ICONS) {
bNewTask.setText(correctLabel(language
.getText("newHuman")));
bDelete.setText(correctLabel(language
.getText("deleteHuman")));
bProperties.setText(correctLabel(language
.getText("propertiesHuman")));
}
}
}
});
// Add tabpan on the content pane
getContentPane().add(getTabs(), BorderLayout.CENTER);
// Add toolbar
toolBar = new JToolBar("GanttProject", options.getToolBarPosition());
toolBar.setBorderPainted(true);
toolBar.setRollover(true);
toolBar.setFloatable(true);
toolBar.addComponentListener(new ComponentListener() {
public void componentResized(ComponentEvent arg0) {
setHiddens();
refresh();
}
public void componentMoved(ComponentEvent arg0) {
}
public void componentShown(ComponentEvent arg0) {
}
public void componentHidden(ComponentEvent arg0) {
}
});
this.addButtons(toolBar);
getContentPane()
.add(
toolBar,
(toolBar.getOrientation() == JToolBar.HORIZONTAL) ? BorderLayout.NORTH
: BorderLayout.WEST);
// add the status bar
statusBar = new GanttStatusBar();
if (!isOnlyViewer)
getContentPane().add(statusBar, BorderLayout.SOUTH);
statusBar.setVisible(options.getShowStatusBar());
// add a keyboard listener
addKeyListener(this);
SwitchViewAction switchAction = new SwitchViewAction(this);
JMenuItem invisibleItem = new JMenuItem(switchAction);
invisibleItem.setVisible(false);
bar.add(invisibleItem);
// Open the the project passed in argument
if (filename != null) {
Document document = DocumentCreator.createDocument(filename);
try {
openDocument(document);
} catch (IOException ex) {
System.err.println(language.getText("msg2") + "\n" + filename);
System.err.println(ex.getMessage());
}
}
// update 18-03-2003
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
177
});
// update 18-03-2003
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension windowSize = getPreferredSize();
// Put the frame at the middle of the screen
setLocation(screenSize.width / 2 - (windowSize.width / 2),
screenSize.height / 2 - (windowSize.height / 2));
this.pack();
changeLanguage();
/*
* [bbaranne] I add a Mediator object so that we can get the GanttProject
* singleton whereever we are in the source code. Perhaps some of you
* don't like this, but I believe that it is practical...
*/
Mediator.registerGanttProject(this);
// changeUndoNumber ();
changeLookAndFeel(lookAndFeel);
changeLookAndFeel(lookAndFeel); // Twice call for update font on menu
if (options.isLoaded()) {
setBounds(options.getX(), options.getY(), options.getWidth(),
options.getHeight());
}
if (options.getOpenTips() && !byCommandLine) {
TipsDialog tips = new TipsDialog(this, options.getOpenTips());
tips.show();
tips.toFront(); // somehow assure, that the TipsDialog is the top
// window an MacOS
}
applyComponentOrientation(GanttLanguage.getInstance()
.getComponentOrientation());
myTaskManager.addTaskListener(new TaskModelModificationListener(this));
if (ourWindowListener != null) {
addWindowListener(ourWindowListener);
}
addMouseListenerToAllContainer(this.getComponents());
myDelayManager = new DelayManager(myTaskManager, tree);
Mediator.registerDelayManager(myDelayManager);
myDelayManager.addObserver(tree);
myTaskManager.addTaskListener(myDelayManager);
}
private void addMouseListenerToAllContainer(Component[] cont) {
for (int i = 0; i < cont.length; i++) {
cont[i].addMouseListener(getStopEditingMouseListener());
if (cont[i] instanceof Container)
addMouseListenerToAllContainer(((Container) cont[i])
.getComponents());
}
}
/**
* Returns a mouseListener that stop the edition in the ganttTreeTable.
*
* @return A mouseListener that stop the edition in the ganttTreeTable.
*/
private MouseListener getStopEditingMouseListener() {
if (myStopEditingMouseListener == null)
myStopEditingMouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getSource() != bNewTask && e.getClickCount() == 1)
tree.stopEditing();
if (e.getButton() == MouseEvent.BUTTON1
&& !(e.getSource() instanceof JTable)
&& !(e.getSource() instanceof AbstractButton)) {
Task taskUnderPointer = area.new MouseSupport()
.findTaskUnderMousePointer(e.getX(), e.getY());
if (taskUnderPointer == null) {
tree.selectTreeRow(-1);
}
}
}
};
return myStopEditingMouseListener;
}
178
private void createProjectMenu() {
miNew = createNewItem("/icons/new_16.gif");
mProject.add(miNew);
miOpen = createNewItem("/icons/open_16.gif");
mProject.add(miOpen);
mProject.add(mMRU);
updateMenuMRU();
mProject.addSeparator();
miSave = createNewItem("/icons/save_16.gif");
miSave.setEnabled(false);
mProject.add(miSave);
miSaveAs = createNewItem("/icons/saveas_16.gif");
mProject.add(miSaveAs);
mProject.addSeparator();
//
ImportFileAction importFile = new ImportFileAction(getUIFacade(), this);
mProject.add(importFile);
ExportFileAction exportFile = new ExportFileAction(getUIFacade(), this,
options);
mProject.add(exportFile);
// miExport = createNewItem("/icons/export_16.gif");
// mProject.add(miExport);
mProject.addSeparator();
miOpenURL = createNewItem("");
miSaveAsURL = createNewItem("");
miPublishToWeb = createNewItem("/icons/publish.gif");
mServer.add(miOpenURL);
mServer.add(miSaveAsURL);
mServer.addSeparator();
mServer.add(miPublishToWeb);
mProject.add(mServer);
mProject.addSeparator();
miPrint = createNewItem("/icons/print_16.gif");
mProject.add(miPrint);
miPreview = createNewItem("/icons/preview_16.gif");
mProject.add(miPreview);
mProject.addSeparator();
miQuit = createNewItem(""/* "/icons/exit_16.gif" */);
mProject.add(miQuit);
}
private JMenu createViewMenu() {
JMenu result = changeMenuLabel(new JMenu(), language.getText("view"));
result.add(miChartOptions);
Chart[] charts = Mediator.getPluginManager().getCharts();
if (charts.length > 0)
result.addSeparator();
for (int i = 0; i < charts.length; i++) {
result.add(new JCheckBoxMenuItem(new ToggleChartAction(charts[i],
getViewManager())));
}
return result;
}
public GanttProject(boolean isOnlyViewer, String filename) {
this(isOnlyViewer, filename, false);
}
/**
* Updates the last open file menu items.
*/
private void updateMenuMRU() {
mMRU.removeAll();
int index = 0;
Iterator iterator = documentsMRU.iterator();
while (iterator.hasNext()) {
index++;
Document document = (Document) iterator.next();
JMenuItem mi = new JMenuItem(new OpenDocumentAction(index,
document, this));
mMRU.add(mi);
}
}
public String getXslDir() {
return options.getXslDir();
}
/** @return the options of ganttproject. */
public GanttOptions getOptions() {
return options;
}
public void restoreOptions() {
options.initByDefault(); // options by default
iconList = initIconList();
179
deletedIconList = initDeletedIconList();
addButtons();
myUIConfiguration = options.getUIConfiguration();
GanttGraphicArea.taskDefaultColor = new Color(140, 182, 206);
area.repaint();
}
/** @return the status Bar of the main frame. */
public GanttStatusBar getStatusBar() {
return statusBar;
}
public String getXslFo() {
return options.getXslFo();
}
/** Create memonic for keyboard */
public void setMemonic() {
int MENU_MASK = GPAction.MENU_MASK;
// --NEW----------------------------------
// miNew.setMnemonic(KeyEvent.VK_N);
miNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, MENU_MASK));
// --OPEN----------------------------------
miOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, MENU_MASK));
// Open from the web
// miOpenURL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I,
// MENU_MASK));
// --SAVE----------------------------------
miSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, MENU_MASK));
// --PRINT----------------------------------
miPrint
.setAccelerator(KeyStroke
.getKeyStroke(KeyEvent.VK_P, MENU_MASK));
// --UNDO----------------------------------
miUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, MENU_MASK));
// --REDO----------------------------------
miRedo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, MENU_MASK));
if (!isOnlyViewer) {
// --QUIT----------------------------------
miQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
MENU_MASK));
// //--CUT----------------------------------
// miCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
// MENU_MASK));
// //--COPY----------------------------------
// miCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
// MENU_MASK));
// //--PASTE----------------------------------
// miPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
// MENU_MASK));
// --OPTIONS----------------------------------
miOptions.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
MENU_MASK));
// --NEW TASK----------------------------------
// miNewTask.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
// MENU_MASK));
// --PROPERTIES TASK----------------------------------
miPropertiesTask.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_R, MENU_MASK));
// --DELETE TASK----------------------------------
miDeleteTask.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,
MENU_MASK));
// --NEW HUMAN----------------------------------
// miNewHuman.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
// MENU_MASK));
// miDelHuman.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_J,
// MENU_MASK));
miPropHuman.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
MENU_MASK));
}
}
/** Create an item with a label */
public JMenuItem createNewItemText(String label) {
180
JMenuItem item = new JMenuItem(label);
item.addActionListener(this);
return item;
}
/** Create an item with an icon */
public JMenuItem createNewItem(String icon) {
URL url = getClass().getResource(icon);
JMenuItem item = url == null ? new JMenuItem() : new JMenuItem(
new ImageIcon(url));
item.addActionListener(this);
return item;
}
/** Create an item with a label and an icon */
public JMenuItem createNewItem(String label, String icon) {
JMenuItem item = new JMenuItem(label, new ImageIcon(getClass()
.getResource(icon)));
item.addActionListener(this);
return item;
}
/** Function to change language of the project */
public void changeLanguage() {
if (helpFrame != null)
helpFrame.dispose();
helpFrame = null;
applyComponentOrientation(language.getComponentOrientation());
changeLanguageOfMenu();
area.repaint();
getResourcePanel().area.repaint();
getResourcePanel().refresh(language);
this.tree.changeLanguage(language);
CustomColumnsStorage.changeLanguage(language);
applyComponentOrientation(language.getComponentOrientation());
// change the value of the separators in iconList
for (int i = 0; i < iconList.size(); i++)
if (iconList.getElementAt(i).getClass() != TestGanttRolloverButton.class) {
iconList.removeElementAt(i);
iconList.add(i, language.getText("separator").toUpperCase());
}
}
/** Change the style of the application */
public void changeLookAndFeel(GanttLookAndFeelInfo lookAndFeel) {
try {
UIManager.setLookAndFeel(lookAndFeel.getClassName());
SwingUtilities.updateComponentTreeUI(this);
this.lookAndFeel = lookAndFeel;
} catch (Exception e) {
GanttLookAndFeelInfo info = GanttLookAndFeels
.getGanttLookAndFeels().getDefaultInfo();
System.out.println("Can't find the LookAndFeel\n"
+ lookAndFeel.getClassName() + "\n" + lookAndFeel.getName()
+ "\nSetting the default Look'n'Feel" + info.getName());
try {
UIManager.setLookAndFeel(info.getClassName());
SwingUtilities.updateComponentTreeUI(this);
this.lookAndFeel = info;
} catch (Exception ex) {
}
}
// MetalLookAndFeel.setCurrentTheme(new GanttMetalTheme());
// must force to do that instead of the task on tree are not in
// continuity of the calendar
if (tree.getTable().getRowHeight() <= 22)
tree.getTable().setRowHeight(20);
}
// Correct the label of menu without '$' character
public static String correctLabel(String label) {
int index = label.indexOf('$');
if (index != -1 && label.length() - index > 1)
label = label.substring(0, index).concat(label.substring(++index));
return label;
}
181
/** Change the label for menu, in fact check in the label contains a mnemonic */
public JMenu changeMenuLabel(JMenu menu, String label) {
int index = label.indexOf('$');
if (index != -1 && label.length() - index > 1) {
menu.setText(label.substring(0, index).concat(
label.substring(++index)));
menu.setMnemonic(Character.toLowerCase(label.charAt(index)));
} else {
menu.setText(label);
// menu.setMnemonic('');
}
return menu;
}
/**
* Change the label for menuItem, in fact check in the label contains a
* mnemonic
*/
public JMenuItem changeMenuLabel(JMenuItem menu, String label) {
int index = label.indexOf('$');
if (index != -1 && label.length() - index > 1) {
menu.setText(label.substring(0, index).concat(
label.substring(++index)));
menu.setMnemonic(Character.toLowerCase(label.charAt(index)));
} else {
menu.setText(label);
// menu.setMnemonic('');
}
return menu;
}
/**
* Change the label for JCheckBoxmenuItem, in fact check in the label
* contains a mnemonic
*/
public JCheckBoxMenuItem changeMenuLabel(JCheckBoxMenuItem menu,
String label) {
int index = label.indexOf('$');
if (index != -1 && label.length() - index > 1) {
menu.setText(label.substring(0, index).concat(
label.substring(++index)));
menu.setMnemonic(Character.toLowerCase(label.charAt(index)));
} else {
menu.setText(label);
// menu.setMnemonic('');
}
return menu;
}
/** Set the menus language after the user select a different language */
private void changeLanguageOfMenu() {
mProject = changeMenuLabel(mProject, language.getText("project"));
mEdit = changeMenuLabel(mEdit, language.getText("edit"));
// mView = changeMenuLabel(mView, language.getText("view"));
mTask = changeMenuLabel(mTask, language.getText("task"));
mHuman = changeMenuLabel(mHuman, language.getText("human"));
mHelp = changeMenuLabel(mHelp, language.getText("help"));
//LH
mReport = changeMenuLabel(mReport, language.getText("report"));
mCalendar = changeMenuLabel(mCalendar, language.getText("calendars"));
miNew = changeMenuLabel(miNew, language.getText("newProject"));
miOpen = changeMenuLabel(miOpen, language.getText("openProject"));
mMRU = changeMenuLabel(mMRU, language.getText("lastOpen"));
miSave = changeMenuLabel(miSave, language.getText("saveProject"));
miSaveAs = changeMenuLabel(miSaveAs, language.getText("saveAsProject"));
mServer = changeMenuLabel(mServer, language.getText("webServer"));
miOpenURL = changeMenuLabel(miOpenURL, language
.getText("openFromServer"));
miSaveAsURL = changeMenuLabel(miSaveAsURL, language
.getText("saveToServer"));
miPublishToWeb = changeMenuLabel(miPublishToWeb, language
.getText("publishToWeb"));
miPrint = changeMenuLabel(miPrint, language.getText("printProject"));
miPreview = changeMenuLabel(miPreview, language.getText("preview"));
miQuit = changeMenuLabel(miQuit, language.getText("quit"));
182
miUndo = changeMenuLabel(miUndo, language.getText("undo"));
miRedo = changeMenuLabel(miRedo, language.getText("redo"));
miCut = changeMenuLabel(miCut, language.getText("cut"));
miCopy = changeMenuLabel(miCopy, language.getText("copy"));
miPaste = changeMenuLabel(miPaste, language.getText("paste"));
miOptions = changeMenuLabel(miOptions, language.getText("settings"));
// miNewTask = changeMenuLabel(miNewTask,
// language.getText("createTask"));
miDeleteTask = changeMenuLabel(miDeleteTask, language
.getText("deleteTask"));
miPropertiesTask = changeMenuLabel(miPropertiesTask, language
.getText("propertiesTask"));
mHuman.insert(changeMenuLabel(mHuman.getItem(0), language
.getText("newHuman")), 0);
miDelHuman = changeMenuLabel(miDelHuman, language
.getText("deleteHuman"));
miPropHuman = changeMenuLabel(miPropHuman, language
.getText("propertiesHuman"));
mHuman.insert(changeMenuLabel(mHuman.getItem(4), language
.getText("importResources")), 4);
miSendMailHuman = changeMenuLabel(miSendMailHuman, language
.getText("sendMail"));
miEditCalendar = changeMenuLabel(miEditCalendar, language
.getText("editCalendars"));
miPrjCal = changeMenuLabel(miPrjCal, language
.getText("projectCalendar"));
miWebPage = changeMenuLabel(miWebPage, language.getText("webPage"));
miReport = changeMenuLabel(miReport, language.getText("report"));
miAbout = changeMenuLabel(miAbout, language.getText("about"));
miTips = changeMenuLabel(miTips, language.getText("tipsOfTheDay"));
miManual = changeMenuLabel(miManual, language.getText("manual"));
miChartOptions = changeMenuLabel(miChartOptions, language
.getText("chartOptions"));
miRefresh = changeMenuLabel(miRefresh, language.getText("refresh"));
// //////////////////////////////////////////
bExit
.setToolTipText(getToolTip(correctLabel(language
.getText("quit"))));
bNew.setToolTipText(getToolTip(correctLabel(language
.getText("newProject"))));
bOpen.setToolTipText(getToolTip(correctLabel(language
.getText("openProject"))));
bSave.setToolTipText(getToolTip(correctLabel(language
.getText("saveProject"))));
bSaveAs.setToolTipText(getToolTip(correctLabel(language
.getText("saveAsProject"))));
bPrint.setToolTipText(getToolTip(correctLabel(language
.getText("printProject"))));
bPreviewPrint.setToolTipText(getToolTip(correctLabel(language
.getText("preview"))));
bExport.setToolTipText(getToolTip(correctLabel(language
.getText("export"))));
bImport.setToolTipText(getToolTip(correctLabel(language
.getText("import"))));
bNewTask.setToolTipText(getToolTip(correctLabel(language
.getText("createTask"))));
bCut.setToolTipText(getToolTip(correctLabel(language.getText("cut"))));
bCopy
.setToolTipText(getToolTip(correctLabel(language
.getText("copy"))));
bPaste
.setToolTipText(getToolTip(correctLabel(language
.getText("paste"))));
bDelete.setToolTipText(getToolTip(correctLabel(language
.getText("deleteTask"))));
bProperties.setToolTipText(getToolTip(correctLabel(language
.getText("propertiesTask"))));
bUnlink.setToolTipText(getToolTip(correctLabel(language
.getText("unlink"))));
bLink
.setToolTipText(getToolTip(correctLabel(language
.getText("link"))));
bInd.setToolTipText(getToolTip(correctLabel(language
.getText("indentTask"))));
bUnind.setToolTipText(getToolTip(correctLabel(language
183
.getText("dedentTask"))));
bUp
.setToolTipText(getToolTip(correctLabel(language
.getText("upTask"))));
bDown.setToolTipText(getToolTip(correctLabel(language
.getText("downTask"))));
bPrev.setToolTipText(getToolTip(correctLabel(language
.getText("backDate"))));
bScrollCenter.setToolTipText(getToolTip(correctLabel(language
.getText("centerOnSelectedTasks"))));
bNext.setToolTipText(getToolTip(correctLabel(language
.getText("forwardDate"))));
bZoomIn.setToolTipText(getToolTip(correctLabel(language
.getText("zoomIn"))));
bZoomOut.setToolTipText(getToolTip(correctLabel(language
.getText("zoomOut"))));
bAbout
.setToolTipText(getToolTip(correctLabel(language
.getText("about"))));
bUndo
.setToolTipText(getToolTip(correctLabel(language
.getText("undo"))));
bRedo
.setToolTipText(getToolTip(correctLabel(language
.getText("redo"))));
// bZoomFit.setToolTipText(getToolTip(language.zoomFit()));
bCritical.setToolTipText(getToolTip(language.getText("criticalPath")));
bComparePrev
.setToolTipText(getToolTip(language.getText("comparePrev")));
bSaveCurrent
.setToolTipText(getToolTip(language.getText("saveCurrent")));
bRefresh.setToolTipText(getToolTip(language.getText("refresh")));
bShowHiddens
.setToolTipText(getToolTip(language.getText("showHiddens")));
getTabs().setTitleAt(1, correctLabel(language.getText("human")));
setButtonText();
}
/** Invoked when a key has been pressed. */
public void keyPressed(KeyEvent e) {
final int MENU_MASK = Toolkit.getDefaultToolkit()
.getMenuShortcutKeyMask();
// System.out.println(e.getKeyCode());
/*
* Consume the event to prevent it to go farther.
*/
int code = e.getKeyCode();
int modifiers = e.getModifiersEx();
if (code == KeyEvent.KEY_LOCATION_UNKNOWN)
e.consume();
switch (code) {
case KeyEvent.VK_DELETE:
e.consume();
if (!isOnlyViewer) {
if (getViewIndex() == UIFacade.GANTT_INDEX)
deleteTasks(true);
else if (getViewIndex() == UIFacade.RESOURCES_INDEX) {
deleteResources();
deleteAssignements();
}
}
break;
// case KeyEvent.VK_INSERT :
// // if(!isOnlyViewer);newTask();break;
case KeyEvent.VK_ENTER:
if (!isOnlyViewer) {
e.consume();
if ((modifiers & InputEvent.ALT_DOWN_MASK) == InputEvent.ALT_DOWN_MASK) {
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// Chart
propertiesTask();
} else if (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) { // Resource
// chart
getResourcePanel().propertiesHuman(GanttProject.this);
184
}
}
}
break;
case KeyEvent.VK_TAB: {
e.consume();
if ((modifiers & InputEvent.SHIFT_DOWN_MASK) == InputEvent.SHIFT_DOWN_MASK) {
tree.dedentCurrentNodes();
} else
tree.indentCurrentNodes();
break;
}
case KeyEvent.VK_F5: {
e.consume();
repaint2();
break;
}
// case KeyEvent.VK_F7:
// {
// if((modifiers & InputEvent.CTRL_DOWN_MASK) ==
// InputEvent.CTRL_DOWN_MASK)
// {
// tabpane.setSelectedIndex((tabpane.getSelectedIndex()+1)%
// tabpane.getTabCount());
// }
// break;
// }
// case KeyEvent.VK_HOME : tree.selectTreeRow(0); break; //go at the
// first task
// case KeyEvent.VK_END : tree.selectTreeRow(tree.nbTasks-1); break;
// //go at the last task
}
}
/** Invoked when a key has been released. */
public void keyReleased(KeyEvent e) {
}
/** Invoked when a key has been typed. */
public void keyTyped(KeyEvent e) {
}
/** Return the tooltip in html (with yello bgcolor */
public static String getToolTip(String msg) {
return "<html><body bgcolor=#EAEAEA>" + msg + "</body></html>";
}
/** Set the text on the buttons. */
public void setButtonText() {
if (options.getButtonShow() == GanttOptions.ICONS) {
bExit.setText("");
bNew.setText("");
bOpen.setText("");
bSave.setText("");
bCut.setText("");
bCopy.setText("");
bPaste.setText("");
bSaveAs.setText("");
bNewTask.setText("");
bImport.setText("");
bExport.setText("");
bPrint.setText("");
bPreviewPrint.setText("");
bDelete.setText("");
bProperties.setText("");
bUnlink.setText("");
bLink.setText("");
bInd.setText("");
bUnind.setText("");
bUp.setText("");
bDown.setText("");
bPrev.setText("");
bNext.setText("");
bScrollCenter.setText("");
bZoomOut.setText("");
bZoomIn.setText("");
bAbout.setText("");
bUndo.setText("");
bRedo.setText("");
bCritical.setText("");
bComparePrev.setText("");
bSaveCurrent.setText("");
bRefresh.setText("");
bShowHiddens.setText("");
} else {
bExit.setText(correctLabel(language.getText("quit")));
bNew.setText(correctLabel(language.getText("newProject")));
185
bOpen.setText(correctLabel(language.getText("openProject")));
bSave.setText(correctLabel(language.getText("saveProject")));
bSaveAs.setText(correctLabel(language.getText("saveAsProject")));
bImport.setText(correctLabel(language.getText("import")));
bExport.setText(correctLabel(language.getText("export")));
bPrint.setText(correctLabel(language.getText("printProject")));
bPreviewPrint.setText(correctLabel(language.getText("preview")));
bCut.setText(correctLabel(language.getText("cut")));
bCopy.setText(correctLabel(language.getText("copy")));
bPaste.setText(correctLabel(language.getText("paste")));
bNewTask.setText(correctLabel(language.getText(getTabs()
.getSelectedIndex() == UIFacade.GANTT_INDEX ? "createTask"
: "newHuman")));
bDelete.setText(correctLabel(language.getText(getTabs()
.getSelectedIndex() == UIFacade.GANTT_INDEX ? "deleteTask"
: "deleteHuman")));
bProperties
.setText(correctLabel(language
.getText(getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX ? "propertiesTask"
: "propertiesHuman")));
bUnlink.setText(correctLabel(language.getText("unlink")));
bLink.setText(correctLabel(language.getText("link")));
bInd.setText(correctLabel(language.getText("indentTask")));
bUnind.setText(correctLabel(language.getText("dedentTask")));
bUp.setText(correctLabel(language.getText("upTask")));
bDown.setText(correctLabel(language.getText("downTask")));
bPrev.setText(correctLabel(language.getText("backDate")));
bScrollCenter.setText(correctLabel(language
.getText("centerOnSelectedTasks")));
bNext.setText(correctLabel(language.getText("forwardDate")));
bZoomOut.setText(correctLabel(language.getText("zoomOut")));
bZoomIn.setText(correctLabel(language.getText("zoomIn")));
bAbout.setText(correctLabel(language.getText("about")));
bUndo.setText(correctLabel(language.getText("undo")));
bRedo.setText(correctLabel(language.getText("redo")));
bCritical.setText(language.getText("criticalPath"));
bComparePrev.setText(correctLabel(language.getText("comparePrev")));
bSaveCurrent.setText(correctLabel(language.getText("saveCurrent")));
bRefresh.setText(correctLabel(language.getText("refresh")));
// bShowHiddens.setText
// (correctLabel(language.getText("showHiddens")));
}
}
/** Apply Buttons options. */
public void applyButtonOptions() {
setButtonText();
if (options.getButtonShow() == GanttOptions.TEXT) {
// remove the icons
bExit.setDefaultIcon(null);
bNew.setDefaultIcon(null);
bOpen.setDefaultIcon(null);
bSave.setDefaultIcon(null);
bSaveAs.setDefaultIcon(null);
bImport.setDefaultIcon(null);
bExport.setDefaultIcon(null);
bPrint.setDefaultIcon(null);
bPreviewPrint.setDefaultIcon(null);
bNewTask.setDefaultIcon(null);
bDelete.setDefaultIcon(null);
bCut.setDefaultIcon(null);
bCopy.setDefaultIcon(null);
bPaste.setDefaultIcon(null);
bProperties.setDefaultIcon(null);
bUnlink.setDefaultIcon(null);
bLink.setDefaultIcon(null);
bInd.setDefaultIcon(null);
bUnind.setDefaultIcon(null);
bUp.setDefaultIcon(null);
bDown.setDefaultIcon(null);
186
bPrint.setDefaultIcon(null);
bPrev.setDefaultIcon(null);
bScrollCenter.setDefaultIcon(null);
bZoomOut.setDefaultIcon(null);
bZoomIn.setDefaultIcon(null);
bAbout.setDefaultIcon(null);
bUndo.setDefaultIcon(null);
bRedo.setDefaultIcon(null);
bCritical.setDefaultIcon(null);
bComparePrev.setDefaultIcon(null);
bSaveCurrent.setDefaultIcon(null);
bRefresh.setDefaultIcon(null);
// bShowHiddens.setDefaultIcon(null);
for (int i = 0; i < myRolloverActions.size(); i++) {
RolloverAction next = (RolloverAction) myRolloverActions.get(i);
next.isIconVisible(false);
next.setIconSize(options.getIconSize());
}
} else {
// set the approrpiate icons
bExit.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/exit_" + options.getIconSize() + ".gif")));
bNew.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/new_" + options.getIconSize() + ".gif")));
bOpen.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/open_" + options.getIconSize() + ".gif")));
bSave.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/save_" + options.getIconSize() + ".gif")));
bSaveAs.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/saveas_" + options.getIconSize() + ".gif")));
bImport.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/import_" + options.getIconSize() + ".gif")));
bExport.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/export_" + options.getIconSize() + ".gif")));
bPrint.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/print_" + options.getIconSize() + ".gif")));
bPreviewPrint.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/preview_" + options.getIconSize() + ".gif")));
bNewTask.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/insert_" + options.getIconSize() + ".gif")));
bDelete.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/delete_" + options.getIconSize() + ".gif")));
bProperties.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/properties_" + options.getIconSize() + ".gif")));
bCut.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/cut_" + options.getIconSize() + ".gif")));
bCopy.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/copy_" + options.getIconSize() + ".gif")));
bPaste.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/paste_" + options.getIconSize() + ".gif")));
bUnlink.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/unlink_" + options.getIconSize() + ".gif")));
bLink.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/link_" + options.getIconSize() + ".gif")));
bInd.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/indent_" + options.getIconSize() + ".gif")));
bUnind.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/unindent_" + options.getIconSize() + ".gif")));
bUp.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/up_" + options.getIconSize() + ".gif")));
bDown.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/down_" + options.getIconSize() + ".gif")));
bPrev.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/prev_" + options.getIconSize() + ".gif")));
187
bNext.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/next_" + options.getIconSize() + ".gif")));
bScrollCenter.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/scrollcenter_" + options.getIconSize() + ".gif")));
bZoomOut.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/zoomm_" + options.getIconSize() + ".gif")));
bZoomIn.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/zoomp_" + options.getIconSize() + ".gif")));
bAbout.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/manual_" + options.getIconSize() + ".gif")));
if (!myUIConfiguration.isCriticalPathOn())
bCritical.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/criticalPathOff_" + options.getIconSize()
+ ".gif")));
else
bCritical.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/criticalPathOn_" + options.getIconSize()
+ ".gif")));
bComparePrev.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/comparePrev_" + options.getIconSize() + ".gif")));
bSaveCurrent.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/saveCurrentAsPrev_" + options.getIconSize()
+ ".gif")));
bRefresh.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/" + myRefreshAction.getIconFilePrefix()
+ options.getIconSize() + ".gif")));
bShowHiddens.setDefaultIcon(new ImageIcon(getClass().getResource(
"/icons/showHiddens.gif")));
for (int i = 0; i < myRolloverActions.size(); i++) {
RolloverAction next = (RolloverAction) myRolloverActions.get(i);
next.isIconVisible(true);
next.setIconSize(options.getIconSize());
}
}
}
/** Create the button on toolbar */
public void addButtons(JToolBar toolBar) {
// toolBar.addSeparator(new Dimension(20,0));
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bExit = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/exit_" + options.getIconSize() + ".gif")));
bExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
quitApplication();
}
});
// if(isOnlyViewer)
// {
// toolBar.add(bExit);
// toolBar.addSeparator(new Dimension(20,0));
// }
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bNew = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/new_" + options.getIconSize() + ".gif")));
bNew.addActionListener(this);
// if(!isOnlyViewer) toolBar.add(bNew);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bOpen = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/open_" + options.getIconSize() + ".gif")));
bOpen.addActionListener(this);
// toolBar.add(bOpen);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bSave = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/save_" + options.getIconSize() + ".gif")));
188
bSave.setEnabled(false);
bSave.addActionListener(this);
// toolBar.add(bSave);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bSaveAs = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/saveas_" + options.getIconSize() + ".gif")));
bSaveAs.addActionListener(this);
// toolBar.add(bSaveAs);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bImport = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/import_" + options.getIconSize() + ".gif")));
bImport.addActionListener(this);
// toolBar.add(bImport);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bExport = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/export_" + options.getIconSize() + ".gif")));
bExport.addActionListener(this);
// toolBar.add(bExport);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bPrint = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/print_" + options.getIconSize() + ".gif")));
bPrint.addActionListener(this);
bPreviewPrint = new TestGanttRolloverButton(new ImageIcon(
getClass().getResource(
"/icons/preview_" + options.getIconSize() + ".gif")));
bPreviewPrint.addActionListener(this);
// toolBar.add(bPrint);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
// toolBar.addSeparator(new Dimension(20,0));
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bComparePrev = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/comparePrev_" + options.getIconSize() + ".gif")));
bComparePrev.setEnabled(false);
bComparePrev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
compareToPreviousState();
if (myPreviousStates.size() == 0)
bComparePrev.setEnabled(false);
}
});
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bSaveCurrent = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource(
"/icons/saveCurrentAsPrev_" + options.getIconSize()
+ ".gif")));
bSaveCurrent.setEnabled(false);
bSaveCurrent.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveAsPreviousState();
}
});
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bCut = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/cut_" + options.getIconSize() + ".gif")));
bCut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tree.cutSelectedNode();
setAskForSave(true);
}
});
// if(!isOnlyViewer)toolBar.add(bCut);
bCopy = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/copy_" + options.getIconSize() + ".gif")));
bCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tree.copySelectedNode();
}
});
189
// if(!isOnlyViewer)toolBar.add(bCopy);
bPaste = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/paste_" + options.getIconSize() + ".gif")));
bPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tree.pasteNode();
setAskForSave(true);
}
});
// bCut = new TestGanttRolloverButton(new
// ImageIcon(getClass().getResource("/icons/cut_"+options.getIconSize()+".gif")));
// bCut.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// tree.cutSelectedNode();
// setAskForSave(true);
// }
// });
// bCut = new TestGanttRolloverButton(myCutAction);
// if(!isOnlyViewer)toolBar.add(bCut);
// bCopy = new TestGanttRolloverButton(new
// ImageIcon(getClass().getResource("/icons/copy_"+options.getIconSize()+".gif")));
// bCopy.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// tree.copySelectedNode();
// }
// });
// bCopy = new TestGanttRolloverButton(myCopyAction);
// if(!isOnlyViewer)toolBar.add(bCopy);
// bPaste = new TestGanttRolloverButton(new
// ImageIcon(getClass().getResource("/icons/paste_"+options.getIconSize()+".gif")));
// bPaste.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// tree.pasteNode();
// setAskForSave(true);
// }
// });
// /bPaste = new TestGanttRolloverButton(myPasteAction);
// if(!isOnlyViewer)
{
// toolBar.add(bPaste);
// toolBar.addSeparator(new Dimension(20,0));
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
// bNewTask = new TestGanttRolloverButton(new
// ImageIcon(getClass().getResource("/icons/insert_"+options.getIconSize()+".gif")));
myNewArtefactAction = new NewArtefactAction(
new NewArtefactAction.ActiveActionProvider() {
public AbstractAction getActiveAction() {
return getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX ? (AbstractAction) myNewTaskAction
: (AbstractAction) myNewHumanAction;
}
}, options.getIconSize());
bNewTask = new TestGanttRolloverButton(myNewArtefactAction);
myRolloverActions.add(myNewArtefactAction);
// bNewTask.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// if (tabpane.getSelectedIndex() == 0) {//Gantt Chart
// newTask();
// } else if (tabpane.getSelectedIndex() == 1) { //Resource chart
// HumanResource people = new HumanResource();
// GanttDialogPerson dp = new GanttDialogPerson(
// GanttProject.this, getLanguage(), people);
// dp.show();
// if (dp.result()) {
// getHumanResourceManager().add(people);
// setAskForSave(true);
// }
// }
// }
// });
// if(!isOnlyViewer) toolBar.add(bNewTask);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bDelete = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/delete_" + options.getIconSize() + ".gif")));
bDelete.addActionListener(new ActionListener() {
190
public void actionPerformed(ActionEvent e) {
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// Chart
// deleteTask();
deleteTasks(true);
} else if (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) { // Resource
// chart
final ProjectResource[] context = getResourcePanel()
.getContext().getResources();
if (context.length > 0) {
GanttDialogInfo gdi = new GanttDialogInfo(
GanttProject.this, GanttDialogInfo.QUESTION,
GanttDialogInfo.YES_NO_OPTION, getLanguage()
.getText("msg6")
+ getDisplayName(context) + "??",
getLanguage().getText("question"));
gdi.show();
if (gdi.res == GanttDialogInfo.YES) {
for (int i = 0; i < context.length; i++) {
getHumanResourceManager().remove(context[i],
getUndoManager());
refreshProjectInfos();
// setQuickSave(true);
}
}
}
deleteAssignements();
}
}
});
// if(!isOnlyViewer) toolBar.add(bDelete);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bProperties = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource(
"/icons/properties_" + options.getIconSize() + ".gif")));
bProperties.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// Chart
propertiesTask();
} else if (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) { // Resource
// chart
getResourcePanel().propertiesHuman(GanttProject.this);
}
}
});
// if(!isOnlyViewer) toolBar.add(bProperties);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bUnlink = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/unlink_" + options.getIconSize() + ".gif")));
bUnlink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// Chart
unlinkRelationships();
}
}
});
// if(!isOnlyViewer) toolBar.add(bUnlink);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bLink = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/link_" + options.getIconSize() + ".gif")));
bLink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// Chart
linkRelationships();
}
}
});
191
// if(!isOnlyViewer) toolBar.add(bLink);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bInd = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/indent_" + options.getIconSize() + ".gif")));
bInd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// Chart
// tree.indentCurrentNode();
tree.indentCurrentNodes();
setAskForSave(true);
}
}
});
// if(!isOnlyViewer) toolBar.add(bInd);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bUnind = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource(
"/icons/unindent_" + options.getIconSize() + ".gif")));
bUnind.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// Chart
// tree.dedentCurrentNode();
tree.dedentCurrentNodes();
setAskForSave(true);
}
}
});
// if(!isOnlyViewer) toolBar.add(bUnind);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bUp = new TestGanttRolloverButton(new ImageIcon(getClass().getResource(
"/icons/up_" + options.getIconSize() + ".gif")));
bUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
upDatas();
}
});
// if(!isOnlyViewer) toolBar.add(bUp);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bDown = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/down_" + options.getIconSize() + ".gif")));
bDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
downDatas();
}
});
if (!isOnlyViewer) {
// toolBar.add(bDown);
// toolBar.addSeparator(new Dimension(20,0));
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
ScrollingManager scrollingManager = getScrollingManager();
scrollingManager.addScrollingListener(area.getViewState());
scrollingManager.addScrollingListener(getResourcePanel().area
.getViewState());
Action scrollLeft = new ScrollGanttChartLeftAction(scrollingManager,
options.getIconSize());
myRolloverActions.add(scrollLeft);
bPrev = new TestGanttRolloverButton(scrollLeft);
bPrev.setAutoRepeatMousePressedEvent(300);
// toolBar.add(bPrev);
Action scrollCenter = area.getScrollCenterAction(scrollingManager,
Mediator.getTaskSelectionManager(), options.getIconSize());
myRolloverActions.add(scrollCenter);
bScrollCenter = new TestGanttRolloverButton(scrollCenter);
bScrollCenter.setAutoRepeatMousePressedEvent(300);
// toolBar.add(bScrollCenter);
Action scrollRight = new ScrollGanttChartRightAction(scrollingManager,
options.getIconSize());
myRolloverActions.add(scrollRight);
bNext = new TestGanttRolloverButton(scrollRight);
bNext.setAutoRepeatMousePressedEvent(300);
192
// toolBar.add(bNext);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
Action zoomOut = new ZoomOutAction(getZoomManager(), options
.getIconSize());
myRolloverActions.add(zoomOut);
bZoomOut = new TestGanttRolloverButton(zoomOut);
// toolBar.add(bZoomOut);
// bZoomOut = new TestGanttRolloverButton(new
// ImageIcon(getClass().getResource("/icons/zoomm_"+options.getIconSize()+".gif")));
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
Action zoomIn = new ZoomInAction(getZoomManager(), options
.getIconSize());
myRolloverActions.add(zoomIn);
bZoomIn = new TestGanttRolloverButton(zoomIn);
// toolBar.add(bZoomIn);
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
bAbout = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/manual_" + options.getIconSize() + ".gif")));
bAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
aboutDialog();
}
});
if (isOnlyViewer) {
// toolBar.addSeparator(new Dimension(20,0));
// toolBar.add(bAbout);
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* bZoomFit = new JButton (new
* ImageIcon(getClass().getResource("/icons/zoomf.gif")));
* bZoomFit.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { area.fitWholeProject(false);
* area.repaint(); } }); toolBar.add(bZoomFit);
*/
Action undo = new UndoAction(getUndoManager(), options.getIconSize());
myRolloverActions.add(undo);
bUndo = new TestGanttRolloverButton(undo);
// bUndo = new TestGanttRolloverButton(new
// ImageIcon(getClass().getResource("/icons/undo_"+options.getIconSize()+".gif")));
// bUndo.setEnabled(false);
// bUndo.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// undo ();}});
Action redo = new RedoAction(getUndoManager(), options.getIconSize());
myRolloverActions.add(redo);
bRedo = new TestGanttRolloverButton(redo);
// bRedo = new TestGanttRolloverButton(new
// ImageIcon(getClass().getResource("/icons/redo_"+options.getIconSize()+".gif")));
// bRedo.setEnabled(false);
// bRedo.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// redo ();}});
// toolBar.addSeparator(new Dimension(20,0));
// toolBar.add(bUndo);
// toolBar.add(bRedo);
Action critic = new CalculateCriticalPathAction(getTaskManager(), tree,
options, getUIConfiguration());
myRolloverActions.add(critic);
bCritical = new TestGanttRolloverButton(critic);
// bCritical.setFocusPainted(false);
// toolBar.addSeparator(new Dimension(20,0));
// toolBar.add(bCritical);
// myRolloverActions.add(myRefreshAction);
// bRefresh = new TestGanttRolloverButton(myRefreshAction);
bRefresh = new TestGanttRolloverButton(new ImageIcon(
getClass().getResource(
"/icons/refresh_" + options.getIconSize() + ".gif")));
bRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
193
getUIFacade().refresh();
}
});
bShowHiddens = new TestGanttRolloverButton(new ImageIcon(getClass()
.getResource("/icons/showHiddens.gif")));
bShowHiddens.addActionListener(this);
iconList = initIconList();
deletedIconList = initDeletedIconList();
addButtons();
applyButtonOptions();
}
protected void saveAsPreviousState() {
GanttDialogSaveAsPreviousState ps = new GanttDialogSaveAsPreviousState(
this);
ps.show();
if (ps.isSaved()) {
bSaveCurrent.setEnabled(false);
bComparePrev.setEnabled(true);
myPreviousStates.add(ps.getPreviousState());
}
}
public ArrayList getPreviouStates() {
return myPreviousStates;
}
protected void compareToPreviousState() {
GanttDialogCompareToPreviousState cp = new GanttDialogCompareToPreviousState(
this);
cp.show();
}
/**
* Adds a separator.
*/
/*
* private static void addToolBarSeparator(JToolBar toolbar, int width, int
* height) { JPanel sepL = new JPanel(); sepL.setMaximumSize(new
* Dimension(width/2,height)); toolbar.add(sepL); JPanel sep = new JPanel();
* sep.setMaximumSize(new Dimension(1,height)); sep.setMinimumSize(new
* Dimension(1,height)); sep.setPreferredSize(new Dimension(1,height));
* sep.setBorder(BorderFactory.createLineBorder(Color.GRAY));
* toolbar.add(sep); JPanel sep2 = new JPanel(); sep2.setMaximumSize(new
* Dimension(1,height)); sep2.setMinimumSize(new Dimension(1,height));
* sep2.setPreferredSize(new Dimension(1,height));
* sep2.setBorder(BorderFactory.createLineBorder(Color.WHITE));
* toolbar.add(sep2); JPanel sepR = new JPanel(); sepR.setMaximumSize(new
* Dimension(width/2,height)); toolbar.add(sepR); }
*/
private void aboutDialog() {
AboutDialog agp = new AboutDialog(this);
agp.show();
}
//LH
private void reportDialog() {
ReportDialog agp = new ReportDialog(this);
agp.show();
}
private String getDisplayName(Object[] objs) {
if (objs.length == 1) {
return objs[0].toString();
}
StringBuffer result = new StringBuffer();
for (int i = 0; i < objs.length; i++) {
result.append(objs[i].toString());
if (i < objs.length - 1) {
result.append(", ");
}
}
return result.toString();
}
/** Move up the datas (resources or tasks) */
private void upDatas() {
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// Chart
tree.upCurrentNodes();
194
} else if (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) { // Resource
// chart
getResourcePanel().upResource();
// getResourcePanel().setPeople(getResourcePanel().getPeople());
getResourcePanel().area.repaint();
}
setAskForSave(true);
}
/** Move down datas (resources or tasks) */
private void downDatas() {
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) { // Gantt
// Chart
tree.downCurrentNodes();
} else if (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) { // Resource
// chart
getResourcePanel().downResource();
// getResourcePanel().setPeople(getResourcePanel().getPeople());
getResourcePanel().area.repaint();
}
setAskForSave(true);
}
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {
quitApplication();
}
/**
* Check if the project has been modified, before creating a new one or open
* another
*/
public boolean checkCurrentProject() {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.WARNING, GanttDialogInfo.YES_NO_CANCEL_OPTION,
language.getText("msg1"), language.getText("warning"));
GanttDialogInfo gdiSaveError = new GanttDialogInfo(this,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_NO_CANCEL_OPTION,
language.getText("msg12"), language.getText("error"));
if (askForSave == true) {
gdi.show();
if (gdi.res == GanttDialogInfo.CANCEL)
return false;
if (gdi.res == GanttDialogInfo.YES) {
boolean trySave = true;
do {
try {
trySave = false;
saveProject();
} catch (Exception e) {
System.err.println(e);
gdiSaveError.show();
if (gdiSaveError.res == GanttDialogInfo.CANCEL)
return false;
trySave = (gdiSaveError.res == GanttDialogInfo.YES);
}
} while (trySave);
}
}
return true;
}
/** A menu has been activate */
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof JMenuItem) {
String arg = evt.getActionCommand();
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
if (arg.equals(correctLabel(language.getText("newProject")))) {
newProject();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("openProject")))) {
try {
if (checkCurrentProject()) {
openFile();
}
} catch (Exception e) {
e.printStackTrace();
if (isVisible()) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
195
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION, language
.getText("msg8"), language
.getText("error"));
gdi.show();
} else
System.out.println("\n====" + language.getText("error")
+ "====\n" + language.getText("msg8") + "\n");
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg
.equals(correctLabel(language.getText("openFromServer")))) {
if (checkCurrentProject()) {
openURL();
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("saveProject")))) {
try {
saveProject();
} catch (Exception e) {
System.err.println(e);
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg
.equals(correctLabel(language.getText("saveAsProject")))) {
try {
saveAsProject();
} catch (Exception e) {
System.err.println(e);
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("saveToServer")))) {
try {
saveAsURLProject();
} catch (Exception e) {
System.err.println(e);
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
// else if (arg.equals(correctLabel(language.getText("export")))) {
// export();}
else if (arg.equals(correctLabel(language.getText("publishToWeb")))) {
ExportFileInfo info = new ExportFileInfo(null,
ExportFileInfo.FORMAT_HTML, options.getExportSettings());
statusBar.setFirstText(language.getText("htmlexport"), 2000);
// construct URL from settings
StringBuffer urlString = new StringBuffer();
urlString.append("ftp://");
urlString.append(options.getFTPUser());
urlString.append(":");
urlString.append(options.getFTPPwd());
urlString.append("@");
urlString.append(options.getFTPUrl());
urlString.append("/");
urlString.append(options.getFTPDirectory() == "" ? "" : options
.getFTPDirectory()
+ "/");
int confirm = JOptionPane.showConfirmDialog(null, language
.getText("confirmFTPTransfer_1")
+ " "
+ urlString.substring(urlString.indexOf("@") + 1)
+ "\n" + language.getText("confirmFTPTransfer_2"),
language.getText("confirm"), JOptionPane.YES_NO_OPTION);
196
/*
* if (confirm == 0) { try { GanttHTMLExport.publish(
* urlString.toString(), prjInfos, this, tree, area,
* getResourcePanel().area,
* statusBar.setFirstText(language.getText("successFTPTransfer"),
* 2000); info.myStorageOptions);
* JOptionPane.showMessageDialog(null,
* language.getText("successFTPTransfer"),
* language.getText("success") ,
* JOptionPane.INFORMATION_MESSAGE); } catch (IOException e) {
* e.printStackTrace(); JOptionPane.showMessageDialog(null,
* e.getMessage(), language.getText("error"),
* JOptionPane.ERROR_MESSAGE); } }
*/
}
else if (arg.equals(language.getText("hideTask"))) {
tree.hideSelectedNodes();
} else if (arg.equals(language.getText("displayHiddenTasks")))
tree.displayHiddenTasks();
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("printProject")))) {
printProject();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("preview")))) {
previewPrint();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("quit")))) {
quitApplication();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("deleteTask")))) {
deleteTasks(true);
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg
.equals(correctLabel(language.getText("propertiesTask")))) {
propertiesTask();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("upTask")))) {
upDatas();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("downTask")))) {
downDatas();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("indentTask")))) {
tree.indentCurrentNodes();
setAskForSave(true);
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("dedentTask")))) {
tree.dedentCurrentNodes();
setAskForSave(true);
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("unlink")))) {
unlinkRelationships();
}
197
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("link")))) {
linkRelationships();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language
.getText("propertiesHuman")))) {
getTabs().setSelectedIndex(UIFacade.RESOURCES_INDEX);
getResourcePanel().propertiesHuman(this);
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg
.equals(correctLabel(language.getText("editCalendars")))) {
GanttDialogCalendar dialogCalendar = new GanttDialogCalendar(
this);
dialogCalendar.show();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language
.getText("projectCalendar")))) {
System.out.println("Project calendar");
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("webPage")))) {
try {
openWebPage();
} catch (Exception e) {
System.err.println(e);
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("tipsOfTheDay")))) {
TipsDialog tips = new TipsDialog(this, options.getOpenTips());
tips.show();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("manual")))) {
if (helpFrame == null) {
try {
helpFrame = new net.sourceforge.helpgui.gui.MainFrame(
"/docs/help/", "eclipse");
// french translation for the user manual
if (language.getText("shortLanguage").equals("fr"))
helpFrame = new net.sourceforge.helpgui.gui.MainFrame(
"/docs/help_fr/", "eclipse");
helpFrame.setTitle(language.getText("ganttManual"));
ImageIcon icon = new ImageIcon(getClass().getResource(
"/icons/ganttproject.png"));
helpFrame.setIconImage(icon.getImage());
helpFrame.setSize((int) (Toolkit.getDefaultToolkit()
.getScreenSize().getWidth() * 0.75),
(int) (Toolkit.getDefaultToolkit()
.getScreenSize().getHeight() * 0.75));
helpFrame.setLocationRelativeTo(null);
} catch (Exception e) {
}
}
helpFrame.setVisible(true);
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("about")))) {
aboutDialog();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
198
else if (arg.equals(correctLabel(language.getText("report")))) {
//LH
reportDialog();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("sendMail")))) {
getTabs().setSelectedIndex(1);
getResourcePanel().sendMail(this);
}
// Newly added code /CL
// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// else if (arg.equals(correctLabel(language.getText("cut")))) {
// tree.cutSelectedNode();
// setAskForSave(true);
// }
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////
// else if (arg.equals(correctLabel(language.getText("copy")))) {
// tree.copySelectedNode();
// }
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////
// else if (arg.equals(correctLabel(language.getText("paste")))) {
// tree.pasteNode();
// setAskForSave(true);
// }
// //////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (arg.equals(correctLabel(language.getText("settings")))) {
launchOptionsDialog();
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// Test if it's a file name
} else if (evt.getSource() instanceof Document) {
if (checkCurrentProject()) {
final ActionEvent ae = evt;
getUndoManager().undoableEdit("StartupDocument",
new Runnable() {
public void run() {
openStartupDocument((Document) ae.getSource());
}
});
}
} // //////////////////////////////////////////////////////////////////////////////////////////////////////////
// Test if it's buttons actions
else if (evt.getSource() instanceof JButton) {
if (evt.getSource() == bNew) // new
newProject();
else if (evt.getSource() == bOpen) { // open
try {
if (checkCurrentProject())
openFile();
} catch (Exception ex) {
System.err.println(ex);
}
} else if (evt.getSource() == bSave) { // save
try {
saveProject();
} catch (Exception ex) {
System.err.println(ex);
}
} else if (evt.getSource() == bSaveAs) { // saveas
try {
saveAsProject();
} catch (Exception ex) {
System.err.println(ex);
}
} else if (evt.getSource() == bExport) { // export
ExportFileWizardImpl wizard = new ExportFileWizardImpl(this
.getUIFacade(), this, this.getOptions());
wizard.show();
} else if (evt.getSource() == bImport) { // import
ImportFileWizardImpl wizard = new ImportFileWizardImpl(this
.getUIFacade(), this);
wizard.show();
} else if (evt.getSource() == bPrint) { // print
printProject();
} else if (evt.getSource() == bPreviewPrint) { // print
previewPrint();
199
} else if (evt.getSource() == bShowHiddens) {
showHiddenButtonsPaneMenu();
}
}
// repaint();
}
/** Launch the options dialog */
public void launchOptionsDialog() {
// old options dialog box
/*
* GanttDialogOptions dialogOptions = new GanttDialogOptions(this,
* myUIConfiguration); dialogOptions.show(); if (dialogOptions.change) {
* setAskForSave(true); }
*/
// new options dialog box
statusBar.setFirstText(language.getText("settingsPreferences"), 2000);
SettingsDialog dialogOptions = new SettingsDialog(this);
dialogOptions.show();
getResourcePanel().reloadRoles();
area.repaint();
}
public ProjectResource newHumanResource() {
final HumanResource people = ((HumanResourceManager) getHumanResourceManager())
.newHumanResource();
people.setRole(getRoleManager().getDefaultRole());
GanttDialogPerson dp = new GanttDialogPerson(this, getLanguage(),
people);
dp.setVisible(true);
if (dp.result()) {
getUndoManager().undoableEdit("new Resource", new Runnable() {
public void run() {
getHumanResourceManager().add(people);
}
});
}
return people;
}
/** Create a new task */
public Task newTask() {
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
int index = -1;
MutableTreeNode selectedNode = (MutableTreeNode) Mediator
.getGanttProjectSingleton().getTree().getSelectedNode();
if (selectedNode != null) {
DefaultMutableTreeNode parent1 = (DefaultMutableTreeNode) selectedNode
.getParent();
index = parent1.getIndex(selectedNode) + 1;
tree.getTreeTable().getTree().setSelectionPath(
new TreePath(parent1.getPath()));
tree.getTreeTable().getTreeTable().editingStopped(
new ChangeEvent(tree.getTreeTable().getTreeTable()));
}
// TODO check if the following code (now commentted) is really
// necessary...
// boolean editing = tree.getTreeTable().getTreeTable().isEditing();
// TaskNode tn = (TaskNode) tree.getSelectedNode();
// TaskNode parent;
// if (editing) {
// System.out.println("Editing");
// if (tn != null) {
// if (tn.isRoot())
// parent = tn;
// else
// parent = (TaskNode) tn.getParent();
// Task t = (Task) parent.getUserObject();
// tree.selectTask(t, false);
// }
// }
// GanttTask current = tree.getSelectedTask();
GanttCalendar cal = new GanttCalendar(area.getViewState()
.getStartDate());
DefaultMutableTreeNode node = tree.getSelectedNode();
200
GanttLanguage lang = GanttLanguage.getInstance();
String nameOfTask = options.getTaskNamePrefix(); // language.getText("newTask");
// if (current != null) {
// current.setMilestone(false);
// node = (TaskNode) tree.getSelectedNode();
// cal = current.getStart();
// if (!node.isRoot())
// nameOfTask = current.toString();
// }
GanttTask task = getTaskManager().createTask();
task.setStart(cal);
task.setLength(1);
getTaskManager().registerTask(task);// create a new task in the tab
// paneneed to register it
task.setName(nameOfTask + "_" + task.getTaskID());
task.setColor(area.getTaskColor());
// if (current != null) {
// if (current.colorDefined()) {
// task.setColor(current.getColor());
// }
// if (current.shapeDefined())
// task.setShape(current.getShape());
// }
TaskNode taskNode = tree.addObject(task, node, index);
/*
* this will add new custom columns to the newly created task.
*/
Mediator.getCustomColumnsStorage().processNewTask(task);
AdjustTaskBoundsAlgorithm alg = getTaskManager()
.getAlgorithmCollection().getAdjustTaskBoundsAlgorithm();
alg.run(task);
RecalculateTaskCompletionPercentageAlgorithm alg2 = getTaskManager()
.getAlgorithmCollection()
.getRecalculateTaskCompletionPercentageAlgorithm();
alg2.run(task);
// refresh the differents tasks
// if (current != null) {
// tree.refreshAllChild(nameOfTask);
// // DefaultMutableTreeNode father = tree.getSelectedNode();
// // GanttTask taskFather = null;
// // For refresh all the parent task
// // while (tree.getNode(task.getTaskID()).isRoot() == false) {
// // father = tree.getFatherNode(task);
// // tree.refreshAllChild(father.toString());
// // taskFather = (GanttTask) father.getUserObject();
// // taskFather.refreshDateAndAdvancement(tree);
// // father.setUserObject(taskFather);
// // task = taskFather;
// // }
// }
area.repaint();
setAskForSave(true);
statusBar.setFirstText(language.getText("createNewTask"), 1000);
if (options.getAutomatic()) {
propertiesTask(new DefaultMutableTreeNode[] { taskNode });
}
// setQuickSave(true);
tree.setEditingTask(task);
repaint2();
return task;
}
public void deleteResources() {
myDeleteHumanAction.actionPerformed(null);
}
public void deleteAssignements() {
myDeleteAssignmentAction.actionPerformed(null);
}
/**
* Delete the currant task
*
* @param confirmation
* TODO
*/
public void deleteTasks(boolean confirmation) {
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
final DefaultMutableTreeNode[] cdmtn = tree.getSelectedNodes();
if (cdmtn == null || cdmtn.length == 0) {
statusBar.setFirstText(language.getText("msg21"), 2000);
return;
}
201
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.QUESTION, GanttDialogInfo.YES_NO_OPTION,
language.getText("msg19"), language.getText("question"));
if (confirmation)
gdi.show();
else
gdi.res = GanttDialogInfo.YES;
if (gdi.res == GanttDialogInfo.YES) {
getUndoManager().undoableEdit("Task removed", new Runnable() {
public void run() {
ArrayList fathers = new ArrayList();
for (int i = 0; i < cdmtn.length; i++) {
if (cdmtn[i] != null && cdmtn[i] instanceof TaskNode) {
Task ttask = (Task) (cdmtn[i].getUserObject());
DefaultMutableTreeNode father = tree
.getFatherNode(ttask);
tree.removeCurrentNode();
if (father != null) {
GanttTask taskFather = (GanttTask) father
.getUserObject();
AdjustTaskBoundsAlgorithm alg = getTaskManager()
.getAlgorithmCollection()
.getAdjustTaskBoundsAlgorithm();
alg.run(taskFather);
// taskFather.refreshDateAndAdvancement(tree);
father.setUserObject(taskFather);
fathers.add(father);
}
getTaskManager().deleteTask(ttask);
ttask.delete();
} else if (cdmtn[i] != null
&& cdmtn[i] instanceof BlankLineNode) {
((GanttTreeTableModel) tree.getTreeTable()
.getTreeTableModel())
.removeNodeFromParent(cdmtn[i]);
}
}
for (int i = 0; i < fathers.size(); i++) {
DefaultMutableTreeNode father = (DefaultMutableTreeNode) fathers
.get(i);
if (father.getChildCount() == 0)
((Task) father.getUserObject())
.setProjectTask(false);
}
}
});
refreshProjectInfos();
area.repaint();
this.repaint2();
getResourcePanel().area.repaint();
setAskForSave(true);
// setQuickSave (true);
// quickSave("deleteTasks");
}
}
/** Edit task parameters */
public void propertiesTask() {
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
if (tree.getSelectedTaskNodes() != null
&& tree.getSelectedTaskNodes().length > 0)
propertiesTask(tree.getSelectedTaskNodes());
}
/** Edit task parameters */
202
public void propertiesTask(DefaultMutableTreeNode[] nodes) {
final int rowHeight = tree.getTreeTable().getTable().getRowHeight();
if (nodes == null || nodes[0].isRoot()) {
statusBar.setFirstText(language.getText("msg21"), 2000);
return;
} else {
statusBar.setFirstText(language.getText("editingParameters"), 2000);
int nbTasks = nodes.length;
String tasksNames = "";
for (int i = 0; i < nodes.length; i++)
if (nodes[i].isRoot()) {
nbTasks = nbTasks - 1;
break;
}
GanttTask[] tasks = new GanttTask[nbTasks];
for (int i = 0; i < nodes.length; i++)
if (!nodes[i].isRoot()) {
tasks[i] = (GanttTask) (nodes[i].getUserObject());
if (!tasksNames.equals(""))
tasksNames = tasksNames + ", ";
tasksNames = tasksNames + tasks[i].getName();
}
GanttDialogProperties pd = new GanttDialogProperties(this, tree,
managerHash, tasks, area, tasksNames);
pd.show();
if (pd.change) {
setAskForSave(true);
setRowHeight(rowHeight);
getResourcePanel().getResourceTreeTableModel()
.updateResources();
}
}
}
/** Unlink the relationships of the selected task */
public void unlinkRelationships() {
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
final DefaultMutableTreeNode[] cdmtn = tree.getSelectedTaskNodes();
if (cdmtn == null) {
statusBar.setFirstText(language.getText("msg21"), 2000);
return;
}
getUndoManager().undoableEdit("Unlink", new Runnable() {
public void run() {
for (int i = 0; i < cdmtn.length; i++) {
if (cdmtn[i] != null && !cdmtn[i].isRoot()) {
GanttTask t = (GanttTask) (cdmtn[i].getUserObject());
t.unlink();
}
// setQuickSave (true);
}
}
});
area.repaint();
setAskForSave(true);
/*
* JFileChooser fc = new JFileChooser(options.getWorkingDir());
* FileFilter ganttFilter = new GanttXMLFileFilter();
* fc.addChoosableFileFilter(ganttFilter); InputStream inputStream =
* null; int returnVal = fc.showOpenDialog(GanttProject.this); if
* (returnVal == JFileChooser.APPROVE_OPTION) { final JFileChooser jfc =
* fc; try { Document document = new FileDocument (new File
* (jfc.getSelectedFile().getAbsolutePath())); inputStream =
* document.getInputStream(); //System.out.println (inputStream.read()); }
* catch (IOException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } }
*/
}
/** Link the selected Tasks */
public void linkRelationships() {
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
final DefaultMutableTreeNode[] cdmtn = tree.getSelectedTaskNodes();
if (cdmtn == null) {
203
statusBar.setFirstText(language.getText("msg21"), 2000);
return;
}
if (cdmtn.length < 2) {
statusBar.setFirstText(language.getText("msg22"), 2000);
return;
}
getUndoManager().undoableEdit("Link", new Runnable() {
public void run() {
for (int i = 0; i < cdmtn.length - 1; i++) {
if (cdmtn[i] != null && cdmtn[i + 1] != null) {
GanttTask firstTask = (GanttTask) (cdmtn[i]
.getUserObject());
;
GanttTask secondTask = (GanttTask) (cdmtn[i + 1]
.getUserObject());
try {
getTaskManager().getDependencyCollection()
.createDependency(secondTask, firstTask,
new FinishStartConstraintImpl());
} catch (TaskDependencyException e1) {
// e1.printStackTrace(); //To change body of catch
// statement use File | Settings | File Templates.
}
}
}
}
});
// setQuickSave (true);
area.repaint();
setAskForSave(true);
}
/** Export the calendar on a png file */
public void export() {
ExportFileInfo info = selectExportFile(null);
if (!info.equals(ExportFileInfo.EMPTY)) {
doExport(info);
}
}
private void doExport(ExportFileInfo info) {
Chart resourcesChart = (Chart) getResourcePanel().area;
Chart ganttChart = (Chart) getArea();
Chart visibleChart = (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) ? resourcesChart
: ganttChart;
ExportFileWizardImpl wizard = new ExportFileWizardImpl(info,
getUIFacade(), (IGanttProject) this, ganttChart,
resourcesChart, visibleChart, options);
wizard.doExport();
}
/** Execute the export functions. */
/** Refresh the informations of the project on the status bar. */
public void refreshProjectInfos() {
if (tree.nbTasks == 0 && resp.nbPeople() == 0)
statusBar.setSecondText("");
else
statusBar.setSecondText(correctLabel(language.getText("task"))
+ " : " + tree.nbTasks + " "
+ correctLabel(language.getText("resources")) + " : "
+ resp.nbPeople());
}
private ExportFileInfo selectExportFile(FileFilter currentFilter) {
ExportFileInfo result = ExportFileInfo.EMPTY;
FileFilter figFilter = new GanttXFIGFileFilter();
FileFilter pngFilter = new GanttPNGFileFilter();
FileFilter jpgFilter = new GanttJPGFileFilter();
FileFilter csvFilter = new GanttCSVFilter();
FileFilter pdfFilter = new GanttPDFFileFilter();
FileFilter htmlFilter = new GanttHTMLFileFilter();
FileFilter msprojectFilter = new GanttMSProjectLFileFilter();
JFileChooser fc = new JFileChooser(options.getWorkingDir());
fc.addChoosableFileFilter(figFilter);
fc.addChoosableFileFilter(msprojectFilter);
fc.addChoosableFileFilter(pngFilter);
fc.addChoosableFileFilter(jpgFilter);
204
fc.addChoosableFileFilter(csvFilter);
fc.addChoosableFileFilter(pdfFilter);
fc.addChoosableFileFilter(htmlFilter);
if (currentFilter != null)
fc.setFileFilter(currentFilter);
// Remove the possibility to use a file filter for all files
FileFilter[] filefilters = fc.getChoosableFileFilters();
for (int i = 0; i < filefilters.length; i++) {
if (filefilters[i] != figFilter && filefilters[i] != pngFilter
&& filefilters[i] != jpgFilter
&& filefilters[i] != csvFilter
&& filefilters[i] != pdfFilter
&& filefilters[i] != htmlFilter
&& filefilters[i] != msprojectFilter)
fc.removeChoosableFileFilter(filefilters[i]);
}
int returnVal = fc.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().toString();
FileFilter selectedFilter = fc.getFileFilter();
// if( the file exists, ask for overwriting
if (new File(filename).exists()) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.WARNING, GanttDialogInfo.YES_NO_OPTION,
filename + "\n" + language.getText("msg18"), language
.getText("warning"));
gdi.show();
if (gdi.res == GanttDialogInfo.NO)
return selectExportFile(selectedFilter);
}
int type = -1;
if (selectedFilter.equals(htmlFilter)) {
type = ExportFileInfo.FORMAT_HTML;
if (!fc.getFileFilter().accept(new File(filename))) {
filename += ".html";
}
} else if (selectedFilter.equals(pngFilter)) {
type = ExportFileInfo.FORMAT_PNG;
} else if (selectedFilter.equals(jpgFilter)) {
type = ExportFileInfo.FORMAT_JPG;
} else if (selectedFilter.equals(pdfFilter)) {
type = ExportFileInfo.FORMAT_PDF;
} else if (selectedFilter.equals(figFilter)) {
type = ExportFileInfo.FORMAT_XFIG;
} else if (selectedFilter.equals(csvFilter)) {
type = ExportFileInfo.FORMAT_CSV;
} else if (selectedFilter.equals(msprojectFilter)) {
type = ExportFileInfo.FORMAT_MSPROJECT;
} else {
statusBar.setFirstText(
"Unknown file filter has been selected : "
+ selectedFilter, 2000);
throw new RuntimeException(
"Unknown file filter has been selected: "
+ selectedFilter);
}
changeWorkingDirectory(new File(filename).getParent());
File file = new File(filename);
result = new ExportFileInfo(file, type, options.getExportSettings());
}
return result;
}
/** Print the project */
public void printProject() {
Object selectedUserObject = getTabs().getSelectedUserObject();
if (selectedUserObject instanceof Chart)
PrintManager.printChart((Chart) selectedUserObject, options
.getExportSettings());
else
System.err.println("not printable");
// if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// // Chart
// GanttExportSettings bool = new GanttExportSettings();
205
// // GanttDialogExport gde = new GanttDialogExport(this, bool,
// // language);
// // gde.show();
// // if (bool.ok)
// // area.printProject(bool.name, bool.percent, bool.depend);
// GanttExportSettings ges = options.getExportSettings();
// // ges.setStartDate(area.getChartModel().getStartDate());
// // ges.setEndDate(area.getChartModel().getEndDate());
// ges.setStartDate(area.getStartDate());
// ges.setEndDate(area.getEndDate());
// area.printProject(ges);
//
// // try
// // {
// // ((GanttTree2)getTree()).getTreeTable().print();
// // }
// // catch (PrinterException e)
// // {
// // // TODO Auto-generated catch block
// // e.printStackTrace();
// // }
//
// } else if (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX)
// {// Resources
// // Chart
// getResourcePanel().area.printProject(options.getExportSettings());
// } else {
// Component comp = getTabs().getSelectedComponent();
//
// Chart chart = (Chart)comp;
// PrintManager.printChart(chart, options.getExportSettings());
// }
}
/** Preview the project before print */
// public void previewPrint() {
// GanttPreviewPrint preview = null;
// if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {// Gantt
// // Chart
// preview = new GanttPreviewPrint(this, area, area.getChartModel()
// .getStartDate(), area.getChartModel().getEndDate());
// } else if (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) {//
// Resources
// // Chart
// preview = new GanttPreviewPrint(this, getResourcePanel().area,
// getResourcePanel().area.getChartModel().getStartDate(),
// getResourcePanel().area.getChartModel().getEndDate());
// }
// if (preview != null)
// preview.setVisible(true);
// }
public void previewPrint() {
Date startDate, endDate;
Object selectedUserObject = getTabs().getSelectedUserObject();
Chart chart = null;
if (selectedUserObject instanceof Chart)
chart = (Chart) selectedUserObject;
else {
System.err.println("not printable");
return;
}
try {
startDate = chart.getStartDate();
endDate = chart.getEndDate();
} catch (UnsupportedOperationException e) {
startDate = null;
endDate = null;
}
PrintPreview preview = null;
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {
startDate = area.getChartModel().getStartDate();
endDate = area.getChartModel().getEndDate();
} else if (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) {
startDate = getResourcePanel().area.getChartModel().getStartDate();
endDate = getResourcePanel().area.getChartModel().getEndDate();
}
preview = new PrintPreview(this, chart, correctLabel(language
.getText("preview")), startDate, endDate);
if (preview != null)
preview.setVisible(true);
206
}
/** Create a new project */
public void newProject() {
getUndoManager().undoableEdit("Init new Project", new Runnable() {
public void run() {
if (checkCurrentProject()) {
closeProject(true);
statusBar.setFirstText(language.getText("newProject2"),
1500);
refreshProjectInfos();
}
}
});
prjInfos = new PrjInfos();
showNewProjectWizard();
}
private void showNewProjectWizard() {
NewProjectWizard wizard = new NewProjectWizard();
wizard.createNewProject(this, getUIFacade());
}
/**
* Closes a project. Make sure you have already called checkCurrentProject()
* before.
*
* @see #checkCurrentProject()
*/
public void closeProject(boolean discardUndoEdits) {
// Clear the jtree
// refresh graphic area
area.repaint();
area.setProjectLevelTaskColor(null);
getResourcePanel().area.repaint();
// reset people
getResourcePanel().reset();
// getHumanResourceManager().clear();
prjInfos = new PrjInfos();
// GanttTask.resetMaxID();
RoleManager.Access.getInstance().clear();
if (null != projectDocument)
projectDocument.releaseLock();
projectDocument = null;
// change title of the frame
if (!isOnlyViewer)
this.setTitle(language.getText("appliTitle"));
else
this.setTitle("GanttViewer");
setAskForSave(false);
getTaskManager().clear();
tree.clearTree();
tree.getTreeTable().initTreeTable();
Mediator.getCustomColumnsStorage().reset();
// getZoomManager().clear();
if (discardUndoEdits)
getUndoManager().die();
for (int i = 0; i < myPreviousStates.size(); i++)
((GanttPreviousState) myPreviousStates.get(i)).remove();
myPreviousStates = new ArrayList();
bSaveCurrent.setEnabled(false);
bComparePrev.setEnabled(false);
area.setPreviousStateTasks(null);
Chart[] charts = Mediator.getPluginManager().getCharts();
for (int i = 0; i < charts.length; i++)
charts[i].reset();
}
/** Open a local project file with dialog box (JFileChooser) */
public void openFile() throws IOException {
// Create a filechooser
JFileChooser fc = new JFileChooser(options.getWorkingDir());
FileFilter ganttFilter = new GanttXMLFileFilter();
fc.addChoosableFileFilter(ganttFilter);
// Remove the possibility to use a file filter for all files
FileFilter[] filefilters = fc.getChoosableFileFilters();
for (int i = 0; i < filefilters.length; i++) {
if (filefilters[i] != ganttFilter)
fc.removeChoosableFileFilter(filefilters[i]);
}
207
int returnVal = fc.showOpenDialog(GanttProject.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final JFileChooser jfc = fc;
getUndoManager().undoableEdit("OpenFile", new Runnable() {
public void run() {
try {
openDocument(getDocumentManager().getDocument(
jfc.getSelectedFile().getAbsolutePath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
changeWorkingDirectory(jfc.getSelectedFile().getParent());
}
});
// changeUndoNumber ();
}
}
/** Open a remote project file with dialog box (GanttURLChooser) */
public void openURL() {
openURL(projectDocument);
}
/** Open a remote project file with dialog box (GanttURLChooser) */
public void openURL(Document lastDocument) {
GanttURLChooser uc = new GanttURLChooser(this, true,
(null != lastDocument) ? lastDocument.getURLPath() : null,
(null != lastDocument) ? lastDocument.getUsername() : null,
(null != lastDocument) ? lastDocument.getPassword() : null);
uc.show();
if (uc.change) {
Document openDoc;
if ((lastDocument instanceof AbstractURLDocument)
&& uc.fileurl.equals(lastDocument.getURLPath())) {
lastDocument.setUserInfo(uc.userName, uc.password);
openDoc = lastDocument;
} else {
openDoc = DocumentCreator.createDocument(uc.fileurl,
uc.userName, uc.password);
}
try {
openDocument(openDoc);
} catch (IOException e) {
if (isVisible()) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION,
language.getText("msg11"), language
.getText("error"));
gdi.show();
} else
System.out.println("\n====" + language.getText("error")
+ "====\n" + language.getText("msg11") + "\n");
openURL(openDoc);
}
}
}
private void openDocument(Document document) throws IOException {
if (document.getDescription().endsWith(".xml")
|| document.getDescription().endsWith(".gan")) {
InputStream inputStream = document.getInputStream();
closeProject(true);
boolean locked = document.acquireLock();
if (!locked) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.WARNING, GanttDialogInfo.YES_NO_OPTION,
language.getText("msg13"), language.getText("warning"));
gdi.show();
if (gdi.res == GanttDialogInfo.NO)
208
return;
}
GanttXMLOpen opener = new GanttXMLOpen(prjInfos, area,
getTaskManager(), getUIFacade());
ResourceManager hrManager = getHumanResourceManager();
RoleManager roleManager = getRoleManager();
TaskManager taskManager = getTaskManager();
ResourceTagHandler resourceHandler = new ResourceTagHandler(
hrManager, roleManager);
DependencyTagHandler dependencyHandler = new DependencyTagHandler(
opener.getContext(), taskManager);
//LH
CostTagHandler costHandler = new CostTagHandler(
opener.getContext(), taskManager);
AllocationTagHandler allocationHandler = new AllocationTagHandler(
hrManager, taskManager, roleManager);
VacationTagHandler vacationHandler = new VacationTagHandler(
hrManager);
RoleTagHandler rolesHandler = new RoleTagHandler(roleManager);
TaskTagHandler taskHandler = new TaskTagHandler(taskManager, opener
.getContext());
BlankLineTagHandler blankLineHandler = new BlankLineTagHandler(tree);
TaskPropertiesTagHandler taskPropHandler = new TaskPropertiesTagHandler(
this.tree.getTreeTable());
opener.addTagHandler(taskPropHandler);
PreviousStateTasksTagHandler previousStateHandler = new PreviousStateTasksTagHandler(
this.getPreviouStates());
DefaultWeekTagHandler weekHandler = new DefaultWeekTagHandler(
getActiveCalendar());
CustomPropertiesTagHandler customPropHandler = new CustomPropertiesTagHandler(
opener.getContext(), taskManager);
opener.addTagHandler(customPropHandler);
TaskDisplayColumnsTagHandler taskDisplayHandler = new TaskDisplayColumnsTagHandler(
this.tree.getTreeTable());
opener.addTagHandler(taskDisplayHandler);
ViewTagHandler viewHandler = new ViewTagHandler(getUIFacade());
HolidayTagHandler holidayHandler = new HolidayTagHandler(this);
opener.addParsingListener(taskDisplayHandler);
opener.addParsingListener(customPropHandler);
opener.addTagHandler(weekHandler);
opener.addTagHandler(previousStateHandler);
opener.addTagHandler(viewHandler);
opener.addTagHandler(holidayHandler);
opener.addParsingListener(holidayHandler);
opener.addParsingListener(taskPropHandler);
opener.addTagHandler(taskHandler);
opener.addTagHandler(blankLineHandler);
opener.addTagHandler(opener.getDefaultTagHandler());
opener.addTagHandler(resourceHandler);
//LH
opener.addTagHandler(costHandler);
opener.addTagHandler(dependencyHandler);
opener.addTagHandler(allocationHandler);
opener.addParsingListener(allocationHandler);
opener.addTagHandler(vacationHandler);
opener.addTagHandler(rolesHandler);
//LH
opener.addParsingListener(costHandler);
opener.addParsingListener(dependencyHandler);
opener.addParsingListener(resourceHandler);
if (opener.load(document.getInputStream())) {
// Add this project to the last opened project
if (documentsMRU.add(document))
updateMenuMRU();
if (locked) {
projectDocument = document;
209
if (!isOnlyViewer)
this.setTitle(language.getText("appliTitle") + " ["
+ document.getDescription() + "]");
else
this.setTitle("GanttViewer ["
+ document.getDescription() + "]");
}
setAskForSave(false);
statusBar.setFirstText(language.getText("opening") + " "
+ document.getPath(), 2000);
if (myPreviousStates.size() != 0)
bComparePrev.setEnabled(true);
}
} else {
if (isVisible()) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION,
language.getText("msg2") + "\n"
+ document.getDescription(), language
.getText("error"));
gdi.show();
} else {
System.out.println("\n====" + language.getText("error")
+ "====\n" + language.getText("msg2") + "\n");
}
}
Chart[] charts = Mediator.getPluginManager().getCharts();
for (int i = 0; i < charts.length; i++) {
charts[i].setTaskManager(myTaskManager);
charts[i].reset();
}
getResourcePanel().reloadRoles();
// myDelayManager.fireDelayObservation(); // it is done in repaint2
addMouseListenerToAllContainer(this.getComponents());
getTaskManager().processCriticalPath((TaskNode) tree.getRoot());
ArrayList projectTasks = tree.getProjectTasks();
if (projectTasks.size() != 0)
for (int i = 0; i < projectTasks.size(); i++)
getTaskManager().processCriticalPath(
(TaskNode) projectTasks.get(i));
repaint2();
}
public void openStartupDocument(String path) {
if (path != null) {
Document document = DocumentCreator.createDocument(path);
openStartupDocument(document);
}
}
public void openStartupDocument(Document document) {
try {
openDocument(document);
} catch (IOException ex) {
if (document instanceof AbstractURLDocument) {
// if there are problems opening an AbstractURLDocument
// (possibly because of bad authentication),
// give the user a chance, to enter correct credentials
openURL(document);
} else {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION,
language.getText("msg2") + "\n"
+ document.getDescription(), language
.getText("error"));
gdi.show();
}
}
}
/**
* Open a XML stream that represent the file //By CL !@#
*
* @param ins
210
*/
public void openXMLStream(InputStream ins, String path) {
try {
tree.clearTree();
getResourcePanel().reset();
// getHumanResourceManager().clear();
// GanttTask.resetMaxID();
getTaskManager().clear();
RoleManager.Access.getInstance().clear();
GanttXMLOpen opener = new GanttXMLOpen(prjInfos, area,
getTaskManager(), getUIFacade());
ResourceManager hrManager = getHumanResourceManager();
RoleManager roleManager = getRoleManager();
ResourceTagHandler resourceHandler = new ResourceTagHandler(
hrManager, roleManager);
DependencyTagHandler dependencyHandler = new DependencyTagHandler(
opener.getContext(), getTaskManager());
//LH
CostTagHandler costHandler = new CostTagHandler(
opener.getContext(), getTaskManager());
AllocationTagHandler allocationHandler = new AllocationTagHandler(
hrManager, getTaskManager(), getRoleManager());
VacationTagHandler vacationHandler = new VacationTagHandler(
hrManager);
TaskTagHandler taskHandler = new TaskTagHandler(getTaskManager(),
opener.getContext());
BlankLineTagHandler blankLineHandler = new BlankLineTagHandler(tree);
TaskPropertiesTagHandler taskPropHandler = new TaskPropertiesTagHandler(
this.tree.getTreeTable());
opener.addTagHandler(taskPropHandler);
CustomPropertiesTagHandler customPropHandler = new CustomPropertiesTagHandler(
opener.getContext(), getTaskManager());
opener.addTagHandler(customPropHandler);
TaskDisplayColumnsTagHandler taskDisplayHandler = new TaskDisplayColumnsTagHandler(
this.tree.getTreeTable());
opener.addTagHandler(taskDisplayHandler);
HolidayTagHandler holidayHandler = new HolidayTagHandler(this);
opener.addTagHandler(holidayHandler);
opener.addParsingListener(holidayHandler);
opener.addTagHandler(taskHandler);
opener.addTagHandler(blankLineHandler);
opener.addParsingListener(taskPropHandler);
opener.addParsingListener(taskDisplayHandler);
opener.addParsingListener(customPropHandler);
opener.addTagHandler(opener.getDefaultTagHandler());
opener.addTagHandler(resourceHandler);
opener.addTagHandler(dependencyHandler);
//LH
opener.addTagHandler(costHandler);
opener.addTagHandler(allocationHandler);
opener.addParsingListener(allocationHandler);
opener.addTagHandler(vacationHandler);
opener.addParsingListener(dependencyHandler);
//LH
opener.addParsingListener(costHandler);
opener.load(ins);
// addProjectFileToLastOpen(projectfile);
} catch (Exception ex) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language
.getText("msg2")
+ "\n" + path, language.getText("error"));
gdi.show();
}
setAskForSave(false);
}
/** Save the project as (with a dialog file chooser) */
public boolean saveAsProject() throws IOException {
tree.displayHiddenTasks();
JFileChooser fc = new JFileChooser(options.getWorkingDir());
FileFilter ganttFilter = new GanttXMLFileFilter();
fc.addChoosableFileFilter(ganttFilter);
// Remove the possibility to use a file filter for all files
FileFilter[] filefilters = fc.getChoosableFileFilters();
for (int i = 0; i < filefilters.length; i++) {
if (filefilters[i] != ganttFilter)
fc.removeChoosableFileFilter(filefilters[i]);
211
}
int returnVal = fc.showSaveDialog(GanttProject.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
String projectfile = fc.getSelectedFile().toString();
if (!fc.getFileFilter().accept(new File(projectfile))) {
if (fc.getFileFilter().accept(new File(projectfile + ".gan"))) {
projectfile += ".gan";
}
}
// if( the file exists, ask for overwriting
if (new File(projectfile).exists()) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.WARNING, GanttDialogInfo.YES_NO_OPTION,
projectfile + "\n" + language.getText("msg18"),
language.getText("warning"));
gdi.show();
if (gdi.res == GanttDialogInfo.NO)
saveAsProject();
}
saveProject(new FileDocument(new File(projectfile)));
return true;
}
return false;
}
/** Save the project on a server (with a GanttURLChooser) */
public boolean saveAsURLProject() throws IOException {
return saveAsURLProject(projectDocument);
}
/** Save the project on a server (with a GanttURLChooser) */
public boolean saveAsURLProject(Document document) throws IOException {
GanttURLChooser uc = new GanttURLChooser(this, false,
(null != document) ? document.getURLPath() : null,
(null != document) ? document.getUsername() : null,
(null != document) ? document.getPassword() : null);
uc.show();
if (uc.change) {
Document saveDocument = null;
if (null != document)
if (uc.fileurl.equals(document.getURLPath())
&& uc.userName.equals(document.getUsername())
&& uc.password.equals(document.getPassword()))
saveDocument = document;
if (null == saveDocument)
saveDocument = DocumentCreator.createDocument(uc.fileurl,
uc.userName, uc.password);
saveProject(saveDocument);
return true;
}
return false;
/*
* ServerDialog sd = new ServerDialog(this); sd.show(); return false;
*/
}
/** Save the project on a file */
public void saveProject() throws IOException {
tree.displayHiddenTasks();
saveProject(projectDocument);
}
/** Save the project to the given document, if possible */
public void saveProject(Document document) throws IOException {
if (null == document) {
saveAsProject();
return;
}
if (!document.canWrite()) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language
.getText("msg10"), language.getText("error"));
gdi.show();
if (document instanceof AbstractURLDocument) {
saveAsURLProject(document);
} else {
saveAsProject();
212
}
return;
}
if (!document.acquireLock()) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language
.getText("msg14"), language.getText("error"));
gdi.show();
if (document instanceof AbstractURLDocument) {
saveAsURLProject(document);
} else {
saveAsProject();
}
return;
}
if (document.getDescription().endsWith(".xml")
|| document.getDescription().endsWith(".gan")) {
GanttXMLSaver saver = new GanttXMLSaver((IGanttProject) this, tree,
getResourcePanel(), area, (UIFacade) this);
saver.save(document.getOutputStream(), version);
statusBar.setFirstText(GanttLanguage.getInstance()
.getText("saving")
+ " " + document.getPath(), 2000);
// Add this project to the last opened projects
if (documentsMRU.add(document))
updateMenuMRU();
if (projectDocument != document) {
if (projectDocument != null)
projectDocument.releaseLock();
projectDocument = document;
}
}
// change title of the window
if (!isOnlyViewer)
this.setTitle(language.getText("appliTitle") + " ["
+ document.getDescription() + "]");
else
this.setTitle("GanttViewer [" + document.getDescription() + "]");
String filepath = document.getFilePath();
if (null != filepath) {
changeWorkingDirectory(new File(filepath).getParent());
}
setAskForSave(false);
}
public void changeWorkingDirectory(String newWorkDir) {
if (null != newWorkDir)
options.setWorkingDirectory(newWorkDir);
}
/** @return the uiconfiguration. */
public UIConfiguration getUIConfiguration() {
return myUIConfiguration;
}
/** Function that launch the dialog to edit project properties */
/*
* public void editSettings() { GanttDialogSettings ds = new
* GanttDialogSettings(this, language); ds.show(); if (ds.change) {
* setAskForSave(ds.change); } }
*/
/** Quit the application */
public void quitApplication() {
options.setWindowPosition(getX(), getY());
options.setWindowSize(getWidth(), getHeight());
options.setUIConfiguration(myUIConfiguration);
options.setDocumentsMRU(documentsMRU);
options.setLookAndFeel(lookAndFeel);
options.setToolBarPosition(toolBar.getOrientation());
options.save();
if (checkCurrentProject()) {
closeProject(true);
setVisible(false);
dispose();
System.exit(0);
} else {
setVisible(true);
}
}
/** Open the web page */
public void openWebPage() throws IOException {
if (!BrowserControl.displayURL("http://ganttproject.org/")) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
213
GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language
.getText("msg4"), language.getText("error"));
gdi.show();
return;
}
statusBar.setFirstText(GanttLanguage.getInstance().getText("opening")
+ " www.ganttproject.org", 2000);
}
// change by G. Herrmann
public void setAskForSave(boolean afs) {
if (isOnlyViewer)
return;
String title = getTitle();
// String last = title.substring(title.length() - 11, title.length());
bSave.setEnabled(afs);
miSave.setEnabled(afs);
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX) {
if (afs)
bSaveCurrent.setEnabled(afs);
if (myPreviousStates.size() != 0)
bComparePrev.setEnabled(true);
}
askForSave = afs;
try {
if (System.getProperty("mrj.version") != null) {
rootPane.putClientProperty("windowModified", Boolean
.valueOf(afs));
// see http://developer.apple.com/qa/qa2001/qa1146.html
} else {
if (askForSave) {
/*
* if (!last.equals(" (modified)")) { setTitle(getTitle() + "
* (modified)"); }
*/
if (!title.endsWith(" *")) {
setTitle(getTitle() + " *");
}
}
}
} catch (AccessControlException e) {
// This can happen when running in a sandbox (Java WebStart)
System.err.println(e + ": " + e.getMessage());
}
}
/** Print the help for ganttproject on the system.out */
private static void usage() {
System.out.println();
System.out
.println("GanttProject usage : java -jar ganttproject-(VERSION).jar <OPTIONS>");
System.out.println();
System.out.println(" Here are the possible options:");
System.out.println(" -h, --help : Print this message");
System.out
.println(" [project_file_name] a XML file based on ganttproject format to directly open (project.xml or project.gan)");
System.out
.println(" -html [project_file_name] [export_directory_name], export directly a ganttproject file to web pages");
System.out
.println(" -xsl-dir [xsl_directory] localisation of the xsl directory for html export");
System.out
.println(" -pdf [project_file_name] [pdf_file_name], export directly a ganttproject file to web pages");
System.out
.println(" -xsl-fo [xsl_fo_file] localisation of the xsl-fo file for pdf export");
System.out
.println(" -csv [project_file_name] [csv_image_filename], export directly a ganttproject file to csv document compatible with spreadsheets");
System.out
.println(" -png [project_file_name] [png_image_filename], export directly a ganttproject file to png image");
System.out
.println(" -jpg [project_file_name] [jpg_image_filename], export directly a ganttproject file to jpg image");
System.out
.println(" -fig/-xfig [project_file_name] [fig_image_filename], export directly a ganttproject file to xfig image");
System.out.println();
System.out
214
.println(" In all these cases the project_file_name can either be a file on local disk or an URL.");
System.out
.println(" If the URL is password-protected, you can give credentials this way:");
System.out
.println(" http://username:[email protected]/filename");
System.out.println(" ");
}
public GanttResourcePanel getResourcePanel() {
if (this.resp == null) {
this.resp = new GanttResourcePanel(this, getTree());
this.resp.setResourceActions(getResourceActions()); // TODO pass
// resource
// actions
// created with
// resource
// panel as
// context
getHumanResourceManager().addView(this.resp);
}
return this.resp;
}
public GanttLanguage getLanguage() {
return this.language;
}
public GanttGraphicArea getArea() {
return this.area;
}
public GanttTree2 getTree() {
return this.tree;
}
public Action getCopyAction() {
return myCopyAction;
}
public Action getCutAction() {
return myCutAction;
}
public Action getPasteAction() {
return myPasteAction;
}
private ResourceActionSet getResourceActions() {
if (myResourceActions == null) {
myResourceActions = new ResourceActionSet((IGanttProject) this,
(ResourceContext) getResourcePanel(), this);
}
return myResourceActions;
}
/** The main */
public static void main(String[] arg) {
// // ------------------------------------------------------------
// List result = new ArrayList();
// String extensionPointID = "net.sourceforge.ganttproject.chart";
// IConfigurationElement[] configElements = Platform
// .getExtensionRegistry().getConfigurationElementsFor(
// extensionPointID);
// for (int i = 0; i < configElements.length; i++) {
// try {
// Object test = configElements[i]
// .createExecutableExtension("class");
// result.add(test);
// } catch (CoreException e) {
// e.printStackTrace();
// // throw new RuntimeException("Failed to instantiate chart", e);
// }
// }
//
// // ------------------------------------------------------------
if (arg.length > 0 && ("-h".equals(arg[0]) || "--help".equals(arg[0]))) {
// Help for the command line
usage();
System.exit(0);
}
/*
* If -xsl-dir with directory has been provided, use the xsls in this
* dir instead of the ones from .ganttproject Can be used in both
* interacive and -html/-export modes From Pawel Lipinski. And set the
215
* new path as default.
*/
GanttOptions options = new GanttOptions(null, false);
for (int i = 0; i < arg.length; i++) {
if (arg[i].equals("-xsl-dir") && (arg.length > i + 1)) {
options.setXslDir(arg[i + 1]);
break;
}
}
for (int i = 0; i < arg.length; i++) {
if (arg[i].equals("-xsl-fo") && (arg.length > i + 1)) {
options.setXslFo(arg[i + 1]);
break;
}
}
if (arg.length > 0
&& ("-html".equals(arg[0]) || "-htm".equals(arg[0]) || "-export"
.equals(arg[0]))) {
if (checkProjectFile(arg))
exportProject(arg);
System.exit(0);
} else if (arg.length > 0 && "-pdf".equals(arg[0])) {
if (checkProjectFile(arg))
exportPDF(arg);
System.exit(0);
} else if (arg.length > 0 && "-png".equals(arg[0])) {
if (checkProjectFile(arg))
exportPNG(arg);
System.exit(0);
} else if (arg.length > 0 && "-jpg".equals(arg[0])) {
if (checkProjectFile(arg))
exportJPG(arg);
System.exit(0);
} else if (arg.length > 0
&& ("-fig".equals(arg[0]) || "-xfig".equals(arg[0]))) {
if (checkProjectFile(arg))
exportXFIG(arg);
System.exit(0);
} else if (arg.length > 0 && ("-csv".equals(arg[0]))) {
if (checkProjectFile(arg))
exportCSV(arg);
System.exit(0);
}
/* Splash image */
GanttSplash splash = new GanttSplash();
splash.setVisible(true);
/** Create main frame */
GanttProject ganttFrame = new GanttProject(false, null);
ganttFrame.setVisible(true);
if (arg.length > 0) {
// todo [bbaranne] remove this hack!!!
if (!arg[0].equals("ganttproject-eclipsito-config.xml")
&& !arg[0].equals("-pdelaunch"))
ganttFrame.openStartupDocument(arg[0]);
} else {
// ganttFrame.showNewProjectWizard();
}
splash.close();
}
static boolean checkProjectFile(String[] arg) {
if (!(arg.length > 1)) {
System.out.println("ERROR...\nMust pass a project file");
return false;
}
return true;
}
/**
* Possibility to export the project into HTML directly by command Line From
* Dmitry Barashev
*/
private static void exportProject(String[] args) {
try {
byCommandLine = true;
GanttProject project = new GanttProject(false, args[1]);
String exportPath;
if (args.length > 2)
exportPath = args[2];
else
exportPath = "htmlExport";
File targetDir = new File(exportPath);
if (!targetDir.exists()) {
targetDir.mkdir();
} else {
if (!targetDir.isDirectory()) {
216
throw new RuntimeException("File " + args[2]
+ " must be directory");
}
}
System.out.println(targetDir.getAbsolutePath());
String index = project.getProjectName();
if (index == null || index.length() == 0) {
index = new String("ganttproject");
} else {
index = project.getProjectName().toLowerCase();
}
File targetFile = new File(targetDir, index + ".html");
System.err.println(targetFile.getAbsolutePath());
if (!targetFile.exists()) {
targetFile.createNewFile();
}
ExportFileInfo info = new ExportFileInfo(targetFile,
ExportFileInfo.FORMAT_HTML, new GanttExportSettings());
project.doExport(info);
} catch (IOException e) {
throw new RuntimeException("IO error", e);
}
}
/** Possibility to export the project into PDF directly by command Line */
private static void exportPDF(String[] args) {
byCommandLine = true;
GanttProject project = new GanttProject(false, args[1]);
String exportFile;
if (args.length > 2)
exportFile = args[2];
else
exportFile = "ganttproject.pdf";
File targetFile = new File(exportFile);
ExportFileInfo info = new ExportFileInfo(targetFile,
ExportFileInfo.FORMAT_PDF, new GanttExportSettings());
project.doExport(info);
}
/** Export directly in PNG image */
private static void exportPNG(String[] args) {
byCommandLine = true;
GanttProject project = new GanttProject(false, args[1]);
File targetFile = null;
if (args.length > 2)
targetFile = new File(args[2]);
ExportFileInfo info = new ExportFileInfo(targetFile,
ExportFileInfo.FORMAT_PNG, new GanttExportSettings());
project.doExport(info);
}
/** Export directly in XFIG image */
private static void exportXFIG(String[] args) {
byCommandLine = true;
GanttProject project = new GanttProject(false, args[1]);
File targetFile = null;
if (args.length > 2)
targetFile = new File(args[2]);
ExportFileInfo info = new ExportFileInfo(targetFile,
ExportFileInfo.FORMAT_XFIG, new GanttExportSettings());
project.doExport(info);
}
/** Export directly in CSV image */
private static void exportCSV(String[] args) {
byCommandLine = true;
GanttProject project = new GanttProject(false, args[1]);
File targetFile = null;
if (args.length > 2)
targetFile = new File(args[2]);
ExportFileInfo info = new ExportFileInfo(targetFile,
ExportFileInfo.FORMAT_CSV, new GanttExportSettings());
project.doExport(info);
}
/** Export directly in JPG image */
private static void exportJPG(String[] args) {
byCommandLine = true;
GanttProject project = new GanttProject(false, args[1]);
File targetFile = null;
if (args.length > 2)
targetFile = new File(args[2]);
ExportFileInfo info = new ExportFileInfo(targetFile,
ExportFileInfo.FORMAT_JPG, new GanttExportSettings());
project.doExport(info);
}
217
/**
* The class able to export directly by command line From Dmitry Barashev
*/
public static class ExportFileInfo {
public final File myFile;
public final int myFormat;
public final GanttExportSettings myStorageOptions;
public static final int FORMAT_HTML = 1;
public static final int FORMAT_PNG = 2;
public static final int FORMAT_JPG = 3;
public static final int FORMAT_PDF = 4;
public static final int FORMAT_XFIG = 5;
public static final int FORMAT_CSV = 6;
public static final int FORMAT_MSPROJECT = 7;
public static final ExportFileInfo EMPTY = new ExportFileInfo(null, -1,
null);
public ExportFileInfo(File file, int format, GanttExportSettings options) {
myFile = file;
myFormat = format;
myStorageOptions = options;
}
}
public static final String HUMAN_RESOURCE_MANAGER_ID = "HUMAN_RESOURCE";
// change
// to
// public
public static final String ROLE_MANAGER_ID = "ROLE_MANAGER";
private GPCalendar myFakeCalendar = new WeekendCalendarImpl();
private final ZoomManager myZoomManager;
// private GPCalendar myFakeCalendar = new AlwaysWorkingTimeCalendarImpl();
private final TimeUnitStack myTimeUnitStack;
private ScrollingManager myScrollingManager;
private DocumentManager myDocumentManager;
private ParserFactory myParserFactory;
private GPUndoManager myUndoManager;
private static WindowListener ourWindowListener;
// ///////////////////////////////////////////////////////
// IGanttProject implementation
public String getProjectName() {
return prjInfos._sProjectName;
}
public void setProjectName(String projectName) {
prjInfos._sProjectName = projectName;
setAskForSave(true);
}
public String getDescription() {
return prjInfos.getDescription();
}
public void setDescription(String description) {
prjInfos._sDescription = description;
setAskForSave(true);
}
public String getOrganization() {
return prjInfos.getOrganization();
}
public void setOrganization(String organization) {
prjInfos._sOrganization = organization;
setAskForSave(true);
}
218
public String getWebLink() {
return prjInfos.getWebLink();
}
public void setWebLink(String webLink) {
prjInfos._sWebLink = webLink;
setAskForSave(true);
}
public ResourceManager getHumanResourceManager() {
ResourceManager result = (ResourceManager) managerHash
.get(HUMAN_RESOURCE_MANAGER_ID);
if (result == null) {
result = new HumanResourceManager(getRoleManager().getDefaultRole());
// result.addView(getPeople());
managerHash.put(HUMAN_RESOURCE_MANAGER_ID, result);
result.addView(this);
}
return result;
}
public TaskManager getTaskManager() {
return myTaskManager;
}
public RoleManager getRoleManager() {
RoleManager result = (RoleManager) managerHash.get(ROLE_MANAGER_ID);
if (result == null) {
result = RoleManager.Access.getInstance();
managerHash.put(ROLE_MANAGER_ID, result);
}
return result;
}
public Document getDocument() {
return projectDocument;
}
public ZoomManager getZoomManager() {
return myZoomManager;
}
public TimeUnitStack getTimeUnitStack() {
return myTimeUnitStack;
}
public GanttLanguage getI18n() {
return getLanguage();
}
public GPCalendar getActiveCalendar() {
return myFakeCalendar;
}
public void setModified() {
setAskForSave(true);
}
public void close() {
closeProject(false);
}
private DocumentManager getDocumentManager() {
if (myDocumentManager == null) {
myDocumentManager = new DocumentCreator(this, getUIFacade(),
getParserFactory());
}
return myDocumentManager;
}
private ParserFactory getParserFactory() {
if (myParserFactory == null) {
myParserFactory = new ParserFactoryImpl();
}
return myParserFactory;
}
public GPUndoManager getUndoManager() {
if (myUndoManager == null) {
myUndoManager = new UndoManagerImpl((IGanttProject) this,
getParserFactory(), getDocumentManager());
Mediator.registerUndoManager(myUndoManager);
}
return myUndoManager;
}
// ///////////////////////////////////////////////////////////////
219
// ResourceView implementation
public void resourceAdded(ResourceEvent event) {
if (getStatusBar() != null) {
// tabpane.setSelectedIndex(1);
getStatusBar().setFirstText(
GanttProject.correctLabel(GanttLanguage.getInstance()
.getText("newHuman")), 2000);
setAskForSave(true);
refreshProjectInfos();
// setQuickSave (true);
}
}
public void resourcesRemoved(ResourceEvent event) {
// setQuickSave (true);
}
// ///////////////////////////////////////////////////////////////
// UIFacade
public UIFacade getUIFacade() {
return this;
}
public ScrollingManager getScrollingManager() {
if (myScrollingManager == null) {
myScrollingManager = new ScrollingManagerImpl(Mediator
.getTaskSelectionManager());
}
return myScrollingManager;
}
public ChartViewState getGanttChartViewState() {
return getArea().getViewState();
}
// public JTabbedPane getTabpane() {
// return getTabs();
// }
private class ParserFactoryImpl implements ParserFactory {
public GPParser newParser() {
return new GanttXMLOpen(prjInfos, getArea(), getTaskManager(),
getUIFacade());
}
public GPSaver newSaver() {
return new GanttXMLSaver(GanttProject.this, (GanttTree2) getTree(),
getResourcePanel(), getArea(), getUIFacade());
}
}
public void setRowHeight(int value) {
tree.getTreeTable().getTable().setRowHeight(value);
}
public void changeOrder(DefaultListModel buttonList,
DefaultListModel deletedButtonList) {
iconList = new DefaultListModel();
for (int i = 0; i < buttonList.size(); i++)
iconList.addElement(buttonList.getElementAt(i));
deletedIconList = new DefaultListModel();
for (int i = 0; i < deletedButtonList.size(); i++)
deletedIconList.addElement(deletedButtonList.getElementAt(i));
addButtons();
options.setIconList(getIconPositions(iconList));
options.setDeletedIconList(getIconPositions(deletedIconList));
setHiddens();
refresh();
}
private String getIconPositions(DefaultListModel list) {
String sIcons = "";
DefaultListModel iconListValues = new DefaultListModel();
if (list != null) {
int i = 0;
if (list.equals(deletedIconList))
i++;
for (; i < list.size(); i++) {
if (!sIcons.equals(""))
sIcons = sIcons + ",";
if (list.elementAt(i).equals(
language.getText("separator").toUpperCase()))
sIcons = sIcons + GanttOptions.SEPARATOR;
else if ((TestGanttRolloverButton) list.elementAt(i) == bExit)
220
sIcons = sIcons + GanttOptions.EXIT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bNew)
sIcons = sIcons + GanttOptions.NEW;
else if ((TestGanttRolloverButton) list.elementAt(i) == bOpen)
sIcons = sIcons + GanttOptions.OPEN;
else if ((TestGanttRolloverButton) list.elementAt(i) == bSave)
sIcons = sIcons + GanttOptions.SAVE;
else if ((TestGanttRolloverButton) list.elementAt(i) == bSaveAs)
sIcons = sIcons + GanttOptions.SAVEAS;
else if ((TestGanttRolloverButton) list.elementAt(i) == bImport)
sIcons = sIcons + GanttOptions.IMPORT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bExport)
sIcons = sIcons + GanttOptions.EXPORT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bPrint)
sIcons = sIcons + GanttOptions.PRINT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bPreviewPrint)
sIcons = sIcons + GanttOptions.PREVIEWPRINT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bCut)
sIcons = sIcons + GanttOptions.CUT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bCopy)
sIcons = sIcons + GanttOptions.COPY;
else if ((TestGanttRolloverButton) list.elementAt(i) == bPaste)
sIcons = sIcons + GanttOptions.PASTE;
else if ((TestGanttRolloverButton) list.elementAt(i) == bNewTask)
sIcons = sIcons + GanttOptions.NEWTASK;
else if ((TestGanttRolloverButton) list.elementAt(i) == bDelete)
sIcons = sIcons + GanttOptions.DELETE;
else if ((TestGanttRolloverButton) list.elementAt(i) == bProperties)
sIcons = sIcons + GanttOptions.PROPERTIES;
else if ((TestGanttRolloverButton) list.elementAt(i) == bUnlink)
sIcons = sIcons + GanttOptions.UNLINK;
else if ((TestGanttRolloverButton) list.elementAt(i) == bLink)
sIcons = sIcons + GanttOptions.LINK;
else if ((TestGanttRolloverButton) list.elementAt(i) == bInd)
sIcons = sIcons + GanttOptions.IND;
else if ((TestGanttRolloverButton) list.elementAt(i) == bUnind)
sIcons = sIcons + GanttOptions.UNIND;
else if ((TestGanttRolloverButton) list.elementAt(i) == bUp)
sIcons = sIcons + GanttOptions.UP;
else if ((TestGanttRolloverButton) list.elementAt(i) == bDown)
sIcons = sIcons + GanttOptions.DOWN;
else if ((TestGanttRolloverButton) list.elementAt(i) == bPrev)
sIcons = sIcons + GanttOptions.PREV;
else if ((TestGanttRolloverButton) list.elementAt(i) == bScrollCenter)
sIcons = sIcons + GanttOptions.CENTER;
else if ((TestGanttRolloverButton) list.elementAt(i) == bNext)
sIcons = sIcons + GanttOptions.NEXT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bZoomOut)
sIcons = sIcons + GanttOptions.ZOOMOUT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bZoomIn)
sIcons = sIcons + GanttOptions.ZOOMIN;
else if ((TestGanttRolloverButton) list.elementAt(i) == bUndo)
sIcons = sIcons + GanttOptions.UNDO;
else if ((TestGanttRolloverButton) list.elementAt(i) == bRedo)
sIcons = sIcons + GanttOptions.REDO;
else if ((TestGanttRolloverButton) list.elementAt(i) == bCritical)
221
sIcons = sIcons + GanttOptions.CRITICAL;
else if ((TestGanttRolloverButton) list.elementAt(i) == bAbout)
sIcons = sIcons + GanttOptions.ABOUT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bSaveCurrent)
sIcons = sIcons + GanttOptions.SAVECURRENT;
else if ((TestGanttRolloverButton) list.elementAt(i) == bComparePrev)
sIcons = sIcons + GanttOptions.COMPAREPREV;
else if ((TestGanttRolloverButton) list.elementAt(i) == bRefresh)
sIcons = sIcons + GanttOptions.REFRESH;
}
}
return sIcons;
}
public DefaultListModel initIconList() {
DefaultListModel list = new DefaultListModel();
int[] icons = options.getIconList();
for (int i = 0; i < icons.length; i++)
addButton(icons[i], list);
return list;
}
public DefaultListModel initDeletedIconList() {
DefaultListModel list = new DefaultListModel();
if (options.getDeletedIconList() != null) {
int[] icons = options.getDeletedIconList();
for (int i = 0; i < icons.length; i++)
addButton(icons[i], list);
}
return list;
}
public void addButton(int icon, DefaultListModel list) {
switch (icon) {
case (GanttOptions.SEPARATOR):
list.addElement(language.getText("separator").toUpperCase());
break;
case (GanttOptions.EXIT):
list.addElement(bExit);
break;
case (GanttOptions.NEW):
list.addElement(bNew);
break;
case (GanttOptions.OPEN):
list.addElement(bOpen);
break;
case (GanttOptions.SAVE):
list.addElement(bSave);
break;
case (GanttOptions.SAVEAS):
list.addElement(bSaveAs);
break;
case (GanttOptions.IMPORT):
list.addElement(bImport);
break;
case (GanttOptions.EXPORT):
list.addElement(bExport);
break;
case (GanttOptions.PRINT):
list.addElement(bPrint);
break;
case (GanttOptions.PREVIEWPRINT):
list.addElement(bPreviewPrint);
break;
case (GanttOptions.CUT):
list.addElement(bCut);
break;
case (GanttOptions.COPY):
list.addElement(bCopy);
break;
case (GanttOptions.PASTE):
list.addElement(bPaste);
break;
case (GanttOptions.NEWTASK):
list.addElement(bNewTask);
break;
case (GanttOptions.DELETE):
list.addElement(bDelete);
break;
case (GanttOptions.PROPERTIES):
list.addElement(bProperties);
break;
case (GanttOptions.UNLINK):
list.addElement(bUnlink);
break;
case (GanttOptions.LINK):
222
list.addElement(bLink);
break;
case (GanttOptions.IND):
list.addElement(bInd);
break;
case (GanttOptions.UNIND):
list.addElement(bUnind);
break;
case (GanttOptions.UP):
list.addElement(bUp);
break;
case (GanttOptions.DOWN):
list.addElement(bDown);
break;
case (GanttOptions.PREV):
list.addElement(bPrev);
break;
case (GanttOptions.CENTER):
list.addElement(bScrollCenter);
break;
case (GanttOptions.NEXT):
list.addElement(bNext);
break;
case (GanttOptions.ZOOMOUT):
list.addElement(bZoomOut);
break;
case (GanttOptions.ZOOMIN):
list.addElement(bZoomIn);
break;
case (GanttOptions.UNDO):
list.addElement(bUndo);
break;
case (GanttOptions.REDO):
list.addElement(bRedo);
break;
case (GanttOptions.CRITICAL):
list.addElement(bCritical);
break;
case (GanttOptions.ABOUT):
list.addElement(bAbout);
break;
case (GanttOptions.SAVECURRENT):
list.addElement(bSaveCurrent);
break;
case (GanttOptions.COMPAREPREV):
list.addElement(bComparePrev);
break;
case (GanttOptions.REFRESH):
list.addElement(bRefresh);
break;
default:
break;
}
}
public void addButtons() {
toolBar.removeAll();
for (int i = 0; i < iconList.size(); i++) {
if (iconList.elementAt(i).equals(
language.getText("separator").toUpperCase())) {
int size = Integer.parseInt(options.getIconSize());
// toolBar.addSeparator(new Dimension(size, size));
ImageIcon icon;
ImageIcon iconV = new ImageIcon(getClass().getResource(
"/icons/sepV_16.png"));
ImageIcon iconH = new ImageIcon(getClass().getResource(
"/icons/sepH_16.png"));
if (toolBar.getOrientation() == JToolBar.HORIZONTAL)
icon = iconV;
else
icon = iconH;
toolBar.add(new JLabel(icon));
} else {
toolBar.add((JButton) iconList.elementAt(i));
}
}
}
public DefaultListModel getButtonList() {
return iconList;
}
public DefaultListModel getDeletedButtonList() {
return deletedIconList;
}
public Chart getActiveChart() {
Chart resourcesChart = getResourceChart();
223
Chart ganttChart = getGanttChart();
Chart visibleChart = (getTabs().getSelectedIndex() == UIFacade.RESOURCES_INDEX) ? resourcesChart
: ganttChart;
return visibleChart;
}
public Chart getGanttChart() {
return (Chart) getArea();
}
public Chart getResourceChart() {
return (Chart) getResourcePanel().area;
}
public void setStatusText(String text) {
statusBar.setFirstText(text, 2000);
}
public void repaint2() {
// try
// {
// Thread.sleep(10);
// }
// catch (InterruptedException e2)
// {
// // TODO Auto-generated catch block
// e2.printStackTrace();
// }
try {
getTaskManager().getAlgorithmCollection()
.getRecalculateTaskScheduleAlgorithm().run();
// there was a bug when importing a project where a FF dependency
// was under a supertask.
// The supertask length was calculated as if it was a FS dependency.
List l = tree.getAllGanttTasks();
Task[] t = new Task[l.size()];
l.toArray(t);
getTaskManager().getAlgorithmCollection()
.getAdjustTaskBoundsAlgorithm().run(t);
} catch (TaskDependencyException e1) {
e1.printStackTrace();
}
recalculateCriticalPath();
try {
getTaskManager().getAlgorithmCollection()
.getRecalculateTaskScheduleAlgorithm().run();
} catch (TaskDependencyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getResourcePanel().getResourceTreeTableModel().updateResources();
getResourcePanel().getResourceTreeTable().setRowHeight(20);
myDelayManager.fireDelayObservation();
super.repaint();
}
public void recalculateCriticalPath() {
if (myUIConfiguration.isCriticalPathOn()) {
getTaskManager().processCriticalPath((TaskNode) tree.getRoot());
ArrayList projectTasks = tree.getProjectTasks();
if (projectTasks.size() != 0) {
for (int i = 0; i < projectTasks.size(); i++)
getTaskManager().processCriticalPath(
(TaskNode) projectTasks.get(i));
}
repaint();
}
}
public int getViewIndex() {
if (getTabs() == null)
return -1;
return getTabs().getSelectedIndex();
}
public void setViewIndex(int viewIndex) {
if (myTabPane.getTabCount() > viewIndex)
myTabPane.setSelectedIndex(viewIndex);
}
public static void setWindowListener(WindowListener windowListener) {
ourWindowListener = windowListener;
}
224
public int getGanttDividerLocation() {
return mySplitPane.getDividerLocation();
}
public void setGanttDividerLocation(int location) {
mySplitPane.setDividerLocation(location);
}
public int getResourceDividerLocation() {
return getResourcePanel().getDividerLocation();
}
public void setResourceDividerLocation(int location) {
getResourcePanel().setDividerLocation(location);
}
public void refresh() {
// // -------------------------
//
// Component glassPane = this.getGlassPane();
// setGlassPane(glassPane);
// glassPane.setVisible(true); // before worker thread
//
// glassPane.addKeyListener(new KeyListener() {
//
// public void keyPressed(KeyEvent arg0) {
// System.out.println("keyPressed");
//
// }
//
// public void keyReleased(KeyEvent arg0) {
// System.out.println("keyReleased");
//
// }
//
// public void keyTyped(KeyEvent arg0) {
// System.out.println("keyTyped");
//
// }
// });
// glassPane.addMouseListener(new MouseListener() {
//
// public void mouseClicked(MouseEvent arg0) {
// // TODO Auto-generated method stub
//
// }
//
// public void mouseEntered(MouseEvent arg0) {
// // TODO Auto-generated method stub
//
// }
//
// public void mouseExited(MouseEvent arg0) {
// // TODO Auto-generated method stub
//
// }
//
// public void mousePressed(MouseEvent arg0) {
// System.out.println("mousePressed");
//
// }
//
// public void mouseReleased(MouseEvent arg0) {
// // TODO Auto-generated method stub
//
// }
// });
//
// // -------------------------
try {
getTaskManager().getAlgorithmCollection()
.getRecalculateTaskScheduleAlgorithm().run();
List l = tree.getAllGanttTasks();
Task[] t = new Task[l.size()];
l.toArray(t);
getTaskManager().getAlgorithmCollection()
.getAdjustTaskBoundsAlgorithm().run(t);
for (int i = 0; i < t.length; i++)
getTaskManager().getAlgorithmCollection()
.getRecalculateTaskCompletionPercentageAlgorithm().run(
t[i]);
} catch (TaskDependencyException e1) {
e1.printStackTrace();
}
225
getTaskManager().processCriticalPath((TaskNode) tree.getRoot());
ArrayList projectTasks = tree.getProjectTasks();
if (projectTasks.size() != 0) {
for (int i = 0; i < projectTasks.size(); i++)
getTaskManager().processCriticalPath(
(TaskNode) projectTasks.get(i));
}
try {
getTaskManager().getAlgorithmCollection()
.getRecalculateTaskScheduleAlgorithm().run();
} catch (TaskDependencyException e) {
e.printStackTrace();
}
getResourcePanel().getResourceTreeTableModel().updateResources();
getResourcePanel().getResourceTreeTable().setRowHeight(20);
if (myDelayManager != null)
myDelayManager.fireDelayObservation();
super.repaint();
}
public void showHiddenButtonsPaneMenu() {
menu.applyComponentOrientation(language.getComponentOrientation());
menu.show(toolBar, bShowHiddens.getX(), bShowHiddens.getY());
}
public void setHiddens() {
menu.removeAll();
addButtons();
int separatorSize = Integer.parseInt(options.getIconSize());
double toolBarlength = 0.;
int buttonSize = 0;
int lastDisplayedIndex = 0;
Component[] buttons = toolBar.getComponents();
if (toolBar.getOrientation() == JToolBar.HORIZONTAL)
toolBarlength = toolBar.getSize().getWidth();
else
toolBarlength = toolBar.getSize().getHeight();
int position = 10;
// searching for hidden buttons
for (int i = 0; i < buttons.length; i++) {
if (buttons[i].getClass() == TestGanttRolloverButton.class) {
if (toolBar.getOrientation() == JToolBar.HORIZONTAL)
buttonSize = buttons[i].getWidth();
else
buttonSize = buttons[i].getHeight();
position = position + buttonSize;
if (position + 2 * bShowHiddens.getWidth() / 3 < toolBarlength) {
lastDisplayedIndex = i;
} else {
menu.add(buttons[i]);
}
} else
position = position + separatorSize;
}
// if there is hidden buttons
if (menu.getComponentCount() != 0) {
for (int i = lastDisplayedIndex + 1; i < buttons.length; i++) {
toolBar.remove(buttons[i]);
}
toolBar.add(bShowHiddens);
}
}
}
net.sourceforge.ganttproject.parser TaskTagHandler
package net.sourceforge.ganttproject.parser;
import java.awt.Color;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Stack;
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttTask;
226
import net.sourceforge.ganttproject.shape.ShapePaint;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskContainmentHierarchyFacade;
import net.sourceforge.ganttproject.task.TaskManager;
import org.xml.sax.Attributes;
public class TaskTagHandler implements TagHandler {
public TaskTagHandler(TaskManager mgr, ParsingContext context) {
myManager = mgr;
myContext = context;
}
public void startElement(String namespaceURI, String sName, String qName,
Attributes attrs) {
if (qName.equals("task")) {
loadTask(attrs);
}
}
/** Method when finish to parse an attibute */
public void endElement(String namespaceURI, String sName, String qName) {
if (qName.equals("task")) {
myStack.pop();
}
}
private void loadTask(Attributes attrs) {
String taskIdAsString = attrs.getValue("id");
GanttTask task = null;
if (taskIdAsString == null) {
task = getManager().createTask();
} else {
int taskId;
try {
taskId = Integer.parseInt(taskIdAsString);
} catch (NumberFormatException e) {
throw new RuntimeException("Failed to parse the value '"
+ taskIdAsString + "' of attribute 'id' of tag <task>",
e);
}
task = getManager().createTask(taskId);
}
//
String taskName = attrs.getValue("name");
if (taskName != null) {
task.setName(taskName);
}
String meeting = attrs.getValue("meeting");
if (meeting != null) {
task.setMilestone(meeting.equals("true"));
}
String project = attrs.getValue("project");
if (project != null)
task.setProjectTask(true);
String start = attrs.getValue("start");
if (start != null) {
task.setStart(GanttCalendar.parseXMLDate(start));
}
String duration = attrs.getValue("duration");
if (duration != null) {
try {
int length = Integer.parseInt(duration);
if (length == 0) {
length = 1;
}
task.setLength(length);
} catch (NumberFormatException e) {
throw new RuntimeException("Failed to parse the value '"
+ duration + "' of attribute 'duration' of tag <task>",
e);
}
}
//LH
String budget = attrs.getValue("budget");
if (budget != null) {
try {
task.setBudget(Double.parseDouble(budget));
} catch (NumberFormatException e) {
227
throw new RuntimeException("Failed to parse the value '"
+ budget + "' of attribute 'budget' of tag <task>",
e);
}
}
String complete = attrs.getValue("complete");
if (complete != null) {
try {
task.setCompletionPercentage(Integer.parseInt(complete));
} catch (NumberFormatException e) {
throw new RuntimeException("Failed to parse the value '"
+ complete + "' of attribute 'complete' of tag <task>",
e);
}
}
String priority = attrs.getValue("priority");
if (priority != null) {
try {
task.setPriority(Integer.parseInt(priority));
} catch (NumberFormatException e) {
throw new RuntimeException("Failed to parse the value '"
+ priority + "' of attribute 'priority' of tag <task>",
e);
}
}
String color = attrs.getValue("color");
if (color != null) {
task.setColor(ColorValueParser.parseString(color));
}
String fixedStart = attrs.getValue("fixed-start");
if ("true".equals(fixedStart)) {
task.setStartFixed(true);
}
// String fixedFinish = attrs.getValue("fixed-finish");
// if ("true".equals(fixedFinish)) {
// task.setFinishFixed(true);
// }
String third = attrs.getValue("thirdDate");
if (third != null) {
task.setThirdDate(GanttCalendar.parseXMLDate(third));
}
String thirdConstraint = attrs.getValue("thirdDate-constraint");
if (thirdConstraint != null) {
try {
task.setThirdDateConstraint(Integer.parseInt(thirdConstraint));
} catch (NumberFormatException e) {
throw new RuntimeException(
"Failed to parse the value '"
+ thirdConstraint
+ "' of attribute 'thirdDate-constraint' of tag <task>",
e);
}
}
String webLink_enc = attrs.getValue("webLink");
String webLink = webLink_enc;
if (webLink_enc != null)
try {
webLink = URLDecoder.decode(webLink_enc, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (webLink != null) {
task.setWebLink(webLink);
}
String expand = attrs.getValue("expand");
if (expand != null) {
task.setExpand("true".equals(expand));
}
String shape = attrs.getValue("shape");
if (shape != null) {
228
java.util.StringTokenizer st1 = new java.util.StringTokenizer(
shape, ",");
int[] array = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
String token = "";
int count = 0;
while (st1.hasMoreTokens()) {
token = st1.nextToken();
array[count] = (new Integer(token)).intValue();
count++;
}
task.setShape(new ShapePaint(4, 4, array, Color.white, task
.getColor()));
}
getManager().registerTask(task);
TaskContainmentHierarchyFacade taskHierarchy = getManager()
.getTaskHierarchy();
myContext.setTaskID(task.getTaskID());
Task lastTask = myStack.isEmpty() ? taskHierarchy.getRootTask()
: (Task) myStack.peek();
taskHierarchy.move(task, lastTask);
myStack.push(task);
}
private TaskManager getManager() {
return myManager;
}
private final ParsingContext myContext;
private final TaskManager myManager;
private final Stack myStack = new Stack();
}
net.sourceforge.ganttproject. document.ProxyDocument
package net.sourceforge.ganttproject.document;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.sourceforge.ganttproject.GanttProject;
import net.sourceforge.ganttproject.GanttTree2;
import net.sourceforge.ganttproject.IGanttProject;
import net.sourceforge.ganttproject.calendar.GPCalendar;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.parser.AllocationTagHandler;
import net.sourceforge.ganttproject.parser.BlankLineTagHandler;
import net.sourceforge.ganttproject.parser.CustomPropertiesTagHandler;
import net.sourceforge.ganttproject.parser.DefaultWeekTagHandler;
import net.sourceforge.ganttproject.parser.DependencyTagHandler;
import net.sourceforge.ganttproject.parser.CostTagHandler;
import net.sourceforge.ganttproject.parser.GPParser;
import net.sourceforge.ganttproject.parser.ParserFactory;
import net.sourceforge.ganttproject.parser.PreviousStateTasksTagHandler;
import net.sourceforge.ganttproject.parser.ResourceTagHandler;
import net.sourceforge.ganttproject.parser.RoleTagHandler;
import net.sourceforge.ganttproject.parser.TaskDisplayColumnsTagHandler;
import net.sourceforge.ganttproject.parser.TaskPropertiesTagHandler;
import net.sourceforge.ganttproject.parser.TaskTagHandler;
import net.sourceforge.ganttproject.parser.VacationTagHandler;
import net.sourceforge.ganttproject.parser.ViewTagHandler;
import net.sourceforge.ganttproject.resource.HumanResourceManager;
import net.sourceforge.ganttproject.resource.ResourceManager;
import net.sourceforge.ganttproject.roles.RoleManager;
import net.sourceforge.ganttproject.task.TaskManager;
/**
* @author bard
*/
class ProxyDocument implements Document {
private final Document myPhysicalDocument;
private IGanttProject myProject;
229
private UIFacade myUIFacade;
private ParserFactory myParserFactory;
private boolean isLoaded;
ProxyDocument(Document physicalDocument, IGanttProject project,
UIFacade uiFacade, ParserFactory parserFactory) {
myPhysicalDocument = physicalDocument;
myProject = project;
myUIFacade = uiFacade;
myParserFactory = parserFactory;
}
public String getDescription() {
return myPhysicalDocument.getDescription();
}
public boolean canRead() {
return myPhysicalDocument.canRead();
}
public boolean canWrite() {
return myPhysicalDocument.canWrite();
}
public boolean isValidForMRU() {
return myPhysicalDocument.isValidForMRU();
}
public boolean acquireLock() {
return myPhysicalDocument.acquireLock();
}
public void releaseLock() {
myPhysicalDocument.releaseLock();
}
public InputStream getInputStream() throws IOException {
return myPhysicalDocument.getInputStream();
}
public OutputStream getOutputStream() throws IOException {
return myPhysicalDocument.getOutputStream();
}
public String getPath() {
return myPhysicalDocument.getPath();
}
public String getFilePath() {
return myPhysicalDocument.getFilePath();
}
public String getURLPath() {
return myPhysicalDocument.getURLPath();
}
public String getUsername() {
return myPhysicalDocument.getUsername();
}
public String getPassword() {
return myPhysicalDocument.getPassword();
}
public void setUserInfo(String user, String pass) {
myPhysicalDocument.setUserInfo(user, pass);
}
public String getLastError() {
return myPhysicalDocument.getLastError();
}
public void read() throws IOException {
FailureState failure = new FailureState();
SuccessState success = new SuccessState();
ParsingState parsing = new ParsingState(success, failure);
OpenCopyConfirmationState confirmation = new OpenCopyConfirmationState(
parsing, failure);
AcquireLockState lock = new AcquireLockState(parsing, confirmation);
lock.enter();
}
private TaskManager getTaskManager() {
return myProject.getTaskManager();
}
230
private RoleManager getRoleManager() {
return myProject.getRoleManager();
}
private HumanResourceManager getHumanResourceManager() {
return (HumanResourceManager) myProject.getHumanResourceManager();
}
private GPCalendar getActiveCalendar() {
return myProject.getActiveCalendar();
}
private UIFacade getUIFacade() {
return myUIFacade;
}
class AcquireLockState {
OpenCopyConfirmationState myConfirmationState;
ParsingState myParsingState;
/**
* @param parsing
* @param confirmation
*/
public AcquireLockState(ParsingState parsing,
OpenCopyConfirmationState confirmation) {
myParsingState = parsing;
myConfirmationState = confirmation;
}
void enter() throws IOException {
boolean locked = acquireLock();
if (!locked) {
myConfirmationState.enter();
} else {
myParsingState.enter();
}
}
}
class OpenCopyConfirmationState {
ParsingState myParsingState;
FailureState myExitState;
/**
* @param parsing
* @param failure
*/
public OpenCopyConfirmationState(ParsingState parsing,
FailureState failure) {
myParsingState = parsing;
myExitState = failure;
}
void enter() throws IOException {
String message = GanttLanguage.getInstance().getText("msg13");
String title = GanttLanguage.getInstance().getText("warning");
if (getUIFacade().showConfirmationDialog(message, title)) {
myParsingState.enter();
} else {
myExitState.enter();
}
}
}
class ParsingState {
FailureState myFailureState;
SuccessState mySuccessState;
/**
* @param success
* @param failure
*/
public ParsingState(SuccessState success, FailureState failure) {
mySuccessState = success;
myFailureState = failure;
}
void enter() throws IOException {
GPParser opener = myParserFactory.newParser();
ResourceManager hrManager = getHumanResourceManager();
RoleManager roleManager = getRoleManager();
231
TaskManager taskManager = getTaskManager();
ResourceTagHandler resourceHandler = new ResourceTagHandler(
hrManager, roleManager);
DependencyTagHandler dependencyHandler = new DependencyTagHandler(
opener.getContext(), taskManager);
//LH
CostTagHandler costHandler = new CostTagHandler(
opener.getContext(), taskManager);
AllocationTagHandler allocationHandler = new AllocationTagHandler(
hrManager, getTaskManager(), getRoleManager());
VacationTagHandler vacationHandler = new VacationTagHandler(
hrManager);
PreviousStateTasksTagHandler previousStateHandler = new PreviousStateTasksTagHandler(
((GanttProject) myProject).getPreviouStates());
RoleTagHandler rolesHandler = new RoleTagHandler(roleManager);
TaskTagHandler taskHandler = new TaskTagHandler(taskManager, opener
.getContext());
BlankLineTagHandler blankLineHandler = new BlankLineTagHandler(myUIFacade.getTree());
DefaultWeekTagHandler weekHandler = new DefaultWeekTagHandler(
getActiveCalendar());
ViewTagHandler viewHandler = new ViewTagHandler(getUIFacade());
TaskPropertiesTagHandler taskPropHandler = new TaskPropertiesTagHandler(
((GanttTree2) ((GanttProject) myProject).getTree())
.getTreeTable());
opener.addTagHandler(taskPropHandler);
CustomPropertiesTagHandler customPropHandler = new CustomPropertiesTagHandler(
opener.getContext(), getTaskManager());
opener.addTagHandler(customPropHandler);
TaskDisplayColumnsTagHandler taskDisplayHandler = new TaskDisplayColumnsTagHandler(
((GanttTree2) ((GanttProject) myProject).getTree())
.getTreeTable());
opener.addTagHandler(taskDisplayHandler);
opener.addTagHandler(taskHandler);
opener.addTagHandler(blankLineHandler);
opener.addParsingListener(taskPropHandler);
opener.addParsingListener(taskDisplayHandler);
opener.addParsingListener(customPropHandler);
opener.addTagHandler(opener.getDefaultTagHandler());
opener.addTagHandler(resourceHandler);
opener.addTagHandler(dependencyHandler);
//LH
opener.addTagHandler(costHandler);
opener.addTagHandler(allocationHandler);
opener.addParsingListener(allocationHandler);
opener.addTagHandler(vacationHandler);
opener.addTagHandler(previousStateHandler);
opener.addTagHandler(rolesHandler);
opener.addTagHandler(weekHandler);
opener.addTagHandler(viewHandler);
//LH
opener.addParsingListener(costHandler);
opener.addParsingListener(dependencyHandler);
opener.addParsingListener(resourceHandler);
if (opener.load(getInputStream())) {
mySuccessState.enter();
} else {
myFailureState.enter();
}
}
}
class SuccessState {
void enter() {
ProxyDocument.this.setLoaded(true);
}
}
232
class FailureState {
void enter() {
}
}
private void setLoaded(boolean b) {
isLoaded = b;
}
}
net.sourceforge.ganttproject.io. CSVOptions
package net.sourceforge.ganttproject.io;
/**
* @author athomas Settings for exporting in csv format
*/
public class CSVOptions {
public boolean bExportTaskID = true;
public boolean bExportTaskName = true;
public boolean bExportTaskStartDate = true;
public boolean bExportTaskEndDate = true;
public boolean bExportTaskPercent = true;
public boolean bExportTaskDuration = true;
//LH
public boolean bExportTaskBudget = true;
public boolean bExportTaskWebLink = true;
public boolean bExportTaskResources = true;
public boolean bExportTaskNotes = true;
public boolean bExportResourceID = true;
public boolean bExportResourceName = true;
public boolean bExportResourceMail = true;
public boolean bExportResourcePhone = true;
public boolean bExportResourceRole = true;
public boolean bFixedSize = false;
public String sSeparatedChar = ",";
public String sSeparatedTextChar = "\"";
/** @return the csv settings as an xml schema. */
public String getXml() {
String res = " <csv-export>\n";
// general options
res += " <csv-general \n";
res += " fixed=\"" + bFixedSize + "\"\n";
res += " separatedChar=\"" + correct(sSeparatedChar) + "\"\n";
res += " separatedTextChar=\"" + correct(sSeparatedTextChar)
+ "\"/>\n";
// tasks export options
res += " <csv-tasks\n";
res += " id=\"" + bExportTaskID + "\"\n";
res += " name=\"" + bExportTaskName + "\"\n";
res += " start-date=\"" + bExportTaskStartDate + "\"\n";
res += " end-date=\"" + bExportTaskEndDate + "\"\n";
res += " percent=\"" + bExportTaskPercent + "\"\n";
res += " duration=\"" + bExportTaskDuration + "\"\n";
//LH
res += " budget=\"" + bExportTaskBudget + "\"\n";
res += " webLink=\"" + bExportTaskWebLink + "\"\n";
res += " resources=\"" + bExportTaskResources + "\"\n";
res += " notes=\"" + bExportTaskNotes + "\"/>\n";
// resources export options
res += " <csv-resources\n";
res += " id=\"" + bExportResourceID + "\"\n";
res += " name=\"" + bExportResourceName + "\"\n";
res += " mail=\"" + bExportResourceMail + "\"\n";
233
res += " phone=\"" + bExportResourcePhone + "\"\n";
res += " role=\"" + bExportResourceRole + "\"/>\n";
return res += " </csv-export>\n";
}
public String correct(String s) {
String res;
res = s.replaceAll("&", "&");
res = res.replaceAll("<", "<");
res = res.replaceAll(">", ">");
res = res.replaceAll("/", "/");
res = res.replaceAll("\"", """);
return res;
}
/** @return a list of the possible separated char. */
public String[] getSeparatedTextChars() {
String[] charText = { " \' ", " \" " };
return charText;
}
}
net.sourceforge.ganttproject.io. GanttCSVExport
package net.sourceforge.ganttproject.io;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import net.sourceforge.ganttproject.GanttTask;
import net.sourceforge.ganttproject.IGanttProject;
import net.sourceforge.ganttproject.resource.HumanResource;
import net.sourceforge.ganttproject.resource.HumanResourceManager;
import net.sourceforge.ganttproject.roles.Role;
import net.sourceforge.ganttproject.task.ResourceAssignment;
import net.sourceforge.ganttproject.task.Task;
/**
* @author athomas Class to export the project in cvs text format
*/
public class GanttCSVExport {
// private GanttTree tree;
// private GanttResourcePanel peop;
private CSVOptions csvOptions;
private HumanResourceManager myHrManager;
// ArrayList lot = new ArrayList();
Task[] myTasks;
ArrayList resources = new ArrayList();
int iMaxSize = 0;
boolean bFixedSize = false;
/** Constructor. */
public GanttCSVExport(IGanttProject project, CSVOptions csvOptions) {
myTasks = project.getTaskManager().getTasks();
myHrManager = (HumanResourceManager) project.getHumanResourceManager();
this.csvOptions = csvOptions;
}
/** Save the project as CSV on a stream */
public void save(OutputStream stream) {
try {
OutputStreamWriter out = new OutputStreamWriter(stream);
beginToSave(out);
out.close();
} catch (IOException e) {
System.out.println("Error in saving the csv file");
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
/** Start saving the csv document. */
public void beginToSave(OutputStreamWriter out) throws IOException {
resources = myHrManager.getResources();
234
bFixedSize = csvOptions.bFixedSize;
if (csvOptions.bFixedSize)
getMaxSize();
/*
* writeProjectInfos(out); out.write("\n");
*/
writeTasks(out);
out.write("\n");
writeResources(out);
out.write("\n");
}
/** Write the project information on the file. */
private void writeProjectInfos(OutputStreamWriter out) throws IOException {
}
/** Write all tasks. */
private void writeTasks(OutputStreamWriter out) throws IOException {
// parse all tasks
for (int i = 0; i < myTasks.length; i++) {
Task task = myTasks[i];
// ID
if (csvOptions.bExportTaskID)
out.write(correctField("" + task.getTaskID())
+ (bFixedSize ? "" : csvOptions.sSeparatedChar));
// Name
if (csvOptions.bExportTaskName)
out.write((bFixedSize ? "" : csvOptions.sSeparatedTextChar)
+ correctField(getName(task))
+ (bFixedSize ? "" : csvOptions.sSeparatedTextChar
+ csvOptions.sSeparatedChar));
// Start Date
if (csvOptions.bExportTaskStartDate)
out.write(correctField(task.getStart().toString())
+ (bFixedSize ? "" : csvOptions.sSeparatedChar));
// End Date
if (csvOptions.bExportTaskEndDate)
out.write(correctField(task.getEnd().toString())
+ (bFixedSize ? "" : csvOptions.sSeparatedChar));
// Duration
if (csvOptions.bExportTaskDuration)
out.write(correctField("" + task.getDuration().getLength())
+ (bFixedSize ? "" : csvOptions.sSeparatedChar));
//LH
// Duration
if (csvOptions.bExportTaskBudget)
out.write(correctField("" + task.getBudget())
+ (bFixedSize ? "" : csvOptions.sSeparatedChar));
// Percent complete
if (csvOptions.bExportTaskPercent)
out.write(correctField("" + task.getCompletionPercentage())
+ (bFixedSize ? "" : csvOptions.sSeparatedChar));
// Web Link
if (csvOptions.bExportTaskWebLink)
out.write((bFixedSize ? "" : csvOptions.sSeparatedTextChar)
+ correctField(getWebLink((GanttTask) task))
+ (bFixedSize ? "" : csvOptions.sSeparatedTextChar
+ csvOptions.sSeparatedChar));
// associated resources
if (csvOptions.bExportTaskResources) {
out.write((bFixedSize ? "" : csvOptions.sSeparatedTextChar));
out.write(correctField(getAssignments(task)));
out.write((bFixedSize ? "" : csvOptions.sSeparatedTextChar
+ csvOptions.sSeparatedChar));
235
}
// Notes
if (csvOptions.bExportTaskNotes)
out.write((bFixedSize ? "" : csvOptions.sSeparatedTextChar)
+ correctField(task.getNotes())
+ (bFixedSize ? "" : csvOptions.sSeparatedTextChar
+ csvOptions.sSeparatedChar));
out.write("\n");
}
} // end of write tasks
/** write the resources. */
private void writeResources(OutputStreamWriter out) throws IOException {
// parse all resources
for (int i = 0; i < resources.size(); i++) {
HumanResource p = (HumanResource) resources.get(i);
// ID
if (csvOptions.bExportResourceID)
out.write(correctField("" + p.getId())
+ (bFixedSize ? "" : csvOptions.sSeparatedChar));
// Name
if (csvOptions.bExportResourceName)
out.write((bFixedSize ? "" : csvOptions.sSeparatedTextChar)
+ correctField(p.getName())
+ (bFixedSize ? "" : csvOptions.sSeparatedTextChar
+ csvOptions.sSeparatedChar));
if (csvOptions.bExportResourceMail)
out.write((bFixedSize ? "" : csvOptions.sSeparatedTextChar)
+ correctField(p.getMail())
+ (bFixedSize ? "" : csvOptions.sSeparatedTextChar
+ csvOptions.sSeparatedChar));
// Phone
if (csvOptions.bExportResourcePhone)
out.write((bFixedSize ? "" : csvOptions.sSeparatedTextChar)
+ correctField(p.getPhone())
+ (bFixedSize ? "" : csvOptions.sSeparatedTextChar
+ csvOptions.sSeparatedChar));
// Role
if (csvOptions.bExportResourcePhone) {
Role role = p.getRole();
String sRoleID = "0";
if (role != null)
sRoleID = role.getPersistentID();
out.write((bFixedSize ? "" : csvOptions.sSeparatedTextChar)
+ correctField(sRoleID)
+ (bFixedSize ? "" : csvOptions.sSeparatedTextChar
+ csvOptions.sSeparatedChar));
}
out.write("\n");
}
} // end of write resources
/** set the maximum size for all strings. */
void getMaxSize() {
iMaxSize = 0;
for (int i = 0; i < myTasks.length; i++) {
Task task = myTasks[i];
if (csvOptions.bExportTaskID) {
String s = "" + task.getTaskID();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportTaskName) {
String s = "" + getName(task);
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportTaskStartDate) {
String s = "" + task.getStart();
236
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportTaskEndDate) {
String s = "" + task.getEnd();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportTaskDuration) {
String s = "" + task.getDuration().getLength();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
//LH
if (csvOptions.bExportTaskBudget) {
String s = "" + task.getBudget();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportTaskPercent) {
String s = "" + task.getCompletionPercentage();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportTaskWebLink) {
String s = "" + getWebLink((GanttTask) task);
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportTaskResources) {
String s = "" + getAssignments(task);
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportTaskNotes) {
String s = "" + task.getNotes();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
}
// parse all resources
for (int i = 0; i < resources.size(); i++) {
HumanResource p = (HumanResource) resources.get(i);
if (csvOptions.bExportResourceID) {
String s = "" + p.getId();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportResourceName) {
String s = "" + p.getName();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportResourceMail) {
String s = "" + p.getMail();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportResourcePhone) {
String s = "" + p.getPhone();
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
if (csvOptions.bExportResourceRole) {
Role role = p.getRole();
String sRoleID = "0";
if (role != null)
sRoleID = role.getPersistentID();
String s = "" + sRoleID;
if (s.length() > iMaxSize)
iMaxSize = s.length();
}
}
} // get maxIndentation end
/** @return the name of task with the correct level. */
private String getName(Task task) {
if (bFixedSize)
237
return task.getName();
String res = "";
int depth = task.getManager().getTaskHierarchy().getDepth(task);
for (int i = 0; i < depth; i++) {
res += " ";
}
return res + task.getName();
}
/** @return the link of the task. */
private String getWebLink(GanttTask task) {
return (task.getWebLink().equals("http://") ? "" : task.getWebLink());
}
/** @return the list of the assignment for the resources. */
private String getAssignments(Task task) {
String res = "";
ResourceAssignment[] assignment = task.getAssignments();
for (int i = 0; i < assignment.length; i++)
res += (assignment[i].getResource() + (i == assignment.length - 1 ? ""
: csvOptions.sSeparatedChar.equals(";") ? "," : ";"));
return res;
}
private String correctField(String field) {
String res = "";
for (int i = 0; i < iMaxSize - field.length(); i++)
res += " ";
res += field;
return res;
}
}
net.sourceforge.ganttproject.io. GanttXMLSaver package net.sourceforge.ganttproject.io;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttGraphicArea;
import net.sourceforge.ganttproject.GanttPreviousState;
import net.sourceforge.ganttproject.GanttPreviousStateTask;
import net.sourceforge.ganttproject.GanttProject;
import net.sourceforge.ganttproject.GanttResourcePanel;
import net.sourceforge.ganttproject.GanttTask;
import net.sourceforge.ganttproject.GanttTaskRelationship;
import net.sourceforge.ganttproject.GanttTree2;
import net.sourceforge.ganttproject.GanttTreeTable;
import net.sourceforge.ganttproject.IGanttProject;
import net.sourceforge.ganttproject.Mediator;
import net.sourceforge.ganttproject.calendar.GanttDaysOff;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.resource.HumanResource;
import net.sourceforge.ganttproject.roles.Role;
import net.sourceforge.ganttproject.roles.RoleManager;
import net.sourceforge.ganttproject.roles.RoleSet;
import net.sourceforge.ganttproject.shape.ShapeConstants;
import net.sourceforge.ganttproject.shape.ShapePaint;
import net.sourceforge.ganttproject.task.Cost;
import net.sourceforge.ganttproject.task.CustomColumn;
import net.sourceforge.ganttproject.task.CustomColumnsException;
import net.sourceforge.ganttproject.task.CustomColumnsStorage;
import net.sourceforge.ganttproject.task.CustomColumnsValues;
import net.sourceforge.ganttproject.task.ResourceAssignment;
import net.sourceforge.ganttproject.task.BlankLineNode;
238
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.util.ColorConvertion;
import org.w3c.util.DateParser;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* Classe for save the project in a XML file
*/
public class GanttXMLSaver implements GPSaver {
private final IGanttProject myProject;
private final UIFacade myUIFacade;
private GanttTree2 tree;
private GanttResourcePanel peop;
private GanttGraphicArea area;
private HashMap usersId = new HashMap();
ArrayList number = new ArrayList();
// List of tasks
ArrayList lot = new ArrayList();
ArrayList lots = new ArrayList();
int cpt;
String s = " "; // the marge
/** The constructor */
public GanttXMLSaver(IGanttProject project, GanttTree2 tree,
GanttResourcePanel peop, GanttGraphicArea area, UIFacade uiFacade) {
this.tree = tree;
this.peop = peop;
this.area = area;
myProject = project;
myUIFacade = uiFacade;
}
/** Replace a part of the string by another one */
public String replaceAll(String notes, String s1, String s2) {
return notes.replaceAll(s1, s2);
}
/** Simple write information of tasks */
public void writeTask(Writer fout, DefaultMutableTreeNode node, String space) {
String space2 = s + space;
try {
if (node instanceof BlankLineNode) {
fout.write(space + "<blankline />\n");
return;
}
GanttTask task = (GanttTask) node.getUserObject();
if (task.getTaskID() == -1)
throw new RuntimeException(
"A task can not has a number equal to -1");
int id = task.getTaskID();
/*
* if (id >= lot.size()) { return; }
*/
boolean haschild = false;
ArrayList child = tree.getAllChildTask(node);
if (child.size() != 0) {
haschild = true;
}
number.add(new Integer(id));
cpt++;
// boolean one = (task.getSuccessorsOld().size() != 0 ||
// (task.getNotes() != null && task.getNotes().length()>=0) ||
// haschild);
239
boolean one = (task.getSuccessorsOld().size() == 0
&& (task.getNotes() == null || task.getNotes().length() == 0) && !haschild)
&& Mediator.getCustomColumnsStorage()
.getCustomColumnCount() == 0;
// Writes data of task
fout.write(space + "<task id=\"" + task.getTaskID() + // lots.indexOf(task.toString())
// + //By CL
"\" ");
fout.write("name=\"" + correct(task.getName()) + "\" ");
if (task.colorDefined()) {
/*
* fout.write("color=\"#"); if (task.getColor().getRed() <= 15) {
* fout.write("0"); }
* fout.write(Integer.toHexString(task.getColor().getRed())); if
* (task.getColor().getGreen() <= 15) { fout.write("0"); }
* fout.write(Integer.toHexString(task.getColor().getGreen()));
* if (task.getColor().getBlue() <= 15) { fout.write("0"); }
* fout.write(Integer.toHexString(task.getColor().getBlue()));
* fout.write("\" ");
*/
fout.write("color=\""
+ ColorConvertion.getColor(task.getColor()) + "\" ");
}
if (task.shapeDefined()
&& task.getShape() != new ShapePaint(
ShapeConstants.BACKSLASH, task.getColor(), task
.getColor())) {
fout.write("shape=\"" + task.getShape().getArray() + "\" ");
}
fout.write("meeting=\"" + ((task.isMilestone()) ? "true" : "false")
+ "\" ");
if (task.isProjectTask())
fout.write("project=\"true\" ");
fout.write("start=\"" + task.getStart().toXMLString() + "\" ");
fout.write("duration=\"" + task.getLength() + "\" ");
//LH
fout.write("budget=\"" + task.getBudget() + "\" ");
fout.write("complete=\"" + task.getCompletionPercentage() + "\" ");
fout.write("fixed-start=\""
+ (task.isStartFixed() ? "true" : "false") + "\" ");
if (task.getThird() != null) {
fout.write("thirdDate=\"" + task.getThird().toXMLString()
+ "\" ");
fout.write("thirdDate-constraint=\""
+ task.getThirdDateConstraint() + "\" ");
}
fout.write("priority=\"" + task.getPriority() + "\"");
// write the web link of the task
String sWebLink = task.getWebLink();
if (sWebLink != null && !sWebLink.equals("")
&& !sWebLink.equals("http://"))
fout.write(" webLink=\""
+ URLEncoder.encode(sWebLink, "ISO-8859-1") + "\"");
// write if the task is expand or collapse
fout.write(" expand=\"" + task.getExpand() + "\"");
if (!one) {
fout.write(">\n");
} else {
fout.write("/>\n");
// fout.writeBytes(">\n");
// Write notes
}
240
if (task.getNotes() != null && task.getNotes().length() > 0) {
fout.write(space2 + "<notes>");
fout.write("\n"
+ space2
+ s
+ correct(replaceAll(task.getNotes(), "\n", "\n"
+ space2 + s)));
fout.write("\n" + space2 + "</notes>\n");
}
// Write the depends of the task
/*
* if (task.getDepend().size() != 0) { //fout.writeBytes(space2+"<depends>\n");
* for (int i = 0; i < task.getDepend().size(); i++) {
* fout.write(space2 + "<depend id=\"" + tree.getTask( (String)
* task.getDepend().get(i)).getTaskID() + // changed By CL
* //lots.indexOf( (String) task.getDepend().get(i)) + "\"/>\n");
* //fout.writeBytes(space2+"</depends>\n"); } }
*/
//LH
Cost[] costs = task.getCosts();
for (int i = 0; i < costs.length; i++) {
fout.write(space2 /* +s */+ "<cost date=\""
+ String.valueOf(costs[i].getDate().getTime()) + "\"" + " value=\""
+ String.valueOf(costs[i].getValue()) + "\"" + " description=\""
+ costs[i].getDescription()
//+ "\" difference=\"" + relationship.getDifference()
+ "\"/>\n");
}
// use successors to write depends information
Vector successors = task.getSuccessorsOld();
for (int i = 0; i < successors.size(); i++) {
GanttTaskRelationship relationship = (GanttTaskRelationship) successors
.get(i);
fout.write(space2 /* +s */+ "<depend id=\""
+ relationship.getSuccessorTaskID() + "\"" + " type=\""
+ relationship.getRelationshipType()
+ "\" difference=\"" + relationship.getDifference()
+ "\"/>\n");
}
CustomColumnsValues ccv = task.getCustomValues();
CustomColumnsStorage ccs = Mediator.getCustomColumnsStorage();
List names = ccs.getCustomColumnsNames();
Iterator it = names.iterator();
while (it.hasNext()) {
String name, idc, value;
name = null;
idc = null;
value = null;
try {
name = (String) it.next();
idc = ccs.getIdFromName(name);
value = ccv.getValue(name).toString();
CustomColumn cc = ccs.getCustomColumn(name);
if (GregorianCalendar.class.isAssignableFrom(cc.getType()))
value = DateParser.getIsoDate(((GanttCalendar) ccv
.getValue(name)).getTime());
fout.write(s + s + s + "<customproperty taskproperty-id=\""
+ idc + "\" value=\"" + value + "\" />\n");
} catch (NullPointerException e) {
System.out.println(name + ", " + idc + ", " + value);
e.printStackTrace();
}
}
// Write the child of the task
if (haschild) {
for (int i = 0; i < child.size(); i++) {
241
Task task2 = (Task) ((DefaultMutableTreeNode) child.get(i))
.getUserObject();
int newid = -1; // lot.lastIndexOf(task2);
for (int j = 0; j < lot.size(); j++) {
String a = task2.toString();
if (a == null)
System.out.println("nul");
String b = lot.get(j).toString();
if (a.equals(b)) {
newid = j;
}
}
writeTask(fout, (DefaultMutableTreeNode) child.get(i),
space + s);
}
}
// end of task section
if (!one) {
fout.write(space + "</task>\n");
// fout.writeBytes(space+"</task>\n");
}
// if (tree.getNode(task.toString()).isLeaf() &&
// !tree.getFatherNode(task).isRoot()) {
// return;
// }
// if (id == lot.size() - 1) {
// return;
// }
// else {
// writeTask(fout, cpt, space);
//
// }
} catch (Exception e) {
e.printStackTrace();
}
}
public void writeTaskProperties(Writer fout, CustomColumnsStorage customCol) {
try {
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd0\" name=\"type\" type=\"default\" valuetype=\"icon\" />\n");
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd1\" name=\"priority\" type=\"default\" valuetype=\"icon\" />\n");
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd2\" name=\"info\" type=\"default\" valuetype=\"icon\" />\n");
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd3\" name=\"name\" type=\"default\" valuetype=\"text\" />\n");
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd4\" name=\"begindate\" type=\"default\" valuetype=\"date\" />\n");
fout
.write(s
+ s
+ s
242
+ "<taskproperty id=\"tpd5\" name=\"enddate\" type=\"default\" valuetype=\"date\" />\n");
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd6\" name=\"duration\" type=\"default\" valuetype=\"int\" />\n");
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd7\" name=\"completion\" type=\"default\" valuetype=\"int\" />\n");
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd8\" name=\"coordinator\" type=\"default\" valuetype=\"text\" />\n");
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd9\" name=\"predecessors\" type=\"default\" valuetype=\"text\" />\n");
//LH
fout
.write(s
+ s
+ s
+ "<taskproperty id=\"tpd10\" name=\"budget\" type=\"default\" valuetype=\"text\" />\n");
Iterator it = customCol.getCustomColumnsNames().iterator();
while (it.hasNext()) {
String colName = (String) it.next();
try {
CustomColumn cc = customCol.getCustomColumn(colName);
Object defVal = cc.getDefaultValue();
String valueType = null;
Class cla = cc.getType();
if (cla.equals(String.class))
valueType = "text";
else if (cla.equals(Boolean.class))
valueType = "boolean";
else if (cla.equals(Integer.class))
valueType = "int";
else if (cla.equals(Double.class))
valueType = "double";
else if (cla.isAssignableFrom(GregorianCalendar.class)) // TODO
// to
// be
// tested
{
valueType = "date";
defVal = DateParser.getIsoDate(((GanttCalendar) cc
.getDefaultValue()).getTime());
}
String idcStr = Mediator.getCustomColumnsStorage()
.getIdFromName(cc.getName());
fout.write(s + s + s + "<taskproperty id=\"" + idcStr
+ "\" name=\"" + cc.getName()
+ "\" type=\"custom\" valuetype=\"" + valueType
+ "\" defaultvalue=\"" + defVal.toString()
+ "\" />\n");
} catch (CustomColumnsException e1) {
e1.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
243
}
public void writeTaskDisplayColumns(Writer fout) {
List displayedColumns = tree.getTreeTable().getDisplayColumns();
if (displayedColumns != null) {
Iterator it = displayedColumns.iterator();
while (it.hasNext()) {
GanttTreeTable.DisplayedColumn dc = (GanttTreeTable.DisplayedColumn) it
.next();
if (dc.isDisplayed())
try {
fout.write(s + s + "<displaycolumn property-id=\""
+ dc.getID() + "\" order=\"" + dc.getOrder()
+ "\" width=\"" + dc.getWidth() + "\" />\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/** Write the resources on the file */
public void writeResources(Writer fout) {
try {
List resources = peop.getPeople();
int cpt_resources = 1;
for (int i = 0; i < resources.size(); i++, cpt_resources++) {
HumanResource p = (HumanResource) resources.get(i);
String string = p.getName();
byte[] btf8 = string.getBytes("UTF-8");
fout.write(s + s + "<resource id=\"" + p.getId() + "\" name=\""
+ (p.getName() != null ? correct(p.getName()) : "")
+ "\" function=\"" + p.getRole().getPersistentID()
+ "\" contacts=\""
+ (p.getMail() != null ? correct(p.getMail()) : "")
+ "\" phone=\""
+ (p.getPhone() != null ? correct(p.getPhone()) : "")
+ "\" />\n");
usersId.put(p.getName(), new Integer(cpt_resources));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/** Write the vacations on the file */
public void writeVacations(Writer fout) {
try {
List resources = peop.getPeople();
int cpt_resources = 1;
for (int i = 0; i < resources.size(); i++, cpt_resources++) {
HumanResource p = (HumanResource) resources.get(i);
if (p.getDaysOff() != null)
for (int j = 0; j < p.getDaysOff().size(); j++) {
GanttDaysOff gdo = (GanttDaysOff) p.getDaysOff()
.getElementAt(j);
fout.write(s + s + "<vacation start=\""
+ gdo.getStart().toXMLString() + "\" end=\""
+ gdo.getFinish().toXMLString()
+ "\" resourceid=\"" + p.getId() + "\"/>\n");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Write all previous states of the project.
*
* @throws IOException
*/
244
public void writePreviousStateTasks(Writer fout) throws IOException {
ArrayList previousStates = ((GanttProject) myProject)
.getPreviouStates();
for (int i = 0; i < previousStates.size(); i++) {
ArrayList list = null;
try {
list = ((GanttPreviousState) previousStates.get(i)).load();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// ArrayList list =
// ((GanttPreviousState)previous.get(i)).getTasks();
fout.write(s + s + "<previous-tasks name=\""
+ ((GanttPreviousState) previousStates.get(i)).getName()
+ "\">\n");
for (int j = 0; j < list.size(); j++) {
GanttPreviousStateTask task = (GanttPreviousStateTask) list
.get(j);
fout.write(s + s + s + "<previous-task id=\"" + task.getId()
+ "\"");
fout.write(" start=\"" + task.getStart().toXMLString() + "\"");
fout.write(" duration=\"" + task.getDuration() + "\"");
fout.write(" meeting=\"" + task.isMilestone() + "\"");
fout.write(" super=\"" + task.hasNested() + "\"");
fout.write("/>\n");
}
fout.write(s + s + "</previous-tasks>\n");
}
}
/** Write the assignement between tasks and users */
public void writeAllocations(Writer fout) {
try {
for (int i = 1; i < lot.size(); i++) {
Task task = (Task) ((DefaultMutableTreeNode) lot.get(i))
.getUserObject();
// ArrayList users = task.getUsersList();
ResourceAssignment[] assignments = task.getAssignments();
for (int j = 0; j < assignments.length; j++) {
int task_id = task.getTaskID();// (i-1);
ResourceAssignment next = assignments[j];
Role roleForAssignment = next.getRoleForAssignment();
if (roleForAssignment == null)
if (next.getResource() instanceof HumanResource)
roleForAssignment = ((HumanResource) next
.getResource()).getRole();
fout.write(s + s + "<allocation task-id=\"" + task_id
+ "\" resource-id=\"" + next.getResource().getId()
+ "\" function=\""
+ roleForAssignment.getPersistentID()
+ "\" responsible=\"" + next.isCoordinator()
+ "\" load=\"" + next.getLoad() + "\"/>\n");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/** Write all roles of the project. */
public void writeRoles(Writer fout) {
try {
// int id=RoleManager.Access.getInstance().DEFAULT_ROLES_NUMBER;
245
// String []roles=RoleManager.Access.getInstance().getRolesShort();
Role[] projectRoles = RoleManager.Access.getInstance()
.getProjectLevelRoles();
for (int i = 0; i < projectRoles.length; i++) {
Role next = projectRoles[i];
fout.write(s + s + "<role id=\"" + (next.getPersistentID())
+ "\" name=\"" + correct(next.getName()) + "\"/>\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/** Correct the charcters to be compatible with xml format */
public String correct(String s) {
String res;
if (s != null) {
res = s.replaceAll("&", "&");
res = res.replaceAll("<", "<");
res = res.replaceAll(">", ">");
res = res.replaceAll("/", "/");
res = res.replaceAll("\"", """);
} else
res = s;
return res;
}
public void save(OutputStream stream) {
save(stream, "1.12");
}
/** Save the project as XML on a stream (including the XML-prolog) */
public void save(OutputStream stream, String version) {
try {
OutputStreamWriter fout = new OutputStreamWriter(stream, "UTF-8");
save(fout, version, true);
} catch (IOException e) {
e.printStackTrace();
System.out.println(e);
// System.out.println("Error in saving the file");
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void startElement(String name, AttributesImpl attrs,
TransformerHandler handler) throws SAXException {
handler.startElement("", name, name, attrs);
attrs.clear();
}
private void endElement(String name, TransformerHandler handler)
throws SAXException {
handler.endElement("", name, name);
}
private void addAttribute(String name, String value, AttributesImpl attrs) {
attrs.addAttribute("", name, name, "CDATA", value);
}
private void emptyElement(String name, AttributesImpl attrs,
TransformerHandler handler) throws SAXException {
startElement(name, attrs, handler);
endElement(name, handler);
attrs.clear();
}
private void emptyComment(TransformerHandler handler) throws SAXException {
handler.comment(new char[] { ' ' }, 0, 1);
}
public void save(OutputStreamWriter _fout, String version,
boolean includeProlog) throws IOException,
TransformerFactoryConfigurationError, TransformerException,
246
SAXException {
try {
AttributesImpl attrs = new AttributesImpl();
StreamResult result = new StreamResult(_fout);
SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory
.newInstance();
TransformerHandler handler = factory.newTransformerHandler();
Transformer serializer = handler.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
handler.setResult(result);
handler.startDocument();
addAttribute("name", getProject().getProjectName(), attrs);
addAttribute("company", getProject().getOrganization(), attrs);
addAttribute("webLink", getProject().getWebLink(), attrs);
addAttribute("view-date", new GanttCalendar(area.getViewState()
.getStartDate()).toXMLString(), attrs);
// TODO: 1.11 repair saving zoom state
// addAttribute("view-zoom", "" + area.getZoom(), attrs);
addAttribute("view-index", "" + myUIFacade.getViewIndex(), attrs);
addAttribute("gantt-divider-location", ""
+ myUIFacade.getGanttDividerLocation(), attrs);
addAttribute("resource-divider-location", ""
+ myUIFacade.getResourceDividerLocation(), attrs);
addAttribute("version", version, attrs);
startElement("project", attrs, handler);
saveViews(handler);
emptyComment(handler);
saveCalendar(handler);
_save(_fout, version, false);
saveRoles(handler);
endElement("project", handler);
handler.endDocument();
_fout.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
private void saveViews(TransformerHandler handler) throws SAXException {
new ViewSaver().save(getUIFacade(), handler);
}
private void saveCalendar(TransformerHandler handler) throws SAXException {
new CalendarSaver().save(getProject(), handler);
}
private void saveRoles(TransformerHandler handler) throws SAXException {
AttributesImpl attrs = new AttributesImpl();
RoleManager roleManager = getProject().getRoleManager();
RoleSet[] roleSets = roleManager.getRoleSets();
for (int i = 0; i < roleSets.length; i++) {
RoleSet next = roleSets[i];
if (next.isEnabled()) {
addAttribute("roleset-name", next.getName(), attrs);
emptyElement("roles", attrs, handler);
}
}
//
RoleSet projectRoleSet = roleManager.getProjectRoleSet();
if (!projectRoleSet.isEmpty()) {
startElement("roles", attrs, handler);
Role[] projectRoles = projectRoleSet.getRoles();
for (int i = 0; i < projectRoles.length; i++) {
Role next = projectRoles[i];
addAttribute("id", next.getPersistentID(), attrs);
addAttribute("name", next.getName(), attrs);
emptyElement("role", attrs, handler);
}
endElement("roles", handler);
247
}
}
/**
* Save the project as XML on a writer
*
* @throws TransformerFactoryConfigurationError
* @throws TransformerFactoryConfigurationError
* @throws TransformerException
* @throws SAXException
*/
public void _save(OutputStreamWriter fout, String version,
boolean includeProlog) throws IOException,
TransformerFactoryConfigurationError, TransformerException,
SAXException {
// String space=" ";
number.clear();
// StringWriter fout = new StringWriter();
if (includeProlog) {
// write header
// fout.writeBytes("<?xml version=\"1.0\"?>\n");
fout.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
// fout.write("<!DOCTYPE project SYSTEM
// \"http://ganttproject.sourceforge.net/dtd/ganttproject.dtd\">\n\n");
fout.write("<!DOCTYPE ganttproject.sourceforge.net>\n\n");
}
// fout.write("<project name=\"" +
// correct(getProject().getProjectName()) +
// "\" company=\"" + correct(getProject().getOrganization()) +
// "\" webLink=\"" + correct(getProject().getWebLink()) +
// "\" view-date=\"" + area.getDate().toXMLString() +
// "\" view-zoom=\"" +
// area.getZoom() + "\" version=\"" + version + "\">\n");
fout.write(s + "<description>");
if (!getProject().getDescription().equals("")) {
fout.write("\n"
+ s
+ s
+ correct(replaceAll(getProject().getDescription(), "\n",
"\n" + s + s)) + "\n");
}
fout.write(s + "</description>\n\n");
lot = tree.getAllTasks();
lots = tree.getArryListTaskString(null);
// begin of tasks
// fout.write(s + "<tasks>\n");
// begin of tasks
fout.write(s + "<tasks ");
fout.write("color=\"" + ColorConvertion.getColor(area.getTaskColor())
+ "\"");
/*
* fout.write("color=\"#"); if (area.getTaskColor().getRed() <= 15) {
* fout.write("0"); }
* fout.write(Integer.toHexString(area.getTaskColor().getRed())); if
* (area.getTaskColor().getGreen() <= 15) { fout.write("0"); }
* fout.write(Integer.toHexString(area.getTaskColor().getGreen())); if
* (area.getTaskColor().getBlue() <= 15) { fout.write("0"); }
* fout.write(Integer.toHexString(area.getTaskColor().getBlue()));
* fout.write("\"");
*/
fout.write(">\n");
fout.write(s + s + "<taskproperties>\n");
writeTaskProperties(fout, Mediator.getCustomColumnsStorage());
fout.write(s + s + "</taskproperties>\n");
cpt = 1;
Enumeration children = ((DefaultMutableTreeNode) tree.getJTree()
.getModel().getRoot()).children();
while (children.hasMoreElements()) {
DefaultMutableTreeNode element = (DefaultMutableTreeNode) children
.nextElement();
248
writeTask(fout, /* lot.indexOf(element) */element, s + s);
}
// end of tasks
fout.write(s + "</tasks>\n\n");
// write the resources
fout.write(s + "<resources>\n");
writeResources(fout);
fout.write(s + "</resources>\n\n");
// write the assign task to user
fout.write(s + "<allocations>\n");
writeAllocations(fout);
fout.write(s + "</allocations>\n\n");
fout.write(s + "<vacations>\n");
writeVacations(fout);
fout.write(s + "</vacations>\n\n");
fout.write(s + "<taskdisplaycolumns>\n");
writeTaskDisplayColumns(fout);
fout.write(s + "</taskdisplaycolumns>\n\n");
fout.write(s + "<previous>\n");
writePreviousStateTasks(fout);
fout.write(s + "</previous>\n\n");
// write the assign task to user
// end of project
// fout.write("</project>\n");
// fout.close();
//
}
IGanttProject getProject() {
return myProject;
}
UIFacade getUIFacade() {
return myUIFacade;
}
}
i18n.properties
about=$About
add=Add
addBlankLine=Insert a blank line
addCustomColumn=New custom column
advancement=Progress
appliTitle=GanttProject
apply=Apply
assignTo=Assign To
authors=Authors
automaticLaunch=Automatic properties launch
availableToolBar=Available toolbar buttons
back=< Back
backDate=Previous
boolean=Boolean
border3D=3D borders
budget=Budget
buttonIcon=Icons
buttonIconText=Icons and text
buttonText=Text
calendars=$Calendars
249
cancel=Cancel
centerOnSelectedTasks=Center on selected tasks
chartOptions=Chart options
chef=Chef
chooseDate=Choose a date
choosePaperFormat=Paper format
choosePublicHoliday=Choose a public holidays calendar
chooseRoleSets=Choose role sets
chooseWeekend=Choose weekend
close=Close
colContact=Contact
colMail=Mail
colName=Name
colPhone=Phone
colRole=Default role
colorButton=Color
colors=Colors
coma=Comma
comparePrev=Compare to previous
confirm=Acknowledgment \
confirmFTPTransfer_1=Do you want to transfer the current project to
confirmFTPTransfer_2=This may take some time!
coordinator=Coordinator
copy=Copy
copy2=Copy
costs=Costs
createNewProject=Create new project
createNewTask=New task created
createTask=$New Task...
criticalPath=Critical path
csvexport=CSV text export
currentToolBar=Current toolbar buttons
customColumns=Custom Columns
cut=Cut
dataBase=$Data-base
date=Date
dateOfBegining=Begin date
dateOfEnd=End date
days=Day(s)
daysOff=Days off
dedentTask=Unindent
default=Default
defaultColor=Default
defaultDirectory=Default Directory
defaultTaskColor=Default task color
defaultValue=Default value
250
delay=Delay
delete=Delete
deleteCalendar=Delete Calendar
deleteCost=Delete Cost
deleteCustomColumn=Delete custom column
deleteHuman=$Delete Resource
deleteTask=$Delete Task...
depends=Depends
description=Description
novo=New
didYouKnow=Did you know ...
displayAll=Display all
displayHiddenTasks=Display hidden tasks
displayWholeProject=Display whole project
dotComa=Semicolon
double=Double
doubledot=Colon
down=Down
downTask=Down
dragTime=Could drag time on chart
duration=Duration
earlierTasks=Previous tasks (earlier)
earliestBegin=Earliest begin
edit=$Edit
editCalendars=$Edit Calendars
editPublicHolidays=Edit public Holidays
editingParameters=Edit parameters
efficency=Efficiency
end=End
error=Error
errorFTPConnection=The connection to your FTP-server could not be established!
export=$Export
exportAborted=Export aborted
exportError=Export aborted
exportSuccess=Export successful
file=File
fileFromServer=File path on web server
filtercsv=CSV documents (csv)
filterfig=XFig images (fig)
filtergan=Projects (xml, gan)
filterhtml=Web pages (html, htm)
filterjpg=JPG images (jpg, jpeg)
filterpdf=PDF documents (pdf)
filterpng=PNG images (png)
filterxsl=XSL documents (xsl)
finishfinish=Finish-Finish
251
finishstart=Finish-Start
fixedDate=Fixed date
fixedWidth=Fixed width
forwardDate=Next
ftpdirectory=subdirectory
ftpexport=FTP-server-settings
ftppwd=password
ftpserver=server-URL
ftpuser=username
gantt=Gantt
ganttChart=Gantt Chart
ganttReport=GanttProject Report
ganttprojectFiles=GanttProject files
general=General
goTo=Go to
help=$Help
hideTask=Hide selected tasks
hight=High
home=Home
htmlexport=HTML export
human=$Resources
id=ID
impex.html.description=HTML Report
impex.image.description=Raster image file
impex.msproject.description="Microsoft Project files"
import=$Import
importCalendar=Import Calendars
importResources=Import Resources...
importerChooserPageTitle=Select importer
importerFileChooserPageTitle=Select file to import from
indentTask=Indent
integer=Integer
javadoc=Javadoc
jinfos=Java Informations
jpgexport=JPG export
landscape=Landscape
language=Language
languages=Languages
lastOpen=Recent Projects
laterTasks=Previous tasks (later)
left=Left
length=Duration
library=Library
license=License
link=Link
lockDAV=Lock WebDAV resources (maximal locking time in minutes)
252
longLanguage=English
looknfeel=Appearance
low=Low
mail=Mail
manual=$Manual
meetingPoint=Milestone
motherTask=Parent task
mpxLanguageSettingComment=Choose the MS Project language version that is used
mpxLanguageSettings=MPX language settings
mpxLanguageSettingsComment=Choose the MS Project language version that is used
msg1=Do you want to save the project first?
msg10=Could not save to the specified path.\n\
Please select a path, for which you have write permissions.
msg11=Could not load from the specified path.\n\
Please select a path, for which you have read permissions.
msg12=An error occured, while saving the file. Retry?
msg13=Could not open the file in exclusive mode.\n\
Do you want to open a copy of the file?
msg14=The specified path is currently locked.\n\
Please select another path.
msg15=For export in PDF documents, you need\n\
the fop, batik and avalon libraries on your classpath\n\
(http://xml.apache.org/fop)
msg16=Please enter numerical characters!
msg17=Do you want to merge with the current project?
msg18=already exists.\n\
Do you want to overwrite?
msg19=Really delete the selected tasks?
msg2=Unable to open the file\
msg20=The panel contains unsaved modifications.\n\
Do you want to save changes before exit?
msg21=Selection is empty
msg22=Selection must contain at least two tasks
msg23=Do you really want to delete the assignment :
msg24=Non valid dates
msg25=Really delete the selected previous state?
msg3=Really delete the task\
msg4=Cannot invoke a browser.\n\
Please Direct your browser manually to:\n\
http://ganttproject.sourceforge.net
msg5=Cannot invoke a browser.\n\
Please Direct your browser manually to:\n\
../doc/index.html
msg6=Really delete the entry for\
msg7=Malformed URL
msg8=Unable to open the file
253
msg9=Unable to find the file
name=Name
narrowChart=Narrow chart
newCalendar=New Calendar
newCost=New Cost
newCustomColumn=New custom column
newHuman=$New Resource
newProject=$New...
newProject2=New project
newTask=New task
next=Next >
nextMonth=Next month
nextYear=Next year
no=No
none=none
normal=Normal
notes=Notes
notesFor=Notes for\
notesTask=Edit Notes...
of=of
ok=Ok
openFromServer=$Open from a server...
openFromdataBase=$Open from a data-base
openProject=$Open...
openWebLink=Open the web link
opening=Opening
option.down.label=Below
optionAdvanced.label="TO BE TRANSLATED"
option.exporter.title=Select exporter
option.exporter.html.advanced.label=HTML
option.impex.image.fileformat.label=File format
option.impex.msproject.fileformat.label=File format
option.impex.msproject.fileformat.label=File format
option.impex.msproject.mpx.language.label=Choose MPX language
option.left.label=Left
option.projectDates.label=Project start/end dates
option.right.label=Right
option.up.label=Above
optionGroup.ganttChartColors.label=Colors
optionGroup.ganttChartDetails.label=Details
optionGroup.exporter.html.label=HTML
optionPage.ganttChart.description=
optionPage.ganttChart.title=Gantt chart settings
optionValue.advancement.label=Task progress
optionValue.coordinator.label=Task coordinator
optionValue.down.label=Show below task bar
254
optionValue.id.label=Task ID
optionValue.impex.image.fileformat.jpeg.label=JPEG
optionValue.impex.image.fileformat.png.label=PNG
optionValue.impex.msproject.fileformat.mpp.label=MPP (proprietary binary format)
optionValue.impex.msproject.fileformat.mpx.label=MPX (ASCII text file)
optionValue.impex.msproject.fileformat.mspdi.label=MSPDI (MS Project XML format)
optionValue.left.label=Show on the left side of task bar
optionValue.length.label=Task duration
optionValue.name.label=Task name
optionValue.off.label=Do not show
optionValue.predecessors.label=Predecessors
optionValue.projectDates.label=Show
optionValue.resources.label=Assigned resources
optionValue.right.label=Show on the right side of task bar
optionValue.taskDates.label=Task start/end dates
optionValue.up.label=Show above task bar
organization=Organization
other=Other
pageNumber=Number of pages:
paperSize=Paper size:
parameters=Parameters
password=Password
paste=Paste
pdfexport=PDF export
personData=Persondata
pertChartLongName=PERT chart
pertChartShortName=PERT
pertCpm=PERT/CPM
pngexport=PNG export
portrait=Portrait
predecessors=Predecessors
preferences=Customize
prevMonth=Previous month
prevYear=Previous year
preview=Pre$view before print
previewBar=Preview
previousStates=Previous states
previousTasks=Previous tasks
printProject=$Print...
priority=Priority
project=$Project
projectCalendar=$Project Calendar
projectDates=Begining and end project's dates
projectProperties=Properties...
projectTask=PRoject
propertiesFor=Properties for
255
propertiesHuman=Human $Properties
propertiesTask=Task $Properties...
publishToWeb=Publish To Web
punctuationSpace=
putDate=Put the date and the time
question=Question
quit=$Quit
redLine=Red line for today
redo=Redo
refresh=Refresh
removeRelationShip=Remove the Relationship
removeResources=Remove resources
rename=Rename
report=Report
reportTaskCost=Report: Costs x Task
reportCostResume=Report: Cost Resume
resAnalysis=analysis
resDeveloper=developer
resDocTranslator=doc translator
resDocWriter=doc writer \
resFields=Resource fields
resGraphicDesigner=graphic designer
resNoSpecificRole=no specific role
resPackager=packager (.rpm, .tgz, ...)
resProjectManager=project manager
resTester=tester
resUndefined=undefined
resWebDesigner=web designer
reset=Reset
resetColor=Click here to reset color to default value.
resourceData=Resourcedata
resourceRole=Resource role
resourcename=Resource Name
resources=Resources
resourcesChart=Resources Chart
resourcesList=Resources List
resourcesOverload=Resources (overload)
resourcesUnderload=Resources (underload)
restoreDefaults=Restore defaults
right=Right
role=Role
roleSet.Default.displayName=Default
roleSet.SoftwareDevelopment.displayName=Software Development
save=Save
saveAsProject=Save $As...
saveCurrent=Save state
256
saveProject=$Save
saveToDataBase=$Save to a data-base
saveToServer=$Save to a server...
saving=Saving
selectColor=Select Color...
selectDays=Select Days of week
selectProjectDomain=Select your project domain
selectProjectWeekend=Configure weekends and public holidays
selectThemeDirectory=Select the theme directory
selectThemeFile=Select the theme file
sendMail=Send an e-mail
separated=Separated
separatedFields=Separated fields
separator=Separator
setEndDate=Set end date
setStartDate=Set start date
settings=$Settings
settingsAbout=This dialog shows information about GanttProject\
settingsAuthors=Thanks a lot for all persons, who help in improving GanttProject (developers, translators, testers, ...)
settingsCVSExport=Parameters for exporting the project in the CSV text format.
settingsDefaultColor=The default colors are used for the creation of new tasks.
settingsExport=Properties for the chart export.
settingsFTPExport=Configure access to your FTP-server. This data is used to publish your projects to your project to your web-server. If you specify a subdirectory, it must exist on the server.
settingsHTMLExport=Theme directory for the HTML export. You can download some themes from the GanttProject web site or create your own themes.
settingsJavaInfos=Here are some informations about your Java system.
settingsLanguages=Choose the language you want to use for GanttProject.
settingsLibrary=Here is a list of the different libraries included in GanttProject.
settingsLicense=GanttProject is under the GPL license.
settingsLooknFeel=Choose the look'n'feel you want to use for GanttProject.
settingsPDFExport=Xsl-fo file for pdf document export. You can download some themes from the GanttProject web site or create your own themes.
settingsParameters=Edit the parameters for GanttProject's user interface.
settingsPreferences=Editing the preferences
settingsProject=Edit the project properties.
settingsReport=Generate Reports.
settingsRoles=Here, you can edit and create new functions for the resources of your project.
settingsWelcome=Welcome to the settings panel. Here you can edit the parameters for GanttProject and for your project.
shape=Shape
shortDescription=Description
shortLanguage=en
show=Show
showHiddens=Show hidden buttons
showStatusBar=Show the status bar
showTipsOnStartup=Show tips on startup
space=Space
257
start=Start
startfinish=Start-Finish
startstart=Start-Start
step=Step
success=Success
successFTPConnection=The connection to your web-server could be successfully established!
successFTPTransfer=All files have been successfully transfered to your web-server!
successors=Successors
tableColBegDate=Begin date
tableColCompletion=Completion
tableColCoordinator=Coordinator
tableColDuration=Duration
tableColEndDate=End date
tableColID=ID
tableColInfo=Info
tableColName=Name
tableColPredecessors=Predecessors
tableColPriority=Priority
tableColResourceEMail=e-mail
tableColResourceName=Name
tableColResourcePhone=Phone
tableColResourceRole=Default role
tableColResourceRoleForTask=Assignment role
tableColType=Type
task=$Tasks
taskDates=Begining and end task's dates
taskFields=Task Fields
taskNamePrefix=Task name prefix
taskViewPreferences=Task view preferences
taskname=Task name
tasksList=Tasks List
testFTPConnection=Test the FTP connection
text=Text
textFiles=Text files (*.txt)
textSeparator=Text separator
tips1=It is possible to move the entire project by dragging the project with the middle mouse button.
tips10=You can organise your tasks by arranging them in a hierarchy using the "Indent" and "Unindent" functions.
tips11=Ganttproject offers the possibility to publish a report as pdf format. You need the fop library and the batik library from the Apache foundation on your classpath. The export uses XSL-FO technology to create the document. There is a default xslfo file in the ganttproject library, but you can edit your own xslfo file to customize the export.
tips12=By using the import menu, you can directly import a list of tasks from a text file.\n\
Each row is inserted into the project as a new task name.
tips13=The selection of multiple tasks on the tree is now possible for some actions like up, down, delete, indent, unindent and unlink.
tips14=If you've entered the email of the resource, you can directly send an email by the GanttProject menu.
tips15=You can specify a prefix for task names, which is used when you create a new task. It can help you to automate the generation of new tasks.\n\
Edit -> Settings -> General -> Paremeters -> Task name prefix
258
tips16=You can hide columns in the 'Gantt View' by right clicking the table header.
tips17=You can customize the Gantt chart view by right clicking in the Gantt view. Tasks names, dates, lengths, completion percentage or even resources could be displayed directly on the chart.
tips18=GanttProject provides some MS Project compatibility features. You can both import and export MS Project files using the export and import features and choosing the MS Project file filter.
tips19=In the Gantt view you can select several tasks by holding down the Ctrl or Shift key.
tips2=You can directly edit the name of the task, on the tree. Press F2 key to enter edition, change the name and press enter.
tips20=You can add custom columns in the tasks table by right clicking the table header and click 'Add a new custom column'.\n\
You can add and remove custom columns via the 'Custom colums' tab in the task properties dialog.
tips21=GanttProject enables you to highlight the critical path of the current project. Click on the critical path icon.
tips3=To export the project into HTML web pages, GanttProject uses XSL transformations. You can create customized xsl files, put them on a directory and use the new theme for your export.
tips4=The "Automatic properties launch" option can be used, if you prefer the program to automatically open the properties dialog for newly created tasks.
tips5=The "Import resources" command enables you to load resources from another project and put them into the current project.
tips6=GanttProject supports working with project plans, that are stored on web servers. If such a server supports WebDAV, you can even save/publish a project plan to it. Of course you must have write permissions for this, so you may have to enter a username and a password for your server. Then you could work at distance by using internet connection and share a common project plan with your team.\n\
\n\
If you want to know more about WebDAV see:\n\
http://www.webdav.org/
tips7=GanttProject is an OpenSource project and is developed by a community of developers all over the world. You can find some statistics, and information at the sourceforge page:\n\
http://sf.net/projects/ganttproject
tips8=The relationships between two tasks have several forms: Finish-Start, Finish-Finish, Start-Finish and Start-Start. This possibility could help you to edit a realistic plan for your projects.
tips9=You can customize the roles for resources on the settings dialog box. The roles are saved on the XML file as <roles> entry.
tipsOfTheDay=$Tips of the day
total=Total
type=Type
typeClass=Type
undo=Undo
undoNumber=Number of undos
unit=Unit
unitsPerDay=Maximum units per day
unlink=Unlink
up=Up
upTask=Up
useSmalIcons=Use small icons
userName=Username
value=Value
view=View
warning=Warning
web=Web
webLink=Web Link
webPage=$Web Page
webServer=$Web Server
259
week=Week\
weekEnd=Week End
welcome=Welcome to GanttProject
wholeProject=Whole project
widenChart=Widen chart
xfigexport=XFIG export
xslDirectory=Default theme directory\
xslFoFile=Default XSL-FO file
yes=Yes
zoom=Zoom
zoomFit=Fit
zoomIn=Zoom In
zoomOut=Zoom Out
i18n_pt_BR.properties about=$Sobre...
add=Adicionar
advancement=Avan\u00e7o
appliTitle=GanttProject
aplly=Aplicar
authors=Autores
automaticLaunch=Lan\u00e7amento autom\u00e1tico de propriedades
assignTo=Atribuir \u00e0
back=< Anterior
backDate=Anterior
border3D=Bordas 3D
budget=Or\u00e7amento
buttonIcon=\u0049cones
buttonIconText=\u0049cones e texto
buttonText=Texto
calendars=$Calend\u00e1rio
cancel=Cancelar
chef=Chefe
chooseDate=Escolha uma data
choosePublicHoliday=Escolha um calendario de feriados publicos
chooseRoleSets=Escolha o conjunto de fun\u00e7oes
chooseWeekend=Escolha os dias de folga
close=Fechar
colContact=Contato
colMail=Mail
colName=Nome
colorButton=Cor
260
colors=Cores
colPhone=Telefone
colRole=Fun\u00e7\u00e3o
coma=v\u00edrgula
copy=Copiar
copy2=Copiar
costs=Custos
csvexport=Exporta\u00e7\u00e3o de texto CSV
createTask=$Nova tarefa...
createNewTask=Nova tarefa criada
createNewProject=Criar novo projeto
cut=Cortar
customColumns=Colunas Customizadas
date=Data
dataBase=Base de dados
dateOfBegining=Data de in\u00edcio
dateOfEnd=Data de t\u00e9rmino
daysOff=Ferias
defaultColor=Cor padr\u00e3o
defaultDirectory=Diret\u00f3rio padr\u00e3o
defaultTaskColor=Cor de tarefa padr\u00e3o
delete=Excluir
deleteCalendar=Apague calend\u00e1rio
deleteCost=Excluir Custo
deleteHuman=Excluir pessoa
deleteTask=Excluir tarefa
dedentTask=Recuar
depends=Depend\u00eancias
description=Descri\u00e7\u00e3o
didYouKnow=Voc\u00ea sabia...
downTask=Abaixo
dotComa=Ponto e v\u00edrgula
doubledot=Dois pontos
dragTime=Poderia arrastar o tempo no diagrama
edit=Editar
editCalendars=$Edi\u00e7\u00e3o do calend\u00e1rio
editingParameters=Editar par\u00e2metros
efficency=Efici\u00eancia
end=Fim
error=Erro
export=Exportar
file=Arquivo
fileFromServer=Caminho do arquivo no servidor web
261
filtercsv=Documento CSV
filterfig=Imagens XFig
filterjpg=Imagens JPG
filterpng=Imagens PNG
filterpdf=Documentos PDF
filterhtml=P\u00e1ginas Web
filtergan=Arquivos GanttProject (xml, gan)
filterxsl=Documentos XSL
finishfinish=Final-Final
finishstart=Final-In\u00edcio
fixedDate=Data fixa
fixedWidth=Largura fixa
forwardDate=Pr\u00f3ximo
gantt=Gantt
ganttChart=Diagrama Gantt
ganttReport=Relat\u00f3rio GanttProject
general=Geral
help=Ajuda
hight=Alta
home=Home
htmlexport=Exportar HTML
human=Pessoa
id=ID
importCalendar=Importar Calend\u00e1rios
indentTask=Avan\u00e7ar
jinfos=Informa\u00e7\u00f5es Java
importResources=Importar Recursos...
import=$Importar
javadoc=Javadoc
jpgexport=Exportar JPG
landscape=Paisagem
language=Linguagem
languages=Linguagens
lastOpen=\u00daltimos abertos
length=Dura\u00e7\u00e3o
library=Biblioteca
license=Licen\u00e7a
link=Link
lockDAV=Bloqueia recurso WebDAV (em minutos)
looknfeel=Apar\u00eancia
longLanguage=Portugu\u00eas do Brasil
262
low=Baixa
mail=Mail
manual=$Manual
motherTask=Tarefa-m\u00e3e
meetingPoint=Ponto de encontro
msg1=Voc\u00ea gostaria de salvar o projeto antes?
msg2=N\u00e3o consegui abrir o arquivo
msg3=Deseja realmente deletar a tarefa
msg4=N\u00e3o consegui abrir o navegador.\n Abra seu navegador manualmente em http://ganttproject.sourceforge.net
msg5=N\u00e3o consegui abrir o navegador.\n Abra seu navegador manualmente em ../doc/index.html
msg6=Deseja realmente deletar a entrada para
msg7=URL malformada
msg8=N\u00e3o consegui abrir o arquivo
msg9=N\u00e3o consegui encontrar o arquivo
msg10=N\u00e3o consegui salvar no caminho especificado.\nPor favor selecione um diret\u00f3rio no qual voc\u00ea tenha permiss\u00f5es de escrita.
msg11=N\u00e3o consegui abrir a partir do caminho especificado.\nPor favor selecione um diret\u00f3rio no qual voc\u00ea tenha permiss\u00f5es de leitura.
msg12=Um erro aconteceu ao salvar o arquivo. Tentar novamente?
msg13=N\u00e3o consegui abrir o arquivo em modo exclusivo.\nVoc\u00ea quer abrir uma c\u00f3pia deste arquivo?
msg14=O caminho especificado est\u00e1 bloqueado.\nPor favor selecione um outro diret\u00f3rio.
msg15=Para exportar um documento PDF, voc\u00ea precisa\ndas bibliotecas fop, batik e avalon em seu classpath\n(cf http://xml.apache.org/fop)
msg16=Por favor digite caracteres num\u00e9ricos!
msg17=Voc\u00ea deseja unir com o projeto atual?
msg18=J\u00e1 existe.\nVoc\u00ea deseja sobre-escrever?
msg19=Realmente deletar a tarefa selecionada?
msg20=O painel cont\u00e9m modifica\u00e7\u00f5es n\u00e3o salvas.\nVoc\u00ea gostaria de salvar as altera\u00e7\u00f5es antes de sair?
msg21=Sele\u00e7\u00e3o vazia
msg22=Sele\u00e7\u00e3o deve conter pelo menos duas tarefas
name=Nome
newCalendar=Calend\u00e1rio novo
newCost=Novo Custo
newHuman=Nova pessoa
newProject=Novo
newProject2=Novo projeto
newTask=Nova tarefa
next=Pr\u00f3ximo >
nextMonth=Pr\u00f3ximo m\u00eas
nextYear=Pr\u00f3ximo ano
no=N\u00e3o
none=Nenhuma
normal=Normal
notes=Notas
notesFor=Notas para
263
notesTask=Editar notas
ok=Ok
openFromdataBase=$Abrir de base de dados
openFromServer=$Abrir de servidor...
openProject=Abrir
openWebLink=Abrir um endere\u00e7o na rede
opening=Abrindo
organization=Organiza\u00e7\u00e3o
other=Outro
parameters=Par\u00e2metros
paste=Colar
password=Senha
pdfexport=Exportar PDF
pertCpm=PERT/CPM
personData=Dados Pessoais
pngexport=Exporta\u00e7\u00e3o PNG
portrait=Retrato
predecessors=Predecessores
preview=$Visualizar impress\u00e3o
prevMonth=M\u00eas anterior
prevYear=Ano anterior
printProject=Imprimir...
priority=Prioridade
project=Projeto
projectCalendar=$Calend\u00e1rio do projeto
projectProperties=Propriedades...
projectTask=Ponto de Encontro
propertiesFor=Propriedades de
propertiesHuman=Propriedades dos recursos
propertiesTask=Propriedades da tarefa
putDate=Coloque a data e hora
quit=Sair
question=Quest\u00e3o
redLine=Linha vermelha para hoje
removeRelationShip=Remover relacionamento
removeResources=Remover recursos
report=Relat\u00f3rio
reportTaskCost=Relat\u00f3rio: Custos x Tarefa
reportCostResume=Relat\u00f3rio: Resumo de Custos
resAnalysis=Analista
resDeveloper=Desenvolvedor
resDocTranslator=Tradutor de documenta\u00e7\u00e3o
264
resDocWriter=Escritor de documenta\u00e7\u00e3o
resetColor=Clique aqui para restaurar a cor ao valor padr\u00e3o.
resFields=Campos de recursos
resGraphicDesigner=Designer Gr\u00e1fico
resNoSpecificRole=Sem papel espec\u00edfico
resourceData=Dados do recurso
resourcename=Nome do recurso
resourceRole=Papel do recurso
resources=Recursos
resourcesOverload=Recursos (sobrecarga)
resourcesChart=Diagrama de recursos
resourcesList=Lista de recursos
resPackager=Empacotador (.rpm, .tgz ...)
resProjectManager=Gerente de Projeto
resTester=Testador
restoreDefaults=Restaurar padr\u00f5es
resUndefined=Indefinido
resWebDesigner=Web Designer
role=Fun\u00e7\u00e3o
roleSet.Default.displayName=Padr\u00e3o
roleSet.SoftwareDevelopment.displayName=Desenvolvimento de Software
saveAsProject=Salvar como
saveProject=Salvar
saveToDataBase=$Salvar em base de dados
saveToServer=$Salvar em servidor...
saving=Salvando
selectColor=Selecione a cor
selectDays=Selecione dias da semana
selectThemeDirectory=Selecione o diret\u00f3rio de temas
selectThemeFile=Selecione o arquivo de temas
selectProjectDomain=Selecione o seu dom\u00ednio de projeto
selectProjectWeekend=Configure feriados e dias de folga
sendMail=Enviar um e-mail
separated=Separados
separatedFields=Campos separados
settings=$Configura\u00e7\u00f5es
settingsAbout=Este di\u00e1logo mostra informa\u00e7\u00f5es sobre GanttProject
settingsAuthors=Muito obrigado a todas as pessoas que ajudaram no melhora do GanttProject (desenvolvedores, tradutores, testadores...)
settingsCVSExport=Par\u00e2metros para exporta\u00e7\u00e3 do projeto em texto formato CVS.
settingsDefaultColor=A c\u00f4r padr\u00e3o \u00e9 usada na cria\u00e7\u00e3o de uma nova tarefa.
settingsExport=Propriedades para a exporta\u00e7\u00e3o.
settingsJavaInfos=Aqui h\u00e1 algumas informa\u00e7\u00f5 sobre o seu sistema Java.
settingsHTMLExport=Diret\u00f3rio de temas para a exporta\u00e7\u00e3o HTML. Voc\u00ea pode baixar outros temas da p\u00e1gina GanttProject ou criar seus pr\u00f3prios temas.
265
settingsLanguages=Escolha a linguagem que voc\u00ea deseja usar no GanttProject.
settingsLibrary=Aqui h\u00e1 uma lista de diferentes bibliotecas inclu\u00eddas no GanttProject.
settingsLicense=GanttProject est\u00e1 sob licen\u00e7a GPL.
settingsLooknFeel=Escolha a apar\u00eancia que voc\u00ea deseja usar no GanttProject.
settingsParameters=Edite os par\u00e2metros para a interface de usu\u00e1rio do GanttProject.
settingsPreferences=Editando as prefer\u00eancias
settingsPDFExport=Arquivo Xsl-fo para a exporta\u00e7\u00e3o de documentos pdf. Voc\u00ea pode baixar outros temas da p\u00e1gina GanttProject ou criar seus pr\u00f3prios temas.
settingsProject=Edite as propriedades do projeto.
settingsReport=Gerar Relat\u00f3rio.
settingsRoles=Aqui, voc\u00ea pode editar e criar novas fun\u00e7\u00f5es para os recursos do seu projeto.
settingsWelcome=Bem vindo ao painel de ajustes. Aqui voc\u00ea pode editar os par\u00e2metros para GanttProject e para seus projetos.
shape=Forma
shortDescription=Descri\u00e7\u00e3o
shortLanguage=pt_BR
showTipsOnStartup=Mostrar dicas ao iniciar
show=Mostra
showStatusBar=Mostra a barra de acompanhamento
space=Espa\u00e7o
successors=Sucessores
start=In\u00edcio
startfinish=In\u00edcio-Fim
startstart=In\u00edcio-In\u00edcio
tableColBegDate=Data de In\u00edcio
tableColEndDate=Data de Fim
tableColName=Nome
tableColPredecessors=Predecessor
tableColPriority=Prioridade
tableColResourceEMail=e-mail
tableColResourceName=Nome
tableColResourcePhone=Telefone
tableColResourceRole=Fun\u00e7\u00e3o padr\u00e3oo
tableColResourceRoleForTask=Fun\u00e7\u00e3o estabelecida
tableColType=Tipo
task=Tarefa
taskFields=Campos de tarefas
tasksList=Lista de tarefas
taskname=Nome da tarefa
taskNamePrefix=Prefixo do nome da tarefa
textSeparator=Separador de textos
tips1=\u00c9 poss\u00edvel mover todo o projeto arrastando o projeto com o bot\u00e3o do meio do mouse.
tips2=Voc\u00ea pode editar o nome de uma tarefa diretamente, na \u00e1rvore. Pressione F2 para editar, modifique o nome e pressione enter.
tips3=Para exportar o projeto em p\u00e1ginas HTML, GanttProject usa transforma\u00e7\u00f5es XSL. Voc\u00ea pode criar seus pr\u00f3prios arquivos xsl e us\u00e1-los como tema.
266
tips4=A op\u00e7\u00e3o "Lan\u00e7amento autom\u00e1tico de propriedades" pode ser usada, se voc\u00ea preferir que o programa automaticamente abra o dialogo de propriedades para a tarefa criada.
tips5=O comando "Importar recursos" capacita voc\u00ea carregar recursos de outro projeto e coloc\u00e1-los no projeto corrente.
tips6=GanttProject suporta armazenar projetos em servidores web. Se tal servidor suporta WebDAV, voc\u00ea pode salvar/publicar um projeto nele. Claro que voc\u00ea deve possuir permiss\u00e3o de escrita, ent\u00e3o voc\u00ea deve entrar com o nome de usu\u00e1rio e senha para o seu servidor. Ent\u00e3o voc\u00ea pode trabalhar \u00e0 dist\u00e2ncia usando uma conex\u00e3o da internet e compartilhando um projeto com a sua equipe de desenvolvimento.\n\nSe voc\u00ea quiser conhecer mais sobre WebDAV visite htttp://www.webdav.org/
tips7=GanttProject \u00e9 desenvolvido como OpenSource (programa aberto ou livre) por uma comunidade de desenvolvedores ao redor do mundo. Voc\u00ea pode achar algumas estat\u00edsticas e informa\u00e7\u00f5es na p\u00e1gina sourceforge: http://sourceforge.net/projects/ganttproject
tips8=O relacionamento entre duas tarefas possui muitas formas: Final-In\u00edcio, Final-Final, In\u00edcio-Final e In\u00edcio-In\u00edcio. Isto possibilita voc\u00ea editar um plano real\u00edstico para os seus projetos.
tips9=Voc\u00ea pode editar suas fun\u00e7\u00f5es de dados de pessoas na caixa de di\u00e1logo de configura\u00e7\u00f5es. As fun\u00e7\u00f5es s\u00e3o salvadas no arquivo XML como entrada <roles>.
tips10=Voc\u00ea pode organizar suas tarefas em hierarquias usando os bot\u00f5es "Avan\u00e7ar", "Recuar", "Acima" e "Abaixo".
tips11=Ganttproject oferece a possibilidade de publicar um relat\u00f3rio com o formato PDF. Voc\u00ea necessita da biblioteca fop e a biblioteca batik da funda\u00e7\u00e3o Apache em sua classpath. A exporta\u00e7\u00e3o usa a tecnologia ZSL-FO para criar o documento. H\u00e1 um arquivo xslfo padr\u00e3o na biblioteca ganttproject mas voc\u00ea pode editar o seu arquivo xslfo para personalizar a exporta\u00e7\u00e3o.
tips12=Usando o menu de importa\u00e7\u00e3o, voc\u00ea pode diretamente importar uma lista de tarefas a partir de um arquivo texto.\nCada linha \u00e9 inserida no projeto como um novo nome de tarefa.
tips13=A sele\u00e7\u00e3o m\u00faltipla em uma \u00e1rvore est\u00e1 habilitada para algumas a\u00e7\u00f5es como acima, abaixo, apagar, avan\u00e7ar, recuar e desvincular.
tips14=Se voc\u00ea colocou o e-mail de um recurso, voc\u00ea pode enviar diretamente um e-mail pelo menu do GanttProject.
tips15=O prefixo do nome da tarefa \u00e9 usado quando voc\u00ea cria uma nova tarefa. Ela pode ajudar na gera\u00e7\u00e3o autom\u00e1tica de nomes de tarefa.
tipsOfTheDay=$Dicas do dia
type=Tipo
unlink=Desvincular
unit=Unidade
unitsPerDay=Unidades m\u00e1ximas por dia
upTask=Acima
userName=Nome de usu\u00e1rio
useSmalIcons=Use \u00edcones pequenos
value=Valor
view=Vizualiza\u00e7\u00e3o
warning=Aten\u00e7\u00e3o
webLink=Liga\u00e7\u00e3o de p\u00e1gina
webPage=P\u00e1gina web
web=Web
webServer=Servidor Web
week=Semana
welcome=Bem vindo ao GanttProject
xfigexport=Exporta\u00e7\u00e3o XFIG
xslDirectory=Diret\u00f3rio padr\u00e3o de temas XSL
267
xslFoFile=Arquivo padr\u00e3o xsl-fo
yes=Sim
zoomFit=Ajustar
zoomIn=Ampliar
zoomOut=Reduzir
Top Related