ミラー

諏訪子 <suwako@076.moe>、2025-12-28 05:21
コミット 4442ef77d3de4eaf5d46ad01e45c0ceb73b5ae10 ・ファイルを見る

10個のファイル、+1132 -0

追加 .gitignore
@@ -0,0 +1,2 @@
1+.svn
2+hexagon
追加 CHANGELOG.md
@@ -0,0 +1,11 @@
1+## 1.1.0 (2025年12月28日)
2+* PgUp・PgDownで使ってページを動ける様に
3+* ^、0、又はHOME、及び$又はENDキーで使って同じ行列で最初や最後のHEXや文字に移動ける様に
4+* CTRL + Cを無効に
5+* OpenBSDでのコンパイラ報告の修正
6+* 逆検索でNとnキーの修正
7+* トップバーの追加
8+* ファイルヘッダーを青色で表示する
9+
10+## 1.0.0 (2025年04月20日)
11+* 最初リリース
追加 LICENSE.md
@@ -0,0 +1,32 @@
1+Copyright (c) 2025 テクニカル諏訪子
2+
3+Permission is hereby granted to any person obtaining a copy of the software
4+Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
5+sublicense, and/or sell copies of the Software, subject to the following conditions:
6+
7+ 1. **Origin Attribution**:
8+ - You must not misrepresent the origin of the Software; you must not claim
9+ you created the original Software.
10+ - If the Software is used in a product, you must either:
11+ a. Provide clear attribution in the product's documentation, user interface,
12+ or other visible areas, **OR**
13+ b. Pay the original developers a fee they specify in writing.
14+ 2. **Usage Restriction**:
15+ - The Software, or any derivative works, dependencies, or libraries
16+ incorporating it, must not be used for censorship or to suppress freedom of
17+ speech, expression, or creativity. Prohibited uses include, but are not
18+ limited to:
19+ - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
20+ ideas, or objective reality.
21+ - Tools or systems designed to restrict access to information or
22+ artistic works.
23+ 3. **Notice Preservation**:
24+ - This license and the above copyright notice must remain intact in all copies
25+ of the source code.
26+
27+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
28+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
29+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
30+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
31+CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
32+OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
追加 Makefile
@@ -0,0 +1,82 @@
1+UNAME_M != uname -m
2+UNAME_S != uname -s
3+OS = $(UNAME_S)
4+ARCH = ${UNAME_M}
5+
6+.if ${UNAME_S} == "OpenBSD"
7+OS = openbsd
8+.elif ${UNAME_S} == "NetBSD"
9+OS = netbsd
10+.elif ${UNAME_S} == "FreeBSD"
11+OS = freebsd
12+.elif ${UNAME_S} == "Dragonfly"
13+OS = dragonfly
14+.elif ${UNAME_S} == "Linux"
15+OS = linux
16+.elif ${UNAME_S} == "Haiku"
17+OS = haiku
18+.elif ${UNAME_S} == "Darwin"
19+OS = macos
20+.endif
21+
22+.if ${UNAME_M} == "x86_64"
23+ARCH = amd64
24+.elif ${UNAME_M} == "macppc"
25+ARCH = powerpc
26+.endif
27+
28+NAME = hexagon
29+VERSION = 1.0.0
30+
31+PREFIX = /usr/local
32+.if ${OS} == "linux"
33+PREFIX = /usr
34+.elif ${OS} == "haiku"
35+PREFIX = /boot/home/config/non-packaged
36+.endif
37+
38+CFLAGS = -I/usr/include -I/usr/local/include -I/usr/pkg/include\
39+ -I/usr/pkg/include/ncurses -I/boot/system/develop/headers\
40+ -L/usr/lib -L/usr/local/lib -L/usr/pkg/lib -L/boot/system/develop/lib
41+
42+.if ${UNAME_S} == "NetBSD"
43+LDFLAGS = -lncurses
44+.else
45+LDFLAGS = -lncursesw
46+.endif
47+
48+CC = c++
49+FILES = main.cc src/*.cc
50+
51+all:
52+ ${CC} -O3 ${CFLAGS} -o ${NAME} ${FILES} -std=c++17 -static ${LDFLAGS}
53+ strip ${NAME}
54+
55+debug:
56+ ${CC} -g ${CFLAGS} -o ${NAME} ${FILES} -std=c++17 ${LDFLAGS}
57+
58+install:
59+ cp -rf ${NAME} ${PREFIX}/bin
60+
61+uninstall:
62+ rm -rf ${PREFIX}/bin/${NAME}
63+
64+clean:
65+ rm -rf ${NAME} *.core
66+
67+dist:
68+ mkdir -p ${NAME}-${VERSION} release/src
69+ cp -R LICENSE.md Makefile CHANGELOG.md README.md main.cc src make-mingw.sh\
70+ ${NAME}-${VERSION}
71+ tar zcfv release/src/${NAME}-${VERSION}.tar.gz ${NAME}-${VERSION}
72+ rm -rf ${NAME}-${VERSION}
73+
74+release:
75+ mkdir -p release/bin/${VERSION}/${OS}/${ARCH}
76+ cp -rf ${NAME} release/bin/${VERSION}/${OS}/${ARCH}
77+
78+publish:
79+ rsync -rtvzP release/bin/${VERSION} 192.168.0.143:/zroot/repo/bin/${NAME}
80+ rsync -rtvzP release/src/* 192.168.0.143:/zroot/repo/src/${NAME}
81+
82+.PHONY: all debug install uninstall clean dist release publish
追加 README.md
@@ -0,0 +1,29 @@
1+# Hexagon
2+VIMキーバインドでのHEXエディター
3+
4+## インストールする方法 | Installation
5+### BSD
6+```sh
7+make
8+doas make install
9+```
10+
11+### Linux/macOS
12+```sh
13+bmake
14+sudo bmake install
15+```
16+
17+### Haiku
18+```sh
19+bmake
20+bmake install
21+```
22+
23+### Windows
24+```sh
25+chmod +x make-mingw.sh
26+./make-mingw.sh
27+```
28+
29+![](スクショ.png)
追加 main.cc
@@ -0,0 +1,20 @@
1+#include <iostream>
2+
3+#include "src/hexeditor.hh"
4+
5+int main(int argc, char *argv[]) {
6+ if (argc != 2) {
7+ std::cerr << "usage: hexagon <filename>\n";
8+ return 1;
9+ }
10+
11+ try {
12+ HexEditor editor(argv[1]);
13+ editor.run();
14+ } catch (const std::exception &e) {
15+ std::cerr << "エラー: " << e.what() << "\n";
16+ return 1;
17+ }
18+
19+ return 0;
20+}
追加 make-mingw.sh
@@ -0,0 +1,5 @@
1+#!/bin/sh
2+
3+g++ -O3 -o hexagon.exe -I/mingw64/include -L/mingw64/lib main.cc src/*.cc\
4+ -std=c++17 -static -lpdcurses -lgdi32 -lcomdlg32 -lwinmm -luser32 -lwinpthread\
5+ -lstdc++ -mwindows
@@ -0,0 +1,868 @@
1+#include <algorithm>
2+#include <csignal>
3+#include <fstream>
4+#include <iomanip>
5+#include <iostream>
6+#include <set>
7+#include <sstream>
8+
9+#include <locale.h>
10+#include <wchar.h>
11+#ifdef _WIN32
12+#include <windows.h>
13+#endif
14+
15+#include "hexeditor.hh"
16+
17+#ifdef _WIN32
18+static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) {
19+ if (dwCtrlType == CTRL_C_EVENT) return TRUE;
20+ return FALSE;
21+}
22+#endif
23+
24+const std::vector<HexEditor::FileSignature> HexEditor::signatures = {
25+ {{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, "PNG"},
26+ {{ 0xFF, 0xD8 }, "JPEG"},
27+ {{ 0x7F, 0x45, 0x4C, 0x46 }, "ELF"},
28+ {{ 0x4D, 0x5A }, "PE"},
29+ {{ 0x25, 0x50, 0x44, 0x46 }, "PDF"},
30+ {{ 0x67, 0x69, 0x6D, 0x70, 0x20, 0x78, 0x63, 0x66 }, "GIMP XCF"},
31+ {{ 0x1A, 0x45, 0xDF, 0xA3, 0x9F, 0x42, 0x86, 0x81, 0x01, 0x42,
32+ 0xF7, 0x81, 0x01, 0x42, 0xF2, 0x81, 0x04, 0x42, 0xF3, 0x81,
33+ 0x08, 0x42, 0x82, 0x84, 0x77, 0x65, 0x62, 0x6D, 0x42, 0x87,
34+ 0x81, 0x04, 0x42, 0x85, 0x81, 0x02, 0x18, 0x53, 0x80, 0x67,
35+ 0x01, 0x00, 0x00, 0x00, 0x01 }, "WEBM"},
36+ {{ 0x1A, 0x45, 0xDF, 0xA3, 0xA3, 0x42, 0x86, 0x81, 0x01, 0x42,
37+ 0xF7, 0x81, 0x01, 0x42, 0xF2, 0x81, 0x04, 0x42, 0xF3, 0x81,
38+ 0x08, 0x42, 0x82, 0x88, 0x6D, 0x61, 0x74, 0x72, 0x6F, 0x73,
39+ 0x6B, 0x61, 0x42, 0x87, 0x81, 0x04, 0x42, 0x85, 0x81, 0x02,
40+ 0x18, 0x53, 0x80, 0x67, 0x01, 0x00, 0x00, 0x00}, "Matroska"},
41+ {{ 0x52, 0x49, 0x46, 0x46 }, "Waveform"},
42+};
43+
44+HexEditor::HexEditor(const std::string &filename)
45+ : curPos(0), dpOffset(0), bpr(16),
46+ statusMode(Status_Normal), modified(false),
47+ running(true),
48+ lastSearchDir(Direction_Forward),
49+ headerLen(0), headerType("") {
50+ // SIGINT (CTRL + C)を無効に
51+#ifdef _WIN32
52+ SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
53+#else
54+ std::signal(SIGINT, SIG_IGN);
55+#endif
56+
57+ setlocale(LC_ALL, "");
58+
59+ // ncurses
60+ initscr();
61+ clearok(stdscr, TRUE);
62+ cbreak();
63+ noecho();
64+ keypad(stdscr, TRUE);
65+ raw();
66+ start_color();
67+
68+ init_pair(1, COLOR_BLACK, COLOR_WHITE); // カーソル
69+ init_pair(2, COLOR_BLACK, COLOR_GREEN); // 変更
70+ init_pair(3, COLOR_BLACK, COLOR_MAGENTA); // 普通
71+ init_pair(4, COLOR_BLACK, COLOR_CYAN); // コマンド
72+ init_pair(5, COLOR_BLACK, COLOR_YELLOW); // 検索
73+ init_pair(6, COLOR_BLACK, COLOR_YELLOW); // 検索ハイライト
74+ init_pair(7, COLOR_BLACK, COLOR_RED); // エラー
75+ init_pair(8, COLOR_WHITE, COLOR_BLACK); // デフォルト
76+ init_pair(9, COLOR_CYAN, COLOR_BLACK); // ファイルヘッダー
77+ refresh();
78+
79+ // ファイルをバッファーに読み込む
80+ std::ifstream file(filename, std::ios::binary);
81+ if (!file) {
82+ endwin();
83+ throw std::runtime_error("ファイルを開くに失敗");
84+ }
85+
86+ buf.assign((std::istreambuf_iterator<char>(file)), {});
87+ file.close();
88+
89+ if (buf.empty()) {
90+ endwin();
91+ throw std::runtime_error("ファイルが空です");
92+ }
93+
94+ fname = filename;
95+
96+ // ファイルヘッダー
97+ for (const auto &sig : signatures) {
98+ if (buf.size() >= sig.signature.size()) {
99+ bool match = true;
100+ for (size_t i = 0; i < sig.signature.size(); ++i) {
101+ if (buf[i] != sig.signature[i]) {
102+ match = false;
103+ break;
104+ }
105+ }
106+
107+ if (match) {
108+ headerLen = sig.signature.size();
109+ headerType = sig.type;
110+ break;
111+ }
112+ }
113+ }
114+
115+ // ウィンドウを作成する
116+ getmaxyx(stdscr, rows, cols);
117+ if (rows < 4 || cols < 20) {
118+ endwin();
119+ throw std::runtime_error("ターミナルが小さ過ぎます");
120+ }
121+
122+ bpr = std::min<size_t>(16, (cols / 2 - 10) / 4);
123+ hexPanel = newwin(rows - 3, cols / 2, 1, 0);
124+ asciiPanel = newwin(rows - 3, cols / 2, 1, cols / 2);
125+ scrollok(hexPanel, TRUE);
126+ scrollok(asciiPanel, TRUE);
127+ wattrset(hexPanel, COLOR_PAIR(8));
128+ wattrset(asciiPanel, COLOR_PAIR(8));
129+}
130+
131+HexEditor::~HexEditor() {
132+ delwin(hexPanel);
133+ delwin(asciiPanel);
134+ endwin();
135+}
136+
137+void HexEditor::highlightcol(size_t i, size_t row, uint8_t byte) {
138+ wattron(hexPanel, COLOR_PAIR(1));
139+ mvwprintw(hexPanel, row, 10 + i * 3, "%02x", byte);
140+ wattroff(hexPanel, COLOR_PAIR(1));
141+
142+ wattron(asciiPanel, COLOR_PAIR(1));
143+ mvwaddch(asciiPanel, row, i, std::isprint(byte) ? byte : '.');
144+ wattroff(asciiPanel, COLOR_PAIR(1));
145+}
146+
147+void HexEditor::topbar() {
148+ int colorPair = 3;
149+ std::string status = "Hexagon 1.1.0";
150+ if (!headerType.empty()) status += " | FILETYPE: " + headerType;
151+
152+ std::wstring wstatus(status.begin(), status.end());
153+ wattron(stdscr, COLOR_PAIR(colorPair));
154+ mvprintw(0, 0, "%s", status.c_str());
155+ for (int i = status.length(); i < cols; ++i) {
156+ mvaddch(0, i, ' ');
157+ }
158+
159+ wattroff(stdscr, COLOR_PAIR(colorPair));
160+}
161+
162+void HexEditor::statusbar() {
163+ int colorPair;
164+ switch (statusMode) {
165+ case Status_Replace: colorPair = 2; break;
166+ case Status_Normal: colorPair = 3; break;
167+ case Status_Command: colorPair = 4; break;
168+ case Status_Search: colorPair = 5; break;
169+ case Status_Error: colorPair = 7; break;
170+ }
171+
172+ std::string status;
173+ if (statusMode == Status_Normal || statusMode == Status_Error) {
174+ status = "FILE: " + fname;
175+ status += " | OFFSET: 0x" + std::to_string(curPos);
176+ status += " | FILE SIZE: " + std::to_string(buf.size()) + " B";
177+ if (!lastSearch.empty()) {
178+ status += " | SEARCH: " + lastSearch;
179+ } else if (!lastHexSearch.empty()) {
180+ std::ostringstream hexSearch;
181+ for (size_t i = 0; i < lastHexSearch.size(); ++i) {
182+ if (i > 0) hexSearch << " ";
183+ hexSearch << std::hex << std::setfill('0') << std::setw(2)
184+ << (int)lastHexSearch[i];
185+ }
186+ status += " | SEARCH: " + hexSearch.str();
187+ }
188+ status += (modified ? " [+]" : "");
189+ if (statusMode == Status_Error) status += " | ERROR: " + statusText;
190+ else status += !statusText.empty() ? " | " + statusText : "";
191+ } else if (statusMode == Status_Command) {
192+ status = ":" + statusText;
193+ } else if (statusMode == Status_Search) {
194+ status = (lastSearchDir == Direction_Forward ? "/" : "?") + statusText;
195+ } else if (statusMode == Status_Replace) {
196+ status = "-- REPLACE --";
197+ }
198+
199+ std::wstring wstatus(status.begin(), status.end());
200+ wattron(stdscr, COLOR_PAIR(colorPair));
201+ mvprintw(rows - 1, 0, "%s", status.c_str());
202+ for (int i = status.length(); i < cols; ++i) {
203+ mvaddch(rows - 1, i, ' ');
204+ }
205+
206+ wattroff(stdscr, COLOR_PAIR(colorPair));
207+}
208+
209+void HexEditor::render() {
210+ werase(hexPanel);
211+ werase(asciiPanel);
212+
213+ getmaxyx(stdscr, rows, cols);
214+ size_t maxRows = rows - 3;
215+
216+ topbar();
217+
218+ std::set<size_t> matchBytes;
219+ if (!lastSearch.empty()) {
220+ for (size_t i = 0; i <= buf.size() - lastSearch.size(); ++i) {
221+ bool match = true;
222+ for (size_t j = 0; j < lastSearch.size(); ++j) {
223+ if (buf[i + j] != static_cast<uint8_t>(lastSearch[j])) {
224+ match = false;
225+ break;
226+ }
227+ }
228+
229+ if (match) {
230+ for (size_t j = 0; j < lastSearch.size(); ++j) {
231+ matchBytes.insert(i + j);
232+ }
233+ }
234+ }
235+ } else if (!lastHexSearch.empty()) {
236+ for (size_t i = 0; i <= buf.size() - lastHexSearch.size(); ++i) {
237+ bool match = true;
238+ for (size_t j = 0; j < lastHexSearch.size(); ++j) {
239+ if (buf[i + j] != lastHexSearch[j]) {
240+ match = false;
241+ break;
242+ }
243+ }
244+
245+ if (match) {
246+ for (size_t j = 0; j < lastHexSearch.size(); ++j) {
247+ matchBytes.insert(i + j);
248+ }
249+ }
250+ }
251+ }
252+
253+ // HEXとASCIIの表示
254+ for (size_t row = 0; row < maxRows; ++row) {
255+ size_t offset = dpOffset + row * bpr;
256+ if (offset >= buf.size()) break;
257+
258+ std::ostringstream hexLine, asciiLine;
259+ hexLine << std::hex << std::setfill('0') << std::setw(8) << offset << ": ";
260+ mvwprintw(hexPanel, row, 0, "%s", hexLine.str().c_str());
261+
262+ // HEXとASCIIのデータ
263+ for (size_t i = 0; i < bpr && (offset + i) < buf.size(); ++i) {
264+ uint8_t byte = buf[offset + i];
265+ bool isMatch = matchBytes.count(offset + i) > 0;
266+ bool isHeader = (offset + i) < headerLen;
267+
268+ if (offset + i == curPos) {
269+ highlightcol(i, row, byte);
270+ } else if (isHeader) {
271+ wattron(hexPanel, COLOR_PAIR(9));
272+ mvwprintw(hexPanel, row, 10 + i * 3, "%02x", byte);
273+ wattroff(hexPanel, COLOR_PAIR(9));
274+
275+ wattron(asciiPanel, COLOR_PAIR(9));
276+ mvwaddch(asciiPanel, row, i, std::isprint(byte) ? byte : '.');
277+ wattroff(asciiPanel, COLOR_PAIR(9));
278+ } else if (isMatch) {
279+ wattron(hexPanel, COLOR_PAIR(6));
280+ mvwprintw(hexPanel, row, 10 + i * 3, "%02x", byte);
281+ wattroff(hexPanel, COLOR_PAIR(6));
282+
283+ wattron(asciiPanel, COLOR_PAIR(6));
284+ mvwaddch(asciiPanel, row, i, std::isprint(byte) ? byte : '.');
285+ wattroff(asciiPanel, COLOR_PAIR(6));
286+ } else {
287+ wattron(hexPanel, COLOR_PAIR(8));
288+ mvwprintw(hexPanel, row, 10 + i * 3, "%02x", byte);
289+ wattroff(hexPanel, COLOR_PAIR(8));
290+
291+ wattron(asciiPanel, COLOR_PAIR(8));
292+ mvwaddch(asciiPanel, row, i, std::isprint(byte) ? byte : '.');
293+ wattroff(asciiPanel, COLOR_PAIR(8));
294+ }
295+ }
296+ }
297+
298+ statusbar();
299+
300+ redrawwin(hexPanel);
301+ redrawwin(asciiPanel);
302+ wrefresh(hexPanel);
303+ wrefresh(asciiPanel);
304+ refresh();
305+}
306+
307+void HexEditor::findNextMatch() {
308+ if (lastSearch.empty() && lastHexSearch.empty()) return;
309+
310+ size_t searchSize = lastSearch.empty() ? lastHexSearch.size() : lastSearch.size();
311+ size_t startPos = curPos + 1;
312+
313+ for (size_t i = startPos; i <= buf.size() - searchSize; ++i) {
314+ bool match = true;
315+ if (!lastSearch.empty()) {
316+ for (size_t j = 0; j < lastSearch.size(); ++j) {
317+ if (buf[i + j] != static_cast<uint8_t>(lastSearch[j])) {
318+ match = false;
319+ break;
320+ }
321+ }
322+ } else {
323+ for (size_t j = 0; j < lastHexSearch.size(); ++j) {
324+ if (buf[i + j] != lastHexSearch[j]) {
325+ match = false;
326+ break;
327+ }
328+ }
329+ }
330+ if (match) {
331+ curPos = i;
332+ dpOffset = curPos - (curPos % bpr);
333+ render();
334+ return;
335+ }
336+ }
337+
338+ for (size_t i = 0; i < startPos && i <= buf.size() - searchSize; ++i) {
339+ bool match = true;
340+ if (!lastSearch.empty()) {
341+ for (size_t j = 0; j < lastSearch.size(); ++j) {
342+ if (buf[i + j] != static_cast<uint8_t>(lastSearch[j])) {
343+ match = false;
344+ break;
345+ }
346+ }
347+ } else {
348+ for (size_t j = 0; j < lastHexSearch.size(); ++j) {
349+ if (buf[i + j] != lastHexSearch[j]) {
350+ match = false;
351+ break;
352+ }
353+ }
354+ }
355+ if (match) {
356+ curPos = i;
357+ dpOffset = curPos - (curPos % bpr);
358+ render();
359+ return;
360+ }
361+ }
362+}
363+
364+void HexEditor::findPrevMatch() {
365+ if (lastSearch.empty() && lastHexSearch.empty()) return;
366+
367+ size_t searchSize = lastSearch.empty() ? lastHexSearch.size() : lastSearch.size();
368+ size_t startPos = curPos > 0 ? curPos - 1 : buf.size() - searchSize;
369+
370+ for (size_t i = startPos + 1; i > 0; --i) {
371+ size_t pos = i - 1;
372+ if (pos > buf.size() - searchSize) continue;
373+ bool match = true;
374+ if (!lastSearch.empty()) {
375+ for (size_t j = 0; j < lastSearch.size(); ++j) {
376+ if (buf[pos + j] != static_cast<uint8_t>(lastSearch[j])) {
377+ match = false;
378+ break;
379+ }
380+ }
381+ } else {
382+ for (size_t j = 0; j < lastHexSearch.size(); ++j) {
383+ if (buf[pos + j] != lastHexSearch[j]) {
384+ match = false;
385+ break;
386+ }
387+ }
388+ }
389+ if (match) {
390+ curPos = pos;
391+ dpOffset = curPos - (curPos % bpr);
392+ render();
393+ return;
394+ }
395+ }
396+
397+ for (size_t i = buf.size() - searchSize; i > startPos; --i) {
398+ bool match = true;
399+ if (!lastSearch.empty()) {
400+ for (size_t j = 0; j < lastSearch.size(); ++j) {
401+ if (buf[i + j] != static_cast<uint8_t>(lastSearch[j])) {
402+ match = false;
403+ break;
404+ }
405+ }
406+ } else {
407+ for (size_t j = 0; j < lastHexSearch.size(); ++j) {
408+ if (buf[i + j] != lastHexSearch[j]) {
409+ match = false;
410+ break;
411+ }
412+ }
413+ }
414+ if (match) {
415+ curPos = i;
416+ dpOffset = curPos - (curPos % bpr);
417+ render();
418+ return;
419+ }
420+ }
421+}
422+
423+void HexEditor::handleCommand() {
424+ statusMode = Status_Command;
425+ statusText.clear();
426+ render();
427+
428+ int ch;
429+ while ((ch = getch()) != '\n' && ch != 27) {
430+#ifdef _WIN32
431+ if (ch == KEY_BACKSPACE || ch == 8) {
432+#else
433+ if (ch == KEY_BACKSPACE || ch == 127) {
434+#endif
435+ if (!statusText.empty()) {
436+ statusText.pop_back();
437+ }
438+ } else if (ch >= 32 && ch <= 126) { // 書き込める文字
439+ statusText += ch;
440+ }
441+
442+ render();
443+ }
444+
445+ if (ch == 27) { // Esc
446+ statusMode = Status_Normal;
447+ statusText.clear();
448+ render();
449+ return;
450+ }
451+
452+ bool isCommand = false;
453+ if (statusText == "w") {
454+ handleSave();
455+ isCommand = true;
456+ } else if (statusText == "q") {
457+ handleQuit(false);
458+ isCommand = true;
459+ } else if (statusText == "wq") {
460+ handleSave();
461+ handleQuit(false);
462+ isCommand = true;
463+ } else if (statusText == "q!") {
464+ handleQuit(true);
465+ isCommand = true;
466+ } else if (statusText == "wq!") {
467+ handleSave();
468+ handleQuit(true);
469+ isCommand = true;
470+ } else if (statusText == "noh") {
471+ lastSearch = "";
472+ isCommand = true;
473+ } else {
474+ statusMode = Status_Error;
475+ statusText.clear();
476+ }
477+
478+ if (isCommand) {
479+ statusMode = Status_Normal;
480+ statusText.clear();
481+ }
482+ render();
483+}
484+
485+void HexEditor::handleQuit(bool force) {
486+ if (force || (!force && !modified)) {
487+ running = false;
488+ } else {
489+ statusMode = Status_Error;
490+ statusText.clear();
491+ render();
492+ }
493+}
494+
495+void HexEditor::handleSave() {
496+ std::ofstream file(fname, std::ios::binary);
497+ if (file) {
498+ file.write(reinterpret_cast<const char *>(buf.data()), buf.size());
499+ file.close();
500+ modified = false;
501+ statusText = "保存済み";
502+ }
503+}
504+
505+void HexEditor::handleSearch() {
506+ statusMode = Status_Search;
507+ lastSearchDir = Direction_Forward;
508+ statusText.clear();
509+ render();
510+
511+ int ch;
512+ while ((ch = getch()) != '\n' && ch != 27) {
513+#ifdef _WIN32
514+ if (ch == KEY_BACKSPACE || ch == 8) {
515+#else
516+ if (ch == KEY_BACKSPACE || ch == 127) {
517+#endif
518+ if (!statusText.empty()) statusText.pop_back();
519+ } else if (ch >= 32 && ch <= 126) { // 書き込める文字
520+ statusText += ch;
521+ }
522+
523+ render();
524+ }
525+
526+ if (ch == 27) { // Esc
527+ statusMode = Status_Normal;
528+ statusText.clear();
529+ render();
530+ return;
531+ }
532+
533+ lastSearch.clear();
534+ lastHexSearch.clear();
535+ matchOff.clear();
536+
537+ std::istringstream iss(statusText);
538+ std::string hexByte;
539+ bool isHexSearch = true;
540+ std::vector<uint8_t> hexSearch;
541+ while (iss >> hexByte) {
542+ if (hexByte.size() != 2 || !std::all_of(hexByte.begin(), hexByte.end(), [](char c) { return std::isxdigit(c); })) {
543+ isHexSearch = false;
544+ break;
545+ }
546+ try {
547+ hexSearch.push_back(static_cast<uint8_t>(std::stoul(hexByte, nullptr, 16)));
548+ } catch (...) {
549+ isHexSearch = false;
550+ break;
551+ }
552+ }
553+
554+ if (isHexSearch && !hexSearch.empty()) { // HEX検索
555+ lastHexSearch = hexSearch;
556+ for (size_t i = curPos + 1; i <= buf.size() - lastHexSearch.size(); ++i) {
557+ bool match = true;
558+ for (size_t j = 0; j < lastHexSearch.size(); ++j) {
559+ if (buf[i + j] != lastHexSearch[j]) {
560+ match = false;
561+ break;
562+ }
563+ }
564+ if (match) {
565+ matchOff.push_back(i);
566+ curPos = i;
567+ dpOffset = curPos - (curPos % bpr);
568+ break;
569+ }
570+ }
571+ } else { // ASCII検索
572+ lastSearch = statusText;
573+ for (size_t i = curPos + 1; i <= buf.size() - lastSearch.size(); ++i) {
574+ bool match = true;
575+ for (size_t j = 0; j < lastSearch.size(); ++j) {
576+ if (buf[i + j] != static_cast<uint8_t>(lastSearch[j])) {
577+ match = false;
578+ break;
579+ }
580+ }
581+ if (match) {
582+ matchOff.push_back(i);
583+ curPos = i;
584+ dpOffset = curPos - (curPos % bpr);
585+ break;
586+ }
587+ }
588+ }
589+
590+ statusMode = Status_Normal;
591+ statusText.clear();
592+ render();
593+}
594+
595+void HexEditor::handleReverseSearch() {
596+ statusMode = Status_Search;
597+ lastSearchDir = Direction_Reverse;
598+ statusText.clear();
599+ render();
600+
601+ int ch;
602+ while ((ch = getch()) != '\n' && ch != 27) {
603+#ifdef _WIN32
604+ if (ch == KEY_BACKSPACE || ch == 8) {
605+#else
606+ if (ch == KEY_BACKSPACE || ch == 127) {
607+#endif
608+ if (!statusText.empty()) statusText.pop_back();
609+ } else if (ch >= 32 && ch <= 126) {
610+ statusText += ch;
611+ }
612+ render();
613+ }
614+
615+ if (ch == 27) { // Esc
616+ statusMode = Status_Normal;
617+ statusText.clear();
618+ render();
619+ return;
620+ }
621+
622+ lastSearch.clear();
623+ lastHexSearch.clear();
624+ matchOff.clear();
625+
626+ std::istringstream iss(statusText);
627+ std::string hexByte;
628+ bool isHexSearch = true;
629+ std::vector<uint8_t> hexSearch;
630+ while (iss >> hexByte) {
631+ if (hexByte.size() != 2 || !std::all_of(hexByte.begin(), hexByte.end(), [](char c) { return std::isxdigit(c); })) {
632+ isHexSearch = false;
633+ break;
634+ }
635+ try {
636+ hexSearch.push_back(static_cast<uint8_t>(std::stoul(hexByte, nullptr, 16)));
637+ } catch (...) {
638+ isHexSearch = false;
639+ break;
640+ }
641+ }
642+
643+ if (isHexSearch && !hexSearch.empty()) {
644+ lastHexSearch = hexSearch;
645+ size_t startPos = curPos > 0 ? curPos - 1 : buf.size() - lastHexSearch.size();
646+ for (size_t i = startPos + 1; i > 0; --i) {
647+ size_t pos = i - 1;
648+ if (pos > buf.size() - lastHexSearch.size()) continue;
649+ bool match = true;
650+ for (size_t j = 0; j < lastHexSearch.size(); ++j) {
651+ if (buf[pos + j] != lastHexSearch[j]) {
652+ match = false;
653+ break;
654+ }
655+ }
656+ if (match) {
657+ matchOff.push_back(pos);
658+ curPos = pos;
659+ dpOffset = curPos - (curPos % bpr);
660+ break;
661+ }
662+ }
663+ } else {
664+ lastSearch = statusText;
665+ size_t startPos = curPos > 0 ? curPos - 1 : buf.size() - lastSearch.size();
666+ for (size_t i = startPos + 1; i > 0; --i) {
667+ size_t pos = i - 1;
668+ if (pos > buf.size() - lastSearch.size()) continue;
669+ bool match = true;
670+ for (size_t j = 0; j < lastSearch.size(); ++j) {
671+ if (buf[pos + j] != static_cast<uint8_t>(lastSearch[j])) {
672+ match = false;
673+ break;
674+ }
675+ }
676+ if (match) {
677+ matchOff.push_back(pos);
678+ curPos = pos;
679+ dpOffset = curPos - (curPos % bpr);
680+ break;
681+ }
682+ }
683+ }
684+
685+ statusMode = Status_Normal;
686+ statusText.clear();
687+ render();
688+}
689+
690+void HexEditor::handleReplace() {
691+ statusMode = Status_Replace;
692+ statusText.clear();
693+ render();
694+
695+ std::string hexInput;
696+ int ch;
697+ while ((ch = getch()) != 27) {
698+ if (std::isxdigit(ch) && hexInput.size() < 2) {
699+ hexInput += ch;
700+ statusText = "REPLACE: " + hexInput;
701+ render();
702+ }
703+
704+ if (hexInput.size() == 2) {
705+ uint8_t byte = std::stoul(hexInput, nullptr, 16);
706+ if (curPos < buf.size()) {
707+ undoStack.push_back({curPos, buf[curPos], byte});
708+ redoStack.clear();
709+ buf[curPos] = byte;
710+ modified = true;
711+ curPos = std::min(curPos + 1, buf.size() - 1);
712+ }
713+
714+ hexInput.clear();
715+ statusText.clear();
716+ render();
717+ }
718+ }
719+
720+ statusMode = Status_Normal;
721+ statusText.clear();
722+ render();
723+}
724+
725+void HexEditor::undo() {
726+ if (undoStack.empty()) {
727+ statusMode = Status_Error;
728+ statusText = "既に一番古い変更です";
729+ render();
730+ return;
731+ }
732+
733+ Edit edit = undoStack.back();
734+ undoStack.pop_back();
735+ redoStack.push_back({edit.offset, edit.newByte, edit.oldByte});
736+ buf[edit.offset] = edit.oldByte;
737+ if (undoStack.empty()) modified = false;
738+ else modified = true;
739+ curPos = edit.offset;
740+ dpOffset = curPos - (curPos % bpr);
741+ render();
742+}
743+
744+void HexEditor::redo() {
745+ if (redoStack.empty()) {
746+ statusMode = Status_Error;
747+ statusText = "既に一番新しい変更です";
748+ render();
749+ return;
750+ }
751+
752+ Edit edit = redoStack.back();
753+ redoStack.pop_back();
754+ undoStack.push_back({edit.offset, edit.newByte, edit.oldByte});
755+ buf[edit.offset] = edit.newByte;
756+ modified = true;
757+ curPos = edit.offset;
758+ dpOffset = curPos - (curPos % bpr);
759+ render();
760+}
761+
762+void HexEditor::input() {
763+ int ch;
764+
765+ while (running) {
766+ if (statusMode != Status_Normal && statusMode != Status_Error) continue;
767+
768+ ch = getch();
769+ if ((ch == 'j' || ch == KEY_DOWN) && curPos + bpr < buf.size()) {
770+ curPos += bpr; // 下
771+ if (statusMode == Status_Error) statusMode = Status_Normal;
772+ } else if ((ch == 'k' || ch == KEY_UP) && curPos >= bpr) {
773+ curPos -= bpr; // 上
774+ if (statusMode == Status_Error) statusMode = Status_Normal;
775+ } else if ((ch == 'l' || ch == KEY_RIGHT) && curPos + 1 < buf.size()) {
776+ curPos += 1; // 右
777+ if (statusMode == Status_Error) statusMode = Status_Normal;
778+ } else if ((ch == 'h' || ch == KEY_LEFT) && curPos > 0) {
779+ curPos -= 1; // 左
780+ if (statusMode == Status_Error) statusMode = Status_Normal;
781+ } else if ((ch == 'J' || ch == KEY_PPAGE) && curPos >= bpr) {
782+ size_t pageSize = (rows - 3) * bpr;
783+ if (curPos >= pageSize) curPos -= pageSize;
784+ else curPos = 0;
785+ if (statusMode == Status_Error) statusMode = Status_Normal;
786+ } else if ((ch == 'K' || ch == KEY_NPAGE) && curPos + bpr < buf.size()) {
787+ size_t pageSize = (rows - 3) * bpr;
788+ if (curPos + pageSize < buf.size()) {
789+ curPos += pageSize;
790+ dpOffset = curPos - ((rows - 4) * bpr);
791+ }
792+ else {
793+ curPos = buf.size() - 1;
794+ dpOffset = (buf.size() - 1) - ((rows - 4) * bpr);
795+ if (dpOffset > buf.size()) dpOffset = 0;
796+ }
797+ if (statusMode == Status_Error) statusMode = Status_Normal;
798+ } else if (ch == '^' || ch == '0' || ch == KEY_HOME) {
799+ curPos = (curPos / bpr) * bpr;
800+ if (statusMode == Status_Error) statusMode = Status_Normal;
801+ } else if (ch == '$' || ch == KEY_END) {
802+ size_t rowStart = (curPos / bpr) * bpr;
803+ curPos = std::min(rowStart + bpr - 1, buf.size() - 1);
804+ if (statusMode == Status_Error) statusMode = Status_Normal;
805+ } else if (ch == 'i') {
806+ if (curPos - 1 > 0) curPos--;
807+ handleReplace();
808+ } else if (ch == 'r') {
809+ handleReplace();
810+ } else if (ch == 'a') {
811+ if (curPos + 1 < buf.size()) curPos++;
812+ handleReplace();
813+ } else if (ch == ':') {
814+ handleCommand();
815+ } else if (ch == '/') {
816+ handleSearch();
817+ } else if (ch == '?') {
818+ handleReverseSearch();
819+ } else if (ch == 'n') {
820+ if (lastSearchDir == Direction_Forward) findNextMatch();
821+ else findPrevMatch();
822+ } else if (ch == 'N') {
823+ if (lastSearchDir == Direction_Forward) findPrevMatch();
824+ else findNextMatch();
825+ } else if (ch == 'u') {
826+ undo();
827+ } else if (ch == 'R') {
828+ redo();
829+ } else if (ch == 'g') {
830+ if (getch() == 'g') {
831+ curPos = 0; // ファイルの一番上
832+ if (statusMode == Status_Error) statusMode = Status_Normal;
833+ }
834+ } else if (ch == 'G') {
835+ curPos = buf.size() - 1; // ファイルの一番下
836+ if (statusMode == Status_Error) statusMode = Status_Normal;
837+ } else if (ch == 'Z') {
838+ int next = getch();
839+ if (next == 'Q') {
840+ handleQuit(true);
841+ break;
842+ } else if (next == 'Z') {
843+ handleSave();
844+ handleQuit(true);
845+ break;
846+ } else if (next == 'S') {
847+ handleSave();
848+ if (statusMode == Status_Error) statusMode = Status_Normal;
849+ }
850+ }
851+
852+ // 画面の動き
853+ int rows, cols;
854+ getmaxyx(stdscr, rows, cols);
855+ if (curPos < dpOffset) {
856+ dpOffset = curPos - (curPos % bpr);
857+ } else if (curPos >= dpOffset + (rows - 3) * bpr) {
858+ dpOffset = curPos - ((rows - 4) * bpr);
859+ }
860+
861+ render();
862+ }
863+}
864+
865+void HexEditor::run() {
866+ render();
867+ input();
868+}
@@ -0,0 +1,83 @@
1+#pragma once
2+
3+#ifdef _WIN32
4+#include <pdcurses.h>
5+#else
6+#include <ncurses.h>
7+#endif
8+
9+#include <string>
10+#include <vector>
11+
12+class HexEditor {
13+ private:
14+ enum StatusMode : uint8_t {
15+ Status_Normal,
16+ Status_Command,
17+ Status_Search,
18+ Status_Replace,
19+ Status_Error,
20+ };
21+
22+ enum SearchDirection : uint8_t {
23+ Direction_Forward,
24+ Direction_Reverse,
25+ };
26+
27+ struct Edit {
28+ size_t offset;
29+ uint8_t oldByte;
30+ uint8_t newByte;
31+ };
32+
33+ struct FileSignature {
34+ std::vector<uint8_t> signature;
35+ std::string type;
36+ };
37+
38+ size_t curPos;
39+ size_t dpOffset;
40+ size_t bpr;
41+ StatusMode statusMode;
42+ bool modified;
43+ bool running;
44+ std::string lastSearch;
45+
46+ WINDOW *hexPanel;
47+ WINDOW *asciiPanel;
48+ std::vector<uint8_t> buf;
49+ std::string fname;
50+ int rows, cols;
51+ std::string statusText;
52+ std::vector<uint8_t> lastHexSearch;
53+ SearchDirection lastSearchDir;
54+ std::vector<size_t> matchOff;
55+ std::vector<Edit> undoStack;
56+ std::vector<Edit> redoStack;
57+
58+ size_t headerLen;
59+ std::string headerType;
60+ static const std::vector<FileSignature> signatures;
61+
62+ void render();
63+ void input();
64+ void highlightcol(size_t i, size_t row, uint8_t byte);
65+ void topbar();
66+ void statusbar();
67+ void handleCommand();
68+ void handleSave();
69+ void handleQuit(bool force);
70+ void handleSearch();
71+ void handleReverseSearch();
72+ void findNextMatch();
73+ void findPrevMatch();
74+ void handleReplace();
75+ void undo();
76+ void redo();
77+
78+ public:
79+ HexEditor(const std::string &filename);
80+ ~HexEditor();
81+
82+ void run();
83+};

バイナリファイル