Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92b4a34496 | ||
|
|
fb2f4a7c18 | ||
|
|
7380edb4ae | ||
|
|
acfee89563 | ||
|
|
f0da7233cc | ||
|
|
4f5641c308 | ||
|
|
f80fca8eea | ||
|
|
637e16b4d7 | ||
|
|
0d463e2047 | ||
|
|
da5d97822e | ||
|
|
18f3f643bb |
No files matched your search
Generated
+45
-46
@@ -4,8 +4,9 @@
|
|||||||
<option name="autoReloadType" value="SELECTIVE" />
|
<option name="autoReloadType" value="SELECTIVE" />
|
||||||
</component>
|
</component>
|
||||||
<component name="ChangeListManager">
|
<component name="ChangeListManager">
|
||||||
<list default="true" id="184f7582-9491-4541-9ea8-677e31b83cd6" name="Changes" comment="">
|
<list default="true" id="62118a1b-608f-4144-b29c-cf46419ca676" name="Changes" comment="">
|
||||||
<change beforePath="$PROJECT_DIR$/plugins.registry.json" beforeDir="false" afterPath="$PROJECT_DIR$/plugins.registry.json" afterDir="false" />
|
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
|
||||||
|
<change beforePath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/udp/SocketUDP.java" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/udp/SocketUDP.java" afterDir="false" />
|
||||||
</list>
|
</list>
|
||||||
<option name="SHOW_DIALOG" value="false" />
|
<option name="SHOW_DIALOG" value="false" />
|
||||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||||
@@ -16,80 +17,78 @@
|
|||||||
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
|
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
|
||||||
</component>
|
</component>
|
||||||
<component name="ProjectColorInfo">{
|
<component name="ProjectColorInfo">{
|
||||||
"associatedIndex": 2,
|
"associatedIndex": 0
|
||||||
"fromUser": false
|
|
||||||
}</component>
|
}</component>
|
||||||
<component name="ProjectId" id="3GjM8jvhMxaHpSRoyB7jkVQR4Bc" />
|
<component name="ProjectId" id="3GbOdQKFlKqBjAjqjAv5TRPxr6Z" />
|
||||||
<component name="ProjectViewState">
|
<component name="ProjectViewState">
|
||||||
<option name="hideEmptyMiddlePackages" value="true" />
|
<option name="hideEmptyMiddlePackages" value="true" />
|
||||||
<option name="showLibraryContents" value="true" />
|
<option name="showLibraryContents" value="true" />
|
||||||
</component>
|
</component>
|
||||||
<component name="PropertiesComponent">{
|
<component name="PropertiesComponent"><![CDATA[{
|
||||||
"keyToString": {
|
"keyToString": {
|
||||||
"ModuleVcsDetector.initialDetectionPerformed": "true",
|
"Application.Main.executor": "Run",
|
||||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
"ModuleVcsDetector.initialDetectionPerformed": "true",
|
||||||
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
|
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||||
"RunOnceActivity.git.unshallow": "true",
|
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
|
||||||
"RunOnceActivity.typescript.service.memoryLimit.init": "true",
|
"RunOnceActivity.git.unshallow": "true",
|
||||||
"codeWithMe.voiceChat.enabledByDefault": "false",
|
"git-widget-placeholder": "main",
|
||||||
"git-widget-placeholder": "main",
|
"ignore.virus.scanning.warn.message": "true",
|
||||||
"ignore.virus.scanning.warn.message": "true",
|
"kotlin-language-version-configured": "true",
|
||||||
"kotlin-language-version-configured": "true",
|
"last_opened_file_path": "C:/Users/extre/OneDrive/Documentos/Faculdade/2026_02/Monitoria/Pitiupi",
|
||||||
"last_opened_file_path": "C:/Users/Gustavo/OneDrive/Documentos/Faculdade/2026_2/Monitoria/pitiupi",
|
"project.structure.last.edited": "Modules",
|
||||||
"node.js.detected.package.eslint": "true",
|
"project.structure.proportion": "0.0",
|
||||||
"node.js.detected.package.tslint": "true",
|
"project.structure.side.proportion": "0.2",
|
||||||
"node.js.selected.package.eslint": "(autodetect)",
|
"settings.editor.selected.configurable": "preferences.keymap"
|
||||||
"node.js.selected.package.tslint": "(autodetect)",
|
|
||||||
"nodejs_package_manager_path": "npm",
|
|
||||||
"project.structure.last.edited": "Project",
|
|
||||||
"project.structure.proportion": "0.0",
|
|
||||||
"project.structure.side.proportion": "0.0",
|
|
||||||
"run.code.analysis.last.selected.profile": "pProject Default",
|
|
||||||
"settings.editor.selected.configurable": "preferences.lookFeel"
|
|
||||||
}
|
}
|
||||||
}</component>
|
}]]></component>
|
||||||
<component name="RecentsManager">
|
<component name="RecentsManager">
|
||||||
<key name="CopyFile.RECENT_KEYS">
|
<key name="CopyFile.RECENT_KEYS">
|
||||||
<recent name="C:\Users\Gustavo\OneDrive\Documentos\Faculdade\2026_2\Monitoria\pitiupi\plugins\ping" />
|
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\pitiupi\plugins" />
|
||||||
<recent name="C:\Users\Gustavo\OneDrive\Documentos\Faculdade\2026_2\Monitoria\pitiupi\pitiupi\plugins" />
|
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\plugins\ping" />
|
||||||
</key>
|
</key>
|
||||||
<key name="MoveFile.RECENT_KEYS">
|
<key name="MoveFile.RECENT_KEYS">
|
||||||
<recent name="C:\Users\Gustavo\OneDrive\Documentos\Faculdade\2026_2\Monitoria\pitiupi\plugins\ping" />
|
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\plugins\ping" />
|
||||||
<recent name="C:\Users\Gustavo\OneDrive\Documentos\Faculdade\2026_2\Monitoria\pitiupi\pitiupi\plugins" />
|
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\privateChat" />
|
||||||
|
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\privateChat\src" />
|
||||||
|
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\pitiupi\plugins" />
|
||||||
|
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\pitiupi.mpChat\out\META-INF" />
|
||||||
</key>
|
</key>
|
||||||
</component>
|
</component>
|
||||||
<component name="RunManager">
|
<component name="RunManager">
|
||||||
<configuration default="true" type="JetRunConfigurationType">
|
<configuration name="Main" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
|
||||||
|
<option name="MAIN_CLASS_NAME" value="pitiupi.Main" />
|
||||||
<module name="pitiupi" />
|
<module name="pitiupi" />
|
||||||
|
<extension name="coverage">
|
||||||
|
<pattern>
|
||||||
|
<option name="PATTERN" value="pitiupi.*" />
|
||||||
|
<option name="ENABLED" value="true" />
|
||||||
|
</pattern>
|
||||||
|
</extension>
|
||||||
<method v="2">
|
<method v="2">
|
||||||
<option name="Make" enabled="true" />
|
<option name="Make" enabled="true" />
|
||||||
</method>
|
</method>
|
||||||
</configuration>
|
</configuration>
|
||||||
<configuration default="true" type="KotlinStandaloneScriptRunConfigurationType">
|
<recent_temporary>
|
||||||
<module name="pitiupi" />
|
<list>
|
||||||
<option name="filePath" />
|
<item itemvalue="Application.Main" />
|
||||||
<method v="2" />
|
</list>
|
||||||
</configuration>
|
</recent_temporary>
|
||||||
</component>
|
</component>
|
||||||
<component name="SharedIndexes">
|
<component name="SharedIndexes">
|
||||||
<attachedChunks>
|
<attachedChunks>
|
||||||
<set>
|
<set>
|
||||||
<option value="bundled-jdk-30f59d01ecdd-37e91769500f-intellij.indexing.shared.core-IU-261.26222.65" />
|
<option value="bundled-jdk-9823dce3aa75-bf35d07a577b-intellij.indexing.shared.core-IU-252.28539.149" />
|
||||||
<option value="bundled-js-predefined-d6986cc7102b-31caf2ab9e3c-JavaScript-IU-261.26222.65" />
|
|
||||||
</set>
|
</set>
|
||||||
</attachedChunks>
|
</attachedChunks>
|
||||||
</component>
|
</component>
|
||||||
<component name="TaskManager">
|
<component name="TaskManager">
|
||||||
<task active="true" id="Default" summary="Default task">
|
<task active="true" id="Default" summary="Default task">
|
||||||
<changelist id="184f7582-9491-4541-9ea8-677e31b83cd6" name="Changes" comment="" />
|
<changelist id="62118a1b-608f-4144-b29c-cf46419ca676" name="Changes" comment="" />
|
||||||
<created>1784480367533</created>
|
<created>1784236888334</created>
|
||||||
<option name="number" value="Default" />
|
<option name="number" value="Default" />
|
||||||
<option name="presentableId" value="Default" />
|
<option name="presentableId" value="Default" />
|
||||||
<updated>1784480367533</updated>
|
<updated>1784236888334</updated>
|
||||||
</task>
|
</task>
|
||||||
<servers />
|
<servers />
|
||||||
</component>
|
</component>
|
||||||
<component name="TypeScriptGeneratedFilesManager">
|
|
||||||
<option name="version" value="3" />
|
|
||||||
</component>
|
|
||||||
</project>
|
</project>
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
# Plugins online no Pitiupi
|
||||||
|
|
||||||
|
Este documento descreve a extensão do sistema de plugins do Pitiupi: baixar e instalar plugins por HTTP, compartilhar os próprios plugins, atualizar plugins e atualizar o próprio Pitiupi.
|
||||||
|
|
||||||
|
- [1. Visão geral](#1-visão-geral)
|
||||||
|
- [2. O que já existia](#2-o-que-já-existia)
|
||||||
|
- [3. O que foi modificado](#3-o-que-foi-modificado)
|
||||||
|
- [4. Como funciona](#4-como-funciona)
|
||||||
|
- [5. Como usar](#5-como-usar)
|
||||||
|
- [6. Segurança](#6-segurança)
|
||||||
|
- [7. Vantagens](#7-vantagens)
|
||||||
|
- [8. Limitações](#8-limitações)
|
||||||
|
- [9. Testes](#9-testes)
|
||||||
|
- [10. Solução de problemas](#10-solução-de-problemas)
|
||||||
|
- [11. Decisões de projeto](#11-decisões-de-projeto)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Visão geral
|
||||||
|
|
||||||
|
Antes, para instalar um plugin era preciso ter o arquivo `.jar` na máquina e escolhê-lo num seletor de arquivos. Agora o Pitiupi também consegue:
|
||||||
|
|
||||||
|
| Item | Recurso | Onde está na interface |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 3 | Consultar um servidor de plugins, ver a lista e baixar/instalar | **Plugins > Plugins online…** |
|
||||||
|
| 4 | Iniciar um servidor HTTP próprio que compartilha os plugins instalados | **Plugins > Compartilhar meus plugins…** |
|
||||||
|
| 5 | Comparar a versão instalada com a do servidor e atualizar | Coluna **Situação** e botão **Atualizar** em *Plugins online…* |
|
||||||
|
| 6 | Verificar se há uma versão nova do Pitiupi, baixar, trocar o JAR e reiniciar | **Ajuda > Verificar atualização…** |
|
||||||
|
|
||||||
|
Tudo usa apenas o que já vem no JDK (`java.net.http.HttpClient` e `com.sun.net.httpserver.HttpServer`). Nenhuma dependência nova foi adicionada.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. O que já existia
|
||||||
|
|
||||||
|
Os itens 1 e 2 da lista original já estavam implementados e **não foram refeitos**:
|
||||||
|
|
||||||
|
1. **Pasta de plugins com caminho absoluto.** `PitiupiHome` resolve a raiz de dados e sempre a converte para caminho absoluto. A pasta de plugins é `<raiz>/plugins`. A raiz é escolhida nesta ordem:
|
||||||
|
1. variável de ambiente `PITIUPI_HOME` (aceita `~/`);
|
||||||
|
2. `.pitiupi/` ao lado do `plugins.registry.json` (raiz do clone);
|
||||||
|
3. `$HOME/pitiupi`, como último recurso.
|
||||||
|
|
||||||
|
Usando `scripts/pitiupi.sh`, o caminho real é `<clone>/.pitiupi/plugins`.
|
||||||
|
|
||||||
|
2. **Gestão local de plugins.** Na aba **Configurações** (`SettingsPanel`): tabela de plugins instalados, **Instalar JAR…** (seletor de arquivo) e **Remover selecionado**. Depois de instalar ou remover, o app oferece reiniciar. A mesma coisa existe por linha de comando em `PluginStoreCli`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. O que foi modificado
|
||||||
|
|
||||||
|
### 3.1 Arquivos novos
|
||||||
|
|
||||||
|
| Arquivo | Função |
|
||||||
|
| --- | --- |
|
||||||
|
| `plugins/remote/RemotePluginEntry` | Uma linha da lista (id, nome, versão, autor, descrição, arquivo, SHA-256) |
|
||||||
|
| `plugins/remote/PluginListFormat` | Lê e gera o `lista-de-plugins.txt`; valida cada campo vindo da rede |
|
||||||
|
| `plugins/remote/PluginRepositoryClient` | Cliente HTTP: normaliza o endereço, busca a lista, baixa o JAR e confere o SHA-256 |
|
||||||
|
| `plugins/remote/PluginServer` | Servidor HTTP embutido que gera a lista na hora e serve os JARs |
|
||||||
|
| `plugins/remote/Sha256` | Hash SHA-256 de arquivo, lendo em blocos |
|
||||||
|
| `plugins/remote/VersionCompare` | Compara versões número a número (`1.10` > `1.9`) |
|
||||||
|
| `plugins/remote/PluginStatus` | Casa plugin instalado com plugin remoto e diz se há atualização |
|
||||||
|
| `platform/AppVersion` | Versão do Pitiupi (do manifesto) e caminho do JAR em execução |
|
||||||
|
| `presentation/shell/RemotePluginsDialog` | Tela *Plugins online* |
|
||||||
|
| `presentation/shell/PluginServerDialog` | Tela *Compartilhar meus plugins* |
|
||||||
|
| `presentation/shell/SelfUpdater` | Verificação e aplicação da atualização do Pitiupi |
|
||||||
|
|
||||||
|
Todos os caminhos acima são relativos a `pitiupi/src/pitiupi/`.
|
||||||
|
|
||||||
|
### 3.2 Arquivos alterados
|
||||||
|
|
||||||
|
| Arquivo | Mudança |
|
||||||
|
| --- | --- |
|
||||||
|
| `PluginStore` | Novo `installFromFile(origem, nomeDestino, atualizaCatalogo)`. A assinatura antiga continua existindo e chama a nova |
|
||||||
|
| `PluginMetadataWriter` | `metaPathFor` virou público; passa a gravar também `description` no `.plugin.meta` |
|
||||||
|
| `models/Plugin` | Novo método `getDescription()`, **não abstrato** (devolve `""`), para não quebrar plugins existentes |
|
||||||
|
| `ConfigLoader` | Novos `getString` e `setString` (usados para a chave `plugins.serverUrl`) |
|
||||||
|
| `ErrorCode` | Seis códigos novos: servidor inacessível, lista inválida, falha no download, hash não confere, falha ao iniciar servidor, falha na atualização |
|
||||||
|
| `ShellMenuBar` | Novo menu **Plugins** e novo item **Ajuda > Verificar atualização…** |
|
||||||
|
| `MainShellFrame` | Cria o `PluginServer`, passa ao menu e o encerra em `exit()` |
|
||||||
|
| `ApplicationRestarter` | `locateRunningJar` agora usa `AppVersion.runningJar()` (antes usava `getLocation().getPath()`, que devolvia caminho codificado e não funcionava fora de JAR) |
|
||||||
|
| `pitiupi/manifest.mf` | Nova linha `Implementation-Version: 1.0.0` |
|
||||||
|
| `scripts/pitiupi.sh` | O `rm -f plugins/*.jar` virou `find ... -type l -name '*.jar' -delete` (ver 4.5) |
|
||||||
|
|
||||||
|
### 3.3 Testes novos
|
||||||
|
|
||||||
|
`VersionCompareTest`, `PluginListFormatTest`, `PluginStatusTest` e `PluginServerTest` em `pitiupi/test/pitiupi/plugins/remote/`: 20 testes novos, somando 74 com os 54 que já existiam.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Como funciona
|
||||||
|
|
||||||
|
### 4.1 Visão geral
|
||||||
|
|
||||||
|
```
|
||||||
|
Máquina A (servidor) Máquina B (cliente)
|
||||||
|
──────────────────── ───────────────────
|
||||||
|
PluginServer (porta 9090) RemotePluginsDialog
|
||||||
|
│ │
|
||||||
|
│ <──── GET /lista-de-plugins.txt ──────────┤ "Atualizar lista"
|
||||||
|
│ lê os .jar e .plugin.meta da pasta │
|
||||||
|
│ calcula o SHA-256, monta o texto │
|
||||||
|
├───────────── texto TSV ───────────────────>│ vira a tabela
|
||||||
|
│ │
|
||||||
|
│ <──── GET /chat.jar ──────────────────────┤ "Instalar" / "Atualizar"
|
||||||
|
├───────────── bytes do JAR ────────────────>│ baixa para cache/, confere o SHA-256
|
||||||
|
│ instala em plugins/
|
||||||
|
│ pede reinício
|
||||||
|
```
|
||||||
|
|
||||||
|
É HTTP puro, independente do UDP/TCP do chat. Por isso o servidor usa outra porta (padrão **9090**): o login do Pitiupi ocupa de 8000 a 9000.
|
||||||
|
|
||||||
|
### 4.2 Formato do `lista-de-plugins.txt`
|
||||||
|
|
||||||
|
Uma linha por plugin, sete colunas separadas por **TAB**. Linhas que começam com `#` são comentário.
|
||||||
|
|
||||||
|
```
|
||||||
|
# id nome versao autor descricao arquivo sha256
|
||||||
|
chat Chat 1.2.0 Fulano Chat de sala pitiupi.chat.jar 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
|
||||||
|
```
|
||||||
|
|
||||||
|
| Coluna | Regra |
|
||||||
|
| --- | --- |
|
||||||
|
| `id` | Letras, números, `.`, `_` e `-`. Serve para casar com o plugin instalado |
|
||||||
|
| `nome` | Texto exibido na tabela |
|
||||||
|
| `versao` | Números separados por ponto (`1.2.0`) |
|
||||||
|
| `autor`, `descricao` | Texto livre (pode ficar vazio) |
|
||||||
|
| `arquivo` | Nome do JAR: só letras, números, `.`, `_`, `-`, terminando em `.jar` (sem `/`, sem `..`) |
|
||||||
|
| `sha256` | Exatamente 64 caracteres hexadecimais |
|
||||||
|
|
||||||
|
Linhas que violam alguma regra são **descartadas**, e as demais continuam valendo. Se a tabela vier vazia, confira primeiro o hash da linha.
|
||||||
|
|
||||||
|
### 4.3 O servidor embutido
|
||||||
|
|
||||||
|
| Pedido | Resposta |
|
||||||
|
| --- | --- |
|
||||||
|
| `GET /lista-de-plugins.txt` | Lista gerada **a cada pedido**, a partir dos `.jar` da pasta de plugins |
|
||||||
|
| `GET /atualizacao-pitiupi.txt` | Uma linha descrevendo o Pitiupi em execução (só se estiver rodando de um JAR) |
|
||||||
|
| `GET /pitiupi.jar` | O JAR do Pitiupi em execução |
|
||||||
|
| `GET /<nome>.jar` | O JAR da pasta de plugins com esse nome, se existir |
|
||||||
|
| outro método (POST etc.) | 405 |
|
||||||
|
| qualquer outra coisa | 404 |
|
||||||
|
|
||||||
|
Detalhes:
|
||||||
|
|
||||||
|
- A **pasta compartilhada** é a pasta de plugins instalados (`PITIUPI_HOME/plugins`).
|
||||||
|
- Versão, autor e descrição vêm do arquivo `<jar>.plugin.meta`, que o Pitiupi grava quando o plugin carrega com sucesso. Um plugin que nunca foi carregado aparece com versão `0`.
|
||||||
|
- O `id` na lista é o `arquivoId` do `.plugin.meta` (por exemplo `chat`, tanto para `chat.jar` quanto para `pitiupi.chat.jar`).
|
||||||
|
- O servidor escuta na interface escolhida em *Configurações > Saída* (`LocalNetworkInfo.bestLocalInet4Address()`), e não em todas.
|
||||||
|
- **Proteção contra path traversal:** o nome pedido nunca vira caminho. Ele precisa casar com a expressão de nome seguro e, depois, o servidor **lista a pasta** e procura um arquivo com aquele nome exato. `/..%2Fconfig.properties` dá 404 (há teste automático para isso).
|
||||||
|
|
||||||
|
### 4.4 O cliente
|
||||||
|
|
||||||
|
- `normalize("192.168.0.10:9090")` vira `http://192.168.0.10:9090/` (acrescenta `http://` e a barra final).
|
||||||
|
- Timeouts: 5 s para conectar, 10 s para a lista, 60 s para o download.
|
||||||
|
- Limites: lista de até 256 KB, JAR de até 50 MB.
|
||||||
|
- O download grava num arquivo temporário em `cache/`, calcula o SHA-256 enquanto grava e, se o hash não bater com o da lista, **apaga o temporário** e recusa a instalação.
|
||||||
|
- Toda a rede roda em `SwingWorker`, então a janela não congela.
|
||||||
|
- O endereço do servidor fica salvo em `config.properties`, na chave `plugins.serverUrl`.
|
||||||
|
|
||||||
|
### 4.5 Instalação e atualização de plugin
|
||||||
|
|
||||||
|
1. O cliente baixa para `cache/` e confere o hash.
|
||||||
|
2. Se o plugin **já está instalado**, o novo JAR substitui o arquivo existente (por exemplo `chat.jar`), em vez de usar o nome do servidor (`pitiupi.chat.jar`). Isso evita ficar com dois JARs do mesmo plugin, que seria carregado duas vezes.
|
||||||
|
3. A troca usa `ATOMIC_MOVE`: o Pitiupi nunca enxerga um JAR pela metade.
|
||||||
|
4. O download **não altera** o `plugins.registry.json` versionado.
|
||||||
|
5. O plugin só passa a valer no próximo início. Por isso a tela mostra **reinício pendente** e oferece reiniciar.
|
||||||
|
|
||||||
|
Como a atualização é detectada: `PluginStatus` casa o `id` remoto com o `arquivoId`, o `identifier` ou o nome do arquivo (sem `.jar` e sem o prefixo `pitiupi.`) de cada JAR instalado. Os estados são:
|
||||||
|
|
||||||
|
| Texto na coluna *Situação* | Significado |
|
||||||
|
| --- | --- |
|
||||||
|
| `—` | Não instalado |
|
||||||
|
| `instalado (1.2.0)` | Instalado e igual ou mais novo que o do servidor |
|
||||||
|
| `atualização: 1.2.0 → 1.3.0` | O servidor tem versão maior |
|
||||||
|
| `versão desconhecida` | JAR instalado, mas sem `.plugin.meta` (nunca foi carregado) |
|
||||||
|
| `reinício pendente` | Baixado nesta sessão; aguardando reiniciar |
|
||||||
|
|
||||||
|
### 4.6 Atualização do próprio Pitiupi
|
||||||
|
|
||||||
|
1. `AppVersion.current()` lê o `Implementation-Version` do manifesto do JAR. Fora de um JAR (IDE), devolve `0.0.0-dev` e a atualização é desativada.
|
||||||
|
2. `SelfUpdater` busca `atualizacao-pitiupi.txt` no servidor cadastrado e compara a versão.
|
||||||
|
3. Se houver versão maior e o usuário confirmar:
|
||||||
|
1. baixa o novo JAR e confere o SHA-256;
|
||||||
|
2. confere que o `Main-Class` do JAR baixado é `pitiupi.Main`;
|
||||||
|
3. copia para `pitiupi.jar.new` (mesma pasta do JAR em execução);
|
||||||
|
4. guarda o JAR atual em `pitiupi.jar.bak`;
|
||||||
|
5. troca `pitiupi.jar.new` por `pitiupi.jar` com `ATOMIC_MOVE`;
|
||||||
|
6. reinicia pelo `ApplicationRestarter`.
|
||||||
|
|
||||||
|
**Por que `.new` e depois mover:** a JVM mantém o JAR aberto e lê classes dele sob demanda. Sobrescrever o conteúdo no lugar corromperia a leitura. No Linux, o `rename` troca o nome e deixa o arquivo antigo existindo enquanto estiver aberto.
|
||||||
|
|
||||||
|
### 4.7 Mudança no `pitiupi.sh`
|
||||||
|
|
||||||
|
Antes, cada `run`/`build`/`link` apagava todos os `.jar` de `.pitiupi/plugins/`, o que destruiria qualquer plugin baixado. Agora só apaga **links simbólicos** e recria os do `plugins.registry.json`. Arquivos comuns (os baixados) sobrevivem.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Como usar
|
||||||
|
|
||||||
|
### 5.1 Compilar e rodar
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/facul/2.26/alice/fls/pitiupi
|
||||||
|
./scripts/pitiupi.sh run --all
|
||||||
|
```
|
||||||
|
|
||||||
|
Só compilar o núcleo: `cd pitiupi && ant jar`. Testes: ver a seção 9.
|
||||||
|
|
||||||
|
### 5.2 Instalar um plugin de um servidor
|
||||||
|
|
||||||
|
1. **Plugins > Plugins online…**
|
||||||
|
2. Em *Servidor*, digite o endereço, por exemplo `192.168.0.10:9090` (o `http://` é opcional).
|
||||||
|
3. Clique em **Atualizar lista**. O endereço fica salvo para a próxima vez.
|
||||||
|
4. Selecione o plugin e clique em **Instalar** (ou **Atualizar**).
|
||||||
|
5. Confirme. O Pitiupi baixa, confere o hash e instala.
|
||||||
|
6. Aceite o reinício para o plugin passar a valer.
|
||||||
|
|
||||||
|
### 5.3 Compartilhar seus plugins
|
||||||
|
|
||||||
|
1. **Plugins > Compartilhar meus plugins…**
|
||||||
|
2. Deixe a porta em 9090 (ou escolha outra entre 1024 e 65535) e clique em **Iniciar**.
|
||||||
|
3. O campo mostra o endereço, por exemplo `192.168.0.10:9090`. Passe-o para quem quiser instalar.
|
||||||
|
4. **Parar** encerra o servidor (fechar o Pitiupi também encerra).
|
||||||
|
|
||||||
|
Se as outras máquinas não conectarem, libere a porta no firewall:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ufw allow 9090/tcp
|
||||||
|
```
|
||||||
|
|
||||||
|
Para conferir de outra máquina:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://192.168.0.10:9090/lista-de-plugins.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Dica:** o servidor lê versão e autor dos arquivos `.plugin.meta`, que só existem depois de o plugin ter carregado uma vez. Abra o Pitiupi com o plugin instalado antes de compartilhá-lo.
|
||||||
|
|
||||||
|
### 5.4 Publicar plugins num servidor web comum
|
||||||
|
|
||||||
|
Não é obrigatório usar o servidor embutido. Qualquer servidor web estático serve, desde que publique os JARs e a lista. Gerando a lista a partir de uma pasta com os JARs:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /caminho/da/pasta/publica
|
||||||
|
{
|
||||||
|
printf '# id\tnome\tversao\tautor\tdescricao\tarquivo\tsha256\n'
|
||||||
|
printf 'chat\tChat\t1.2.0\tAutor\tChat de sala\tpitiupi.chat.jar\t%s\n' \
|
||||||
|
"$(sha256sum pitiupi.chat.jar | cut -d' ' -f1)"
|
||||||
|
} > lista-de-plugins.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Repita a linha `printf` para cada plugin e **refaça a lista sempre que trocar um JAR** (o hash muda).
|
||||||
|
|
||||||
|
### 5.5 Atualizar o próprio Pitiupi
|
||||||
|
|
||||||
|
Quem publica a versão nova:
|
||||||
|
|
||||||
|
1. Suba o número em `pitiupi/manifest.mf` (`Implementation-Version: 1.1.0`).
|
||||||
|
2. Compile: `cd pitiupi && ant jar`.
|
||||||
|
3. Publique `pitiupi/dist/pitiupi.jar` e um `atualizacao-pitiupi.txt` com **uma linha**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
printf 'pitiupi\tPitiupi\t1.1.0\t\t\tpitiupi.jar\t%s\n' \
|
||||||
|
"$(sha256sum pitiupi.jar | cut -d' ' -f1)" > atualizacao-pitiupi.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Quem usa:
|
||||||
|
|
||||||
|
1. Rode o Pitiupi **pelo JAR** (`java -jar pitiupi.jar`) e cadastre o servidor em *Plugins online…*.
|
||||||
|
2. **Ajuda > Verificar atualização…**
|
||||||
|
3. Se houver versão nova, confirme. O programa baixa, troca o JAR e reinicia sozinho. O JAR anterior fica em `pitiupi.jar.bak`.
|
||||||
|
|
||||||
|
Se a versão nova não abrir, volte a anterior:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mv pitiupi.jar.bak pitiupi.jar
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Segurança
|
||||||
|
|
||||||
|
- **Integridade:** o SHA-256 garante que o arquivo baixado é o mesmo descrito na lista (nada corrompido nem cortado no meio).
|
||||||
|
- **Autenticidade, não:** o hash vem da **mesma lista, pelo mesmo HTTP puro**. Quem controla o servidor, ou a rede entre você e ele, pode trocar o JAR e o hash juntos. Para uma rede de laboratório isso é aceitável; para algo mais sério, a evolução natural é assinar os JARs (por exemplo com Ed25519, que o JDK já suporta) e embutir a chave pública no Pitiupi, ou usar HTTPS.
|
||||||
|
- **Plugin é código:** um plugin instalado roda com o mesmo poder do Pitiupi (não há sandbox). A tela pede confirmação e avisa disso, mas **só instale de quem você confia**.
|
||||||
|
- **Validação do que vem da rede:** nome de arquivo, id e hash passam por expressões restritivas na leitura da lista, e o `PluginStore` valida de novo o nome de destino (`.jar`, sem `..`, sem `/` nem `\`).
|
||||||
|
- **Servidor sem autenticação:** quem alcançar a porta pode listar e baixar todos os JARs da pasta de plugins. Compartilhe só em redes em que isso seja aceitável.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Vantagens
|
||||||
|
|
||||||
|
- **Sem dependências novas:** só classes do JDK (cliente e servidor HTTP, `MessageDigest`).
|
||||||
|
- **Sem infraestrutura obrigatória:** o próprio Pitiupi vira servidor de plugins, e qualquer servidor estático também funciona.
|
||||||
|
- **Formato simples:** a lista é um `.txt` em TSV, legível e editável à mão, sem biblioteca de JSON.
|
||||||
|
- **Resistente a arquivo ruim:** uma linha inválida não derruba a lista; um download corrompido é recusado e não deixa resíduo.
|
||||||
|
- **Instalação segura contra interrupção:** troca atômica, sem JAR pela metade.
|
||||||
|
- **Não polui o repositório:** downloads não alteram o `plugins.registry.json` versionado.
|
||||||
|
- **Sem plugin duplicado:** a atualização reaproveita o nome do JAR já instalado.
|
||||||
|
- **Reversível:** a atualização do Pitiupi mantém `pitiupi.jar.bak`.
|
||||||
|
- **Compatível com o que existia:** `getDescription()` não é abstrato, a assinatura antiga de `installFromFile` continua válida, e os 54 testes anteriores seguem passando.
|
||||||
|
- **Interface sem travar:** toda a rede roda fora da thread da janela.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Limitações
|
||||||
|
|
||||||
|
**Segurança**
|
||||||
|
- Sem assinatura de JAR e sem HTTPS por padrão (ver a seção 6).
|
||||||
|
- Servidor embutido sem autenticação.
|
||||||
|
|
||||||
|
**Funcionamento**
|
||||||
|
- **Reinício obrigatório:** plugins são carregados só na inicialização.
|
||||||
|
- **Um único servidor cadastrado:** há uma só chave `plugins.serverUrl`.
|
||||||
|
- **Plugins do `plugins.registry.json` não se mantêm atualizados:** o `pitiupi.sh run` recompila e religa esses plugins a cada execução, desfazendo uma atualização baixada. A atualização por HTTP vale para plugins **fora** do registro.
|
||||||
|
- **Auto-atualização do Pitiupi só funciona rodando pelo JAR** (`java -jar`). Rodando por `./scripts/pitiupi.sh run`, o script recompila `pitiupi/dist/pitiupi.jar` e sobrescreve a atualização. Rodando da IDE (pasta de classes), a opção é desativada.
|
||||||
|
- **Versão desconhecida até o primeiro carregamento:** um plugin sem `.plugin.meta` aparece como `versão desconhecida` (no cliente) ou com versão `0` (no servidor).
|
||||||
|
- **Comparação de versões simples:** só números separados por ponto. Sufixos como `-beta` são ignorados (`1.0.0-beta` conta como `1.0.0`).
|
||||||
|
- **Sem verificação automática ao abrir:** a checagem de atualização é manual.
|
||||||
|
- **O servidor recalcula o hash a cada pedido de lista:** irrelevante para poucos plugins; para muitos ou muito grandes, valeria guardar em cache.
|
||||||
|
- **Sem retomada de download** nem barra de progresso.
|
||||||
|
|
||||||
|
**Plataforma**
|
||||||
|
- **Windows não foi tratado:** o Windows trava arquivos abertos, então trocar um JAR já carregado (um plugin em uso ou o `pitiupi.jar`) pode falhar. A solução seria gravar como `.update` e aplicar na próxima subida, antes de carregar os plugins. O desenvolvimento e o uso previsto são em Linux.
|
||||||
|
- **Firewall:** para outras máquinas acessarem o servidor, a porta precisa estar liberada.
|
||||||
|
|
||||||
|
**Reinício**
|
||||||
|
- `ApplicationRestarter.restart()` usa `System.exit(0)` sem passar por `shutdownGracefully()`. Os outros usuários só te removem da lista no timeout de presença (cerca de 15 s).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Testes
|
||||||
|
|
||||||
|
Testes automáticos (JUnit 5, pelo Ant):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd pitiupi && ant test
|
||||||
|
```
|
||||||
|
|
||||||
|
Precisa do `junit-platform-console-standalone-1.10.2.jar` em `pitiupi/test/lib/` (o `README.md` dessa pasta diz onde baixar). Resultado atual: **74 testes, todos passando** (54 anteriores + 20 novos).
|
||||||
|
|
||||||
|
| Teste | O que cobre |
|
||||||
|
| --- | --- |
|
||||||
|
| `VersionCompareTest` | `1.10 > 1.9`, `1.0 = 1.0.0`, sufixos ignorados |
|
||||||
|
| `PluginListFormatTest` | gerar e ler devolve a mesma lista; linhas ruins descartadas; BOM; TAB dentro de campo; validação de nome de JAR |
|
||||||
|
| `PluginStatusTest` | casar instalado com remoto (por `arquivoId` e por nome); estados de atualização |
|
||||||
|
| `PluginServerTest` | lista só com JARs e metadados corretos; download com o mesmo conteúdo; hash errado recusado sem deixar resíduo; só JARs listados são servidos; `..%2F` dá 404; POST dá 405 |
|
||||||
|
|
||||||
|
**Não coberto por teste automático** (verificar à mão): as telas Swing e o fluxo de reinício, em especial a atualização do próprio Pitiupi.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Solução de problemas
|
||||||
|
|
||||||
|
| Sintoma | Causa provável | O que fazer |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| A tabela de *Plugins online* vem vazia | Hash da linha inválido ou colunas faltando (a linha é descartada) | `curl -s http://ENDERECO/lista-de-plugins.txt` e confira 7 colunas e hash de 64 caracteres |
|
||||||
|
| "O arquivo baixado não confere com o hash" | A lista está com hash de outro arquivo (JAR foi trocado e a lista não) | Refaça a lista com `sha256sum` do JAR atual |
|
||||||
|
| "Não foi possível acessar o servidor" | Endereço errado, servidor parado ou firewall | `curl -v http://ENDERECO/lista-de-plugins.txt`; `sudo ufw allow 9090/tcp` |
|
||||||
|
| Servidor não inicia | Porta ocupada | Escolha outra porta no diálogo |
|
||||||
|
| Situação "versão desconhecida" | O plugin nunca foi carregado, então não tem `.plugin.meta` | Reinicie o Pitiupi com o plugin instalado |
|
||||||
|
| Plugin voltou à versão antiga | O plugin está no `plugins.registry.json` e o `pitiupi.sh run` o religou | Atualize pelo registro, ou use plugins fora do registro |
|
||||||
|
| "A atualização automática só funciona quando o Pitiupi roda pelo JAR" | Está rodando da IDE ou pelo script | Rode com `java -jar pitiupi/dist/pitiupi.jar` |
|
||||||
|
| Dois JARs do mesmo plugin em `plugins/` | Instalação manual com nome diferente do instalado | Apague o extra com `rm` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Decisões de projeto
|
||||||
|
|
||||||
|
Sugestão de linhas para o `docs/decision-register.md`, na numeração seguinte à última existente:
|
||||||
|
|
||||||
|
| ID | Decisão | Motivação |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| D31 | Lista de plugins em TSV com SHA-256 | Formato simples e editável, sem biblioteca de JSON; o hash detecta arquivo corrompido |
|
||||||
|
| D32 | Servidor HTTP em porta própria (padrão 9090) | Fora da faixa 8000–9000 do login, que é usada por UDP e TCP |
|
||||||
|
| D33 | Servidor só serve nomes que existem na pasta | Elimina path traversal: o pedido nunca vira caminho de arquivo |
|
||||||
|
| D34 | Atualização reaproveita o nome do JAR instalado | Evita dois JARs do mesmo plugin sendo carregados |
|
||||||
|
| D35 | Downloads não alteram o `plugins.registry.json` | O registro é versionado; downloads são dado de execução |
|
||||||
|
| D36 | Auto-atualização por `.new` + `ATOMIC_MOVE` + `.bak` | A JVM mantém o JAR aberto; o rename atômico não corrompe a leitura e o backup permite voltar |
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
Manifest-Version: 1.0
|
Manifest-Version: 1.0
|
||||||
X-COMMENT: Main-Class will be added automatically by build
|
X-COMMENT: Main-Class will be added automatically by build
|
||||||
|
Implementation-Version: 1.0.0
|
||||||
|
|
||||||
@@ -7,7 +7,13 @@ public enum ErrorCode {
|
|||||||
PLUGIN_INSTALL_FAILED("Não foi possível instalar o plugin."),
|
PLUGIN_INSTALL_FAILED("Não foi possível instalar o plugin."),
|
||||||
PLUGIN_REMOVE_FAILED("Não foi possível remover o plugin."),
|
PLUGIN_REMOVE_FAILED("Não foi possível remover o plugin."),
|
||||||
PLUGIN_LOAD_FAILED("Falha ao carregar um plugin."),
|
PLUGIN_LOAD_FAILED("Falha ao carregar um plugin."),
|
||||||
INVALID_PATH("Caminho de arquivo inválido.");
|
INVALID_PATH("Caminho de arquivo inválido."),
|
||||||
|
PLUGIN_SERVER_UNREACHABLE("Não foi possível acessar o servidor de plugins."),
|
||||||
|
PLUGIN_LIST_INVALID("A lista de plugins do servidor está inválida."),
|
||||||
|
PLUGIN_DOWNLOAD_FAILED("Não foi possível baixar o plugin."),
|
||||||
|
PLUGIN_HASH_MISMATCH("O arquivo baixado não confere com o hash da lista. Instalação cancelada."),
|
||||||
|
PLUGIN_SERVER_START_FAILED("Não foi possível iniciar o servidor de plugins."),
|
||||||
|
UPDATE_FAILED("Não foi possível atualizar o Pitiupi.");
|
||||||
|
|
||||||
private final String userMessage;
|
private final String userMessage;
|
||||||
|
|
||||||
|
|||||||
@@ -37,6 +37,13 @@ public abstract class Plugin {
|
|||||||
|
|
||||||
public abstract String getAuthor();
|
public abstract String getAuthor();
|
||||||
public abstract String getVersion();
|
public abstract String getVersion();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Descrição curta exibida na lista de plugins online. Padrão: vazia.
|
||||||
|
*/
|
||||||
|
public String getDescription() {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
public abstract String getIdentifier();
|
public abstract String getIdentifier();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import java.io.IOException;
|
|||||||
import java.io.ObjectInput;
|
import java.io.ObjectInput;
|
||||||
import java.io.ObjectInputStream;
|
import java.io.ObjectInputStream;
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
|
import java.util.Arrays;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
@@ -163,35 +164,73 @@ public class SocketUDP extends Thread {
|
|||||||
* @throws ClassNotFoundException caso ocorra um erro ao verificar uma
|
* @throws ClassNotFoundException caso ocorra um erro ao verificar uma
|
||||||
* mensagem de heartbeat.
|
* mensagem de heartbeat.
|
||||||
*/
|
*/
|
||||||
public void receive() throws UnknownHostException, IOException, ClassNotFoundException {
|
public void receive() throws IOException {
|
||||||
byte[] buf = new byte[256000];
|
byte[] buffer = new byte[256000];
|
||||||
|
|
||||||
while (running) {
|
while (running) {
|
||||||
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
|
DatagramPacket packet = new DatagramPacket(
|
||||||
|
buffer,
|
||||||
|
buffer.length
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
multicastSocket.receive(msgPacket);
|
multicastSocket.receive(packet);
|
||||||
|
handlePacket(packet);
|
||||||
|
|
||||||
|
} catch (SocketException ex) {
|
||||||
|
if (!running) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.getLogger(SocketUDP.class.getName())
|
||||||
|
.log(Level.SEVERE, "Erro no socket UDP", ex);
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
if (!running) {
|
if (!running) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
throw ex;
|
|
||||||
|
Logger.getLogger(SocketUDP.class.getName())
|
||||||
|
.log(Level.SEVERE, "Erro ao receber datagrama UDP", ex);
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
} catch (RuntimeException ex) {
|
||||||
|
Logger.getLogger(SocketUDP.class.getName())
|
||||||
|
.log(Level.WARNING, "Falha ao processar datagrama UDP", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Object coreMessage = tryParseCoreUdpMessage(msgPacket.getData());
|
private void handlePacket(DatagramPacket packet) {
|
||||||
|
byte[] data = Arrays.copyOf(
|
||||||
|
packet.getData(),
|
||||||
|
packet.getLength()
|
||||||
|
);
|
||||||
|
|
||||||
|
Object coreMessage = tryParseCoreUdpMessage(data);
|
||||||
|
|
||||||
if (coreMessage instanceof HeartbeatMessage heartbeat) {
|
if (coreMessage instanceof HeartbeatMessage heartbeat) {
|
||||||
connectionManager.receiveHeartbeat(heartbeat, msgPacket.getAddress());
|
connectionManager.receiveHeartbeat(
|
||||||
continue;
|
heartbeat,
|
||||||
|
packet.getAddress()
|
||||||
|
);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (coreMessage instanceof GoodbyeMessage goodbye) {
|
if (coreMessage instanceof GoodbyeMessage goodbye) {
|
||||||
connectionManager.receiveGoodbye(goodbye);
|
connectionManager.receiveGoodbye(goodbye);
|
||||||
continue;
|
return;
|
||||||
}
|
|
||||||
if (coreMessage instanceof SessionInviteMessage invite) {
|
|
||||||
connectionManager.receiveSessionInvite(invite);
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pluginManager.handleMessage(msgPacket.getData());
|
if (coreMessage instanceof SessionInviteMessage invite) {
|
||||||
|
connectionManager.receiveSessionInvite(invite);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pluginManager.handleMessage(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -224,7 +263,7 @@ public class SocketUDP extends Thread {
|
|||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
this.receive();
|
this.receive();
|
||||||
} catch (IOException | ClassNotFoundException ex) {
|
} catch (IOException ex) {
|
||||||
Logger.getLogger(SocketUDP.class.getName()).log(Level.SEVERE, null, ex);
|
Logger.getLogger(SocketUDP.class.getName()).log(Level.SEVERE, null, ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package pitiupi.platform;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public final class AppVersion {
|
||||||
|
private AppVersion() { }
|
||||||
|
|
||||||
|
public static String current() {
|
||||||
|
String v = AppVersion.class.getPackage().getImplementationVersion();
|
||||||
|
return v != null ? v : "0.0.0-dev";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** O JAR em execução, ou vazio se estiver rodando de pasta de classes (IDE). */
|
||||||
|
public static Optional<Path> runningJar() {
|
||||||
|
try {
|
||||||
|
Path p = Path.of(AppVersion.class.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||||
|
return Files.isRegularFile(p) && p.toString().endsWith(".jar") ? Optional.of(p) : Optional.empty();
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -50,6 +50,15 @@ public final class ConfigLoader {
|
|||||||
store();
|
store();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getString(String key, String defaultValue) {
|
||||||
|
return properties.getProperty(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setString(String key, String value) throws IOException {
|
||||||
|
properties.setProperty(key, value);
|
||||||
|
store();
|
||||||
|
}
|
||||||
|
|
||||||
public boolean isMigrationCwdPluginsDone() {
|
public boolean isMigrationCwdPluginsDone() {
|
||||||
return getBoolean("migration.cwdPluginsDone", false);
|
return getBoolean("migration.cwdPluginsDone", false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
public final class PluginListFormat {
|
||||||
|
public static final String FILE_NAME = "lista-de-plugins.txt";
|
||||||
|
public static final String CORE_FILE_NAME = "atualizacao-pitiupi.txt";
|
||||||
|
private static final Pattern SAFE_JAR = Pattern.compile("[A-Za-z0-9._-]+\\.jar");
|
||||||
|
private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9._-]+");
|
||||||
|
private static final Pattern SHA256 = Pattern.compile("[0-9a-fA-F]{64}");
|
||||||
|
|
||||||
|
private PluginListFormat() { }
|
||||||
|
|
||||||
|
public static boolean isSafeJarName(String name) {
|
||||||
|
return name != null && SAFE_JAR.matcher(name).matches();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<RemotePluginEntry> parse(String text) {
|
||||||
|
List<RemotePluginEntry> out = new ArrayList<>();
|
||||||
|
if (text.startsWith("\uFEFF")) {
|
||||||
|
text = text.substring(1);
|
||||||
|
}
|
||||||
|
for (String raw : text.split("\\R")) {
|
||||||
|
if (raw.isBlank() || raw.stripLeading().startsWith("#")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String[] c = raw.split("\t", -1);
|
||||||
|
if (c.length < 7) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String id = c[0].trim(), file = c[5].trim(), sha = c[6].trim();
|
||||||
|
if (!SAFE_ID.matcher(id).matches() || !isSafeJarName(file)
|
||||||
|
|| !SHA256.matcher(sha).matches()) {
|
||||||
|
continue; // linha ruim não derruba a lista inteira
|
||||||
|
}
|
||||||
|
out.add(new RemotePluginEntry(id, c[1].trim(), c[2].trim(), c[3].trim(),
|
||||||
|
c[4].trim(), file, sha));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String format(List<RemotePluginEntry> entries) {
|
||||||
|
StringBuilder sb = new StringBuilder("# id\tnome\tversao\tautor\tdescricao\tarquivo\tsha256\n");
|
||||||
|
for (RemotePluginEntry e : entries) {
|
||||||
|
sb.append(String.join("\t", clean(e.id()), clean(e.name()), clean(e.version()),
|
||||||
|
clean(e.author()), clean(e.description()), e.file(), e.sha256())).append('\n');
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String clean(String s) {
|
||||||
|
return s == null ? "" : s.replaceAll("[\\t\\r\\n]+", " ").trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
import java.util.List;
|
||||||
|
import pitiupi.errors.ErrorCode;
|
||||||
|
import pitiupi.errors.PitiupiException;
|
||||||
|
|
||||||
|
public final class PluginRepositoryClient {
|
||||||
|
private static final long MAX_JAR_BYTES = 50L * 1024 * 1024;
|
||||||
|
private static final long MAX_LIST_BYTES = 256L * 1024;
|
||||||
|
|
||||||
|
private final HttpClient http = HttpClient.newBuilder()
|
||||||
|
.connectTimeout(Duration.ofSeconds(5))
|
||||||
|
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
/** "192.168.0.10:9090" vira "http://192.168.0.10:9090/". */
|
||||||
|
public static URI normalize(String input) {
|
||||||
|
String s = input == null ? "" : input.trim();
|
||||||
|
if (s.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Informe o endereço do servidor.");
|
||||||
|
}
|
||||||
|
if (!s.contains("://")) {
|
||||||
|
s = "http://" + s;
|
||||||
|
}
|
||||||
|
URI uri = URI.create(s);
|
||||||
|
String scheme = uri.getScheme();
|
||||||
|
if (!"http".equals(scheme) && !"https".equals(scheme) || uri.getHost() == null) {
|
||||||
|
throw new IllegalArgumentException("Endereço inválido: " + input);
|
||||||
|
}
|
||||||
|
return URI.create(s.endsWith("/") ? s : s + "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<RemotePluginEntry> fetchList(URI base, String listName) throws PitiupiException {
|
||||||
|
try {
|
||||||
|
HttpRequest req = HttpRequest.newBuilder(base.resolve(listName))
|
||||||
|
.timeout(Duration.ofSeconds(10)).GET().build();
|
||||||
|
HttpResponse<byte[]> res = http.send(req, HttpResponse.BodyHandlers.ofByteArray());
|
||||||
|
if (res.statusCode() != 200) {
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_UNREACHABLE, "HTTP " + res.statusCode());
|
||||||
|
}
|
||||||
|
if (res.body().length > MAX_LIST_BYTES) {
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_LIST_INVALID);
|
||||||
|
}
|
||||||
|
return PluginListFormat.parse(new String(res.body(), StandardCharsets.UTF_8));
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_UNREACHABLE, e);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_UNREACHABLE, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Baixa para um arquivo temporário em cacheDir, conferindo tamanho e SHA-256. */
|
||||||
|
public Path download(URI base, RemotePluginEntry entry, Path cacheDir) throws PitiupiException {
|
||||||
|
Path tmp = null;
|
||||||
|
try {
|
||||||
|
Files.createDirectories(cacheDir);
|
||||||
|
HttpRequest req = HttpRequest.newBuilder(base.resolve(entry.file()))
|
||||||
|
.timeout(Duration.ofSeconds(60)).GET().build();
|
||||||
|
HttpResponse<InputStream> res = http.send(req, HttpResponse.BodyHandlers.ofInputStream());
|
||||||
|
if (res.statusCode() != 200) {
|
||||||
|
res.body().close();
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, "HTTP " + res.statusCode());
|
||||||
|
}
|
||||||
|
tmp = Files.createTempFile(cacheDir, "dl-", ".part");
|
||||||
|
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||||
|
long total = 0;
|
||||||
|
try (InputStream in = res.body(); OutputStream out = Files.newOutputStream(tmp)) {
|
||||||
|
byte[] buf = new byte[8192];
|
||||||
|
int n;
|
||||||
|
while ((n = in.read(buf)) != -1) {
|
||||||
|
total += n;
|
||||||
|
if (total > MAX_JAR_BYTES) {
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, "Arquivo grande demais");
|
||||||
|
}
|
||||||
|
md.update(buf, 0, n);
|
||||||
|
out.write(buf, 0, n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!HexFormat.of().formatHex(md.digest()).equalsIgnoreCase(entry.sha256())) {
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_HASH_MISMATCH);
|
||||||
|
}
|
||||||
|
return tmp;
|
||||||
|
} catch (PitiupiException e) {
|
||||||
|
deleteQuietly(tmp);
|
||||||
|
throw e;
|
||||||
|
} catch (IOException | NoSuchAlgorithmException e) {
|
||||||
|
deleteQuietly(tmp);
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, e);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
deleteQuietly(tmp);
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void deleteQuietly(Path p) {
|
||||||
|
if (p != null) {
|
||||||
|
try { Files.deleteIfExists(p); } catch (IOException ignored) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
import com.sun.net.httpserver.HttpExchange;
|
||||||
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import pitiupi.errors.ErrorCode;
|
||||||
|
import pitiupi.errors.PitiupiException;
|
||||||
|
import pitiupi.platform.AppVersion;
|
||||||
|
import pitiupi.plugins.store.PluginMetadataWriter;
|
||||||
|
|
||||||
|
public final class PluginServer {
|
||||||
|
|
||||||
|
private final Path sharedDir;
|
||||||
|
private HttpServer server;
|
||||||
|
private ExecutorService pool;
|
||||||
|
|
||||||
|
public PluginServer(Path sharedDir) {
|
||||||
|
this.sharedDir = sharedDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void start(InetAddress bind, int port) throws PitiupiException {
|
||||||
|
if (server != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// bind == null -> todas as interfaces
|
||||||
|
server = HttpServer.create(new InetSocketAddress(bind, port), 0);
|
||||||
|
pool = Executors.newFixedThreadPool(4);
|
||||||
|
server.setExecutor(pool);
|
||||||
|
server.createContext("/", this::handle);
|
||||||
|
server.start();
|
||||||
|
} catch (IOException e) {
|
||||||
|
server = null;
|
||||||
|
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_START_FAILED, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void stop() {
|
||||||
|
if (server != null) {
|
||||||
|
server.stop(0);
|
||||||
|
pool.shutdownNow();
|
||||||
|
server = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized boolean isRunning() { return server != null; }
|
||||||
|
public synchronized int getPort() { return server.getAddress().getPort(); }
|
||||||
|
|
||||||
|
private void handle(HttpExchange ex) throws IOException {
|
||||||
|
try (ex) {
|
||||||
|
if (!"GET".equals(ex.getRequestMethod())) {
|
||||||
|
reply(ex, 405, "text/plain", new byte[0]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String path = ex.getRequestURI().getPath();
|
||||||
|
if (("/" + PluginListFormat.FILE_NAME).equals(path)) {
|
||||||
|
byte[] body = PluginListFormat.format(buildList()).getBytes(StandardCharsets.UTF_8);
|
||||||
|
reply(ex, 200, "text/plain; charset=utf-8", body);
|
||||||
|
} else if (("/" + PluginListFormat.CORE_FILE_NAME).equals(path)) {
|
||||||
|
reply(ex, 200, "text/plain; charset=utf-8", coreList().getBytes(StandardCharsets.UTF_8));
|
||||||
|
} else {
|
||||||
|
Path jar = "/pitiupi.jar".equals(path) ? AppVersion.runningJar().orElse(null)
|
||||||
|
: findShared(path.substring(1));
|
||||||
|
if (jar == null) {
|
||||||
|
reply(ex, 404, "text/plain", new byte[0]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ex.getResponseHeaders().set("Content-Type", "application/java-archive");
|
||||||
|
ex.sendResponseHeaders(200, Files.size(jar));
|
||||||
|
try (OutputStream out = ex.getResponseBody()) {
|
||||||
|
Files.copy(jar, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
// cliente caiu no meio ou erro de leitura: a conexão é fechada pelo try-with-resources
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Só serve arquivos que estão na pasta: o nome do pedido nunca vira caminho (sem path traversal). */
|
||||||
|
private Path findShared(String name) throws IOException {
|
||||||
|
if (!PluginListFormat.isSafeJarName(name)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try (Stream<Path> s = Files.list(sharedDir)) {
|
||||||
|
return s.filter(p -> p.getFileName().toString().equals(name))
|
||||||
|
.filter(Files::isRegularFile).findFirst().orElse(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<RemotePluginEntry> buildList() throws IOException {
|
||||||
|
List<RemotePluginEntry> out = new ArrayList<>();
|
||||||
|
try (Stream<Path> s = Files.list(sharedDir)) {
|
||||||
|
for (Path jar : s.filter(p -> PluginListFormat.isSafeJarName(p.getFileName().toString()))
|
||||||
|
.sorted().toList()) {
|
||||||
|
String file = jar.getFileName().toString();
|
||||||
|
String stem = file.substring(0, file.length() - 4);
|
||||||
|
Properties meta = readMeta(jar);
|
||||||
|
out.add(new RemotePluginEntry(
|
||||||
|
meta.getProperty("arquivoId", stem),
|
||||||
|
meta.getProperty("displayName", meta.getProperty("name", stem)),
|
||||||
|
meta.getProperty("version", "0"),
|
||||||
|
meta.getProperty("author", ""),
|
||||||
|
meta.getProperty("description", ""),
|
||||||
|
file,
|
||||||
|
Sha256.of(jar)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String coreList() throws IOException {
|
||||||
|
Optional<Path> jar = AppVersion.runningJar();
|
||||||
|
if (jar.isEmpty()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return PluginListFormat.format(List.of(new RemotePluginEntry(
|
||||||
|
"pitiupi", "Pitiupi", AppVersion.current(), "", "", "pitiupi.jar", Sha256.of(jar.get()))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Properties readMeta(Path jar) {
|
||||||
|
Properties p = new Properties();
|
||||||
|
Path meta = PluginMetadataWriter.metaPathFor(jar);
|
||||||
|
if (Files.isRegularFile(meta)) {
|
||||||
|
try (InputStream in = Files.newInputStream(meta)) {
|
||||||
|
p.load(in);
|
||||||
|
} catch (IOException ignored) { }
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void reply(HttpExchange ex, int code, String type, byte[] body) throws IOException {
|
||||||
|
ex.getResponseHeaders().set("Content-Type", type);
|
||||||
|
ex.sendResponseHeaders(code, body.length == 0 ? -1 : body.length);
|
||||||
|
if (body.length > 0) {
|
||||||
|
try (OutputStream out = ex.getResponseBody()) {
|
||||||
|
out.write(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import pitiupi.plugins.store.InstalledPluginRef;
|
||||||
|
|
||||||
|
|
||||||
|
public final class PluginStatus {
|
||||||
|
public enum State { NOT_INSTALLED, UP_TO_DATE, UPDATE_AVAILABLE, UNKNOWN_VERSION }
|
||||||
|
|
||||||
|
private PluginStatus() { }
|
||||||
|
|
||||||
|
/** Casa pelo id remoto contra arquivoId, identifier ou nome do arquivo (sem ".jar"/"pitiupi."). */
|
||||||
|
public static Optional<InstalledPluginRef> findInstalled(List<InstalledPluginRef> installed, String remoteId) {
|
||||||
|
for (InstalledPluginRef ref : installed) {
|
||||||
|
String stem = ref.getFileName().replaceFirst("\\.jar$", "").replaceFirst("^pitiupi\\.", "");
|
||||||
|
if (remoteId.equalsIgnoreCase(ref.getArquivoId().orElse(""))
|
||||||
|
|| remoteId.equalsIgnoreCase(ref.getIdentifier().orElse(""))
|
||||||
|
|| remoteId.equalsIgnoreCase(stem)) {
|
||||||
|
return Optional.of(ref);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static State of(RemotePluginEntry remote, Optional<InstalledPluginRef> installed) {
|
||||||
|
if (installed.isEmpty()) {
|
||||||
|
return State.NOT_INSTALLED;
|
||||||
|
}
|
||||||
|
Optional<String> v = installed.get().getVersion();
|
||||||
|
if (v.isEmpty()) {
|
||||||
|
return State.UNKNOWN_VERSION; // JAR nunca carregado: sem .plugin.meta ainda
|
||||||
|
}
|
||||||
|
return VersionCompare.compare(remote.version(), v.get()) > 0
|
||||||
|
? State.UPDATE_AVAILABLE : State.UP_TO_DATE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
public record RemotePluginEntry(String id, String name, String version, String author,
|
||||||
|
String description, String file, String sha256) { }
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
|
||||||
|
|
||||||
|
public final class Sha256 {
|
||||||
|
private Sha256() { }
|
||||||
|
|
||||||
|
public static String of(Path file) throws IOException {
|
||||||
|
try (InputStream in = Files.newInputStream(file)) {
|
||||||
|
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||||
|
byte[] buf = new byte[8192];
|
||||||
|
int n;
|
||||||
|
while ((n = in.read(buf)) != -1) {
|
||||||
|
md.update(buf, 0, n);
|
||||||
|
}
|
||||||
|
return HexFormat.of().formatHex(md.digest());
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
|
||||||
|
public final class VersionCompare {
|
||||||
|
private VersionCompare() { }
|
||||||
|
|
||||||
|
public static int compare(String a, String b) {
|
||||||
|
String[] x = a.trim().split("\\."), y = b.trim().split("\\.");
|
||||||
|
for (int i = 0; i < Math.max(x.length, y.length); i++) {
|
||||||
|
int cmp = Integer.compare(part(x, i), part(y, i));
|
||||||
|
if (cmp != 0) {
|
||||||
|
return cmp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int part(String[] p, int i) {
|
||||||
|
if (i >= p.length) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
String digits = p[i].replaceAll("^(\\d*).*$", "$1"); // "3-beta" -> "3"
|
||||||
|
return digits.isEmpty() ? 0 : Integer.parseInt(digits);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ public final class PluginMetadataWriter {
|
|||||||
props.setProperty("displayName", plugin.getDisplayName());
|
props.setProperty("displayName", plugin.getDisplayName());
|
||||||
props.setProperty("author", plugin.getAuthor());
|
props.setProperty("author", plugin.getAuthor());
|
||||||
props.setProperty("version", plugin.getVersion());
|
props.setProperty("version", plugin.getVersion());
|
||||||
|
props.setProperty("description", java.util.Objects.requireNonNullElse(plugin.getDescription(), ""));
|
||||||
String arquivoId = deriveArquivoId(jarPath, plugin);
|
String arquivoId = deriveArquivoId(jarPath, plugin);
|
||||||
props.setProperty("arquivoId", arquivoId);
|
props.setProperty("arquivoId", arquivoId);
|
||||||
|
|
||||||
@@ -29,7 +30,7 @@ public final class PluginMetadataWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static Path metaPathFor(Path jarPath) {
|
public static Path metaPathFor(Path jarPath) {
|
||||||
return Path.of(jarPath.toString() + ".plugin.meta");
|
return Path.of(jarPath.toString() + ".plugin.meta");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -55,27 +55,28 @@ public final class PluginStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Path installFromFile(Path sourceJar) throws PitiupiException, IOException {
|
public Path installFromFile(Path sourceJar) throws PitiupiException, IOException {
|
||||||
|
return installFromFile(sourceJar, null, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Path installFromFile(Path sourceJar, String targetName, boolean updateCatalog)
|
||||||
|
throws PitiupiException, IOException {
|
||||||
if (sourceJar == null || !Files.isRegularFile(sourceJar)) {
|
if (sourceJar == null || !Files.isRegularFile(sourceJar)) {
|
||||||
throw new PitiupiException(ErrorCode.INVALID_PATH);
|
throw new PitiupiException(ErrorCode.INVALID_PATH);
|
||||||
}
|
}
|
||||||
String fileName = sourceJar.getFileName().toString();
|
String fileName = targetName != null ? targetName : sourceJar.getFileName().toString();
|
||||||
if (!fileName.endsWith(".jar") || fileName.contains("..")) {
|
if (!fileName.endsWith(".jar") || fileName.contains("..")
|
||||||
|
|| fileName.contains("/") || fileName.contains("\\")) {
|
||||||
throw new PitiupiException(ErrorCode.INVALID_PATH);
|
throw new PitiupiException(ErrorCode.INVALID_PATH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Files.createDirectories(pluginsDir);
|
|
||||||
Files.createDirectories(cacheDir);
|
|
||||||
|
|
||||||
Path dest = pluginsDir.resolve(fileName).normalize();
|
|
||||||
if (!dest.startsWith(pluginsDir.normalize().toAbsolutePath())) {
|
|
||||||
throw new PitiupiException(ErrorCode.INVALID_PATH);
|
|
||||||
}
|
|
||||||
|
|
||||||
Path tmp = cacheDir.resolve(fileName + "." + UUID.randomUUID() + ".part");
|
Path tmp = cacheDir.resolve(fileName + "." + UUID.randomUUID() + ".part");
|
||||||
|
Path dest = pluginsDir.resolve(fileName);
|
||||||
try {
|
try {
|
||||||
Files.copy(sourceJar, tmp, StandardCopyOption.REPLACE_EXISTING);
|
Files.copy(sourceJar, tmp, StandardCopyOption.REPLACE_EXISTING);
|
||||||
Files.move(tmp, dest, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
Files.move(tmp, dest, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
if (updateCatalog) {
|
||||||
rememberInCatalog(sourceJar, fileName);
|
rememberInCatalog(sourceJar, fileName);
|
||||||
|
}
|
||||||
|
|
||||||
return dest;
|
return dest;
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ public final class ApplicationRestarter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static String locateRunningJar() {
|
private static String locateRunningJar() {
|
||||||
return pitiupi.Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
|
return pitiupi.platform.AppVersion.runningJar().map(java.nio.file.Path::toString).orElse(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -25,6 +25,8 @@ public final class MainShellFrame extends JFrame implements ShellHost {
|
|||||||
private final PluginGalleryPanel galleryPanel;
|
private final PluginGalleryPanel galleryPanel;
|
||||||
private final SettingsPanel settingsPanel;
|
private final SettingsPanel settingsPanel;
|
||||||
private final JLabel statusLabel = new JLabel(" ");
|
private final JLabel statusLabel = new JLabel(" ");
|
||||||
|
private final pitiupi.plugins.remote.PluginServer pluginServer =
|
||||||
|
new pitiupi.plugins.remote.PluginServer(pitiupi.platform.PitiupiHome.get().pluginsDirectory());
|
||||||
|
|
||||||
public MainShellFrame(String userName, int port) {
|
public MainShellFrame(String userName, int port) {
|
||||||
setTitle("Pitiupi");
|
setTitle("Pitiupi");
|
||||||
@@ -45,7 +47,7 @@ public final class MainShellFrame extends JFrame implements ShellHost {
|
|||||||
galleryPanel.setOpenHandler(this::openPluginTabFromGallery);
|
galleryPanel.setOpenHandler(this::openPluginTabFromGallery);
|
||||||
|
|
||||||
networkUsersPanel = new NetworkUsersPanel(connectionManager);
|
networkUsersPanel = new NetworkUsersPanel(connectionManager);
|
||||||
ShellMenuBar menuBar = new ShellMenuBar();
|
ShellMenuBar menuBar = new ShellMenuBar(this, pluginServer);
|
||||||
setJMenuBar(menuBar);
|
setJMenuBar(menuBar);
|
||||||
|
|
||||||
JPanel center = new JPanel(new BorderLayout());
|
JPanel center = new JPanel(new BorderLayout());
|
||||||
@@ -126,6 +128,7 @@ public final class MainShellFrame extends JFrame implements ShellHost {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void exit() {
|
public void exit() {
|
||||||
|
pluginServer.stop();
|
||||||
connectionManager.shutdownGracefully();
|
connectionManager.shutdownGracefully();
|
||||||
setVisible(false);
|
setVisible(false);
|
||||||
dispose();
|
dispose();
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package pitiupi.presentation.shell;
|
||||||
|
|
||||||
|
import javax.swing.JButton;
|
||||||
|
import javax.swing.JDialog;
|
||||||
|
import javax.swing.JLabel;
|
||||||
|
import javax.swing.JOptionPane;
|
||||||
|
import javax.swing.JPanel;
|
||||||
|
import javax.swing.JSpinner;
|
||||||
|
import javax.swing.JTextField;
|
||||||
|
import javax.swing.SpinnerNumberModel;
|
||||||
|
import javax.swing.border.EmptyBorder;
|
||||||
|
import java.awt.Frame;
|
||||||
|
import java.awt.GridLayout;
|
||||||
|
import pitiupi.errors.PitiupiException;
|
||||||
|
import pitiupi.plugins.remote.PluginServer;
|
||||||
|
import pitiupi.presentation.shell.ui.ShellUi;
|
||||||
|
|
||||||
|
public final class PluginServerDialog extends JDialog {
|
||||||
|
public PluginServerDialog(Frame owner, PluginServer server) {
|
||||||
|
super(owner, "Compartilhar meus plugins", true);
|
||||||
|
JSpinner port = new JSpinner(new SpinnerNumberModel(9090, 1024, 65535, 1));
|
||||||
|
JButton toggle = new JButton();
|
||||||
|
JTextField url = new JTextField(24);
|
||||||
|
url.setEditable(false);
|
||||||
|
|
||||||
|
Runnable sync = () -> {
|
||||||
|
boolean on = server.isRunning();
|
||||||
|
toggle.setText(on ? "Parar" : "Iniciar");
|
||||||
|
port.setEnabled(!on);
|
||||||
|
url.setText(on ? LocalNetworkInfo.bestLocalIpv4() + ":" + server.getPort() : "");
|
||||||
|
};
|
||||||
|
toggle.addActionListener(e -> {
|
||||||
|
try {
|
||||||
|
if (server.isRunning()) {
|
||||||
|
server.stop();
|
||||||
|
} else {
|
||||||
|
port.commitEdit();
|
||||||
|
server.start(LocalNetworkInfo.bestLocalInet4Address(), (Integer) port.getValue());
|
||||||
|
}
|
||||||
|
} catch (PitiupiException ex) {
|
||||||
|
JOptionPane.showMessageDialog(this, ex.getUserMessage()
|
||||||
|
+ (ex.getCause() != null ? "\n(" + ex.getCause().getMessage() + ")" : ""));
|
||||||
|
} catch (java.text.ParseException ignored) { }
|
||||||
|
sync.run();
|
||||||
|
});
|
||||||
|
|
||||||
|
JPanel p = new JPanel(new GridLayout(0, 2, 6, 6));
|
||||||
|
p.setBorder(new EmptyBorder(10, 10, 10, 10));
|
||||||
|
p.add(new JLabel("Porta HTTP:")); p.add(port);
|
||||||
|
p.add(new JLabel("Endereço p/ outros:")); p.add(url);
|
||||||
|
p.add(ShellUi.mutedLabel("Pasta compartilhada: plugins instalados."));
|
||||||
|
p.add(toggle);
|
||||||
|
add(p);
|
||||||
|
sync.run();
|
||||||
|
pack();
|
||||||
|
setLocationRelativeTo(owner);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
package pitiupi.presentation.shell;
|
||||||
|
|
||||||
|
import javax.swing.JButton;
|
||||||
|
import javax.swing.JComponent;
|
||||||
|
import javax.swing.JDialog;
|
||||||
|
import javax.swing.JLabel;
|
||||||
|
import javax.swing.JOptionPane;
|
||||||
|
import javax.swing.JPanel;
|
||||||
|
import javax.swing.JScrollPane;
|
||||||
|
import javax.swing.JTable;
|
||||||
|
import javax.swing.JTextField;
|
||||||
|
import javax.swing.SwingWorker;
|
||||||
|
import javax.swing.border.EmptyBorder;
|
||||||
|
import javax.swing.table.DefaultTableModel;
|
||||||
|
import java.awt.BorderLayout;
|
||||||
|
import java.awt.Dimension;
|
||||||
|
import java.awt.Frame;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
import pitiupi.errors.PitiupiException;
|
||||||
|
import pitiupi.platform.PitiupiHome;
|
||||||
|
import pitiupi.plugins.remote.PluginListFormat;
|
||||||
|
import pitiupi.plugins.remote.PluginRepositoryClient;
|
||||||
|
import pitiupi.plugins.remote.PluginStatus;
|
||||||
|
import pitiupi.plugins.remote.RemotePluginEntry;
|
||||||
|
import pitiupi.plugins.store.InstalledPluginRef;
|
||||||
|
import pitiupi.plugins.store.PluginStore;
|
||||||
|
import pitiupi.presentation.shell.ui.ShellUi;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plugins online: consulta um servidor, mostra a situação de cada plugin
|
||||||
|
* (não instalado, atualizado, atualização disponível) e instala ou atualiza.
|
||||||
|
*/
|
||||||
|
public final class RemotePluginsDialog extends JDialog {
|
||||||
|
|
||||||
|
private static final String CFG_URL = "plugins.serverUrl";
|
||||||
|
|
||||||
|
private final PluginRepositoryClient client = new PluginRepositoryClient();
|
||||||
|
private final PluginStore store = new PluginStore();
|
||||||
|
private final JTextField urlField = new JTextField(28);
|
||||||
|
private final DefaultTableModel model = new DefaultTableModel(
|
||||||
|
new String[]{"Nome", "Versão", "Autor", "Descrição", "Situação"}, 0) {
|
||||||
|
@Override public boolean isCellEditable(int r, int c) { return false; }
|
||||||
|
};
|
||||||
|
private final JTable table = new JTable(model);
|
||||||
|
private final JLabel status = ShellUi.mutedLabel(" ");
|
||||||
|
private final JButton installButton = new JButton("Instalar");
|
||||||
|
/** Plugins baixados nesta sessão: o .plugin.meta só é reescrito no próximo início. */
|
||||||
|
private final Set<String> pendingRestart = new HashSet<>();
|
||||||
|
private List<RemotePluginEntry> entries = List.of();
|
||||||
|
private URI currentBase;
|
||||||
|
|
||||||
|
public RemotePluginsDialog(Frame owner) {
|
||||||
|
super(owner, "Plugins online", true);
|
||||||
|
setLayout(new BorderLayout(8, 8));
|
||||||
|
((JComponent) getContentPane()).setBorder(new EmptyBorder(8, 8, 8, 8));
|
||||||
|
|
||||||
|
try {
|
||||||
|
urlField.setText(PitiupiHome.get().config().getString(CFG_URL, ""));
|
||||||
|
} catch (IOException ignored) { }
|
||||||
|
|
||||||
|
JButton refresh = new JButton("Atualizar lista");
|
||||||
|
refresh.addActionListener(e -> refresh());
|
||||||
|
JPanel top = new JPanel(new BorderLayout(6, 0));
|
||||||
|
top.add(new JLabel("Servidor:"), BorderLayout.WEST);
|
||||||
|
top.add(urlField, BorderLayout.CENTER);
|
||||||
|
top.add(refresh, BorderLayout.EAST);
|
||||||
|
add(top, BorderLayout.NORTH);
|
||||||
|
|
||||||
|
JScrollPane scroll = new JScrollPane(table);
|
||||||
|
ShellUi.borderlessScroll(scroll);
|
||||||
|
scroll.setPreferredSize(new Dimension(760, 260));
|
||||||
|
add(scroll, BorderLayout.CENTER);
|
||||||
|
|
||||||
|
installButton.addActionListener(e -> installSelected());
|
||||||
|
table.getSelectionModel().addListSelectionListener(ev -> {
|
||||||
|
if (!ev.getValueIsAdjusting()) {
|
||||||
|
updateInstallLabel();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
JPanel bottom = new JPanel(new BorderLayout());
|
||||||
|
bottom.add(status, BorderLayout.CENTER);
|
||||||
|
bottom.add(installButton, BorderLayout.EAST);
|
||||||
|
add(bottom, BorderLayout.SOUTH);
|
||||||
|
|
||||||
|
pack();
|
||||||
|
setLocationRelativeTo(owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void refresh() {
|
||||||
|
final URI base;
|
||||||
|
try {
|
||||||
|
base = PluginRepositoryClient.normalize(urlField.getText());
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
JOptionPane.showMessageDialog(this, ex.getMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
PitiupiHome.get().config().setString(CFG_URL, urlField.getText().trim());
|
||||||
|
} catch (IOException ignored) { }
|
||||||
|
status.setText("Consultando…");
|
||||||
|
new SwingWorker<List<RemotePluginEntry>, Void>() {
|
||||||
|
@Override protected List<RemotePluginEntry> doInBackground() throws Exception {
|
||||||
|
return client.fetchList(base, PluginListFormat.FILE_NAME);
|
||||||
|
}
|
||||||
|
@Override protected void done() {
|
||||||
|
try {
|
||||||
|
entries = get();
|
||||||
|
currentBase = base;
|
||||||
|
fill();
|
||||||
|
status.setText(entries.size() + " plugin(s) no servidor");
|
||||||
|
} catch (Exception ex) {
|
||||||
|
status.setText(" ");
|
||||||
|
showError(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lê a pasta de plugins; se falhar, trata como "nada instalado". */
|
||||||
|
private List<InstalledPluginRef> installedNow() {
|
||||||
|
try {
|
||||||
|
return store.listInstalled();
|
||||||
|
} catch (IOException ex) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fill() {
|
||||||
|
model.setRowCount(0);
|
||||||
|
List<InstalledPluginRef> installed = installedNow();
|
||||||
|
for (RemotePluginEntry e : entries) {
|
||||||
|
Optional<InstalledPluginRef> inst = PluginStatus.findInstalled(installed, e.id());
|
||||||
|
model.addRow(new Object[]{
|
||||||
|
e.name(), e.version(), e.author(), e.description(), situation(e, inst)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
updateInstallLabel();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String situation(RemotePluginEntry e, Optional<InstalledPluginRef> inst) {
|
||||||
|
if (pendingRestart.contains(e.id())) {
|
||||||
|
return "reinício pendente";
|
||||||
|
}
|
||||||
|
return switch (PluginStatus.of(e, inst)) {
|
||||||
|
case NOT_INSTALLED -> "—";
|
||||||
|
case UP_TO_DATE -> "instalado (" + inst.get().getVersion().orElse("?") + ")";
|
||||||
|
case UPDATE_AVAILABLE -> "atualização: " + inst.get().getVersion().orElse("?")
|
||||||
|
+ " → " + e.version();
|
||||||
|
case UNKNOWN_VERSION -> "versão desconhecida";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateInstallLabel() {
|
||||||
|
int row = table.getSelectedRow();
|
||||||
|
if (row < 0 || row >= entries.size()) {
|
||||||
|
installButton.setText("Instalar");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
RemotePluginEntry e = entries.get(table.convertRowIndexToModel(row));
|
||||||
|
Optional<InstalledPluginRef> inst = PluginStatus.findInstalled(installedNow(), e.id());
|
||||||
|
boolean update = !pendingRestart.contains(e.id())
|
||||||
|
&& PluginStatus.of(e, inst) == PluginStatus.State.UPDATE_AVAILABLE;
|
||||||
|
installButton.setText(update ? "Atualizar" : "Instalar");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void installSelected() {
|
||||||
|
int row = table.getSelectedRow();
|
||||||
|
if (row < 0 || currentBase == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
RemotePluginEntry e = entries.get(table.convertRowIndexToModel(row));
|
||||||
|
|
||||||
|
// Se o plugin já está instalado, o novo JAR substitui o arquivo existente
|
||||||
|
// (evita ter chat.jar e pitiupi.chat.jar ao mesmo tempo).
|
||||||
|
Optional<InstalledPluginRef> inst = PluginStatus.findInstalled(installedNow(), e.id());
|
||||||
|
final String targetName = inst.map(InstalledPluginRef::getFileName).orElse(e.file());
|
||||||
|
PluginStatus.State state = PluginStatus.of(e, inst);
|
||||||
|
|
||||||
|
String question;
|
||||||
|
if (pendingRestart.contains(e.id())) {
|
||||||
|
question = e.name() + " já foi baixado nesta sessão e aguarda reinício.\nBaixar de novo?";
|
||||||
|
} else if (state == PluginStatus.State.UP_TO_DATE) {
|
||||||
|
question = e.name() + " já está na versão " + inst.get().getVersion().orElse("?")
|
||||||
|
+ ".\nReinstalar mesmo assim?";
|
||||||
|
} else if (state == PluginStatus.State.UPDATE_AVAILABLE) {
|
||||||
|
question = "Atualizar " + e.name() + " de " + inst.get().getVersion().orElse("?")
|
||||||
|
+ " para " + e.version() + "?";
|
||||||
|
} else {
|
||||||
|
question = "Instalar " + e.name() + " " + e.version() + "?";
|
||||||
|
}
|
||||||
|
question += "\nServidor: " + currentBase
|
||||||
|
+ "\nUm plugin roda com o mesmo poder do programa. Só instale de quem você confia.";
|
||||||
|
|
||||||
|
int ok = JOptionPane.showConfirmDialog(this, question,
|
||||||
|
"Confirmar", JOptionPane.YES_NO_OPTION);
|
||||||
|
if (ok != JOptionPane.YES_OPTION) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final URI base = currentBase;
|
||||||
|
status.setText("Baixando " + e.file() + "…");
|
||||||
|
new SwingWorker<Void, Void>() {
|
||||||
|
@Override protected Void doInBackground() throws Exception {
|
||||||
|
Path tmp = client.download(base, e, PitiupiHome.get().cacheDirectory());
|
||||||
|
try {
|
||||||
|
store.installFromFile(tmp, targetName, false);
|
||||||
|
} finally {
|
||||||
|
Files.deleteIfExists(tmp);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
@Override protected void done() {
|
||||||
|
try {
|
||||||
|
get();
|
||||||
|
pendingRestart.add(e.id());
|
||||||
|
fill();
|
||||||
|
status.setText("Instalado: " + e.name());
|
||||||
|
ApplicationRestarter.promptRestartIfNeeded(RemotePluginsDialog.this);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
status.setText(" ");
|
||||||
|
showError(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void showError(Exception ex) {
|
||||||
|
Throwable t = ex instanceof ExecutionException && ex.getCause() != null
|
||||||
|
? ex.getCause() : ex;
|
||||||
|
String msg = "Erro: " + t.getMessage();
|
||||||
|
if (t instanceof PitiupiException pe) {
|
||||||
|
msg = pe.getUserMessage();
|
||||||
|
if (pe.getMessage() != null && !pe.getMessage().equals(msg)) {
|
||||||
|
msg += "\n(" + pe.getMessage() + ")";
|
||||||
|
}
|
||||||
|
if (pe.getCause() != null && pe.getCause().getMessage() != null) {
|
||||||
|
msg += "\n(" + pe.getCause().getMessage() + ")";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
JOptionPane.showMessageDialog(this, msg, "Plugins online", JOptionPane.WARNING_MESSAGE);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package pitiupi.presentation.shell;
|
||||||
|
|
||||||
|
import javax.swing.JOptionPane;
|
||||||
|
import javax.swing.SwingWorker;
|
||||||
|
import java.awt.Component;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
import java.util.jar.Manifest;
|
||||||
|
import pitiupi.errors.ErrorCode;
|
||||||
|
import pitiupi.errors.PitiupiException;
|
||||||
|
import pitiupi.platform.AppVersion;
|
||||||
|
import pitiupi.platform.PitiupiHome;
|
||||||
|
import pitiupi.plugins.remote.*;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public final class SelfUpdater {
|
||||||
|
private SelfUpdater() { }
|
||||||
|
|
||||||
|
public static void checkAndPrompt(Component parent) {
|
||||||
|
Optional<Path> jar = AppVersion.runningJar();
|
||||||
|
if (jar.isEmpty()) {
|
||||||
|
JOptionPane.showMessageDialog(parent,
|
||||||
|
"A atualização automática só funciona quando o Pitiupi roda pelo JAR (java -jar).");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final URI base;
|
||||||
|
try {
|
||||||
|
base = PluginRepositoryClient.normalize(
|
||||||
|
PitiupiHome.get().config().getString("plugins.serverUrl", ""));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
JOptionPane.showMessageDialog(parent,
|
||||||
|
"Cadastre o servidor em Plugins > Plugins online… antes de verificar.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
PluginRepositoryClient client = new PluginRepositoryClient();
|
||||||
|
new SwingWorker<Optional<RemotePluginEntry>, Void>() {
|
||||||
|
@Override protected Optional<RemotePluginEntry> doInBackground() throws Exception {
|
||||||
|
return client.fetchList(base, PluginListFormat.CORE_FILE_NAME).stream().findFirst();
|
||||||
|
}
|
||||||
|
@Override protected void done() {
|
||||||
|
try {
|
||||||
|
Optional<RemotePluginEntry> remote = get();
|
||||||
|
String current = AppVersion.current();
|
||||||
|
if (remote.isEmpty() || VersionCompare.compare(remote.get().version(), current) <= 0) {
|
||||||
|
JOptionPane.showMessageDialog(parent, "Você já está na versão mais recente (" + current + ").");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int ok = JOptionPane.showConfirmDialog(parent,
|
||||||
|
"Versão atual: " + current + "\nDisponível: " + remote.get().version()
|
||||||
|
+ "\nBaixar, substituir e reiniciar agora?",
|
||||||
|
"Atualização do Pitiupi", JOptionPane.YES_NO_OPTION);
|
||||||
|
if (ok == JOptionPane.YES_OPTION) {
|
||||||
|
apply(parent, client, base, remote.get(), jar.get());
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
JOptionPane.showMessageDialog(parent, "Não foi possível verificar: " + messageOf(ex));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void apply(Component parent, PluginRepositoryClient client, URI base,
|
||||||
|
RemotePluginEntry entry, Path jar) {
|
||||||
|
new SwingWorker<Void, Void>() {
|
||||||
|
@Override protected Void doInBackground() throws Exception {
|
||||||
|
Path tmp = client.download(base, entry, PitiupiHome.get().cacheDirectory());
|
||||||
|
try {
|
||||||
|
verifyIsPitiupi(tmp);
|
||||||
|
Path next = jar.resolveSibling(jar.getFileName() + ".new");
|
||||||
|
Files.copy(tmp, next, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
Files.copy(jar, jar.resolveSibling(jar.getFileName() + ".bak"),
|
||||||
|
StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
Files.move(next, jar, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
} finally {
|
||||||
|
Files.deleteIfExists(tmp);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
@Override protected void done() {
|
||||||
|
try {
|
||||||
|
get();
|
||||||
|
ApplicationRestarter.restart();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
JOptionPane.showMessageDialog(parent, "Falha ao atualizar: " + messageOf(ex)
|
||||||
|
+ "\nA versão antiga foi mantida (backup: " + jar.getFileName() + ".bak).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void verifyIsPitiupi(Path jar) throws Exception {
|
||||||
|
try (JarFile jf = new JarFile(jar.toFile())) {
|
||||||
|
Manifest m = jf.getManifest();
|
||||||
|
String main = m == null ? null : m.getMainAttributes().getValue("Main-Class");
|
||||||
|
if (!"pitiupi.Main".equals(main)) {
|
||||||
|
throw new PitiupiException(ErrorCode.UPDATE_FAILED, "O arquivo baixado não é um Pitiupi.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String messageOf(Exception ex) {
|
||||||
|
Throwable t = ex.getCause() != null ? ex.getCause() : ex;
|
||||||
|
return t instanceof PitiupiException pe ? pe.getUserMessage() : String.valueOf(t.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,15 +5,27 @@ import javax.swing.JMenuBar;
|
|||||||
import javax.swing.JMenuItem;
|
import javax.swing.JMenuItem;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Barra de menus mínima (apenas Ajuda).
|
* Barra de menus: Plugins (online) e Ajuda.
|
||||||
*/
|
*/
|
||||||
public final class ShellMenuBar extends JMenuBar {
|
public final class ShellMenuBar extends JMenuBar {
|
||||||
|
|
||||||
public ShellMenuBar() {
|
public ShellMenuBar(java.awt.Frame owner, pitiupi.plugins.remote.PluginServer server) {
|
||||||
|
JMenu plugins = new JMenu("Plugins");
|
||||||
|
JMenuItem online = new JMenuItem("Plugins online…");
|
||||||
|
online.addActionListener(e -> new RemotePluginsDialog(owner).setVisible(true));
|
||||||
|
plugins.add(online);
|
||||||
|
JMenuItem share = new JMenuItem("Compartilhar meus plugins…");
|
||||||
|
share.addActionListener(e -> new PluginServerDialog(owner, server).setVisible(true));
|
||||||
|
plugins.add(share);
|
||||||
|
add(plugins);
|
||||||
|
|
||||||
JMenu help = new JMenu("Ajuda");
|
JMenu help = new JMenu("Ajuda");
|
||||||
JMenuItem about = new JMenuItem("Sobre");
|
JMenuItem about = new JMenuItem("Sobre");
|
||||||
about.addActionListener(e -> new AboutDialog().setVisible(true));
|
about.addActionListener(e -> new AboutDialog().setVisible(true));
|
||||||
help.add(about);
|
help.add(about);
|
||||||
|
JMenuItem update = new JMenuItem("Verificar atualização…");
|
||||||
|
update.addActionListener(e -> SelfUpdater.checkAndPrompt(owner));
|
||||||
|
help.add(update);
|
||||||
add(help);
|
add(help);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class PluginListFormatTest {
|
||||||
|
|
||||||
|
private static final String HASH = "a".repeat(64);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void formatThenParseGivesTheSameList() {
|
||||||
|
List<RemotePluginEntry> list = List.of(
|
||||||
|
new RemotePluginEntry("chat", "Chat", "1.2.0", "Fulano", "Chat de sala", "chat.jar", HASH),
|
||||||
|
new RemotePluginEntry("ping", "Ping", "0.1", "", "", "pitiupi.ping.jar", HASH));
|
||||||
|
assertEquals(list, PluginListFormat.parse(PluginListFormat.format(list)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void badLinesAreDroppedButGoodOnesStay() {
|
||||||
|
String text = String.join("\n",
|
||||||
|
"# comentário",
|
||||||
|
"",
|
||||||
|
"bom\tBom\t1\ta\td\tbom.jar\t" + HASH,
|
||||||
|
"curto\tCurto\t1\ta\td\tcurto.jar", // menos de 7 colunas
|
||||||
|
"hashruim\tX\t1\ta\td\tx.jar\t1234", // hash curto
|
||||||
|
"fuga\tX\t1\ta\td\t../evil.jar\t" + HASH, // nome com ..
|
||||||
|
"barra\tX\t1\ta\td\tpasta/x.jar\t" + HASH, // nome com /
|
||||||
|
"naojar\tX\t1\ta\td\tx.txt\t" + HASH); // não termina em .jar
|
||||||
|
List<RemotePluginEntry> parsed = PluginListFormat.parse(text);
|
||||||
|
assertEquals(1, parsed.size());
|
||||||
|
assertEquals("bom", parsed.get(0).id());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void byteOrderMarkIsIgnored() {
|
||||||
|
List<RemotePluginEntry> parsed = PluginListFormat.parse(
|
||||||
|
"\uFEFFchat\tChat\t1\ta\td\tchat.jar\t" + HASH + "\n");
|
||||||
|
assertEquals(1, parsed.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void tabsInsideFieldsDoNotBreakColumns() {
|
||||||
|
List<RemotePluginEntry> list = List.of(
|
||||||
|
new RemotePluginEntry("chat", "Chat", "1", "a", "uma\tdescrição", "chat.jar", HASH));
|
||||||
|
List<RemotePluginEntry> back = PluginListFormat.parse(PluginListFormat.format(list));
|
||||||
|
assertEquals(1, back.size());
|
||||||
|
assertEquals("uma descrição", back.get(0).description());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void jarNameValidation() {
|
||||||
|
assertTrue(PluginListFormat.isSafeJarName("pitiupi.chat.jar"));
|
||||||
|
assertFalse(PluginListFormat.isSafeJarName("../x.jar"));
|
||||||
|
assertFalse(PluginListFormat.isSafeJarName("a/b.jar"));
|
||||||
|
assertFalse(PluginListFormat.isSafeJarName("x.txt"));
|
||||||
|
assertFalse(PluginListFormat.isSafeJarName(null));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import pitiupi.errors.ErrorCode;
|
||||||
|
import pitiupi.errors.PitiupiException;
|
||||||
|
import pitiupi.plugins.store.PluginMetadataWriter;
|
||||||
|
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class PluginServerTest {
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
Path temp;
|
||||||
|
|
||||||
|
private PluginServer server;
|
||||||
|
private URI base;
|
||||||
|
private Path chatJar;
|
||||||
|
private final PluginRepositoryClient client = new PluginRepositoryClient();
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws Exception {
|
||||||
|
Path shared = temp.resolve("shared");
|
||||||
|
Files.createDirectories(shared);
|
||||||
|
|
||||||
|
chatJar = shared.resolve("chat.jar");
|
||||||
|
Files.writeString(chatJar, "conteudo-do-jar");
|
||||||
|
Properties meta = new Properties();
|
||||||
|
meta.setProperty("arquivoId", "chat");
|
||||||
|
meta.setProperty("displayName", "Chat");
|
||||||
|
meta.setProperty("version", "1.2.0");
|
||||||
|
meta.setProperty("author", "Fulano");
|
||||||
|
meta.setProperty("description", "Chat de teste");
|
||||||
|
try (OutputStream out = Files.newOutputStream(PluginMetadataWriter.metaPathFor(chatJar))) {
|
||||||
|
meta.store(out, null);
|
||||||
|
}
|
||||||
|
Files.writeString(shared.resolve("extra.jar"), "outro"); // sem .plugin.meta
|
||||||
|
Files.writeString(shared.resolve("notas.txt"), "nao e jar"); // não deve aparecer
|
||||||
|
|
||||||
|
server = new PluginServer(shared);
|
||||||
|
server.start(InetAddress.getByAddress(new byte[]{127, 0, 0, 1}), 0);
|
||||||
|
base = URI.create("http://127.0.0.1:" + server.getPort() + "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
server.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
private int status(String path, String method) throws Exception {
|
||||||
|
HttpRequest req = HttpRequest.newBuilder(URI.create(base + path))
|
||||||
|
.method(method, HttpRequest.BodyPublishers.noBody()).build();
|
||||||
|
return HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.discarding()).statusCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listShowsOnlyJarsAndReadsMetadata() throws Exception {
|
||||||
|
List<RemotePluginEntry> list = client.fetchList(base, PluginListFormat.FILE_NAME);
|
||||||
|
assertEquals(2, list.size());
|
||||||
|
|
||||||
|
RemotePluginEntry chat = list.get(0);
|
||||||
|
assertEquals("chat", chat.id());
|
||||||
|
assertEquals("Chat", chat.name());
|
||||||
|
assertEquals("1.2.0", chat.version());
|
||||||
|
assertEquals("Fulano", chat.author());
|
||||||
|
assertEquals(Sha256.of(chatJar), chat.sha256());
|
||||||
|
|
||||||
|
RemotePluginEntry extra = list.get(1);
|
||||||
|
assertEquals("extra", extra.id());
|
||||||
|
assertEquals("0", extra.version());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void downloadDeliversTheSameBytes() throws Exception {
|
||||||
|
RemotePluginEntry chat = client.fetchList(base, PluginListFormat.FILE_NAME).get(0);
|
||||||
|
Path downloaded = client.download(base, chat, temp.resolve("cache"));
|
||||||
|
assertEquals("conteudo-do-jar", Files.readString(downloaded));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void wrongHashIsRejectedAndNothingIsLeftBehind() throws Exception {
|
||||||
|
RemotePluginEntry bad = new RemotePluginEntry(
|
||||||
|
"chat", "Chat", "1", "", "", "chat.jar", "0".repeat(64));
|
||||||
|
Path cache = temp.resolve("cache");
|
||||||
|
|
||||||
|
PitiupiException ex = assertThrows(PitiupiException.class, () -> client.download(base, bad, cache));
|
||||||
|
assertEquals(ErrorCode.PLUGIN_HASH_MISMATCH, ex.getCode());
|
||||||
|
try (Stream<Path> s = Files.list(cache)) {
|
||||||
|
assertEquals(0, s.count());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void onlyListedJarsAreServed() throws Exception {
|
||||||
|
assertEquals(200, status("chat.jar", "GET"));
|
||||||
|
assertEquals(404, status("nao-existe.jar", "GET"));
|
||||||
|
assertEquals(404, status("notas.txt", "GET"));
|
||||||
|
assertEquals(404, status("..%2Fconfig.properties", "GET"));
|
||||||
|
assertEquals(404, status("..%2F..%2Fetc%2Fpasswd", "GET"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void onlyGetIsAllowed() throws Exception {
|
||||||
|
assertEquals(405, status("chat.jar", "POST"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import pitiupi.plugins.store.InstalledPluginRef;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class PluginStatusTest {
|
||||||
|
|
||||||
|
private static RemotePluginEntry remote(String id, String version) {
|
||||||
|
return new RemotePluginEntry(id, id, version, "", "", id + ".jar", "a".repeat(64));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static InstalledPluginRef installed(String file, String arquivoId, String version) {
|
||||||
|
return new InstalledPluginRef(Path.of("/x/" + file), file,
|
||||||
|
Optional.ofNullable(arquivoId), Optional.ofNullable(version),
|
||||||
|
Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matchesByFileNameWithoutPrefix() {
|
||||||
|
List<InstalledPluginRef> list = List.of(installed("pitiupi.chat.jar", null, "1.0"));
|
||||||
|
assertTrue(PluginStatus.findInstalled(list, "chat").isPresent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matchesByArquivoId() {
|
||||||
|
List<InstalledPluginRef> list = List.of(installed("chat.jar", "chat", "1.0"));
|
||||||
|
assertTrue(PluginStatus.findInstalled(list, "chat").isPresent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void notInstalled() {
|
||||||
|
assertEquals(PluginStatus.State.NOT_INSTALLED,
|
||||||
|
PluginStatus.of(remote("chat", "1.0"), Optional.empty()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateAvailableWhenRemoteIsNewer() {
|
||||||
|
Optional<InstalledPluginRef> inst = Optional.of(installed("chat.jar", "chat", "1.9.0"));
|
||||||
|
assertEquals(PluginStatus.State.UPDATE_AVAILABLE, PluginStatus.of(remote("chat", "1.10.0"), inst));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void upToDateWhenSameOrOlder() {
|
||||||
|
Optional<InstalledPluginRef> inst = Optional.of(installed("chat.jar", "chat", "2.0"));
|
||||||
|
assertEquals(PluginStatus.State.UP_TO_DATE, PluginStatus.of(remote("chat", "2.0"), inst));
|
||||||
|
assertEquals(PluginStatus.State.UP_TO_DATE, PluginStatus.of(remote("chat", "1.0"), inst));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unknownVersionWhenThereIsNoMetadata() {
|
||||||
|
Optional<InstalledPluginRef> inst = Optional.of(installed("chat.jar", null, null));
|
||||||
|
assertEquals(PluginStatus.State.UNKNOWN_VERSION, PluginStatus.of(remote("chat", "1.0"), inst));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package pitiupi.plugins.remote;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class VersionCompareTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void comparesNumbersNotText() {
|
||||||
|
assertTrue(VersionCompare.compare("1.10.0", "1.9.0") > 0);
|
||||||
|
assertTrue(VersionCompare.compare("1.9.0", "1.10.0") < 0);
|
||||||
|
assertTrue(VersionCompare.compare("2.0", "1.99") > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void missingPartsCountAsZero() {
|
||||||
|
assertEquals(0, VersionCompare.compare("1.0", "1.0.0"));
|
||||||
|
assertTrue(VersionCompare.compare("1.0.1", "1.0") > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void equalVersionsAreEqual() {
|
||||||
|
assertEquals(0, VersionCompare.compare("3.2.1", "3.2.1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suffixIsIgnored() {
|
||||||
|
assertEquals(0, VersionCompare.compare("1.0.0-beta", "1.0.0"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,14 +20,6 @@
|
|||||||
"build": "ant",
|
"build": "ant",
|
||||||
"jar": "dist/pitiupi.ping.jar",
|
"jar": "dist/pitiupi.ping.jar",
|
||||||
"menuCategory": "Social"
|
"menuCategory": "Social"
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "damas",
|
|
||||||
"dir": "plugins/damas",
|
|
||||||
"build": "ant",
|
|
||||||
"jar": "dist/pitiupi.damas.jar",
|
|
||||||
"menuCategory": "Jogos"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
Generated
-10
@@ -1,10 +0,0 @@
|
|||||||
# Default ignored files
|
|
||||||
/shelf/
|
|
||||||
/workspace.xml
|
|
||||||
# Editor-based HTTP Client requests
|
|
||||||
/httpRequests/
|
|
||||||
# Ignored default folder with query files
|
|
||||||
/queries/
|
|
||||||
# Datasource local storage ignored files
|
|
||||||
/dataSources/
|
|
||||||
/dataSources.local.xml
|
|
||||||
-9
@@ -1,9 +0,0 @@
|
|||||||
<component name="libraryTable">
|
|
||||||
<library name="pitiupi.damas">
|
|
||||||
<CLASSES>
|
|
||||||
<root url="jar://$PROJECT_DIR$/dist/pitiupi.damas.jar!/" />
|
|
||||||
</CLASSES>
|
|
||||||
<JAVADOC />
|
|
||||||
<SOURCES />
|
|
||||||
</library>
|
|
||||||
</component>
|
|
||||||
Generated
-6
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="ProjectRootManager" version="2" project-jdk-name="openjdk-26" project-jdk-type="JavaSDK">
|
|
||||||
<output url="file://$PROJECT_DIR$/out" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
Generated
-8
@@ -1,8 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="ProjectModuleManager">
|
|
||||||
<modules>
|
|
||||||
<module fileurl="file://$PROJECT_DIR$/damas.iml" filepath="$PROJECT_DIR$/damas.iml" />
|
|
||||||
</modules>
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
Generated
-6
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="VcsDirectoryMappings">
|
|
||||||
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
# Plugin Damas
|
|
||||||
|
|
||||||
Jogo de damas para dois peers da mesma sala, com regras brasileiras. Não exige nenhuma mudança no núcleo.
|
|
||||||
|
|
||||||
## Como jogar
|
|
||||||
|
|
||||||
1. Abra **Damas** na aba **Plugins**, escolha um adversário e clique em **Convidar**. Outra opção é clicar no nome do peer na lista lateral e usar **Damas → Convidar para uma partida**.
|
|
||||||
2. O convidado vê o convite na aba do plugin, que abre sozinha, e clica em **Aceitar** ou **Recusar**. Os lados são sorteados.
|
|
||||||
3. Na sua vez, as peças que podem jogar ficam contornadas em verde. Clique na peça e depois em cada casa de pouso, uma por vez nas capturas em sequência. Para refazer a escolha no meio de uma sequência, clique em qualquer outra casa.
|
|
||||||
|
|
||||||
Fechar a aba não encerra a partida: ela continua em andamento e a barra de status avisa quando for a sua vez. Para voltar, abra **Damas** de novo.
|
|
||||||
|
|
||||||
Os dois peers precisam ter a **mesma versão do JAR** e usar a **mesma porta** no login, inclusive no mesmo computador. Com portas diferentes, as instâncias não se enxergam.
|
|
||||||
|
|
||||||
## Regras
|
|
||||||
|
|
||||||
- Tabuleiro 8×8, 12 peças para cada lado, e as brancas começam.
|
|
||||||
- Pedras andam uma casa para a frente e capturam para a frente e para trás.
|
|
||||||
- Damas são voadoras: andam e capturam a qualquer distância na diagonal.
|
|
||||||
- A captura é obrigatória, e a lei da maioria exige a sequência com mais peças. Em caso de igualdade, a escolha é livre.
|
|
||||||
- Peças capturadas só saem no fim da sequência e não podem ser saltadas duas vezes.
|
|
||||||
- Pedra que passa pela última linha no meio de uma captura só vira dama se terminar nela.
|
|
||||||
- Perde quem fica sem peças ou sem lances.
|
|
||||||
- Empate após 20 lances de cada lado só com damas, sem captura nem movimento de pedra.
|
|
||||||
|
|
||||||
## Protocolo
|
|
||||||
|
|
||||||
**Teoria:** UDP não garante entrega nem ordem. Para ter confiabilidade sobre ele, a aplicação precisa confirmar o recebimento (ACK), retransmitir o que não foi confirmado e ignorar duplicatas.
|
|
||||||
|
|
||||||
**No Pitiupi:** toda comunicação é uma única `DamasMessage`, enviada por UDP multicast com `to` indicando o destinatário. O multicast foi escolhido porque é o caminho do heartbeat: se o peer aparece na lista, o canal funciona. TCP e unicast usam a porta local como destino e não alcançam outra instância no mesmo computador.
|
|
||||||
|
|
||||||
| Tipo | Quando |
|
|
||||||
| --- | --- |
|
|
||||||
| `INVITE` | Convite, com o lado sorteado de quem convida |
|
|
||||||
| `ACCEPT`, `DECLINE`, `CANCEL` | Resposta ao convite ou cancelamento |
|
|
||||||
| `BUSY` | Resposta automática de quem já está em partida ou com convite aberto |
|
|
||||||
| `MOVE` | Caminho completo do lance |
|
|
||||||
| `RESIGN` | Desistência ou encerramento |
|
|
||||||
| `ACK` | Confirmação de `gameId` + `seq` |
|
|
||||||
|
|
||||||
`DamasController` reenvia a cada 500 ms o que não foi confirmado e processa cada mensagem uma única vez. O convite é abandonado após 10 s sem ACK. O lance da partida em curso é reenviado até ser confirmado, porque o adversário pode voltar à rede. Cada peer valida o lance recebido com o próprio `DamasGame`.
|
|
||||||
|
|
||||||
**Limitação:** não há criptografia nem autenticação, e qualquer peer da sala pode ler as mensagens. As partidas não são salvas em disco e não existe proposta de empate. A regra oficial de empate em finais como duas damas contra uma não foi implementada.
|
|
||||||
|
|
||||||
## Build e testes
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd plugins/damas
|
|
||||||
ant jar # requer pitiupi/dist/pitiupi.jar
|
|
||||||
ant test # requer o JUnit em pitiupi/test/lib (ver README da pasta)
|
|
||||||
```
|
|
||||||
|
|
||||||
| Pacote | Conteúdo |
|
|
||||||
| --- | --- |
|
|
||||||
| `game` | Regras, sem rede nem Swing |
|
|
||||||
| `net` | `DamasMessage` |
|
|
||||||
| `control` | Sessão, convites e entrega confiável |
|
|
||||||
| `GUI` | Tabuleiro e painel |
|
|
||||||
| `plugin` | Integração com o núcleo (`DamasPlugin`) |
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project name="pitiupi.damas" default="default" basedir=".">
|
|
||||||
<description>Builds, tests, and runs the project pitiupi.damas.</description>
|
|
||||||
<import file="nbproject/build-impl.xml"/>
|
|
||||||
|
|
||||||
<property name="junit.standalone" location="../../pitiupi/test/lib/junit-platform-console-standalone-1.10.2.jar"/>
|
|
||||||
|
|
||||||
<target name="test" depends="jar" description="JUnit 5 (console launcher)">
|
|
||||||
<mkdir dir="${build.test.classes.dir}"/>
|
|
||||||
<javac srcdir="test"
|
|
||||||
destdir="${build.test.classes.dir}"
|
|
||||||
classpath="${run.classpath}:${junit.standalone}"
|
|
||||||
includeantruntime="false"
|
|
||||||
source="17"
|
|
||||||
target="17"
|
|
||||||
encoding="UTF-8"/>
|
|
||||||
<java classname="org.junit.platform.console.ConsoleLauncher" fork="true" failonerror="true">
|
|
||||||
<classpath>
|
|
||||||
<pathelement path="${build.test.classes.dir}"/>
|
|
||||||
<pathelement path="${run.classpath}"/>
|
|
||||||
<pathelement location="${junit.standalone}"/>
|
|
||||||
</classpath>
|
|
||||||
<arg value="--scan-classpath"/>
|
|
||||||
<arg value="${build.test.classes.dir}"/>
|
|
||||||
</java>
|
|
||||||
</target>
|
|
||||||
</project>
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
#Wed, 04 Nov 2026 10:51:29 -0300
|
|
||||||
|
|
||||||
|
|
||||||
C\:\\Users\\Gustavo\\OneDrive\\Documentos\\Faculdade\\2026_2\\Monitoria\\dama\\pitiupi\\plugins\\damas=
|
|
||||||
|
|
||||||
C\:\\Users\\Gustavo\\OneDrive\\Documentos\\Faculdade\\2026_2\\Monitoria\\dama\\pitiupi\\pitiupi=
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
pitiupi.damas.plugin.DamasPlugin
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,22 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<module type="JAVA_MODULE" version="4">
|
|
||||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
|
||||||
<exclude-output />
|
|
||||||
<content url="file://$MODULE_DIR$">
|
|
||||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
|
||||||
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
|
|
||||||
</content>
|
|
||||||
<orderEntry type="inheritedJdk" />
|
|
||||||
<orderEntry type="module-library">
|
|
||||||
<library>
|
|
||||||
<CLASSES>
|
|
||||||
<root url="jar://$MODULE_DIR$/../../pitiupi/dist/pitiupi.jar!/" />
|
|
||||||
</CLASSES>
|
|
||||||
<JAVADOC />
|
|
||||||
<SOURCES />
|
|
||||||
</library>
|
|
||||||
</orderEntry>
|
|
||||||
<orderEntry type="sourceFolder" forTests="false" />
|
|
||||||
<orderEntry type="library" name="pitiupi.damas" level="project" />
|
|
||||||
</component>
|
|
||||||
</module>
|
|
||||||
Vendored
BIN
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -1,8 +0,0 @@
|
|||||||
build.xml.data.CRC32=3f66efc2
|
|
||||||
build.xml.script.CRC32=3953f1a4
|
|
||||||
build.xml.stylesheet.CRC32=f85dc8f2@1.119.0.48
|
|
||||||
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
|
|
||||||
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
|
|
||||||
nbproject/build-impl.xml.data.CRC32=3f66efc2
|
|
||||||
nbproject/build-impl.xml.script.CRC32=a4594806
|
|
||||||
nbproject/build-impl.xml.stylesheet.CRC32=12e0a6c2@1.119.0.48
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
annotation.processing.enabled=true
|
|
||||||
annotation.processing.enabled.in.editor=false
|
|
||||||
annotation.processing.processors.list=
|
|
||||||
annotation.processing.run.all.processors=true
|
|
||||||
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
|
|
||||||
application.title=pitiupi.damas
|
|
||||||
application.vendor=pitiupi
|
|
||||||
build.classes.dir=${build.dir}/classes
|
|
||||||
build.classes.excludes=**/*.java,**/*.form
|
|
||||||
# This directory is removed when the project is cleaned:
|
|
||||||
build.dir=build
|
|
||||||
build.generated.dir=${build.dir}/generated
|
|
||||||
build.generated.sources.dir=${build.dir}/generated-sources
|
|
||||||
# Only compile against the classpath explicitly listed here:
|
|
||||||
build.sysclasspath=ignore
|
|
||||||
build.test.classes.dir=${build.dir}/test/classes
|
|
||||||
build.test.results.dir=${build.dir}/test/results
|
|
||||||
# Uncomment to specify the preferred debugger connection transport:
|
|
||||||
#debug.transport=dt_socket
|
|
||||||
debug.classpath=\
|
|
||||||
${run.classpath}
|
|
||||||
debug.modulepath=\
|
|
||||||
${run.modulepath}
|
|
||||||
debug.test.classpath=\
|
|
||||||
${run.test.classpath}
|
|
||||||
debug.test.modulepath=\
|
|
||||||
${run.test.modulepath}
|
|
||||||
# Files in build.classes.dir which should be excluded from distribution jar
|
|
||||||
dist.archive.excludes=
|
|
||||||
# This directory is removed when the project is cleaned:
|
|
||||||
dist.dir=dist
|
|
||||||
dist.jar=${dist.dir}/pitiupi.damas.jar
|
|
||||||
dist.javadoc.dir=${dist.dir}/javadoc
|
|
||||||
dist.jlink.dir=${dist.dir}/jlink
|
|
||||||
dist.jlink.output=${dist.jlink.dir}/pitiupi.damas
|
|
||||||
endorsed.classpath=
|
|
||||||
excludes=
|
|
||||||
includes=**
|
|
||||||
jar.compress=false
|
|
||||||
javac.classpath=\
|
|
||||||
${reference.pitiupi.jar}
|
|
||||||
# Space-separated list of extra javac options
|
|
||||||
javac.compilerargs=
|
|
||||||
javac.deprecation=false
|
|
||||||
javac.external.vm=true
|
|
||||||
javac.modulepath=
|
|
||||||
javac.processormodulepath=
|
|
||||||
javac.processorpath=\
|
|
||||||
${javac.classpath}
|
|
||||||
javac.source=17
|
|
||||||
javac.target=17
|
|
||||||
javac.test.classpath=\
|
|
||||||
${javac.classpath}:\
|
|
||||||
${build.classes.dir}
|
|
||||||
javac.test.modulepath=\
|
|
||||||
${javac.modulepath}
|
|
||||||
javac.test.processorpath=\
|
|
||||||
${javac.test.classpath}
|
|
||||||
javadoc.additionalparam=
|
|
||||||
javadoc.author=false
|
|
||||||
javadoc.encoding=${source.encoding}
|
|
||||||
javadoc.html5=false
|
|
||||||
javadoc.noindex=false
|
|
||||||
javadoc.nonavbar=false
|
|
||||||
javadoc.notree=false
|
|
||||||
javadoc.private=false
|
|
||||||
javadoc.splitindex=true
|
|
||||||
javadoc.use=true
|
|
||||||
javadoc.version=false
|
|
||||||
javadoc.windowtitle=
|
|
||||||
# The jlink additional root modules to resolve
|
|
||||||
jlink.additionalmodules=
|
|
||||||
# The jlink additional command line parameters
|
|
||||||
jlink.additionalparam=
|
|
||||||
jlink.launcher=true
|
|
||||||
jlink.launcher.name=pitiupi.damas
|
|
||||||
meta.inf.dir=${src.dir}/META-INF
|
|
||||||
mkdist.disabled=true
|
|
||||||
platform.active=default_platform
|
|
||||||
project.pitiupi=../../pitiupi
|
|
||||||
reference.pitiupi.jar=${project.pitiupi}/dist/pitiupi.jar
|
|
||||||
run.classpath=\
|
|
||||||
${javac.classpath}:\
|
|
||||||
${build.classes.dir}
|
|
||||||
# Space-separated list of JVM arguments used when running the project.
|
|
||||||
# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value.
|
|
||||||
# To set system properties for unit tests define test-sys-prop.name=value:
|
|
||||||
run.jvmargs=
|
|
||||||
run.modulepath=\
|
|
||||||
${javac.modulepath}
|
|
||||||
run.test.classpath=\
|
|
||||||
${javac.test.classpath}:\
|
|
||||||
${build.test.classes.dir}
|
|
||||||
run.test.modulepath=\
|
|
||||||
${javac.test.modulepath}
|
|
||||||
source.encoding=UTF-8
|
|
||||||
src.dir=src
|
|
||||||
test.src.dir=test
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://www.netbeans.org/ns/project/1">
|
|
||||||
<type>org.netbeans.modules.java.j2seproject</type>
|
|
||||||
<configuration>
|
|
||||||
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
|
|
||||||
<name>pitiupi.damas</name>
|
|
||||||
<source-roots>
|
|
||||||
<root id="src.dir"/>
|
|
||||||
</source-roots>
|
|
||||||
<test-roots>
|
|
||||||
<root id="test.src.dir"/>
|
|
||||||
</test-roots>
|
|
||||||
</data>
|
|
||||||
<references xmlns="http://www.netbeans.org/ns/ant-project-references/1">
|
|
||||||
<reference>
|
|
||||||
<foreign-project>pitiupi</foreign-project>
|
|
||||||
<artifact-type>jar</artifact-type>
|
|
||||||
<script>build.xml</script>
|
|
||||||
<target>jar</target>
|
|
||||||
<clean-target>clean</clean-target>
|
|
||||||
<id>jar</id>
|
|
||||||
</reference>
|
|
||||||
</references>
|
|
||||||
</configuration>
|
|
||||||
</project>
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
pitiupi.damas.plugin.DamasPlugin
|
|
||||||
@@ -1,252 +0,0 @@
|
|||||||
package pitiupi.damas.GUI;
|
|
||||||
|
|
||||||
import pitiupi.damas.game.DamasGame;
|
|
||||||
import pitiupi.damas.game.Move;
|
|
||||||
import pitiupi.damas.game.Piece;
|
|
||||||
import pitiupi.damas.game.Side;
|
|
||||||
|
|
||||||
import javax.swing.JComponent;
|
|
||||||
import java.awt.BasicStroke;
|
|
||||||
import java.awt.Color;
|
|
||||||
import java.awt.Cursor;
|
|
||||||
import java.awt.Dimension;
|
|
||||||
import java.awt.Graphics;
|
|
||||||
import java.awt.Graphics2D;
|
|
||||||
import java.awt.RenderingHints;
|
|
||||||
import java.awt.event.MouseAdapter;
|
|
||||||
import java.awt.event.MouseEvent;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tabuleiro desenhado em Swing. O lance é montado clique a clique (origem e cada pouso) e só é
|
|
||||||
* entregue a {@code onMove} quando o caminho formar um lance legal completo.
|
|
||||||
*/
|
|
||||||
final class BoardView extends JComponent {
|
|
||||||
|
|
||||||
private static final Color LIGHT_SQUARE = new Color(238, 217, 181);
|
|
||||||
private static final Color DARK_SQUARE = new Color(148, 98, 64);
|
|
||||||
private static final Color LAST_MOVE = new Color(186, 162, 72);
|
|
||||||
private static final Color MOVABLE = new Color(90, 200, 120);
|
|
||||||
private static final Color SELECTED = new Color(250, 210, 60);
|
|
||||||
private static final Color WHITE_PIECE = new Color(245, 240, 228);
|
|
||||||
private static final Color BLACK_PIECE = new Color(44, 40, 38);
|
|
||||||
private static final Color CROWN = new Color(214, 160, 40);
|
|
||||||
|
|
||||||
private final Consumer<List<Integer>> onMove;
|
|
||||||
private final List<Integer> partialPath = new ArrayList<>();
|
|
||||||
private DamasGame game;
|
|
||||||
private Side viewSide = Side.WHITE;
|
|
||||||
private boolean interactive;
|
|
||||||
|
|
||||||
BoardView(Consumer<List<Integer>> onMove) {
|
|
||||||
this.onMove = onMove;
|
|
||||||
setPreferredSize(new Dimension(520, 520));
|
|
||||||
addMouseListener(new MouseAdapter() {
|
|
||||||
@Override
|
|
||||||
public void mousePressed(MouseEvent e) {
|
|
||||||
int square = squareAt(e.getX(), e.getY());
|
|
||||||
if (interactive && square >= 0) {
|
|
||||||
onSquareClicked(square);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void setState(DamasGame game, Side viewSide, boolean interactive) {
|
|
||||||
this.game = game;
|
|
||||||
this.viewSide = viewSide != null ? viewSide : Side.WHITE;
|
|
||||||
this.interactive = interactive && game != null;
|
|
||||||
partialPath.clear();
|
|
||||||
setCursor(Cursor.getPredefinedCursor(this.interactive ? Cursor.HAND_CURSOR : Cursor.DEFAULT_CURSOR));
|
|
||||||
repaint();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onSquareClicked(int square) {
|
|
||||||
for (Move move : candidates()) {
|
|
||||||
if (!partialPath.isEmpty() && move.path().get(partialPath.size()) == square) {
|
|
||||||
partialPath.add(square);
|
|
||||||
if (move.path().size() == partialPath.size()) {
|
|
||||||
List<Integer> complete = List.copyOf(partialPath);
|
|
||||||
partialPath.clear();
|
|
||||||
onMove.accept(complete);
|
|
||||||
}
|
|
||||||
repaint();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
partialPath.clear();
|
|
||||||
if (isMovable(square)) {
|
|
||||||
partialPath.add(square);
|
|
||||||
}
|
|
||||||
repaint();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Lances legais que continuam o caminho já clicado. */
|
|
||||||
private List<Move> candidates() {
|
|
||||||
List<Move> matching = new ArrayList<>();
|
|
||||||
for (Move move : game.getLegalMoves()) {
|
|
||||||
if (move.path().size() > partialPath.size()
|
|
||||||
&& move.path().subList(0, partialPath.size()).equals(partialPath)) {
|
|
||||||
matching.add(move);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return matching;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isMovable(int square) {
|
|
||||||
return game.getLegalMoves().stream().anyMatch(move -> move.from() == square);
|
|
||||||
}
|
|
||||||
|
|
||||||
private int boardSize() {
|
|
||||||
return Math.min(getWidth(), getHeight());
|
|
||||||
}
|
|
||||||
|
|
||||||
private int cellSize() {
|
|
||||||
return boardSize() / DamasGame.SIZE;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int originX() {
|
|
||||||
return (getWidth() - cellSize() * DamasGame.SIZE) / 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int originY() {
|
|
||||||
return (getHeight() - cellSize() * DamasGame.SIZE) / 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Linha na tela: quem joga de pretas vê o tabuleiro girado 180°. */
|
|
||||||
private int toView(int index) {
|
|
||||||
return viewSide == Side.WHITE ? index : DamasGame.SIZE - 1 - index;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int squareAt(int x, int y) {
|
|
||||||
int cell = cellSize();
|
|
||||||
if (cell == 0) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
int viewCol = Math.floorDiv(x - originX(), cell);
|
|
||||||
int viewRow = Math.floorDiv(y - originY(), cell);
|
|
||||||
if (viewCol < 0 || viewRow < 0 || viewCol >= DamasGame.SIZE || viewRow >= DamasGame.SIZE) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
return DamasGame.square(toView(viewRow), toView(viewCol));
|
|
||||||
}
|
|
||||||
|
|
||||||
private int cellX(int square) {
|
|
||||||
return originX() + toView(DamasGame.colOf(square)) * cellSize();
|
|
||||||
}
|
|
||||||
|
|
||||||
private int cellY(int square) {
|
|
||||||
return originY() + toView(DamasGame.rowOf(square)) * cellSize();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void paintComponent(Graphics graphics) {
|
|
||||||
Graphics2D g = (Graphics2D) graphics.create();
|
|
||||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
|
||||||
paintSquares(g);
|
|
||||||
if (game != null) {
|
|
||||||
paintPieces(g);
|
|
||||||
if (interactive) {
|
|
||||||
paintHints(g);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
g.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void paintSquares(Graphics2D g) {
|
|
||||||
Move lastMove = game != null ? game.getLastMove() : null;
|
|
||||||
int cell = cellSize();
|
|
||||||
for (int square = 0; square < DamasGame.SIZE * DamasGame.SIZE; square++) {
|
|
||||||
boolean dark = DamasGame.isDarkSquare(DamasGame.rowOf(square), DamasGame.colOf(square));
|
|
||||||
boolean highlighted = lastMove != null && lastMove.path().contains(square);
|
|
||||||
g.setColor(highlighted ? LAST_MOVE : dark ? DARK_SQUARE : LIGHT_SQUARE);
|
|
||||||
g.fillRect(cellX(square), cellY(square), cell, cell);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void paintPieces(Graphics2D g) {
|
|
||||||
List<Integer> capturedSoFar = capturedSoFar();
|
|
||||||
Piece moving = partialPath.isEmpty() ? null : game.pieceAt(partialPath.get(0));
|
|
||||||
for (int square = 0; square < DamasGame.SIZE * DamasGame.SIZE; square++) {
|
|
||||||
Piece piece = game.pieceAt(square);
|
|
||||||
boolean movedAway = !partialPath.isEmpty() && partialPath.get(0) == square;
|
|
||||||
if (piece != null && !movedAway) {
|
|
||||||
paintPiece(g, piece, square, capturedSoFar.contains(square));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (moving != null) {
|
|
||||||
paintPiece(g, moving, partialPath.get(partialPath.size() - 1), false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<Integer> capturedSoFar() {
|
|
||||||
if (partialPath.size() < 2) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
List<Move> matching = candidates();
|
|
||||||
if (matching.isEmpty() || matching.get(0).captured().isEmpty()) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
return matching.get(0).captured().subList(0, partialPath.size() - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void paintPiece(Graphics2D g, Piece piece, int square, boolean dimmed) {
|
|
||||||
int cell = cellSize();
|
|
||||||
int margin = cell / 8;
|
|
||||||
int size = cell - 2 * margin;
|
|
||||||
int x = cellX(square) + margin;
|
|
||||||
int y = cellY(square) + margin;
|
|
||||||
Color fill = piece.getSide() == Side.WHITE ? WHITE_PIECE : BLACK_PIECE;
|
|
||||||
Color edge = piece.getSide() == Side.WHITE ? BLACK_PIECE : WHITE_PIECE;
|
|
||||||
if (dimmed) {
|
|
||||||
fill = new Color(fill.getRed(), fill.getGreen(), fill.getBlue(), 90);
|
|
||||||
edge = new Color(edge.getRed(), edge.getGreen(), edge.getBlue(), 90);
|
|
||||||
}
|
|
||||||
g.setColor(fill);
|
|
||||||
g.fillOval(x, y, size, size);
|
|
||||||
g.setColor(edge);
|
|
||||||
g.setStroke(new BasicStroke(Math.max(1f, cell / 40f)));
|
|
||||||
g.drawOval(x, y, size, size);
|
|
||||||
g.drawOval(x + size / 6, y + size / 6, size * 2 / 3, size * 2 / 3);
|
|
||||||
if (piece.isKing()) {
|
|
||||||
paintCrown(g, x, y, size);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void paintCrown(Graphics2D g, int x, int y, int size) {
|
|
||||||
int left = x + size / 4;
|
|
||||||
int right = x + size * 3 / 4;
|
|
||||||
int top = y + size * 3 / 10;
|
|
||||||
int bottom = y + size * 2 / 3;
|
|
||||||
int mid = (left + right) / 2;
|
|
||||||
int inner = y + size / 2;
|
|
||||||
g.setColor(CROWN);
|
|
||||||
g.fillPolygon(
|
|
||||||
new int[]{left, left, (left + mid) / 2, mid, (mid + right) / 2, right, right},
|
|
||||||
new int[]{bottom, top, inner, top, inner, top, bottom},
|
|
||||||
7
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void paintHints(Graphics2D g) {
|
|
||||||
int cell = cellSize();
|
|
||||||
g.setStroke(new BasicStroke(Math.max(2f, cell / 20f)));
|
|
||||||
if (partialPath.isEmpty()) {
|
|
||||||
g.setColor(MOVABLE);
|
|
||||||
for (Move move : game.getLegalMoves()) {
|
|
||||||
g.drawRect(cellX(move.from()) + 1, cellY(move.from()) + 1, cell - 3, cell - 3);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
int current = partialPath.get(partialPath.size() - 1);
|
|
||||||
g.setColor(SELECTED);
|
|
||||||
g.drawRect(cellX(current) + 1, cellY(current) + 1, cell - 3, cell - 3);
|
|
||||||
int dot = cell / 3;
|
|
||||||
for (Move move : candidates()) {
|
|
||||||
int next = move.path().get(partialPath.size());
|
|
||||||
g.fillOval(cellX(next) + (cell - dot) / 2, cellY(next) + (cell - dot) / 2, dot, dot);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,296 +0,0 @@
|
|||||||
package pitiupi.damas.GUI;
|
|
||||||
|
|
||||||
import pitiupi.application.presence.UserPeerView;
|
|
||||||
import pitiupi.control.ConnectionManager;
|
|
||||||
import pitiupi.damas.control.DamasController;
|
|
||||||
import pitiupi.damas.game.DamasGame;
|
|
||||||
import pitiupi.damas.game.Side;
|
|
||||||
import pitiupi.presentation.shell.ui.ShellUi;
|
|
||||||
|
|
||||||
import javax.swing.BorderFactory;
|
|
||||||
import javax.swing.Box;
|
|
||||||
import javax.swing.BoxLayout;
|
|
||||||
import javax.swing.DefaultListCellRenderer;
|
|
||||||
import javax.swing.DefaultListModel;
|
|
||||||
import javax.swing.JButton;
|
|
||||||
import javax.swing.JComponent;
|
|
||||||
import javax.swing.JLabel;
|
|
||||||
import javax.swing.JList;
|
|
||||||
import javax.swing.JOptionPane;
|
|
||||||
import javax.swing.JPanel;
|
|
||||||
import javax.swing.JScrollPane;
|
|
||||||
import javax.swing.JTextArea;
|
|
||||||
import javax.swing.ListSelectionModel;
|
|
||||||
import javax.swing.UIManager;
|
|
||||||
import javax.swing.plaf.basic.BasicTextAreaUI;
|
|
||||||
import java.awt.BorderLayout;
|
|
||||||
import java.awt.CardLayout;
|
|
||||||
import java.awt.Component;
|
|
||||||
import java.awt.Dimension;
|
|
||||||
import java.awt.Font;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Aba do plugin: tabuleiro à esquerda e, à direita, as ações da fase atual da sessão.
|
|
||||||
*/
|
|
||||||
public final class DamasPanel extends JPanel {
|
|
||||||
|
|
||||||
private static final String CARD_LOBBY = "lobby";
|
|
||||||
private static final String CARD_INVITE_SENT = "inviteSent";
|
|
||||||
private static final String CARD_INVITE_RECEIVED = "inviteReceived";
|
|
||||||
private static final String CARD_PLAYING = "playing";
|
|
||||||
private static final String CARD_FINISHED = "finished";
|
|
||||||
|
|
||||||
private final DamasController controller;
|
|
||||||
private final ConnectionManager connectionManager;
|
|
||||||
private final BoardView boardView;
|
|
||||||
|
|
||||||
private final CardLayout cards = new CardLayout();
|
|
||||||
private final JPanel cardHost = new JPanel(cards);
|
|
||||||
private final JTextArea noticeText = wrappedText();
|
|
||||||
private final DefaultListModel<PeerItem> peerModel = new DefaultListModel<>();
|
|
||||||
private final JList<PeerItem> peerList = new JList<>(peerModel);
|
|
||||||
private final JButton inviteButton = new JButton("Convidar");
|
|
||||||
private final JTextArea inviteSentText = wrappedText();
|
|
||||||
private final JTextArea inviteReceivedText = wrappedText();
|
|
||||||
private final JTextArea playingText = wrappedText();
|
|
||||||
private final JTextArea awayText = wrappedText();
|
|
||||||
private final JButton resignButton = new JButton("Desistir");
|
|
||||||
private final JTextArea finishedText = wrappedText();
|
|
||||||
|
|
||||||
public DamasPanel(DamasController controller, ConnectionManager connectionManager) {
|
|
||||||
this.controller = controller;
|
|
||||||
this.connectionManager = connectionManager;
|
|
||||||
this.boardView = new BoardView(controller::play);
|
|
||||||
|
|
||||||
setLayout(new BorderLayout(8, 0));
|
|
||||||
setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
|
|
||||||
add(boardView, BorderLayout.CENTER);
|
|
||||||
add(buildSidePanel(), BorderLayout.EAST);
|
|
||||||
|
|
||||||
refreshPeers();
|
|
||||||
refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
private JComponent buildSidePanel() {
|
|
||||||
cardHost.add(buildLobbyCard(), CARD_LOBBY);
|
|
||||||
cardHost.add(buildInviteSentCard(), CARD_INVITE_SENT);
|
|
||||||
cardHost.add(buildInviteReceivedCard(), CARD_INVITE_RECEIVED);
|
|
||||||
cardHost.add(buildPlayingCard(), CARD_PLAYING);
|
|
||||||
cardHost.add(buildFinishedCard(), CARD_FINISHED);
|
|
||||||
|
|
||||||
JPanel side = new JPanel(new BorderLayout(0, 8));
|
|
||||||
side.setPreferredSize(new Dimension(220, 0));
|
|
||||||
side.add(cardHost, BorderLayout.CENTER);
|
|
||||||
side.add(noticeText, BorderLayout.SOUTH);
|
|
||||||
return side;
|
|
||||||
}
|
|
||||||
|
|
||||||
private JComponent buildLobbyCard() {
|
|
||||||
peerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
|
|
||||||
peerList.setCellRenderer(new DefaultListCellRenderer() {
|
|
||||||
@Override
|
|
||||||
public Component getListCellRendererComponent(
|
|
||||||
JList<?> list,
|
|
||||||
Object value,
|
|
||||||
int index,
|
|
||||||
boolean isSelected,
|
|
||||||
boolean cellHasFocus
|
|
||||||
) {
|
|
||||||
JLabel label = (JLabel) super.getListCellRendererComponent(
|
|
||||||
list, value, index, isSelected, cellHasFocus);
|
|
||||||
// Nomes vêm da rede: não deixar o Swing interpretar HTML.
|
|
||||||
label.putClientProperty("html.disable", Boolean.TRUE);
|
|
||||||
return label;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
peerList.addListSelectionListener(e -> updateInviteButton());
|
|
||||||
inviteButton.addActionListener(e -> {
|
|
||||||
PeerItem selected = peerList.getSelectedValue();
|
|
||||||
if (selected != null) {
|
|
||||||
controller.invite(selected.id(), selected.name());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
JPanel card = new JPanel(new BorderLayout(0, 6));
|
|
||||||
card.add(titleLabel("Escolha um adversário"), BorderLayout.NORTH);
|
|
||||||
card.add(new JScrollPane(peerList), BorderLayout.CENTER);
|
|
||||||
card.add(inviteButton, BorderLayout.SOUTH);
|
|
||||||
return card;
|
|
||||||
}
|
|
||||||
|
|
||||||
private JComponent buildInviteSentCard() {
|
|
||||||
return stackedCard("Convite enviado", inviteSentText, button("Cancelar", controller::cancelInvite));
|
|
||||||
}
|
|
||||||
|
|
||||||
private JComponent buildInviteReceivedCard() {
|
|
||||||
return stackedCard(
|
|
||||||
"Convite recebido",
|
|
||||||
inviteReceivedText,
|
|
||||||
button("Aceitar", controller::acceptInvite),
|
|
||||||
button("Recusar", controller::declineInvite)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private JComponent buildPlayingCard() {
|
|
||||||
resignButton.addActionListener(e -> confirmResign());
|
|
||||||
return stackedCard("Partida", playingText, awayText, resignButton);
|
|
||||||
}
|
|
||||||
|
|
||||||
private JComponent buildFinishedCard() {
|
|
||||||
return stackedCard(
|
|
||||||
"Fim de partida",
|
|
||||||
finishedText,
|
|
||||||
button("Jogar de novo", this::rematch),
|
|
||||||
button("Escolher outro adversário", controller::backToLobby)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void confirmResign() {
|
|
||||||
if (controller.isOpponentAway()) {
|
|
||||||
controller.resign();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
int answer = JOptionPane.showConfirmDialog(
|
|
||||||
this,
|
|
||||||
"Desistir desta partida?",
|
|
||||||
"Damas",
|
|
||||||
JOptionPane.YES_NO_OPTION
|
|
||||||
);
|
|
||||||
if (answer == JOptionPane.YES_OPTION) {
|
|
||||||
controller.resign();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void rematch() {
|
|
||||||
controller.invite(controller.getOpponentId(), controller.getOpponentName());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Sincroniza a tela com o estado do controller. */
|
|
||||||
public void refresh() {
|
|
||||||
DamasController.Phase phase = controller.getPhase();
|
|
||||||
DamasGame game = controller.getGame();
|
|
||||||
boardView.setState(game, controller.getMySide(), controller.isMyTurn());
|
|
||||||
|
|
||||||
DamasController.IncomingInvite invite = controller.getIncomingInvite();
|
|
||||||
if (invite != null) {
|
|
||||||
inviteReceivedText.setText(invite.fromName() + " convidou você para uma partida. "
|
|
||||||
+ "Você jogaria de " + invite.inviterSide().opposite().getLabel() + ".");
|
|
||||||
cards.show(cardHost, CARD_INVITE_RECEIVED);
|
|
||||||
} else {
|
|
||||||
switch (phase) {
|
|
||||||
case LOBBY -> cards.show(cardHost, CARD_LOBBY);
|
|
||||||
case INVITE_SENT -> {
|
|
||||||
inviteSentText.setText("Aguardando resposta de " + controller.getOpponentName() + "…");
|
|
||||||
cards.show(cardHost, CARD_INVITE_SENT);
|
|
||||||
}
|
|
||||||
case PLAYING -> {
|
|
||||||
updatePlayingCard(game);
|
|
||||||
cards.show(cardHost, CARD_PLAYING);
|
|
||||||
}
|
|
||||||
case FINISHED -> {
|
|
||||||
finishedText.setText(controller.getNotice());
|
|
||||||
cards.show(cardHost, CARD_FINISHED);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
boolean showNotice = phase != DamasController.Phase.FINISHED && !controller.getNotice().isEmpty();
|
|
||||||
noticeText.setText(showNotice ? controller.getNotice() : "");
|
|
||||||
noticeText.setVisible(showNotice);
|
|
||||||
updateInviteButton();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updatePlayingCard(DamasGame game) {
|
|
||||||
Side me = controller.getMySide();
|
|
||||||
Side other = me.opposite();
|
|
||||||
String turnLine = controller.isMyTurn() ? "Sua vez." : "Vez de " + controller.getOpponentName() + ".";
|
|
||||||
String captureLine = controller.isMyTurn() && !game.getLegalMoves().get(0).captured().isEmpty()
|
|
||||||
? "\nCaptura obrigatória."
|
|
||||||
: "";
|
|
||||||
playingText.setText(
|
|
||||||
"Você: " + me.getLabel() + " (" + game.countPieces(me) + " peças)\n"
|
|
||||||
+ controller.getOpponentName() + ": " + other.getLabel()
|
|
||||||
+ " (" + game.countPieces(other) + " peças)\n\n"
|
|
||||||
+ turnLine + captureLine
|
|
||||||
);
|
|
||||||
boolean away = controller.isOpponentAway();
|
|
||||||
awayText.setText(away
|
|
||||||
? controller.getOpponentName() + " saiu da rede. A partida continua se voltar."
|
|
||||||
: "");
|
|
||||||
awayText.setVisible(away);
|
|
||||||
resignButton.setText(away ? "Encerrar partida" : "Desistir");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void refreshPeers() {
|
|
||||||
PeerItem selected = peerList.getSelectedValue();
|
|
||||||
List<UserPeerView> views = connectionManager.getPresenceService().listPeerViews();
|
|
||||||
peerModel.clear();
|
|
||||||
for (UserPeerView view : views) {
|
|
||||||
if (!view.isBroadcastTarget() && !view.isSelf()) {
|
|
||||||
peerModel.addElement(new PeerItem(view.getInstanceId(), view.getDisplayName()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (selected != null && peerModel.contains(selected)) {
|
|
||||||
peerList.setSelectedValue(selected, false);
|
|
||||||
}
|
|
||||||
updateInviteButton();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateInviteButton() {
|
|
||||||
inviteButton.setEnabled(peerList.getSelectedValue() != null && controller.canInvite());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JButton button(String text, Runnable action) {
|
|
||||||
JButton button = new JButton(text);
|
|
||||||
button.addActionListener(e -> action.run());
|
|
||||||
return button;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JLabel titleLabel(String text) {
|
|
||||||
JLabel label = new JLabel(text);
|
|
||||||
label.setFont(label.getFont().deriveFont(Font.BOLD));
|
|
||||||
return label;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JPanel stackedCard(String title, JComponent... rows) {
|
|
||||||
JPanel stack = new JPanel();
|
|
||||||
stack.setLayout(new BoxLayout(stack, BoxLayout.Y_AXIS));
|
|
||||||
JLabel titleLabel = titleLabel(title);
|
|
||||||
titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
|
|
||||||
stack.add(titleLabel);
|
|
||||||
for (JComponent row : rows) {
|
|
||||||
stack.add(Box.createVerticalStrut(8));
|
|
||||||
row.setAlignmentX(Component.LEFT_ALIGNMENT);
|
|
||||||
if (row instanceof JButton) {
|
|
||||||
row.setMaximumSize(new Dimension(Integer.MAX_VALUE, row.getPreferredSize().height));
|
|
||||||
}
|
|
||||||
stack.add(row);
|
|
||||||
}
|
|
||||||
JPanel card = new JPanel(new BorderLayout());
|
|
||||||
card.add(stack, BorderLayout.NORTH);
|
|
||||||
return card;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Texto com quebra de linha sem HTML, pois inclui nomes vindos da rede. */
|
|
||||||
private static JTextArea wrappedText() {
|
|
||||||
JTextArea area = new JTextArea();
|
|
||||||
// O Nimbus pinta fundo e borda de campo de texto mesmo com setOpaque(false).
|
|
||||||
area.setUI(new BasicTextAreaUI());
|
|
||||||
area.setEditable(false);
|
|
||||||
area.setFocusable(false);
|
|
||||||
area.setOpaque(false);
|
|
||||||
area.setBorder(null);
|
|
||||||
area.setForeground(UIManager.getColor("Label.foreground"));
|
|
||||||
area.setLineWrap(true);
|
|
||||||
area.setWrapStyleWord(true);
|
|
||||||
area.setFont(UIManager.getFont("Label.font"));
|
|
||||||
return area;
|
|
||||||
}
|
|
||||||
|
|
||||||
private record PeerItem(String id, String name) {
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,422 +0,0 @@
|
|||||||
package pitiupi.damas.control;
|
|
||||||
|
|
||||||
import pitiupi.damas.game.DamasGame;
|
|
||||||
import pitiupi.damas.game.GameResult;
|
|
||||||
import pitiupi.damas.game.Side;
|
|
||||||
import pitiupi.damas.net.DamasMessage;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.concurrent.ThreadLocalRandom;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
import java.util.function.Supplier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sessão de jogo: convites, lances e entrega confiável sobre UDP.
|
|
||||||
*
|
|
||||||
* <p>Cada mensagem enviada fica pendente até chegar o ACK e é reenviada a cada {@link #tick()}.
|
|
||||||
* O receptor confirma sempre, mesmo as duplicadas, e processa cada mensagem uma única vez.
|
|
||||||
* Lances recebidos são validados pelas regras locais antes de serem aplicados.</p>
|
|
||||||
*
|
|
||||||
* <p>Não é thread-safe: todas as chamadas devem vir da mesma thread (no plugin, a EDT).</p>
|
|
||||||
*/
|
|
||||||
public final class DamasController {
|
|
||||||
|
|
||||||
public enum Phase {
|
|
||||||
LOBBY,
|
|
||||||
INVITE_SENT,
|
|
||||||
PLAYING,
|
|
||||||
FINISHED
|
|
||||||
}
|
|
||||||
|
|
||||||
public interface Listener {
|
|
||||||
void onStateChanged();
|
|
||||||
|
|
||||||
/** Algo exige a atenção do jogador: convite recebido ou partida iniciada. */
|
|
||||||
void onAttentionNeeded();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Convite recebido aguardando a resposta do jogador. */
|
|
||||||
public record IncomingInvite(String gameId, String fromId, String fromName, Side inviterSide) {
|
|
||||||
}
|
|
||||||
|
|
||||||
static final int INVITE_MAX_ATTEMPTS = 20;
|
|
||||||
static final int MESSAGE_MAX_ATTEMPTS = 120;
|
|
||||||
|
|
||||||
private final String selfId;
|
|
||||||
private final Supplier<String> selfName;
|
|
||||||
private final Consumer<DamasMessage> link;
|
|
||||||
private final Listener listener;
|
|
||||||
|
|
||||||
private final List<Pending> pending = new ArrayList<>();
|
|
||||||
private final Set<String> processed = new HashSet<>();
|
|
||||||
private Set<String> knownPeers = Set.of();
|
|
||||||
private int nextSeq = 1;
|
|
||||||
|
|
||||||
private Phase phase = Phase.LOBBY;
|
|
||||||
private String gameId;
|
|
||||||
private String opponentId;
|
|
||||||
private String opponentName;
|
|
||||||
private Side mySide;
|
|
||||||
private DamasGame game;
|
|
||||||
private boolean opponentAway;
|
|
||||||
private IncomingInvite incomingInvite;
|
|
||||||
private String notice = "";
|
|
||||||
|
|
||||||
public DamasController(
|
|
||||||
String selfId,
|
|
||||||
Supplier<String> selfName,
|
|
||||||
Consumer<DamasMessage> link,
|
|
||||||
Listener listener
|
|
||||||
) {
|
|
||||||
this.selfId = selfId;
|
|
||||||
this.selfName = selfName;
|
|
||||||
this.link = link;
|
|
||||||
this.listener = listener;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Phase getPhase() {
|
|
||||||
return phase;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DamasGame getGame() {
|
|
||||||
return game;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Side getMySide() {
|
|
||||||
return mySide;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOpponentId() {
|
|
||||||
return opponentId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOpponentName() {
|
|
||||||
return opponentName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isOpponentAway() {
|
|
||||||
return opponentAway;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IncomingInvite getIncomingInvite() {
|
|
||||||
return incomingInvite;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Último aviso para o jogador (recusa, fim de partida, adversário saiu…). */
|
|
||||||
public String getNotice() {
|
|
||||||
return notice;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isMyTurn() {
|
|
||||||
return phase == Phase.PLAYING && game.getTurn() == mySide;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean canInvite() {
|
|
||||||
return (phase == Phase.LOBBY || phase == Phase.FINISHED) && incomingInvite == null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean invite(String peerId, String peerName) {
|
|
||||||
if (!canInvite()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
gameId = UUID.randomUUID().toString();
|
|
||||||
opponentId = peerId;
|
|
||||||
opponentName = peerName;
|
|
||||||
mySide = ThreadLocalRandom.current().nextBoolean() ? Side.WHITE : Side.BLACK;
|
|
||||||
game = null;
|
|
||||||
opponentAway = false;
|
|
||||||
phase = Phase.INVITE_SENT;
|
|
||||||
notice = "";
|
|
||||||
sendReliable(DamasMessage.invite(gameId, selfId, peerId, selfName.get(), nextSeq++, mySide));
|
|
||||||
listener.onStateChanged();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void cancelInvite() {
|
|
||||||
if (phase != Phase.INVITE_SENT) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
forgetCurrentGameMessages();
|
|
||||||
sendControl(DamasMessage.Type.CANCEL);
|
|
||||||
phase = Phase.LOBBY;
|
|
||||||
notice = "";
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void acceptInvite() {
|
|
||||||
IncomingInvite invite = incomingInvite;
|
|
||||||
if (invite == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
incomingInvite = null;
|
|
||||||
gameId = invite.gameId();
|
|
||||||
opponentId = invite.fromId();
|
|
||||||
opponentName = invite.fromName();
|
|
||||||
mySide = invite.inviterSide().opposite();
|
|
||||||
sendControl(DamasMessage.Type.ACCEPT);
|
|
||||||
startGame();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void declineInvite() {
|
|
||||||
IncomingInvite invite = incomingInvite;
|
|
||||||
if (invite == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
incomingInvite = null;
|
|
||||||
sendReliable(DamasMessage.control(
|
|
||||||
DamasMessage.Type.DECLINE, invite.gameId(), selfId, invite.fromId(), selfName.get(), nextSeq++));
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Joga o lance local.
|
|
||||||
*
|
|
||||||
* @return {@code false} se não for a vez do jogador ou o caminho não for legal.
|
|
||||||
*/
|
|
||||||
public boolean play(List<Integer> path) {
|
|
||||||
if (!isMyTurn() || game.apply(path) == null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
sendReliable(DamasMessage.move(gameId, selfId, opponentId, selfName.get(), nextSeq++, path));
|
|
||||||
finishIfGameOver();
|
|
||||||
listener.onStateChanged();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Desiste da partida ou, se o adversário saiu da rede, apenas a encerra. */
|
|
||||||
public void resign() {
|
|
||||||
if (phase != Phase.PLAYING) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sendControl(DamasMessage.Type.RESIGN);
|
|
||||||
phase = Phase.FINISHED;
|
|
||||||
notice = opponentAway
|
|
||||||
? "Partida encerrada: " + opponentName + " saiu da rede."
|
|
||||||
: "Você desistiu. " + opponentName + " venceu.";
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void backToLobby() {
|
|
||||||
if (phase != Phase.FINISHED) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
phase = Phase.LOBBY;
|
|
||||||
game = null;
|
|
||||||
notice = "";
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Reenvia o que ainda não foi confirmado. Chamar periodicamente. */
|
|
||||||
public void tick() {
|
|
||||||
boolean changed = false;
|
|
||||||
for (Iterator<Pending> it = pending.iterator(); it.hasNext(); ) {
|
|
||||||
Pending item = it.next();
|
|
||||||
if (item.attempts >= maxAttempts(item.message)) {
|
|
||||||
it.remove();
|
|
||||||
if (item.message.getType() == DamasMessage.Type.INVITE && isCurrentGame(item.message)
|
|
||||||
&& phase == Phase.INVITE_SENT) {
|
|
||||||
phase = Phase.LOBBY;
|
|
||||||
notice = opponentName + " não respondeu ao convite.";
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
item.attempts++;
|
|
||||||
link.accept(item.message);
|
|
||||||
}
|
|
||||||
if (changed) {
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Atualiza a presença. O adversário que sumir pode voltar (ex.: falha rápida no Wi-Fi). */
|
|
||||||
public void onPeersChanged(Set<String> peerIds) {
|
|
||||||
Set<String> previous = knownPeers;
|
|
||||||
knownPeers = Set.copyOf(peerIds);
|
|
||||||
boolean changed = false;
|
|
||||||
|
|
||||||
if (incomingInvite != null && previous.contains(incomingInvite.fromId())
|
|
||||||
&& !peerIds.contains(incomingInvite.fromId())) {
|
|
||||||
notice = incomingInvite.fromName() + " saiu da rede; convite cancelado.";
|
|
||||||
incomingInvite = null;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
if (phase == Phase.INVITE_SENT && previous.contains(opponentId) && !peerIds.contains(opponentId)) {
|
|
||||||
forgetCurrentGameMessages();
|
|
||||||
phase = Phase.LOBBY;
|
|
||||||
notice = opponentName + " saiu da rede; convite cancelado.";
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
if (phase == Phase.PLAYING) {
|
|
||||||
boolean away = previous.contains(opponentId) && !peerIds.contains(opponentId)
|
|
||||||
|| opponentAway && !peerIds.contains(opponentId);
|
|
||||||
if (away != opponentAway) {
|
|
||||||
opponentAway = away;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (changed) {
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void receive(DamasMessage message) {
|
|
||||||
if (!selfId.equals(message.getTo()) || message.getFrom() == null || message.getGameId() == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (message.getType() == DamasMessage.Type.ACK) {
|
|
||||||
pending.removeIf(item -> item.message.getSeq() == message.getSeq()
|
|
||||||
&& item.message.getGameId().equals(message.getGameId())
|
|
||||||
&& item.message.getTo().equals(message.getFrom()));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
link.accept(DamasMessage.ack(message, selfId));
|
|
||||||
String key = message.getFrom() + "|" + message.getGameId() + "|" + message.getSeq();
|
|
||||||
if (!processed.add(key)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
switch (message.getType()) {
|
|
||||||
case INVITE -> onInvite(message);
|
|
||||||
case ACCEPT -> onAccept(message);
|
|
||||||
case DECLINE -> onInviteRefused(message, " recusou o convite.");
|
|
||||||
case BUSY -> onInviteRefused(message, " está ocupado no momento.");
|
|
||||||
case CANCEL -> onCancel(message);
|
|
||||||
case MOVE -> onMove(message);
|
|
||||||
case RESIGN -> onResign(message);
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onInvite(DamasMessage message) {
|
|
||||||
if (message.getInviterSide() == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!canInvite()) {
|
|
||||||
sendReliable(DamasMessage.control(
|
|
||||||
DamasMessage.Type.BUSY, message.getGameId(), selfId, message.getFrom(), selfName.get(), nextSeq++));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
incomingInvite = new IncomingInvite(
|
|
||||||
message.getGameId(), message.getFrom(), message.getFromName(), message.getInviterSide());
|
|
||||||
listener.onStateChanged();
|
|
||||||
listener.onAttentionNeeded();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onAccept(DamasMessage message) {
|
|
||||||
if (phase == Phase.INVITE_SENT && isFromOpponent(message)) {
|
|
||||||
startGame();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onInviteRefused(DamasMessage message, String reason) {
|
|
||||||
if (phase == Phase.INVITE_SENT && isFromOpponent(message)) {
|
|
||||||
phase = Phase.LOBBY;
|
|
||||||
notice = opponentName + reason;
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onCancel(DamasMessage message) {
|
|
||||||
if (incomingInvite != null && incomingInvite.gameId().equals(message.getGameId())) {
|
|
||||||
notice = incomingInvite.fromName() + " cancelou o convite.";
|
|
||||||
incomingInvite = null;
|
|
||||||
listener.onStateChanged();
|
|
||||||
} else if (phase == Phase.PLAYING && isFromOpponent(message)) {
|
|
||||||
// O convite foi cancelado enquanto o aceite estava a caminho.
|
|
||||||
phase = Phase.LOBBY;
|
|
||||||
game = null;
|
|
||||||
notice = opponentName + " cancelou o convite.";
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onMove(DamasMessage message) {
|
|
||||||
if (phase != Phase.PLAYING || !isFromOpponent(message) || message.getPath() == null || isMyTurn()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (game.apply(message.getPath()) == null) {
|
|
||||||
phase = Phase.FINISHED;
|
|
||||||
notice = "Partida interrompida: lance inválido recebido de " + opponentName + ".";
|
|
||||||
} else {
|
|
||||||
finishIfGameOver();
|
|
||||||
}
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onResign(DamasMessage message) {
|
|
||||||
if (phase == Phase.PLAYING && isFromOpponent(message)) {
|
|
||||||
phase = Phase.FINISHED;
|
|
||||||
notice = opponentName + " desistiu. Você venceu!";
|
|
||||||
listener.onStateChanged();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void startGame() {
|
|
||||||
game = new DamasGame();
|
|
||||||
phase = Phase.PLAYING;
|
|
||||||
opponentAway = false;
|
|
||||||
notice = "";
|
|
||||||
listener.onStateChanged();
|
|
||||||
listener.onAttentionNeeded();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void finishIfGameOver() {
|
|
||||||
GameResult result = game.getResult();
|
|
||||||
if (result == GameResult.IN_PROGRESS) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
phase = Phase.FINISHED;
|
|
||||||
if (result == GameResult.DRAW) {
|
|
||||||
notice = "Empate: 20 lances de cada lado só com damas, sem captura.";
|
|
||||||
} else {
|
|
||||||
Side winner = result == GameResult.WHITE_WINS ? Side.WHITE : Side.BLACK;
|
|
||||||
notice = winner == mySide ? "Você venceu!" : opponentName + " venceu.";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isFromOpponent(DamasMessage message) {
|
|
||||||
return isCurrentGame(message) && message.getFrom().equals(opponentId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isCurrentGame(DamasMessage message) {
|
|
||||||
return message.getGameId().equals(gameId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Um lance da partida em curso nunca é descartado: o adversário pode voltar à rede. */
|
|
||||||
private int maxAttempts(DamasMessage message) {
|
|
||||||
return switch (message.getType()) {
|
|
||||||
case INVITE -> INVITE_MAX_ATTEMPTS;
|
|
||||||
case MOVE -> phase == Phase.PLAYING && isCurrentGame(message) ? Integer.MAX_VALUE : MESSAGE_MAX_ATTEMPTS;
|
|
||||||
default -> MESSAGE_MAX_ATTEMPTS;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Preserva o que ainda está a caminho de partidas anteriores, como o lance final. */
|
|
||||||
private void forgetCurrentGameMessages() {
|
|
||||||
pending.removeIf(item -> isCurrentGame(item.message));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendControl(DamasMessage.Type type) {
|
|
||||||
sendReliable(DamasMessage.control(type, gameId, selfId, opponentId, selfName.get(), nextSeq++));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendReliable(DamasMessage message) {
|
|
||||||
pending.add(new Pending(message));
|
|
||||||
link.accept(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final class Pending {
|
|
||||||
private final DamasMessage message;
|
|
||||||
private int attempts;
|
|
||||||
|
|
||||||
private Pending(DamasMessage message) {
|
|
||||||
this.message = message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,271 +0,0 @@
|
|||||||
package pitiupi.damas.game;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Regras do jogo de damas brasileiro (tabuleiro 8×8), sem rede nem Swing.
|
|
||||||
*
|
|
||||||
* <p>Pedras andam uma casa para a frente e capturam para a frente e para trás. Damas são
|
|
||||||
* voadoras. A captura é obrigatória e vale a lei da maioria: só são legais as sequências com
|
|
||||||
* o maior número de peças; em caso de igualdade, a escolha é livre. As peças capturadas só
|
|
||||||
* saem do tabuleiro no fim da sequência e não podem ser saltadas duas vezes. A pedra que
|
|
||||||
* passa pela última linha no meio de uma captura só é promovida se terminar nela.</p>
|
|
||||||
*
|
|
||||||
* <p>Empate após 20 lances de cada lado só com damas, sem captura nem movimento de pedra.</p>
|
|
||||||
*/
|
|
||||||
public final class DamasGame {
|
|
||||||
|
|
||||||
public static final int SIZE = 8;
|
|
||||||
private static final int INITIAL_ROWS = 3;
|
|
||||||
private static final int DRAW_QUIET_PLIES = 40;
|
|
||||||
private static final int[][] DIRECTIONS = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}};
|
|
||||||
|
|
||||||
private final Piece[] board = new Piece[SIZE * SIZE];
|
|
||||||
private Side turn = Side.WHITE;
|
|
||||||
private int quietPlies;
|
|
||||||
private GameResult result = GameResult.IN_PROGRESS;
|
|
||||||
private Move lastMove;
|
|
||||||
private List<Move> legalMoves;
|
|
||||||
|
|
||||||
public DamasGame() {
|
|
||||||
for (int row = 0; row < SIZE; row++) {
|
|
||||||
for (int col = 0; col < SIZE; col++) {
|
|
||||||
if (!isDarkSquare(row, col)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (row < INITIAL_ROWS) {
|
|
||||||
board[square(row, col)] = Piece.BLACK_MAN;
|
|
||||||
} else if (row >= SIZE - INITIAL_ROWS) {
|
|
||||||
board[square(row, col)] = Piece.WHITE_MAN;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
legalMoves = computeLegalMoves();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Posição arbitrária para testes: uma string por linha, com {@code w b W B} e {@code .}.
|
|
||||||
*/
|
|
||||||
static DamasGame fromRows(Side turn, String... rows) {
|
|
||||||
DamasGame game = new DamasGame();
|
|
||||||
for (int row = 0; row < SIZE; row++) {
|
|
||||||
for (int col = 0; col < SIZE; col++) {
|
|
||||||
game.board[square(row, col)] = switch (rows[row].charAt(col)) {
|
|
||||||
case 'w' -> Piece.WHITE_MAN;
|
|
||||||
case 'W' -> Piece.WHITE_KING;
|
|
||||||
case 'b' -> Piece.BLACK_MAN;
|
|
||||||
case 'B' -> Piece.BLACK_KING;
|
|
||||||
default -> null;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
game.turn = turn;
|
|
||||||
game.legalMoves = game.computeLegalMoves();
|
|
||||||
return game;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static int square(int row, int col) {
|
|
||||||
return row * SIZE + col;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static int rowOf(int square) {
|
|
||||||
return square / SIZE;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static int colOf(int square) {
|
|
||||||
return square % SIZE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A casa escura fica no canto inferior esquerdo de cada jogador. */
|
|
||||||
public static boolean isDarkSquare(int row, int col) {
|
|
||||||
return (row + col) % 2 == 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Piece pieceAt(int square) {
|
|
||||||
return board[square];
|
|
||||||
}
|
|
||||||
|
|
||||||
public Side getTurn() {
|
|
||||||
return turn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public GameResult getResult() {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Move getLastMove() {
|
|
||||||
return lastMove;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Move> getLegalMoves() {
|
|
||||||
return legalMoves;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int countPieces(Side side) {
|
|
||||||
int count = 0;
|
|
||||||
for (Piece piece : board) {
|
|
||||||
if (piece != null && piece.getSide() == side) {
|
|
||||||
count++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return count;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Aplica o lance com este caminho.
|
|
||||||
*
|
|
||||||
* @return o lance aplicado ou {@code null} se o caminho não for legal nesta posição.
|
|
||||||
*/
|
|
||||||
public Move apply(List<Integer> path) {
|
|
||||||
if (result != GameResult.IN_PROGRESS) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (Move move : legalMoves) {
|
|
||||||
if (move.path().equals(path)) {
|
|
||||||
applyLegal(move);
|
|
||||||
return move;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyLegal(Move move) {
|
|
||||||
Piece piece = board[move.from()];
|
|
||||||
board[move.from()] = null;
|
|
||||||
for (int captured : move.captured()) {
|
|
||||||
board[captured] = null;
|
|
||||||
}
|
|
||||||
boolean promotes = !piece.isKing() && rowOf(move.to()) == piece.getSide().getPromotionRow();
|
|
||||||
board[move.to()] = promotes ? piece.promoted() : piece;
|
|
||||||
|
|
||||||
quietPlies = piece.isKing() && move.captured().isEmpty() ? quietPlies + 1 : 0;
|
|
||||||
lastMove = move;
|
|
||||||
Side mover = turn;
|
|
||||||
turn = mover.opposite();
|
|
||||||
legalMoves = computeLegalMoves();
|
|
||||||
|
|
||||||
if (legalMoves.isEmpty()) {
|
|
||||||
result = mover == Side.WHITE ? GameResult.WHITE_WINS : GameResult.BLACK_WINS;
|
|
||||||
} else if (quietPlies >= DRAW_QUIET_PLIES) {
|
|
||||||
result = GameResult.DRAW;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<Move> computeLegalMoves() {
|
|
||||||
List<Move> captures = new ArrayList<>();
|
|
||||||
for (int square = 0; square < board.length; square++) {
|
|
||||||
Piece piece = board[square];
|
|
||||||
if (piece != null && piece.getSide() == turn) {
|
|
||||||
// A peça em movimento não bloqueia o próprio caminho durante a sequência.
|
|
||||||
board[square] = null;
|
|
||||||
List<Integer> path = new ArrayList<>(List.of(square));
|
|
||||||
collectCaptures(square, piece, path, new ArrayList<>(), captures);
|
|
||||||
board[square] = piece;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!captures.isEmpty()) {
|
|
||||||
return keepLargestCaptures(captures);
|
|
||||||
}
|
|
||||||
List<Move> moves = new ArrayList<>();
|
|
||||||
for (int square = 0; square < board.length; square++) {
|
|
||||||
Piece piece = board[square];
|
|
||||||
if (piece != null && piece.getSide() == turn) {
|
|
||||||
collectSimpleMoves(square, piece, moves);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return moves;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<Move> keepLargestCaptures(List<Move> captures) {
|
|
||||||
int largest = 0;
|
|
||||||
for (Move move : captures) {
|
|
||||||
largest = Math.max(largest, move.captured().size());
|
|
||||||
}
|
|
||||||
List<Move> kept = new ArrayList<>();
|
|
||||||
for (Move move : captures) {
|
|
||||||
if (move.captured().size() == largest) {
|
|
||||||
kept.add(move);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return kept;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void collectCaptures(
|
|
||||||
int from,
|
|
||||||
Piece piece,
|
|
||||||
List<Integer> path,
|
|
||||||
List<Integer> captured,
|
|
||||||
List<Move> out
|
|
||||||
) {
|
|
||||||
boolean extended = false;
|
|
||||||
for (int[] direction : DIRECTIONS) {
|
|
||||||
int victim = findVictim(from, direction, piece, captured);
|
|
||||||
if (victim < 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
int row = rowOf(victim) + direction[0];
|
|
||||||
int col = colOf(victim) + direction[1];
|
|
||||||
while (isOnBoard(row, col) && board[square(row, col)] == null) {
|
|
||||||
extended = true;
|
|
||||||
path.add(square(row, col));
|
|
||||||
captured.add(victim);
|
|
||||||
collectCaptures(square(row, col), piece, path, captured, out);
|
|
||||||
captured.remove(captured.size() - 1);
|
|
||||||
path.remove(path.size() - 1);
|
|
||||||
if (!piece.isKing()) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
row += direction[0];
|
|
||||||
col += direction[1];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!extended && !captured.isEmpty()) {
|
|
||||||
out.add(new Move(path, captured));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Primeira peça encontrada na direção, se puder ser capturada; {@code -1} caso contrário.
|
|
||||||
* Peças já capturadas seguem no tabuleiro e bloqueiam a passagem.
|
|
||||||
*/
|
|
||||||
private int findVictim(int from, int[] direction, Piece piece, List<Integer> captured) {
|
|
||||||
int row = rowOf(from) + direction[0];
|
|
||||||
int col = colOf(from) + direction[1];
|
|
||||||
while (isOnBoard(row, col)) {
|
|
||||||
Piece found = board[square(row, col)];
|
|
||||||
if (found != null) {
|
|
||||||
boolean capturable = found.getSide() != piece.getSide() && !captured.contains(square(row, col));
|
|
||||||
return capturable ? square(row, col) : -1;
|
|
||||||
}
|
|
||||||
if (!piece.isKing()) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
row += direction[0];
|
|
||||||
col += direction[1];
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void collectSimpleMoves(int from, Piece piece, List<Move> out) {
|
|
||||||
for (int[] direction : DIRECTIONS) {
|
|
||||||
if (!piece.isKing() && direction[0] != piece.getSide().getForwardRow()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
int row = rowOf(from) + direction[0];
|
|
||||||
int col = colOf(from) + direction[1];
|
|
||||||
while (isOnBoard(row, col) && board[square(row, col)] == null) {
|
|
||||||
out.add(new Move(List.of(from, square(row, col)), List.of()));
|
|
||||||
if (!piece.isKing()) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
row += direction[0];
|
|
||||||
col += direction[1];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean isOnBoard(int row, int col) {
|
|
||||||
return row >= 0 && row < SIZE && col >= 0 && col < SIZE;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
package pitiupi.damas.game;
|
|
||||||
|
|
||||||
public enum GameResult {
|
|
||||||
IN_PROGRESS,
|
|
||||||
WHITE_WINS,
|
|
||||||
BLACK_WINS,
|
|
||||||
DRAW
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
package pitiupi.damas.game;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Lance completo: casas percorridas (origem, pousos) e peças capturadas, na ordem do salto.
|
|
||||||
*/
|
|
||||||
public record Move(List<Integer> path, List<Integer> captured) {
|
|
||||||
|
|
||||||
public Move {
|
|
||||||
path = List.copyOf(path);
|
|
||||||
captured = List.copyOf(captured);
|
|
||||||
}
|
|
||||||
|
|
||||||
public int from() {
|
|
||||||
return path.get(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public int to() {
|
|
||||||
return path.get(path.size() - 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
package pitiupi.damas.game;
|
|
||||||
|
|
||||||
public enum Piece {
|
|
||||||
WHITE_MAN(Side.WHITE, false),
|
|
||||||
WHITE_KING(Side.WHITE, true),
|
|
||||||
BLACK_MAN(Side.BLACK, false),
|
|
||||||
BLACK_KING(Side.BLACK, true);
|
|
||||||
|
|
||||||
private final Side side;
|
|
||||||
private final boolean king;
|
|
||||||
|
|
||||||
Piece(Side side, boolean king) {
|
|
||||||
this.side = side;
|
|
||||||
this.king = king;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Side getSide() {
|
|
||||||
return side;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isKing() {
|
|
||||||
return king;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Piece promoted() {
|
|
||||||
return side == Side.WHITE ? WHITE_KING : BLACK_KING;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package pitiupi.damas.game;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Lado de um jogador. As brancas começam e sobem o tabuleiro (linha 7 → linha 0).
|
|
||||||
*/
|
|
||||||
public enum Side {
|
|
||||||
WHITE("brancas", -1, 0),
|
|
||||||
BLACK("pretas", 1, 7);
|
|
||||||
|
|
||||||
private final String label;
|
|
||||||
private final int forwardRow;
|
|
||||||
private final int promotionRow;
|
|
||||||
|
|
||||||
Side(String label, int forwardRow, int promotionRow) {
|
|
||||||
this.label = label;
|
|
||||||
this.forwardRow = forwardRow;
|
|
||||||
this.promotionRow = promotionRow;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getLabel() {
|
|
||||||
return label;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getForwardRow() {
|
|
||||||
return forwardRow;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getPromotionRow() {
|
|
||||||
return promotionRow;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Side opposite() {
|
|
||||||
return this == WHITE ? BLACK : WHITE;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
package pitiupi.damas.net;
|
|
||||||
|
|
||||||
import pitiupi.damas.game.Side;
|
|
||||||
import pitiupi.models.Messages.Message;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Mensagem do protocolo de damas. Viaja em UDP multicast: {@code to} indica o destinatário e os
|
|
||||||
* demais peers a ignoram. Exceto {@link Type#ACK}, toda mensagem é confirmada e retransmitida.
|
|
||||||
*/
|
|
||||||
public class DamasMessage extends Message {
|
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
public enum Type {
|
|
||||||
INVITE,
|
|
||||||
ACCEPT,
|
|
||||||
DECLINE,
|
|
||||||
BUSY,
|
|
||||||
CANCEL,
|
|
||||||
MOVE,
|
|
||||||
RESIGN,
|
|
||||||
ACK
|
|
||||||
}
|
|
||||||
|
|
||||||
private final Type type;
|
|
||||||
private final String gameId;
|
|
||||||
private final String from;
|
|
||||||
private final String to;
|
|
||||||
private final String fromName;
|
|
||||||
private final int seq;
|
|
||||||
private final Side inviterSide;
|
|
||||||
private final int[] path;
|
|
||||||
|
|
||||||
private DamasMessage(
|
|
||||||
Type type,
|
|
||||||
String gameId,
|
|
||||||
String from,
|
|
||||||
String to,
|
|
||||||
String fromName,
|
|
||||||
int seq,
|
|
||||||
Side inviterSide,
|
|
||||||
int[] path
|
|
||||||
) {
|
|
||||||
this.type = type;
|
|
||||||
this.gameId = gameId;
|
|
||||||
this.from = from;
|
|
||||||
this.to = to;
|
|
||||||
this.fromName = fromName;
|
|
||||||
this.seq = seq;
|
|
||||||
this.inviterSide = inviterSide;
|
|
||||||
this.path = path;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static DamasMessage invite(String gameId, String from, String to, String fromName, int seq, Side inviterSide) {
|
|
||||||
return new DamasMessage(Type.INVITE, gameId, from, to, fromName, seq, inviterSide, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static DamasMessage move(String gameId, String from, String to, String fromName, int seq, List<Integer> path) {
|
|
||||||
int[] squares = path.stream().mapToInt(Integer::intValue).toArray();
|
|
||||||
return new DamasMessage(Type.MOVE, gameId, from, to, fromName, seq, null, squares);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** ACCEPT, DECLINE, BUSY, CANCEL ou RESIGN. */
|
|
||||||
public static DamasMessage control(Type type, String gameId, String from, String to, String fromName, int seq) {
|
|
||||||
return new DamasMessage(type, gameId, from, to, fromName, seq, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static DamasMessage ack(DamasMessage received, String from) {
|
|
||||||
return new DamasMessage(Type.ACK, received.gameId, from, received.from, null, received.seq, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Type getType() {
|
|
||||||
return type;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getGameId() {
|
|
||||||
return gameId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getFrom() {
|
|
||||||
return from;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTo() {
|
|
||||||
return to;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getFromName() {
|
|
||||||
return fromName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getSeq() {
|
|
||||||
return seq;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Side getInviterSide() {
|
|
||||||
return inviterSide;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Caminho do lance ou {@code null} se a mensagem não for {@link Type#MOVE}. */
|
|
||||||
public List<Integer> getPath() {
|
|
||||||
return path == null ? null : java.util.Arrays.stream(path).boxed().toList();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
package pitiupi.damas.plugin;
|
|
||||||
|
|
||||||
import pitiupi.api.plugin.PeerActionsRegistrar;
|
|
||||||
import pitiupi.api.plugin.PluginWorkspace;
|
|
||||||
import pitiupi.application.messaging.MessageDispatcher;
|
|
||||||
import pitiupi.application.messaging.SendTarget;
|
|
||||||
import pitiupi.application.messaging.TransportMode;
|
|
||||||
import pitiupi.application.peeractions.PeerAction;
|
|
||||||
import pitiupi.application.peeractions.PeerActionTarget;
|
|
||||||
import pitiupi.application.peeractions.PeerTarget;
|
|
||||||
import pitiupi.control.ConnectionManager;
|
|
||||||
import pitiupi.damas.GUI.DamasPanel;
|
|
||||||
import pitiupi.damas.control.DamasController;
|
|
||||||
import pitiupi.damas.net.DamasMessage;
|
|
||||||
import pitiupi.models.Messages.Message;
|
|
||||||
import pitiupi.models.Plugin;
|
|
||||||
import pitiupi.models.User;
|
|
||||||
|
|
||||||
import javax.swing.SwingUtilities;
|
|
||||||
import javax.swing.Timer;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
public class DamasPlugin extends Plugin {
|
|
||||||
|
|
||||||
private static final int RESEND_INTERVAL_MS = 500;
|
|
||||||
|
|
||||||
private ConnectionManager connectionManager;
|
|
||||||
private PluginWorkspace workspace;
|
|
||||||
private DamasController controller;
|
|
||||||
private DamasPanel panel;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void createPlugin(ConnectionManager connectionManager, PluginWorkspace workspace) {
|
|
||||||
this.connectionManager = connectionManager;
|
|
||||||
this.workspace = workspace;
|
|
||||||
this.controller = new DamasController(
|
|
||||||
connectionManager.getHeartbeatManager().getInstanceId(),
|
|
||||||
connectionManager::getUserName,
|
|
||||||
this::send,
|
|
||||||
new DamasController.Listener() {
|
|
||||||
@Override
|
|
||||||
public void onStateChanged() {
|
|
||||||
panel.refresh();
|
|
||||||
updateStatusBar();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onAttentionNeeded() {
|
|
||||||
openTab();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
this.panel = new DamasPanel(controller, connectionManager);
|
|
||||||
bindShellWorkspaceContent(panel);
|
|
||||||
installPeerActions(workspace.peerActions());
|
|
||||||
|
|
||||||
connectionManager.addPeerListener(peers -> {
|
|
||||||
Set<String> ids = peers.stream().map(User::getInstanceId).collect(Collectors.toSet());
|
|
||||||
SwingUtilities.invokeLater(() -> {
|
|
||||||
controller.onPeersChanged(ids);
|
|
||||||
panel.refreshPeers();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
new Timer(RESEND_INTERVAL_MS, e -> controller.tick()).start();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void installPeerActions(PeerActionsRegistrar registrar) {
|
|
||||||
registrar.register(PeerAction.of(
|
|
||||||
"damas.open",
|
|
||||||
"Abrir damas",
|
|
||||||
PeerActionTarget.ALL_PEERS,
|
|
||||||
target -> openTab()
|
|
||||||
));
|
|
||||||
registrar.register(PeerAction.of(
|
|
||||||
"damas.invite",
|
|
||||||
"Convidar para uma partida",
|
|
||||||
PeerActionTarget.SINGLE_PEER,
|
|
||||||
this::inviteFromPeerList
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void inviteFromPeerList(PeerTarget target) {
|
|
||||||
openTab();
|
|
||||||
if (target instanceof PeerTarget.Single single) {
|
|
||||||
controller.invite(single.peer().getInstanceId(), single.peer().getDisplayName());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void openTab() {
|
|
||||||
workspace.openOrFocusTab(getIdentifier(), getDisplayName());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Com a aba fechada, a barra de status é o que avisa sobre convite e vez de jogar. */
|
|
||||||
private void updateStatusBar() {
|
|
||||||
String text = statusBarText();
|
|
||||||
if (text != null) {
|
|
||||||
workspace.setStatusMessage(text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String statusBarText() {
|
|
||||||
if (controller.getIncomingInvite() != null) {
|
|
||||||
return "Damas: " + controller.getIncomingInvite().fromName() + " convidou você para uma partida";
|
|
||||||
}
|
|
||||||
return switch (controller.getPhase()) {
|
|
||||||
case LOBBY -> null;
|
|
||||||
case INVITE_SENT -> "Damas: aguardando resposta de " + controller.getOpponentName();
|
|
||||||
case PLAYING -> controller.isMyTurn()
|
|
||||||
? "Damas: sua vez contra " + controller.getOpponentName()
|
|
||||||
: "Damas: vez de " + controller.getOpponentName();
|
|
||||||
case FINISHED -> "Damas: " + controller.getNotice();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Multicast é o único transporte que funciona sempre que o peer aparece na lista, pois é
|
|
||||||
* o caminho do heartbeat. A entrega confiável fica a cargo do {@link DamasController}.
|
|
||||||
*/
|
|
||||||
private void send(DamasMessage message) {
|
|
||||||
MessageDispatcher.send(connectionManager, message, SendTarget.broadcastAll(), TransportMode.MULTICAST_UDP);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<Class<? extends Message>> getMessages() {
|
|
||||||
return List.of(DamasMessage.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void receiveMessage(Message message) {
|
|
||||||
if (message instanceof DamasMessage damasMessage) {
|
|
||||||
SwingUtilities.invokeLater(() -> controller.receive(damasMessage));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getName() {
|
|
||||||
return "Damas";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getDisplayName() {
|
|
||||||
return "Damas";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getAuthor() {
|
|
||||||
return "Felipe Chaves";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getVersion() {
|
|
||||||
return "1";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getIdentifier() {
|
|
||||||
return "Pitiupi.Damas";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,312 +0,0 @@
|
|||||||
package pitiupi.damas.control;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import pitiupi.damas.game.Move;
|
|
||||||
import pitiupi.damas.game.Side;
|
|
||||||
import pitiupi.damas.net.DamasMessage;
|
|
||||||
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.ObjectInputStream;
|
|
||||||
import java.util.ArrayDeque;
|
|
||||||
import java.util.Deque;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Random;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
class DamasControllerTest {
|
|
||||||
|
|
||||||
/** Rede simulada em multicast: todos recebem tudo, inclusive o eco do próprio envio. */
|
|
||||||
private final Deque<DamasMessage> wire = new ArrayDeque<>();
|
|
||||||
private Random loss;
|
|
||||||
private double lossRate;
|
|
||||||
private int attentionA;
|
|
||||||
private int attentionB;
|
|
||||||
private DamasController a;
|
|
||||||
private DamasController b;
|
|
||||||
private DamasController c;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
lossRate = 0;
|
|
||||||
loss = new Random(42);
|
|
||||||
a = controller("a", () -> attentionA++);
|
|
||||||
b = controller("b", () -> attentionB++);
|
|
||||||
c = controller("c", () -> { });
|
|
||||||
}
|
|
||||||
|
|
||||||
private DamasController controller(String id, Runnable onAttention) {
|
|
||||||
return new DamasController(id, () -> id.toUpperCase(), wire::add, new DamasController.Listener() {
|
|
||||||
@Override
|
|
||||||
public void onStateChanged() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onAttentionNeeded() {
|
|
||||||
onAttention.run();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Entrega o que está na rede, passando pela serialização real e descartando conforme a perda. */
|
|
||||||
private void deliver() {
|
|
||||||
for (int guard = 0; guard < 10_000 && !wire.isEmpty(); guard++) {
|
|
||||||
DamasMessage message = wire.poll();
|
|
||||||
for (DamasController target : List.of(a, b, c)) {
|
|
||||||
if (loss.nextDouble() >= lossRate) {
|
|
||||||
target.receive(roundTrip(message));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void settle() {
|
|
||||||
deliver();
|
|
||||||
for (int i = 0; i < 200; i++) {
|
|
||||||
a.tick();
|
|
||||||
b.tick();
|
|
||||||
c.tick();
|
|
||||||
deliver();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static DamasMessage roundTrip(DamasMessage message) {
|
|
||||||
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(message.toByteArray()))) {
|
|
||||||
return (DamasMessage) in.readObject();
|
|
||||||
} catch (IOException | ClassNotFoundException e) {
|
|
||||||
throw new AssertionError(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void startGame() {
|
|
||||||
assertTrue(a.invite("b", "B"));
|
|
||||||
deliver();
|
|
||||||
b.acceptInvite();
|
|
||||||
deliver();
|
|
||||||
}
|
|
||||||
|
|
||||||
private DamasController whitePlayer() {
|
|
||||||
return a.getMySide() == Side.WHITE ? a : b;
|
|
||||||
}
|
|
||||||
|
|
||||||
private DamasController blackPlayer() {
|
|
||||||
return a.getMySide() == Side.WHITE ? b : a;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void acceptedInviteStartsGameWithOppositeSides() {
|
|
||||||
startGame();
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, a.getPhase());
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, b.getPhase());
|
|
||||||
assertEquals(a.getMySide().opposite(), b.getMySide());
|
|
||||||
assertEquals("B", a.getOpponentName());
|
|
||||||
assertEquals("A", b.getOpponentName());
|
|
||||||
assertTrue(attentionA > 0 && attentionB > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void thirdPeerIgnoresTheConversation() {
|
|
||||||
startGame();
|
|
||||||
assertEquals(DamasController.Phase.LOBBY, c.getPhase());
|
|
||||||
assertNull(c.getIncomingInvite());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void declinedInviteReturnsInviterToLobby() {
|
|
||||||
a.invite("b", "B");
|
|
||||||
deliver();
|
|
||||||
b.declineInvite();
|
|
||||||
deliver();
|
|
||||||
assertEquals(DamasController.Phase.LOBBY, a.getPhase());
|
|
||||||
assertEquals("B recusou o convite.", a.getNotice());
|
|
||||||
assertNull(b.getIncomingInvite());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void cancelledInviteDisappearsFromInvitee() {
|
|
||||||
a.invite("b", "B");
|
|
||||||
deliver();
|
|
||||||
assertNotNull(b.getIncomingInvite());
|
|
||||||
a.cancelInvite();
|
|
||||||
deliver();
|
|
||||||
assertNull(b.getIncomingInvite());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void inviteWhileBusyIsAnsweredAutomatically() {
|
|
||||||
startGame();
|
|
||||||
assertTrue(c.invite("b", "B"));
|
|
||||||
deliver();
|
|
||||||
assertEquals(DamasController.Phase.LOBBY, c.getPhase());
|
|
||||||
assertEquals("B está ocupado no momento.", c.getNotice());
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, b.getPhase());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void movesReachOpponentAndAlternateTurns() {
|
|
||||||
startGame();
|
|
||||||
DamasController white = whitePlayer();
|
|
||||||
DamasController black = blackPlayer();
|
|
||||||
assertTrue(white.isMyTurn());
|
|
||||||
assertFalse(black.isMyTurn());
|
|
||||||
assertFalse(black.play(black.getGame().getLegalMoves().get(0).path()));
|
|
||||||
|
|
||||||
Move move = white.getGame().getLegalMoves().get(0);
|
|
||||||
assertTrue(white.play(move.path()));
|
|
||||||
deliver();
|
|
||||||
assertEquals(move, black.getGame().getLastMove());
|
|
||||||
assertTrue(black.isMyTurn());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void duplicatedMoveIsAppliedOnce() {
|
|
||||||
startGame();
|
|
||||||
DamasController white = whitePlayer();
|
|
||||||
DamasController black = blackPlayer();
|
|
||||||
white.play(white.getGame().getLegalMoves().get(0).path());
|
|
||||||
DamasMessage sent = wire.peek();
|
|
||||||
deliver();
|
|
||||||
black.receive(sent);
|
|
||||||
deliver();
|
|
||||||
assertTrue(black.isMyTurn());
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, black.getPhase());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void wholeGameStaysInSyncOverLossyNetwork() {
|
|
||||||
lossRate = 0.4;
|
|
||||||
a.invite("b", "B");
|
|
||||||
settle();
|
|
||||||
b.acceptInvite();
|
|
||||||
settle();
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, a.getPhase());
|
|
||||||
|
|
||||||
Random choice = new Random(7);
|
|
||||||
for (int ply = 0; ply < 400 && a.getPhase() == DamasController.Phase.PLAYING; ply++) {
|
|
||||||
DamasController mover = a.isMyTurn() ? a : b;
|
|
||||||
assertTrue(mover.isMyTurn(), "um dos jogadores deve ter a vez");
|
|
||||||
List<Move> moves = mover.getGame().getLegalMoves();
|
|
||||||
assertTrue(mover.play(moves.get(choice.nextInt(moves.size())).path()));
|
|
||||||
settle();
|
|
||||||
assertEquals(a.getGame().getLastMove(), b.getGame().getLastMove());
|
|
||||||
assertEquals(a.getGame().getTurn(), b.getGame().getTurn());
|
|
||||||
assertEquals(a.getGame().getLegalMoves(), b.getGame().getLegalMoves());
|
|
||||||
}
|
|
||||||
assertEquals(a.getPhase(), b.getPhase());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void unansweredInviteTimesOut() {
|
|
||||||
lossRate = 1;
|
|
||||||
a.invite("b", "B");
|
|
||||||
for (int i = 0; i <= DamasController.INVITE_MAX_ATTEMPTS; i++) {
|
|
||||||
a.tick();
|
|
||||||
}
|
|
||||||
assertEquals(DamasController.Phase.LOBBY, a.getPhase());
|
|
||||||
assertEquals("B não respondeu ao convite.", a.getNotice());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void illegalMoveFromOpponentEndsGameWithoutApplyingIt() {
|
|
||||||
startGame();
|
|
||||||
DamasController white = whitePlayer();
|
|
||||||
DamasController black = blackPlayer();
|
|
||||||
String blackId = black == a ? "a" : "b";
|
|
||||||
String whiteId = white == a ? "a" : "b";
|
|
||||||
String gameId = gameIdOf(white, whiteId, blackId);
|
|
||||||
black.receive(DamasMessage.move(gameId, whiteId, blackId, "X", 999, List.of(0, 63)));
|
|
||||||
assertEquals(DamasController.Phase.FINISHED, black.getPhase());
|
|
||||||
assertEquals(12, black.getGame().countPieces(Side.WHITE));
|
|
||||||
}
|
|
||||||
|
|
||||||
private String gameIdOf(DamasController white, String whiteId, String blackId) {
|
|
||||||
white.play(white.getGame().getLegalMoves().get(0).path());
|
|
||||||
DamasMessage sent = wire.poll();
|
|
||||||
wire.clear();
|
|
||||||
return sent.getGameId();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void forgedMoveFromThirdPeerIsIgnored() {
|
|
||||||
startGame();
|
|
||||||
DamasController black = blackPlayer();
|
|
||||||
String blackId = black == a ? "a" : "b";
|
|
||||||
DamasController white = whitePlayer();
|
|
||||||
white.play(white.getGame().getLegalMoves().get(0).path());
|
|
||||||
DamasMessage real = wire.poll();
|
|
||||||
wire.clear();
|
|
||||||
black.receive(DamasMessage.move(real.getGameId(), "c", blackId, "C", 1000, real.getPath()));
|
|
||||||
assertFalse(black.isMyTurn());
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, black.getPhase());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void resignFinishesBothSides() {
|
|
||||||
startGame();
|
|
||||||
a.resign();
|
|
||||||
deliver();
|
|
||||||
assertEquals(DamasController.Phase.FINISHED, a.getPhase());
|
|
||||||
assertEquals(DamasController.Phase.FINISHED, b.getPhase());
|
|
||||||
assertEquals("A desistiu. Você venceu!", b.getNotice());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void opponentLeavingMarksAwayAndReturningClearsIt() {
|
|
||||||
a.onPeersChanged(Set.of("b"));
|
|
||||||
startGame();
|
|
||||||
a.onPeersChanged(Set.of());
|
|
||||||
assertTrue(a.isOpponentAway());
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, a.getPhase());
|
|
||||||
a.onPeersChanged(Set.of("b"));
|
|
||||||
assertFalse(a.isOpponentAway());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void refusedRematchLeavesNoStaleBoard() {
|
|
||||||
startGame();
|
|
||||||
a.resign();
|
|
||||||
deliver();
|
|
||||||
a.invite("b", "B");
|
|
||||||
deliver();
|
|
||||||
b.declineInvite();
|
|
||||||
deliver();
|
|
||||||
assertEquals(DamasController.Phase.LOBBY, a.getPhase());
|
|
||||||
assertNull(a.getGame());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void cancellingRematchStillDeliversLastMessageOfPreviousGame() {
|
|
||||||
startGame();
|
|
||||||
lossRate = 1;
|
|
||||||
a.resign();
|
|
||||||
deliver();
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, b.getPhase());
|
|
||||||
a.invite("c", "C");
|
|
||||||
a.cancelInvite();
|
|
||||||
lossRate = 0;
|
|
||||||
settle();
|
|
||||||
assertEquals(DamasController.Phase.FINISHED, b.getPhase());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void rematchWorksAfterGameEnds() {
|
|
||||||
startGame();
|
|
||||||
a.resign();
|
|
||||||
deliver();
|
|
||||||
assertTrue(a.invite("b", "B"));
|
|
||||||
deliver();
|
|
||||||
assertNotNull(b.getIncomingInvite());
|
|
||||||
b.acceptInvite();
|
|
||||||
deliver();
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, a.getPhase());
|
|
||||||
assertEquals(DamasController.Phase.PLAYING, b.getPhase());
|
|
||||||
assertEquals(12, a.getGame().countPieces(Side.WHITE));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,248 +0,0 @@
|
|||||||
package pitiupi.damas.game;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
class DamasGameTest {
|
|
||||||
|
|
||||||
private static int sq(int row, int col) {
|
|
||||||
return DamasGame.square(row, col);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void initialPositionHasTwelvePiecesAndSevenMovesForWhite() {
|
|
||||||
DamasGame game = new DamasGame();
|
|
||||||
assertEquals(12, game.countPieces(Side.WHITE));
|
|
||||||
assertEquals(12, game.countPieces(Side.BLACK));
|
|
||||||
assertEquals(Side.WHITE, game.getTurn());
|
|
||||||
assertEquals(7, game.getLegalMoves().size());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void lowerLeftCornerIsDarkForWhite() {
|
|
||||||
assertTrue(DamasGame.isDarkSquare(7, 0));
|
|
||||||
assertFalse(DamasGame.isDarkSquare(7, 7));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void manCannotMoveBackwards() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"b.......",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"...w....",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........");
|
|
||||||
assertNull(game.apply(List.of(sq(4, 3), sq(5, 2))));
|
|
||||||
assertNotNull(game.apply(List.of(sq(4, 3), sq(3, 2))));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void captureIsMandatoryAndManCapturesBackwards() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"..w.....",
|
|
||||||
"...b....",
|
|
||||||
"........",
|
|
||||||
".w......",
|
|
||||||
"........");
|
|
||||||
assertEquals(1, game.getLegalMoves().size());
|
|
||||||
assertNull(game.apply(List.of(sq(6, 1), sq(5, 0))));
|
|
||||||
Move move = game.apply(List.of(sq(3, 2), sq(5, 4)));
|
|
||||||
assertEquals(List.of(sq(4, 3)), move.captured());
|
|
||||||
assertNull(game.pieceAt(sq(4, 3)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void majorityRuleForcesLongestSequence() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"...b....",
|
|
||||||
"........",
|
|
||||||
"...b.b..",
|
|
||||||
"....w...",
|
|
||||||
"........",
|
|
||||||
"........");
|
|
||||||
assertEquals(1, game.getLegalMoves().size());
|
|
||||||
assertEquals(List.of(sq(5, 4), sq(3, 2), sq(1, 4)), game.getLegalMoves().get(0).path());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void capturedPiecesCannotBeJumpedTwiceAndOriginCountsAsEmpty() {
|
|
||||||
// Ciclo de quatro saltos que termina na origem, sem repetir a primeira peça.
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
".b.b....",
|
|
||||||
"........",
|
|
||||||
".b.b....",
|
|
||||||
"..w.....",
|
|
||||||
"........",
|
|
||||||
"........");
|
|
||||||
assertEquals(2, game.getLegalMoves().size());
|
|
||||||
Move move = game.apply(List.of(sq(5, 2), sq(3, 4), sq(1, 2), sq(3, 0), sq(5, 2)));
|
|
||||||
assertEquals(4, move.captured().size());
|
|
||||||
assertEquals(0, game.countPieces(Side.BLACK));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void flyingKingMayLandOnAnySquareBehindTheCapturedPiece() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"...b....",
|
|
||||||
"........",
|
|
||||||
".W......",
|
|
||||||
"........");
|
|
||||||
assertEquals(4, game.getLegalMoves().size());
|
|
||||||
for (Move move : game.getLegalMoves()) {
|
|
||||||
assertEquals(List.of(sq(4, 3)), move.captured());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void flyingKingMovesAnyDistanceButNotOverOwnPieces() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"..w.....",
|
|
||||||
"........",
|
|
||||||
"W......b");
|
|
||||||
assertNotNull(game.getLegalMoves().stream()
|
|
||||||
.filter(m -> m.from() == sq(7, 0)).findAny().orElse(null));
|
|
||||||
assertTrue(game.getLegalMoves().stream().noneMatch(m -> m.from() == sq(7, 0) && m.to() == sq(4, 3)));
|
|
||||||
|
|
||||||
DamasGame open = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"W......b");
|
|
||||||
assertNotNull(open.apply(List.of(sq(7, 0), sq(0, 7))));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void manReachingLastRowPromotes() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"..w.....",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"b.......");
|
|
||||||
game.apply(List.of(sq(1, 2), sq(0, 1)));
|
|
||||||
assertEquals(Piece.WHITE_KING, game.pieceAt(sq(0, 1)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void manPassingLastRowDuringCaptureDoesNotPromote() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"..b.b...",
|
|
||||||
".w......",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"...b....");
|
|
||||||
Move move = game.getLegalMoves().get(0);
|
|
||||||
assertEquals(List.of(sq(2, 1), sq(0, 3), sq(2, 5)), move.path());
|
|
||||||
game.apply(move.path());
|
|
||||||
assertEquals(Piece.WHITE_MAN, game.pieceAt(sq(2, 5)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void playerWithoutMovesLoses() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
"........",
|
|
||||||
"..b.....",
|
|
||||||
".w......",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........");
|
|
||||||
game.apply(List.of(sq(2, 1), sq(0, 3)));
|
|
||||||
assertEquals(GameResult.WHITE_WINS, game.getResult());
|
|
||||||
assertTrue(game.getLegalMoves().isEmpty());
|
|
||||||
assertNull(game.apply(List.of(sq(0, 3), sq(1, 2))));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void twentyQuietKingMovesEachIsADraw() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
".B......",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"W.......");
|
|
||||||
int[][] whiteSquares = {{7, 0}, {6, 1}};
|
|
||||||
int[][] blackSquares = {{0, 1}, {1, 0}};
|
|
||||||
for (int ply = 0; ply < 40; ply++) {
|
|
||||||
assertEquals(GameResult.IN_PROGRESS, game.getResult());
|
|
||||||
int[][] squares = ply % 2 == 0 ? whiteSquares : blackSquares;
|
|
||||||
int[] from = squares[ply % 4 < 2 ? 0 : 1];
|
|
||||||
int[] to = squares[ply % 4 < 2 ? 1 : 0];
|
|
||||||
assertNotNull(game.apply(List.of(sq(from[0], from[1]), sq(to[0], to[1]))));
|
|
||||||
}
|
|
||||||
assertEquals(GameResult.DRAW, game.getResult());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void manMoveResetsTheDrawCount() {
|
|
||||||
DamasGame game = DamasGame.fromRows(Side.WHITE,
|
|
||||||
".B......",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"........",
|
|
||||||
"w.......",
|
|
||||||
"........",
|
|
||||||
"..W.....");
|
|
||||||
for (int ply = 0; ply < 38; ply++) {
|
|
||||||
boolean out = ply % 4 < 2;
|
|
||||||
if (ply % 2 == 0) {
|
|
||||||
game.apply(out ? List.of(sq(7, 2), sq(6, 3)) : List.of(sq(6, 3), sq(7, 2)));
|
|
||||||
} else {
|
|
||||||
game.apply(out ? List.of(sq(0, 1), sq(1, 2)) : List.of(sq(1, 2), sq(0, 1)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assertNotNull(game.apply(List.of(sq(5, 0), sq(4, 1))));
|
|
||||||
// Sem zerar, estes dois lances de dama completariam os 40 e dariam empate.
|
|
||||||
assertNotNull(game.apply(List.of(sq(1, 2), sq(0, 1))));
|
|
||||||
assertNotNull(game.apply(List.of(sq(6, 3), sq(7, 2))));
|
|
||||||
assertEquals(GameResult.IN_PROGRESS, game.getResult());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void illegalPathIsRejectedWithoutChangingTurn() {
|
|
||||||
DamasGame game = new DamasGame();
|
|
||||||
assertNull(game.apply(List.of(sq(5, 0), sq(3, 2))));
|
|
||||||
assertEquals(Side.WHITE, game.getTurn());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+1
-1
@@ -238,7 +238,7 @@ link_plugins_from_selection() {
|
|||||||
local mode="${1:-link}"
|
local mode="${1:-link}"
|
||||||
local id dir jar_rel link_name src_abs
|
local id dir jar_rel link_name src_abs
|
||||||
mkdir -p "${PLUGINS_DIR}"
|
mkdir -p "${PLUGINS_DIR}"
|
||||||
rm -f "${PLUGINS_DIR}/"*.jar
|
find "${PLUGINS_DIR}" -maxdepth 1 -type l -name '*.jar' -delete
|
||||||
|
|
||||||
while IFS= read -r id; do
|
while IFS= read -r id; do
|
||||||
[[ -z "$id" ]] && continue
|
[[ -z "$id" ]] && continue
|
||||||
|
|||||||
Reference in new issue
Block a user