Compare commits

..

476 Commits

Author SHA1 Message Date
WerWolv
77c1ee3e7a build: Bumped version to 1.36.2 2024-12-28 16:09:51 +01:00
WerWolv
4be2c33985 fix: Crash when providing invalid version string to semantic version class
Fixes #2036
2024-12-28 15:59:48 +01:00
WerWolv
3034d79373 build: Bumped version to 1.36.1 2024-12-28 14:09:43 +01:00
WerWolv
e7daa586ba build: Switch to custom lunasvg repo to allow offline builds 2024-12-28 13:45:21 +01:00
WerWolv
3f4bdfdf61 fix: Exception being thrown when getting version parts from invalid version 2024-12-28 13:45:07 +01:00
WerWolv
ab5860dc9a impr: Display "ImHex" in title bar when null provider is open 2024-12-28 13:45:01 +01:00
WerWolv
53b2347358 impr: Allow command palette to be closed by clicking on the menu bar 2024-12-28 13:44:55 +01:00
WerWolv
a195179101 fix: Rendering issues with text editor in bookmark view 2024-12-28 13:44:48 +01:00
WerWolv
fdccc55805 fix: Ctrl sometimes getting stuck when pressing ALT GR and other keys at the same time
#2019
2024-12-28 13:44:42 +01:00
WerWolv
55dce338b2 impr: Better create hash popup size 2024-12-28 13:44:32 +01:00
WerWolv
03c217addb fix: Don't show library plugins in --plugins subcommand 2024-12-28 13:44:27 +01:00
WerWolv
a3a3f52b48 impr: Make interactive tutorials select windows when they're highlighted 2024-12-28 13:44:19 +01:00
WerWolv
477b284041 fix: Tutorial highlights not working anymore correctly 2024-12-28 13:44:12 +01:00
WerWolv
b52495bc33 build: Fix remaining build issues 2024-12-28 13:44:06 +01:00
WerWolv
46ed451712 fix: Warning on macOS about wrong format argument 2024-12-28 13:40:53 +01:00
WerWolv
963afdce96 fix: ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback -> ImGui_ImplGlfw_InstallEmscriptenCallbacks 2024-12-28 13:40:44 +01:00
WerWolv
3f18a9a536 fix: Wrong --reset-settings subcommand description 2024-12-28 13:40:36 +01:00
WerWolv
64b226e12d build: Updated more dependencies 2024-12-28 13:40:27 +01:00
WerWolv
b74dc3d8b9 build: Updated dependencies 2024-12-28 13:40:11 +01:00
WerWolv
9668a885e8 fix: Added migration routine to fix shortcuts 2024-12-26 14:03:00 +01:00
WerWolv
b7afbf4a74 feat: Added system to handle version migrations 2024-12-26 14:02:49 +01:00
paxcut
4784a82d51 fix: Pattern Editor console scroll jumping. (#2029)
Some issues related to the padding added to scroll past the end for
console that has padding added.
Added a shortcut to scroll editors one pixel at a time.
Fixed whole lines always drawn at the top even if scroll value is chosen
so that only a portion of the top line is visible. This caused errors in
horizontal scrolling.
Fixed Ctrl-F Ctrl-G and Ctrl-H messing the editor display. 
Fixed the end of the line could not be clicked with mouse 
Fixed line numbers and their lines could be displayed at different
heights.
Made numbers that represented lines floats instead of integers to allow
partial line display.
2024-12-26 14:02:43 +01:00
WerWolv
a1ff1af754 fix: Disable ImGui assert that causes random crashes on resize 2024-12-26 14:02:34 +01:00
WerWolv
5c6b20c0ec build: Updated ImGui glfw backend 2024-12-26 14:02:25 +01:00
WerWolv
79af360822 fix: Crashes when disassembling data
Fixes #2025
2024-12-25 18:25:26 +01:00
WerWolv
fb23708220 fix: Wrong localStorage key for achievements 2024-12-25 18:25:20 +01:00
WerWolv
93f6ab25e6 fix: Missing emscripten include 2024-12-25 18:25:16 +01:00
WerWolv
6faefed4f4 fix: Disable browser ctrl + S in web build 2024-12-25 18:25:10 +01:00
WerWolv
6a159be861 fix: Properly save achievements in web version 2024-12-25 18:25:00 +01:00
WerWolv
d7b43b54f9 fix: Saving files in web version not working correctly 2024-12-25 18:24:53 +01:00
WerWolv
1a92425995 impr: Force update all installed content store items after an update 2024-12-25 18:24:44 +01:00
WerWolv
347bdd9508 fix: Unused variable in wasm build 2024-12-25 18:24:31 +01:00
WerWolv
b80e8b63c9 fix: Certain shortcuts not being captured by ImHex Web 2024-12-25 18:24:23 +01:00
WerWolv
621d529682 fix: Shortcuts not working correctly in Web build 2024-12-25 18:23:54 +01:00
WerWolv
6005af1595 build: Bumped version to 1.36.0 2024-12-24 13:43:04 +01:00
WerWolv
9a4329807a patterns: Updated pattern language 2024-12-24 13:07:26 +01:00
WerWolv
8e01da4c12 lang: Fixed settings language string in hashes view 2024-12-24 13:06:38 +01:00
WerWolv
eb8ea520c7 build: Make ImGui use old CRC algorithm 2024-12-24 11:09:45 +01:00
WerWolv
512fcd361b impr: Modernize the disassembler, hashes and yara view 2024-12-24 10:57:09 +01:00
WerWolv
aad6f6bcbe build: Updated ImGui to v1.91.6 2024-12-24 00:37:04 +01:00
WerWolv
0af21505d7 git: Add retry mechanism for creating dmg on x86 mac 2024-12-24 00:00:22 +01:00
WerWolv
2ae69e8e72 feat: Allow command palette to work with previous results 2024-12-23 23:42:45 +01:00
WerWolv
9274fac8e1 build: Updated libwolv
Fixes #2007
2024-12-23 23:24:38 +01:00
WerWolv
e2f82c60e6 fix: Crash when using text editor as last item in a window 2024-12-23 23:17:19 +01:00
WerWolv
bfddf24204 impr: Added hints to various input fields 2024-12-23 23:16:55 +01:00
WerWolv
382599dcf6 fix: Better icon text input width calculation 2024-12-23 23:16:35 +01:00
WerWolv
5f2c07f2d8 fix: Icon text inputs not being the same length as other items 2024-12-23 21:48:47 +01:00
WerWolv
914024c0b5 impr: Added note about adding new data inspector row 2024-12-23 21:47:16 +01:00
WerWolv
c5d3387962 impr: Replaced centered text notes with overlays 2024-12-23 21:30:31 +01:00
WerWolv
7cc99c6fc9 impr: Added better notes to the settings tabs in the pattern editor view 2024-12-23 21:26:22 +01:00
WerWolv
a29b502a33 impr: Made pattern editor resize separator taller 2024-12-23 20:15:50 +01:00
paxcut
20cb74364f fix: Jumpy text editor scrolling (#2023)
Two major improvements:
1) see through scrollbars when not hovered.
2) un-scrollable line numbers.

Also enlarged display region by eliminating padding. There is still a
problem with lines jumping when the scrollbar is dragged but it is
limited to one line and probably due to floating point error for scroll
bar number. It is much less noticeable than the previous jumping which
could involve several pages.

---------

Co-authored-by: WerWolv <werwolv98@gmail.com>
2024-12-23 20:14:42 +01:00
WerWolv
1c5a50c8d8 impr: Added better file open error messages to the file provider 2024-12-23 14:07:35 +01:00
WerWolv
470523cc86 fix: Jittery scrolling in Text Editor 2024-12-23 11:44:34 +01:00
WerWolv
f6bc3d4650 impr: Replace more assert() calls with IM_ASSERT() 2024-12-23 11:22:20 +01:00
WerWolv
41b1228d31 fix: Make sure all text editor members are correctly initialized 2024-12-23 11:21:39 +01:00
paxcut
2cb4462274 impr: Better top margin handling for text editor. (#2021)
The top margin changes when popups block some portion on the screen.
Previously it was implemented adding blank lines at the bottom which
created problems if the windows was scrolled all the way to the bottom
and the popups were issued. The newer implementation doesn't use spaces
and simply resets the top of the window to be higher making the popup
interaction with the window more natural (no text disappears on the
lines the popup overlaps the text). changes can be identified form the
variables mTopMargin,mOldTopMargin and mNewTopMargin.

Unfortunately those changes revealed problems in cursor navigation that
needed to be addressed. Namely, the window will scroll up and down on
the line before last/second line at the top and similar problems for the
left and right. Those changes correspond to the function
EnsureCUrsorVisible()

Fixing those reveled yet more problems with scrolling past the end of
the file using the keyboard which required adding some more variables
and functions to support the correct handling, You find those changes in
the function MoveDown.

I also renamed some variables that had the wrong casing and fixed the
pasting but that is missing one line.
2024-12-23 10:35:53 +01:00
WerWolv
810cd40ccd impr: Replace strerror with C++ functions 2024-12-23 01:42:06 +01:00
WerWolv
f931beb49a impr: Make inserting bytes at the start of the file with insert mode work better 2024-12-23 01:33:52 +01:00
WerWolv
1c3dfc9b2f fix: ID collision in Jump To menu 2024-12-23 01:00:58 +01:00
WerWolv
a1d4545e29 fix: Don't allow negative regions in region widgets 2024-12-23 01:00:41 +01:00
WerWolv
8865db2007 lang: Added missing memory file rename key 2024-12-23 01:00:13 +01:00
WerWolv
d2056d9409 fix: Crash on exit 2024-12-23 00:59:55 +01:00
Nik
74e74ddc38 git: Make CodeQL CI use ninja 2024-12-23 00:06:59 +01:00
WerWolv
5fcb737559 fix: Only update widgets of settings that were changed
Fixed crashing on exit and speeds up settings writes
2024-12-20 21:23:19 +01:00
Nik
9303025427 git: Just disable coverage generation for now 2024-12-18 22:56:44 +01:00
WerWolv
680985fc13 git: Update gcovr filters 2024-12-18 21:57:40 +01:00
WerWolv
5a360eb614 patterns: Updated pattern language 2024-12-18 20:33:05 +01:00
paxcut
4a74bd78fd fix: Console either printed no newlines or printed extra ones. (#2016)
The reason for the error were the text preprocessor added to deal with
tabs was created to process entire files, not just lines or words. In
that context it cleaned trailing new lines if any existed but in the new
role that's not only unwanted but erroneous.

### Problem description
After that was fixed the console started to add two empty lines between
each output line. When splitting a string using new lines you need to
not add a new line to the last line created. Even if the text ends in an
end line, the split screen code is set to not discard empty lines.

### Implementation description
The fixes are straightforward.
2024-12-18 20:19:18 +01:00
WerWolv
0f53656952 build: Small ImPlot3D fixes to make it build on all platforms 2024-12-18 20:18:27 +01:00
WerWolv
9ca40d3651 build: Added ImPlot3D 2024-12-17 23:51:45 +01:00
WerWolv
ab12503f62 patterns: Drastically improved time it takes to find favorites 2024-12-17 23:37:39 +01:00
paxcut
b446d7fd4a impr: Make scrolling in pattern editor feel less janky (#2009)
I have implemented a fix that makes the scrollbars behave like they do
in VScode. Vertically you can scroll past the end of the file until only
the last line can be seen at the top. The horizontal bar behaves as if
every line was the same length which is the length of the longest line
in the file. Not only this creates a better user experience, but it also
fixes the annoying flicker that occurs when scrolling through large
files. Also, I have switched all the old draw calls to render text to
regular TextUnformatted calls which adds extra stability to the
resulting display.

To implement the behavior I added a dummy widget with the desired
dimensions.
2024-12-17 22:44:40 +01:00
WerWolv
fd46d85762 git: Another attempt fixing gcovr 2024-12-17 22:42:48 +01:00
WerWolv
fa421afb00 git: Ignore all gcov errors related to missing files 2024-12-17 22:07:16 +01:00
paxcut
a79d3e28ca fix: Crashes when getting tabs into text editor (#2008)
This time it may be for good. 


### Implementation description
As requested I added the preprocessing functionality into the pattern
editor. I had to duplicate a few functions and update the c++ library to
version 20. but now I can make sure the pattern editor doesn't see a tab
again. I also removed the preprocessor from where it was before because
it is not needed anymore. The changes were tested using a file that used
tabs for all its white space. The file was pasted into the pattern
editor and imported as well. I both cases no crashes occurred and the
files had no tabs on them.
2024-12-17 21:36:00 +01:00
WerWolv
fbb4f65735 patterns: Updated pattern language 2024-12-17 21:34:18 +01:00
WerWolv
00c62c90f6 git: Try to fix coverage scan 2024-12-17 21:33:53 +01:00
WerWolv
384aa6e6a9 fix: Narrow to wide type compare in loop in timestamp visualizer 2024-12-16 22:17:58 +01:00
WerWolv
1c755249ec git: Use ninja for building everything 2024-12-16 22:10:22 +01:00
WerWolv
2c303b5bf2 build: Actually fixed unit tests 2024-12-16 21:47:40 +01:00
WerWolv
415e3b4a93 impr: Added commit hash and branch to nightly popup on welcome screen 2024-12-16 21:37:34 +01:00
WerWolv
8d9b056c8c build: Fixed building of unit tests 2024-12-16 21:37:11 +01:00
WerWolv
a527a7f0b0 patterns: Updated pattern language 2024-12-16 21:32:19 +01:00
WerWolv
d78d955d11 impr: Better ellipsis usage in menus 2024-12-16 21:27:57 +01:00
BioTheWolff
9375a60cd9 feat: Implement paste behaviour popup when pasting over one-byte regions (#2004)
### Problem description
This PR implements the feature request described in #1995, that
describes a problem with the `Paste` vs `Paste all` commands. Users
could be thrown off by having `Ctrl+V` act as a simple "Paste over
selection", whereas it's generally accepted as a "Paste all".

### Implementation description
<!-- Explain what you did to correct the problem -->
This PR introduces a new setting, called "Paste behaviour" (under the
"Hex Editor" category).
This setting has three values:
- `Paste over selection`: the current implementation for ImHex. Pastes
only over the selection region, in this case pasting only one byte;
- `Paste everything`: allows ImHex's `Paste` to behave like a `Paste
all` when selecting one-byte regions;
- `Ask me next time`: prompts the user for a choice of behaviour
(default value).

*Note: as users generally use `Paste all` when selecting one-byte
regions, calling `Paste` when selecting over two or more bytes is not
affected by this change, and will still behave like the usual `Paste`
command.*

When selecting a one-byte region, and calling the Paste command, users
that have not defined a preferred behaviour in the settings will be
prompted to choose one, using a brand new popup. The popup also allows
the user to cancel, which will not change the settings' value, and will
cancel the paste action altogether.

### Screenshots
The new popup:

![image](https://github.com/user-attachments/assets/2b0fd532-d4e7-4209-9dd7-8a79278692ea)

The new setting:

![image](https://github.com/user-attachments/assets/2644c35e-7332-422e-8fae-ae8ad0507126)

### Additional things
I'm not very good with long descriptions, so I'm open to any suggestions
regarding the text that is included in the popup!
I do think however that we should keep a hint indicating that `Paste
all` is always an option, which could solve the issue altogether for
very new users.

---------

Signed-off-by: BioTheWolff <47079795+BioTheWolff@users.noreply.github.com>
Co-authored-by: Nik <werwolv98@gmail.com>
2024-12-16 20:35:48 +01:00
WerWolv
bb99b9a0ef fix: Shortcuts acting as duplicates in settings 2024-12-16 20:26:04 +01:00
WerWolv
313e59d7f9 fix: Shortcuts applying to multiple views at once 2024-12-16 20:14:26 +01:00
WerWolv
e34e0e62f2 patterns: Fixed json builtin types throwing non-patternlanguage exceptions 2024-12-15 23:13:43 +01:00
paxcut
212f75f1cb fix: Tabs messing up content of text editor (#2005)
<!--
Please provide as much information as possible about what your PR aims
to do.
PRs with no description will most likely be closed until more
information is provided.
If you're planing on changing fundamental behaviour or add big new
features, please open a GitHub Issue first before starting to work on
it.
If it's not something big and you still want to contact us about it,
feel free to do so !
-->

### Problem description
<!-- Describe the bug that you fixed/feature request that you
implemented, or link to an existing issue describing it -->

### Implementation description
<!-- Explain what you did to correct the problem -->

### Screenshots
<!-- If your change is visual, take a screenshot showing it. Ideally,
make before/after sceenshots -->

### Additional things
<!-- Anything else you would like to say -->
2024-12-15 23:08:26 +01:00
WerWolv
a07c79efcb fix: Pattern editor shortcuts being set to use CTRL on macOS 2024-12-15 22:39:24 +01:00
WerWolv
89090b25e3 impr: Various shortcut improvements 2024-12-15 21:44:43 +01:00
WerWolv
721164e562 fix: Deinitialization order 2024-12-15 21:44:36 +01:00
BioTheWolff
b8ba980a20 fix: Chinese (Simplified) translation showing up twice (#2006)
### Problem description
As described in issue #1841, there was a duplicate on the `Chinese
(Simplified)` translation.
After closer inspection, this came from an i18n file (Script loader,
specifically) having a bad ISO code (`zh_CN` instead of the expected
`zh-CN`).

This also caused a big impact on end users, as loading the latter
(`zh_CN`) would cause the whole UI to be displayed in English (the
fallback language), and only the script loader being translated into
Chinese.

### Implementation description
Fixed the i18n code in the Script loader file.

### Additional things
Closes issue #1841

Signed-off-by: BioTheWolff <47079795+BioTheWolff@users.noreply.github.com>
2024-12-15 17:20:04 +01:00
WerWolv
79ded38434 patterns: Updated pattern language 2024-12-15 14:12:27 +01:00
WerWolv
f52db884a9 lang: Update casing of next provider / previous provider options 2024-12-15 12:16:57 +01:00
WerWolv
ee4bb33b0a impr: Display sub menus for shortcut settings 2024-12-15 11:54:10 +01:00
WerWolv
caf8fa8e25 impr: Show byte relationship diagrams side by side if there's enough space 2024-12-15 11:46:54 +01:00
WerWolv
c46dea4c9e impr: Update settings menu values when settings are changed 2024-12-15 11:12:56 +01:00
WerWolv
002b7b4f87 impr: Make Copy as ASCII string use ALT + C to be more consistent 2024-12-15 11:02:34 +01:00
WerWolv
0a6a8c671f impr: Better naming for various menu entries 2024-12-15 11:02:20 +01:00
WerWolv
36014b706d fix: Wrong header location in disassembler view 2024-12-15 10:52:11 +01:00
paxcut
df5e01d4eb impr: Better 3D Visualizer error messages, wrap long visualizer errors (#1969)
### Problem description
Long error messages were forcing the width of the window to span the
entire screen.

### Implementation description
The fix was sending the long message to the log and outputting a short
message to the 3d visualizer window.

---------

Co-authored-by: WerWolv <werwolv98@gmail.com>
2024-12-15 10:12:14 +01:00
WerWolv
c6f1525f55 git: Silence last brew call 2024-12-15 10:01:24 +01:00
WerWolv
5511259f2d git: Updated more workflows 2024-12-15 00:44:32 +01:00
WerWolv
f2ea7ca5d1 git: Silence brew github actions annotations 2024-12-15 00:28:22 +01:00
WerWolv
6184bbeae2 build: Updated libwolv 2024-12-14 23:55:04 +01:00
WerWolv
21506578f5 impr: Removed more instanced of codecvt 2024-12-14 22:39:07 +01:00
WerWolv
f39f395393 impr: Replace codecvt with libwolv conversion functions 2024-12-14 22:20:48 +01:00
WerWolv
ed0a94659e impr: Added load and base address to instruction pl types 2024-12-14 21:52:19 +01:00
WerWolv
7f75706584 impr: Replace hex::unused with std::ignore 2024-12-14 21:35:54 +01:00
WerWolv
3f316e42f2 build: Remove unavailable warning flags from gcc builds 2024-12-14 21:35:42 +01:00
WerWolv
4a331c0331 git: Replace gcc-toolset-12 with gcc-toolset-14 fir EL9 runner 2024-12-14 20:36:32 +01:00
WerWolv
6a28de100c impr: Rename font definition files 2024-12-14 20:36:09 +01:00
WerWolv
992f18b94b impr: Optimize build times a bit 2024-12-14 19:15:49 +01:00
Nik
040a606b39 feat: Added various custom built-in types to the pattern language (#1991) 2024-12-14 16:52:36 +01:00
BioTheWolff
13e079d1b8 feat: Add capability to paste as string literal in files (#1998)
### Problem description
As suggested in #1904, ImHex could benefit from having the capability of
pasting text directly into the editor.
This also complements the "Copy as... ASCII string" capability already
implemented in the software.

### Implementation description
A new shortcut called `Paste all as string` (to resemble the naming of
the `ASCII string` copy option) now allows to paste plaintext directly.
This shortcut is mapped to the `CTRL + ALT + SHIFT + V` keybind.

Internally, a new flag called `asPlainText` has been added to the
`pasteBytes` function, to minimise code changes and streamline code
readability.
The buffer is a simple type cast of the clipboard, without any
modification applied, which is then handed to the provider's `write`
function.

### Screenshots
The new shortcut is visible in the menu, just below the other paste
options:

![image](https://github.com/user-attachments/assets/41a2a512-5c39-4984-bab6-114c58266351)

---------

Signed-off-by: BioTheWolff <47079795+BioTheWolff@users.noreply.github.com>
2024-12-14 16:52:14 +01:00
Roman
d9a7f40eb4 fix: Shortcuts not being disabled correctly when menu items are disabled (#1992)
Fix crash on UNDO/REDO shortcut press when in "title screen"

### Problem description
ImHex crashes when (by default CTRL + Z/Y) undo/redo is pressed when on
"title"/"starting" screen (no file open, tested on Windows release build
and Linux [WSL] from-source build).

This is due to the shortcut's callback being called even if the
`provider` is `nullptr`. (see `createEditMenu` function).
Theoretically, this is prevented by the `enabledCallback` function
passsed to `addMenuItem`. In this case, though,
`addMenuItem` correctly propagates `enabledCallback` to menu item
creation but does not pass `enabledCallback` to
shortcut creation. Thus, when handling shortcuts, `enabledCallback` is
not used at all and the shortcut's callback
can be called in contradiction with its preconditions. (specified by
`enabledCallback`)

### Implementation description
The implementation wraps the callback in a check that decides whether
the shortcut is enabled or not.

(see changed files)
```c++
        auto callbackIfEnabled  = [enabledCallback, function]{ if (enabledCallback()) { function(); } };
```

This function is then passed along instead of the `function` (shortcut's
callback).

Alternatively, we can check for `nullptr` in the callback directly. This
would require modification of `createEditMenu`'s contents.
(I did not choose this implementation because I do not think it
addresses the root of the issue).

### Screenshots
None

### Additional things
I'm not sure how big of a deal it is but I am unsure whether I can
capture (`[enabledCallback, function]`) by reference or not.
2024-12-14 16:51:40 +01:00
paxcut
8d123da847 feat: Added goto line popup to text editors (#1984)
Since the popup is fairly small I opted for a straight addition parallel
to the find/replace. To make code more clear the functions that create
each popup were coalesced and made their interface simpler. That forced
a reorganization of the data processing which translates to a larger
number of changes than usual. Most of those changes are just moving some
action from one function to another.

The old method to identify popups using the size and position of the
window was dropped in favor of one based on child windows and using
their names for a much easier and robust identification.

Added specialized functions to text editor to jump to a line or to given
coordinates with a simple interface that simplifies older code that
performed the same task.

Because this PR modifies heavily the same code as the previous PR (1983)
it is also included here to make merging easier.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-12-14 16:50:45 +01:00
Nik
093310a9e5 git: Updated CI to latest available compilers and distros (#2003) 2024-12-13 00:07:46 +01:00
WerWolv
21b315b97e impr: Added image load and image base address to disassembler
#1994
2024-12-10 20:33:28 +01:00
Nik
c70cc3a6f1 git: Disable AppArmor to make fedpkg not fail anymore (#1997) 2024-12-10 13:34:39 +01:00
WerWolv
1e71d8afc0 feat: Added Disassemble selection option to the Edit menu
#1994
2024-12-09 21:35:08 +01:00
WerWolv
cb6b74b269 fix: Use after free when deleting data processor nodes with errors 2024-12-09 14:40:07 +01:00
WerWolv
a1e399aa1a fix: Use after free in Text Editor when copying ErrorHoverBoxes 2024-12-09 14:39:46 +01:00
WerWolv
e1dfdd9400 fix: Missing include 2024-12-09 00:05:36 +01:00
iTrooz
6ab2e81f1c chore: Add documentation about popup opening 2024-12-06 23:40:05 +01:00
paxcut
cf09029847 feat: Added clickable links to error messages in the pattern editor (#1988)
Errors printed in the console can be clicked to have the cursor jump to
the source code line where the error is at.

The mouse cursor changes its shape to indicate which parts of the error
message can be clicked on the console. When the cursor jumps, the text
editor takes the focus away from the console and it scrolls the window
to make the line with the error is visible if it isn't. This code uses
the function created for the go-to PR but adds code to switch focus to
the target. When the codes are merged please keep both the part that
jumps the cursor and the part that sets the focus.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-12-06 22:45:36 +01:00
WerWolv
d02e170dac fix: Build issue on systems where size_t is not u64 2024-12-06 22:03:12 +01:00
WerWolv
2b715bb0de impr: Batch fills into larger chunks 2024-12-06 10:15:32 +01:00
BioTheWolff
2dcaf2c77b fix: Various achievements issues (Edit the Hex, ROM Hacks) (#1985)
### Problem description
As described in #1846:
- the `Edit the Hex` achievement doesn't unlock when it should
- the `ROM Hacks` achievement is not using event-driven architecture
(the functions call `unlockAchievement` themselves)

### Implementation description
Firstly, for the `Edit the Hex` achievement:
- replaced the old event listener on `EventPatchCreated` with a listener
on `EventProviderDataModified`, which picks up bytes changes
- ensured the provider data change comes from a File provider, else
unlocking the achievement wouldn't make sense
- *Note*: a discovered side effect is that the "Fill" function modifies
the provider byte per byte (with a for loop)
- there is no use in testing the size of the data change, as it is
always 1 byte
- the Fill function could probably be reworked to fill in whole regions
at a time?

About the `ROM Hacks` achievement:
- implemented the new, still unused `EventPatchCreated` event.
- signal signature is `const unsigned char *, u64, const IPSKind`:
buffer pointer, buffer size, and IPS kind (IPS/IPS32)
- make use of the `::post` and `::subscribe` methods on said event to
unlock the achievement
- **WARNING::behaviour change**: the event's `post` signal has been
moved in the success branch of the IPS generation condition, meaning
that achievement will only unlock if IPS patch export has worked. I felt
it would make more sense than unlocking an achievement on an error, if
there was any to raise.

---------

Signed-off-by: BioTheWolff <47079795+BioTheWolff@users.noreply.github.com>
2024-12-06 00:36:42 +01:00
BioTheWolff
1b9f4f33de feat: Added export disassembler results to ASM file (#1987)
### Problem description
<!-- Describe the bug that you fixed/feature request that you
implemented, or link to an existing issue describing it -->
This PR implements the feature request #1781, that suggests adding a
button to export disassembled instructions into an ASM file.

### Implementation description
This adds a button to export the current disassembled instructions to an
ASM file. Said file is suffixed by an `.asm` extension if not specified
at file creation.

*Note: the file is written to for every `Disassembly` item in the
vector, as it was the easiest and most memory-conservative way of doing
it.*

The file creation task is implemented based on IPS patch exports, so it
fits the same pattern.
A `ToastError` is raised when the ASM export could not complete
successfully.

Translations have been implemented for both `en_US` and `de_DE` for the
two new keys:
- `hex.disassembler.view.disassembler.export`: file export button
- `hex.disassembler.view.disassembler.export.popup.error`: error popup
text

### Screenshots
The button is disabled when the disassembler is working, or when the
disassembly vector is empty.

Here is a complete breakdown of the visual changes:

![image](https://github.com/user-attachments/assets/af0ce701-9d77-45f1-9a5a-90d68d00bb0d)

### Additional things
As expected, the exporter writes every item's `mnemonic` and `operators`
to the file, producing an output like this:

`example.asm`
```asm
.byte 0x7f, 0x45, 0x4c, 0x46
andeq r0, r1, r2, lsl #2
andeq r0, r0, r0
andeq r0, r0, r0
eorseq r0, lr, r3
andeq r0, r0, r1
andeq r1, r0, r0, asr #32
andeq r0, r0, r0
andeq r0, r0, r0, asr #32
```

---------

Signed-off-by: BioTheWolff <47079795+BioTheWolff@users.noreply.github.com>
2024-12-05 23:04:38 +01:00
Justus Garbe
3c73f88a52 fix: AES ECB mode in Data processor not working at all (#1986)
Fix the AES ECB mode in the data processor along with some other misc
fixes:
- Fixed nullpointer node not working
- Fixed crypto module incorrectly using mbedtls api
- Fixed crypto module ignoring mbedtls errors
- Fixed silently ignoring of errors in AES node
2024-12-05 20:56:43 +01:00
paxcut
8acdc19be4 fix: Pattern Editor context menus being entries greyed out when they shouldn't be (#1983)
Some context menu entries that were available as shortcuts were greyed
out. This PR aims to fix them and improve how context menus work for the
text editor and the console. The improvements include:
- automatic focus on right click
- automatic selection on right click. If selected text is right-clicked
then copy, cut and find will use the selection, if no selection is
clicked but there is text were right-clicked, then the word will be
selected and used. If right-clicking empty space copy and cut will be
greyed out and find will start empty.
- similar functionality now exists for the console as well except the
menu has fewer options due to it being read-only.
- added esc to close console context menu
2024-12-05 19:34:51 +01:00
WerWolv
22252d9044 fix: Patterns in pattern data view not being editable in providers that are not writable from the start 2024-12-05 16:37:31 +01:00
WerWolv
5948a74ad1 fix: Multiple memory corruption issues 2024-12-05 16:36:27 +01:00
alexkar598
e46d9d7650 fix: HexII visualisation does not allow hex characters in the edit field (#1982)
### Problem description
At the moment, attempting to edit files using HexII data visualization
is impossible as the editing fields only allow numeric characters but is
interpreted as a hex value

### Implementation description
I yoinked the params used for the hex visualization edit field. 

### Screenshots

![image](https://github.com/user-attachments/assets/2d61bf61-9893-4cfb-a2bf-6ff954aef903)

### Additional things
Ideally this should instead accept the format used by HexII, but I have
what scientists describe as a skill issue and this at least makes it
possible to use HexII without switching back to hex for editing.
2024-12-03 23:05:00 +01:00
Justus Garbe
813276c907 feat: Add constant data input to buffer node (#1981)
Added a hex data input field to the buffer node in the data processor.


![image](https://github.com/user-attachments/assets/a98e1174-7d35-4130-b9f7-9ef5d0703bc7)
2024-12-03 23:03:04 +01:00
BioTheWolff
7032473ecf impr: Added MIME types for project files on UNIX systems (#1980)
<!--
Please provide as much information as possible about what your PR aims
to do.
PRs with no description will most likely be closed until more
information is provided.
If you're planing on changing fundamental behaviour or add big new
features, please open a GitHub Issue first before starting to work on
it.
If it's not something big and you still want to contact us about it,
feel free to do so !
-->

### Problem description
<!-- Describe the bug that you fixed/feature request that you
implemented, or link to an existing issue describing it -->
This PR addresses issue #491 regarding the inability to open ImHex
project files (`.hexproj`) directly from various UNIX Desktop
Environments.

_NB: This PR's scope is limited to UNIX systems, as I have no access to
MacOS systems and could not find a way to automatically create file
associations on Windows._

### Implementation description
<!-- Explain what you did to correct the problem -->
In order for project files to be recognised as such, we need to create a
new MIME type. According to [RFC 6838 section
3.2](https://www.rfc-editor.org/rfc/rfc6838#section-3.2), additional
application MIME types should be defined with a vendor prefix.
_NB: This is preferred over the deprecated `x-` prefix, although RFC
6838 states that the vendor should be "a well known producer"_

This PR proposes a new mime type for ImHex project files:
`application/vnd.imhex.proj`, and associates it with the file format
`*.hexproj`.

It also implements small changes in the Arch Linux and RPM builds, in
order to correctly ship the MIME XML file during installation.

### Additional things
<!-- Anything else you would like to say -->
The implemented change has been manually tested in the following UNIX
systems and graphical environments:
- Arch Linux, with Gnome 47.2
- Arch Linux, with XFCE4
- Fedora 41 Workstation Edition, with Gnome 47.0
- Fedora 41 Plasma, with KDE Plasma 24.08.2
- Ubuntu 22.04.5, with Gnome 42.9

Which tests the functionality of the following build types:
- Arch Linux's `.zst` packages
- Debian `.deb` packages
- RPM packages

For Arch Linux and RPM packages, this has been tested to ensure that
post-installation hooks (such as regeneration of the MIME database) is
correctly executed (which it is). No further changes than those
implemented in the PR are needed.

---------

Signed-off-by: BioTheWolff <47079795+BioTheWolff@users.noreply.github.com>
2024-12-03 23:02:40 +01:00
WerWolv
807f1fb561 patterns: Updated pattern language 2024-12-02 21:16:35 +01:00
WerWolv
296f80ffe5 fix: Data information sections getting duplicated in NullProvieders 2024-12-02 21:16:20 +01:00
paxcut
d45e0d1cac impr: Replace all asserts with IM_ASSERT in the Text Editor (#1979)
All asserts in TextEditor.cpp were replaced with IM_ASSERTs so that if
they are hit ImHex won't crash and give a nice popup message instead.
2024-12-02 20:21:57 +01:00
WerWolv
4b8f9984d5 fix: Get rid of ranges again because still not all compilers support it 2024-12-02 20:21:15 +01:00
WerWolv
7623610704 build: Updated dependencies 2024-12-01 23:24:57 +01:00
WerWolv
a7fe384a31 feat: Added entropy drop/spike annotations to the entropy graph 2024-12-01 22:27:04 +01:00
WerWolv
485ce887ea patterns: Updated pattern language 2024-12-01 17:38:59 +01:00
Nik
2a0bb79513 fix: Potential overflow when calculating audio sample index
Fixes
[https://github.com/WerWolv/ImHex/security/code-scanning/223](https://github.com/WerWolv/ImHex/security/code-scanning/223)

To fix the problem, we need to ensure that the multiplication is
performed using a larger integer type to avoid overflow. This can be
achieved by casting one of the operands to `u64` before performing the
multiplication. This way, the multiplication will be done in the larger
type, preventing overflow.

We will modify the line `index += frameCount *
device->playback.channels;` to cast `frameCount` to `u64` before the
multiplication.


_Suggested fixes powered by Copilot Autofix. Review carefully before
merging._

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2024-12-01 16:07:24 +01:00
paxcut
21ae88702f fix: Empty text editor has no cursor. (#1976)
Even if focus is given to the pattern editor the cursor will not show
until the editor contains printable chars.

### Problem description
I was using the wrong condition to enter the loop that skipped the
default empty document.

### Implementation description
The fix was to check if there are lines of text that need to be
processed even if they are empty.
2024-12-01 09:58:37 +01:00
BobSmun
0ff1bb392c fix: CRC64 parameters being limited to 32bit (#1975)
This addresses #1974
2024-11-30 18:35:03 +01:00
WerWolv
01af2f364c patterns: Updated pattern language 2024-11-30 13:49:27 +01:00
paxcut
a639dddd19 impr: Turned static variables into member variable in the Text Editor (#1973)
to avoid potential problems in the future if opening several popup
windows at the same time becomes possible.
2024-11-29 20:44:56 +01:00
WerWolv
71ec6c5061 fix: Separator stride setting displaying incorrect values 2024-11-29 20:44:04 +01:00
WerWolv
8c4c4f5e8b impr: Hide segment number in hex editor when holding down shift 2024-11-29 20:43:37 +01:00
WerWolv
2c2d3b2de3 feat: Display visualizers in pattern tooltips 2024-11-29 20:23:36 +01:00
WerWolv
caae5c9711 fix: Move visualizer drawer to correct library 2024-11-29 17:37:02 +01:00
paxcut
72822d03aa fix: Stereo sound visualizations (#1970)
Even tough the sound visualizer has `channels` as one of its parameters
it wasn't using it properly.

### Problem description
The biggest problem is that at each frame the index was being advanced
per channel frame_count increments. The number of channels also
determines how many graph will be needed to display the graphs of the
visualized sound files. Besides these two problems there were many
others like incorrect playback time, cracking audio, etc. which will not
be mentioned.

### Implementation description
To sample the signal a channel sampler was created based on the one used
previously that returns as many sampled signals as there are channels.
This PR aims hopefully at fixing all the problems encountered, and it
has been tested extensively using `Audacity` exported samples to ensure
the visualizer fidelity on playback and graph appearance.

### Screenshots

![image](https://github.com/user-attachments/assets/03453860-693f-4af4-b6c6-e828a102c389)
2024-11-29 17:22:22 +01:00
paxcut
9de3dd89c5 feat: Added support for inline visualizers in custom data inspectors (#1966)
### Problem description
This PR aims at making inline visualizers work on the data inspector so
that more rgb encodings can be added as custom pattern language
inspector rows. This was never setup to work because the inline
visualizer rendering function was a private member function.

### Implementation description
In order to be accessible from the inspector class the rendering
function was made public.

### Additional things
Missing still is the tooltip to make it behave like other color entries.
2024-11-29 17:20:28 +01:00
dependabot[bot]
bcb69b9855 git: bump dawidd6/action-download-artifact from 3 to 6 (#1972)
Bumps
[dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact)
from 3 to 6.

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-29 13:55:41 +01:00
paxcut
6d2761f141 feat: Added multiline search/replace and fixed various crashes. (#1911)
### Problem description
Previous implementation ignored everything after the first newline.
Other changes include:
- Added isEmpty() function that checks if editor has no content.
- replaced asserts with default behavior to avoid unneeded crashes.
- fixed off by one error in DeleteRange()
- some crashes occurred because readily available corrective actions
were not being taken. For example start/end being -1 in DeleteRange().
- At the heart of search/replace is the ability to translate from
indices into the text string to line/column coordinates used for
everything. To this end a function (StringIndexToCoordinates) was added
to do the translation taking utf-8 chars into account. This made the
recently added Utf8BytesToChars function unneeded, so it was removed.
- Removed commented out code that is not useful anymore. Also removed
tooltip code which is also unused.
- Removed unused parameter wrapAround to FindNext().
2024-11-29 09:37:05 +01:00
WerWolv
05c25b6aff patterns: Updated pattern language 2024-11-28 21:27:02 +01:00
WerWolv
9be9eb90f6 feat: Added hex editor segment separators 2024-11-28 21:26:55 +01:00
WerWolv
71f2f3a5fc patterns: Updated pattern language 2024-11-27 20:44:14 +01:00
WerWolv
862b1d407c patterns: Updated pattern language 2024-11-26 21:27:09 +01:00
WerWolv
5da0da48c8 build: Fix building for webassembly 2024-11-25 00:08:08 +01:00
WerWolv
3f1a51e350 patterns: Updated pattern language 2024-11-24 23:48:13 +01:00
WerWolv
d167e43252 impr: Optimization for searching for favorite and group patterns 2024-11-24 23:21:23 +01:00
WerWolv
fe9eecd031 build: Updated ImGui to v1.91.5 2024-11-24 18:55:56 +01:00
WerWolv
ded8cff415 build: Update to macOS 13 in more places 2024-11-24 15:51:22 +01:00
WerWolv
3497716a00 git: Bumped macOS runners to macOS 13 2024-11-24 15:33:55 +01:00
WerWolv
c78b4a3343 patterns: Updated pattern language 2024-11-24 15:16:06 +01:00
WerWolv
17359be58a build: Fixed remaining build issues 2024-11-24 14:16:48 +01:00
paxcut
382a62343d fix: Fixes for breakpoints (#1923)
WARNING: this PR won't compile unless [PR 132 from pattern language
repository](https://github.com/WerWolv/PatternLanguage/pull/132) is
merged first. Some changes here are shared by at least another PR to
this repository but there should not be any conflicts as the shared
changes are identical.

### Problem description
fix: Editing patterns with breakpoints sets behaves unexpectedly. As a
simple example, set a breakpoint and insert a blank line somewhere
before the breakpoint location. The breakpoint will appear to move but
in reality it hasn't. To see this set another breakpoint elsewhere in
the file and the old one will be displayed where it is really located
at.

The reason for this and many other problems with breakpoints is that
currently ImHex keeps two set of breakpoints in text editor and in
evaluator that are independent of each other, ie, changes to one don't
affect the other. This PR aims at synchronizing the two sets through the
per provider breakpoints that exist in view pattern editor.

### Implementation description

It accomplishes this by making the text editor version of breakpoints
the principal source of vectors and the ones in evaluator the effective
version. The first allows one to modify the text around and at the
breakpoint and notify others that the changes have induced changes in
the breakpoint locations. The effective breakpoints allow the insertion
and deletion of breakpoints.

View pattern editor is where breakpoints are updated. It receives
notifications from text editor about changes and then makes sure the
version in evaluator is updated with those changes. View pattern editor
also manages breakpoint addition and deletion so before making changes
it gets a copy of the current ones from text editor, sets the ones in
evaluator, uses the evaluator functions to add or delete breakpoints and
finally sets the text editor version with the new version.
2024-11-24 12:06:44 +01:00
paxcut
7e0f60615b fix: Achievements resetting after restart (#1965)
### Problem description
Loading a file on the command line or using the context menu in windows
was triggering an achievement before the achievements file was loaded.
This resulted on the achievements.json file to be overwritten with all
the achievements reset except for the one to open files.

### Implementation description
This PR fixes the problem by introducing a boolean that is used to check
if the file has been loaded.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-11-24 11:34:44 +01:00
Kirill R.
e1a49b38a7 build: Fix macos blurry flicker (#1956)
<!--
Please provide as much information as possible about what your PR aims
to do.
PRs with no description will most likely be closed until more
information is provided.
If you're planing on changing fundamental behaviour or add big new
features, please open a GitHub Issue first before starting to work on
it.
If it's not something big and you still want to contact us about it,
feel free to do so !
-->

### Problem description
<!-- Describe the bug that you fixed/feature request that you
implemented, or link to an existing issue describing it -->

seem to fix #1809. I couldn't build the app, so hoping that's the right
place to update resulting `Info.plist`

### Implementation description
<!-- Explain what you did to correct the problem -->

### Screenshots
<!-- If your change is visual, take a screenshot showing it. Ideally,
make before/after sceenshots -->

### Additional things
<!-- Anything else you would like to say -->
2024-11-24 11:31:30 +01:00
paxcut
4333b8c351 fix: Text cursor not moving to the correct location with ctrl+c -> ctrl+v (#1951)
This code fixes issue #1950 This PR depends on PR [#27
](https://github.com/WerWolv/libwolv/pull/27) on libwolv repo


### Problem description
See description of the problem on the issue linked above

### Implementation description
The code in the PR uses function added to the libwolv repository to
remove tabs if they exist on the provider. Additionally, any pasted tab
on the pattern editor will be translated to spaces automatically. This
code was tested successfully using the pattern posted in the issue.
2024-11-24 11:31:06 +01:00
paxcut
6464377a89 impr: Added code so that when debugger pauses at a line, the line is highlighted (#1932)
regardless of the method used to pause the evaluation at that line.
2024-11-24 11:29:08 +01:00
Shubhankar Sarangi
4fcf732814 impr: Reserve space to avoid multiple allocations when loading scripts (#1929)
std::forward ensures that the arguments are perfectly forwarded to
loadScript
By reserving space in the features vector based on the size of scripts,
we can avoid multiple memory allocations during the loop. If an
exception occurs, returning an empty vector immediately clarifies that
no scripts were loaded. Without reservation, each call to emplace_back
could potentially trigger a reallocation if the current capacity is
exceeded, which is costly in terms of performance. This leads to more
efficient memory management and can significantly speed up the execution
time when dealing with a large number of scripts.


![image](https://github.com/user-attachments/assets/3e290162-fb8b-4f00-a71b-6009494b2dab)
2024-11-24 11:28:45 +01:00
paxcut
0d4f3e5735 fix: ImHex hangs when pressing F5 while in a breakpoint (#1920)
### Problem description
fix: pressing F5 (start pattern execution ) while being in a break point
hangs ImHex.


The reason for hanging ImHex was that the shortcut procedure was not
checking if the pattern was already running, and it attempted to start
another one. This makes ImHex wait indefinitely for a lock to be
released

### Implementation description

To fix the hanging of ImHex we check the runtime for current evaluation
and if detected we stop it. In all cases the evaluation is started
again.
2024-11-24 11:24:42 +01:00
paxcut
1f2e453e20 fix: Various pattern editor settings not being per-provider (#1917)
### Problem description
Fixes provided for the following unreported bugs.

- Environment variables are set to be per provider but used as if they
are not. When a project is loaded all the environment variables for each
provider are assigned to the first provider making it impossible to add
new ones to the other providers.

- When switching providers, the text editor selection, the text editor
breakpoints, the console text, the console selection and the console
cursor position of the old provider are being assigned to the new
provider

### Implementation description

This PR aims at fixing both errors by:
- using variable defined to be per provider so that they affect their
provider only when necessary.

- creating new per provider variables and using them so that each
provider has their own console, selections and breakpoints.

In order to support the newly added per provided features new functions
were added to the text processor for selections and breakpoints. All the
new per provider variables are defined and used in view pattern editor.
2024-11-24 11:24:14 +01:00
Paulo Casaretto
5236c7b468 fix: Use machine headers to auto select arch for macOS process memory provider (#1910)
Fixes https://github.com/WerWolv/ImHex/issues/1807

### Problem description

Build fails for MacOS x86-64 due to using a wrong architecture header.

### Implementation description

Used the headers for mach that auto select the correct architecture.

### Additional things

This is being used in https://github.com/NixOS/nixpkgs/pull/330303 as a
patch

Co-authored-by: Nik <werwolv98@gmail.com>
2024-11-24 11:21:29 +01:00
Ikko Eltociear Ashimine
1738e8883f fix: Typo in tar.hpp (#1909)
occured -> occurred
2024-11-24 11:20:51 +01:00
paxcut
cc4563afb0 impr: Added back missing runtime error markers (#1907)
### Problem description
Moving error markers to be underwaved created s couple of errors: 
- Markers that were 1 char long and located at the end of the line
didn't show on text editor.
- Markers that had zero length or no stack trace didn't show on text
editor.

### Implementation description

- The first error was caused by an off by one error in the column index.
- There was no implementation for errors that had no location or zero
length. Now errors with no location will be shown at the beginning of
the line where they occur. Errors with zero length will be marked from
their location to the end of the line, therefore, errors with no stack
trace will be marked from the beginning to the end of the line.
2024-11-24 11:20:15 +01:00
paxcut
4b3bf2f358 fix: Textures, uv coordinates and light source not updating properly. (#1872)
### Problem description
The only time textures would update was through the file picker. Once UV
coordinates were used, disabling them didn't have any effect because the
vertex array didn't invalidate the corresponding buffer array. When
`shouldUpdate` is true, the light source needs to know as well,
otherwise it will set the location at 0,0.

### Implementation description

Textures were fixed by creating a member variable that holds the file
name of the texture used in the last model rendering.

Instead of invalidating buffer arrays it is much simpler to define a
default UV coordinate set for the case when no UV is specified. if a
texture is not present then the values of UV will not be used. If there
is a texture it must be a minimum of 1 pixel in size. So we choose the
UV coordinates so that every vertex gets assigned the color at the 0,0
coordinate of the texture.

When `shouldUpdate` is on, we also turn `shouldUpdateLightSource` on.

Also included are some formatting changes that are purely aesthetic.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-11-24 11:18:19 +01:00
WerWolv
80084f5c5a patterns: Updated pattern language 2024-11-24 11:17:29 +01:00
descawed
6d14b3f6bd Fix process memory provider on Linux (#1933)
### Problem description
The process memory provider currently doesn't function correctly on
Linux due to incorrect handling of the special procfs file
`/proc/<pid>/maps`. I don't know if some of this behavior could vary by
distro and/or kernel version, but I've observed the following issues in
my Ubuntu 24.04 environment.

- The current code in master calls `file.readString()` which attempts to
determine the size of the file by [seeking to the
end](https://github.com/WerWolv/libwolv/blob/master/libs/io/source/io/file_unix.cpp#L148).
However, procfs files don't have a defined size, so this fails with a
return of -1. libwolv [interprets this as the file size and attempts to
allocate an enormous
buffer](https://github.com/WerWolv/libwolv/blob/master/libs/io/source/io/file.cpp#L30),
which results in an exception, so ultimately the process memory provider
is unusable on the current code.
- The previous version of the code that went out in 1.35.4 was calling
`readString` with a fixed maximum size of `0xF'FFFF`. This avoids the
seek issue, but when working with special files, a single `read` call
isn't guaranteed to read the requested number of bytes even if that many
bytes are available. In practice, on my machine, this call only ever
reads the first few dozen lines of the file. So the feature works in
this version, but it's unable to see the vast majority of the process'
address space.
- On a more minor note, on rows in the `maps` file that have a filename,
the filenames are visually aligned by padding spaces between the inode
column and filename column. ImHex includes these spaces as part of the
filename, resulting in most of the path being pushed out of the visible
area of the window.

### Implementation description

- To ensure the entire `maps` file is read, I've changed the code to
read from the file in a loop until we stop getting data. I've also set a
fixed limit on the maximum number of bytes to read in one go to avoid
issues with trying to determine the file size.
- I've added a `trim` call to remove any padding around the filename.

### Screenshots
Exception in `file.readString()` in current code (for some reason this
also causes the window to become transparent):

![mem_regions_exception](https://github.com/user-attachments/assets/ac9f472b-3d60-446d-be9c-b028b041e547)

Abridged memory region list in 1.35.4:

![mem_regions_truncated](https://github.com/user-attachments/assets/44e60b23-49f8-41b9-a56b-54cb5c82ee72)

Complete memory region list after this PR:

![mem_regions_working](https://github.com/user-attachments/assets/bdb42dc6-bcd3-42b1-b605-a233b98e8d2e)

### Additional things
I was focused on fixing this ImHex feature here, but I wonder if some of
this should be addressed in libwolv. Maybe `readBuffer` in file_unix.cpp
should read in a loop until it has the requested number of bytes or
encounters EOF/error?

---------

Co-authored-by: Justus Garbe <55301990+jumanji144@users.noreply.github.com>
2024-11-07 13:41:04 +01:00
iTrooz
592f613a61 fix: re-enable C/C++ languages in CMake (#1942) 2024-10-24 08:14:07 +02:00
WerWolv
3739bcc40c fix: Multiple race conditions with pattern sorting 2024-10-22 16:20:08 +02:00
WerWolv
101c7a36fb patterns: Updated pattern language 2024-09-18 23:54:56 +02:00
WerWolv
21be959cba fix: Another text editor merge issue 2024-09-15 16:14:43 +02:00
WerWolv
b3a0ebe7b6 fix: Some merge issues 2024-09-15 15:55:21 +02:00
paxcut
96a588bd86 fix: F3 failed to locate the correct set of matches if file was edited after doing a search (#1867)
### Problem description
The bug can be reproduced as follows:
1) Using Ctrl-F do a search for a term that occurs several times in the
file. and press F3 to visit them.
2) Go back to the fop of the file and insert 3 blank lines. 
3) Pressing F3 once or many times will not find the term entered above.


### Implementation description
The reason for this bug is that the positions of the matches are not
being reset when changes can potentially move them.
The fix consists on resetting the search locations when changing the
contents of the file and redoing the search after the changes are made.
The bug was specially problematic when doing replace because the
replacement position would be identified as a match. This PR fixes
replace as well.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-09-15 15:32:10 +02:00
paxcut
866b956680 feat: Added per provider cursor position for the Pattern editor (#1861)
### Problem description
Currently, the pattern editor does not remember where the cursor is
located in each provider. For example, suppose you have 2 providers in
your project, and you scrolled down to line 200 in the first pattern to
make some changes and remembered that the code you want to insert is in
the second provider. Then you switch to the second provider, look for
the code and find it in line 235. Switch back to the first one, and you
are at the beginning of the file. So you again look for the line to edit
paste it to realize that it needs code a few lines before the place you
found it. You switch to the second provider, and you are at the top
again. This gets annoying very fast.

### Implementation description

This PR ensures that, when you return to the pattern in the editor for
any of the opened providers, the cursor will still be at the same place
it was when you switched to a different one. Each provider pattern saves
its cursor position and returns to it when you switch to that provider.
It does that by creating a PerProvider variable and using it when
providers are first opened to set it to the origin and when switching
providers it first saves the position of the old provider and then loads
and sets the saved position of the new provider.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-09-15 15:28:37 +02:00
paxcut
d88252c6fd fix: Unable to resize 3d-visualizer window in x-direction (#1860)
changes needed were:
1) add an extra dummy empty widget so that width of child and parent are
not always the same. 2) Width of reset button needs to be adjusted when
the width of the child is decreased so that the parent is decreased too.

<!--
Please provide as much information as possible about what your PR aims
to do.
PRs with no description will most likely be closed until more
information is provided.
If you're planing on changing fundamental behaviour or add big new
features, please open a GitHub Issue first before starting to work on
it.
If it's not something big and you still want to contact us about it,
feel free to do so !
-->

### Problem description
<!-- Describe the bug that you fixed/feature request that you
implemented, or link to an existing issue describing it -->

### Implementation description
<!-- Explain what you did to correct the problem -->

### Screenshots
<!-- If your change is visual, take a screenshot showing it. Ideally,
make before/after sceenshots -->

### Additional things
<!-- Anything else you would like to say -->
2024-09-15 15:27:39 +02:00
paxcut
414e7d36a0 fix: Double-clicking a string selects the closing double quotes (#1862)
This is a simple fix for a simple issue. Just check if the last char in
the selection is a double quote and if it is, make the selection one
char shorter.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-09-15 15:27:24 +02:00
paxcut
e0b4931a54 fix: 3D visualizer running very slowly with energy saving enabled (#1866)
### Problem description
The bug described in #1663 was caused by an optimization of the display
rendering that uses drawlists to detect changes. The changes in the 3-d
visualizer don't contain drawlists when axes are turned off.

### Implementation description
The fix is to identify the 3d visualizer among the command lists of the
main window and, if found, avoid skipping frames regardless of the
result of the comparison of drawlists.

Closes #1663
2024-09-15 15:23:58 +02:00
paxcut
a587c5ff74 feat: Added a quarter precision (8 bits) button to IEEE 745 tool (#1868)
Per discussions on Discord.
2024-09-15 15:22:35 +02:00
paxcut
0b2eca3066 fix: LZMA decompressor memory errors (#1873)
<!--
Please provide as much information as possible about what your PR aims
to do.
PRs with no description will most likely be closed until more
information is provided.
If you're planing on changing fundamental behaviour or add big new
features, please open a GitHub Issue first before starting to work on
it.
If it's not something big and you still want to contact us about it,
feel free to do so !
-->

### Problem description
I was unable to use the LZMA de-compressor even though 7zip was able to
identify them as LZMA compressed and decompress them without a problem.
Under the debugger the `lzma_code()` call was returning
`LZMA_MEMLIMIT_ERROR`.
### Implementation description
I found online that the error can be fixed using `lzma_memlimit_set()`
using a value obtained with `lzma_memusage()`. I tried to avoid having
to call `lzma_code()` twice but if the functions are called before the
first `lzma_code()`the values of memory obtained fall short and error
occurs again.

I suspect that there are better ways to deal with this other than the
code proposed in this PR, but I haven't been able to find any.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-09-15 15:20:17 +02:00
paxcut
fa28052958 fix: Avoid crashing ImHex when passing invalid data to the 3D visualizer (#1874)
### Problem description
There are some obvious constrains in the various array data sizes that
we can use to determine if their sizes and in some cases their values
are correct.

### Implementation description
To test their validity, the most important of the various arrays are the
indices, so their definition and use has been simplified a great deal.
In order to treat all variables in a similar manner the changes to the
uv variable posted in an earlier PR were also added here.

With this one, all the recently opened PR's combined should contain
exactly the same changes and fixes as the older 3-d visualizer PR #1850
which I will close shortly after this one is opened.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-09-15 15:19:41 +02:00
paxcut
54f5bd1d80 feat: Added underwaved text functions (#1889)
### Problem description
Currently when errors are found the entire line where the error occurred
is highlighted and one has to look at the error message in order to find
where the error is located on the line. With this PR the line will no
longer be highlighted and the location of the error will be marked with
an red waved line under the error location. Hovering over the text where
the error occurred produces an error overlay so if several errors occur
on the same line they can all be seen separately.

### Implementation description
The definition of error marker was switched to include column and size
as well as line and message like before.
This change required changing the way view pattern editor draws the
error markers because the errors themselves don't have size information.
Also, a new errorHoverBoxes type was defined to help in the detection of
the floating error messages when error is hovered.

Note that the underwave code depends on having a monospaced. If font is
not monospaced the underwaved text can be short/long or displaced.


### Screenshots

![image](https://github.com/user-attachments/assets/f0b08e10-612c-404a-8863-d4f00054d198)


![image](https://github.com/user-attachments/assets/911fcacb-2a1e-431f-bbc8-8e05bcd61341)
2024-09-15 15:19:04 +02:00
paxcut
4b3bbb4a97 impr: Moved pattern editor shortcuts to the Shortcut manager (#1892)
### Problem description
There are some recent issues about Mac keys not configured properly for
the pattern editor. This PR moves all the shortcuts to the shortcut
manager, so they can be edited at will. Even if the key is not
identified correctly it should be possible to use preferred keys for any
action.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-09-15 15:18:50 +02:00
xtex
187d90e8f2 lang: Update Chinese (Simplified) translations (#1894)
Co-authored-by: JustFor <35858818+zhongqingsong@users.noreply.github.com>
2024-09-15 15:17:25 +02:00
rockisch
2f60f61c15 impr: Add streaming decompression to zstd_decompress (#1898)
<!--
Please provide as much information as possible about what your PR aims
to do.
PRs with no description will most likely be closed until more
information is provided.
If you're planing on changing fundamental behaviour or add big new
features, please open a GitHub Issue first before starting to work on
it.
If it's not something big and you still want to contact us about it,
feel free to do so !
-->

### Problem description

https://github.com/WerWolv/ImHex/issues/1895

### Implementation description

Added code that handles streamed zstd data. It is based around the
[official
documentation](http://facebook.github.io/zstd/zstd_manual.html) and the
[example](https://github.com/facebook/zstd/blob/dev/examples/simple_decompression.c)
provided at the main zstd repo.

The loop around the non-streamed version was also removed because I
don't think it was doing anything (no `continue`s, `sourceSize` was
always being set to 0).

### Additional things

To test, I generated streamed zstd data with this python script:

```py
import io; import pyzstd;
with open("data.zstd", "wb") as f:
    pyzstd.compress_stream(io.BytesIO(b'ab' * 100), f)
```

And then I ran this pattern script:
```
import std.mem;
import hex.dec;

u8 data[while(!std::mem::eof())] @ 0x00;
std::mem::Section data_sec = std::mem::create_section("data_sec");
hex::dec::zstd_decompress(data, data_sec);
```

Inspecting the section shows the correct data:

![image](https://github.com/user-attachments/assets/83fc9d4c-e6fa-49ee-9923-29dc0c280739)

Co-authored-by: Nik <werwolv98@gmail.com>
2024-09-15 15:16:57 +02:00
paxcut
057543da15 feat: Extended bitmap visualizer to handle indexed colormaps (#1901)
### Problem description
Older image format use to store color values in a small lookup table so
that the image could simply store an index to the table. The pattern
language is not designed to handle this sort of operation which makes
this extension necessary to be able to visualize images of this type.

### Implementation description

The changes add an optional parameter to the bitmap visualizer which
holds the color lookup table. If the image contains values that are
outside the range of possible colors then the first color in the map is
chosen. The dimensions of the image can be equal to or smaller than
rows*columns depending on how the indices to the color map are stored.
For example, you can use 4 bit indices which would make the image half
the size (in bytes) but that limits the number of colors to 16. To store
colors in sizes larger than one byte use an array of the appropriate
sized integers.

### Screenshots


![image](https://github.com/user-attachments/assets/d068cb7e-3ff3-450d-8ac2-1bfc6e38043f)
2024-09-15 15:16:36 +02:00
paxcut
3c060cc57a fix: Finding utf-8 strings failed to select their location. (#1902)
other separate, but closely related fixes are:

- fix: The previous fix also solved the (unreported) bug of being unable
to select utf-8 works by double-clicking.
- fix: The move to next/previous word (Ctr-arrow) behaved differently
depending on the direction. I made both the move left/right functions
share a much simpler algorithm and rewrote the find start/end of word
functions share the same code structure.


### Problem description
The code was using the byte index of the match into the utf-8 string to
store the match locations, but the code that sets the selection uses the
char index into the utf-8 string instead. Another problem was that the
search uses the byte index to determine if it needs to find more
matches.

### Implementation description
Both problems were solved by introducing two functions to switch from
coordinates in units of bytes to coordinates in units of chars and vice
versa.

Co-authored-by: Nik <werwolv98@gmail.com>
2024-09-15 15:16:19 +02:00
paxcut
928b4c6c4c fix: Reset cursor blink when moving selection (#1903)
### Problem description
When this feature was implemented the text editor handled all the
keyboard input so the blink reset function could be called in one place
for all the key presses. Now that shortcuts are done in the shortcut
manager we need to reset the blink state inside all the functions that
can affect cursor movement.

### Implementation description
Every function that moves the cursor now calls the blink state reset
function at the very start. There may be more functions that need this
that haven't been merged but git should show merging conflicts so it
should be easy to deal with.
2024-09-15 15:15:14 +02:00
WerWolv
871a0d535c build: Fix building issues on macOS with clang 18 2024-09-08 10:45:38 +02:00
WerWolv
87db9def32 build: Updated libwolv 2024-09-03 11:09:01 +02:00
WerWolv
04763eaeea patterns: Updated pattern language 2024-08-23 21:37:46 +02:00
JustFor
b6c08a1a11 lang: Updated zh_CN language definition (#1827)
### Problem description
1. Old Chinese text json, the order is chaotic. It doesn't compare well
with English.
2. Missing a batch of new English strings.

### Implementation description
1. Synchronize the key sequence of English files.
2. Added a missing batch of text, and translate to CN.

### Screenshots
None

### Additional things
None
2024-08-20 20:31:33 +02:00
xtex
811c995047 build: Find boost with name "Boost" (#1840)
On many distributions like AOSC OS, Alpine Linux, Arch Linux, etc.,
boost should be searched with name "Boost".

This should fix the packaging issue on AOSC OS.

### Problem description
CMake fails to find system boost when `USE_SYSTEM_BOOST` is set to ON.

### Implementation description
Find Boost.

Signed-off-by: xtex <xtexchooser@duck.com>
2024-08-20 20:29:03 +02:00
WerWolv
7011df2ced fix: Reading entire file content of base64 file into memory not working 2024-08-20 20:27:08 +02:00
WerWolv
a24692b4be fix: Revert ndf-extended changes for now to fix file dialogs on Linux 2024-08-20 20:08:01 +02:00
WerWolv
0e7a32470b patterns: Updated pattern language 2024-08-20 20:04:52 +02:00
WerWolv
212d2f9db4 patterns: Updated pattern language 2024-08-10 09:17:41 +02:00
Colin Snover
0263d3538e fix: Don't supress stderr anymore (#1822)
### Problem description

Typing `--help` causes ImHex to exit without outputting anything.
Diagnostic messages from glib, ASan, other libraries that might have
something important to say, etc. are also suppressed.

### Implementation description

This effectively reverts 7c1e33dde6, which
was partially reverted only on Windows by code that was left commented
out in f114239f51.

Allowing other libraries to print to stderr may make the output ‘ugly’,
but lots of things print to stderr that are important for figuring out
why something is bugged, like ASan and glib.

### Additional things


![image](https://github.com/user-attachments/assets/fa6771e2-da2e-45ea-93cd-06c3f6bfd3bf)
2024-08-09 22:15:34 +02:00
WerWolv
63c6028522 build: Updated ImGui to v1.91.0 2024-08-03 23:49:47 +02:00
WerWolv
075ece2da7 impr: Clean up windows window code 2024-08-03 22:18:16 +02:00
WerWolv
e9fb02285e impr: Allow tasks to be created without getting the task handle as parameter 2024-08-03 22:01:18 +02:00
WerWolv
5dfd8c89a3 feat: Display pattern descriptions in file chooser and pattern popup 2024-08-03 22:00:47 +02:00
WerWolv
e9f7908afb git: Increase stale issue operations to 200 2024-08-03 20:10:09 +02:00
WerWolv
fafce72c01 fix: Errors causing #pragma magic to not work as expected 2024-08-03 20:09:10 +02:00
WerWolv
c3d15157ad git: Silence brew commands spewing errors into the CI log 2024-08-03 18:41:17 +02:00
WerWolv
e0712f73c2 git: Better build CI script formatting 2024-08-03 18:40:56 +02:00
WerWolv
3dd5b2365a git: Increased stale issue operations per run to 100 2024-08-03 18:39:26 +02:00
WerWolv
b523f55984 git: Kill XProtect on git runners to work around race condition 2024-08-03 18:32:45 +02:00
Nik
79b8b77b25 git: Allow inactive issues ci to be triggered manually 2024-08-03 18:24:31 +02:00
WerWolv
c6065808a7 git: Skip codecov CI step if token isn't set 2024-08-03 18:22:15 +02:00
Justus Garbe
d69ae39b6f git: Added stale issues action (#1836)
Added stale issues action:
- Runs on cron every 30 days
- Marks issues as stale after 11 months
- Closes issues marked as stale after 1 month
2024-08-03 18:22:11 +02:00
WerWolv
35739d6d0d feat: Display pattern description on the accept pattern popup 2024-08-03 18:15:30 +02:00
WerWolv
e726fce360 patterns: Updated pattern language
Fixes #1835
2024-08-03 17:56:13 +02:00
WerWolv
0a038fecff impr: Re-parse patterns only when the user stopped typing 2024-08-03 17:00:23 +02:00
WerWolv
0184bf9a7d impr: Only mark providers dirty when they're not dirty already 2024-08-03 17:00:09 +02:00
WerWolv
60663babc8 impr: Optimize hovering over patterns in the hex editor 2024-08-03 16:50:30 +02:00
WerWolv
a7115d4300 fix: Race condition during data processor execution 2024-08-03 15:17:35 +02:00
WerWolv
29558c9910 impr: Remove superfluous concatenation operators for Lang strings 2024-08-03 11:35:36 +02:00
WerWolv
7c1d643f97 patterns: Updated pattern language 2024-08-03 11:33:15 +02:00
WerWolv
b2fc80f970 impr: Fix various issues with runtime-generated language strings 2024-08-03 11:32:17 +02:00
WerWolv
efee128c1c patterns: Updated pattern language 2024-07-28 10:43:15 +02:00
WerWolv
c3ddd68866 fix: Correct more language strings 2024-07-27 16:54:05 +02:00
WerWolv
3cde4472c8 impr: Jump to selection in main hex editor as well when clicking on diff entries 2024-07-27 16:52:15 +02:00
WerWolv
4c38fe261d feat: Make diff table resizable 2024-07-27 16:51:43 +02:00
WerWolv
33f7191c0d fix: Copy paste error 2024-07-27 16:46:10 +02:00
WerWolv
cda9ad3b30 patterns: Updated pattern language 2024-07-27 16:33:37 +02:00
WerWolv
1a7bd49361 impr: Make all task names properly translatable 2024-07-27 16:29:06 +02:00
WerWolv
cf2e189049 fix: Building issues on Fedora 2024-07-27 15:55:59 +02:00
WerWolv
d5f5ba941a patterns: Updated pattern language 2024-07-27 14:16:01 +02:00
WerWolv
9a973be7ba fix: Background service thread names 2024-07-27 14:15:51 +02:00
WerWolv
d8e1284946 fix: Task names not displaying correctly anymore 2024-07-27 14:09:52 +02:00
WerWolv
ce26fe1db7 impr: Move language string interpretation to compile time 2024-07-27 11:23:21 +02:00
WerWolv
a8ad045248 fix: Parent offset calculation with non-zero base addresses 2024-07-26 19:43:15 +02:00
WerWolv
d097f6ada0 impr: Make pattern tooltips more appropriately sized 2024-07-26 19:38:21 +02:00
WerWolv
1b26db40f7 feat: Added parent offset to pattern hover tooltip 2024-07-26 19:38:01 +02:00
WerWolv
602b946fc9 patterns: Updated pattern language 2024-07-24 19:52:03 +02:00
WerWolv
48fc1a7a1e fix: Allow ImHex to build under wayland again 2024-07-24 19:41:34 +02:00
WerWolv
416889f49d impr: Optimize time it takes to find favorites in patterns 2024-07-24 19:41:12 +02:00
WerWolv
5ca3222e5b patterns: Updated pattern language
Fixes #1828
2024-07-24 19:40:27 +02:00
WerWolv
d49d82e982 fix: Building with latest pattern language changes 2024-07-23 20:32:16 +02:00
WerWolv
a4d5679219 fix: Crash when opening hex editor popups 2024-07-23 20:32:04 +02:00
WerWolv
bead103f3d patterns: Updated pattern language 2024-07-23 18:29:37 +02:00
Jean-François Nguyen
e50b6733c4 fix: Segfault when hashing regions spanning multiple MiBs (#1804)
### Problem description

Attempting to do an MD5 hash of a large region (e.g. 2 MiB, ``u8
data[0x200000]``) crashes with a segfault.

### Implementation description

In ``hex::plugin::hashes::hashProviderRegionWithHashLib()``,
``hashFunction->TransformBytes()`` is called with an offset of 0,
because it iterates over ``data`` and not the entire region.
2024-07-21 20:35:38 +02:00
xndcn
75e5dbaaa4 build: Fix incorrect name case in FindmbedTLS.cmake (#1817)
Corrected MBEDTLS_FIND_REQUIRED to mbedTLS_FIND_REQUIRED, since the
package name is "mbedTLS" for case sensitive environment
2024-07-21 20:34:23 +02:00
xndcn
965113c2b4 fix: Fix lzma stream end constant name (#1818)
Corrected BZ_STREAM_END to LZMA_STREAM_END.
Also removed redundant condition of LZMA_STREAM_END for error checking.
2024-07-21 20:33:46 +02:00
checkraisefold
3bddaf509d fix: Textures provided through the pattern language not rendering in the 3D visualizer (#1819)
<!--
Please provide as much information as possible about what your PR aims
to do.
PRs with no description will most likely be closed until more
information is provided.
If you're planing on changing fundamental behaviour or add big new
features, please open a GitHub Issue first before starting to work on
it.
If it's not something big and you still want to contact us about it,
feel free to do so !
-->

### Problem description
Because of `s_drawTexture` never being set to true, textures rarely or
never drew in the 3D visualizer.

### Implementation description
Set `s_drawTexture` to true when correct (valid texture file/object).
2024-07-21 20:33:05 +02:00
Colin Snover
c1c51e0baf feat: Enumerate fonts on Linux using Fontconfig when available (#1821)
### Problem description

The fonts list on Linux does not show all system fonts, and does not
show font names at all.

### Implementation description

Use Fontconfig to make the list less bad if Fontconfig headers are
available.

### Additional things

I like fonts.

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-07-21 20:28:37 +02:00
WerWolv
09b6c2ab5b fix: Error log spamming when viewing invalid regions in process memory provider on linux 2024-07-21 20:24:26 +02:00
Colin Snover
13fd956039 fix: Do not connect to api on startup when server contact setting is disabled (#1823)
### Problem description

ImHex asks users whether they wish to opt-in to network connections on
start (excellent!), then ignores that and tries to connect to the
network anyway when the welcome screen loads (less excellent!).

### Implementation description

Also don’t connect to the network on the welcome screen if it is
supposed to not do that.
2024-07-21 20:14:02 +02:00
WerWolv
b6f0ee90af fix: Sidebar panels not being resizable anymore properly 2024-07-16 18:15:28 +02:00
WerWolv
90e11e1c5d fix: Crash when parsing process memory provider regions 2024-07-16 18:11:06 +02:00
WerWolv
fc40e8ba70 fix: Process memory provider region parsing skipping unnamed regions 2024-07-16 17:58:49 +02:00
WerWolv
7652b4a5b8 fix: Compiling on Linux with older glfw versions 2024-07-16 17:58:19 +02:00
Colin Snover
fb249767f1 fix: Crash on exit when using custom font from file (#1815)
### Problem description
WerWolv/ImHex#1814

### Implementation description
1. Remove the flag that wrongly tells `ImFontAtlas` that it owns font
data, and remove that parameter from the function signature entirely
since now it is always `false`.
2. Rename `takeAtlas` to `getAtlas` since it no longer transfers
ownership as of b652565b57.
2024-07-15 22:22:02 +02:00
WerWolv
d7ed311bcf impr: Don't auto-scale the framebuffer on Linux 2024-07-12 17:34:20 +02:00
WerWolv
8422965d0b impr: Run data processor in a worker task 2024-07-11 23:30:54 +02:00
WerWolv
7975edade4 feat: Added loop data processor node 2024-07-11 20:38:33 +02:00
WerWolv
1e18935513 impr: Handle demangling of identifiers without leading underscore 2024-07-11 20:38:22 +02:00
WerWolv
c311b5315f patterns: Updated pattern language 2024-07-11 18:02:48 +02:00
WerWolv
26a73e0fba patterns: Updated pattern language 2024-07-11 17:40:18 +02:00
WerWolv
07c259c9c1 fix: Multiple issues causing visualizers to crash when used _slightly_ incorrectly 2024-07-10 20:50:58 +02:00
WerWolv
9e1c2d5a2c build: Fix copy-paste bug 2024-07-10 20:50:20 +02:00
WerWolv
d7fb1b737f fix: Occasional crash when closing providers 2024-07-09 19:01:49 +02:00
iTrooz
84c9c69fa3 fix: Remove DSA key from AUR deploy action (#1806) 2024-07-09 09:23:33 +00:00
WerWolv
12ca4e29cf fix: Multiple definitions errors with plugin features 2024-07-08 21:34:47 +02:00
WerWolv
27b1a5dc98 impr: Make highlight hovering more efficient 2024-07-08 21:34:27 +02:00
WerWolv
de36cc8445 impr: Disable pattern debug mode after evaluation has finished 2024-07-08 19:49:31 +02:00
WerWolv
03d344c0a2 build: Streamline definition on plugin features 2024-07-08 18:12:46 +02:00
WerWolv
39f01538c7 git: Update Mesa3D link for Windows NoGPU version 2024-07-07 16:17:03 +02:00
WerWolv
28c57cf666 patterns: Updated pattern language 2024-07-07 15:47:58 +02:00
WerWolv
59d120537d feat: Added non-frame lz4 compression support to the pattern language 2024-07-07 15:23:18 +02:00
WerWolv
66d18e9475 patterns: Updated pattern language 2024-07-07 13:59:56 +02:00
WerWolv
1f5e4ceb0c feat: Added basic support for lz4 decompression to the pattern language 2024-07-07 10:26:24 +02:00
Sébastien Szymanski
0cbc65a52f build: Fix Gentoo ebuild (#1787)
### Problem description
Ebuild is invalid, i.e:
```
# ebuild ImHex-9999.ebuild manifest
Error(s) in metadata for 'app-editors/ImHex-9999':
  RDEPEND: Invalid atom (dbus), token 5
```

### Implementation description
* mbedtls is in net-libs category
* RDEPEND must contain atoms (category/packagename)

Signed-off-by: Sébastien Szymanski <sebastien.szymanski@armadeus.com>
Co-authored-by: Nik <werwolv98@gmail.com>
2024-07-07 10:25:10 +02:00
WerWolv
2b0367cca6 impr: Better handling of the scaling warning when using custom fonts 2024-07-06 11:30:59 +02:00
WerWolv
1f01f480e0 impr: Enable native scaling by default again 2024-07-06 11:29:52 +02:00
WerWolv
7a167962d6 fix: Font scaling not always being applied consistently 2024-07-06 11:29:14 +02:00
WerWolv
dae028d25d fix: Build issue due to uncaptured this pointer 2024-07-05 21:03:24 +02:00
WerWolv
88e2fa04e7 fix: Crash on macOS when dirtying or undirtying a provider from a thread
Fixes #1799
2024-07-05 20:59:20 +02:00
WerWolv
bb0a8047ea fix: Hex editor popups getting transparent when hovering over combo box popup 2024-07-05 19:26:08 +02:00
WerWolv
b652565b57 feat: Added DPI awareness on Windows, added FiraCode as optional default font 2024-07-05 17:39:07 +02:00
WerWolv
9aaf6f3105 web: Trigger right click when long touching area 2024-07-04 23:15:33 +02:00
WerWolv
c26eccfe28 web: Fix canvas to the top left of the screen 2024-07-04 21:37:51 +02:00
WerWolv
9fd547112d impr: Only handle SIGINT on release builds so IDEs can fast-kill ImHex 2024-07-04 21:28:43 +02:00
WerWolv
14bfc8af72 fix: Remove unnecessary touch padding 2024-07-04 21:18:46 +02:00
WerWolv
20f3458e37 patterns: Updated pattern language 2024-07-04 21:18:34 +02:00
WerWolv
6326e2d141 web: Improve logo size on mobile 2024-07-03 22:35:47 +02:00
WerWolv
23ca3c1d2d patterns: Updated pattern language 2024-07-03 22:35:47 +02:00
WerWolv
0656ab4b88 fix: Make sure welcome screen always stays in the background 2024-07-03 22:35:47 +02:00
WerWolv
90bb5d187c web: Fix touch input 2024-07-03 22:35:47 +02:00
WerWolv
75a62e2bde fix: Wrong start/end offset and size for static array entries in pattern data view 2024-07-03 16:58:56 +02:00
WerWolv
7cd36b80eb impr: Added tooltips to toolbar buttons 2024-07-03 16:58:25 +02:00
Bernard Teo
dd607621d7 build: Update nativefiledialog and keep dialogs on top (#1771)
This PR updates the nativefiledialog submodule and uses its new feature
to set the ImHex main window as the parent of the dialog window. This
ensures that the dialog stays on top of the main window. This is
currently supported by NFDe on Windows, macOS, and Linux/X11.
Linux/Wayland behaves as it did previously due to limitations in NFDe.

Note that macOS file dialogs have already been parented properly as NFDe
previously used the key window (the window currently receiving keyboard
events) on macOS. However, it's probably better to do the correct thing
and pass the main window to NFDe even on macOS.

### Problem description
The file dialog go behind the main window if the main window is clicked
while the file dialog is open.

### Implementation description
Update nativefiledialog and pass the `GLFWwindow*` of the main window to
the library function.

### Screenshots
Before:


https://github.com/WerWolv/ImHex/assets/6948096/589c3401-702a-4b0a-99ed-02d3e4d9080e

After:


https://github.com/WerWolv/ImHex/assets/6948096/8fef4900-eedc-48d5-8a4e-7bd81e37e3c0

### Additional things
I have tested this on Windows and Linux/X11, but did not test this on
macOS. It would be ideal if someone can help with this. (But as far as
NFDe is concerned, macOS `NSWindow*` handles have been tested (with
SDL2) and works.)

Co-authored-by: Nik <werwolv98@gmail.com>
2024-07-03 05:53:55 +00:00
WerWolv
2595febf14 patterns: Updated pattern language 2024-07-02 23:46:06 +02:00
WerWolv
dc058c4cf3 fix: Remove interactive help debug code 2024-07-02 23:17:12 +02:00
WerWolv
25824e1821 patterns: Updated pattern language 2024-07-02 23:16:32 +02:00
WerWolv
381c2d52ee web: Improved canvas webgl creation logic 2024-07-02 23:16:19 +02:00
WerWolv
4020ac9843 impr: Added nicer console warning when .NET runtime isn't installed 2024-07-02 23:15:54 +02:00
WerWolv
b3b7a19df4 fix: Wrong end address for bitfield fields in pattern data view 2024-07-02 17:38:53 +02:00
WerWolv
313e3e748f impr: Improved size display in pattern data view 2024-07-02 17:38:39 +02:00
WerWolv
09b9f26e6f patterns: Updated pattern language 2024-07-02 17:37:47 +02:00
WerWolv
01b9cc64d6 impr: Disable tab overlines 2024-07-01 23:53:14 +02:00
WerWolv
97bf1dc850 fix: Potential race condition with sorting in the pattern drawer 2024-07-01 23:36:17 +02:00
WerWolv
f94794fe3e patterns: Updated pattern language 2024-07-01 22:14:51 +02:00
WerWolv
68e528dd3a impr: Added Boost.Regex to about page 2024-07-01 22:01:28 +02:00
WerWolv
06ab1d34aa build: Updated ImGui, libfmt and libyara 2024-07-01 22:00:08 +02:00
WerWolv
2f2717e9aa impr: Completely eradicate Window resize flickering on Windows 2024-07-01 20:50:10 +02:00
WerWolv
88d24c2a03 web: Fix ImHex logo and progress bar default fill 2024-07-01 20:36:55 +02:00
WerWolv
ec2a2a6fbb git: Improve GPU information in the readme 2024-07-01 20:09:30 +02:00
WerWolv
60b81e714b impr: Prevent canvas flickering in web build 2024-07-01 20:09:16 +02:00
WerWolv
2cd8b13c1d build: Use ninja to build web version 2024-07-01 20:07:21 +02:00
Ikko Eltociear Ashimine
4afedb5131 chore: Fixed typo in cmake script (#1783)
<!--
Please provide as much information as possible about what your PR aims
to do.
PRs with no description will most likely be closed until more
information is provided.
If you're planing on changing fundamental behaviour or add big new
features, please open a GitHub Issue first before starting to work on
it.
If it's not something big and you still want to contact us about it,
feel free to do so !
-->

### Problem description
<!-- Describe the bug that you fixed/feature request that you
implemented, or link to an existing issue describing it -->
Accomodate -> Accommodate
### Implementation description
<!-- Explain what you did to correct the problem -->

### Screenshots
<!-- If your change is visual, take a screenshot showing it. Ideally,
make before/after sceenshots -->

### Additional things
<!-- Anything else you would like to say -->
2024-07-01 08:24:59 +02:00
WerWolv
71880ad2ad git: Checkout correct repositories in plugin test CI 2024-06-30 22:35:15 +02:00
WerWolv
a30cce4cbc git: Checkout ImHex main repo in plugin template test runner 2024-06-30 22:25:09 +02:00
WerWolv
08b4f60ead git: Added CI runner to test plugin template building 2024-06-30 22:15:04 +02:00
WerWolv
11498bd09b build: Properly look for boost and libimhex library in sdk again 2024-06-30 21:55:29 +02:00
Nik
7384c88ad6 git: Update resource requirement in readme 2024-06-30 10:46:00 +02:00
WerWolv
6f22d70d59 fix: Updater executable not being launched correctly when path had spaces in it
Fixes #1780
2024-06-30 07:59:25 +02:00
WerWolv
adc279d681 impr: Further try to improve window resize flickering on Windows 2024-06-29 23:32:44 +02:00
WerWolv
f90dc5d619 fix: ImHex hanging at startup in certain cases 2024-06-29 21:13:04 +02:00
WerWolv
6fd594c1f4 fix: Don't delete font atlas after passing it to ImGui 2024-06-29 20:26:46 +02:00
WerWolv
b94a4288bf fix: Standard magic file not getting bundled into executable correctly 2024-06-29 19:43:24 +02:00
WerWolv
cbf415256b fix: Default folders still not being created correctly on Linux 2024-06-29 19:15:09 +02:00
WerWolv
4b1884944d fix: Exception when opening a null provider 2024-06-29 18:49:23 +02:00
WerWolv
5ff752c9af build: Bumped version to 1.36.0.WIP 2024-06-29 18:48:36 +02:00
WerWolv
0e331a7cd1 build: Bumped version to 1.35.1 2024-06-29 13:01:53 +02:00
WerWolv
10970d170c fix: Default folders not being created correctly anymore 2024-06-29 13:01:25 +02:00
WerWolv
ac1a28311c build: Bumped version to 1.35.0 2024-06-29 11:27:24 +02:00
WerWolv
01d1938fea git: Update macOS version requirement in readme
#1647
2024-06-29 10:34:41 +02:00
WerWolv
802694ec68 build: Silence macOS CI build warnings 2024-06-28 22:29:38 +02:00
WerWolv
2aef5e4eef build: Lock install path in rpath behind an option 2024-06-28 22:21:10 +02:00
WerWolv
9a0a4d47dc build: Disable source_date_epoch_from_changelog 2024-06-28 21:53:34 +02:00
WerWolv
96b7366d53 build: Try fixing fedora build spec again 2024-06-28 21:29:49 +02:00
WerWolv
90ac96298a impr: Only re-render frame once during window resize or move operations 2024-06-28 21:27:35 +02:00
WerWolv
a6e5040e8f fix: Build issues on Fedora due to missing Changelog value 2024-06-28 18:29:24 +02:00
WerWolv
19e5aafc85 fix: String truncating being completely borken 2024-06-28 18:29:10 +02:00
WerWolv
77301fd018 impr: Swap some items between File and Edit menu to fit better 2024-06-28 11:13:03 +02:00
WerWolv
ed56b3dd12 impr: Limit string length by cutting out part of the middle instead 2024-06-28 11:12:41 +02:00
WerWolv
91f6aae9ef impr: Make Win32 API properly use unicode support 2024-06-28 11:12:17 +02:00
WerWolv
b642c493d7 fix: Opening files with unicode paths in external program/explorer not working 2024-06-27 23:12:20 +02:00
WerWolv
a950796306 fix: Recent file entry name encoding being broken 2024-06-27 22:40:19 +02:00
WerWolv
8672a2cfe0 fix: Content store downloads getting stuck sometimes 2024-06-27 19:54:45 +02:00
WerWolv
301e8c5a96 impr: Improve contrast of text in pattern data table when hovering 2024-06-27 19:45:49 +02:00
WerWolv
699a91c46b fix: Path in pattern tooltip wrapping too quickly 2024-06-27 19:27:54 +02:00
WerWolv
e43016735d fix: Open file in containing folder not working 2024-06-27 19:25:02 +02:00
WerWolv
d9cecbbb5f impr: Don't flash bang people when the ImHex main window appears 2024-06-27 17:11:28 +02:00
WerWolv
6e186e7d6a impr: Clean up .NET script loader error messages 2024-06-27 17:11:28 +02:00
WerWolv
af3680649c patterns: Updated pattern language 2024-06-27 17:10:48 +02:00
WerWolv
82f1d08dd7 fix: Race condition when loading projects while other providers are loaded already 2024-06-27 17:10:42 +02:00
WerWolv
b1b54a5fe7 impr: Drastically optimize event handler 2024-06-27 17:10:01 +02:00
WerWolv
ced3af3935 fix: Revert pattern include path back to the original paths 2024-06-27 17:09:48 +02:00
WerWolv
e5c782ebe9 impr: Further optimize ImGui text rendering 2024-06-27 17:09:20 +02:00
WerWolv
7d42742684 fix: Properly check return value of std::fgets 2024-06-26 22:46:01 +02:00
FireNX70
41820311cc fix: Off-by-one error in "Export selection to file" (#1774)
### Problem description
Export selection to file would never finish and wouldn't export the last
byte.

### Implementation description
It was just a simple off by one when using the selection's end address
to calculate the remaining data size. Add one to the remaining size
calculation.

### Additional things
Fixes https://github.com/WerWolv/ImHex/issues/1733,
https://github.com/WerWolv/ImHex/issues/1619 and
https://github.com/WerWolv/ImHex/issues/1597.
2024-06-26 22:44:10 +02:00
WerWolv
e132adad5d impr: Add short delay before a hover tooltip appears 2024-06-26 20:38:06 +02:00
WerWolv
2132e5adbf feat: Added tooltip to nightly icon on welcome screen 2024-06-26 20:37:39 +02:00
WerWolv
e2d55446fe impr: Get rid of more unnecessary ImGui::Text() calls 2024-06-26 19:41:06 +02:00
WerWolv
1dfce6a5c2 feat: Added --reset-settings command 2024-06-26 19:38:25 +02:00
WerWolv
a84db9821c impr: Optimize default hex cell visualizer 2024-06-26 19:15:49 +02:00
WerWolv
ec080ad69f fix: Indentation and wrapping of pattern hex editor tooltips 2024-06-26 19:14:43 +02:00
WerWolv
75cc9e4d84 fix: Pattern data filtering not applying correctly after rerunning pattern 2024-06-26 19:14:23 +02:00
WerWolv
d241a3ed5f impr: Make PageUp and PageDown not move the selection anymore 2024-06-26 19:14:01 +02:00
WerWolv
682aab8b23 feat: Allow faster hex editor scrolling by holding down CTRL or SHIFT + CTRL 2024-06-26 19:13:42 +02:00
WerWolv
474862b4af impr: Replace hardcoded pattern syntax highlighting colors style colors 2024-06-26 19:13:15 +02:00
WerWolv
dd02ec7a8e impr: Make the highlights minimap visualizer the default 2024-06-26 19:12:20 +02:00
WerWolv
1eadb77722 fix: Item tooltips being sized incorrectly 2024-06-26 19:11:59 +02:00
WerWolv
95f71bcb10 fix: Sub windows being used incorrectly 2024-06-26 19:11:31 +02:00
WerWolv
e1a4707569 impr: Make sure assertion handler doesn't get called too often 2024-06-26 19:10:43 +02:00
WerWolv
5a10613dd2 build: Add lib folder to all plugin's RPATH 2024-06-25 23:17:15 +02:00
WerWolv
c6a569ed88 impr: Don't reconstruct toolbar items list every frame 2024-06-25 23:14:05 +02:00
WerWolv
de24453fb9 impr: Open windowing menu on mouse down instead of on mouse up 2024-06-25 22:59:46 +02:00
WerWolv
d7c5c84110 build: Don't link plugins with plugin test library except in the test CI 2024-06-25 21:54:48 +02:00
WerWolv
95166ccfb8 impr: Further cleanup hex editor footer 2024-06-25 21:19:59 +02:00
WerWolv
c56667b0dd patterns: Updated pattern language 2024-06-25 20:57:45 +02:00
WerWolv
f754560bca patterns: Allow bitfield fields to be edited properly, improve type formatting 2024-06-25 16:14:28 +02:00
WerWolv
b54bb6cd56 patterns: Updated pattern language 2024-06-25 14:30:03 +02:00
WerWolv
b03b159907 impr: Better UI/UX for pattern drawer 2024-06-25 14:29:27 +02:00
WerWolv
bb7e6c9775 patterns: Updated pattern language 2024-06-25 13:54:55 +02:00
WerWolv
4bc724791d impr: Optimize frame times 2024-06-25 13:54:46 +02:00
WerWolv
ba7c10f4b1 feat: Fix sub menus, allow recent items to be collapsed 2024-06-25 13:54:29 +02:00
WerWolv
c1561c7b6a impr: Only allow scaling factors between 0.1x and 4.0x with slider
The old scaling values can still be entered by ctrl-clicking the slider and entering it manually
2024-06-24 23:04:20 +02:00
WerWolv
91a0be2d78 impr: Better UI/UX for interactive help 2024-06-24 23:01:46 +02:00
WerWolv
1f27530241 impr: Optimize event processing 2024-06-24 22:53:45 +02:00
WerWolv
e236872af3 feat: Added simple interactive help system 2024-06-24 22:53:25 +02:00
WerWolv
3d301c4202 fix: Don't automatically create directories in read-only locations
Fixes #1767
2024-06-24 21:51:37 +02:00
WerWolv
a5aaa60d29 fix: Build error due to uninitialized variable in web builds 2024-06-24 21:49:59 +02:00
WerWolv
d4a2de3b23 patterns: Updated pattern language 2024-06-24 14:27:32 +02:00
WerWolv
e85746ddba fix: Data paths being stored in config paths instead 2024-06-24 14:27:24 +02:00
WerWolv
a002eb1bc1 fix: Mixed path separators in default paths 2024-06-23 15:03:36 +02:00
WerWolv
7d4486f407 fix: Remove accidentally committed test code 2024-06-22 23:03:54 +02:00
WerWolv
a9915579a0 impr: Better detection of Intel GPUs with really bad driver bugs 2024-06-22 22:58:58 +02:00
iTrooz
65dfd4da0f feat: log stacktrace implementation used (#1769) 2024-06-22 21:33:52 +02:00
WerWolv
b93fd523aa fix: Remove last remaining getDefaultPaths 2024-06-22 12:57:13 +02:00
WerWolv
24621e6612 fix: Build issues on Linux due to unused parameter 2024-06-22 12:02:19 +02:00
WerWolv
1b383bdcf1 patterns: Updated pattern language 2024-06-22 11:56:17 +02:00
WerWolv
f47b357b23 impr: Reset unicode loading and scaling factor values if fonts fail to load 2024-06-22 11:25:32 +02:00
WerWolv
f9b778ecb8 impr: Use 1.0x scaling by default 2024-06-22 11:25:07 +02:00
WerWolv
f36d9831bb patterns: Updated pattern language 2024-06-22 10:45:03 +02:00
WerWolv
b60a262b58 fix: Replace old defaults path system with a new one
#1767
2024-06-22 10:44:55 +02:00
WerWolv
beef0fff33 impr: Better background opacity for the digital signal visualizer 2024-06-20 22:33:55 +02:00
WerWolv
24f535474a fix: Sidebar background and separator line overlapping footer 2024-06-20 22:33:42 +02:00
WerWolv
2e3f523f32 feat: Added digital signal pattern visualizer 2024-06-20 14:04:05 +02:00
WerWolv
c5f5973a9d feat: Added per-byte highlights to the hex editor minimap 2024-06-20 11:21:20 +02:00
WerWolv
5d59b8599d fix: Loading of file providers from UNC paths 2024-06-20 11:11:01 +02:00
WerWolv
3bfb0096e6 fix: Undefined behaviour when sending empty arguments to main instance 2024-06-20 11:09:57 +02:00
WerWolv
ca5763650b patterns: Updated pattern language 2024-06-19 13:59:58 +02:00
WerWolv
bf7beab0ab impr: Make auto backups not remove dirty status from project 2024-06-19 13:51:36 +02:00
SparkyTD
9b594d81bd feat: Added CSV, TSV and JSON as export options for Find results (#1673)
### Problem description
The default result export functionality of the Find tool is limited to
only exporting data in a nonstandard text format. This PR adds support
for exporting the results in CSV, TSV or JSON format. The PR also
removes the old format.

### Implementation description
I added the classes `ExportFormatter`, `ExportFormatterCsv`,
`ExportFormatterTsv` and `ExportFormatterJson`, with similar
implementations to the pattern data exporters.

~~I also moved the `ViewFind::Occurrence` class into
`hex/helpers/types.hh`, so the exporters can access it.~~

### Screenshots

![image](https://github.com/WerWolv/ImHex/assets/45818400/c7a1016b-6494-416d-a963-86484952837c)

### Additional things
Another small change I made is moving the "{} entries found" line on the
same line as the Search and Reset buttons. I think it looks cleaner this
way, but if anyone disagrees, I can revert it.

---------

Co-authored-by: WerWolv <werwolv98@gmail.com>
2024-06-18 20:57:55 +00:00
WerWolv
6a26c6002b git: Added ImHex pronunciation to readme 2024-06-18 22:12:01 +02:00
WerWolv
4fa64500af impr: Make sure footer items all start at the same height 2024-06-18 22:11:43 +02:00
WerWolv
085737af15 fix: Opening files on network drives (using UNC paths) crashing ImHex on startup 2024-06-18 22:11:26 +02:00
WerWolv
3e347fb6d4 impr: Improve icon scaling a bit 2024-06-18 22:10:02 +02:00
WerWolv
80cb126200 build: Cleanup configure step logging 2024-06-18 22:09:38 +02:00
WerWolv
f49715c7a0 impr: Better font loading logic 2024-06-16 22:41:16 +02:00
WerWolv
deee76e455 patterns: Updated pattern language 2024-06-16 15:42:04 +02:00
WerWolv
33885b863a fix: Disassembler always using little endian, no matter the setting
Fixes #1763
2024-06-16 15:06:30 +02:00
WerWolv
3ce9dbb278 fix: Alt and Ctrl being swapped in the text editor on macOS 2024-06-16 14:59:48 +02:00
WerWolv
bee4b906fb fix: Crash when closing providers 2024-06-16 14:48:31 +02:00
WerWolv
b3b79b3ee8 impr: Show document edited icon in close button on macOS 2024-06-12 19:51:12 +02:00
iTrooz
bd085dd495 git: Remove Fedora 38 and add Fedora 40 (#1755)
Fedora 38 is EOL
2024-06-12 09:21:35 +02:00
WerWolv
bf518b3590 fix: Pattern data view filter text box being too wide 2024-06-09 21:36:25 +02:00
WerWolv
32a8fcb84d fix: ImGui ID Push/Pop mismatch when disabling inspector rows 2024-06-09 21:18:29 +02:00
WerWolv
4fd65403c0 impr: Don't show separator in bookmark drag tooltip if no comment is present 2024-06-09 21:01:22 +02:00
WerWolv
ecf871a6f1 impr: Allow files to be switched between memory loaded and direct access 2024-06-09 20:59:06 +02:00
WerWolv
531c049bb0 impr: Improve bookmark drag-n-drop logic
Fixes #1745
2024-06-09 20:11:55 +02:00
WerWolv
99716eff1e impr: Make sure floating windows don't get reopened after restart 2024-06-09 20:11:21 +02:00
WerWolv
74205d5438 impr: Make sure icon input text boxes are the expected width 2024-06-09 14:56:56 +02:00
WerWolv
0136877978 fix: Bookmark "Open in View" tooltip not being displayed
Fixes #1749
2024-06-09 14:56:40 +02:00
Murmele
fb7d40ddbe fix: Allow bookmark region to be set to 1 Byte length (#1747)
<!--
Please provide as much information as possible about what your PR aims
to do.
PRs with no description will most likely be closed until more
information is provided.
If you're planing on changing fundamental behaviour or add big new
features, please open a GitHub Issue first before starting to work on
it.
If it's not something big and you still want to contact us about it,
feel free to do so !
-->

### Problem description
<!-- Describe the bug that you fixed/feature request that you
implemented, or link to an existing issue describing it -->
When entering for the end value the same value as the start it is not
recorgnized as valid region, because end must be strictly greater than
begin. Due to the +1 in the Region constructor this is not correct,
because the end is included in the range.

### Implementation description
<!-- Explain what you did to correct the problem -->

### Screenshots
<!-- If your change is visual, take a screenshot showing it. Ideally,
make before/after sceenshots -->
After:

![image](https://github.com/WerWolv/ImHex/assets/10099533/c45d2001-8790-430a-8f1a-4b65130f4d01)


### Additional things
<!-- Anything else you would like to say -->
2024-06-09 10:54:09 +02:00
WerWolv
c761054805 feat: Allow view providers to be renamed
Closes #1746
2024-06-09 10:51:59 +02:00
WerWolv
55e24b5e23 fix: Bookmarks not being correctly reorderable anymore
Fixes #1745
2024-06-09 10:28:58 +02:00
WerWolv
9cff5b8af4 fix: Release notes in about page not working in nightly builds 2024-06-08 14:07:52 +02:00
Justus Garbe
41b2523005 impr: Refactor various view drawing code (#1698)
Refactored:
- ViewDatainspector
- ViewAbout

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-06-08 13:56:48 +02:00
WerWolv
2ef256ee74 impr: Show full error message for custom data inspector row errors 2024-06-08 13:40:39 +02:00
WerWolv
e954d49c29 feat: Handle SIGINT 2024-06-08 00:57:56 +02:00
WerWolv
041bf47ff4 fix: Title bar height on non-macOS platforms 2024-06-08 00:56:52 +02:00
WerWolv
53ced98529 impr: Enable auto project backup by default 2024-06-08 00:52:27 +02:00
WerWolv
cb475c471d build: Updated libwolv 2024-06-08 00:39:12 +02:00
WerWolv
bf82690c80 fix: Build and drawing of title bar buttons on macOS 2024-06-08 00:28:17 +02:00
WerWolv
72a3a1acab build: Updated libwolv 2024-06-07 23:48:57 +02:00
WerWolv
18e2b0eaa2 fix: Regex crashes with too long input strings 2024-06-07 23:12:18 +02:00
WerWolv
b80a6152b3 fix: Unifont being blurry again 2024-06-07 22:50:47 +02:00
WerWolv
ffe3dae7b2 build: Updated ImGui to v1.90.8 2024-06-07 22:12:50 +02:00
WerWolv
d7845ec690 fix: Build issues 2024-06-07 21:57:39 +02:00
WerWolv
8531a67519 fix: Don't unload background .NET scripts 2024-06-07 21:27:01 +02:00
WerWolv
af59b9d2ca fix: Infinite loop when doing forwards/backwards searches in some cases
Fixes #1734
2024-06-07 21:00:55 +02:00
Tsukasa OI
08bb69c048 fix: Wrong query path when saving layouts (#1735)
### Problem description

At least on Windows (I have tested), it fails to save a layout on the
non-portable version of ImHex (unless we have an administrator
privilege).

The log (after an attempt to save a layout as "sample") will look like:

| Component | Message |
| --------- | ------- |
| `libimhex` | `Failed to save layout 'sample'. No writable path found`
|

But the underlying problem is platform-agnostic. It can be also a
problem on other platforms in other ways.

### Implementation description

The layout manager incorrectly queried whether the empty path
(effectively the current working directory) is writable before saving
the layout (not each "layouts" directories it queried earlier).

This is the snippet of the root cause.

```cxx
std::fs::path layoutPath;
for (const auto &path : hex::fs::getDefaultPaths(fs::ImHexPath::Layouts)) {
    if (!hex::fs::isPathWritable(layoutPath))
        continue;

    layoutPath = path / fileName;
}
```

Look at the argument we are passing to `isPathWritable`. `layoutPath` is
a default (empty) `std::fs::path` object and will not be updated until
the directory describing itself is confirmed to be writable.

That caused a problem on non-portable version of Windows because:

1. The current working directory is usually the one of the executable
(`imhex-gui.exe`) and
2. That directory (`C:\Program Files\ImHex` by default) is usually not
writable unless ImHex is executed with an Administrator privilege.

The argument to `isPathWritable` should be `path` (containing one of the
`layouts` directories) and this PR fixes so that.

### Screenshots

### Additional things

This issue is hard to notice when developing because, to reproduce this
bug, the current working directory MUST NOT BE writable (usually
writable when we develop, even when we are working on the non-portable
Windows builds).
2024-06-07 20:33:43 +02:00
WerWolv
6fb32d20b3 fix: Don't try to compile process memory provider into Web build 2024-06-07 20:32:04 +02:00
WerWolv
ea09bfe8ea feat: Highlight patterns in pattern data view that are fully selected
Fixes #1741
2024-06-07 19:59:11 +02:00
WerWolv
c0dde570e4 feat: Highlight patterns in hex editor when hovering over pattern data row
Fixes #1742
2024-06-07 19:48:10 +02:00
WerWolv
6fd3fa77ed impr: Don't scroll hex editor view when jumping to a region that's on-screen already
Fixes #1743
2024-06-07 19:29:55 +02:00
WerWolv
ff20f81cfd impr: Added back selection size in hex to the footer 2024-06-07 19:21:38 +02:00
WerWolv
de8465a8f4 feat: Added limited support for the process memory provider to macOS 2024-06-07 19:17:14 +02:00
WerWolv
4540e1b561 impr: Select second to last provider when last one is selected and closed 2024-06-05 23:21:15 +02:00
WerWolv
789d469477 impr: Make providers close instantly 2024-06-05 23:02:38 +02:00
WerWolv
4797512207 fix: Variable naming style in splash window 2024-06-05 22:24:00 +02:00
WerWolv
348fe27a3c impr: Added small moon icon to the welcome screen of nightly builds 2024-06-05 22:23:43 +02:00
WerWolv
c217b1b100 build: Replace -WIP version suffix with .WIP 2024-06-05 20:59:48 +02:00
WerWolv
0e757e5fb1 build: Bumped version to 1.35.0-WIP 2024-06-03 23:06:28 +02:00
471 changed files with 78119 additions and 9636 deletions

View File

@@ -8,7 +8,7 @@ on:
jobs:
codeql:
name: 🐛 CodeQL
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
permissions:
actions: read
contents: read
@@ -49,7 +49,7 @@ jobs:
set -x
mkdir -p build
cd build
CC=gcc-12 CXX=g++-12 cmake \
CC=gcc-14 CXX=g++-14 cmake \
-DCMAKE_BUILD_TYPE=$BUILD_TYPE \
-DCMAKE_INSTALL_PREFIX="$PWD/install" \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
@@ -57,8 +57,9 @@ jobs:
-DCMAKE_C_FLAGS="-fuse-ld=lld" \
-DCMAKE_CXX_FLAGS="-fuse-ld=lld" \
-DIMHEX_PATTERNS_PULL_MASTER=ON \
-G Ninja \
..
make -j 4 install
ninja install
- name: 🗯️ Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

View File

@@ -64,7 +64,7 @@ jobs:
cd build
cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} \
-DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
-DCMAKE_INSTALL_PREFIX="$PWD/install" \
-DIMHEX_GENERATE_PACKAGE=ON \
-DIMHEX_USE_DEFAULT_BUILD_SETTINGS=ON \
@@ -76,13 +76,13 @@ jobs:
-DIMHEX_REPLACE_DWARF_WITH_PDB=ON \
-DDOTNET_EXECUTABLE="C:/Program Files/dotnet/dotnet.exe" \
..
- name: 🛠️ Build
run: |
cd build
ninja install
cpack
mv ImHex-*.msi ../imhex-${{env.IMHEX_VERSION}}-Windows-x86_64.msi
mv ImHex-*.msi ../imhex-${{ env.IMHEX_VERSION }}-Windows-x86_64.msi
echo "ImHex checks for the existence of this file to determine if it is running in portable mode. You should not delete this file" > $PWD/install/PORTABLE
@@ -107,7 +107,7 @@ jobs:
run: |
set -x
echo "NoGPU version Powered by Mesa 3D : https://fdossena.com/?p=mesa%2Findex.frag" > build/install/MESA.md
curl https://werwolv.net/downloads/mesa/MesaForWindows-x64-latest.7z -L -o mesa.7z
curl https://downloads.fdossena.com/geth.php?r=mesa64-latest -L -o mesa.7z
7z e mesa.7z
mv opengl32.dll build/install
@@ -119,9 +119,62 @@ jobs:
path: |
build/install/*
win-plugin-template-test:
runs-on: windows-2022
name: 🧪 Plugin Template Test
defaults:
run:
shell: msys2 {0}
needs: win
env:
IMHEX_SDK_PATH: "${{ github.workspace }}/out/sdk"
steps:
- name: 🧰 Checkout ImHex
uses: actions/checkout@v4
with:
path: imhex
- name: 🟦 Install msys2
uses: msys2/setup-msys2@v2
with:
msystem: mingw64
- name: ⬇️ Install dependencies
run: |
set -x
imhex/dist/get_deps_msys2.sh
- name: 🧰 Checkout ImHex-Plugin-Template
uses: actions/checkout@v4
with:
repository: WerWolv/ImHex-Plugin-Template
submodules: recursive
path: template
- name: ⬇️ Download artifact
uses: actions/download-artifact@v4
with:
name: Windows Portable x86_64
path: out
- name: 🛠️ Build
run: |
set -x
cd template
mkdir -p build
cd build
cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
-DIMHEX_USE_DEFAULT_BUILD_SETTINGS=ON \
-DUSE_SYSTEM_CAPSTONE=ON \
..
ninja
# MacOS build
macos:
runs-on: macos-12
runs-on: macos-13
strategy:
fail-fast: false
@@ -132,7 +185,7 @@ jobs:
- suffix: ""
custom_glfw: false
name: 🍎 macOS 12.0${{matrix.suffix}}
name: 🍎 macOS 13${{ matrix.suffix }}
steps:
- name: 🧰 Checkout
@@ -153,15 +206,15 @@ jobs:
- name: ⬇️ Install dependencies
run: |
set -x
brew reinstall python || brew link --overwrite python
brew bundle --no-lock --file dist/Brewfile
brew reinstall python --quiet || true
brew link --overwrite --quiet python || true
brew bundle --no-lock --quiet --file dist/Brewfile || true
rm -rf /usr/local/Cellar/capstone
- name: ⬇️ Install classic glfw
if: ${{! matrix.custom_glfw}}
if: ${{! matrix.custom_glfw }}
run: |
brew install glfw
brew install --quiet glfw || true
- name: ⬇️ Install .NET
uses: actions/setup-dotnet@v4
@@ -169,15 +222,15 @@ jobs:
dotnet-version: '8.0.100'
- name: 🧰 Checkout glfw
if: ${{matrix.custom_glfw}}
if: ${{ matrix.custom_glfw }}
uses: actions/checkout@v4
with:
repository: glfw/glfw
path: glfw
# GLFW custom build (to allow software rendering)
- name: ⬇️ Patch and install custom glfw
if: ${{matrix.custom_glfw}}
if: ${{ matrix.custom_glfw }}
run: |
set -x
cd glfw
@@ -187,7 +240,7 @@ jobs:
cd build
cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} \
-DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
-DBUILD_SHARED_LIBS=ON \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
@@ -202,14 +255,15 @@ jobs:
set -x
mkdir -p build
cd build
CC=$(brew --prefix gcc@12)/bin/gcc-12 \
CXX=$(brew --prefix gcc@12)/bin/g++-12 \
CC=$(brew --prefix llvm)/bin/clang \
CXX=$(brew --prefix llvm)/bin/clang++ \
OBJC=$(brew --prefix llvm)/bin/clang \
OBJCXX=$(brew --prefix llvm)/bin/clang++ \
PKG_CONFIG_PATH="$(brew --prefix openssl)/lib/pkgconfig":"$(brew --prefix)/lib/pkgconfig" \
cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} \
-DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
-DIMHEX_GENERATE_PACKAGE=ON \
-DIMHEX_SYSTEM_LIBRARY_PATH="$(brew --prefix llvm)/lib;$(brew --prefix llvm)/lib/unwind;$(brew --prefix llvm)/lib/c++;$(brew --prefix)/lib" \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
-DCMAKE_OBJC_COMPILER_LAUNCHER=ccache \
@@ -219,7 +273,7 @@ jobs:
-DIMHEX_COMMIT_HASH_LONG="${GITHUB_SHA}" \
-DIMHEX_COMMIT_BRANCH="${GITHUB_REF##*/}" \
..
- name: 🛠️ Build
run: cd build && ninja install
@@ -237,6 +291,12 @@ jobs:
cd build/install
chmod -R 755 ImHex.app/
- name: 🔫 Kill XProtect
run: |
# See https://github.com/actions/runner-images/issues/7522
echo Killing XProtect...; sudo pkill -9 XProtect >/dev/null || true;
echo Waiting for XProtect process...; while pgrep XProtect; do sleep 3; done;
- name: 📦 Create DMG
run: |
set -x
@@ -245,18 +305,24 @@ jobs:
cd bundle
ln -s /Applications Applications
cd ..
hdiutil create -volname "ImHex" -srcfolder bundle -ov -format UDZO imhex-${{env.IMHEX_VERSION}}-macOS${{matrix.suffix}}-x86_64.dmg
for i in $(seq 1 10); do
if hdiutil create -volname "ImHex" -srcfolder bundle -ov -format UDZO imhex-${{ env.IMHEX_VERSION }}-macOS${{ matrix.suffix }}-x86_64.dmg; then
echo "Created dmg after ${i} attempts"
break
fi
sleep 10
done
- name: ⬆️ Upload DMG
uses: actions/upload-artifact@v4
with:
if-no-files-found: error
name: macOS DMG${{matrix.suffix}} x86_64
name: macOS DMG${{ matrix.suffix }} x86_64
path: ./*.dmg
macos-arm64-build:
runs-on: ubuntu-22.04
name: 🍎 macOS 12.1 arm64
runs-on: ubuntu-24.04
name: 🍎 macOS 13 arm64
outputs:
IMHEX_VERSION: ${{ steps.build.outputs.IMHEX_VERSION }}
steps:
@@ -264,7 +330,7 @@ jobs:
uses: actions/checkout@v4
with:
submodules: recursive
- name: 📁 Restore docker /cache
uses: actions/cache@v4
with:
@@ -299,8 +365,8 @@ jobs:
gh actions-cache delete "build-macos-arm64-cache" --confirm || true
macos-arm64-package:
runs-on: macos-12
name: 🍎 macOS 12.1 arm64 Packaging
runs-on: macos-13
name: 🍎 macOS 13 arm64 Packaging
needs: macos-arm64-build
env:
IMHEX_VERSION: ${{ needs.macos-arm64-build.outputs.IMHEX_VERSION }}
@@ -330,6 +396,12 @@ jobs:
cd out
chmod -R 755 ImHex.app/
- name: 🔫 Kill XProtect
run: |
# See https://github.com/actions/runner-images/issues/7522
echo Killing XProtect...; sudo pkill -9 XProtect >/dev/null || true;
echo Waiting for XProtect process...; while pgrep XProtect; do sleep 3; done;
- name: 📦 Create DMG
run: |
set -x
@@ -338,7 +410,13 @@ jobs:
cd bundle
ln -s /Applications Applications
cd ..
hdiutil create -volname "ImHex" -srcfolder bundle -ov -format UDZO imhex-${{env.IMHEX_VERSION}}-macOS-arm64.dmg
for i in $(seq 1 10); do
if hdiutil create -volname "ImHex" -srcfolder bundle -ov -format UDZO imhex-${{ env.IMHEX_VERSION }}-macOS-arm64.dmg; then
echo "Created dmg after ${i} attempts"
break
fi
sleep 10
done
- name: ⬆️ Upload DMG
uses: actions/upload-artifact@v4
@@ -346,18 +424,18 @@ jobs:
if-no-files-found: error
name: macOS DMG arm64
path: ./*.dmg
# Ubuntu build
ubuntu:
strategy:
fail-fast: false
matrix:
include:
- release_num: 22.04
- release_num: 24.04
- release_num: "24.04"
- release_num: "24.10"
name: 🐧 Ubuntu ${{ matrix.release_num }}
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
container:
image: "ubuntu:${{ matrix.release_num }}"
@@ -375,8 +453,8 @@ jobs:
- name: 📜 Setup ccache
uses: hendrikmuhs/ccache-action@v1
with:
key: Ubuntu-${{matrix.release_num}}-ccache-${{ github.run_id }}
restore-keys: Ubuntu-${{matrix.release_num}}-ccache
key: Ubuntu-${{ matrix.release_num }}-ccache-${{ github.run_id }}
restore-keys: Ubuntu-${{ matrix.release_num }}-ccache
max-size: 1G
- name: ⬇️ Install dependencies
@@ -397,8 +475,8 @@ jobs:
git config --global --add safe.directory '*'
mkdir -p build
cd build
CC=gcc-12 CXX=g++-12 cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} \
CC=gcc-14 CXX=g++-14 cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
-DCMAKE_INSTALL_PREFIX="/usr" \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
@@ -409,9 +487,9 @@ jobs:
-DIMHEX_USE_GTK_FILE_PICKER=ON \
-DDOTNET_EXECUTABLE="dotnet" \
..
- name: 🛠️ Build
run: cd build && DESTDIR=DebDir ninja install
run: cd build && DESTDIR=DebDir ninja install
- name: 📜 Set version variable
run: |
@@ -421,7 +499,7 @@ jobs:
run: |
cp -r build/DEBIAN build/DebDir
dpkg-deb -Zgzip --build build/DebDir
mv build/DebDir.deb imhex-${{env.IMHEX_VERSION}}-Ubuntu-${{ matrix.release_num }}-x86_64.deb
mv build/DebDir.deb imhex-${{ env.IMHEX_VERSION }}-Ubuntu-${{ matrix.release_num }}-x86_64.deb
- name: ⬆️ Upload DEB
uses: actions/upload-artifact@v4
@@ -432,7 +510,7 @@ jobs:
# AppImage build
appimage:
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
name: ⬇️ AppImage
steps:
- name: 🧰 Checkout
@@ -446,7 +524,7 @@ jobs:
path: cache
key: appimage-ccache-${{ github.run_id }}
restore-keys: appimage-cache
- name: 🐳 Inject /cache into docker
uses: reproducible-containers/buildkit-cache-dance@v2
with:
@@ -476,7 +554,7 @@ jobs:
# ArchLinux build
archlinux-build:
name: 🐧 ArchLinux
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
container:
image: archlinux:base-devel
@@ -518,7 +596,7 @@ jobs:
mkdir -p build
cd build
CC=gcc CXX=g++ cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} \
-DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
-DCMAKE_INSTALL_PREFIX="/usr" \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
@@ -532,9 +610,9 @@ jobs:
-DIMHEX_ENABLE_LTO=ON \
-DIMHEX_USE_GTK_FILE_PICKER=ON \
..
- name: 🛠️ Build
run: cd build && DESTDIR=installDir ninja install
run: cd build && DESTDIR=installDir ninja install
- name: 📜 Set version variable
run: |
@@ -543,7 +621,7 @@ jobs:
- name: ✒️ Prepare PKGBUILD
run: |
cp dist/Arch/PKGBUILD build
sed -i 's/%version%/${{env.IMHEX_VERSION}}/g' build/PKGBUILD
sed -i 's/%version%/${{ env.IMHEX_VERSION }}/g' build/PKGBUILD
# makepkg doesn't want to run as root, so I had to chmod 777 all over
- name: 📦 Package ArchLinux .pkg.tar.zst
@@ -553,16 +631,16 @@ jobs:
# the name is a small trick to make makepkg recognize it as the source
# else, it would try to download the file from the release
tar -cvf imhex-${{env.IMHEX_VERSION}}-ArchLinux-x86_64.pkg.tar.zst -C installDir .
tar -cvf imhex-${{ env.IMHEX_VERSION }}-ArchLinux-x86_64.pkg.tar.zst -C installDir .
chmod -R 777 .
sudo -u nobody makepkg
# Replace the old file
rm imhex-${{env.IMHEX_VERSION}}-ArchLinux-x86_64.pkg.tar.zst
rm imhex-${{ env.IMHEX_VERSION }}-ArchLinux-x86_64.pkg.tar.zst
rm *imhex-bin-debug* # rm debug package which is created for some reason
mv *.pkg.tar.zst imhex-${{env.IMHEX_VERSION}}-ArchLinux-x86_64.pkg.tar.zst
mv *.pkg.tar.zst imhex-${{ env.IMHEX_VERSION }}-ArchLinux-x86_64.pkg.tar.zst
- name: ⬆️ Upload imhex-archlinux.pkg.tar.zst
uses: actions/upload-artifact@v4
@@ -570,7 +648,7 @@ jobs:
if-no-files-found: error
name: ArchLinux .pkg.tar.zst x86_64
path: |
build/imhex-${{env.IMHEX_VERSION}}-ArchLinux-x86_64.pkg.tar.zst
build/imhex-${{ env.IMHEX_VERSION }}-ArchLinux-x86_64.pkg.tar.zst
# RPM distro builds
rpm-build:
@@ -583,28 +661,41 @@ jobs:
release_num: rawhide
mock_config: fedora-rawhide
- name: Fedora
mock_release: f39
release_num: 39
mock_config: fedora-39
mock_release: f41
release_num: 41
mock_config: fedora-41
- name: Fedora
mock_release: f38
release_num: 38
mock_config: fedora-38
mock_release: f40
release_num: 40
mock_config: fedora-40
- name: RHEL-AlmaLinux
mock_release: epel9
release_num: 9
mock_config: "alma+epel-9"
name: 🐧 ${{ matrix.name }} ${{ matrix.release_num }}
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
container:
image: "fedora:latest"
options: --privileged
image: "almalinux:9"
options: --privileged --pid=host --security-opt apparmor=unconfined
steps:
- name: ⬇️ Install git-core
run: dnf install --disablerepo="*" --enablerepo="fedora" git-core -y
# This, together with the `--pid=host --security-opt apparmor=unconfined` docker options is required to allow
# fedpkg to work inside a Docker container running on Ubuntu again.
# GitHub seems to have enabled AppArmor on their Ubuntu CI runners which limits Docker in ways that cause
# programs inside it to fail.
# Without this, fedpkg will throw the unhelpful error message 'Insufficient Rights'
# This step uses nsenter to execute commands on the host that disable AppArmor entirely.
- name: 🛡️ Disable AppArmor on Host
run: |
nsenter -t 1 -m -u -n -i sudo systemctl disable --now apparmor.service
nsenter -t 1 -m -u -n -i sudo aa-teardown || true
nsenter -t 1 -m -u -n -i sudo sysctl --write kernel.apparmor_restrict_unprivileged_unconfined=0
nsenter -t 1 -m -u -n -i sudo sysctl --write kernel.apparmor_restrict_unprivileged_userns=0
- name: ⬇️ Install git-core and EPEL repo
run: dnf install git-core epel-release -y
- name: 🧰 Checkout
uses: actions/checkout@v4
@@ -623,8 +714,8 @@ jobs:
- name: ⬇️ Update all packages and install dependencies
run: |
set -x
dnf upgrade --disablerepo="*" --enablerepo="fedora,updates" -y
dnf install --disablerepo="*" --enablerepo="fedora,updates" -y \
dnf upgrade -y
dnf install -y \
fedpkg \
ccache
@@ -650,16 +741,16 @@ jobs:
- name: ✒️ Modify spec file
run: |
sed -i \
-e 's/Version: VERSION$/Version: ${{env.IMHEX_VERSION}}/g' \
-e 's/IMHEX_OFFLINE_BUILD=ON/IMHEX_OFFLINE_BUILD=OFF/g' \
-e '/IMHEX_OFFLINE_BUILD=OFF/a -D IMHEX_PATTERNS_PULL_MASTER=ON \\' \
-e '/BuildRequires: cmake/a BuildRequires: git-core' \
-e '/%files/a %{_datadir}/%{name}/' \
-e 's/Version: VERSION$/Version: ${{ env.IMHEX_VERSION }}/g' \
-e 's/IMHEX_OFFLINE_BUILD=ON/IMHEX_OFFLINE_BUILD=OFF/g' \
-e '/IMHEX_OFFLINE_BUILD=OFF/a -D IMHEX_PATTERNS_PULL_MASTER=ON \\' \
-e '/BuildRequires: cmake/a BuildRequires: git-core' \
-e '/%files/a %{_datadir}/%{name}/' \
$GITHUB_WORKSPACE/ImHex/dist/rpm/imhex.spec
- name: 📜 Fix ccache on EL9
if: matrix.mock_release == 'epel9'
run: sed -i '/\. \/opt\/rh\/gcc-toolset-12\/enable/a PATH=/usr/lib64/ccache:$PATH' $GITHUB_WORKSPACE/ImHex/dist/rpm/imhex.spec
run: sed -i '/\. \/opt\/rh\/gcc-toolset-14\/enable/a PATH=/usr/lib64/ccache:$PATH' $GITHUB_WORKSPACE/ImHex/dist/rpm/imhex.spec
- name: 🟩 Copy spec file to build root
run: mv $GITHUB_WORKSPACE/ImHex/dist/rpm/imhex.spec $GITHUB_WORKSPACE/imhex.spec
@@ -681,8 +772,8 @@ jobs:
- name: 🟩 Move and rename finished RPM
run: |
mv $GITHUB_WORKSPACE/results_imhex/${{env.IMHEX_VERSION}}/*/imhex-${{env.IMHEX_VERSION}}-0.*.x86_64.rpm \
$GITHUB_WORKSPACE/imhex-${{env.IMHEX_VERSION}}-${{matrix.name}}-${{matrix.release_num}}-x86_64.rpm
mv $GITHUB_WORKSPACE/results_imhex/${{ env.IMHEX_VERSION }}/*/imhex-${{ env.IMHEX_VERSION }}-0.*.x86_64.rpm \
$GITHUB_WORKSPACE/imhex-${{ env.IMHEX_VERSION }}-${{ matrix.name }}-${{ matrix.release_num }}-x86_64.rpm
- name: ⬆️ Upload RPM
uses: actions/upload-artifact@v4
@@ -690,4 +781,4 @@ jobs:
if-no-files-found: error
name: ${{ matrix.name }} ${{ matrix.release_num }} RPM x86_64
path: |
imhex-${{env.IMHEX_VERSION}}-${{matrix.name}}-${{matrix.release_num}}-x86_64.rpm
imhex-${{ env.IMHEX_VERSION }}-${{ matrix.name }}-${{ matrix.release_num }}-x86_64.rpm

View File

@@ -20,7 +20,7 @@ permissions:
jobs:
build:
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
name: 🌍 WebAssembly
steps:
- name: 🧰 Checkout
@@ -49,7 +49,7 @@ jobs:
chmod -c -R +rX "out/"
- name: ⬆️ Upload artifacts
uses: actions/upload-pages-artifact@v2
uses: actions/upload-pages-artifact@v3
with:
path: out/
@@ -59,9 +59,8 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
run: |
gh extension install actions/gh-actions-cache
gh actions-cache delete "build-web-cache" --confirm
gh extension install actions/gh-actions-cache || true
gh actions-cache delete "build-web-cache" --confirm || true
deploy:
environment:
@@ -69,7 +68,7 @@ jobs:
url: ${{ steps.deployment.outputs.page_url }}
name: 📃 Deploy to GitHub Pages
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
if: ${{ github.ref == 'refs/heads/master' && github.event.repository.fork == false }}
needs: build
@@ -77,4 +76,4 @@ jobs:
steps:
- name: 🌍 Deploy
id: deployment
uses: actions/deploy-pages@v2
uses: actions/deploy-pages@v4

View File

@@ -10,7 +10,7 @@ on:
jobs:
release-update-repos:
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
name: Release Update Repos
steps:
@@ -90,7 +90,7 @@ jobs:
run: tar --exclude-vcs -czvf Full.Sources.tar.gz ImHex
- name: ⬇️ Download artifacts from latest workflow
uses: dawidd6/action-download-artifact@v3
uses: dawidd6/action-download-artifact@v6
with:
github_token: ${{secrets.GITHUB_TOKEN}}
workflow: build.yml
@@ -147,7 +147,7 @@ jobs:
commit_email: itrooz@protonmail.com
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
commit_message: Bump to version ${{ env.IMHEX_VERSION }}
ssh_keyscan_types: rsa,dsa,ecdsa,ed25519
ssh_keyscan_types: rsa,ecdsa,ed25519
release-update-winget:
name: Release update winget package

30
.github/workflows/stale_issues.yml vendored Normal file
View File

@@ -0,0 +1,30 @@
name: Close inactive issues
on:
schedule:
- cron: "30 1 * * 0"
workflow_dispatch:
jobs:
close-issues:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v5
with:
operations-per-run: '200'
ascending: true
days-before-issue-stale: 334
days-before-issue-close: 30
stale-issue-label: "stale"
stale-issue-message: |
This issue is marked stale as it has been open for 11 months without activity.
Please try the latest ImHex version. (Avaiable here: https://imhex.download/ for release and https://imhex.download/#nightly for development version)
If the issue persists on the latest version, please make a comment on this issue again
Without response, this issue will be closed in one month.
close-issue-message: ""
days-before-pr-stale: -1
days-before-pr-close: -1
repo-token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -15,7 +15,7 @@ on:
jobs:
tests:
name: 🧪 Unit Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
permissions:
actions: read
contents: read
@@ -38,23 +38,25 @@ jobs:
run: |
sudo apt update
sudo bash dist/get_deps_debian.sh
sudo apt install gcovr -y
- name: 🛠️ Build
run: |
set -x
mkdir -p build
cd build
CC=gcc-12 CXX=g++-12 cmake \
CC=gcc-14 CXX=g++-14 cmake \
-DCMAKE_BUILD_TYPE=Debug \
-DIMHEX_ENABLE_UNIT_TESTS=ON \
-DIMHEX_ENABLE_PLUGIN_TESTS=ON \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
-DCMAKE_C_FLAGS="-fuse-ld=lld -fsanitize=address,leak,undefined -fno-sanitize-recover=all --coverage" \
-DCMAKE_CXX_FLAGS="-fuse-ld=lld -fsanitize=address,leak,undefined -fno-sanitize-recover=all --coverage" \
-DIMHEX_OFFLINE_BUILD=ON \
-G Ninja \
..
make -j4 unit_tests
ninja unit_tests
ninja imhex_all
- name: 🧪 Perform plcli Integration Tests
run: |
@@ -67,16 +69,24 @@ jobs:
ctest --output-on-failure
# Generate report from all gcov .gcda files
- name: 🧪 Generate coverage report
run: |
gcovr --gcov-executable /usr/bin/gcov-12 -r . build --xml coverage_report.xml --verbose
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v4
with:
fail_ci_if_error: true
token: ${{ secrets.CODECOV_TOKEN }}
file: coverage_report.xml
#- name: 🧪 Generate coverage report
# run: |
# sudo apt install python3-pip python3-venv
# python3 -m venv venv
# . venv/bin/activate
# pip3 install gcovr
# cd build
# gcovr --gcov-executable /usr/bin/gcov-14 --exclude '.*/yara_rules/' --exclude '.*/third_party/' --exclude '.*/external/' --root .. --xml coverage_report.xml --verbose --gcov-ignore-errors all
#
#- name: Upload coverage reports to Codecov
# env:
# CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
# if: ${{ env.CODECOV_TOKEN }}
# uses: codecov/codecov-action@v4
# with:
# fail_ci_if_error: true
# token: ${{ secrets.CODECOV_TOKEN }}
# file: build/coverage_report.xml
langs:
name: 🧪 Langs

1
.gitignore vendored
View File

@@ -6,6 +6,7 @@ cmake-build-*/
build*/
local/
venv/
.cache/
*.mgc
*.kdev4

2
.gitmodules vendored
View File

@@ -28,7 +28,7 @@
ignore = dirty
[submodule "lib/third_party/lunasvg"]
path = lib/third_party/lunasvg
url = https://github.com/sammycage/lunasvg
url = https://github.com/WerWolv/lunasvg
ignore = dirty
[submodule "lib/external/libromfs"]

View File

@@ -21,7 +21,7 @@ option(IMHEX_REPLACE_DWARF_WITH_PDB "Remove DWARF information from binaries
option(IMHEX_ENABLE_STD_ASSERTS "Enable debug asserts in the C++ std library. (Breaks Plugin ABI!)" OFF)
option(IMHEX_ENABLE_UNIT_TESTS "Enable building unit tests" OFF)
option(IMHEX_ENABLE_PRECOMPILED_HEADERS "Enable precompiled headers" OFF)
option(IMHEX_COMPRESS_DEBUG_INFO "Compress debug information" ON )
option(IMHEX_COMPRESS_DEBUG_INFO "Compress debug information" ON )
set(IMHEX_BASE_FOLDER "${CMAKE_CURRENT_SOURCE_DIR}")
set(CMAKE_MODULE_PATH "${IMHEX_BASE_FOLDER}/cmake/modules")
@@ -32,16 +32,17 @@ include("${IMHEX_BASE_FOLDER}/cmake/ide_helpers.cmake")
# Basic compiler and cmake configurations
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_INCLUDE_DIRECTORIES_BEFORE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include("${IMHEX_BASE_FOLDER}/cmake/build_helpers.cmake")
# Setup project
loadVersion(IMHEX_VERSION)
loadVersion(IMHEX_VERSION IMHEX_VERSION_PLAIN)
setVariableInParent(IMHEX_VERSION ${IMHEX_VERSION})
configureCMake()
configureCMake()
project(imhex
LANGUAGES C CXX
VERSION ${IMHEX_VERSION}
VERSION ${IMHEX_VERSION_PLAIN}
DESCRIPTION "The ImHex Hex Editor"
HOMEPAGE_URL "https://imhex.werwolv.net"
)
@@ -72,8 +73,11 @@ addPluginDirectories()
# Add unit tests
if (IMHEX_ENABLE_UNIT_TESTS)
enable_testing()
add_subdirectory(tests EXCLUDE_FROM_ALL)
if (NOT TARGET unit_tests)
enable_testing()
add_custom_target(unit_tests)
add_subdirectory(tests EXCLUDE_FROM_ALL)
endif ()
endif ()
# Configure more resources that will be added to the install package
@@ -83,5 +87,5 @@ generateSDKDirectory()
# Handle package generation
createPackage()
# Accomodate IDEs with FOLDER support
# Accommodate IDEs with FOLDER support
tweakTargetsForIDESupport()

View File

@@ -1,13 +1,16 @@
<a href="https://imhex.werwolv.net">
<h1 align="center">
<picture>
<img height="300px" src="./resources/dist/common/logo/ImHexLogoSVGBG.svg">
<img height="300px" style="margin: 0; padding: 0" src="./resources/dist/common/logo/ImHexLogoSVGBG.svg">
</picture>
</h1>
</a>
<p align="center">A Hex Editor for Reverse Engineers, Programmers and people who value their retinas when working at 3 AM.</p>
<p align="center">
A Hex Editor for Reverse Engineers, Programmers and people who value their retinas when working at 3 AM.
<br>
<a href="https://itinerarium.github.io/phoneme-synthesis/?w=/'ˈɪmhɛks/"><strong>/ˈɪmhɛks/</strong></a>
</p>
<p align="center">
<a title="'Build' workflow Status" href="https://github.com/WerWolv/ImHex/actions?query=workflow%3ABuild"><img alt="'Build' workflow Status" src="https://img.shields.io/github/actions/workflow/status/WerWolv/ImHex/build.yml?longCache=true&style=for-the-badge&label=Build&logoColor=fff&logo=GitHub%20Actions&branch=master"></a>
<a title="Discord Server" href="https://discord.gg/X63jZ36xBY"><img alt="Discord Server" src="https://img.shields.io/discord/789833418631675954?label=Discord&logo=Discord&logoColor=fff&style=for-the-badge"></a>
@@ -311,22 +314,26 @@ To use ImHex, the following minimal system requirements need to be met.
> ImHex requires a GPU with OpenGL 3.0 support in general.
> There are releases available (with the `-NoGPU` suffix) that are software rendered and don't require a GPU, however these can be a lot slower than the GPU accelerated versions.
>
> If possible at all, make ImHex use the dedicated GPU on your system instead of the integrated one (especially Intel HD GPUs are known to cause issues).
> If possible at all, make ImHex use the dedicated GPU on your system instead of the integrated one.
> ImHex will usually run fine with integrated GPUs as well but certain Intel HD GPU drivers on Windows are known to cause graphical artifacts.
- **OS**:
- **Windows**: Windows 7 or higher (Windows 10/11 recommended)
- **macOS**: macOS 11 (Big Sur) or higher,
- **macOS**: macOS 13 (Ventura) or higher,
- Lower versions should still work too, but you'll need to compile ImHex yourself. The release binaries will NOT work.
- The macOS build is not signed and will require you to manually allow them in the Security & Privacy settings.
- **Linux**: "Modern" Linux. The following distributions have official releases available. Other distros are supported through the AppImage and Flatpak releases.
- Ubuntu 22.04/23.04
- Fedora 36/37
- RHEL/AlmaLinux 9
- Ubuntu and Debian
- Fedora
- RHEL/AlmaLinux
- Arch Linux
- Basically any other distro will work as well when compiling ImHex from sources.
- **CPU**: x86_64 (64 Bit)
- **GPU**: OpenGL 3.0 or higher
- Intel HD drivers are really buggy and often cause graphic artifacts
- Integrated Intel HD iGPUs are supported, however certain drivers are known to cause various graphical artifacts, especially on Windows. Use at your own risk.
- In case you don't have a GPU available, there are software rendered releases available for Windows and macOS
- **RAM**: 256MB, more may be required for more complicated analysis
- **Storage**: 100MB
- **Storage**: 150MB
## Installing

View File

@@ -1 +1 @@
1.34.0
1.36.2

View File

@@ -59,6 +59,7 @@ macro(detectOS)
set(CMAKE_INSTALL_LIBDIR ".")
set(PLUGINS_INSTALL_LOCATION "plugins")
add_compile_definitions(WIN32_LEAN_AND_MEAN)
add_compile_definitions(UNICODE)
elseif (APPLE)
add_compile_definitions(OS_MACOS)
set(CMAKE_INSTALL_BINDIR ".")
@@ -224,6 +225,7 @@ macro(createPackage)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/LICENSE DESTINATION ${CMAKE_INSTALL_PREFIX}/share/licenses/imhex)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/dist/imhex.desktop DESTINATION ${CMAKE_INSTALL_PREFIX}/share/applications)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/dist/imhex.mime.xml DESTINATION ${CMAKE_INSTALL_PREFIX}/share/mime/packages RENAME imhex.xml)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/icon.png DESTINATION ${CMAKE_INSTALL_PREFIX}/share/pixmaps RENAME imhex.png)
downloadImHexPatternsFiles("./share/imhex")
@@ -238,6 +240,7 @@ macro(createPackage)
if (APPLE)
if (IMHEX_GENERATE_PACKAGE)
set(EXTRA_BUNDLE_LIBRARY_PATHS ${EXTRA_BUNDLE_LIBRARY_PATHS} "${IMHEX_SYSTEM_LIBRARY_PATH}")
include(PostprocessBundle)
set_target_properties(libimhex PROPERTIES SOVERSION ${IMHEX_VERSION})
@@ -268,7 +271,7 @@ macro(createPackage)
find_program(CODESIGN_PATH codesign)
if (CODESIGN_PATH)
install(CODE "message(STATUS \"Signing bundle '${CMAKE_INSTALL_PREFIX}/${BUNDLE_NAME}'...\")")
install(CODE "execute_process(COMMAND ${CODESIGN_PATH} --force --deep --sign - ${CMAKE_INSTALL_PREFIX}/${BUNDLE_NAME} COMMAND_ERROR_IS_FATAL ANY)")
install(CODE "execute_process(COMMAND ${CODESIGN_PATH} --force --deep --entitlements ${CMAKE_SOURCE_DIR}/resources/macos/Entitlements.plist --sign - ${CMAKE_INSTALL_PREFIX}/${BUNDLE_NAME} COMMAND_ERROR_IS_FATAL ANY)")
endif()
endif()
@@ -306,9 +309,6 @@ endfunction()
macro(configureCMake)
message(STATUS "Configuring ImHex v${IMHEX_VERSION}")
# Enable C and C++ languages
enable_language(C CXX)
set(CMAKE_POSITION_INDEPENDENT_CODE ON CACHE BOOL "Enable position independent code for all targets" FORCE)
# Configure use of recommended build tools
@@ -382,6 +382,9 @@ macro(configureCMake)
endmacro()
function(configureProject)
# Enable C and C++ languages
enable_language(C CXX)
if (XCODE)
# Support Xcode's multi configuration paradigm by placing built artifacts into separate directories
set(IMHEX_MAIN_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Configs/$<CONFIG>" PARENT_SCOPE)
@@ -397,12 +400,14 @@ macro(setDefaultBuiltTypeIfUnset)
endif()
endmacro()
function(loadVersion version)
function(loadVersion version plain_version)
set(VERSION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/VERSION")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${VERSION_FILE})
file(READ "${VERSION_FILE}" read_version)
string(STRIP ${read_version} read_version)
string(REPLACE ".WIP" "" read_version_plain ${read_version})
set(${version} ${read_version} PARENT_SCOPE)
set(${plain_version} ${read_version_plain} PARENT_SCOPE)
endfunction()
function(detectBadClone)
@@ -548,8 +553,6 @@ macro(setupDebugCompressionFlag)
elseif (COMPRESS_AVAILABLE_COMPILER AND COMPRESS_AVAILABLE_LINKER)
message("Using default compression for debug info because both compiler and linker support it")
set(DEBUG_COMPRESSION_FLAG "-gz" CACHE STRING "Cache to use for debug info compression")
else()
message("No compression available for debug info")
endif()
endif()
@@ -572,7 +575,7 @@ macro(setupCompilerFlags target)
set(IMHEX_CXX_FLAGS "-fexceptions -frtti")
# Disable some warnings
set(IMHEX_C_CXX_FLAGS "-Wno-unknown-warning-option -Wno-array-bounds -Wno-deprecated-declarations -Wno-unknown-pragmas")
set(IMHEX_C_CXX_FLAGS "-Wno-array-bounds -Wno-deprecated-declarations -Wno-unknown-pragmas")
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU")
@@ -581,6 +584,13 @@ macro(setupCompilerFlags target)
endif ()
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND APPLE)
execute_process(COMMAND brew --prefix llvm OUTPUT_VARIABLE LLVM_PREFIX OUTPUT_STRIP_TRAILING_WHITESPACE)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L${LLVM_PREFIX}/lib/c++")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L${LLVM_PREFIX}/lib/c++")
set(IMHEX_C_CXX_FLAGS "-Wno-unknown-warning-option")
endif()
# Disable some warnings for gcc
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU")
set(IMHEX_C_CXX_FLAGS "${IMHEX_C_CXX_FLAGS} -Wno-restrict -Wno-stringop-overread -Wno-stringop-overflow -Wno-dangling-reference")
@@ -700,6 +710,14 @@ macro(addBundledLibraries)
set(JTHREAD_LIBRARIES jthread)
endif()
if (USE_SYSTEM_BOOST)
find_package(Boost REQUIRED)
set(BOOST_LIBRARIES Boost::regex)
else()
add_subdirectory(${THIRD_PARTY_LIBS_FOLDER}/boost ${CMAKE_CURRENT_BINARY_DIR}/boost EXCLUDE_FROM_ALL)
set(BOOST_LIBRARIES boost::regex)
endif()
set(LIBPL_BUILD_CLI_AS_EXECUTABLE OFF CACHE BOOL "" FORCE)
set(LIBPL_ENABLE_PRECOMPILED_HEADERS ${IMHEX_ENABLE_PRECOMPILED_HEADERS} CACHE BOOL "" FORCE)
@@ -839,6 +857,9 @@ function(generateSDKDirectory)
if (NOT USE_SYSTEM_NLOHMANN_JSON)
install(DIRECTORY ${CMAKE_SOURCE_DIR}/lib/third_party/nlohmann_json DESTINATION "${SDK_PATH}/lib/third_party")
endif()
if (NOT USE_SYSTEM_BOOST)
install(DIRECTORY ${CMAKE_SOURCE_DIR}/lib/third_party/boost DESTINATION "${SDK_PATH}/lib/third_party")
endif()
install(DIRECTORY ${CMAKE_SOURCE_DIR}/cmake/modules DESTINATION "${SDK_PATH}/cmake")
install(FILES ${CMAKE_SOURCE_DIR}/cmake/build_helpers.cmake DESTINATION "${SDK_PATH}/cmake")

View File

@@ -89,4 +89,5 @@ if (CoreClrEmbed_INCLUDE_DIR AND CoreClrEmbed_LIBRARY)
set(CoreClrEmbed_LIBRARIES "${CoreClrEmbed_LIBRARY}" CACHE STRING "CoreClrEmbed libraries" FORCE)
set(CoreClrEmbed_SHARED_LIBRARIES "${CoreClrEmbed_SHARED_LIBRARY}" CACHE STRING "CoreClrEmbed shared libraries" FORCE)
set(CoreClrEmbed_INCLUDE_DIRS "${CoreClrEmbed_INCLUDE_DIR}" CACHE STRING "CoreClrEmbed include directories" FORCE)
set(CoreClrEmbed_VERSION "${CORECLR_RUNTIME_VERSION_FULL}" CACHE STRING "CoreClrEmbed version" FORCE)
endif()

View File

@@ -0,0 +1,60 @@
find_path(LZ4_INCLUDE_DIR
NAMES lz4.h
HINTS "${LZ4_INCLUDEDIR}" "${LZ4_HINTS}/include"
PATHS
/usr/local/include
/usr/include
)
find_library(LZ4_LIBRARY
NAMES lz4 liblz4
HINTS "${LZ4_LIBDIR}" "${LZ4_HINTS}/lib"
PATHS
/usr/local/lib
/usr/lib
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args( LZ4 DEFAULT_MSG LZ4_LIBRARY LZ4_INCLUDE_DIR )
if( LZ4_FOUND )
include( CheckIncludeFile )
include( CMakePushCheckState )
set( LZ4_INCLUDE_DIRS ${LZ4_INCLUDE_DIR} )
set( LZ4_LIBRARIES ${LZ4_LIBRARY} )
cmake_push_check_state()
set( CMAKE_REQUIRED_INCLUDES ${LZ4_INCLUDE_DIRS} )
check_include_file( lz4frame.h HAVE_LZ4FRAME_H )
cmake_pop_check_state()
if (WIN32)
set ( LZ4_DLL_DIR "${LZ4_HINTS}/bin"
CACHE PATH "Path to LZ4 DLL"
)
file( GLOB _lz4_dll RELATIVE "${LZ4_DLL_DIR}"
"${LZ4_DLL_DIR}/lz4*.dll"
)
set ( LZ4_DLL ${_lz4_dll}
# We're storing filenames only. Should we use STRING instead?
CACHE FILEPATH "LZ4 DLL file name"
)
file( GLOB _lz4_pdb RELATIVE "${LZ4_DLL_DIR}"
"${LZ4_DLL_DIR}/lz4*.pdb"
)
set ( LZ4_PDB ${_lz4_pdb}
CACHE FILEPATH "LZ4 PDB file name"
)
mark_as_advanced( LZ4_DLL_DIR LZ4_DLL LZ4_PDB )
endif()
else()
set( LZ4_INCLUDE_DIRS )
set( LZ4_LIBRARIES )
endif()
mark_as_advanced( LZ4_LIBRARIES LZ4_INCLUDE_DIRS )
add_library( LZ4::lz4 INTERFACE IMPORTED )
set_property( TARGET LZ4::lz4 PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${LZ4_INCLUDE_DIRS} )
set_property( TARGET LZ4::lz4 PROPERTY INTERFACE_LINK_LIBRARIES ${LZ4_LIBRARIES} )

View File

@@ -38,4 +38,8 @@ if (ZSTD_FOUND)
message(STATUS "Found Zstd: ${ZSTD_LIBRARY}")
endif()
mark_as_advanced(ZSTD_INCLUDE_DIR ZSTD_LIBRARY)
mark_as_advanced(ZSTD_INCLUDE_DIR ZSTD_LIBRARY)
add_library(ZSTD::zstd INTERFACE IMPORTED)
set_property(TARGET ZSTD::zstd PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${ZSTD_INCLUDE_DIR})
set_property(TARGET ZSTD::zstd PROPERTY INTERFACE_LINK_LIBRARIES ${ZSTD_LIBRARY})

View File

@@ -55,9 +55,9 @@ IF(MBEDTLS_FOUND)
MESSAGE(STATUS " Crypto: ${MBEDCRYPTO_LIBRARY}")
ENDIF(NOT MBEDTLS_FIND_QUIETLY)
ELSE(MBEDTLS_FOUND)
IF(MBEDTLS_FIND_REQUIRED)
IF(mbedTLS_FIND_REQUIRED)
MESSAGE(FATAL_ERROR "Could not find mbedTLS")
ENDIF(MBEDTLS_FIND_REQUIRED)
ENDIF(mbedTLS_FIND_REQUIRED)
ENDIF(MBEDTLS_FOUND)
MARK_AS_ADVANCED(
@@ -67,4 +67,4 @@ MARK_AS_ADVANCED(
MBEDTLS_LIBRARY
MBEDX509_LIBRARY
MBEDCRYPTO_LIBRARY
)
)

View File

@@ -72,10 +72,23 @@ macro(add_imhex_plugin)
add_subdirectory(${IMHEX_BASE_FOLDER}/lib/external/libromfs ${CMAKE_CURRENT_BINARY_DIR}/libromfs)
target_link_libraries(${IMHEX_PLUGIN_NAME} PRIVATE ${LIBROMFS_LIBRARY})
foreach(feature ${IMHEX_PLUGIN_FEATURES})
string(TOUPPER ${feature} feature)
add_definitions(-DIMHEX_PLUGIN_${IMHEX_PLUGIN_NAME}_FEATURE_${feature}=0)
endforeach()
set(FEATURE_DEFINE_CONTENT)
if (IMHEX_PLUGIN_FEATURES)
list(LENGTH IMHEX_PLUGIN_FEATURES IMHEX_FEATURE_COUNT)
math(EXPR IMHEX_FEATURE_COUNT "${IMHEX_FEATURE_COUNT} - 1" OUTPUT_FORMAT DECIMAL)
foreach(index RANGE 0 ${IMHEX_FEATURE_COUNT} 2)
list(SUBLIST IMHEX_PLUGIN_FEATURES ${index} 2 IMHEX_PLUGIN_FEATURE)
list(GET IMHEX_PLUGIN_FEATURE 0 feature_define)
list(GET IMHEX_PLUGIN_FEATURE 1 feature_description)
string(TOUPPER ${feature_define} feature_define)
add_definitions(-DIMHEX_PLUGIN_${IMHEX_PLUGIN_NAME}_FEATURE_${feature_define}=0)
set(FEATURE_DEFINE_CONTENT "${FEATURE_DEFINE_CONTENT}{ \"${feature_description}\", IMHEX_FEATURE_ENABLED(${feature_define}) },")
endforeach()
endif()
target_compile_options(${IMHEX_PLUGIN_NAME} PRIVATE -DIMHEX_PLUGIN_FEATURES_CONTENT=${FEATURE_DEFINE_CONTENT})
# Add the new plugin to the main dependency list so it gets built by default
if (TARGET imhex_all)
@@ -88,12 +101,28 @@ macro(add_imhex_plugin)
# Fix rpath
if (APPLE)
set_target_properties(${IMHEX_PLUGIN_NAME} PROPERTIES INSTALL_RPATH "@executable_path/../Frameworks;@executable_path/plugins")
set_target_properties(
${IMHEX_PLUGIN_NAME}
PROPERTIES
INSTALL_RPATH "@executable_path/../Frameworks;@executable_path/plugins"
)
elseif (UNIX)
set_target_properties(${IMHEX_PLUGIN_NAME} PROPERTIES INSTALL_RPATH_USE_ORIGIN ON INSTALL_RPATH "$ORIGIN/")
set(PLUGIN_RPATH "")
list(APPEND PLUGIN_RPATH "$ORIGIN")
if (IMHEX_PLUGIN_ADD_INSTALL_PREFIX_TO_RPATH)
list(APPEND PLUGIN_RPATH "${CMAKE_INSTALL_PREFIX}/lib")
endif()
set_target_properties(
${IMHEX_PLUGIN_NAME}
PROPERTIES
INSTALL_RPATH_USE_ORIGIN ON
INSTALL_RPATH "${PLUGIN_RPATH}"
)
endif()
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt AND IMHEX_ENABLE_UNIT_TESTS)
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt AND IMHEX_ENABLE_UNIT_TESTS AND IMHEX_ENABLE_PLUGIN_TESTS)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/tests)
target_link_libraries(${IMHEX_PLUGIN_NAME} PUBLIC ${IMHEX_PLUGIN_NAME}_tests)
target_compile_definitions(${IMHEX_PLUGIN_NAME}_tests PRIVATE IMHEX_PROJECT_NAME="${IMHEX_PLUGIN_NAME}-tests")
@@ -101,6 +130,10 @@ macro(add_imhex_plugin)
endmacro()
macro(add_romfs_resource input output)
if (NOT EXISTS ${input})
message(WARNING "Resource file ${input} does not exist")
endif()
configure_file(${input} ${CMAKE_CURRENT_BINARY_DIR}/romfs/${output} COPYONLY)
list(APPEND LIBROMFS_RESOURCE_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/romfs)

View File

@@ -29,6 +29,10 @@ add_subdirectory_if_exists(lib/third_party/nlohmann_json)
set(NLOHMANN_JSON_LIBRARIES nlohmann_json PARENT_SCOPE)
set(NLOHMANN_JSON_LIBRARIES nlohmann_json)
add_subdirectory_if_exists(lib/third_party/boost)
set(BOOST_LIBRARIES boost::regex PARENT_SCOPE)
set(BOOST_LIBRARIES boost::regex)
add_subdirectory(lib/external/libwolv EXCLUDE_FROM_ALL)
set(LIBPL_ENABLE_CLI OFF CACHE BOOL "" FORCE)
@@ -44,7 +48,7 @@ add_subdirectory(lib/libimhex)
if (WIN32)
set_target_properties(libimhex PROPERTIES
IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/../libimhex.dll"
IMPORTED_IMPLIB "${CMAKE_CURRENT_SOURCE_DIR}/lib/libimhex.dll.a"
IMPORTED_IMPLIB "${CMAKE_CURRENT_SOURCE_DIR}/lib/liblibimhex.dll.a"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/lib/libimhex/include")
elseif (APPLE)
file(GLOB LIBIMHEX_DYLIB "${CMAKE_CURRENT_SOURCE_DIR}/../../Frameworks/libimhex.*.dylib")

View File

@@ -14,22 +14,23 @@ AppDir:
- amd64
allow_unauthenticated: true
sources:
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ jammy main restricted
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ jammy-updates main restricted
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ jammy universe
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ jammy-updates universe
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ jammy multiverse
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ jammy-updates multiverse
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ jammy-backports main restricted
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ oracular main restricted
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ oracular-updates main restricted
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ oracular universe
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ oracular-updates universe
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ oracular multiverse
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ oracular-updates multiverse
- sourceline: deb http://us.archive.ubuntu.com/ubuntu/ oracular-backports main restricted
universe multiverse
- sourceline: deb http://security.ubuntu.com/ubuntu jammy-security main restricted
- sourceline: deb http://security.ubuntu.com/ubuntu jammy-security universe
- sourceline: deb http://security.ubuntu.com/ubuntu jammy-security multiverse
- sourceline: deb http://security.ubuntu.com/ubuntu oracular-security main restricted
- sourceline: deb http://security.ubuntu.com/ubuntu oracular-security universe
- sourceline: deb http://security.ubuntu.com/ubuntu oracular-security multiverse
include:
- librsvg2-common
- libbz2-1.0:amd64
- libcap2:amd64
- libdbus-1-3:amd64
- libfontconfig1:amd64
- libgpg-error0:amd64
- liblzma5:amd64
- libnss-mdns:amd64

View File

@@ -13,6 +13,7 @@ RUN pacman -S --needed --noconfirm \
glfw-x11 \
file \
mbedtls \
fontconfig \
freetype2 \
curl \
dbus \

4
dist/Arch/PKGBUILD vendored
View File

@@ -8,7 +8,7 @@ pkgdesc="A Hex Editor for Reverse Engineers, Programmers and people who value th
arch=("x86_64")
url="https://github.com/WerWolv/ImHex"
license=('GPL2')
depends=(glfw mbedtls freetype2 libglvnd dbus gtk3 curl fmt yara nlohmann-json zlib bzip2 xz zstd)
depends=(glfw mbedtls fontconfig freetype2 libglvnd dbus gtk3 curl fmt yara nlohmann-json zlib bzip2 xz zstd)
makedepends=(git)
provides=(imhex)
conflicts=(imhex)
@@ -26,5 +26,5 @@ package() {
install -d "$pkgdir/usr/share/imhex"
cp -r "$srcdir/usr/share/imhex/"{constants,encodings,includes,magic,patterns} "$pkgdir/usr/share/imhex"
cp -r "$srcdir/usr/share/"{applications,licenses,pixmaps} "$pkgdir/usr/share"
cp -r "$srcdir/usr/share/"{applications,licenses,pixmaps,mime} "$pkgdir/usr/share"
}

1
dist/Brewfile vendored
View File

@@ -6,7 +6,6 @@ brew "freetype2"
brew "libmagic"
brew "pkg-config"
brew "curl"
brew "gcc@12"
brew "llvm"
brew "glfw"
brew "ninja"

View File

@@ -4,7 +4,7 @@ Section: editors
Priority: optional
Architecture: amd64
License: GNU GPL-2
Depends: libglfw3 | libglfw3-wayland, libmagic1, libmbedtls14, libfreetype6, libopengl0, libdbus-1-3, xdg-desktop-portal
Depends: libfontconfig1, libglfw3 | libglfw3-wayland, libmagic1, libmbedtls14, libfreetype6, libopengl0, libdbus-1-3, xdg-desktop-portal
Maintainer: WerWolv <hey@werwolv.net>
Description: ImHex Hex Editor
A Hex Editor for Reverse Engineers, Programmers and

View File

@@ -20,13 +20,14 @@ DEPEND=""
RDEPEND="${DEPEND}
media-libs/glfw
sys-apps/file
dev-libs/mbedtls
net-libs/mbedtls
dev-cpp/nlohmann_json
dbus
xdg-desktop-portal
sys-apps/dbus
sys-apps/xdg-desktop-portal
sys-libs/zlib
app-arch/bzip2
app-arch/lzma
app-arch/zstd
app-arch/bzip2
app-arch/lzma
app-arch/zstd
app-arch/lz4
"
BDEPEND="${DEPEND}"

View File

@@ -1,4 +1,4 @@
FROM ubuntu:22.04 as build
FROM ubuntu:24.10 as build
# Used to invalidate layer cache but not mount cache
# See https://github.com/moby/moby/issues/41715#issuecomment-733976493
@@ -14,24 +14,13 @@ apt update
# general deps
apt install -y ccache git wget
# appimage tools deps
apt install -y python3-pip python3-setuptools desktop-file-utils libgdk-pixbuf2.0-dev fuse ninja-build
apt install -y python3-pip python3-venv python3-setuptools desktop-file-utils libgdk-pixbuf2.0-dev fuse ninja-build
apt install -y squashfs-tools zsync
# imhex deps
/tmp/get_deps_debian.sh
EOF
RUN --mount=type=cache,target=/cache <<EOF
# Download appimage-builder
set -xe
mkdir -p /cache/bin
wget -nc https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage -O /cache/bin/appimagetool || true
chmod +x /cache/bin/appimagetool
pip3 install git+https://github.com/AppImageCrafters/appimage-builder@f38699e
EOF
ENV PATH="/cache/bin/:${PATH}"
# Copy Imhex source
@@ -47,7 +36,7 @@ RUN <<EOF
# Prepare ImHex build
set -xe
CC=gcc-12 CXX=g++-12 cmake -G "Ninja" \
CC=gcc-14 CXX=g++-14 cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE=${BUILD_TYPE} \
-DCMAKE_INSTALL_PREFIX="/usr" \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
@@ -71,9 +60,18 @@ ccache -s
EOF
RUN <<EOF
# Package ImHex as AppImage
# Download appimage-builder
set -xe
mkdir -p /cache/bin
wget -nc https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage -O /cache/bin/appimagetool || true
chmod +x /cache/bin/appimagetool
python3 -m venv venv
. venv/bin/activate
pip3 install git+https://github.com/AppImageCrafters/appimage-builder@f38699e
# Package ImHex as AppImage
export VERSION=$(cat /imhex/VERSION)
appimage-builder --recipe /imhex/dist/AppImageBuilder.yml
EOF

View File

@@ -5,6 +5,7 @@ pacman -S $@ --needed \
gcc \
lld \
glfw \
fontconfig \
file \
mbedtls \
freetype2 \
@@ -18,4 +19,5 @@ pacman -S $@ --needed \
zlib \
bzip2 \
xz \
zstd
zstd \
lz4

View File

@@ -8,8 +8,8 @@ fi
apt install -y \
build-essential \
gcc-12 \
g++-12 \
gcc-14 \
g++-14 \
lld \
${PKGCONF:-} \
cmake \
@@ -18,6 +18,7 @@ apt install -y \
libglm-dev \
libmagic-dev \
libmbedtls-dev \
libfontconfig-dev \
libfreetype-dev \
libdbus-1-dev \
libcurl4-gnutls-dev \
@@ -26,4 +27,5 @@ apt install -y \
zlib1g-dev \
libbz2-dev \
liblzma-dev \
libzstd-dev
libzstd-dev \
liblz4-dev

View File

@@ -4,6 +4,7 @@ dnf install -y \
cmake \
dbus-devel \
file-devel \
fontconfig-devel \
freetype-devel \
libcurl-devel \
gcc-c++ \
@@ -16,4 +17,5 @@ dnf install -y \
libzstd-devel \
zlib-devel \
bzip2-devel \
xz-devel
xz-devel \
lz4-devel

View File

@@ -17,4 +17,5 @@ pacboy -S --needed --noconfirm \
zlib:p \
bzip2:p \
xz:p \
zstd:p
zstd:p \
lz4:p

View File

@@ -3,8 +3,9 @@
zypper install \
cmake \
ninja \
gcc12 \
gcc12-c++ \
gcc14 \
gcc14-c++ \
fontconfig-devel \
freetype2-devel \
libcurl-devel \
dbus-1-devel \
@@ -16,4 +17,5 @@ zypper install \
libzstd-devel \
zlib-devel \
bzip3-devel \
xz-devel
xz-devel \
lz4-dev

1
dist/imhex.desktop vendored
View File

@@ -9,3 +9,4 @@ StartupNotify=true
Categories=Development;IDE;
StartupWMClass=imhex
Keywords=static-analysis;reverse-engineering;disassembler;disassembly;hacking;forensics;hex-editor;cybersecurity;security;binary-analysis;
MimeType=application/vnd.imhex.proj;

8
dist/imhex.mime.xml vendored Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
<mime-type type="application/vnd.imhex.proj">
<comment>ImHex Project</comment>
<glob pattern="*.hexproj"/>
</mime-type>
</mime-info>

16
dist/langtool.py vendored
View File

@@ -129,16 +129,19 @@ def main():
key in lang_data["translations"]
and lang_data["translations"][key] != INVALID_TRANSLATION
)
if not has_translation and not (
(command == "retranslate" or command == "untranslate")
and re.compile(args.keys).fullmatch(key)
if (
has_translation
and not (
(command == "retranslate" or command == "untranslate")
and re.compile(args.keys).fullmatch(key)
)
and not command == "fmtzh"
):
continue
if command == "check":
print(
f"Error: Translation {lang_data['code']} is missing translation for key '{key}'"
)
exit(2)
elif (
command == "translate"
or command == "retranslate"
@@ -148,7 +151,10 @@ def main():
continue
reference_tranlsation = (
" '%s'" % reference_lang_data["translations"][key]
if reference_lang_data
if (
reference_lang_data
and key in reference_lang_data["translations"]
)
else ""
)
print(

View File

@@ -1,7 +1,7 @@
# This base image is also known as "crosscompile". See arm64.crosscompile.Dockerfile
FROM ghcr.io/itrooz/macos-crosscompile:clang17-nosdk as build
ENV MACOSX_DEPLOYMENT_TARGET 12.1
ENV MACOSX_DEPLOYMENT_TARGET 13.0
# -- DOWNLOADING STUFF
@@ -118,7 +118,7 @@ if [ "$CUSTOM_GLFW" ]; then
cd /mnt/glfw
mkdir build
cd build
CC=o64-gcc CXX=o64-g++ cmake -G "Ninja" \
CC=o64-clang CXX=o64-clang++ cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE=$BUILD_TYPE \
-DBUILD_SHARED_LIBS=ON \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
@@ -126,7 +126,7 @@ if [ "$CUSTOM_GLFW" ]; then
-DCMAKE_OBJC_COMPILER_LAUNCHER=ccache \
-DCMAKE_OBJCXX_COMPILER_LAUNCHER=ccache \
-DCMAKE_INSTALL_PREFIX=/vcpkg/installed/arm-osx-mytriplet \
-DVCPKG_TARGET_TRIPLET=arm-osx-mytriplet -DCMAKE_TOOLCHAIN_FILE=/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE=/osxcross/target/toolchain.cmake -DCMAKE_OSX_SYSROOT=/osxcross/target/SDK/MacOSX14.0.sdk -DCMAKE_OSX_DEPLOYMENT_TARGET=12.1 \
-DVCPKG_TARGET_TRIPLET=arm-osx-mytriplet -DCMAKE_TOOLCHAIN_FILE=/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE=/osxcross/target/toolchain.cmake -DCMAKE_OSX_SYSROOT=/osxcross/target/SDK/MacOSX14.0.sdk -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 \
..
ninja -j $JOBS install
@@ -148,7 +148,7 @@ RUN --mount=type=cache,target=/cache --mount=type=cache,target=/mnt/ImHex/build/
`# ccache flags` \
-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_OBJC_COMPILER_LAUNCHER=ccache -DCMAKE_OBJCXX_COMPILER_LAUNCHER=ccache \
`# MacOS cross-compiling flags` \
-DVCPKG_TARGET_TRIPLET=arm-osx-mytriplet -DCMAKE_TOOLCHAIN_FILE=/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE=/osxcross/target/toolchain.cmake -DCMAKE_OSX_SYSROOT=/osxcross/target/SDK/MacOSX14.0.sdk -DCMAKE_OSX_DEPLOYMENT_TARGET=12.1 \
-DVCPKG_TARGET_TRIPLET=arm-osx-mytriplet -DCMAKE_TOOLCHAIN_FILE=/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE=/osxcross/target/toolchain.cmake -DCMAKE_OSX_SYSROOT=/osxcross/target/SDK/MacOSX14.0.sdk -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 \
`# Override compilers for code generators` \
-DNATIVE_CMAKE_C_COMPILER=/usr/bin/clang -DNATIVE_CMAKE_CXX_COMPILER=/usr/bin/clang++ \
`# Normal ImHex flags` \

View File

@@ -68,19 +68,6 @@ RUN --mount=type=cache,target=/cache <<EOF
ccache -s
EOF
# Not needed, because we don't use gcc for cross-compiling anymore
# ## Install dependencies for gcc-13
# RUN apt install -y gcc g++ zlib1g-dev libmpc-dev libmpfr-dev libgmp-dev
# ## Build cross-compiler gcc-13
# RUN --mount=type=cache,target=/cache <<EOF
# set -xe
# ccache -zs
# cd /osxcross
# UNATTENDED=1 CC=/usr/lib/ccache/gcc CXX=/usr/lib/ccache/g++ GCC_VERSION=13.2.0 ./build_gcc.sh
# ccache -s
# EOF
ARG DELETE_SDK=1
RUN <<EOF

19
dist/rpm/imhex.spec vendored
View File

@@ -1,3 +1,5 @@
%define source_date_epoch_from_changelog 0
Name: imhex
Version: VERSION
Release: 0%{?dist}
@@ -14,6 +16,7 @@ BuildRequires: cmake
BuildRequires: desktop-file-utils
BuildRequires: dbus-devel
BuildRequires: file-devel
BuildRequires: fontconfig-devel
BuildRequires: freetype-devel
BuildRequires: fmt-devel
BuildRequires: gcc-c++
@@ -32,7 +35,7 @@ BuildRequires: zlib-devel
BuildRequires: bzip2-devel
BuildRequires: xz-devel
%if 0%{?rhel}
BuildRequires: gcc-toolset-12
BuildRequires: gcc-toolset-14
%endif
Provides: bundled(gnulib)
@@ -68,9 +71,9 @@ rm -rf lib/third_party/{fmt,nlohmann_json,yara}
%build
%if 0%{?rhel}
. /opt/rh/gcc-toolset-12/enable
. /opt/rh/gcc-toolset-14/enable
%set_build_flags
CXXFLAGS+=" -std=gnu++2b"
CXXFLAGS+=" -std=gnu++23"
%endif
%cmake \
-D CMAKE_BUILD_TYPE=Release \
@@ -91,9 +94,9 @@ CXXFLAGS+=" -std=gnu++2b"
%check
%if 0%{?rhel}
. /opt/rh/gcc-toolset-12/enable
. /opt/rh/gcc-toolset-14/enable
%set_build_flags
CXXFLAGS+=" -std=gnu++2b"
CXXFLAGS+=" -std=gnu++23"
%endif
@@ -122,9 +125,7 @@ cp -a lib/third_party/xdgpp/LICENSE %{buildroot
%{_bindir}/imhex-updater
%{_datadir}/pixmaps/%{name}.png
%{_datadir}/applications/%{name}.desktop
%{_datadir}/mime/packages/%{name}.xml
%{_libdir}/libimhex.so*
%{_libdir}/%{name}/
%{_metainfodir}/net.werwolv.%{name}.metainfo.xml
%changelog
%{_metainfodir}/net.werwolv.%{name}.metainfo.xml

5
dist/web/Dockerfile vendored
View File

@@ -5,7 +5,7 @@ FROM emscripten/emsdk:3.1.51 as build
ARG UNIQUEKEY 1
RUN apt update
RUN apt install -y git ccache autoconf automake libtool cmake pkg-config
RUN apt install -y git ccache autoconf automake libtool cmake pkg-config ninja-build
RUN <<EOF
# Install vcpkg
@@ -56,6 +56,7 @@ set -xe
ccache -zs
cmake /imhex \
-G "Ninja" \
-DIMHEX_OFFLINE_BUILD=ON \
-DIMHEX_STATIC_LINK_PLUGINS=ON \
-DIMHEX_EXCLUDE_PLUGINS="script_loader" \
@@ -68,7 +69,7 @@ cmake /imhex
-DVCPKG_CHAINLOAD_TOOLCHAIN_FILE=/emsdk/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake \
-DCMAKE_BUILD_TYPE=Release
make -j $JOBS
ninja -j $JOBS
cp /imhex/dist/web/source/* /build
ccache -s

View File

@@ -62,7 +62,7 @@
</head>
<body>
<div id="loading" class="centered">
<img src="https://raw.githubusercontent.com/WerWolv/ImHex/master/plugins/builtin/romfs/assets/dark/banner.png" id="logo" alt="ImHex Logo">
<img src="https://raw.githubusercontent.com/WerWolv/ImHex/master/plugins/builtin/romfs/assets/dark/banner.svg" id="logo" alt="ImHex Logo">
<h1>A Hex Editor for Reverse Engineers, Programmers and people who value their retinas when working at 3 AM.</h1>
<h2>Available both natively and on the web</h2>
<h5>ImHex runs directly in your web browser with the help of Emscripten and WebAssembly.</h5>

View File

@@ -137,7 +137,7 @@ a:hover {
:root {
--progress: 25%;
--progress: 0%;
}
.progress-bar-container {
@@ -174,4 +174,15 @@ a:hover {
.progress-moved .progress-bar {
width: var(--progress);
background-color: #3864cb;
}
#logo {
height: 25%;
margin-top: 50px;
}
.canvas-fixed {
position: absolute;
top: 0;
left: 0;
}

View File

@@ -100,7 +100,77 @@ var notWorkingTimer = setTimeout(() => {
var Module = {
preRun: [],
postRun: [],
postRun: function() {
// Patch the emscripten GLFW module to send mouse and touch events in the right order
// For ImGui interactions to correctly work with touch input, MousePos events need
// to be processed first and then MouseButton events in the next frame. By default,
// GLFW does the exact opposite, which causes buttons to require two taps to register
// and windows get "stuck" to the cursor when dragged or resized
GLFW.onMousemove = event => {
if (event.type === "touchmove") {
event.preventDefault();
let primaryChanged = false;
for (let i of event.changedTouches) {
if (GLFW.primaryTouchId === i.identifier) {
Browser.setMouseCoords(i.pageX, i.pageY);
primaryChanged = true;
break;
}
}
if (!primaryChanged) {
return;
}
} else {
Browser.calculateMouseEvent(event);
}
};
GLFW.onMouseButtonChanged = (event, status) => {
if (!GLFW.active) return;
if (event.target != Module["canvas"]) return;
const isTouchType = event.type === "touchstart" || event.type === "touchend" || event.type === "touchcancel";
let eventButton = 0;
if (isTouchType) {
event.preventDefault();
let primaryChanged = false;
if (GLFW.primaryTouchId === null && event.type === "touchstart" && event.targetTouches.length > 0) {
const chosenTouch = event.targetTouches[0];
GLFW.primaryTouchId = chosenTouch.identifier;
Browser.setMouseCoords(chosenTouch.pageX, chosenTouch.pageY);
primaryChanged = true;
} else if (event.type === "touchend" || event.type === "touchcancel") {
for (let i of event.changedTouches) {
if (GLFW.primaryTouchId === i.identifier) {
GLFW.primaryTouchId = null;
primaryChanged = true;
break;
}
}
}
if (!primaryChanged) {
return;
}
} else {
Browser.calculateMouseEvent(event);
eventButton = GLFW.DOMToGLFWMouseButton(event);
}
if (status == 1) {
GLFW.active.buttons |= (1 << eventButton);
try {
event.target.setCapture();
} catch (e) {}
} else {
GLFW.active.buttons &= ~(1 << eventButton);
}
if (GLFW.active.cursorPosFunc) {
getWasmTableEntry(GLFW.active.cursorPosFunc)(GLFW.active.id, Browser.mouseX, Browser.mouseY);
}
if (GLFW.active.mouseButtonFunc) {
getWasmTableEntry(GLFW.active.mouseButtonFunc)(GLFW.active.id, eventButton, status, GLFW.getModBits(GLFW.active));
}
};
},
onRuntimeInitialized: function() {
// Triggered when the wasm module is loaded and ready to use.
document.getElementById("loading").style.display = "none"
@@ -111,13 +181,55 @@ var Module = {
print: (function() { })(),
printErr: function(text) { },
canvas: (function() {
let canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
const canvas = document.getElementById('canvas');
canvas.addEventListener("webglcontextlost", function(e) {
alert('WebGL context lost, please reload the page');
e.preventDefault();
}, false);
return canvas;
// Turn long touches into right-clicks
let timer = null;
canvas.addEventListener('touchstart', event => {
timer = setTimeout(() => {
let eventArgs = {
bubbles: true,
cancelable: true,
view: window,
screenX: event.touches[0].screenX,
screenY: event.touches[0].screenY,
clientX: event.touches[0].clientX,
clientY: event.touches[0].clientY,
button: 2,
buttons: 2,
relatedTarget: event.target,
region: event.region
}
canvas.dispatchEvent(new MouseEvent('mousedown', eventArgs));
canvas.dispatchEvent(new MouseEvent('mouseup', eventArgs));
}, 400);
});
canvas.addEventListener('touchend', event => {
if (timer) {
clearTimeout(timer);
timer = null;
}
});
if (typeof WebGL2RenderingContext !== 'undefined') {
let gl = canvas.getContext('webgl2', { stencil: true });
if (!gl) {
console.error('WebGL 2 not available, falling back to WebGL');
gl = canvas.getContext('webgl', { stencil: true });
}
if (!gl) {
alert('WebGL not available with stencil buffer');
}
return canvas;
} else {
alert('WebGL 2 not supported by this browser');
}
})(),
setStatus: function(text) { },
totalDependencies: 0,
@@ -144,14 +256,16 @@ if (urlParams.has("lang")) {
window.addEventListener('resize', js_resizeCanvas, false);
function js_resizeCanvas() {
let canvas = document.getElementById('canvas');
canvas.top = document.documentElement.clientTop;
canvas.left = document.documentElement.clientLeft;
canvas.width = Math.min(document.documentElement.clientWidth, window.innerWidth || 0);
canvas.height = Math.min(document.documentElement.clientHeight, window.innerHeight || 0);
}
canvas.classList.add("canvas_full_screen")
if (GLFW.active && GLFW.active.windowPosFunc) {
getWasmTableEntry(GLFW.active.windowPosFunc)(GLFW.active.id, GLFW.active.x, GLFW.active.y);
// Prevent some default browser shortcuts from preventing ImHex ones to work
document.addEventListener('keydown', e => {
if (e.ctrlKey) {
if (e.which == 83) e.preventDefault();
}
GLFW.onWindowSizeChanged();
}
})

View File

@@ -36,6 +36,9 @@ set(LIBIMHEX_SOURCES
source/helpers/logger.cpp
source/helpers/tar.cpp
source/helpers/debugging.cpp
source/helpers/default_paths.cpp
source/helpers/imgui_hooks.cpp
source/helpers/semantic_version.cpp
source/test/tests.cpp
@@ -123,7 +126,7 @@ target_link_directories(libimhex ${LIBIMHEX_LIBRARY_TYPE} ${MBEDTLS_LIBRARY_DIR}
if (NOT EMSCRIPTEN)
# curl is only used in non-emscripten builds
target_link_libraries(libimhex ${LIBIMHEX_LIBRARY_TYPE} ${CURL_LIBRARIES})
target_link_libraries(libimhex ${LIBIMHEX_LIBRARY_TYPE} CURL::libcurl)
endif()
@@ -142,7 +145,7 @@ if (NOT IMHEX_EXTERNAL_PLUGIN_BUILD)
precompileHeaders(libimhex "${CMAKE_CURRENT_SOURCE_DIR}/include")
endif()
target_link_libraries(libimhex ${LIBIMHEX_LIBRARY_TYPE} ${NLOHMANN_JSON_LIBRARIES} imgui_all_includes ${MBEDTLS_LIBRARIES} ${FMT_LIBRARIES} ${LUNASVG_LIBRARIES})
target_link_libraries(libimhex ${LIBIMHEX_LIBRARY_TYPE} ${NLOHMANN_JSON_LIBRARIES} imgui_all_includes ${MBEDTLS_LIBRARIES} ${FMT_LIBRARIES} ${LUNASVG_LIBRARIES} ${BOOST_LIBRARIES})
set_property(TARGET libimhex PROPERTY INTERPROCEDURAL_OPTIMIZATION FALSE)

View File

@@ -1,4 +1,3 @@
#pragma once
#include <hex/helpers/types.hpp>
#include <hex/helpers/intrinsics.hpp>

View File

@@ -295,6 +295,7 @@ namespace hex {
};
class AchievementManager {
static bool s_initialized;
public:
AchievementManager() = delete;

View File

@@ -2,10 +2,10 @@
#include <hex.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/api/shortcut_manager.hpp>
#include <hex/helpers/concepts.hpp>
#include <functional>
#include <map>
#include <mutex>
#include <span>
#include <string>
@@ -24,7 +24,6 @@ enum ImGuiCustomCol : int;
namespace hex {
class View;
class Shortcut;
class Task;
namespace dp {
@@ -381,7 +380,7 @@ namespace hex {
};
using DisplayCallback = std::function<std::string(std::string)>;
using ExecuteCallback = std::function<void(std::string)>;
using ExecuteCallback = std::function<std::optional<std::string>(std::string)>;
using QueryCallback = std::function<std::vector<QueryResult>(std::string)>;
struct Entry {
@@ -417,7 +416,7 @@ namespace hex {
const std::string &command,
const UnlocalizedString &unlocalizedDescription,
const impl::DisplayCallback &displayCallback,
const impl::ExecuteCallback &executeCallback = [](auto) {});
const impl::ExecuteCallback &executeCallback = [](auto) { return std::nullopt; });
/**
* @brief Adds a new command handler to the command palette
@@ -438,7 +437,7 @@ namespace hex {
namespace impl {
using VisualizerFunctionCallback = std::function<void(pl::ptrn::Pattern&, pl::ptrn::IIterable&, bool, std::span<const pl::core::Token::Literal>)>;
using VisualizerFunctionCallback = std::function<void(pl::ptrn::Pattern&, bool, std::span<const pl::core::Token::Literal>)>;
struct FunctionDefinition {
pl::api::Namespace ns;
@@ -450,6 +449,14 @@ namespace hex {
bool dangerous;
};
struct TypeDefinition {
pl::api::Namespace ns;
std::string name;
pl::api::FunctionParameterCount parameterCount;
pl::api::TypeCallback callback;
};
struct Visualizer {
pl::api::FunctionParameterCount parameterCount;
VisualizerFunctionCallback callback;
@@ -459,6 +466,7 @@ namespace hex {
const std::map<std::string, Visualizer>& getInlineVisualizers();
const std::map<std::string, pl::api::PragmaHandler>& getPragmas();
const std::vector<FunctionDefinition>& getFunctions();
const std::vector<TypeDefinition>& getTypes();
}
@@ -517,6 +525,20 @@ namespace hex {
const pl::api::FunctionCallback &func
);
/**
* @brief Adds a new type to the pattern language
* @param ns The namespace of the type
* @param name The name of the type
* @param parameterCount The amount of non-type template parameters the type takes
* @param func The type callback
*/
void addType(
const pl::api::Namespace &ns,
const std::string &name,
pl::api::FunctionParameterCount parameterCount,
const pl::api::TypeCallback &func
);
/**
* @brief Adds a new visualizer to the pattern language
* @note Visualizers are extensions to the [[hex::visualize]] attribute, used to visualize data
@@ -748,7 +770,7 @@ namespace hex {
struct MenuItem {
std::vector<UnlocalizedString> unlocalizedNames;
Icon icon;
std::unique_ptr<Shortcut> shortcut;
Shortcut shortcut;
View *view;
MenuCallback callback;
EnabledCallback enabledCallback;
@@ -774,6 +796,7 @@ namespace hex {
const std::multimap<u32, MainMenuItem>& getMainMenuItems();
const std::multimap<u32, MenuItem>& getMenuItems();
const std::vector<MenuItem*>& getToolbarMenuItems();
std::multimap<u32, MenuItem>& getMenuItemsMutable();
const std::vector<DrawCallback>& getWelcomeScreenEntries();
@@ -916,6 +939,11 @@ namespace hex {
*/
void addMenuItemToToolbar(const UnlocalizedString &unlocalizedName, ImGuiCustomCol color);
/**
* @brief Reconstructs the toolbar items list after they have been modified
*/
void updateToolbarItems();
/**
* @brief Adds a new sidebar item
* @param icon The icon to use for the item
@@ -981,12 +1009,34 @@ namespace hex {
namespace impl {
using Callback = std::function<std::string(prv::Provider *provider, u64 address, size_t size)>;
struct Entry {
struct ExportMenuEntry {
UnlocalizedString unlocalizedName;
Callback callback;
};
const std::vector<Entry>& getEntries();
struct FindOccurrence {
Region region;
enum class DecodeType { ASCII, Binary, UTF16, Unsigned, Signed, Float, Double } decodeType;
std::endian endian = std::endian::native;
bool selected;
};
using FindExporterCallback = std::function<std::vector<u8>(const std::vector<FindOccurrence>&, std::function<std::string(FindOccurrence)>)>;
struct FindExporterEntry {
UnlocalizedString unlocalizedName;
std::string fileExtension;
FindExporterCallback callback;
};
/**
* @brief Retrieves a list of all registered data formatters used by the 'File -> Export' menu
*/
const std::vector<ExportMenuEntry>& getExportMenuEntries();
/**
* @brief Retrieves a list of all registered data formatters used in the Results section of the 'Find' view
*/
const std::vector<FindExporterEntry>& getFindExporterEntries();
}
@@ -996,7 +1046,14 @@ namespace hex {
* @param unlocalizedName The unlocalized name of the formatter
* @param callback The function to call to format the data
*/
void add(const UnlocalizedString &unlocalizedName, const impl::Callback &callback);
void addExportMenuEntry(const UnlocalizedString &unlocalizedName, const impl::Callback &callback);
/**
* @brief Adds a new data exporter for Find results
* @param unlocalizedName The unlocalized name of the formatter
* @param callback The function to call to format the data
*/
void addFindExportFormatter(const UnlocalizedString &unlocalizedName, const std::string fileExtension, const impl::FindExporterCallback &callback);
}
@@ -1057,7 +1114,7 @@ namespace hex {
};
struct MiniMapVisualizer {
using Callback = std::function<ImColor(const std::vector<u8>&)>;
using Callback = std::function<void(u64, std::span<const u8>, std::vector<ImColor>&)>;
UnlocalizedString unlocalizedName;
Callback callback;
@@ -1238,7 +1295,7 @@ namespace hex {
void stopServices();
}
void registerService(const UnlocalizedString &unlocalizedName, const impl::Callback &callback);
void registerService(const UnlocalizedString &unlocalizedString, const impl::Callback &callback);
}
/* Network Communication Interface Registry. Allows adding new communication interface endpoints */

View File

@@ -11,21 +11,22 @@
#include <hex/api/imhex_api.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/patches.hpp>
#include <wolv/types/type_name.hpp>
#define EVENT_DEF_IMPL(event_name, event_name_string, should_log, ...) \
struct event_name final : public hex::impl::Event<__VA_ARGS__> { \
constexpr static auto Id = [] { return hex::impl::EventId(event_name_string); }(); \
constexpr static auto ShouldLog = (should_log); \
explicit event_name(Callback func) noexcept : Event(std::move(func)) { } \
\
static EventManager::EventList::iterator subscribe(Event::Callback function) { return EventManager::subscribe<event_name>(function); } \
static void subscribe(void *token, Event::Callback function) { EventManager::subscribe<event_name>(token, function); } \
static void unsubscribe(const EventManager::EventList::iterator &token) noexcept { EventManager::unsubscribe(token); } \
static void unsubscribe(void *token) noexcept { EventManager::unsubscribe<event_name>(token); } \
static void post(auto &&...args) { EventManager::post<event_name>(std::forward<decltype(args)>(args)...); } \
};
#define EVENT_DEF_IMPL(event_name, event_name_string, should_log, ...) \
struct event_name final : public hex::impl::Event<__VA_ARGS__> { \
constexpr static auto Id = [] { return hex::impl::EventId(event_name_string); }(); \
constexpr static auto ShouldLog = (should_log); \
explicit event_name(Callback func) noexcept : Event(std::move(func)) { } \
\
static EventManager::EventList::iterator subscribe(Event::Callback function) { return EventManager::subscribe<event_name>(std::move(function)); } \
static void subscribe(void *token, Event::Callback function) { EventManager::subscribe<event_name>(token, std::move(function)); } \
static void unsubscribe(const EventManager::EventList::iterator &token) noexcept { EventManager::unsubscribe(token); } \
static void unsubscribe(void *token) noexcept { EventManager::unsubscribe<event_name>(token); } \
static void post(auto &&...args) { EventManager::post<event_name>(std::forward<decltype(args)>(args)...); } \
}
#define EVENT_DEF(event_name, ...) EVENT_DEF_IMPL(event_name, #event_name, true, __VA_ARGS__)
#define EVENT_DEF_NO_LOG(event_name, ...) EVENT_DEF_IMPL(event_name, #event_name, false, __VA_ARGS__)
@@ -58,6 +59,10 @@ namespace hex {
return m_hash == other.m_hash;
}
constexpr auto operator<=>(const EventId &other) const {
return m_hash <=> other.m_hash;
}
private:
u32 m_hash;
};
@@ -73,11 +78,12 @@ namespace hex {
explicit Event(Callback func) noexcept : m_func(std::move(func)) { }
void operator()(std::string_view eventName, Params... params) const {
template<typename E>
void call(Params... params) const {
try {
m_func(params...);
} catch (const std::exception &e) {
log::error("An exception occurred while handling event {}: {}", eventName, e.what());
log::error("An exception occurred while handling event {}: {}", wolv::type::getTypeName<E>(), e.what());
throw;
}
}
@@ -98,7 +104,7 @@ namespace hex {
*/
class EventManager {
public:
using EventList = std::list<std::pair<impl::EventId, std::unique_ptr<impl::EventBase>>>;
using EventList = std::multimap<impl::EventId, std::unique_ptr<impl::EventBase>>;
/**
* @brief Subscribes to an event
@@ -111,7 +117,7 @@ namespace hex {
std::scoped_lock lock(getEventMutex());
auto &events = getEvents();
return events.insert(events.end(), std::make_pair(E::Id, std::make_unique<E>(function)));
return events.insert({ E::Id, std::make_unique<E>(function) });
}
/**
@@ -124,15 +130,9 @@ namespace hex {
static void subscribe(void *token, typename E::Callback function) {
std::scoped_lock lock(getEventMutex());
if (getTokenStore().contains(token)) {
auto&& [begin, end] = getTokenStore().equal_range(token);
const auto eventRegistered = std::any_of(begin, end, [&](auto &item) {
return item.second->first == E::Id;
});
if (eventRegistered) {
log::fatal("The token '{}' has already registered the same event ('{}')", token, wolv::type::getTypeName<E>());
return;
}
if (isAlreadyRegistered(token, E::Id)) {
log::fatal("The token '{}' has already registered the same event ('{}')", token, wolv::type::getTypeName<E>());
return;
}
getTokenStore().insert({ token, subscribe<E>(function) });
@@ -157,16 +157,7 @@ namespace hex {
static void unsubscribe(void *token) noexcept {
std::scoped_lock lock(getEventMutex());
auto &tokenStore = getTokenStore();
auto iter = std::find_if(tokenStore.begin(), tokenStore.end(), [&](auto &item) {
return item.first == token && item.second->first == E::Id;
});
if (iter != tokenStore.end()) {
getEvents().remove(*iter->second);
tokenStore.erase(iter);
}
unsubscribe(token, E::Id);
}
/**
@@ -178,14 +169,14 @@ namespace hex {
static void post(auto && ...args) {
std::scoped_lock lock(getEventMutex());
for (const auto &[id, event] : getEvents()) {
if (id == E::Id) {
(*static_cast<E *const>(event.get()))(wolv::type::getTypeName<E>(), std::forward<decltype(args)>(args)...);
}
auto [begin, end] = getEvents().equal_range(E::Id);
for (auto it = begin; it != end; ++it) {
const auto &[id, event] = *it;
(*static_cast<E *const>(event.get())).template call<E>(std::forward<decltype(args)>(args)...);
}
#if defined (DEBUG)
if (E::ShouldLog)
if constexpr (E::ShouldLog)
log::debug("Event posted: '{}'", wolv::type::getTypeName<E>());
#endif
}
@@ -204,6 +195,9 @@ namespace hex {
static std::multimap<void *, EventList::iterator>& getTokenStore();
static EventList& getEvents();
static std::recursive_mutex& getEventMutex();
static bool isAlreadyRegistered(void *token, impl::EventId id);
static void unsubscribe(void *token, impl::EventId id);
};
/* Default Events */
@@ -221,7 +215,9 @@ namespace hex {
EVENT_DEF(EventAbnormalTermination, int);
EVENT_DEF(EventThemeChanged);
EVENT_DEF(EventOSThemeChanged);
EVENT_DEF(EventDPIChanged, float, float);
EVENT_DEF(EventWindowFocused, bool);
EVENT_DEF(EventImHexUpdated, SemanticVersion, SemanticVersion);
/**
* @brief Called when the provider is created.
@@ -247,7 +243,12 @@ namespace hex {
EVENT_DEF(EventWindowInitialized);
EVENT_DEF(EventWindowDeinitializing, GLFWwindow *);
EVENT_DEF(EventBookmarkCreated, ImHexApi::Bookmarks::Entry&);
EVENT_DEF(EventPatchCreated, u64, u8, u8);
/**
* @brief Called upon creation of an IPS patch.
* As for now, the event only serves a purpose for the achievement unlock.
*/
EVENT_DEF(EventPatchCreated, const u8*, u64, const PatchKind);
EVENT_DEF(EventPatternEvaluating);
EVENT_DEF(EventPatternExecuted, const std::string&);
EVENT_DEF(EventPatternEditorChanged, const std::string&);
@@ -265,6 +266,7 @@ namespace hex {
EVENT_DEF(EventProviderDataModified, prv::Provider *, u64, u64, const u8*);
EVENT_DEF(EventProviderDataInserted, prv::Provider *, u64, u64);
EVENT_DEF(EventProviderDataRemoved, prv::Provider *, u64, u64);
EVENT_DEF(EventProviderDirtied, prv::Provider *);
/**
* @brief Called when a project has been loaded
@@ -274,6 +276,7 @@ namespace hex {
EVENT_DEF_NO_LOG(EventFrameBegin);
EVENT_DEF_NO_LOG(EventFrameEnd);
EVENT_DEF_NO_LOG(EventSetTaskBarIconState, u32, u32, u32);
EVENT_DEF_NO_LOG(EventImGuiElementRendered, ImGuiID, const std::array<float, 4>&);
EVENT_DEF(RequestAddInitTask, std::string, bool, std::function<bool()>);
EVENT_DEF(RequestAddExitTask, std::string, std::function<bool()>);

View File

@@ -2,6 +2,7 @@
#include <hex.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/helpers/semantic_version.hpp>
#include <functional>
#include <optional>
@@ -75,7 +76,7 @@ namespace hex {
namespace impl {
using HighlightingFunction = std::function<std::optional<color_t>(u64, const u8*, size_t, bool)>;
using HoveringFunction = std::function<bool(const prv::Provider *, u64, const u8*, size_t)>;
using HoveringFunction = std::function<std::set<Region>(const prv::Provider *, u64, size_t)>;
const std::map<u32, Highlighting>& getBackgroundHighlights();
const std::map<u32, HighlightingFunction>& getBackgroundHighlightingFunctions();
@@ -293,7 +294,7 @@ namespace hex {
namespace impl {
void resetClosingProvider();
const std::set<prv::Provider*>& getClosingProviders();
std::set<prv::Provider*> getClosingProviders();
}
@@ -434,6 +435,7 @@ namespace hex {
void setInitialWindowProperties(InitialWindowProperties properties);
void setGPUVendor(const std::string &vendor);
void setGLRenderer(const std::string &renderer);
void addInitArgument(const std::string &key, const std::string &value = { });
@@ -573,6 +575,12 @@ namespace hex {
*/
const std::string& getGPUVendor();
/**
* @brief Gets the current GPU vendor
* @return The current GPU vendor
*/
const std::string& getGLRenderer();
/**
* @brief Checks if ImHex is running in portable mode
* @return Whether ImHex is running in portable mode
@@ -611,7 +619,7 @@ namespace hex {
* @brief Gets the current ImHex version
* @return ImHex version
*/
std::string getImHexVersion(bool withBuildType = true);
SemanticVersion getImHexVersion();
/**
* @brief Gets the current git commit hash
@@ -632,6 +640,12 @@ namespace hex {
*/
bool isDebugBuild();
/**
* @brief Checks if this version of ImHex is a nightly build
* @return True if this version is a nightly, false if it's a release
*/
bool isNightlyBuild();
enum class UpdateType {
Stable,
Nightly
@@ -682,6 +696,13 @@ namespace hex {
*/
void* getLibImHexModuleHandle();
/**
* Adds a new migration routine that will be executed when upgrading from a lower version than specified in migrationVersion
* @param migrationVersion Upgrade point version
* @param function Function to run
*/
void addMigrationRoutine(SemanticVersion migrationVersion, std::function<void()> function);
}
/**

View File

@@ -1,11 +1,14 @@
#pragma once
#include <hex.hpp>
#include <map>
#include <string>
#include <string_view>
#include <vector>
#include <fmt/format.h>
#include <fmt/core.h>
#include <wolv/types/static_string.hpp>
namespace hex {
@@ -22,8 +25,10 @@ namespace hex {
};
namespace impl {
void setFallbackLanguage(const std::string &language);
void resetLanguageStrings();
}
void loadLanguage(const std::string &language);
@@ -32,14 +37,18 @@ namespace hex {
[[nodiscard]] const std::map<std::string, std::string> &getSupportedLanguages();
[[nodiscard]] const std::string &getFallbackLanguage();
[[nodiscard]] const std::string &getSelectedLanguage();
}
struct UnlocalizedString;
class LangConst;
class Lang {
public:
explicit Lang(const char *unlocalizedString);
explicit Lang(const std::string &unlocalizedString);
explicit(false) Lang(const LangConst &localizedString);
explicit Lang(const UnlocalizedString &unlocalizedString);
explicit Lang(std::string_view unlocalizedString);
@@ -47,30 +56,54 @@ namespace hex {
[[nodiscard]] operator std::string_view() const;
[[nodiscard]] operator const char *() const;
[[nodiscard]] const std::string &get() const;
const char* get() const;
private:
std::size_t m_entryHash;
std::string m_unlocalizedString;
};
[[nodiscard]] std::string operator+(const std::string &&left, const Lang &&right);
[[nodiscard]] std::string operator+(const Lang &&left, const std::string &&right);
[[nodiscard]] std::string operator+(const std::string_view &&left, const Lang &&right);
[[nodiscard]] std::string operator+(const Lang &&left, const std::string_view &&right);
[[nodiscard]] std::string operator+(const char *left, const Lang &&right);
[[nodiscard]] std::string operator+(const Lang &&left, const char *right);
[[nodiscard]] std::string operator+(const Lang &&left, const Lang &&right);
class LangConst {
public:
[[nodiscard]] operator std::string() const;
[[nodiscard]] operator std::string_view() const;
[[nodiscard]] operator const char *() const;
[[nodiscard]] inline Lang operator""_lang(const char *string, size_t) {
return Lang(string);
}
const char* get() const;
constexpr static size_t hash(std::string_view string) {
constexpr u64 p = 131;
constexpr u64 m = std::numeric_limits<std::uint32_t>::max() - 4;
u64 total = 0;
u64 currentMultiplier = 1;
for (char c : string) {
total = (total + currentMultiplier * c) % m;
currentMultiplier = (currentMultiplier * p) % m;
}
return total;
}
private:
constexpr explicit LangConst(std::size_t hash, const char *unlocalizedString) : m_entryHash(hash), m_unlocalizedString(unlocalizedString) {}
template<wolv::type::StaticString>
friend consteval LangConst operator""_lang();
friend class Lang;
private:
std::size_t m_entryHash;
const char *m_unlocalizedString = nullptr;
};
struct UnlocalizedString {
public:
UnlocalizedString() = default;
UnlocalizedString(auto && arg) : m_unlocalizedString(std::forward<decltype(arg)>(arg)) {
static_assert(!std::same_as<std::remove_cvref_t<decltype(arg)>, Lang>, "Expected a unlocalized name, got a localized one!");
template<typename T>
UnlocalizedString(T &&arg) : m_unlocalizedString(std::forward<T>(arg)) {
static_assert(!std::same_as<std::remove_cvref_t<T>, Lang>, "Expected a unlocalized name, got a localized one!");
}
[[nodiscard]] operator std::string() const {
@@ -102,12 +135,17 @@ namespace hex {
std::string m_unlocalizedString;
};
}
template<>
struct fmt::formatter<hex::Lang> : fmt::formatter<std::string_view> {
template<typename FormatContext>
auto format(const hex::Lang &entry, FormatContext &ctx) {
return fmt::formatter<std::string_view>::format(entry.get(), ctx);
template<wolv::type::StaticString String>
[[nodiscard]] consteval LangConst operator""_lang() {
return LangConst(LangConst::hash(String.value.data()), String.value.data());
}
};
// {fmt} formatter for hex::Lang and hex::LangConst
inline auto format_as(const hex::Lang &entry) {
return entry.get();
}
inline auto format_as(const hex::LangConst &entry) {
return entry.get();
}
}

View File

@@ -17,7 +17,7 @@ namespace hex {
class View;
enum class Keys {
enum class Keys : u32 {
Space = GLFW_KEY_SPACE,
Apostrophe = GLFW_KEY_APOSTROPHE,
Comma = GLFW_KEY_COMMA,
@@ -138,6 +138,7 @@ namespace hex {
constexpr Key() = default;
constexpr Key(Keys key) : m_key(static_cast<u32>(key)) { }
bool operator==(const Key &) const = default;
auto operator<=>(const Key &) const = default;
[[nodiscard]] constexpr u32 getKeyCode() const { return m_key; }
@@ -152,224 +153,31 @@ namespace hex {
constexpr static auto SUPER = Key(static_cast<Keys>(0x0800'0000));
constexpr static auto CurrentView = Key(static_cast<Keys>(0x1000'0000));
constexpr static auto AllowWhileTyping = Key(static_cast<Keys>(0x2000'0000));
#if defined (OS_MACOS)
constexpr static auto CTRLCMD = SUPER;
#else
constexpr static auto CTRLCMD = CTRL;
#endif
constexpr static auto CTRLCMD = Key(static_cast<Keys>(0x4000'0000));
class Shortcut {
public:
Shortcut() = default;
Shortcut(Keys key) : m_keys({ key }) { }
explicit Shortcut(std::set<Key> keys) : m_keys(std::move(keys)) { }
Shortcut(Keys key);
explicit Shortcut(std::set<Key> keys);
Shortcut(const Shortcut &other) = default;
Shortcut(Shortcut &&) noexcept = default;
Shortcut& operator=(const Shortcut &other) = default;
constexpr static auto None = Keys(0);
Shortcut& operator=(const Shortcut &other) = default;
Shortcut& operator=(Shortcut &&) noexcept = default;
constexpr static inline auto None = Keys(0);
Shortcut operator+(const Key &other) const;
Shortcut &operator+=(const Key &other);
bool operator<(const Shortcut &other) const;
bool operator==(const Shortcut &other) const;
Shortcut operator+(const Key &other) const {
Shortcut result = *this;
result.m_keys.insert(other);
return result;
}
Shortcut &operator+=(const Key &other) {
m_keys.insert(other);
return *this;
}
bool operator<(const Shortcut &other) const {
return m_keys < other.m_keys;
}
bool operator==(const Shortcut &other) const {
auto thisKeys = m_keys;
auto otherKeys = other.m_keys;
thisKeys.erase(CurrentView);
thisKeys.erase(AllowWhileTyping);
otherKeys.erase(CurrentView);
otherKeys.erase(AllowWhileTyping);
return thisKeys == otherKeys;
}
bool isLocal() const {
return m_keys.contains(CurrentView);
}
std::string toString() const {
std::string result;
#if defined(OS_MACOS)
constexpr static auto CTRL_NAME = "CTRL";
constexpr static auto ALT_NAME = "OPT";
constexpr static auto SHIFT_NAME = "SHIFT";
constexpr static auto SUPER_NAME = "CMD";
#else
constexpr static auto CTRL_NAME = "CTRL";
constexpr static auto ALT_NAME = "ALT";
constexpr static auto SHIFT_NAME = "SHIFT";
constexpr static auto SUPER_NAME = "SUPER";
#endif
constexpr static auto Concatination = " + ";
auto keys = m_keys;
if (keys.erase(CTRL) > 0) {
result += CTRL_NAME;
result += Concatination;
}
if (keys.erase(ALT) > 0) {
result += ALT_NAME;
result += Concatination;
}
if (keys.erase(SHIFT) > 0) {
result += SHIFT_NAME;
result += Concatination;
}
if (keys.erase(SUPER) > 0) {
result += SUPER_NAME;
result += Concatination;
}
keys.erase(CurrentView);
for (const auto &key : keys) {
switch (Keys(key.getKeyCode())) {
case Keys::Space: result += "SPACE"; break;
case Keys::Apostrophe: result += "'"; break;
case Keys::Comma: result += ","; break;
case Keys::Minus: result += "-"; break;
case Keys::Period: result += "."; break;
case Keys::Slash: result += "/"; break;
case Keys::Num0: result += "0"; break;
case Keys::Num1: result += "1"; break;
case Keys::Num2: result += "2"; break;
case Keys::Num3: result += "3"; break;
case Keys::Num4: result += "4"; break;
case Keys::Num5: result += "5"; break;
case Keys::Num6: result += "6"; break;
case Keys::Num7: result += "7"; break;
case Keys::Num8: result += "8"; break;
case Keys::Num9: result += "9"; break;
case Keys::Semicolon: result += ";"; break;
case Keys::Equals: result += "="; break;
case Keys::A: result += "A"; break;
case Keys::B: result += "B"; break;
case Keys::C: result += "C"; break;
case Keys::D: result += "D"; break;
case Keys::E: result += "E"; break;
case Keys::F: result += "F"; break;
case Keys::G: result += "G"; break;
case Keys::H: result += "H"; break;
case Keys::I: result += "I"; break;
case Keys::J: result += "J"; break;
case Keys::K: result += "K"; break;
case Keys::L: result += "L"; break;
case Keys::M: result += "M"; break;
case Keys::N: result += "N"; break;
case Keys::O: result += "O"; break;
case Keys::P: result += "P"; break;
case Keys::Q: result += "Q"; break;
case Keys::R: result += "R"; break;
case Keys::S: result += "S"; break;
case Keys::T: result += "T"; break;
case Keys::U: result += "U"; break;
case Keys::V: result += "V"; break;
case Keys::W: result += "W"; break;
case Keys::X: result += "X"; break;
case Keys::Y: result += "Y"; break;
case Keys::Z: result += "Z"; break;
case Keys::LeftBracket: result += "["; break;
case Keys::Backslash: result += "\\"; break;
case Keys::RightBracket: result += "]"; break;
case Keys::GraveAccent: result += "`"; break;
case Keys::World1: result += "WORLD1"; break;
case Keys::World2: result += "WORLD2"; break;
case Keys::Escape: result += "ESC"; break;
case Keys::Enter: result += "ENTER"; break;
case Keys::Tab: result += "TAB"; break;
case Keys::Backspace: result += "BACKSPACE"; break;
case Keys::Insert: result += "INSERT"; break;
case Keys::Delete: result += "DELETE"; break;
case Keys::Right: result += "RIGHT"; break;
case Keys::Left: result += "LEFT"; break;
case Keys::Down: result += "DOWN"; break;
case Keys::Up: result += "UP"; break;
case Keys::PageUp: result += "PAGEUP"; break;
case Keys::PageDown: result += "PAGEDOWN"; break;
case Keys::Home: result += "HOME"; break;
case Keys::End: result += "END"; break;
case Keys::CapsLock: result += "CAPSLOCK"; break;
case Keys::ScrollLock: result += "SCROLLLOCK"; break;
case Keys::NumLock: result += "NUMLOCK"; break;
case Keys::PrintScreen: result += "PRINTSCREEN"; break;
case Keys::Pause: result += "PAUSE"; break;
case Keys::F1: result += "F1"; break;
case Keys::F2: result += "F2"; break;
case Keys::F3: result += "F3"; break;
case Keys::F4: result += "F4"; break;
case Keys::F5: result += "F5"; break;
case Keys::F6: result += "F6"; break;
case Keys::F7: result += "F7"; break;
case Keys::F8: result += "F8"; break;
case Keys::F9: result += "F9"; break;
case Keys::F10: result += "F10"; break;
case Keys::F11: result += "F11"; break;
case Keys::F12: result += "F12"; break;
case Keys::F13: result += "F13"; break;
case Keys::F14: result += "F14"; break;
case Keys::F15: result += "F15"; break;
case Keys::F16: result += "F16"; break;
case Keys::F17: result += "F17"; break;
case Keys::F18: result += "F18"; break;
case Keys::F19: result += "F19"; break;
case Keys::F20: result += "F20"; break;
case Keys::F21: result += "F21"; break;
case Keys::F22: result += "F22"; break;
case Keys::F23: result += "F23"; break;
case Keys::F24: result += "F24"; break;
case Keys::F25: result += "F25"; break;
case Keys::KeyPad0: result += "KP0"; break;
case Keys::KeyPad1: result += "KP1"; break;
case Keys::KeyPad2: result += "KP2"; break;
case Keys::KeyPad3: result += "KP3"; break;
case Keys::KeyPad4: result += "KP4"; break;
case Keys::KeyPad5: result += "KP5"; break;
case Keys::KeyPad6: result += "KP6"; break;
case Keys::KeyPad7: result += "KP7"; break;
case Keys::KeyPad8: result += "KP8"; break;
case Keys::KeyPad9: result += "KP9"; break;
case Keys::KeyPadDecimal: result += "KPDECIMAL"; break;
case Keys::KeyPadDivide: result += "KPDIVIDE"; break;
case Keys::KeyPadMultiply: result += "KPMULTIPLY"; break;
case Keys::KeyPadSubtract: result += "KPSUBTRACT"; break;
case Keys::KeyPadAdd: result += "KPADD"; break;
case Keys::KeyPadEnter: result += "KPENTER"; break;
case Keys::KeyPadEqual: result += "KPEQUAL"; break;
case Keys::Menu: result += "MENU"; break;
default:
continue;
}
result += " + ";
}
if (result.ends_with(" + "))
result = result.substr(0, result.size() - 3);
return result;
}
const std::set<Key>& getKeys() const { return m_keys; }
bool isLocal() const;
std::string toString() const;
const std::set<Key>& getKeys() const;
bool has(Key key) const;
bool matches(const Shortcut &other) const;
private:
friend Shortcut operator+(const Key &lhs, const Key &rhs);
@@ -377,12 +185,7 @@ namespace hex {
std::set<Key> m_keys;
};
inline Shortcut operator+(const Key &lhs, const Key &rhs) {
Shortcut result;
result.m_keys = { lhs, rhs };
return result;
}
Shortcut operator+(const Key &lhs, const Key &rhs);
/**
* @brief The ShortcutManager handles global and view-specific shortcuts.
@@ -393,7 +196,7 @@ namespace hex {
using Callback = std::function<void()>;
struct ShortcutEntry {
Shortcut shortcut;
UnlocalizedString unlocalizedName;
std::vector<UnlocalizedString> unlocalizedName;
Callback callback;
};
@@ -403,6 +206,7 @@ namespace hex {
* @param unlocalizedName The unlocalized name of the shortcut
* @param callback The callback to call when the shortcut is triggered.
*/
static void addGlobalShortcut(const Shortcut &shortcut, const std::vector<UnlocalizedString> &unlocalizedName, const Callback &callback);
static void addGlobalShortcut(const Shortcut &shortcut, const UnlocalizedString &unlocalizedName, const Callback &callback);
/**
@@ -412,6 +216,7 @@ namespace hex {
* @param unlocalizedName The unlocalized name of the shortcut
* @param callback The callback to call when the shortcut is triggered.
*/
static void addShortcut(View *view, const Shortcut &shortcut, const std::vector<UnlocalizedString> &unlocalizedName, const Callback &callback);
static void addShortcut(View *view, const Shortcut &shortcut, const UnlocalizedString &unlocalizedName, const Callback &callback);
@@ -445,12 +250,14 @@ namespace hex {
static void resumeShortcuts();
static void pauseShortcuts();
static void enableMacOSMode();
[[nodiscard]] static std::optional<Shortcut> getPreviousShortcut();
[[nodiscard]] static std::vector<ShortcutEntry> getGlobalShortcuts();
[[nodiscard]] static std::vector<ShortcutEntry> getViewShortcuts(const View *view);
[[nodiscard]] static bool updateShortcut(const Shortcut &oldShortcut, const Shortcut &newShortcut, View *view = nullptr);
[[nodiscard]] static bool updateShortcut(const Shortcut &oldShortcut, Shortcut newShortcut, View *view = nullptr);
};
}

View File

@@ -22,7 +22,7 @@ namespace hex {
class Task {
public:
Task() = default;
Task(UnlocalizedString unlocalizedName, u64 maxValue, bool background, std::function<void(Task &)> function);
Task(const UnlocalizedString &unlocalizedName, u64 maxValue, bool background, std::function<void(Task &)> function);
Task(const Task&) = delete;
Task(Task &&other) noexcept;
@@ -130,20 +130,37 @@ namespace hex {
/**
* @brief Creates a new asynchronous task that gets displayed in the Task Manager in the footer
* @param name Name of the task
* @param unlocalizedName Name of the task
* @param maxValue Maximum value of the task
* @param function Function to be executed
* @return A TaskHolder holding a weak reference to the task
*/
static TaskHolder createTask(std::string name, u64 maxValue, std::function<void(Task &)> function);
static TaskHolder createTask(const UnlocalizedString &unlocalizedName, u64 maxValue, std::function<void(Task &)> function);
/**
* @brief Creates a new asynchronous task that gets displayed in the Task Manager in the footer
* @param unlocalizedName Name of the task
* @param maxValue Maximum value of the task
* @param function Function to be executed
* @return A TaskHolder holding a weak reference to the task
*/
static TaskHolder createTask(const UnlocalizedString &unlocalizedName, u64 maxValue, std::function<void()> function);
/**
* @brief Creates a new asynchronous task that does not get displayed in the Task Manager
* @param name Name of the task
* @param unlocalizedName Name of the task
* @param function Function to be executed
* @return A TaskHolder holding a weak reference to the task
*/
static TaskHolder createBackgroundTask(std::string name, std::function<void(Task &)> function);
static TaskHolder createBackgroundTask(const UnlocalizedString &unlocalizedName, std::function<void(Task &)> function);
/**
* @brief Creates a new asynchronous task that does not get displayed in the Task Manager
* @param unlocalizedName Name of the task
* @param function Function to be executed
* @return A TaskHolder holding a weak reference to the task
*/
static TaskHolder createBackgroundTask(const UnlocalizedString &unlocalizedName, std::function<void()> function);
/**
* @brief Creates a new synchronous task that will execute the given function at the start of the next frame
@@ -190,7 +207,7 @@ namespace hex {
static void runDeferredCalls();
private:
static TaskHolder createTask(std::string name, u64 maxValue, bool background, std::function<void(Task &)> function);
static TaskHolder createTask(const UnlocalizedString &unlocalizedName, u64 maxValue, bool background, std::function<void(Task &)> function);
};
}

View File

@@ -56,6 +56,7 @@ namespace hex {
*/
static void addStyleHandler(const std::string &name, const StyleMap &styleMap);
static void reapplyCurrentTheme();
static std::vector<std::string> getThemeNames();
static const std::string &getImageTheme();

View File

@@ -119,6 +119,8 @@ namespace hex {
decltype(m_steps)::iterator m_currentStep, m_latestStep;
};
static void init();
/**
* @brief Gets a list of all tutorials
* @return List of all tutorials
@@ -145,6 +147,10 @@ namespace hex {
*/
static void startTutorial(const UnlocalizedString &unlocalizedName);
static void startHelpHover();
static void addInteractiveHelpText(std::initializer_list<std::variant<Lang, std::string, int>> &&ids, UnlocalizedString unlocalizedString);
static void addInteractiveHelpLink(std::initializer_list<std::variant<Lang, std::string, int>> &&ids, std::string link);
/**
* @brief Draws the tutorial

View File

@@ -3,7 +3,6 @@
#include <hex.hpp>
#include <hex/api/localization_manager.hpp>
#include <hex/helpers/intrinsics.hpp>
#include <hex/data_processor/attribute.hpp>
#include <set>
@@ -12,6 +11,7 @@
#include <nlohmann/json_fwd.hpp>
#include <imgui.h>
#include <hex/providers/provider_data.hpp>
namespace hex::prv {
class Provider;
@@ -42,11 +42,12 @@ namespace hex::dp {
m_overlay = overlay;
}
virtual void drawNode() { }
void draw();
virtual void process() = 0;
virtual void reset() { }
virtual void store(nlohmann::json &j) const { hex::unused(j); }
virtual void load(const nlohmann::json &j) { hex::unused(j); }
virtual void store(nlohmann::json &j) const { std::ignore = j; }
virtual void load(const nlohmann::json &j) { std::ignore = j; }
struct NodeError {
Node *node;
@@ -80,6 +81,11 @@ namespace hex::dp {
void setIntegerOnOutput(u32 index, i128 integer);
void setFloatOnOutput(u32 index, double floatingPoint);
static void interrupt();
protected:
virtual void drawNode() { }
private:
int m_id;
UnlocalizedString m_unlocalizedTitle, m_unlocalizedName;
@@ -90,45 +96,16 @@ namespace hex::dp {
static int s_idCounter;
Attribute& getAttribute(u32 index) {
if (index >= this->getAttributes().size())
throw std::runtime_error("Attribute index out of bounds!");
return this->getAttributes()[index];
}
Attribute *getConnectedInputAttribute(u32 index) {
const auto &connectedAttribute = this->getAttribute(index).getConnectedAttributes();
if (connectedAttribute.empty())
return nullptr;
return connectedAttribute.begin()->second;
}
void markInputProcessed(u32 index) {
const auto &[iter, inserted] = m_processedInputs.insert(index);
if (!inserted)
throwNodeError("Recursion detected!");
}
void unmarkInputProcessed(u32 index) {
m_processedInputs.erase(index);
}
Attribute& getAttribute(u32 index);
Attribute *getConnectedInputAttribute(u32 index);
void markInputProcessed(u32 index);
void unmarkInputProcessed(u32 index);
protected:
[[noreturn]] void throwNodeError(const std::string &message) {
throw NodeError { this, message };
}
[[noreturn]] void throwNodeError(const std::string &message);
void setOverlayData(u64 address, const std::vector<u8> &data);
void setAttributes(std::vector<Attribute> attributes) {
m_attributes = std::move(attributes);
for (auto &attr : m_attributes)
attr.setParentNode(this);
}
void setAttributes(std::vector<Attribute> attributes);
};
}

View File

@@ -2,10 +2,15 @@
#include <hex.hpp>
#include <wolv/utils/expected.hpp>
#include <array>
#include <string>
#include <vector>
#define CRYPTO_ERROR_INVALID_KEY_LENGTH (-1)
#define CRYPTO_ERROR_INVALID_MODE (-2)
namespace hex::prv {
class Provider;
}
@@ -60,5 +65,5 @@ namespace hex::crypt {
Key256Bits = 2
};
std::vector<u8> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input);
wolv::util::Expected<std::vector<u8>, int> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input);
}

View File

@@ -0,0 +1,111 @@
#pragma once
#include <hex/helpers/fs.hpp>
#include <vector>
namespace hex::paths {
namespace impl {
class DefaultPath {
protected:
constexpr DefaultPath() = default;
virtual ~DefaultPath() = default;
public:
DefaultPath(const DefaultPath&) = delete;
DefaultPath(DefaultPath&&) = delete;
DefaultPath& operator=(const DefaultPath&) = delete;
DefaultPath& operator=(DefaultPath&&) = delete;
virtual std::vector<std::fs::path> all() const = 0;
virtual std::vector<std::fs::path> read() const;
virtual std::vector<std::fs::path> write() const;
};
class ConfigPath : public DefaultPath {
public:
explicit ConfigPath(std::fs::path postfix) : m_postfix(std::move(postfix)) {}
std::vector<std::fs::path> all() const override;
private:
std::fs::path m_postfix;
};
class DataPath : public DefaultPath {
public:
explicit DataPath(std::fs::path postfix) : m_postfix(std::move(postfix)) {}
std::vector<std::fs::path> all() const override;
std::vector<std::fs::path> write() const override;
private:
std::fs::path m_postfix;
};
class PluginPath : public DefaultPath {
public:
explicit PluginPath(std::fs::path postfix) : m_postfix(std::move(postfix)) {}
std::vector<std::fs::path> all() const override;
private:
std::fs::path m_postfix;
};
}
std::vector<std::fs::path> getDataPaths(bool includeSystemFolders);
std::vector<std::fs::path> getConfigPaths(bool includeSystemFolders);
const static inline impl::ConfigPath Config("config");
const static inline impl::ConfigPath Recent("recent");
const static inline impl::PluginPath Libraries("lib");
const static inline impl::PluginPath Plugins("plugins");
const static inline impl::DataPath Patterns("patterns");
const static inline impl::DataPath PatternsInclude("includes");
const static inline impl::DataPath Magic("magic");
const static inline impl::DataPath Yara("yara");
const static inline impl::DataPath YaraAdvancedAnalysis("yara/advanced_analysis");
const static inline impl::DataPath Backups("backups");
const static inline impl::DataPath Resources("resources");
const static inline impl::DataPath Constants("constants");
const static inline impl::DataPath Encodings("encodings");
const static inline impl::DataPath Logs("logs");
const static inline impl::DataPath Scripts("scripts");
const static inline impl::DataPath Inspectors("scripts/inspectors");
const static inline impl::DataPath Themes("themes");
const static inline impl::DataPath Nodes("scripts/nodes");
const static inline impl::DataPath Layouts("layouts");
const static inline impl::DataPath Workspaces("workspaces");
constexpr static inline std::array<const impl::DefaultPath*, 20> All = {
&Config,
&Recent,
&Libraries,
&Plugins,
&Patterns,
&PatternsInclude,
&Magic,
&Yara,
&YaraAdvancedAnalysis,
&Backups,
&Resources,
&Constants,
&Encodings,
&Logs,
&Scripts,
&Inspectors,
&Themes,
&Nodes,
&Layouts,
&Workspaces,
};
}

View File

@@ -1,7 +1,8 @@
#pragma once
#include <string_view>
#include <fmt/format.h>
#include <fmt/core.h>
#include <fmt/ranges.h>
namespace hex {

View File

@@ -1,7 +1,5 @@
#pragma once
#include <hex.hpp>
#include <string>
#include <vector>
#include <filesystem>
@@ -31,36 +29,7 @@ namespace hex::fs {
void openFolderExternal(const std::fs::path &dirPath);
void openFolderWithSelectionExternal(const std::fs::path &selectedFilePath);
enum class ImHexPath : u32 {
Patterns = 0,
PatternsInclude,
Magic,
Plugins,
Yara,
YaraAdvancedAnalysis,
Config,
Backups,
Resources,
Constants,
Encodings,
Logs,
Recent,
Scripts,
Inspectors,
Themes,
Libraries,
Nodes,
Layouts,
Workspaces,
END
};
bool isPathWritable(const std::fs::path &path);
std::vector<std::fs::path> getDefaultPaths(ImHexPath path, bool listNonExisting = false);
// Temporarily expose these for the migration function
std::vector<std::fs::path> getDataPaths();
std::vector<std::fs::path> appendPath(std::vector<std::fs::path> paths, const std::fs::path &folder);
}

View File

@@ -25,13 +25,16 @@
template<typename T>
std::future<HttpRequest::Result<T>> HttpRequest::uploadFile(const std::fs::path &path, const std::string &mimeName) {
hex::unused(path, mimeName);
std::ignore = path;
std::ignore = mimeName;
throw std::logic_error("Not implemented");
}
template<typename T>
std::future<HttpRequest::Result<T>> HttpRequest::uploadFile(std::vector<u8> data, const std::string &mimeName, const std::fs::path &fileName) {
hex::unused(data, mimeName, fileName);
std::ignore = data;
std::ignore = mimeName;
std::ignore = fileName;
throw std::logic_error("Not implemented");
}

View File

@@ -1,9 +0,0 @@
#pragma once
namespace hex {
void unused(auto && ... x) {
((void)x, ...);
}
}

View File

@@ -21,6 +21,11 @@ namespace hex {
MissingEOF
};
enum class PatchKind {
IPS,
IPS32
};
class Patches {
public:
Patches() = default;

View File

@@ -0,0 +1,36 @@
#pragma once
#include <hex.hpp>
#include <compare>
#include <string>
#include <vector>
namespace hex {
class SemanticVersion {
public:
SemanticVersion() = default;
SemanticVersion(std::string version);
SemanticVersion(std::string_view version);
SemanticVersion(const char *version);
std::strong_ordering operator<=>(const SemanticVersion &) const;
bool operator==(const SemanticVersion &other) const;
u32 major() const;
u32 minor() const;
u32 patch() const;
bool nightly() const;
const std::string& buildType() const;
bool isValid() const;
std::string get(bool withBuildType = true) const;
private:
std::vector<std::string> m_parts;
std::string m_buildType;
};
}

View File

@@ -29,7 +29,7 @@ namespace hex {
void close();
/**
* @brief get the error string explaining the error that occured when opening the file.
* @brief get the error string explaining the error that occurred when opening the file.
* This error is a combination of the tar error and the native file open error
*/
std::string getOpenErrorString() const;
@@ -59,4 +59,4 @@ namespace hex {
int m_fileOpenErrno = 0;
};
}
}

View File

@@ -4,6 +4,7 @@
#include <cstdint>
#include <concepts>
#include <type_traits>
using u8 = std::uint8_t;
using u16 = std::uint16_t;
@@ -61,6 +62,10 @@ namespace hex {
constexpr static Region Invalid() {
return { 0, 0 };
}
constexpr bool operator<(const Region &other) const {
return this->address < other.address;
}
};

View File

@@ -34,6 +34,29 @@ namespace hex {
class Provider;
}
template<typename T>
[[nodiscard]] std::vector<std::vector<T>> sampleChannels(const std::vector<T> &data, size_t count, size_t channels) {
if (channels == 0) return {};
size_t signalLength = std::max(1.0, double(data.size()) / channels);
size_t stride = std::max(1.0, double(signalLength) / count);
std::vector<std::vector<T>> result;
result.resize(channels);
for (size_t i = 0; i < channels; i++) {
result[i].reserve(count);
}
result.reserve(count);
for (size_t i = 0; i < data.size(); i += stride) {
for (size_t j = 0; j < channels; j++) {
result[j].push_back(data[i + j]);
}
}
return result;
}
template<typename T>
[[nodiscard]] std::vector<T> sampleData(const std::vector<T> &data, size_t count) {
size_t stride = std::max(1.0, double(data.size()) / count);
@@ -262,13 +285,13 @@ namespace hex {
[[nodiscard]] float float16ToFloat32(u16 float16);
[[nodiscard]] inline bool equalsIgnoreCase(const std::string &left, const std::string &right) {
[[nodiscard]] inline bool equalsIgnoreCase(std::string_view left, std::string_view right) {
return std::equal(left.begin(), left.end(), right.begin(), right.end(), [](char a, char b) {
return tolower(a) == tolower(b);
});
}
[[nodiscard]] inline bool containsIgnoreCase(const std::string &a, const std::string &b) {
[[nodiscard]] inline bool containsIgnoreCase(std::string_view a, std::string_view b) {
auto iter = std::search(a.begin(), a.end(), b.begin(), b.end(), [](char ch1, char ch2) {
return std::toupper(ch1) == std::toupper(ch2);
});
@@ -298,31 +321,7 @@ namespace hex {
[[nodiscard]] std::optional<std::string> getEnvironmentVariable(const std::string &env);
[[nodiscard]] inline std::string limitStringLength(const std::string &string, size_t maxLength) {
// If the string is shorter than the max length, return it as is
if (string.size() < maxLength)
return string;
// If the string is longer than the max length, find the last space before the max length
auto it = string.begin() + maxLength;
while (it != string.begin() && !std::isspace(*it)) --it;
// If there's no space before the max length, just cut the string
if (it == string.begin()) {
it = string.begin() + maxLength;
// Try to find a UTF-8 character boundary
while (it != string.begin() && (*it & 0x80) != 0x00) --it;
++it;
}
// If we still didn't find a valid boundary, just return the string as is
if (it == string.begin())
return string;
// Append
return std::string(string.begin(), it) + "";
}
[[nodiscard]] std::string limitStringLength(const std::string &string, size_t maxLength);
[[nodiscard]] std::optional<std::fs::path> getInitialFilePath();

View File

@@ -18,6 +18,7 @@
void macosHandleTitlebarDoubleClickGesture(GLFWwindow *window);
bool macosIsWindowBeingResizedByUser(GLFWwindow *window);
void macosMarkContentEdited(GLFWwindow *window, bool edited = true);
}
#endif

View File

@@ -37,21 +37,40 @@ void* PluginSubCommandsFunctionHelper<T>::getSubCommands() {
return nullptr;
}
[[maybe_unused]] static auto& getFeaturesImpl() {
static std::vector<hex::Feature> features;
return features;
}
#if defined (IMHEX_STATIC_LINK_PLUGINS)
#define IMHEX_PLUGIN_VISIBILITY_PREFIX static
#else
#define IMHEX_PLUGIN_VISIBILITY_PREFIX extern "C" [[gnu::visibility("default")]]
#endif
#define IMHEX_FEATURE_ENABLED(feature) WOLV_TOKEN_CONCAT(WOLV_TOKEN_CONCAT(WOLV_TOKEN_CONCAT(IMHEX_PLUGIN_, IMHEX_PLUGIN_NAME), _FEATURE_), feature)
#define IMHEX_DEFINE_PLUGIN_FEATURES() IMHEX_DEFINE_PLUGIN_FEATURES_IMPL()
#define IMHEX_DEFINE_PLUGIN_FEATURES_IMPL() \
template<> \
struct PluginFeatureFunctionHelper<PluginFunctionHelperInstantiation> { \
static void* getFeatures(); \
}; \
void* PluginFeatureFunctionHelper<PluginFunctionHelperInstantiation>::getFeatures() { \
return &getFeaturesImpl(); \
} \
static auto initFeatures = [] { getFeaturesImpl() = std::vector<hex::Feature>({ IMHEX_PLUGIN_FEATURES_CONTENT }); return 0; }()
#define IMHEX_PLUGIN_FEATURES ::getFeaturesImpl()
/**
* This macro is used to define all the required entry points for a plugin.
* Name, Author and Description will be displayed in the in the plugin list on the Welcome screen.
* Name, Author and Description will be displayed in the plugin list on the Welcome screen.
*/
#define IMHEX_PLUGIN_SETUP(name, author, description) IMHEX_PLUGIN_SETUP_IMPL(name, author, description)
#define IMHEX_LIBRARY_SETUP(name) IMHEX_LIBRARY_SETUP_IMPL(name)
#define IMHEX_LIBRARY_SETUP_IMPL(name) \
namespace { static struct EXIT_HANDLER { ~EXIT_HANDLER() { hex::log::debug("Unloaded library '{}'", name); } } HANDLER; } \
namespace { static struct EXIT_HANDLER { ~EXIT_HANDLER() { hex::log::info("Unloaded library '{}'", name); } } HANDLER; } \
IMHEX_PLUGIN_VISIBILITY_PREFIX void WOLV_TOKEN_CONCAT(initializeLibrary_, IMHEX_PLUGIN_NAME)(); \
IMHEX_PLUGIN_VISIBILITY_PREFIX const char *WOLV_TOKEN_CONCAT(getLibraryName_, IMHEX_PLUGIN_NAME)() { return name; } \
IMHEX_PLUGIN_VISIBILITY_PREFIX void WOLV_TOKEN_CONCAT(setImGuiContext_, IMHEX_PLUGIN_NAME)(ImGuiContext *ctx) { \
@@ -85,6 +104,7 @@ void* PluginSubCommandsFunctionHelper<T>::getSubCommands() {
ImGui::SetCurrentContext(ctx); \
GImGui = ctx; \
} \
IMHEX_DEFINE_PLUGIN_FEATURES(); \
IMHEX_PLUGIN_VISIBILITY_PREFIX void* getFeatures() { \
return PluginFeatureFunctionHelper<PluginFunctionHelperInstantiation>::getFeatures(); \
} \
@@ -129,18 +149,3 @@ void* PluginSubCommandsFunctionHelper<T>::getSubCommands() {
return &g_subCommands; \
} \
std::vector<hex::SubCommand> g_subCommands
#define IMHEX_FEATURE_ENABLED(feature) WOLV_TOKEN_CONCAT(WOLV_TOKEN_CONCAT(WOLV_TOKEN_CONCAT(IMHEX_PLUGIN_, IMHEX_PLUGIN_NAME), _FEATURE_), feature)
#define IMHEX_DEFINE_PLUGIN_FEATURES() IMHEX_DEFINE_PLUGIN_FEATURES_IMPL()
#define IMHEX_DEFINE_PLUGIN_FEATURES_IMPL() \
extern std::vector<hex::Feature> g_features; \
template<> \
struct PluginFeatureFunctionHelper<PluginFunctionHelperInstantiation> { \
static void* getFeatures(); \
}; \
void* PluginFeatureFunctionHelper<PluginFunctionHelperInstantiation>::getFeatures() { \
return &g_features; \
} \
std::vector<hex::Feature> g_features
#define IMHEX_PLUGIN_FEATURES g_features

View File

@@ -165,7 +165,7 @@ namespace hex::prv {
void insert(u64 offset, u64 size);
void remove(u64 offset, u64 size);
virtual void resizeRaw(u64 newSize) { hex::unused(newSize); }
virtual void resizeRaw(u64 newSize) { std::ignore = newSize; }
virtual void insertRaw(u64 offset, u64 size);
virtual void removeRaw(u64 offset, u64 size);

View File

@@ -97,32 +97,30 @@ namespace ImGuiExt {
Texture& operator=(Texture&& other) noexcept;
[[nodiscard]] constexpr bool isValid() const noexcept {
return m_textureId != nullptr;
return m_textureId != 0;
}
[[nodiscard]] operator ImTextureID() const noexcept {
return m_textureId;
}
[[nodiscard]] operator intptr_t() const noexcept {
return reinterpret_cast<intptr_t>(m_textureId);
}
[[nodiscard]] auto getSize() const noexcept {
[[nodiscard]] ImVec2 getSize() const noexcept {
return ImVec2(m_width, m_height);
}
[[nodiscard]] constexpr auto getAspectRatio() const noexcept {
[[nodiscard]] constexpr float getAspectRatio() const noexcept {
if (m_height == 0) return 1.0F;
return float(m_width) / float(m_height);
}
private:
ImTextureID m_textureId = nullptr;
ImTextureID m_textureId = 0;
int m_width = 0, m_height = 0;
};
float GetTextWrapPos();
int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data);
bool IconHyperlink(const char *icon, const char *label, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0);
@@ -135,6 +133,8 @@ namespace ImGuiExt {
void UnderlinedText(const char *label, ImColor color = ImGui::GetStyleColorVec4(ImGuiCol_Text), const ImVec2 &size_arg = ImVec2(0, 0));
void UnderwavedText(const char *label, ImColor textColor = ImGui::GetStyleColorVec4(ImGuiCol_Text), ImColor lineColor = ImGui::GetStyleColorVec4(ImGuiCol_Text), const ImVec2 &size_arg = ImVec2(0, 0));
void TextSpinner(const char *label);
void Header(const char *label, bool firstEntry = false);
@@ -186,7 +186,12 @@ namespace ImGuiExt {
void SmallProgressBar(float fraction, float yOffset = 0.0F);
inline void TextFormatted(std::string_view fmt, auto &&...args) {
ImGui::TextUnformatted(hex::format(fmt, std::forward<decltype(args)>(args)...).c_str());
if constexpr (sizeof...(args) == 0) {
ImGui::TextUnformatted(fmt.data(), fmt.data() + fmt.size());
} else {
const auto string = hex::format(fmt, std::forward<decltype(args)>(args)...);
ImGui::TextUnformatted(string.c_str(), string.c_str() + string.size());
}
}
inline void TextFormattedSelectable(std::string_view fmt, auto &&...args) {
@@ -208,15 +213,24 @@ namespace ImGuiExt {
}
inline void TextFormattedColored(ImColor color, std::string_view fmt, auto &&...args) {
ImGui::TextColored(color, "%s", hex::format(fmt, std::forward<decltype(args)>(args)...).c_str());
ImGui::PushStyleColor(ImGuiCol_Text, color.Value);
ImGuiExt::TextFormatted(fmt, std::forward<decltype(args)>(args)...);
ImGui::PopStyleColor();
}
inline void TextFormattedDisabled(std::string_view fmt, auto &&...args) {
ImGui::TextDisabled("%s", hex::format(fmt, std::forward<decltype(args)>(args)...).c_str());
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_TextDisabled]);
ImGuiExt::TextFormatted(fmt, std::forward<decltype(args)>(args)...);
ImGui::PopStyleColor();
}
inline void TextFormattedWrapped(std::string_view fmt, auto &&...args) {
ImGui::TextWrapped("%s", hex::format(fmt, std::forward<decltype(args)>(args)...).c_str());
const bool need_backup = ImGuiExt::GetTextWrapPos() < 0.0F; // Keep existing wrap position if one is already set
if (need_backup)
ImGui::PushTextWrapPos(0.0F);
ImGuiExt::TextFormatted(fmt, std::forward<decltype(args)>(args)...);
if (need_backup)
ImGui::PopTextWrapPos();
}
inline void TextFormattedWrappedSelectable(std::string_view fmt, auto &&...args) {
@@ -268,6 +282,7 @@ namespace ImGuiExt {
}
bool InputTextIcon(const char* label, const char *icon, std::string &buffer, ImGuiInputTextFlags flags = ImGuiInputTextFlags_None);
bool InputTextIconHint(const char* label, const char *icon, const char *hint, std::string &buffer, ImGuiInputTextFlags flags = ImGuiInputTextFlags_None);
bool InputScalarCallback(const char* label, ImGuiDataType data_type, void* p_data, const char* format, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data);
@@ -281,12 +296,12 @@ namespace ImGuiExt {
bool DimmedIconToggle(const char *icon, bool *v);
bool DimmedIconToggle(const char *iconOn, const char *iconOff, bool *v);
void TextOverlay(const char *text, ImVec2 pos);
void TextOverlay(const char *text, ImVec2 pos, float maxWidth = -1);
bool BeginBox();
void EndBox();
void BeginSubWindow(const char *label, ImVec2 size = ImVec2(0, 0), ImGuiChildFlags flags = ImGuiChildFlags_None);
bool BeginSubWindow(const char *label, bool *collapsed = nullptr, ImVec2 size = ImVec2(0, 0), ImGuiChildFlags flags = ImGuiChildFlags_None);
void EndSubWindow();
void ConfirmButtons(const char *textLeft, const char *textRight, const auto &leftButtonCallback, const auto &rightButtonCallback) {

View File

@@ -158,6 +158,7 @@ namespace hex {
explicit Floating(UnlocalizedString unlocalizedName) : Window(std::move(unlocalizedName), "") {}
[[nodiscard]] ImGuiWindowFlags getWindowFlags() const override { return ImGuiWindowFlags_NoDocking; }
[[nodiscard]] bool shouldStoreWindowState() const override { return false; }
};
/**

View File

@@ -2,9 +2,14 @@
#include <hex/api/event_manager.hpp>
#include <hex/helpers/auto_reset.hpp>
#include <hex/helpers/default_paths.hpp>
#include <nlohmann/json.hpp>
#if defined(OS_WEB)
#include <emscripten.h>
#endif
namespace hex {
static AutoReset<std::unordered_map<std::string, std::unordered_map<std::string, std::unique_ptr<Achievement>>>> s_achievements;
@@ -195,9 +200,12 @@ namespace hex {
constexpr static auto AchievementsFile = "achievements.json";
bool AchievementManager::s_initialized = false;
void AchievementManager::loadProgress() {
for (const auto &directory : fs::getDefaultPaths(fs::ImHexPath::Config)) {
if (s_initialized)
return;
for (const auto &directory : paths::Config.read()) {
auto path = directory / AchievementsFile;
if (!wolv::io::fs::exists(path)) {
@@ -211,7 +219,16 @@ namespace hex {
}
try {
auto json = nlohmann::json::parse(file.readString());
#if defined(OS_WEB)
auto data = (char *) MAIN_THREAD_EM_ASM_INT({
let data = localStorage.getItem("achievements");
return data ? stringToNewUTF8(data) : null;
});
#else
auto data = file.readString();
#endif
auto json = nlohmann::json::parse(data);
for (const auto &[categoryName, achievements] : getAchievements()) {
for (const auto &[achievementName, achievement] : achievements) {
@@ -226,6 +243,8 @@ namespace hex {
}
}
}
s_initialized = true;
} catch (const std::exception &e) {
log::error("Failed to load achievements: {}", e.what());
}
@@ -234,6 +253,8 @@ namespace hex {
}
void AchievementManager::storeProgress() {
if (!s_initialized)
loadProgress();
nlohmann::json json;
for (const auto &[categoryName, achievements] : getAchievements()) {
json[categoryName] = nlohmann::json::object();
@@ -246,16 +267,23 @@ namespace hex {
if (json.empty())
return;
for (const auto &directory : fs::getDefaultPaths(fs::ImHexPath::Config)) {
auto path = directory / AchievementsFile;
#if defined(OS_WEB)
auto data = json.dump();
MAIN_THREAD_EM_ASM({
localStorage.setItem("achievements", UTF8ToString($0));
}, data.c_str());
#else
for (const auto &directory : paths::Config.write()) {
auto path = directory / AchievementsFile;
wolv::io::File file(path, wolv::io::File::Mode::Create);
if (!file.isValid())
continue;
wolv::io::File file(path, wolv::io::File::Mode::Create);
if (!file.isValid())
continue;
file.writeString(json.dump(4));
break;
}
file.writeString(json.dump(4));
break;
}
#endif
}
}

View File

@@ -4,6 +4,7 @@
#include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/auto_reset.hpp>
#include <hex/helpers/default_paths.hpp>
#include <hex/ui/view.hpp>
#include <hex/data_processor/node.hpp>
@@ -101,7 +102,7 @@ namespace hex {
void load() {
bool loaded = false;
for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Config)) {
for (const auto &dir : paths::Config.read()) {
wolv::io::File file(dir / SettingsFile, wolv::io::File::Mode::Read);
if (file.isValid()) {
@@ -142,7 +143,7 @@ namespace hex {
if (result.empty()) {
return;
}
for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Config)) {
for (const auto &dir : paths::Config.write()) {
wolv::io::File file(dir / SettingsFile, wolv::io::File::Mode::Create);
if (file.isValid()) {
@@ -153,7 +154,7 @@ namespace hex {
}
void clear() {
for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Config)) {
for (const auto &dir : paths::Config.write()) {
wolv::io::fs::remove(dir / SettingsFile);
}
}
@@ -190,6 +191,17 @@ namespace hex {
const auto entry = insertOrGetEntry(subCategory->entries, unlocalizedName);
entry->widget = std::move(widget);
if (entry->widget != nullptr) {
onChange(unlocalizedCategory, unlocalizedName, [widget = entry->widget.get(), unlocalizedCategory, unlocalizedName](const SettingsValue &) {
try {
auto defaultValue = widget->store();
widget->load(ContentRegistry::Settings::impl::getSetting(unlocalizedCategory, unlocalizedName, defaultValue));
widget->onChanged();
} catch (const std::exception &e) {
log::error("Failed to load setting [{} / {}]: {}", unlocalizedCategory.get(), unlocalizedName.get(), e.what());
}
});
}
return entry->widget.get();
}
@@ -551,6 +563,11 @@ namespace hex {
return *s_functions;
}
static AutoReset<std::vector<TypeDefinition>> s_types;
const std::vector<TypeDefinition>& getTypes() {
return *s_types;
}
}
static std::string getFunctionName(const pl::api::Namespace &ns, const std::string &name) {
@@ -595,7 +612,7 @@ namespace hex {
);
}
runtime.setIncludePaths(fs::getDefaultPaths(fs::ImHexPath::PatternsInclude) | fs::getDefaultPaths(fs::ImHexPath::Patterns));
runtime.setIncludePaths(paths::PatternsInclude.read() | paths::Patterns.read());
for (const auto &[ns, name, paramCount, callback, dangerous] : impl::getFunctions()) {
if (dangerous)
@@ -604,12 +621,16 @@ namespace hex {
runtime.addFunction(ns, name, paramCount, callback);
}
for (const auto &[ns, name, paramCount, callback] : impl::getTypes()) {
runtime.addType(ns, name, paramCount, callback);
}
for (const auto &[name, callback] : impl::getPragmas()) {
runtime.addPragma(name, callback);
}
runtime.addDefine("__IMHEX__");
runtime.addDefine("__IMHEX_VERSION__", ImHexApi::System::getImHexVersion());
runtime.addDefine("__IMHEX_VERSION__", ImHexApi::System::getImHexVersion().get());
}
void addPragma(const std::string &name, const pl::api::PragmaHandler &handler) {
@@ -638,6 +659,15 @@ namespace hex {
});
}
void addType(const pl::api::Namespace &ns, const std::string &name, pl::api::FunctionParameterCount parameterCount, const pl::api::TypeCallback &func) {
log::debug("Registered new pattern language type: {}", getFunctionName(ns, name));
impl::s_types->push_back({
ns, name,
parameterCount, func
});
}
void addVisualizer(const std::string &name, const impl::VisualizerFunctionCallback &function, pl::api::FunctionParameterCount parameterCount) {
log::debug("Registered new pattern visualizer function: {}", name);
@@ -820,6 +850,12 @@ namespace hex {
return *s_menuItems;
}
static AutoReset<std::vector<MenuItem*>> s_toolbarMenuItems;
const std::vector<MenuItem*>& getToolbarMenuItems() {
return s_toolbarMenuItems;
}
std::multimap<u32, MenuItem>& getMenuItemsMutable() {
return *s_menuItems;
}
@@ -877,14 +913,21 @@ namespace hex {
coloredIcon.color = ImGuiCustomCol_ToolbarGray;
impl::s_menuItems->insert({
priority, impl::MenuItem { unlocalizedMainMenuNames, coloredIcon, std::make_unique<Shortcut>(shortcut), view, function, enabledCallback, selectedCallback, -1 }
priority, impl::MenuItem { unlocalizedMainMenuNames, coloredIcon, shortcut, view, function, enabledCallback, selectedCallback, -1 }
});
if (shortcut != Shortcut::None) {
auto callbackIfEnabled = [enabledCallback, function]{ if (enabledCallback()) { function(); } };
const auto unlocalizedShortcutName =
unlocalizedMainMenuNames.size() == 1 ?
std::vector { unlocalizedMainMenuNames.back() } :
std::vector(unlocalizedMainMenuNames.begin() + 1, unlocalizedMainMenuNames.end());
if (shortcut.isLocal() && view != nullptr)
ShortcutManager::addShortcut(view, shortcut, unlocalizedMainMenuNames.back(), function);
ShortcutManager::addShortcut(view, shortcut, unlocalizedShortcutName, callbackIfEnabled);
else
ShortcutManager::addGlobalShortcut(shortcut, unlocalizedMainMenuNames.back(), function);
ShortcutManager::addGlobalShortcut(shortcut, unlocalizedShortcutName, callbackIfEnabled);
}
}
@@ -897,14 +940,14 @@ namespace hex {
unlocalizedMainMenuNames.emplace_back(impl::SubMenuValue);
impl::s_menuItems->insert({
priority, impl::MenuItem { unlocalizedMainMenuNames, icon, std::make_unique<Shortcut>(), nullptr, function, enabledCallback, []{ return false; }, -1 }
priority, impl::MenuItem { unlocalizedMainMenuNames, icon, Shortcut::None, nullptr, function, enabledCallback, []{ return false; }, -1 }
});
}
void addMenuItemSeparator(std::vector<UnlocalizedString> unlocalizedMainMenuNames, u32 priority) {
unlocalizedMainMenuNames.emplace_back(impl::SeparatorValue);
impl::s_menuItems->insert({
priority, impl::MenuItem { unlocalizedMainMenuNames, "", std::make_unique<Shortcut>(), nullptr, []{}, []{ return true; }, []{ return false; }, -1 }
priority, impl::MenuItem { unlocalizedMainMenuNames, "", Shortcut::None, nullptr, []{}, []{ return true; }, []{ return false; }, -1 }
});
}
@@ -929,11 +972,35 @@ namespace hex {
if (menuItem.unlocalizedNames.back() == unlocalizedName) {
menuItem.toolbarIndex = maxIndex + 1;
menuItem.icon.color = color;
updateToolbarItems();
break;
}
}
}
struct MenuItemSorter {
bool operator()(const auto *a, const auto *b) const {
return a->toolbarIndex < b->toolbarIndex;
}
};
void updateToolbarItems() {
std::set<ContentRegistry::Interface::impl::MenuItem*, MenuItemSorter> menuItems;
for (auto &[priority, menuItem] : impl::getMenuItemsMutable()) {
if (menuItem.toolbarIndex != -1) {
menuItems.insert(&menuItem);
}
}
impl::s_toolbarMenuItems->clear();
for (auto menuItem : menuItems) {
impl::s_toolbarMenuItems->push_back(menuItem);
}
}
void addSidebarItem(const std::string &icon, const impl::DrawCallback &function, const impl::EnabledCallback &enabledCallback) {
impl::s_sidebarItems->push_back({ icon, function, enabledCallback });
@@ -982,17 +1049,28 @@ namespace hex {
namespace impl {
static AutoReset<std::vector<Entry>> s_entries;
const std::vector<Entry>& getEntries() {
return *s_entries;
static AutoReset<std::vector<ExportMenuEntry>> s_exportMenuEntries;
const std::vector<ExportMenuEntry>& getExportMenuEntries() {
return *s_exportMenuEntries;
}
static AutoReset<std::vector<FindExporterEntry>> s_findExportEntries;
const std::vector<FindExporterEntry>& getFindExporterEntries() {
return *s_findExportEntries;
}
}
void add(const UnlocalizedString &unlocalizedName, const impl::Callback &callback) {
void addExportMenuEntry(const UnlocalizedString &unlocalizedName, const impl::Callback &callback) {
log::debug("Registered new data formatter: {}", unlocalizedName.get());
impl::s_entries->push_back({ unlocalizedName, callback });
impl::s_exportMenuEntries->push_back({ unlocalizedName, callback });
}
void addFindExportFormatter(const UnlocalizedString &unlocalizedName, const std::string fileExtension, const impl::FindExporterCallback &callback) {
log::debug("Registered new export formatter: {}", unlocalizedName.get());
impl::s_findExportEntries->push_back({ unlocalizedName, fileExtension, callback });
}
}
@@ -1157,7 +1235,7 @@ namespace hex {
class Service {
public:
Service(std::string name, std::jthread thread) : m_name(std::move(name)), m_thread(std::move(thread)) { }
Service(const UnlocalizedString &unlocalizedName, std::jthread thread) : m_unlocalizedName(std::move(unlocalizedName)), m_thread(std::move(thread)) { }
Service(const Service&) = delete;
Service(Service &&) = default;
~Service() {
@@ -1169,8 +1247,8 @@ namespace hex {
Service& operator=(const Service&) = delete;
Service& operator=(Service &&) = default;
[[nodiscard]] const std::string& getName() const {
return m_name;
[[nodiscard]] const UnlocalizedString& getUnlocalizedName() const {
return m_unlocalizedName;
}
[[nodiscard]] const std::jthread& getThread() const {
@@ -1178,7 +1256,7 @@ namespace hex {
}
private:
std::string m_name;
UnlocalizedString m_unlocalizedName;
std::jthread m_thread;
};

View File

@@ -21,4 +21,30 @@ namespace hex {
}
bool EventManager::isAlreadyRegistered(void *token, impl::EventId id) {
if (getTokenStore().contains(token)) {
auto&& [begin, end] = getTokenStore().equal_range(token);
return std::any_of(begin, end, [&](auto &item) {
return item.second->first == id;
});
}
return false;
}
void EventManager::unsubscribe(void *token, impl::EventId id) {
auto &tokenStore = getTokenStore();
auto iter = std::find_if(tokenStore.begin(), tokenStore.end(), [&](auto &item) {
return item.first == token && item.second->first == id;
});
if (iter != tokenStore.end()) {
getEvents().erase(iter->second);
tokenStore.erase(iter);
}
}
}

View File

@@ -15,7 +15,6 @@
#include <imgui.h>
#include <imgui_internal.h>
#include <set>
#include <fstream>
#include <algorithm>
#include <GLFW/glfw3.h>
@@ -185,24 +184,24 @@ namespace hex {
impl::s_hoveringFunctions->erase(id);
}
static u32 tooltipId = 0;
static u32 s_tooltipId = 0;
u32 addTooltip(Region region, std::string value, color_t color) {
tooltipId++;
impl::s_tooltips->insert({ tooltipId, { region, std::move(value), color } });
s_tooltipId++;
impl::s_tooltips->insert({ s_tooltipId, { region, std::move(value), color } });
return tooltipId;
return s_tooltipId;
}
void removeTooltip(u32 id) {
impl::s_tooltips->erase(id);
}
static u32 tooltipFunctionId;
static u32 s_tooltipFunctionId;
u32 addTooltipProvider(TooltipFunction function) {
tooltipFunctionId++;
impl::s_tooltipFunctions->insert({ tooltipFunctionId, std::move(function) });
s_tooltipFunctionId++;
impl::s_tooltipFunctions->insert({ s_tooltipFunctionId, std::move(function) });
return tooltipFunctionId;
return s_tooltipFunctionId;
}
void removeTooltipProvider(u32 id) {
@@ -269,6 +268,7 @@ namespace hex {
static i64 s_currentProvider = -1;
static AutoReset<std::vector<std::unique_ptr<prv::Provider>>> s_providers;
static AutoReset<std::map<prv::Provider*, std::unique_ptr<prv::Provider>>> s_providersToRemove;
namespace impl {
@@ -277,7 +277,7 @@ namespace hex {
s_closingProviders.clear();
}
const std::set<prv::Provider*>& getClosingProviders() {
std::set<prv::Provider*> getClosingProviders() {
return s_closingProviders;
}
@@ -337,7 +337,11 @@ namespace hex {
}
void markDirty() {
get()->markDirty();
const auto provider = get();
if (!provider->isDirty()) {
provider->markDirty();
EventProviderDirtied::post(provider);
}
}
void resetDirty() {
@@ -425,20 +429,38 @@ namespace hex {
}
}
provider->close();
EventProviderClosed::post(provider);
static std::mutex eraseMutex;
// Move provider over to a list of providers to delete
eraseMutex.lock();
auto providerToRemove = it->get();
(*s_providersToRemove)[providerToRemove] = std::move(*it);
eraseMutex.unlock();
// Remove left over references from the main provider list
s_providers->erase(it);
impl::s_closingProviders.erase(provider);
if (s_currentProvider >= i64(s_providers->size()) && !s_providers->empty())
setCurrentProvider(s_providers->size() - 1);
if (s_providers->empty())
EventProviderChanged::post(provider, nullptr);
EventProviderClosed::post(it->get());
RequestUpdateWindowTitle::post();
TaskManager::runWhenTasksFinished([it, provider] {
EventProviderDeleted::post(provider);
impl::s_closingProviders.erase(provider);
// Do the destruction of the provider in the background once all tasks have finished
TaskManager::runWhenTasksFinished([providerToRemove] {
EventProviderDeleted::post(providerToRemove);
TaskManager::createBackgroundTask("Closing Provider", [providerToRemove](Task &) {
eraseMutex.lock();
auto provider = std::move((*s_providersToRemove)[providerToRemove]);
s_providersToRemove->erase(providerToRemove);
eraseMutex.unlock();
s_providers->erase(it);
if (s_currentProvider >= i64(s_providers->size()))
setCurrentProvider(0);
if (s_providers->empty())
EventProviderChanged::post(provider, nullptr);
provider->close();
});
});
}
@@ -514,6 +536,11 @@ namespace hex {
s_gpuVendor = vendor;
}
static AutoReset<std::string> s_glRenderer;
void setGLRenderer(const std::string &renderer) {
s_glRenderer = renderer;
}
static AutoReset<std::map<std::string, std::string>> s_initArguments;
void addInitArgument(const std::string &key, const std::string &value) {
static std::mutex initArgumentsMutex;
@@ -615,7 +642,15 @@ namespace hex {
}
void* getLibImHexModuleHandle() {
return hex::getContainingModule((void*)&getLibImHexModuleHandle);
return hex::getContainingModule(reinterpret_cast<void*>(&getLibImHexModuleHandle));
}
void addMigrationRoutine(SemanticVersion migrationVersion, std::function<void()> function) {
EventImHexUpdated::subscribe([migrationVersion, function](const SemanticVersion &oldVersion, const SemanticVersion &newVersion) {
if (oldVersion < migrationVersion && newVersion >= migrationVersion) {
function();
}
});
}
@@ -658,6 +693,10 @@ namespace hex {
return impl::s_gpuVendor;
}
const std::string &getGLRenderer() {
return impl::s_glRenderer;
}
bool isPortableVersion() {
static std::optional<bool> portable;
if (portable.has_value())
@@ -745,34 +784,29 @@ namespace hex {
}
std::optional<LinuxDistro> getLinuxDistro() {
std::ifstream file("/etc/os-release");
wolv::io::File file("/etc/os-release", wolv::io::File::Mode::Read);
std::string name;
std::string version;
std::string line;
while (std::getline(file, line)) {
auto fileContent = file.readString();
for (const auto &line : wolv::util::splitString(fileContent, "\n")) {
if (line.find("PRETTY_NAME=") != std::string::npos) {
name = line.substr(line.find("=") + 1);
name.erase(std::remove(name.begin(), name.end(), '\"'), name.end());
std::erase(name, '\"');
} else if (line.find("VERSION_ID=") != std::string::npos) {
version = line.substr(line.find("=") + 1);
version.erase(std::remove(version.begin(), version.end(), '\"'), version.end());
std::erase(version, '\"');
}
}
return {{name, version}};
return { { name, version } };
}
std::string getImHexVersion(bool withBuildType) {
SemanticVersion getImHexVersion() {
#if defined IMHEX_VERSION
if (withBuildType) {
return IMHEX_VERSION;
} else {
auto version = std::string(IMHEX_VERSION);
return version.substr(0, version.find('-'));
}
return SemanticVersion(IMHEX_VERSION);
#else
return "Unknown";
return {};
#endif
}
@@ -784,7 +818,7 @@ namespace hex {
return std::string(GIT_COMMIT_HASH_LONG).substr(0, 7);
}
#else
hex::unused(longHash);
std::ignore = longHash;
return "Unknown";
#endif
}
@@ -805,6 +839,10 @@ namespace hex {
#endif
}
bool isNightlyBuild() {
return getImHexVersion().nightly();
}
bool updateImHex(UpdateType updateType) {
// Get the path of the updater executable
std::fs::path executablePath;
@@ -831,7 +869,7 @@ namespace hex {
EventImHexClosing::subscribe([executablePath, updateTypeString] {
hex::executeCommand(
hex::format("{} {}",
hex::format("\"{}\" \"{}\"",
wolv::util::toUTF8String(executablePath),
updateTypeString
)
@@ -910,9 +948,9 @@ namespace hex {
s_fontSize = size;
}
static AutoReset<std::shared_ptr<ImFontAtlas>> s_fontAtlas;
static AutoReset<ImFontAtlas*> s_fontAtlas;
void setFontAtlas(ImFontAtlas* fontAtlas) {
s_fontAtlas = std::unique_ptr<ImFontAtlas, void(*)(ImFontAtlas*)>(fontAtlas, IM_DELETE);
s_fontAtlas = fontAtlas;
}
static ImFont *s_boldFont = nullptr;
@@ -995,7 +1033,7 @@ namespace hex {
}
ImFontAtlas* getFontAtlas() {
return impl::s_fontAtlas->get();
return impl::s_fontAtlas;
}
ImFont* Bold() {

View File

@@ -1,13 +1,15 @@
#include <hex/api/layout_manager.hpp>
#include <hex/api/content_registry.hpp>
#include <hex/ui/view.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/auto_reset.hpp>
#include <hex/helpers/default_paths.hpp>
#include <wolv/utils/string.hpp>
#include <imgui.h>
#include <hex/api/content_registry.hpp>
#include <hex/ui/view.hpp>
namespace hex {
@@ -40,10 +42,7 @@ namespace hex {
fileName += ".hexlyt";
std::fs::path layoutPath;
for (const auto &path : hex::fs::getDefaultPaths(fs::ImHexPath::Layouts)) {
if (!hex::fs::isPathWritable(layoutPath))
continue;
for (const auto &path : paths::Layouts.write()) {
layoutPath = path / fileName;
}
@@ -109,7 +108,7 @@ namespace hex {
void LayoutManager::reload() {
s_layouts->clear();
for (const auto &directory : hex::fs::getDefaultPaths(fs::ImHexPath::Layouts)) {
for (const auto &directory : paths::Layouts.read()) {
for (const auto &entry : std::fs::directory_iterator(directory)) {
const auto &path = entry.path();

View File

@@ -10,7 +10,7 @@ namespace hex {
AutoReset<std::string> s_fallbackLanguage;
AutoReset<std::string> s_selectedLanguage;
AutoReset<std::map<std::string, std::string>> s_currStrings;
AutoReset<std::map<size_t, std::string>> s_currStrings;
}
@@ -41,6 +41,21 @@ namespace hex {
return m_entries;
}
static void loadLanguageDefinitions(const std::vector<LanguageDefinition> &definitions) {
for (const auto &definition : definitions) {
const auto &entries = definition.getEntries();
if (entries.empty())
continue;
for (const auto &[key, value] : entries) {
if (value.empty())
continue;
s_currStrings->emplace(LangConst::hash(key), value);
}
}
}
void loadLanguage(const std::string &language) {
auto &definitions = ContentRegistry::Language::impl::getLanguageDefinitions();
@@ -49,14 +64,10 @@ namespace hex {
s_currStrings->clear();
for (const auto &definition : definitions.at(language))
s_currStrings->insert(definition.getEntries().begin(), definition.getEntries().end());
loadLanguageDefinitions(definitions.at(language));
const auto& fallbackLanguage = getFallbackLanguage();
if (language != fallbackLanguage && definitions.contains(fallbackLanguage)) {
for (const auto &definition : definitions.at(fallbackLanguage))
s_currStrings->insert(definition.getEntries().begin(), definition.getEntries().end());
}
loadLanguageDefinitions(definitions.at(fallbackLanguage));
s_selectedLanguage = language;
}
@@ -98,11 +109,11 @@ namespace hex {
}
Lang::Lang(const char *unlocalizedString) : m_unlocalizedString(unlocalizedString) { }
Lang::Lang(const std::string &unlocalizedString) : m_unlocalizedString(unlocalizedString) { }
Lang::Lang(const UnlocalizedString &unlocalizedString) : m_unlocalizedString(unlocalizedString.get()) { }
Lang::Lang(std::string_view unlocalizedString) : m_unlocalizedString(unlocalizedString) { }
Lang::Lang(const char *unlocalizedString) : m_entryHash(LangConst::hash(unlocalizedString)), m_unlocalizedString(unlocalizedString) { }
Lang::Lang(const std::string &unlocalizedString) : m_entryHash(LangConst::hash(unlocalizedString)), m_unlocalizedString(unlocalizedString) { }
Lang::Lang(const LangConst &localizedString) : m_entryHash(localizedString.m_entryHash), m_unlocalizedString(localizedString.m_unlocalizedString) { }
Lang::Lang(const UnlocalizedString &unlocalizedString) : m_entryHash(LangConst::hash(unlocalizedString.get())), m_unlocalizedString(unlocalizedString.get()) { }
Lang::Lang(std::string_view unlocalizedString) : m_entryHash(LangConst::hash(unlocalizedString)), m_unlocalizedString(unlocalizedString) { }
Lang::operator std::string() const {
return get();
@@ -113,43 +124,41 @@ namespace hex {
}
Lang::operator const char *() const {
return get().c_str();
return get();
}
std::string operator+(const std::string &&left, const Lang &&right) {
return left + static_cast<std::string>(right);
const char *Lang::get() const {
const auto &lang = *LocalizationManager::s_currStrings;
const auto it = lang.find(m_entryHash);
if (it == lang.end()) {
return m_unlocalizedString.c_str();
} else {
return it->second.c_str();
}
}
std::string operator+(const Lang &&left, const std::string &&right) {
return static_cast<std::string>(left) + right;
LangConst::operator std::string() const {
return get();
}
std::string operator+(const Lang &&left, const Lang &&right) {
return static_cast<std::string>(left) + static_cast<std::string>(right);
LangConst::operator std::string_view() const {
return get();
}
std::string operator+(const std::string_view &&left, const Lang &&right) {
return std::string(left) + static_cast<std::string>(right);
LangConst::operator const char *() const {
return get();
}
std::string operator+(const Lang &&left, const std::string_view &&right) {
return static_cast<std::string>(left) + std::string(right);
}
const char *LangConst::get() const {
const auto &lang = *LocalizationManager::s_currStrings;
std::string operator+(const char *left, const Lang &&right) {
return left + static_cast<std::string>(right);
}
std::string operator+(const Lang &&left, const char *right) {
return static_cast<std::string>(left) + right;
}
const std::string &Lang::get() const {
auto &lang = LocalizationManager::s_currStrings;
if (lang->contains(m_unlocalizedString))
return lang->at(m_unlocalizedString);
else
const auto it = lang.find(m_entryHash);
if (it == lang.end()) {
return m_unlocalizedString;
} else {
return it->second.c_str();
}
}
}

View File

@@ -5,6 +5,7 @@
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/auto_reset.hpp>
#include <hex/helpers/utils.hpp>
#include <hex/helpers/default_paths.hpp>
#include <wolv/utils/string.hpp>
@@ -111,10 +112,6 @@ namespace hex {
}
Plugin::~Plugin() {
if (isLoaded()) {
log::info("Trying to unload plugin '{}'", getPluginName());
}
unloadLibrary(m_handle, m_path);
}
@@ -132,7 +129,7 @@ namespace hex {
const auto requestedVersion = getCompatibleVersion();
const auto imhexVersion = ImHexApi::System::getImHexVersion();
const auto imhexVersion = ImHexApi::System::getImHexVersion().get();
if (!imhexVersion.starts_with(requestedVersion)) {
if (requestedVersion.empty()) {
log::warn("Plugin '{}' did not specify a compatible version, assuming it is compatible with the current version of ImHex.", wolv::util::toUTF8String(m_path.filename()));
@@ -306,7 +303,7 @@ namespace hex {
bool PluginManager::loadLibraries() {
bool success = true;
for (const auto &loadPath : fs::getDefaultPaths(fs::ImHexPath::Libraries))
for (const auto &loadPath : paths::Libraries.read())
success = PluginManager::loadLibraries(loadPath) && success;
return success;
@@ -334,7 +331,7 @@ namespace hex {
void PluginManager::initializeNewPlugins() {
for (const auto &plugin : getPlugins()) {
if (!plugin.isLoaded())
hex::unused(plugin.initializePlugin());
std::ignore = plugin.initializePlugin();
}
}

View File

@@ -12,31 +12,265 @@ namespace hex {
AutoReset<std::map<Shortcut, ShortcutManager::ShortcutEntry>> s_globalShortcuts;
std::atomic<bool> s_paused;
std::optional<Shortcut> s_prevShortcut;
bool s_macOSMode = false;
}
Shortcut operator+(const Key &lhs, const Key &rhs) {
Shortcut result;
result.m_keys = { lhs, rhs };
return result;
}
Shortcut::Shortcut(Keys key) : m_keys({ key }) {
}
Shortcut::Shortcut(std::set<Key> keys) : m_keys(std::move(keys)) {
}
Shortcut Shortcut::operator+(const Key &other) const {
Shortcut result = *this;
result.m_keys.insert(other);
return result;
}
Shortcut& Shortcut::operator+=(const Key &other) {
m_keys.insert(other);
return *this;
}
bool Shortcut::operator<(const Shortcut &other) const {
return m_keys < other.m_keys;
}
bool Shortcut::operator==(const Shortcut &other) const {
return m_keys == other.m_keys;
}
bool Shortcut::isLocal() const {
return m_keys.contains(CurrentView);
}
const std::set<Key>& Shortcut::getKeys() const {
return m_keys;
}
bool Shortcut::has(Key key) const {
return m_keys.contains(key);
}
bool Shortcut::matches(const Shortcut& other) const {
auto left = this->m_keys;
auto right = other.m_keys;
left.erase(CurrentView);
left.erase(AllowWhileTyping);
right.erase(CurrentView);
right.erase(AllowWhileTyping);
return left == right;
}
std::string Shortcut::toString() const {
std::string result;
const auto CTRL_NAME = s_macOSMode ? "" : "CTRL";
const auto ALT_NAME = s_macOSMode ? "" : "ALT";
const auto SHIFT_NAME = s_macOSMode ? "" : "SHIFT";
const auto SUPER_NAME = s_macOSMode ? "" : "SUPER";
const auto Concatination = s_macOSMode ? " " : " + ";
auto keys = m_keys;
if (keys.erase(CTRL) > 0 || (!s_macOSMode && keys.erase(CTRLCMD) > 0)) {
result += CTRL_NAME;
result += Concatination;
}
if (keys.erase(ALT) > 0) {
result += ALT_NAME;
result += Concatination;
}
if (keys.erase(SHIFT) > 0) {
result += SHIFT_NAME;
result += Concatination;
}
if (keys.erase(SUPER) > 0 || (s_macOSMode && keys.erase(CTRLCMD) > 0)) {
result += SUPER_NAME;
result += Concatination;
}
keys.erase(CurrentView);
for (const auto &key : keys) {
switch (Keys(key.getKeyCode())) {
case Keys::Space: result += ""; break;
case Keys::Apostrophe: result += "'"; break;
case Keys::Comma: result += ","; break;
case Keys::Minus: result += "-"; break;
case Keys::Period: result += "."; break;
case Keys::Slash: result += "/"; break;
case Keys::Num0: result += "0"; break;
case Keys::Num1: result += "1"; break;
case Keys::Num2: result += "2"; break;
case Keys::Num3: result += "3"; break;
case Keys::Num4: result += "4"; break;
case Keys::Num5: result += "5"; break;
case Keys::Num6: result += "6"; break;
case Keys::Num7: result += "7"; break;
case Keys::Num8: result += "8"; break;
case Keys::Num9: result += "9"; break;
case Keys::Semicolon: result += ";"; break;
case Keys::Equals: result += "="; break;
case Keys::A: result += "A"; break;
case Keys::B: result += "B"; break;
case Keys::C: result += "C"; break;
case Keys::D: result += "D"; break;
case Keys::E: result += "E"; break;
case Keys::F: result += "F"; break;
case Keys::G: result += "G"; break;
case Keys::H: result += "H"; break;
case Keys::I: result += "I"; break;
case Keys::J: result += "J"; break;
case Keys::K: result += "K"; break;
case Keys::L: result += "L"; break;
case Keys::M: result += "M"; break;
case Keys::N: result += "N"; break;
case Keys::O: result += "O"; break;
case Keys::P: result += "P"; break;
case Keys::Q: result += "Q"; break;
case Keys::R: result += "R"; break;
case Keys::S: result += "S"; break;
case Keys::T: result += "T"; break;
case Keys::U: result += "U"; break;
case Keys::V: result += "V"; break;
case Keys::W: result += "W"; break;
case Keys::X: result += "X"; break;
case Keys::Y: result += "Y"; break;
case Keys::Z: result += "Z"; break;
case Keys::LeftBracket: result += "["; break;
case Keys::Backslash: result += "\\"; break;
case Keys::RightBracket: result += "]"; break;
case Keys::GraveAccent: result += "`"; break;
case Keys::World1: result += "WORLD1"; break;
case Keys::World2: result += "WORLD2"; break;
case Keys::Escape: result += "ESC"; break;
case Keys::Enter: result += ""; break;
case Keys::Tab: result += ""; break;
case Keys::Backspace: result += ""; break;
case Keys::Insert: result += "INSERT"; break;
case Keys::Delete: result += "DELETE"; break;
case Keys::Right: result += "RIGHT"; break;
case Keys::Left: result += "LEFT"; break;
case Keys::Down: result += "DOWN"; break;
case Keys::Up: result += "UP"; break;
case Keys::PageUp: result += "PAGEUP"; break;
case Keys::PageDown: result += "PAGEDOWN"; break;
case Keys::Home: result += "HOME"; break;
case Keys::End: result += "END"; break;
case Keys::CapsLock: result += ""; break;
case Keys::ScrollLock: result += "SCROLLLOCK"; break;
case Keys::NumLock: result += "NUMLOCK"; break;
case Keys::PrintScreen: result += "PRINTSCREEN"; break;
case Keys::Pause: result += "PAUSE"; break;
case Keys::F1: result += "F1"; break;
case Keys::F2: result += "F2"; break;
case Keys::F3: result += "F3"; break;
case Keys::F4: result += "F4"; break;
case Keys::F5: result += "F5"; break;
case Keys::F6: result += "F6"; break;
case Keys::F7: result += "F7"; break;
case Keys::F8: result += "F8"; break;
case Keys::F9: result += "F9"; break;
case Keys::F10: result += "F10"; break;
case Keys::F11: result += "F11"; break;
case Keys::F12: result += "F12"; break;
case Keys::F13: result += "F13"; break;
case Keys::F14: result += "F14"; break;
case Keys::F15: result += "F15"; break;
case Keys::F16: result += "F16"; break;
case Keys::F17: result += "F17"; break;
case Keys::F18: result += "F18"; break;
case Keys::F19: result += "F19"; break;
case Keys::F20: result += "F20"; break;
case Keys::F21: result += "F21"; break;
case Keys::F22: result += "F22"; break;
case Keys::F23: result += "F23"; break;
case Keys::F24: result += "F24"; break;
case Keys::F25: result += "F25"; break;
case Keys::KeyPad0: result += "KP0"; break;
case Keys::KeyPad1: result += "KP1"; break;
case Keys::KeyPad2: result += "KP2"; break;
case Keys::KeyPad3: result += "KP3"; break;
case Keys::KeyPad4: result += "KP4"; break;
case Keys::KeyPad5: result += "KP5"; break;
case Keys::KeyPad6: result += "KP6"; break;
case Keys::KeyPad7: result += "KP7"; break;
case Keys::KeyPad8: result += "KP8"; break;
case Keys::KeyPad9: result += "KP9"; break;
case Keys::KeyPadDecimal: result += "KPDECIMAL"; break;
case Keys::KeyPadDivide: result += "KPDIVIDE"; break;
case Keys::KeyPadMultiply: result += "KPMULTIPLY"; break;
case Keys::KeyPadSubtract: result += "KPSUBTRACT"; break;
case Keys::KeyPadAdd: result += "KPADD"; break;
case Keys::KeyPadEnter: result += "KPENTER"; break;
case Keys::KeyPadEqual: result += "KPEQUAL"; break;
case Keys::Menu: result += "MENU"; break;
default:
continue;
}
result += Concatination;
}
if (result.ends_with(Concatination))
result = result.substr(0, result.size() - strlen(Concatination));
return result;
}
void ShortcutManager::addGlobalShortcut(const Shortcut &shortcut, const std::vector<UnlocalizedString> &unlocalizedName, const std::function<void()> &callback) {
log::debug("Adding global shortcut {} for {}", shortcut.toString(), unlocalizedName.back().get());
auto [it, inserted] = s_globalShortcuts->insert({ shortcut, { shortcut, unlocalizedName, callback } });
if (!inserted) log::error("Failed to add shortcut!");
}
void ShortcutManager::addGlobalShortcut(const Shortcut &shortcut, const UnlocalizedString &unlocalizedName, const std::function<void()> &callback) {
s_globalShortcuts->insert({ shortcut, { shortcut, unlocalizedName, callback } });
log::debug("Adding global shortcut {} for {}", shortcut.toString(), unlocalizedName.get());
auto [it, inserted] = s_globalShortcuts->insert({ shortcut, { shortcut, { unlocalizedName }, callback } });
if (!inserted) log::error("Failed to add shortcut!");
}
void ShortcutManager::addShortcut(View *view, const Shortcut &shortcut, const std::vector<UnlocalizedString> &unlocalizedName, const std::function<void()> &callback) {
log::debug("Adding shortcut {} for {}", shortcut.toString(), unlocalizedName.back().get());
auto [it, inserted] = view->m_shortcuts.insert({ shortcut + CurrentView, { shortcut, unlocalizedName, callback } });
if (!inserted) log::error("Failed to add shortcut!");
}
void ShortcutManager::addShortcut(View *view, const Shortcut &shortcut, const UnlocalizedString &unlocalizedName, const std::function<void()> &callback) {
view->m_shortcuts.insert({ shortcut + CurrentView, { shortcut, unlocalizedName, callback } });
log::debug("Adding shortcut {} for {}", shortcut.toString(), unlocalizedName.get());
auto [it, inserted] = view->m_shortcuts.insert({ shortcut + CurrentView, { shortcut, { unlocalizedName }, callback } });
if (!inserted) log::error("Failed to add shortcut!");
}
static Shortcut getShortcut(bool ctrl, bool alt, bool shift, bool super, bool focused, u32 keyCode) {
Shortcut pressedShortcut;
if (ctrl)
pressedShortcut += CTRL;
pressedShortcut += s_macOSMode ? CTRL : CTRLCMD;
if (alt)
pressedShortcut += ALT;
if (shift)
pressedShortcut += SHIFT;
if (super)
pressedShortcut += SUPER;
pressedShortcut += s_macOSMode ? CTRLCMD : SUPER;
if (focused)
pressedShortcut += CurrentView;
if (ImGui::GetIO().WantTextInput)
pressedShortcut += AllowWhileTyping;
pressedShortcut += static_cast<Keys>(keyCode);
@@ -49,11 +283,9 @@ namespace hex {
if (ImGui::IsPopupOpen(ImGuiID(0), ImGuiPopupFlags_AnyPopupId))
return;
if (shortcuts.contains(shortcut + AllowWhileTyping)) {
shortcuts.at(shortcut + AllowWhileTyping).callback();
} else if (shortcuts.contains(shortcut)) {
if (!ImGui::GetIO().WantTextInput)
shortcuts.at(shortcut).callback();
if (auto it = shortcuts.find(shortcut); it != shortcuts.end()) {
const auto &[foundShortcut, entry] = *it;
entry.callback();
}
}
@@ -122,10 +354,13 @@ namespace hex {
return true;
}
bool ShortcutManager::updateShortcut(const Shortcut &oldShortcut, const Shortcut &newShortcut, View *view) {
if (oldShortcut == newShortcut)
bool ShortcutManager::updateShortcut(const Shortcut &oldShortcut, Shortcut newShortcut, View *view) {
if (oldShortcut.matches(newShortcut))
return true;
if (oldShortcut.has(AllowWhileTyping))
newShortcut += AllowWhileTyping;
bool result;
if (view != nullptr) {
result = updateShortcutImpl(oldShortcut + CurrentView, newShortcut + CurrentView , view->m_shortcuts);
@@ -134,9 +369,9 @@ namespace hex {
}
if (result) {
for (auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItems()) {
if (menuItem.view == view && *menuItem.shortcut == oldShortcut) {
*menuItem.shortcut = newShortcut;
for (auto &[priority, menuItem] : ContentRegistry::Interface::impl::getMenuItemsMutable()) {
if (menuItem.view == view && menuItem.shortcut == oldShortcut) {
menuItem.shortcut = newShortcut;
break;
}
}
@@ -145,4 +380,9 @@ namespace hex {
return result;
}
void ShortcutManager::enableMacOSMode() {
s_macOSMode = true;
}
}

View File

@@ -63,7 +63,7 @@ namespace hex {
}
Task::Task(UnlocalizedString unlocalizedName, u64 maxValue, bool background, std::function<void(Task &)> function)
Task::Task(const UnlocalizedString &unlocalizedName, u64 maxValue, bool background, std::function<void(Task &)> function)
: m_unlocalizedName(std::move(unlocalizedName)), m_maxValue(maxValue), m_function(std::move(function)), m_background(background) { }
Task::Task(hex::Task &&other) noexcept {
@@ -327,11 +327,11 @@ namespace hex {
s_tasksFinishedCallbacks.clear();
}
TaskHolder TaskManager::createTask(std::string name, u64 maxValue, bool background, std::function<void(Task&)> function) {
TaskHolder TaskManager::createTask(const UnlocalizedString &unlocalizedName, u64 maxValue, bool background, std::function<void(Task&)> function) {
std::scoped_lock lock(s_queueMutex);
// Construct new task
auto task = std::make_shared<Task>(std::move(name), maxValue, background, std::move(function));
auto task = std::make_shared<Task>(std::move(unlocalizedName), maxValue, background, std::move(function));
s_tasks.emplace_back(task);
@@ -344,14 +344,32 @@ namespace hex {
}
TaskHolder TaskManager::createTask(std::string name, u64 maxValue, std::function<void(Task &)> function) {
log::debug("Creating task {}", name);
return createTask(std::move(name), maxValue, false, std::move(function));
TaskHolder TaskManager::createTask(const UnlocalizedString &unlocalizedName, u64 maxValue, std::function<void(Task &)> function) {
log::debug("Creating task {}", unlocalizedName.get());
return createTask(std::move(unlocalizedName), maxValue, false, std::move(function));
}
TaskHolder TaskManager::createBackgroundTask(std::string name, std::function<void(Task &)> function) {
log::debug("Creating background task {}", name);
return createTask(std::move(name), 0, true, std::move(function));
TaskHolder TaskManager::createTask(const UnlocalizedString &unlocalizedName, u64 maxValue, std::function<void()> function) {
log::debug("Creating task {}", unlocalizedName.get());
return createTask(std::move(unlocalizedName), maxValue, false,
[function = std::move(function)](Task&) {
function();
}
);
}
TaskHolder TaskManager::createBackgroundTask(const UnlocalizedString &unlocalizedName, std::function<void(Task &)> function) {
log::debug("Creating background task {}", unlocalizedName.get());
return createTask(std::move(unlocalizedName), 0, true, std::move(function));
}
TaskHolder TaskManager::createBackgroundTask(const UnlocalizedString &unlocalizedName, std::function<void()> function) {
log::debug("Creating background task {}", unlocalizedName.get());
return createTask(std::move(unlocalizedName), 0, true,
[function = std::move(function)](Task&) {
function();
}
);
}
void TaskManager::collectGarbage() {
@@ -443,7 +461,7 @@ namespace hex {
static auto setThreadDescription = reinterpret_cast<SetThreadDescriptionFunc>(
reinterpret_cast<uintptr_t>(
::GetProcAddress(
::GetModuleHandle("Kernel32.dll"),
::GetModuleHandleW(L"Kernel32.dll"),
"SetThreadDescription"
)
)
@@ -472,7 +490,7 @@ namespace hex {
#elif defined(OS_LINUX)
pthread_setname_np(pthread_self(), name.c_str());
#elif defined(OS_WEB)
hex::unused(name);
std::ignore = name;
#elif defined(OS_MACOS)
pthread_setname_np(name.c_str());
#endif

View File

@@ -21,6 +21,11 @@ namespace hex {
}
void ThemeManager::reapplyCurrentTheme() {
ThemeManager::changeTheme(s_currTheme);
}
void ThemeManager::addThemeHandler(const std::string &name, const ColorMap &colorMap, const std::function<ImColor(u32)> &getFunction, const std::function<void(u32, ImColor)> &setFunction) {
std::unique_lock lock(s_themeMutex);

View File

@@ -21,6 +21,11 @@ namespace hex {
AutoReset<std::map<ImGuiID, std::string>> s_highlights;
AutoReset<std::vector<std::pair<ImRect, std::string>>> s_highlightDisplays;
AutoReset<std::map<ImGuiID, std::function<void()>>> s_interactiveHelpItems;
ImRect s_hoveredRect;
ImGuiID s_hoveredId;
bool s_helpHoverActive = false;
class IDStack {
public:
@@ -28,6 +33,13 @@ namespace hex {
idStack.push_back(0);
}
void add(const char *string) {
const ImGuiID seed = idStack.back();
const ImGuiID id = ImHashStr(string, 0, seed);
idStack.push_back(id);
}
void add(const std::string &string) {
const ImGuiID seed = idStack.back();
const ImGuiID id = ImHashStr(string.c_str(), string.length(), seed);
@@ -56,8 +68,46 @@ namespace hex {
ImVector<ImGuiID> idStack;
};
ImGuiID calculateId(const auto &ids) {
IDStack idStack;
for (const auto &id : ids) {
std::visit(wolv::util::overloaded {
[&idStack](const Lang &id) {
idStack.add(id.get());
},
[&idStack](const auto &id) {
idStack.add(id);
}
}, id);
}
return idStack.get();
}
}
void TutorialManager::init() {
EventImGuiElementRendered::subscribe([](ImGuiID id, const std::array<float, 4> bb){
const auto boundingBox = ImRect(bb[0], bb[1], bb[2], bb[3]);
const auto element = hex::s_highlights->find(id);
if (element != hex::s_highlights->end()) {
hex::s_highlightDisplays->emplace_back(boundingBox, element->second);
const auto window = ImGui::GetCurrentWindow();
if (window != nullptr && window->DockNode != nullptr && window->DockNode->TabBar != nullptr)
window->DockNode->TabBar->NextSelectedTabId = window->TabId;
}
if (id != 0 && boundingBox.Contains(ImGui::GetMousePos())) {
if ((s_hoveredRect.GetArea() == 0 || boundingBox.GetArea() < s_hoveredRect.GetArea()) && s_interactiveHelpItems->contains(id)) {
s_hoveredRect = boundingBox;
s_hoveredId = id;
}
}
});
}
const std::map<std::string, TutorialManager::Tutorial>& TutorialManager::getTutorials() {
return s_tutorials;
@@ -72,6 +122,28 @@ namespace hex {
return s_tutorials->try_emplace(unlocalizedName, Tutorial(unlocalizedName, unlocalizedDescription)).first->second;
}
void TutorialManager::startHelpHover() {
TaskManager::doLater([]{
s_helpHoverActive = true;
});
}
void TutorialManager::addInteractiveHelpText(std::initializer_list<std::variant<Lang, std::string, int>> &&ids, UnlocalizedString text) {
auto id = calculateId(ids);
s_interactiveHelpItems->emplace(id, [text = std::move(text)]{
log::info("{}", Lang(text).get());
});
}
void TutorialManager::addInteractiveHelpLink(std::initializer_list<std::variant<Lang, std::string, int>> &&ids, std::string link) {
auto id = calculateId(ids);
s_interactiveHelpItems->emplace(id, [link = std::move(link)]{
hex::openWebpage(link);
});
}
void TutorialManager::startTutorial(const UnlocalizedString &unlocalizedName) {
s_currentTutorial = s_tutorials->find(unlocalizedName);
if (s_currentTutorial == s_tutorials->end())
@@ -81,6 +153,30 @@ namespace hex {
}
void TutorialManager::drawHighlights() {
if (s_helpHoverActive) {
const auto &drawList = ImGui::GetForegroundDrawList();
drawList->AddText(ImGui::GetMousePos() + scaled({ 10, -5, }), ImGui::GetColorU32(ImGuiCol_Text), "?");
const bool mouseClicked = ImGui::IsMouseClicked(ImGuiMouseButton_Left);
if (s_hoveredId != 0) {
drawList->AddRectFilled(s_hoveredRect.Min, s_hoveredRect.Max, 0x30FFFFFF);
if (mouseClicked) {
auto it = s_interactiveHelpItems->find(s_hoveredId);
if (it != s_interactiveHelpItems->end()) {
it->second();
}
}
s_hoveredId = 0;
s_hoveredRect = {};
}
if (mouseClicked || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
s_helpHoverActive = false;
}
}
for (const auto &[rect, unlocalizedText] : *s_highlightDisplays) {
const auto drawList = ImGui::GetForegroundDrawList();
@@ -241,39 +337,13 @@ namespace hex {
m_onAppear();
for (const auto &[text, ids] : m_highlights) {
IDStack idStack;
for (const auto &id : ids) {
std::visit(wolv::util::overloaded {
[&idStack](const Lang &id) {
idStack.add(id.get());
},
[&idStack](const auto &id) {
idStack.add(id);
}
}, id);
}
s_highlights->emplace(idStack.get(), text);
s_highlights->emplace(calculateId(ids), text);
}
}
void TutorialManager::Tutorial::Step::removeHighlights() const {
for (const auto &[text, ids] : m_highlights) {
IDStack idStack;
for (const auto &id : ids) {
std::visit(wolv::util::overloaded {
[&idStack](const Lang &id) {
idStack.add(id.get());
},
[&idStack](const auto &id) {
idStack.add(id);
}
}, id);
}
s_highlights->erase(idStack.get());
s_highlights->erase(calculateId(ids));
}
}
@@ -368,15 +438,4 @@ namespace hex {
}
}
}
void ImGuiTestEngineHook_ItemAdd(ImGuiContext*, ImGuiID id, const ImRect& bb, const ImGuiLastItemData*) {
const auto element = hex::s_highlights->find(id);
if (element != hex::s_highlights->end()) {
hex::s_highlightDisplays->emplace_back(bb, element->second);
}
}
void ImGuiTestEngineHook_ItemInfo(ImGuiContext*, ImGuiID, const char*, ImGuiItemStatusFlags) {}
void ImGuiTestEngineHook_Log(ImGuiContext*, const char*, ...) {}
const char* ImGuiTestEngine_FindItemDebugLabel(ImGuiContext*, ImGuiID) { return nullptr; }
}

View File

@@ -3,6 +3,7 @@
#include <hex/helpers/logger.hpp>
#include <hex/helpers/auto_reset.hpp>
#include <hex/helpers/default_paths.hpp>
#include <wolv/io/file.hpp>
@@ -25,7 +26,7 @@ namespace hex {
.builtin = false
}).first;
for (const auto &workspaceFolder : fs::getDefaultPaths(fs::ImHexPath::Workspaces)) {
for (const auto &workspaceFolder : paths::Workspaces.write()) {
const auto workspacePath = workspaceFolder / (name + ".hexws");
if (exportToFile(workspacePath)) {
s_currentWorkspace->second.path = workspacePath;
@@ -157,7 +158,7 @@ namespace hex {
void WorkspaceManager::reload() {
WorkspaceManager::reset();
for (const auto &defaultPath : fs::getDefaultPaths(fs::ImHexPath::Workspaces)) {
for (const auto &defaultPath : paths::Workspaces.read()) {
for (const auto &entry : std::fs::directory_iterator(defaultPath)) {
if (!entry.is_regular_file()) {
continue;

View File

@@ -8,12 +8,18 @@
namespace hex::dp {
int Node::s_idCounter = 1;
static std::atomic_bool s_interrupted;
Node::Node(UnlocalizedString unlocalizedTitle, std::vector<Attribute> attributes) : m_id(s_idCounter++), m_unlocalizedTitle(std::move(unlocalizedTitle)), m_attributes(std::move(attributes)) {
for (auto &attr : m_attributes)
attr.setParentNode(this);
}
void Node::draw() {
this->drawNode();
}
const std::vector<u8>& Node::getBufferOnInput(u32 index) {
auto attribute = this->getConnectedInputAttribute(index);
@@ -29,9 +35,6 @@ namespace hex::dp {
auto &outputData = attribute->getOutputData();
if (outputData.empty())
throwNodeError("No data available at connected attribute");
return outputData;
}
@@ -148,9 +151,56 @@ namespace hex::dp {
m_overlay->getData() = data;
}
[[noreturn]] void Node::throwNodeError(const std::string &message) {
throw NodeError { this, message };
}
void Node::setAttributes(std::vector<Attribute> attributes) {
m_attributes = std::move(attributes);
for (auto &attr : m_attributes)
attr.setParentNode(this);
}
void Node::setIdCounter(int id) {
if (id > s_idCounter)
s_idCounter = id;
}
Attribute& Node::getAttribute(u32 index) {
if (index >= this->getAttributes().size())
throw std::runtime_error("Attribute index out of bounds!");
return this->getAttributes()[index];
}
Attribute *Node::getConnectedInputAttribute(u32 index) {
const auto &connectedAttribute = this->getAttribute(index).getConnectedAttributes();
if (connectedAttribute.empty())
return nullptr;
return connectedAttribute.begin()->second;
}
void Node::markInputProcessed(u32 index) {
const auto &[iter, inserted] = m_processedInputs.insert(index);
if (!inserted)
throwNodeError("Recursion detected!");
if (s_interrupted) {
s_interrupted = false;
throwNodeError("Execution interrupted!");
}
}
void Node::unmarkInputProcessed(u32 index) {
m_processedInputs.erase(index);
}
void Node::interrupt() {
s_interrupted = true;
}
}

View File

@@ -1,8 +1,10 @@
#include <algorithm>
#include <hex/helpers/crypto.hpp>
#include <hex/providers/provider.hpp>
#include <wolv/utils/guards.hpp>
#include <wolv/utils/expected.hpp>
#include <mbedtls/version.h>
#include <mbedtls/base64.h>
@@ -496,8 +498,8 @@ namespace hex::crypt {
return encodeLeb128<i128>(value);
}
static std::vector<u8> aes(mbedtls_cipher_type_t type, mbedtls_operation_t operation, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input) {
std::vector<u8> output;
static wolv::util::Expected<std::vector<u8>, int> aes(mbedtls_cipher_type_t type, mbedtls_operation_t operation, const std::vector<u8> &key,
std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::span<const u8> &input) {
if (input.empty())
return {};
@@ -507,38 +509,65 @@ namespace hex::crypt {
mbedtls_cipher_context_t ctx;
auto cipherInfo = mbedtls_cipher_info_from_type(type);
if (cipherInfo == nullptr)
return {};
mbedtls_cipher_setup(&ctx, cipherInfo);
mbedtls_cipher_setkey(&ctx, key.data(), key.size() * 8, operation);
int setupResult = mbedtls_cipher_setup(&ctx, cipherInfo);
if (setupResult != 0)
return wolv::util::Unexpected(setupResult);
int setKeyResult = mbedtls_cipher_setkey(&ctx, key.data(), key.size() * 8, operation);
if (setKeyResult != 0)
return wolv::util::Unexpected(setKeyResult);
std::array<u8, 16> nonceCounter = { 0 };
std::copy(nonce.begin(), nonce.end(), nonceCounter.begin());
std::copy(iv.begin(), iv.end(), nonceCounter.begin() + 8);
auto mode = mbedtls_cipher_get_cipher_mode(&ctx);
// if we are in ECB mode, we don't need to set the nonce
if (mode != MBEDTLS_MODE_ECB) {
std::ranges::copy(nonce, nonceCounter.begin());
std::ranges::copy(iv, nonceCounter.begin() + 8);
}
size_t outputSize = input.size() + mbedtls_cipher_get_block_size(&ctx);
output.resize(outputSize, 0x00);
mbedtls_cipher_crypt(&ctx, nonceCounter.data(), nonceCounter.size(), input.data(), input.size(), output.data(), &outputSize);
std::vector<u8> output(outputSize, 0x00);
int cryptResult = 0;
if (mode == MBEDTLS_MODE_ECB) {
cryptResult = mbedtls_cipher_crypt(&ctx, nullptr, 0, input.data(), input.size(), output.data(), &outputSize);
} else {
cryptResult = mbedtls_cipher_crypt(&ctx, nonceCounter.data(), nonceCounter.size(), input.data(), input.size(), output.data(), &outputSize);
}
// free regardless of the result
mbedtls_cipher_free(&ctx);
if (cryptResult != 0) {
return wolv::util::Unexpected(cryptResult);
}
output.resize(input.size());
return output;
}
std::vector<u8> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input) {
wolv::util::Expected<std::vector<u8>, int> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input) {
switch (keyLength) {
case KeyLength::Key128Bits:
if (key.size() != 128 / 8) return {};
if (key.size() != 128 / 8)
return wolv::util::Unexpected(CRYPTO_ERROR_INVALID_KEY_LENGTH);
break;
case KeyLength::Key192Bits:
if (key.size() != 192 / 8) return {};
if (key.size() != 192 / 8)
return wolv::util::Unexpected(CRYPTO_ERROR_INVALID_KEY_LENGTH);
break;
case KeyLength::Key256Bits:
if (key.size() != 256 / 8) return {};
if (key.size() != 256 / 8)
return wolv::util::Unexpected(CRYPTO_ERROR_INVALID_KEY_LENGTH);
break;
default:
return {};
return wolv::util::Unexpected(CRYPTO_ERROR_INVALID_KEY_LENGTH);
}
mbedtls_cipher_type_t type;
@@ -568,7 +597,7 @@ namespace hex::crypt {
type = MBEDTLS_CIPHER_AES_128_XTS;
break;
default:
return {};
return wolv::util::Unexpected(CRYPTO_ERROR_INVALID_MODE);
}
type = mbedtls_cipher_type_t(type + u8(keyLength));

View File

@@ -0,0 +1,153 @@
#include <hex/helpers/default_paths.hpp>
#include <hex/api/imhex_api.hpp>
#include <hex/api/project_file_manager.hpp>
#if defined(OS_WINDOWS)
#include <windows.h>
#include <shlobj.h>
#elif defined(OS_LINUX) || defined(OS_WEB)
#include <xdg.hpp>
# endif
namespace hex::paths {
std::vector<std::fs::path> getDataPaths(bool includeSystemFolders) {
std::vector<std::fs::path> paths;
#if defined(OS_WINDOWS)
// In the portable Windows version, we just use the executable directory
// Prevent the use of the AppData folder here
if (!ImHexApi::System::isPortableVersion()) {
PWSTR wAppDataPath = nullptr;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &wAppDataPath))) {
paths.emplace_back(wAppDataPath);
CoTaskMemFree(wAppDataPath);
}
}
#elif defined(OS_MACOS)
paths.push_back(wolv::io::fs::getApplicationSupportDirectoryPath() / "imhex");
#elif defined(OS_LINUX) || defined(OS_WEB)
paths.push_back(xdg::DataHomeDir());
auto dataDirs = xdg::DataDirs();
std::copy(dataDirs.begin(), dataDirs.end(), std::back_inserter(paths));
#endif
#if defined(OS_MACOS)
if (includeSystemFolders) {
if (auto executablePath = wolv::io::fs::getExecutablePath(); executablePath.has_value()) {
paths.push_back(*executablePath);
}
}
#else
for (auto &path : paths)
path = path / "imhex";
if (ImHexApi::System::isPortableVersion() || includeSystemFolders) {
if (auto executablePath = wolv::io::fs::getExecutablePath(); executablePath.has_value())
paths.push_back(executablePath->parent_path());
}
#endif
// Add additional data directories to the path
auto additionalDirs = ImHexApi::System::getAdditionalFolderPaths();
std::ranges::copy(additionalDirs, std::back_inserter(paths));
// Add the project file directory to the path, if one is loaded
if (ProjectFile::hasPath()) {
paths.push_back(ProjectFile::getPath().parent_path());
}
return paths;
}
std::vector<std::fs::path> getConfigPaths(bool includeSystemFolders) {
#if defined(OS_WINDOWS)
return getDataPaths(includeSystemFolders);
#elif defined(OS_MACOS)
return getDataPaths(includeSystemFolders);
#elif defined(OS_LINUX) || defined(OS_WEB)
std::ignore = includeSystemFolders;
return {xdg::ConfigHomeDir() / "imhex"};
#endif
}
static std::vector<std::fs::path> appendPath(std::vector<std::fs::path> paths, std::fs::path folder) {
folder.make_preferred();
for (auto &path : paths)
path = path / folder;
return paths;
}
static std::vector<std::fs::path> getPluginPaths() {
std::vector<std::fs::path> paths = getDataPaths(true);
// Add the system plugin directory to the path if one was provided at compile time
#if defined(OS_LINUX) && defined(SYSTEM_PLUGINS_LOCATION)
paths.push_back(SYSTEM_PLUGINS_LOCATION);
#endif
return paths;
}
namespace impl {
std::vector<std::fs::path> DefaultPath::read() const {
auto result = this->all();
std::erase_if(result, [](const auto &entryPath) {
return !wolv::io::fs::isDirectory(entryPath);
});
return result;
}
std::vector<std::fs::path> DefaultPath::write() const {
auto result = this->read();
std::erase_if(result, [](const auto &entryPath) {
return !hex::fs::isPathWritable(entryPath);
});
return result;
}
std::vector<std::fs::path> ConfigPath::all() const {
return appendPath(getConfigPaths(false), m_postfix);
}
std::vector<std::fs::path> DataPath::all() const {
return appendPath(getDataPaths(true), m_postfix);
}
std::vector<std::fs::path> DataPath::write() const {
auto result = appendPath(getDataPaths(false), m_postfix);
std::erase_if(result, [](const auto &entryPath) {
return !hex::fs::isPathWritable(entryPath);
});
return result;
}
std::vector<std::fs::path> PluginPath::all() const {
return appendPath(getPluginPaths(), m_postfix);
}
}
}

View File

@@ -23,6 +23,7 @@
#if defined(OS_WEB)
#include <emscripten.h>
#else
#include <GLFW/glfw3.h>
#include <nfd.hpp>
#endif
@@ -32,6 +33,9 @@
#include <wolv/io/fs.hpp>
#include <wolv/utils/string.hpp>
#include <fmt/format.h>
#include <fmt/xchar.h>
namespace hex::fs {
static AutoReset<std::function<void(const std::string&)>> s_fileBrowserErrorCallback;
@@ -47,13 +51,11 @@ namespace hex::fs {
}
#if defined(OS_WINDOWS)
hex::unused(
ShellExecute(nullptr, "open", wolv::util::toUTF8String(filePath).c_str(), nullptr, nullptr, SW_SHOWNORMAL)
);
std::ignore = ShellExecuteW(nullptr, L"open", filePath.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
#elif defined(OS_MACOS)
hex::unused(system(
std::ignore = system(
hex::format("open {}", wolv::util::toUTF8String(filePath)).c_str()
));
);
#elif defined(OS_LINUX)
executeCmd({"xdg-open", wolv::util::toUTF8String(filePath)});
#endif
@@ -66,13 +68,12 @@ namespace hex::fs {
}
#if defined(OS_WINDOWS)
hex::unused(system(
hex::format("explorer.exe {}", wolv::util::toUTF8String(dirPath)).c_str()
));
auto args = fmt::format(L"\"{}\"", dirPath.c_str());
ShellExecuteW(nullptr, L"open", L"explorer.exe", args.c_str(), nullptr, SW_SHOWNORMAL);
#elif defined(OS_MACOS)
hex::unused(system(
std::ignore = system(
hex::format("open {}", wolv::util::toUTF8String(dirPath)).c_str()
));
);
#elif defined(OS_LINUX)
executeCmd({"xdg-open", wolv::util::toUTF8String(dirPath)});
#endif
@@ -85,16 +86,15 @@ namespace hex::fs {
}
#if defined(OS_WINDOWS)
hex::unused(system(
hex::format(R"(explorer.exe /select,"{}")", wolv::util::toUTF8String(selectedFilePath)).c_str()
));
auto args = fmt::format(L"/select,\"{}\"", selectedFilePath.c_str());
ShellExecuteW(nullptr, L"open", L"explorer.exe", args.c_str(), nullptr, SW_SHOWNORMAL);
#elif defined(OS_MACOS)
hex::unused(system(
std::ignore = system(
hex::format(
R"(osascript -e 'tell application "Finder" to reveal POSIX file "{}"')",
wolv::util::toUTF8String(selectedFilePath)
).c_str()
));
);
system(R"(osascript -e 'tell application "Finder" to activate')");
#elif defined(OS_LINUX)
// Fallback to only opening the folder for now
@@ -123,7 +123,13 @@ namespace hex::fs {
// Call callback that will write the file
Module._fileBrowserCallback(stringToNewUTF8("/savedFiles/" + filename));
let data = FS.readFile("/savedFiles/" + filename);
let data;
try {
data = FS.readFile("/savedFiles/" + filename);
} catch (e) {
console.log(e);
return;
}
const reader = Object.assign(new FileReader(), {
onload: () => {
@@ -191,6 +197,7 @@ namespace hex::fs {
else if (!validExtensions.empty())
path = "file." + validExtensions[0].spec;
std::fs::create_directory("/savedFiles");
callJs_saveFile(path.filename().string().c_str());
break;
}
@@ -286,170 +293,6 @@ namespace hex::fs {
#endif
std::vector<std::fs::path> getDataPaths() {
std::vector<std::fs::path> paths;
#if defined(OS_WINDOWS)
// In the portable Windows version, we just use the executable directory
// Prevent the use of the AppData folder here
if (!ImHexApi::System::isPortableVersion()) {
PWSTR wAppDataPath = nullptr;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &wAppDataPath))) {
paths.emplace_back(wAppDataPath);
CoTaskMemFree(wAppDataPath);
}
}
#elif defined(OS_MACOS)
paths.push_back(wolv::io::fs::getApplicationSupportDirectoryPath());
#elif defined(OS_LINUX) || defined(OS_WEB)
paths.push_back(xdg::DataHomeDir());
auto dataDirs = xdg::DataDirs();
std::copy(dataDirs.begin(), dataDirs.end(), std::back_inserter(paths));
#endif
#if defined(OS_MACOS)
if (auto executablePath = wolv::io::fs::getExecutablePath(); executablePath.has_value())
paths.push_back(*executablePath);
#else
for (auto &path : paths)
path = path / "imhex";
if (auto executablePath = wolv::io::fs::getExecutablePath(); executablePath.has_value())
paths.push_back(executablePath->parent_path());
#endif
// Add additional data directories to the path
auto additionalDirs = ImHexApi::System::getAdditionalFolderPaths();
std::ranges::copy(additionalDirs, std::back_inserter(paths));
// Add the project file directory to the path, if one is loaded
if (ProjectFile::hasPath()) {
paths.push_back(ProjectFile::getPath().parent_path());
}
return paths;
}
static std::vector<std::fs::path> getConfigPaths() {
#if defined(OS_WINDOWS)
return getDataPaths();
#elif defined(OS_MACOS)
return getDataPaths();
#elif defined(OS_LINUX) || defined(OS_WEB)
return {xdg::ConfigHomeDir() / "imhex"};
#endif
}
std::vector<std::fs::path> appendPath(std::vector<std::fs::path> paths, const std::fs::path &folder) {
for (auto &path : paths)
path = path / folder;
return paths;
}
std::vector<std::fs::path> getPluginPaths() {
std::vector<std::fs::path> paths = getDataPaths();
// Add the system plugin directory to the path if one was provided at compile time
#if defined(OS_LINUX) && defined(SYSTEM_PLUGINS_LOCATION)
paths.push_back(SYSTEM_PLUGINS_LOCATION);
#endif
return paths;
}
std::vector<std::fs::path> getDefaultPaths(ImHexPath path, bool listNonExisting) {
std::vector<std::fs::path> result;
// Return the correct path based on the ImHexPath enum
switch (path) {
case ImHexPath::END:
return { };
case ImHexPath::Constants:
result = appendPath(getDataPaths(), "constants");
break;
case ImHexPath::Config:
result = appendPath(getConfigPaths(), "config");
break;
case ImHexPath::Backups:
result = appendPath(getDataPaths(), "backups");
break;
case ImHexPath::Encodings:
result = appendPath(getDataPaths(), "encodings");
break;
case ImHexPath::Logs:
result = appendPath(getDataPaths(), "logs");
break;
case ImHexPath::Plugins:
result = appendPath(getPluginPaths(), "plugins");
break;
case ImHexPath::Libraries:
result = appendPath(getPluginPaths(), "lib");
break;
case ImHexPath::Resources:
result = appendPath(getDataPaths(), "resources");
break;
case ImHexPath::Magic:
result = appendPath(getDataPaths(), "magic");
break;
case ImHexPath::Patterns:
result = appendPath(getDataPaths(), "patterns");
break;
case ImHexPath::PatternsInclude:
result = appendPath(getDataPaths(), "includes");
break;
case ImHexPath::Yara:
result = appendPath(getDataPaths(), "yara");
break;
case ImHexPath::YaraAdvancedAnalysis:
result = appendPath(getDefaultPaths(ImHexPath::Yara), "advanced_analysis");
break;
case ImHexPath::Recent:
result = appendPath(getConfigPaths(), "recent");
break;
case ImHexPath::Scripts:
result = appendPath(getDataPaths(), "scripts");
break;
case ImHexPath::Inspectors:
result = appendPath(getDefaultPaths(ImHexPath::Scripts), "inspectors");
break;
case ImHexPath::Nodes:
result = appendPath(getDefaultPaths(ImHexPath::Scripts), "nodes");
break;
case ImHexPath::Themes:
result = appendPath(getDataPaths(), "themes");
break;
case ImHexPath::Layouts:
result = appendPath(getDataPaths(), "layouts");
break;
case ImHexPath::Workspaces:
result = appendPath(getDataPaths(), "workspaces");
break;
}
// Remove all paths that don't exist if requested
if (!listNonExisting) {
std::erase_if(result, [](const auto &entryPath) {
return !wolv::io::fs::isDirectory(entryPath);
});
}
return result;
}
bool isPathWritable(const std::fs::path &path) {
constexpr static auto TestFileName = "__imhex__tmp__";

View File

@@ -41,17 +41,21 @@ namespace hex {
}
void HttpRequest::setProxyUrl(std::string proxy) {
hex::unused(proxy);
std::ignore = proxy;
}
void HttpRequest::setProxyState(bool state) {
hex::unused(state);
std::ignore = state;
}
void HttpRequest::checkProxyErrors() { }
int HttpRequest::progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow) {
hex::unused(contents, dlTotal, dlNow, ulTotal, ulNow);
std::ignore = contents;
std::ignore = dlTotal;
std::ignore = dlNow;
std::ignore = ulTotal;
std::ignore = ulNow;
return -1;
}
}

View File

@@ -0,0 +1,15 @@
#include <hex/api/event_manager.hpp>
#include <imgui.h>
#include <imgui_internal.h>
#include <array>
void ImGuiTestEngineHook_ItemAdd(ImGuiContext*, ImGuiID id, const ImRect& bb, const ImGuiLastItemData*) {
std::array<float, 4> boundingBox = { bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y };
hex::EventImGuiElementRendered::post(id, boundingBox);
}
void ImGuiTestEngineHook_ItemInfo(ImGuiContext*, ImGuiID, const char*, ImGuiItemStatusFlags) {}
void ImGuiTestEngineHook_Log(ImGuiContext*, const char*, ...) {}
const char* ImGuiTestEngine_FindItemDebugLabel(ImGuiContext*, ImGuiID) { return nullptr; }

View File

@@ -2,8 +2,10 @@
#include <hex/api/task_manager.hpp>
#include <hex/api/event_manager.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/default_paths.hpp>
#include <wolv/io/file.hpp>
@@ -80,7 +82,7 @@ namespace hex::log {
void redirectToFile() {
if (s_loggerFile.isValid()) return;
for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::Logs, true)) {
for (const auto &path : paths::Logs.all()) {
wolv::io::fs::createDirectories(path);
s_loggerFile = wolv::io::File(path / hex::format("{0:%Y%m%d_%H%M%S}.log", fmt::localtime(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()))), wolv::io::File::Mode::Create);
s_loggerFile.disableBuffering();
@@ -142,14 +144,12 @@ namespace hex::log {
fmt::print(dest, "{0}", std::string(projectNameLength > MaxTagLength ? 0 : MaxTagLength - projectNameLength, ' '));
}
void assertionHandler(bool expr, const char* exprString, const char* file, int line) {
if (!expr) {
log::error("Assertion failed: {} at {}:{}", exprString, file, line);
void assertionHandler(const char* exprString, const char* file, int line) {
log::error("Assertion failed: {} at {}:{}", exprString, file, line);
#if defined (DEBUG)
std::abort();
#endif
}
#if defined (DEBUG)
std::abort();
#endif
}
namespace color {

View File

@@ -3,6 +3,7 @@
#include <hex/helpers/utils.hpp>
#include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/default_paths.hpp>
#include <wolv/utils/guards.hpp>
#include <wolv/utils/string.hpp>
@@ -29,7 +30,7 @@ namespace hex::magic {
std::string magicFiles;
std::error_code error;
for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Magic)) {
for (const auto &dir : paths::Magic.read()) {
for (const auto &entry : std::fs::directory_iterator(dir, error)) {
auto path = std::fs::absolute(entry.path());
@@ -64,12 +65,12 @@ namespace hex::magic {
if (magicFiles->empty())
return true;
std::array<char, 1024> cwd = { 0x00 };
std::array<char, 1024> cwd = { };
if (getcwd(cwd.data(), cwd.size()) == nullptr)
return false;
std::optional<std::fs::path> magicFolder;
for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Magic)) {
for (const auto &dir : paths::Magic.write()) {
if (std::fs::exists(dir) && fs::isPathWritable(dir)) {
magicFolder = dir;
break;

View File

@@ -28,7 +28,9 @@ namespace hex {
void close() override { }
void readRaw(u64 offset, void *buffer, size_t size) override {
hex::unused(offset, buffer, size);
std::ignore = offset;
std::ignore = buffer;
std::ignore = size;
}
void writeRaw(u64 offset, const void *buffer, size_t size) override {
@@ -44,7 +46,7 @@ namespace hex {
}
void resizeRaw(u64 newSize) override {
hex::unused(newSize);
std::ignore = newSize;
}
void insertRaw(u64 offset, u64 size) override {

View File

@@ -0,0 +1,118 @@
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/semantic_version.hpp>
#include <wolv/utils/string.hpp>
namespace hex {
SemanticVersion::SemanticVersion(const char *version) : SemanticVersion(std::string(version)) {
}
SemanticVersion::SemanticVersion(std::string_view version) : SemanticVersion(std::string(version.begin(), version.end())) {
}
SemanticVersion::SemanticVersion(std::string version) {
if (version.empty())
return;
if (version.starts_with("v"))
version = version.substr(1);
m_parts = wolv::util::splitString(version, ".");
if (m_parts.size() != 3 && m_parts.size() != 4) {
m_parts.clear();
return;
}
if (m_parts.back().contains("-")) {
auto buildTypeParts = wolv::util::splitString(m_parts.back(), "-");
if (buildTypeParts.size() != 2) {
m_parts.clear();
return;
}
m_parts.back() = buildTypeParts[0];
m_buildType = buildTypeParts[1];
}
}
u32 SemanticVersion::major() const {
if (!isValid()) return 0;
try {
return std::stoul(m_parts[0]);
} catch (...) {
return 0;
}
}
u32 SemanticVersion::minor() const {
if (!isValid()) return 0;
try {
return std::stoul(m_parts[1]);
} catch (...) {
return 0;
}
}
u32 SemanticVersion::patch() const {
if (!isValid()) return 0;
try {
return std::stoul(m_parts[2]);
} catch (...) {
return 0;
}
}
bool SemanticVersion::nightly() const {
if (!isValid()) return false;
return m_parts.size() == 4 && m_parts[3] == "WIP";
}
const std::string& SemanticVersion::buildType() const {
return m_buildType;
}
bool SemanticVersion::isValid() const {
return !m_parts.empty();
}
bool SemanticVersion::operator==(const SemanticVersion& other) const {
return this->m_parts == other.m_parts;
}
std::strong_ordering SemanticVersion::operator<=>(const SemanticVersion &other) const {
if (*this == other)
return std::strong_ordering::equivalent;
if (this->major() > other.major())
return std::strong_ordering::greater;
if (this->minor() > other.minor())
return std::strong_ordering::greater;
if (this->patch() > other.patch())
return std::strong_ordering::greater;
if (!this->nightly() && other.nightly())
return std::strong_ordering::greater;
return std::strong_ordering::less;
}
std::string SemanticVersion::get(bool withBuildType) const {
if (!isValid()) return "";
auto result = wolv::util::combineStrings(m_parts, ".");
if (withBuildType && !m_buildType.empty())
result += hex::format("-{}", m_buildType);
return result;
}
}

View File

@@ -336,13 +336,13 @@ namespace hex {
void startProgram(const std::string &command) {
#if defined(OS_WINDOWS)
hex::unused(system(hex::format("start {0}", command).c_str()));
std::ignore = system(hex::format("start {0}", command).c_str());
#elif defined(OS_MACOS)
hex::unused(system(hex::format("open {0}", command).c_str()));
std::ignore = system(hex::format("open {0}", command).c_str());
#elif defined(OS_LINUX)
executeCmd({"xdg-open", command});
#elif defined(OS_WEB)
hex::unused(command);
std::ignore = command;
#endif
}
@@ -355,7 +355,7 @@ namespace hex {
url = "https://" + url;
#if defined(OS_WINDOWS)
ShellExecute(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
ShellExecuteA(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
#elif defined(OS_MACOS)
openWebpageMacos(url.c_str());
#elif defined(OS_LINUX)
@@ -679,6 +679,44 @@ namespace hex {
return value;
}
[[nodiscard]] std::string limitStringLength(const std::string &string, size_t maxLength) {
// If the string is shorter than the max length, return it as is
if (string.size() < maxLength)
return string;
// If the string is longer than the max length, find the last space before the max length
auto it = string.begin() + maxLength;
while (it != string.begin() && !std::isspace(*it)) --it;
// If there's no space before the max length, just cut the string
if (it == string.begin()) {
it = string.begin() + maxLength / 2;
// Try to find a UTF-8 character boundary
while (it != string.begin() && (*it & 0xC0) == 0x80) --it;
}
// If we still didn't find a valid boundary, just return the string as is
if (it == string.begin())
return string;
auto result = std::string(string.begin(), it) + "";
// If the string is longer than the max length, find the last space before the max length
it = string.end() - 1 - maxLength / 2;
while (it != string.end() && !std::isspace(*it)) ++it;
// If there's no space before the max length, just cut the string
if (it == string.end()) {
it = string.end() - 1 - maxLength / 2;
// Try to find a UTF-8 character boundary
while (it != string.end() && (*it & 0xC0) == 0x80) ++it;
}
return result + std::string(it, string.end());
}
static std::optional<std::fs::path> s_fileToOpen;
extern "C" void openFile(const char *path) {
log::info("Opening file: {0}", path);
@@ -801,7 +839,7 @@ namespace hex {
return dlopen(info.dli_fname, RTLD_LAZY);
#else
hex::unused(symbol);
std::ignore = symbol;
return nullptr;
#endif
}

View File

@@ -118,6 +118,12 @@
return cocoaWindow.inLiveResize;
}
void macosMarkContentEdited(GLFWwindow *window, bool edited) {
NSWindow* cocoaWindow = glfwGetCocoaWindow(window);
[cocoaWindow setDocumentEdited:edited];
}
@interface HexDocument : NSDocument
@end

View File

@@ -104,7 +104,8 @@ namespace hex::prv {
void Provider::insertRaw(u64 offset, u64 size) {
auto oldSize = this->getActualSize();
this->resizeRaw(oldSize + size);
auto newSize = oldSize + size;
this->resizeRaw(newSize);
std::vector<u8> buffer(0x1000);
const std::vector<u8> zeroBuffer(0x1000);
@@ -116,7 +117,7 @@ namespace hex::prv {
position -= readSize;
this->readRaw(position, buffer.data(), readSize);
this->writeRaw(position, zeroBuffer.data(), readSize);
this->writeRaw(position, zeroBuffer.data(), newSize - oldSize);
this->writeRaw(position + size, buffer.data(), readSize);
}
}

View File

@@ -20,6 +20,7 @@ namespace hex::subcommands {
}
}
}
return std::nullopt;
}
@@ -27,7 +28,8 @@ namespace hex::subcommands {
// If no arguments, do not even try to process arguments
// (important because this function will exit ImHex if an instance is already opened,
// and we don't want that if no arguments were provided)
if (args.empty()) return;
if (args.empty())
return;
std::vector<std::pair<SubCommand, std::vector<std::string>>> subCommands;
@@ -76,18 +78,18 @@ namespace hex::subcommands {
}
// Save last command to run
if (currentSubCommand) {
if (currentSubCommand.has_value()) {
subCommands.emplace_back(*currentSubCommand, currentSubCommandArgs);
}
// Run the subcommands
for (auto& subCommandPair : subCommands) {
subCommandPair.first.callback(subCommandPair.second);
for (auto &[subcommand, args] : subCommands) {
subcommand.callback(args);
}
// Exit the process if its not the main instance (the commands have been forwarded to another instance)
// Exit the process if it's not the main instance (the commands have been forwarded to another instance)
if (!ImHexApi::System::isMainInstance()) {
exit(0);
std::exit(0);
}
}
@@ -95,12 +97,15 @@ namespace hex::subcommands {
log::debug("Forwarding subcommand {} (maybe to us)", cmdName);
std::vector<u8> data;
for (const auto &arg: args) {
data.insert(data.end(), arg.begin(), arg.end());
data.push_back('\0');
if (!args.empty()) {
for (const auto &arg: args) {
data.insert(data.end(), arg.begin(), arg.end());
data.push_back('\0');
}
data.pop_back();
}
data.erase(data.end()-1);
SendMessageToMainInstance::post(hex::format("command/{}", cmdName), data);
}

View File

@@ -165,7 +165,7 @@ namespace ImGuiExt {
STBI_FREE(imageData);
result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture));
result.m_textureId = texture;
return result;
}
@@ -189,14 +189,14 @@ namespace ImGuiExt {
STBI_FREE(imageData);
result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture));
result.m_textureId = texture;
return result;
}
Texture Texture::fromGLTexture(unsigned int glTexture, int width, int height) {
Texture texture;
texture.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(glTexture));
texture.m_textureId = glTexture;
texture.m_width = width;
texture.m_height = height;
@@ -216,7 +216,7 @@ namespace ImGuiExt {
Texture result;
result.m_width = width;
result.m_height = height;
result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture));
result.m_textureId = texture;
return result;
}
@@ -230,7 +230,7 @@ namespace ImGuiExt {
Texture result;
result.m_width = bitmap.width();
result.m_height = bitmap.height();
result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture));
result.m_textureId = texture;
return result;
}
@@ -249,42 +249,46 @@ namespace ImGuiExt {
Texture result;
result.m_width = bitmap.width();
result.m_height = bitmap.height();
result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture));
result.m_textureId = texture;
return result;
}
Texture::Texture(Texture&& other) noexcept {
if (m_textureId != nullptr)
if (m_textureId != 0)
glDeleteTextures(1, reinterpret_cast<GLuint*>(&m_textureId));
m_textureId = other.m_textureId;
m_width = other.m_width;
m_height = other.m_height;
other.m_textureId = nullptr;
other.m_textureId = 0;
}
Texture& Texture::operator=(Texture&& other) noexcept {
if (m_textureId != nullptr)
if (m_textureId != 0)
glDeleteTextures(1, reinterpret_cast<GLuint*>(&m_textureId));
m_textureId = other.m_textureId;
m_width = other.m_width;
m_height = other.m_height;
other.m_textureId = nullptr;
other.m_textureId = 0;
return *this;
}
Texture::~Texture() {
if (m_textureId == nullptr)
if (m_textureId == 0)
return;
glDeleteTextures(1, reinterpret_cast<GLuint*>(&m_textureId));
}
float GetTextWrapPos() {
return GImGui->CurrentWindow->DC.TextWrapPos;
}
int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data) {
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) {
auto &string = *static_cast<std::string *>(data->UserData);
@@ -313,8 +317,6 @@ namespace ImGuiExt {
if (!ItemAdd(bb, id))
return false;
if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
@@ -346,8 +348,6 @@ namespace ImGuiExt {
const ImRect bb(pos, pos + size);
ItemAdd(bb, id);
if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
@@ -383,8 +383,6 @@ namespace ImGuiExt {
if (!ItemAdd(bb, id))
return false;
if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
@@ -421,8 +419,6 @@ namespace ImGuiExt {
if (!ItemAdd(bb, id))
return false;
if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
@@ -432,7 +428,7 @@ namespace ImGuiExt {
// Render
const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered
: ImGuiCustomCol_DescButton);
RenderNavHighlight(bb, id);
RenderNavCursor(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive));
RenderTextClipped(bb.Min + style.FramePadding * 2, bb.Max - style.FramePadding, label, nullptr, nullptr);
@@ -474,8 +470,6 @@ namespace ImGuiExt {
if (!ItemAdd(bb, id))
return false;
if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
@@ -485,7 +479,7 @@ namespace ImGuiExt {
// Render
const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered
: ImGuiCustomCol_DescButton);
RenderNavHighlight(bb, id);
RenderNavCursor(bb, id);
RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding);
PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive));
RenderTextClipped(bb.Min + style.FramePadding * 2, bb.Max - style.FramePadding, label, nullptr, nullptr);
@@ -514,15 +508,17 @@ namespace ImGuiExt {
PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0, 0, 0, 0));
PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0));
PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, GetStyle().FramePadding.y));
PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0F);
PushStyleColor(ImGuiCol_Text, iconColor);
ImGui::PushID(text);
Button(icon);
ImGui::PopID();
PopStyleColor();
if (IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
SetNextWindowSizeConstraints(ImVec2(GetTextLineHeight() * 25, 0), ImVec2(GetTextLineHeight() * 25, FLT_MAX));
SetNextWindowSizeConstraints(ImVec2(GetTextLineHeight() * 25, 0), ImVec2(GetTextLineHeight() * 35, FLT_MAX));
BeginTooltip();
TextFormattedWrapped("{}", text);
EndTooltip();
@@ -546,6 +542,34 @@ namespace ImGuiExt {
PopStyleColor();
}
void UnderwavedText(const char *label, ImColor textColor, ImColor lineColor, const ImVec2 &size_arg) {
ImGuiWindow *window = GetCurrentWindow();
std::string labelStr(label);
for (char letter : labelStr) {
std::string letterStr(1, letter);
const ImVec2 label_size = CalcTextSize(letterStr.c_str(), nullptr, true);
ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y);
ImVec2 pos = window->DC.CursorPos;
float lineWidth = size.x / 3.0f;
float halfLineW = lineWidth / 2.0f;
float lineY = pos.y + size.y;
ImVec2 initial = ImVec2(pos.x, lineY);
ImVec2 pos1 = ImVec2(pos.x + lineWidth, lineY - 2.0f);
ImVec2 pos2 = ImVec2(pos.x + lineWidth + halfLineW, lineY);
ImVec2 pos3 = ImVec2(pos.x + lineWidth * 2 + halfLineW, lineY - 2.0f);
ImVec2 pos4 = ImVec2(pos.x + lineWidth * 3, lineY - 1.0f);
PushStyleColor(ImGuiCol_Text, ImU32(textColor));
TextEx(letterStr.c_str(), nullptr, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting
GetWindowDrawList()->AddLine(initial, pos1, ImU32(lineColor),0.4f);
GetWindowDrawList()->AddLine(pos1, pos2, ImU32(lineColor),0.3f);
GetWindowDrawList()->AddLine(pos2, pos3, ImU32(lineColor),0.4f);
GetWindowDrawList()->AddLine(pos3, pos4, ImU32(lineColor),0.3f);
PopStyleColor();
window->DC.CursorPos = ImVec2(pos.x + size.x, pos.y);
}
}
void TextSpinner(const char *label) {
Text("[%c] %s", "|/-\\"[ImU32(GetTime() * 20) % 4], label);
}
@@ -571,15 +595,27 @@ namespace ImGuiExt {
ImGuiID hoveredID = GetHoveredID();
bool result = false;
if (IsItemHovered() && (currTime - lastMoveTime) >= 0.5 && hoveredID == lastHoveredID) {
if (IsItemHovered(ImGuiHoveredFlags_DelayNormal) && (currTime - lastMoveTime) >= 0.5 && hoveredID == lastHoveredID) {
if (!std::string_view(text).empty()) {
const auto width = 300 * hex::ImHexApi::System::getGlobalScale();
ImGui::SetNextWindowSizeConstraints(ImVec2(width, 0), ImVec2(width, FLT_MAX));
const auto textWidth = CalcTextSize(text).x;
const auto maxWidth = 300 * hex::ImHexApi::System::getGlobalScale();
const bool wrapping = textWidth > maxWidth;
if (wrapping)
ImGui::SetNextWindowSizeConstraints(ImVec2(maxWidth, 0), ImVec2(maxWidth, FLT_MAX));
else
ImGui::SetNextWindowSize(ImVec2(textWidth + GetStyle().WindowPadding.x * 2, 0));
if (BeginTooltip()) {
if (isSeparator)
SeparatorText(text);
else
TextFormattedWrapped("{}", text);
else {
if (wrapping)
TextFormattedWrapped("{}", text);
else
TextFormatted("{}", text);
}
EndTooltip();
}
@@ -726,7 +762,7 @@ namespace ImGuiExt {
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered
: ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderNavCursor(bb, id);
RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, nullptr, &label_size, style.ButtonTextAlign, &bb);
@@ -752,7 +788,9 @@ namespace ImGuiExt {
ImVec2 pos = window->DC.CursorPos;
ImVec2 size = CalcItemSize(ImVec2(1, 1) * GetCurrentWindow()->MenuBarHeight(), label_size.x + style.FramePadding.x * 2.0F, label_size.y + style.FramePadding.y * 2.0F);
ImVec2 size = CalcItemSize(ImVec2(1, 1) * GetCurrentWindow()->MenuBarHeight, label_size.x + style.FramePadding.x * 2.0F, label_size.y + style.FramePadding.y * 2.0F);
ImVec2 padding = (size - label_size) / 2;
const ImRect bb(pos, pos + size);
ItemSize(size, style.FramePadding.y);
@@ -767,9 +805,9 @@ namespace ImGuiExt {
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered
: ImGuiCol_MenuBarBg);
RenderNavHighlight(bb, id);
RenderNavCursor(bb, id);
RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, symbol, nullptr, &label_size, style.ButtonTextAlign, &bb);
RenderTextClipped(bb.Min + padding, bb.Max - padding, symbol, nullptr, &size, style.ButtonTextAlign, &bb);
PopStyleColor();
@@ -810,7 +848,7 @@ namespace ImGuiExt {
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered
: ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderNavCursor(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1.3, 1), bb.Max - style.FramePadding, symbol, nullptr, &label_size, style.ButtonTextAlign, &bb);
@@ -839,7 +877,7 @@ namespace ImGuiExt {
char buf[64];
DataTypeFormatString(buf, IM_ARRAYSIZE(buf), type, value, format);
RenderNavHighlight(frame_bb, id);
RenderNavCursor(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
PushStyleVar(ImGuiStyleVar_Alpha, 0.6F);
@@ -863,7 +901,7 @@ namespace ImGuiExt {
}
bool InputHexadecimal(const char *label, u32 *value, ImGuiInputTextFlags flags) {
return InputIntegerPrefix(label, "0x", value, ImGuiDataType_U32, "%lX", flags | ImGuiInputTextFlags_CharsHexadecimal);
return InputIntegerPrefix(label, "0x", value, ImGuiDataType_U32, "%X", flags | ImGuiInputTextFlags_CharsHexadecimal);
}
bool InputHexadecimal(const char *label, u64 *value, ImGuiInputTextFlags flags) {
@@ -933,11 +971,14 @@ namespace ImGuiExt {
}
bool InputTextIcon(const char *label, const char *icon, std::string &buffer, ImGuiInputTextFlags flags) {
return InputTextIconHint(label, icon, nullptr, buffer, flags);
}
bool InputTextIconHint(const char* label, const char *icon, const char *hint, std::string &buffer, ImGuiInputTextFlags flags) {
auto window = GetCurrentWindow();
const ImGuiID id = window->GetID(label);
const ImGuiStyle &style = GImGui->Style;
const ImVec2 label_size = CalcTextSize(label, nullptr, true);
const ImVec2 icon_frame_size = CalcTextSize(icon) + style.FramePadding * 2.0F;
const ImVec2 frame_size = CalcItemSize(ImVec2(0, 0), icon_frame_size.x, label_size.y + style.FramePadding.y * 2.0F);
@@ -945,12 +986,14 @@ namespace ImGuiExt {
SetCursorPosX(GetCursorPosX() + frame_size.x);
bool value_changed = InputTextEx(label, nullptr, buffer.data(), buffer.size() + 1, ImVec2(CalcItemWidth() - icon_frame_size.x, label_size.y + style.FramePadding.y * 2.0F), ImGuiInputTextFlags_CallbackResize | flags, UpdateStringSizeCallback, &buffer);
float width_adjustment = window->DC.ItemWidth < 0 ? 0 : icon_frame_size.x;
bool value_changed = InputTextEx(label, hint, buffer.data(), buffer.size() + 1, ImVec2(CalcItemWidth() - width_adjustment, label_size.y + style.FramePadding.y * 2.0F), ImGuiInputTextFlags_CallbackResize | flags, UpdateStringSizeCallback, &buffer);
if (value_changed)
MarkItemEdited(GImGui->LastItemData.ID);
RenderNavHighlight(frame_bb, id);
RenderNavCursor(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
RenderFrame(frame_bb.Min, frame_bb.Min + icon_frame_size, GetColorU32(ImGuiCol_TableBorderStrong), true, style.FrameRounding);
@@ -976,7 +1019,6 @@ namespace ImGuiExt {
if ((flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0)
flags |= ImGuiInputTextFlags_CharsDecimal;
flags |= ImGuiInputTextFlags_AutoSelectAll;
flags |= ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselves by comparing the actual data rather than the string.
if (ImGui::InputText(label, buf, IM_ARRAYSIZE(buf), flags, callback, user_data))
value_changed = DataTypeApplyFromText(buf, data_type, p_data, format);
@@ -1026,7 +1068,7 @@ namespace ImGuiExt {
}
const ImRect check_bb(pos, pos + size);
RenderNavHighlight(total_bb, id);
RenderNavCursor(total_bb, id);
RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
RenderText(check_bb.Min + style.FramePadding, *v ? "1" : "0");
@@ -1129,17 +1171,19 @@ namespace ImGuiExt {
return toggled;
}
void TextOverlay(const char *text, ImVec2 pos) {
const auto textSize = CalcTextSize(text);
void TextOverlay(const char *text, ImVec2 pos, float maxWidth) {
const auto textSize = CalcTextSize(text, nullptr, false, maxWidth);
const auto textPos = pos - textSize / 2;
const auto margin = GetStyle().FramePadding * 2;
const auto textRect = ImRect(textPos - margin, textPos + textSize + margin);
auto drawList = GetForegroundDrawList();
auto drawList = GetWindowDrawList();
drawList->AddDrawCmd();
drawList->AddRectFilled(textRect.Min, textRect.Max, GetColorU32(ImGuiCol_WindowBg) | 0xFF000000);
drawList->AddRect(textRect.Min, textRect.Max, GetColorU32(ImGuiCol_Border));
drawList->AddText(textPos, GetColorU32(ImGuiCol_Text), text);
drawList->AddDrawCmd();
drawList->AddText(nullptr, 0.0F, textPos, GetColorU32(ImGuiCol_Text), text, nullptr, maxWidth);
}
bool BeginBox() {
@@ -1156,17 +1200,37 @@ namespace ImGuiExt {
PopStyleVar();
}
void BeginSubWindow(const char *label, ImVec2 size, ImGuiChildFlags flags) {
bool BeginSubWindow(const char *label, bool *collapsed, ImVec2 size, ImGuiChildFlags flags) {
const bool hasMenuBar = !std::string_view(label).empty();
bool result = false;
ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0F);
if (ImGui::BeginChild(hex::format("{}##SubWindow", label).c_str(), size, ImGuiChildFlags_Border | ImGuiChildFlags_AutoResizeY | flags, hasMenuBar ? ImGuiWindowFlags_MenuBar : ImGuiWindowFlags_None)) {
if (ImGui::BeginChild(hex::format("{}##SubWindow", label).c_str(), size, ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY | flags, hasMenuBar ? ImGuiWindowFlags_MenuBar : ImGuiWindowFlags_None)) {
result = true;
if (hasMenuBar && ImGui::BeginMenuBar()) {
ImGui::TextUnformatted(label);
if (collapsed == nullptr)
ImGui::TextUnformatted(label);
else {
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, ImGui::GetStyle().FramePadding.y));
ImGui::PushStyleColor(ImGuiCol_Button, 0x00);
if (ImGui::Button(label))
*collapsed = !*collapsed;
ImGui::PopStyleColor();
ImGui::PopStyleVar();
}
ImGui::EndMenuBar();
}
if (collapsed != nullptr && *collapsed) {
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - (ImGui::GetStyle().FramePadding.y * 2));
ImGuiExt::TextFormattedDisabled("...");
result = false;
}
}
ImGui::PopStyleVar();
return result;
}
void EndSubWindow() {

View File

@@ -71,7 +71,7 @@ namespace hex {
}
std::string View::toWindowName(const UnlocalizedString &unlocalizedName) {
return Lang(unlocalizedName) + "###" + unlocalizedName.get();
return fmt::format("{}###{}", Lang(unlocalizedName), unlocalizedName.get());
}
}

3
lib/third_party/boost/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,3 @@
project(boost)
add_subdirectory(regex)

View File

@@ -0,0 +1,10 @@
project(boost-regex)
add_library(boost-regex INTERFACE)
target_include_directories(boost-regex INTERFACE
include
)
target_compile_definitions(boost-regex INTERFACE BOOST_REGEX_STANDALONE)
add_library(boost::regex ALIAS boost-regex)

Some files were not shown because too many files have changed in this diff Show More