Desenvolvimento de um Sistema de planejamento e

Transcription

Desenvolvimento de um Sistema de planejamento e
UNIVERSIDADE FEDERAL DE SANTA CATARINA
Desenvolvimento de um Sistema de planejamento e
acompanhamento técnico e financeiro de projetos
Luis Henrique Spoladore Amaral
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.
2
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
3
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
4
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
5
Lista de Figuras
Figura 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
6
Lista de Tabelas
Tabela 1: Requisitos no software Open Benchwork ................................................. 19
Tabela 2: Requisitos no software GanttProject .......................................................... 21
Tabela 3: Requisitos no software dotProject .............................................................. 22
7
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.
8
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.
9
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.
10
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.
11
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]:
12
• 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]..
13
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.
14
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
15
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.
16
• 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) ;
17
•
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.
18
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
RF01
RF02
RF03
RF04
Sim
Sim
Sim
Sim
RF05
Sim
RF06
RF07
RF08
RF09
RF10
Sim
Sim
Sim
Sim
Não
Observações
Permite a definição de descrição dos projetos.
Permite a definição de tarefas e suas interdependências.
Permite a definição e alocação de recursos para as tarefas.
Permite a definição de custos para as tarefas, através dos
custos dos recursos a ela associados.
Permite o acompanhamento do andamento do projeto, a
visualização e manutenção dos estados das tarefas, seus
prazos e custos.
Permite a visualização de Gantt Chart.
Permite a visualização de Pert Chart.
Permite a visualização do caminho crítico.
Possui suporte a WBS - Work Breakdown Structure.
Não gera relatório de atividades.
19
RF11
Não
Não gera relatório de custos.
RNF01
RNF02
RNF03
Sim
Não
Não
RNF04
Sim
RNF05
Sim
RNF06
RNF07
Não
Não
RNF08
RNF09
Não
Sim
O sistema é executado localmente.
Não permite execução em rede nem publica relatórios web.
A interface não é intuitiva, exigindo esforços para o
aprendizado.
Após o estudo e compreensão da interface, o usuário
consegue executar a maioria das operações com bastante
agilidade.
O código fonte é disponibilizado, porem em linguagem
proprietária.
O sistema é executado apenas na plataforma Windows.
Os dados são armazenados em arquivos proprietários e a
opção para salvar em XML, na versão testada, não
funcionava.
Não possui tradução para a língua portuguesa.
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- laVallee 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
20
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
RF02
RF03
RF04
RF05
Sim
Sim
Sim
Não
Sim
Permite a definição de descrição dos projetos.
Permite a definição de tarefas e suas interdependências.
Permite a definição e alocação de recursos para as tarefas.
Não permite a definição de custos para as tarefas.
Permite o acompanhamento do andamento do projeto, a
visualização e manutenção dos estados das tarefas, seus
prazos e custos.
Permite a visualização de Gantt Chart.
Permite a visualização de Pert Chart.
Permite a visualização do caminho crítico.
Não possui suporte a WBS - Work Breakdown Structure.
Permite gerar relatório de atividades, através de arquivos
HTML, porem nao muito satisfatório.
Não permite gerar relatório de custos.
RF06
RF07
RF08
RF09
RF10
Sim
Sim
Sim
Nao
Sim
RF11
Não
RNF01
RNF02
Sim
Sim
RNF03
Sim
RNF04
RNF05
RNF06
RNF07
RNF08
RNF09
Sim
Sim
Sim
Sim
Sim
Sim
5.3
dotProject
O sistema é executado localmente.
Permite execução em rede através de um servidor WebDAV.
Permite exportar relatórios em formato de paginas web.
A interface é bem intuitiva, não exigindo esforços para o
aprendizado.
Tem excelente usabilidade a interface so sistema.
O código fonte é disponibilizado, em linguagem Java.
O sistema é executado em plataforma Windows e Linux.
Os dados são armazenados em arquivos XML.
Possui tradução para a língua portuguesa.
A instalação é simples, guiado através de um wizard ou
executado diretamente sem instalação.
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
21
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
RF01
RF02
RF03
RF04
Sim
Sim
Sim
Sim
RF05
Sim
RF06
RF07
RF08
RF09
RF10
RF11
Sim
Sim
Sim
Nao
Sim
Não
RNF01
RNF02
Sim
Sim
RNF03
Sim
RNF04
Não
RNF05
RNF06
Sim
Sim
RNF07
RNF08
RNF09
Sim
Sim
Não
Observações
Permite a definição de descrição dos projetos.
Permite a definição de tarefas e suas interdependências.
Permite a definição e alocação de recursos para as tarefas.
Permite a definição de custos para as tarefas, através dos
custos dos recursos a ela associados.
Permite o acompanhamento do andamento do projeto, a
visualização e manutenção dos estados das tarefas, seus
prazos e custos.
Permite a visualização de Gantt Chart.
Permite a visualização de Pert Chart.
Permite a visualização do caminho crítico.
Não possui suporte a WBS - Work Breakdown Structure.
Permite gerar relatório de atividades, entre outros.
Não permite gerar relatório de custos.
O sistema é executado localmente.
Permite execução em rede através de ambiente web, esse é o
seu foco.
A interface é bem intuitiva, não exigindo esforços para o
aprendizado.
Não apresenta usabilidade na interface, característica comum
em ambiente web.
O código fonte é disponibilizado, em linguagem PHP.
O sistema é executado em plataforma Windows e Linux,
utilizando um servidor Apache.
Os dados são armazenados na base de dados MySQL.
Possui tradução para a língua portuguesa.
A instalação não é simples, exigindo a instalação do servidor
web Apache e base de dados MySQL..
22
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.
23
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
24
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
25
Figura 5 - Tela de propriedades gerais de Recurso
Figura 6 - Tela de propriedades ferias de Recurso
26
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
27
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
28
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).
29
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
30
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
31
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.
32
Figura 14 - Tela de propriedades gerais de Tarefa, agora com campo orçamento
Figura 15 - Nova Tela de custos de Tarefa
33
Figura 16 - Nova Tela para execução de relatórios
Figura 17 - Relatório de Custos por Atividade
34
Figura 18 - Relatório Financeiro
35
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.
36
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
37
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:
Início:
22/11/2006
Fim:
Início:
20/12/2006
Fim:
Início:
29/01/2007
Fim:
Início:
19/02/2007
Fim:
Início:
05/03/2007
Fim:
Início:
16/04/2007
Fim:
Início:
23/04/2007
Fim:
Início:
07/05/2007
Fim:
20/12/2006
•
Seleção de colégios beneficiados
20/12/2006
Módulo 1
•
Busca de referências bibliográficas
27/01/2007
•
Levantamento de requisitos para a ferramenta
17/02/2007
•
Avaliação de ferramentas similares
03/03/2007
Módulo 2
•
Desenvolvimento da Ferramenta
14/04/2007
Módulo 3
•
Instalação da ferramenta nos colégios
21/04/2007
•
Treinamento dos professores
05/05/2007
•
Aulas introdutórias da nos colégios
16/06/2007
38
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
39
Figura 23 - Definindo custos de tarefa
Figura 24 - Visualização do Gráfico Gantt
40
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
41
Estes recursos foram associados às tarefas.
Figura 26 - Associando recursos à Tarefa
Figura 27 - Visualização de Gráfico de Alocação de Recursos
42
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
43
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
44
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
45
Figura 32 - Relatório de Resumo de custos
Foram também publicados relatório web em um servidor FTP.
Figura 33 - Configurando Servidor FTP
46
Figura 34 - Relatório Web Gráfico de Gantt
Figura 35 - Relatório Web - Recursos
47
Figura 36 - Relatório Web - Tarefas
Dessa maneira, foi exemplificado um caso de uso da ferramenta, já com as
novas funcionalidades implementadas.
48
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.
49
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.
50
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
51
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.
52
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].
53
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.
54
[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.
55
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.163176, 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.
56
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
57
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
58
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
59
Código Fonte
Classes e arquivos criados
/**
* Exception to be thrown in several cases : A custom column
net.sourceforge.ganttproject.task.already exists (and
* someone tries to add a nex one
Cost
with the same name) A
custom column does not
* exists (and someone tried to get it) A class mismatch.
package net.sourceforge.ganttproject.task;
*
* @author LH (Luis Amaral) Oct 24, 2005
import java.util.Date;
*/
public class CostException extends Exception {
/**
public static final int ALREADY_EXIST = 0;
* This class describes a cost.
* @author Luis Amaral Oct 24, 2005
public static final int DO_NOT_EXIST = 1;
*
*/
public static final int CLASS_MISMATCH = 2;
/**
* @author luisamaral
/**
* Oct 24, 2005
* Exception type.
*/
*/
public interface Cost {
private int type = -1;
//String getId();
public CostException(int type, String message) {
super(message);
//void setId(String newId);
this.type = type;
}
String getDescription();
public int getType() {
void setDescription(String description);
return type;
}
Date getDate();
}
void setDate(Date date);
net.sourceforge.ganttproject.task
CostImpl
double getValue();
package net.sourceforge.ganttproject.task;
void setValue(double value);
import java.util.Date;
String toString();
/**
}
* This class describes a ost.
* @author Luis Amaral Oct 24, 2005
net.sourceforge.ganttproject.task. *
CostException
*/
package net.sourceforge.ganttproject.task;
60
/**
* @author luisamaral
public void setId(String newId) {
id = newId;
* Oct 24, 2005
*/
}
public class CostImpl implements Cost{
*/
/**
//private String id = null;
* Returns the default value.
*
/**
* @return The defautl value.
* The column date.
*/
*/
public String getDescription() {
return description;
private Date date = null;
}
private double value = 0;
/**
private String description = null;
* Sets the default value.
*
/**
* @param defaultValue
* Creates an instance of CustomColmn.
*
*/
*/
public CostImpl() {
public void setDescription(String description) {
this.description = description;
//this.id = id;
}
}
/**
/**
* Creates an instance of CustomColmn with a name, a type
(class) and a
* default value.
*
* @return The column name.
public Date getDate() {
return date;
}
The colmun type.
* @param colDefaultValue
*
*
The column name.
* @param colType
*
* Returns the column name.
*/
* @param colName
*
The default value to be set.
The default value.
*/
/**
* Sets the column name.
*
public CostImpl(Date date, String description, double value) {
this.date = date;
this.description = description;
this.value = value;
* @param name
*
The column name to be set.
*/
public void setDate(Date date) {
}
this.date = date;
}
/*
public String getId() {
return id;
}
/**
* Returns the column type.
*
61
* @return The column type.
import net.sourceforge.ganttproject.task.CostImpl;
*/
import net.sourceforge.ganttproject.task.Task;
public double getValue() {
import net.sourceforge.ganttproject.task.TaskManager;
return value;
}
import
net.sourceforge.ganttproject.task.dependency.TaskDependenc
yException;
/**
* Sets the column type.
*
* @param type
*
import
net.sourceforge.ganttproject.task.dependency.TaskDependenc
y;
import
net.sourceforge.ganttproject.task.dependency.constraint.Finish
StartConstraintImpl;
The column type to be set.
import org.xml.sax.Attributes;
*/
public void setValue(double value) {
this.value = value;
public class CostTagHandler
ParsingListener {
}
implements
TagHandler,
private final TaskManager myTaskManager;
/**
* Returns a string representation of the CustomColumn.
public
CostTagHandler(ParsingContext
TaskManager taskManager) {
context,
myContext = context;
*
myTaskManager = taskManager;
* @return A string representation of the CustomColumn.
}
*/
public String toString() {
return this.date + " [" + this.description + "] <" + this.value +
">";
}
}
/**
*
@see
net.sourceforge.ganttproject.parser.TagHandler#endElement(St
ring,
*
String, String)
*/
net.sourceforge.ganttproject.task.
public void endElement(String
CostMutator
sName, String qName) {
package net.sourceforge.ganttproject.task;
public interface CostMutator extends
*
if
("dependencies".equals
myDependenciesSectionStarted =
}
net.sourceforge.ganttproject.pars
er.CostTagHandler
/**
*
@see
net.sourceforge.ganttproject.parser.TagHandler#startElement(S
tring,
*
import java.util.Date;
{
*/
}
import java.util.List;
(qName))
* false; }
void commit();
import java.util.ArrayList;
String
/*
MutableCostsTaskCollection {
package net.sourceforge.ganttproject.parser;
namespaceURI,
String, String, Attributes)
*/
public void startElement(String
sName, String qName,
namespaceURI,
String
Attributes attrs) {
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttTaskRelationship;
/*
import net.sourceforge.ganttproject.task.Cost;
62
*
if
("dependencies".equals
myDependenciesSectionStarted =
(qName))
} catch (Exception e) {
{
System.out.println("Erro
na
data"
+
e.getMessage());
* true; }
*/
}
if ("cost".equals(qName)) {
cost.setDescription(attrs.getValue("description"));
/*
GanttCostStructure
gcs
=
GanttCostStructure(getContext().getTaskID(),cost);
Found
getCosts().add(gcs);
* if (!myDependenciesSectionStarted) { throw new
* RuntimeException("Invalid
'dependency' tag
file
format.
new
* without prior 'dependencies' tag"); } else {
}
*/
}
loadCost(attrs);
}
private List getCosts() {
}
return myCosts;
}
public void parsingStarted() {
}
private ParsingContext getContext() {
return myContext;
public void parsingFinished() {
}
for (int i = 0; i < getCosts().size(); i++) {
GanttCostStructure
getCosts().get(i);
gcs
=
(GanttCostStructure)
private List myCosts = new ArrayList();
myTaskManager.getTask(gcs.taskID).getCostsTaskCollection().
addCost(gcs.cost);
private ParsingContext myContext;
//System.out.println("Custo
adicionado
"
+
cost.getDescription()
+
"
"
+
myTaskManager.getTask(getContext().getTaskID()).getName()
);
private class GanttCostStructure {
public int taskID;
}
}
public Cost cost = null;
protected void loadCost(Attributes attrs) {
public GanttCostStructure(int taskID, Cost cost) {
this.taskID = taskID;
if (attrs != null) {
this.cost = cost;
}
Cost cost = new CostImpl();
}
String dateAsString = attrs.getValue("date");
}
String valueAsString = attrs.getValue("value");
try {
double
Double.parseDouble(valueAsString);
net.sourceforge.ganttproject.task.
CostsTaskCollection
value
=
cost.setValue(value);
package net.sourceforge.ganttproject.task;
} catch (NumberFormatException e) {
System.out.println("Erro
no
e.getMessage());
valor"
+
import net.sourceforge.ganttproject.resource.ProjectResource;
import java.util.Collection;
}
try {
Date
date
Date(Long.parseLong(dateAsString));
cost.setDate(date);
=
/**
new
* @author lh
*/
63
public
interface
CostsTaskCollection
MutableCostsTaskCollection {
extends
//private ResourceManager myResourceManager;
Cost[] getCosts();
public CostsTaskCollectionImpl(TaskImpl task) {
Collection getCollection();
myTask = task;
//myResourceManager = resourceManager;
double getTotalCosts();
Cost getCost(String costId);
}
private CostsTaskCollectionImpl(
CostsTaskCollectionImpl collection) {
CostMutator createMutator();
myTask = collection.myTask;
Cost[] costs = collection.getCosts();
void clear();
for (int i = 0; i < costs.length; i++) {
}
Cost next = costs[i];
Cost copy = new CostImpl();
interface MutableCostsTaskCollection {
copy.setDate(next.getDate());
void addCost(Cost cost);
copy.setDescription(next.getDescription());
copy.setValue(next.getValue());
void deleteCost(Cost cost);
addCost(copy);
}
//Cost[] getCachedCosts();
}
}
net.sourceforge.ganttproject.task.
CostsTaskCollectionImpl
public void clear() {
Cost[] costs = getCosts();
for (int i = 0; i < costs.length; i++) {
package net.sourceforge.ganttproject.task;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Collection;
import java.util.HashMap;
costs[i] = null;
}
}
public Cost[] getCosts() {
return (Cost[]) myCosts.values().toArray(
import java.util.List;
import java.util.Map;
import net.sourceforge.ganttproject.resource.ProjectResource;
import
net.sourceforge.ganttproject.resource.ResourceManager;
new Cost[myCosts.size()]);
}
public double getTotalCosts() {
double total = 0;
Cost[] costs = this.getCosts();
import net.sourceforge.ganttproject.roles.Role;
for (int i = 0; i < costs.length; i++) {
total+=costs[i].getValue();
}
class CostsTaskCollectionImpl implements CostsTaskCollection
{
return total;
}
private final Map myCosts = new HashMap();
public Collection getCollection() {
return myCosts.values();
private final TaskImpl myTask;
}
64
public void commit() {
public Cost getCost(String costId) {
List
ArrayList(myQueue.values());
return (Cost) myCosts.get(costId);
}
mutations
=
new
Collections.sort(mutations);
for (int i = 0; i < mutations.size(); i++) {
public CostMutator createMutator() {
MutationCostInfo
(MutationCostInfo) mutations.get(i);
return new CostMutatorImpl();
}
next
=
switch (next.myOperation) {
case MutationCostInfo.DELETE: {
CostsTaskCollectionImpl copy() {
myCosts.remove(next.myCost.toString());
return new CostsTaskCollectionImpl(this);
break;
}
}
case MutationCostInfo.ADD: {
//Cost result = next.myCost;
public void deleteCost(Cost cost) {
myCosts.remove(cost.toString());
}
myCosts.put(next.myCost.toString(),next.myCost);
//Talvez seja necessário criar
public void addCost(Cost cost) {
outro objeto
myCosts.put(cost.toString(), cost);
/*
}
* ResourceAssignment result =
auxAddAssignment(next.myResource);
result.setLoad(next.myAssignment.getLoad());
private Task getTask() {
return myTask;
result.setCoordinator(next.myAssignment.isCoordinator());
}
result.setRoleForAssignment(next.myAssignment
.getRoleForAssignment());
private class CostMutatorImpl implements
*/
CostMutator {
}
private Map myQueue = new HashMap();
default:
break;
public void addCost(Cost cost) {
myQueue.put(cost.toString(),
MutationCostInfo(cost, MutationCostInfo.ADD));
}
}
new
}
}
}
public void deleteCost(Cost cost) {
MutationCostInfo
(MutationCostInfo) myQueue.get(cost);
info
=
private static class MutationCostInfo implements
Comparable {
if (info == null) {
static final int ADD = 0;
myQueue.put(cost.toString(),
new
MutationCostInfo(cost,
static final int DELETE = 1;
MutationCostInfo.DELETE));
}
MutationCostInfo.ADD) {
else
if
(info.myOperation
==
private final Cost myCost;
myQueue.remove(cost.toString());
}
private final int myOrder;
}
65
private static int ourOrder;
import java.beans.PropertyChangeListener;
private int myOperation;
import java.beans.PropertyChangeEvent;
public MutationCostInfo(Cost cost, int operation) {
import javax.swing.ImageIcon;
myCost = cost;
import javax.swing.JButton;
myOrder = ourOrder++;
import javax.swing.JPanel;
myOperation = operation;
import javax.swing.JTextField;
import javax.swing.JLabel;
}
import javax.swing.JScrollPane;
public boolean equals(Object o) {
import javax.swing.border.EtchedBorder;
boolean result = o instanceof MutationCostInfo;
import javax.swing.border.TitledBorder;
if (result) {
import javax.swing.table.DefaultTableModel;
result = myCost.equals(
import javax.swing.JFormattedTextField;
((MutationCostInfo) o).myCost);
}
import net.sourceforge.ganttproject.GanttProject;
return result;
import net.sourceforge.ganttproject.Mediator;
import net.sourceforge.ganttproject.language.GanttLanguage;
}
import net.sourceforge.ganttproject.task.CostsTaskCollection;
public int compareTo(Object o) {
if (!(o instanceof MutationCostInfo)) {
throw new IllegalArgumentException();
}
return myOrder - ((MutationCostInfo) o).myOrder;
}
}
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;
net.sourceforge.ganttproject.gui.
taskproperties.CostsPanel
package net.sourceforge.ganttproject.gui.taskproperties;
import org.jdesktop.swing.JXTable;
import org.jdesktop.swing.decorator.AlternateRowHighlighter;
import org.jdesktop.swing.decorator.Highlighter;
import org.jdesktop.swing.decorator.HighlighterPipeline;
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;
/**
* @author bbaranne Mar 4, 2005
*/
public class CostsPanel extends CommonPanel {
private
static
GanttLanguage
GanttLanguage.getInstance();
language
=
import java.awt.event.ActionListener;
import java.util.GregorianCalendar;
private JPanel costsPanel;
import java.util.Iterator;
import java.util.Vector;
import java.text.NumberFormat;
private JXTable costsTable;
private JScrollPane costsScrollPane;
66
//costsTable.getColumnModel().getColumn(3).setPreferredWidt
h(200);
//private JTextField totalCostField = null;
private JFormattedTextField totalCostField = null;
costsTable.setHighlighters(new HighlighterPipeline(
new Highlighter[] { new Highlighter(
private NumberFormat costFormat;
new Color(0xFF, 0xFF, 0xFF), null) }));
costsScrollPane = new JScrollPane(costsTable);
private JLabel totalCostLabel = null;
costsScrollPane.setPreferredSize(new
130));
Dimension(520,
JPanel secondResourcesScrollPane = new JPanel();
private CostsTableModel myCostTableModel = null;
secondResourcesScrollPane.setBorder(new TitledBorder(
//new
GanttProject.correctLabel(getLanguage()
//private Task myTask = null;
//
.getText("human"))));
new
language.getText("costs")));
public CostsPanel(Task task) {
super(task);
EtchedBorder(),
EtchedBorder(),
secondResourcesScrollPane.add(costsScrollPane);
//myTask = task;
//this.initComponents();
JButton bremove = new TestGanttRolloverButton(new
ImageIcon(getClass()
}
.getResource("/icons/delete_16.gif")));
public JPanel getComponent() {
//bremove.setToolTipText(GanttProject.getToolTip(getLanguag
e().getText(
if (costsPanel == null) {
//
constructCostsPanel();
"removeResources")));
}
bremove.setToolTipText(language.getText("deleteCost"));
return costsPanel;
bremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
}
int[] selectedRow = costsTable.getSelectedRows();
for (int i = 0; i < selectedRow.length; ++i) {
private void constructCostsPanel() {
CostsTaskCollection
getTask().getCostsTaskCollection();
costs
if
=
(costsTable.getModel().getValueAt(selectedRow[i],1) != null) {
try {
costsPanel = new JPanel(new GridBagLayout());
myCostTableModel = new CostsTableModel(costs);
costsTable = new JXTable(myCostTableModel);
sumTotalCost(false,(NumberFormat.getCurrencyInsta
nce().parse((String)costsTable.getModel().getValueAt(selected
Row[i],1))).doubleValue());
} catch (Exception e) {
//setUpResourcesComboColumn(resourcesTable); // set
column editor
System.out.println("Erro
CostsPanel : " + e.getMessage());
//setUpCoordinatorBooleanColumn(resourcesTable);
}
//setUpRolesComboColumn(resourcesTable);
costsTable.setRowHeight(23);
costsTable.getModel().setValueAt(null,
selectedRow[i],1);
costsTable.getColumnModel().getColumn(0).setPreferredWidth
(80);
}
costsTable.getColumnModel().getColumn(1).setPreferredWidth
(130);
costsTable.getColumnModel().getColumn(2).setPreferredWidth
(310);
}
}
});
secondResourcesScrollPane.add(bremove);
67
JButton
buttonAdd
JButton(language.getText("add"));
=
new
gbc.gridx = 0;
buttonAdd.addActionListener(new ActionListener() {
gbc.gridy = 2;
costsPanel.add(totalCostPane, gbc);
public void actionPerformed(ActionEvent e) {
}
Cost cost = new CostImpl();
GanttDialogCost d = new GanttDialogCost(Mediator
.getGanttProjectSingleton(),
getTableModel());
public CostsTableModel getTableModel() {
cost,
return myCostTableModel;
}
d.setVisible(true);
sumTotalCost(true,d.getValue());
private void sumTotalCost(boolean sum, double value) {
}
});
double
actValue
((Number)totalCostField.getValue()).doubleValue();
=
if (sum)
secondResourcesScrollPane.add(buttonAdd);
actValue+= value;
else
actValue-=value;
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
totalCostField.setValue(new Double(actValue));
gbc.insets.right = 15;
}
gbc.insets.left = 10;
gbc.insets.top = 10;
private void showTotalCost() {
gbc.weighty = 0;
JPanel commonFields = setupCommonFields(true);
Cost[]
costs
getTask().getCostsTaskCollection().getCosts();
=
double totalCosts = 0;
for (int i=0;i <costs.length;i++) {
addUsingGBL(costsPanel, commonFields, gbc, 0, 0, 1, 1);
totalCosts+=costs[i].getValue();
}
gbc.gridx = 0;
totalCostField.setValue(new Double(totalCosts));
gbc.gridy = 1;
}
gbc.gridwidth = 8;
gbc.gridheight = 1;
}
gbc.weighty = 1;
costsPanel.add(secondResourcesScrollPane, gbc);
//totalCostField = new JTextField();
net.sourceforge.ganttproject.gui.
CostsTableModel
package net.sourceforge.ganttproject.gui;
costFormat = NumberFormat.getCurrencyInstance();
totalCostField = new JFormattedTextField(costFormat);
import java.util.ArrayList;
totalCostField.setColumns(15);
import java.util.Arrays;
totalCostField.setEditable(false);
import java.util.Iterator;
totalCostLabel = new JLabel();
import java.util.List;
totalCostLabel.setText(language.getText("total"));
import java.util.Date;
showTotalCost();
import java.util.Vector;
import java.text.NumberFormat;
JPanel totalCostPane = new JPanel();
totalCostPane.add(totalCostLabel);
import javax.swing.table.AbstractTableModel;
totalCostPane.add(totalCostField);
68
import net.sourceforge.ganttproject.GanttCalendar;
/**
import net.sourceforge.ganttproject.language.GanttLanguage;
* Return the number of rows
import net.sourceforge.ganttproject.resource.HumanResource;
*/
import net.sourceforge.ganttproject.resource.ProjectResource;
public int getRowCount() {
return myCosts.size() + 1;
import net.sourceforge.ganttproject.roles.Role;
}
import net.sourceforge.ganttproject.task.Cost;
import net.sourceforge.ganttproject.task.CostsTaskCollection;
/**
import net.sourceforge.ganttproject.task.CostMutator;;
* Return the name of the column at col index
*/
public class CostsTableModel extends AbstractTableModel {
public String getColumnName(int col) {
private
static
GanttLanguage
GanttLanguage.getInstance();
final
String[]
{language.getText("date"),
language
return columnNames[col];
=
}
columnNames
=
/**
language.getText("value"),
* Return the object a specify cell
language.getText("description"),
*/
language.getText("id")};
public Object getValueAt(int row, int col) {
Object result = null;
if (row >= 0) {
//private final CostsTaskCollection myCostsTaskCollection;
if (row < myCosts.size()) {
private final List myCosts;
Cost cost = (Cost) myCosts
//private static final int MAX_ROW_COUNT = 100;
switch (col) {
.get(row);
case 3:
result = cost.toString();
private final CostMutator myMutator;
break;
case 0:
private boolean isChanged = false;
result = new GanttCalendar(cost.getDate());
public
costsTaskCollection) {
break;
CostsTableModel(CostsTaskCollection
case 1:
//myCostsTaskCollection = costsTaskCollection;
myCosts
=
ArrayList(Arrays.asList(costsTaskCollection
//result = new Double(cost.getValue());
new
result
=
NumberFormat.getCurrencyInstance().format(cost.getValue());
.getCosts()));
break;
myMutator = costsTaskCollection.createMutator();
case 2:
}
result = cost.getDescription();
break;
/**
default:
* Return the number of colums
result = "";
*/
}
public int getColumnCount() {
} else {
result = null;
return columnNames.length - 1;
}
} else {
}
throw new IllegalArgumentException("I can't return data
in row="
69
+ row);
private void deleteCost(int row) {
}
String costString = (String) getValueAt(row,3);
return result;
Iterator it = myCosts.iterator();
}
Cost cost = null;
/*
while (it.hasNext() && cost == null){
* JTable uses this method to determine the default renderer/
editor for
cost = (Cost) it.next();
* each cell. If we didn't implement this method, then the last
column would
if (cost.toString().equals(costString))
it.remove();
* contain text ("true"/"false"), rather than a check box.
else
*/
cost = null;
}
public Class getColumnClass(int c) {
switch (c) {
myMutator.deleteCost(cost);
case 3:
fireTableRowsDeleted(row,row);
}
case 0:
return Date.class;
private void createCost(Object value) {
case 1:
if (value instanceof Cost) {
//return Double.class;
Cost newCost = (Cost) value;
return String.class;
myMutator.addCost(newCost);
case 2:
myCosts.add(newCost);
return String.class;
fireTableRowsInserted(myCosts.size(), myCosts.size());
default:
}
return String.class;
}
}
}
public List getCosts() {
return myCosts;
public boolean isCellEditable(int row, int col) {
}
return false;
}
void commit() {
myMutator.commit();
/*
* Don't need to implement this method unless your table's
data can change.
*/
}
public boolean isChanged() {
return isChanged;
public void setValueAt(Object value, int row, int col) {
}
if (value == null)
deleteCost(row);
}
else
createCost(value);
isChanged = true;
net.sourceforge.ganttproject.gui.
GanttDialogCost
package net.sourceforge.ganttproject.gui;
// fireTableCellUpdated(row, col);
import java.awt.BorderLayout;
}
import java.awt.CardLayout;
70
private JPanel panelText = null;
import java.awt.Frame;
import java.awt.GridBagConstraints;
private JTextArea textArea = null;
import java.awt.GridBagLayout;
import java.awt.Insets;
private JLabel labelDate = null;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
private JButton buttonDate = null;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
private JLabel labelName = null;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
private JLabel labelValue = null;
import java.text.NumberFormat;
import java.util.Date;
import java.util.GregorianCalendar;
private JTextField fieldValue = null;
import javax.swing.ButtonGroup;
private JLabel labelDescription = null;
import javax.swing.ImageIcon;
private JButton buttonOK = null;
import javax.swing.JButton;
import javax.swing.JComboBox;
private JButton buttonCancel = null;
import javax.swing.JDialog;
import javax.swing.JLabel;
private GanttCalendar date = null;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
private CostsTableModel myCostTableModel = null;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public
GanttDialogCost(Frame
parent,
CostsTableModel myCostTableModel) {
import javax.swing.JTextField;
import javax.swing.SwingConstants;
Cost
cost,
super(parent, language.getText("newCost"), true);
this.cost = cost;
import net.sourceforge.ganttproject.GanttCalendar;
initComponents();
import net.sourceforge.ganttproject.Mediator;
DialogAligner.center(this, parent);
import net.sourceforge.ganttproject.language.GanttLanguage;
this.myCostTableModel = myCostTableModel;
import net.sourceforge.ganttproject.task.Cost;
}
/**
private void initComponents() {
* Dialog opened to create a new cost.
GridBagConstraints
GridBagConstraints();
*
constraints
=
new
* @author lh Oct 24, 2005
*/
labelName = new JLabel(language.getText("date") + ": ");
public class GanttDialogCost extends JDialog {
private
static
GanttLanguage
GanttLanguage.getInstance();
labelValue = new JLabel(language.getText("value") + ": ");
language
=
labelDescription
=
JLabel(language.getText("shortDescription") + ": ");
/**
fieldValue = new JTextField();
* Created Cost.
fieldValue.setColumns(10);
new
*/
private Cost cost = null;
// Text
textArea = new JTextArea();
71
textArea.setWrapStyleWord(true);
buttonCancel.setHorizontalAlignment(SwingConstants.CENTE
R);
textArea.setLineWrap(true);
textArea.setColumns(25);
buttonCancel.setText(language.getText("cancel"));
textArea.setRows(5);
buttonCancel.addActionListener(new ActionListener() {
JScrollPane jsp = new JScrollPane(textArea);
public void actionPerformed(ActionEvent evt) {
//panelText = new JPanel(new BorderLayout());
cancel();
//panelText.add(jsp, BorderLayout.CENTER);
}
});
// Date
ImageIcon icon = new ImageIcon(getClass().getResource(
"/icons/calendar_16.gif"));
setResizable(false);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
date = new GanttCalendar(new Date());
closeDialog();
final GanttDialogDate dd = new GanttDialogDate(this,
date, false);
}
});
labelDate = new JLabel(date.toString());
buttonDate = new JButton(icon);
constraints.fill = GridBagConstraints.HORIZONTAL;
buttonDate.addActionListener(new ActionListener() {
JPanel panelMain = new JPanel(new GridBagLayout());
public void actionPerformed(ActionEvent e) {
// name
dd.show();
constraints = new GridBagConstraints();
date = dd.getDate();
constraints.gridx = 0;
labelDate.setText(date.toString());
constraints.gridy = 0;
}
constraints.insets = new Insets(5, 5, 10, 10);
panelMain.add(labelName, constraints);
});
constraints.gridx = 1;
constraints.gridy = 0;
date = dd.getDate();
//constraints.gridwidth = 5;
labelDate.setText(date.toString());
//constraints.ipadx = 100;
panelMain.add(labelDate, constraints);
//comboTypes
=
JComboBox(CostStorage.availableTypes);
new
constraints.gridx = 2;
constraints.gridy = 0;
//constraints.gridwidth = 10;
//constraints.ipadx = 100;
buttonOK = new JButton();
//constraints.insets = new Insets(0, 5, 0, 5);
panelMain.add(buttonDate, constraints);
buttonOK.setHorizontalTextPosition(SwingConstants.CENTER)
;
buttonOK.setText(language.getText("ok"));
// type
buttonOK.addActionListener(new ActionListener() {
constraints = new GridBagConstraints();
public void actionPerformed(ActionEvent evt) {
ok();
}
constraints.gridx = 0;
constraints.gridy = 1;
constraints.insets = new Insets(5, 5, 10, 10);
});
panelMain.add(labelValue, constraints);
getRootPane().setDefaultButton(buttonOK);
constraints.gridx = 1;
constraints.gridy = 1;
buttonCancel = new JButton();
//constraints.gridwidth = 5;
72
panelMain.add(fieldValue, constraints);
Mediator.getGanttProjectSingleton().setAskForSave(true);
// panelDefaultValue
try {
constraints = new GridBagConstraints();
constraints.gridx = 0;
double
value
=
(NumberFormat.getNumberInstance().parse(fieldValue.getText(
))).doubleValue();
constraints.gridy = 2;
constraints.insets = new Insets(5, 5, 10, 10);
if (fieldValue.getText().length() != 0) {
panelMain.add(labelDescription, constraints);
constraints.gridx = 1;
if (cost != null) {
constraints.gridy = 2;
cost.setDate(date.getTime());
//constraints.gridwidth = 5;
cost.setValue(value);
//panelMain.add(panelText, constraints);
cost.setDescription(textArea.getText());
panelMain.add(jsp, constraints);
myCostTableModel.setValueAt(cost,0,0);
}
// buttonOK
closeDialog();
constraints = new GridBagConstraints();
} else
constraints.gridx = 3;
fieldValue.requestFocus();
constraints.gridy = 3;
} catch (Exception e) {
constraints.anchor = java.awt.GridBagConstraints.EAST;
fieldValue.requestFocus();
constraints.insets = new Insets(10, 10, 10, 10);
}
panelMain.add(buttonOK, constraints);
}
// buttonCancel
public double getValue() {
constraints = new java.awt.GridBagConstraints();
if (fieldValue.getText().length() == 0)
constraints.gridx = 4;
return 0;
constraints.gridy = 3;
else
constraints.anchor = java.awt.GridBagConstraints.EAST;
return Double.parseDouble(fieldValue.getText());
constraints.insets = new Insets(10, 10, 10, 10);
}
panelMain.add(buttonCancel, constraints);
private void cancel() {
// All
getContentPane().setLayout(new GridBagLayout());
fieldValue.setText(""); //its important to the CostPanel
-> totalCosts
closeDialog();
constraints = new java.awt.GridBagConstraints();
}
constraints.gridx = 0;
constraints.gridy = 0;
private void closeDialog() {
constraints.gridwidth = 5;
setVisible(false);
constraints.gridheight = 5;
dispose();
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() {
}
net.sourceforge.ganttproject.gui.
report.ReportDialog
package net.sourceforge.ganttproject.gui.report;
import javax.swing.Box;
73
if (sNode.equals(language.getText("report")))
import javax.swing.event.TreeSelectionEvent;
settingPanel = new ReportPanel(appli);
import javax.swing.tree.DefaultMutableTreeNode;
import net.sourceforge.ganttproject.GanttProject;
//else
if
(sNode.equals(GanttProject.correctLabel(language.getText("ab
out"))))
import net.sourceforge.ganttproject.gui.GeneralDialog;
//
settingPanel = new AboutPanel(appli);
import
net.sourceforge.ganttproject.gui.about.AboutAuthorPanel;
import
net.sourceforge.ganttproject.gui.about.AboutJavaInfosPanel;
import
net.sourceforge.ganttproject.gui.about.AboutLibraryPanel;
Box vb = Box.createVerticalBox();
vb.add(new TopPanel("
settingPanel
import
net.sourceforge.ganttproject.gui.about.AboutLicensePanel;
" + settingPanel.getTitle(),
.getComment()));
vb.add(settingPanel);
import net.sourceforge.ganttproject.gui.about.AboutPanel;
settingPanel.initialize();
import net.sourceforge.ganttproject.gui.options.TopPanel;
import net.sourceforge.ganttproject.language.GanttLanguage;
// - add the settingPanel into the main Panel
mainPanel2.add(vb, 0);
/**
mainPanel2.repaint();
* @author Luis Henrique
mainPanel2.validate(); // valide the changes
*/
}
public class ReportDialog extends GeneralDialog {
/** Coonstruct the menu settings. */
/** Constructor. */
public void constructSections() {
public ReportDialog(GanttProject parent) {
super(parent,
GanttProject.correctLabel(GanttLanguage.getInstance()
DefaultMutableTreeNode
addObject(language
reportNode
=
.getText("report"), null);
.getText("report"))
//DefaultMutableTreeNode
+ " - Ganttproject", false, new ReportPanel(parent)); addObject(GanttProject
//
aboutNode
=
.correctLabel(language.getText("about")), null);
// hide the cancel button
cancelButton.hide();
}
}
}
/** Callback for the tree selection event. */
net.sourceforge.ganttproject.gui.
report.ReportPanel
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode
(DefaultMutableTreeNode) (e.getPath()
node
.getLastPathComponent());
String sNode = (String) (node.getUserObject());
=package net.sourceforge.ganttproject.gui.report;
import edu.ufsc.ganttproject.report.ReportCostDataSource;
import
edu.ufsc.ganttproject.report.ReportCostResumeDataSource;
// - ask the settingPanel if parameters are changed
//
boolean
bHasChange
settingPanel.applyChanges(true); //no change to
// do on this panel
=import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.io.InputStream;
// - remove the settingPanel
import java.io.IOException;
mainPanel2.remove(0);
import java.awt.event.ActionEvent;
// - Create the new panel
74
import java.awt.event.ActionListener;
vb.add(new JPanel());
JButton
bViewReport
JButton(GanttProject.correctLabel(language
import javax.swing.ImageIcon;
import javax.swing.JButton;
=
new
.getText("reportTaskCost")),
ImageIcon(getClass().getResource(
import javax.swing.JLabel;
import javax.swing.JPanel;
new
"/icons/settings_16.gif")));
bViewReport.setToolTipText(GanttProject.getToolTip(language
import net.sourceforge.ganttproject.GanttProject;
.getText("reportTaskCost"))); // add a simple tool tip
import net.sourceforge.ganttproject.GanttSplash;
import net.sourceforge.ganttproject.gui.GanttDialogInfo;
// text :)
import
net.sourceforge.ganttproject.gui.options.GeneralOptionPanel;
bViewReport.addActionListener(new ActionListener() {
import net.sourceforge.ganttproject.language.GanttLanguage;
public void actionPerformed(ActionEvent e) {
import net.sourceforge.ganttproject.task.Task;
showTaskCostReport();
import net.sourceforge.ganttproject.task.TaskManager;
}
import net.sourceforge.ganttproject.util.BrowserControl;
});
vb.add(bViewReport);
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
JButton
bViewCostResumeReport
JButton(GanttProject.correctLabel(language
import net.sf.jasperreports.engine.JasperPrint;
=
.getText("reportCostResume")),
ImageIcon(getClass().getResource(
import net.sf.jasperreports.view.JasperViewer;
/**
new
new
"/icons/settings_16.gif")));
* @author athomas The About panel.
*/
bViewCostResumeReport.setToolTipText(GanttProject.getTool
Tip(language
public class ReportPanel extends GeneralOptionPanel {
.getText("reportCostResume"))); // add a simple tool
tip
private
static
final
String
"/edu/ufsc/ganttproject/report/TaskReport.jasper";
rel1
private
static
final
String
rel2
"edu/ufsc/ganttproject/report/CostsTaskReport.jasper";
// text :)
=
bViewCostResumeReport.addActionListener(new
ActionListener() {
=
public void actionPerformed(ActionEvent e) {
showCostResumeReport();
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(bViewCostResumeReport);
applyComponentOrientation(language.getComponentOrientatio
n());
}
private void createTaskCollection(Task task, int depth,
ArrayList arrayList) {
Task[]
nestedTasks
task.getManager().getTaskHierarchy()
=
.getNestedTasks(task);
75
for (int i = 0; i < nestedTasks.length; i++) {
GanttDialogInfo
GanttDialogInfo(null,
Task next = nestedTasks[i];
//String nextSerialized = serializeTask(next, depth);
//out.append(nextSerialized);
gdi
=
new
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION,
language.getText("msg21"),
language.getText("error"));
arrayList.add(next);
gdi.show();
createTaskCollection(next, depth + 1, arrayList);
}
}
}
}
private void showTaskCostReport() {
private void showCostResumeReport() {
if
(!gp.getTaskManager().getTasksCollection().isEmpty()) {
if
(!gp.getTaskManager().getTasksCollection().isEmpty()) {
ArrayList
alTasks
=
new
ArrayList
alTasks
=
new
ArrayList(gp.getTaskManager().getTasksCollection().size());
ArrayList(gp.getTaskManager().getTasksCollection().size());
createTaskCollection(gp.getTaskManager().getRootT
createTaskCollection(gp.getTaskManager().getRootT
ask(), 0, alTasks);
ask(), 0, alTasks);
//ReportCostDataSource
ds
=
new
//ReportCostDataSource
ds
=
new
ReportCostDataSource(gp.getTaskManager().getTasksCollecti ReportCostDataSource(gp.getTaskManager().getTasksCollecti
on());
on());
ReportCostDataSource
ReportCostDataSource(alTasks);
ds
=
ReportCostResumeDataSource ds = new
new
ReportCostResumeDataSource(alTasks);
// Parametros do relatorio
// Parametros do relatorio
Map parametros = new HashMap();
//Map parametros = new HashMap();
parametros.put("pathSubRel",rel2);
//parametros.put("pathSubRel",rel2);
JasperViewer viewer = null;
JasperViewer viewer = null;
try {
try {
JasperPrint
impressao
=
JasperPrint
impressao
=
JasperFillManager.fillReport(getClass().getResourceAsStream(rJasperFillManager.fillReport(getClass().getResourceAsStream(
costResumeRel), null, ds);
el1), parametros, ds);
//exibe o relatório
//exibe o relatório
viewer
JasperViewer(impressao, false);
viewer
new
JasperViewer(impressao, false);
=
} catch (JRException jre) {
} catch (JRException jre) {
System.out.println("Erro:
}
} else {
new
viewer.show();
viewer.show();
jre.getMessage());
=
"
System.out.println("Erro:
+
jre.getMessage());
"
+
}
} else {
76
GanttDialogInfo
GanttDialogInfo(null,
gdi
=
new
* @param campos
* @param itr
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION,
*/
public ReportCostDataSource(Collection lista) {
language.getText("msg21"),
language.getText("error"));
super();
gdi.show();
this.itrTasks = lista.iterator();
}
}
}
/*
/** This method check if the value has changed, and assk for
commit changes. */
* (non-Javadoc)
*
public boolean applyChanges(boolean askForApply) {
* @see net.sf.jasperreports.engine.JRDataSource#next()
// nothing to do :)
*/
return bHasChange = false;
public boolean next() throws JRException {
}
valorAtual = itrTasks.hasNext() ? itrTasks.next() : null;
irParaProximoAluno = (valorAtual != null);
/** Initialize the component. */
return irParaProximoAluno;
public void initialize() {
}
// nothing to do :)
}
/*
* (non-Javadoc)
}
*
edu.ufsc.ganttproject.report.
ReportCostDataSource
*
@see
net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf
.jasperreports.engine.JRField)
*/
package edu.ufsc.ganttproject.report;
import java.util.Iterator;
public Object
JRException {
getFieldValue(JRField
campo)
throws
Object valor = null;
import java.util.List;
Task task = (Task) valorAtual;
import java.util.Collection;
//teste
import net.sourceforge.ganttproject.task.Task;
if ("name".equals(campo.getName())) {
import net.sf.jasperreports.engine.JRDataSource;
valor = task.getName();
import net.sf.jasperreports.engine.JRException;
} else if ("CostsList".equals(campo.getName())) {
import net.sf.jasperreports.engine.JRField;
valor
=
new
import
JRBeanCollectionDataSource(task.getCostsTaskCollection().ge
net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; tCollection());
} else if ("start".equals(campo.getName())) {
public class ReportCostDataSource implements JRDataSource
{
private Iterator itrTasks;
private Object valorAtual;
private boolean irParaProximoAluno = true;
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
=
Double(task.getCostsTaskCollection().getTotalCosts());
new
} else if ("remain".equals(campo.getName())) {
/**
valor
=
new
Double(task.getBudget()
task.getCostsTaskCollection().getTotalCosts());
-
77
}
/*
* (non-Javadoc)
return valor;
*
}
}
edu.ufsc.ganttproject.report.
ReportCostResumeDataSource
package edu.ufsc.ganttproject.report;
*
@see
net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf
.jasperreports.engine.JRField)
*/
public Object
JRException {
getFieldValue(JRField
campo)
throws
Object valor = null;
import java.util.Iterator;
Task task = (Task) valorAtual;
import java.util.Collection;
if ("name".equals(campo.getName())) {
valor = task.getName();
import net.sourceforge.ganttproject.task.Task;
} else if ("start".equals(campo.getName())) {
valor = task.getStart().getTime();
import net.sf.jasperreports.engine.JRDataSource;
} else if ("end".equals(campo.getName())) {
import net.sf.jasperreports.engine.JRException;
valor = task.getEnd().getTime();
import net.sf.jasperreports.engine.JRField;
} else if ("budget".equals(campo.getName())) {
public class ReportCostResumeDataSource
JRDataSource {
valor = new Double(task.getBudget());
implements
} else if ("totalCosts".equals(campo.getName())) {
valor
=
Double(task.getCostsTaskCollection().getTotalCosts());
private Iterator itrTasks;
new
} else if ("remain".equals(campo.getName())) {
valor
=
new
Double(task.getBudget()
task.getCostsTaskCollection().getTotalCosts());
private Object valorAtual;
-
}
private boolean irParaProximoAluno = true;
return valor;
/**
}
* @param campos
}
* @param itr
*/
public
ReportCostResumeDataSource(Collection
lista)
edu.ufsc.ganttproject.report.
CostsResumeReport
{
super();
package edu.ufsc.ganttproject.report;
this.itrTasks = lista.iterator();
/*
* Generated by JasperReports - 03/02/06 17:39
}
*/
/*
import net.sf.jasperreports.engine.*;
* (non-Javadoc)
import net.sf.jasperreports.engine.fill.*;
*
* @see net.sf.jasperreports.engine.JRDataSource#next()
import java.util.*;
*/
import java.math.*;
public boolean next() throws JRException {
import java.text.*;
valorAtual = itrTasks.hasNext() ? itrTasks.next() : null;
import java.io.*;
irParaProximoAluno = (valorAtual != null);
import java.net.*;
return irParaProximoAluno;
}
import java.util.*;
78
public void customizedInit(
import net.sf.jasperreports.engine.*;
Map pm,
import net.sf.jasperreports.engine.data.*;
Map fm,
Map vm
)
/**
{
*
*/
initParams(pm);
public class CostsResumeReport extends JREvaluator
initFields(fm);
initVars(vm);
{
}
/**
*
/**
*/
*
private
JRFillParameter
parameter_REPORT_RESOURCE_BUNDLE = null;
private
parameter_REPORT_CONNECTION = null;
JRFillParameter
*/
private void initParams(Map pm)
{
parameter_REPORT_RESOURCE_BUNDLE
=
private
JRFillParameter
(JRFillParameter)pm.get("REPORT_RESOURCE_BUNDLE");
parameter_REPORT_PARAMETERS_MAP = null;
parameter_REPORT_CONNECTION
=
private
JRFillParameter
(JRFillParameter)pm.get("REPORT_CONNECTION");
parameter_IS_IGNORE_PAGINATION = null;
parameter_REPORT_PARAMETERS_MAP
=
private
JRFillParameter
(JRFillParameter)pm.get("REPORT_PARAMETERS_MAP");
parameter_REPORT_CLASS_LOADER = null;
parameter_IS_IGNORE_PAGINATION
=
private JRFillParameter parameter_REPORT_VIRTUALIZER
(JRFillParameter)pm.get("IS_IGNORE_PAGINATION");
= null;
parameter_REPORT_CLASS_LOADER
private JRFillParameter parameter_REPORT_LOCALE =
(JRFillParameter)pm.get("REPORT_CLASS_LOADER");
null;
parameter_REPORT_VIRTUALIZER
private
JRFillParameter
(JRFillParameter)pm.get("REPORT_VIRTUALIZER");
parameter_REPORT_DATA_SOURCE = null;
parameter_REPORT_LOCALE
private JRFillParameter parameter_REPORT_SCRIPTLET =
(JRFillParameter)pm.get("REPORT_LOCALE");
null;
parameter_REPORT_DATA_SOURCE
private JRFillParameter parameter_REPORT_MAX_COUNT
(JRFillParameter)pm.get("REPORT_DATA_SOURCE");
= null;
private JRFillField field_totalCosts = null;
private JRFillField field_start = null;
private JRFillField field_end = null;
private JRFillField field_budget = null;
=
=
=
=
parameter_REPORT_SCRIPTLET
(JRFillParameter)pm.get("REPORT_SCRIPTLET");
=
parameter_REPORT_MAX_COUNT
(JRFillParameter)pm.get("REPORT_MAX_COUNT");
=
}
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 void initFields(Map fm)
private JRFillVariable variable_COLUMN_COUNT = null;
{
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");
79
value = (java.lang.Integer)(new Integer(0));
field_name = (JRFillField)fm.get("name");
break;
}
}
case 4 :
{
/**
value = (java.lang.Integer)(new Integer(1));
*
break;
*/
}
private void initVars(Map vm)
case 5 :
{
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");
=
{
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;
*/
}
public Object evaluate(int id) throws Throwable
case 8 :
{
{
Object value = null;
value
(java.lang.String)(((java.lang.String)field_name.getValue()));
=
break;
switch (id)
}
{
case 0 :
case 9 :
{
{
value = (java.lang.Integer)(new Integer(1));
value
(java.util.Date)(((java.util.Date)field_start.getValue()));
break;
break;
}
}
case 1 :
case 10 :
{
{
value = (java.lang.Integer)(new Integer(1));
break;
value
=
(java.lang.Double)(((java.lang.Double)field_budget.getValue()));
break;
}
case 2 :
}
{
case 11 :
value = (java.lang.Integer)(new Integer(1));
break;
{
value
(java.util.Date)(((java.util.Date)field_end.getValue()));
}
case 3 :
{
=
=
break;
}
case 12 :
80
value = (java.lang.Integer)(new Integer(0));
{
value
=
(java.lang.Double)(((java.lang.Double)field_remain.getValue()));
break;
break;
}
case 4 :
}
{
case 13 :
value = (java.lang.Integer)(new Integer(1));
{
break;
value
=
(java.lang.Double)(((java.lang.Double)field_totalCosts.getValue(
)));
break;
}
case 5 :
{
}
value = (java.lang.Integer)(new Integer(0));
default :
break;
{
}
}
case 6 :
}
{
value = (java.lang.Integer)(new Integer(1));
return value;
}
break;
}
case 7 :
{
/**
value = (java.lang.Integer)(new Integer(0));
*
break;
*/
}
public Object evaluateOld(int id) throws Throwable
case 8 :
{
{
Object value = null;
value
=
(java.lang.String)(((java.lang.String)field_name.getOldValue()));
break;
switch (id)
}
{
case 0 :
case 9 :
{
{
value = (java.lang.Integer)(new Integer(1));
value
(java.util.Date)(((java.util.Date)field_start.getOldValue()));
break;
}
break;
}
case 1 :
{
case 10 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
value
=
(java.lang.Double)(((java.lang.Double)field_budget.getOldValue
()));
break;
case 2 :
}
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 11 :
{
value
(java.util.Date)(((java.util.Date)field_end.getOldValue()));
case 3 :
{
=
=
break;
}
81
{
case 12 :
value = (java.lang.Integer)(new Integer(0));
{
value
=
(java.lang.Double)(((java.lang.Double)field_remain.getOldValue
()));
break;
}
case 4 :
break;
{
}
case 13 :
value = (java.lang.Integer)(new Integer(1));
{
break;
value
=
(java.lang.Double)(((java.lang.Double)field_totalCosts.getOldVa
lue()));
break;
}
case 5 :
{
value = (java.lang.Integer)(new Integer(0));
}
break;
default :
}
{
case 6 :
}
{
}
value = (java.lang.Integer)(new Integer(1));
break;
return value;
}
}
case 7 :
{
value = (java.lang.Integer)(new Integer(0));
/**
break;
*
}
*/
public Object evaluateEstimated(int id) throws Throwable
case 8 :
{
{
Object value = null;
value
(java.lang.String)(((java.lang.String)field_name.getValue()));
=
break;
switch (id)
}
{
case 9 :
case 0 :
{
value = (java.lang.Integer)(new Integer(1));
{
value
(java.util.Date)(((java.util.Date)field_start.getValue()));
break;
break;
}
}
case 1 :
case 10 :
{
{
value = (java.lang.Integer)(new Integer(1));
value
=
(java.lang.Double)(((java.lang.Double)field_budget.getValue()));
break;
}
=
break;
}
case 2 :
{
case 11 :
{
value = (java.lang.Integer)(new Integer(1));
break;
value
(java.util.Date)(((java.util.Date)field_end.getValue()));
break;
}
case 3 :
=
}
82
case 12 :
{
value
=
(java.lang.Double)(((java.lang.Double)field_remain.getValue()));
break;
}
case 13 :
/**
*
*/
private
JRFillParameter
parameter_REPORT_RESOURCE_BUNDLE = null;
{
private
JRFillParameter
parameter_REPORT_CONNECTION = null;
value
=
(java.lang.Double)(((java.lang.Double)field_totalCosts.getValue( private
JRFillParameter
)));
parameter_REPORT_PARAMETERS_MAP = null;
break;
}
default :
{
}
}
return value;
}
}
edu.ufsc.ganttproject.report.Cost
sTaskReport
package edu.ufsc.ganttproject.report;
/*
* Generated by JasperReports - 03/02/06 15:43
*/
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.fill.*;
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;
import java.util.*;
import java.math.*;
import java.text.*;
import java.io.*;
import java.net.*;
/**
*
*/
public void customizedInit(
Map pm,
import java.util.*;
Map fm,
import net.sf.jasperreports.engine.*;
Map vm
import net.sf.jasperreports.engine.data.*;
)
{
initParams(pm);
/**
initFields(fm);
*
*/
initVars(vm);
}
public class CostsTaskReport extends JREvaluator
{
83
/**
*
*/
variable_PAGE_COUNT
(JRFillVariable)vm.get("PAGE_COUNT");
=
variable_COLUMN_COUNT
(JRFillVariable)vm.get("COLUMN_COUNT");
=
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");
*/
public Object evaluate(int id) throws Throwable
parameter_IS_IGNORE_PAGINATION
(JRFillParameter)pm.get("IS_IGNORE_PAGINATION");
=
parameter_REPORT_CLASS_LOADER
(JRFillParameter)pm.get("REPORT_CLASS_LOADER");
=
Object value = null;
parameter_REPORT_VIRTUALIZER
(JRFillParameter)pm.get("REPORT_VIRTUALIZER");
=
switch (id)
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");
=
{
{
case 0 :
{
value = (java.lang.Integer)(new Integer(1));
break;
}
case 1 :
}
{
value = (java.lang.Integer)(new Integer(1));
break;
/**
}
*
case 2 :
*/
{
private void initFields(Map fm)
value = (java.lang.Integer)(new Integer(1));
{
break;
field_value = (JRFillField)fm.get("value");
}
field_description = (JRFillField)fm.get("description");
case 3 :
field_date = (JRFillField)fm.get("date");
{
}
value = (java.lang.Integer)(new Integer(0));
break;
}
/**
case 4 :
*
{
*/
value = (java.lang.Integer)(new Integer(1));
private void initVars(Map vm)
break;
{
}
variable_PAGE_NUMBER
(JRFillVariable)vm.get("PAGE_NUMBER");
=
variable_COLUMN_NUMBER
(JRFillVariable)vm.get("COLUMN_NUMBER");
=
variable_REPORT_COUNT
(JRFillVariable)vm.get("REPORT_COUNT");
=
case 5 :
{
value = (java.lang.Integer)(new Integer(0));
break;
}
case 6 :
84
value = (java.lang.Integer)(new Integer(1));
{
break;
value = (java.lang.Integer)(new Integer(1));
}
break;
}
case 1 :
case 7 :
{
value = (java.lang.Integer)(new Integer(1));
{
break;
value = (java.lang.Integer)(new Integer(0));
}
break;
}
case 2 :
case 8 :
{
value = (java.lang.Integer)(new Integer(1));
{
value
(java.util.Date)(((java.util.Date)field_date.getValue()));
=
break;
}
break;
case 3 :
}
{
case 9 :
value = (java.lang.Integer)(new Integer(0));
{
break;
value
=
(java.lang.String)(((java.lang.String)field_description.getValue())
);
break;
}
case 4 :
{
}
value = (java.lang.Integer)(new Integer(1));
case 10 :
break;
{
}
value
=
(java.lang.Double)(((java.lang.Double)field_value.getValue()));
break;
case 5 :
{
value = (java.lang.Integer)(new Integer(0));
}
break;
default :
{
}
}
case 6 :
{
}
value = (java.lang.Integer)(new Integer(1));
break;
return value;
}
}
case 7 :
{
value = (java.lang.Integer)(new Integer(0));
/**
break;
*
}
*/
public Object evaluateOld(int id) throws Throwable
case 8 :
{
{
Object value = null;
value
(java.util.Date)(((java.util.Date)field_date.getOldValue()));
=
break;
switch (id)
}
{
case 9 :
case 0 :
{
{
85
break;
value
=
(java.lang.String)(((java.lang.String)field_description.getOldValu
e()));
}
case 4 :
break;
{
}
case 10 :
value = (java.lang.Integer)(new Integer(1));
{
break;
}
value
=
(java.lang.Double)(((java.lang.Double)field_value.getOldValue()
));
case 5 :
{
break;
value = (java.lang.Integer)(new Integer(0));
}
break;
default :
}
{
case 6 :
}
{
}
value = (java.lang.Integer)(new Integer(1));
break;
return value;
}
}
case 7 :
{
value = (java.lang.Integer)(new Integer(0));
/**
break;
*
}
*/
case 8 :
public Object evaluateEstimated(int id) throws Throwable
{
{
Object value = null;
value
(java.util.Date)(((java.util.Date)field_date.getValue()));
=
break;
switch (id)
}
{
case 9 :
case 0 :
{
value = (java.lang.Integer)(new Integer(1));
{
value
=
(java.lang.String)(((java.lang.String)field_description.getValue())
);
break;
break;
}
}
case 1 :
case 10 :
{
{
value = (java.lang.Integer)(new Integer(1));
break;
value
=
(java.lang.Double)(((java.lang.Double)field_value.getValue()));
break;
}
case 2 :
}
{
default :
value = (java.lang.Integer)(new Integer(1));
{
break;
}
}
}
case 3 :
return value;
{
value = (java.lang.Integer)(new Integer(0));
}
86
}
edu.ufsc.ganttproject.report.
CostsResumeReport.jrxml
</band>
</pageHeader>
<columnHeader>
<band height="44" isSplitAllowed="true" >
<rectangle radius="0" >
<reportElement
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Created with iReport - A designer for JasperReports -->
mode="Opaque"
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD
Report
Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
x="2"
y="2"
width="530"
<jasperReport
height="21"
name="CostsResumeReport"
forecolor="#000000"
columnCount="1"
backcolor="#CC0033"
printOrder="Vertical"
key="rectangle-1"
orientation="Portrait"
stretchType="NoStretch"
pageWidth="595"
positionType="FixRelativeToTop"
pageHeight="842"
isPrintRepeatedValues="true"
columnWidth="535"
isRemoveLineWhenBlank="false"
columnSpacing="0"
isPrintInFirstWholeBand="false"
leftMargin="30"
isPrintWhenDetailOverflows="false"/>
rightMargin="30"
topMargin="20"
<graphicElement
pen="None" fill="Solid" />
bottomMargin="20"
</rectangle>
whenNoDataType="NoPages"
<staticText>
isTitleNewPage="false"
stretchType="NoStretch"
<reportElement
isSummaryNewPage="false">
mode="Opaque"
<property name="ireport.scriptlethandling" value="0" />
x="206"
<property name="ireport.encoding" value="UTF-8" />
y="5"
<import value="java.util.*" />
width="145"
<import value="net.sf.jasperreports.engine.*" />
height="16"
<import value="net.sf.jasperreports.engine.data.*" />
forecolor="#FFFFFF"
<field name="name" class="java.lang.String"/>
backcolor="#CC0033"
<field name="start" class="java.util.Date"/>
key="staticText-1"
<field name="end" class="java.util.Date"/>
stretchType="NoStretch"
<field name="budget" class="java.lang.Double"/>
positionType="FixRelativeToTop"
<field name="totalCosts" class="java.lang.Double"/>
isPrintRepeatedValues="true"
<field name="remain" class="java.lang.Double"/>
isRemoveLineWhenBlank="false"
<background>
isPrintInFirstWholeBand="false"
<band height="0" isSplitAllowed="true" >
</band>
</background>
<title>
<band height="0" isSplitAllowed="true" >
</band>
</title>
<pageHeader>
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" />
<band height="0" isSplitAllowed="true" >
87
</textElement>
<text><![CDATA[Relatório Financeiro]]></text>
</staticText>
<box topBorder="None" topBorderColor="#000000"
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
<staticText>
<reportElement
mode="Transparent"
textAlignment="Left"
rotation="None"
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
x="6"
y="24"
</textElement>
width="55"
height="18"
<text><![CDATA[Orçamento]]></text>
forecolor="#000000"
</staticText>
backcolor="#FFFFFF"
<staticText>
<reportElement
key="staticText-2"
stretchType="NoStretch"
mode="Transparent"
positionType="FixRelativeToTop"
x="196"
isPrintRepeatedValues="true"
y="24"
isRemoveLineWhenBlank="false"
width="33"
isPrintInFirstWholeBand="false"
height="18"
isPrintWhenDetailOverflows="false"/>
forecolor="#000000"
<box topBorder="None" topBorderColor="#000000"
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
backcolor="#FFFFFF"
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
textAlignment="Left"
rotation="None"
positionType="FixRelativeToTop"
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
isRemoveLineWhenBlank="false"
</textElement>
<text><![CDATA[Atividade]]></text>
</staticText>
<staticText>
<reportElement
mode="Transparent"
x="397"
y="24"
width="63"
key="staticText-5"
stretchType="NoStretch"
isPrintRepeatedValues="true"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000"
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
height="18"
<text><![CDATA[Início]]></text>
forecolor="#000000"
</staticText>
backcolor="#FFFFFF"
<staticText>
key="staticText-3"
textAlignment="Left"
rotation="None"
<reportElement
stretchType="NoStretch"
mode="Transparent"
positionType="FixRelativeToTop"
x="261"
isPrintRepeatedValues="true"
y="24"
isRemoveLineWhenBlank="false"
width="27"
isPrintInFirstWholeBand="false"
height="18"
isPrintWhenDetailOverflows="false"/>
forecolor="#000000"
88
<staticText>
backcolor="#FFFFFF"
<reportElement
key="staticText-6"
stretchType="NoStretch"
mode="Transparent"
positionType="FixRelativeToTop"
x="355"
isPrintRepeatedValues="true"
y="24"
isRemoveLineWhenBlank="false"
width="34"
isPrintInFirstWholeBand="false"
height="18"
isPrintWhenDetailOverflows="false"/>
forecolor="#000000"
<box topBorder="None" topBorderColor="#000000"
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
backcolor="#FFFFFF"
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
positionType="FixRelativeToTop"
key="staticText-9"
stretchType="NoStretch"
textAlignment="Left"
rotation="None"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000"
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<text><![CDATA[Fim]]></text>
</staticText>
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
<staticText>
<reportElement
mode="Transparent"
textAlignment="Left"
rotation="None"
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
x="473"
y="24"
</textElement>
width="59"
height="18"
<text><![CDATA[Gasto]]></text>
forecolor="#000000"
</staticText>
backcolor="#FFFFFF"
</band>
key="staticText-7"
</columnHeader>
stretchType="NoStretch"
<detail>
positionType="FixRelativeToTop"
<band height="25" isSplitAllowed="true" >
isPrintRepeatedValues="true"
<textField
isStretchWithOverflow="false"
pattern=""
isBlankWhenNull="false"
evaluationTime="Now"
hyperlinkType="None" hyperlinkTarget="Self" >
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000"
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
textAlignment="Left"
rotation="None"
<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>
isPrintInFirstWholeBand="false"
<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"
89
isPrintInFirstWholeBand="false"
<reportElement
isPrintWhenDetailOverflows="false"/>
mode="Opaque"
<box topBorder="None" topBorderColor="#000000"
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
x="394"
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
height="18"
y="1"
width="64"
textAlignment="Left"
rotation="None"
forecolor="#000000"
backcolor="#FFFFFF"
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
key="textField-7"
stretchType="NoStretch"
</textElement>
positionType="Float"
<textFieldExpression
class="java.lang.String"><![CDATA[$F{name}]]></textFieldExpr
ession>
isPrintRepeatedValues="true"
</textField>
isPrintInFirstWholeBand="false"
isRemoveLineWhenBlank="false"
isPrintWhenDetailOverflows="false"/>
<textField isStretchWithOverflow="false" pattern="dd/MM/yyyy"
isBlankWhenNull="false"
evaluationTime="Now"
<box topBorder="None" topBorderColor="#000000"
hyperlinkType="None" hyperlinkTarget="Self" >
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"
<reportElement
bottomBorder="None" bottomBorderColor="#000000"/>
mode="Opaque"
<textElement
textAlignment="Right"
x="196"
verticalAlignment="Bottom"
rotation="None"
lineSpacing="Single">
y="1"
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
width="64"
height="18"
forecolor="#000000"
</textElement>
backcolor="#FFFFFF"
stretchType="NoStretch"
<textFieldExpression
class="java.lang.Double"><![CDATA[$F{budget}]]></textFieldEx
pression>
positionType="FixRelativeToTop"
</textField>
isPrintRepeatedValues="true"
<textField isStretchWithOverflow="false" pattern="dd/MM/yyyy"
isBlankWhenNull="false"
evaluationTime="Now"
hyperlinkType="None" hyperlinkTarget="Self" >
key="textField-4"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
isPrintWhenDetailOverflows="false"/>
<reportElement
mode="Opaque"
<box topBorder="None" topBorderColor="#000000"
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
x="262"
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
height="18"
textAlignment="Left"
rotation="None"
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
</textElement>
y="1"
width="63"
forecolor="#000000"
backcolor="#FFFFFF"
key="textField-5"
stretchType="NoStretch"
positionType="FixRelativeToTop"
<textFieldExpression
class="java.util.Date"><![CDATA[$F{start}]]></textFieldExpressi
on>
isPrintRepeatedValues="true"
</textField>
isPrintInFirstWholeBand="false"
isRemoveLineWhenBlank="false"
isPrintWhenDetailOverflows="false"/>
<textField isStretchWithOverflow="false" pattern="#,##0.00"
isBlankWhenNull="false"
evaluationTime="Now"
<box
topBorder="None"
topBorderColor="#000000"
hyperlinkType="None" hyperlinkTarget="Self" >
leftBorder="None"
leftBorderColor="#000000"
90
width="56"
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
height="18"
textAlignment="Left"
rotation="None"
forecolor="#000000"
backcolor="#FFFFFF"
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
key="textField-9"
stretchType="NoStretch"
positionType="Float"
</textElement>
isPrintRepeatedValues="true"
<textFieldExpression
class="java.util.Date"><![CDATA[$F{end}]]></textFieldExpressi
on>
isRemoveLineWhenBlank="false"
</textField>
isPrintWhenDetailOverflows="false"/>
isPrintInFirstWholeBand="false"
<textField isStretchWithOverflow="false" pattern="#,##0.00"
<box topBorder="None" topBorderColor="#000000"
isBlankWhenNull="false"
evaluationTime="Now"leftBorder="None"
leftBorderColor="#000000"
hyperlinkType="None" hyperlinkTarget="Self" >
rightBorder="None"
rightBorderColor="#000000"
bottomBorder="None" bottomBorderColor="#000000"/>
<reportElement
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
mode="Opaque"
x="467"
textAlignment="Right"
rotation="None"
<font
fontName="Arial"
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"
pdfEncoding ="Cp1252" isStrikeThrough="false" />
y="1"
width="64"
height="18"
</textElement>
forecolor="#000000"
key="textField-8"
<textFieldExpression
class="java.lang.Double"><![CDATA[$F{totalCosts}]]></textFiel
dExpression>
stretchType="NoStretch"
</textField>
positionType="Float"
</band>
isPrintRepeatedValues="true"
</detail>
isRemoveLineWhenBlank="false"
<columnFooter>
isPrintInFirstWholeBand="false"
<band height="8" isSplitAllowed="true" >
isPrintWhenDetailOverflows="false"/>
</band>
backcolor="#FFFFFF"
<box topBorder="None" topBorderColor="#000000"</columnFooter>
leftBorder="None"
leftBorderColor="#000000"
rightBorder="None"
rightBorderColor="#000000"<pageFooter>
bottomBorder="None" bottomBorderColor="#000000"/>
<band height="0" isSplitAllowed="true" >
<textElement
verticalAlignment="Bottom"
lineSpacing="Single">
textAlignment="Right"</band>
rotation="None"
</pageFooter>
<font
fontName="Arial"<summary>
pdfFontName="Helvetica"
size="12"
isBold="false"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"<band height="11" isSplitAllowed="true" >
pdfEncoding ="Cp1252" isStrikeThrough="false" />
</band>
</textElement>
</summary>
<textFieldExpression
</jasperReport>
class="java.lang.Double"><![CDATA[$F{remain}]]></textFieldEx
pression>
edu.ufsc.ganttproject.report.
pattern="#,##0.00"CostsTaskReport.jrxml
</textField>
<textField isStretchWithOverflow="false"
isBlankWhenNull="false"
evaluationTime="Now"<?xml version="1.0" encoding="UTF-8" ?>
hyperlinkType="None" hyperlinkTarget="Self" >
<!-- Created with iReport - A designer for JasperReports -->
<reportElement
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD
mode="Opaque"
Report
Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
x="333"
y="1"
<jasperReport
91
name="CostsTaskReport"
y="5"
columnCount="1"
width="67"
printOrder="Vertical"
height="17"
orientation="Portrait"
forecolor="#000000"
pageWidth="536"
backcolor="#FFFFFF"
pageHeight="842"
key="textField-1"
columnWidth="535"
stretchType="NoStretch"
columnSpacing="0"
positionType="FixRelativeToTop"
leftMargin="0"
isPrintRepeatedValues="true"
rightMargin="0"
isRemoveLineWhenBlank="false"
topMargin="0"
isPrintInFirstWholeBand="false"
bottomMargin="0"
isPrintWhenDetailOverflows="false"/>
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>
<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}]]></textFieldExpressi
on>
</textField>
<textField
isStretchWithOverflow="false"
pattern=""
isBlankWhenNull="false"
evaluationTime="Now"
hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
</background>
mode="Opaque"
<title>
<band height="0" isSplitAllowed="true" >
x="76"
y="5"
</band>
width="237"
</title>
height="17"
<pageHeader>
<band height="1" isSplitAllowed="true" >
forecolor="#000000"
backcolor="#FFFFFF"
</band>
key="textField-2"
</pageHeader>
stretchType="NoStretch"
<columnHeader>
<band height="0" isSplitAllowed="true" >
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
</band>
isRemoveLineWhenBlank="false"
</columnHeader>
isPrintInFirstWholeBand="false"
<detail>
<band height="25" isSplitAllowed="true" >
isPrintWhenDetailOverflows="false"/>
<box topBorder="None" topBorderColor="#000000"
<textField isStretchWithOverflow="false" pattern="dd/MM/yyyy"leftBorder="None"
leftBorderColor="#000000"
isBlankWhenNull="false"
evaluationTime="Now"
rightBorder="None"
rightBorderColor="#000000"
hyperlinkType="None" hyperlinkTarget="Self" >
bottomBorder="None" bottomBorderColor="#000000"/>
<reportElement
<textElement
textAlignment="Left"
mode="Opaque"
verticalAlignment="Top" rotation="None" lineSpacing="Single">
x="5"
92
<font
fontName="Arial"<summary>
pdfFontName="Helvetica"
size="10"
isBold="true"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"<band height="0" isSplitAllowed="true" >
pdfEncoding ="Cp1252" isStrikeThrough="false" />
</band>
</textElement>
</summary>
<textFieldExpression
</jasperReport>
class="java.lang.String"><![CDATA[$F{description}]]></textField
Expression>
</textField>
<textField isStretchWithOverflow="false" pattern="#,##0.00"
isBlankWhenNull="false"
evaluationTime="Now"
hyperlinkType="None" hyperlinkTarget="Self" >
<reportElement
mode="Opaque"
x="318"
y="4"
width="63"
Classes e arquivos alterados
net.sourceforge.ganttproject.gui.
GanttDialogProperties
height="17"
forecolor="#000000"
package net.sourceforge.ganttproject.gui;
backcolor="#FFFFFF"
key="textField-3"
stretchType="NoStretch"
positionType="FixRelativeToTop"
isPrintRepeatedValues="true"
isRemoveLineWhenBlank="false"
isPrintInFirstWholeBand="false"
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;
isPrintWhenDetailOverflows="false"/>
import javax.swing.JButton;
<box topBorder="None" topBorderColor="#000000"
leftBorder="None"
leftBorderColor="#000000"import javax.swing.JCheckBox;
rightBorder="None"
rightBorderColor="#000000"
import javax.swing.JColorChooser;
bottomBorder="None" bottomBorderColor="#000000"/>
<textElement
textAlignment="Right"import javax.swing.JComboBox;
verticalAlignment="Top" rotation="None" lineSpacing="Single"> import javax.swing.JDialog;
<font
fontName="Arial"import javax.swing.JFrame;
pdfFontName="Helvetica"
size="10"
isBold="true"
isItalic="false" isUnderline="false" isPdfEmbedded ="false"import javax.swing.JLabel;
pdfEncoding ="Cp1252" isStrikeThrough="false" />
import javax.swing.JSlider;
</textElement>
import javax.swing.JTextField;
<textFieldExpression
class="java.lang.Double"><![CDATA[$F{value}]]></textFieldExp import javax.swing.tree.DefaultMutableTreeNode;
ression>
</textField>
import net.sourceforge.ganttproject.GanttCalendar;
</band>
import net.sourceforge.ganttproject.GanttGraphicArea;
</detail>
import net.sourceforge.ganttproject.GanttTask;
<columnFooter>
import net.sourceforge.ganttproject.GanttTree2;
<band height="0" isSplitAllowed="true" >
import net.sourceforge.ganttproject.Mediator;
</band>
import net.sourceforge.ganttproject.language.GanttLanguage;
</columnFooter>
import net.sourceforge.ganttproject.task.Task;
<pageFooter>
import net.sourceforge.ganttproject.task.TaskManager;
<band height="1" isSplitAllowed="true" >
</band>
/**
</pageFooter>
* Dialog to edit the properties of a task
93
*/
/** GanttTask to edit */
public class GanttDialogProperties
private Task ttask;
extends JDialog
/** GanttGraphicArea of the application. */
implements ActionListener {
private GanttGraphicArea aarea;
/** JTextField for the name of task */
/** Button to choose the date */
private JTextField jtfname;
private JButton button;
/** JConboBox for the mother task */
/** Store old percent state value */
private JComboBox jcbfather;
int percentValue;
/** JTextField for the begining of the task */
/** The language */
private JTextField jtfbegin;
private GanttLanguage lang = GanttLanguage.getInstance();
/** JTextField for duration of task */
JFrame prj;
private JTextField jtflength;
int saveDuration;
/** JList for depends of task */
//LH
// private JList jldepend;
double saveCost;
/** JSlider for advent state of task */
Color saveColor;
private JSlider spercent;
/** true if the ok button was pressed */
/** JPanel for advancement label */
public boolean change = false;
private JLabel advancementLabel;
/** Color chooser dialog */
/** 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;
protected static
JColorChooser();
JColorChooser
colorChooser
=
new
// By CL
private GanttTaskPropertiesBean taskPropertiesBean;
private Task task;
private GanttTask[] tasks;
94
setResizable(false);
private GanttTree2 tree;
DialogAligner.center(this, getParent());
private GanttGraphicArea area;
applyComponentOrientation(lang.getComponentOrientation());
// GanttTask returnTask = taskPropertiesBean.getReturnTask();
private JFrame parent;
// set the ok button as default action for enter
if (getRootPane() != null)
/** Constructor */
getRootPane().setDefaultButton(taskPropertiesBean.okButton);
public GanttDialogProperties(JFrame parent, GanttTree2 tree, }
Hashtable managerHash, GanttTask[] tasks, GanttGraphicArea
area,
/** Search a string on an array */
String tasksNames) {
private int findTheIndex(Object s, String[] lot) {
super(parent,
GanttLanguage.getInstance().getText("propertiesFor")
+ " '" + tasksNames + "'", true);
for (int i = 0; i < lot.length; i++) {
if (s.toString() == lot[i]) {
this.tree = tree;
return i;
this.tasks = tasks;
}
// this.task = tasks [0];
}
saveDuration = tasks[0].getLength();
return 0;
//LH
saveCost = tasks[0].getBudget();
}
this.area = area;
/** When click on date button, it open the dialog to select date.
*/
this.parent = parent;
public void actionPerformed(ActionEvent evt) {
// tree.forwardScheduling();
taskPropertiesBean
tasks, tree,
=
new
if (evt.getSource() instanceof TestGanttRolloverButton) {
GanttTaskPropertiesBean(this,
TestGanttRolloverButton button = (TestGanttRolloverButton)
evt
managerHash);
Container cp = getContentPane();
taskPropertiesBean.addActionListener(this);
cp.add(taskPropertiesBean, BorderLayout.CENTER);
.getSource();
if (button.getName().equals("start")) {
GanttCalendar date = taskPropertiesBean.getStart();
GanttDialogDate dd = new GanttDialogDate(this,
date, true);
// this.setSize(600, 350);
this.pack();
dd.show();
95
//
taskPropertiesBean.setStart(dd.getDate(), false);
System.err.println("[GanttDialogProperties]
//
returnTask="+returnTask);
}
//
returnTask.setTaskID(this.task.getTaskID());
//
else if (button.getName().equals("finish")) {
getTaskManager().setTask(returnTask);
GanttCalendar date = taskPropertiesBean.getFinish();
DefaultMutableTreeNode father;
GanttDialogDate dd = new GanttDialogDate(this,
date, true);
< returnTask.length; i++) {
for (int i = 0; i
tree.getNode(tasks[i].getTaskID())
dd.show();
.setUserObject(returnTask[i]);
taskPropertiesBean.setEnd(dd.getDate(), false);
//
Refresh all father
} else if (button.getName().equals("third")) {
father = tree.getFatherNode(tree
GanttCalendar date = taskPropertiesBean.getThird();
.getNode(tasks[i].getTaskID()));
GanttDialogDate dd = new GanttDialogDate(this,
while (father != null) {
date);
tree.forwardScheduling();
dd.show();
father = tree.getFatherNode(father);
}
taskPropertiesBean.setThird(dd.getDate(), false);
}
}
}
}
});
else if (evt.getSource() instanceof JButton) {
tree.getJTree().repaint();
JButton button = (JButton) evt.getSource();
tree.getJTree().updateUI();
tree.getTable().setRowHeight(20);
if (button.getName().equals("ok")) {
area.repaint();
change = true;
this.setVisible(false);
}
dispose();
Mediator.getUndoManager().undoableEdit("Propertie else if (button.getName().equals("cancel")) {
s changed",
new Runnable() {
this.setVisible(false);
public void run() {
dispose();
Task[]
returnTask = taskPropertiesBean
.getReturnTask();
}
}
96
taskPropertiesBean.changeNameOfTask();
else if (evt.getSource() instanceof JTextField) {
}
JTextField textfield = (JTextField) evt.getSource();
} else if (evt.getSource() instanceof JComboBox) {
JComboBox comboBox = (JComboBox) evt.getSource();
if (comboBox.getName().equals("third")) {
if (textfield.getName().equals("length")) {
if (taskPropertiesBean.getThird() != null)
try {
int
duration
Integer.parseInt(textfield.getText().trim());
=
taskPropertiesBean.setThird(taskPropertiesBean.get
Third(),
false);
taskPropertiesBean.changeLength(duration);
else
saveDuration = duration;
} catch (Exception e) {
textfield.setText(saveDuration + "");
GanttDialogInfo
GanttDialogInfo(parent,
gdiError
=
taskPropertiesBean.setThird(taskPropertiesBean.get
Start()
new
.newAdd(0), false);
}
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION,
}
lang.getText("msg16"),
lang.getText("error"));
}
gdiError.show();
private TaskManager getTaskManager() {
taskPropertiesBean.changeLength(saveDuration);
return this.task.getManager();
}
}
}//LH
}
else if (textfield.getName().equals("cost")) {
try {
net.sourceforge.ganttproject.gui.
GanttTaskPropertiesBean
double
cost
Double.parseDouble(textfield.getText().trim());
=
taskPropertiesBean.changeBudget(cost);
saveCost = cost;
} catch (Exception e) {
import java.awt.BorderLayout;
textfield.setText(saveCost + "");
// TODO change the error message
GanttDialogInfo
GanttDialogInfo(parent,
gdiError
package net.sourceforge.ganttproject.gui;
=
import java.awt.Color;
import java.awt.Component;
new
import java.awt.Container;
import java.awt.FlowLayout;
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION,
import java.awt.GridBagConstraints;
lang.getText("msg16"),
lang.getText("error"));
gdiError.show();
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
taskPropertiesBean.changeBudget(saveCost);
import java.util.Hashtable;
import java.util.Vector;
}
import java.text.NumberFormat;
}
// Change the name of task
else
if
(textfield.getName().equals("name_of_task"))
import javax.swing.JFormattedTextField;
{
import javax.swing.ImageIcon;
import javax.swing.JButton;
97
import javax.swing.JCheckBox;
* Real panel for editing task properties
import javax.swing.JColorChooser;
*/
import javax.swing.JComboBox;
public class GanttTaskPropertiesBean
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
extends JPanel {
import javax.swing.JLabel;
import javax.swing.JPanel;
// Input attributes
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
// protected GanttTask selectedTask; //Task whose properties
will be shown
import javax.swing.JTextArea;
import javax.swing.JTextField;
protected GanttTask[] selectedTasks;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EtchedBorder;
protected Vector savePredecessors;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
private GanttTree2 tree; // GanttTree that contain all the tasks
information
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultMutableTreeNode;
private
GanttLanguage
language
GanttLanguage.getInstance(); // language
=
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttGraphicArea;
// the panel
import net.sourceforge.ganttproject.GanttProject;
// will
import net.sourceforge.ganttproject.GanttTask;
// display
import net.sourceforge.ganttproject.GanttTree2;
import net.sourceforge.ganttproject.Mediator;
private JDialog parent;
import
net.sourceforge.ganttproject.gui.taskproperties.CustomColumns // Output attributes: you can find the definition is GanttTask
Panel;
import
net.sourceforge.ganttproject.gui.taskproperties.CostsPanel;
// private String name;
import
net.sourceforge.ganttproject.gui.taskproperties.TaskAllocations
private int length;
Panel;
import
net.sourceforge.ganttproject.gui.taskproperties.TaskDependenc private int percentComplete;
iesPanel;
import net.sourceforge.ganttproject.language.GanttLanguage;
import
net.sourceforge.ganttproject.resource.HumanResourceManage
r;
import net.sourceforge.ganttproject.roles.RoleManager;
private int priority;
//LH
private double budget;
import net.sourceforge.ganttproject.shape.JPaintCombo;
import net.sourceforge.ganttproject.shape.ShapeConstants;
private GanttCalendar start;
import net.sourceforge.ganttproject.shape.ShapePaint;
import net.sourceforge.ganttproject.task.Task;
private GanttCalendar end;
import net.sourceforge.ganttproject.task.TaskImpl;
import net.sourceforge.ganttproject.task.TaskMutator;
private GanttCalendar third;
import net.sourceforge.ganttproject.util.BrowserControl;
private boolean bilan;
/**
98
private boolean isProjectTask;
//LH
JLabel budgetLabel1;
private String notes;
JLabel lblWebLink;
// private GanttTask selectedTaskClone;
JTextField tfWebLink;
// private Hashtable managerHash;
//
JButton bWebLink;
// private Hashtable assignedResources = new Hashtable();
// private attributes for internal use
JPanel secondRowPanel1; // components in second row
GridBagConstraints gbc = new GridBagConstraints();
JSpinner percentCompleteSlider;
FlowLayout flowL = new FlowLayout(FlowLayout.LEFT, 10, 10); JLabel percentCompleteLabel1;
JTabbedPane tabbedPane; // TabbedPane that include theJLabel priorityLabel1;
following four items
JComboBox priorityComboBox;
JPanel generalPanel;
JPanel thirdRowPanel1; // componets in third row
JPanel predecessorsPanel;
JTextField startDateField1;
JPanel resourcesPanel;
JTextField finishDateField1;
JPanel notesPanel;
JTextField thirdDateField1;
//LH
JPanel costsPanel;
// Components on general pannel
JPanel firstRowPanel1; // components in first row
JTextField nameField1;
JTextField durationField1;
//LH
JLabel startDateLabel1;
JLabel finishDateLabel1;
JComboBox thirdDateComboBox;
JButton startDateButton1;
JButton finishDateButton1;
JButton thirdDateButton1;
//JTextField budgetField1;
JFormattedTextField budgetField1;
JPanel lastRowPanel1; // components in last row
JPanel webLinkPanel; // components in web link panel
JLabel nameLabel1;
JLabel mileStoneLabel1;
JLabel durationLabel1;
99
JCheckBox mileStoneCheckBox1;
JPanel firstRowPanelNotes;
JCheckBox projectTaskCheckBox1;
JPanel secondRowPanelNotes;
JButton colorButton;
// Component on the SOUTH ok CANCEL buttons
boolean isColorChanged;
public JButton okButton;
JButton colorSpace;
JButton cancelButton;
JPanel colorPanel;
JPanel southPanel;
/** Shape chooser combo Box */
private boolean onlyOneTask = false;
JPaintCombo shapeComboBox;
private String taskWebLink;
// Components on predecessors pannel
private boolean taskIsMilestone;
JLabel nameLabel2; // first row, here the textfield is un-editable
private GanttCalendar taskStartDate;
JLabel durationLabel2;
private GanttCalendar taskEndDate;
JTextField nameField2;
private GanttCalendar taskThirdDate;
JPanel firstRowPanel2;
private int taskThirdDateConstraint;
JScrollPane predecessorsScrollPane; // second row, a table
private boolean taskIsProjectTask;
JLabel nameLabelNotes;
private int taskLength;
JLabel durationLabelNotes;
private String taskNotes;
//LH
JLabel budgetLabelNotes;
private int taskCompletionPercentage;
JTextField nameFieldNotes;
private int taskPriority;
JTextField durationFieldNotes;
//LH
private double taskBudget;
//LH
//JTextField budgetFieldNotes;
private boolean taskIsStartFixed;
JFormattedTextField budgetFieldNotes;
private boolean taskIsFinishFixed;
JScrollPane scrollPaneNotes;
private Color taskColor;
JTextArea noteAreaNotes;
private ShapePaint taskShape;
100
container.setLayout(new GridBagLayout());
gbc.weightx = 0;
private CustomColumnsPanel myCustomColumnPanel = null;
gbc.weighty = 0;
// private ResourcesTableModel myResourcesTableModel;
gbc.anchor = GridBagConstraints.WEST;
private TaskDependenciesPanel myDependenciesPanel;
gbc.insets.right = 15;
gbc.insets.left = 10;
gbc.insets.top = 10;
private TaskAllocationsPanel[] myAllocationsPanel;
addUsingGBL(container, nameLabel, gbc, 0, 0, 1, 1);
addUsingGBL(container, nameField, gbc, 1, 0, 1, 1);
private CostsPanel myCostsPanel = null;;
addUsingGBL(container, durationLabel, gbc, 2, 0, 1,
1);
private boolean isStartFixed;
gbc.weightx = 1;
//
addUsingGBL(container, durationField, gbc, 3, 0, 1,
private boolean isFinishFixed;
1);
//LH
private
final
myHumanResourceManager;
HumanResourceManager
addUsingGBL(container, budgetLabel, gbc, 4, 0, 1,
1);
addUsingGBL(container, budgetField, gbc, 5, 0, 1, 1);
private final RoleManager myRoleManager;
}
private Task myUnpluggedClone;
/** Construct the general panel */
private void constructGeneralPanel() {
/** add a component to container by using GridBagConstraints.
generalPanel = new JPanel(new GridBagLayout());
*/
// first row
private void addUsingGBL(Container container, Component+ ":");
component,
nameLabel1 = new JLabel(language.getText("name")
nameField1 = new JTextField(20);
nameField1.setName("name_of_task");
GridBagConstraints gbc, int x,
if (!onlyOneTask) {
int y, int w, int h) {
nameLabel1.setVisible(false);
gbc.gridx = x;
nameField1.setVisible(false);
gbc.gridy = y;
}
gbc.gridwidth = w;
gbc.gridheight = h;
gbc.weighty = 0;
durationLabel1
=
JLabel(language.getText("length") + ":");
container.add(component, gbc);
new
durationField1 = new JTextField(8);
durationField1.setName("length");
firstRowPanel1 = new JPanel(flowL);
}
//LH
/** set the first row in all the tabbed pane. thus give them a
budgetLabel1
=
common look */
JLabel(language.getText("budget") + ":");
new
//budgetField1 = new JTextField(8);
private
void
setFirstRow(Container
GridBagConstraints gbc,
container,
NumberFormat
format
JLabel nameLabel, JTextField nameField,NumberFormat.getNumberInstance();
JLabel durationLabel,
format.setMinimumFractionDigits(2);
JTextField
durationField,
JLabel
format.setMaximumFractionDigits(2);
budgetLabel, JTextField budgetField) {
=
101
thirdDateComboBox.setSelectedIndex(selectedTasks
budgetField1 = new JFormattedTextField(format);
[0]
.getThirdDateConstraint());
budgetField1.setColumns(8);
thirdDateField1 = new JTextField(12);
budgetField1.setName("budget");
thirdDateField1.setEditable(false);
setFirstRow(firstRowPanel1,
nameField1,
gbc,
nameLabel1,
ImageIcon
icon
=
ImageIcon(getClass().getResource(
durationField1,
"/icons/calendar_16.gif"));
durationLabel1,
budgetLabel1, budgetField1);
new
// second row
percentCompleteLabel1
=
JLabel(language.getText("advancement")); // Progress
startDateButton1
new
TestGanttRolloverButton(icon);
SpinnerNumberModel
spinnerModel
SpinnerNumberModel(0, 0, 100, 1);
new
percentCompleteSlider
JSpinner(spinnerModel);
=
=
startDateButton1.setName("start");
.getText("chooseDate")));
finishDateButton1
TestGanttRolloverButton(icon);
// secondRowPanel1.add(percentCompleteField1);
secondRowPanel1.add(percentCompleteSlider);
=
=
new
finishDateButton1.setName("finish");
secondRowPanel1.add(percentCompleteLabel1);
finishDateButton1.setToolTipText(GanttProject.getTo
olTip(language
.getText("chooseDate")));
new
thirdDateButton1
TestGanttRolloverButton(icon);
secondRowPanel1.add(priorityLabel1);
=
new
thirdDateButton1.setName("third");
priorityComboBox = new JComboBox();
"));
new
startDateButton1.setToolTipText(GanttProject.getTool
newTip(language
secondRowPanel1 = new JPanel(flowL);
priorityLabel1
JLabel(language.getText("priority"));
=
thirdDateButton1.setToolTipText(GanttProject.getTool
priorityComboBox.addItem(language.getText("low")); Tip(language
priorityComboBox.addItem(language.getText("normal
.getText("chooseDate")));
priorityComboBox.addItem(language.getText("hight"))
if (selectedTasks[0].getThirdDateConstraint() == 0)
;
thirdDateButton1.setEnabled(false);
priorityComboBox.setEditable(false);
GridBagLayout
GridBagLayout();
secondRowPanel1.add(priorityComboBox);
new
TitledBorder(new
.getText("date")));
startDateField1.setEditable(false);
new
finishDateField1 = new JTextField(12);
finishDateField1.setEditable(false);
thirdDateComboBox = new JComboBox();
thirdDateComboBox.addItem("");
thirdDateComboBox.addItem(language.getText("earli
estBegin"));
thirdDateComboBox.setName("third");
new
thirdRowPanel1 = new JPanel(flowL);
thirdRowPanel1.setBorder(new
EtchedBorder(), language
startDateField1 = new JTextField(12);
finishDateLabel1
=
JLabel(language.getText("dateOfEnd") + ":");
=
// TODO put the date
// third row
startDateLabel1
=
JLabel(language.getText("dateOfBegining") + ":");
thirdRowPanel1Layout
JPanel startDatePanel = new JPanel(
new
FlowLayout(FlowLayout.LEFT, 5, 0));
startDatePanel.add(startDateLabel1);
startDatePanel.add(startDateField1);
startDatePanel.add(startDateButton1);
JPanel
finishDatePanel
FlowLayout(FlowLayout.LEFT, 5,
=
new
JPanel(new
0));
finishDatePanel.add(finishDateLabel1);
finishDatePanel.add(finishDateField1);
102
new
finishDatePanel.add(finishDateButton1);
ActionListener() {
JPanel thirdDatePanel = new JPanel(
public void actionPerformed(ActionEvent e) {
new
FlowLayout(FlowLayout.LEFT, 5, 0));
colorButton
thirdDatePanel.add(thirdDateComboBox);
thirdDatePanel.add(thirdDateField1);
.setBackground(GanttDialogProperties.colorChooser
thirdDatePanel.add(thirdDateButton1);
.getColor());
// thirdRowPanel1.add(startDatePanel);
isColorChanged = true;
// thirdRowPanel1.add(finishDatePanel);
}
// thirdRowPanel1.add(thirdDatePanel);
}
addUsingGBL(thirdRowPanel1, startDatePanel, gbc,
0, 0, 1, 1);
addUsingGBL(thirdRowPanel1, finishDatePanel, gbc,
0, 1, 1, 1);
ActionListener() {
addUsingGBL(thirdRowPanel1, thirdDatePanel, gbc,
0, 2, 1, 1);
,
new
public void actionPerformed(ActionEvent e) {
// nothing to do for "Cancel"
// fourth row
}
JCheckBox checkBox = constructCheckBox ();
});
lastRowPanel1 = new JPanel(flowL);
if (checkBox != null)
/*
lastRowPanel1.add(checkBox);
*
AbstractColorChooserPanel[]
panels =
*
GanttDialogProperties.colorChooser.getChooserPanels();
JPanel shapePanel = new JPanel();
shapePanel.setLayout(new BorderLayout());
JLabel
lshape
=
language.getText("shape") + " ");
new
JLabel("
"
*
GanttDialogProperties.colorChooser.removeChooserPanel(pan
+els[0]);
*
newGanttDialogProperties.colorChooser.addChooserPanel(panels[
0]);
shapeComboBox
=
JPaintCombo(ShapeConstants.PATTERN_LIST);
*/
shapePanel.add(lshape, BorderLayout.WEST);
shapePanel.add(shapeComboBox,
BorderLayout.CENTER);
GanttDialogProperties.colorChooser.setColor(colorBu
tton
colorButton
=
JButton(language.getText("colorButton"));
new
.getBackground());
dialog.show();
colorButton.setBackground(selectedTasks[0].getColor
());
}
final
String
language.getText("selectColor");
colorChooserTitle
=
});
colorButton.addActionListener(new ActionListener() {
colorSpace
=
public void actionPerformed(ActionEvent e)JButton(language.getText("defaultColor"));
{
colorSpace.setBackground(GanttGraphicArea.taskDe
faultColor);
JDialog dialog;
dialog
JColorChooser.createDialog(parent, colorChooserTitle,
true,
GanttDialogProperties.colorChooser,
new
=
nguage
colorSpace.setToolTipText(GanttProject.getToolTip(la
.getText("resetColor")));
colorSpace.addActionListener(new ActionListener() {
103
public void actionPerformed(ActionEvent e)
{
bWebLink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
colorButton.setBackground(GanttGraphicArea.taskDe
{
faultColor);
// link to open the web link
isColorChanged = true;
try {
}
if
(!BrowserControl.displayURL(tfWebLink.getText())) {
});
GanttDialogInfo gdi = new GanttDialogInfo(null,
colorPanel = new JPanel();
colorPanel.setLayout(new BorderLayout());
GanttDialogInfo.ERROR,
colorPanel.add(colorButton, "West");
colorPanel.add(colorSpace, "Center");
GanttDialogInfo.YES_OPTION, language
colorPanel.add(shapePanel, BorderLayout.EAST);
.getText("msg4"), language
lastRowPanel1.add(colorPanel);
.getText("error"));
// ---Set GridBagConstraints constant
gdi.show();
gbc.anchor = GridBagConstraints.WEST;
}
gbc.insets.right = 15;
} catch (Exception ex) {
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.gridy = 4;
generalPanel.add(webLinkPanel, gbc);
gbc.gridx = 0;
}
gbc.gridy = 3;
gbc.gridwidth = 1;
/** Add the differents action listener on the differents widgets */
gbc.gridheight = GridBagConstraints.RELATIVE;
public void addActionListener(ActionListener l) {
gbc.anchor = GridBagConstraints.WEST;
gbc.weighty = 1;
nameField1.addActionListener(l);
generalPanel.add(lastRowPanel1, gbc);
startDateButton1.addActionListener(l);
// The panel for the web link
webLinkPanel = new JPanel(flowL);
lblWebLink
=
JLabel(language.getText("webLink"));
new
webLinkPanel.add(lblWebLink);
finishDateButton1.addActionListener(l);
thirdDateButton1.addActionListener(l);
tfWebLink = new JTextField(30);
webLinkPanel.add(tfWebLink);
bWebLink =
ImageIcon(getClass()
new
thirdDateComboBox.addActionListener(l);
TestGanttRolloverButton(new
okButton.addActionListener(l);
.getResource("/icons/web_16.gif")));
bWebLink.setToolTipText(GanttProject.getToolTip(lan
cancelButton.addActionListener(l);
guage
.getText("openWebLink")));
durationField1.addActionListener(l);
webLinkPanel.add(bWebLink);
104
budgetField1.addActionListener(l);
}
}
/** construct the notes pannel */
/** Change the name of the task on all textfiled of task name */ private void constructNotesPanel() {
public void changeNameOfTask() {
if (nameField1 != null && nameFieldNotes != null) {
String
nameField1.getText().trim();
nameOfTask
notesPanel = new JPanel(new GridBagLayout());
=
// first row
nameField1.setText(nameOfTask);
if (onlyOneTask)
nameLabelNotes
JLabel(language.getText("name") + ":");
=
new
myDependenciesPanel.nameChanged(nameOfTask);
nameFieldNotes = new JTextField(20);
myAllocationsPanel[0].nameChanged(nameOfTask);
nameFieldNotes.setText(nameOfTask);
if (!onlyOneTask) {
}
nameLabelNotes.setVisible(false);
}
nameFieldNotes.setVisible(false);
}
private void constructCustomColumnPanel() {
myCustomColumnPanel
CustomColumnsPanel(Mediator
=
new
durationLabelNotes
JLabel(language.getText("length") + ":");
.getCustomColumnsStorage());
=
new
=
new
}
//LH
/** Construct the predecessors tabbed pane */
// TODO put string in properties
budgetLabelNotes
JLabel(language.getText("budget") + ":");
new
private void constructPredecessorsPanel() {
myDependenciesPanel
=
TaskDependenciesPanel(selectedTasks[0]);
predecessorsPanel
myDependenciesPanel.getComponent();
=
}
durationFieldNotes = new JTextField(8);
//LH
//budgetFieldNotes = new JTextField(8);
/** Construct the resources panel */
budgetFieldNotes
=
new
JFormattedTextField(NumberFormat.getCurrencyInstance());
budgetFieldNotes.setColumns(8);
private void constructResourcesPanel() {
myAllocationsPanel
=
TaskAllocationsPanel[selectedTasks.length];
new
nameFieldNotes.setEditable(false);
for (int i = 0; i < myAllocationsPanel.length; i++) {
myAllocationsPanel[i]
TaskAllocationsPanel(selectedTasks[i],
myHumanResourceManager,
onlyOneTask);
=
new
myRoleManager,
if (i != 0)
durationFieldNotes.setEditable(false);
budgetFieldNotes.setEditable(false);
firstRowPanelNotes = new JPanel();
myAllocationsPanel[i].getComponent();
setFirstRow(firstRowPanelNotes,
nameLabelNotes, nameFieldNotes,
}
resourcesPanel
myAllocationsPanel[0].getComponent();
gbc,
=
105
durationLabelNotes,
budgetLabelNotes, budgetFieldNotes);
durationFieldNotes,
gbc.weighty = 1;
gbc.gridx = 0;
secondRowPanelNotes = new JPanel();
gbc.gridy = 1;
secondRowPanelNotes.setBorder(new
TitledBorder(new EtchedBorder(),
gbc.gridwidth = 1;
language.getText("notesTask") +
":"));
gbc.gridheight = 1;
noteAreaNotes = new JTextArea(8, 40);
noteAreaNotes.setLineWrap(true);
notesPanel.add(secondRowPanelNotes, gbc);
noteAreaNotes.setWrapStyleWord(true);
1.0f));
noteAreaNotes.setBackground(new Color(1.0f, 1.0f,}
scrollPaneNotes = new JScrollPane(noteAreaNotes);
//LH
/** construct the costs pannel */
secondRowPanelNotes.add(scrollPaneNotes);
private void constructCostsPanel() {
JButton bdate = new TestGanttRolloverButton(newMediator
ImageIcon(getClass()
//costsPanel = new CostsPanel(selectedTasks[0],
//
.getCostStorage());
.getResource("/icons/clock_16.gif")));
myCostsPanel = new CostsPanel(selectedTasks[0]);
bdate.setToolTipText(GanttProject.getToolTip(langua
costsPanel = myCostsPanel.getComponent();
ge
}
.getText("putDate")));
bdate.addActionListener(new ActionListener() {
public
void
/** Construct the south panel */
actionPerformed(ActionEvent
evt) {
noteAreaNotes.append("\n"
GanttCalendar.getDateAndTime()
+private void constructSouthPanel() {
+ "\n");
okButton = new JButton(language.getText("ok"));
}
});
okButton.setName("ok");
secondRowPanelNotes.add(bdate);
if (getRootPane() != null)
gbc.anchor = GridBagConstraints.WEST;
getRootPane().setDefaultButton(okButton);
// set ok the defuault
// button when press
gbc.insets.right = 15;
// "enter" --> check
// because
gbc.insets.left = 10;
// getRootPane()==null
// !!!
gbc.insets.top = 10;
gbc.weighty = 0;
cancelButton
JButton(language.getText("cancel"));
addUsingGBL(notesPanel, firstRowPanelNotes, gbc,
0, 0, 1, 1);
=
new
cancelButton.setName("cancel");
106
southPanel
=
new
FlowLayout(FlowLayout.TRAILING, 50, 10));
JPanel(new
// set resources comboBox
southPanel.add(okButton);
/*
*
setUpResourcesComboColumn(((ResourceManager)managerH
ash.get("HUMAN_RESOURCE")).getResources(),
southPanel.add(cancelButton);
* resourcesTable.getColumnModel().getColumn(0));
//set column editor
}
*/
/** Constructor */
/*
public GanttTaskPropertiesBean(JDialog parent, GanttTask[]
*
tabbedPane
=
new
JTabbedPane();
selectedTasks,
constructGeneralPanel();
GanttTree2 tree, Hashtable managerHash)
* tabbedPane.add("General", generalPanel);
{
*
constructPredecessorsPanel();
this.parent = parent;
tabbedPane.add("Predecessors",
this.onlyOneTask = false;
* predecessorsPanel); constructResourcesPanel();
if (selectedTasks.length == 1)
this.onlyOneTask = true;
this.selectedTasks = selectedTasks;
* tabbedPane.add("Resources",
constructNotesPanel();
resourcesPanel);
*
tabbedPane.add("Notes",
add(tabbedPane);
notesPanel);
setInitialValues(selectedTasks[0]);
*/
savePredecessors
selectedTasks[0].getPredecessorsOld();
=
myHumanResourceManager
(HumanResourceManager) managerHash
=}
.get(GanttProject.HUMAN_RESOURCE_MANAGER_
ID);
/** Init the widgets */
public void init() {
myRoleManager = (RoleManager) managerHash
tabbedPane = new JTabbedPane();
.get(GanttProject.ROLE_MANAGER_ID);
setTree(tree);
tabbedPane.getModel().addChangeListener(new
ChangeListener() {
init();
public void stateChanged(ChangeEvent e) {
changeNameOfTask();
// this.managerHash = managerHash;
fireDurationChanged();
fireBudgetChanged();
setSelectedTask();
}
});
constructGeneralPanel();
// set predecessor comboBox
tabbedPane.addTab(language.getText("general"),
new ImageIcon(getClass()
//
.getResource("/icons/properties_16.gif")),
setUpPredecessorComboColumn(predecessorsTable.getColum generalPanel);
nModel().getColumn(1),
// predecessorsTable); //set column editor
if (onlyOneTask) {
//
setUpTypeComboColumn(predecessorsTable.getColumnModel
().getColumn(2));
// //set column editor
constructPredecessorsPanel();
tabbedPane.addTab(language.getText("predecessors
"), new ImageIcon(
107
/**
getClass().getResource("/icons/relashion.gif")),
predecessorsPanel);
* as the name indicated, it will not replace the original
GanttTask in the
* Tree.
}
*/
constructResourcesPanel();
public Task[] getReturnTask() {
GanttTask[]
returnTask
tabbedPane.addTab(GanttProject.correctLabel(langu
GanttTask[selectedTasks.length];
age.getText("human")),
new
ImageIcon(getClass().getResource("/icons/res_16.gif")),
resourcesPanel);
=
new
for (int i = 0; i < selectedTasks.length; i++) {
if
(myAllocationsPanel[0].getTableModel().isChanged()) {
if (i != 0)
constructNotesPanel();
copyValues(myAllocationsPanel[0].getTableModel(),
tabbedPane.addTab(language.getText("notesTask"),
new ImageIcon(
myAllocationsPanel[i].getTableModel());
getClass().getResource("/icons/note_16.gif")),
notesPanel);
}
myAllocationsPanel[i].getTableModel().commit();
setLayout(new BorderLayout());
returnTask[i] = selectedTasks[i];
add(tabbedPane, BorderLayout.CENTER);
//
returnTask.setTaskID(selectedTask.getTaskID());
constructSouthPanel();
TaskMutator
returnTask[i].createMutator();
mutator
=
add(southPanel, BorderLayout.SOUTH);
if (onlyOneTask) {
constructCustomColumnPanel();
mutator.setName(getTaskName()); // getName()
tabbedPane.addTab(language.getText("customColu
mns"), new ImageIcon(
mutator.setProjectTask (false);
}
getClass().getResource("/icons/custom.gif")),
myCustomColumnPanel);
if
(this.taskWebLink
!this.taskWebLink.equals(getWebLink()))
!=
null
&&
returnTask[i].setWebLink(getWebLink()); // getName()
//LH
if (mileStoneCheckBox1 != null) {
if (onlyOneTask) {
constructCostsPanel();
if
(this.taskIsMilestone
!=
isBilan())
tabbedPane.addTab(language.getText("costs"), new
ImageIcon(
mutator.setMilestone(isBilan());
returnTask[i].setChecked(false);
getClass().getResource("/icons/custom.gif")),
}
costsPanel);
else if (projectTaskCheckBox1 != null) {
}
}
if
(this.taskIsProjectTask
!=
isProjectTask())
mutator.setProjectTask(isProjectTask());
// Input methods
}
if (!this.taskStartDate.equals(getStart()))
108
mutator.setStart(getStart());
if
(((this.taskThirdDate
==
null)
.equals((ShapePaint) shapeComboBox
&&
(getThird() != null))
.getSelectedPaint()))))
||
((this.taskThirdDate
||
ShapePaint(
((this.taskThirdDate
!= null) && (getThird() == null))
returnTask[i].setShape(new
!= null) && (!this.taskThirdDate
(ShapePaint)
shapeComboBox.getSelectedPaint(),
.equals(getThird()))))
Color.white,
returnTask[i].getColor()));
mutator.setThird(getThird(),
getThirdDateConstraint());
if (returnTask[i].getShape() != null)
returnTask[i].setShape(new
ShapePaint(returnTask[i].getShape(),
if (getLength() > 0) {
if (this.taskLength != getLength()) returnTask[i].getColor()));
Color.white,
mutator.setDuration(returnTask[i].getManager()
mutator.commit();
.createLength(getLength()));
if (onlyOneTask) {
myDependenciesPanel.getTableModel().commit();
}
}
if (!this.taskNotes.equals(getNotes()))
returnTask[i].applyThirdDateConstraint();
}
returnTask[i].setNotes(getNotes());
if
getPercentComplete())
(this.taskCompletionPercentage
!=
return returnTask;
mutator.setCompletionPercentage(getPercentComple
te());
}
if (this.taskPriority != getPriority())
/** as the name indicated */
returnTask[i].setPriority(getPriority());
//LH
public void setSelectedTask() {
if (this.taskBudget != getBudget())
// this.selectedTask = selectedTask;
returnTask[i].setBudget(getBudget());
if (this.taskIsStartFixed != isStartFixed)
nameField1.setText(selectedTasks[0].getName());
returnTask[i].setStartFixed(isStartFixed);
//LH
// nameField2.setText(selectedTask.toString());
if (onlyOneTask)
nameFieldNotes.setText(selectedTasks[0].toString());
myCostsPanel.getTableModel().commit();
//
//
setName(selectedTasks[0].toString());
if (this.taskIsFinishFixed != isFinishFixed)
returnTask[i].setFinishFixed(isFinishFixed);
durationField1.setText(selectedTasks[0].getLength()
if (isColorChanged)
+ "");
returnTask[i].setColor(colorButton.getBackground());
if
((((this.taskShape
==
(shapeComboBox.getSelectedIndex() != 0)))
||
null)
((this.taskShape
&&
"");
// durationField2.setText(selectedTask.getLength() +
!=
null) && (!this.taskShape
durationFieldNotes.setText(selectedTasks[0].getLeng
th() + "");
109
for
(int
j
=
0;
ShapeConstants.PATTERN_LIST.length; j++) {
//LH
+ "");
j
<
if
//budgetField1.setText(selectedTasks[0].getBudget() (selectedTasks[0].getShape().equals(
budgetField1.setValue(new
Double(selectedTasks[0].getBudget()));
ShapeConstants.PATTERN_LIST[j])) {
//budgetFieldNotes.setText(selectedTasks[0].getBudg
shapeComboBox.setSelectedIndex(j);
et() + "");
break;
budgetFieldNotes.setValue(new
Double(selectedTasks[0].getBudget()));
}
}
percentCompleteSlider.setValue(new
Integer(selectedTasks[0]
}
.getCompletionPercentage()));
noteAreaNotes.setText(selectedTasks[0].getNotes());
percentCompleteLabel1.setText(language.getText("a
dvancement"));
setStartFixed(selectedTasks[0].isStartFixed());
//
setFinishFixed(selectedTasks[0].isFinishFixed());
myUnpluggedClone
priorityComboBox.setSelectedIndex(selectedTasks[0]
selectedTasks[0].unpluggedClone();
.getPriority());
}
=
startDateField1.setText(selectedTasks[0].getStart().to
String());
String());
/** as the name indicated */
finishDateField1.setText(selectedTasks[0].getEnd().to public void setTree(GanttTree2 tree) {
this.tree = tree;
if (selectedTasks[0].getThird() != null) {
thirdDateField1.setText(selectedTasks[0].getThird().to}
String());
setThird(selectedTasks[0].getThird().Clone(), true);
// Output methods
}
/** as the name indicated */
setStart(selectedTasks[0].getStart().Clone(), true);
public boolean isBilan() {
setEnd(selectedTasks[0].getEnd().Clone(), true);
bilan = mileStoneCheckBox1.isSelected();
bilan = selectedTasks[0].isMilestone();
return bilan;
isProjectTask = selectedTasks[0].isProjectTask();
}
if (mileStoneCheckBox1 != null)
mileStoneCheckBox1.setSelected(bilan);
public boolean isProjectTask() {
else if (projectTaskCheckBox1 != null)
isProjectTask = projectTaskCheckBox1.isSelected();
projectTaskCheckBox1.setSelected(isProjectTask);
return isProjectTask;
tfWebLink.setText(selectedTasks[0].getWebLink());
}
if (selectedTasks[0].shapeDefined()) {
110
/** as the name indicated */
} catch (NumberFormatException e) {
//
}
public GanttCalendar getEnd() {
//
//
}
return end;
//
//
public void fireBudgetChanged() {
}
//String value = budgetField1.getText();
if (budgetField1.getValue() != null)
try {
/** as the name indicated */
public GanttCalendar getThird() {
return third;
}
//double
Double.parseDouble(value);
budget
=
//double
budget
((Number)budgetField1.getValue()).doubleValue();
=
double
budget
=
((Number)NumberFormat.getNumberInstance().parse(budgetFi
eld1.getText())).doubleValue();
public int getThirdDateConstraint() {
changeBudget(budget);
return thirdDateComboBox.getSelectedIndex();
} catch (Exception e) {
}
System.out.println("Budget
Error:"
+
e.getMessage());
/** as the name indicated */
public int getLength() {
length
Integer.parseInt(durationField1.getText().trim());
}
}
=/** Set the duration of the task */
public void changeLength(int _length) {
return length;
if (_length <= 0) {
_length = 1;
}
}
//LH
durationField1.setText(_length + "");
public double getBudget() {
if (onlyOneTask)
//budget
Double.parseDouble(budgetField1.getText().trim());
=
budget
((Number)budgetField1.getValue()).doubleValue();
=
myDependenciesPanel.durationChanged(_length);
myAllocationsPanel[0].durationChanged(_length);
durationFieldNotes.setText(_length + "");
length = _length;
// change the end date
return budget;
GanttCalendar _end = start.newAdd(length);
this.end = _end;
}
finishDateField1.setText(_end.toString());
public void fireDurationChanged() {
}
String value = durationField1.getText();
/** Change the budget of the task on all textfiled of task budget
*/
try {
int duration = Integer.parseInt(value);
changeLength(duration);
public void changeBudget(double _budget) {
//budgetField1.setText(_budget + "");
111
budgetField1.setValue(new Double(_budget));
/** Return the priority level of the task */
if (onlyOneTask)
public int getPriority() {
myDependenciesPanel.budgetChanged(_budget);
priority = priorityComboBox.getSelectedIndex();
myAllocationsPanel[0].budgetChanged(_budget);
myCostsPanel.budgetChanged(_budget);
return priority;
}
//budgetFieldNotes.setText(_budget + "");
budgetFieldNotes.setValue(new Double(_budget));
public void setStartFixed(boolean startFixed) {
budget = _budget;
isStartFixed = startFixed;
startDateField1.setForeground(isStartFixed
Color.BLACK : Color.GRAY);
}
?
}
/** as the name indicated */
//
public String getNotes() {
notes = noteAreaNotes.getText();
//
isFinishFixed = startFixed;
//
finishDateField1
//
Color.GRAY);
//
return notes;
public void setFinishFixed(boolean startFixed) {
.setForeground(isFinishFixed ? Color.BLACK :
}
/** Return the start date of the task */
}
public GanttCalendar getStart() {
start.setFixed(isStartFixed);
/** Return the name of the task */
return start;
}
public String getTaskName() {
String text = nameField1.getText();
return text == null ? "" : text.trim();
public GanttCalendar getFinish() {
//
}
end.setFixed(isFinishFixed);
return end;
}
/** @return the web link of the task. */
public String getWebLink() {
String text = tfWebLink.getText();
return text == null ? "" : text.trim();
/** Change the start date of the task */
public void setStart(GanttCalendar dstart, boolean test) {
if (test == true) {
}
startDateField1.setText(dstart.toString());
this.start = dstart;
/** as the name indicated */
return;
}
public int getPercentComplete() {
percentComplete
percentCompleteSlider.getValue())
=
.hashCode();
return percentComplete;
((Integer)
startDateField1.setText(dstart.toString());
this.start = dstart;
this.setStartFixed(dstart.isFixed());
if (this.start.compareTo(this.end) < 0) {
adjustLength();
}
} else {
112
GanttCalendar
start.newAdd(length);
_end
this.third = null;
=
break;
this.end = _end;
finishDateField1.setText(_end.toString());
}
}
}
}
private void adjustLength() {
myUnpluggedClone.setStart(this.start);
/** Change the end date of the task */
public void setEnd(GanttCalendar dend, boolean test) {
myUnpluggedClone.setEnd(this.end);
length
=
myUnpluggedClone.getDuration().getLength();
durationField1.setText("" + length);
if (test == true) {
finishDateField1.setText(dend.toString());
// durationField2.setText(""+length);
this.end = dend;
myAllocationsPanel[0].durationChanged(length);
return;
durationFieldNotes.setText("" + length);
}
}
finishDateField1.setText(dend.toString());
private void setInitialValues(GanttTask task) {
this.taskWebLink = task.getWebLink();
this.end = dend;
//
(int)
this.taskIsMilestone = task.isMilestone();
this.setFinishFixed(dend.isFixed());
this.taskStartDate = task.getStart();
this.taskEndDate = task.getEnd();
if (this.start.compareTo(this.end) < 0) {
this.taskLength = task.getLength();
adjustLength();
this.taskNotes = task.getNotes();
} else {
GanttCalendar _start = this.end.newAdd(length);
this.taskCompletionPercentage
task.getCompletionPercentage();
this.start = _start;
this.taskPriority = task.getPriority();
startDateField1.setText(_start.toString());
//LH
=
this.taskBudget = task.getBudget();
}
this.taskIsStartFixed = task.isStartFixed();
}
//
this.taskIsFinishFixed = task.isFinishFixed();
/** Change the third date of the task */
this.taskColor = task.getColor();
public void setThird(GanttCalendar dthird, boolean test) {
this.taskShape = task.getShape();
this.taskThirdDate = task.getThird();
if (test) {
thirdDateField1.setText(dthird.toString());
this.third = dthird;
this.taskThirdDateConstraint
task.getThirdDateConstraint();
=
this.taskIsProjectTask = task.isProjectTask();
return;
}
}
switch (thirdDateComboBox.getSelectedIndex()) {
private void copyValues(ResourcesTableModel original,
ResourcesTableModel clone) {
case TaskImpl.EARLIESTBEGIN:
for (int i = 0; i < clone.getRowCount(); i++)
thirdDateButton1.setEnabled(true);
clone.setValueAt(null, i, 1);
thirdDateField1.setText(dthird.toString());
for (int j = 0; j < original.getRowCount(); j++)
this.third = dthird;
break;
for (int k = 0; k < original.getColumnCount();
k++)
case TaskImpl.NONE:
clone.setValueAt(original.getValueAt(j, k), j, k);
thirdDateButton1.setEnabled(false);
thirdDateField1.setText("");
}
113
import javax.swing.JLabel;
private JCheckBox constructCheckBox () {
boolean
=import javax.swing.JPanel;
hasAParentOrDescendantProjectTask
true;
import javax.swing.JTextField;
boolean isASuperTask = false;
for (int i = 0 ; i < selectedTasks.length ; i++) {
import net.sourceforge.ganttproject.language.GanttLanguage;
=
import net.sourceforge.ganttproject.task.Task;
DefaultMutableTreeNode
node
((GanttTree2)tree).getNode (selectedTasks[i].getTaskID());
if (node.getChildCount() != 0)
/**
isASuperTask = true;
//check if the task has a projectTask * Created by IntelliJ IDEA. User: bard
descendant or parent
*/
if
abstract class CommonPanel implements InternalStateListener
(((GanttTree2)tree).haveParentOrDescendantProjectTask(node {
)) {
private final GanttLanguage language;
hasAParentOrDescendantProjectTask = false;
private JLabel nameLabel3;
}
}
private JLabel durationLabel3;
if (hasAParentOrDescendantProjectTask)
projectTaskCheckBox1 = new JCheckBox
(language.getText("projectTask"));
private JTextField nameField3;
private JTextField durationField3;
if
(projectTaskCheckBox1
(!isASuperTask)) {
==
null
&&
mileStoneCheckBox1
=
new
JCheckBox(language.getText("meetingPoint")); // Milestone
return mileStoneCheckBox1;
}
private JPanel firstRowPanel3;
private
FlowLayout
flowL
FlowLayout(FlowLayout.LEFT, 10, 10);
=
new
return projectTaskCheckBox1;
}
private GridBagConstraints gbc = new GridBagConstraints();
}
private final Task myTask;
//LH
net.sourceforge.ganttproject.gui.
taskproperties.CommonPanel
private JLabel budgetLabel3;
//private JTextField budgetField3;
private JFormattedTextField budgetField3;
package net.sourceforge.ganttproject.gui.taskproperties;
public CommonPanel(Task task) {
import java.awt.Component;
language = GanttLanguage.getInstance();
import java.awt.ComponentOrientation;
myTask = task;
import java.awt.Container;
}
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
protected
void
addUsingGBL(Container
Component component,
container,
import java.awt.GridBagLayout;
import java.util.Locale;
GridBagConstraints gbc, int x,
import java.text.NumberFormat;
int y, int w, int h) {
import javax.swing.JFormattedTextField;
114
budgetField3.setValue(new Double(newBudget));
gbc.gridx = x;
}
gbc.gridy = y;
gbc.gridwidth = w;
protected
onlyOneTask) {
gbc.gridheight = h;
gbc.weighty = 0;
JPanel
setupCommonFields(boolean
nameLabel3 = new JLabel(getLanguage().getText("name")
+ ":");
container.add(component, gbc);
nameField3 = new JTextField(20);
container.applyComponentOrientation(ComponentOrientation
nameField3.setText(getTask().getName());
.getOrientation(Locale.getDefault()));
durationLabel3
=
JLabel(getLanguage().getText("length") + ":");
}
new
durationField3 = new JTextField(8);
/** set the first row in all the tabbed pane. thus give them a
durationField3.setText(""
common look */
getTask().getDuration().getLength());
+
nameField3.setEditable(false);
protected
void
setFirstRow(Container
GridBagConstraints gbc,
JLabel
durationLabel,
nameLabel,
JTextField
JTextField
durationField,
JTextField budgetField) {
container,
nameField,
durationField3.setEditable(false);
firstRowPanel3 = new JPanel(flowL);
JLabel
//Lh
JLabel
budgetLabel3
=
budgetLabel,
JLabel(getLanguage().getText("budget") + ":");
//budgetField3 = new JTextField(8);
container.setLayout(new GridBagLayout());
gbc.weightx = 0;
gbc.weighty = 0;
budgetField3
=
new
JFormattedTextField(NumberFormat.getCurrencyInstance());
//budgetField3.setText("" + getTask().getBudget());
gbc.anchor = GridBagConstraints.WEST;
gbc.insets.right = 15;
new
budgetField3.setValue(new
Double(getTask().getBudget()));
gbc.insets.left = 10;
budgetField3.setColumns(8);
gbc.insets.top = 10;
budgetField3.setEditable(false);
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;
setFirstRow(firstRowPanel3,
nameField3,
durationLabel3,
budgetField3);
gbc,
durationField3,
nameLabel3,
budgetLabel3,
addUsingGBL(container, durationField, gbc, 3, 0, 1, 1);
addUsingGBL(container, budgetLabel, gbc, 4, 0, 1, 1);
if (!onlyOneTask) {
addUsingGBL(container, budgetField, gbc, 5, 0, 1, 1);
nameLabel3.setVisible(false);
nameField3.setVisible(false);
}
}
return firstRowPanel3;
public void nameChanged(String newName) {
}
nameField3.setText(newName);
}
protected GanttLanguage getLanguage() {
return language;
public void durationChanged(int newDuration) {
}
durationField3.setText("" + newDuration);
}
protected Task getTask() {
return myTask;
//LH
public void budgetChanged(double newBudget) {
}
}
//budgetField3.setText("" + newBudget);
115
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.TaskDependenc
ySlice;
ShapePaint getShape();
Color getColor();
String getNotes();
boolean getExpand();
//
// relationships with other entities
GanttTaskRelationship[] getPredecessors();
GanttTaskRelationship[] getSuccessors();
/**
* Created by IntelliJ IDEA.
*
// HumanResource[] getAssignedHumanResources();
ResourceAssignment[] getAssignments();
* @author bard Date: 27.01.2004
*/
TaskDependencySlice getDependencies();
public interface Task extends MutableTask {
TaskMutator createMutator();
// main properties
TaskDependencySlice getDependenciesAsDependant();
TaskDependencySlice getDependenciesAsDependee();
int getTaskID();
ResourceAssignmentCollection getAssignmentCollection();
String getName();
//LH
boolean isMilestone();
CostsTaskCollection getCostsTaskCollection();
Cost[] getCosts();
int getPriority();
//
TaskActivity[] getActivities();
GanttCalendar getStart();
GanttCalendar getEnd();
TaskLength getDuration();
TaskLength translateDuration(TaskLength duration);
int getCompletionPercentage();
boolean isStartFixed();
//
Task getSupertask();
Task[] getNestedTasks();
void move(Task targetSupertask);
void delete();
TaskManager getManager();
Task unpluggedClone();
// Color DEFAULT_COLOR = new Color( 140, 182, 206); not
used
boolean isFinishFixed();
116
CustomColumnsValues getCustomValues();
import
net.sourceforge.ganttproject.task.dependency.TaskDependenc
ySliceAsDependant;
import
net.sourceforge.ganttproject.task.dependency.TaskDependenc
ySliceAsDependee;
boolean isCritical();
GanttCalendar getThird();
import
net.sourceforge.ganttproject.task.dependency.TaskDependenc
ySliceImpl;
import
net.sourceforge.ganttproject.task.hierarchy.TaskHierarchyItem;
void applyThirdDateConstraint();
import net.sourceforge.ganttproject.time.TimeUnit;
int getThirdDateConstraint();
/**
* Created by IntelliJ IDEA.
void setThirdDate(GanttCalendar thirdDate);
*
* @author bard Date: 31.01.2004
void setThirdDateConstraint(int dateConstraint);
*/
public class TaskImpl implements Task {
TaskInfo getTaskInfo();
private int myID;
boolean isProjectTask ();
private final TaskManagerImpl myManager;
//LH
private String myName;
double getBudget();
private String myWebLink = new String("http://");
}
private boolean isMilestone;
net.sourceforge.ganttproject.task.
TaskImpl
boolean isProjectTask;
private int myPriority;
package net.sourceforge.ganttproject.task;
private GanttCalendar myStart;
import java.awt.Color;
import java.util.ArrayList;
private GanttCalendar myEnd;
import java.util.Date;
import java.util.List;
import net.sourceforge.ganttproject.GanttCalendar;
private GanttCalendar myThird;
private int myThirdDateConstraint;
import net.sourceforge.ganttproject.GanttTaskRelationship;
import
net.sourceforge.ganttproject.calendar.AlwaysWorkingTimeCale
ndarImpl;
import net.sourceforge.ganttproject.calendar.GPCalendar;
import
net.sourceforge.ganttproject.calendar.GPCalendarActivity;
import net.sourceforge.ganttproject.shape.ShapePaint;
import
net.sourceforge.ganttproject.task.dependency.TaskDependenc
ySlice;
private int myCompletionPercentage;
private TaskLength myLength;
private List myActivities = new ArrayList();
private boolean isStartFixed;
117
//
myManager.increaseMaxID();
private boolean isFinishFixed;
} else {
if (myManager.getTask(taskID) != null) {
private boolean bExpand;
throw new IllegalArgumentException("There is a task
with ID="
// private final TaskDependencyCollection myDependencies
= new
+ taskID + " already");
// TaskDependencyCollectionImpl();
}
private ResourceAssignmentCollectionImpl myAssignments;
myID = taskID;
//LH
}
private CostsTaskCollectionImpl myCosts;
//LH
myCosts = new CostsTaskCollectionImpl(this);
private TaskDependencySlice myDependencySlice;
myAssignments
=
ResourceAssignmentCollectionImpl(this, myManager
private
myDependencySliceAsDependant;
TaskDependencySlice
private
myDependencySliceAsDependee;
TaskDependencySlice
new
.getConfig().getResourceManager());
myDependencySlice
=
TaskDependencySliceImpl(this, myManager
new
.getDependencyCollection());
myDependencySliceAsDependant
TaskDependencySliceAsDependant(this,
=
new
myManager.getDependencyCollection());
private boolean myEventsEnabled;
myDependencySliceAsDependee
TaskDependencySliceAsDependee(this,
private final TaskHierarchyItem myTaskHierarchyItem;
=
new
myManager.getDependencyCollection());
myPriority = 1;
private ShapePaint myShape;
myTaskHierarchyItem
myManager.getHierarchyManager().createItem(this);
=
isStartFixed = false;
private Color myColor;
//
isFinishFixed = false;
myNotes = "";
private String myNotes;
bExpand = true;
myColor = null;
private MutatorImpl myMutator;
customValues = new CustomColumnsValues();
private CustomColumnsValues customValues = null;
}
private boolean critical;
protected TaskImpl(TaskImpl copy, boolean isUnplugged) {
myManager = copy.myManager;
public final static int NONE = 0;
if (!isUnplugged) {
public final static int EARLIESTBEGIN = 1;
myTaskHierarchyItem
myManager.getHierarchyManager().createItem(
=
this);
//LH
} else {
private double myBudget;
myTaskHierarchyItem = null;
}
protected TaskImpl(TaskManager taskManager, int taskID) {
myManager = (TaskManagerImpl) taskManager;
importData(copy);
}
if (taskID == -1) {
myID = myManager.getMaxID();
//TODO implementar importação de custos
118
protected void importData(TaskImpl copy) {
myAssignments
=
ResourceAssignmentCollectionImpl(this, myManager
throw new RuntimeException("Two mutators have been
requested",
new
myException);
}
.getConfig().getResourceManager());
myMutator = new MutatorImpl();
myAssignments.importData(copy.getAssignmentCollection());
myException = new Exception();
myID = copy.myID;
return myMutator;
myName = copy.myName;
}
myWebLink = copy.myWebLink;
isMilestone = copy.isMilestone;
private Exception myException;
isProjectTask = copy.isProjectTask;
myPriority = copy.myPriority;
// main properties
myStart = copy.myStart;
public int getTaskID() {
myEnd = copy.myEnd;
return myID;
myThird = copy.myThird;
}
myThirdDateConstraint = copy.myThirdDateConstraint;
myCompletionPercentage
copy.myCompletionPercentage;
=
public String getName() {
return myName;
myLength = copy.myLength;
}
isStartFixed = copy.isStartFixed;
//
isFinishFixed = copy.isFinishFixed;
public String getWebLink() {
myShape = copy.myShape;
return myWebLink;
myColor = copy.myColor;
}
myNotes = copy.myNotes;
bExpand = copy.bExpand;
public boolean isMilestone() {
//
myDependencySlice
=
TaskDependencySliceImpl(this, myManager
return isMilestone;
new
}
.getDependencyCollection());
myDependencySliceAsDependant
TaskDependencySliceAsDependant(this,
=
new
public int getPriority() {
return myPriority;
myManager.getDependencyCollection());
myDependencySliceAsDependee
TaskDependencySliceAsDependee(this,
=
myManager.getDependencyCollection());
new
}
public GanttCalendar getStart() {
if (myMutator != null
customValues
=
copy.getCustomValues().clone();
&&
myMutator.myIsolationLevel
(CustomColumnsValues)
TaskMutator.READ_UNCOMMITED) {
==
return myMutator.getStart();
} else {
recalculateActivities();
return myStart;
}
}
public Task unpluggedClone() {
}
TaskImpl result = new TaskImpl(this, true);
return result;
public GanttCalendar getEnd() {
if (myMutator != null
}
public TaskMutator createMutator() {
if (myMutator != null) {
&&
myMutator.myIsolationLevel
TaskMutator.READ_UNCOMMITED) {
==
return myMutator.getEnd();
119
public boolean isStartFixed() {
} else {
return isStartFixed;
if (myEnd == null) {
}
myEnd = getStart().Clone();
myEnd.add((int) getDuration().getLength());
}
//
return myEnd;
//
public boolean isFinishFixed() {
return isFinishFixed;
//
}
}
}
public boolean getExpand() {
return bExpand;
public GanttCalendar getThird() {
}
if (myMutator != null
&&
myMutator.myIsolationLevel
TaskMutator.READ_UNCOMMITED) {
==
public ShapePaint getShape() {
return myMutator.getThird();
return myShape;
} else {
}
return myThird;
}
public Color getColor() {
}
Color result = myColor;
if (result == null) {
public int getThirdDateConstraint() {
if (isMilestone() || getNestedTasks().length > 0) {
return myThirdDateConstraint;
result = Color.BLACK;
}
} else {
result = myManager.getConfig().getDefaultColor();
public TaskActivity[] getActivities() {
List activities = myMutator
myMutator.getActivities();
}
==
null
?
null
:
}
return result;
if (activities == null) {
}
activities = myActivities;
}
return
(TaskActivity[])
TaskActivity[activities
.size()]);
activities.toArray(new
public String getNotes() {
return myNotes;
}
}
public GanttTaskRelationship[] getPredecessors() {
public TaskLength getDuration() {
return new GanttTaskRelationship[0]; // To change body of
return (myMutator != null && myMutator.myIsolationLevelimplemented
== TaskMutator.READ_UNCOMMITED) ? myMutator
// methods use Options | File
.getDuration()
: myLength;
// Templates.
}
}
public GanttTaskRelationship[] getSuccessors() {
public int getCompletionPercentage() {
return new GanttTaskRelationship[0]; // To change body of
return (myMutator != null && myMutator.myIsolationLevelimplemented
== TaskMutator.READ_UNCOMMITED) ? myMutator
// methods use Options | File
.getCompletionPercentage()
: myCompletionPercentage;
// Templates.
}
}
public ResourceAssignment[] getAssignments() {
120
}
return myAssignments.getAssignments();
}
public
getAssignmentCollection() {
public
TaskDependencySlice
getDependenciesAsDependant() {
ResourceAssignmentCollection
return myDependencySliceAsDependant;
}
return myAssignments;
}
public Cost[] getCosts() {
public
getDependenciesAsDependee() {
TaskDependencySlice
return myDependencySliceAsDependee;
return myCosts.getCosts();
}
}
public TaskManager getManager() {
public CostsTaskCollection getCostsTaskCollection() {
return myManager;
return myCosts;
}
}
// TODO: remove this hack. ID must never be changed
//
protected void setTaskIDHack(int taskID) {
public Task getSupertask() {
TaskHierarchyItem
container
myTaskHierarchyItem.getContainerItem();
myID = taskID;
=
}
return container.getTask();
private static interface EventSender {
}
void enable();
public Task[] getNestedTasks() {
TaskHierarchyItem[]
nestedItems
myTaskHierarchyItem.getNestedItems();
void fireEvent();
=
}
Task[] result = new Task[nestedItems.length];
for (int i = 0; i < nestedItems.length; i++) {
result[i] = nestedItems[i].getTask();
private class ProgressEventSender implements EventSender
{
private boolean myEnabled;
}
return result;
public void fireEvent() {
}
if (myEnabled) {
public void move(Task targetSupertask) {
TaskImpl supertaskImpl = (TaskImpl) targetSupertask;
TaskHierarchyItem
targetItem
supertaskImpl.myTaskHierarchyItem;
myManager.fireTaskProgressChanged(TaskImpl.this);
}
=
myEnabled = false;
}
myTaskHierarchyItem.delete();
targetItem.addNestedItem(myTaskHierarchyItem);
public void enable() {
}
myEnabled = true;
}
public void delete() {
getDependencies().clear();
getAssignmentCollection().clear();
}
}
public TaskDependencySlice getDependencies() {
return myDependencySlice;
private
class
EventSender {
PropertiesEventSender
implements
private boolean myEnabled;
121
index++;
}
public void fireEvent() {
while (index > myDates.size()) {
if (myEnabled) {
myDates.add(null);
myManager.fireTaskPropertiesChanged(TaskImpl.this);
}
}
if (index == -1) {
myEnabled = false;
myDates.add(0, date);
}
} else if (index == myDates.size()) {
myDates.add(date);
public void enable() {
} else {
myEnabled = true;
myDates.set(index, date);
}
}
}
}
private static class FieldChange {
private int myMinLength = 0;
String myFieldName;
private List myDates;
Object myFieldValue;
}
EventSender myEventSender;
private class MutatorImpl implements TaskMutator {
void setValue(Object newValue) {
myFieldValue = newValue;
private EventSender myPropertiesEventSender = new
PropertiesEventSender();
myEventSender.enable();
private EventSender myProgressEventSender = new
ProgressEventSender();
}
}
private static class DurationChange extends FieldChange {
private FieldChange myCompletionPercentageChange;
Date getCachedDate(int length) {
if (myDates == null) {
private FieldChange myStartChange;
return null;
private FieldChange myEndChange;
}
int index = length - myMinLength;
if (index < 0 || index >= myDates.size()) {
private FieldChange myThirdChange;
return null;
private DurationChange myDurationChange;
}
return (Date) myDates.get(index);
private List myActivities;
}
void cacheDate(Date date, int length) {
private final List myCommands = new ArrayList();
if (myDates == null) {
myDates = new ArrayList();
private int myIsolationLevel;
}
int index = length - myMinLength;
while (index <= -1) {
myDates.add(0, null);
public void commit() {
try {
boolean fireChanges = false;
if (myStartChange != null) {
122
GanttCalendar start = getStart();
}
TaskImpl.this.setStart(start);
}
public void setName(final String name) {
if (myDurationChange != null) {
myCommands.add(new Runnable() {
TaskLength duration = getDuration();
public void run() {
TaskImpl.this.setDuration(duration);
TaskImpl.this.setName(name);
myEndChange = null;
}
}
});
if (myCompletionPercentageChange != null) {
}
int newValue = getCompletionPercentage();
public void setProjectTask(final boolean projectTask) {
TaskImpl.this.setCompletionPercentage(newValue);
myCommands.add(new Runnable() {
}
public void run() {
if (myEndChange != null) {
TaskImpl.this.setProjectTask(projectTask);
GanttCalendar end = getEnd();
}
TaskImpl.this.setEnd(end);
}
});
}
if (myThirdChange != null) {
GanttCalendar third = getThird();
public void setMilestone(final boolean milestone) {
TaskImpl.this.setThirdDate(third);
myCommands.add(new Runnable() {
}
public void run() {
for (int i = 0; i < myCommands.size(); i++) {
TaskImpl.this.setMilestone(milestone);
Runnable next = (Runnable) myCommands.get(i);
}
next.run();
}
});
}
myCommands.clear();
myPropertiesEventSender.fireEvent();
public void setPriority(final int priority) {
myProgressEventSender.fireEvent();
myCommands.add(new Runnable() {
} finally {
public void run() {
TaskImpl.this.myMutator = null;
TaskImpl.this.setPriority(priority);
}
}
}
});
}
public GanttCalendar getThird() {
return myThirdChange == null ? TaskImpl.this.myThird
public void setStart(final GanttCalendar start) {
: (GanttCalendar) myThirdChange.myFieldValue;
if (myStartChange == null) {
}
myStartChange = new FieldChange();
public List getActivities() {
myStartChange.myEventSender
myPropertiesEventSender;
}
if (myActivities == null && (myStartChange != null)
myStartChange.setValue(start);
|| (myDurationChange != null)) {
myActivities = null;
myActivities = new ArrayList();
TaskImpl.this.recalculateActivities(myActivities,
=
}
getStart()
.getTime(), getEnd().getTime());
}
public void setEnd(final GanttCalendar end) {
if (myEndChange == null) {
return myActivities;
123
myEndChange = new FieldChange();
myEndChange.myEventSender
myPropertiesEventSender;
=
//
System.err.println("previously
shift="+prevEnd);
cached
myDurationChange.setValue(length);
}
GanttCalendar newEnd;
myEndChange.setValue(end);
Date shifted;
myActivities = null;
if (prevEnd == null) {
}
//
System.err.println("no
length="+length.getLength());
public void setThird(final GanttCalendar third,
length
prev,
shifted = TaskImpl.this.shiftDate(getStart().getTime(),
final int thirdDateConstraint) {
.getTimeUnit(), length.getLength());
myCommands.add(new Runnable() {
} else {
public void run() {
// System.err.println("yes prev,
//
prevLength.getLength()));
TaskImpl.this.setThirdDateConstraint(thirdDateConstraint);
}
length="+(length.getLength()-
shifted = TaskImpl.this.shiftDate(prevEnd,
});
length.getTimeUnit(), length.getLength()
if (myThirdChange == null) {
- prevLength.getLength());
myThirdChange = new FieldChange();
}
myThirdChange.myEventSender
myPropertiesEventSender;
=
// System.err.println("caching shift="+shifted+" for
// duration="+length);
}
//
myDurationChange.cacheDate(shifted,
(int)length.getLength());
myThirdChange.setValue(third);
myActivities = null;
newEnd = new GanttCalendar(shifted);
setEnd(newEnd);
}
myActivities = null;
}
public void setDuration(final TaskLength length) {
if (myDurationChange == null) {
public void setExpand(final boolean expand) {
myDurationChange = new DurationChange();
myDurationChange.myEventSender
myPropertiesEventSender;
myCommands.add(new Runnable() {
=
public void run() {
TaskImpl.this.setExpand(expand);
myDurationChange.setValue(length);
}
} else {
TaskLength
currentLength
myDurationChange.myFieldValue;
=
});
(TaskLength)
}
if (currentLength.getLength() - length.getLength() ==
0) {
public void setCompletionPercentage(final int percentage)
return;
}
{
if (myCompletionPercentageChange == null) {
}
myCompletionPercentageChange
=
new
FieldChange();
TaskLength
prevLength
=
(TaskLength)
myDurationChange.myFieldValue;
myCompletionPercentageChange.myEventSender =
myProgressEventSender;
// System.err.println("new duration="+length+"
}
// previous="+prevLength);
myCompletionPercentageChange.setValue(new
// Date prevEnd =
Integer(percentage));
//
}
myDurationChange.getCachedDate((int)prevLength.getLength()
);
Date prevEnd = null;
public void setStartFixed(final boolean isFixed) {
myCommands.add(new Runnable() {
124
public void run() {
TaskImpl.this.setStartFixed(isFixed);
public void addNotes(final String notes) {
myCommands.add(new Runnable() {
}
public void run() {
});
TaskImpl.this.addNotes(notes);
}
}
//
});
public void setFinishFixed(final boolean isFixed) {
//
myCommands.add(new Runnable() {
//
}
public void run() {
//
TaskImpl.this.setFinishFixed(isFixed);
//
return myCompletionPercentageChange
TaskImpl.this.myCompletionPercentage
}
//
public int getCompletionPercentage() {
});
==
:
myCompletionPercentageChange.myFieldValue)
//
//
}
null
?
((Integer)
.intValue();
}
public void setCritical(final boolean critical) {
myCommands.add(new Runnable() {
GanttCalendar getStart() {
public void run() {
return myStartChange == null ? TaskImpl.this.myStart
TaskImpl.this.setCritical(critical);
}
: (GanttCalendar) myStartChange.myFieldValue;
}
});
}
GanttCalendar getEnd() {
return myEndChange == null ? TaskImpl.this.myEnd
public void setShape(final ShapePaint shape) {
myCommands.add(new Runnable() {
: (GanttCalendar) myEndChange.myFieldValue;
}
public void run() {
TaskImpl.this.setShape(shape);
}
TaskLength getDuration() {
return
myDurationChange
TaskImpl.this.myLength
});
==
null
?
: (TaskLength) myDurationChange.myFieldValue;
}
}
public void setColor(final Color color) {
myCommands.add(new Runnable() {
public void shift(float unitCount) {
public void run() {
Task result = getPrecomputedShift(unitCount);
TaskImpl.this.setColor(color);
if (result == null) {
}
result = TaskImpl.this.shift(unitCount);
});
cachePrecomputedShift(result, unitCount);
}
}
public void setNotes(final String notes) {
//
System.err.println("[MutatorImpl]
result="+result);
myCommands.add(new Runnable() {
setStart(result.getStart());
public void run() {
setDuration(result.getDuration());
TaskImpl.this.setNotes(notes);
}
shift():
setEnd(result.getEnd());
}
});
}
public void shift(TaskLength shift) {
125
TaskImpl.this.shift(shift);
public void setMilestone(boolean milestone) {
}
isMilestone = milestone;
}
public void setIsolationLevel(int level) {
myIsolationLevel = level;
public void setPriority(int priority) {
}
myPriority = priority;
private void cachePrecomputedShift(Task result, float
unitCount) {
}
}
public void setStart(GanttCalendar start) {
private Task getPrecomputedShift(float unitCount) {
Date
closestWorkingStart
myManager.findClosestWorkingTime(start
=
.getTime());
return null;
start.setTime(closestWorkingStart);
}
private TaskInfo myTaskInfo;
GanttCalendar oldStart = myStart == null ? null :
myStart.Clone();
myStart = start;
if (areEventsEnabled()) {
public TaskInfo getTaskInfo() {
return myTaskInfo;
myManager.fireTaskScheduleChanged(this,
getEnd());
}
oldStart,
}
recalculateActivities();
public void setTaskInfo(TaskInfo taskInfo) {
myTaskInfo = taskInfo;
}
}
public void setEnd(GanttCalendar end) {
GanttCalendar oldFinish = myEnd == null ? null :
myEnd.Clone();
//LH
myEnd = end;
public void setBudget(final double cost) {
recalculateActivities();
myCommands.add(new Runnable() {
public void run() {
// System.err.println("we
activities");
TaskImpl.this.setBudget(cost);
}
});
have
"+myActivities.size()+"
if (areEventsEnabled()) {
myManager.fireTaskScheduleChanged(this,
myStart.Clone(), oldFinish);
}
}
}
}
public void setThirdDate(GanttCalendar third) {
public void setName(String name) {
GanttCalendar oldThird = myThird == null ? null :
myThird.Clone();
myThird = third;
myName = name;
// recalculateActivities();
}
// if (areEventsEnabled()) {
public void setWebLink(String webLink) {
//
myManager.fireTaskScheduleChanged(this,
myThird.Clone(), oldThird);
// }
myWebLink = webLink;
}
}
126
public void setThirdDateConstraint(int thirdDateConstraint) {
GanttCalendar oldFinish = myEnd == null ? null :
myEnd.Clone();
myThirdDateConstraint = thirdDateConstraint;
myLength = length;
}
Date newEndDate = shiftDate(myStart.getTime(),
public void shift(TaskLength shift) {
length.getTimeUnit(), length.getLength());
float unitCount = shift.getLength(myLength.getTimeUnit());
if (unitCount != 0f) {
myEnd = new GanttCalendar(newEndDate);
Task resultTask = shift(unitCount);
// myEnd = myStart.newAdd((int) length.getLength());
GanttCalendar oldStart = myStart;
recalculateActivities();
GanttCalendar oldEnd = myEnd;
if (areEventsEnabled()) {
myStart = resultTask.getStart();
myManager.fireTaskScheduleChanged(this,
myStart.Clone(),
myLength = resultTask.getDuration();
myEnd = resultTask.getEnd();
oldFinish);
if (areEventsEnabled()) {
}
myManager.fireTaskScheduleChanged(this, oldStart,
oldEnd);
}
}
recalculateActivities();
}
}
private Date shiftDate(Date input, TimeUnit timeUnit, long
length) {
public Task shift(float unitCount) {
return
shiftDate(input,
myManager.getConfig()
}
if (unitCount > 0) {
TaskLength
length
myManager.createLength(myLength.getTimeUnit(),
=
unitCount);
private Date shiftDate(Date input, TimeUnit timeUnit, long
length,
GPCalendar calendar) {
// clone.setDuration(length);
Date shiftedDate = shiftDate(myStart.getTime(), length
List activities = calendar.getActivities(input, timeUnit,
length);
length.getLength(),
clone.setStart(new GanttCalendar(shiftedDate));
if (activities.isEmpty()) {
throw new RuntimeException("Can't set length=" +
length + " start="
clone.setDuration(myLength);
+ input);
} else {
}
// TODO: hack assuming unit=day
Date result;
//
clone.setStart(clone.getStart().newAdd((int)unitCount));
clone
length,
.getCalendar());
Task clone = unpluggedClone();
.getTimeUnit(),
RESTLESS_CALENDAR);
timeUnit,
if (length >= 0) {
GPCalendarActivity lastActivity = (GPCalendarActivity)
Date newStart = shiftDate(clone.getStart().getTime(),
activities
.get(activities.size() - 1);
.getDuration().getTimeUnit(), (long) unitCount);
result = lastActivity.getEnd();
clone.setStart(new GanttCalendar(newStart));
} else {
clone.setDuration(myLength);
}
GPCalendarActivity firstActivity = (GPCalendarActivity)
activities
return clone;
.get(0);
}
result = firstActivity.getStart();
}
public void setDuration(TaskLength length) {
return result;
}
127
public TaskLength translateDuration(TaskLength duration) {
GPCalendar
calendar
myManager.getConfig().getCalendar();
=
List activities = calendar.getActivities(startDate, endDate);
return myManager.createLength(myLength.getTimeUnit(),
output.clear();
translateDurationValue(duration));
for (int i = 0; i < activities.size(); i++) {
}
GPCalendarActivity
(GPCalendarActivity) activities
private float translateDurationValue(TaskLength duration) {
nextCalendarActivity
=
.get(i);
if (myLength.getTimeUnit().equals(duration.getTimeUnit()))
TaskActivityImpl nextTaskActivity;
{
if (nextCalendarActivity.isWorkingTime()) {
return duration.getValue();
nextTaskActivity = new TaskActivityImpl(this,
}
nextCalendarActivity.getStart(),
if
nextCalendarActivity
(myLength.getTimeUnit().isConstructedFrom(duration.getTimeU
.getEnd());
nit())) {
} else if (i > 0 && i + 1 < activities.size()) {
return duration.getValue()
nextTaskActivity = new TaskActivityImpl(this,
/ myLength.getTimeUnit().getAtomCount(
nextCalendarActivity.getStart(),
nextCalendarActivity
duration.getTimeUnit());
}
.getEnd(), 0);
if
(duration.getTimeUnit().isConstructedFrom(myLength.getTimeU
nit())) {
} else {
continue;
return duration.getValue()
}
* duration.getTimeUnit().getAtomCount(
output.add(nextTaskActivity);
myLength.getTimeUnit());
}
}
}
throw new RuntimeException("Can't transalte duration=" +
duration
public void setCompletionPercentage(int percentage) {
+ " into units=" + myLength.getTimeUnit());
int oldPercentage = myCompletionPercentage;
}
myCompletionPercentage = percentage;
if (oldPercentage != myCompletionPercentage) {
private void recalculateActivities() {
if (myEnd == null || myManager == null) {
EventSender
progressEventSender
ProgressEventSender();
return;
=
new
progressEventSender.enable();
}
progressEventSender.fireEvent();
recalculateActivities(myActivities,
myEnd.getTime());
myStart.getTime(),
}
}
int length = 0;
for (int i = 0; i < myActivities.size(); i++) {
public void setStartFixed(boolean isFixed) {
TaskActivity next = (TaskActivity) myActivities.get(i);
isStartFixed = isFixed;
if (next.getIntensity() > 0) {
}
length += next.getDuration().getLength(
getDuration().getTimeUnit());
}
}
//
public void setFinishFixed(boolean isFixed) {
//
isFinishFixed = isFixed;
myLength
=//
getManager().createLength(myLength.getTimeUnit(), length);
}
}
public void setShape(ShapePaint shape) {
myShape = shape;
private void recalculateActivities(List output, Date startDate,
Date endDate) {
}
128
public String toString() {
public void setColor(Color color) {
myColor = color;
}
return myName + ": " + myStart.getTime() + "-" +
myLength;
}
public void setNotes(String notes) {
public boolean isUnplugged() {
myNotes = notes;
return myTaskHierarchyItem == null;
}
}
public void setExpand(boolean expand) {
/**
bExpand = expand;
* Returns the CustomColumnValues.
}
*
* @return The CustomColumnValues.
public void addNotes(String notes) {
*/
myNotes += notes;
public CustomColumnsValues getCustomValues() {
}
return customValues;
}
protected void enableEvents(boolean enabled) {
myEventsEnabled = enabled;
/**
}
* @inheritDoc
*/
protected boolean areEventsEnabled() {
public void setCritical(boolean critical) {
return myEventsEnabled;
this.critical = critical;
}
}
/**
* Allows to determine, if a special shape is defined for this
task.
/**
* @inheritDoc
*
*/
* @return true, if this task has its own shape defined.
public boolean isCritical() {
return this.critical;
*/
public boolean shapeDefined() {
}
return (myShape != null);
// TODO: implementation of this method has no correlation
with algorithms
}
// recalculating schedules,
/**
// doesn't affect subtasks and supertasks. It is necessary to
* Allows to determine, if a special color is defined for thiscall this
task.
// method explicitly from other
*
// parts of code to be sure that constraint fulfils
* @return true, if this task has its own color defined.
//
*/
// Method GanttCalendar.newAdd() assumes that time unit is
day
public boolean colorDefined() {
public void applyThirdDateConstraint() {
TaskLength length = getDuration();
return (myColor != null);
if (getThird() != null)
switch (getThirdDateConstraint()) {
}
case EARLIESTBEGIN:
129
// TODO: TIME UNIT (assumption about days)
if (getThird().after(getStart())) {
int difference = getThird().diff(getStart());
net.sourceforge.ganttproject.task.
TaskNode
GanttCalendar
getStart().newAdd(difference);
_start
=
package net.sourceforge.ganttproject.task;
GanttCalendar
getEnd().newAdd(difference);
_end
=
import javax.swing.tree.DefaultMutableTreeNode;
setEnd(_end);
setStart(_start);
import net.sourceforge.ganttproject.GanttCalendar;
setDuration(length);
}
/**
break;
* This class is the class to use to discribe the tasks hierarchy.
}
*
}
* @author bbaranne (Benoit Baranne)
*/
private TaskInfo myTaskInfo;
public class TaskNode extends DefaultMutableTreeNode {
/**
public TaskInfo getTaskInfo() {
* The reference task
return myTaskInfo;
*/
}
private final Task task;
public void setTaskInfo(TaskInfo taskInfo) {
myTaskInfo = taskInfo;
/**
* Creates an instance of TaskNode with the given task as
reference.
*
}
* @param t
public boolean isProjectTask() {
return isProjectTask;
*
Task of reference.
*/
public TaskNode(Task t) {
}
super(t);
task = t;
public void setProjectTask(boolean projectTask) {
isProjectTask = projectTask;
}
}
/**
private static final GPCalendar RESTLESS_CALENDAR =
new AlwaysWorkingTimeCalendarImpl();
* Sets the priority of the task.
*
* @param priority
//LH
*
public double getBudget() {
return myBudget;
The priority to be set.
*/
public void setPriority(int priority) {
}
task.setPriority(priority);
}
//LH
public void setBudget(double cost) {
myBudget = cost;
}
}
/**
* Returns the priority of the task.
*
* @return The priority of the task.
130
* @param endDate
*/
public int getPriority() {
return task.getPriority();
*
The end date of the task to be set.
*/
public void setEnd(GanttCalendar endDate) {
}
task.setEnd(endDate);
}
/**
* Sets the name of the task.
/**
*
* @param newName
* Returns the end date of the task.
*
*
The name to be set.
*/
* @return The end date of the task.
public void setName(String newName) {
*/
task.setName(newName);
public GanttCalendar getEnd() {
return task.getEnd();
}
}
/**
* Returns the name of the task.
/**
*
* Sets the duration of the task.
* @return The name of the task.
*
*/
* @param length
public String getName() {
*
return task.getName();
*/
The duration to be set.
public void setDuration(TaskLength length) {
}
task.setDuration(length);
}
/**
* Sets the start date of the task.
/**
*
* @param startDate
* Returns the duration of the task.
*
*
The start date of the task to be set.
*/
* @return The duration of the task.
public void setStart(GanttCalendar startDate) {
*/
task.setStart(startDate);
public int getDuration() {
return (int) task.getDuration().getValue();
}
}
/**
* Returns the start date of the task.
/**
*
* Sets the completion percentage of the task.
* @return The start date of the task.
*
*/
* @param percentage
public GanttCalendar getStart() {
*
return task.getStart();
}
The percentage to be set.
*/
public void setCompletionPercentage(int percentage) {
task.setCompletionPercentage(percentage);
/**
}
* Sets the end date of the task.
*
/**
131
public void setBudget(double budget) {
* Returns the completion percentage of the task.
task.setBudget(budget);
*
}
* @return The completion percentage of the task.
*/
/**
public int getCompletionPercentage() {
* Returns the budget of the task.
return task.getCompletionPercentage();
*
}
* @return The budget of the task.
*/
public void setTaskInfo(TaskInfo info) {
public double getBudget() {
task.setTaskInfo(info);
return task.getBudget();
}
}
public TaskInfo getTaskInfo() {
return task.getTaskInfo();
}
}
/**
* @inheritDoc
net.sourceforge.ganttproject.task.
MutableTask
*/
public String toString() {
package net.sourceforge.ganttproject.task;
return task.getName();
}
import java.awt.Color;
/**
import net.sourceforge.ganttproject.GanttCalendar;
* @inheritDoc
import net.sourceforge.ganttproject.shape.ShapePaint;
*/
public Object getUserObject() {
return task;
/**
* Created by IntelliJ IDEA.
*
}
* @author bard Date: 06.02.2004
public void applyThirdDateConstraint() {
if (task.getThird() != null)
switch (task.getThirdDateConstraint()) {
*/
public interface MutableTask {
void setName(String name);
case TaskImpl.EARLIESTBEGIN:
if (task.getThird().after(getStart())) {
void setMilestone(boolean isMilestone);
task.setStart(task.getThird().newAdd(0));
void setPriority(int priority);
}
}
}
void setStart(GanttCalendar start);
/**
void setEnd(GanttCalendar end);
* Sets the budget of the task.
void setDuration(TaskLength length);
*
* @param budget
*
The budget to be set.
void shift(TaskLength shift);
*/
132
//
void setCompletionPercentage(int percentage);
import net.sourceforge.ganttproject.language.GanttLanguage;
void setStartFixed(boolean isFixed);
import
net.sourceforge.ganttproject.task.dependency.TaskDependenc
y;
void setFinishFixed(boolean isFixed);
void setShape(ShapePaint shape);
/**
* Class with which one can get any properties (even custom)
from any task.
*
void setColor(Color color);
* @author bbaranne
*
void setNotes(String notes);
*/
public class TaskProperties {
void addNotes(String notes);
public static final String ID_TASK_DATES = "taskDates";
void setExpand(boolean expand);
public static final String ID_TASK_NAME = "name";
//LH
void setBudget(double budget);
public static final String ID_TASK_LENGTH = "length";
/**
//LH
* Sets the task as critical or not. The method is used be
TaskManager after
public static final String ID_TASK_BUDGET = "budget";
* having run a CriticalPathAlgorithm to set the critical tasks. public static final String ID_TASK_ADVANCEMENT =
When
"advancement";
* painted, the tasks are rendered as critical using
Task.isCritical(). So,
public static final String ID_TASK_COORDINATOR =
* a task is set as critical only if critical path is displayed.
"coordinator";
*
* @param critical
*
<code>false</code>
*
public static
<code>true</code> if this is critical,"resources";
otherwise.
final
String
ID_TASK_RESOURCES
=
public static final String ID_TASK_ID = "id";
*/
void setCritical(boolean critical);
public static final String ID_TASK_PREDECESSORS =
"predecessors";
void setTaskInfo(TaskInfo taskInfo);
/**
void setProjectTask (boolean projectTask);
*
Returns
the
task
<code>propertyID</code>.
property
specified
by
*
}
net.sourceforge.ganttproject.task.
TaskProperties
package net.sourceforge.ganttproject.task;
import java.text.NumberFormat;
* @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
<code>propertyID</code>. The
property
specified
by
133
*
close = true;
result may be <code>null</code>.
*/
first = false;
public static Object getProperty(Task task, String propertyID)
sb.append("{");
{
}
Object res = null;
if (j > 1) {
StringBuffer sb = new StringBuffer();
sb.append(", ");
if (propertyID != null) {
}
if (propertyID.equals(ID_TASK_DATES)) {
sb.append(assignments[i].getResource().getName());
sb.append(" [ ");
}
sb.append(task.getStart() + " - " + task.getEnd());
sb.append(" ] ");
}
res = sb.toString();
if (close)
sb.append("}");
} else if (propertyID.equals(ID_TASK_NAME)) {
}
sb.append(" " + task.getName() + " ");
res = sb.toString();
res = sb.toString();
} else if (propertyID.equals(ID_TASK_RESOURCES)) {
} else if (propertyID.equals(ID_TASK_LENGTH)) {
ResourceAssignment[]
task.getAssignments();
sb.append(" [ ");
sb.append((int) task.getDuration().getLength() + " "
assignments
=
if (assignments.length > 0) {
+ GanttLanguage.getInstance().getText("days"));
sb.append(" ");
sb.append(" ] ");
for (int i = 0; i < assignments.length; i++) {
res = sb.toString();
} else if (propertyID.equals(ID_TASK_BUDGET)) { //LH sb.append(assignments[i].getResource().getName());
sb.append(" [ ");
if (i < assignments.length - 1) {
//LH
sb.append(",");
//sb.append((double) task.getBudget() + " $");
}
}
sb.append(NumberFormat.getCurrencyInstance().format(task.g
etBudget()));
sb.append(" ");
}
sb.append(" ] ");
res = sb.toString();
res = sb.toString();
}
else
(propertyID.equals(ID_TASK_ADVANCEMENT)) {
if
} else if (propertyID.equals(ID_TASK_ID)) {
sb.append("# ").append(task.getTaskID());
sb.append(" [ ");
res = sb.toString();
sb.append(task.getCompletionPercentage() + "%");
sb.append(" ] ");
res = sb.toString();
} else if (propertyID.equals(ID_TASK_COORDINATOR))
}
else
(propertyID.equals(ID_TASK_PREDECESSORS)) {
if
TaskDependency[]
dep
task.getDependenciesAsDependant().toArray();
=
int i = 0;
{
ResourceAssignment[]
task.getAssignments();
assignments
if (dep != null && dep.length > 0) {
=
for (i = 0; i < dep.length - 1; i++)
if (assignments.length > 0) {
boolean first = true;
sb.append(dep[i].getDependee().getTaskID() + ",
");
sb.append(dep[i].getDependee().getTaskID());
boolean close = false;
}
int j = 0;
for (int i = 0; i < assignments.length; i++) {
if (assignments[i].isCoordinator()) {
res = sb.toString();
} else {
j++;
if (first) {
res = task.getCustomValues().getValue(propertyID);
}
134
}
import javax.swing.JTable;
return res;
import javax.swing.JTextField;
import javax.swing.JTree;
}
}
net.sourceforge.ganttproject.
GanttTreeTable
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;
package net.sourceforge.ganttproject;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import java.awt.Color;
import javax.swing.event.TableModelListener;
import java.awt.Component;
import javax.swing.table.DefaultTableColumnModel;
import java.awt.Dimension;
import javax.swing.table.TableColumn;
import java.awt.Point;
import javax.swing.table.TableColumnModel;
import java.awt.Rectangle;
import java.awt.Toolkit;
import net.sourceforge.ganttproject.delay.Delay;
import java.awt.event.ActionEvent;
import
net.sourceforge.ganttproject.gui.GanttDialogCustomColumn;
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 net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.CustomColumn;
import
net.sourceforge.ganttproject.task.CustomColumnsException;
import java.text.ParseException;
import
net.sourceforge.ganttproject.task.CustomColumnsManager;
import java.util.ArrayList;
import net.sourceforge.ganttproject.task.Task;
import java.util.Collection;
import java.util.Collections;
import
net.sourceforge.ganttproject.task.TaskContainmentHierarchyFa
cade;
import java.util.Date;
import net.sourceforge.ganttproject.task.TaskNode;
import java.util.Enumeration;
import net.sourceforge.ganttproject.util.DateUtils;
import java.util.EventListener;
import java.util.GregorianCalendar;
import org.jdesktop.jdnc.JNTreeTable;
import java.util.HashMap;
import org.jdesktop.swing.decorator.AlternateRowHighlighter;
import java.util.Iterator;
import
org.jdesktop.swing.decorator.HierarchicalColumnHighlighter;
import java.util.List;
import java.util.Map;
import org.jdesktop.swing.decorator.Highlighter;
import org.jdesktop.swing.decorator.HighlighterPipeline;
import javax.swing.Action;
import javax.swing.DefaultCellEditor;
import org.jdesktop.swing.table.TableColumnExt;
import org.jdesktop.swing.treetable.TreeTableModel;
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;
/**
* Treetable used to displayed tabular data and hierarchical
data.
*
* @author bbaranne
* @version 1.0 (20050301) (yyyymmdd)
*/
public class GanttTreeTable extends JNTreeTable {
135
/**
*/
* Unique instance of GanttLanguage.
public GanttTreeTable(TreeTableModel model) {
super(model);
*/
private
static
GanttLanguage
GanttLanguage.getInstance();
language
initTreeTable();
=
}
/**
public void setAction(Action action) {
* PopupMenu showed on right click (window, linux) on the
table header.
InputMap inputMap = new InputMap();
*/
inputMap.put((KeyStroke)
action.getValue(Action.ACCELERATOR_KEY),
private JPopupMenu popupMenu;
action.getValue(Action.NAME));
/**
* Map ColumnName -> MenuItem
inputMap.setParent(getTreeTable().getInputMap(JComponent.
WHEN_FOCUSED));
*/
private Map mapColNameMenuItem;
getTreeTable().setInputMap(JComponent.WHEN_FOCUSED,
inputMap);
/**
* Point where the user has just right clicked on the table
header.
// Add the action to the component
*/
getTreeTable().getActionMap().put(action.getValue(Action.NAM
E), action);
private Point clickPoint = null;
}
/**
* model of the treetable.
private void updateDisplayedColumnsOrder() {
*/
Iterator it = this.listDisplayedColumns.iterator();
private GanttTreeTableModel ttModel;
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
/**
if (dc.isDisplayed()) {
* stores the tableColum
ColumnKeeper. it is used to
associated
with
there
String id = dc.getID();
String name = getNameForId(id);
* retore the column at the same index it has been removed.
int
viewIndex
getTable().convertColumnIndexToView(
*/
private Map mapTableColumnColumnKeeper = null;
=
getColumn(name).getModelIndex());
dc.setOrder(viewIndex);
/**
dc.setWidth(getColumn(name).getPreferredWidth());
* Menu item to delete columns.
}
*/
}
private JMenuItem jmiDeleteColumn;
}
DisplayedColumnsList listDisplayedColumns = null;
public DisplayedColumnsList getDisplayColumns() {
updateDisplayedColumnsOrder();
/**
return this.listDisplayedColumns;
* Creates an instance of GanttTreeTable with the given
TreeTableModel.
}
*
* @param model
*
public void setDisplayedColumns(DisplayedColumnsList
displayedColumns) {
TreeTableModel.
136
DisplayedColumnsList
displayedColumns
l
=
(DisplayedColumnsList)
.clone();
}
Iterator it = lToDel.iterator();
while (it.hasNext())
if (displayedColumns.size() != 0) {
getTable().removeColumn((TableColumn) it.next());
this.listDisplayedColumns = displayedColumns;
displayAllColumns();
getTable().setAutoCreateColumnsFromModel(false);
hideAllColumns();
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_SUBSE
QUENT_COLUMNS);
this.listDisplayedColumns = l;
}
Collections.sort(this.listDisplayedColumns);
TableColumnExt tce1 = new TableColumnExt(0);
tce1.setTitle(GanttTreeTableModel.strColType);
Iterator it = this.listDisplayedColumns.iterator();
TableColumnExt tce2 = new TableColumnExt(1);
while (it.hasNext()) {
tce2.setTitle(GanttTreeTableModel.strColPriority);
DisplayedColumn dc = (DisplayedColumn) it.next();
TableColumnExt tce3 = new TableColumnExt(2);
String id = dc.getID();
tce3.setTitle(GanttTreeTableModel.strColInfo);
String name = getNameForId(id);
TableColumnExt tce4 = new TableColumnExt(3);
tce4.setTitle(GanttTreeTableModel.strColName);
if (dc.displayed)
TableColumnExt tce5 = new TableColumnExt(4);
displayColumn(name);
tce5.setTitle(GanttTreeTableModel.strColBegDate);
else
TableColumnExt tce6 = new TableColumnExt(5);
hideColumn(name);
tce6.setTitle(GanttTreeTableModel.strColEndDate);
}
TableColumnExt tce7 = new TableColumnExt(6);
}
tce7.setTitle(GanttTreeTableModel.strColDuration);
TableColumnExt tce8 = new TableColumnExt(7);
/**
* Initialize the treetable. Addition of various listeners, tree's
icons,
tce8.setTitle(GanttTreeTableModel.strColCompletion);
TableColumnExt tce9 = new TableColumnExt(8);
*/
tce9.setTitle(GanttTreeTableModel.strColCoordinator);
public void initTreeTable() {
TableColumnExt tce10 = new TableColumnExt(9);
clickPoint = null;
tce10.setTitle(GanttTreeTableModel.strColPredecessors);
if(Mediator.getCustomColumnsManager() == null)
TableColumnExt tce11 = new TableColumnExt(10);
tce11.setTitle(GanttTreeTableModel.strColID);
Mediator.registerCustomColumnsManager(new
CustomColumnsManager(this));
//LH
mapColNameMenuItem = new HashMap();
TableColumnExt tce12 = new TableColumnExt(11);
mapTableColumnColumnKeeper = new HashMap();
ttModel
=
this.getTreeTableModel();
tce12.setTitle(GanttTreeTableModel.strColBudget);
(GanttTreeTableModel)
this.addColumn(tce1);
Enumeration
enumeration
getTable().getColumnModel().getColumns();
=
Collection lToDel = new ArrayList();
tc
=
(TableColumnExt)
// System.out.println(tc.getTitle());
// if (!ttModel.titles.contains(tc.getTitle()))
lToDel.add(tc);
this.addColumn(tce3);
this.addColumn(tce4);
while (enumeration.hasMoreElements()) {
TableColumnExt
enumeration.nextElement();
this.addColumn(tce2);
this.addColumn(tce5);
this.addColumn(tce6);
this.addColumn(tce7);
this.addColumn(tce8);
this.addColumn(tce9);
this.addColumn(tce10);
137
this.addColumn(tce11);
dc6.setOrder(this.getTable().convertColumnIndexToView(
this.addColumn(tce12);
tce6.getModelIndex()));
dc6.setWidth(tce6.getPreferredWidth());
listDisplayedColumns = new DisplayedColumnsList();
listDisplayedColumns.add(dc6);
// Type
// Duration
DisplayedColumn
dc1
=
DisplayedColumn(getIdForName(tce1.getTitle()));
new
DisplayedColumn
dc7
=
DisplayedColumn(getIdForName(tce7.getTitle()));
new
dc1.setDisplayed(false);
dc7.setDisplayed(false);
dc1.setOrder(this.getTable().convertColumnIndexToView(
dc7.setOrder(this.getTable().convertColumnIndexToView(
tce1.getModelIndex()));
tce7.getModelIndex()));
dc1.setWidth(tce1.getPreferredWidth());
dc7.setWidth(tce7.getPreferredWidth());
listDisplayedColumns.add(dc1);
listDisplayedColumns.add(dc7);
// Priority
DisplayedColumn
dc2
=
DisplayedColumn(getIdForName(tce2.getTitle()));
// Completion
new
DisplayedColumn
dc8
=
DisplayedColumn(getIdForName(tce8.getTitle()));
new
dc2.setDisplayed(false);
dc8.setDisplayed(false);
dc2.setOrder(this.getTable().convertColumnIndexToView(
dc8.setOrder(this.getTable().convertColumnIndexToView(
tce2.getModelIndex()));
tce8.getModelIndex()));
dc2.setWidth(tce2.getPreferredWidth());
dc8.setWidth(tce8.getPreferredWidth());
listDisplayedColumns.add(dc2);
listDisplayedColumns.add(dc8);
// Info
DisplayedColumn
dc3
=
DisplayedColumn(getIdForName(tce3.getTitle()));
// Coordinator
new
DisplayedColumn
dc9
=
DisplayedColumn(getIdForName(tce9.getTitle()));
new
dc3.setDisplayed(false);
dc9.setDisplayed(false);
dc3.setOrder(this.getTable().convertColumnIndexToView(
dc9.setOrder(this.getTable().convertColumnIndexToView(
tce3.getModelIndex()));
tce9.getModelIndex()));
dc3.setWidth(tce3.getPreferredWidth());
dc9.setWidth(tce9.getPreferredWidth());
listDisplayedColumns.add(dc3);
listDisplayedColumns.add(dc9);
// Name
DisplayedColumn
dc4
=
DisplayedColumn(getIdForName(tce4.getTitle()));
new
// Predecessors
DisplayedColumn
dc10
DisplayedColumn(getIdForName(tce10
dc4.setDisplayed(true);
dc4.setOrder(this.getTable().convertColumnIndexToView(
=
new
.getTitle()));
tce4.getModelIndex()));
dc10.setDisplayed(false);
dc4.setWidth(tce4.getPreferredWidth());
dc10.setOrder(this.getTable().convertColumnIndexToView(
listDisplayedColumns.add(dc4);
tce10.getModelIndex()));
// Begin date
DisplayedColumn
dc5
=
DisplayedColumn(getIdForName(tce5.getTitle()));
new
dc10.setWidth(tce10.getPreferredWidth());
listDisplayedColumns.add(dc10);
dc5.setDisplayed(true);
dc5.setOrder(this.getTable().convertColumnIndexToView(
tce5.getModelIndex()));
dc5.setWidth(tce5.getPreferredWidth());
listDisplayedColumns.add(dc5);
// End date
DisplayedColumn
dc6
=
DisplayedColumn(getIdForName(tce6.getTitle()));
dc6.setDisplayed(true);
// ID
DisplayedColumn
dc11
DisplayedColumn(getIdForName(tce11
=
new
.getTitle()));
dc11.setDisplayed(false);
newdc11.setOrder(this.getTable().convertColumnIndexToView(
tce11.getModelIndex()));
dc11.setWidth(tce11.getPreferredWidth());
138
public
columnRemoved(TableColumnModelEvent e) {
listDisplayedColumns.add(dc11);
// nothing to do
// LH
//
void
}
BUDGET
DisplayedColumn
dc12
DisplayedColumn(getIdForName(tce12
=
new
.getTitle()));
dc12.setDisplayed(false);
public
columnMoved(TableColumnModelEvent e) {
DefaultTableColumnModel
(DefaultTableColumnModel) e
dc12.setWidth(tce12.getPreferredWidth());
listDisplayedColumns.add(dc12);
o
=
.getSource();
dc12.setOrder(this.getTable().convertColumnIndexToView(
tce12.getModelIndex()));
void
TableColumn
o.getColumn(e.getFromIndex());
ColumnKeeper
ck
mapTableColumnColumnKeeper
tc
=
=
((ColumnKeeper)
.get(tc));
if (ck != null)
this.setDisplayedColumns(listDisplayedColumns);
ck.setInitIndex(e.getToIndex());
if (Mediator.getGanttProjectSingleton() != null)
this.mapTableColumnColumnKeeper.put(tce1, null);
this.mapTableColumnColumnKeeper.put(tce2, null);
Mediator.getGanttProjectSingleton().setAskForSave(
this.mapTableColumnColumnKeeper.put(tce3, null);
true);
this.mapTableColumnColumnKeeper.put(tce4, null);
updateDisplayedColumnsOrder();
this.mapTableColumnColumnKeeper.put(tce5, null);
}
this.mapTableColumnColumnKeeper.put(tce6, null);
this.mapTableColumnColumnKeeper.put(tce7, null);
this.mapTableColumnColumnKeeper.put(tce8, null);
public void columnMarginChanged(ChangeEvent
e) {
this.mapTableColumnColumnKeeper.put(tce9, null);
// nothing to do
this.mapTableColumnColumnKeeper.put(tce10, null);
}
this.mapTableColumnColumnKeeper.put(tce11, null);
//LH
this.mapTableColumnColumnKeeper.put(tce12, null);
public
columnSelectionChanged(ListSelectionEvent e) {
void
// nothing to do
}
// the model must implement TableColumnModelListener
});
getTable().getColumnModel().addColumnModelListener(
(TableColumnModelListener)
this.getTreeTableModel());
initColumnsAlignements();
getTable().getModel().addTableModelListener(new
ModelListener());
// Highlighters to ease the reading of the table.
getTable().getTableHeader().addMouseListener(new
HeaderMouseListener());
setHighlighters(new HighlighterPipeline(new Highlighter[] {
// The following is used to store the new index of a moved
column in
AlternateRowHighlighter.quickSilver,
new HierarchicalColumnHighlighter() }));
// order
// to restore it properly.
// set the CellEditor for the dates.
getTable().getColumnModel().addColumnModelListener(
new TableColumnModelListener() {
getTable().getColumnExt(GanttTreeTableModel.strColBegDate)
public void columnAdded(TableColumnModelEvent
.setCellEditor(new DateCellEditor(new JTextField()));
e) {
// nothing to do
}
getTable().getColumnExt(GanttTreeTableModel.strColEndDate)
.setCellEditor(new DateCellEditor(new JTextField()));
139
.getListeners(MouseListener.class);
getTable().getColumnExt(GanttTreeTableModel.strColName).s
etCellEditor(
for (int i = 0; i < listeners.length; i++)
this.getTreeTable().getParent().removeMouseListener(
new NameCellEditor());
(MouseListener) listeners[i]);
setShowHorizontalLines(true);
this.getTreeTable().getParent().addMouseListener(new
MouseAdapter() {
public void mouseClicked(MouseEvent e) {
ImageIcon icon = new ImageIcon(getClass().getResource(
e.consume();
"/icons/simple_task.gif"));
if (e.getClickCount() == 1)
Mediator.getGanttProjectSingleton().getTree()
setOpenIcon(null);
.selectTreeRow(-1);
setClosedIcon(null);
else if (e.getClickCount() == 2
setCollapsedIcon(new ImageIcon(getClass()
&& e.getButton() == MouseEvent.BUTTON1) {
.getResource("/icons/plus.gif")));
setExpandedIcon(new ImageIcon(getClass()
Mediator.getGanttProjectSingleton().getUndoManager()
.undoableEdit("New
.getResource("/icons/minus.gif")));
setLeafIcon(null);
Task
by
click",
new
Runnable() {
public void run() {
Mediator.getGanttProjectSingleton()
createPopupMenu();
.newTask();
}
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);
void addScrollPaneMouseListener(MouseListener ml) {
this.getTreeTable().getParent().addMouseListener(ml);
// this.setDisplayedColumns(l);
// // hideColumn("Name");
if (listDisplayedColumns != null)
this.setDisplayedColumns(listDisplayedColumns);
}
private void initColumnsAlignements() {
// set the columns horizontal aligment. It also associate an
// appropiate renderer according to the column class.
else
this.displayAllColumns();
Thread t = new Thread() {
public void run() {
calculateWidth();
revalidate();
setColumnHorizontalAlignment(GanttTreeTableModel.strColTy
pe,
SwingConstants.CENTER);
setColumnHorizontalAlignment(GanttTreeTableModel.strColPri
ority,
SwingConstants.CENTER);
}
};
SwingUtilities.invokeLater(t);
setColumnHorizontalAlignment(GanttTreeTableModel.strColInf
o,
SwingConstants.CENTER);
//
this.getTreeTable().getParent().setBackground(Color.WHITE); setColumnHorizontalAlignment(GanttTreeTableModel.strColNa
EventListener listeners[] = this.getTreeTable().getParent() me,
140
// SwingConstants.LEFT);
setColumnHorizontalAlignment(GanttTreeTableModel.strColBe
gDate,
SwingConstants.RIGHT);
.setPreferredWidth(50);
//
getTable().getColumnExt(GanttTreeTableModel.strColType).set
MaxWidth(32);
//
setColumnHorizontalAlignment(GanttTreeTableModel.strColEn getTable().getColumnExt(GanttTreeTableModel.strColPriority).s
dDate,
etMaxWidth(42);
SwingConstants.RIGHT);
setColumnHorizontalAlignment(GanttTreeTableModel.strColDur
ation,
SwingConstants.CENTER);
//
getTable().getColumnExt(GanttTreeTableModel.strColInfo).set
MaxWidth(32);
//
getTable().getColumnExt(GanttTreeTableModel.strColName).s
etMaxWidth(800);
//
setColumnHorizontalAlignment(GanttTreeTableModel.strColCo getTable().getColumnExt(GanttTreeTableModel.strColBegDate)
mpletion,
.setMaxWidth(300);
SwingConstants.CENTER);
//
getTable().getColumnExt(GanttTreeTableModel.strColEndDate)
setColumnHorizontalAlignment(GanttTreeTableModel.strColCo .setMaxWidth(300);
ordinator,
//
getTable().getColumnExt(GanttTreeTableModel.strColDuration)
SwingConstants.CENTER);
.setMaxWidth(300);
//
setColumnHorizontalAlignment(GanttTreeTableModel.strColPre
getTable().getColumnExt(GanttTreeTableModel.strColCompleti
decessors,
on).setMaxWidth(300);
SwingConstants.RIGHT);
//
getTable().getColumnExt(GanttTreeTableModel.strColCoordina
setColumnHorizontalAlignment(GanttTreeTableModel.strColID, tor).setMaxWidth(300);
SwingConstants.CENTER);
}
//LH
void calculateWidth() {
setColumnHorizontalAlignment(GanttTreeTableModel.strColBu
dget,
int width = 0;
SwingConstants.CENTER);
int nbCol = getTable().getColumnCount();
// Set the columns widths
for (int i = 0; i < nbCol; i++) {
getTable().getColumnExt(GanttTreeTableModel.strColID)
TableColumnExt tce = getTable().getColumnExt(i);
.setPreferredWidth(32);
if (tce.isVisible())
//LH
width += tce.getPreferredWidth();
getTable().getColumnExt(GanttTreeTableModel.strColBudget)
}
.setPreferredWidth(32);
getTable().getColumnExt(GanttTreeTableModel.strColType)
.setPreferredWidth(32);
getTable().setPreferredScrollableViewportSize(new
Dimension(width, 0));
}
getTable().getColumnExt(GanttTreeTableModel.strColPriority)
.setPreferredWidth(42);
/**
* Creates the popupMenu used to hide/show columns and to
getTable().getColumnExt(GanttTreeTableModel.strColInfo) add customs
.setPreferredWidth(32);
getTable().getColumnExt(GanttTreeTableModel.strColName)
.setPreferredWidth(120);
getTable().getColumnExt(GanttTreeTableModel.strColDuration)
* columns. It will associate each tablecolumn with an
ColumnKeeper in
* charge of adding and removing the tablecolumn.
*/
private void createPopupMenu() {
141
Iterator
it
mapTableColumnColumnKeeper.keySet().iterator();
});
=
}
mapColNameMenuItem.clear();
});
popupMenu = new JPopupMenu();
TableColumnModel
this.getTable().getColumnModel();
tcModel
=
JMenuItem
jmiDisplayAll
JMenuItem(language.getText("displayAll"));
// int nbCol = tcModel.getColumnCount();
new
jmiDisplayAll.addActionListener(new ActionListener() {
int
nbCol
mapTableColumnColumnKeeper.keySet().size();
=
for (int i = 0; i < nbCol; i++) {
public void actionPerformed(ActionEvent e) {
Mediator.getGanttProjectSingleton().getUndoManager()
// TableColumn column = tcModel.getColumn(i);
.undoableEdit("displayAllColumns",
jcbmi
=
new
Runnable() {
TableColumn column = (TableColumn) it.next();
JCheckBoxMenuItem
JCheckBoxMenuItem(column
=
public void run() {
new
displayAllColumns();
.getHeaderValue().toString());
}
});
ColumnKeeper
ck
mapTableColumnColumnKeeper
=
(ColumnKeeper)
}
.get(column);
});
if (ck == null)
/*
ck = new ColumnKeeper(column);
* To delete a custom column the user has to right click on
the column
jcbmi.setSelected(ck.isShown);
* header. If the colum header match with a custom column
the menu item
jcbmi.addActionListener(ck);
* will be enable. Otherwise it is disable.
mapTableColumnColumnKeeper.put(column, ck);
*/
jmiDeleteColumn
=
JMenuItem(language.getText("deleteCustomColumn"));
new
mapColNameMenuItem.put(column.getHeaderValue().toString(
jmiDeleteColumn.setIcon(new
), jcbmi);
ImageIcon(getClass().getResource(
popupMenu.add(jcbmi);
"/icons/removeCol_16.gif")));
}
jmiDeleteColumn.addActionListener(new ActionListener() {
popupMenu.addSeparator();
public void actionPerformed(ActionEvent e) {
JMenuItem jmiAddColumn = new JMenuItem(language
Mediator.getGanttProjectSingleton().getUndoManager()
.undoableEdit("deleteCustomColumn",
.getText("addCustomColumn"));
jmiAddColumn.setIcon(new
ImageIcon(getClass().getResource(
public void run() {
"/icons/addCol_16.gif")));
jmiAddColumn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//
deleteCustomColumn(getTable().getColumnName(getTable().c
olumnAtPoint(clickPoint)));
int
getTable().columnAtPoint(clickPoint);
ind
=
if(ind >=0){
Mediator.getGanttProjectSingleton().getUndoManager()
.undoableEdit("PopUpNewColumn",
new
Runnable() {
new
Mediator
Runnable() {
.getCustomColumnsManager()
public void run() {
Mediator.getCustomColumnsManager()
.addNewCustomColumn(null);
}
.deleteCustomColumn(getTable().getColumnName(ind));
jmiDeleteColumn.setEnabled(false);
}
142
}
});
}
else
comp[i]).isSelected())
if
(((JCheckBoxMenuItem)
jcbmi.setEnabled(true);
}
}
});
Collection col = mapColNameMenuItem.keySet();
jmiDeleteColumn.setEnabled(false);
Iterator it2 = col.iterator();
while (it2.hasNext()) {
popupMenu.add(jmiDisplayAll);
String s = (String) it2.next();
popupMenu.addSeparator();
int o = listDisplayedColumns.getOrderForName(s);
popupMenu.add(jmiAddColumn);
if (o == -1)
popupMenu.add(jmiDeleteColumn);
popupMenu.add((JMenuItem)
mapColNameMenuItem.get(s), last);
}
private void reorderPopuMenu() {
last = popupMenu.getComponentCount() - 5;
int total = popupMenu.getComponentCount() - 5;
}
int last = popupMenu.getComponentCount() - 5;
}
for (int i = 0; i < total; i++)
popupMenu.remove(0);
Collections.sort(listDisplayedColumns);
/**
* Rename the MenuItem named <code>oldName</code>
intor
Collections.reverse(listDisplayedColumns);
* <code>newName</code>.
Iterator it = listDisplayedColumns.iterator();
*
boolean disable = false;
* @param oldName
while (it.hasNext()) {
*
MenuItem old name.
last = popupMenu.getComponentCount() - 5;
* @param newName
DisplayedColumn dc = (DisplayedColumn) it.next();
*
*/
JMenuItem jmi = null;
int pos = 0;
MenuItem new name.
private void
newName) {
if (dc.isDisplayed())
renameMenuItem(String
oldName,
String
Component[] t = popupMenu.getComponents();
jmi
=
(JMenuItem)
mapColNameMenuItem.get(getNameForId(dc.id));
JCheckBoxMenuItem jcbmi = null;
for (int i = 0; i < t.length; i++) {
else {
if (t[i] instanceof JCheckBoxMenuItem) {
jmi
=
(JMenuItem)
mapColNameMenuItem.get(getNameForId(dc.id));
jcbmi = (JCheckBoxMenuItem) t[i];
pos = last;
if (jcbmi.getText().equals(oldName)) {
}
jcbmi.setText(newName);
popupMenu.add(jmi, pos);
break;
}
}
Component comp[] = popupMenu.getComponents();
}
JCheckBoxMenuItem jcbmi = null;
}
for (int i = 0; i < comp.length; i++) {
if (jcbmi != null) {
if (comp[i] instanceof JCheckBoxMenuItem)
mapColNameMenuItem.remove(oldName);
if (jcbmi == null) {
mapColNameMenuItem.put(newName, jcbmi);
jcbmi = (JCheckBoxMenuItem) comp[i];
if (jcbmi.isSelected())
}
}
jcbmi.setEnabled(false);
else
jcbmi = null;
/**
* Displays all the table columns.
143
TableColumn c = (TableColumn) it.next();
*/
String n = (String) c.getHeaderValue();
private void displayAllColumns() {
Iterator
it
mapTableColumnColumnKeeper.values().iterator();
if (n.equals(name)) {
=
ColumnKeeper
ck
mapTableColumnColumnKeeper
while (it.hasNext()) {
=
(ColumnKeeper)
.get(c);
ColumnKeeper ck = (ColumnKeeper) it.next();
if (indexView != -1)
if (!ck.isShown)
ck.index = indexView;
ck.show();
if (!ck.isShown)
}
ck.show();
createPopupMenu();
break;
}
}
}
/**
* Displays all the table columns.
getTable().getColumnExt(name).setPreferredWidth(width);
*/
private void hideAllColumns() {
Iterator
it
mapTableColumnColumnKeeper.values().iterator();
createPopupMenu();
=
}
while (it.hasNext()) {
ColumnKeeper ck = (ColumnKeeper) it.next();
private void hideColumn(String name) {
if (ck.isShown)
Iterator
it
mapTableColumnColumnKeeper.keySet().iterator();
ck.hide();
=
while (it.hasNext()) {
}
TableColumn c = (TableColumn) it.next();
createPopupMenu();
String n = (String) c.getHeaderValue();
}
if (n.equals(name)) {
ColumnKeeper
ck
mapTableColumnColumnKeeper
/**
* Display the column whose name is given in parameter.
=
(ColumnKeeper)
.get(c);
*
if (ck.isShown)
* @param name
*
ck.hide();
Name of the column to display.
break;
*/
}
private void displayColumn(String name) {
}
int indexView = -1;
createPopupMenu();
int width = -1;
}
Iterator itDc = this.listDisplayedColumns.iterator();
while (itDc.hasNext()) {
/**
DisplayedColumn dc = (DisplayedColumn) itDc.next();
* Adds a new custom column. The custom column will affect
all tasks and
if (getNameForId(dc.getID()).equals(name)) {
indexView = dc.getOrder();
* future tasks. Several types are available for the custom
columns (string,
width = dc.getWidth();
* date, integer, double, boolean). A default value is also set.
}
*/
}
public
void
customColumn) {
Iterator
it
mapTableColumnColumnKeeper.keySet().iterator();
while (it.hasNext()) {
=
addNewCustomColumn(CustomColumn
if (customColumn == null) {
customColumn = new CustomColumn();
144
GanttDialogCustomColumn
GanttDialogCustomColumn(Mediator
d
=
if
new
(customColumn.getType().equals(GregorianCalendar.class))
align = SwingConstants.RIGHT;
.getGanttProjectSingleton(), customColumn);
setColumnHorizontalAlignment(newName, align);
d.setVisible(true);
}
DisplayedColumn dc = new DisplayedColumn(Mediator
if (customColumn.getName() != null) // if something has
.getCustomColumnsStorage().getIdFromName(newName));
been entered
dc.setDisplayed(true);
{
GanttTreeTableModel
treeTableModel
(GanttTreeTableModel) getTreeTableModel();
=
dc.setOrder(getTable().convertColumnIndexToView(
getColumn(newName).getModelIndex()));
int nbCol = treeTableModel.getColumnCountTotal(); // +
// treeTableModel.getCustomColumnCount();
dc.setWidth(getColumn(newName).getPreferredWidth());
String newName = customColumn.getName();
this.listDisplayedColumns.add(dc);
((GanttTreeTableModel)
ttModel).addCustomColumn(newName);
if (GregorianCalendar.class
.isAssignableFrom(customColumn.getType()))
getTable().getColumnExt(newName).setCellEditor(
try {
new DateCellEditor(new JTextField()));
Mediator.getCustomColumnsStorage()
.addCustomColumn(customColumn);
} catch (CustomColumnsException ex) {
if
(ex.getType()
CustomColumnsException.ALREADY_EXIST)
//
JCheckBoxMenuItem
==JCheckBoxMenuItem(newName);
jcbmi
=
new
jcbmi.setSelected(true);
addNewCustomColumn(null);
ColumnKeeper ck = new ColumnKeeper(t);
return;
jcbmi.addActionListener(ck);
}
mapColNameMenuItem.put(newName, jcbmi);
mapTableColumnColumnKeeper.put(t, ck);
TaskContainmentHierarchyFacade tchf = Mediator
.getGanttProjectSingleton().getTaskManager()
popupMenu.insert(jcbmi,
popupMenu.getSubElements().length - 3);
//
.getTaskHierarchy();
setCustomColumnValueToAllNestedTask(tchf,
tchf.getRootTask(),
Mediator.getGanttProjectSingleton().setAskForSave(true);
customColumn.getName(),
customColumn.getDefaultValue());
}
TableColumnExt t = new TableColumnExt(nbCol);
Thread t = new Thread() {
t.setMaxWidth(500);
public void run() {
t.setHeaderValue(newName);
calculateWidth();
getTable().getColumnModel().addColumn(t);
revalidate();
try {
}
if (clickPoint != null)
};
getTable().getColumnModel().moveColumn(
SwingUtilities.invokeLater(t);
getTable().getColumnCount() - 1,
getTable().columnAtPoint(clickPoint));
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
/**
* Delete permanently a custom column.
int align = SwingConstants.CENTER;
145
*
* @param name
*
// CustomColumnsStorage level
Name of the column to delete.
Mediator.getCustomColumnsStorage().removeCustomColumn(
name);
*/
public void deleteCustomColumn(String name) {
// Every tasks
try {
TaskContainmentHierarchyFacade tchf = Mediator
Mediator.getCustomColumnsStorage().getCustomColumn(nam .getGanttProjectSingleton().getTaskManager().getTaskHierarch
e);
y();
} catch (CustomColumnsException e) {
tchf.getRootTask().getCustomValues().removeCustomColumn(
name);
// e.printStackTrace();
return;
removeCustomColumnToAllNestedTask(tchf,
tchf.getRootTask(), name);
}
// the column has to be displayed to be removed.
// MenuItem
this.displayColumn(name);
popupMenu.remove(popupMenu
.getComponentIndex((Component)
mapColNameMenuItem.get(name)));
// DisplayedColumns
mapColNameMenuItem.remove(name);
DisplayedColumn toDel = null;
Iterator it = listDisplayedColumns.iterator();
// newBB
Iterator
it2
mapTableColumnColumnKeeper.keySet().iterator();
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
=
while (it2.hasNext()) {
if (getNameForId(dc.getID()).equals(name))
TableColumn c = (TableColumn) it2.next();
toDel = dc;
String n = (String) c.getHeaderValue();
}
if (n.equals(name)) {
if (toDel != null)
mapTableColumnColumnKeeper.remove(c);
listDisplayedColumns.remove(toDel);
break;
}
int
index
getTable().getColumnModel().getColumnIndex(name);
=
int
modelIndex
getTable().convertColumnIndexToModel(index);
=
TableColumnModelEvent
tcme
TableColumnModelEvent(getTable()
}
Mediator.getGanttProjectSingleton().setAskForSave(true);
=
new
.getColumnModel(), modelIndex, modelIndex);
getTable().removeColumn(getTable().getColumnExt(name));
getTable().columnRemoved(tcme);
}
public void
newName) {
renameCustomcolumn(String
name,
String
Mediator.getGanttProjectSingleton().setAskForSave(true);
this.displayColumn(name);
/*
TableColumnExt
tc
=
(TableColumnExt)
* TODO There is a problem here : I don't remove thegetTable().getColumn(name);
custom column from
tc.setTitle(newName);
* the treetablemodel. If I remove it there will be a problem
Mediator.getGanttProjectSingleton().repaint();
when
* deleting a custom column if it isn't the last created.
renameMenuItem(name, newName);
*/
// TreeTableModel
TaskContainmentHierarchyFacade tchf = Mediator
ttModel.deleteCustomColumn(name);
146
try {
.getGanttProjectSingleton().getTaskManager().getTaskHierarch
y();
root.getCustomValues().setValue(colName, value);
} catch (CustomColumnsException e) {
tchf.getRootTask().getCustomValues().renameCustomColumn(
name, newName);
e.printStackTrace();
}
renameCustomColumnForAllNestedTask(tchf,
tchf.getRootTask(), name,
Task[] tt = facade.getNestedTasks(root);
for (int i = 0; i < tt.length; i++) {
newName);
ttModel.renameCustomColumn(name, newName);
try {
// newBB
} catch (CustomColumnsException e1) {
tt[i].getCustomValues().setValue(colName, value);
Iterator
it
mapTableColumnColumnKeeper.keySet().iterator();
while (it.hasNext()) {
TableColumn c = (TableColumn) it.next();
e1.printStackTrace();
=
}
setCustomColumnValueToAllNestedTask(facade,
colName, value);
}
String n = (String) c.getHeaderValue();
}
if (n.equals(name)) {
ColumnKeeper
ck
mapTableColumnColumnKeeper
tt[i],
=
(ColumnKeeper)
.get(c);
((TableColumnExt) c).setTitle(newName);
/**
* Remove permanetly the custom column for the task
<code>root</code> and
* all its children.
break;
*
}
* @param facade
}
*
tasks.
}
TaskContainmentHierarchyFacade ot retrive nested
* @param root
// public void changeDefaultValue(String name, Object
newDefaultValue)
*
Root task to start with.
* @param colName
*
// {
Name of the custom column to remove.
// // this.displayColumn(name);
*/
// }
private void removeCustomColumnToAllNestedTask(
TaskContainmentHierarchyFacade facade, Task root,
String colName) {
/**
* @param facade
*
tasks.
//
root.getCustomValues().removeCustomColumn(colName);
TaskContainmentHierarchyFacade ot retrive nested
Task[] tt = facade.getNestedTasks(root);
* @param root
*
* @param colName
*
tasks.
for (int i = 0; i < tt.length; i++) {
Root task to start with.
tt[i].getCustomValues().removeCustomColumn(colName);
Name of the new custom column to add to the
removeCustomColumnToAllNestedTask(facade,
colName);
* @param value
*
Value for this new custom column.
tt[i],
}
}
*/
private void setCustomColumnValueToAllNestedTask(
private void renameCustomColumnForAllNestedTask(
TaskContainmentHierarchyFacade facade, Task root,
TaskContainmentHierarchyFacade facade, Task root,
String colName,
String oldName,
Object value) {
String newName) {
147
int
iColType
//
root.getCustomValues().renameCustomColumn(oldName,newN tcm.getColumnIndex(GanttTreeTableModel.strColType);
ame);
int iColPriority = tcm
=
Task[] tt = facade.getNestedTasks(root);
.getColumnIndex(GanttTreeTableModel.strColPriority);
for (int i = 0; i < tt.length; i++) {
int
iColInfo
tcm.getColumnIndex(GanttTreeTableModel.strColInfo);
=
tt[i].getCustomValues().renameCustomColumn(oldName,
newName);
int
iColName
tcm.getColumnIndex(GanttTreeTableModel.strColName);
=
renameCustomColumnForAllNestedTask(facade,
oldName, newName);
int
iColBegDate
tt[i],
tcm.getColumnIndex(GanttTreeTableModel.strColBegDate);
=
int
iColEndDate
tcm.getColumnIndex(GanttTreeTableModel.strColEndDate);
=
}
}
int iColDuration = tcm
/**
.getColumnIndex(GanttTreeTableModel.strColDuration);
* Changes the language. The table headers change and
int iColCompletion = tcm
also the menu items.
* For the moment when the user changes the language.getColumnIndex(GanttTreeTableModel.strColCompletion);
every columns are
int iColCoordinator = tcm
* redisplayed (even if they were hidden).
*
.getColumnIndex(GanttTreeTableModel.strColCoordinator);
* @param ganttLanguage
int iColPredecessor = tcm
*/
public
void
ganttLanguage) {
changeLanguage(GanttLanguage.getColumnIndex(GanttTreeTableModel.strColPredecessors);
int
iColID
tcm.getColumnIndex(GanttTreeTableModel.strColID);
/*
* The following is ugly but it seems to work. I've had some
problems
//LH
int
iColBudget
* when changing the language. the solution I'vetcm.getColumnIndex(GanttTreeTableModel.strColBudget);
implemented is to get
* the TableColum and set the new header name.
tcm
=
((GanttTreeTableModel)
this.ttModel).changeLanguage(ganttLanguage);
*/
TableColumnModel
this.getTable().getColumnModel();
=
=
tcm.getColumn(iColType).setHeaderValue(GanttTreeTableMod
el.strColType);
List listTableColumnToHide = new ArrayList();
tcm.getColumn(iColPriority).setHeaderValue(
GanttTreeTableModel.strColPriority);
Iterator
it
mapTableColumnColumnKeeper.keySet().iterator();
while (it.hasNext()) {
=
tcm.getColumn(iColInfo).setHeaderValue(GanttTreeTableModel
.strColInfo);
TableColumn tc = (TableColumn) it.next();
ColumnKeeper
ck
=
mapTableColumnColumnKeeper.get(tc);
tcm.getColumn(iColName).setHeaderValue(GanttTreeTableMo
(ColumnKeeper)del.strColName);
tcm.getColumn(iColBegDate).setHeaderValue(
if (!ck.isShown) {
listTableColumnToHide.add(tc);
//
Integer(ck.getInitIndex()));
ck.show();
}
}
listColIndexToHide.add(new
GanttTreeTableModel.strColBegDate);
tcm.getColumn(iColEndDate).setHeaderValue(
GanttTreeTableModel.strColEndDate);
tcm.getColumn(iColDuration).setHeaderValue(
GanttTreeTableModel.strColDuration);
tcm.getColumn(iColCompletion).setHeaderValue(
GanttTreeTableModel.strColCompletion);
148
tcm.getColumn(iColCoordinator).setHeaderValue(
.setSelected(((ColumnKeeper)
mapTableColumnColumnKeeper
GanttTreeTableModel.strColCoordinator);
tcm.getColumn(iColPredecessor).setHeaderValue(
.get(tcm.getColumn(tcm.getColumnIndex(c
GanttTreeTableModel.strColPredecessors);
.getText())))).isShown);
} catch (IllegalArgumentException e) {
tcm.getColumn(iColID).setHeaderValue(GanttTreeTableModel.
strColID);
c.setSelected(false);
//LH
}
}
tcm.getColumn(iColBudget).setHeaderValue(GanttTreeTableM
odel.strColBudget);
}
}
this.createPopupMenu();
String getIdForName(String colName) {
/*
String id = null;
* Presently when the language is modified, every columns
if (colName.equals(GanttTreeTableModel.strColType))
are
id = "tpd0";
* redisplayed even those which were hidden.
else
(colName.equals(GanttTreeTableModel.strColPriority))
*/
if
id = "tpd1";
// Collections.sort(listColIndexToHide);
else if (colName.equals(GanttTreeTableModel.strColInfo))
// Collections.reverse(listColIndexToHide);
id = "tpd2";
// System.out.println(listColIndexToHide);
else
(colName.equals(GanttTreeTableModel.strColName))
it = listTableColumnToHide.iterator();
while (it.hasNext()) {
if
id = "tpd3";
// int i = ((Integer) it.next()).intValue();
else
(colName.equals(GanttTreeTableModel.strColBegDate))
// System.out.println(i +" pour " + tcm.getColumnCount()
+ ", model
if
id = "tpd4";
else
(colName.equals(GanttTreeTableModel.strColEndDate))
// : " +
if
id = "tpd5";
// i);
else
(colName.equals(GanttTreeTableModel.strColDuration))
((ColumnKeeper)
mapTableColumnColumnKeeper.get(it.next())).hide();
//
TableColumnModelEvent
TableColumnModelEvent(tcm,i,i);
tcme
if
id = "tpd6";
=
else
new
(colName.equals(GanttTreeTableModel.strColCompletion))
id = "tpd7";
// getTable().columnRemoved(tcme);
}
Component tcomp[] = popupMenu.getComponents();
if
else
(colName.equals(GanttTreeTableModel.strColCoordinator))
if
id = "tpd8";
else
if
(colName.equals(GanttTreeTableModel.strColPredecessors))
for (int i = 0; i < tcomp.length; i++) {
if (tcomp[i] instanceof JCheckBoxMenuItem) {
JCheckBoxMenuItem
c
=
id = "tpd9";
(JCheckBoxMenuItem)
tcomp[i];
id = "tpd10";
// The following isn't well done...
// catching an exception to set the menu slected or
not is
// ugly...
// TODO make this more beautiful
try {
else if (colName.equals(GanttTreeTableModel.strColID))
//LH
else
(colName.equals(GanttTreeTableModel.strColBudget))
if
id = "tpd11";
else
c
149
id
=
Mediator.getCustomColumnsStorage().getIdFromName(colNam
e);
/**
* Returns the vertical scrollbar.
return id;
*
}
* @return The vertical scrollbar.
*/
private String getNameForId(String id) {
public JScrollBar getVerticalScrollBar() {
String name = null;
return scrollPane.getVerticalScrollBar();
if (id.equals("tpd0"))
}
name = GanttTreeTableModel.strColType;
else if (id.equals("tpd1"))
public JScrollPane getScrollPane() {
name = GanttTreeTableModel.strColPriority;
return scrollPane;
else if (id.equals("tpd2"))
}
name = GanttTreeTableModel.strColInfo;
else if (id.equals("tpd3"))
/**
name = GanttTreeTableModel.strColName;
*
else if (id.equals("tpd4"))
* @inheritDoc
name = GanttTreeTableModel.strColBegDate;
*/
else if (id.equals("tpd5"))
public void requestFocus() {
name = GanttTreeTableModel.strColEndDate;
else if (id.equals("tpd6"))
name = GanttTreeTableModel.strColDuration;
if
(getDisplayColumns().isDisplayed(GanttTreeTableModel.strCol
Name)) {
int c = getTable().convertColumnIndexToView(
else if (id.equals("tpd7"))
name = GanttTreeTableModel.strColCompletion;
else if (id.equals("tpd8"))
getColumn(GanttTreeTableModel.strColName).getModelIndex()
);
name = GanttTreeTableModel.strColCoordinator;
NameCellEditor ed = (NameCellEditor) getTable()
else if (id.equals("tpd9"))
.getCellEditor(-1, c);
name = GanttTreeTableModel.strColPredecessors;
ed.requestFocus();
else if (id.equals("tpd10"))
}
name = GanttTreeTableModel.strColID;
}
//LH
else if (id.equals("tpd11"))
public void centerViewOnSelectedCell() {
name = GanttTreeTableModel.strColBudget;
int row = getTable().getSelectedRow();
else
name
Mediator.getCustomColumnsStorage().getNameFromId(id);
int col = getTable().getEditingColumn();
=
if (col == -1)
col = getTable().getSelectedColumn();
return name;
Rectangle rect = getTable().getCellRect(row, col, true);
}
scrollPane.getHorizontalScrollBar().scrollRectToVisible(rect);
/**
scrollPane.getViewport().scrollRectToVisible(rect);
* Returns the JTree used in the treetable.
*
}
* @return The JTree used in the treetable.
*/
public JTree getTree() {
return this.getTreeTable().getTree();
}
public
void
mouseListener) {
addMouseListener(MouseListener
super.addMouseListener(mouseListener);
getTable().addMouseListener(mouseListener);
150
Iterator it = this.iterator();
getTree().addMouseListener(mouseListener);
while (it.hasNext()) {
this.getTreeTable().getParent().addMouseListener(mouseListen
er);
DisplayedColumn dc = (DisplayedColumn) it.next();
if (getNameForId(dc.getID()).equals(name))
}
return dc.isDisplayed();
}
/**
return false;
* Adds the key listener to the Table, the tree and this.
}
*/
public void addKeyListener(KeyListener keyListener) {
public int getOrderForName(String name) {
super.addKeyListener(keyListener);
getTable().addKeyListener(keyListener);
Iterator it = this.iterator();
getTree().addKeyListener(keyListener);
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
}
if (getNameForId(dc.getID()).equals(name))
return dc.getOrder();
void setDelay(TaskNode taskNode, Delay delay) {
}
try {
int
indexInfo
getTable().getColumnModel().getColumnIndex(
return -1;
=
}
GanttTreeTableModel.strColInfo);
indexInfo
getTable().convertColumnIndexToModel(indexInfo);
=
public String getNameForOrder(int order) {
Iterator it = this.iterator();
ttModel.setValueAt(delay, taskNode, indexInfo);
while (it.hasNext()) {
} catch (IllegalArgumentException e) {
DisplayedColumn dc = (DisplayedColumn) it.next();
}
if (dc.getOrder() == order)
}
return getNameForId(dc.getID());
}
/*
return null;
* ----- INNER CLASSES ----}
*/
public class DisplayedColumnsList extends ArrayList {
public boolean add(Object o) {
if (o instanceof DisplayedColumn) {
public DisplayedColumnsList() {
DisplayedColumn dc1 = (DisplayedColumn) o;
super();
Iterator it = this.iterator();
}
while (it.hasNext()) {
DisplayedColumn dc = (DisplayedColumn) it.next();
/**
if (dc.getID().equals(dc1.getID())) {
* Returns <code>true</code> if the column name
<code>name</code>
this.remove(dc);
return super.add(dc1);
* is displayed, <code>false</code> otherwise.
}
*
* @param name
}
*
return super.add(dc1);
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.
*/
return false;
}
public boolean isDisplayed(String name) {
151
}
public Object clone() {
DisplayedColumnsList l = new DisplayedColumnsList();
public int getWidth() {
Iterator it = this.iterator();
return width;
while (it.hasNext())
}
l.add(((DisplayedColumn) it.next()).clone());
public void setWidth(int width) {
return l;
this.width = width;
}
}
}
public Object clone() {
DisplayedColumn dc = new DisplayedColumn(this.id);
public class DisplayedColumn implements Comparable {
dc.setDisplayed(this.isDisplayed());
private String id = null;
dc.setOrder(this.getOrder());
dc.setWidth(this.getWidth());
private boolean displayed = false;
return dc;
private int order = -1;
}
private int width = 0;
public String toString() {
public DisplayedColumn(String id) {
return "[ID = " + id + ", displayed = " + displayed + ",
order = "
+ order + "]";
this.id = id;
}
}
/*
public void setID(String id) {
* (non-Javadoc)
this.id = id;
*
}
*
java.lang.Comparable#compareTo(java.lang.Object)
public void setDisplayed(boolean disp) {
@see
*/
this.displayed = disp;
public int compareTo(Object o) {
}
if (o == null)
public boolean isDisplayed() {
if (o instanceof DisplayedColumn) {
return 0;
return this.displayed;
DisplayedColumn dc = (DisplayedColumn) o;
}
if (this.order != dc.order)
return this.order - dc.order;
public String getID() {
return this.id.compareTo(dc.id);
return this.id;
}
}
return 0;
}
public void setOrder(int order) {
}
this.order = order;
}
/**
public int getOrder() {
return this.order;
* This actionListener manages the column to be hiden or
displayed. It has a
* TableColumn and hide it or display it
152
public int getInitIndex() {
*
return index;
* @author bbaranne Mar 1, 2005
}
*/
class ColumnKeeper implements ActionListener {
/**
/**
* the initial index of the table column.
* Hides the table column.
*/
*/
private int index;
void hide() {
getTable().getColumnModel().removeColumn(column);
/**
isShown = false;
* True if the table column is displayed, false otherwise.
String name = (String) column.getHeaderValue();
*/
private boolean isShown = true;
String id = getIdForName(name);
/**
Iterator it = listDisplayedColumns.iterator();
* The managed table column.
while (it.hasNext()) {
*/
DisplayedColumn dc = (DisplayedColumn) it.next();
protected TableColumn column;
if (dc.getID().equals(id))
dc.setDisplayed(false);
}
/**
* Creates
TableColumn.
a
new
ColumnKeeper
for
the
// Thread t = new Thread(){
given
// public void run(){
*
calculateWidth();
* @param tc
*
revalidate();
TableColumn to manage.
// }
*/
// };
public ColumnKeeper(TableColumn tc) {
column = tc;
// SwingUtilities.invokeLater(t);
}
index = column.getModelIndex();
}
/**
* Shows the table column.
/**
*/
* Set the initial index of the table column.
*
boolean reloadInfo = false;
* @param initIndex
*
void show() {
The initial index of the table column.
*/
getTable().getColumnModel().addColumn(column);
try {
int columnViewIndexOld = index;
public void setInitIndex(int initIndex) {
index = initIndex;
}
int
columnModelIndexActual
column.getModelIndex();
=
if (column.getIdentifier().equals(
GanttTreeTableModel.strColInfo))
/**
* Returns the initial index of the table column.
reloadInfo = true;
int columnViewIndexActual = getTable()
*
* @return The initial index of the table column.
*/
.convertColumnIndexToView(columnModelIndexActual);
getTable()
153
hide();
.moveColumn(columnViewIndexActual,
columnViewIndexOld);
getTable().repaint();
} catch (IllegalArgumentException e) {
}
index = getTable().getModel().getColumnCount() - 1;
});
}
}
isShown = true;
String name = (String) column.getHeaderValue();
String id = getIdForName(name);
boolean found = false;
}
/**
* This class handles the mouse actions on the treetable
header.
Iterator it = listDisplayedColumns.iterator();
*
while (it.hasNext()) {
* @author bbaranne Mar 1, 2005
DisplayedColumn dc = (DisplayedColumn) it.next();
if (dc.getID().equals(id)) {
dc.setDisplayed(true);
found = true;
}
* @version 1.0 Show the popupMenu when popup is
triggered.
*/
class HeaderMouseListener extends MouseAdapter {
/**
* Creates a new HeaderMouseListener
}
if (!found && id != null) {
DisplayedColumn dc = new DisplayedColumn(id);
*/
public HeaderMouseListener() {
super();
dc.setDisplayed(true);
listDisplayedColumns.add(dc);
}
}
/*
if (reloadInfo)
if (Mediator.getDelayManager() != null)
Mediator.getDelayManager().fireDelayObservation();
* Something ugly !! TODO find a means to display the
popupmenu with the
* right UI.
*/
boolean first = false;
// Thread t = new Thread(){
// public void run(){
calculateWidth();
/**
* @inheritDoc Shows the popupMenu to hide/show
columns and to add
revalidate();
*
// }
*/
// };
public void mouseClicked(MouseEvent e) {
// SwingUtilities.invokeLater(t);
custom columns.
if (!first) {
createPopupMenu();
}
first = true;
}
public void actionPerformed(ActionEvent e) {
// On windows e.isPopupTrigger doesn't work, strange...
if
(e.getButton()
==
MouseEvent.BUTTON3
Mediator.getGanttProjectSingleton().getUndoManager().undoab e.isPopupTrigger()) {
leEdit(
Component c = (Component) e.getSource();
"HIDE OR SHOW A COLUMN", new Runnable() {
reorderPopuMenu();
public void run() {
popupMenu.show(c, e.getX(), e.getY());
if (!isShown)
clickPoint
show();
e.getPoint();//popupMenu.getLocationOnScreen();
else
||
=
154
}
CustomColumn cc = null;
try {
cc
Mediator.getCustomColumnsStorage().getCustomColumn(
/**
=
* @inheritDoc
getTable().getColumnName(
*/
getTable().columnAtPoint(e.getPoint())));
public Object getCellEditorValue() {
} catch (CustomColumnsException e1) {
// TODO Auto-generated catch block
return new GanttCalendar(date == null ? new Date() :
date);
}
// e1.printStackTrace();
}
/**
if (cc != null)
jmiDeleteColumn.setEnabled(true);
else
* @inheritDoc If the date is not correct, the textfield's
background
*
jmiDeleteColumn.setEnabled(false);
goes red until the user enters a correct date.
*/
}
public boolean stopCellEditing() {
}
boolean res = true;
}
try {
date = DateUtils.parseDate(field.getText(), language
/**
.getLocale());
* CellEditor that uses DateUtils.parseDate to parse the given
date.
field.setBackground(colorNormal);
super.fireEditingStopped();
*
} catch (ParseException e) {
* @author bbaranne Mar 1, 2005
*/
Toolkit.getDefaultToolkit().beep();
class DateCellEditor extends DefaultCellEditor {
field.setBackground(colorError);
res = false;
// textfield used for editing.
JTextField field = null;
}
// normal textfield background color
return res;
}
private Color colorNormal = null;
}
// error textfield background color (when the date isn't
correct
private final Color colorError = new Color(255, 125, 125);
/**
* The class replaces the cell editor used in the hierarchical
column of
// the returned date
* the tree table.
private Date date = null;
*
* @author bbaranne (Benoit Baranne)
/**
*/
* Creates a new DateCellEditor.
class NameCellEditor extends DefaultCellEditor {
private JTextField field = null;
*
* @param field
*
JTextField used to edit the date.
public NameCellEditor() {
*/
super(new JTextField());
public DateCellEditor(JTextField field) {
field = (JTextField) this.editorComponent;
super(field);
}
this.field = field;
155
public void requestFocus() {
import java.util.Enumeration;
this.field.requestFocusInWindow();
import java.util.GregorianCalendar;
this.field.selectAll();
import java.util.List;
}
import java.util.Vector;
public boolean stopCellEditing() {
import javax.swing.Icon;
if (field.getText().trim().length() != 0)
super.stopCellEditing();
else {
import javax.swing.ImageIcon;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
Mediator.getGanttProjectSingleton().deleteTasks(false);
super.fireEditingCanceled();
import javax.swing.event.TableColumnModelListener;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
}
return super.stopCellEditing();
}
import net.sourceforge.ganttproject.delay.Delay;
import net.sourceforge.ganttproject.language.GanttLanguage;
// public void cancelCellEditing()
import
net.sourceforge.ganttproject.task.CustomColumnsException;
// {
import net.sourceforge.ganttproject.task.ResourceAssignment;
// super.cancelCellEditing();
import net.sourceforge.ganttproject.task.Task;
// }
import
net.sourceforge.ganttproject.task.TaskContainmentHierarchyFa
cade;
}
import net.sourceforge.ganttproject.task.TaskInfo;
/**
import net.sourceforge.ganttproject.task.TaskLength;
* This class repaints the GraphicArea and the table everyimport net.sourceforge.ganttproject.task.TaskLengthImpl;
time the table
import net.sourceforge.ganttproject.task.TaskNode;
* model has been modified. TODO Add the refresh
import
functionnality when
net.sourceforge.ganttproject.task.dependency.TaskDependenc
* available.
y;
*
* @author Benoit Baranne
import org.jdesktop.swing.treetable.DefaultTreeTableModel;
*/
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;
/**
* This class is the model for GanttTreeTable to display tasks.
*
* @author bbaranne (Benoit Baranne)
*/
public
class
GanttTreeTableModel
DefaultTreeTableModel implements
extends
TableColumnModelListener,
TaskContainmentHierarchyFacade {
private
static
GanttLanguage
GanttLanguage.getInstance();
language
=
public static String strColType = null;
public static String strColPriority = null;
156
*/
public static String strColInfo = null;
public GanttTreeTableModel(TreeNode root) {
super(root);
titles = new ArrayList();
public static String strColName = null;
customColumns = new Vector();
changeLanguage(language);
public static String strColBegDate = null;
}
public static String strColEndDate = null;
/**
public static String strColDuration = null;
* Changes the language.
*
//LH
* @param ganttLanguage
public static String strColBudget = null;
*
public static String strColCompletion = null;
public void changeLanguage(GanttLanguage ganttLanguage) {
New language to use.
*/
strColType = language.getText("tableColType");
strColPriority = language.getText("tableColPriority");
public static String strColCoordinator = null;
strColInfo = language.getText("tableColInfo");
strColName = language.getText("tableColName");
public static String strColPredecessors = null;
public static String strColID = null;
/** The colums titles */
public List titles = null;
strColBegDate
language.getText("tableColBegDate");
=
strColEndDate
language.getText("tableColEndDate");
=
strColDuration
language.getText("tableColDuration");
=
//LH
/**
//TODO put string in properties
* Custom columns list.
strColBudget = language.getText("budget");
*/
private Vector customColumns = null;
/**
* Number of columns (presently in the model)
strColCompletion
language.getText("tableColCompletion");
=
strColCoordinator
language.getText("tableColCoordinator");
=
strColPredecessors
language.getText("tableColPredecessors");
=
strColID = language.getText("tableColID");
*/
private int nbCol = 12;
titles.clear();
//LH : private int nbCol = 11;
//LH
String[] cols
strColPriority, strColInfo,
/**
* Number of columns (at all, even hiden)
*/
private int nbColTot = nbCol;
=
new
String[]
strColName,
strColEndDate, strColDuration,
{
strColType,
strColBegDate,
strColCompletion,
strColCoordinator, strColPredecessors,
strColID, strColBudget };
/**
for (int i = 0; i < cols.length; i++)
* Creates an instance of GanttTreeTableModel with a root.
*
titles.add(new String(cols[i]));
}
* @param root
*
The root.
/**
157
* Invoked this to insert newChild at location index in parents
children.
customColumns.add(title);
nbColTot++;
* 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.
/**
*/
* Delete a custom column.
public void insertNodeInto(MutableTreeNode newChild,
*
* @param title
MutableTreeNode parent, int index) {
*/
parent.insert(newChild, index);
public void deleteCustomColumn(String title) {
customColumns.remove(title);
int[] newIndexs = new int[1];
this.columnRemoved(null);
nbColTot--;
newIndexs[0] = index;
}
nodesWereInserted(parent, newIndexs);
}
public void renameCustomColumn(String oldName, String
newName) {
/**
customColumns.set(customColumns.indexOf(oldNam
* Message this to remove node from its parent. This wille), newName);
message
}
* nodesWereRemoved to create the appropriate event. This is
the preferred
* way to remove a node as it handles the event creation for// /**
you.
// * Returns the number of custom columns.
*/
// * @return
public void removeNodeFromParent(MutableTreeNode node) { // */
MutableTreeNode
node.getParent();
parent
=
(MutableTreeNode)// public int getCustomColumnCount()
// {
// return customColumns.size();
if (parent == null)
throw new IllegalArgumentException("node
does not have a parent.");
// }
public int getColumnCount() {
return nbCol;
int[] childIndex = new int[1];
Object[] removedArray = new Object[1];
}
childIndex[0] = parent.getIndex(node);
public int getColumnCountTotal() {
return nbColTot;
parent.remove(childIndex[0]);
removedArray[0] = node;
nodesWereRemoved(parent,
removedArray);
}
}
childIndex,
/**
* {@inheritDoc}
*/
/**
* Add a custom column to the model.
*
* @param title
*/
public void addCustomColumn(String title) {
public Class getColumnClass(int column) {
switch (column) {
case 0:
case 1:
case 2:
return Icon.class;
158
case 3:
* @inheritDoc
return hierarchicalColumnClass;
case 4:
*/
public boolean isCellEditable(Object node, int column) {
case 5:
if (node instanceof TaskNode)
return GregorianCalendar.class;
case 6:
return column != 8 && column != 9 &&
column != 10 && column !=2 && column !=11;
return false;
case 7:
return Integer.class;
}
case 8:
return String.class;
// public Object getChild(Object parent, int index)
// {
case 9:
return String.class;
//
// }
case 10:
return Integer.class;
//
// public int getChildCount(Object parent)
//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);
/**
=
* @inheritDoc
*/
public Object getValueAt(Object node, int column) {
Object res = null;
if (o == null) {
if (!(node instanceof TaskNode))
o = "erreur";
return null;
System.err.println("!!!!!!!!!!!!!!!!!");
}
TaskNode tn = (TaskNode) node;
return o.getClass();
Task t = (Task) tn.getUserObject();
// if(tn.getParent()!=null){
}
}
switch (column) {
}
case 0:
public String getColumnName(int column) {
if (column < titles.size())
return (String) titles.get(column);
if
tn.getUserObject()).isProjectTask()) {
res
ImageIcon(getClass().getResource(
(((Task)
=
new
"/icons/mproject.gif"));
try {
return (String) customColumns.get(column titles.size());
} catch (IndexOutOfBoundsException e) {
} else if (!tn.isLeaf())
res
=
ImageIcon(getClass().getResource("/icons/mtask.gif"));
return (String) customColumns.get(column -
new
else if (t.isMilestone())
titles.size() - 1);
res = new ImageIcon(getClass()
}
.getResource("/icons/meeting.gif"));
}
else
res
=
ImageIcon(getClass().getResource("/icons/tasks2.png"));
/**
new
break;
159
case 1:
int nb = 0;
Task task = (Task) tn.getUserObject();
for (int i = 0; i < tAssign.length; i++) {
String path = (task.getPriority() == 0 ?
"/icons/task1.gif" : task
tAssign[i];
ResourceAssignment resAss =
.getPriority() == 1 ?
if (resAss.isCoordinator())
"/icons/task.gif"
sb.append(nb++ == 0 ?
: "/icons/task2.gif");
res
=
ImageIcon(getClass().getResource(path));
"" : ", ").append(
new
resAss.getResource().getName());
break;
}
case 2: // info
// res = "Not implemented";
TaskInfo info = t.getTaskInfo();
res = sb.toString();
if (info != null) {
break;
if (info instanceof Delay) {
int
type
}
=
((Delay)
(type
==
case 9: {
info).getType();
String resStr = "";
if
Delay.NORMAL)
res
=
ImageIcon(getClass().getResource(
TaskDependency[]
t.getDependenciesAsDependant().toArray();
new
int i = 0;
dep
=
if (dep != null && dep.length > 0) {
"/icons/alert1_16.gif"));
for (i = 0; i < dep.length - 1; i++)
else
if
(type
Delay.CRITICAL)
res
=
ImageIcon(getClass().getResource(
==
resStr
dep[i].getDependee().getTaskID() + ", ";
new
resStr
dep[i].getDependee().getTaskID() + "";
+=
+=
}
"/icons/alert2_16.gif"));
res = resStr;
}
break;
}
}
break;
case 10:
case 3:
res = new Integer(t.getTaskID());
res = tn.getName();
break;
break;
//LH
case 4:
case 11:
res = tn.getStart();
res = new Double(t.getBudget());
break;
break;
case 5:
default:
res = tn.getEnd();
String
this.getColumnName(column);
break;
case 6:
colName
=
// System.out.println(" -> "+colName);
res = new Integer(tn.getDuration());
break;
//
"+t.getCustomValues());
System.out.println(t+"
res
t.getCustomValues().getValue(colName);
new
break;
case 7:
res
=
Integer(tn.getCompletionPercentage());
:
=
}
break;
// }
case 8: {
ResourceAssignment[]
tAssign
t.getAssignments();
=
// else
// res ="";
StringBuffer sb = new StringBuffer();
return res;
160
}
((TaskNode)
node).setName(value.toString());
break;
/**
case 4:
* @inheritDoc
((TaskNode)
node).setStart((GanttCalendar) value);
*/
public void setValueAt(final Object value, final Object node,
((TaskNode)
node).applyThirdDateConstraint();
final int column) {
break;
if (isCellEditable(node, column)) {
//
colonne: " + column);
case 5:
System.out.println("undoable
((TaskNode) node).setEnd((GanttCalendar)
value);
Mediator.getGanttProjectSingleton().getUndoManage
r().undoableEdit(
"Change
break;
case 6:
properties
column", new Runnable() {
public
TaskLength
node).getUserObject())
void
tl
run() {
=
((Task)
((TaskNode)
.getDuration();
tl.getTimeUnit();
setValue(value, node, column);
}
((TaskNode)
TaskLengthImpl(tl.getTimeUnit(),
});
node).setDuration(new
((Integer)
value).intValue()));
} else {
break;
//
System.out.println("NOT
undoable colonne: " + column);
setValue(value, node, column);
}
case 7:
((TaskNode)
node).setCompletionPercentage(((Integer) value)
.intValue());
// System.out.println("node : " + node);
break;
// System.out.println("valeur : " + value);
//LH
Mediator.getGanttProjectSingleton().repaint();
case 11:
Mediator.getGanttProjectSingleton().setAskForSave(t
rue);
((TaskNode)
value).doubleValue());
}
node).setBudget(((Double)
break;
default: // custom colums
/**
try {
* Set value in left pane cell
((Task)
node).getUserObject()).getCustomValues()
* @param value
((TaskNode)
* @param node
.setValue(this.getColumnName(column), value);
* @param column
} catch (CustomColumnsException e) {
*/
e.printStackTrace();
private void setValue(final Object value, final Object node,
}
final int column) {
}
switch (column) {
case 0:
}
case 1:
case 2: // info
((TaskNode)
value);
node).setTaskInfo((TaskInfo)/**
* @inheritDoc
case 8:
*/
break;
public void columnAdded(TableColumnModelEvent arg0) {
case 3:
161
nbCol++;
}
}
/**
/**
* @inheritDoc
* Purpose: Should return true if this Tasks has any nested
subtasks.
*/
public void columnRemoved(TableColumnModelEvent arg0) {
*/
public boolean hasNestedTasks(Task container) {
nbCol--;
TaskNode r = (TaskNode) root;
}
if (r.getChildCount() > 0) {
return true;
/**
} else {
* @inheritDoc
return false;
*/
}
public void columnMoved(TableColumnModelEvent arg0) {
// TODO Auto-generated method stub
}
/**
}
* @inheritDoc
*/
/**
public Task getRootTask() {
* @inheritDoc
return
(Task)
this.getRoot()).getUserObject();
*/
public void columnMarginChanged(ChangeEvent arg0) {
((TaskNode)
}
// TODO Auto-generated method stub
/**
}
* Returns the corresponding task node according to the given
task.
/**
*
* @inheritDoc
* @param task
*/
*
The task whom tasknode we want to get.
public void columnSelectionChanged(ListSelectionEvent arg0) { * @return The corresponding task node according to the given
task.
// TODO Auto-generated method stub
*/
}
public TaskNode getTaskNodeForTask(Task task) {
Enumeration
enumeration
getRoot()).preorderEnumeration();
/**
* @inheritDoc
=
((TaskNode)
while (enumeration.hasMoreElements()) {
*/
Object next = enumeration.nextElement();
public Task[] getNestedTasks(Task container) {
if (!(next instanceof TaskNode))
TaskNode r = (TaskNode) root;
continue;
Enumeration e = r.children();
TaskNode tn = (TaskNode) next;
Task t = (Task) tn.getUserObject();
Vector v = new Vector();
if (t.equals(task))
while (e.hasMoreElements())
return tn;
v.add((TaskNode) e.nextElement());
}
Task[] res = new Task[v.size()];
v.toArray(res);
return null;
}
return res;
162
/**
* @inheritDoc
import
net.sourceforge.ganttproject.task.CustomColumnsStorage;
import net.sourceforge.ganttproject.task.TaskManager;
*/
public Task getContainer(Task nestedTask) {
// TODO Auto-generated method stub
import
net.sourceforge.ganttproject.task.TaskSelectionManager;
import net.sourceforge.ganttproject.undo.GPUndoManager;
return null;
}
/**
/**
* This class allow the developer to get some useful references.
- GanttProject
* @inheritDoc
* reference; - CustomColumnManager
CustomColumnStorage reference.
*/
reference;
-
*
public void move(Task whatMove, Task whereMove) {
* @author bbaranne Mar 2, 2005
// TODO Auto-generated method stub
*/
public class Mediator {
}
/**
* The unique GanttProject instance.
/**
*/
* @inheritDoc
private static GanttProject ganttprojectSingleton = null;
*/
public boolean areUnrelated(Task dependant, Task dependee)
{
// TODO Auto-generated method stub
return false;
}
public int getDepth(Task task) {
// TODO Auto-generated method stub
/**
* The unique CustomColumnsManager instance.
*/
private
static
customColumnsManager = null;
CustomColumnsManager
private
static
customColumnsStorage = null;
CustomColumnsStorage
return 0;
}
}
net.sourceforge.ganttproject.
Mediator
private static TaskSelectionManager taskSelectionManager =
null;
private static RoleManager roleManager = null;
private static TaskManager taskManager = null;
package net.sourceforge.ganttproject;
private static GPUndoManager undoManager = null;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.ganttproject.delay.DelayManager;
import
net.sourceforge.ganttproject.gui.options.model.ChangeValueDi
spatcher;
private static DelayManager delayManager = null;
private static
PluginManager();
PluginManager
pluginManager
=
new
private static List changeValueDispatchers = new ArrayList();
import net.sourceforge.ganttproject.plugins.PluginManager;
import net.sourceforge.ganttproject.roles.RoleManager;
/**
import
net.sourceforge.ganttproject.task.CustomColumnsManager;
* Regsiters the unique GanttProject instance.
*
163
* @param gp
*
The unique GanttProject instance.
public
static
addChangeValueDispatcher(ChangeValueDispatcher
dispatcher){
*/
public static void registerGanttProject(GanttProject gp) {
void
changeValueDispatchers.add(dispatcher);
ganttprojectSingleton = gp;
}
}
/**
/**
* Returns the unique GanttProject instance.
* Regsiters the unique CustomColumnsManager instance.
*
*
* @return The unique GanttProject instance.
* @param managerThe
*/
*
public static GanttProject getGanttProjectSingleton() {
unique CustomColumnsManager instance.
*/
return ganttprojectSingleton;
public
static
void
registerCustomColumnsManager(CustomColumnsManager
manager) {
customColumnsManager = manager;
}
/**
}
* Returns the unique CustomColumnsStorage instance.
*
public
static
registerCustomColumnsStorage(CustomColumnsStorage
storage) {
void
customColumnsStorage = storage;
* @return The unique CustomColumnsStorage instance.
*/
public
static
getCustomColumnsStorage() {
}
CustomColumnsStorage
return customColumnsStorage;
}
public static void registerTaskSelectionManager(
TaskSelectionManager taskSelection) {
/**
taskSelectionManager = taskSelection;
* Returns the unique CustomColumnsManager instance.
}
*
* @return The unique CustomColumnsManager instance.
public
static
roleMgr) {
void
registerRoleManager(RoleManager
roleManager = roleMgr;
*/
public
static
getCustomColumnsManager() {
}
CustomColumnsManager
return customColumnsManager;
}
public
static
taskMgr) {
void
registerTaskManager(TaskManager
taskManager = taskMgr;
public
static
getTaskSelectionManager() {
}
TaskSelectionManager
return taskSelectionManager;
}
public static void registerUndoManager(GPUndoManager
undoMgr) {
undoManager = undoMgr;
public static RoleManager getRoleManager() {
return roleManager;
}
}
public static
delayMgr) {
void
registerDelayManager(DelayManager
public static TaskManager getTaskManager() {
delayManager = delayMgr;
}
return taskManager;
}
164
import java.util.Date;
public static GPUndoManager getUndoManager() {
return undoManager;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
}
import java.util.Iterator;
public static DelayManager getDelayManager() {
return delayManager;
import java.util.List;
import java.util.Map;
}
import javax.swing.AbstractAction;
public static PluginManager getPluginManager() {
return pluginManager;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.DefaultListModel;
}
import javax.swing.ImageIcon;
public static List getChangeValueDispatchers(){
return changeValueDispatchers;
}
}
net.sourceforge.ganttproject.
GanttProject
package net.sourceforge.ganttproject;
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 java.awt.BorderLayout;
import javax.swing.JOptionPane;
import java.awt.Color;
import javax.swing.JPanel;
import java.awt.Component;
import javax.swing.JPopupMenu;
import java.awt.ComponentOrientation;
import javax.swing.JSplitPane;
import java.awt.Container;
import javax.swing.JTabbedPane;
import java.awt.Dimension;
import javax.swing.JTable;
import java.awt.Toolkit;
import javax.swing.JToolBar;
import java.awt.event.ActionEvent;
import javax.swing.KeyStroke;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import java.awt.event.ComponentEvent;
import javax.swing.ToolTipManager;
import java.awt.event.ComponentListener;
import javax.swing.UIManager;
import java.awt.event.InputEvent;
import javax.swing.event.ChangeEvent;
import java.awt.event.KeyEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.KeyListener;
import javax.swing.event.TreeModelEvent;
import java.awt.event.MouseAdapter;
import javax.swing.event.TreeModelListener;
import java.awt.event.MouseEvent;
import javax.swing.filechooser.FileFilter;
import java.awt.event.MouseListener;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.event.WindowListener;
import javax.swing.tree.MutableTreeNode;
import java.io.File;
import javax.swing.tree.TreeModel;
import java.io.IOException;
import javax.swing.tree.TreePath;
import java.io.InputStream;
import java.net.URL;
import java.security.AccessControlException;
import java.util.ArrayList;
import
net.sourceforge.ganttproject.GanttGraphicArea.MouseSupport;
import
net.sourceforge.ganttproject.action.CalculateCriticalPathAction;
165
import net.sourceforge.ganttproject.action.CopyAction;
import net.sourceforge.ganttproject.action.CutAction;
import
net.sourceforge.ganttproject.action.DeleteAssignmentAction;
import
net.sourceforge.ganttproject.filter.GanttMSProjectLFileFilter;
import net.sourceforge.ganttproject.filter.GanttPDFFileFilter;
import net.sourceforge.ganttproject.filter.GanttPNGFileFilter;
import net.sourceforge.ganttproject.action.DeleteHumanAction; import net.sourceforge.ganttproject.filter.GanttXFIGFileFilter;
import net.sourceforge.ganttproject.action.GPAction;
import net.sourceforge.ganttproject.filter.GanttXMLFileFilter;
import net.sourceforge.ganttproject.action.ImportResources;
import net.sourceforge.ganttproject.gui.GanttDialogCalendar;
import net.sourceforge.ganttproject.action.NewArtefactAction;
import net.sourceforge.ganttproject.gui.GanttDialogInfo;
import net.sourceforge.ganttproject.action.NewHumanAction;
import net.sourceforge.ganttproject.gui.GanttDialogPerson;
import net.sourceforge.ganttproject.action.NewTaskAction;
import net.sourceforge.ganttproject.gui.GanttDialogProperties;
import net.sourceforge.ganttproject.action.PasteAction;
import net.sourceforge.ganttproject.gui.GanttLookAndFeelInfo;
import net.sourceforge.ganttproject.action.RedoAction;
import net.sourceforge.ganttproject.gui.GanttLookAndFeels;
import net.sourceforge.ganttproject.action.RefreshViewAction; import net.sourceforge.ganttproject.gui.GanttStatusBar;
import net.sourceforge.ganttproject.action.ResourceActionSet; import net.sourceforge.ganttproject.gui.GanttURLChooser;
import net.sourceforge.ganttproject.action.RolloverAction;
import
net.sourceforge.ganttproject.gui.TestGanttRolloverButton;
import
net.sourceforge.ganttproject.action.ScrollGanttChartLeftAction; import net.sourceforge.ganttproject.gui.TipsDialog;
import
import net.sourceforge.ganttproject.gui.UIConfiguration;
net.sourceforge.ganttproject.action.ScrollGanttChartRightAction
import net.sourceforge.ganttproject.gui.UIFacade;
;
import net.sourceforge.ganttproject.action.SwitchViewAction;
import net.sourceforge.ganttproject.gui.about.AboutDialog;
import net.sourceforge.ganttproject.action.UndoAction;
import net.sourceforge.ganttproject.gui.report.ReportDialog;
import net.sourceforge.ganttproject.action.ZoomInAction;
import net.sourceforge.ganttproject.gui.options.SettingsDialog;
import net.sourceforge.ganttproject.action.ZoomOutAction;
import
net.sourceforge.ganttproject.gui.previousState.GanttDialogCom
pareToPreviousState;
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.gui.previousState.GanttDialogSave
AsPreviousState;
import
net.sourceforge.ganttproject.gui.projectwizard.NewProjectWizar
d;
import
net.sourceforge.ganttproject.gui.scrolling.ScrollingManager;
import
net.sourceforge.ganttproject.document.AbstractURLDocument; import
net.sourceforge.ganttproject.gui.scrolling.ScrollingManagerImpl;
import net.sourceforge.ganttproject.document.Document;
import net.sourceforge.ganttproject.gui.zoom.ZoomManager;
import
import net.sourceforge.ganttproject.importer.ImportFileAction;
net.sourceforge.ganttproject.document.DocumentCreator;
import
net.sourceforge.ganttproject.document.DocumentManager;
import
net.sourceforge.ganttproject.importer.ImportFileWizardImpl;
import net.sourceforge.ganttproject.document.DocumentsMRU; import net.sourceforge.ganttproject.io.GPSaver;
import net.sourceforge.ganttproject.document.FileDocument;
import net.sourceforge.ganttproject.io.GanttXMLOpen;
import net.sourceforge.ganttproject.document.HttpDocument;
import net.sourceforge.ganttproject.io.GanttXMLSaver;
import net.sourceforge.ganttproject.language.GanttLanguage;
import
net.sourceforge.ganttproject.document.OpenDocumentAction; import
net.sourceforge.ganttproject.parser.AllocationTagHandler;
import net.sourceforge.ganttproject.export.ExportFileAction;
import
net.sourceforge.ganttproject.export.ExportFileWizardImpl;
import
net.sourceforge.ganttproject.parser.BlankLineTagHandler;
import net.sourceforge.ganttproject.filter.GanttCSVFilter;
import
net.sourceforge.ganttproject.parser.CustomPropertiesTagHandl
er;
import net.sourceforge.ganttproject.filter.GanttHTMLFileFilter;
import net.sourceforge.ganttproject.filter.GanttJPGFileFilter;
import
net.sourceforge.ganttproject.parser.DefaultWeekTagHandler;
166
import
net.sourceforge.ganttproject.parser.DependencyTagHandler;
import net.sourceforge.ganttproject.parser.CostTagHandler;
import
net.sourceforge.ganttproject.task.dependency.TaskDependenc
yException;
import
net.sourceforge.ganttproject.task.dependency.constraint.Finish
import net.sourceforge.ganttproject.parser.HolidayTagHandler; StartConstraintImpl;
import net.sourceforge.ganttproject.parser.GPParser;
import net.sourceforge.ganttproject.parser.ParserFactory;
import net.sourceforge.ganttproject.time.TimeUnitStack;
import
import
net.sourceforge.ganttproject.parser.PreviousStateTasksTagHan net.sourceforge.ganttproject.time.gregorian.GPTimeUnitStack;
dler;
import net.sourceforge.ganttproject.undo.GPUndoManager;
import
net.sourceforge.ganttproject.parser.ResourceTagHandler;
import net.sourceforge.ganttproject.parser.RoleTagHandler;
import net.sourceforge.ganttproject.undo.UndoManagerImpl;
import net.sourceforge.ganttproject.util.BrowserControl;
import
net.sourceforge.ganttproject.parser.TaskDisplayColumnsTagHa /**
ndler;
* Main frame of the project
import
net.sourceforge.ganttproject.parser.TaskPropertiesTagHandler; */
import net.sourceforge.ganttproject.parser.TaskTagHandler;
import net.sourceforge.ganttproject.parser.VacationTagHandler;
public class GanttProject extends GanttProjectBase implements
ActionListener,
IGanttProject, ResourceView, KeyListener, UIFacade {
import net.sourceforge.ganttproject.parser.ViewTagHandler;
import net.sourceforge.ganttproject.print.PrintManager;
import net.sourceforge.ganttproject.print.PrintPreview;
/** The current version of ganttproject */
public static final String version = "2.0-pre1";
import
net.sourceforge.ganttproject.resource.AssignmentContext;
import net.sourceforge.ganttproject.resource.HumanResource; /* List of calendar for the project */
private ArrayList listOfCalendar = new ArrayList();
import
net.sourceforge.ganttproject.resource.HumanResourceManage
r;
import net.sourceforge.ganttproject.resource.ProjectResource;
import net.sourceforge.ganttproject.resource.ResourceContext;
/** Command line creation or gui creation */
public static boolean byCommandLine = false;
import net.sourceforge.ganttproject.resource.ResourceEvent;
import
net.sourceforge.ganttproject.resource.ResourceManager;
import net.sourceforge.ganttproject.resource.ResourceView;
/** The language use */
private
GanttLanguage
GanttLanguage.getInstance();
language
=
import net.sourceforge.ganttproject.roles.RoleManager;
import net.sourceforge.ganttproject.task.BlankLineNode;
import
net.sourceforge.ganttproject.task.CustomColumnsStorage;
import net.sourceforge.ganttproject.task.Task;
/** The JTree part. */
private GanttTree2 tree;
/** GanttGraphicArea for the calendar with Gantt */
private GanttGraphicArea area;
import
net.sourceforge.ganttproject.task.TaskContainmentHierarchyFa
cade;
/** GanttPeoplePanel to edit person that work on the project */
import net.sourceforge.ganttproject.task.TaskManager;
import net.sourceforge.ganttproject.task.TaskManagerConfig;
private GanttResourcePanel resp;
import net.sourceforge.ganttproject.task.TaskNode;
import
net.sourceforge.ganttproject.task.TaskSelectionManager;
//LH
/** The differents menus */
import
public JMenu mProject, mMRU, mEdit, mTask, mHuman,
net.sourceforge.ganttproject.task.algorithm.AdjustTaskBoundsA mHelp, mServer, mReport,
lgorithm;
mCalendar;
import
net.sourceforge.ganttproject.task.algorithm.RecalculateTaskCo
mpletionPercentageAlgorithm;
// public JMenu mView;
167
public PrjInfos prjInfos = new PrjInfos();
//LH
/** The differetns menuitem */
/** Boolean to know if the file has been modify */
public JMenuItem miNew, miOpen, miOpenURL, miSave,public boolean askForSave = false;
miSaveAs, miSaveAsURL,
miPublishToWeb, /* miOpenDB,miSaveAsDB, */
/** The info for the look'n'feel */
miPrint, miPreview, miQuit, miCut, miCopy, miPaste,
public GanttLookAndFeelInfo lookAndFeel;
miOptions,
miDeleteTask, miPropertiesTask, miUp, miDown,
miDelHuman,
/** Is the application only for viewer. */
miPropHuman, miSendMailHuman, miEditCalendar,public boolean isOnlyViewer;
miPrjCal, miWebPage,
miTips, miReport, miAbout, miManual, miRefresh,
/** The list of all managers installed in this project */
miChartOptions;
private Hashtable managerHash = new Hashtable();
public JMenuItem miUndo, miRedo;
private ResourceActionSet myResourceActions;
private static final int maxSizeMRU = 5;
private boolean isApplet;
private
DocumentsMRU
documentsMRU
DocumentsMRU(maxSizeMRU);
=
new
/** Frame for the help Viewer */
private JFrame helpFrame = null;
/** The differents button of toolbar */
private TestGanttRolloverButton bExit, bNew, bOpen, bSave,
private final TaskManager myTaskManager;
bSaveAs,
bPaste,
bExport, bImport, bPrint, bPreviewPrint, bCopy, bCut,
private FacadeInvalidator myFacadeInvalidator;
bNewTask, bDelete, bProperties, bUnlink, bLink,
bInd, bUnind, bUp,
private UIConfiguration myUIConfiguration;
bDown, bPrev, bScrollCenter, bNext, bZoomFit,
bAbout;
private TestGanttRolloverButton bShowHiddens;
private static
implements
class
TaskContainmentHierarchyFacadeImpl
TaskContainmentHierarchyFacade {
private JPopupMenu menu = new JPopupMenu();;
TestGanttRolloverButton bZoomIn, bZoomOut;
private TestGanttRolloverButton bUndo, bRedo;
private TestGanttRolloverButton bCritical;
private Map myTask2treeNode = new HashMap();
private Task myRootTask;
private List myPathBuffer = new ArrayList();
private GanttTree2 myTree;
public TaskContainmentHierarchyFacadeImpl(GanttTree2 tree)
private TestGanttRolloverButton bSaveCurrent, bComparePrev; {
ArrayList allTasks = ((GanttTree2) tree).getAllTasks();
private TestGanttRolloverButton bRefresh;
// comboBox.addItem("no set");
// for (int i = 0; i < allTasks.size(); i++) {
/** The project filename */
public Document projectDocument = null;
//
DefaultMutableTreeNode
(DefaultMutableTreeNode)
treeNode
=
// allTasks.get(i);
/** Informations for the current project. */
for (Iterator it = allTasks.iterator(); it.hasNext();) {
168
}
TaskNode treeNode = (TaskNode) it.next();
Task
treeNode.getUserObject();
task
=
}
(Task)
return false;
if (treeNode.isRoot()) {
}
myRootTask = task;
}
public Task getRootTask() {
myTask2treeNode.put(task, treeNode);
return myRootTask;
}
}
myTree = tree;
}
public Task getContainer(Task nestedTask) {
DefaultMutableTreeNode
treeNode
(DefaultMutableTreeNode) myTask2treeNode
public Task[] getNestedTasks(Task container) {
=
.get(nestedTask);
Task[] result = null;
DefaultMutableTreeNode
treeNode
(DefaultMutableTreeNode) myTask2treeNode
if (treeNode == null) {
=
return null;
.get(container);
}
if (treeNode != null) {
DefaultMutableTreeNode
(DefaultMutableTreeNode) treeNode
ArrayList list = new ArrayList();
for
(Enumeration
treeNode.children(); children
children
containerNode
=
.getParent();
=
return containerNode == null ? null : (Task)
.hasMoreElements();) { containerNode
DefaultMutableTreeNode next =
(DefaultMutableTreeNode) children
.getUserObject();
}
.nextElement();
if (next instanceof TaskNode)
public boolean areUnrelated(Task first, Task second) {
myPathBuffer.clear();
list.add(next.getUserObject());
}
for (Task container = getContainer(first); container !=
null; container = getContainer(container)) {
myPathBuffer.add(container);
result = (Task[]) list.toArray(new Task[0]);
}
}
return result == null ? new Task[0] : result;
if (myPathBuffer.contains(second)) {
return false;
}
}
myPathBuffer.clear();
/**
for (Task container = getContainer(second); container
* Purpose: Returns true if the container Task has any nested
!= null; container = getContainer(container)) {
tasks.
myPathBuffer.add(container);
* This should be a quicker check than using getNestedTasks().
*
}
* @param container
if (myPathBuffer.contains(first)) {
*
return false;
The Task on which to check for children.
}
*/
return true;
public boolean hasNestedTasks(Task container) {
DefaultMutableTreeNode
treeNode
(DefaultMutableTreeNode) myTask2treeNode
.get(container);
if (treeNode != null) {
{
=}
public void move(Task whatMove, Task whereMove) {
DefaultMutableTreeNode
targetNode
if (treeNode.children().hasMoreElements())(DefaultMutableTreeNode) myTask2treeNode
.get(whereMove);
=
return true;
169
DefaultMutableTreeNode
movedNode
(DefaultMutableTreeNode) myTask2treeNode
=
treeModel.addTreeModelListener(this);
}
.get(whatMove);
if (movedNode != null) {
TreePath
movedPath
TreePath(movedNode.getPath());
=
boolean isValid() {
new
return isValid;
=}
boolean
wasSelected
(myTree.getJTree().getSelectionModel()
void reset() {
.isPathSelected(movedPath));
isValid = true;
if (wasSelected) {
}
myTree.getJTree().getSelectionModel().removeSelect
ionPath(
public void treeNodesChanged(TreeModelEvent e) {
movedPath);
}
isValid = false;
}
myTree.getModel().removeNodeFromParent(movedN
ode);
public void treeNodesInserted(TreeModelEvent e) {
isValid = false;
myTree.getModel().insertNodeInto(movedNode,
targetNode,
}
targetNode.getChildCount());
public void treeNodesRemoved(TreeModelEvent e) {
if (wasSelected) {
movedPath
TreePath(movedNode.getPath());
Path(
isValid = false;
=
new
}
myTree.getJTree().getSelectionModel().addSelection public void treeStructureChanged(TreeModelEvent e) {
movedPath);
}
isValid = false;
}
}
} else {
private final GanttOptions options;
myTree.addObjectWithExpand(whatMove,
targetNode);
private JMenuBar bar;
}
}
// ! Toolbar of ui
private JToolBar toolBar;
public int getDepth(Task task) {
DefaultMutableTreeNode
treeNode
(DefaultMutableTreeNode) myTask2treeNode
=
private DefaultListModel iconList = new DefaultListModel();
.get(task);
return treeNode.getLevel();
private JList list = new JList(iconList);
}
}
private
DefaultListModel
DefaultListModel();
private
static
class
TreeModelListener {
FacadeInvalidator
deletedIconList
=
new
implements
private JList deletedList = new JList(deletedIconList);
private boolean isValid;
// list.setName("list");
public FacadeInvalidator(TreeModel treeModel) {
isValid = false;
170
// ! a status bar on the main frame
if (!myFacadeInvalidator.isValid() || myCachedFacade == null) {
private GanttStatusBar statusBar;
myCachedFacade
=
TaskContainmentHierarchyFacadeImpl(tree);
new
myFacadeInvalidator.reset();
private NewTaskAction myNewTaskAction;
}
private NewHumanAction myNewHumanAction;
return myCachedFacade;
}
private NewArtefactAction myNewArtefactAction;
/** Constructor */
private CopyAction myCopyAction;
public GanttProject(boolean isOnlyViewer, String filename,
boolean isApplet) {
ToolTipManager.sharedInstance().setInitialDelay(200);
private PasteAction myPasteAction;
ToolTipManager.sharedInstance().setDismissDelay(60000);
private CutAction myCutAction;
Mediator.registerRoleManager(getRoleManager());
private RefreshViewAction myRefreshAction;
CustomColumnsStorage customColumnsStorage
CustomColumnsStorage();
private DeleteHumanAction myDeleteHumanAction;
Mediator.registerCustomColumnsStorage(customColumnsStora
ge);
private DeleteAssignmentAction myDeleteAssignmentAction;
private
myCachedFacade;
TaskSelectionManager
taskSelectionManager
TaskSelectionManager();
=
=
new
new
TaskContainmentHierarchyFacadeImplMediator.registerTaskSelectionManager(taskSelectionManager)
;
private List myRolloverActions = new ArrayList();
this.isOnlyViewer = isOnlyViewer;
if (!isOnlyViewer)
private ArrayList myPreviousStates = new ArrayList();
setTitle(language.getText("appliTitle"));
else
private MouseListener myStopEditingMouseListener = null;
setTitle("GanttViewer");
setFocusable(true);
private DelayManager myDelayManager;
lookAndFeel
=
GanttLookAndFeels.getGanttLookAndFeels().getDefaultInfo();
options = new GanttOptions(getRoleManager(), isOnlyViewer);
// private boolean bQuickSave;//to know if gantt has to
quicksave the
// Color color = GanttGraphicArea.taskDefaultColor;
// project
options.setUIConfiguration(myUIConfiguration);
// private int currentQuickSave;
options.setDocumentsMRU(documentsMRU);
// private ArrayList aQuick;//List of all the quicksaves
options.setLookAndFeel(lookAndFeel);
// private int lastQuickSave;
if (options.load()) {
// private int firstQuickSave;
language = options.getLanguage();
// private int undoNumber;
GanttGraphicArea.taskDefaultColor
options.getDefaultColor();
=
private JSplitPane mySplitPane;
lookAndFeel = options.getLnfInfos();
private Chart[] myCharts = null;
public
getTaskContainment() {
HttpDocument.setLockDAVMinutes(options.getLockD
AVMinutes());
}
TaskContainmentHierarchyFacade
myUIConfiguration = options.getUIConfiguration();
171
class TaskManagerConfigImpl implements TaskManagerConfigGanttImagePanel
{
"tasks.png", 300,
public Color getDefaultColor() {
but
=
new
GanttImagePanel("big.png",
42);
return myUIConfiguration.getTaskColor();
tree.setGraphicArea(area);
}
//
public GPCalendar getCalendar() {
miChartOptions
=
JMenuItem(area.getOptionsDialogAction());
return
GanttProject.this.getActiveCalendar();
}
new
getZoomManager().addZoomListener(area.getZoomListener());
public TimeUnitStack getTimeUnitStack() {
return GanttProject.this.getTimeUnitStack();
myCopyAction = new CopyAction((GanttTree2) getTree(),
options
.getIconSize());
}
myPasteAction = new PasteAction((GanttTree2) getTree(),
options
public ResourceManager getResourceManager() {
return
GanttProject.this.getHumanResourceManager();
.getIconSize());
myCutAction = new CutAction((GanttTree2) getTree(), options
.getIconSize());
}
myRefreshAction = new RefreshViewAction(getUIFacade(),
options);
}
TaskManagerConfig
TaskManagerConfigImpl();
taskConfig
=
myTimeUnitStack = new GPTimeUnitStack(getLanguage());
myTaskManager = TaskManager.Access.newInstance(
new
TaskContainmentHierarchyFacade.Factory() {
public
TaskContainmentHierarchyFacade createFacede() {
newmyRolloverActions.add(myCopyAction);
myRolloverActions.add(myPasteAction);
myRolloverActions.add(myCutAction);
myRolloverActions.add(myRefreshAction);
tree.setActions();
// Create the menus
return
GanttProject.this.getTaskContainment();
bar = new JMenuBar();
}
if (!isOnlyViewer)
}, taskConfig);
setJMenuBar(bar);
Mediator.registerTaskManager(myTaskManager);
this.isApplet = isApplet;
// Allocation of the menus
myZoomManager = new ZoomManager(this);
mProject = new JMenu();
ImageIcon icon = new ImageIcon(getClass().getResource(
mMRU = new JMenu();
"/icons/ganttproject.png"));
mMRU.setIcon(new ImageIcon(getClass().getResource(
"/icons/recent_16.gif")));
setIconImage(icon.getImage());
mEdit = new JMenu();
// mView = new JMenu ();
// Create each objects
tree = new GanttTree2(this, myTaskManager, getUIFacade()); mTask = new JMenu();
myFacadeInvalidator
=
newmHuman = new JMenu();
FacadeInvalidator(tree.getJTree().getModel());
mHelp = new JMenu();
area = new GanttGraphicArea(this, tree, getTaskManager(),
//LH
getZoomManager(),
myUIConfiguration);
getUndoManager(),mReport = new JMenu();
area.getMyChartModel().addOptionChangeListener(
new
area.getMyChartModel()));
mCalendar = new JMenu();
mServer = new JMenu();
RowHeightAligner(tree,
mServer.setIcon(new ImageIcon(getClass().getResource(
172
getHumanResourceManager(),
"/icons/server_16.gif")));
(AssignmentContext) getResourcePanel(),
miUndo = new JMenuItem(new UndoAction(getUndoManager(),
this);
"16"));
mEdit.add(miUndo);
mHuman.add(myNewHumanAction);
// miUndo.setEnabled(false);
=
miRedo = new JMenuItem(new RedoAction(getUndoManager(),myDeleteHumanAction
DeleteHumanAction(getHumanResourceManager(),
"16"));
(ResourceContext)
mEdit.add(miRedo);
new
getResourcePanel(),
this);
// miRedo.setEnabled(false);
miDelHuman = new JMenuItem(myDeleteHumanAction);
mEdit.addSeparator();
mHuman.add(miDelHuman);
miPropHuman = createNewItem("/icons/properties_16.gif");
createProjectMenu();
mHuman.add(miPropHuman);
miSendMailHuman
createNewItem("/icons/send_mail_16.gif");
miRefresh = new JMenuItem(myRefreshAction);
=
//
mHuman.add(miSendMailHuman);
miRefresh.setAccelerator((KeyStroke)myRefreshAction.getValu
e(Action.ACCELERATOR_KEY));
mHuman.add(new
ImportResources(getHumanResourceManager(),
mEdit.add(miRefresh);
mEdit.addSeparator();
getTaskManager(),
getRoleManager(),
this));
miCut = new JMenuItem(myCutAction);
mEdit.add(miCut);
//LH
miCopy = new JMenuItem(myCopyAction);
miReport = createNewItem("/icons/help_16.gif");
mEdit.add(miCopy);
mReport.add(miReport);
miPaste = new JMenuItem(myPasteAction);
mEdit.add(miPaste);
miEditCalendar = createNewItem("/icons/clock_16.gif");
mEdit.addSeparator();
mCalendar.add(miEditCalendar);
miOptions = createNewItem("/icons/settings_16.gif");
miPrjCal = createNewItem("/icons/default_calendar_16.gif");
mEdit.add(miOptions);
mCalendar.add(miPrjCal);
myNewTaskAction = new NewTaskAction((IGanttProject) this); miWebPage = createNewItem("/icons/home_16.gif");
mTask.add(myNewTaskAction);
mHelp.add(miWebPage);
miDeleteTask = createNewItem("/icons/delete_16.gif");
miManual = createNewItem("/icons/help_16.gif");
mTask.add(miDeleteTask);
try { // See if helpgui library is on the classpath
miPropertiesTask = createNewItem("/icons/properties_16.gif");
Class.forName("net.sourceforge.helpgui.HelpGui");
mTask.add(miPropertiesTask);
mHelp.add(miManual);
//
miManual.setAccelerator(KeyStroke.getKeyStroke("F
1"));
//
myNewHumanAction
=
NewHumanAction(getHumanResourceManager(),
new} catch (Exception ex) {
getRoleManager(), this, this) {
public void actionPerformed(ActionEvent event) {
super.actionPerformed(event);
getTabs().setSelectedIndex(UIFacade.RESOURCES
// 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);
_INDEX);
}
};
myDeleteAssignmentAction = new DeleteAssignmentAction(
if (!isApplet) {
bar.add(mProject); // for a applet veiwer, Project
menu is not
// neccessary By CL
173
}
getTabs().addTab(language.getText("gantt"),
bar.add(mEdit);
new
ImageIcon(getClass().getResource("/icons/tasks_16.gif")),
JMenu viewMenu = createViewMenu();
mySplitPane, area);
if (viewMenu != null)
getTabs().addTab(language.getText("human"),
bar.add(viewMenu);
new
ImageIcon(getClass().getResource("/icons/res_16.gif")),
// bar.add (mView);
bar.add(mTask);
bar.add(mHuman);
getResourcePanel(),
getResourcePanel().area);
// bar.add(mCalendar);
// pert area
//LH
getTabs().setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_L
AYOUT);
bar.add(mReport);
getTabs().addChangeListener(new ChangeListener() {
bar.add(mHelp);
public void stateChanged(ChangeEvent e) {
setMemonic();
bUnlink
// to create a default project
// createDefaultTree(tree);
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
JPanel left = new JPanel(new BorderLayout());
bLink
left.add(but, BorderLayout.NORTH);
left.add(tree, BorderLayout.CENTER);
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
left.setPreferredSize(new Dimension(315, 600));
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
// A splitpane is use
if
(language.getComponentOrientation()
ComponentOrientation.LEFT_TO_RIGHT) {
==
bInd
left.setBackground(Color.white);
mySplitPane
=
JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
==
new
==
bUnind
==
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
==
mySplitPane.setLeftComponent(left);
mySplitPane.setRightComponent(area);
bCut
mySplitPane
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
.applyComponentOrientation(ComponentOrientation.
LEFT_TO_RIGHT);
==
bCopy
} else {
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
mySplitPane.setRightComponent(left);
mySplitPane.setLeftComponent(area);
mySplitPane.setDividerLocation((int)
(Toolkit.getDefaultToolkit()
.getScreenSize().getWidth()
==
bPaste
.setEnabled(getTabs().getSelectedIndex()
-UIFacade.GANTT_INDEX);
left.getPreferredSize()
==
bCritical
.getWidth()));
mySplitPane
.applyComponentOrientation(ComponentOrientation.
RIGHT_TO_LEFT);
}
mySplitPane.setOneTouchExpandable(true);
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
==
bScrollCenter
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
==
bComparePrev
mySplitPane.setPreferredSize(new Dimension(800, 500));
// Add Gantt Panel, Human resource pannel and RESOURCE
panel
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
==
174
bPrev
bSaveCurrent
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX);
==
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX
==
||
getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX);
bNewTask
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX
bNext
==
||
getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX);
==
==
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX
==
||
getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX);
==
bDelete
if
(getTabs().getSelectedIndex()
==UIFacade.GANTT_INDEX) { // Gantt
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX
// Chart
||
getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX);
==
==
bNewTask.setToolTipText(getToolTip(correctLabel(la
nguage
bProperties
.getText("createTask"))));
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX
==
bDelete.setToolTipText(getToolTip(correctLabel(lang
uage
||
getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX);
==
.getText("deleteTask"))));
bProperties.setToolTipText(getToolTip(correctLabel(l
anguage
bDown
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX
.getText("propertiesTask"))));
==
||
getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX);
==GanttOptions.ICONS) {
bUp
if
(options.getButtonShow()
!=
bNewTask.setText(correctLabel(language
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX
==
.getText("createTask")));
||
getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX);
bDelete.setText(correctLabel(language
==
.getText("deleteTask")));
bZoomIn
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX
bProperties.setText(correctLabel(language
==
.getText("propertiesTask")));
||
getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX);
==
}
} else if (getTabs().getSelectedIndex() ==
UIFacade.RESOURCES_INDEX) { // Resources
bZoomOut
// Chart
.setEnabled(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX
==
bNewTask.setToolTipText(getToolTip(correctLabel(la
||
getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX);
nguage
==
175
}
.getText("newHuman"))));
bDelete.setToolTipText(getToolTip(correctLabel(lang
uage
public void componentHidden(ComponentEvent arg0)
{
}
.getText("deleteHuman"))));
});
bProperties.setToolTipText(getToolTip(correctLabel(l
this.addButtons(toolBar);
getContentPane()
anguage
.add(
.getText("propertiesHuman"))));
if
(options.getButtonShow()
GanttOptions.ICONS) {
toolBar,
(toolBar.getOrientation() == JToolBar.HORIZONTAL)
!=
? BorderLayout.NORTH
:
bNewTask.setText(correctLabel(language
.getText("newHuman")));
BorderLayout.WEST);
// add the status bar
bDelete.setText(correctLabel(language
statusBar = new GanttStatusBar();
if (!isOnlyViewer)
.getText("deleteHuman")));
getContentPane().add(statusBar,
BorderLayout.SOUTH);
bProperties.setText(correctLabel(language
statusBar.setVisible(options.getShowStatusBar());
.getText("propertiesHuman")));
// add a keyboard listener
}
addKeyListener(this);
}
}
SwitchViewAction switchAction = new SwitchViewAction(this);
});
JMenuItem invisibleItem = new JMenuItem(switchAction);
// Add tabpan on the content pane
getContentPane().add(getTabs(), BorderLayout.CENTER);
invisibleItem.setVisible(false);
bar.add(invisibleItem);
// Add toolbar
toolBar
=
new
options.getToolBarPosition());
JToolBar("GanttProject",
// Open the the project passed in argument
toolBar.setBorderPainted(true);
if (filename != null) {
toolBar.setRollover(true);
Document
document
DocumentCreator.createDocument(filename);
toolBar.setFloatable(true);
=
try {
toolBar.addComponentListener(new ComponentListener() {
openDocument(document);
public
void
componentResized(ComponentEvent
} catch (IOException ex) {
arg0) {
setHiddens();
System.err.println(language.getText("msg2") + "\n" +
filename);
refresh();
System.err.println(ex.getMessage());
}
}
}
{
public void componentMoved(ComponentEvent arg0)// update 18-03-2003
}
addWindowListener(new java.awt.event.WindowAdapter() {
public
windowClosing(java.awt.event.WindowEvent evt) {
public void componentShown(ComponentEvent arg0)
void
exitForm(evt);
{
}
176
});
myTaskManager.addTaskListener(myDelayManager);
// update 18-03-2003
}
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
=private
cont) {
Dimension
screenSize
Toolkit.getDefaultToolkit().getScreenSize();
void
addMouseListenerToAllContainer(Component[]
for (int i = 0; i < cont.length; i++) {
Dimension windowSize = getPreferredSize();
cont[i].addMouseListener(getStopEditingMouseListen
// Put the frame at the middle of the screen
setLocation(screenSize.width / 2 - (windowSize.width / 2),
er());
screenSize.height / 2 - (windowSize.height /
if (cont[i] instanceof Container)
2));
addMouseListenerToAllContainer(((Container) cont[i])
this.pack();
.getComponents());
changeLanguage();
}
}
/*
* [bbaranne] I add a Mediator object so that we can get the
/**
GanttProject
* singleton whereever we are in the source code. Perhaps* Returns a mouseListener that stop the edition in the
ganttTreeTable.
some of you
* don't like this, but I believe that it is practical...
*
*/
* @return A mouseListener that stop the edition in the
ganttTreeTable.
Mediator.registerGanttProject(this);
*/
private MouseListener getStopEditingMouseListener() {
// changeUndoNumber ();
if (myStopEditingMouseListener == null)
changeLookAndFeel(lookAndFeel);
changeLookAndFeel(lookAndFeel); // Twice call for update font{
on menu
myStopEditingMouseListener = new MouseAdapter()
public void mouseClicked(MouseEvent e) {
if (options.isLoaded()) {
setBounds(options.getX(),
options.getWidth(),
options.getY(),e.getClickCount() == 1)
if (e.getSource() != bNewTask &&
tree.stopEditing();
options.getHeight());
if
}
(e.getButton()
if (options.getOpenTips() && !byCommandLine) {
TipsDialog
tips
options.getOpenTips());
=
new
&&
TipsDialog(this,!(e.getSource() instanceof JTable)
tips.show();
is the top
==
MouseEvent.BUTTON1
&&
!(e.getSource() instanceof AbstractButton)) {
Task taskUnderPointer
tips.toFront(); // somehow assure, that the TipsDialog
= area.new MouseSupport()
// window an MacOS
.findTaskUnderMousePointer(e.getX(), e.getY());
}
if (taskUnderPointer ==
applyComponentOrientation(GanttLanguage.getInstance()
null) {
.getComponentOrientation());
tree.selectTreeRow(-1);
myTaskManager.addTaskListener(new
TaskModelModificationListener(this));
}
if (ourWindowListener != null) {
}
addWindowListener(ourWindowListener);
}
}
addMouseListenerToAllContainer(this.getComponents());
};
return myStopEditingMouseListener;
myDelayManager = new DelayManager(myTaskManager, tree); }
Mediator.registerDelayManager(myDelayManager);
myDelayManager.addObserver(tree);
177
private void createProjectMenu() {
result.add(miChartOptions);
miNew = createNewItem("/icons/new_16.gif");
Chart[] charts = Mediator.getPluginManager().getCharts();
mProject.add(miNew);
if (charts.length > 0)
miOpen = createNewItem("/icons/open_16.gif");
result.addSeparator();
mProject.add(miOpen);
mProject.add(mMRU);
updateMenuMRU();
for (int i = 0; i < charts.length; i++) {
mProject.addSeparator();
result.add(new
ToggleChartAction(charts[i],
miSave = createNewItem("/icons/save_16.gif");
JCheckBoxMenuItem(new
getViewManager())));
miSave.setEnabled(false);
}
mProject.add(miSave);
return result;
miSaveAs = createNewItem("/icons/saveas_16.gif");
}
mProject.add(miSaveAs);
mProject.addSeparator();
public GanttProject(boolean isOnlyViewer, String filename) {
//
ImportFileAction
importFile
ImportFileAction(getUIFacade(), this);
=
this(isOnlyViewer, filename, false);
new
}
=
new/**
mProject.add(importFile);
ExportFileAction
exportFile
ExportFileAction(getUIFacade(), this,
* Updates the last open file menu items.
options);
*/
mProject.add(exportFile);
private void updateMenuMRU() {
// miExport = createNewItem("/icons/export_16.gif");
mMRU.removeAll();
// mProject.add(miExport);
int index = 0;
mProject.addSeparator();
Iterator iterator = documentsMRU.iterator();
while (iterator.hasNext()) {
miOpenURL = createNewItem("");
index++;
miSaveAsURL = createNewItem("");
Document document = (Document) iterator.next();
miPublishToWeb = createNewItem("/icons/publish.gif");
mServer.add(miOpenURL);
JMenuItem
mi
OpenDocumentAction(index,
=
new
JMenuItem(new
document, this));
mServer.add(miSaveAsURL);
mMRU.add(mi);
mServer.addSeparator();
mServer.add(miPublishToWeb);
}
mProject.add(mServer);
}
mProject.addSeparator();
miPrint = createNewItem("/icons/print_16.gif");
public String getXslDir() {
mProject.add(miPrint);
return options.getXslDir();
miPreview = createNewItem("/icons/preview_16.gif");
}
mProject.add(miPreview);
mProject.addSeparator();
/** @return the options of ganttproject. */
miQuit = createNewItem(""/* "/icons/exit_16.gif" */);
public GanttOptions getOptions() {
mProject.add(miQuit);
return options;
}
}
private JMenu createViewMenu() {
JMenu
result
=
changeMenuLabel(new
language.getText("view"));
public void restoreOptions() {
JMenu(),options.initByDefault(); // options by default
iconList = initIconList();
178
deletedIconList = initDeletedIconList();
addButtons();
miQuit.setAccelerator(KeyStroke.getKeyStroke(KeyE
vent.VK_Q,
MENU_MASK));
myUIConfiguration = options.getUIConfiguration();
GanttGraphicArea.taskDefaultColor = new Color(140, 182,
206);
area.repaint();
// //--CUT---------------------------------//
miCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
// MENU_MASK));
}
// //--COPY---------------------------------/** @return the status Bar of the main frame. */
public GanttStatusBar getStatusBar() {
//
miCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_
C,
return statusBar;
// MENU_MASK));
}
// //--PASTE----------------------------------
public String getXslFo() {
//
miPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_
V,
return options.getXslFo();
// MENU_MASK));
}
// --OPTIONS----------------------------------
/** Create memonic for keyboard */
miOptions.setAccelerator(KeyStroke.getKeyStroke(K
eyEvent.VK_G,
MENU_MASK));
public void setMemonic() {
// --NEW TASK----------------------------------
int MENU_MASK = GPAction.MENU_MASK;
// --NEW----------------------------------
//
miNewTask.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.
VK_T,
// miNew.setMnemonic(KeyEvent.VK_N);
// MENU_MASK));
miNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_
N, MENU_MASK));
// --PROPERTIES TASK----------------------------------
// --OPEN----------------------------------
miPropertiesTask.setAccelerator(KeyStroke.getKeySt
roke(
KeyEvent.VK_R, MENU_MASK));
miOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_
O, MENU_MASK));
// --DELETE TASK----------------------------------
// Open from the web
miDeleteTask.setAccelerator(KeyStroke.getKeyStrok
e(KeyEvent.VK_D,
//
miOpenURL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.
MENU_MASK));
VK_I,
// --NEW HUMAN---------------------------------// MENU_MASK));
//
// --SAVE---------------------------------miNewHuman.setAccelerator(KeyStroke.getKeyStroke(KeyEve
miSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ nt.VK_H,
S, MENU_MASK));
// MENU_MASK));
// --PRINT---------------------------------miPrint
//
miDelHuman.setAccelerator(KeyStroke.getKeyStroke(KeyEvent
.VK_J,
.setAccelerator(KeyStroke
.getKeyStroke(KeyEvent.VK_P, MENU_MASK));
// MENU_MASK));
miPropHuman.setAccelerator(KeyStroke.getKeyStrok
e(KeyEvent.VK_L,
MENU_MASK));
// --UNDO----------------------------------
}
miUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_
Z, MENU_MASK));
// --REDO----------------------------------
}
miRedo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_
Y, MENU_MASK));
/** Create an item with a label */
if (!isOnlyViewer) {
public JMenuItem createNewItemText(String label) {
// --QUIT----------------------------------
179
iconList.removeElementAt(i);
JMenuItem item = new JMenuItem(label);
iconList.add(i,
language.getText("separator").toUpperCase());
item.addActionListener(this);
return item;
}
}
}
/** Create an item with an icon */
/** Change the style of the application */
public JMenuItem createNewItem(String icon) {
public
void
changeLookAndFeel(GanttLookAndFeelInfo
lookAndFeel) {
JMenuItem item = url == null ? new JMenuItem() : newtry {
JMenuItem(
UIManager.setLookAndFeel(lookAndFeel.getClassNa
new ImageIcon(url));
me());
item.addActionListener(this);
SwingUtilities.updateComponentTreeUI(this);
URL url = getClass().getResource(icon);
return item;
this.lookAndFeel = lookAndFeel;
}
} catch (Exception e) {
GanttLookAndFeelInfo info = GanttLookAndFeels
/** Create an item with a label and an icon */
.getGanttLookAndFeels().getDefaultInfo();
public JMenuItem createNewItem(String label, String icon) {
JMenuItem
item
ImageIcon(getClass()
=
new
JMenuItem(label,
new
System.out.println("Can't find the LookAndFeel\n"
+ lookAndFeel.getClassName() +
"\n" + lookAndFeel.getName()
.getResource(icon)));
+
Look'n'Feel" + info.getName());
item.addActionListener(this);
return item;
"\nSetting
the
default
try {
}
UIManager.setLookAndFeel(info.getClassName());
/** Function to change language of the project */
SwingUtilities.updateComponentTreeUI(this);
public void changeLanguage() {
this.lookAndFeel = info;
} catch (Exception ex) {
if (helpFrame != null)
}
helpFrame.dispose();
}
helpFrame = null;
//
MetalLookAndFeel.setCurrentTheme(new
GanttMetalTheme());
applyComponentOrientation(language.getComponentOrientatio // must force to do that instead of the task on tree are not in
n());
// continuity of the calendar
changeLanguageOfMenu();
if (tree.getTable().getRowHeight() <= 22)
area.repaint();
tree.getTable().setRowHeight(20);
getResourcePanel().area.repaint();
}
getResourcePanel().refresh(language);
// Correct the label of menu without '$' character
this.tree.changeLanguage(language);
public static String correctLabel(String label) {
CustomColumnsStorage.changeLanguage(language);
int index = label.indexOf('$');
applyComponentOrientation(language.getComponentOrientatio
n());
// change the value of the separators in iconList
for (int i = 0; i < iconList.size(); i++)
if
(iconList.getElementAt(i).getClass()
TestGanttRolloverButton.class) {
if (index != -1 && label.length() - index > 1)
label
=
index).concat(label.substring(++index));
label.substring(0,
return label;
}
!=
180
menu.setMnemonic(Character.toLowerCase(label.ch
/** Change the label for menu, in fact check in the label
arAt(index)));
contains a mnemonic */
public JMenu changeMenuLabel(JMenu menu, String label) {
} else {
int index = label.indexOf('$');
menu.setText(label);
if (index != -1 && label.length() - index > 1) {
// menu.setMnemonic('');
menu.setText(label.substring(0, index).concat(
label.substring(++index)));
}
return menu;
menu.setMnemonic(Character.toLowerCase(label.ch }
arAt(index)));
} else {
menu.setText(label);
/** Set the menus language after the user select a different
language */
// menu.setMnemonic('');
private void changeLanguageOfMenu() {
mProject
=
language.getText("project"));
}
return menu;
changeMenuLabel(mProject,
mEdit = changeMenuLabel(mEdit, language.getText("edit"));
}
//
mView
=
language.getText("view"));
changeMenuLabel(mView,
/**
mTask = changeMenuLabel(mTask, language.getText("task"));
* Change the label for menuItem, in fact check in the labelmHuman
=
changeMenuLabel(mHuman,
contains a
language.getText("human"));
* mnemonic
mHelp = changeMenuLabel(mHelp, language.getText("help"));
*/
//LH
public JMenuItem changeMenuLabel(JMenuItem menu, StringmReport
=
label) {
language.getText("report"));
int index = label.indexOf('$');
mCalendar
=
if (index != -1 && label.length() - index > 1) {
menu.setText(label.substring(0, index).concat(
changeMenuLabel(mReport,
changeMenuLabel(mCalendar,
language.getText("calendars"));
miNew
=
language.getText("newProject"));
changeMenuLabel(miNew,
label.substring(++index)));
miOpen
=
changeMenuLabel(miOpen,
menu.setMnemonic(Character.toLowerCase(label.ch language.getText("openProject"));
arAt(index)));
mMRU
=
changeMenuLabel(mMRU,
} else {
language.getText("lastOpen"));
menu.setText(label);
// menu.setMnemonic('');
miSave
=
language.getText("saveProject"));
changeMenuLabel(miSave,
miSaveAs
=
changeMenuLabel(miSaveAs,
language.getText("saveAsProject"));
}
return menu;
}
mServer
=
language.getText("webServer"));
/**
miOpenURL = changeMenuLabel(miOpenURL, language
changeMenuLabel(mServer,
.getText("openFromServer"));
* Change the label for JCheckBoxmenuItem, in fact check in the
label
miSaveAsURL = changeMenuLabel(miSaveAsURL, language
* contains a mnemonic
.getText("saveToServer"));
*/
miPublishToWeb
public
JCheckBoxMenuItemlanguage
changeMenuLabel(JCheckBoxMenuItem menu,
=
changeMenuLabel(miPublishToWeb,
.getText("publishToWeb"));
String label) {
int index = label.indexOf('$');
if (index != -1 && label.length() - index > 1) {
menu.setText(label.substring(0, index).concat(
label.substring(++index)));
miPrint
=
language.getText("printProject"));
miPreview
=
language.getText("preview"));
changeMenuLabel(miPrint,
changeMenuLabel(miPreview,
miQuit = changeMenuLabel(miQuit, language.getText("quit"));
181
miUndo
=
language.getText("undo"));
changeMenuLabel(miUndo,// //////////////////////////////////////////
miRedo
=
language.getText("redo"));
changeMenuLabel(miRedo,
bExit
miCut = changeMenuLabel(miCut, language.getText("cut"));
.setToolTipText(getToolTip(correctLabel(language
miCopy
=
language.getText("copy"));
changeMenuLabel(miCopy,
miPaste
=
language.getText("paste"));
changeMenuLabel(miPaste,bNew.setToolTipText(getToolTip(correctLabel(language
.getText("newProject"))));
miOptions
=
language.getText("settings"));
changeMenuLabel(miOptions,bOpen.setToolTipText(getToolTip(correctLabel(language
.getText("openProject"))));
// miNewTask = changeMenuLabel(miNewTask,
bSave.setToolTipText(getToolTip(correctLabel(language
// language.getText("createTask"));
.getText("saveProject"))));
miDeleteTask = changeMenuLabel(miDeleteTask, language
.getText("deleteTask"));
miPropertiesTask
language
=
bSaveAs.setToolTipText(getToolTip(correctLabel(language
.getText("saveAsProject"))));
changeMenuLabel(miPropertiesTask,
bPrint.setToolTipText(getToolTip(correctLabel(language
.getText("printProject"))));
.getText("propertiesTask"));
mHuman.insert(changeMenuLabel(mHuman.getItem(0),
language
.getText("newHuman")), 0);
bPreviewPrint.setToolTipText(getToolTip(correctLabel(languag
e
.getText("preview"))));
bExport.setToolTipText(getToolTip(correctLabel(language
.getText("export"))));
miDelHuman = changeMenuLabel(miDelHuman, language
.getText("deleteHuman"));
bImport.setToolTipText(getToolTip(correctLabel(language
.getText("import"))));
miPropHuman = changeMenuLabel(miPropHuman, language
.getText("propertiesHuman"));
mHuman.insert(changeMenuLabel(mHuman.getItem(4),
language
.getText("importResources")), 4);
miSendMailHuman
language
=
.getText("quit"))));
bNewTask.setToolTipText(getToolTip(correctLabel(language
.getText("createTask"))));
bCut.setToolTipText(getToolTip(correctLabel(language.getText(
"cut"))));
changeMenuLabel(miSendMailHuman,bCopy
.setToolTipText(getToolTip(correctLabel(language
.getText("sendMail"));
.getText("copy"))));
miEditCalendar = changeMenuLabel(miEditCalendar, language bPaste
.getText("editCalendars"));
.setToolTipText(getToolTip(correctLabel(language
miPrjCal = changeMenuLabel(miPrjCal, language
.getText("paste"))));
.getText("projectCalendar"));
bDelete.setToolTipText(getToolTip(correctLabel(language
.getText("deleteTask"))));
miWebPage
=
changeMenuLabel(miWebPage,
bProperties.setToolTipText(getToolTip(correctLabel(language
language.getText("webPage"));
miReport
=
language.getText("report"));
miAbout
=
language.getText("about"));
changeMenuLabel(miReport,
.getText("propertiesTask"))));
bUnlink.setToolTipText(getToolTip(correctLabel(language
changeMenuLabel(miAbout,
.getText("unlink"))));
miTips
=
changeMenuLabel(miTips,bLink
language.getText("tipsOfTheDay"));
miManual
=
language.getText("manual"));
changeMenuLabel(miManual,
.setToolTipText(getToolTip(correctLabel(language
.getText("link"))));
miChartOptions = changeMenuLabel(miChartOptions, language bInd.setToolTipText(getToolTip(correctLabel(language
.getText("chartOptions"));
miRefresh
=
language.getText("refresh"));
.getText("indentTask"))));
changeMenuLabel(miRefresh,bUnind.setToolTipText(getToolTip(correctLabel(language
182
.getText("dedentTask"))));
bUp
/** Invoked when a key has been pressed. */
public void keyPressed(KeyEvent e) {
.setToolTipText(getToolTip(correctLabel(language
final int MENU_MASK = Toolkit.getDefaultToolkit()
.getText("upTask"))));
.getMenuShortcutKeyMask();
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
// System.out.println(e.getKeyCode());
/*
* Consume the event to prevent it to go farther.
*/
int code = e.getKeyCode();
int modifiers = e.getModifiersEx();
.getText("forwardDate"))));
bZoomIn.setToolTipText(getToolTip(correctLabel(language
if (code == KeyEvent.KEY_LOCATION_UNKNOWN)
.getText("zoomIn"))));
e.consume();
bZoomOut.setToolTipText(getToolTip(correctLabel(language
.getText("zoomOut"))));
bAbout
switch (code) {
case KeyEvent.VK_DELETE:
e.consume();
.setToolTipText(getToolTip(correctLabel(language
if (!isOnlyViewer) {
.getText("about"))));
if
UIFacade.GANTT_INDEX)
bUndo
==
deleteTasks(true);
.setToolTipText(getToolTip(correctLabel(language
.getText("undo"))));
(getViewIndex()
else
if
UIFacade.RESOURCES_INDEX) {
bRedo
(getViewIndex()
==
deleteResources();
deleteAssignements();
.setToolTipText(getToolTip(correctLabel(language
}
.getText("redo"))));
}
// bZoomFit.setToolTipText(getToolTip(language.zoomFit()));
break;
bCritical.setToolTipText(getToolTip(language.getText("criticalP // case KeyEvent.VK_INSERT :
ath")));
// // if(!isOnlyViewer);newTask();break;
bComparePrev
.setToolTipText(getToolTip(language.getText("compa
rePrev")));
case KeyEvent.VK_ENTER:
if (!isOnlyViewer) {
e.consume();
bSaveCurrent
if
.setToolTipText(getToolTip(language.getText("saveC InputEvent.ALT_DOWN_MASK)
InputEvent.ALT_DOWN_MASK) {
urrent")));
((modifiers
&
==
if (getTabs().getSelectedIndex()
bRefresh.setToolTipText(getToolTip(language.getText("refresh"
== UIFacade.GANTT_INDEX) {// Gantt
)));
// Chart
bShowHiddens
propertiesTask();
.setToolTipText(getToolTip(language.getText("showH
iddens")));
getTabs().setTitleAt(1,
correctLabel(language.getText("human")));
}
else
(getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX) { // Resource
if
==
// chart
setButtonText();
getResourcePanel().propertiesHuman(GanttProject.th
}
is);
183
}
}
}
public static String getToolTip(String msg) {
return "<html><body
"</body></html>";
bgcolor=#EAEAEA>"
+
msg
+
}
break;
case KeyEvent.VK_TAB: {
e.consume();
/** Set the text on the buttons. */
public void setButtonText() {
if ((modifiers & InputEvent.SHIFT_DOWN_MASK) ==
if (options.getButtonShow() == GanttOptions.ICONS) {
InputEvent.SHIFT_DOWN_MASK) {
bExit.setText("");
tree.dedentCurrentNodes();
bNew.setText("");
} else
bOpen.setText("");
tree.indentCurrentNodes();
bSave.setText("");
break;
}
bCut.setText("");
case KeyEvent.VK_F5: {
bCopy.setText("");
e.consume();
bPaste.setText("");
repaint2();
bSaveAs.setText("");
break;
bNewTask.setText("");
bImport.setText("");
}
bExport.setText("");
// case KeyEvent.VK_F7:
bPrint.setText("");
// {
bPreviewPrint.setText("");
// if((modifiers & InputEvent.CTRL_DOWN_MASK) ==
bDelete.setText("");
// InputEvent.CTRL_DOWN_MASK)
bProperties.setText("");
// {
bUnlink.setText("");
// tabpane.setSelectedIndex((tabpane.getSelectedIndex()+1)%
bLink.setText("");
// tabpane.getTabCount());
bInd.setText("");
// }
bUnind.setText("");
// break;
bUp.setText("");
// }
bDown.setText("");
// case KeyEvent.VK_HOME : tree.selectTreeRow(0); break;
//go at the
bPrev.setText("");
// first task
bNext.setText("");
bScrollCenter.setText("");
// case KeyEvent.VK_END : tree.selectTreeRow(tree.nbTasks1); break;
bZoomOut.setText("");
// //go at the last task
bZoomIn.setText("");
}
bAbout.setText("");
}
bUndo.setText("");
bRedo.setText("");
/** Invoked when a key has been released. */
bCritical.setText("");
public void keyReleased(KeyEvent e) {
bComparePrev.setText("");
}
bSaveCurrent.setText("");
bRefresh.setText("");
bShowHiddens.setText("");
/** Invoked when a key has been typed. */
public void keyTyped(KeyEvent e) {
} else {
bExit.setText(correctLabel(language.getText("quit")));
}
bNew.setText(correctLabel(language.getText("newPr
oject")));
/** Return the tooltip in html (with yello bgcolor */
184
bOpen.setText(correctLabel(language.getText("open
bNext.setText(correctLabel(language.getText("forwar
Project")));
dDate")));
bSave.setText(correctLabel(language.getText("saveP
roject")));
bZoomOut.setText(correctLabel(language.getText("z
oomOut")));
bSaveAs.setText(correctLabel(language.getText("sav
eAsProject")));
mIn")));
bImport.setText(correctLabel(language.getText("impo
rt")));
bZoomIn.setText(correctLabel(language.getText("zoo
bAbout.setText(correctLabel(language.getText("about
")));
bExport.setText(correctLabel(language.getText("expo
rt")));
bUndo.setText(correctLabel(language.getText("undo"
)));
bPrint.setText(correctLabel(language.getText("printPr
oject")));
bRedo.setText(correctLabel(language.getText("redo")
));
bPreviewPrint.setText(correctLabel(language.getText
("preview")));
bCritical.setText(language.getText("criticalPath"));
bComparePrev.setText(correctLabel(language.getTex
bCut.setText(correctLabel(language.getText("cut"))); t("comparePrev")));
bCopy.setText(correctLabel(language.getText("copy")
));
bSaveCurrent.setText(correctLabel(language.getText
("saveCurrent")));
bPaste.setText(correctLabel(language.getText("paste
")));
bRefresh.setText(correctLabel(language.getText("refr
esh")));
// bShowHiddens.setText
bNewTask.setText(correctLabel(language.getText(get
Tabs()
.getSelectedIndex()
UIFacade.GANTT_INDEX ? "createTask"
// (correctLabel(language.getText("showHiddens")));
}
==
}
: "newHuman")));
bs()
bDelete.setText(correctLabel(language.getText(getTa /** Apply Buttons options. */
public void applyButtonOptions() {
.getSelectedIndex()
UIFacade.GANTT_INDEX ? "deleteTask"
==setButtonText();
if (options.getButtonShow() == GanttOptions.TEXT) {
: "deleteHuman")));
// remove the icons
bProperties
bExit.setDefaultIcon(null);
.setText(correctLabel(language
bNew.setDefaultIcon(null);
.getText(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX ? "propertiesTask"
==
: "propertiesHuman")));
bOpen.setDefaultIcon(null);
bSave.setDefaultIcon(null);
bSaveAs.setDefaultIcon(null);
bImport.setDefaultIcon(null);
bUnlink.setText(correctLabel(language.getText("unlin
k")));
bExport.setDefaultIcon(null);
bPrint.setDefaultIcon(null);
bLink.setText(correctLabel(language.getText("link")));
bPreviewPrint.setDefaultIcon(null);
bInd.setText(correctLabel(language.getText("indentT
bNewTask.setDefaultIcon(null);
ask")));
bUnind.setText(correctLabel(language.getText("dede
ntTask")));
bUp.setText(correctLabel(language.getText("upTask"
)));
bDelete.setDefaultIcon(null);
bCut.setDefaultIcon(null);
bCopy.setDefaultIcon(null);
bPaste.setDefaultIcon(null);
bDown.setText(correctLabel(language.getText("down
Task")));
bPrev.setText(correctLabel(language.getText("backD
ate")));
bProperties.setDefaultIcon(null);
bUnlink.setDefaultIcon(null);
bLink.setDefaultIcon(null);
bScrollCenter.setText(correctLabel(language
.getText("centerOnSelectedTasks")));
bInd.setDefaultIcon(null);
bUnind.setDefaultIcon(null);
bUp.setDefaultIcon(null);
bDown.setDefaultIcon(null);
185
bPreviewPrint.setDefaultIcon(new
ImageIcon(getClass().getResource(
bPrint.setDefaultIcon(null);
bPrev.setDefaultIcon(null);
"/icons/preview_"
options.getIconSize() + ".gif")));
bScrollCenter.setDefaultIcon(null);
bZoomOut.setDefaultIcon(null);
+
bNewTask.setDefaultIcon(new
ImageIcon(getClass().getResource(
bZoomIn.setDefaultIcon(null);
"/icons/insert_"
options.getIconSize() + ".gif")));
bAbout.setDefaultIcon(null);
bUndo.setDefaultIcon(null);
+
bDelete.setDefaultIcon(new
ImageIcon(getClass().getResource(
bRedo.setDefaultIcon(null);
bCritical.setDefaultIcon(null);
"/icons/delete_"
options.getIconSize() + ".gif")));
bComparePrev.setDefaultIcon(null);
+
bProperties.setDefaultIcon(new
ImageIcon(getClass().getResource(
bSaveCurrent.setDefaultIcon(null);
bRefresh.setDefaultIcon(null);
"/icons/properties_"
options.getIconSize() + ".gif")));
// bShowHiddens.setDefaultIcon(null);
bCut.setDefaultIcon(new
ImageIcon(getClass().getResource(
(RolloverAction)
"/icons/cut_"
options.getIconSize() + ".gif")));
+
for (int i = 0; i < myRolloverActions.size(); i++) {
RolloverAction
myRolloverActions.get(i);
next
=
next.isIconVisible(false);
bCopy.setDefaultIcon(new
ImageIcon(getClass().getResource(
next.setIconSize(options.getIconSize());
}
"/icons/copy_"
options.getIconSize() + ".gif")));
} else {
"/icons/exit_"
options.getIconSize() + ".gif")));
"/icons/paste_"
options.getIconSize() + ".gif")));
+
bUnlink.setDefaultIcon(new
"/icons/unlink_"
options.getIconSize() + ".gif")));
+
bOpen.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/link_"
options.getIconSize() + ".gif")));
+
bSave.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/indent_"
options.getIconSize() + ".gif")));
+
bUnind.setDefaultIcon(new
bSaveAs.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/saveas_"
options.getIconSize() + ".gif")));
bImport.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/import_"
options.getIconSize() + ".gif")));
+
bInd.setDefaultIcon(new
ImageIcon(getClass().getResource(
+
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(
bExport.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/down_"
options.getIconSize() + ".gif")));
"/icons/export_"
options.getIconSize() + ".gif")));
+
bPrint.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/prev_"
options.getIconSize() + ".gif")));
+
"/icons/print_"
options.getIconSize() + ".gif")));
+
bLink.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/open_"
options.getIconSize() + ".gif")));
"/icons/save_"
options.getIconSize() + ".gif")));
+
ImageIcon(getClass().getResource(
bNew.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/new_"
options.getIconSize() + ".gif")));
+
bPaste.setDefaultIcon(new
ImageIcon(getClass().getResource(
// set the approrpiate icons
bExit.setDefaultIcon(new
ImageIcon(getClass().getResource(
+
+
bPrev.setDefaultIcon(new
ImageIcon(getClass().getResource(
+
186
bNext.setDefaultIcon(new
ImageIcon(getClass().getResource(
next.setIconSize(options.getIconSize());
"/icons/next_"
options.getIconSize() + ".gif")));
+
}
}
bScrollCenter.setDefaultIcon(new
ImageIcon(getClass().getResource(
}
"/icons/scrollcenter_"
options.getIconSize() + ".gif")));
+
/** Create the button on toolbar */
bZoomOut.setDefaultIcon(new
ImageIcon(getClass().getResource(
public void addButtons(JToolBar toolBar) {
+// toolBar.addSeparator(new Dimension(20,0));
"/icons/zoomm_"
options.getIconSize() + ".gif")));
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
bZoomIn.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/zoomp_"
options.getIconSize() + ".gif")));
+
bExit
=
new
ImageIcon(getClass()
bAbout.setDefaultIcon(new
ImageIcon(getClass().getResource(
TestGanttRolloverButton(new
.getResource("/icons/exit_"
+options.getIconSize() + ".gif")));
"/icons/manual_"
options.getIconSize() + ".gif")));
+
bExit.addActionListener(new ActionListener() {
if (!myUIConfiguration.isCriticalPathOn())
public void actionPerformed(ActionEvent e) {
bCritical.setDefaultIcon(new
ImageIcon(getClass().getResource(
quitApplication();
}
"/icons/criticalPathOff_"
+ options.getIconSize()
});
+
".gif")));
// if(isOnlyViewer)
// {
else
// toolBar.add(bExit);
bCritical.setDefaultIcon(new
ImageIcon(getClass().getResource(
// toolBar.addSeparator(new Dimension(20,0));
"/icons/criticalPathOn_" // }
+ options.getIconSize()
".gif")));
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
bComparePrev.setDefaultIcon(new
ImageIcon(getClass().getResource(
bNew
=
new
ImageIcon(getClass()
+
"/icons/comparePrev_"
options.getIconSize() + ".gif")));
TestGanttRolloverButton(new
.getResource("/icons/new_"
+
options.getIconSize() + ".gif")));
+
bNew.addActionListener(this);
bSaveCurrent.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/saveCurrentAsPrev_"
options.getIconSize()
+ ".gif")));
// if(!isOnlyViewer) toolBar.add(bNew);
+
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
bOpen
=
new
ImageIcon(getClass()
bRefresh.setDefaultIcon(new
ImageIcon(getClass().getResource(
TestGanttRolloverButton(new
.getResource("/icons/open_"
+
options.getIconSize() + ".gif")));
"/icons/"
myRefreshAction.getIconFilePrefix()
+
options.getIconSize() + ".gif")));
+
bOpen.addActionListener(this);
// toolBar.add(bOpen);
bShowHiddens.setDefaultIcon(new
ImageIcon(getClass().getResource(
"/icons/showHiddens.gif")));
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
bSave
=
new
TestGanttRolloverButton(new
ImageIcon(getClass()
(RolloverAction)
.getResource("/icons/save_"
+
options.getIconSize() + ".gif")));
for (int i = 0; i < myRolloverActions.size(); i++) {
RolloverAction
myRolloverActions.get(i);
next
next.isIconVisible(true);
=
187
"/icons/comparePrev_"
bSave.setEnabled(false);
+ options.getIconSize() + ".gif")));
bSave.addActionListener(this);
bComparePrev.setEnabled(false);
// toolBar.add(bSave);
bComparePrev.addActionListener(new ActionListener() {
//
public void actionPerformed(ActionEvent e) {
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
compareToPreviousState();
bSaveAs = new TestGanttRolloverButton(
if (myPreviousStates.size() == 0)
new ImageIcon(getClass().getResource(
bComparePrev.setEnabled(false);
"/icons/saveas_"
+
}
options.getIconSize() + ".gif")));
});
bSaveAs.addActionListener(this);
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
bSaveCurrent
=
new
TestGanttRolloverButton(new
///
ImageIcon(getClass()
bImport = new TestGanttRolloverButton(
.getResource(
new ImageIcon(getClass().getResource(
// toolBar.add(bSaveAs);
"/icons/import_"
+
"/icons/saveCurrentAsPrev_" + options.getIconSize()
options.getIconSize() + ".gif")));
+
bImport.addActionListener(this);
".gif")));
// toolBar.add(bImport);
bSaveCurrent.setEnabled(false);
bSaveCurrent.addActionListener(new ActionListener() {
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent e) {
///
saveAsPreviousState();
bExport = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/export_"
}
+
options.getIconSize() + ".gif")));
});
bExport.addActionListener(this);
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
// toolBar.add(bExport);
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
bCut = new TestGanttRolloverButton(new ImageIcon(getClass()
bPrint
=
new
ImageIcon(getClass()
TestGanttRolloverButton(new
.getResource("/icons/cut_"
options.getIconSize() + ".gif")));
.getResource("/icons/print_"
options.getIconSize() + ".gif")));
+
+bCut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bPrint.addActionListener(this);
tree.cutSelectedNode();
bPreviewPrint = new TestGanttRolloverButton(new ImageIcon(
setAskForSave(true);
getClass().getResource(
"/icons/preview_"
}
+
options.getIconSize() + ".gif")));
});
bPreviewPrint.addActionListener(this);
// if(!isOnlyViewer)toolBar.add(bCut);
// toolBar.add(bPrint);
bCopy
=
new
ImageIcon(getClass()
TestGanttRolloverButton(new
//
.getResource("/icons/copy_"
//////////////////////////////////////////////////////////////////////////////////////////////////////
options.getIconSize() + ".gif")));
///
// toolBar.addSeparator(new Dimension(20,0));
bCopy.addActionListener(new ActionListener() {
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
public void actionPerformed(ActionEvent e) {
bComparePrev = new TestGanttRolloverButton(
}
new ImageIcon(getClass().getResource(
+
tree.copySelectedNode();
});
188
// toolBar.addSeparator(new Dimension(20,0));
// if(!isOnlyViewer)toolBar.add(bCopy);
bPaste
=
new
ImageIcon(getClass()
TestGanttRolloverButton(new}
.getResource("/icons/paste_"
options.getIconSize() + ".gif")));
bPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tree.pasteNode();
setAskForSave(true);
}
});
+
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
// bNewTask = new TestGanttRolloverButton(new
//
ImageIcon(getClass().getResource("/icons/insert_"+options.getI
conSize()+".gif")));
myNewArtefactAction = new NewArtefactAction(
new
NewArtefactAction.ActiveActionProvider() {
// bCut = new TestGanttRolloverButton(new
public
AbstractAction
getActiveAction() {
//
return
ImageIcon(getClass().getResource("/icons/cut_"+options.getIco
getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX ?
nSize()+".gif")));
(AbstractAction) myNewTaskAction
// bCut.addActionListener(new ActionListener() {
:
// public void actionPerformed(ActionEvent e) {
(AbstractAction) myNewHumanAction;
// tree.cutSelectedNode();
// setAskForSave(true);
}
// }
}, options.getIconSize());
// });
// bCut = new TestGanttRolloverButton(myCutAction);
// if(!isOnlyViewer)toolBar.add(bCut);
// bCopy = new TestGanttRolloverButton(new
bNewTask
=
TestGanttRolloverButton(myNewArtefactAction);
new
myRolloverActions.add(myNewArtefactAction);
// bNewTask.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
//
ImageIcon(getClass().getResource("/icons/copy_"+options.getI // if (tabpane.getSelectedIndex() == 0) {//Gantt Chart
conSize()+".gif")));
// newTask();
// bCopy.addActionListener(new ActionListener() {
// } else if (tabpane.getSelectedIndex() == 1) { //Resource chart
// public void actionPerformed(ActionEvent e) {
// HumanResource people = new HumanResource();
// tree.copySelectedNode();
// GanttDialogPerson dp = new GanttDialogPerson(
// }
// GanttProject.this, getLanguage(), people);
// });
// dp.show();
// bCopy = new TestGanttRolloverButton(myCopyAction);
// if (dp.result()) {
// if(!isOnlyViewer)toolBar.add(bCopy);
// getHumanResourceManager().add(people);
// bPaste = new TestGanttRolloverButton(new
// setAskForSave(true);
//
ImageIcon(getClass().getResource("/icons/paste_"+options.getI // }
conSize()+".gif")));
// }
// bPaste.addActionListener(new ActionListener() {
// }
// public void actionPerformed(ActionEvent e) {
// });
// tree.pasteNode();
// if(!isOnlyViewer) toolBar.add(bNewTask);
// setAskForSave(true);
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
// }
// });
bDelete = new TestGanttRolloverButton(
// /bPaste = new TestGanttRolloverButton(myPasteAction);
new ImageIcon(getClass().getResource(
// if(!isOnlyViewer)
{
"/icons/delete_"
+
options.getIconSize() + ".gif")));
// toolBar.add(bPaste);
bDelete.addActionListener(new ActionListener() {
189
public void actionPerformed(ActionEvent e) {
"/icons/properties_"
if
(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX) {// Gantt
==
+
options.getIconSize() + ".gif")));
bProperties.addActionListener(new ActionListener() {
// Chart
public void actionPerformed(ActionEvent e) {
// deleteTask();
if
(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX) {// Gantt
deleteTasks(true);
==
// Chart
} else if (getTabs().getSelectedIndex() ==
UIFacade.RESOURCES_INDEX) { // Resource
propertiesTask();
// chart
} else if (getTabs().getSelectedIndex() ==
UIFacade.RESOURCES_INDEX) { // Resource
final ProjectResource[] context =
// chart
getResourcePanel()
.getContext().getResources();
getResourcePanel().propertiesHuman(GanttProject.th
is);
if (context.length > 0) {
}
GanttDialogInfo gdi =
new GanttDialogInfo(
}
});
GanttProject.this, GanttDialogInfo.QUESTION,
// if(!isOnlyViewer) toolBar.add(bProperties);
GanttDialogInfo.YES_NO_OPTION, getLanguage()
.getText("msg6")
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
bUnlink = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
+ getDisplayName(context) + "??",
"/icons/unlink_"
bUnlink.addActionListener(new ActionListener() {
gdi.show();
if
GanttDialogInfo.YES) {
(gdi.res
==
public void actionPerformed(ActionEvent e) {
if
(getTabs().getSelectedIndex()
for (int i = 0; iUIFacade.GANTT_INDEX) {// Gantt
// Chart
< context.length; i++) {
+
options.getIconSize() + ".gif")));
getLanguage().getText("question"));
==
unlinkRelationships();
getHumanResourceManager().remove(context[i],
}
}
getUndoManager());
});
refreshProjectInfos();
// if(!isOnlyViewer) toolBar.add(bUnlink);
//
setQuickSave(true);
}
}
}
deleteAssignements();
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
bLink
=
new
ImageIcon(getClass()
TestGanttRolloverButton(new
.getResource("/icons/link_"
options.getIconSize() + ".gif")));
+
bLink.addActionListener(new ActionListener() {
}
public void actionPerformed(ActionEvent e) {
});
// if(!isOnlyViewer) toolBar.add(bDelete);
if
(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX) {// Gantt
// Chart
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
bProperties
=
ImageIcon(getClass()
new
.getResource(
==
linkRelationships();
}
TestGanttRolloverButton(new
}
});
190
});
// if(!isOnlyViewer) toolBar.add(bLink);
// if(!isOnlyViewer) toolBar.add(bUp);
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
//
///
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
bInd = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/indent_"
options.getIconSize() + ".gif")));
=
new
+bDown
ImageIcon(getClass()
.getResource("/icons/down_"
options.getIconSize() + ".gif")));
bInd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if
(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX) {// Gantt
TestGanttRolloverButton(new
==
+
bDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
downDatas();
// Chart
}
// tree.indentCurrentNode();
tree.indentCurrentNodes();
});
setAskForSave(true);
if (!isOnlyViewer) {
// toolBar.add(bDown);
}
// toolBar.addSeparator(new Dimension(20,0));
}
}
});
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
//
///
//////////////////////////////////////////////////////////////////////////////////////////////////////
ScrollingManager scrollingManager = getScrollingManager();
///
// if(!isOnlyViewer) toolBar.add(bInd);
TestGanttRolloverButton(newscrollingManager.addScrollingListener(area.getViewState());
bUnind
=
new
ImageIcon(getClass()
scrollingManager.addScrollingListener(getResourcePanel().are
a
.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();
+
.getViewState());
Action
scrollLeft
=
ScrollGanttChartLeftAction(scrollingManager,
new
options.getIconSize());
==myRolloverActions.add(scrollLeft);
bPrev = new TestGanttRolloverButton(scrollLeft);
bPrev.setAutoRepeatMousePressedEvent(300);
// toolBar.add(bPrev);
tree.dedentCurrentNodes();
setAskForSave(true);
}
}
Action
scrollCenter
area.getScrollCenterAction(scrollingManager,
=
Mediator.getTaskSelectionManager(),
options.getIconSize());
});
// if(!isOnlyViewer) toolBar.add(bUnind);
myRolloverActions.add(scrollCenter);
bScrollCenter = new TestGanttRolloverButton(scrollCenter);
//
//////////////////////////////////////////////////////////////////////////////////////////////////////bScrollCenter.setAutoRepeatMousePressedEvent(300);
///
// toolBar.add(bScrollCenter);
bUp
=
new
TestGanttRolloverButton(new
ImageIcon(getClass().getResource(
scrollRight
=
new
"/icons/up_" + options.getIconSize() +Action
ScrollGanttChartRightAction(scrollingManager,
".gif")));
bUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
upDatas();
}
options.getIconSize());
myRolloverActions.add(scrollRight);
bNext = new TestGanttRolloverButton(scrollRight);
bNext.setAutoRepeatMousePressedEvent(300);
191
// toolBar.add(bNext);
* area.repaint(); } }); toolBar.add(bZoomFit);
*/
//
Action
undo
=
new
UndoAction(getUndoManager(),
//////////////////////////////////////////////////////////////////////////////////////////////////////options.getIconSize());
///
myRolloverActions.add(undo);
Action zoomOut = new ZoomOutAction(getZoomManager(),
bUndo = new TestGanttRolloverButton(undo);
options
.getIconSize());
myRolloverActions.add(zoomOut);
// bUndo = new TestGanttRolloverButton(new
bZoomOut = new TestGanttRolloverButton(zoomOut);
//
ImageIcon(getClass().getResource("/icons/undo_"+options.getI
conSize()+".gif")));
// toolBar.add(bZoomOut);
// bUndo.setEnabled(false);
// bZoomOut = new TestGanttRolloverButton(new
// bUndo.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
//
ImageIcon(getClass().getResource("/icons/zoomm_"+options.g
// undo ();}});
etIconSize()+".gif")));
Action
redo
=
new
RedoAction(getUndoManager(),
options.getIconSize());
//
//////////////////////////////////////////////////////////////////////////////////////////////////////myRolloverActions.add(redo);
///
bRedo = new TestGanttRolloverButton(redo);
Action zoomIn
options
=
new
ZoomInAction(getZoomManager(),// bRedo = new TestGanttRolloverButton(new
myRolloverActions.add(zoomIn);
//
ImageIcon(getClass().getResource("/icons/redo_"+options.getIc
onSize()+".gif")));
bZoomIn = new TestGanttRolloverButton(zoomIn);
// bRedo.setEnabled(false);
// toolBar.add(bZoomIn);
// bRedo.addActionListener(new ActionListener() {
.getIconSize());
// public void actionPerformed(ActionEvent e) {
//
//////////////////////////////////////////////////////////////////////////////////////////////////////// redo ();}});
///
bAbout = new TestGanttRolloverButton(
new ImageIcon(getClass().getResource(
"/icons/manual_"
options.getIconSize() + ".gif")));
// toolBar.addSeparator(new Dimension(20,0));
// toolBar.add(bUndo);
+
// toolBar.add(bRedo);
bAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
aboutDialog();
}
new
options, getUIConfiguration());
myRolloverActions.add(critic);
});
if (isOnlyViewer) {
// toolBar.addSeparator(new Dimension(20,0));
// toolBar.add(bAbout);
}
Action
critic
=
CalculateCriticalPathAction(getTaskManager(), tree,
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(
* bZoomFit = new JButton (new
getClass().getResource(
* ImageIcon(getClass().getResource("/icons/zoomf.gif")));
"/icons/refresh_"
+
* bZoomFit.addActionListener(new ActionListener() { publicoptions.getIconSize() + ".gif")));
void
bRefresh.addActionListener(new ActionListener() {
* actionPerformed(ActionEvent e) { area.fitWholeProject(false);
public void actionPerformed(ActionEvent e) {
192
*
sep.setMaximumSize(new
sep.setMinimumSize(new
getUIFacade().refresh();
}
*
Dimension(1,height));
Dimension(1,height));
});
Dimension(1,height));
sep.setPreferredSize(new
* sep.setBorder(BorderFactory.createLineBorder(Color.GRAY));
TestGanttRolloverButton(new* toolbar.add(sep); JPanel sep2 = new JPanel();
sep2.setMaximumSize(new
.getResource("/icons/showHiddens.gif"))); *
Dimension(1,height));
sep2.setMinimumSize(new
bShowHiddens
=
ImageIcon(getClass()
new
bShowHiddens.addActionListener(this);
Dimension(1,height));
iconList = initIconList();
* sep2.setPreferredSize(new Dimension(1,height));
deletedIconList = initDeletedIconList();
*
sep2.setBorder(BorderFactory.createLineBorder(Color.WHITE))
;
addButtons();
applyButtonOptions();
* toolbar.add(sep2); JPanel
sepR.setMaximumSize(new
}
sepR
=
new
JPanel();
* Dimension(width/2,height)); toolbar.add(sepR); }
*/
protected void saveAsPreviousState() {
GanttDialogSaveAsPreviousState
GanttDialogSaveAsPreviousState(
ps
=
new
private void aboutDialog() {
this);
AboutDialog agp = new AboutDialog(this);
ps.show();
agp.show();
if (ps.isSaved()) {
}
bSaveCurrent.setEnabled(false);
bComparePrev.setEnabled(true);
//LH
myPreviousStates.add(ps.getPreviousState());
private void reportDialog() {
}
ReportDialog agp = new ReportDialog(this);
agp.show();
}
}
public ArrayList getPreviouStates() {
private String getDisplayName(Object[] objs) {
return myPreviousStates;
if (objs.length == 1) {
}
return objs[0].toString();
}
protected void compareToPreviousState() {
GanttDialogCompareToPreviousState
GanttDialogCompareToPreviousState(
StringBuffer result = new StringBuffer();
cp
=
newfor (int i = 0; i < objs.length; i++) {
result.append(objs[i].toString());
this);
if (i < objs.length - 1) {
cp.show();
result.append(", ");
}
}
}
/**
return result.toString();
* Adds a separator.
}
*/
/*
/** Move up the datas (resources or tasks) */
* private static void addToolBarSeparator(JToolBar toolbar, int
private void upDatas() {
width, int
*
height)
{
JPanel
sepL.setMaximumSize(new
sepL
=
new
JPanel();if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX)
{// Gantt
* Dimension(width/2,height)); toolbar.add(sepL); JPanel sep =
new JPanel();
// Chart
tree.upCurrentNodes();
193
}
else
if
(getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX) { // Resource
==if (askForSave == true) {
gdi.show();
// chart
if (gdi.res == GanttDialogInfo.CANCEL)
getResourcePanel().upResource();
return false;
//
getResourcePanel().setPeople(getResourcePanel().getPeople()
);
if (gdi.res == GanttDialogInfo.YES) {
boolean trySave = true;
getResourcePanel().area.repaint();
do {
}
try {
setAskForSave(true);
trySave = false;
}
saveProject();
} catch (Exception e) {
/** Move down datas (resources or tasks) */
System.err.println(e);
private void downDatas() {
gdiSaveError.show();
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX)
{ // Gantt
GanttDialogInfo.CANCEL)
if (gdiSaveError.res ==
// Chart
tree.downCurrentNodes();
}
else
if
(getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX) { // Resource
return false;
trySave
==(gdiSaveError.res == GanttDialogInfo.YES);
}
// chart
=
} while (trySave);
getResourcePanel().downResource();
}
//
}
getResourcePanel().setPeople(getResourcePanel().getPeople()
return true;
);
getResourcePanel().area.repaint();
}
}
setAskForSave(true);
/** A menu has been activate */
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof JMenuItem) {
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {
quitApplication();
}
String arg = evt.getActionCommand();
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
if
(arg.equals(correctLabel(language.getText("newProject")))) {
newProject();
/**
}
* Check if the project has been modified, before creating a new
one or open
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
* another
///
*/
else
if
(arg.equals(correctLabel(language.getText("openProject")))) {
public boolean checkCurrentProject() {
GanttDialogInfo gdi = new GanttDialogInfo(this,
try {
if (checkCurrentProject()) {
GanttDialogInfo.WARNING,
GanttDialogInfo.YES_NO_CANCEL_OPTION,
openFile();
language.getText("msg1"),
language.getText("warning"));
GanttDialogInfo gdiSaveError = new GanttDialogInfo(this,
}
} catch (Exception e) {
e.printStackTrace();
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_NO_CANCEL_OPTION,
language.getText("msg12"),
language.getText("error"));
if (isVisible()) {
GanttDialogInfo gdi =
new GanttDialogInfo(this,
194
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION, language
else
if
(arg.equals(correctLabel(language.getText("saveToServer")))) {
.getText("msg8"), language
try {
saveAsURLProject();
.getText("error"));
} catch (Exception e) {
gdi.show();
System.err.println(e);
} else
}
System.out.println("\n===="
language.getText("error")
}
+
+
"====\n" + language.getText("msg8") + "\n");
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
//
else
(arg.equals(correctLabel(language.getText("export")))) {
}
if
}
// export();}
//
else
if
//////////////////////////////////////////////////////////////////////////////////////////////////////
(arg.equals(correctLabel(language.getText("publishToWeb")))) {
///
ExportFileInfo
else if (arg
info
=
new
ExportFileInfo(null,
.equals(correctLabel(language.getText("openFromSe
rver")))) {
ExportFileInfo.FORMAT_HTML,
options.getExportSettings());
if (checkCurrentProject()) {
openURL();
statusBar.setFirstText(language.getText("htmlexport")
, 2000);
}
// construct URL from settings
}
StringBuffer urlString = new StringBuffer();
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
urlString.append("ftp://");
urlString.append(options.getFTPUser());
else
if
(arg.equals(correctLabel(language.getText("saveProject")))) {
urlString.append(":");
urlString.append(options.getFTPPwd());
try {
urlString.append("@");
saveProject();
urlString.append(options.getFTPUrl());
} catch (Exception e) {
urlString.append("/");
System.err.println(e);
urlString.append(options.getFTPDirectory()
}
== "" ? "" : options
}
.getFTPDirectory()
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
else if (arg
+ "/");
int
confirm
JOptionPane.showConfirmDialog(null, language
=
.equals(correctLabel(language.getText("saveAsProje
ct")))) {
.getText("confirmFTPTransfer_1")
try {
+""
saveAsProject();
} catch (Exception e) {
System.err.println(e);
+
urlString.substring(urlString.indexOf("@") + 1)
+
language.getText("confirmFTPTransfer_2"),
"\n"
+
}
}
language.getText("confirm"),
JOptionPane.YES_NO_OPTION);
195
/*
*
if
GanttHTMLExport.publish(
(confirm
==
0)
{
try
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
{///
else
* urlString.toString(), prjInfos, this, tree,(arg.equals(correctLabel(language.getText("deleteTask")))) {
area,
if
deleteTasks(true);
* getResourcePanel().area,
}
*
statusBar.setFirstText(language.getText("successFTPTransfer"
//
),
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
* 2000); info.myStorageOptions);
else if (arg
* JOptionPane.showMessageDialog(null,
*
language.getText("successFTPTransfer"),
.equals(correctLabel(language.getText("propertiesTa
sk")))) {
* language.getText("success") ,
*
JOptionPane.INFORMATION_MESSAGE);
(IOException e) {
*
JOptionPane.showMessageDialog(null,
}
propertiesTask();
catch
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
e.printStackTrace();///
*
language.getText("error"),
else
e.getMessage(),(arg.equals(correctLabel(language.getText("upTask")))) {
if
upDatas();
* JOptionPane.ERROR_MESSAGE); } }
}
*/
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
else if (arg.equals(language.getText("hideTask"))) {
else
(arg.equals(correctLabel(language.getText("downTask")))) {
tree.hideSelectedNodes();
}
else
(arg.equals(language.getText("displayHiddenTasks")))
tree.displayHiddenTasks();
downDatas();
if
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
//
else
//////////////////////////////////////////////////////////////////////////////////////////////////////(arg.equals(correctLabel(language.getText("indentTask")))) {
///
tree.indentCurrentNodes();
else
if
setAskForSave(true);
(arg.equals(correctLabel(language.getText("printProject")))) {
printProject();
if
if
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
//
///
//////////////////////////////////////////////////////////////////////////////////////////////////////
else
if
///
(arg.equals(correctLabel(language.getText("dedentTask")))) {
else
if
tree.dedentCurrentNodes();
(arg.equals(correctLabel(language.getText("preview")))) {
}
setAskForSave(true);
previewPrint();
}
}
//
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///
///
else
(arg.equals(correctLabel(language.getText("quit")))) {
else
if
(arg.equals(correctLabel(language.getText("unlink")))) {
unlinkRelationships();
quitApplication();
}
if
}
196
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
else
(arg.equals(correctLabel(language.getText("link")))) {
tips.show();
}
//
if
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
linkRelationships();
else
(arg.equals(correctLabel(language.getText("manual")))) {
}
if (helpFrame == null) {
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
try {
helpFrame
net.sourceforge.helpgui.gui.MainFrame(
else if (arg.equals(correctLabel(language
if
=
new
.getText("propertiesHuman")))) {
"/docs/help/", "eclipse");
getTabs().setSelectedIndex(UIFacade.RESOURCES
_INDEX);
// french translation for
the user manual
getResourcePanel().propertiesHuman(this);
}
if
(language.getText("shortLanguage").equals("fr"))
//
//////////////////////////////////////////////////////////////////////////////////////////////////////new net.sourceforge.helpgui.gui.MainFrame(
///
helpFrame =
"/docs/help_fr/", "eclipse");
else if (arg
.equals(correctLabel(language.getText("editCalendar
s")))) {
helpFrame.setTitle(language.getText("ganttManual"));
GanttDialogCalendar dialogCalendar = new
ImageIcon icon = new
GanttDialogCalendar(
ImageIcon(getClass().getResource(
this);
"/icons/ganttproject.png"));
dialogCalendar.show();
}
helpFrame.setIconImage(icon.getImage());
//
helpFrame.setSize((int)
//////////////////////////////////////////////////////////////////////////////////////////////////////
(Toolkit.getDefaultToolkit()
///
else if (arg.equals(correctLabel(language
.getScreenSize().getWidth() * 0.75),
.getText("projectCalendar")))) {
System.out.println("Project calendar");
(int)
(Toolkit.getDefaultToolkit()
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
else
(arg.equals(correctLabel(language.getText("webPage")))) {
.getScreenSize().getHeight() * 0.75));
helpFrame.setLocationRelativeTo(null);
if
} catch (Exception e) {
}
try {
}
openWebPage();
helpFrame.setVisible(true);
} catch (Exception e) {
}
System.err.println(e);
}
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
else
//
//////////////////////////////////////////////////////////////////////////////////////////////////////(arg.equals(correctLabel(language.getText("about")))) {
///
aboutDialog();
else
if
(arg.equals(correctLabel(language.getText("tipsOfTheDay")))) {
if
}
//
TipsDialog tips = new TipsDialog(this,//////////////////////////////////////////////////////////////////////////////////////////////////////
options.getOpenTips());
///
197
else
(arg.equals(correctLabel(language.getText("report")))) {
new Runnable() {
if
public
void
run() {
//LH
reportDialog();
openStartupDocument((Document) ae.getSource());
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
///
else
(arg.equals(correctLabel(language.getText("sendMail")))) {
getTabs().setSelectedIndex(1);
}
});
}
if
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
////
// Test if it's buttons actions
getResourcePanel().sendMail(this);
else if (evt.getSource() instanceof JButton) {
}
if (evt.getSource() == bNew) // new
// Newly added code /CL
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
////
//
else
(arg.equals(correctLabel(language.getText("cut")))) {
newProject();
else if (evt.getSource() == bOpen) { // open
try {
if
if (checkCurrentProject())
// tree.cutSelectedNode();
openFile();
// setAskForSave(true);
} catch (Exception ex) {
// }
System.err.println(ex);
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////
//
else
(arg.equals(correctLabel(language.getText("copy")))) {
}
} else if (evt.getSource() == bSave) { // save
try {
if
saveProject();
// tree.copySelectedNode();
} catch (Exception ex) {
// }
System.err.println(ex);
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////
//
else
(arg.equals(correctLabel(language.getText("paste")))) {
}
} else if (evt.getSource() == bSaveAs) { // saveas
if
try {
saveAsProject();
// tree.pasteNode();
} catch (Exception ex) {
// setAskForSave(true);
System.err.println(ex);
// }
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
////
else
(arg.equals(correctLabel(language.getText("settings")))) {
}
} else if (evt.getSource() == bExport) { // export
ExportFileWizardImpl
ifExportFileWizardImpl(this
launchOptionsDialog();
}
wizard
=
new
.getUIFacade(),
this,
this.getOptions());
wizard.show();
} else if (evt.getSource() == bImport) { // import
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
ImportFileWizardImpl
wizard
=
new
////
ImportFileWizardImpl(this
// Test if it's a file name
.getUIFacade(), this);
} else if (evt.getSource() instanceof Document) {
wizard.show();
if (checkCurrentProject()) {
} else if (evt.getSource() == bPrint) { // print
final ActionEvent ae = evt;
printProject();
getUndoManager().undoableEdit("StartupDocument",
} else if (evt.getSource() == bPreviewPrint) { // print
previewPrint();
198
} else if (evt.getSource() == bShowHiddens) {
/** Create a new task */
showHiddenButtonsPaneMenu();
}
public Task newTask() {
}
// repaint();
}
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
/** Launch the options dialog */
int index = -1;
public void launchOptionsDialog() {
MutableTreeNode
Mediator
// old options dialog box
selectedNode
=
(MutableTreeNode)
.getGanttProjectSingleton().getTree().getSelectedNod
e();
/*
*
GanttDialogOptions
GanttDialogOptions(this,
dialogOptions
*
myUIConfiguration);
(dialogOptions.change) {
=
dialogOptions.show();
newif (selectedNode != null) {
DefaultMutableTreeNode
if(DefaultMutableTreeNode) selectedNode
parent1
=
.getParent();
* setAskForSave(true); }
index = parent1.getIndex(selectedNode) + 1;
*/
tree.getTreeTable().getTree().setSelectionPath(
new
TreePath(parent1.getPath()));
// new options dialog box
statusBar.setFirstText(language.getText("settingsPreferences"),
2000);
tree.getTreeTable().getTreeTable().editingStopped(
SettingsDialog dialogOptions = new SettingsDialog(this);
new
ChangeEvent(tree.getTreeTable().getTreeTable()));
dialogOptions.show();
}
getResourcePanel().reloadRoles();
area.repaint();
// TODO check if the following code (now commentted) is really
}
// necessary...
//
boolean
editing
tree.getTreeTable().getTreeTable().isEditing();
=
public ProjectResource newHumanResource() {
// TaskNode tn = (TaskNode) tree.getSelectedNode();
final HumanResource people = ((HumanResourceManager)
// TaskNode parent;
getHumanResourceManager())
// if (editing) {
.newHumanResource();
// System.out.println("Editing");
people.setRole(getRoleManager().getDefaultRole());
GanttDialogPerson
getLanguage(),
dp
=
new
GanttDialogPerson(this,// if (tn != null) {
// if (tn.isRoot())
people);
// parent = tn;
dp.setVisible(true);
// else
if (dp.result()) {
// parent = (TaskNode) tn.getParent();
getUndoManager().undoableEdit("new
new Runnable() {
// Task t = (Task) parent.getUserObject();
Resource",// tree.selectTask(t, false);
public void run() {
// }
// }
getHumanResourceManager().add(people);
}
});
}
// GanttTask current = tree.getSelectedTask();
GanttCalendar cal = new GanttCalendar(area.getViewState()
.getStartDate());
return people;
}
DefaultMutableTreeNode node = tree.getSelectedNode();
199
// // For refresh all the parent task
GanttLanguage lang = GanttLanguage.getInstance();
String nameOfTask = options.getTaskNamePrefix();
language.getText("newTask");
//// // while (tree.getNode(task.getTaskID()).isRoot() == false) {
// // father = tree.getFatherNode(task);
// if (current != null) {
// // tree.refreshAllChild(father.toString());
// current.setMilestone(false);
// // taskFather = (GanttTask) father.getUserObject();
// node = (TaskNode) tree.getSelectedNode();
// // taskFather.refreshDateAndAdvancement(tree);
// cal = current.getStart();
// // father.setUserObject(taskFather);
// if (!node.isRoot())
// // task = taskFather;
// nameOfTask = current.toString();
// // }
// }
// }
GanttTask task = getTaskManager().createTask();
area.repaint();
task.setStart(cal);
setAskForSave(true);
task.setLength(1);
statusBar.setFirstText(language.getText("createNewTask"),
getTaskManager().registerTask(task);// create a new task in the1000);
tab
if (options.getAutomatic()) {
// paneneed to register it
propertiesTask(new
DefaultMutableTreeNode[]
taskNode });
task.setName(nameOfTask + "_" + task.getTaskID());
task.setColor(area.getTaskColor());
}
// if (current != null) {
// setQuickSave(true);
// if (current.colorDefined()) {
tree.setEditingTask(task);
// task.setColor(current.getColor());
repaint2();
// }
return task;
// if (current.shapeDefined())
}
{
// task.setShape(current.getShape());
// }
public void deleteResources() {
TaskNode taskNode = tree.addObject(task, node, index);
myDeleteHumanAction.actionPerformed(null);
}
/*
* this will add new custom columns to the newly created task. public void deleteAssignements() {
myDeleteAssignmentAction.actionPerformed(null);
*/
Mediator.getCustomColumnsStorage().processNewTask(task); }
/**
AdjustTaskBoundsAlgorithm alg = getTaskManager()
* Delete the currant task
.getAlgorithmCollection().getAdjustTaskBoundsAlgorit
hm();
*
alg.run(task);
* @param confirmation
RecalculateTaskCompletionPercentageAlgorithm
getTaskManager()
alg2
=*
*/
.getAlgorithmCollection()
.getRecalculateTaskCompletionPercentageAlgorithm(
TODO
public void deleteTasks(boolean confirmation) {
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
);
alg2.run(task);
// refresh the differents tasks
// if (current != null) {
// tree.refreshAllChild(nameOfTask);
final
DefaultMutableTreeNode[]
tree.getSelectedNodes();
=
if (cdmtn == null || cdmtn.length == 0) {
statusBar.setFirstText(language.getText("msg21"),
2000);
// // DefaultMutableTreeNode father = tree.getSelectedNode();
// // GanttTask taskFather = null;
cdmtn
return;
}
200
ttask.delete();
} else if (cdmtn[i] != null
GanttDialogInfo gdi = new GanttDialogInfo(this,
&&
GanttDialogInfo.QUESTION,
GanttDialogInfo.YES_NO_OPTION,
cdmtn[i] instanceof BlankLineNode) {
language.getText("msg19"),
language.getText("question"));
((GanttTreeTableModel) tree.getTreeTable()
.getTreeTableModel())
if (confirmation)
gdi.show();
.removeNodeFromParent(cdmtn[i]);
else
}
gdi.res = GanttDialogInfo.YES;
}
if (gdi.res == GanttDialogInfo.YES) {
for (int i = 0; i < fathers.size(); i++)
removed",{
getUndoManager().undoableEdit("Task
new Runnable() {
public void run() {
ArrayList
fathers
=
DefaultMutableTreeNode
(DefaultMutableTreeNode) fathers
new
ArrayList();
father
=
.get(i);
for (int i = 0; i < cdmtn.length; i++)
{
if
(father.getChildCount() == 0)
if (cdmtn[i] != null &&
cdmtn[i] instanceof TaskNode) {
((Task)
father.getUserObject())
Task ttask =
(Task) (cdmtn[i].getUserObject());
.setProjectTask(false);
}
DefaultMutableTreeNode father = tree
}
.getFatherNode(ttask);
});
refreshProjectInfos();
tree.removeCurrentNode();
if (father !=
area.repaint();
this.repaint2();
null) {
getResourcePanel().area.repaint();
GanttTask taskFather = (GanttTask) father
setAskForSave(true);
// setQuickSave (true);
.getUserObject();
// quickSave("deleteTasks");
AdjustTaskBoundsAlgorithm alg = getTaskManager() }
}
.getAlgorithmCollection()
/** Edit task parameters */
.getAdjustTaskBoundsAlgorithm();
public void propertiesTask() {
alg.run(taskFather);
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
//
taskFather.refreshDateAndAdvancement(tree);
if (tree.getSelectedTaskNodes() != null
&& tree.getSelectedTaskNodes().length >
father.setUserObject(taskFather);
0)
fathers.add(father);
}
propertiesTask(tree.getSelectedTaskNodes());
}
getTaskManager().deleteTask(ttask);
/** Edit task parameters */
201
DefaultMutableTreeNode[]
public void propertiesTask(DefaultMutableTreeNode[] nodes) { final
tree.getSelectedTaskNodes();
final
int
rowHeight
=
if (cdmtn == null) {
tree.getTreeTable().getTable().getRowHeight();
cdmtn
=
statusBar.setFirstText(language.getText("msg21"),
if (nodes == null || nodes[0].isRoot()) {
2000);
statusBar.setFirstText(language.getText("msg21"),
return;
2000);
}
return;
} else {
getUndoManager().undoableEdit("Unlink", new Runnable() {
statusBar.setFirstText(language.getText("editingPara
meters"), 2000);
public void run() {
for (int i = 0; i < cdmtn.length; i++) {
int nbTasks = nodes.length;
if
String tasksNames = "";
(cdmtn[i]
!=
null
&&
t
=
!cdmtn[i].isRoot()) {
for (int i = 0; i < nodes.length; i++)
GanttTask
(GanttTask) (cdmtn[i].getUserObject());
if (nodes[i].isRoot()) {
t.unlink();
nbTasks = nbTasks - 1;
}
break;
// setQuickSave (true);
}
}
}
GanttTask[] tasks = new GanttTask[nbTasks];
});
for (int i = 0; i < nodes.length; i++)
area.repaint();
if (!nodes[i].isRoot()) {
tasks[i]
setAskForSave(true);
(GanttTask)
/*
=
(nodes[i].getUserObject());
*
JFileChooser
fc
=
JFileChooser(options.getWorkingDir());
=
* FileFilter ganttFilter = new GanttXMLFileFilter();
if (!tasksNames.equals(""))
tasksNames
tasksNames + ", ";
fc.addChoosableFileFilter(ganttFilter);
tasksNames = tasksNames + *
inputStream =
tasks[i].getName();
new
InputStream
* null; int returnVal = fc.showOpenDialog(GanttProject.this); if
}
GanttDialogProperties
GanttDialogProperties(this, tree,
pd
managerHash,
=
tasks,
* (returnVal == JFileChooser.APPROVE_OPTION) { final
JFileChooser jfc =
new
* fc; try { Document document = new FileDocument (new File
area, * (jfc.getSelectedFile().getAbsolutePath())); inputStream =
tasksNames);
pd.show();
*
document.getInputStream();
(inputStream.read()); }
if (pd.change) {
* catch (IOException e) { // TODO Auto-generated catch block
setAskForSave(true);
* e.printStackTrace(); } }
setRowHeight(rowHeight);
*/
getResourcePanel().getResourceTreeTableModel()
//System.out.println
}
.updateResources();
}
}
}
/** Unlink the relationships of the selected task */
/** Link the selected Tasks */
public void linkRelationships() {
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
public void unlinkRelationships() {
final
DefaultMutableTreeNode[]
tree.getSelectedTaskNodes();
getTabs().setSelectedIndex(UIFacade.GANTT_INDEX);
if (cdmtn == null) {
cdmtn
=
202
statusBar.setFirstText(language.getText("msg21"),
2000);
ExportFileInfo info = selectExportFile(null);
if (!info.equals(ExportFileInfo.EMPTY)) {
return;
doExport(info);
}
}
}
if (cdmtn.length < 2) {
statusBar.setFirstText(language.getText("msg22"),
2000);
private void doExport(ExportFileInfo info) {
Chart resourcesChart = (Chart) getResourcePanel().area;
return;
Chart ganttChart = (Chart) getArea();
}
Chart visibleChart = (getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX) ? resourcesChart
getUndoManager().undoableEdit("Link", new Runnable() {
==
: ganttChart;
public void run() {
ExportFileWizardImpl wizard = new ExportFileWizardImpl(info,
for (int i = 0; i < cdmtn.length - 1; i++) {
getUIFacade(),
(IGanttProject)
this,
if (cdmtn[i] != null && cdmtn[i + 1]ganttChart,
!= null) {
resourcesChart, visibleChart, options);
GanttTask firstTask =
wizard.doExport();
(GanttTask) (cdmtn[i]
}
.getUserObject());
;
/** Execute the export functions. */
GanttTask secondTask
= (GanttTask) (cdmtn[i + 1]
/** Refresh the informations of the project on the status bar. */
public void refreshProjectInfos() {
.getUserObject());
if (tree.nbTasks == 0 && resp.nbPeople() == 0)
try {
statusBar.setSecondText("");
getTaskManager().getDependencyCollection()
else
statusBar.setSecondText(correctLabel(language.getT
ext("task"))
.createDependency(secondTask, firstTask,
+ " : " + tree.nbTasks + " "
new FinishStartConstraintImpl());
+
catch
correctLabel(language.getText("resources")) + " : "
}
(TaskDependencyException e1) {
+ resp.nbPeople());
//
e1.printStackTrace(); //To change body of catch
}
//
statement
use File | Settings | File Templates.
}
}
}
}
});
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();
// setQuickSave (true);
area.repaint();
setAskForSave(true);
}
FileFilter pdfFilter = new GanttPDFFileFilter();
FileFilter htmlFilter = new GanttHTMLFileFilter();
FileFilter msprojectFilter = new GanttMSProjectLFileFilter();
JFileChooser fc = new JFileChooser(options.getWorkingDir());
fc.addChoosableFileFilter(figFilter);
/** Export the calendar on a png file */
public void export() {
fc.addChoosableFileFilter(msprojectFilter);
fc.addChoosableFileFilter(pngFilter);
fc.addChoosableFileFilter(jpgFilter);
203
} else if (selectedFilter.equals(jpgFilter)) {
fc.addChoosableFileFilter(csvFilter);
fc.addChoosableFileFilter(pdfFilter);
type = ExportFileInfo.FORMAT_JPG;
fc.addChoosableFileFilter(htmlFilter);
} else if (selectedFilter.equals(pdfFilter)) {
if (currentFilter != null)
type = ExportFileInfo.FORMAT_PDF;
fc.setFileFilter(currentFilter);
} else if (selectedFilter.equals(figFilter)) {
type = ExportFileInfo.FORMAT_XFIG;
// Remove the possibility to use a file filter for all files
} else if (selectedFilter.equals(csvFilter)) {
type = ExportFileInfo.FORMAT_CSV;
FileFilter[] filefilters = fc.getChoosableFileFilters();
} else if (selectedFilter.equals(msprojectFilter)) {
for (int i = 0; i < filefilters.length; i++) {
if (filefilters[i] != figFilter && filefilters[i] != pngFilter
type
ExportFileInfo.FORMAT_MSPROJECT;
&& filefilters[i] != jpgFilter
=
} else {
&& filefilters[i] != csvFilter
statusBar.setFirstText(
&& filefilters[i] != pdfFilter
"Unknown file filter has
&& filefilters[i] != htmlFilter
been selected : "
&& filefilters[i] != msprojectFilter)
+
selectedFilter, 2000);
fc.removeChoosableFileFilter(filefilters[i]);
throw new RuntimeException(
}
"Unknown file filter has
been selected: "
int returnVal = fc.showSaveDialog(this);
+
if (returnVal == JFileChooser.APPROVE_OPTION) {
selectedFilter);
String filename = fc.getSelectedFile().toString();
}
FileFilter selectedFilter = fc.getFileFilter();
changeWorkingDirectory(new
File(filename).getParent());
File file = new File(filename);
// if( the file exists, ask for overwriting
if (new File(filename).exists()) {
GanttDialogInfo
GanttDialogInfo(this,
gdi
result
=
new
newoptions.getExportSettings());
=
GanttDialogInfo.WARNING,
GanttDialogInfo.YES_NO_OPTION,
ExportFileInfo(file,
type,
}
return result;
filename
+
"\n"
language.getText("msg18"), language
.getText("warning"));
+
}
/** Print the project */
gdi.show();
public void printProject() {
if (gdi.res == GanttDialogInfo.NO)
return
selectExportFile(selectedFilter);
Object
selectedUserObject
getTabs().getSelectedUserObject();
}
if (selectedUserObject instanceof Chart)
int type = -1;
options
=
PrintManager.printChart((Chart) selectedUserObject,
.getExportSettings());
if (selectedFilter.equals(htmlFilter)) {
type = ExportFileInfo.FORMAT_HTML;
if
else
(!fc.getFileFilter().accept(new
System.err.println("not printable");
File(filename))) {
filename += ".html";
}
} else if (selectedFilter.equals(pngFilter)) {
type = ExportFileInfo.FORMAT_PNG;
//
if
(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX) {// Gantt
==
// // Chart
// GanttExportSettings bool = new GanttExportSettings();
204
// // GanttDialogExport gde = new GanttDialogExport(this, bool, // Resources
// // language);
// // Chart
// // gde.show();
//
preview
=
getResourcePanel().area,
// // if (bool.ok)
new
GanttPreviewPrint(this,
// getResourcePanel().area.getChartModel().getStartDate(),
// // area.printProject(bool.name, bool.percent, bool.depend);
// getResourcePanel().area.getChartModel().getEndDate());
// GanttExportSettings ges = options.getExportSettings();
// }
// // ges.setStartDate(area.getChartModel().getStartDate());
// if (preview != null)
// // ges.setEndDate(area.getChartModel().getEndDate());
// preview.setVisible(true);
// ges.setStartDate(area.getStartDate());
// }
// ges.setEndDate(area.getEndDate());
public void previewPrint() {
// area.printProject(ges);
//
Date startDate, endDate;
// // try
// // {
Object
selectedUserObject
getTabs().getSelectedUserObject();
// // ((GanttTree2)getTree()).getTreeTable().print();
Chart chart = null;
=
// // }
// // catch (PrinterException e)
if (selectedUserObject instanceof Chart)
// // {
chart = (Chart) selectedUserObject;
// // // TODO Auto-generated catch block
else {
// // e.printStackTrace();
System.err.println("not printable");
// // }
return;
//
//
}
else
if
(getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX)
}
==
try {
// {// Resources
startDate = chart.getStartDate();
// // Chart
endDate = chart.getEndDate();
//
getResourcePanel().area.printProject(options.getExportSettings } catch (UnsupportedOperationException e) {
());
startDate = null;
// } else {
endDate = null;
// Component comp = getTabs().getSelectedComponent();
}
//
// Chart chart = (Chart)comp;
PrintPreview preview = null;
// PrintManager.printChart(chart, options.getExportSettings());
// }
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX)
{
startDate = area.getChartModel().getStartDate();
}
endDate = area.getChartModel().getEndDate();
/** Preview the project before print */
// public void previewPrint() {
// GanttPreviewPrint preview = null;
//
if
(getTabs().getSelectedIndex()
UIFacade.GANTT_INDEX) {// Gantt
// // Chart
//
preview
=
new
area.getChartModel()
GanttPreviewPrint(this,
// .getStartDate(), area.getChartModel().getEndDate());
//
}
else
if
(getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX) {//
}
else
if
(getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX) {
==
startDate
getResourcePanel().area.getChartModel().getStartDate();
==
endDate
=
=
getResourcePanel().area.getChartModel().getEndDate();
}
area,preview = new PrintPreview(this, chart, correctLabel(language
.getText("preview")), startDate, endDate);
if (preview != null)
==
preview.setVisible(true);
205
// GanttTask.resetMaxID();
}
RoleManager.Access.getInstance().clear();
if (null != projectDocument)
/** Create a new project */
projectDocument.releaseLock();
public void newProject() {
getUndoManager().undoableEdit("Init
Runnable() {
new
Project",
newprojectDocument = null;
// change title of the frame
public void run() {
if (!isOnlyViewer)
if (checkCurrentProject()) {
this.setTitle(language.getText("appliTitle"));
else
closeProject(true);
2"),
this.setTitle("GanttViewer");
statusBar.setFirstText(language.getText("newProject setAskForSave(false);
getTaskManager().clear();
1500);
refreshProjectInfos();
}
}
});
tree.clearTree();
tree.getTreeTable().initTreeTable();
Mediator.getCustomColumnsStorage().reset();
// getZoomManager().clear();
if (discardUndoEdits)
getUndoManager().die();
prjInfos = new PrjInfos();
for (int i = 0; i < myPreviousStates.size(); i++)
showNewProjectWizard();
((GanttPreviousState)
myPreviousStates.get(i)).remove();
myPreviousStates = new ArrayList();
}
bSaveCurrent.setEnabled(false);
private void showNewProjectWizard() {
bComparePrev.setEnabled(false);
NewProjectWizard wizard = new NewProjectWizard();
area.setPreviousStateTasks(null);
wizard.createNewProject(this, getUIFacade());
Chart[] charts = Mediator.getPluginManager().getCharts();
}
for (int i = 0; i < charts.length; i++)
charts[i].reset();
/**
}
* Closes a project. Make sure you have already called
checkCurrentProject()
/** Open a local project file with dialog box (JFileChooser) */
* before.
public void openFile() throws IOException {
*
// Create a filechooser
* @see #checkCurrentProject()
JFileChooser fc = new JFileChooser(options.getWorkingDir());
*/
FileFilter ganttFilter = new GanttXMLFileFilter();
public void closeProject(boolean discardUndoEdits) {
fc.addChoosableFileFilter(ganttFilter);
// Clear the jtree
// refresh graphic area
// Remove the possibility to use a file filter for all files
area.repaint();
FileFilter[] filefilters = fc.getChoosableFileFilters();
area.setProjectLevelTaskColor(null);
for (int i = 0; i < filefilters.length; i++) {
getResourcePanel().area.repaint();
if (filefilters[i] != ganttFilter)
// reset people
getResourcePanel().reset();
fc.removeChoosableFileFilter(filefilters[i]);
}
// getHumanResourceManager().clear();
prjInfos = new PrjInfos();
206
lastDocument.setUserInfo(uc.userName,
int returnVal = fc.showOpenDialog(GanttProject.this);
uc.password);
if (returnVal == JFileChooser.APPROVE_OPTION) {
openDoc = lastDocument;
final JFileChooser jfc = fc;
} else {
openDoc
newDocumentCreator.createDocument(uc.fileurl,
getUndoManager().undoableEdit("OpenFile",
Runnable() {
=
uc.userName,
public void run() {
uc.password);
try {
}
openDocument(getDocumentManager().getDocument
try {
openDocument(openDoc);
(
} catch (IOException e) {
jfc.getSelectedFile().getAbsolutePath()));
if (isVisible()) {
} catch (IOException e) {
//
TODO
GanttDialogInfo
gdi
=
new
Auto-GanttDialogInfo(this,
generated catch block
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION,
e.printStackTrace();
}
language.getText("msg11"), language
changeWorkingDirectory(jfc.getSelectedFile().getPare
nt());
.getText("error"));
}
gdi.show();
});
} else
// changeUndoNumber ();
System.out.println("\n===="
}
+
language.getText("error")
}
+ "====\n" +
language.getText("msg11") + "\n");
/** Open a remote
(GanttURLChooser) */
project
file
with
dialog
openURL(openDoc);
box
}
public void openURL() {
}
openURL(projectDocument);
}
}
/** Open a remote
(GanttURLChooser) */
project
file
with
dialog
private void openDocument(Document
boxIOException {
document)
throws
if (document.getDescription().endsWith(".xml")
||
document.getDescription().endsWith(".gan")) {
public void openURL(Document lastDocument) {
InputStream
document.getInputStream();
GanttURLChooser uc = new GanttURLChooser(this, true,
(null
!=
lastDocument.getURLPath() : null,
lastDocument)
?
(null
!=
lastDocument.getUsername() : null,
lastDocument)
?
(null
!=
lastDocument.getPassword() : null);
lastDocument)
?
inputStream
=
closeProject(true);
boolean locked = document.acquireLock();
if (!locked) {
GanttDialogInfo
GanttDialogInfo(this,
gdi
=
new
uc.show();
if (uc.change) {
GanttDialogInfo.WARNING,
GanttDialogInfo.YES_NO_OPTION,
Document openDoc;
if ((lastDocument instanceof AbstractURLDocument)
&&
uc.fileurl.equals(lastDocument.getURLPath())) {
language.getText("msg13"),
language.getText("warning"));
gdi.show();
if (gdi.res == GanttDialogInfo.NO)
207
return;
opener.getContext(),
taskManager);
}
opener.addTagHandler(customPropHandler);
GanttXMLOpen
GanttXMLOpen(prjInfos, area,
opener
TaskDisplayColumnsTagHandler taskDisplayHandler
new= new TaskDisplayColumnsTagHandler(
=
this.tree.getTreeTable());
getTaskManager(),
getUIFacade());
opener.addTagHandler(taskDisplayHandler);
ResourceManager
getHumanResourceManager();
hrManager
=
ViewTagHandler
viewHandler
ViewTagHandler(getUIFacade());
HolidayTagHandler
HolidayTagHandler(this);
RoleManager roleManager = getRoleManager();
=
holidayHandler
new
=
new
opener.addParsingListener(taskDisplayHandler);
TaskManager taskManager = getTaskManager();
opener.addParsingListener(customPropHandler);
ResourceTagHandler
ResourceTagHandler(
resourceHandler
=
new
opener.addTagHandler(weekHandler);
opener.addTagHandler(previousStateHandler);
opener.addTagHandler(viewHandler);
hrManager, roleManager);
DependencyTagHandler dependencyHandler = new
DependencyTagHandler(
opener.getContext(),
opener.addTagHandler(holidayHandler);
opener.addParsingListener(holidayHandler);
opener.addParsingListener(taskPropHandler);
taskManager);
//LH
CostTagHandler costHandler = new CostTagHandler(
opener.addTagHandler(taskHandler);
opener.addTagHandler(blankLineHandler);
opener.getContext(),
taskManager);
AllocationTagHandler
AllocationTagHandler(
allocationHandler
hrManager,
=
new
());
taskManager,
roleManager);
VacationTagHandler
VacationTagHandler(
vacationHandler
=
new
opener.addTagHandler(opener.getDefaultTagHandler
opener.addTagHandler(resourceHandler);
//LH
opener.addTagHandler(costHandler);
opener.addTagHandler(dependencyHandler);
hrManager);
opener.addTagHandler(allocationHandler);
RoleTagHandler
rolesHandler
RoleTagHandler(roleManager);
=
new
TaskTagHandler
taskHandler
TaskTagHandler(taskManager, opener
=
new
opener.addTagHandler(vacationHandler);
opener.addTagHandler(rolesHandler);
.getContext());
BlankLineTagHandler
BlankLineTagHandler(tree);
opener.addParsingListener(allocationHandler);
blankLineHandler
=
new
//LH
TaskPropertiesTagHandler taskPropHandler = new
TaskPropertiesTagHandler(
opener.addParsingListener(costHandler);
opener.addParsingListener(dependencyHandler);
this.tree.getTreeTable());
opener.addParsingListener(resourceHandler);
opener.addTagHandler(taskPropHandler);
PreviousStateTasksTagHandler
previousStateHandler = new PreviousStateTasksTagHandler(
if (opener.load(document.getInputStream())) {
this.getPreviouStates());
DefaultWeekTagHandler
DefaultWeekTagHandler(
weekHandler
=
new
getActiveCalendar());
CustomPropertiesTagHandler customPropHandler =
new CustomPropertiesTagHandler(
// Add this project to the last opened project
if (documentsMRU.add(document))
updateMenuMRU();
if (locked) {
projectDocument = document;
208
if (!isOnlyViewer)
ArrayList projectTasks = tree.getProjectTasks();
if (projectTasks.size() != 0)
this.setTitle(language.getText("appliTitle") + " ["
for (int i = 0; i < projectTasks.size(); i++)
+
getTaskManager().processCriticalPath(
document.getDescription() + "]");
(TaskNode)
else
projectTasks.get(i));
this.setTitle("GanttViewer ["
repaint2();
+
document.getDescription() + "]");
}
}
setAskForSave(false);
public void openStartupDocument(String path) {
statusBar.setFirstText(language.getText("opening") +
""
+
2000);
if (path != null) {
Document
document
DocumentCreator.createDocument(path);
document.getPath(),
openStartupDocument(document);
=
}
if (myPreviousStates.size() != 0)
bComparePrev.setEnabled(true); }
}
public void openStartupDocument(Document document) {
} else {
try {
if (isVisible()) {
GanttDialogInfo
GanttDialogInfo(this,
gdi
=
new
openDocument(document);
} catch (IOException ex) {
if (document instanceof AbstractURLDocument) {
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION,
// if there are problems opening an
AbstractURLDocument
language.getText("msg2") + "\n"
// (possibly because of bad authentication),
+
// give the user a chance, to enter correct
document.getDescription(), language
credentials
openURL(document);
.getText("error"));
} else {
gdi.show();
GanttDialogInfo
GanttDialogInfo(this,
} else {
System.out.println("\n===="
language.getText("error")
+
gdi
=
new
+
"====\n"
GanttDialogInfo.ERROR,
+GanttDialogInfo.YES_OPTION,
language.getText("msg2") + "\n");
language.getText("msg2") + "\n"
}
+
}
document.getDescription(), language
Chart[] charts = Mediator.getPluginManager().getCharts();
.getText("error"));
for (int i = 0; i < charts.length; i++) {
gdi.show();
charts[i].setTaskManager(myTaskManager);
}
charts[i].reset();
}
}
}
getResourcePanel().reloadRoles();
// myDelayManager.fireDelayObservation(); // it is done in/**
repaint2
* Open a XML stream that represent the file //By CL !@#
addMouseListenerToAllContainer(this.getComponents());
*
getTaskManager().processCriticalPath((TaskNode)
* @param ins
tree.getRoot());
209
HolidayTagHandler
HolidayTagHandler(this);
*/
public void openXMLStream(InputStream ins, String path) {
holidayHandler
=
new
opener.addTagHandler(holidayHandler);
try {
opener.addParsingListener(holidayHandler);
tree.clearTree();
opener.addTagHandler(taskHandler);
getResourcePanel().reset();
opener.addTagHandler(blankLineHandler);
// getHumanResourceManager().clear();
opener.addParsingListener(taskPropHandler);
// GanttTask.resetMaxID();
opener.addParsingListener(taskDisplayHandler);
getTaskManager().clear();
opener.addParsingListener(customPropHandler);
RoleManager.Access.getInstance().clear();
GanttXMLOpen
GanttXMLOpen(prjInfos, area,
opener
=
new());
opener.addTagHandler(opener.getDefaultTagHandler
opener.addTagHandler(resourceHandler);
getTaskManager(),
opener.addTagHandler(dependencyHandler);
getUIFacade());
ResourceManager
getHumanResourceManager();
hrManager
//LH
=
opener.addTagHandler(costHandler);
RoleManager roleManager = getRoleManager();
ResourceTagHandler
ResourceTagHandler(
resourceHandler
=
opener.addTagHandler(allocationHandler);
new
opener.addParsingListener(allocationHandler);
opener.addTagHandler(vacationHandler);
hrManager, roleManager);
DependencyTagHandler dependencyHandler = new
DependencyTagHandler(
opener.getContext(),
opener.addParsingListener(dependencyHandler);
//LH
opener.addParsingListener(costHandler);
getTaskManager());
opener.load(ins);
//LH
// addProjectFileToLastOpen(projectfile);
CostTagHandler costHandler = new CostTagHandler(
} catch (Exception ex) {
opener.getContext(),
GanttDialogInfo gdi = new GanttDialogInfo(this,
getTaskManager());
AllocationTagHandler
AllocationTagHandler(
allocationHandler
hrManager,
=
GanttDialogInfo.ERROR,
new
GanttDialogInfo.YES_OPTION, language
getTaskManager(),
.getText("msg2")
getRoleManager());
VacationTagHandler
VacationTagHandler(
vacationHandler
=
new
language.getText("error"));
gdi.show();
hrManager);
TaskTagHandler
taskHandler
TaskTagHandler(getTaskManager(),
new}
=
setAskForSave(false);
opener.getContext());
BlankLineTagHandler
BlankLineTagHandler(tree);
+ "\n" + path,
blankLineHandler
=
}
new
TaskPropertiesTagHandler taskPropHandler = new/** Save the project as (with a dialog file chooser) */
TaskPropertiesTagHandler(
public boolean saveAsProject() throws IOException {
this.tree.getTreeTable());
opener.addTagHandler(taskPropHandler);
tree.displayHiddenTasks();
JFileChooser fc = new JFileChooser(options.getWorkingDir());
CustomPropertiesTagHandler customPropHandler =FileFilter ganttFilter = new GanttXMLFileFilter();
new CustomPropertiesTagHandler(
fc.addChoosableFileFilter(ganttFilter);
opener.getContext(),
getTaskManager());
opener.addTagHandler(customPropHandler);
// Remove the possibility to use a file filter for all files
TaskDisplayColumnsTagHandler taskDisplayHandlerFileFilter[] filefilters = fc.getChoosableFileFilters();
= new TaskDisplayColumnsTagHandler(
for (int i = 0; i < filefilters.length; i++) {
this.tree.getTreeTable());
if (filefilters[i] != ganttFilter)
opener.addTagHandler(taskDisplayHandler);
fc.removeChoosableFileFilter(filefilters[i]);
210
if (uc.change) {
}
Document saveDocument = null;
if (null != document)
int returnVal = fc.showSaveDialog(GanttProject.this);
if
(uc.fileurl.equals(document.getURLPath())
if (returnVal == JFileChooser.APPROVE_OPTION) {
String projectfile = fc.getSelectedFile().toString();
&&
uc.userName.equals(document.getUsername())
(fc.getFileFilter().accept(new
&&
if (!fc.getFileFilter().accept(new File(projectfile))) {
if
File(projectfile + ".gan"))) {
uc.password.equals(document.getPassword()))
projectfile += ".gan";
saveDocument = document;
}
if (null == saveDocument)
}
saveDocument
DocumentCreator.createDocument(uc.fileurl,
uc.userName,
// if( the file exists, ask for overwriting
uc.password);
if (new File(projectfile).exists()) {
GanttDialogInfo
GanttDialogInfo(this,
=
saveProject(saveDocument);
gdi
=
new
return true;
}
GanttDialogInfo.WARNING,
GanttDialogInfo.YES_NO_OPTION,
return false;
projectfile
+
"\n"
language.getText("msg18"),
+
/*
* ServerDialog sd = new ServerDialog(this); sd.show(); return
false;
language.getText("warning"));
gdi.show();
*/
if (gdi.res == GanttDialogInfo.NO)
}
saveAsProject();
}
/** Save the project on a file */
public void saveProject() throws IOException {
saveProject(new FileDocument(new File(projectfile))); tree.displayHiddenTasks();
return true;
saveProject(projectDocument);
}
}
return false;
}
/** Save the project to the given document, if possible */
/** Save the project on a server (with a GanttURLChooser) */
public boolean saveAsURLProject() throws IOException {
public
void
IOException {
saveProject(Document
document)
throws
if (null == document) {
saveAsProject();
return saveAsURLProject(projectDocument);
return;
}
}
/** Save the project on a server (with a GanttURLChooser) */
if (!document.canWrite()) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
public boolean saveAsURLProject(Document document) throws
GanttDialogInfo.ERROR,
IOException {
GanttDialogInfo.YES_OPTION, language
GanttURLChooser uc = new GanttURLChooser(this, false,
(null
document.getURLPath() : null,
!=
document)
?
(null
!=
document.getUsername() : null,
document)
?
(null
!=
document.getPassword() : null);
document)
?
uc.show();
.getText("msg10"), language.getText("error"));
gdi.show();
if (document instanceof AbstractURLDocument) {
saveAsURLProject(document);
} else {
saveAsProject();
211
}
if (null != filepath) {
return;
changeWorkingDirectory(new
File(filepath).getParent());
}
}
if (!document.acquireLock()) {
setAskForSave(false);
GanttDialogInfo gdi = new GanttDialogInfo(this,
}
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION, language
public void changeWorkingDirectory(String newWorkDir) {
.getText("msg14"), language.getText("error"));
if (null != newWorkDir)
gdi.show();
options.setWorkingDirectory(newWorkDir);
if (document instanceof AbstractURLDocument) {
}
saveAsURLProject(document);
} else {
/** @return the uiconfiguration. */
saveAsProject();
public UIConfiguration getUIConfiguration() {
}
return myUIConfiguration;
return;
}
}
if (document.getDescription().endsWith(".xml")
/** Function that launch the dialog to edit project properties */
||
document.getDescription().endsWith(".gan")) {
GanttXMLSaver
saver
GanttXMLSaver((IGanttProject) this, tree,
/*
=
getResourcePanel(),
new* public void editSettings() { GanttDialogSettings ds = new
* GanttDialogSettings(this, language); ds.show(); if (ds.change)
area,{
(UIFacade) this);
* setAskForSave(ds.change); } }
saver.save(document.getOutputStream(), version);
*/
statusBar.setFirstText(GanttLanguage.getInstance() /** Quit the application */
.getText("saving")
+
"
"
+
2000);
public void quitApplication() {
document.getPath(),options.setWindowPosition(getX(), getY());
options.setWindowSize(getWidth(), getHeight());
// Add this project to the last opened projects
options.setUIConfiguration(myUIConfiguration);
options.setDocumentsMRU(documentsMRU);
if (documentsMRU.add(document))
options.setLookAndFeel(lookAndFeel);
updateMenuMRU();
options.setToolBarPosition(toolBar.getOrientation());
if (projectDocument != document) {
options.save();
if (projectDocument != null)
projectDocument.releaseLock();
if (checkCurrentProject()) {
closeProject(true);
projectDocument = document;
setVisible(false);
}
dispose();
}
System.exit(0);
} else {
// change title of the window
setVisible(true);
if (!isOnlyViewer)
this.setTitle(language.getText("appliTitle") + " ["
+
document.getDescription()
}
}
+
"]");
/** Open the web page */
else
this.setTitle("GanttViewer
document.getDescription() + "]");
String filepath = document.getFilePath();
["
+public void openWebPage() throws IOException {
if (!BrowserControl.displayURL("http://ganttproject.org/")) {
GanttDialogInfo gdi = new GanttDialogInfo(this,
212
GanttDialogInfo.ERROR,
GanttDialogInfo.YES_OPTION, language
}
} catch (AccessControlException e) {
// This can happen when running in a sandbox (Java
WebStart)
.getText("msg4"), language.getText("error"));
gdi.show();
System.err.println(e + ": " + e.getMessage());
return;
}
}
}
statusBar.setFirstText(GanttLanguage.getInstance().getText("o
pening")
/** Print the help for ganttproject on the system.out */
+ " www.ganttproject.org", 2000);
private static void usage() {
}
System.out.println();
// change by G. Herrmann
System.out
public void setAskForSave(boolean afs) {
.println("GanttProject usage : java -jar
ganttproject-(VERSION).jar <OPTIONS>");
if (isOnlyViewer)
System.out.println();
return;
System.out.println(" Here are the possible options:");
String title = getTitle();
System.out.println("
// String last = title.substring(title.length() - 11, title.length());
-h, --help : Print this message");
System.out
bSave.setEnabled(afs);
.println("
[project_file_name] a XML file
based on ganttproject format to directly open (project.xml or
project.gan)");
miSave.setEnabled(afs);
if (getTabs().getSelectedIndex() == UIFacade.GANTT_INDEX)
{
System.out
if (afs)
.println("
-html [project_file_name]
[export_directory_name], export directly a ganttproject file to
web pages");
bSaveCurrent.setEnabled(afs);
if (myPreviousStates.size() != 0)
System.out
bComparePrev.setEnabled(true);
}
.println("
-xsl-dir [xsl_directory]
localisation of the xsl directory for html export");
askForSave = afs;
System.out
try {
[pdf_file_name],
pages");
if (System.getProperty("mrj.version") != null) {
.println("
-pdf
[project_file_name]
export directly a ganttproject file to web
System.out
rootPane.putClientProperty("windowModified",
.println("
-xsl-fo [xsl_fo_file]
localisation of the xsl-fo file for pdf export");
Boolean
.valueOf(afs));
//
http://developer.apple.com/qa/qa2001/qa1146.html
System.out
see
} else {
if (askForSave) {
.println("
-csv
[project_file_name]
[csv_image_filename], export directly a ganttproject file to csv
document compatible with spreadsheets");
System.out
/*
setTitle(getTitle() + "
.println("
-png
[project_file_name]
[png_image_filename],
export directly a ganttproject file to
* if (!last.equals(" (modified)")) {png image");
* (modified)"); }
*/
.println("
-jpg
[project_file_name]
[jpg_image_filename], export directly a ganttproject file to jpg
image");
if (!title.endsWith(" *")) {
System.out
setTitle(getTitle() + " *");
}
}
System.out
.println("
-fig/-xfig [project_file_name]
[fig_image_filename], export directly a ganttproject file to xfig
image");
System.out.println();
System.out
213
.println("
In all these cases thereturn myPasteAction;
project_file_name can either be a file on local disk or an URL.");
}
System.out
.println("
If the URL is passwordprivate ResourceActionSet getResourceActions() {
protected, you can give credentials this way:");
if (myResourceActions == null) {
System.out
.println("
http://username:[email protected]/filename");
System.out.println(" ");
}
myResourceActions
ResourceActionSet((IGanttProject) this,
=
new
(ResourceContext)
getResourcePanel(), this);
}
return myResourceActions;
public GanttResourcePanel getResourcePanel() {
}
if (this.resp == null) {
this.resp = new GanttResourcePanel(this, getTree());
/** The main */
this.resp.setResourceActions(getResourceActions());
public static void main(String[] arg) {
// TODO pass
// resource
// actions
// // ------------------------------------------------------------
// created with
// List result = new ArrayList();
// resource
//
String
extensionPointID
"net.sourceforge.ganttproject.chart";
// panel as
// context
getHumanResourceManager().addView(this.resp);
}
return this.resp;
}
=
// IConfigurationElement[] configElements = Platform
// .getExtensionRegistry().getConfigurationElementsFor(
// extensionPointID);
// for (int i = 0; i < configElements.length; i++) {
// try {
// Object test = configElements[i]
// .createExecutableExtension("class");
public GanttLanguage getLanguage() {
return this.language;
}
// result.add(test);
// } catch (CoreException e) {
// e.printStackTrace();
public GanttGraphicArea getArea() {
// // throw new RuntimeException("Failed to instantiate chart",
e);
return this.area;
// }
}
// }
//
public GanttTree2 getTree() {
// // ------------------------------------------------------------
return this.tree;
}
if
(arg.length >
0
help".equals(arg[0]))) {
&&
("-h".equals(arg[0])
||
"--
// Help for the command line
public Action getCopyAction() {
usage();
return myCopyAction;
System.exit(0);
}
}
public Action getCutAction() {
return myCutAction;
}
/*
* 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
public Action getPasteAction() {
214
* new path as default.
/* Splash image */
*/
GanttSplash splash = new GanttSplash();
splash.setVisible(true);
/** Create main frame */
GanttOptions options = new GanttOptions(null, false);
GanttProject ganttFrame = new GanttProject(false, null);
ganttFrame.setVisible(true);
for (int i = 0; i < arg.length; i++) {
if (arg.length > 0) {
if (arg[i].equals("-xsl-dir") && (arg.length > i + 1)) {
options.setXslDir(arg[i + 1]);
// todo [bbaranne] remove this hack!!!
break;
if (!arg[0].equals("ganttproject-eclipsito-config.xml")
}
&& !arg[0].equals("-pdelaunch"))
}
ganttFrame.openStartupDocument(arg[0]);
for (int i = 0; i < arg.length; i++) {
} else {
if (arg[i].equals("-xsl-fo") && (arg.length > i + 1)) {
// ganttFrame.showNewProjectWizard();
options.setXslFo(arg[i + 1]);
}
break;
splash.close();
}
}
}
if (arg.length > 0
&&
("-html".equals(arg[0])
htm".equals(arg[0]) || "-export"
||
"-static boolean checkProjectFile(String[] arg) {
if (!(arg.length > 1)) {
.equals(arg[0]))) {
System.out.println("ERROR...\nMust pass a project
file");
if (checkProjectFile(arg))
return false;
exportProject(arg);
}
System.exit(0);
return true;
} else if (arg.length > 0 && "-pdf".equals(arg[0])) {
}
if (checkProjectFile(arg))
exportPDF(arg);
/**
System.exit(0);
* Possibility to export the project into HTML directly by
command Line From
} else if (arg.length > 0 && "-png".equals(arg[0])) {
if (checkProjectFile(arg))
* Dmitry Barashev
exportPNG(arg);
*/
System.exit(0);
private static void exportProject(String[] args) {
} else if (arg.length > 0 && "-jpg".equals(arg[0])) {
try {
if (checkProjectFile(arg))
byCommandLine = true;
exportJPG(arg);
GanttProject
System.exit(0);
} else if (arg.length > 0
&&
xfig".equals(arg[0]))) {
exportXFIG(arg);
||
"-
new
GanttProject(false,
if (args.length > 2)
exportPath = args[2];
else
exportPath = "htmlExport";
System.exit(0);
} else if (arg.length > 0 && ("-csv".equals(arg[0]))) {
if (checkProjectFile(arg))
File targetDir = new File(exportPath);
if (!targetDir.exists()) {
targetDir.mkdir();
exportCSV(arg);
}
=
String exportPath;
("-fig".equals(arg[0])
if (checkProjectFile(arg))
System.exit(0);
project
args[1]);
} else {
if (!targetDir.isDirectory()) {
215
throw
RuntimeException("File " + args[2]
directory");
newGanttProject project = new GanttProject(false, args[1]);
File targetFile = null;
+ " must be
if (args.length > 2)
targetFile = new File(args[2]);
}
}
ExportFileInfo info = new ExportFileInfo(targetFile,
System.out.println(targetDir.getAbsolutePath());
ExportFileInfo.FORMAT_PNG,
GanttExportSettings());
String index = project.getProjectName();
new
project.doExport(info);
if (index == null || index.length() == 0) {
}
index = new String("ganttproject");
} else {
/** Export directly in XFIG image */
index
project.getProjectName().toLowerCase();
=
private static void exportXFIG(String[] args) {
}
byCommandLine = true;
File targetFile = new File(targetDir, index + ".html");
GanttProject project = new GanttProject(false, args[1]);
System.err.println(targetFile.getAbsolutePath());
File targetFile = null;
if (!targetFile.exists()) {
if (args.length > 2)
targetFile = new File(args[2]);
targetFile.createNewFile();
}
ExportFileInfo info = new ExportFileInfo(targetFile,
ExportFileInfo info = new ExportFileInfo(targetFile,
ExportFileInfo.FORMAT_XFIG,
GanttExportSettings());
ExportFileInfo.FORMAT_HTML,
new GanttExportSettings());
project.doExport(info);
new
project.doExport(info);
}
} catch (IOException e) {
throw new RuntimeException("IO error", e);
/** Export directly in CSV image */
}
private static void exportCSV(String[] args) {
}
byCommandLine = true;
GanttProject project = new GanttProject(false, args[1]);
/** Possibility to export the project into PDF directly byFile targetFile = null;
command Line */
if (args.length > 2)
private static void exportPDF(String[] args) {
targetFile = new File(args[2]);
byCommandLine = true;
ExportFileInfo info = new ExportFileInfo(targetFile,
GanttProject project = new GanttProject(false, args[1]);
String exportFile;
ExportFileInfo.FORMAT_CSV,
GanttExportSettings());
if (args.length > 2)
project.doExport(info);
exportFile = args[2];
}
exportFile = "ganttproject.pdf";
/** Export directly in JPG image */
new
else
File targetFile = new File(exportFile);
private static void exportJPG(String[] args) {
ExportFileInfo info = new ExportFileInfo(targetFile,
byCommandLine = true;
ExportFileInfo.FORMAT_PDF,
GanttExportSettings());
project.doExport(info);
newGanttProject project = new GanttProject(false, args[1]);
File targetFile = null;
if (args.length > 2)
}
targetFile = new File(args[2]);
ExportFileInfo info = new ExportFileInfo(targetFile,
/** Export directly in PNG image */
private static void exportPNG(String[] args) {
ExportFileInfo.FORMAT_JPG,
GanttExportSettings());
byCommandLine = true;
project.doExport(info);
new
}
216
private
GPCalendar
WeekendCalendarImpl();
/**
myFakeCalendar
=
new
* The class able to export directly by command line From Dmitry
private final ZoomManager myZoomManager;
Barashev
*/
//
private
GPCalendar
myFakeCalendar
AlwaysWorkingTimeCalendarImpl();
public static class ExportFileInfo {
public final File myFile;
=
new
private final TimeUnitStack myTimeUnitStack;
public final int myFormat;
private ScrollingManager myScrollingManager;
public final GanttExportSettings myStorageOptions;
private DocumentManager myDocumentManager;
public static final int FORMAT_HTML = 1;
private ParserFactory myParserFactory;
public static final int FORMAT_PNG = 2;
private GPUndoManager myUndoManager;
public static final int FORMAT_JPG = 3;
private static WindowListener ourWindowListener;
public static final int FORMAT_PDF = 4;
// ///////////////////////////////////////////////////////
// IGanttProject implementation
public static final int FORMAT_XFIG = 5;
public String getProjectName() {
return prjInfos._sProjectName;
public static final int FORMAT_CSV = 6;
}
public static final int FORMAT_MSPROJECT = 7;
public void setProjectName(String projectName) {
public
static
final
ExportFileInfo(null, -1,
ExportFileInfo
EMPTY
=
prjInfos._sProjectName = projectName;
new
setAskForSave(true);
}
null);
public ExportFileInfo(File file, int format, GanttExportSettingspublic String getDescription() {
options) {
return prjInfos.getDescription();
myFile = file;
}
myFormat = format;
myStorageOptions = options;
}
public void setDescription(String description) {
prjInfos._sDescription = description;
}
setAskForSave(true);
}
public static final String HUMAN_RESOURCE_MANAGER_ID
= "HUMAN_RESOURCE";
public String getOrganization() {
// change
return prjInfos.getOrganization();
// to
}
// public
public void setOrganization(String organization) {
public
static
final
"ROLE_MANAGER";
String
ROLE_MANAGER_ID
=prjInfos._sOrganization = organization;
setAskForSave(true);
}
217
return myTimeUnitStack;
}
public String getWebLink() {
return prjInfos.getWebLink();
public GanttLanguage getI18n() {
}
return getLanguage();
}
public void setWebLink(String webLink) {
prjInfos._sWebLink = webLink;
setAskForSave(true);
public GPCalendar getActiveCalendar() {
}
return myFakeCalendar;
}
public ResourceManager getHumanResourceManager() {
ResourceManager result = (ResourceManager) managerHash public void setModified() {
setAskForSave(true);
.get(HUMAN_RESOURCE_MANAGER_ID);
}
if (result == null) {
result
=
new
HumanResourceManager(getRoleManager().getDefaultRole()); public void close() {
closeProject(false);
// result.addView(getPeople());
managerHash.put(HUMAN_RESOURCE_MANAGER }
_ID, result);
result.addView(this);
private DocumentManager getDocumentManager() {
}
if (myDocumentManager == null) {
return result;
myDocumentManager = new DocumentCreator(this,
getUIFacade(),
}
getParserFactory());
public TaskManager getTaskManager() {
}
return myTaskManager;
return myDocumentManager;
}
}
public RoleManager getRoleManager() {
private ParserFactory getParserFactory() {
RoleManager
result
=
managerHash.get(ROLE_MANAGER_ID);
(RoleManager)if (myParserFactory == null) {
myParserFactory = new ParserFactoryImpl();
if (result == null) {
}
result = RoleManager.Access.getInstance();
return myParserFactory;
managerHash.put(ROLE_MANAGER_ID, result);
}
}
return result;
public GPUndoManager getUndoManager() {
}
if (myUndoManager == null) {
public Document getDocument() {
myUndoManager
UndoManagerImpl((IGanttProject) this,
return projectDocument;
=
new
getParserFactory(),
getDocumentManager());
}
Mediator.registerUndoManager(myUndoManager);
}
public ZoomManager getZoomManager() {
return myZoomManager;
return myUndoManager;
}
}
// ///////////////////////////////////////////////////////////////
public TimeUnitStack getTimeUnitStack() {
218
}
// ResourceView implementation
public void resourceAdded(ResourceEvent event) {
public GPSaver newSaver() {
if (getStatusBar() != null) {
return
new
(GanttTree2) getTree(),
// tabpane.setSelectedIndex(1);
getStatusBar().setFirstText(
GanttXMLSaver(GanttProject.this,
getResourcePanel(),
GanttProject.correctLabel(GanttLanguage.getInstanc
e()
getArea(),
getUIFacade());
}
.getText("newHuman")), 2000);
}
setAskForSave(true);
refreshProjectInfos();
public void setRowHeight(int value) {
// setQuickSave (true);
tree.getTreeTable().getTable().setRowHeight(value);
}
}
}
public void changeOrder(DefaultListModel buttonList,
public void resourcesRemoved(ResourceEvent event) {
DefaultListModel deletedButtonList) {
// setQuickSave (true);
iconList = new DefaultListModel();
}
for (int i = 0; i < buttonList.size(); i++)
iconList.addElement(buttonList.getElementAt(i));
// ///////////////////////////////////////////////////////////////
deletedIconList = new DefaultListModel();
// UIFacade
for (int i = 0; i < deletedButtonList.size(); i++)
public UIFacade getUIFacade() {
return this;
deletedIconList.addElement(deletedButtonList.getEle
mentAt(i));
}
addButtons();
options.setIconList(getIconPositions(iconList));
public ScrollingManager getScrollingManager() {
options.setDeletedIconList(getIconPositions(deletedIconList));
if (myScrollingManager == null) {
setHiddens();
myScrollingManager
ScrollingManagerImpl(Mediator
newrefresh();
=
}
.getTaskSelectionManager());
}
private String getIconPositions(DefaultListModel list) {
return myScrollingManager;
String sIcons = "";
}
DefaultListModel iconListValues = new DefaultListModel();
if (list != null) {
public ChartViewState getGanttChartViewState() {
int i = 0;
return getArea().getViewState();
if (list.equals(deletedIconList))
}
i++;
for (; i < list.size(); i++) {
// public JTabbedPane getTabpane() {
if (!sIcons.equals(""))
// return getTabs();
sIcons = sIcons + ",";
// }
if (list.elementAt(i).equals(
private class ParserFactoryImpl implements ParserFactory {
public GPParser newParser() {
return new
getTaskManager(),
GanttXMLOpen(prjInfos,
getUIFacade());
language.getText("separator").toUpperCase()))
sIcons
=
sIcons
+
GanttOptions.SEPARATOR;
getArea(),
else
if
((TestGanttRolloverButton)
list.elementAt(i) == bExit)
219
sIcons
=
sIcons
GanttOptions.EXIT;
else
list.elementAt(i) == bNew)
if
sIcons
((TestGanttRolloverButton)
else
if
list.elementAt(i) == bUnlink)
=
sIcons
GanttOptions.NEW;
else
list.elementAt(i) == bOpen)
if
sIcons
if
sIcons
=
sIcons
sIcons
=
sIcons
sIcons
=
sIcons
sIcons
=
sIcons
if
sIcons
=
sIcons
sIcons
GanttOptions.PREVIEWPRINT;
else
list.elementAt(i) == bCut)
if
sIcons
=
sIcons
if
sIcons
=
sIcons
if
sIcons
=
sIcons
sIcons
=
sIcons
sIcons
GanttOptions.DELETE;
else
if
list.elementAt(i) == bProperties)
sIcons
if
sIcons
if
sIcons
if
sIcons
if
sIcons
if
sIcons
+
GanttOptions.NEXT;
sIcons
if
sIcons
+
GanttOptions.ZOOMOUT;
sIcons
((TestGanttRolloverButton)
else
if
list.elementAt(i) == bZoomIn)
=
sIcons
+
GanttOptions.ZOOMIN;
((TestGanttRolloverButton)
else
list.elementAt(i) == bUndo)
=
sIcons
GanttOptions.NEWTASK;
else
if
list.elementAt(i) == bDelete)
if
((TestGanttRolloverButton)
else
if
list.elementAt(i) == bZoomOut)
GanttOptions.PASTE;
else
if
list.elementAt(i) == bNewTask)
+
GanttOptions.CENTER;
((TestGanttRolloverButton)
else
list.elementAt(i) == bNext)
GanttOptions.COPY;
else
list.elementAt(i) == bPaste)
+
GanttOptions.PREV;
sIcons
((TestGanttRolloverButton)
else
if
list.elementAt(i) == bScrollCenter)
GanttOptions.CUT;
else
list.elementAt(i) == bCopy)
+
GanttOptions.DOWN;
((TestGanttRolloverButton)
else
list.elementAt(i) == bPrev)
GanttOptions.PRINT;
else
if
list.elementAt(i) == bPreviewPrint)
+
GanttOptions.UP;
((TestGanttRolloverButton)
else
list.elementAt(i) == bDown)
GanttOptions.EXPORT;
else
list.elementAt(i) == bPrint)
+
GanttOptions.UNIND;
((TestGanttRolloverButton)
else
list.elementAt(i) == bUp)
GanttOptions.IMPORT;
else
if
list.elementAt(i) == bExport)
+
GanttOptions.IND;
((TestGanttRolloverButton)
else
list.elementAt(i) == bUnind)
GanttOptions.SAVEAS;
else
if
list.elementAt(i) == bImport)
+
GanttOptions.LINK;
((TestGanttRolloverButton)
else
list.elementAt(i) == bInd)
GanttOptions.SAVE;
else
if
list.elementAt(i) == bSaveAs)
+
GanttOptions.UNLINK;
((TestGanttRolloverButton)
else
list.elementAt(i) == bLink)
GanttOptions.OPEN;
else
list.elementAt(i) == bSave)
+
sIcons
GanttOptions.PROPERTIES;
+
GanttOptions.UNDO;
((TestGanttRolloverButton)
else
list.elementAt(i) == bRedo)
=
sIcons
+
GanttOptions.REDO;
sIcons
if
sIcons
if
sIcons
((TestGanttRolloverButton)
else
if
list.elementAt(i) == bCritical)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
=
sIcons
+
((TestGanttRolloverButton)
220
sIcons
=
sIcons
+case (GanttOptions.NEW):
GanttOptions.CRITICAL;
else
list.elementAt(i) == bAbout)
list.addElement(bNew);
if
((TestGanttRolloverButton)
sIcons
=
sIcons
GanttOptions.ABOUT;
else
if
list.elementAt(i) == bSaveCurrent)
+case (GanttOptions.OPEN):
list.addElement(bOpen);
((TestGanttRolloverButton)
sIcons
GanttOptions.SAVECURRENT;
=
sIcons
break;
break;
case (GanttOptions.SAVE):
+
list.addElement(bSave);
break;
else
if
((TestGanttRolloverButton)
list.elementAt(i) == bComparePrev)
case (GanttOptions.SAVEAS):
sIcons
=
sIcons
+
list.addElement(bSaveAs);
GanttOptions.COMPAREPREV;
break;
else
if
((TestGanttRolloverButton)
list.elementAt(i) == bRefresh)
case (GanttOptions.IMPORT):
sIcons
=
sIcons
+
GanttOptions.REFRESH;
list.addElement(bImport);
break;
}
case (GanttOptions.EXPORT):
}
list.addElement(bExport);
return sIcons;
break;
}
case (GanttOptions.PRINT):
public DefaultListModel initIconList() {
DefaultListModel list = new DefaultListModel();
int[] icons = options.getIconList();
for (int i = 0; i < icons.length; i++)
addButton(icons[i], list);
list.addElement(bPrint);
break;
case (GanttOptions.PREVIEWPRINT):
list.addElement(bPreviewPrint);
break;
case (GanttOptions.CUT):
return list;
list.addElement(bCut);
}
break;
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);
case (GanttOptions.COPY):
list.addElement(bCopy);
break;
case (GanttOptions.PASTE):
list.addElement(bPaste);
break;
case (GanttOptions.NEWTASK):
}
list.addElement(bNewTask);
return list;
break;
}
case (GanttOptions.DELETE):
public void addButton(int icon, DefaultListModel list) {
switch (icon) {
case (GanttOptions.SEPARATOR):
list.addElement(language.getText("separator").toUpp
erCase());
break;
case (GanttOptions.EXIT):
list.addElement(bExit);
break;
list.addElement(bDelete);
break;
case (GanttOptions.PROPERTIES):
list.addElement(bProperties);
break;
case (GanttOptions.UNLINK):
list.addElement(bUnlink);
break;
case (GanttOptions.LINK):
221
break;
list.addElement(bLink);
break;
case (GanttOptions.REFRESH):
list.addElement(bRefresh);
case (GanttOptions.IND):
break;
list.addElement(bInd);
break;
default:
break;
case (GanttOptions.UNIND):
list.addElement(bUnind);
}
break;
}
case (GanttOptions.UP):
list.addElement(bUp);
public void addButtons() {
break;
toolBar.removeAll();
case (GanttOptions.DOWN):
for (int i = 0; i < iconList.size(); i++) {
if (iconList.elementAt(i).equals(
list.addElement(bDown);
break;
language.getText("separator").toUpperCase())) {
case (GanttOptions.PREV):
list.addElement(bPrev);
break;
case (GanttOptions.CENTER):
int
size
Integer.parseInt(options.getIconSize());
//
Dimension(size, size));
toolBar.addSeparator(new
ImageIcon icon;
list.addElement(bScrollCenter);
break;
ImageIcon
iconV
ImageIcon(getClass().getResource(
case (GanttOptions.NEXT):
list.addElement(bNext);
break;
break;
ImageIcon
iconH
ImageIcon(getClass().getResource(
if
JToolBar.HORIZONTAL)
=
new
(toolBar.getOrientation()
==
icon = iconV;
else
list.addElement(bZoomIn);
icon = iconH;
break;
toolBar.add(new JLabel(icon));
case (GanttOptions.UNDO):
} else {
list.addElement(bUndo);
toolBar.add((JButton) iconList.elementAt(i));
break;
}
case (GanttOptions.REDO):
break;
new
"/icons/sepH_16.png"));
case (GanttOptions.ZOOMIN):
list.addElement(bRedo);
=
"/icons/sepV_16.png"));
case (GanttOptions.ZOOMOUT):
list.addElement(bZoomOut);
=
}
}
case (GanttOptions.CRITICAL):
list.addElement(bCritical);
break;
case (GanttOptions.ABOUT):
public DefaultListModel getButtonList() {
return iconList;
}
list.addElement(bAbout);
break;
case (GanttOptions.SAVECURRENT):
list.addElement(bSaveCurrent);
public DefaultListModel getDeletedButtonList() {
return deletedIconList;
}
break;
case (GanttOptions.COMPAREPREV):
list.addElement(bComparePrev);
public Chart getActiveChart() {
Chart resourcesChart = getResourceChart();
222
recalculateCriticalPath();
Chart ganttChart = getGanttChart();
Chart visibleChart = (getTabs().getSelectedIndex()
UIFacade.RESOURCES_INDEX) ? resourcesChart
==
try {
: ganttChart;
getTaskManager().getAlgorithmCollection()
return visibleChart;
.getRecalculateTaskScheduleAlgorithm().run();
}
} catch (TaskDependencyException e) {
public Chart getGanttChart() {
// TODO Auto-generated catch block
return (Chart) getArea();
e.printStackTrace();
}
}
public Chart getResourceChart() {
getResourcePanel().getResourceTreeTableModel().updateRes
ources();
return (Chart) getResourcePanel().area;
getResourcePanel().getResourceTreeTable().setRowHeight(20
);
}
myDelayManager.fireDelayObservation();
super.repaint();
public void setStatusText(String text) {
}
statusBar.setFirstText(text, 2000);
}
public void recalculateCriticalPath() {
if (myUIConfiguration.isCriticalPathOn()) {
public void repaint2() {
// try
getTaskManager().processCriticalPath((TaskNode)
tree.getRoot());
// {
ArrayList projectTasks = tree.getProjectTasks();
// Thread.sleep(10);
if (projectTasks.size() != 0) {
for (int i = 0; i < projectTasks.size(); i++)
// }
// catch (InterruptedException e2)
getTaskManager().processCriticalPath(
// {
(TaskNode)
// // TODO Auto-generated catch block
projectTasks.get(i));
// e2.printStackTrace();
}
// }
repaint();
try {
}
getTaskManager().getAlgorithmCollection()
.getRecalculateTaskScheduleAlgorithm().run();
}
public int getViewIndex() {
if (getTabs() == null)
// there was a bug when importing a project where a
FF dependency
// was under a supertask.
return -1;
return getTabs().getSelectedIndex();
// The supertask length was calculated as if it was a}
FS dependency.
List l = tree.getAllGanttTasks();
public void setViewIndex(int viewIndex) {
Task[] t = new Task[l.size()];
if (myTabPane.getTabCount() > viewIndex)
l.toArray(t);
getTaskManager().getAlgorithmCollection()
myTabPane.setSelectedIndex(viewIndex);
}
.getAdjustTaskBoundsAlgorithm().run(t);
} catch (TaskDependencyException e1) {
e1.printStackTrace();
}
public
static
void
windowListener) {
setWindowListener(WindowListener
ourWindowListener = windowListener;
}
223
// }
public int getGanttDividerLocation() {
//
return mySplitPane.getDividerLocation();
// public void mouseEntered(MouseEvent arg0) {
}
// // TODO Auto-generated method stub
//
public void setGanttDividerLocation(int location) {
// }
mySplitPane.setDividerLocation(location);
//
}
// public void mouseExited(MouseEvent arg0) {
// // TODO Auto-generated method stub
public int getResourceDividerLocation() {
//
return getResourcePanel().getDividerLocation();
// }
}
//
// public void mousePressed(MouseEvent arg0) {
public void setResourceDividerLocation(int location) {
// System.out.println("mousePressed");
getResourcePanel().setDividerLocation(location);
//
}
// }
//
public void refresh() {
// public void mouseReleased(MouseEvent arg0) {
// // -------------------------
// // TODO Auto-generated method stub
//
//
// Component glassPane = this.getGlassPane();
// }
// setGlassPane(glassPane);
// });
// glassPane.setVisible(true); // before worker thread
//
//
// // -------------------------
// glassPane.addKeyListener(new KeyListener() {
//
try {
getTaskManager().getAlgorithmCollection()
// public void keyPressed(KeyEvent arg0) {
// System.out.println("keyPressed");
.getRecalculateTaskScheduleAlgorithm().run();
//
// }
List l = tree.getAllGanttTasks();
//
Task[] t = new Task[l.size()];
// public void keyReleased(KeyEvent arg0) {
l.toArray(t);
// System.out.println("keyReleased");
getTaskManager().getAlgorithmCollection()
//
// }
.getAdjustTaskBoundsAlgorithm().run(t);
//
// public void keyTyped(KeyEvent arg0) {
for (int i = 0; i < t.length; i++)
// System.out.println("keyTyped");
getTaskManager().getAlgorithmCollection()
//
// }
.getRecalculateTaskCompletionPercentageAlgorithm(
).run(
// });
t[i]);
// glassPane.addMouseListener(new MouseListener() {
//
} catch (TaskDependencyException e1) {
// public void mouseClicked(MouseEvent arg0) {
// // TODO Auto-generated method stub
e1.printStackTrace();
}
//
224
getTaskManager().processCriticalPath((TaskNode)
tree.getRoot());
ArrayList projectTasks = tree.getProjectTasks();
if (projectTasks.size() != 0) {
int position = 10;
// searching for hidden buttons
for (int i = 0; i < buttons.length; i++) {
for (int i = 0; i < projectTasks.size(); i++)
getTaskManager().processCriticalPath(
(TaskNode)
projectTasks.get(i));
if
(buttons[i].getClass()
TestGanttRolloverButton.class) {
==
if
JToolBar.HORIZONTAL)
==
}
(toolBar.getOrientation()
buttonSize
=
buttonSize
=
buttons[i].getWidth();
else
try {
getTaskManager().getAlgorithmCollection()
buttons[i].getHeight();
position = position + buttonSize;
.getRecalculateTaskScheduleAlgorithm().run();
if (position + 2 * bShowHiddens.getWidth() /
} catch (TaskDependencyException e) {
3 < toolBarlength) {
e.printStackTrace();
lastDisplayedIndex = i;
}
} else {
menu.add(buttons[i]);
getResourcePanel().getResourceTreeTableModel().updateRes
ources();
}
} else
getResourcePanel().getResourceTreeTable().setRowHeight(20
);
position = position + separatorSize;
}
if (myDelayManager != null)
myDelayManager.fireDelayObservation();
super.repaint();
// if there is hidden buttons
}
if (menu.getComponentCount() != 0) {
for (int i = lastDisplayedIndex + 1; i < buttons.length;
public void showHiddenButtonsPaneMenu() {
i++) {
toolBar.remove(buttons[i]);
menu.applyComponentOrientation(language.getComponentOri
entation());
menu.show(toolBar,
bShowHiddens.getY());
}
bShowHiddens.getX(),
}
toolBar.add(bShowHiddens);
}
}
}
public void setHiddens() {
menu.removeAll();
addButtons();
int separatorSize = Integer.parseInt(options.getIconSize());
net.sourceforge.ganttproject.pars
er
TaskTagHandler
package net.sourceforge.ganttproject.parser;
double toolBarlength = 0.;
int buttonSize = 0;
int lastDisplayedIndex = 0;
Component[] buttons = toolBar.getComponents();
import java.awt.Color;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Stack;
if (toolBar.getOrientation() == JToolBar.HORIZONTAL)
toolBarlength = toolBar.getSize().getWidth();
else
import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttTask;
toolBarlength = toolBar.getSize().getHeight();
225
task = getManager().createTask(taskId);
import net.sourceforge.ganttproject.shape.ShapePaint;
import net.sourceforge.ganttproject.task.Task;
}
import
net.sourceforge.ganttproject.task.TaskContainmentHierarchyFa
cade;
//
import net.sourceforge.ganttproject.task.TaskManager;
if (taskName != null) {
String taskName = attrs.getValue("name");
task.setName(taskName);
import org.xml.sax.Attributes;
}
public class TaskTagHandler implements TagHandler {
String meeting = attrs.getValue("meeting");
public TaskTagHandler(TaskManager
context) {
if (meeting != null) {
mgr,
ParsingContext
task.setMilestone(meeting.equals("true"));
myManager = mgr;
}
myContext = context;
}
String project = attrs.getValue("project");
if (project != null)
public void startElement(String namespaceURI, String sName,
String qName,
task.setProjectTask(true);
Attributes attrs) {
String start = attrs.getValue("start");
if (qName.equals("task")) {
if (start != null) {
loadTask(attrs);
}
task.setStart(GanttCalendar.parseXMLDate(start));
}
}
/** Method when finish to parse an attibute */
String duration = attrs.getValue("duration");
public void endElement(String namespaceURI, String sName,
String qName) {
if (duration != null) {
try {
if (qName.equals("task")) {
int
myStack.pop();
length
=
Integer.parseInt(duration);
}
if (length == 0) {
}
length = 1;
}
private void loadTask(Attributes attrs) {
task.setLength(length);
String taskIdAsString = attrs.getValue("id");
GanttTask task = null;
} catch (NumberFormatException e) {
throw
RuntimeException("Failed to parse the value '"
if (taskIdAsString == null) {
task = getManager().createTask();
new
+ duration + "'
of attribute 'duration' of tag <task>",
} else {
e);
int taskId;
}
try {
}
taskId
Integer.parseInt(taskIdAsString);
=
//LH
} catch (NumberFormatException e) {
throw
RuntimeException("Failed to parse the value '"
new
if (budget != null) {
+
taskIdAsString + "' of attribute 'id' of tag <task>",
e);
}
String budget = attrs.getValue("budget");
try {
task.setBudget(Double.parseDouble(budget));
} catch (NumberFormatException e) {
226
new//
throw
RuntimeException("Failed to parse the value '"
//
task.setFinishFixed(true);
}
+ budget + "'
of attribute 'budget' of tag <task>",
String third = attrs.getValue("thirdDate");
e);
if (third != null) {
}
}
task.setThirdDate(GanttCalendar.parseXMLDate(third
));
}
String complete = attrs.getValue("complete");
String thirdConstraint = attrs.getValue("thirdDateconstraint");
if (complete != null) {
try {
if (thirdConstraint != null) {
try {
task.setCompletionPercentage(Integer.parseInt(comp
lete));
task.setThirdDateConstraint(Integer.parseInt(thirdCon
} catch (NumberFormatException e) {
straint));
new
throw
RuntimeException("Failed to parse the value '"
} catch (NumberFormatException e) {
throw new RuntimeException(
+ complete +
"' of attribute 'complete' of tag <task>",
"Failed
to
parse the value '"
e);
}
+ thirdConstraint
}
+ "' of attribute 'thirdDate-constraint' of tag <task>",
String priority = attrs.getValue("priority");
e);
if (priority != null) {
}
try {
}
task.setPriority(Integer.parseInt(priority));
String webLink_enc = attrs.getValue("webLink");
} catch (NumberFormatException e) {
throw
RuntimeException("Failed to parse the value '"
new
String webLink = webLink_enc;
if (webLink_enc != null)
try {
+ priority + "'
of attribute 'priority' of tag <task>",
e);
webLink
URLDecoder.decode(webLink_enc, "ISO-8859-1");
=
} catch (UnsupportedEncodingException e)
}
{
}
e.printStackTrace();
}
String color = attrs.getValue("color");
if (color != null) {
if (webLink != null) {
task.setWebLink(webLink);
task.setColor(ColorValueParser.parseString(color));
}
}
String expand = attrs.getValue("expand");
String fixedStart = attrs.getValue("fixed-start");
if (expand != null) {
task.setExpand("true".equals(expand));
if ("true".equals(fixedStart)) {
task.setStartFixed(true);
}
}
String shape = attrs.getValue("shape");
//
String fixedFinish = attrs.getValue("fixed-finish");
//
if ("true".equals(fixedFinish)) {
if (shape != null) {
227
java.util.StringTokenizer
java.util.StringTokenizer(
st1
=
newimport java.io.InputStream;
import java.io.OutputStream;
shape, ",");
0, 0, 0, 0 };
int[] array = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
import net.sourceforge.ganttproject.GanttProject;
String token = "";
import net.sourceforge.ganttproject.GanttTree2;
int count = 0;
import net.sourceforge.ganttproject.IGanttProject;
while (st1.hasMoreTokens()) {
token = st1.nextToken();
array[count]
=
Integer(token)).intValue();
count++;
import net.sourceforge.ganttproject.calendar.GPCalendar;
import net.sourceforge.ganttproject.gui.UIFacade;
(newimport net.sourceforge.ganttproject.language.GanttLanguage;
import
net.sourceforge.ganttproject.parser.AllocationTagHandler;
import
net.sourceforge.ganttproject.parser.BlankLineTagHandler;
task.setShape(new ShapePaint(4, 4, array,
import
net.sourceforge.ganttproject.parser.CustomPropertiesTagHandl
.getColor()));
er;
}
Color.white, task
}
import
net.sourceforge.ganttproject.parser.DefaultWeekTagHandler;
import
net.sourceforge.ganttproject.parser.DependencyTagHandler;
TaskContainmentHierarchyFacade taskHierarchy =import net.sourceforge.ganttproject.parser.CostTagHandler;
getManager()
import net.sourceforge.ganttproject.parser.GPParser;
.getTaskHierarchy();
import net.sourceforge.ganttproject.parser.ParserFactory;
myContext.setTaskID(task.getTaskID());
import
Task
lastTask
=
myStack.isEmpty()
?net.sourceforge.ganttproject.parser.PreviousStateTasksTagHan
taskHierarchy.getRootTask()
dler;
: (Task) myStack.peek();
import
getManager().registerTask(task);
taskHierarchy.move(task, lastTask);
net.sourceforge.ganttproject.parser.ResourceTagHandler;
myStack.push(task);
import net.sourceforge.ganttproject.parser.RoleTagHandler;
import
net.sourceforge.ganttproject.parser.TaskDisplayColumnsTagHa
ndler;
}
private TaskManager getManager() {
return myManager;
}
import
net.sourceforge.ganttproject.parser.TaskPropertiesTagHandler;
import net.sourceforge.ganttproject.parser.TaskTagHandler;
import net.sourceforge.ganttproject.parser.VacationTagHandler;
private final ParsingContext myContext;
private final TaskManager myManager;
import net.sourceforge.ganttproject.parser.ViewTagHandler;
import
net.sourceforge.ganttproject.resource.HumanResourceManage
r;
import
net.sourceforge.ganttproject.resource.ResourceManager;
private final Stack myStack = new Stack();
}
net.sourceforge.ganttproject.
document.ProxyDocument
import net.sourceforge.ganttproject.roles.RoleManager;
import net.sourceforge.ganttproject.task.TaskManager;
/**
* @author bard
*/
package net.sourceforge.ganttproject.document;
class ProxyDocument implements Document {
private final Document myPhysicalDocument;
import java.io.IOException;
private IGanttProject myProject;
228
}
private UIFacade myUIFacade;
public String getPath() {
return myPhysicalDocument.getPath();
private ParserFactory myParserFactory;
}
private boolean isLoaded;
public String getFilePath() {
ProxyDocument(Document
project,
physicalDocument,
UIFacade
uiFacade,
IGanttProject
return myPhysicalDocument.getFilePath();
}
ParserFactory
parserFactory) {
myPhysicalDocument = physicalDocument;
public String getURLPath() {
return myPhysicalDocument.getURLPath();
myProject = project;
myUIFacade = uiFacade;
}
myParserFactory = parserFactory;
}
public String getUsername() {
public String getDescription() {
}
return myPhysicalDocument.getUsername();
return myPhysicalDocument.getDescription();
public String getPassword() {
}
return myPhysicalDocument.getPassword();
public boolean canRead() {
}
return myPhysicalDocument.canRead();
public void setUserInfo(String user, String pass) {
}
myPhysicalDocument.setUserInfo(user, pass);
public boolean canWrite() {
}
return myPhysicalDocument.canWrite();
}
public String getLastError() {
public boolean isValidForMRU() {
}
return myPhysicalDocument.getLastError();
return myPhysicalDocument.isValidForMRU();
public void read() throws IOException {
}
FailureState failure = new FailureState();
SuccessState success = new SuccessState();
public boolean acquireLock() {
return myPhysicalDocument.acquireLock();
}
ParsingState parsing = new ParsingState(success,
failure);
OpenCopyConfirmationState
OpenCopyConfirmationState(
}
=
new
parsing, failure);
public void releaseLock() {
myPhysicalDocument.releaseLock();
confirmation
AcquireLockState
lock
AcquireLockState(parsing, confirmation);
=
new
lock.enter();
public InputStream getInputStream() throws IOException {
}
return myPhysicalDocument.getInputStream();
private TaskManager getTaskManager() {
}
return myProject.getTaskManager();
public OutputStream getOutputStream() throws IOException {
}
return myPhysicalDocument.getOutputStream();
229
FailureState myExitState;
private RoleManager getRoleManager() {
return myProject.getRoleManager();
/**
}
* @param parsing
private
getHumanResourceManager() {
HumanResourceManager
* @param failure
*/
return
(HumanResourceManager)
public
myProject.getHumanResourceManager();
parsing,
}
OpenCopyConfirmationState(ParsingState
FailureState failure) {
myParsingState = parsing;
private GPCalendar getActiveCalendar() {
myExitState = failure;
return myProject.getActiveCalendar();
}
}
void enter() throws IOException {
private UIFacade getUIFacade() {
return myUIFacade;
}
String
message
GanttLanguage.getInstance().getText("msg13");
=
String
title
GanttLanguage.getInstance().getText("warning");
=
if
(getUIFacade().showConfirmationDialog(message, title)) {
class AcquireLockState {
OpenCopyConfirmationState myConfirmationState;
myParsingState.enter();
} else {
ParsingState myParsingState;
myExitState.enter();
}
/**
}
* @param parsing
}
* @param confirmation
*/
class ParsingState {
public AcquireLockState(ParsingState parsing,
FailureState myFailureState;
OpenCopyConfirmationState
confirmation) {
myParsingState = parsing;
SuccessState mySuccessState;
myConfirmationState = confirmation;
/**
}
* @param success
void enter() throws IOException {
boolean locked = acquireLock();
if (!locked) {
* @param failure
*/
public
ParsingState(SuccessState
FailureState failure) {
myConfirmationState.enter();
success,
mySuccessState = success;
} else {
myFailureState = failure;
myParsingState.enter();
}
}
}
void enter() throws IOException {
}
GPParser
myParserFactory.newParser();
class OpenCopyConfirmationState {
ResourceManager
getHumanResourceManager();
ParsingState myParsingState;
RoleManager
opener
hrManager
roleManager
=
=
=
getRoleManager();
230
TaskManager
taskManager
=
.getTreeTable());
getTaskManager();
ResourceTagHandler
new ResourceTagHandler(
resourceHandler
=
opener.addTagHandler(taskDisplayHandler);
hrManager,
roleManager);
opener.addTagHandler(taskHandler);
DependencyTagHandler
dependencyHandler = new DependencyTagHandler(
opener.addTagHandler(blankLineHandler);
opener.getContext(),
taskManager);
opener.addParsingListener(taskPropHandler);
//LH
CostTagHandler
costHandler
=
new
CostTagHandler(
opener.getContext(),
opener.addParsingListener(taskDisplayHandler);
opener.addParsingListener(customPropHandler);
taskManager);
AllocationTagHandler allocationHandler =
new AllocationTagHandler(
opener.addTagHandler(opener.getDefaultTagHandler
hrManager,
());
getTaskManager(), getRoleManager());
VacationTagHandler
new VacationTagHandler(
vacationHandler
opener.addTagHandler(resourceHandler);
=
opener.addTagHandler(dependencyHandler);
hrManager);
//LH
PreviousStateTasksTagHandler
previousStateHandler = new PreviousStateTasksTagHandler(
opener.addTagHandler(costHandler);
((GanttProject)
opener.addTagHandler(allocationHandler);
myProject).getPreviouStates());
RoleTagHandler
RoleTagHandler(roleManager);
rolesHandler
=
new
TaskTagHandler taskHandler
TaskTagHandler(taskManager, opener
=
new
opener.addParsingListener(allocationHandler);
opener.addTagHandler(vacationHandler);
opener.addTagHandler(previousStateHandler);
.getContext());
opener.addTagHandler(rolesHandler);
BlankLineTagHandler blankLineHandler =
new BlankLineTagHandler(myUIFacade.getTree());
DefaultWeekTagHandler
new DefaultWeekTagHandler(
weekHandler
opener.addTagHandler(weekHandler);
opener.addTagHandler(viewHandler);
=
//LH
getActiveCalendar());
ViewTagHandler
ViewTagHandler(getUIFacade());
viewHandler
=
opener.addParsingListener(costHandler);
new
opener.addParsingListener(dependencyHandler);
opener.addParsingListener(resourceHandler);
TaskPropertiesTagHandler
taskPropHandler = new TaskPropertiesTagHandler(
if (opener.load(getInputStream())) {
((GanttTree2)
mySuccessState.enter();
((GanttProject) myProject).getTree())
} else {
.getTreeTable());
myFailureState.enter();
opener.addTagHandler(taskPropHandler);
}
CustomPropertiesTagHandler
customPropHandler = new CustomPropertiesTagHandler(
opener.getContext(),
}
}
getTaskManager());
class SuccessState {
opener.addTagHandler(customPropHandler);
void enter() {
TaskDisplayColumnsTagHandler
taskDisplayHandler = new TaskDisplayColumnsTagHandler(
ProxyDocument.this.setLoaded(true);
}
((GanttTree2)
((GanttProject) myProject).getTree())
}
231
public boolean bExportResourceMail = true;
class FailureState {
void enter() {
public boolean bExportResourcePhone = true;
}
public boolean bExportResourceRole = true;
}
public boolean bFixedSize = false;
private void setLoaded(boolean b) {
isLoaded = b;
public String sSeparatedChar = ",";
}
public String sSeparatedTextChar = "\"";
}
net.sourceforge.ganttproject.io.
CSVOptions
/** @return the csv settings as an xml schema. */
public String getXml() {
String res = "
package net.sourceforge.ganttproject.io;
// general options
res += "
/**
* @author athomas Settings for exporting in csv format
*/
public class CSVOptions {
<csv-export>\n";
res += "
<csv-general \n";
fixed=\"" + bFixedSize + "\"\n";
res += "
correct(sSeparatedChar) + "\"\n";
res += "
correct(sSeparatedTextChar)
public boolean bExportTaskID = true;
separatedChar=\""
+
separatedTextChar=\"" +
+ "\"/>\n";
public boolean bExportTaskName = true;
// tasks export options
res += "
public boolean bExportTaskStartDate = true;
public boolean bExportTaskEndDate = true;
<csv-tasks\n";
res += "
id=\"" + bExportTaskID + "\"\n";
res += "
name=\"" + bExportTaskName + "\"\n";
res += "
start-date=\"" + bExportTaskStartDate +
res += "
end-date=\"" + bExportTaskEndDate +
res += "
percent=\"" + bExportTaskPercent +
res += "
duration=\"" + bExportTaskDuration +
"\"\n";
public boolean bExportTaskPercent = true;
public boolean bExportTaskDuration = true;
//LH
"\"\n";
"\"\n";
"\"\n";
//LH
public boolean bExportTaskBudget = true;
public boolean bExportTaskWebLink = true;
public boolean bExportTaskResources = true;
res += "
budget=\"" + bExportTaskBudget + "\"\n";
res += "
webLink=\"" + bExportTaskWebLink +
res += "
resources=\"" + bExportTaskResources
"\"\n";
+ "\"\n";
res += "
notes=\"" + bExportTaskNotes + "\"/>\n";
public boolean bExportTaskNotes = true;
// resources export options
res += "
public boolean bExportResourceID = true;
res += "
res += "
public boolean bExportResourceName = true;
<csv-resources\n";
id=\"" + bExportResourceID + "\"\n";
name=\"" + bExportResourceName +
"\"\n";
res += "
mail=\"" + bExportResourceMail + "\"\n";
232
res += "
phone=\"" + bExportResourcePhone +*/
"\"\n";
public class GanttCSVExport {
role=\"" + bExportResourceRole +
// private GanttTree tree;
res += "
"\"/>\n";
// private GanttResourcePanel peop;
return res += "
</csv-export>\n";
private CSVOptions csvOptions;
}
private HumanResourceManager myHrManager;
public String correct(String s) {
String res;
// ArrayList lot = new ArrayList();
res = s.replaceAll("&", "&#38;");
Task[] myTasks;
res = res.replaceAll("<", "&#60;");
res = res.replaceAll(">", "&#62;");
ArrayList resources = new ArrayList();
res = res.replaceAll("/", "&#47;");
res = res.replaceAll("\"", "&#34;");
int iMaxSize = 0;
return res;
}
boolean bFixedSize = false;
/** @return a list of the possible separated char. */
/** Constructor. */
public String[] getSeparatedTextChars() {
public GanttCSVExport(IGanttProject
csvOptions) {
String[] charText = { " \' ", " \" " };
return charText;
}
package net.sourceforge.ganttproject.io;
CSVOptions
myTasks = project.getTaskManager().getTasks();
myHrManager
=
(HumanResourceManager)
project.getHumanResourceManager();
}
net.sourceforge.ganttproject.io.
GanttCSVExport
project,
this.csvOptions = csvOptions;
}
/** Save the project as CSV on a stream */
public void save(OutputStream stream) {
try {
import java.io.IOException;
import java.io.OutputStream;
OutputStreamWriter
OutputStreamWriter(stream);
out
=
new
beginToSave(out);
import java.io.OutputStreamWriter;
out.close();
import java.util.ArrayList;
} catch (IOException e) {
import net.sourceforge.ganttproject.GanttTask;
System.out.println("Error in saving the csv
file");
import net.sourceforge.ganttproject.IGanttProject;
} catch (Exception e) {
import net.sourceforge.ganttproject.resource.HumanResource;
System.out.println(e);
import
net.sourceforge.ganttproject.resource.HumanResourceManage
r;
import net.sourceforge.ganttproject.roles.Role;
e.printStackTrace();
}
}
import net.sourceforge.ganttproject.task.ResourceAssignment;
import net.sourceforge.ganttproject.task.Task;
/**
/** Start saving the csv document. */
public void beginToSave(OutputStreamWriter
IOException {
* @author athomas Class to export the project in cvs text
format
out)
throws
resources = myHrManager.getResources();
233
+ (bFixedSize
bFixedSize = csvOptions.bFixedSize;
? "" : csvOptions.sSeparatedChar));
if (csvOptions.bFixedSize)
// End Date
getMaxSize();
if (csvOptions.bExportTaskEndDate)
/*
out.write(correctField(task.getEnd().toString())
* writeProjectInfos(out); out.write("\n");
+ (bFixedSize
? "" : csvOptions.sSeparatedChar));
*/
writeTasks(out);
// Duration
out.write("\n");
if (csvOptions.bExportTaskDuration)
out.write(correctField(""
task.getDuration().getLength())
writeResources(out);
out.write("\n");
+
+ (bFixedSize
}
? "" : csvOptions.sSeparatedChar));
/** Write the project information on the file. */
//LH
private void writeProjectInfos(OutputStreamWriter out) throws
IOException {
// Duration
if (csvOptions.bExportTaskBudget)
out.write(correctField(""
}
+
task.getBudget())
+ (bFixedSize
? "" : csvOptions.sSeparatedChar));
/** Write all tasks. */
private void
IOException {
writeTasks(OutputStreamWriter
out)
throws
// Percent complete
// parse all tasks
if (csvOptions.bExportTaskPercent)
for (int i = 0; i < myTasks.length; i++) {
out.write(correctField(""
task.getCompletionPercentage())
Task task = myTasks[i];
+
+ (bFixedSize
// ID
? "" : csvOptions.sSeparatedChar));
if (csvOptions.bExportTaskID)
out.write(correctField(""
+
task.getTaskID())
+ (bFixedSize
? "" : csvOptions.sSeparatedChar));
// Web Link
if (csvOptions.bExportTaskWebLink)
out.write((bFixedSize
csvOptions.sSeparatedTextChar)
?
""
:
+
// Name
correctField(getWebLink((GanttTask) task))
if (csvOptions.bExportTaskName)
out.write((bFixedSize
csvOptions.sSeparatedTextChar)
+ (bFixedSize
?
""
:? "" : csvOptions.sSeparatedTextChar
+
+ csvOptions.sSeparatedChar));
correctField(getName(task))
+ (bFixedSize
? "" : csvOptions.sSeparatedTextChar
// associated resources
if (csvOptions.bExportTaskResources) {
+ csvOptions.sSeparatedChar));
// Start Date
if (csvOptions.bExportTaskStartDate)
out.write((bFixedSize
csvOptions.sSeparatedTextChar));
?
""
:
""
:
out.write(correctField(getAssignments(task)));
out.write((bFixedSize
csvOptions.sSeparatedTextChar
out.write(correctField(task.getStart().toString())
?
+
csvOptions.sSeparatedChar));
234
}
if (csvOptions.bExportResourcePhone)
out.write((bFixedSize
csvOptions.sSeparatedTextChar)
// Notes
""
:
+
if (csvOptions.bExportTaskNotes)
out.write((bFixedSize
csvOptions.sSeparatedTextChar)
?
correctField(p.getPhone())
?
""
:
+ (bFixedSize
? "" : csvOptions.sSeparatedTextChar
+
correctField(task.getNotes())
+ csvOptions.sSeparatedChar));
+ (bFixedSize
// Role
? "" : csvOptions.sSeparatedTextChar
if (csvOptions.bExportResourcePhone) {
+ csvOptions.sSeparatedChar));
Role role = p.getRole();
String sRoleID = "0";
out.write("\n");
if (role != null)
}
sRoleID
=
role.getPersistentID();
} // end of write tasks
out.write((bFixedSize
csvOptions.sSeparatedTextChar)
/** write the resources. */
private void writeResources(OutputStreamWriter out) throws
IOException {
correctField(sRoleID)
// parse all resources
?
""
:
+
+ (bFixedSize
? "" : csvOptions.sSeparatedTextChar
for (int i = 0; i < resources.size(); i++) {
HumanResource p = (HumanResource)
resources.get(i);
+ csvOptions.sSeparatedChar));
}
out.write("\n");
// ID
}
if (csvOptions.bExportResourceID)
+} // end of write resources
out.write(correctField(""
p.getId())
? "" : csvOptions.sSeparatedChar));
+ (bFixedSize/** set the maximum size for all strings. */
void getMaxSize() {
// Name
iMaxSize = 0;
if (csvOptions.bExportResourceName)
out.write((bFixedSize
csvOptions.sSeparatedTextChar)
?
""
:
for (int i = 0; i < myTasks.length; i++) {
Task task = myTasks[i];
+
correctField(p.getName())
if (csvOptions.bExportTaskID) {
+ (bFixedSize
String s = "" + task.getTaskID();
? "" : csvOptions.sSeparatedTextChar
if (s.length() > iMaxSize)
+ csvOptions.sSeparatedChar));
iMaxSize = s.length();
// Mail
}
if (csvOptions.bExportResourceMail)
out.write((bFixedSize
csvOptions.sSeparatedTextChar)
?
""
:
if (csvOptions.bExportTaskName) {
String s = "" + getName(task);
+
if (s.length() > iMaxSize)
correctField(p.getMail())
iMaxSize = s.length();
+ (bFixedSize
? "" : csvOptions.sSeparatedTextChar
}
+ csvOptions.sSeparatedChar));
// Phone
if (csvOptions.bExportTaskStartDate) {
String s = "" + task.getStart();
235
iMaxSize = s.length();
if (s.length() > iMaxSize)
}
iMaxSize = s.length();
}
}
if (csvOptions.bExportTaskEndDate) {
String s = "" + task.getEnd();
// parse all resources
if (s.length() > iMaxSize)
for (int i = 0; i < resources.size(); i++) {
HumanResource p = (HumanResource)
iMaxSize = s.length();
resources.get(i);
}
if (csvOptions.bExportResourceID) {
if (csvOptions.bExportTaskDuration) {
String
task.getDuration().getLength();
s
=
""
String s = "" + p.getId();
+
if (s.length() > iMaxSize)
iMaxSize = s.length();
if (s.length() > iMaxSize)
}
iMaxSize = s.length();
if (csvOptions.bExportResourceName) {
}
String s = "" + p.getName();
if (s.length() > iMaxSize)
//LH
iMaxSize = s.length();
if (csvOptions.bExportTaskBudget) {
String s = "" + task.getBudget();
}
if (s.length() > iMaxSize)
if (csvOptions.bExportResourceMail) {
String s = "" + p.getMail();
iMaxSize = s.length();
if (s.length() > iMaxSize)
}
iMaxSize = s.length();
}
if (csvOptions.bExportTaskPercent) {
String
task.getCompletionPercentage();
s
=
""
if (csvOptions.bExportResourcePhone) {
+
String s = "" + p.getPhone();
if (s.length() > iMaxSize)
if (s.length() > iMaxSize)
iMaxSize = s.length();
iMaxSize = s.length();
}
}
if (csvOptions.bExportResourceRole) {
if (csvOptions.bExportTaskWebLink) {
String
getWebLink((GanttTask) task);
s
=
""
Role role = p.getRole();
+
String sRoleID = "0";
if (role != null)
if (s.length() > iMaxSize)
sRoleID
iMaxSize = s.length();
=
role.getPersistentID();
}
String s = "" + sRoleID;
if (s.length() > iMaxSize)
if (csvOptions.bExportTaskResources) {
String
s
=
""
iMaxSize = s.length();
+
}
getAssignments(task);
if (s.length() > iMaxSize)
}
iMaxSize = s.length();
}
} // get maxIndentation end
if (csvOptions.bExportTaskNotes) {
/** @return the name of task with the correct level. */
String s = "" + task.getNotes();
if (s.length() > iMaxSize)
private String getName(Task task) {
if (bFixedSize)
236
return task.getName();
import java.util.ArrayList;
String res = "";
import java.util.Enumeration;
int
depth
task.getManager().getTaskHierarchy().getDepth(task);
=import java.util.GregorianCalendar;
import java.util.HashMap;
for (int i = 0; i < depth; i++) {
import java.util.Iterator;
res += " ";
import java.util.List;
}
import java.util.Vector;
return res + task.getName();
}
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.transform.OutputKeys;
/** @return the link of the task. */
import javax.xml.transform.Transformer;
private String getWebLink(GanttTask task) {
return (task.getWebLink().equals("http://")
task.getWebLink());
import javax.xml.transform.TransformerException;
?
""
}
:
import
javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
/** @return the list of the assignment for the resources. */
import javax.xml.transform.stream.StreamResult;
private String getAssignments(Task task) {
String res = "";
ResourceAssignment[]
task.getAssignments();
assignment
for (int i = 0; i < assignment.length; i++)
import net.sourceforge.ganttproject.GanttCalendar;
=
import net.sourceforge.ganttproject.GanttGraphicArea;
import net.sourceforge.ganttproject.GanttPreviousState;
res += (assignment[i].getResource() + (i ==import net.sourceforge.ganttproject.GanttPreviousStateTask;
assignment.length - 1 ? ""
import net.sourceforge.ganttproject.GanttProject;
:
csvOptions.sSeparatedChar.equals(";") ? "," : ";"));
return res;
import net.sourceforge.ganttproject.GanttResourcePanel;
import net.sourceforge.ganttproject.GanttTask;
import net.sourceforge.ganttproject.GanttTaskRelationship;
}
import net.sourceforge.ganttproject.GanttTree2;
private String correctField(String field) {
String res = "";
for (int i = 0; i < iMaxSize - field.length(); i++)
res += " ";
res += field;
return res;
}
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;
}
net.sourceforge.ganttproject.io.
GanttXMLSaver
package net.sourceforge.ganttproject.io;
import java.io.IOException;
import java.io.OutputStream;
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 java.io.OutputStreamWriter;
import
net.sourceforge.ganttproject.task.CustomColumnsValues;
import java.io.Writer;
import net.sourceforge.ganttproject.task.ResourceAssignment;
import java.net.URLEncoder;
import net.sourceforge.ganttproject.task.BlankLineNode;
237
import net.sourceforge.ganttproject.task.Task;
/** Replace a part of the string by another one */
import net.sourceforge.ganttproject.util.ColorConvertion;
public String replaceAll(String notes, String s1, String s2) {
return notes.replaceAll(s1, s2);
import org.w3c.util.DateParser;
}
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/** Simple write information of tasks */
public void writeTask(Writer fout, DefaultMutableTreeNode
node, String space) {
/**
* Classe for save the project in a XML file
String space2 = s + space;
*/
try {
public class GanttXMLSaver implements GPSaver {
if (node instanceof BlankLineNode) {
private final IGanttProject myProject;
fout.write(space
+
"<blankline
/>\n");
private final UIFacade myUIFacade;
return;
}
private GanttTree2 tree;
GanttTask
node.getUserObject();
private GanttResourcePanel peop;
task
=
(GanttTask)
if (task.getTaskID() == -1)
private GanttGraphicArea area;
throw new RuntimeException(
"A task can
private HashMap usersId = new HashMap();
not has a number equal to -1");
ArrayList number = new ArrayList();
int id = task.getTaskID();
// List of tasks
/*
ArrayList lot = new ArrayList();
* if (id >= lot.size()) { return; }
*/
ArrayList lots = new ArrayList();
boolean haschild = false;
int cpt;
String s = "
ArrayList
tree.getAllChildTask(node);
"; // the marge
child
=
if (child.size() != 0) {
/** The constructor */
haschild = true;
public GanttXMLSaver(IGanttProject project, GanttTree2 tree,
GanttResourcePanel
GanttGraphicArea area, UIFacade uiFacade) {
this.tree = tree;
this.peop = peop;
peop,
}
number.add(new Integer(id));
cpt++;
this.area = area;
myProject = project;
myUIFacade = uiFacade;
}
//
boolean
(task.getSuccessorsOld().size() != 0 ||
//
(task.getNotes()
task.getNotes().length()>=0) ||
one
!=
=
null
&&
// haschild);
238
+ "\" ");
boolean
(task.getSuccessorsOld().size() == 0
one
=
if (task.isProjectTask())
fout.write("project=\"true\" ");
&& (task.getNotes() ==
fout.write("start=\""
+
null || task.getNotes().length() == 0) && !haschild)
task.getStart().toXMLString() + "\" ");
&&
fout.write("duration=\"" + task.getLength() +
Mediator.getCustomColumnsStorage()
"\" ");
//LH
.getCustomColumnCount() == 0;
fout.write("budget=\"" + task.getBudget() +
"\" ");
// Writes data of task
fout.write(space
+
"<task
task.getTaskID() + // lots.indexOf(task.toString())
id=\""
fout.write("complete=\""
+task.getCompletionPercentage() + "\" ");
+
fout.write("fixed-start=\""
// + //By CL
+ (task.isStartFixed() ?
"\" ");
"true" : "false") + "\" ");
fout.write("name=\""
correct(task.getName()) + "\" ");
+
if (task.getThird() != null) {
fout.write("thirdDate=\""
if (task.colorDefined()) {
/*
*
(task.getColor().getRed() <= 15) {
+
task.getThird().toXMLString()
+ "\" ");
fout.write("color=\"#");
if
fout.write("thirdDate-constraint=\""
+
* fout.write("0"); }
task.getThirdDateConstraint() + "\" ");
*
fout.write(Integer.toHexString(task.getColor().getRed())); if
}
* (task.getColor().getGreen() <=
15) { fout.write("0"); }
fout.write("priority=\"" + task.getPriority() +
"\"");
*
fout.write(Integer.toHexString(task.getColor().getGreen()));
* if (task.getColor().getBlue() <=
15) { fout.write("0"); }
// write the web link of the task
String sWebLink = task.getWebLink();
*
fout.write(Integer.toHexString(task.getColor().getBlue()));
if
!sWebLink.equals("")
(sWebLink
* fout.write("\" ");
!=
null
&&
&&
!sWebLink.equals("http://"))
*/
fout.write(" webLink=\""
fout.write("color=\""
+
URLEncoder.encode(sWebLink, "ISO-8859-1") + "\"");
+
ColorConvertion.getColor(task.getColor()) + "\" ");
}
// write if the task is expand or collapse
fout.write(" expand=\"" + task.getExpand() +
if (task.shapeDefined()
"\"");
&& task.getShape() !=
new ShapePaint(
if (!one) {
ShapeConstants.BACKSLASH, task.getColor(), task
fout.write(">\n");
} else {
.getColor())) {
fout.write("shape=\""
task.getShape().getArray() + "\" ");
fout.write("/>\n");
+
// fout.writeBytes(">\n");
}
// Write notes
fout.write("meeting=\""
((task.isMilestone()) ? "true" : "false")
+
}
239
if
(task.getNotes()
task.getNotes().length() > 0) {
!=
null
.get(i);
&&
fout.write(space2
/*
fout.write(space2 + "<notes>");
"<depend id=\""
fout.write("\n"
+
relationship.getSuccessorTaskID() + "\"" + " type=\""
+ space2
+s
*/+
+
+s
relationship.getRelationshipType()
+
+
correct(replaceAll(task.getNotes(), "\n", "\n"
"\"
difference=\"" + relationship.getDifference()
+ "\"/>\n");
+ space2 + s)));
fout.write("\n"
+
space2
}
+
"</notes>\n");
}
// Write the depends of the task
/*
* if (task.getDepend().size()
//fout.writeBytes(space2+"<depends>\n");
!=
0)
CustomColumnsValues
task.getCustomValues();
ccv
=
CustomColumnsStorage
Mediator.getCustomColumnsStorage();
ccs
=
List
{ccs.getCustomColumnsNames();
names
=
Iterator it = names.iterator();
* for (int i = 0; i < task.getDepend().size();
while (it.hasNext()) {
i++) {
String name, idc, value;
* fout.write(space2 + "<depend id=\"" +
tree.getTask( (String)
name = null;
idc = null;
* task.getDepend().get(i)).getTaskID() + //
changed By CL
value = null;
*
//lots.indexOf(
task.getDepend().get(i)) + "\"/>\n");
(String)
try {
name
*
//fout.writeBytes(space2+"</depends>\n"); } }
=
(String)
it.next();
*/
idc
=
value
=
ccs.getIdFromName(name);
ccv.getValue(name).toString();
//LH
CustomColumn
Cost[] costs = task.getCosts();
cc
=
ccs.getCustomColumn(name);
for (int i = 0; i < costs.length; i++) {
if
fout.write(space2 /* +s */+ "<cost(GregorianCalendar.class.isAssignableFrom(cc.getType()))
date=\""
+
DateParser.getIsoDate(((GanttCalendar) ccv
String.valueOf(costs[i].getDate().getTime()) + "\"" + " value=\""
+
String.valueOf(costs[i].getValue()) + "\"" + " description=\""
value
=
.getValue(name)).getTime());
fout.write(s + s + s +
+
"<customproperty taskproperty-id=\""
costs[i].getDescription()
//+
+
"\"idc + "\" value=\"" + value + "\" />\n");
difference=\"" + relationship.getDifference()
} catch (NullPointerException e) {
+ "\"/>\n");
}
System.out.println(name + ", " + idc + ", " + value);
e.printStackTrace();
//
use
successors
to
write
depends
}
information
Vector
task.getSuccessorsOld();
successors
for (int i = 0; i < successors.size(); i++) {
GanttTaskRelationship
relationship = (GanttTaskRelationship) successors
=
}
// Write the child of the task
if (haschild) {
for (int i = 0; i < child.size(); i++) {
240
Task task2 = (Task)
((DefaultMutableTreeNode) child.get(i))
} catch (Exception e) {
e.printStackTrace();
.getUserObject();
int
newid
=
-1;
lot.lastIndexOf(task2);
//
}
}
for (int j = 0; j <public
void
writeTaskProperties(Writer
CustomColumnsStorage customCol) {
lot.size(); j++) {
String
a
=
task2.toString();
fout,
try {
if (a == null)
fout
.write(s
System.out.println("nul");
String
b
+s
=
lot.get(j).toString();
+s
if
(a.equals(b)) {
"<taskproperty id=\"tpd0\"
valuetype=\"icon\" />\n");
name=\"type\"
+
type=\"default\"
fout
newid = j;
.write(s
}
+s
}
+s
writeTask(fout,
(DefaultMutableTreeNode) child.get(i),
space + s);
"<taskproperty id=\"tpd1\"
valuetype=\"icon\" />\n");
name=\"priority\"
+
type=\"default\"
fout
}
.write(s
+s
}
+s
// end of task section
if (!one) {
fout.write(space + "</task>\n");
"<taskproperty
id=\"tpd2\"
valuetype=\"icon\" />\n");
name=\"info\"
+
type=\"default\"
fout
.write(s
//
fout.writeBytes(space+"</task>\n");
+s
+s
}
&&
"<taskproperty id=\"tpd3\"
// if (tree.getNode(task.toString()).isLeaf()valuetype=\"text\" />\n");
// !tree.getFatherNode(task).isRoot()) {
name=\"name\"
+
type=\"default\"
fout
.write(s
// return;
+s
// }
+s
// if (id == lot.size() - 1) {
// return;
// }
// else {
+
"<taskproperty id=\"tpd4\" name=\"begindate\" type=\"default\"
valuetype=\"date\" />\n");
fout
.write(s
// writeTask(fout, cpt, space);
+s
//
+s
// }
241
if
+
"<taskproperty id=\"tpd5\" name=\"enddate\" type=\"default\"(cla.equals(String.class))
valuetype=\"date\" />\n");
valueType
=
"text";
fout
else
.write(s
+s
if
(cla.equals(Boolean.class))
valueType
+ s "boolean";
+
"<taskproperty id=\"tpd6\" name=\"duration\" type=\"default\"(cla.equals(Integer.class))
valuetype=\"int\" />\n");
else
if
valueType
fout
=
=
"int";
.write(s
else
if
+ s (cla.equals(Double.class))
+s
valueType
=
"double";
+
else
"<taskproperty id=\"tpd7\" name=\"completion\" type=\"default\"
(cla.isAssignableFrom(GregorianCalendar.class)) // TODO
valuetype=\"int\" />\n");
if
// to
fout
// be
.write(s
+s
// tested
+s
{
+
"<taskproperty id=\"tpd8\" name=\"coordinator\" type=\"default\""date";
valuetype=\"text\" />\n");
valueType
=
defVal
=
DateParser.getIsoDate(((GanttCalendar) cc
fout
.write(s
.getDefaultValue()).getTime());
+s
}
+s
+
String
"<taskproperty
id=\"tpd9\"
name=\"predecessors\"
Mediator.getCustomColumnsStorage()
type=\"default\" valuetype=\"text\" />\n");
//LH
idcStr
=
.getIdFromName(cc.getName());
fout
.write(s
fout.write(s + s + s +
+ s "<taskproperty id=\"" + idcStr
+s
+
"\" name=\"" + cc.getName()
+
"<taskproperty id=\"tpd10\" name=\"budget\" type=\"default\"
valuetype=\"text\" />\n");
"\" type=\"custom\" valuetype=\"" + valueType
+
+
"\" defaultvalue=\"" + defVal.toString()
=
Iterator
it
customCol.getCustomColumnsNames().iterator();
+
"\" />\n");
while (it.hasNext()) {
String
colName
=
it.next();
}
(String)(CustomColumnsException e1) {
e1.printStackTrace();
try {
CustomColumn
customCol.getCustomColumn(colName);
Object
defVal
cc
}
=
}
=
cc.getDefaultValue();
} catch (IOException e) {
String valueType = null;
Class
cc.getType();
catch
cla
=
e.printStackTrace();
}
242
+ (p.getMail()
!= null ? correct(p.getMail()) : "")
}
+
"\"
phone=\""
public void writeTaskDisplayColumns(Writer fout) {
+
=(p.getPhone() != null ? correct(p.getPhone()) : "")
List
displayedColumns
tree.getTreeTable().getDisplayColumns();
+ "\" />\n");
if (displayedColumns != null) {
usersId.put(p.getName(),
Iterator it = displayedColumns.iterator();
new
Integer(cpt_resources));
}
while (it.hasNext()) {
} catch (Exception e) {
GanttTreeTable.DisplayedColumn
(GanttTreeTable.DisplayedColumn) it
dc
=
e.printStackTrace();
}
.next();
}
if (dc.isDisplayed())
try {
/** Write the vacations on the file */
fout.write(s +
public void writeVacations(Writer fout) {
s + "<displaycolumn property-id=\""
try {
+ dc.getID() + "\" order=\"" + dc.getOrder()
List resources = peop.getPeople();
int cpt_resources = 1;
+ "\" width=\"" + dc.getWidth() + "\" />\n");
for (int i = 0; i < resources.size(); i++,
} catch (IOException e)
cpt_resources++) {
{
HumanResource
(HumanResource) resources.get(i);
e.printStackTrace();
p
=
if (p.getDaysOff() != null)
}
for (int j = 0; j <
}
p.getDaysOff().size(); j++) {
}
GanttDaysOff
}
gdo = (GanttDaysOff) p.getDaysOff()
.getElementAt(j);
/** Write the resources on the file */
fout.write(s +
public void writeResources(Writer fout) {
s + "<vacation start=\""
try {
+ gdo.getStart().toXMLString() + "\" end=\""
List resources = peop.getPeople();
int cpt_resources = 1;
+ gdo.getFinish().toXMLString()
for (int i = 0; i < resources.size(); i++,
cpt_resources++) {
+ "\" resourceid=\"" + p.getId() + "\"/>\n");
HumanResource
(HumanResource) resources.get(i);
p
=
}
}
String string = p.getName();
byte[]
btf8
} catch (Exception e) {
=
string.getBytes("UTF-8");
e.printStackTrace();
}
fout.write(s + s + "<resource}
id=\"" + p.getId() + "\" name=\""
+
(p.getName() != null ? correct(p.getName()) : "")
/**
+
"\" * Write all previous states of the project.
+
"\"
function=\"" + p.getRole().getPersistentID()
contacts=\""
*
* @throws IOException
*/
243
public void writePreviousStateTasks(Writer
IOException {
fout)
throws
for (int i = 1; i < lot.size(); i++) {
Task
ArrayList previousStates = ((GanttProject) myProject) ((DefaultMutableTreeNode) lot.get(i))
task
=
(Task)
.getPreviouStates();
.getUserObject();
for (int i = 0; i < previousStates.size(); i++) {
//
ArrayList list = null;
try {
list
users
=
ResourceAssignment[]
((GanttPreviousState)assignments = task.getAssignments();
=
previousStates.get(i)).load();
for
(int
j
=
0;
j
<
assignments.length; j++) {
} catch (Exception e) {
block
ArrayList
task.getUsersList();
// TODO Auto-generated catch
task.getTaskID();// (i-1);
int
task_id
=
e.printStackTrace();
ResourceAssignment
next = assignments[j];
}
Role
roleForAssignment = next.getRoleForAssignment();
// ArrayList list =
//
((GanttPreviousState)previous.get(i)).getTasks();
if
(roleForAssignment
== null)
fout.write(s + s + "<previous-tasks name=\""
if
(next.getResource() instanceof HumanResource)
+ ((GanttPreviousState)
previousStates.get(i)).getName()
roleForAssignment = ((HumanResource) next
+ "\">\n");
for (int j = 0; j < list.size(); j++) {
.getResource()).getRole();
GanttPreviousStateTask task =
(GanttPreviousStateTask) list
fout.write(s
.get(j);
+
s
+
"<allocation task-id=\"" + task_id
+
fout.write(s + s + s + "<previous-"\" resource-id=\"" + next.getResource().getId()
task id=\"" + task.getId()
+
"\" function=\""
+ "\"");
fout.write("
task.getStart().toXMLString() + "\"");
start=\""
+
fout.write("
duration=\""
+
fout.write("
meeting=\""
+
fout.write("
super=\""
+
task.getDuration() + "\"");
task.isMilestone() + "\"");
+
roleForAssignment.getPersistentID()
+
"\" responsible=\"" + next.isCoordinator()
+
"\" load=\"" + next.getLoad() + "\"/>\n");
}
task.hasNested() + "\"");
}
fout.write("/>\n");
} catch (Exception e) {
}
e.printStackTrace();
fout.write(s + s + "</previous-tasks>\n");
}
}
}
}
/** Write all roles of the project. */
public void writeRoles(Writer fout) {
/** Write the assignement between tasks and users */
public void writeAllocations(Writer fout) {
try {
try {
//
int
id=RoleManager.Access.getInstance().DEFAULT_ROLES_NU
MBER;
244
//
String
[]roles=RoleManager.Access.getInstance().getRolesShort();
Role[]
RoleManager.Access.getInstance()
projectRoles
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
=
e.printStackTrace();
} catch (TransformerException e) {
.getProjectLevelRoles();
// TODO Auto-generated catch block
for (int i = 0; i < projectRoles.length; i++) {
e.printStackTrace();
Role next = projectRoles[i];
} catch (SAXException e) {
fout.write(s + s + "<role id=\"" +
// TODO Auto-generated catch block
(next.getPersistentID())
e.printStackTrace();
+ "\" name=\""
}
+ correct(next.getName()) + "\"/>\n");
}
} catch (Exception e) {
}
private void startElement(String name, AttributesImpl attrs,
TransformerHandler
e.printStackTrace();
handler)
throws
SAXException {
}
handler.startElement("", name, name, attrs);
}
attrs.clear();
/** Correct the charcters to be compatible with xml format */
}
public String correct(String s) {
String res;
private void endElement(String name, TransformerHandler
handler)
if (s != null) {
throws SAXException {
res = s.replaceAll("&", "&#38;");
res = res.replaceAll("<", "&#60;");
handler.endElement("", name, name);
}
res = res.replaceAll(">", "&#62;");
res = res.replaceAll("/", "&#47;");
res = res.replaceAll("\"", "&#34;");
private void addAttribute(String
AttributesImpl attrs) {
name,
String
value,
attrs.addAttribute("", name, name, "CDATA", value);
} else
res = s;
}
return res;
private void emptyElement(String name, AttributesImpl attrs,
}
TransformerHandler
handler)
throws
SAXException {
public void save(OutputStream stream) {
save(stream, "1.12");
}
startElement(name, attrs, handler);
endElement(name, handler);
attrs.clear();
}
/** Save the project as XML on a stream (including the XMLprolog) */
private void emptyComment(TransformerHandler
public void save(OutputStream stream, String version) {
throws SAXException {
try {
handler.comment(new char[] { ' ' }, 0, 1);
OutputStreamWriter
fout
=
new
OutputStreamWriter(stream, "UTF-8");
}
save(fout, version, true);
handler)
} catch (IOException e) {
e.printStackTrace();
System.out.println(e);
file");
public void save(OutputStreamWriter _fout, String version,
boolean includeProlog) throws IOException,
TransformerFactoryConfigurationError,
// System.out.println("Error in saving the
TransformerException,
245
SAXException {
handler.endDocument();
AttributesImpl attrs = new AttributesImpl();
_fout.close();
try {
StreamResult
StreamResult(_fout);
result
=
new
} catch (Throwable e) {
e.printStackTrace();
SAXTransformerFactory
factory
(SAXTransformerFactory) SAXTransformerFactory
=
}
.newInstance();
TransformerHandler
factory.newTransformerHandler();
Transformer
handler.getTransformer();
}
handler
=
private void saveViews(TransformerHandler handler) throws
=SAXException {
serializer
new ViewSaver().save(getUIFacade(), handler);
serializer.setOutputProperty(OutputKeys.ENCODING,
}
"UTF-8");
private void saveCalendar(TransformerHandler handler) throws
SAXException {
serializer.setOutputProperty(OutputKeys.INDENT,
"yes");
new CalendarSaver().save(getProject(), handler);
serializer.setOutputProperty(
}
"{http://xml.apache.org/xslt}indent-amount", "4");
private void saveRoles(TransformerHandler handler) throws
SAXException {
handler.setResult(result);
handler.startDocument();
AttributesImpl attrs = new AttributesImpl();
addAttribute("name",
getProject().getProjectName(), attrs);
RoleManager
getProject().getRoleManager();
addAttribute("company",
getProject().getOrganization(), attrs);
roleManager
=
RoleSet[] roleSets = roleManager.getRoleSets();
for (int i = 0; i < roleSets.length; i++) {
addAttribute("webLink",
getProject().getWebLink(), attrs);
RoleSet next = roleSets[i];
addAttribute("view-date",
GanttCalendar(area.getViewState()
new
if (next.isEnabled()) {
addAttribute("roleset-name",
next.getName(), attrs);
.getStartDate()).toXMLString(), attrs);
emptyElement("roles",
// TODO: 1.11 repair saving zoom state
//
area.getZoom(), attrs);
addAttribute("view-zoom",
addAttribute("view-index",
myUIFacade.getViewIndex(), attrs);
""
""
addAttribute("gantt-divider-location", ""
+
myUIFacade.getGanttDividerLocation(), attrs);
+
}
}
+
//
RoleSet
projectRoleSet
roleManager.getProjectRoleSet();
startElement("roles", attrs, handler);
Role[]
projectRoleSet.getRoles();
=
Role next = projectRoles[i];
startElement("project", attrs, handler);
addAttribute("id",
saveViews(handler);
saveCalendar(handler);
projectRoles
for (int i = 0; i < projectRoles.length; i++) {
addAttribute("version", version, attrs);
emptyComment(handler);
=
if (!projectRoleSet.isEmpty()) {
addAttribute("resource-divider-location", ""
+
myUIFacade.getResourceDividerLocation(), attrs);
attrs,
handler);
next.getPersistentID(), attrs);
addAttribute("name",
next.getName(), attrs);
_save(_fout, version, false);
emptyElement("role",
attrs,
handler);
saveRoles(handler);
}
endElement("project", handler);
endElement("roles", handler);
246
+
correct(replaceAll(getProject().getDescription(), "\n",
}
}
"\n"
+ s + s)) + "\n");
/**
}
* Save the project as XML on a writer
fout.write(s + "</description>\n\n");
*
* @throws TransformerFactoryConfigurationError
lot = tree.getAllTasks();
* @throws TransformerFactoryConfigurationError
lots = tree.getArryListTaskString(null);
* @throws TransformerException
* @throws SAXException
// begin of tasks
*/
// fout.write(s + "<tasks>\n");
public void _save(OutputStreamWriter fout, String version,
boolean includeProlog) throws IOException,
// begin of tasks
TransformerFactoryConfigurationError,
TransformerException,
fout.write(s + "<tasks ");
fout.write("color=\""
ColorConvertion.getColor(area.getTaskColor())
SAXException {
// String space=" ";
+
+ "\"");
number.clear();
/*
*
fout.write("color=\"#");
(area.getTaskColor().getRed() <= 15) {
// StringWriter fout = new StringWriter();
if
* fout.write("0"); }
if (includeProlog) {
*
fout.write(Integer.toHexString(area.getTaskColor().getRed())); if
// write header
//
version=\"1.0\"?>\n");
fout.writeBytes("<?xml
* (area.getTaskColor().getGreen() <= 15) {
fout.write("0"); }
fout.write("<?xml
version=\"1.0\"
*
encoding=\"UTF-8\"?>\n");
fout.write(Integer.toHexString(area.getTaskColor().getGreen()));
// fout.write("<!DOCTYPE project SYSTEM if
//
*
(area.getTaskColor().getBlue()
\"http://ganttproject.sourceforge.net/dtd/ganttproject.dtd\">\n\n"); fout.write("0"); }
fout.write("<!DOCTYPE
ganttproject.sourceforge.net>\n\n");
<=
15)
{
*
fout.write(Integer.toHexString(area.getTaskColor().getBlue()));
}
* fout.write("\"");
*/
// fout.write("<project name=\"" +
// correct(getProject().getProjectName()) +
//
"\"
company=\""
correct(getProject().getOrganization()) +
fout.write(">\n");
+
fout.write(s + s + "<taskproperties>\n");
// "\" webLink=\"" + correct(getProject().getWebLink())
writeTaskProperties(fout,
Mediator.getCustomColumnsStorage());
+
// "\" view-date=\"" + area.getDate().toXMLString() +
fout.write(s + s + "</taskproperties>\n");
// "\" view-zoom=\"" +
// area.getZoom() + "\" version=\"" + version + "\">\n");
fout.write(s + "<description>");
if (!getProject().getDescription().equals("")) {
fout.write("\n"
cpt = 1;
Enumeration children = ((DefaultMutableTreeNode)
tree.getJTree()
.getModel().getRoot()).children();
while (children.hasMoreElements()) {
+s
+s
DefaultMutableTreeNode
(DefaultMutableTreeNode) children
element
=
.nextElement();
247
writeTask(fout,
/*
lot.indexOf(element)
*/element, s + s);
fout.write(s + "<previous>\n");
}
writePreviousStateTasks(fout);
fout.write(s + "</previous>\n\n");
// end of tasks
fout.write(s + "</tasks>\n\n");
// write the assign task to user
// write the resources
// end of project
fout.write(s + "<resources>\n");
// fout.write("</project>\n");
writeResources(fout);
fout.write(s + "</resources>\n\n");
// fout.close();
//
// write the assign task to user
fout.write(s + "<allocations>\n");
}
writeAllocations(fout);
fout.write(s + "</allocations>\n\n");
IGanttProject getProject() {
return myProject;
fout.write(s + "<vacations>\n");
}
writeVacations(fout);
fout.write(s + "</vacations>\n\n");
UIFacade getUIFacade() {
return myUIFacade;
fout.write(s + "<taskdisplaycolumns>\n");
writeTaskDisplayColumns(fout);
}
}
fout.write(s + "</taskdisplaycolumns>\n\n");
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
248
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
249
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
250
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)
251
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
252
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
253
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
254
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
255
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 webserver. 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
256
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
257
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
258
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
259
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
260
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
261
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
altera\u00e7\u00f5es antes de sair?
n\u00e3o
salvas.\nVoc\u00ea
gostaria
de
salvar
as
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
262
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
263
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.
264
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.
265
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
configura\u00e7\u00f5es. As fun\u00e7\u00f5es s\u00e3o salvadas no arquivo XML como entrada <roles>.
di\u00e1logo
de
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
266
xslFoFile=Arquivo padr\u00e3o xsl-fo
yes=Sim
zoomFit=Ajustar
zoomIn=Ampliar
zoomOut=Reduzir
267

Similar documents