diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..d08c7af
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,54 @@
+# Fins de linha e binarios do repositorio. Segue a convencao do DX.Comply
+# (https://github.com/omonien/DelphiStandards): no repositorio o texto fica com LF, na pasta de trabalho com CRLF.
+# O .bat precisa mesmo de CRLF: com LF o cmd.exe pode falhar nos "goto" e nos "call :etiqueta".
+
+# Fontes e projectos do Delphi
+*.pas text eol=crlf
+*.dfm text eol=crlf
+*.fmx text eol=crlf
+*.dpr text eol=crlf
+*.dpk text eol=crlf
+*.inc text eol=crlf
+*.rc text eol=crlf
+*.dproj text eol=crlf
+*.groupproj text eol=crlf
+
+# Configuracao, documentacao e dados
+*.json text eol=crlf
+*.xml text eol=crlf
+*.yml text eol=crlf
+*.yaml text eol=crlf
+*.properties text eol=crlf
+*.md text eol=crlf
+*.txt text eol=crlf
+*.tsv text eol=crlf
+*.html text eol=crlf
+*.css text eol=crlf
+*.js text eol=crlf
+*.svg text eol=crlf
+
+# Scripts
+*.bat text eol=crlf
+*.cmd text eol=crlf
+*.ps1 text eol=crlf
+*.py text eol=crlf
+
+# Binarios
+*.res binary
+*.dcr binary
+*.ico binary
+*.bmp binary
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.gif binary
+*.pdf binary
+*.exe binary
+*.dll binary
+*.bpl binary
+*.dcp binary
+*.dcu binary
+*.lib binary
+*.obj binary
+*.o binary
+*.a binary
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0a832c0..24ee182 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,58 @@ Todas as alterações relevantes ficam registadas aqui. O formato segue o
(MIT, Apache-2.0, BSD, MPL, GPL, LGPL, ISC, Zlib e outras), e só quando o texto a justifica. A lista ganha a coluna
Licença; o resumo e os relatórios, o número de componentes sem licença conhecida e um ponto de atenção; o CycloneDX
escreve `version`, `licenses` e a ligação do projeto, e o SPDX `versionInfo` e `licenseDeclared`.
+- **SBOM em CycloneDX 1.6:** o formato passa de 1.5 a **1.6**, a versão mínima que a BSI TR-03183-2 v2.1.0 aceita
+ (acompanha o DX.Comply 2.x). Os dois formatos levam o **copyright** do projeto (`LegalCopyright`), e as dependências
+ do CycloneDX saem por ordem: dois SBOM do mesmo projeto só diferem no número de série e na data.
+- **Grafo:** navegação pelo **teclado** (setas, `+`/`−`, `0` para ajustar, `Esc`, `Enter` para abrir) e **Shift + roda**
+ para deslocar na horizontal; muito afastado, o nome de cada unit dá lugar a uma barra que se desvanece (ideias do
+ DelphiNodeEditor).
+- **Chart4D 1.3.0:** o projeto usa a 1.3.0 quando está instalada e continua a compilar com a 1.2.0.
+- **Conforto visual:**
+ - **Contraste:** no tema claro, as marcas Compila e Sonar, a estrela e as cores das camadas do grafo chegam a 4,5:1
+ (texto) ou 3:1 (formas); no escuro, o texto secundário também se lê sobre os fundos realçados. As caixas de texto e
+ as barras de deslocamento têm um contorno visível, e as cores de destaque escolhidas no Aspeto leem-se também nos
+ fundos secundários.
+ - **Painel:** o texto dos eixos e das legendas passa de ~10,8 para ~12 px e segue a escala do Aspeto; os números dos
+ cartões encolhem para caber; as medidas do mesmo tipo usam a mesma cor; as distribuições mostram o número em cada
+ barra; nomes compridos cortam-se; o histograma usa limites redondos (0, 10, 20...); no tema escuro, a dica dos
+ gráficos (uma caixa branca ilegível) passa para a dica da aplicação.
+ - **Janela:** numa janela baixa a barra lateral fica só com os ícones (o nome vai para a dica), em vez de esconder os
+ últimos; o cabeçalho e os textos da página Projeto acompanham a escala do texto; a compilação Debug também se adapta
+ à escala do Windows.
+ - **Listas:** as etiquetas (EXTRA, ALTERADO, interface...) passam de 9,5 para 10,5 px; a assinatura dos métodos já não
+ repete `function`/`procedure`; na página Classes, o espaço reparte-se entre o nome e o ficheiro, que já não se corta.
+ - **Outros:** o ícone das Classes deixa de ser igual ao do Grafo; o grafo mostra quando tem o foco do teclado e os nós
+ esbatidos leem-se melhor; na página Acerca os valores ficam perto das etiquetas.
+
+### Correções
+
+- **SBOM, origem das units:** só o `lib\` e as pastas da Embarcadero em `source\` contam como Embarcadero; uma
+ biblioteca posta em `source\` ou nos `Extras\` da instalação passa a ser de terceiros (regra do DX.Comply).
+- **SBOM, configurações derivadas:** uma configuração criada a partir de outra (`CfgParent`) herda os caminhos, o mapa e
+ a versão da mãe, como no compilador.
+- **SBOM, ficheiro `.map`:** num package procura-se ao lado do `.bpl` e com o sufixo (`DCC_BplOutput`, `DllSuffix`,
+ também com os valores por omissão do IDE `$(BDSCOMMONDIR)\Bpl` e `$(Auto)`); um mapa sem units legíveis (cortado ou de
+ outro formato) já não põe todos os componentes «fora do mapa» e dá um aviso; a leitura
+ de mapas grandes é mais rápida (as expressões regulares compilam-se uma vez).
+- **Grafo:** a curva de um ciclo podia desaparecer quando muito aproximada junto à margem esquerda.
+
+### Desempenho
+
+- **Git/SVN/Hg em segundo plano:** a verificação dos ficheiros alterados desde a revisão (depois de cada análise e de
+ cada gravação vigiada) já não congela a janela; o histórico completo só se lê quando há revisões antigas sem commit
+ gravado. Um resultado que chega depois de reveres um ficheiro já não o volta a marcar como alterado.
+- **Dica de ficheiro alterado:** passar o rato já não espera pelo `git log`; o pormenor chega em segundo plano.
+- **Modo vigiar:** a reconciliação da árvore deixa de ser quadrática, os totais recontam-se uma vez por lote e os
+ ficheiros de compilação (`.dcu`, `.exe`, `.map`...) já não vão ao disco.
+- **Pesquisa no Mapa e na Checklist:** cada unit põe-se em minúsculas uma vez, não a cada tecla.
+- **Grafo, Classes, SBOM e Código:** o texto dos nós e a legenda ficam em cache por zoom; a pesquisa nas Classes deixa de
+ ser quadrática; o código guarda a linha mais longa, a largura da margem e os marcadores por linha; o texto mede-se com
+ a letra com que se desenha (nomes que saíam da caixa).
+
+### Manutenção
+
+- `.gitattributes` com o fim de linha CRLF nas fontes do Delphi e os binários marcados como tal (convenção do DX.Comply).
## [1.0.4] - 2026-10-06
diff --git a/CodeManager.dproj b/CodeManager.dproj
index a22c81c..c9f5a56 100644
--- a/CodeManager.dproj
+++ b/CodeManager.dproj
@@ -2,7 +2,8 @@
{6B0F3C1E-7A52-4D6B-9C1A-3E5D8B2F4A90}
20.3
-
+
+ $(USERPROFILE)\Documents\Embarcadero\Studio\37.0\CatalogRepository\Chart4D-13\1.3.0
$(USERPROFILE)\Documents\Embarcadero\Studio\37.0\CatalogRepository\Chart4D-13\1.2.0
FMX
CodeManager.dpr
@@ -79,10 +80,7 @@
true
true
-
- (None)
- none
-
+
false
RELEASE;$(DCC_Define)
diff --git a/README.en.md b/README.en.md
index 9bfe98d..d82905f 100644
--- a/README.en.md
+++ b/README.en.md
@@ -90,7 +90,7 @@ What changed in **version 1.0.4** (the full history is in the [changelog](CHANGE
- **Classes and inheritance** — a new page with the project's classes, interfaces and records and the **inheritance depth** of each, its children and its methods. Click the headings to sort, filter, and double-click to open the code at the declaration; when the chain leaves the project for an unknown class, the depth is shown as a minimum («>=»). It exports Markdown and CSV, and the Dashboard gets the deepest classes and the depth distribution.
**Previous version (1.0.3)**
-- **SBOM** — a new page with the project's **software bill of materials**: the outside units it uses, where each one comes from (Embarcadero or third party), how sure we are about each, and the **SHA-256** of the files. It starts from the source code and the `.dproj`, without compiling, and uses the `.map` file if there is one. It exports **CycloneDX 1.5** and **SPDX 2.3** (JSON) and a report in HTML (four languages, with a switcher in the page) or Markdown. Adapts ideas from [DX.Comply](https://github.com/omonien/DX.Comply) (MIT, Olaf Monien).
+- **SBOM** — a new page with the project's **software bill of materials**: the outside units it uses, where each one comes from (Embarcadero or third party), how sure we are about each, and the **SHA-256** of the files. It starts from the source code and the `.dproj`, without compiling, and uses the `.map` file if there is one. It exports **CycloneDX 1.6** and **SPDX 2.3** (JSON) and a report in HTML (four languages, with a switcher in the page) or Markdown. Adapts ideas from [DX.Comply](https://github.com/omonien/DX.Comply) (MIT, Olaf Monien).
**Behind the scenes**
- About 60 new automated tests (now over 920), including extracting class declarations and computing the hierarchy and depth.
diff --git a/README.md b/README.md
index 63b01e2..b452ce6 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@ Designed for developers maintaining, modernising, auditing or inheriting Delphi
- **Understand an unfamiliar codebase:** browse folders, units, methods, and their metrics.
- **Find architectural hotspots:** inspect `uses` dependencies, coupling and cycles; explore class inheritance depth.
- **Prioritise reviews:** track checked methods, notes, priorities and changes since a review.
-- **Document dependencies:** export software bills of materials in CycloneDX 1.5 and SPDX 2.3 JSON.
+- **Document dependencies:** export software bills of materials in CycloneDX 1.6 and SPDX 2.3 JSON.
- **Make progress visible:** dashboards and charts track complexity, distribution and review progress.
- **Compare plans with code:** use a Markdown specification to identify implemented, planned and extra elements.
@@ -49,7 +49,7 @@ Designed for developers maintaining, modernising, auditing or inheriting Delphi
| **Dependency graph** | Visual unit relationships from `uses`, coupling, cycles, HTML/SVG and Markdown reports |
| **Review checklist** | Per-method review tracking, priority, notes, build/Sonar status and repository changes |
| **Source viewer** | Read-only Delphi syntax highlighting with line numbers and method navigation |
-| **SBOM** | External unit inventory, provenance confidence, SHA-256, CycloneDX 1.5, SPDX 2.3 |
+| **SBOM** | External unit inventory, provenance confidence, SHA-256, CycloneDX 1.6, SPDX 2.3 |
| **Dashboard** | Complexity hotspots, progress tracking, class depth, project overview and trends |
| **Plan comparison** | Markdown-driven intended structure versus implemented code |
| **Integrations** | Optional Git, Subversion, Mercurial and SonarQube integration |
@@ -70,7 +70,7 @@ See [installation and build instructions (English)](docs/INSTALLATION.en.md).
## Build from source
-**Build requirements:** RAD Studio / Delphi 13 (Win64 compiler), [Chart4D 1.2.0](https://github.com/GDKsoftware/Chart4D) installed via GetIt, and Windows 10/11.
+**Build requirements:** RAD Studio / Delphi 13 (Win64 compiler), [Chart4D 1.3.0](https://github.com/GDKsoftware/Chart4D) (1.2.0 also works) installed via GetIt, and Windows 10/11.
```bat
git clone https://github.com/JFSF/CodeManager.git
diff --git a/README.pt-PT.md b/README.pt-PT.md
index 63b01e2..b452ce6 100644
--- a/README.pt-PT.md
+++ b/README.pt-PT.md
@@ -24,7 +24,7 @@ Designed for developers maintaining, modernising, auditing or inheriting Delphi
- **Understand an unfamiliar codebase:** browse folders, units, methods, and their metrics.
- **Find architectural hotspots:** inspect `uses` dependencies, coupling and cycles; explore class inheritance depth.
- **Prioritise reviews:** track checked methods, notes, priorities and changes since a review.
-- **Document dependencies:** export software bills of materials in CycloneDX 1.5 and SPDX 2.3 JSON.
+- **Document dependencies:** export software bills of materials in CycloneDX 1.6 and SPDX 2.3 JSON.
- **Make progress visible:** dashboards and charts track complexity, distribution and review progress.
- **Compare plans with code:** use a Markdown specification to identify implemented, planned and extra elements.
@@ -49,7 +49,7 @@ Designed for developers maintaining, modernising, auditing or inheriting Delphi
| **Dependency graph** | Visual unit relationships from `uses`, coupling, cycles, HTML/SVG and Markdown reports |
| **Review checklist** | Per-method review tracking, priority, notes, build/Sonar status and repository changes |
| **Source viewer** | Read-only Delphi syntax highlighting with line numbers and method navigation |
-| **SBOM** | External unit inventory, provenance confidence, SHA-256, CycloneDX 1.5, SPDX 2.3 |
+| **SBOM** | External unit inventory, provenance confidence, SHA-256, CycloneDX 1.6, SPDX 2.3 |
| **Dashboard** | Complexity hotspots, progress tracking, class depth, project overview and trends |
| **Plan comparison** | Markdown-driven intended structure versus implemented code |
| **Integrations** | Optional Git, Subversion, Mercurial and SonarQube integration |
@@ -70,7 +70,7 @@ See [installation and build instructions (English)](docs/INSTALLATION.en.md).
## Build from source
-**Build requirements:** RAD Studio / Delphi 13 (Win64 compiler), [Chart4D 1.2.0](https://github.com/GDKsoftware/Chart4D) installed via GetIt, and Windows 10/11.
+**Build requirements:** RAD Studio / Delphi 13 (Win64 compiler), [Chart4D 1.3.0](https://github.com/GDKsoftware/Chart4D) (1.2.0 also works) installed via GetIt, and Windows 10/11.
```bat
git clone https://github.com/JFSF/CodeManager.git
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index a7d6e26..2d07fbc 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -7,7 +7,7 @@ O CodeManager usa os componentes abaixo. Os seus avisos de licença acompanham e
Gráficos do Painel. É compilado a partir do código-fonte para dentro do executável.
- Projeto: (instalado pelo GetIt do Delphi)
-- Versão usada: 1.2.0
+- Versão usada: 1.3.0 (compatível com a 1.2.0)
- Licença: MIT
```text
@@ -51,7 +51,7 @@ Os ícones da interface (`CM.Theme`) são formas vetoriais dos Material Design I
## DX.Comply
A funcionalidade **SBOM** (a página SBOM, o relatório e os formatos CycloneDX e SPDX) adapta ideias e regras do DX.Comply:
-as regras de classificação da origem das units, a leitura do ficheiro `.map`, a estrutura dos documentos CycloneDX 1.5 e
+as regras de classificação da origem das units, a leitura do ficheiro `.map`, a estrutura dos documentos CycloneDX 1.6 e
SPDX 2.3 e o desenho dos relatórios. O código do CodeManager é próprio, escrito para a sua arquitetura (só leitura, sem
IDE nem compilação), e está nas unidades `CM.Sbom`, `CM.Dproj`, `CM.MapFile`, `CM.SbomResolve`, `CM.SbomFormats`,
`CM.SbomReport` e `CM.SbomService`.
@@ -86,10 +86,11 @@ SOFTWARE.
## DelphiNodeEditor
-A forma dos nós e das ligações em curva do mapa de dependências inspira-se neste projeto; o código do CodeManager é
-próprio (não copia o do DelphiNodeEditor).
+Um editor de nós em FireMonkey. A forma dos nós e das ligações em curva do mapa de dependências inspira-se neste
+projeto, tal como a barra que substitui o nome quando o mapa está muito afastado e a navegação pelo teclado e pela roda
+com Shift; o código do CodeManager é próprio (não copia o do DelphiNodeEditor).
-- Projeto:
+- Projeto: (revisto contra `d13fb5d`, 19-08-2026)
- Autor: HemulGM
-- Licença: MIT
+- Licença: MIT — Copyright (c) 2026 HemulGM
diff --git a/docs/ARQUITETURA.md b/docs/ARQUITETURA.md
index 4051bf8..006be23 100644
--- a/docs/ARQUITETURA.md
+++ b/docs/ARQUITETURA.md
@@ -353,7 +353,7 @@ classDiagram
| `Pages.Code` | Leitura do código em separadores (`UI.CodeView` desenha; `Core.Highlight` parte em linhas, realça a sintaxe e encontra a linha de um método). Abre-se por duplo clique (`UI.Clicks`) no Grafo, no Mapa e na Checklist, via `IPageHost.OpenCode`. |
| `Core.SonarModel` / `Infrastructure.Sonar` | O retrato do Sonar (por ficheiro: problemas, medidas, hotspots; do projeto: medidas e classificações) e o cliente de leitura da API; os analisadores das respostas são puros. Alimentam o Mapa, a Checklist, a página Código e o Painel. |
| `Pages.Classes` / `UI.ClassView` / `Core.Classes` / `Core.ClassHierarchy` / `Services.ClassReport` | As classes e a profundidade de herança. `Classes` extrai as declarações de tipos do texto limpo (`ExtractClasses`, chamado pelo analisador, que guarda o resultado em `TUnitInfo.Classes`); `ClassHierarchy` liga cada classe ao ancestral (primeiro na mesma unit, depois no projeto), calcula a profundidade (com uma tabela das classes conhecidas da RTL/FMX; ancestral externo desconhecido dá um mínimo) e as filhas; `ClassReport` faz o Markdown e o CSV. A hierarquia refaz-se quando a análise muda. Só leitura. |
-| `Pages.Sbom` / `Core.Sbom` / `Core.Dproj` / `Core.MapFile` / `Infrastructure.SbomResolve` / `Services.SbomFormats` / `SbomReport` / `SbomService` | A lista de materiais de software. `Dproj` lê o projeto (configuração, plataforma, caminhos, variáveis) e `MapFile` o `.map`; `Sbom` é o modelo (origem, evidência, confiança) e a montagem a partir do grafo de dependências; `SbomResolve` procura cada unit nos caminhos do projeto, nas fontes do Delphi e na biblioteca do IDE e calcula o SHA-256; `SbomLibs` (com `Core.Licenses`, que reconhece licenças pelo texto e lê o `boss.json` e o `boss-lock.json`) sobe pelas pastas de cada unit de terceiros até à raiz da biblioteca e apura o nome, a versão e a licença; `SbomFormats` escreve CycloneDX 1.5 e SPDX 2.3 e valida-os; `SbomReport` faz o relatório HTML (frases nos quatro idiomas, em `Services.HtmlLang`, partilhado com o relatório de dependências) e Markdown; `SbomService` orquestra tudo (corre em segundo plano). Só leitura. |
+| `Pages.Sbom` / `Core.Sbom` / `Core.Dproj` / `Core.MapFile` / `Infrastructure.SbomResolve` / `Services.SbomFormats` / `SbomReport` / `SbomService` | A lista de materiais de software. `Dproj` lê o projeto (configuração, plataforma, caminhos, variáveis) e `MapFile` o `.map`; `Sbom` é o modelo (origem, evidência, confiança) e a montagem a partir do grafo de dependências; `SbomResolve` procura cada unit nos caminhos do projeto, nas fontes do Delphi e na biblioteca do IDE e calcula o SHA-256; `SbomLibs` (com `Core.Licenses`, que reconhece licenças pelo texto e lê o `boss.json` e o `boss-lock.json`) sobe pelas pastas de cada unit de terceiros até à raiz da biblioteca e apura o nome, a versão e a licença; `SbomFormats` escreve CycloneDX 1.6 e SPDX 2.3 e valida-os; `SbomReport` faz o relatório HTML (frases nos quatro idiomas, em `Services.HtmlLang`, partilhado com o relatório de dependências) e Markdown; `SbomService` orquestra tudo (corre em segundo plano). Só leitura. |
| `Infrastructure.Vcs` / `Git` / `Svn` / `Hg` | `Vcs` descobre se a pasta é Git, Subversion ou Mercurial (o marcador `.git` / `.svn` / `.hg` mais próximo) e despacha para o cliente; `Proc` corre os programas sem janela. Só leitura. `Services.GitReview` usa só `Vcs`. |
| `Pages.Appearance` / `Theme` / `Core.Colors` | A página Aspeto (cor de destaque, fontes, escala). `Theme` guarda o aspeto (`ApplyAppearance`), deriva as paletas e aplica a escala do texto em `DrawTextRect` / `MeasureText`; `Core.Colors` é a matemática de cor (hex, HSL, contraste, `DeriveAccent`), sem interface. |
| `Pages.About` / `Core.AppInfo` / `Infrastructure.SysInfo` | A página Acerca. `AppInfo` (puro) lê e compara versões, nomeia o Delphi e monta o texto de diagnóstico; `SysInfo` lê o executável (versão e data), a compilação e o Windows. A versão mostrada é a do recurso de versão do executável (`VerInfo_Keys` no `CodeManager.dproj`). |
diff --git a/docs/DESENVOLVIMENTO.md b/docs/DESENVOLVIMENTO.md
index 1060511..903414c 100644
--- a/docs/DESENVOLVIMENTO.md
+++ b/docs/DESENVOLVIMENTO.md
@@ -17,13 +17,14 @@ Como compilar, testar e contribuir com código para o CodeManager.
| O quê | Versão | Notas |
|---|---|---|
| **RAD Studio / Delphi** | 13 (Florence) | Com o compilador de **Win64**. O caminho por omissão é `C:\Program Files (x86)\Embarcadero\Studio\37.0`. |
-| **Chart4D** | 1.2.0 | Instala-se pelo **GetIt** do IDE (*Chart4D*). É compilado a partir do código-fonte; **não** é preciso instalar pacotes. |
+| **Chart4D** | 1.3.0 (ou 1.2.0) | Instala-se pelo **GetIt** do IDE (*Chart4D*). É compilado a partir do código-fonte; **não** é preciso instalar pacotes. |
| **Windows** | 10 ou 11 | A aplicação usa APIs do Windows (`ReadDirectoryChangesW`, DWM, registo). |
| DUnitX | — | Já vem com o Delphi. |
O `.dproj` procura o Chart4D em
-`%USERPROFILE%\Documents\Embarcadero\Studio\37.0\CatalogRepository\Chart4D-13\1.2.0`. Se o instalaste noutro sítio,
-define a variável de ambiente **`Chart4DDir`** com essa pasta (a que contém `Source\`).
+`%USERPROFILE%\Documents\Embarcadero\Studio\37.0\CatalogRepository\Chart4D-13\1.3.0` e, se essa pasta não existir, em
+`...\Chart4D-13\1.2.0`. O código só usa o que as duas versões têm. Se o instalaste noutro sítio, define a variável de
+ambiente **`Chart4DDir`** com essa pasta (a que contém `Source\`).
## Compilar
diff --git a/docs/GUIA-DO-UTILIZADOR.md b/docs/GUIA-DO-UTILIZADOR.md
index f4c127c..5c99df7 100644
--- a/docs/GUIA-DO-UTILIZADOR.md
+++ b/docs/GUIA-DO-UTILIZADOR.md
@@ -291,6 +291,9 @@ contadas como *units externas*.
- **Simplificar** esconde as ligações para as units usadas por muitas outras (voltam a aparecer ao selecionar uma
unit); **Ajustar** enquadra o mapa todo; **− / +** afastam e aproximam. O filtro aceita nomes de unit ou de camada
(atalho: `/`).
+- **Navegar:** arrasta para mover; a **roda** aproxima e afasta em volta do cursor e, com **Shift**, desloca na
+ horizontal. Depois de clicares no mapa, as **setas** deslocam, **+** e **−** aproximam e afastam, **0** ajusta o mapa,
+ **Esc** larga a seleção e **Enter** abre a unit selecionada. Muito afastado, o nome de cada unit dá lugar a uma barra.
- O cartão **Ciclos** avisa quando há units que se usam em círculo.
- O **relatório de dependências** exporta-se em **HTML** (autónomo, com o mapa em SVG, tabelas ordenáveis e filtro)
ou em **Markdown**.
@@ -363,7 +366,13 @@ O CodeManager **não compila** nada. Parte do código-fonte:
3. Cada unit procura-se nos caminhos do `.dproj`, nas **fontes do Delphi** (`source\`) e nos caminhos da biblioteca do
IDE. A instalação do Delphi vem da variável `BDS` ou, se não existir, do registo (a mais recente). Uma unit achada
fica com o ficheiro e o **SHA-256**; uma biblioteca copiada para a pasta do projeto (`libs\`, `modules\`) conta como
- terceiros, não como código do projeto. O DUnitX, o Indy e o Skia, apesar de virem com o Delphi, também são de terceiros.
+ terceiros, não como código do projeto. Só conta como **Embarcadero** o que está no `lib\` do Delphi ou nas pastas
+ dela em `source\` (`rtl`, `vcl`, `fmx`, `data`, `soap`, `xml`, `internet`...). O resto da instalação é de terceiros:
+ o DUnit, o DUnitX, o Indy, o Skia e o FlatBox2D (vêm com o Delphi, mas têm licença própria; no `lib\`, os seus DCU
+ reconhecem-se pelo nome) e qualquer biblioteca
+ que lá se ponha (`source\MinhaLib`, `Extras\`).
+4. Se a configuração **deriva de outra** (no IDE, uma configuração criada a partir da `Release`), herda dela os
+ caminhos, o mapa e a versão, como faz o compilador.
A **confiança** diz quanto se sabe de cada componente:
@@ -399,7 +408,10 @@ A deteção é uma ajuda e não um parecer jurídico: confirma sempre a licença
Sem compilar, a lista pode incluir units que não chegam ao executável e não tem as que as bibliotecas usam entre si. Um
**mapa detalhado** resolve isso: compila o projeto uma vez com **Projeto › Opções › Compilador Delphi › Ligação ›
Ficheiro de mapa: Detalhado** (ou `DCC_MapFile=3`). O CodeManager procura-o em `DCC_ExeOutput\.map` (ou na pasta da
-plataforma e da configuração). Com ele, o SBOM:
+plataforma e da configuração); num **package**, primeiro ao lado do `.bpl` (`DCC_BplOutput\.map`, incluindo
+os valores por omissão do IDE, `$(BDSCOMMONDIR)\Bpl` e o sufixo `$(Auto)`). Os mapas de segmentos e de símbolos públicos
+(`DCC_MapFile` 1 ou 2) também servem: listam as units ligadas. Um `.map` em que não se acha nenhuma unit (cortado ou de
+outro formato) não se usa e aparece um aviso. Com o mapa, o SBOM:
- **confirma** as units realmente ligadas ao executável (a evidência passa a *Mapa de ligação*);
- **acrescenta** as units que ninguém nomeia no código (o que a RTL e as bibliotecas usam entre si);
@@ -416,12 +428,16 @@ plataforma e da configuração). Com ele, o SBOM:
### Exportar
-- **CycloneDX (JSON)** — CycloneDX 1.5 (`.cdx.json`).
+- **CycloneDX (JSON)** — CycloneDX 1.6 (`.cdx.json`).
- **SPDX (JSON)** — SPDX 2.3 (`.spdx.json`).
- **Relatório HTML** — uma página autónoma com o resumo, os pontos de atenção e todos os componentes (tabela ordenável e
filtro), **nos quatro idiomas** com um seletor na própria página.
- **Markdown** — o mesmo relatório em texto.
+Os ficheiros CycloneDX e SPDX levam o **copyright** do projeto (o `LegalCopyright` das informações de versão), quando
+existe, e saem sempre pela mesma ordem: dois SBOM do mesmo projeto só diferem no número de série e na data, o que
+facilita compará-los.
+

Os dois ficheiros JSON são **validados** antes de se gravarem (campos obrigatórios, referências, identificadores únicos e
@@ -434,6 +450,8 @@ relativo), para não mostrar a estrutura das tuas pastas.
dos ficheiros que acompanham a biblioteca (acima); sem eles ficam por declarar (`NOASSERTION` no SPDX) e o fornecedor
só se indica para a Embarcadero. As units da Embarcadero não têm licença nem versão no relatório.
- Sem `.map` a lista vem das cláusulas `uses` e pode não coincidir exatamente com o executável.
+- Para a norma alemã **BSI TR-03183-2** (v2.1.0), que detalha o que o Cyber Resilience Act pede, serve o **CycloneDX 1.6**;
+ o SPDX 2.3 fica para as ferramentas que só leem esse formato (a norma pede SPDX 3.0.1 ou mais recente).
- É só leitura: nunca altera o projeto.
A ideia e as regras de classificação adaptam o [DX.Comply](https://github.com/omonien/DX.Comply) (MIT, Olaf Monien).
diff --git a/docs/INSTALLATION.en.md b/docs/INSTALLATION.en.md
index 77020f6..3c3bf4f 100644
--- a/docs/INSTALLATION.en.md
+++ b/docs/INSTALLATION.en.md
@@ -16,7 +16,7 @@ CodeManager is a standalone Windows application, not a design-time component or
- RAD Studio / Delphi 13 with the Win64 compiler
- Windows 10/11
-- Chart4D 1.2.0, installed using the RAD Studio GetIt Package Manager
+- Chart4D 1.3.0 (1.2.0 also works), installed using the RAD Studio GetIt Package Manager
- DUnitX (bundled with Delphi) for tests
```bat
@@ -27,7 +27,7 @@ build.bat Release Win64
Output: `out\bin\Win64\Release\CodeManager.exe`.
-`build.bat` defaults to a Delphi installation at `C:\Program Files (x86)\Embarcadero\Studio\37.0`; override with `CM_RSVARS` pointing to another `rsvars.bat` if needed. The `.dproj` defaults to Chart4D under `%USERPROFILE%\Documents\Embarcadero\Studio\37.0\CatalogRepository\Chart4D-13\1.2.0`. If Chart4D is elsewhere, set `Chart4DDir` to its root folder (the one containing `Source`).
+`build.bat` defaults to a Delphi installation at `C:\Program Files (x86)\Embarcadero\Studio\37.0`; override with `CM_RSVARS` pointing to another `rsvars.bat` if needed. The `.dproj` defaults to Chart4D under `%USERPROFILE%\Documents\Embarcadero\Studio\37.0\CatalogRepository\Chart4D-13\1.3.0`, falling back to `...\Chart4D-13\1.2.0` when 1.3.0 is not installed. If Chart4D is elsewhere, set `Chart4DDir` to its root folder (the one containing `Source`).
Chart4D is compiled into the executable from source and is **not an additional runtime package** required by users of the published binary.
diff --git a/src/Core/CM.Analyzer.pas b/src/Core/CM.Analyzer.pas
index 7bc5314..425781e 100644
--- a/src/Core/CM.Analyzer.pas
+++ b/src/Core/CM.Analyzer.pas
@@ -83,12 +83,16 @@ function ScanProject(const ARoot: string; const AExclude: TArray;
// volta a analisar um so ficheiro (caminho relativo com '/') e actualiza AScan: junta, altera ou
// retira a unit conforme o estado no disco. Nao e thread-safe (usa as regex partilhadas do modulo).
function RescanFile(AScan: TProjectScan; const ARelPath: string): TRescanKind; overload;
-function RescanFile(AScan: TProjectScan; const ARelPath: string; out AChange: TScanChange): TRescanKind; overload;
+// ARecount = False adia o RecountScan: num lote de ficheiros, chamar RecountScan uma vez no fim
+function RescanFile(AScan: TProjectScan; const ARelPath: string; out AChange: TScanChange;
+ ARecount: Boolean = True): TRescanKind; overload;
// compara os ficheiros no disco com as units da analise e junta/retira as que faltam ou sobram
// (pastas criadas, renomeadas ou apagadas); acrescenta a AChanges o que mudou
procedure ReconcileScan(AScan: TProjectScan; AChanges: TList);
// o caminho relativo passa por uma pasta ignorada?
function IsPathExcluded(AScan: TProjectScan; const ARelPath: string): Boolean;
+// o nome (de uma so pasta) esta na lista de ignoradas? (sem distinguir maiusculas)
+function IsExcludedDir(const AName: string; const AExclude: TArray): Boolean;
function ExtractMethods(const AFilePath: string): TArray; overload;
// o mesmo, e devolve tambem as classes que a unit declara
function ExtractMethods(const AFilePath: string; out AClasses: TArray): TArray; overload;
@@ -1041,7 +1045,8 @@ function FindUnitIndex(AScan: TProjectScan; const ARelPath: string): Integer;
Result := -1;
end;
-function RescanFile(AScan: TProjectScan; const ARelPath: string; out AChange: TScanChange): TRescanKind; overload;
+function RescanFile(AScan: TProjectScan; const ARelPath: string; out AChange: TScanChange;
+ ARecount: Boolean): TRescanKind; overload;
var
Idx, Pos, I, J: Integer;
Full: string;
@@ -1117,7 +1122,7 @@ function RescanFile(AScan: TProjectScan; const ARelPath: string; out AChange: TS
Result := rcRemoved;
end;
AChange.Kind := Result;
- if Result <> rcNone then
+ if ARecount and (Result <> rcNone) then
RecountScan(AScan);
end;
@@ -1131,14 +1136,17 @@ function RescanFile(AScan: TProjectScan; const ARelPath: string): TRescanKind; o
procedure ReconcileScan(AScan: TProjectScan; AChanges: TList);
var
OnDisk: TStringList;
- Known: THashSet;
+ Known, InScan: THashSet;
Stale: TList;
U: TUnitInfo;
Rel: string;
Change: TScanChange;
+ Before: Integer;
begin
+ Before := AChanges.Count;
OnDisk := TStringList.Create;
Known := THashSet.Create;
+ InScan := THashSet.Create;
Stale := TList.Create;
try
CollectFiles(AScan.Root, '', AScan.ExcludeDirs, OnDisk);
@@ -1148,14 +1156,20 @@ procedure ReconcileScan(AScan: TProjectScan; AChanges: TList);
if not Known.Contains(LowerCase(U.Path)) then
Stale.Add(U.Path);
for Rel in Stale do
- if RescanFile(AScan, Rel, Change) <> rcNone then
+ if RescanFile(AScan, Rel, Change, False) <> rcNone then
AChanges.Add(Change);
+ // conjunto em vez de FindUnitIndex por ficheiro (O(n^2)); os ficheiros do disco sao unicos
+ for U in AScan.Units do
+ InScan.Add(LowerCase(U.Path));
for Rel in OnDisk do
- if FindUnitIndex(AScan, Rel) < 0 then
- if RescanFile(AScan, Rel, Change) <> rcNone then
+ if not InScan.Contains(LowerCase(Rel)) then
+ if RescanFile(AScan, Rel, Change, False) <> rcNone then
AChanges.Add(Change);
+ if AChanges.Count > Before then
+ RecountScan(AScan);
finally
Stale.Free;
+ InScan.Free;
Known.Free;
OnDisk.Free;
end;
diff --git a/src/Core/CM.Colors.pas b/src/Core/CM.Colors.pas
index e713506..c372f4d 100644
--- a/src/Core/CM.Colors.pas
+++ b/src/Core/CM.Colors.pas
@@ -34,8 +34,9 @@ function MixColors(AFrom, ATo: Cardinal; AAmount: Double): Cardinal;
function RelativeLuminance(AColor: Cardinal): Double;
function ContrastRatio(AColor1, AColor2: Cardinal): Double;
-// as cores do tema claro ou escuro para a cor de destaque escolhida. ASurface e o fundo dos cartoes desse tema
-function DeriveAccent(ABase: Cardinal; ADark: Boolean; ASurface: Cardinal): TAccentSet;
+// as cores do tema claro ou escuro para a cor de destaque escolhida. ASurface e o fundo dos cartoes desse tema e
+// ASurface2 o fundo secundario (linhas realcadas, caixas); a cor tem de se ler bem sobre os dois (0 = so ASurface)
+function DeriveAccent(ABase: Cardinal; ADark: Boolean; ASurface: Cardinal; ASurface2: Cardinal = 0): TAccentSet;
implementation
@@ -181,7 +182,7 @@ function ContrastRatio(AColor1, AColor2: Cardinal): Double;
Result := (L1 + 0.05) / (L2 + 0.05);
end;
-function DeriveAccent(ABase: Cardinal; ADark: Boolean; ASurface: Cardinal): TAccentSet;
+function DeriveAccent(ABase: Cardinal; ADark: Boolean; ASurface: Cardinal; ASurface2: Cardinal): TAccentSet;
const
White = $FFFFFFFF;
Black = $FF0E1513;
@@ -190,6 +191,14 @@ function DeriveAccent(ABase: Cardinal; ADark: Boolean; ASurface: Cardinal): TAcc
H, S, L: Double;
Color: Cardinal;
Guard: Integer;
+
+ // a cor ainda nao se le bem sobre algum dos fundos?
+ function Weak(AColor, AFirst: Cardinal): Boolean;
+ begin
+ Result := (ContrastRatio(AColor, AFirst) < MinContrast) or
+ ((ASurface2 <> 0) and (ContrastRatio(AColor, ASurface2) < MinContrast));
+ end;
+
begin
ColorToHsl(ABase, H, S, L);
Color := ABase;
@@ -197,7 +206,7 @@ function DeriveAccent(ABase: Cardinal; ADark: Boolean; ASurface: Cardinal): TAcc
if ADark then
begin
// no tema escuro a cor sobe de luminosidade ate se ler bem sobre os cartoes
- while (ContrastRatio(Color, ASurface) < MinContrast) and (L < 0.92) and (Guard < 60) do
+ while Weak(Color, ASurface) and (L < 0.92) and (Guard < 60) do
begin
L := L + 0.02;
Color := HslToColor(H, S, L);
@@ -209,8 +218,8 @@ function DeriveAccent(ABase: Cardinal; ADark: Boolean; ASurface: Cardinal): TAcc
end
else
begin
- // no tema claro desce ate o texto branco por cima ler bem (botoes cheios)
- while (ContrastRatio(Color, White) < MinContrast) and (L > 0.08) and (Guard < 60) do
+ // no tema claro desce ate o texto branco por cima ler bem (botoes cheios) e ela propria se ler sobre os fundos
+ while Weak(Color, White) and (L > 0.08) and (Guard < 60) do
begin
L := L - 0.02;
Color := HslToColor(H, S, L);
diff --git a/src/Core/CM.Dproj.pas b/src/Core/CM.Dproj.pas
index abf6aaf..bebfea3 100644
--- a/src/Core/CM.Dproj.pas
+++ b/src/Core/CM.Dproj.pas
@@ -4,7 +4,8 @@
caminhos de procura de units, os espacos de nomes e se o compilador gera o ficheiro .map.
O .dproj e XML do MSBuild: varios PropertyGroup, cada um com uma condicao ("Base", "Cfg_1", "Cfg_2_Win64"...). Escolhe-se uma
- configuracao e uma plataforma, juntam-se por ordem os grupos que lhes dizem respeito (o ultimo valor ganha; um valor que
+ configuracao e uma plataforma, juntam-se por ordem os grupos que lhes dizem respeito, incluindo os das configuracoes de
+ que ela deriva (CfgParent) (o ultimo valor ganha; um valor que
usa $(Nome) leva o valor anterior da propria propriedade, como faz o MSBuild) e expandem-se as variaveis conhecidas.
Le-se com expressoes regulares, sem MSXML, por isso funciona em qualquer lado.
@@ -35,6 +36,8 @@ TDprojInfo = record
Namespaces: TArray;
MapFileMode: Integer; // DCC_MapFile: 0 nenhum, 1 segmentos, 2 publicos, 3 detalhado
ExeOutput: string; // DCC_ExeOutput, com as variaveis expandidas ('' = pasta do projecto)
+ BplOutput: string; // DCC_BplOutput (onde um package grava o .bpl e o .map), expandido
+ DllSuffix: string; // DllSuffix de um package ('290'); '' se nao tem ou se nao se consegue expandir
IsPackage: Boolean; // o projecto principal e um .dpk
end;
@@ -157,8 +160,10 @@ procedure ParseDproj(const AXml, AFileName, AConfig, APlatform: string; AVars: T
Vars: TDictionary;
Groups: TMatchCollection;
G, E, B: TMatch;
- Key, Cfg, Plat, Value, Prev, CfgKey: string;
+ Key, Cfg, Plat, Value, Prev, CfgKey, Parent: string;
CfgList, PlatList: TList;
+ Parents: TDictionary; // chave da configuracao -> chave da configuracao-mae (CfgParent), em minusculas
+ Depth: Integer;
function Prop(const AName: string): string;
begin
@@ -178,8 +183,9 @@ procedure ParseDproj(const AXml, AFileName, AConfig, APlatform: string; AVars: T
Vars := TDictionary.Create;
CfgList := TList.Create;
PlatList := TList.Create;
+ Parents := TDictionary.Create;
try
- // configuracoes e a chave de cada uma (Release -> Cfg_2)
+ // configuracoes, a chave de cada uma (Release -> Cfg_2) e de qual deriva (CfgParent)
CfgKey := '';
Cfg := AConfig;
for B in TRegEx.Matches(AXml, ']*>(.*?)',
@@ -190,6 +196,9 @@ procedure ParseDproj(const AXml, AFileName, AConfig, APlatform: string; AVars: T
E := TRegEx.Match(B.Groups[2].Value, '([^<]*)');
if E.Success and (Cfg <> '') and SameText(B.Groups[1].Value, Cfg) then
CfgKey := E.Groups[1].Value;
+ G := TRegEx.Match(B.Groups[2].Value, '([^<]*)');
+ if E.Success and G.Success then
+ Parents.AddOrSetValue(LowerCase(Trim(E.Groups[1].Value)), LowerCase(Trim(G.Groups[1].Value)));
end;
// plataformas activas
for B in TRegEx.Matches(AXml, '\s*True\s*', [roIgnoreCase]) do
@@ -241,6 +250,17 @@ procedure ParseDproj(const AXml, AFileName, AConfig, APlatform: string; AVars: T
begin
Flags.Add(LowerCase(CfgKey), True);
Flags.Add(LowerCase(CfgKey) + '_' + LowerCase(Plat), True);
+ // uma configuracao derivada (Cfg_3 de Release) herda os grupos da mae, e esta os da sua, ate a Base; para num ciclo.
+ // So a chave da mae: o MSBuild nunca liga o grupo da plataforma dela (Cfg_2_Win64), porque o cabecalho desse grupo
+ // vem antes do da derivada, que e quem liga Cfg_2
+ Key := LowerCase(CfgKey);
+ Depth := 0;
+ while Parents.TryGetValue(Key, Parent) and (Parent <> '') and (Parent <> 'base') and (Depth < 32) and
+ Flags.TryAdd(Parent, True) do
+ begin
+ Key := Parent;
+ Inc(Depth);
+ end;
end;
// variaveis proprias do projecto
@@ -285,7 +305,13 @@ procedure ParseDproj(const AXml, AFileName, AConfig, APlatform: string; AVars: T
AInfo.Namespaces := SplitList(Expand(Prop('DCC_Namespace'), Vars, Props));
AInfo.MapFileMode := StrToIntDef(Trim(Prop('DCC_MapFile')), 0);
AInfo.ExeOutput := Trim(Expand(Prop('DCC_ExeOutput'), Vars, Props));
+ AInfo.BplOutput := Trim(Expand(Prop('DCC_BplOutput'), Vars, Props));
+ // um sufixo que ficou com $(...) (o $(Auto) do IDE, por exemplo) nao da um nome de ficheiro em que se possa confiar
+ AInfo.DllSuffix := Trim(Expand(Prop('DllSuffix'), Vars, Props));
+ if AInfo.DllSuffix.Contains('$') then
+ AInfo.DllSuffix := '';
finally
+ Parents.Free;
PlatList.Free;
CfgList.Free;
Vars.Free;
diff --git a/src/Core/CM.Highlight.pas b/src/Core/CM.Highlight.pas
index 5017f98..084d431 100644
--- a/src/Core/CM.Highlight.pas
+++ b/src/Core/CM.Highlight.pas
@@ -26,6 +26,7 @@ TCodeLine = record
TCodeDoc = class
private
FLines: TArray;
+ FLongest: Integer; // calculado uma vez no Create (as linhas nao mudam depois)
public
constructor Create(const AText: string);
function Count: Integer;
@@ -278,6 +279,8 @@ constructor TCodeDoc.Create(const AText: string);
begin
FLines[I].Text := ExpandTabs(Raw[I]);
FLines[I].Spans := ScanLine(FLines[I].Text, Block);
+ if Length(FLines[I].Text) > FLongest then
+ FLongest := Length(FLines[I].Text);
end;
end;
@@ -292,13 +295,8 @@ function TCodeDoc.Line(AIndex: Integer): TCodeLine;
end;
function TCodeDoc.LongestLine: Integer;
-var
- I: Integer;
begin
- Result := 0;
- for I := 0 to High(FLines) do
- if Length(FLines[I].Text) > Result then
- Result := Length(FLines[I].Text);
+ Result := FLongest;
end;
{ procurar rotinas }
diff --git a/src/Core/CM.Lang.Table.pas b/src/Core/CM.Lang.Table.pas
index 53c19c5..eb9abf2 100644
--- a/src/Core/CM.Lang.Table.pas
+++ b/src/Core/CM.Lang.Table.pas
@@ -6,7 +6,7 @@
interface
const
- LangRows: array[0..624] of array[0..3] of string = (
+ LangRows: array[0..625] of array[0..3] of string = (
('Projeto', 'Project', 'Projet', 'Projekt'),
('Mapa', 'Map', 'Carte', 'Karte'),
('Checklist', 'Checklist', 'Checklist', 'Checkliste'),
@@ -620,6 +620,9 @@ interface
('Não se encontrou o ficheiro .dproj: a versão e os caminhos de procura ficam por preencher.', 'The .dproj file was not found: the version and the search paths stay empty.', 'Le fichier .dproj est introuvable : la version et les chemins de recherche restent vides.', 'Die .dproj-Datei wurde nicht gefunden: Version und Suchpfade bleiben leer.'),
('Não se encontrou a instalação do Delphi: as units da Embarcadero só se reconhecem pelo nome.', 'The Delphi installation was not found: Embarcadero units are only recognised by name.', 'L''installation de Delphi est introuvable : les unités d''Embarcadero ne sont reconnues que par leur nom.', 'Die Delphi-Installation wurde nicht gefunden: Embarcadero-Units werden nur am Namen erkannt.'),
('Não se encontrou o ficheiro .map: compila o projeto com o mapa «Detailed» para confirmar as units ligadas.', 'The .map file was not found: build the project with a "Detailed" map to confirm the linked units.', 'Le fichier .map est introuvable : compile le projet avec une map « Detailed » pour confirmer les unités liées.', 'Die .map-Datei wurde nicht gefunden: Kompiliere das Projekt mit einer „Detailed“-Map, um die gebundenen Units zu bestätigen.'),
+ ('O ficheiro .map não tem units que se consigam ler (pode estar incompleto ou ter outro formato): volta a compilar o projeto com o mapa ligado.', 'The .map file has no readable units (it may be incomplete or in another format): build the project again with the map turned on.', 'Le fichier .map ne contient aucune unité lisible (il est peut-être incomplet ou dans un autre format) : recompile le projet avec la map activée.',
+ 'Die .map-Datei enthält keine lesbaren Units (sie ist vielleicht unvollständig oder hat ein anderes Format): Kompiliere das Projekt erneut mit eingeschalteter Ma'
+ + 'p.'),
('SBOM inspirado no DX.Comply (MIT, Olaf Monien).', 'SBOM inspired by DX.Comply (MIT, Olaf Monien).', 'SBOM inspirée de DX.Comply (MIT, Olaf Monien).', 'SBOM inspiriert von DX.Comply (MIT, Olaf Monien).'),
('classe', 'class', 'classe', 'Klasse'),
('interface', 'interface', 'interface', 'Schnittstelle'),
diff --git a/src/Core/CM.MapFile.pas b/src/Core/CM.MapFile.pas
index 39ba964..1fe1b7f 100644
--- a/src/Core/CM.MapFile.pas
+++ b/src/Core/CM.MapFile.pas
@@ -30,7 +30,11 @@ function ParseMapUnits(const AText: string): TArray;
Seen: TDictionary;
Line, Name: string;
M: TMatch;
+ LineRe, SegRe: TRegEx;
begin
+ // compiladas uma vez: a funcao de classe TRegEx.Match volta a compilar a expressao em cada linha
+ LineRe := TRegEx.Create('^\s*Line numbers for\s+([A-Za-z0-9_\.]+)\s*\(', [roIgnoreCase, roCompiled]);
+ SegRe := TRegEx.Create('\bM=([A-Za-z0-9_\.]+)\b', [roCompiled]);
List := TList.Create;
Seen := TDictionary.Create;
try
@@ -40,13 +44,13 @@ function ParseMapUnits(const AText: string): TArray;
// um mapa detalhado tem centenas de milhares de linhas: so as que podem trazer uma unit passam pela expressao regular
if Pos('Line numbers for', Line) > 0 then
begin
- M := TRegEx.Match(Line, '^\s*Line numbers for\s+([A-Za-z0-9_\.]+)\s*\(', [roIgnoreCase]);
+ M := LineRe.Match(Line);
if M.Success then
Name := M.Groups[1].Value;
end
else if Pos(' M=', Line) > 0 then
begin
- M := TRegEx.Match(Line, '\bM=([A-Za-z0-9_\.]+)\b');
+ M := SegRe.Match(Line);
if M.Success then
Name := M.Groups[1].Value;
end;
diff --git a/src/Infrastructure/CM.SbomResolve.pas b/src/Infrastructure/CM.SbomResolve.pas
index 3c28ac0..1427105 100644
--- a/src/Infrastructure/CM.SbomResolve.pas
+++ b/src/Infrastructure/CM.SbomResolve.pas
@@ -28,6 +28,8 @@ TSbomResolveOptions = record
// onde esta instalado o Delphi: a variavel BDS e, se nao existir, a instalacao mais recente do registo ('' se nenhuma)
function DetectDelphiRoot: string;
+// a pasta comum do Delphi ($(BDSCOMMONDIR)): Publico\Documentos\Embarcadero\Studio\, onde ficam os .bpl
+function BdsCommonDir(const ADelphiRoot: string): string;
// as variaveis de ambiente definidas no IDE (Ferramentas > Opcoes > Variaveis de ambiente), com o nome em minusculas; sem o PATH
// (quem chama liberta o dicionario)
function IdeEnvironmentVars(const ADelphiRoot: string): TDictionary;
@@ -37,8 +39,8 @@ function DelphiLibraryPaths(const ADelphiRoot, APlatform: string): TArray.map, a pasta plataforma\configuracao ou a do
-// projecto; '' se nao existe
+// o .map do projecto (se ja foi compilado com mapa): num package, primeiro DCC_BplOutput\.map; depois
+// DCC_ExeOutput\.map, a pasta plataforma\configuracao ou a do projecto; '' se nao existe
function FindMapFile(const ADproj: TDprojInfo): string;
// preenche o ficheiro, o hash, a origem e a confianca dos componentes
procedure ResolveSbom(ASbom: TSbom; const AOptions: TSbomResolveOptions; const AProgress: TScanProgress = nil);
@@ -175,13 +177,17 @@ function DetectDelphiRoot: string;
end;
end;
+function BdsCommonDir(const ADelphiRoot: string): string;
+begin
+ Result := GetEnvironmentVariable('PUBLIC') + '\Documents\Embarcadero\Studio\' + ExtractFileName(ADelphiRoot);
+end;
+
function ExpandIdeVars(const AText, ADelphiRoot, APlatform: string): string;
begin
Result := AText.Replace('$(BDS)', ADelphiRoot, [rfReplaceAll, rfIgnoreCase])
.Replace('$(BDSLIB)', ADelphiRoot + '\lib', [rfReplaceAll, rfIgnoreCase])
.Replace('$(Platform)', APlatform, [rfReplaceAll, rfIgnoreCase])
- .Replace('$(BDSCOMMONDIR)', GetEnvironmentVariable('PUBLIC') + '\Documents\Embarcadero\Studio\' +
- ExtractFileName(ADelphiRoot), [rfReplaceAll, rfIgnoreCase]);
+ .Replace('$(BDSCOMMONDIR)', BdsCommonDir(ADelphiRoot), [rfReplaceAll, rfIgnoreCase]);
end;
function IdeEnvironmentVars(const ADelphiRoot: string): TDictionary;
@@ -305,6 +311,13 @@ function FindMapFile(const ADproj: TDprojInfo): string;
Name := ADproj.ProjectName + '.map';
Candidates := TList.Create;
try
+ // um package grava o .map ao lado do .bpl, com o sufixo no nome (Demo290.map)
+ if ADproj.IsPackage and (ADproj.BplOutput <> '') and not ADproj.BplOutput.Contains('$(') then
+ begin
+ if ADproj.DllSuffix <> '' then
+ Candidates.Add(TPath.Combine(TPath.Combine(Dir, ADproj.BplOutput), ADproj.ProjectName + ADproj.DllSuffix + '.map'));
+ Candidates.Add(TPath.Combine(TPath.Combine(Dir, ADproj.BplOutput), Name));
+ end;
if ADproj.ExeOutput <> '' then
Candidates.Add(TPath.Combine(TPath.Combine(Dir, ADproj.ExeOutput), Name));
Candidates.Add(TPath.Combine(TPath.Combine(TPath.Combine(Dir, ADproj.Platform), ADproj.Config), Name));
@@ -337,28 +350,52 @@ function AbsolutePath(const APath, ABase: string): string;
end;
const
- // bibliotecas de terceiros que vem dentro da instalacao do Delphi (pastas de source\): continuam a ser de terceiros
- ShippedThirdParty: array[0..6] of string = ('dunitx', 'dunit', 'indy10', 'indy', 'indyimpl', 'skia', 'flatbox2d');
+ // as pastas de source\ que sao da Embarcadero (db, websnap e clx so existem em instalacoes antigas). Tudo o resto que
+ // esteja dentro da instalacao e de terceiros: as bibliotecas que vem com o Delphi mas tem licenca propria (DUnit, DUnitX,
+ // Indy, Skia, FlatBox2D) e o que alguem la ponha (source\MinhaLib, Extras\, um CatalogRepository)
+ EmbarcaderoSourceFolders: array[0..17] of string = ('rtl', 'vcl', 'fmx', 'data', 'databinding', 'dataexplorer',
+ 'experts', 'ibx', 'internet', 'property editors', 'soap', 'tethering', 'toolsapi', 'visualizers', 'xml', 'db',
+ 'websnap', 'clx');
-function IsShippedThirdParty(const APath: string): Boolean;
+// uma unit das bibliotecas de terceiros que vem com o Delphi (Indy, DUnit, DUnitX, Skia, FlatBox2D), pelo nome.
+// As do Indy comecam por Id seguido de maiuscula (IdHTTP, IdGlobal); nenhuma unit da Embarcadero tem esse padrao
+function IsBundledThirdPartyUnit(const AUnitName: string): Boolean;
+begin
+ Result := ((Length(AUnitName) > 2) and AUnitName.StartsWith('Id') and CharInSet(AUnitName[3], ['A'..'Z'])) or
+ StartsText('DUnitX.', AUnitName) or StartsText('TestFramework', AUnitName) or StartsText('TestExtensions', AUnitName) or
+ StartsText('GUITestRunner', AUnitName) or StartsText('TextTestRunner', AUnitName) or
+ ContainsText(AUnitName, 'Skia') or StartsText('Box2D', AUnitName);
+end;
+
+// o ficheiro e da propria Embarcadero: esta em \lib\ (menos os DCU das bibliotecas de terceiros) ou numa pasta
+// conhecida de \source\
+function IsEmbarcaderoPath(const APath, ADelphiRoot: string): Boolean;
var
- Lower, Folder: string;
+ Rel: string;
+ Slash: Integer;
begin
- Lower := LowerCase(APath);
- for Folder in ShippedThirdParty do
- if Pos('\source\' + Folder + '\', Lower) > 0 then
- Exit(True);
- Result := False;
+ if not IsUnderFolder(APath, ADelphiRoot) then
+ Exit(False);
+ Rel := LowerCase(Copy(TPath.GetFullPath(APath), Length(IncludeTrailingPathDelimiter(TPath.GetFullPath(ADelphiRoot))) + 1,
+ MaxInt));
+ // o lib\ tem tambem os DCU das bibliotecas de terceiros que vem com o Delphi: contam como terceiros pelo nome
+ if Rel.StartsWith('lib\') then
+ Exit(not IsBundledThirdPartyUnit(TPath.GetFileNameWithoutExtension(APath))); // APath: Rel esta em minusculas
+ if not Rel.StartsWith('source\') then
+ Exit(False);
+ Rel := Copy(Rel, Length('source\') + 1, MaxInt);
+ Slash := Pos('\', Rel);
+ Result := (Slash > 1) and MatchText(Copy(Rel, 1, Slash - 1), EmbarcaderoSourceFolders);
end;
-// de quem e uma unit de fora do codigo analisado: da Embarcadero (se o ficheiro esta dentro da instalacao) ou de terceiros.
+// de quem e uma unit de fora do codigo analisado: da Embarcadero (so as pastas dela dentro da instalacao) ou de terceiros.
// As units do proprio projecto ja estao no grafo; uma que apareca noutra pasta, mesmo dentro da do projecto (uma biblioteca
// copiada para libs\ ou modules\), e uma dependencia
function OriginOfPath(const APath, AUnitName, ADelphiRoot: string): TSbomOrigin;
var
Lower: string;
begin
- if IsUnderFolder(APath, ADelphiRoot) and not IsShippedThirdParty(APath) then
+ if IsEmbarcaderoPath(APath, ADelphiRoot) then
begin
Lower := LowerCase(APath);
if SameText(Copy(AUnitName, 1, 4), 'Vcl.') or (Pos('\source\vcl\', Lower) > 0) then
diff --git a/src/Services/CM.DepsReport.pas b/src/Services/CM.DepsReport.pas
index 40c372b..97ab3b1 100644
--- a/src/Services/CM.DepsReport.pas
+++ b/src/Services/CM.DepsReport.pas
@@ -233,10 +233,10 @@ function DepsMarkdown(AGraph: TDepGraph; const AProjectName: string): string;
const
HtmlCss =
- ':root{--bg:#f6f7f4;--surface:#fff;--surface2:#eef0eb;--border:#dcded7;--text:#1b1d1a;--dim:#5a5f58;--faint:#8b908a;' +
+ ':root{--bg:#f6f7f4;--surface:#fff;--surface2:#eef0eb;--border:#dcded7;--text:#1b1d1a;--dim:#5a5f58;--faint:#676c62;' +
'--accent:#216b59;--accent2:#e0ece8;--danger:#c5523d;--blue:#3f7fe0}' +
'@media(prefers-color-scheme:dark){:root{--bg:#121514;--surface:#1a1e1d;--surface2:#222726;--border:#2e3433;' +
- '--text:#e8ebe8;--dim:#a3aaa5;--faint:#6f7772;--accent:#4fb89b;--accent2:#1e2f2b;--danger:#e0705a;--blue:#6fa8ff}}' +
+ '--text:#e8ebe8;--dim:#a3aaa5;--faint:#8a908b;--accent:#4fb89b;--accent2:#1e2f2b;--danger:#e0705a;--blue:#6fa8ff}}' +
'*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:14px/1.5 "Segoe UI",system-ui,sans-serif}' +
'.wrap{max-width:1280px;margin:0 auto;padding:28px 24px 60px}h1{margin:0 0 4px;font-size:26px}' +
'h2{margin:34px 0 12px;font-size:18px}.sub{color:var(--dim);margin:0 0 20px}' +
diff --git a/src/Services/CM.GitReview.pas b/src/Services/CM.GitReview.pas
index 63da3ed..48ba8ea 100644
--- a/src/Services/CM.GitReview.pas
+++ b/src/Services/CM.GitReview.pas
@@ -1,102 +1,206 @@
-unit CM.GitReview;
-
-{ Cruza as revisoes guardadas com o Git: que ficheiros revistos mudaram desde a revisao.
-
- Cada ficheiro guarda o commit em que foi revisto (TUnitState.Rev). Aqui comparam-se esses
- commits com o estado actual do repositorio (incluindo o que ainda nao foi gravado no Git). As
- revisoes antigas, feitas antes de existir este registo, ganham o commit que era o actual na hora em
- que foram concluidas. Sem Git, ou fora de um repositorio, nao ha nada para mostrar. }
-
-interface
-
-uses
- System.SysUtils, System.Classes, System.Math, System.Generics.Collections, CM.Analyzer, CM.Store, CM.Stats, CM.Vcs;
-
-type
- TGitReviewResult = record
- Head: string; // commit actual ('' = sem Git / sem repositorio)
- Stale: THashSet; // caminhos dos ficheiros revistos que mudaram desde a revisao
- Backfilled: Integer; // revisoes antigas a que se deduziu o commit (o progresso mudou)
- end;
-
-// o resultado e de quem chama (liberta Stale)
-function FindStaleReviews(const ARoot: string; AScan: TProjectScan; AState: TProgressState): TGitReviewResult;
-// texto para a dica de um ficheiro alterado: quantos commits desde a revisao e o ultimo
-function StaleHint(const ARoot, ARev, ARelPath: string): string;
-
-implementation
-
-
-uses
- CM.Lang;
-function FindStaleReviews(const ARoot: string; AScan: TProjectScan; AState: TProgressState): TGitReviewResult;
-var
- Groups: TObjectDictionary>;
- Pair: TPair>;
- U: TUnitInfo;
- S: TUnitState;
- Changed: THashSet;
- Timeline: TArray;
- List: TList;
-begin
- Result := Default(TGitReviewResult);
- Result.Stale := THashSet.Create;
- if (AScan = nil) or (AState = nil) or (ARoot = '') then
- Exit;
- Result.Head := VcsHead(ARoot);
- if Result.Head = '' then
- Exit;
-
- Timeline := VcsTimeline(ARoot);
- Result.Backfilled := BackfillRevisions(AScan, AState, Timeline);
-
- // agrupa por commit de revisao: uma consulta ao Git por commit, nao por ficheiro
- Groups := TObjectDictionary>.Create([doOwnsValues]);
- try
- for U in AScan.Units do
- begin
- S := AState.Find(U.Path);
- if (S = nil) or (S.Rev = '') or (ReviewOfUnit(U, AState) = rsPending) then
- Continue;
- if not Groups.TryGetValue(S.Rev, List) then
- begin
- List := TList.Create;
- Groups.Add(S.Rev, List);
- end;
- List.Add(U);
- end;
- for Pair in Groups do
- begin
- Changed := THashSet.Create;
- try
- if VcsChangedSince(ARoot, Pair.Key, Changed) then
- for U in Pair.Value do
- if Changed.Contains(U.Path) then
- Result.Stale.Add(U.Path);
- finally
- Changed.Free;
- end;
- end;
- finally
- Groups.Free;
- end;
-end;
-
-function StaleHint(const ARoot, ARev, ARelPath: string): string;
-const
- Shown = 3;
-var
- Commits: TArray;
- I: Integer;
-begin
- Commits := VcsCommitsSince(ARoot, ARev, ARelPath, Shown + 1);
- if Length(Commits) = 0 then
- Exit(TrF('Mudou desde a revisão (alterações ainda por gravar no %s)', [VcsName(DetectVcs(ARoot))]));
- Result := Tr('Mudou desde a revisão:');
- for I := 0 to Min(Shown, Length(Commits)) - 1 do
- Result := Result + sLineBreak + Commits[I].Date + ' · ' + Commits[I].Author + ' · ' + Commits[I].Subject;
- if Length(Commits) > Shown then
- Result := Result + sLineBreak + '…';
-end;
-
-end.
+unit CM.GitReview;
+
+{ Cruza as revisoes guardadas com o Git: que ficheiros revistos mudaram desde a revisao.
+
+ Cada ficheiro guarda o commit em que foi revisto (TUnitState.Rev). Aqui comparam-se esses
+ commits com o estado actual do repositorio (incluindo o que ainda nao foi gravado no Git). As
+ revisoes antigas, feitas antes de existir este registo, ganham o commit que era o actual na hora em
+ que foram concluidas. Sem Git, ou fora de um repositorio, nao ha nada para mostrar. }
+
+interface
+
+uses
+ System.SysUtils, System.Classes, System.Math, System.Generics.Collections, CM.Analyzer, CM.Store, CM.Stats, CM.Vcs;
+
+type
+ // um ficheiro revisto copiado na thread da interface, para a consulta ao Git correr em segundo plano
+ TReviewSnap = record
+ Path: string;
+ Rev: string; // commit da revisao ('' = revisao antiga: deduz-se da hora)
+ Ts: Int64; // hora da conclusao (ms)
+ end;
+
+ TGitReviewResult = record
+ Head: string; // commit actual ('' = sem Git / sem repositorio)
+ Stale: THashSet; // caminhos dos ficheiros revistos que mudaram desde a revisao
+ Backfilled: Integer; // revisoes antigas a que se deduziu o commit (o progresso mudou)
+ Backfill: TArray; // as revisoes antigas com o commit deduzido em Rev (por gravar no progresso)
+ end;
+
+// o resultado e de quem chama (liberta Stale). Tudo seguido: le o Git e grava os commits deduzidos
+function FindStaleReviews(const ARoot: string; AScan: TProjectScan; AState: TProgressState): TGitReviewResult;
+// os ficheiros revistos (menos os "por rever") com commit ou hora de conclusao; corre na thread da interface
+function SnapReviews(AScan: TProjectScan; AState: TProgressState): TArray;
+// o historico completo so faz falta se alguma revisao antiga ainda nao tem commit
+function NeedsTimeline(const ASnaps: TArray): Boolean;
+// so le o controlo de versoes (pode correr em segundo plano): nao mexe no progresso, Backfilled fica 0
+function ComputeStaleReviews(const ARoot: string; const ASnaps: TArray): TGitReviewResult;
+// grava os commits deduzidos onde o ficheiro continua como foi copiado (sem commit, mesma hora); devolve quantos
+function ApplyBackfill(AState: TProgressState; const ABackfill: TArray): Integer;
+// texto para a dica de um ficheiro alterado: quantos commits desde a revisao e o ultimo
+function StaleHint(const ARoot, ARev, ARelPath: string): string;
+
+implementation
+
+
+uses
+ CM.Lang;
+function FindStaleReviews(const ARoot: string; AScan: TProjectScan; AState: TProgressState): TGitReviewResult;
+begin
+ if (AScan = nil) or (AState = nil) or (ARoot = '') then
+ begin
+ Result := Default(TGitReviewResult);
+ Result.Stale := THashSet.Create;
+ Exit;
+ end;
+ Result := ComputeStaleReviews(ARoot, SnapReviews(AScan, AState));
+ Result.Backfilled := ApplyBackfill(AState, Result.Backfill);
+end;
+
+function SnapReviews(AScan: TProjectScan; AState: TProgressState): TArray;
+var
+ U: TUnitInfo;
+ S: TUnitState;
+ Snap: TReviewSnap;
+ List: TList;
+begin
+ Result := nil;
+ if (AScan = nil) or (AState = nil) then
+ Exit;
+ List := TList.Create;
+ try
+ for U in AScan.Units do
+ begin
+ S := AState.Find(U.Path);
+ // sem commit nem hora nao ha com que comparar (o mesmo criterio de BackfillRevisions)
+ if (S = nil) or ((S.Rev = '') and (S.Ts <= 0)) or (ReviewOfUnit(U, AState) = rsPending) then
+ Continue;
+ Snap.Path := U.Path;
+ Snap.Rev := S.Rev;
+ Snap.Ts := S.Ts;
+ List.Add(Snap);
+ end;
+ Result := List.ToArray;
+ finally
+ List.Free;
+ end;
+end;
+
+function NeedsTimeline(const ASnaps: TArray): Boolean;
+var
+ Snap: TReviewSnap;
+begin
+ for Snap in ASnaps do
+ if Snap.Rev = '' then
+ Exit(True);
+ Result := False;
+end;
+
+function ComputeStaleReviews(const ARoot: string; const ASnaps: TArray): TGitReviewResult;
+var
+ Groups: TObjectDictionary>;
+ Pair: TPair>;
+ Snap, Found: TReviewSnap;
+ Changed: THashSet;
+ Timeline: TArray;
+ Backfill: TList;
+ List: TList;
+ Rev, Path: string;
+begin
+ Result := Default(TGitReviewResult);
+ Result.Stale := THashSet.Create;
+ try
+ if ARoot = '' then
+ Exit;
+ Result.Head := VcsHead(ARoot);
+ if Result.Head = '' then
+ Exit;
+ // o "git log" completo so quando alguma revisao antiga ainda precisa do commit
+ if NeedsTimeline(ASnaps) then
+ Timeline := VcsTimeline(ARoot);
+
+ // agrupa por commit de revisao: uma consulta ao Git por commit, nao por ficheiro
+ Groups := TObjectDictionary>.Create([doOwnsValues]);
+ Backfill := TList.Create;
+ try
+ for Snap in ASnaps do
+ begin
+ Rev := Snap.Rev;
+ if Rev = '' then
+ begin
+ Rev := CommitAt(Timeline, Snap.Ts div 1000);
+ if Rev = '' then
+ Continue;
+ Found := Snap;
+ Found.Rev := Rev;
+ Backfill.Add(Found);
+ end;
+ if not Groups.TryGetValue(Rev, List) then
+ begin
+ List := TList.Create;
+ Groups.Add(Rev, List);
+ end;
+ List.Add(Snap.Path);
+ end;
+ Result.Backfill := Backfill.ToArray;
+ for Pair in Groups do
+ begin
+ Changed := THashSet.Create;
+ try
+ if VcsChangedSince(ARoot, Pair.Key, Changed) then
+ for Path in Pair.Value do
+ if Changed.Contains(Path) then
+ Result.Stale.Add(Path);
+ finally
+ Changed.Free;
+ end;
+ end;
+ finally
+ Backfill.Free;
+ Groups.Free;
+ end;
+ except
+ Result.Stale.Free;
+ Result.Stale := nil;
+ raise;
+ end;
+end;
+
+function ApplyBackfill(AState: TProgressState; const ABackfill: TArray): Integer;
+var
+ Snap: TReviewSnap;
+ S: TUnitState;
+begin
+ Result := 0;
+ if AState = nil then
+ Exit;
+ for Snap in ABackfill do
+ begin
+ S := AState.Find(Snap.Path);
+ // entretanto pode ter sido revisto de novo ou reposto: a deducao ja nao vale
+ if (S <> nil) and (S.Rev = '') and (S.Ts = Snap.Ts) then
+ begin
+ S.Rev := Snap.Rev;
+ Inc(Result);
+ end;
+ end;
+end;
+
+function StaleHint(const ARoot, ARev, ARelPath: string): string;
+const
+ Shown = 3;
+var
+ Commits: TArray;
+ I: Integer;
+begin
+ Commits := VcsCommitsSince(ARoot, ARev, ARelPath, Shown + 1);
+ if Length(Commits) = 0 then
+ Exit(TrF('Mudou desde a revisão (alterações ainda por gravar no %s)', [VcsName(DetectVcs(ARoot))]));
+ Result := Tr('Mudou desde a revisão:');
+ for I := 0 to Min(Shown, Length(Commits)) - 1 do
+ Result := Result + sLineBreak + Commits[I].Date + ' · ' + Commits[I].Author + ' · ' + Commits[I].Subject;
+ if Length(Commits) > Shown then
+ Result := Result + sLineBreak + '…';
+end;
+
+end.
diff --git a/src/Services/CM.SbomFormats.pas b/src/Services/CM.SbomFormats.pas
index 9716973..c5f0f1e 100644
--- a/src/Services/CM.SbomFormats.pas
+++ b/src/Services/CM.SbomFormats.pas
@@ -1,6 +1,6 @@
unit CM.SbomFormats;
-{ Escreve um SBOM (CM.Sbom) nos dois formatos padrao em JSON: CycloneDX 1.5 e SPDX 2.3. Cada componente e uma unit com o
+{ Escreve um SBOM (CM.Sbom) nos dois formatos padrao em JSON: CycloneDX 1.6 e SPDX 2.3. Cada componente e uma unit com o
seu SHA-256 (quando se achou o ficheiro), a origem, a evidencia e a confianca. Os validadores conferem o essencial
(campos obrigatorios, referencias que existem, identificadores unicos e hashes bem formados) e dizem o que falha.
@@ -38,7 +38,8 @@ implementation
System.Classes, System.IOUtils, System.JSON, System.DateUtils, System.TimeSpan, System.Generics.Collections, System.RegularExpressions, System.StrUtils;
const
- CdxSpecVersion = '1.5';
+ // 1.6: a versao minima que a BSI TR-03183-2 v2.1.0 aceita (o SPDX 2.3 nao chega para ela)
+ CdxSpecVersion = '1.6';
SpdxVersion = 'SPDX-2.3';
EmbarcaderoSupplier = 'Embarcadero Technologies, Inc.';
@@ -220,6 +221,8 @@ function CdxMetadata(ASbom: TSbom; const AOptions: TSbomWriteOptions): TJSONObje
Sup.AddPair('name', P.Company);
App.AddPair('supplier', Sup);
end;
+ if P.Copyright <> '' then
+ App.AddPair('copyright', P.Copyright);
Result.AddPair('component', App);
Props := TJSONArray.Create;
if P.FrameworkType <> '' then
@@ -247,6 +250,7 @@ function CdxDependencies(ASbom: TSbom): TJSONArray;
Entry: TJSONObject;
Item: TPair>;
Ref: string;
+ Keys: TArray;
begin
Result := TJSONArray.Create;
Deps := TDictionary>.Create;
@@ -273,12 +277,15 @@ function CdxDependencies(ASbom: TSbom): TJSONArray;
end;
Root.AddPair('dependsOn', RootDeps);
Result.Add(Root);
- for Item in Deps do
+ // por ordem do nome: o dicionario nao tem ordem, e assim dois SBOM do mesmo projecto so diferem no numero de serie e na data
+ Keys := Deps.Keys.ToArray;
+ TArray.Sort(Keys);
+ for Key in Keys do
begin
Entry := TJSONObject.Create;
- Entry.AddPair('ref', Item.Key);
+ Entry.AddPair('ref', Key);
List := TJSONArray.Create;
- for Ref in Item.Value do
+ for Ref in Deps[Key] do
List.Add(Ref);
Entry.AddPair('dependsOn', List);
Result.Add(Entry);
@@ -302,7 +309,7 @@ function SbomCycloneDxJson(ASbom: TSbom; const AOptions: TSbomWriteOptions): str
Serial := NewGuidText;
Root := TJSONObject.Create;
try
- Root.AddPair('$schema', 'http://cyclonedx.org/schema/bom-1.5.schema.json');
+ Root.AddPair('$schema', 'http://cyclonedx.org/schema/bom-' + CdxSpecVersion + '.schema.json');
Root.AddPair('bomFormat', 'CycloneDX');
Root.AddPair('specVersion', CdxSpecVersion);
Root.AddPair('serialNumber', 'urn:uuid:' + Serial);
@@ -334,7 +341,7 @@ function SpdxSafe(const AValue: string): string;
end;
function SpdxPackage(const ASpdxId, AName, AVersion, ASupplier, AHash, ADescription: string; const ALicense: string = '';
- const AHomePage: string = ''): TJSONObject;
+ const AHomePage: string = ''; const ACopyright: string = ''): TJSONObject;
var
Sums: TJSONArray;
Sum: TJSONObject;
@@ -357,7 +364,7 @@ function SpdxPackage(const ASpdxId, AName, AVersion, ASupplier, AHash, ADescript
Result.AddPair('licenseDeclared', 'NOASSERTION');
if IsWebUrl(AHomePage) then
Result.AddPair('homepage', AHomePage);
- Result.AddPair('copyrightText', 'NOASSERTION');
+ Result.AddPair('copyrightText', IfThen(ACopyright <> '', ACopyright, 'NOASSERTION'));
if AHash <> '' then
begin
Sums := TJSONArray.Create;
@@ -429,7 +436,7 @@ function SbomSpdxJson(ASbom: TSbom; const AOptions: TSbomWriteOptions): string;
Root.AddPair('creationInfo', Creation);
Packages := TJSONArray.Create;
- Packages.Add(SpdxPackage(RootId, ProjectNameOf(ASbom), P.Version, P.Company, '', P.Description));
+ Packages.Add(SpdxPackage(RootId, ProjectNameOf(ASbom), P.Version, P.Company, '', P.Description, '', '', P.Copyright));
for C in ASbom.Components do
Packages.Add(SpdxPackage(Ids[LowerCase(C.Name)], C.Name, C.Version, SupplierOf(C.Origin), C.Hash,
OriginName(C.Origin) + ' · ' + EvidenceName(C.Evidence) + ' · ' + ConfidenceName(C.Confidence) +
diff --git a/src/Services/CM.SbomReport.pas b/src/Services/CM.SbomReport.pas
index ed9ec59..bf12ae4 100644
--- a/src/Services/CM.SbomReport.pas
+++ b/src/Services/CM.SbomReport.pas
@@ -27,10 +27,10 @@ implementation
const
ReportCss =
- ':root{--bg:#f6f7f4;--surface:#fff;--surface2:#eef0eb;--border:#dcded7;--text:#1b1d1a;--dim:#5a5f58;--faint:#8b908a;' +
+ ':root{--bg:#f6f7f4;--surface:#fff;--surface2:#eef0eb;--border:#dcded7;--text:#1b1d1a;--dim:#5a5f58;--faint:#676c62;' +
'--accent:#216b59;--accent2:#e0ece8;--danger:#c5523d;--warn:#a8741a;--blue:#3f7fe0}' +
'@media(prefers-color-scheme:dark){:root{--bg:#121514;--surface:#1a1e1d;--surface2:#222726;--border:#2e3433;' +
- '--text:#e8ebe8;--dim:#a3aaa5;--faint:#6f7772;--accent:#4fb89b;--accent2:#1e2f2b;--danger:#e0705a;--warn:#e0b050;--blue:#6fa8ff}}' +
+ '--text:#e8ebe8;--dim:#a3aaa5;--faint:#8a908b;--accent:#4fb89b;--accent2:#1e2f2b;--danger:#e0705a;--warn:#e0b050;--blue:#6fa8ff}}' +
'*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:14px/1.5 "Segoe UI",system-ui,sans-serif}' +
'.wrap{max-width:1180px;margin:0 auto;padding:28px 24px 60px}h1{margin:0 0 4px;font-size:26px}' +
'h2{margin:34px 0 12px;font-size:18px}.sub{color:var(--dim);margin:0 0 20px}p.note{color:var(--dim);max-width:900px}' +
diff --git a/src/Services/CM.SbomService.pas b/src/Services/CM.SbomService.pas
index 10864e2..065ae95 100644
--- a/src/Services/CM.SbomService.pas
+++ b/src/Services/CM.SbomService.pas
@@ -38,6 +38,7 @@ implementation
WarnNoDproj = 'Não se encontrou o ficheiro .dproj: a versão e os caminhos de procura ficam por preencher.';
WarnNoDelphi = 'Não se encontrou a instalação do Delphi: as units da Embarcadero só se reconhecem pelo nome.';
WarnNoMap = 'Não se encontrou o ficheiro .map: compila o projeto com o mapa «Detailed» para confirmar as units ligadas.';
+ WarnMapNoUnits = 'O ficheiro .map não tem units que se consigam ler (pode estar incompleto ou ter outro formato): volta a compilar o projeto com o mapa ligado.';
function DefaultSbomGenOptions: TSbomGenOptions;
begin
@@ -73,6 +74,7 @@ function GenerateSbom(AGraph: TDepGraph; const ARoot, AProjectName: string; cons
Project: TSbomProject;
Resolve: TSbomResolveOptions;
DelphiRoot, DprojFile, MapPath, BaseDir: string;
+ MapUnits: TArray;
begin
DelphiRoot := AOptions.DelphiRoot;
if (DelphiRoot = '') and AOptions.AutoDelphi then
@@ -81,7 +83,13 @@ function GenerateSbom(AGraph: TDepGraph; const ARoot, AProjectName: string; cons
Vars := IdeEnvironmentVars(DelphiRoot); // as variaveis do IDE (so as que o utilizador definiu)
try
if DelphiRoot <> '' then
+ begin
Vars.AddOrSetValue('bds', DelphiRoot);
+ // o que os packages do IDE usam por omissao: DCC_BplOutput $(BDSCOMMONDIR)\Bpl e DllSuffix $(Auto) (37.0 -> 370)
+ // (se o utilizador definiu a sua no IDE, vale essa)
+ Vars.TryAdd('bdscommondir', BdsCommonDir(DelphiRoot));
+ Vars.TryAdd('auto', StringReplace(ExtractFileName(DelphiRoot), '.', '', [rfReplaceAll]));
+ end;
DprojFile := FindDprojFile(ARoot, AProjectName);
LoadDproj(DprojFile, AOptions.Config, AOptions.Platform, Vars, Dproj);
finally
@@ -122,10 +130,17 @@ function GenerateSbom(AGraph: TDepGraph; const ARoot, AProjectName: string; cons
if AOptions.UseMap then
begin
MapPath := FindMapFile(Dproj);
- if MapPath <> '' then
- ApplyMapUnits(Result, LoadMapUnits(MapPath), MapPath)
+ if MapPath = '' then
+ Result.Warnings.Add(WarnNoMap)
else
- Result.Warnings.Add(WarnNoMap);
+ begin
+ MapUnits := LoadMapUnits(MapPath);
+ // um mapa sem units legiveis (incompleto, ou de outro linker) nao diz que units ficaram: usa-lo poria todas de fora
+ if Length(MapUnits) > 0 then
+ ApplyMapUnits(Result, MapUnits, MapPath)
+ else
+ Result.Warnings.Add(WarnMapNoUnits);
+ end;
end;
if Dproj.Found then
diff --git a/src/UI/CM.ClassView.pas b/src/UI/CM.ClassView.pas
index 6f2ece4..ee521da 100644
--- a/src/UI/CM.ClassView.pas
+++ b/src/UI/CM.ClassView.pas
@@ -21,11 +21,12 @@ TClassRow = record
Children: Integer;
Methods: Integer;
FileText: string;
- Hint: string;
- Tag: Integer; // o indice da classe, para quem abre o codigo
+ Tag: Integer; // o indice da classe, para quem abre o codigo e para a dica
end;
TClassOpenEvent = procedure(Sender: TObject; ATag: Integer) of object;
+ // a dica de uma linha, pedida so quando o rato passa por ela (montar todas a cada tecla da pesquisa custava)
+ TClassHintEvent = function(Sender: TObject; ATag: Integer): string of object;
TClassSortEvent = procedure(Sender: TObject; AColumn: Integer) of object;
TCMClassList = class(TCMControl)
@@ -40,10 +41,12 @@ TCMClassList = class(TCMControl)
FDblClick: TDoubleClickTracker;
FOnOpen: TClassOpenEvent;
FOnSort: TClassSortEvent;
+ FOnHint: TClassHintEvent;
function MaxScroll: Single;
function RowAt(Y: Single): Integer;
function ColumnAt(X: Single): Integer;
function NameWidth: Single;
+ function FileWidth: Single;
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
@@ -63,6 +66,7 @@ TCMClassList = class(TCMControl)
property SortDescending: Boolean read FSortDesc;
property OnOpen: TClassOpenEvent read FOnOpen write FOnOpen;
property OnSort: TClassSortEvent read FOnSort write FOnSort;
+ property OnHint: TClassHintEvent read FOnHint write FOnHint;
end;
implementation
@@ -73,7 +77,6 @@ implementation
DepthW = 92;
ChildW = 70;
MethW = 80;
- FileW = 230;
Indent = 14;
function ChildrenText(AChildren: Integer): string;
@@ -128,7 +131,14 @@ procedure TCMClassList.SetSort(AColumn: Integer; ADescending: Boolean);
function TCMClassList.NameWidth: Single;
begin
- Result := Max(120, Width - 16 - DepthW - ChildW - MethW - FileW - 20);
+ // o espaco que sobra reparte-se entre o nome e o ficheiro (com o ficheiro fixo, os caminhos ficavam cortados e a
+ // coluna do nome quase vazia)
+ Result := Max(140, (Width - 16 - DepthW - ChildW - MethW - 20) * 0.5);
+end;
+
+function TCMClassList.FileWidth: Single;
+begin
+ Result := Max(120, Width - 16 - DepthW - ChildW - MethW - 20 - NameWidth);
end;
function TCMClassList.MaxScroll: Single;
@@ -190,6 +200,14 @@ procedure TCMClassList.Paint;
DrawTextRect(Canvas, TRectF.Create(ALeft, 0, ALeft + AWidth, HeadH), T, Color, 11, UiFont, [TFontStyle.fsBold], AAlign);
end;
+ // o FitText mede com a fonte do canvas: tem de ser a que se desenha a seguir
+ procedure SetFont(ASize: Single; const AFamily: string);
+ begin
+ Canvas.Font.Family := AFamily;
+ Canvas.Font.Size := ScaledSize(ASize);
+ Canvas.Font.Style := [];
+ end;
+
begin
NameW := NameWidth;
X := 12;
@@ -201,7 +219,7 @@ procedure TCMClassList.Paint;
X := X + ChildW;
Head(3, X, MethW - 10, TTextAlign.Trailing);
X := X + MethW;
- Head(4, X + 10, FileW - 10, TTextAlign.Leading);
+ Head(4, X + 10, FileWidth - 10, TTextAlign.Leading);
FillRound(Canvas, TRectF.Create(8, HeadH - 1, Width - 8, HeadH), 0, Pal.Border);
if Length(FRows) = 0 then
@@ -225,13 +243,14 @@ procedure TCMClassList.Paint;
W := NameW - Row.Indent * Indent;
if Row.KindText <> '' then
begin
- TagR := TRectF.Create(Left, R.CenterPoint.Y - 8, Left + MeasureText(Row.KindText, 9.5, UiFont, [TFontStyle.fsBold]) + 12,
+ TagR := TRectF.Create(Left, R.CenterPoint.Y - 8, Left + MeasureText(Row.KindText, 10.5, UiFont, [TFontStyle.fsBold]) + 12,
R.CenterPoint.Y + 8);
StrokeRound(Canvas, TagR, 8, Pal.TextFaint, 1);
- DrawTextRect(Canvas, TagR, Row.KindText, Pal.TextFaint, 9.5, UiFont, [TFontStyle.fsBold], TTextAlign.Center);
+ DrawTextRect(Canvas, TagR, Row.KindText, Pal.TextFaint, 10.5, UiFont, [TFontStyle.fsBold], TTextAlign.Center);
Left := TagR.Right + 6;
W := W - (TagR.Width + 6);
end;
+ SetFont(12, MonoFont);
DrawTextRect(Canvas, TRectF.Create(Left, R.Top, Left + Max(20, W), R.Bottom), FitText(Canvas, Row.Name, Max(20, W)),
Pal.Text, 12, MonoFont);
X := X + NameW + 8;
@@ -246,7 +265,8 @@ procedure TCMClassList.Paint;
DrawTextRect(Canvas, TRectF.Create(X, R.Top, X + MethW - 10, R.Bottom), IntToStr(Row.Methods), Pal.TextDim, 11.5, MonoFont,
[], TTextAlign.Trailing);
X := X + MethW;
- DrawTextRect(Canvas, TRectF.Create(X + 10, R.Top, X + FileW, R.Bottom), FitText(Canvas, Row.FileText, FileW - 10),
+ SetFont(11, MonoFont);
+ DrawTextRect(Canvas, TRectF.Create(X + 10, R.Top, X + FileWidth, R.Bottom), FitText(Canvas, Row.FileText, FileWidth - 10),
Pal.TextFaint, 11, MonoFont);
end;
if MaxScroll > 0 then
@@ -255,7 +275,7 @@ procedure TCMClassList.Paint;
ThumbH := Max(24, TrackH * (Height - HeadH) / (Length(FRows) * RowH + 8));
ThumbR := TRectF.Create(Width - 9, HeadH + 4 + (TrackH - ThumbH) * (FScrollY / MaxScroll), Width - 3,
HeadH + 4 + (TrackH - ThumbH) * (FScrollY / MaxScroll) + ThumbH);
- FillRound(Canvas, ThumbR, 3, Fade(Pal.TextFaint, 0.55));
+ FillRound(Canvas, ThumbR, 3, Fade(Pal.TextFaint, 0.8));
end;
end;
@@ -290,9 +310,9 @@ procedure TCMClassList.MouseMove(Shift: TShiftState; X, Y: Single);
if Idx <> FHover then
begin
FHover := Idx;
- if Idx >= 0 then
+ if (Idx >= 0) and Assigned(FOnHint) then
begin
- Hint := FRows[Idx].Hint;
+ Hint := FOnHint(Self, FRows[Idx].Tag);
ShowHint := True;
end;
Repaint;
diff --git a/src/UI/CM.CodeView.pas b/src/UI/CM.CodeView.pas
index 3e2d7f5..521e94b 100644
--- a/src/UI/CM.CodeView.pas
+++ b/src/UI/CM.CodeView.pas
@@ -30,6 +30,8 @@ TCMCodeView = class(TCMControl)
FLineH, FCharW: Single;
FLigatures: Boolean;
FMarkers: TArray; // por linha, a ordem de chegada
+ FFirstMark: TDictionary; // linha -> indice do primeiro ponto dessa linha em FMarkers
+ FGutter: Single; // GutterW, medido uma vez por Paint (usado por DrawSegment)
function MarkersOnLine(ALine: Integer): TArray;
procedure MeasureFont;
procedure SetLigatures(const Value: Boolean);
@@ -58,6 +60,7 @@ TCMCodeView = class(TCMControl)
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
+ destructor Destroy; override;
// ADoc continua a ser de quem o passou; nil limpa a vista. O scroll volta ao principio
procedure SetDoc(ADoc: TCodeDoc);
// leva a linha (a partir de 0) para o terco de cima da vista e destaca-a
@@ -165,10 +168,17 @@ constructor TCMCodeView.Create(AOwner: TComponent);
FMarkLine := -1;
FLineH := Round(ScaledSize(CodeFontSize) * 1.6);
FLigatures := True;
+ FFirstMark := TDictionary.Create;
MeasureFont;
FEmptyText := Tr('Sem código para mostrar.');
end;
+destructor TCMCodeView.Destroy;
+begin
+ FFirstMark.Free;
+ inherited;
+end;
+
procedure TCMCodeView.MeasureFont;
begin
FLineH := Round(ScaledSize(CodeFontSize) * 1.6);
@@ -178,8 +188,13 @@ procedure TCMCodeView.MeasureFont;
end;
procedure TCMCodeView.SetMarkers(const AMarkers: TArray);
+var
+ I: Integer;
begin
FMarkers := AMarkers;
+ FFirstMark.Clear;
+ for I := 0 to High(FMarkers) do
+ FFirstMark.TryAdd(FMarkers[I].Line, I); // so o primeiro de cada linha: e o que o Paint desenha
Repaint;
end;
@@ -188,6 +203,8 @@ function TCMCodeView.MarkersOnLine(ALine: Integer): TArray;
M: TCodeMarker;
begin
Result := nil;
+ if not FFirstMark.ContainsKey(ALine) then
+ Exit;
for M in FMarkers do
if M.Line = ALine then
Result := Result + [M];
@@ -330,10 +347,12 @@ procedure TCMCodeView.DrawSegment(const AText: string; AFrom, ALen: Integer; AKi
begin
if ALen <= 0 then
Exit;
- X := GutterW + 12 + (AFrom - 1) * FCharW - FScrollX;
- if (X + ALen * FCharW < GutterW) or (X > Width) then
+ X := FGutter + 12 + (AFrom - 1) * FCharW - FScrollX;
+ if (X + ALen * FCharW < FGutter) or (X > Width) then
Exit; // fora da vista
S := Copy(AText, AFrom, ALen);
+ if (AKind = skPlain) and (Trim(S) = '') then
+ Exit; // so espacos (o recuo): nao ha nada para desenhar
Style := [];
if AKind = skKeyword then
Style := [TFontStyle.fsBold]
@@ -423,9 +442,9 @@ function TCMCodeView.HThumb: TRectF;
procedure TCMCodeView.DrawScrollbars;
begin
if MaxScrollY > 0 then
- FillRound(Canvas, VThumb, 4, Fade(Pal.TextFaint, IfThen(FDragV, 0.9, 0.55)));
+ FillRound(Canvas, VThumb, 4, Fade(Pal.TextFaint, IfThen(FDragV, 0.9, 0.8)));
if MaxScrollX > 0 then
- FillRound(Canvas, HThumb, 4, Fade(Pal.TextFaint, IfThen(FDragH, 0.9, 0.55)));
+ FillRound(Canvas, HThumb, 4, Fade(Pal.TextFaint, IfThen(FDragH, 0.9, 0.8)));
end;
procedure TCMCodeView.Paint;
@@ -436,6 +455,7 @@ procedure TCMCodeView.Paint;
G: Single;
NumR, Row, Dot: TRectF;
Mk: TCodeMarker;
+ MkIdx: Integer;
begin
State := Canvas.SaveState;
try
@@ -447,6 +467,7 @@ procedure TCMCodeView.Paint;
Exit;
end;
G := GutterW;
+ FGutter := G;
// a margem com os numeros de linha
FillRound(Canvas, TRectF.Create(0, 0, G, Height), 0, Pal.Surface2);
FillRound(Canvas, TRectF.Create(G, 0, G + 1, Height), 0, Pal.Border);
@@ -462,16 +483,15 @@ procedure TCMCodeView.Paint;
FillRound(Canvas, Row, 0, Fade(Pal.Accent, 0.13));
end;
NumR := TRectF.Create(0, Y, G - 10, Y + FLineH);
- if Length(FMarkers) > 0 then
- for Mk in MarkersOnLine(I) do
- begin
- Dot := TRectF.Create(5, Y + FLineH / 2 - 3.5, 12, Y + FLineH / 2 + 3.5);
- if Mk.Ring then
- StrokeRound(Canvas, Dot, 3.5, Mk.Color, 1.5)
- else
- FillRound(Canvas, Dot, 3.5, Mk.Color);
- Break; // um ponto por linha: a dica leva todos
- end;
+ if FFirstMark.TryGetValue(I, MkIdx) then
+ begin
+ Mk := FMarkers[MkIdx]; // um ponto por linha: a dica leva todos
+ Dot := TRectF.Create(5, Y + FLineH / 2 - 3.5, 12, Y + FLineH / 2 + 3.5);
+ if Mk.Ring then
+ StrokeRound(Canvas, Dot, 3.5, Mk.Color, 1.5)
+ else
+ FillRound(Canvas, Dot, 3.5, Mk.Color);
+ end;
DrawTextRect(Canvas, NumR, IntToStr(I + 1), Pick(I = FMarkLine, Pal.Accent, Pal.TextFaint), CodeFontSize - 1,
CodeFont, [], TTextAlign.Trailing);
end;
@@ -669,6 +689,10 @@ procedure TCMIssueList.Paint;
ThumbR := TRectF.Create(R.Left + 82, R.CenterPoint.Y - 9, R.Left + 82 + W, R.CenterPoint.Y + 9);
StrokeRound(Canvas, ThumbR, 9, Row.Color, 1);
DrawTextRect(Canvas, ThumbR, Row.Tag, Row.Color, 10, UiFont, [TFontStyle.fsBold], TTextAlign.Center);
+ // o FitText mede com a fonte do canvas: tem de ser a que se desenha a seguir
+ Canvas.Font.Family := UiFont;
+ Canvas.Font.Size := ScaledSize(12);
+ Canvas.Font.Style := [];
DrawTextRect(Canvas, TRectF.Create(ThumbR.Right + 10, R.Top, R.Right - 6, R.Bottom),
FitText(Canvas, Row.Text, R.Right - 6 - (ThumbR.Right + 10)), Pal.Text, 12, UiFont);
end;
@@ -678,7 +702,7 @@ procedure TCMIssueList.Paint;
ThumbH := Max(24, TrackH * Height / (Length(FRows) * IssueRowH + 8));
ThumbR := TRectF.Create(Width - 9, 4 + (TrackH - ThumbH) * (FScrollY / MaxScroll), Width - 3,
4 + (TrackH - ThumbH) * (FScrollY / MaxScroll) + ThumbH);
- FillRound(Canvas, ThumbR, 3, Fade(Pal.TextFaint, 0.55));
+ FillRound(Canvas, ThumbR, 3, Fade(Pal.TextFaint, 0.8));
end;
end;
@@ -829,11 +853,15 @@ procedure TCMTabBar.Paint;
StrokeRound(Canvas, R, 8, Pal.Border, 1);
end;
C := CloseRect(I);
- Txt := FitText(Canvas, FTitles[I], R.Width - 12 - 30);
if Active then
Style := [TFontStyle.fsBold]
else
Style := [];
+ // o FitText mede com a fonte do canvas: tem de ser a que se desenha a seguir
+ Canvas.Font.Family := MonoFont;
+ Canvas.Font.Size := ScaledSize(12);
+ Canvas.Font.Style := Style;
+ Txt := FitText(Canvas, FTitles[I], R.Width - 12 - 30);
DrawTextRect(Canvas, TRectF.Create(R.Left + 12, R.Top, C.Left, R.Bottom), Txt,
Pick(Active, Pal.AccentStrong, Pal.TextDim), 12, MonoFont, Style);
if (I = FHoverClose) then
diff --git a/src/UI/CM.Controls.pas b/src/UI/CM.Controls.pas
index e0e104c..c10f1b1 100644
--- a/src/UI/CM.Controls.pas
+++ b/src/UI/CM.Controls.pas
@@ -398,7 +398,7 @@ constructor TCMKpi.Create(AOwner: TComponent);
begin
inherited;
Role := prSurface;
- Radius := 14;
+ Radius := 12; // o mesmo dos outros cartoes
Bordered := True;
end;
@@ -419,7 +419,7 @@ procedure TCMKpi.Paint;
var
P: TPalette;
I: Integer;
- Hi, X0, X1, Y0, Y1: Single;
+ Hi, X0, X1, Y0, Y1, Sz: Single;
A, B: TPointF;
function Pt(AIndex: Integer): TPointF;
@@ -432,7 +432,11 @@ procedure TCMKpi.Paint;
inherited;
P := Pal;
DrawTextRect(Canvas, TRectF.Create(Pad, 12, Width - Pad, 32), FCaption, P.TextDim, 12.5, UiFont);
- DrawTextRect(Canvas, TRectF.Create(Pad, 32, Width * 0.62, 68), FValue, P.Text, 26, MonoFont,
+ // o valor encolhe ate caber ("1073 / 2520" num cartao estreito ficava cortado)
+ Sz := 26;
+ while (Sz > 16) and (MeasureText(FValue, Sz, MonoFont, [TFontStyle.fsBold]) > Width * 0.62 - Pad) do
+ Sz := Sz - 1;
+ DrawTextRect(Canvas, TRectF.Create(Pad, 32, Width * 0.62, 68), FValue, P.Text, Sz, MonoFont,
[TFontStyle.fsBold]);
DrawTextRect(Canvas, TRectF.Create(Pad, 68, Width - Pad, 90), FSub, P.TextDim, 12, UiFont);
if Length(FSpark) < 2 then
@@ -748,6 +752,7 @@ procedure TCMNavButton.Paint;
R, IR, TR, BubbleR: TRectF;
Fg: TAlphaColor;
Style: TFontStyles;
+ Sz: Single;
begin
P := Pal;
R := LocalRect;
@@ -761,9 +766,17 @@ procedure TCMNavButton.Paint;
IR := TRectF.Create(0, 0, 20, 20);
IR.SetLocation((R.Width - 20) / 2, 11);
DrawIcon(Canvas, FIcon, IR, Fg);
+ // botao baixo (barra compacta, janela pouco alta): so o icone; o nome fica na dica
+ if R.Height < 50 then
+ Exit;
TR := TRectF.Create(0, 40, R.Width, R.Height - 4);
if FSelected then Style := [TFontStyle.fsBold] else Style := [];
- DrawTextRect(Canvas, TR, FText, Pick(FSelected, P.AccentStrong, P.TextDim), 10.5, UiFont,
+ // 11,5 quando o nome cabe; os mais compridos (Aparência em alemao, por exemplo) ficam a 10,5
+ if MeasureText(FText, 11.5, UiFont, Style) <= R.Width - 6 then
+ Sz := 11.5
+ else
+ Sz := 10.5;
+ DrawTextRect(Canvas, TR, FText, Pick(FSelected, P.AccentStrong, P.TextDim), Sz, UiFont,
Style, TTextAlign.Center, TTextAlign.Leading);
end;
@@ -942,7 +955,9 @@ procedure TCMInput.Paint;
P := Pal;
R := LocalRect;
FillRound(Canvas, R, 10, P.Surface);
- StrokeRound(Canvas, R, 10, Pick(FFocused, P.Accent, P.Border), IfThen(FFocused, 1.5, 1));
+ // contorno com 3:1 sobre o fundo (o Border dos cartoes, a 1,3:1, quase nao mostrava onde se escreve)
+ StrokeRound(Canvas, R, 10, Pick(FFocused, P.Accent, Pick(ThemeMode = tmDark, $FF666E73, $FF878C80)),
+ IfThen(FFocused, 1.5, 1));
if FHasIcon then
begin
IR := TRectF.Create(0, 0, 18, 18);
diff --git a/src/UI/CM.GraphView.pas b/src/UI/CM.GraphView.pas
index 3c26aa8..5d76200 100644
--- a/src/UI/CM.GraphView.pas
+++ b/src/UI/CM.GraphView.pas
@@ -2,8 +2,9 @@
{ Mapa visual das dependencias: cada unit e um no e cada "uses" uma curva. As units dispoem-se em colunas
(a da esquerda tem as que ninguem usa; cada coluna seguinte fica um passo mais "por baixo"), com a cor da
- camada (pasta) e um traco vermelho nos ciclos. Arrasta-se para mover, a roda aproxima/afasta, um clique
- seleciona uma unit e realca o que ela usa (a verde) e o que a usa (a azul).
+ camada (pasta) e um traco vermelho nos ciclos. Arrasta-se para mover, a roda aproxima/afasta (com Shift desloca
+ na horizontal), as setas deslocam, + e - aproximam, 0 ajusta a janela; um clique seleciona uma unit e realca o
+ que ela usa (a verde) e o que a usa (a azul), Esc larga a selecao e Enter abre-a.
A forma dos nos e das ligacoes em curva de Bezier inspira-se no DelphiNodeEditor (MIT, HemulGM);
o codigo aqui e proprio, a medida do CodeManager (ver THIRD-PARTY-NOTICES.md). }
@@ -36,6 +37,11 @@ TCMGraphView = class(TCMControl)
FOnSelect: TNotifyEvent;
FOnOpen: TNotifyEvent;
FDblClick: TDoubleClickTracker;
+ // textos ja cortados a medida de cada no ('' = por calcular) e largura da legenda; valem para FTextKey
+ FFitName, FFitDetail: TArray;
+ FLegendW: Single;
+ FTextKey: string;
+ procedure CheckTextCache;
procedure SetFilter(const Value: string);
procedure SetEmptyText(const Value: string);
procedure SetSimplify(const Value: Boolean);
@@ -55,6 +61,7 @@ TCMGraphView = class(TCMControl)
procedure MouseMove(Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); override;
+ procedure KeyDown(var Key: Word; var KeyChar: WideChar; Shift: TShiftState); override;
procedure DoMouseLeave; override;
procedure Resize; override;
public
@@ -86,7 +93,7 @@ TCMGraphView = class(TCMControl)
implementation
uses
- CM.Lang;
+ CM.Lang, CM.Colors;
const
ColW = 300;
@@ -97,12 +104,15 @@ implementation
MinZoom = 0.05;
ReadableZoom = 0.75;
MaxZoom = 2.5;
-
+ MinTextZoom = 0.42; // abaixo disto o nome ja nao se le
+ MinTextBarZoom = 0.15; // e abaixo disto nem a barra que o substitui
+ KeyPanStep = 40;
constructor TCMGraphView.Create(AOwner: TComponent);
begin
inherited;
HitTest := True;
+ CanFocus := True; // para as teclas (setas, + e -, Esc, Enter)
ClipChildren := True;
FZoom := 1;
FSelected := -1;
@@ -132,6 +142,8 @@ procedure TCMGraphView.SetGraph(AGraph: TDepGraph);
FGraph := AGraph;
FSelected := -1;
FHover := -1;
+ Hint := '';
+ FTextKey := ''; // outros nos: a cache de textos refaz-se
FLayerColors.Clear;
FLayers := nil;
FColSizes := nil;
@@ -170,10 +182,34 @@ function TCMGraphView.LayerColor(AIndex: Integer): TAlphaColor;
Result := ColorOfLayer(FLayers[AIndex]);
end;
+var
+ GLightTones: TDictionary; // cor da camada -> a mesma, escurecida para o tema claro
+
+// a paleta das camadas foi afinada para o fundo escuro; no claro cada cor escurece (mesmo tom) ate ter 3:1 sobre branco
+function LightTone(AColor: TAlphaColor): TAlphaColor;
+var
+ H, S, L: Double;
+begin
+ if GLightTones = nil then
+ GLightTones := TDictionary.Create;
+ if GLightTones.TryGetValue(AColor, Result) then
+ Exit;
+ Result := AColor;
+ ColorToHsl(AColor, H, S, L);
+ while (ContrastRatio(Result, $FFFFFFFF) < 3) and (L > 0.1) do
+ begin
+ L := L - 0.02;
+ Result := HslToColor(H, S, L);
+ end;
+ GLightTones.Add(AColor, Result);
+end;
+
function TCMGraphView.ColorOfLayer(const ALayer: string): TAlphaColor;
begin
if not FLayerColors.TryGetValue(ALayer, Result) then
- Result := Pal.TextFaint;
+ Exit(Pal.TextFaint);
+ if ThemeMode = tmLight then
+ Result := LightTone(Result);
end;
procedure TCMGraphView.SetSimplify(const Value: Boolean);
@@ -373,7 +409,10 @@ procedure TCMGraphView.DrawEdges(const AView: TRectF);
begin
S := ToScreen(WorldRect(E.Source));
T := ToScreen(WorldRect(E.Target));
- Box := TRectF.Create(Min(S.Left, T.Left), Min(S.Top, T.Top), Max(S.Right, T.Right) + 80, Max(S.Bottom, T.Bottom));
+ CurvePoints(S, T, FGraph.Nodes[E.Source].Level = FGraph.Nodes[E.Target].Level, P0, P1, P2, P3);
+ // uma curva de Bezier nunca sai da caixa dos seus quatro pontos: o teste e exacto mesmo com o laco de um ciclo
+ Box := TRectF.Create(Min(Min(P0.X, P1.X), Min(P2.X, P3.X)) - 4, Min(Min(P0.Y, P1.Y), Min(P2.Y, P3.Y)) - 4,
+ Max(Max(P0.X, P1.X), Max(P2.X, P3.X)) + 4, Max(Max(P0.Y, P1.Y), Max(P2.Y, P3.Y)) + 4);
if not IntersectRect(Box, AView) then
Continue;
Out_ := Active and (E.Source = FSelected);
@@ -407,8 +446,7 @@ procedure TCMGraphView.DrawEdges(const AView: TRectF);
Thick := 1.6;
end
else
- Col := Fade(Pal.TextFaint, 0.32);
- CurvePoints(S, T, FGraph.Nodes[E.Source].Level = FGraph.Nodes[E.Target].Level, P0, P1, P2, P3);
+ Col := Fade(Pal.TextFaint, 0.45);
FPath.Clear;
FPath.MoveTo(P0);
FPath.CurveTo(P1, P2, P3);
@@ -439,11 +477,10 @@ procedure TCMGraphView.DrawNodes(const AView: TRectF);
Alpha: Single;
Border, FillC: TAlphaColor;
Rel: Integer;
- Detail: string;
ShowText: Boolean;
begin
P := Pal;
- ShowText := FZoom >= 0.42;
+ ShowText := FZoom >= MinTextZoom;
for I := 0 to FGraph.Nodes.Count - 1 do
begin
N := FGraph.Nodes[I];
@@ -457,7 +494,7 @@ procedure TCMGraphView.DrawNodes(const AView: TRectF);
if (Length(FMatch) > 0) and not FMatch[I] then
Dim := True;
if Dim then
- Alpha := 0.3
+ Alpha := 0.45 // secundario, mas ainda se le o nome
else
Alpha := 1;
@@ -485,11 +522,29 @@ procedure TCMGraphView.DrawNodes(const AView: TRectF);
if ShowText then
begin
TextR := TRectF.Create(R.Left + 14 * FZoom, R.Top + 2 * FZoom, R.Right - 14 * FZoom, R.Top + R.Height * 0.58);
- DrawTextRect(Canvas, TextR, FitText(Canvas, N.Name, TextR.Width), Fade(P.Text, Alpha), 11.5 * FZoom, MonoFont,
- [TFontStyle.fsBold]);
SubR := TRectF.Create(R.Left + 14 * FZoom, R.Top + R.Height * 0.52, R.Right - 6 * FZoom, R.Bottom - 2 * FZoom);
- Detail := TrF('usa %d · usada por %d', [N.FanOut, N.FanIn]);
- DrawTextRect(Canvas, SubR, FitText(Canvas, Detail, SubR.Width), Fade(P.TextFaint, Alpha), 9.5 * FZoom, UiFont);
+ if FFitName[I] = '' then
+ begin
+ // FitText mede com a fonte do canvas: tem de ser a mesma com que o texto se desenha
+ Canvas.Font.Family := MonoFont;
+ Canvas.Font.Size := ScaledSize(11.5 * FZoom);
+ Canvas.Font.Style := [TFontStyle.fsBold];
+ FFitName[I] := FitText(Canvas, N.Name, TextR.Width);
+ Canvas.Font.Family := UiFont;
+ Canvas.Font.Size := ScaledSize(9.5 * FZoom);
+ Canvas.Font.Style := [];
+ FFitDetail[I] := FitText(Canvas, TrF('usa %d · usada por %d', [N.FanOut, N.FanIn]), SubR.Width);
+ end;
+ DrawTextRect(Canvas, TextR, FFitName[I], Fade(P.Text, Alpha), 11.5 * FZoom, MonoFont, [TFontStyle.fsBold]);
+ DrawTextRect(Canvas, SubR, FFitDetail[I], Fade(P.TextFaint, Alpha), 9.5 * FZoom, UiFont);
+ end
+ else if FZoom > MinTextBarZoom then
+ begin
+ // longe de mais para ler: uma barra no lugar do nome (do tamanho dele; a letra e monoespacada) que se desvanece
+ TextR := TRectF.Create(R.Left + 14 * FZoom, R.Top + R.Height * 0.3, R.Right - 14 * FZoom, R.Top + R.Height * 0.48);
+ TextR.Width := Min(TextR.Width, Length(N.Name) * 6.9 * FZoom);
+ FillRound(Canvas, TextR, 2 * FZoom, Fade(P.Text, Alpha * EnsureRange(0.5 * (FZoom - MinTextBarZoom) /
+ (MinTextZoom - MinTextBarZoom), 0, 0.5)));
end;
end;
end;
@@ -504,10 +559,14 @@ procedure TCMGraphView.DrawLegend;
Exit;
X := 12;
Y := 10;
- RowW := 0;
- for I := 0 to High(FLayers) do
- RowW := Max(RowW, MeasureText(FLayers[I], 11, UiFont));
- W := RowW + 44;
+ if FLegendW < 0 then
+ begin
+ RowW := 0;
+ for I := 0 to High(FLayers) do
+ RowW := Max(RowW, MeasureText(FLayers[I], 11, UiFont));
+ FLegendW := RowW + 44;
+ end;
+ W := FLegendW;
R := TRectF.Create(X, Y, X + W, Y + 12 + Length(FLayers) * 20);
FillRound(Canvas, R, 8, Fade(Pal.Surface, 0.92));
StrokeRound(Canvas, R, 8, Pal.Border);
@@ -519,6 +578,22 @@ procedure TCMGraphView.DrawLegend;
end;
end;
+// os textos cortados so mudam com o zoom, a escala, as fontes ou a lingua (e com o grafo: SetGraph limpa a chave)
+procedure TCMGraphView.CheckTextCache;
+var
+ Key: string;
+begin
+ Key := Format('%g|%g|%s|%s|%d', [FZoom, TextScale, MonoFont, UiFont, Ord(CurrentLang)]);
+ if Key = FTextKey then
+ Exit;
+ FTextKey := Key;
+ FFitName := nil;
+ FFitDetail := nil;
+ SetLength(FFitName, FGraph.Nodes.Count);
+ SetLength(FFitDetail, FGraph.Nodes.Count);
+ FLegendW := -1;
+end;
+
procedure TCMGraphView.Paint;
var
View: TRectF;
@@ -529,9 +604,17 @@ procedure TCMGraphView.Paint;
DrawTextRect(Canvas, LocalRect, FEmptyText, Pal.TextFaint, 14, UiFont, [], TTextAlign.Center);
Exit;
end;
+ CheckTextCache;
DrawEdges(View);
DrawNodes(View);
DrawLegend;
+ if IsFocused then
+ begin
+ // as teclas estao a ir para o mapa: um contorno discreto (para dentro, senao o recorte comia-o)
+ View := LocalRect;
+ View.Inflate(-1, -1);
+ StrokeRound(Canvas, View, 6, Fade(Pal.Accent, 0.6), 1.5);
+ end;
end;
{ rato }
@@ -577,21 +660,22 @@ procedure TCMGraphView.MouseMove(Shift: TShiftState; X, Y: Single);
if Idx <> FHover then
begin
FHover := Idx;
+ // a dica so se refaz quando muda a unit apontada
+ if Idx >= 0 then
+ begin
+ N := FGraph.Nodes[Idx];
+ Hint := N.Path + sLineBreak + TrF('%d métodos · %d linhas · complexidade máx. %d',
+ [N.Methods, N.Lines, N.MaxComplexity]) + sLineBreak + TrF('usa %d · usada por %d', [N.FanOut, N.FanIn]);
+ ShowHint := True;
+ end
+ else
+ Hint := '';
Repaint;
end;
if Idx >= 0 then
- begin
- N := FGraph.Nodes[Idx];
- Cursor := crHandPoint;
- Hint := N.Path + sLineBreak + TrF('%d métodos · %d linhas · complexidade máx. %d',
- [N.Methods, N.Lines, N.MaxComplexity]) + sLineBreak + TrF('usa %d · usada por %d', [N.FanOut, N.FanIn]);
- ShowHint := True;
- end
+ Cursor := crHandPoint
else
- begin
Cursor := crDefault;
- Hint := '';
- end;
end;
procedure TCMGraphView.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
@@ -627,6 +711,15 @@ procedure TCMGraphView.MouseWheel(Shift: TShiftState; WheelDelta: Integer; var H
NewZoom: Single;
begin
inherited;
+ if ssShift in Shift then
+ begin
+ // Shift + roda: desloca na horizontal (o grafo cresce para a direita)
+ FPanX := FPanX + WheelDelta / 2;
+ ClampPan;
+ Handled := True;
+ Repaint;
+ Exit;
+ end;
NewZoom := EnsureRange(FZoom * Power(1.12, WheelDelta / 120), MinZoom, MaxZoom);
// aproxima em volta do cursor
FPanX := FLastX - (FLastX - FPanX) * NewZoom / FZoom;
@@ -637,10 +730,52 @@ procedure TCMGraphView.MouseWheel(Shift: TShiftState; WheelDelta: Integer; var H
Repaint;
end;
+procedure TCMGraphView.KeyDown(var Key: Word; var KeyChar: WideChar; Shift: TShiftState);
+
+ procedure PanBy(ADx, ADy: Single);
+ begin
+ FPanX := FPanX + ADx;
+ FPanY := FPanY + ADy;
+ ClampPan;
+ Repaint;
+ end;
+
+begin
+ inherited;
+ if (FGraph = nil) or (FGraph.Nodes.Count = 0) then
+ Exit;
+ // as setas deslocam a vista, + e - aproximam, 0 ajusta a janela, Esc larga a selecao e Enter abre a unit
+ case Key of
+ vkLeft: PanBy(KeyPanStep, 0);
+ vkRight: PanBy(-KeyPanStep, 0);
+ vkUp: PanBy(0, KeyPanStep);
+ vkDown: PanBy(0, -KeyPanStep);
+ vkAdd: ZoomBy(1.25);
+ vkSubtract: ZoomBy(0.8);
+ vkEscape: SelectNode(-1);
+ vkReturn:
+ if (FSelected >= 0) and Assigned(FOnOpen) then
+ FOnOpen(Self)
+ else
+ Exit;
+ else
+ case KeyChar of
+ '+': ZoomBy(1.25);
+ '-': ZoomBy(0.8);
+ '0': FitToView(True);
+ else
+ Exit;
+ end;
+ end;
+ Key := 0;
+ KeyChar := #0;
+end;
+
procedure TCMGraphView.DoMouseLeave;
begin
inherited;
FHover := -1;
+ Hint := '';
FDown := False;
Repaint;
end;
@@ -651,4 +786,9 @@ procedure TCMGraphView.Resize;
Repaint;
end;
+initialization
+
+finalization
+ GLightTones.Free;
+
end.
diff --git a/src/UI/CM.MainForm.pas b/src/UI/CM.MainForm.pas
index 70270eb..c95fdad 100644
--- a/src/UI/CM.MainForm.pas
+++ b/src/UI/CM.MainForm.pas
@@ -128,8 +128,10 @@ TMainForm = class(TForm, IPageHost)
procedure DevSonarDemo;
procedure DevPrintPreview(APage, ADpi: Integer; ALandscape: Boolean; const AFile: string);
{$ENDIF}
+ procedure FitRail;
protected
procedure DoShow; override;
+ procedure Resize; override;
public
procedure KeyDown(var Key: Word; var KeyChar: WideChar; Shift: TShiftState); override;
constructor Create(AOwner: TComponent); override;
@@ -375,6 +377,32 @@ procedure TMainForm.BuildRail;
FThemeBtn.Align := TAlignLayout.Bottom;
FThemeBtn.Height := 44;
FThemeBtn.Margins.Rect := TRectF.Create(20, 0, 20, 20);
+ FitRail;
+end;
+
+// os botoes com nome precisam do logotipo (20 + 40 + 14), de 62 + 6 cada e do botao do tema (44 + 20); numa janela mais
+// baixa (o minimo e 640) ficam so com o icone e o nome passa para a dica, em vez de os ultimos desaparecerem por baixo
+// do botao do tema
+procedure TMainForm.FitRail;
+var
+ P: TPage;
+ Compact: Boolean;
+begin
+ Compact := ClientHeight < 74 + (Ord(High(TPage)) + 1) * 68 + 64;
+ for P := Low(TPage) to High(TPage) do
+ if FNav[P] <> nil then
+ begin
+ FNav[P].Height := IfThen(Compact, 44, 62);
+ FNav[P].Margins.Bottom := IfThen(Compact, 2, 6);
+ FNav[P].Hint := IfThen(Compact, FNav[P].Text, '');
+ FNav[P].ShowHint := Compact;
+ end;
+end;
+
+procedure TMainForm.Resize;
+begin
+ inherited;
+ FitRail;
end;
procedure TMainForm.BuildHeader;
@@ -398,13 +426,15 @@ procedure TMainForm.BuildHeader;
FBadgeLabel.Align := TAlignLayout.Client;
FBadgeLabel.HAlign := TTextAlign.Center;
+ // as alturas acompanham a escala do texto (Aspeto): a 125% o titulo ja nao cabia nos 38 px
FTitle := TCMLabel.Make(FHeader, Tr('Projeto'), 26, True);
FTitle.Align := TAlignLayout.Top;
- FTitle.Height := 38;
+ FTitle.Height := Ceil(38 * TextScale);
FTitle.Margins.Top := 26;
FSubtitle := TCMLabel.Make(FHeader, '', 13, False, lcDim);
FSubtitle.Align := TAlignLayout.Top;
- FSubtitle.Height := 22;
+ FSubtitle.Height := Ceil(22 * TextScale);
+ FHeader.Height := 26 + FTitle.Height + FSubtitle.Height + 10;
end;
{ ---------------------------------------------------------------- tema e navegacao }
diff --git a/src/UI/CM.SbomView.pas b/src/UI/CM.SbomView.pas
index 4d970b9..4761860 100644
--- a/src/UI/CM.SbomView.pas
+++ b/src/UI/CM.SbomView.pas
@@ -121,6 +121,14 @@ procedure TCMSbomList.Paint;
DrawTextRect(Canvas, TagR, AText, AColor, 10, UiFont, [TFontStyle.fsBold], TTextAlign.Center);
end;
+ // o FitText mede com a fonte do canvas: tem de ser a que se desenha a seguir
+ procedure SetFont(ASize: Single);
+ begin
+ Canvas.Font.Family := MonoFont;
+ Canvas.Font.Size := ScaledSize(ASize);
+ Canvas.Font.Style := [];
+ end;
+
begin
NameW := Max(120, Width - 16 - OriginW - LicenseW - ConfW - UsedW - HashW - 20);
// cabecalho
@@ -157,11 +165,13 @@ procedure TCMSbomList.Paint;
if I = FHover then
FillRound(Canvas, R, 6, Pal.Hover);
X := 12;
+ SetFont(12);
DrawTextRect(Canvas, TRectF.Create(X, R.Top, X + NameW, R.Bottom), FitText(Canvas, Row.Name, NameW), Pal.Text, 12,
MonoFont);
X := X + NameW + 8;
Tag(Row.OriginText, Row.OriginColor, X, OriginW);
X := X + OriginW;
+ SetFont(11);
if Row.LicenseText = '' then
DrawTextRect(Canvas, TRectF.Create(X, R.Top, X + LicenseW - 6, R.Bottom), '—', Pal.TextFaint, 11, MonoFont)
else if Row.LicenseKnown then
@@ -185,7 +195,7 @@ procedure TCMSbomList.Paint;
ThumbH := Max(24, TrackH * (Height - HeadH) / (Length(FRows) * RowH + 8));
ThumbR := TRectF.Create(Width - 9, HeadH + 4 + (TrackH - ThumbH) * (FScrollY / MaxScroll), Width - 3,
HeadH + 4 + (TrackH - ThumbH) * (FScrollY / MaxScroll) + ThumbH);
- FillRound(Canvas, ThumbR, 3, Fade(Pal.TextFaint, 0.55));
+ FillRound(Canvas, ThumbR, 3, Fade(Pal.TextFaint, 0.8));
end;
end;
diff --git a/src/UI/CM.Theme.pas b/src/UI/CM.Theme.pas
index 834dc9c..2adb702 100644
--- a/src/UI/CM.Theme.pas
+++ b/src/UI/CM.Theme.pas
@@ -31,12 +31,13 @@ TPalette = record
Bg: $FFF6F7F4; Surface: $FFFFFFFF; Surface2: $FFEEF0EB; Border: $FFDCDED7; BorderStrong: $FFC4C7BE;
Text: $FF1B1E1A; TextDim: $FF565B52; TextFaint: $FF676C62;
Accent: $FF23705F; AccentStrong: $FF17493D; AccentSoft: $FFE3EDE9; OnAccent: $FFFFFFFF;
- Star: $FFB8860B; Pending: $FF8A6500; DoneStrike: $FF6A6F65; FlagCompila: $FF2F6FED;
- FlagSonar: $FF8B5CF6; Danger: $FFB8452F; Hover: $FFEEF0EB);
+ // Star, FlagCompila e FlagSonar escurecidos para chegar a 4,5:1 (texto pequeno) nas superficies claras
+ Star: $FFA47708; Pending: $FF8A6500; DoneStrike: $FF6A6F65; FlagCompila: $FF2160D8;
+ FlagSonar: $FF6D28D9; Danger: $FFB8452F; Hover: $FFEEF0EB);
DarkPalette: TPalette = (
Bg: $FF14171A; Surface: $FF1B1F22; Surface2: $FF202426; Border: $FF2C3134; BorderStrong: $FF3D4448;
- Text: $FFE9EBE6; TextDim: $FF9AA09A; TextFaint: $FF8A908B;
+ Text: $FFE9EBE6; TextDim: $FF9AA09A; TextFaint: $FF959B96; // TextFaint: 4,5:1 tambem sobre AccentSoft
Accent: $FF4FB89B; AccentStrong: $FF7FD6BC; AccentSoft: $FF1E2F2B; OnAccent: $FF0E1513;
Star: $FFE0B23C; Pending: $FFD7A53A; DoneStrike: $FF858B86; FlagCompila: $FF6FA8FF;
FlagSonar: $FFC9A6FF; Danger: $FFE0705A; Hover: $FF202426);
@@ -153,7 +154,7 @@ implementation
{ icPalette } 'M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10c1.38 0 2.5-1.12 2.5-2.5 0-.61-.23-1.2-.64-1.67-.08-.1-.13-.21-.13-.33 0-.28.22-.5.5-.5H16c3.31 0 6-2.69 6-6 0-4.96-4.49-9-10-9zm-5.5 9c-.83 0-1.5-.67-1.5-1.5S5.67 8 6.5 8 8 8.67 8 9.5 7.33 11 6.5 11zm3-4C8.67 7 8 6.33 8 5.5S8.67 4 9.5 4s1.5.67 1.5 1.5S10.33 7 9.5 7zm5 0c-.83 0-1.5-.67-1.5-1.5S13.67 4 14.5 4s1.5.67 1.5 1.5S15.33 7 14.5 7zm3 4c-.83 0-1.5-.67-1.5-1.5S16.67 8 17.5 8s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z',
{ icInfo } 'M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z',
{ icBox } 'M20 2H4c-1 0-2 .9-2 2v3.01c0 .72.43 1.34 1 1.69V20c0 1.1 1.1 2 2 2h14c.9 0 2-.9 2-2V8.7c.57-.35 1-.97 1-1.69V4c0-1.1-1-2-2-2zm-5 12H9v-2h6v2zm5-7H4V4h16v3z',
- { icClasses } 'M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3z'
+ { icClasses } 'M12 2l-5.5 9h11L12 2zm5.5 11c-2.49 0-4.5 2.01-4.5 4.5s2.01 4.5 4.5 4.5 4.5-2.01 4.5-4.5-2.01-4.5-4.5-4.5zM3 21.5h8v-8H3v8z'
);
function Pal: TPalette;
@@ -337,14 +338,15 @@ procedure RebuildPalettes;
begin
GLight := LightPalette;
GDark := DarkPalette;
- if GAppearance.Accent = 0 then
+ // a cor original (escolhida a zero ou pela primeira amostra) usa as cores afinadas de cada paleta
+ if (GAppearance.Accent = 0) or (GAppearance.Accent = AccentPresetColors[0]) then
Exit;
- D := DeriveAccent(GAppearance.Accent, False, LightPalette.Surface);
+ D := DeriveAccent(GAppearance.Accent, False, LightPalette.Surface, LightPalette.Surface2);
GLight.Accent := D.Accent;
GLight.AccentStrong := D.Strong;
GLight.AccentSoft := D.Soft;
GLight.OnAccent := D.OnAccent;
- D := DeriveAccent(GAppearance.Accent, True, DarkPalette.Surface);
+ D := DeriveAccent(GAppearance.Accent, True, DarkPalette.Surface, DarkPalette.Surface2);
GDark.Accent := D.Accent;
GDark.AccentStrong := D.Strong;
GDark.AccentSoft := D.Soft;
diff --git a/src/UI/CM.TreeList.pas b/src/UI/CM.TreeList.pas
index 81afd8f..ccac912 100644
--- a/src/UI/CM.TreeList.pas
+++ b/src/UI/CM.TreeList.pas
@@ -51,6 +51,12 @@ TDirNode = class
destructor Destroy; override;
end;
+ // geracao das dicas pedidas em segundo plano; contada por referencia, por isso sobrevive a lista
+ TCMHintGen = class(TInterfacedObject)
+ public
+ Value: Integer;
+ end;
+
TCMTreeList = class(TCMControl)
private
FMode: TListMode;
@@ -68,6 +74,9 @@ TCMTreeList = class(TCMControl)
FReviewFilter: TReviewFilter; // vazio = todos os estados
FStale: THashSet; // ficheiros revistos que mudaram desde a revisao (Git)
FStaleHints: TDictionary; // dicas ja calculadas (cada uma custa uma chamada ao git)
+ FHintGen: TCMHintGen; // muda em SetGit e no destrutor: as respostas antigas do git sao ignoradas
+ FHintGenRef: IInterface; // mantem FHintGen vivo enquanto houver tarefas a usa-lo
+ FHay: TDictionary; // nome e metodos de cada unit em minusculas, para a pesquisa
FStaleOnly: Boolean;
FGitRoot, FGitHead: string;
FSonar: TSonarSnapshot; // nao e nosso; nil sem Sonar
@@ -185,7 +194,7 @@ implementation
uses
- CM.Lang;
+ System.Threading, CM.Lang;
const
DirH = 42;
FileH = 38;
@@ -224,6 +233,9 @@ constructor TCMTreeList.Create(AOwner: TComponent);
FLayers := THashSet.Create;
FStale := THashSet.Create;
FStaleHints := TDictionary.Create;
+ FHintGen := TCMHintGen.Create;
+ FHintGenRef := FHintGen;
+ FHay := TDictionary.Create;
FGroups := TObjectDictionary>.Create([doOwnsValues]);
FGroupKeys := TList.Create;
FHoverRow := -1;
@@ -237,6 +249,7 @@ constructor TCMTreeList.Create(AOwner: TComponent);
destructor TCMTreeList.Destroy;
begin
+ Inc(FHintGen.Value); // uma dica ainda a ser calculada deixa de ter efeito
FFlashTimer.Enabled := False;
FFlash.Free;
FRoot.Free;
@@ -248,6 +261,7 @@ destructor TCMTreeList.Destroy;
FLayers.Free;
FStale.Free;
FStaleHints.Free;
+ FHay.Free;
inherited;
end;
@@ -406,6 +420,7 @@ procedure TCMTreeList.BuildStructure;
begin
FreeAndNil(FRoot);
+ FHay.Clear;
FGroups.Clear;
FGroupKeys.Clear;
if FScan = nil then
@@ -478,16 +493,20 @@ procedure TCMTreeList.AddRow(AKind: TRowKind; ALevel: Integer; const ACaption, A
function TCMTreeList.FileMatchesMap(U: TUnitInfo): Boolean;
var
- M: TMethodInfo;
+ Hay: string;
+ I: Integer;
begin
if FQuery = '' then
Exit(True);
- if Pos(FQuery, LowerCase(U.FileName)) > 0 then
- Exit(True);
- for M in U.Methods do
- if (Pos(FQuery, LowerCase(M.Name)) > 0) or (Pos(FQuery, LowerCase(M.Sig)) > 0) then
- Exit(True);
- Result := False;
+ // o texto de cada unit passa a minusculas uma so vez (FHay limpa-se em BuildStructure); #1 separa as partes
+ if not FHay.TryGetValue(U, Hay) then
+ begin
+ Hay := LowerCase(U.FileName);
+ for I := 0 to High(U.Methods) do
+ Hay := Hay + #1 + LowerCase(U.Methods[I].Name) + #1 + LowerCase(U.Methods[I].Sig);
+ FHay.Add(U, Hay);
+ end;
+ Result := Pos(FQuery, Hay) > 0;
end;
function TCMTreeList.NodeHasMatch(ANode: TDirNode): Boolean;
@@ -942,26 +961,62 @@ function TCMTreeList.DrawTag(ARight, ACenterY: Single; const AText: string; ACol
var
R: TRectF;
begin
- Result := MeasureText(AText, 9.5, MonoFont, [TFontStyle.fsBold]) + 14;
+ Result := MeasureText(AText, 10.5, MonoFont, [TFontStyle.fsBold]) + 14;
R := TRectF.Create(ARight - Result, ACenterY - 9, ARight, ACenterY + 9);
StrokeRound(Canvas, R, 9, AColor, 1);
- DrawTextRect(Canvas, R, AText, AColor, 9.5, MonoFont, [TFontStyle.fsBold], TTextAlign.Center);
+ DrawTextRect(Canvas, R, AText, AColor, 10.5, MonoFont, [TFontStyle.fsBold], TTextAlign.Center);
end;
-// dica de um ficheiro que mudou desde a revisao (calculada uma vez e guardada)
+// dica de um ficheiro que mudou desde a revisao (calculada uma vez e guardada). O git/svn corre em segundo
+// plano: ate responder fica um texto provisorio e a dica completa aparece no movimento seguinte do rato
function TCMTreeList.StaleHintFor(const ARow: TRow): string;
var
S: TUnitState;
+ Root, Rev, Path, Placeholder: string;
+ Gen: Integer;
+ Box: TCMHintGen;
+ BoxRef: IInterface;
begin
- if not FStaleHints.TryGetValue(ARow.U.Path, Result) then
+ if FStaleHints.TryGetValue(ARow.U.Path, Result) then
+ Exit;
+ S := FState.Find(ARow.U.Path);
+ if S = nil then
begin
- S := FState.Find(ARow.U.Path);
- if S = nil then
- Result := ''
- else
- Result := StaleHint(FGitRoot, S.Rev, ARow.U.Path);
- FStaleHints.Add(ARow.U.Path, Result);
- end;
+ FStaleHints.Add(ARow.U.Path, '');
+ Exit('');
+ end;
+ Placeholder := Tr('Mudou desde a revisão:') + ' …';
+ FStaleHints.Add(ARow.U.Path, Placeholder); // nao volta a ser pedida enquanto a tarefa corre
+ Root := FGitRoot;
+ Rev := S.Rev;
+ Path := ARow.U.Path;
+ Gen := FHintGen.Value;
+ Box := FHintGen;
+ BoxRef := FHintGenRef; // a tarefa segura a geracao mesmo que a lista seja destruida
+ TTask.Run(
+ procedure
+ var
+ Text: string;
+ begin
+ try
+ Text := StaleHint(Root, Rev, Path);
+ except
+ Exit; // fica o texto provisorio
+ end;
+ TThread.Queue(nil,
+ procedure
+ var
+ Cur: string;
+ begin
+ // a lista foi destruida ou o Git mudou entretanto (SetGit): o resultado ja nao serve.
+ // BoxRef tem de ser usado aqui para ficar capturado (e manter Box vivo)
+ if (BoxRef = nil) or (Box.Value <> Gen) then
+ Exit;
+ if FStaleHints.TryGetValue(Path, Cur) and (Cur = Placeholder) then
+ FStaleHints[Path] := Text;
+ end);
+ end);
+ Result := Placeholder;
end;
// texto completo de um nome/assinatura que foi cortado com "..." (so se o rato estiver sobre ele)
@@ -1235,7 +1290,7 @@ procedure TCMTreeList.DrawScrollbar;
begin
if MaxScroll <= 0 then
Exit;
- FillRound(Canvas, ThumbRect, 4, Fade(Pal.TextFaint, IfThen(FDragThumb, 0.9, 0.55)));
+ FillRound(Canvas, ThumbRect, 4, Fade(Pal.TextFaint, IfThen(FDragThumb, 0.9, 0.8)));
end;
procedure TCMTreeList.DrawFlag(const ARect: TRectF; const ALabel: string; AChecked: Boolean;
@@ -1554,7 +1609,11 @@ procedure TCMTreeList.DrawMethodRow(const ARow: TRow; const L: TRowLayout);
if TagW > 0 then
NR.Right := NR.Right - TagW - 10;
SetFont(12, MonoFont, SigStyle);
- Sig := FitText(Canvas, M.Sig, NR.Width);
+ // a coluna do tipo ja diz function/procedure: nao se repete no inicio da assinatura
+ Sig := M.Sig;
+ if StartsText(M.Kind + ' ', Sig) then
+ Delete(Sig, 1, Length(M.Kind) + 1);
+ Sig := FitText(Canvas, Sig, NR.Width);
DrawTextRect(Canvas, NR, Sig, SigColor, 12, MonoFont, SigStyle);
if Done and (FMode = lmChecklist) then
begin
@@ -1720,6 +1779,7 @@ procedure TCMTreeList.SetGit(const ARoot, AHead: string; AStale: THashSet nil then
for P in AStale do
FStale.Add(P);
diff --git a/src/UI/Pages/CM.Pages.About.pas b/src/UI/Pages/CM.Pages.About.pas
index 034f788..d63fb3e 100644
--- a/src/UI/Pages/CM.Pages.About.pas
+++ b/src/UI/Pages/CM.Pages.About.pas
@@ -174,6 +174,8 @@ procedure TAboutPage.Resize;
procedure TAboutPage.FitCards;
begin
+ // num ecra largo os valores ficavam a ~1100 px das etiquetas: o bloco nao passa de 640
+ FInfo.Margins.Right := Max(0, FCards[1].Width - FCards[1].Padding.Left - FCards[1].Padding.Right - 640);
FLinks.Relayout;
FCards[2].Height := 18 + 18 + 28 + 12 + FLinks.Height + 8;
FBody.Height := FCards[0].Height + FCards[1].Height + FCards[2].Height + FCards[3].Height + 4 * 16 + 8;
diff --git a/src/UI/Pages/CM.Pages.Appearance.pas b/src/UI/Pages/CM.Pages.Appearance.pas
index 343a1f5..08cc7d4 100644
--- a/src/UI/Pages/CM.Pages.Appearance.pas
+++ b/src/UI/Pages/CM.Pages.Appearance.pas
@@ -317,7 +317,14 @@ procedure TCMSwatchBar.Paint;
begin
R := SwatchRect(I);
C := AccentPresetColors[I];
- Shown := DeriveAccent(C, ThemeMode = tmDark, Pal.Surface); // a cor tal como vai aparecer neste tema
+ // a cor tal como vai aparecer neste tema; a primeira e a original, que usa as cores proprias de cada paleta
+ if I = 0 then
+ begin
+ Shown.Accent := Pick(ThemeMode = tmDark, DarkPalette.Accent, LightPalette.Accent);
+ Shown.OnAccent := Pick(ThemeMode = tmDark, DarkPalette.OnAccent, LightPalette.OnAccent);
+ end
+ else
+ Shown := DeriveAccent(C, ThemeMode = tmDark, Pal.Surface, Pal.Surface2);
FillRound(Canvas, R, R.Width / 2, Shown.Accent);
if I = FActive then
begin
diff --git a/src/UI/Pages/CM.Pages.Checklist.pas b/src/UI/Pages/CM.Pages.Checklist.pas
index 9c7e379..40c018a 100644
--- a/src/UI/Pages/CM.Pages.Checklist.pas
+++ b/src/UI/Pages/CM.Pages.Checklist.pas
@@ -7,7 +7,7 @@ interface
uses
System.SysUtils, System.Classes, System.Types, System.UITypes, System.Math, System.IOUtils,
- System.Rtti, System.StrUtils,
+ System.Rtti, System.StrUtils, System.Threading,
FMX.Types, FMX.Controls, FMX.Layouts, FMX.Dialogs, FMX.Platform, FMX.DialogService.Sync,
CM.Theme, CM.Controls, CM.Layouts, CM.TreeList, CM.Analyzer, CM.Store, CM.Stats, CM.Plan, CM.GitReview, CM.Vcs, CM.SonarModel, CM.Pages.Host;
@@ -28,6 +28,9 @@ TChecklistPage = class(TCMControl)
FGitShowBtn: TCMButton;
FGitTimer: TTimer; // adia a consulta ao git: o IDE grava varias vezes seguidas
FStalePaths: TArray;
+ FGitBusy: Boolean; // ha uma consulta ao Git em curso (so corre uma de cada vez)
+ FGitAgain: Boolean; // pediram outra consulta enquanto essa corria
+ FGitToast: Boolean; // "Atualizar" pediu o aviso com o resultado
FPlanStats: TCMKeyValue; // cobertura do plano; o cartao so aparece quando ha plano
FChips: TCMChipFlow;
FStateChips: TCMChipFlow; // filtros por estado de revisao, com a contagem de ficheiros
@@ -41,6 +44,7 @@ TChecklistPage = class(TCMControl)
procedure FitProgressCard;
procedure ShowPlanCard;
procedure GitTick(Sender: TObject);
+ procedure GitDone(AScan: TProjectScan; const ARoot: string; const ASnaps: TArray; var R: TGitReviewResult);
procedure SonarRefreshClick(Sender: TObject);
procedure SonarSyncClick(Sender: TObject);
procedure GitShowClick(Sender: TObject);
@@ -507,26 +511,91 @@ procedure TChecklistPage.GitTick(Sender: TObject);
procedure TChecklistPage.RefreshGit;
var
Scan: TProjectScan;
- R: TGitReviewResult;
+ Root: string;
+ Snaps: TArray;
begin
FGitTimer.Enabled := False;
Scan := FHost.CurrentScan;
- if (Scan = nil) or (Scan.Root = '') then
+ if (Scan = nil) or (Scan.Root = '') or (FHost.CurrentState = nil) then
begin
+ FGitToast := False;
FList.SetGit('', '', nil);
FStalePaths := nil;
ShowGitCard('');
Exit;
end;
- R := FindStaleReviews(Scan.Root, Scan, FHost.CurrentState);
+ // uma consulta de cada vez: as que chegam entretanto juntam-se numa so, feita no fim (GitDone)
+ if FGitBusy then
+ begin
+ FGitAgain := True;
+ Exit;
+ end;
+ FGitBusy := True;
+ // o progresso copia-se aqui (na thread da interface); so as consultas ao Git correm em segundo plano
+ Root := Scan.Root;
+ Snaps := SnapReviews(Scan, FHost.CurrentState);
+ TTask.Run(
+ procedure
+ var
+ R: TGitReviewResult;
+ begin
+ try
+ R := ComputeStaleReviews(Root, Snaps);
+ except
+ R := Default(TGitReviewResult); // como fora de um repositorio
+ end;
+ TThread.Queue(nil,
+ procedure
+ begin
+ GitDone(Scan, Root, Snaps, R);
+ end);
+ end);
+end;
+
+procedure TChecklistPage.GitDone(AScan: TProjectScan; const ARoot: string; const ASnaps: TArray; var R: TGitReviewResult);
+var
+ Again: Boolean;
+ Snap: TReviewSnap;
+ S: TUnitState;
+begin
try
- FList.SetGit(Scan.Root, R.Head, R.Stale);
- FStalePaths := R.Stale.ToArray;
- if R.Backfilled > 0 then
- FHost.MarkStateDirty; // as revisoes antigas ganharam o commit
- ShowGitCard(R.Head);
+ FGitBusy := False;
+ Again := FGitAgain;
+ FGitAgain := False;
+ if FHost.ShuttingDown then
+ Exit;
+ // AScan so se compara: pode ja ter sido libertado (e o endereco reaproveitado noutra pasta)
+ if (AScan = FHost.CurrentScan) and (FHost.CurrentState <> nil) and SameText(FHost.CurrentScan.Root, ARoot) then
+ begin
+ // revisto ou reposto enquanto o Git corria: a copia desse ficheiro ja nao vale
+ // (antes de ApplyBackfill, que muda o Rev das revisoes antigas)
+ if R.Stale <> nil then
+ for Snap in ASnaps do
+ begin
+ S := FHost.CurrentState.Find(Snap.Path);
+ if (S = nil) or (S.Ts <> Snap.Ts) or (S.Rev <> Snap.Rev) then
+ R.Stale.Remove(Snap.Path);
+ end;
+ if ApplyBackfill(FHost.CurrentState, R.Backfill) > 0 then
+ FHost.MarkStateDirty; // as revisoes antigas ganharam o commit
+ FList.SetGit(ARoot, R.Head, R.Stale);
+ if R.Stale <> nil then
+ FStalePaths := R.Stale.ToArray
+ else
+ FStalePaths := nil;
+ ShowGitCard(R.Head);
+ if FGitToast and not Again then // o aviso fica para a consulta que ainda vai correr
+ begin
+ FGitToast := False;
+ FHost.Toast(Format(Tr('%s: %d ficheiros revistos mudaram desde a revisão'),
+ [VcsName(DetectVcs(ARoot)), Length(FStalePaths)]));
+ end;
+ end;
+ if Again then
+ RefreshGit;
finally
R.Stale.Free;
+ R.Stale := nil;
end;
end;
@@ -570,27 +639,28 @@ procedure TChecklistPage.GitShowClick(Sender: TObject);
procedure TChecklistPage.GitRefreshClick(Sender: TObject);
begin
+ FGitToast := True; // o aviso sai quando a consulta acabar (GitDone)
RefreshGit;
- FHost.Toast(Format(Tr('%s: %d ficheiros revistos mudaram desde a revisão'),
- [VcsName(DetectVcs(FHost.CurrentScan.Root)), Length(FStalePaths)]));
end;
procedure TChecklistPage.GitResetClick(Sender: TObject);
var
Path: string;
+ Paths: TArray;
S: TUnitState;
begin
- if Length(FStalePaths) = 0 then
+ Paths := FStalePaths; // o dialogo processa a fila: GitDone pode trocar FStalePaths entretanto
+ if Length(Paths) = 0 then
begin
FHost.Toast(Tr('Nenhum ficheiro revisto mudou desde a revisão'));
Exit;
end;
if TDialogServiceSync.MessageDialog(
Format(Tr('Voltar a «por rever» os %d ficheiros que mudaram desde a revisão? ') +
- Tr('Ficam sem estado de revisão; Compila, Sonar, prioridade e notas mantêm-se.'), [Length(FStalePaths)]),
+ Tr('Ficam sem estado de revisão; Compila, Sonar, prioridade e notas mantêm-se.'), [Length(Paths)]),
TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], TMsgDlgBtn.mbNo, 0) <> mrYes then
Exit;
- for Path in FStalePaths do
+ for Path in Paths do
begin
S := FHost.CurrentState.Find(Path);
if S <> nil then
diff --git a/src/UI/Pages/CM.Pages.Classes.pas b/src/UI/Pages/CM.Pages.Classes.pas
index 74f8beb..ef8f4a0 100644
--- a/src/UI/Pages/CM.Pages.Classes.pas
+++ b/src/UI/Pages/CM.Pages.Classes.pas
@@ -21,6 +21,7 @@ TClassesPage = class(TCMControl)
FNote: TCMLabel;
FInterfacesSwitch: TCMSwitch;
FHier: THierarchy; // dono da hierarquia actual
+ FIndex: TDictionary; // no -> indice em FHier.Nodes (o IndexOf era linear por linha)
FStale: Boolean;
FSortColumn: Integer; // -1 = pela arvore
FSortDesc: Boolean;
@@ -28,6 +29,7 @@ TClassesPage = class(TCMControl)
procedure OptionChanged(Sender: TObject);
procedure SortClick(Sender: TObject; AColumn: Integer);
procedure OpenClick(Sender: TObject; ATag: Integer);
+ function RowHint(Sender: TObject; ATag: Integer): string;
procedure ExportMdClick(Sender: TObject);
procedure ExportCsvClick(Sender: TObject);
procedure DoExport(AKind: Integer);
@@ -92,8 +94,9 @@ constructor TClassesPage.Create(AOwner: TComponent; AParent: TFmxObject; const A
Visible := False;
FStale := True;
FSortColumn := -1;
+ FIndex := TDictionary.Create;
- Bar := TCMControl.Create(Self);
+ Bar :=TCMControl.Create(Self);
Bar.Parent := Self;
Bar.Align := TAlignLayout.Top;
Bar.Height := 42;
@@ -148,6 +151,7 @@ constructor TClassesPage.Create(AOwner: TComponent; AParent: TFmxObject; const A
FList.EmptyText := Tr('Analise um projeto para ver as classes.');
FList.OnSort := SortClick;
FList.OnOpen := OpenClick;
+ FList.OnHint := RowHint;
ShowSummary;
ShowNote;
end;
@@ -155,6 +159,7 @@ constructor TClassesPage.Create(AOwner: TComponent; AParent: TFmxObject; const A
destructor TClassesPage.Destroy;
begin
FreeAndNil(FHier);
+ FIndex.Free;
inherited;
end;
@@ -219,6 +224,7 @@ procedure TClassesPage.OpenClick(Sender: TObject; ATag: Integer);
procedure TClassesPage.Invalidate;
begin
FStale := True;
+ FIndex.Clear;
FreeAndNil(FHier);
FSearch.Text := '';
FSortColumn := -1;
@@ -236,9 +242,14 @@ procedure TClassesPage.Activate;
end;
procedure TClassesPage.Build;
+var
+ I: Integer;
begin
+ FIndex.Clear;
FreeAndNil(FHier);
FHier := BuildHierarchy(FHost.CurrentScan);
+ for I := 0 to FHier.Nodes.Count - 1 do
+ FIndex.Add(FHier.Nodes[I], I);
FStale := False;
FList.EmptyText := Tr('Este projeto não declara classes.');
ShowSummary;
@@ -312,9 +323,8 @@ procedure TClassesPage.ShowRows;
var
Rows: TArray;
N: TClassNode;
- Q, Chain: string;
+ Q: string;
R: TClassRow;
- Part: string;
begin
FList.SetSort(FSortColumn, FSortDesc);
if FHier = nil then
@@ -343,31 +353,43 @@ procedure TClassesPage.ShowRows;
R.Children := N.Children;
R.Methods := N.Methods;
R.FileText := N.UnitPath + ':' + IntToStr(N.Line);
- R.Tag := FHier.Nodes.IndexOf(N);
- Chain := '';
- for Part in N.Chain do
- begin
- if Chain <> '' then
- Chain := Chain + ' → ';
- Chain := Chain + Part;
- end;
- if N.ExternalBase <> '' then
- begin
- Chain := Chain + ' → ' + N.ExternalBase;
- if not N.Exact then
- Chain := Chain + ' …';
- end;
- R.Hint := Chain + sLineBreak + Tr('Profundidade') + ': ' + DepthText(N);
- if N.Descendants > 0 then
- R.Hint := R.Hint + sLineBreak + Tr('Descendentes') + ': ' + IntToStr(N.Descendants);
- if Length(N.Interfaces) > 0 then
- R.Hint := R.Hint + sLineBreak + Tr('Interfaces') + ': ' + string.Join(', ', N.Interfaces);
- R.Hint := R.Hint + sLineBreak + R.FileText;
+ if not FIndex.TryGetValue(N, R.Tag) then
+ R.Tag := -1; // como o IndexOf de antes
Rows := Rows + [R];
end;
FList.SetRows(Rows);
end;
+// a dica de uma linha: monta-se so quando o rato chega a ela
+function TClassesPage.RowHint(Sender: TObject; ATag: Integer): string;
+var
+ N: TClassNode;
+ Chain, Part: string;
+begin
+ if (FHier = nil) or (ATag < 0) or (ATag >= FHier.Nodes.Count) then
+ Exit('');
+ N := FHier.Nodes[ATag];
+ Chain := '';
+ for Part in N.Chain do
+ begin
+ if Chain <> '' then
+ Chain := Chain + ' → ';
+ Chain := Chain + Part;
+ end;
+ if N.ExternalBase <> '' then
+ begin
+ Chain := Chain + ' → ' + N.ExternalBase;
+ if not N.Exact then
+ Chain := Chain + ' …';
+ end;
+ Result := Chain + sLineBreak + Tr('Profundidade') + ': ' + DepthText(N);
+ if N.Descendants > 0 then
+ Result := Result + sLineBreak + Tr('Descendentes') + ': ' + IntToStr(N.Descendants);
+ if Length(N.Interfaces) > 0 then
+ Result := Result + sLineBreak + Tr('Interfaces') + ': ' + string.Join(', ', N.Interfaces);
+ Result := Result + sLineBreak + N.UnitPath + ':' + IntToStr(N.Line);
+end;
+
procedure TClassesPage.ShowNote;
begin
if FHier = nil then
diff --git a/src/UI/Pages/CM.Pages.Dashboard.pas b/src/UI/Pages/CM.Pages.Dashboard.pas
index 59d4eff..a0ed1be 100644
--- a/src/UI/Pages/CM.Pages.Dashboard.pas
+++ b/src/UI/Pages/CM.Pages.Dashboard.pas
@@ -58,6 +58,7 @@ TDashboardPage = class(TCMControl)
const AMeasure: TFunc);
procedure FillSonar;
procedure Reset(AChart: TChart4D; AKind: TChartKind; const ATitle, ASubtitle: string);
+ procedure ChartHover(Sender: TObject; const Info: TChartHitInfo);
protected
procedure Resize; override;
public
@@ -92,6 +93,28 @@ function ThemedStyle: TChartStyle;
Result.GridColor := Pal.Border;
Result.BaselineColor := Pal.BorderStrong;
Result.ScaleFactor := ChartScale;
+ // o texto segue a escala escolhida no Aspeto; eixos e legendas a ~12 DIP (os 18 de origem davam 10,8, pequenos de mais)
+ Result.TitleFontSize := 28 * TextScale;
+ Result.SubtitleFontSize := 21 * TextScale;
+ Result.LegendFontSize := 20 * TextScale;
+ Result.AxisFontSize := 20 * TextScale;
+ Result.CaptionFontSize := 20 * TextScale;
+end;
+
+// a serie "o que falta": um cinzento com contraste de 3:1 (as cores dos contornos quase nao se viam)
+function NeutralSeriesColor: TAlphaColor;
+begin
+ Result := Pick(ThemeMode = tmDark, $FF6B757B, $FF8F9585);
+end;
+
+// o nome de uma categoria, cortado para nao comer a area das barras
+function ShortLabel(const AName: string): string;
+const
+ MaxLen = 28;
+begin
+ Result := AName;
+ if Length(Result) > MaxLen then
+ Result := Copy(Result, 1, MaxLen - 1) + '…';
end;
constructor TDashboardPage.Create(AOwner: TComponent; AParent: TFmxObject; const AHost: IPageHost);
@@ -246,6 +269,26 @@ function TDashboardPage.MakeChart(AParent: TFmxObject; AFill: Boolean): TChart4D
Result.Parent := Card;
Result.Align := TAlignLayout.Client;
Result.ShowTooltips := True;
+ Result.OnDataPointHover := ChartHover;
+end;
+
+// no tema escuro a caixa da dica do Chart4D e sempre branca (com o texto claro do tema nao se le): o valor vai para a
+// dica da propria aplicacao
+procedure TDashboardPage.ChartHover(Sender: TObject; const Info: TChartHitInfo);
+var
+ C: TChart4D;
+begin
+ C := Sender as TChart4D;
+ if C.ShowTooltips or not Info.HasHit then
+ begin
+ C.Hint := '';
+ Exit;
+ end;
+ C.Hint := Info.CategoryLabel;
+ if Info.SeriesName <> '' then
+ C.Hint := C.Hint + ' · ' + Info.SeriesName;
+ C.Hint := C.Hint + ': ' + FormatFloat('0.##', Info.Value);
+ C.ShowHint := True;
end;
procedure TDashboardPage.StyleAll;
@@ -253,7 +296,11 @@ procedure TDashboardPage.StyleAll;
C: TChart4D;
begin
for C in [FEvolution, FLayers, FStatus, FTop, FHist, FLayerMethods, FCompilaSonar, FPlanLayers, FPlanOverview, FComplexTop, FComplexDist, FParamsTop, FNestingTop, FCogTop, FCogDist, FClassesTop, FClassesDepth, FSonarDebt, FSonarTop] do
+ begin
C.Plot.Style := ThemedStyle;
+ C.ShowTooltips := ThemeMode = tmLight;
+ C.Hint := '';
+ end;
end;
procedure TDashboardPage.ApplyTheme;
@@ -367,7 +414,8 @@ procedure TDashboardPage.FillEvolution;
Exit;
FEvolution.Plot.LegendPosition := TLegendPosition.Top;
FEvolution.Plot.AddLineSeries(Tr('Ficheiros concluídos'), Days, FilesPct).Color := Pal.Accent;
- FEvolution.Plot.AddLineSeries(Tr('Métodos revistos'), Days, MethodsPct).Color := Pal.FlagCompila;
+ // a cor do anel dos metodos na Checklist (a azul e a da marca Compila)
+ FEvolution.Plot.AddLineSeries(Tr('Métodos revistos'), Days, MethodsPct).Color := Pal.Star;
Axis := FEvolution.Plot.YAxis;
Axis.MinValue := 0;
Axis.MaxValue := 100;
@@ -399,7 +447,7 @@ procedure TDashboardPage.FillLayers;
FLayers.Plot.LegendPosition := TLegendPosition.Top;
FLayers.Plot.Categories := Names;
FLayers.Plot.AddSeries(Tr('Concluídos'), Done).Color := Pal.Accent;
- FLayers.Plot.AddSeries(Tr('Por concluir'), Pending).Color := Pal.BorderStrong;
+ FLayers.Plot.AddSeries(Tr('Por concluir'), Pending).Color := NeutralSeriesColor;
end;
// SonarQube: numeros do projecto e onde esta a divida tecnica. So aparece quando a ultima consulta traz medidas
@@ -530,7 +578,7 @@ procedure TDashboardPage.FillKpis;
FKpi[0].SetValues(Tr('Ficheiros concluídos'), Format('%d / %d', [FStats.DoneFiles, FStats.Files]),
Format(Tr('%d%% do projeto'), [Pct(FStats.DoneFiles, FStats.Files)]), Files, Pal.Accent);
FKpi[1].SetValues(Tr('Métodos revistos'), Format('%d / %d', [FStats.DoneMethods, FStats.Methods]),
- Format(Tr('%d%% dos métodos'), [Pct(FStats.DoneMethods, FStats.Methods)]), Methods, Pal.FlagCompila);
+ Format(Tr('%d%% dos métodos'), [Pct(FStats.DoneMethods, FStats.Methods)]), Methods, Pal.Star);
FKpi[2].SetValues(Tr('Compila'), Format('%d / %d', [FStats.FilesCompila, FStats.Files]),
Format(Tr('%d%% dos ficheiros'), [Pct(FStats.FilesCompila, FStats.Files)]), Compila, Pal.FlagCompila);
FKpi[3].SetValues(Tr('Sonar'), Format('%d / %d', [FStats.FilesSonar, FStats.Files]),
@@ -625,7 +673,7 @@ TEntry = record
SetLength(Values, N);
for I := 0 to N - 1 do
begin
- Names[I] := Items[I].Name;
+ Names[I] := ShortLabel(Items[I].Name);
Values[I] := Items[I].Value;
end;
finally
@@ -651,7 +699,7 @@ procedure TDashboardPage.FillComplexity;
if M.Lines > 0 then
Inc(Levels[ComplexityLevel(M.Complexity)]);
FillTopMethods(FComplexTop, Tr('Métodos mais complexos'), Tr('Os %d com maior complexidade ciclomática'),
- Tr('Complexidade'), Pal.Pending,
+ Tr('Complexidade'), Pal.Accent,
function(AMethod: TMethodInfo): Integer
begin
Result := AMethod.Complexity;
@@ -662,19 +710,21 @@ procedure TDashboardPage.FillComplexity;
FComplexDist.Plot.Categories := [Tr('Simples'), Tr('Moderada'), Tr('Alta')];
FComplexDist.Plot.AddSeries(Tr('Métodos'),
[Levels[cxLow], Levels[cxModerate], Levels[cxHigh]]).Color := Pal.Accent;
+ // as moderadas e as altas sao poucas ao lado das simples: o numero em cima de cada barra
+ FComplexDist.Plot.ValueLabels := TValueLabelMode.All;
end;
// forma dos metodos: os com mais parametros e os mais aninhados
procedure TDashboardPage.FillShape;
begin
FillTopMethods(FParamsTop, Tr('Métodos com mais parâmetros'), Tr('Os %d com mais parâmetros'),
- Tr('Parâmetros'), Pal.FlagCompila,
+ Tr('Parâmetros'), Pal.Accent,
function(AMethod: TMethodInfo): Integer
begin
Result := AMethod.ParamCount;
end);
FillTopMethods(FNestingTop, Tr('Métodos mais aninhados'), Tr('Os %d com maior aninhamento de blocos'),
- Tr('Aninhamento'), Pal.FlagSonar,
+ Tr('Aninhamento'), Pal.Accent,
function(AMethod: TMethodInfo): Integer
begin
Result := AMethod.Nesting;
@@ -695,7 +745,7 @@ procedure TDashboardPage.FillCognitive;
if M.Lines > 0 then
Inc(Levels[CognitiveLevel(M.Cognitive)]);
FillTopMethods(FCogTop, Tr('Métodos de maior complexidade cognitiva'), Tr('Os %d com maior complexidade cognitiva'),
- Tr('Cognitiva'), Pal.Danger,
+ Tr('Cognitiva'), Pal.Accent,
function(AMethod: TMethodInfo): Integer
begin
Result := AMethod.Cognitive;
@@ -706,6 +756,7 @@ procedure TDashboardPage.FillCognitive;
FCogDist.Plot.Categories := [Tr('Simples'), Tr('Moderada'), Tr('Alta')];
FCogDist.Plot.AddSeries(Tr('Métodos'),
[Levels[cxNone] + Levels[cxLow], Levels[cxModerate], Levels[cxHigh]]).Color := Pal.Accent;
+ FCogDist.Plot.ValueLabels := TValueLabelMode.All;
end;
// heranca: as classes mais profundas e quantas ha em cada profundidade (so classes e interfaces do projeto)
@@ -727,7 +778,7 @@ procedure TDashboardPage.FillClasses;
SetLength(Values, Length(Top));
for I := 0 to High(Top) do
begin
- Names[I] := Top[I].Name;
+ Names[I] := ShortLabel(Top[I].Name);
Values[I] := Top[I].Depth;
end;
Counts := H.Histogram;
@@ -745,12 +796,13 @@ procedure TDashboardPage.FillClasses;
Format(Tr('As %d com maior profundidade de herança'), [Length(Top)]));
FClassesTop.Plot.Orientation := TChartOrientation.Horizontal;
FClassesTop.Plot.Categories := Names;
- FClassesTop.Plot.AddSeries(Tr('Profundidade'), Values).Color := Pal.FlagCompila;
+ FClassesTop.Plot.AddSeries(Tr('Profundidade'), Values).Color := Pal.Accent;
Reset(FClassesDepth, TChartKind.Bar, Tr('Profundidade de herança'),
Tr('Quantas classes em cada profundidade (1 = sem ancestral do projeto)'));
FClassesDepth.Plot.Categories := Depths;
FClassesDepth.Plot.AddSeries(Tr('Classes'), Amounts).Color := Pal.Accent;
+ FClassesDepth.Plot.ValueLabels := TValueLabelMode.All;
end;
// cobertura do plano: por camada (ficheiros) e o total de ficheiros e metodos; so com plano
@@ -837,7 +889,7 @@ procedure TDashboardPage.FillTop;
SetLength(Counts, N);
for I := 0 to N - 1 do
begin
- Names[I] := Units[I].BaseName;
+ Names[I] := ShortLabel(Units[I].BaseName);
Counts[I] := Length(Units[I].Methods);
end;
finally
@@ -872,7 +924,19 @@ procedure TDashboardPage.FillHistogram;
Reset(FHist, TChartKind.Histogram, Tr('Métodos por ficheiro'), Tr('Quantos ficheiros têm cada número de métodos'));
if Length(Values) = 0 then
Exit;
- Width := Max(1, Ceil(MaxM / 8));
+ // um passo "redondo" (1, 2, 5, 10, 20, 25, 50...) perto de MaxM/10: limites de classe que se leem (0, 10, 20...)
+ Width := Max(1, Ceil(MaxM / 10));
+ if Width > 2 then
+ if Width <= 5 then
+ Width := 5
+ else if Width <= 10 then
+ Width := 10
+ else if Width <= 20 then
+ Width := 20
+ else if Width <= 25 then
+ Width := 25
+ else
+ Width := Ceil(Width / 50) * 50;
FHist.Plot.SetHistogramData(Values, Width);
if FHist.Plot.Series.Count > 0 then
FHist.Plot.Series[0].Color := Pal.Accent;
diff --git a/src/UI/Pages/CM.Pages.Project.pas b/src/UI/Pages/CM.Pages.Project.pas
index 1d79ae1..9100d78 100644
--- a/src/UI/Pages/CM.Pages.Project.pas
+++ b/src/UI/Pages/CM.Pages.Project.pas
@@ -213,10 +213,10 @@ constructor TProjectPage.Create(AOwner: TComponent; AParent: TFmxObject; const A
FWatchSwitch.Text := Tr('Acompanhar alterações na pasta do projeto');
FWatchSwitch.OnChange := WatchSwitchChanged;
Sub := TCMLabel.Make(Card, Tr('Em branco = predefinidas. Analisa .pas, .dpr e .dpk. Com pasta e plano, o Mapa mostra o que falta e o que sobra.'),
- 11.5, False, lcFaint, True);
+ 11.5, False, lcFaint); // uma frase: na letra da interface, nao na monoespacada
Sub.Align := TAlignLayout.Top;
Sub.Wrap := True; // em alemao a frase ocupa duas linhas
- Sub.Height := 34;
+ Sub.Height := Ceil(34 * TextScale);
Sub.Margins.Top := 10;
FNameIn.OnChangeText := FieldChanged;
FRootIn.OnChangeText := FieldChanged;
@@ -234,7 +234,7 @@ constructor TProjectPage.Create(AOwner: TComponent; AParent: TFmxObject; const A
Sub := TCMLabel.Make(Card, Tr('Cada utilizador decide se o usa. O endereço e o token ficam nos teus dados;') + sLineBreak +
Tr('o token é cifrado e só funciona neste computador e nesta conta do Windows.'), 11.5, False, lcFaint);
Sub.Align := TAlignLayout.Top;
- Sub.Height := 36;
+ Sub.Height := Ceil(36 * TextScale);
Sub.Margins.Top := 4;
FSonarSwitch := TCMSwitch.Create(Self);
FSonarSwitch.Parent := Card;
@@ -709,7 +709,7 @@ procedure TProjectPage.ApplyWatchChanges;
var
Paths: TArray;
Overflow, Reconcile: Boolean;
- Path: string;
+ Path, Ext: string;
Changes: TList;
Change: TScanChange;
Scan: TProjectScan;
@@ -727,14 +727,24 @@ procedure TProjectPage.ApplyWatchChanges;
Continue;
if IsSourceFile(Path) then
begin
- if RescanFile(Scan, Path, Change) <> rcNone then
+ if RescanFile(Scan, Path, Change, False) <> rcNone then
Changes.Add(Change);
- end
+ Continue;
+ end;
+ // a propria pasta ignorada (p.ex. __history a cada gravacao do IDE) nao muda a analise
+ if IsExcludedDir(Copy(Path, Path.LastIndexOf('/') + 2, MaxInt), Scan.ExcludeDirs) then
+ Continue;
+ Ext := LowerCase(TPath.GetExtension(Path));
+ // saidas de compilacao e ficheiros do IDE: nunca sao pastas, poupa a ida ao disco
+ if Ext.StartsWith('.~') or MatchText(Ext, ['.dcu', '.exe', '.dll', '.bpl', '.dcp', '.res',
+ '.map', '.drc', '.identcache', '.local', '.tvsconfig', '.rsm', '.obj', '.o']) then
+ Continue;
// sem extensao ou pasta existente: pasta criada, renomeada ou apagada
- else if (TPath.GetExtension(Path) = '') or
- TDirectory.Exists(TPath.Combine(Scan.Root, Path.Replace('/', PathDelim))) then
+ if (Ext = '') or TDirectory.Exists(TPath.Combine(Scan.Root, Path.Replace('/', PathDelim))) then
Reconcile := True;
end;
+ if Changes.Count > 0 then
+ RecountScan(Scan); // uma vez por lote, nao por ficheiro
if Reconcile then
ReconcileScan(Scan, Changes);
if Changes.Count > 0 then
diff --git a/tests/Tests.Analyzer.Scan.pas b/tests/Tests.Analyzer.Scan.pas
index 358694f..3812fa9 100644
--- a/tests/Tests.Analyzer.Scan.pas
+++ b/tests/Tests.Analyzer.Scan.pas
@@ -69,6 +69,8 @@ TRescanTests = class
[Test] procedure ReconcilePicksUpCreatedAndDeletedFiles;
[Test] procedure ReconcileWithoutChangesReportsNothing;
[Test] procedure ReconcileHandlesRenamedFolder;
+ [Test] procedure ReconcileFindsChangesAndRecountsTotals;
+ [Test] procedure RescanWithoutRecountDefersTotals;
end;
implementation
@@ -499,6 +501,43 @@ procedure TRescanTests.ReconcileHandlesRenamedFolder;
end;
end;
+procedure TRescanTests.ReconcileFindsChangesAndRecountsTotals;
+var
+ Changes: TList;
+begin
+ // ja havia uma alteracao no lote: a reconciliacao so junta as suas e recalcula os totais no fim
+ FDir.Write('New/n.pas', UnitWith(['N1', 'N2']));
+ FDir.Write('New/Deep/m.pas', UnitWith(['M1']));
+ FDir.Delete('c.pas');
+ Changes := TList.Create;
+ try
+ Changes.Add(Default(TScanChange));
+ ReconcileScan(FScan, Changes);
+ Assert.AreEqual(4, Changes.Count);
+ Assert.AreEqual('c.pas', Changes[1].Path);
+ Assert.AreEqual(Ord(rcRemoved), Ord(Changes[1].Kind));
+ Assert.AreEqual(Ord(rcAdded), Ord(Changes[2].Kind));
+ Assert.AreEqual(Ord(rcAdded), Ord(Changes[3].Kind));
+ Assert.AreEqual('a.pas|New/Deep/m.pas|New/n.pas|Sub/x.pas', UnitPaths(FScan));
+ Assert.AreEqual(6, FScan.TotalMethods); // A1, A2, N1, N2, M1, X1
+ Assert.AreEqual(3, FScan.Folders); // New, New/Deep, Sub
+ Assert.AreEqual(4, FScan.UnitsWithMethods);
+ finally
+ Changes.Free;
+ end;
+end;
+
+procedure TRescanTests.RescanWithoutRecountDefersTotals;
+var
+ Change: TScanChange;
+begin
+ FDir.Write('a.pas', UnitWith(['A1']));
+ Assert.AreEqual(Ord(rcChanged), Ord(RescanFile(FScan, 'a.pas', Change, False)));
+ Assert.AreEqual(4, FScan.TotalMethods, 'sem recontagem os totais ficam como estavam');
+ RecountScan(FScan);
+ Assert.AreEqual(3, FScan.TotalMethods);
+end;
+
initialization
TDUnitX.RegisterTestFixture(TAnalyzerHelperTests);
TDUnitX.RegisterTestFixture(TScanProjectTests);
diff --git a/tests/Tests.Colors.pas b/tests/Tests.Colors.pas
index 82fd01b..fc11d3b 100644
--- a/tests/Tests.Colors.pas
+++ b/tests/Tests.Colors.pas
@@ -26,6 +26,7 @@ TColorsTests = class
[Test] procedure OnAccentIsTheBestOfBlackAndWhite;
[Test] procedure PresetsAreValidAndDistinct;
[Test] procedure ExtremeColorsDoNotBreakTheDerivation;
+ [Test] procedure AccentsAlsoReadOnTheSecondSurface;
end;
implementation
@@ -192,6 +193,26 @@ procedure TColorsTests.ExtremeColorsDoNotBreakTheDerivation;
end;
end;
+procedure TColorsTests.AccentsAlsoReadOnTheSecondSurface;
+const
+ LightSurface2 = $FFEEF0EB;
+ DarkSurface2 = $FF202426;
+var
+ I: Integer;
+ S: TAccentSet;
+begin
+ // as linhas realcadas e as caixas usam o fundo secundario: a cor de destaque tem de se ler la tambem
+ for I := 0 to AccentPresetCount - 1 do
+ begin
+ S := DeriveAccent(AccentPresetColors[I], False, LightSurface, LightSurface2);
+ Assert.IsTrue(ContrastRatio(S.Accent, LightSurface2) >= 4.5, AccentPresetNames[I] + ' (claro)');
+ Assert.IsTrue(ContrastRatio(S.Accent, LightSurface) >= 4.5, AccentPresetNames[I] + ' (claro, branco)');
+ S := DeriveAccent(AccentPresetColors[I], True, DarkSurface, DarkSurface2);
+ Assert.IsTrue(ContrastRatio(S.Accent, DarkSurface2) >= 4.5, AccentPresetNames[I] + ' (escuro)');
+ Assert.IsTrue(ContrastRatio(S.Accent, DarkSurface) >= 4.5, AccentPresetNames[I] + ' (escuro, cartao)');
+ end;
+end;
+
initialization
TDUnitX.RegisterTestFixture(TColorsTests);
diff --git a/tests/Tests.Dproj.pas b/tests/Tests.Dproj.pas
index 262307f..d9886f5 100644
--- a/tests/Tests.Dproj.pas
+++ b/tests/Tests.Dproj.pas
@@ -36,6 +36,10 @@ TDprojTests = class
[Test] procedure PrefersTheDprojWithTheGivenName;
[Test] procedure NoDprojMeansEmpty;
[Test] procedure LoadsAFileFromDisk;
+ [Test] procedure ADerivedConfigurationInheritsFromItsParent;
+ [Test] procedure ADerivedConfigurationDoesNotTakeTheParentPlatformGroup;
+ [Test] procedure ACycleOfParentsDoesNotHang;
+ [Test] procedure APackageReadsItsOutputFolderAndSuffix;
end;
implementation
@@ -371,4 +375,84 @@ procedure TDprojTests.LoadsAFileFromDisk;
end;
end;
+// junta ao exemplo uma configuracao "Shipping" (Cfg_3) que deriva de AParent e so define o nome do executavel
+function WithShipping(const ASample, AParent: string): string;
+begin
+ Result := StringReplace(ASample, ' ',
+ ' ' + Crlf +
+ ' true' + Crlf +
+ ' ' + Crlf +
+ ' ' + Crlf +
+ ' DemoShip' + Crlf +
+ ' ' + Crlf +
+ ' ', []);
+ Result := StringReplace(Result, '',
+ ' Cfg_3' + AParent + '' +
+ Crlf + ' ', []);
+end;
+
+procedure TDprojTests.ADerivedConfigurationInheritsFromItsParent;
+var
+ D: TDprojInfo;
+ P: string;
+ HasRelease: Boolean;
+begin
+ ParseDproj(WithShipping(Sample, 'Cfg_2'), 'C:\Proj\Demo.dproj', 'Shipping', 'Win64', nil, D);
+ Assert.AreEqual('Shipping', D.Config);
+ Assert.AreEqual(3, D.MapFileMode, 'o mapa detalhado vem da Release, a mae');
+ HasRelease := False;
+ for P in D.UnitSearchPath do
+ if P = 'src\Release' then
+ HasRelease := True;
+ Assert.IsTrue(HasRelease, 'os caminhos da Release tambem');
+ Assert.AreEqual('.\out\bin\Win64\Shipping', D.ExeOutput, 'e os da Base');
+ // derivada da Debug, herda a Debug (sem mapa)
+ ParseDproj(WithShipping(Sample, 'Cfg_1'), 'C:\Proj\Demo.dproj', 'Shipping', 'Win64', nil, D);
+ Assert.AreEqual(0, D.MapFileMode);
+end;
+
+procedure TDprojTests.ADerivedConfigurationDoesNotTakeTheParentPlatformGroup;
+var
+ D: TDprojInfo;
+ Xml: string;
+begin
+ // o grupo da Release so para Win64 (Cfg_2_Win64): o MSBuild nao o aplica a Shipping/Win64
+ Xml := StringReplace(WithShipping(Sample, 'Cfg_2'), ' ',
+ ' ' + Crlf +
+ ' 1' + Crlf +
+ ' ' + Crlf +
+ ' ', []);
+ ParseDproj(Xml, 'C:\Proj\Demo.dproj', 'Release', 'Win64', nil, D);
+ Assert.AreEqual(1, D.MapFileMode, 'a propria Release/Win64 usa-o');
+ ParseDproj(Xml, 'C:\Proj\Demo.dproj', 'Shipping', 'Win64', nil, D);
+ Assert.AreEqual(3, D.MapFileMode, 'a derivada fica com o da Release, sem o da plataforma');
+end;
+
+procedure TDprojTests.ACycleOfParentsDoesNotHang;
+var
+ D: TDprojInfo;
+ Xml: string;
+begin
+ // Release (Cfg_2) a dizer que deriva de Shipping (Cfg_3), que deriva de Release
+ Xml := StringReplace(WithShipping(Sample, 'Cfg_2'), 'Cfg_2', 'Cfg_2Cfg_3', []);
+ ParseDproj(Xml, 'C:\Proj\Demo.dproj', 'Shipping', 'Win64', nil, D);
+ Assert.IsTrue(D.Found);
+ Assert.AreEqual(3, D.MapFileMode);
+end;
+
+procedure TDprojTests.APackageReadsItsOutputFolderAndSuffix;
+var
+ D: TDprojInfo;
+ Xml: string;
+begin
+ Xml := StringReplace(Sample, '',
+ '.\bpl\$(Platform)290', []);
+ ParseDproj(StringReplace(Xml, 'Demo.dpr', 'Demo.dpk', []), 'C:\Proj\Demo.dproj', 'Release', 'Win64', nil, D);
+ Assert.AreEqual('.\bpl\Win64', D.BplOutput);
+ Assert.AreEqual('290', D.DllSuffix);
+ // o $(Auto) do IDE nao se sabe expandir: fica sem sufixo
+ ParseDproj(StringReplace(Xml, '290', '$(Auto)', []), 'C:\Proj\Demo.dproj', 'Release', 'Win64', nil, D);
+ Assert.AreEqual('', D.DllSuffix);
+end;
+
end.
diff --git a/tests/Tests.MapFile.pas b/tests/Tests.MapFile.pas
index 42cdde4..eeab2ca 100644
--- a/tests/Tests.MapFile.pas
+++ b/tests/Tests.MapFile.pas
@@ -30,6 +30,7 @@ TMapFileTests = class
[Test] procedure FindsTheMapNextToTheExecutable;
[Test] procedure FindsTheMapInThePlatformAndConfigurationFolder;
[Test] procedure NoMapMeansEmpty;
+ [Test] procedure APackageMapIsNextToTheBplWithTheSuffix;
end;
implementation
@@ -309,4 +310,33 @@ procedure TMapFileTests.NoMapMeansEmpty;
end;
end;
+procedure TMapFileTests.APackageMapIsNextToTheBplWithTheSuffix;
+var
+ Dir: TTempDir;
+ D: TDprojInfo;
+begin
+ Dir := TTempDir.Create;
+ try
+ D := Default(TDprojInfo);
+ D.Found := True;
+ D.FileName := Dir.Full('Demo.dproj');
+ D.ProjectName := 'Demo';
+ D.Platform := 'Win64';
+ D.Config := 'Release';
+ D.IsPackage := True;
+ D.BplOutput := '.\bpl';
+ D.DllSuffix := '290';
+ Dir.Write('Win64/Release/Demo.map', 'um mapa antigo');
+ Dir.Write('bpl/Demo290.map', 'map');
+ Assert.AreEqual(TPath.GetFullPath(Dir.Full('bpl/Demo290.map')), FindMapFile(D), 'o do .bpl ganha');
+ D.DllSuffix := '';
+ Dir.Write('bpl/Demo.map', 'map');
+ Assert.AreEqual(TPath.GetFullPath(Dir.Full('bpl/Demo.map')), FindMapFile(D), 'sem sufixo');
+ D.IsPackage := False;
+ Assert.AreEqual(TPath.GetFullPath(Dir.Full('Win64/Release/Demo.map')), FindMapFile(D), 'uma aplicacao ignora o BplOutput');
+ finally
+ Dir.Free;
+ end;
+end;
+
end.
diff --git a/tests/Tests.Review.pas b/tests/Tests.Review.pas
index 6890d3b..0b0daba 100644
--- a/tests/Tests.Review.pas
+++ b/tests/Tests.Review.pas
@@ -7,7 +7,8 @@
interface
uses
- System.SysUtils, System.Generics.Collections, DUnitX.TestFramework, CM.Analyzer, CM.Store, CM.Stats, Tests.Helpers;
+ System.SysUtils, System.Generics.Collections, DUnitX.TestFramework, CM.Analyzer, CM.Store, CM.Stats, CM.GitReview,
+ Tests.Helpers;
type
[TestFixture]
@@ -46,6 +47,9 @@ TReviewRulesTests = class
[Test] procedure BackfillGivesTheCommitOfTheCompletionTime;
[Test] procedure BackfillSkipsFilesWithoutTimeOrAlreadyKnown;
[Test] procedure RevisionRoundTripsThroughJson;
+ [Test] procedure SnapKeepsOnlyReviewedFilesWithCommitOrTime;
+ [Test] procedure TimelineIsOnlyNeededForOldReviews;
+ [Test] procedure ApplyBackfillSkipsFilesChangedMeanwhile;
end;
implementation
@@ -471,4 +475,74 @@ procedure TReviewRulesTests.RevisionRoundTripsThroughJson;
Assert.AreEqual('{"a.pas":{"done":true}}', FState.ToJSONString, 'sem commit, o formato de sempre');
end;
+procedure TReviewRulesTests.SnapKeepsOnlyReviewedFilesWithCommitOrTime;
+var
+ Scan: TProjectScan;
+ A, B, C, D: TUnitInfo;
+ Snaps: TArray;
+begin
+ A := MakeUnitInfo('a.pas', 'Raiz', [Meth('One')]);
+ B := MakeUnitInfo('b.pas', 'Raiz', [Meth('Two')]);
+ C := MakeUnitInfo('c.pas', 'Raiz', [Meth('Three')]);
+ D := MakeUnitInfo('d.pas', 'Raiz', [Meth('Four')]);
+ Scan := NewScan(1, [A, B, C, D]);
+ try
+ SetMethodReview(A, FState.Rec('a.pas'), 'One', rsDone);
+ FState.Rec('a.pas').Rev := 'h1';
+ SetMethodReview(B, FState.Rec('b.pas'), 'Two', rsInReview); // sem commit nem hora
+ FState.Rec('c.pas').Rev := 'h1'; // tem commit mas esta por rever
+ SetMethodReview(D, FState.Rec('d.pas'), 'Four', rsDone);
+ FState.Rec('d.pas').Ts := 5000; // revisao antiga: so a hora
+ Snaps := SnapReviews(Scan, FState);
+ Assert.AreEqual(2, Length(Snaps));
+ Assert.AreEqual('a.pas', Snaps[0].Path);
+ Assert.AreEqual('h1', Snaps[0].Rev);
+ Assert.AreEqual('d.pas', Snaps[1].Path);
+ Assert.AreEqual('', Snaps[1].Rev);
+ Assert.AreEqual(5000, Snaps[1].Ts);
+ finally
+ Scan.Free;
+ end;
+end;
+
+procedure TReviewRulesTests.TimelineIsOnlyNeededForOldReviews;
+var
+ Scan: TProjectScan;
+ A: TUnitInfo;
+begin
+ A := MakeUnitInfo('a.pas', 'Raiz', [Meth('One')]);
+ Scan := NewScan(1, [A]);
+ try
+ Assert.IsFalse(NeedsTimeline(SnapReviews(Scan, FState)), 'nada revisto');
+ SetMethodReview(A, FState.Rec('a.pas'), 'One', rsDone);
+ FState.Rec('a.pas').Ts := 5000;
+ FState.Rec('a.pas').Rev := '';
+ Assert.IsTrue(NeedsTimeline(SnapReviews(Scan, FState)), 'revisao antiga sem commit');
+ FState.Rec('a.pas').Rev := 'h1';
+ Assert.IsFalse(NeedsTimeline(SnapReviews(Scan, FState)), 'todas ja tem commit: sem "git log"');
+ finally
+ Scan.Free;
+ end;
+end;
+
+procedure TReviewRulesTests.ApplyBackfillSkipsFilesChangedMeanwhile;
+var
+ B: TArray;
+begin
+ FState.Rec('a.pas').Ts := 1000;
+ FState.Rec('b.pas').Ts := 2000; // revisto de novo depois da copia
+ FState.Rec('c.pas').Ts := 3000;
+ FState.Rec('c.pas').Rev := 'ja-tem';
+ SetLength(B, 4);
+ B[0].Path := 'a.pas'; B[0].Rev := 'h'; B[0].Ts := 1000;
+ B[1].Path := 'b.pas'; B[1].Rev := 'h'; B[1].Ts := 1500;
+ B[2].Path := 'c.pas'; B[2].Rev := 'h'; B[2].Ts := 3000;
+ B[3].Path := 'x.pas'; B[3].Rev := 'h'; B[3].Ts := 1000; // ja nao existe no progresso
+ Assert.AreEqual(1, ApplyBackfill(FState, B));
+ Assert.AreEqual('h', FState.Find('a.pas').Rev);
+ Assert.AreEqual('', FState.Find('b.pas').Rev);
+ Assert.AreEqual('ja-tem', FState.Find('c.pas').Rev);
+ Assert.IsNull(FState.Find('x.pas'));
+end;
+
end.
diff --git a/tests/Tests.SbomFormats.pas b/tests/Tests.SbomFormats.pas
index c01465f..66fb4ce 100644
--- a/tests/Tests.SbomFormats.pas
+++ b/tests/Tests.SbomFormats.pas
@@ -1,6 +1,6 @@
unit Tests.SbomFormats;
-// Testes dos escritores de SBOM (CM.SbomFormats): CycloneDX 1.5 e SPDX 2.3 em JSON, e dos validadores.
+// Testes dos escritores de SBOM (CM.SbomFormats): CycloneDX 1.6 e SPDX 2.3 em JSON, e dos validadores.
interface
@@ -50,6 +50,8 @@ TSbomFormatsTests = class
[Test] procedure CycloneDxValidatorRejectsAnEmptyLicense;
[Test] procedure SpdxWritesVersionAndDeclaredLicense;
[Test] procedure SpdxKeepsNoAssertionWithoutLicense;
+ [Test] procedure BothFormatsWriteTheProjectCopyright;
+ [Test] procedure CycloneDxDependenciesAreInAStableOrder;
end;
implementation
@@ -150,7 +152,8 @@ procedure TSbomFormatsTests.CycloneDxHasTheRequiredTopLevelFields;
R := Cdx;
try
Assert.AreEqual('CycloneDX', R.GetValue('bomFormat'));
- Assert.AreEqual('1.5', R.GetValue('specVersion'));
+ Assert.AreEqual('1.6', R.GetValue('specVersion'));
+ Assert.AreEqual('http://cyclonedx.org/schema/bom-1.6.schema.json', R.GetValue('$schema'));
Assert.AreEqual('urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79', R.GetValue('serialNumber'));
Assert.AreEqual(1, R.GetValue('version'));
Assert.IsTrue(R.GetValue('metadata') is TJSONObject);
@@ -458,7 +461,7 @@ procedure TSbomFormatsTests.CycloneDxValidatorFindsEachProblem;
Assert.Contains(Problem, 'não existe');
Assert.IsFalse(ValidateCycloneDx(Good.Replace(StringOfChar('c', 64), 'curto'), Problem));
Assert.Contains(Problem, 'hash SHA-256');
- Assert.IsFalse(ValidateCycloneDx(Good.Replace('"specVersion": "1.5"', '"x": "1.5"'), Problem));
+ Assert.IsFalse(ValidateCycloneDx(Good.Replace('"specVersion": "1.6"', '"x": "1.6"'), Problem));
Assert.Contains(Problem, 'specVersion');
end;
@@ -665,4 +668,57 @@ procedure TSbomFormatsTests.SpdxKeepsNoAssertionWithoutLicense;
end;
end;
+procedure TSbomFormatsTests.BothFormatsWriteTheProjectCopyright;
+var
+ R: TJSONObject;
+ Arr: TJSONArray;
+begin
+ // sem copyright: o CycloneDX nao escreve o campo e o SPDX diz NOASSERTION
+ R := Cdx;
+ try
+ Assert.IsNull(R.FindValue('metadata.component.copyright'));
+ finally
+ R.Free;
+ end;
+ FSbom.Project.Copyright := '(c) 2026 Acme';
+ R := Cdx;
+ try
+ Assert.AreEqual('(c) 2026 Acme', R.GetValue('metadata.component.copyright'));
+ finally
+ R.Free;
+ end;
+ R := Spdx;
+ try
+ Arr := R.GetValue('packages') as TJSONArray;
+ Assert.AreEqual('(c) 2026 Acme', (Arr.Items[0] as TJSONObject).GetValue('copyrightText'), 'o pacote da aplicacao');
+ Assert.AreEqual('NOASSERTION', (Arr.Items[1] as TJSONObject).GetValue('copyrightText'), 'as units nao herdam');
+ finally
+ R.Free;
+ end;
+end;
+
+procedure TSbomFormatsTests.CycloneDxDependenciesAreInAStableOrder;
+var
+ R: TJSONObject;
+ Deps: TJSONArray;
+ I: Integer;
+ Prev, Ref: string;
+begin
+ R := Cdx;
+ try
+ Deps := R.GetValue('dependencies') as TJSONArray;
+ Assert.AreEqual('app:Demo', (Deps.Items[0] as TJSONObject).GetValue('ref'), 'a aplicacao vem primeiro');
+ Prev := '';
+ for I := 1 to Deps.Count - 1 do
+ begin
+ Ref := (Deps.Items[I] as TJSONObject).GetValue('ref');
+ Assert.IsTrue(CompareStr(Prev, Ref) < 0, Prev + ' antes de ' + Ref);
+ Prev := Ref;
+ end;
+ finally
+ R.Free;
+ end;
+ Assert.AreEqual(SbomCycloneDxJson(FSbom, FOptions), SbomCycloneDxJson(FSbom, FOptions), 'o mesmo SBOM da o mesmo texto');
+end;
+
end.
diff --git a/tests/Tests.SbomResolve.pas b/tests/Tests.SbomResolve.pas
index 8fa4b14..ca8854e 100644
--- a/tests/Tests.SbomResolve.pas
+++ b/tests/Tests.SbomResolve.pas
@@ -25,6 +25,8 @@ TSbomResolveTests = class
[Test] procedure VclAndFmxAreToldApartByNameOrFolder;
[Test] procedure OldNamesWithoutNamespaceUseTheScopes;
[Test] procedure LibrariesShippedWithDelphiStayThirdParty;
+ [Test] procedure OnlyEmbarcaderoFoldersInsideTheInstallCount;
+ [Test] procedure BundledThirdPartyDcusInLibStayThirdParty;
[Test] procedure ThirdPartyIsFoundInTheProjectSearchPaths;
[Test] procedure PasIsPreferredOverDcu;
[Test] procedure DcuIsTheFallback;
@@ -163,6 +165,46 @@ procedure TSbomResolveTests.LibrariesShippedWithDelphiStayThirdParty;
Assert.AreEqual(Ord(soRtl), Ord(FSbom.Find('System.SysUtils').Origin), 'a RTL continua da Embarcadero');
end;
+procedure TSbomResolveTests.OnlyEmbarcaderoFoldersInsideTheInstallCount;
+begin
+ // dentro da instalacao, mas fora das pastas da Embarcadero: uma biblioteca posta em source\, os Extras e o lib\
+ FDir.Write('delphi/source/MinhaLib/Minha.Unit.pas', 'unit Minha.Unit;');
+ FDir.Write('delphi/source/Skia/System.Skia.pas', 'unit System.Skia;');
+ FDir.Write('delphi/Extras/Tool/Extra.Tool.pas', 'unit Extra.Tool;');
+ FDir.Write('delphi/lib/win64/release/Data.DB.dcu', 'dcu');
+ FDir.Write('delphi/source/Property Editors/DesignEditors.pas', 'unit DesignEditors;');
+ FOptions.SearchPaths := [FDir.Full('delphi/Extras/Tool'), FDir.Full('delphi/lib/win64/release')];
+ Add('Minha.Unit', soRtl);
+ Add('System.Skia', soRtl);
+ Add('Extra.Tool', soRtl);
+ Add('Data.DB', soThirdParty);
+ Add('DesignEditors', soThirdParty);
+ Add('System.SysUtils', soThirdParty);
+ ResolveSbom(FSbom, FOptions);
+ Assert.AreEqual(Ord(soThirdParty), Ord(FSbom.Find('Minha.Unit').Origin), 'source\MinhaLib nao e da Embarcadero');
+ Assert.AreEqual(Ord(soThirdParty), Ord(FSbom.Find('System.Skia').Origin), 'o Skia tem licenca propria, mesmo com nome System.');
+ Assert.AreEqual(Ord(soThirdParty), Ord(FSbom.Find('Extra.Tool').Origin), 'os Extras sao de terceiros');
+ Assert.AreEqual(Ord(soRtl), Ord(FSbom.Find('Data.DB').Origin), 'o lib\ do Delphi');
+ Assert.AreEqual(Ord(soRtl), Ord(FSbom.Find('DesignEditors').Origin), 'uma pasta conhecida com espaco no nome');
+ Assert.AreEqual(Ord(soRtl), Ord(FSbom.Find('System.SysUtils').Origin), 'source\rtl');
+end;
+
+procedure TSbomResolveTests.BundledThirdPartyDcusInLibStayThirdParty;
+begin
+ // o lib\ tem os DCU do Indy e do DUnitX ao lado dos da Embarcadero
+ FDir.Write('delphi/lib/win64/release/IdHL7.dcu', 'dcu');
+ FDir.Write('delphi/lib/win64/release/TestFrameworkExtension.dcu', 'dcu');
+ FDir.Write('delphi/lib/win64/release/Idioma.Embarcadero.dcu', 'dcu');
+ FOptions.SearchPaths := [FDir.Full('delphi/lib/win64/release')];
+ Add('IdHL7', soRtl);
+ Add('TestFrameworkExtension', soRtl);
+ Add('Idioma.Embarcadero', soThirdParty);
+ ResolveSbom(FSbom, FOptions);
+ Assert.AreEqual(Ord(soThirdParty), Ord(FSbom.Find('IdHL7').Origin), 'Indy');
+ Assert.AreEqual(Ord(soThirdParty), Ord(FSbom.Find('TestFrameworkExtension').Origin), 'DUnit');
+ Assert.AreEqual(Ord(soRtl), Ord(FSbom.Find('Idioma.Embarcadero').Origin), '"Id" seguido de minuscula nao e do Indy');
+end;
+
procedure TSbomResolveTests.ThirdPartyIsFoundInTheProjectSearchPaths;
var
C: TSbomComponent;
diff --git a/tests/Tests.SbomService.pas b/tests/Tests.SbomService.pas
index e36615d..202606c 100644
--- a/tests/Tests.SbomService.pas
+++ b/tests/Tests.SbomService.pas
@@ -5,7 +5,8 @@
interface
uses
- System.SysUtils, System.IOUtils, System.Hash, DUnitX.TestFramework, CM.Deps, CM.Sbom, CM.SbomService, Tests.Helpers;
+ System.SysUtils, System.IOUtils, System.Hash, Winapi.Windows, DUnitX.TestFramework, CM.Deps, CM.Sbom, CM.SbomService,
+ Tests.Helpers;
type
[TestFixture]
@@ -26,6 +27,8 @@ TSbomServiceTests = class
[Test] procedure ProjectUnitsAreListedOnlyWhenAsked;
[Test] procedure TheMapConfirmsAndAddsUnits;
[Test] procedure AMissingMapRaisesAWarning;
+ [Test] procedure AMapWithoutUnitsIsNotUsed;
+ [Test] procedure APackageWithTheIdeDefaultsFindsItsMap;
[Test] procedure TheMapCanBeSwitchedOff;
[Test] procedure HashesCanBeSwitchedOff;
[Test] procedure WithoutDelphiAWarningIsRaised;
@@ -228,6 +231,55 @@ procedure TSbomServiceTests.AMissingMapRaisesAWarning;
end;
end;
+procedure TSbomServiceTests.AMapWithoutUnitsIsNotUsed;
+var
+ S: TSbom;
+begin
+ // um mapa sem linhas M= nem "Line numbers for" (um ficheiro cortado, por exemplo): existe, mas nao diz que units ficaram
+ WriteProject(False);
+ FDir.Write('proj/out/Win64/Release/Demo.map',
+ ' Start Length Name Class' + #13#10 +
+ ' 0001:00401000 0000F234H .text CODE' + #13#10);
+ S := Gen;
+ try
+ Assert.AreEqual('', S.MapFile, 'o mapa nao se usa');
+ Assert.AreEqual(0, S.NotLinkedCount, 'nenhum componente fica "fora do mapa"');
+ Assert.IsTrue(S.Warnings.Contains('O ficheiro .map não tem units que se consigam ler (pode estar incompleto ou ter outro formato): volta a compilar o projeto com o mapa ligado.'));
+ finally
+ S.Free;
+ end;
+end;
+
+procedure TSbomServiceTests.APackageWithTheIdeDefaultsFindsItsMap;
+var
+ S: TSbom;
+ OldPublic: string;
+begin
+ // um package criado pelo IDE: DCC_BplOutput $(BDSCOMMONDIR)\Bpl\$(Platform) e DllSuffix $(Auto); a pasta comum vem
+ // da variavel PUBLIC, que aqui aponta para a pasta temporaria
+ FDir.Write('proj/Pkg.dproj',
+ 'Pkg.dpkTrue' +
+ '$(BDSCOMMONDIR)\Bpl\$(Platform)' +
+ '$(Auto)' +
+ 'Cfg_2');
+ FDir.Write('proj/Core.pas', 'unit Core;');
+ FDir.Write('public/Documents/Embarcadero/Studio/37.0/Bpl/Win32/Pkg370.map',
+ 'Detailed map of segments' + #13#10 + ' 0001:00000000 000071A4 C=CODE S=.text G=(none) M=System ACBP=A9' + #13#10);
+ FOptions.DelphiRoot := FDir.Full('Studio/37.0');
+ OldPublic := GetEnvironmentVariable('PUBLIC');
+ SetEnvironmentVariable('PUBLIC', PChar(FDir.Full('public')));
+ try
+ S := Gen;
+ finally
+ SetEnvironmentVariable('PUBLIC', PChar(OldPublic));
+ end;
+ try
+ Assert.AreEqual('Pkg370.map', ExtractFileName(S.MapFile));
+ finally
+ S.Free;
+ end;
+end;
+
procedure TSbomServiceTests.TheMapCanBeSwitchedOff;
var
S: TSbom;
diff --git a/tools/i18n/translations.tsv b/tools/i18n/translations.tsv
index 0fa4fab..2e7e5e5 100644
--- a/tools/i18n/translations.tsv
+++ b/tools/i18n/translations.tsv
@@ -616,6 +616,7 @@ Aguarde: o SBOM ainda não está pronto. Wait: the SBOM is not ready yet. Patien
Não se encontrou o ficheiro .dproj: a versão e os caminhos de procura ficam por preencher. The .dproj file was not found: the version and the search paths stay empty. Le fichier .dproj est introuvable : la version et les chemins de recherche restent vides. Die .dproj-Datei wurde nicht gefunden: Version und Suchpfade bleiben leer.
Não se encontrou a instalação do Delphi: as units da Embarcadero só se reconhecem pelo nome. The Delphi installation was not found: Embarcadero units are only recognised by name. L'installation de Delphi est introuvable : les unités d'Embarcadero ne sont reconnues que par leur nom. Die Delphi-Installation wurde nicht gefunden: Embarcadero-Units werden nur am Namen erkannt.
Não se encontrou o ficheiro .map: compila o projeto com o mapa «Detailed» para confirmar as units ligadas. The .map file was not found: build the project with a "Detailed" map to confirm the linked units. Le fichier .map est introuvable : compile le projet avec une map « Detailed » pour confirmer les unités liées. Die .map-Datei wurde nicht gefunden: Kompiliere das Projekt mit einer „Detailed“-Map, um die gebundenen Units zu bestätigen.
+O ficheiro .map não tem units que se consigam ler (pode estar incompleto ou ter outro formato): volta a compilar o projeto com o mapa ligado. The .map file has no readable units (it may be incomplete or in another format): build the project again with the map turned on. Le fichier .map ne contient aucune unité lisible (il est peut-être incomplet ou dans un autre format) : recompile le projet avec la map activée. Die .map-Datei enthält keine lesbaren Units (sie ist vielleicht unvollständig oder hat ein anderes Format): Kompiliere das Projekt erneut mit eingeschalteter Map.
SBOM inspirado no DX.Comply (MIT, Olaf Monien). SBOM inspired by DX.Comply (MIT, Olaf Monien). SBOM inspirée de DX.Comply (MIT, Olaf Monien). SBOM inspiriert von DX.Comply (MIT, Olaf Monien).
# --- Classes e heranca
classe class classe Klasse