Skip to content

Commit c4f0bf5

Browse files
committedOct 13, 2022
Opening commit
0 parents  commit c4f0bf5

File tree

16 files changed

+993
-0
lines changed

16 files changed

+993
-0
lines changed
 

‎.github/workflows/compile_bins.yml

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
2+
name: Compile binaries for the current release
3+
on:
4+
release:
5+
types: [published]
6+
workflow_dispatch:
7+
8+
jobs:
9+
Linux-MacOS-build:
10+
strategy:
11+
fail-fast: false
12+
matrix:
13+
os: [ubuntu-latest, macos-latest]
14+
15+
runs-on: ${{matrix.os}}
16+
steps:
17+
- uses: actions/checkout@v3
18+
- name: Add LLVM to path [${{ matrix.os }}]
19+
if: runner.os == 'macOS'
20+
run: |
21+
echo $(brew --prefix llvm)*/bin >> $GITHUB_PATH
22+
23+
- name: Delete Icon.o from package.yaml
24+
run: |
25+
sed '/- src\/Icon\.o/d' ./package.yaml > temp && mv temp ./package.yaml
26+
27+
- name: Build i386
28+
if: runner.os == 'macOS'
29+
run: |
30+
stack build --local-bin-path=bin --copy-bins --arch i386
31+
mv bin/binary-exe "bin/$(echo '${{github.repository}}' | rev | cut -d '/' -f 1 | rev)-${{runner.os}}-x86"
32+
33+
- name: Build x86_64
34+
run: |
35+
stack build --local-bin-path=bin --copy-bins --arch x86_64
36+
mv bin/binary-exe "bin/$(echo '${{github.repository}}' | rev | cut -d '/' -f 1 | rev)-${{runner.os}}-x86_64"
37+
38+
- name: Build summary
39+
run: ls bin
40+
41+
- name: Add Linux|MacOS binary to release
42+
uses: softprops/action-gh-release@v1
43+
if: startsWith(github.ref, 'refs/tags/')
44+
with:
45+
files: bin/*
46+
47+
- name: Job summary
48+
run: |
49+
echo "### ✔ Build ${{runner.os}}" >> $GITHUB_STEP_SUMMARY
50+
51+
52+
53+
Windows-build:
54+
runs-on: windows-latest
55+
56+
env:
57+
BACKEND_ROOT: 'llvm_backend'
58+
LLVM_ZIP_NAME: 'llvm_zip.7z'
59+
LLVM_ROOT_NAME: 'llvm'
60+
CLANG_ZIP_NAME: 'clang_zip.7z'
61+
CLANG_ROOT_NAME: 'clang'
62+
63+
steps:
64+
- uses: actions/checkout@v3
65+
66+
- name: Downloading LLVM Windows binary
67+
uses: dsaltares/fetch-gh-release-asset@1.0.0
68+
with:
69+
repo: 'vovkos/llvm-package-windows'
70+
version: 'tags/llvm-12.0.1'
71+
file: 'llvm-12.0.1-windows-amd64-msvc15-msvcrt.7z'
72+
target: '${{env.BACKEND_ROOT}}/${{env.LLVM_ZIP_NAME}}'
73+
74+
- name: Extract LLVM
75+
run: |
76+
7z x -y ${{env.BACKEND_ROOT}}/llvm* -o${{env.BACKEND_ROOT}}/
77+
Get-ChildItem ${{env.BACKEND_ROOT}}/llvm-* | Rename-Item -NewName "${{env.LLVM_ROOT_NAME}}"
78+
echo "${{env.LLVM_ROOT}}" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
79+
env:
80+
LLVM_ROOT: "$pwd/${{env.BACKEND_ROOT}}/${{env.LLVM_ROOT_NAME}}/bin"
81+
82+
83+
- name: Exctraction summary
84+
run: |
85+
ls $pwd/${{env.BACKEND_ROOT}}/${{env.LLVM_ROOT_NAME}}/bin/llc*
86+
87+
echo ("LLVM llc exist: " + ((Get-Command "llc" -ErrorAction SilentlyContinue) -ne $null))
88+
echo ("LLVM clang(preinstalled) exist: " + ((Get-Command "clang" -ErrorAction SilentlyContinue) -ne $null))
89+
(&{If((Get-Command "llc" -ErrorAction SilentlyContinue) -eq $null -or (Get-Command "clang" -ErrorAction SilentlyContinue) -eq $null) {exit 1}})
90+
91+
- name: Build binary
92+
run: |
93+
stack build --local-bin-path=bin --copy-bins
94+
ls bin
95+
96+
- name: Rename binary to platform specific name
97+
run: Get-ChildItem bin/binary-exe* | Rename-Item -NewName ("${{github.repository}}".Split("/")[-1] + "-win-amd64.exe")
98+
99+
- name: Add Windows binary to release
100+
uses: softprops/action-gh-release@v1
101+
if: startsWith(github.ref, 'refs/tags/')
102+
with:
103+
files: bin/*
104+
105+
106+
- name: Job summary
107+
run: |
108+
echo "### ✔ Build ${{runner.os}}" >> $GITHUB_STEP_SUMMARY

‎.gitignore

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
*~
2+
dist
3+
dist-*
4+
cabal-dev
5+
*.o
6+
*.hi
7+
*.hie
8+
*.chi
9+
*.chs.h
10+
*.dyn_o
11+
*.dyn_hi
12+
.hpc
13+
.hsenv
14+
.cabal-sandbox/
15+
cabal.sandbox.config
16+
*.prof
17+
*.aux
18+
*.hp
19+
*.eventlog
20+
.stack-work/
21+
cabal.project.local
22+
cabal.project.local~
23+
.HTF/
24+
.ghc.environment.*
25+
/*.png
26+
/bin

‎CHANGELOG.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Changelog for `hsDummyImage`
2+
3+
All notable changes to this project will be documented in this file.
4+
5+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6+
and this project adheres to the
7+
[Haskell Package Versioning Policy](https://pvp.haskell.org/).
8+
9+
## Unreleased
10+
11+
## 0.1.0 - 2022-10-07
12+
### Added
13+
- Main functionality to generate PNG dummies
14+
- Basic generator functions => {stains | fastest_mono | alt_stains | matrix | cold_grid | high_crosswalk}

‎LICENSE

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
Apache License
2+
Version 2.0, January 2004
3+
http://www.apache.org/licenses/
4+
5+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+
1. Definitions.
8+
9+
"License" shall mean the terms and conditions for use, reproduction,
10+
and distribution as defined by Sections 1 through 9 of this document.
11+
12+
"Licensor" shall mean the copyright owner or entity authorized by
13+
the copyright owner that is granting the License.
14+
15+
"Legal Entity" shall mean the union of the acting entity and all
16+
other entities that control, are controlled by, or are under common
17+
control with that entity. For the purposes of this definition,
18+
"control" means (i) the power, direct or indirect, to cause the
19+
direction or management of such entity, whether by contract or
20+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
21+
outstanding shares, or (iii) beneficial ownership of such entity.
22+
23+
"You" (or "Your") shall mean an individual or Legal Entity
24+
exercising permissions granted by this License.
25+
26+
"Source" form shall mean the preferred form for making modifications,
27+
including but not limited to software source code, documentation
28+
source, and configuration files.
29+
30+
"Object" form shall mean any form resulting from mechanical
31+
transformation or translation of a Source form, including but
32+
not limited to compiled object code, generated documentation,
33+
and conversions to other media types.
34+
35+
"Work" shall mean the work of authorship, whether in Source or
36+
Object form, made available under the License, as indicated by a
37+
copyright notice that is included in or attached to the work
38+
(an example is provided in the Appendix below).
39+
40+
"Derivative Works" shall mean any work, whether in Source or Object
41+
form, that is based on (or derived from) the Work and for which the
42+
editorial revisions, annotations, elaborations, or other modifications
43+
represent, as a whole, an original work of authorship. For the purposes
44+
of this License, Derivative Works shall not include works that remain
45+
separable from, or merely link (or bind by name) to the interfaces of,
46+
the Work and Derivative Works thereof.
47+
48+
"Contribution" shall mean any work of authorship, including
49+
the original version of the Work and any modifications or additions
50+
to that Work or Derivative Works thereof, that is intentionally
51+
submitted to Licensor for inclusion in the Work by the copyright owner
52+
or by an individual or Legal Entity authorized to submit on behalf of
53+
the copyright owner. For the purposes of this definition, "submitted"
54+
means any form of electronic, verbal, or written communication sent
55+
to the Licensor or its representatives, including but not limited to
56+
communication on electronic mailing lists, source code control systems,
57+
and issue tracking systems that are managed by, or on behalf of, the
58+
Licensor for the purpose of discussing and improving the Work, but
59+
excluding communication that is conspicuously marked or otherwise
60+
designated in writing by the copyright owner as "Not a Contribution."
61+
62+
"Contributor" shall mean Licensor and any individual or Legal Entity
63+
on behalf of whom a Contribution has been received by Licensor and
64+
subsequently incorporated within the Work.
65+
66+
2. Grant of Copyright License. Subject to the terms and conditions of
67+
this License, each Contributor hereby grants to You a perpetual,
68+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69+
copyright license to reproduce, prepare Derivative Works of,
70+
publicly display, publicly perform, sublicense, and distribute the
71+
Work and such Derivative Works in Source or Object form.
72+
73+
3. Grant of Patent License. Subject to the terms and conditions of
74+
this License, each Contributor hereby grants to You a perpetual,
75+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76+
(except as stated in this section) patent license to make, have made,
77+
use, offer to sell, sell, import, and otherwise transfer the Work,
78+
where such license applies only to those patent claims licensable
79+
by such Contributor that are necessarily infringed by their
80+
Contribution(s) alone or by combination of their Contribution(s)
81+
with the Work to which such Contribution(s) was submitted. If You
82+
institute patent litigation against any entity (including a
83+
cross-claim or counterclaim in a lawsuit) alleging that the Work
84+
or a Contribution incorporated within the Work constitutes direct
85+
or contributory patent infringement, then any patent licenses
86+
granted to You under this License for that Work shall terminate
87+
as of the date such litigation is filed.
88+
89+
4. Redistribution. You may reproduce and distribute copies of the
90+
Work or Derivative Works thereof in any medium, with or without
91+
modifications, and in Source or Object form, provided that You
92+
meet the following conditions:
93+
94+
(a) You must give any other recipients of the Work or
95+
Derivative Works a copy of this License; and
96+
97+
(b) You must cause any modified files to carry prominent notices
98+
stating that You changed the files; and
99+
100+
(c) You must retain, in the Source form of any Derivative Works
101+
that You distribute, all copyright, patent, trademark, and
102+
attribution notices from the Source form of the Work,
103+
excluding those notices that do not pertain to any part of
104+
the Derivative Works; and
105+
106+
(d) If the Work includes a "NOTICE" text file as part of its
107+
distribution, then any Derivative Works that You distribute must
108+
include a readable copy of the attribution notices contained
109+
within such NOTICE file, excluding those notices that do not
110+
pertain to any part of the Derivative Works, in at least one
111+
of the following places: within a NOTICE text file distributed
112+
as part of the Derivative Works; within the Source form or
113+
documentation, if provided along with the Derivative Works; or,
114+
within a display generated by the Derivative Works, if and
115+
wherever such third-party notices normally appear. The contents
116+
of the NOTICE file are for informational purposes only and
117+
do not modify the License. You may add Your own attribution
118+
notices within Derivative Works that You distribute, alongside
119+
or as an addendum to the NOTICE text from the Work, provided
120+
that such additional attribution notices cannot be construed
121+
as modifying the License.
122+
123+
You may add Your own copyright statement to Your modifications and
124+
may provide additional or different license terms and conditions
125+
for use, reproduction, or distribution of Your modifications, or
126+
for any such Derivative Works as a whole, provided Your use,
127+
reproduction, and distribution of the Work otherwise complies with
128+
the conditions stated in this License.
129+
130+
5. Submission of Contributions. Unless You explicitly state otherwise,
131+
any Contribution intentionally submitted for inclusion in the Work
132+
by You to the Licensor shall be under the terms and conditions of
133+
this License, without any additional terms or conditions.
134+
Notwithstanding the above, nothing herein shall supersede or modify
135+
the terms of any separate license agreement you may have executed
136+
with Licensor regarding such Contributions.
137+
138+
6. Trademarks. This License does not grant permission to use the trade
139+
names, trademarks, service marks, or product names of the Licensor,
140+
except as required for reasonable and customary use in describing the
141+
origin of the Work and reproducing the content of the NOTICE file.
142+
143+
7. Disclaimer of Warranty. Unless required by applicable law or
144+
agreed to in writing, Licensor provides the Work (and each
145+
Contributor provides its Contributions) on an "AS IS" BASIS,
146+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147+
implied, including, without limitation, any warranties or conditions
148+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149+
PARTICULAR PURPOSE. You are solely responsible for determining the
150+
appropriateness of using or redistributing the Work and assume any
151+
risks associated with Your exercise of permissions under this License.
152+
153+
8. Limitation of Liability. In no event and under no legal theory,
154+
whether in tort (including negligence), contract, or otherwise,
155+
unless required by applicable law (such as deliberate and grossly
156+
negligent acts) or agreed to in writing, shall any Contributor be
157+
liable to You for damages, including any direct, indirect, special,
158+
incidental, or consequential damages of any character arising as a
159+
result of this License or out of the use or inability to use the
160+
Work (including but not limited to damages for loss of goodwill,
161+
work stoppage, computer failure or malfunction, or any and all
162+
other commercial damages or losses), even if such Contributor
163+
has been advised of the possibility of such damages.
164+
165+
9. Accepting Warranty or Additional Liability. While redistributing
166+
the Work or Derivative Works thereof, You may choose to offer,
167+
and charge a fee for, acceptance of support, warranty, indemnity,
168+
or other liability obligations and/or rights consistent with this
169+
License. However, in accepting such obligations, You may act only
170+
on Your own behalf and on Your sole responsibility, not on behalf
171+
of any other Contributor, and only if You agree to indemnify,
172+
defend, and hold each Contributor harmless for any liability
173+
incurred by, or claims asserted against, such Contributor by reason
174+
of your accepting any such warranty or additional liability.
175+
176+
END OF TERMS AND CONDITIONS
177+
178+
APPENDIX: How to apply the Apache License to your work.
179+
180+
To apply the Apache License to your work, attach the following
181+
boilerplate notice, with the fields enclosed by brackets "[]"
182+
replaced with your own identifying information. (Don't include
183+
the brackets!) The text should be enclosed in the appropriate
184+
comment syntax for the file format. We also recommend that a
185+
file or class name and description of purpose be included on the
186+
same "printed page" as the copyright notice for easier
187+
identification within third-party archives.
188+
189+
Copyright 2022 S0D3S
190+
191+
Licensed under the Apache License, Version 2.0 (the "License");
192+
you may not use this file except in compliance with the License.
193+
You may obtain a copy of the License at
194+
195+
http://www.apache.org/licenses/LICENSE-2.0
196+
197+
Unless required by applicable law or agreed to in writing, software
198+
distributed under the License is distributed on an "AS IS" BASIS,
199+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200+
See the License for the specific language governing permissions and
201+
limitations under the License.

‎README.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<div align="center">
2+
3+
![hsDummyImage logo](assets/readme_logo.png)
4+
5+
# hsDummmyImage
6+
7+
8+
9+
### Generate image with target size for testing & more!
10+
11+
</div>
12+
13+
<summary><h2 style="display: inline-block;">🌟 About</h2></summary>
14+
15+
This is a small utility written in Haskell for generating images with a certain size.<br>
16+
Developed for the needs of testing.<br>
17+
It was originally written in Python.
18+
19+
<summary><h2 style="display: inline-block;">⚡ Futures</h2></summary>
20+
21+
* Generate PNG images with target size
22+
* Parallel processing
23+
* Scaling images (same images with deferent sizes)
24+
25+
> If you need more formats -> open an Issue <br>
26+
> Have interesting ideas for generator functions -> welcome to PR!
27+
28+
<summary><h2 style="display: inline-block;">💻 Usage</h2></summary>
29+
30+
Go to [release page](https://github.com/DummyFiles/hsDummyImage/releases) and get binary for your platform
31+
32+
```
33+
hsDummyImage - tool for generating images with target file size
34+
35+
Usage: hsDummyImage* [-s|--size SIZE] [-u|--units {b, kb, mb, gb}]
36+
[-o|--output NAME] [-d|--output-dir PATH]
37+
[-f|--gen-func GEN_FUNC] [--dump-func-list]
38+
39+
Available options:
40+
-s,--size SIZE Target size for dummy in UNITS (default: 100)
41+
-u,--units {b, kb, mb, gb}
42+
One of {b, kb, mb, gb} (default: "kb")
43+
-o,--output NAME ⁽¹⁾Output name (default: "dummy_%v_%v.png")
44+
-d,--output-dir PATH Output dir (default: "./")
45+
-f,--gen-func GEN_FUNC The function to generate. Available -> {stains |
46+
fastest_mono | alt_stains | matrix | cold_grid |
47+
high_crosswalk} (default: "stains")
48+
--dump-func-list List available functions and exit
49+
-h,--help Show this help text
50+
51+
For example:
52+
> hsDummyImage.exe -s 204 -u mb -f matrix
53+
```
54+
\[1] The output name can contain either exactly two placeholders (%v) or none. The placeholders will be replaced by the size and units of measurement, respectively.

‎Setup.hs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import Distribution.Simple
2+
main = defaultMain

‎app/Main.hs

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
module Main (main) where
2+
3+
import Lib (
4+
handleArgsAndGenPng,
5+
defaultDummyName,
6+
availableGenFunctions,
7+
availableGenFunctionsStr,
8+
availableUnitsStr
9+
)
10+
11+
import Options.Applicative
12+
13+
14+
data DummyArgs = DummyArgs
15+
{ _size :: Int
16+
, _units :: String
17+
, _output :: String
18+
, _output_dir :: String
19+
, _gen_func :: String
20+
, _dump_func_list :: Bool }
21+
22+
23+
dArgs :: Parser DummyArgs
24+
dArgs = DummyArgs
25+
<$> option auto
26+
( long "size"
27+
<> short 's'
28+
<> metavar "SIZE"
29+
<> showDefault
30+
<> value 100
31+
<> help "Target size for dummy in UNITS" )
32+
<*> strOption
33+
( long "units"
34+
<> short 'u'
35+
<> metavar availableUnitsStr
36+
<> help ("One of " ++ availableUnitsStr)
37+
<> showDefault
38+
<> value "kb" )
39+
<*> strOption
40+
( long "output"
41+
<> short 'o'
42+
<> help "Output name"
43+
<> showDefault
44+
<> value defaultDummyName
45+
<> metavar "NAME" )
46+
<*> strOption
47+
( long "output-dir"
48+
<> short 'd'
49+
<> help "Output dir"
50+
<> showDefault
51+
<> value "./"
52+
<> metavar "PATH" )
53+
<*> strOption
54+
( long "gen-func"
55+
<> short 'f'
56+
<> help ("The function to generate. Available -> "++availableGenFunctionsStr)
57+
<> showDefault
58+
<> value (fst (head availableGenFunctions))
59+
<> metavar "GEN_FUNC" )
60+
<*> switch
61+
( long "dump-func-list"
62+
<> help "List available functions and exit")
63+
64+
main :: IO ()
65+
main = checkAndRun =<< execParser opts
66+
where
67+
opts = info (dArgs <**> helper)
68+
( fullDesc
69+
<> header "hsDummyImage - tool for generating images with target file size" )
70+
71+
checkAndRun :: DummyArgs -> IO ()
72+
checkAndRun (DummyArgs tSize tUnits tName tDir tFunc dump_func_l)
73+
| dump_func_l = putStr availableGenFunctionsStr
74+
| otherwise = handleArgsAndGenPng tSize tUnits tName tDir tFunc

‎assets/favicon.ico

13.3 KB
Binary file not shown.

‎assets/readme_logo.png

23.7 KB
Loading

‎hsDummyImage.cabal

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
cabal-version: 1.12
2+
3+
-- This file has been generated from package.yaml by hpack version 0.34.4.
4+
--
5+
-- see: https://github.com/sol/hpack
6+
7+
name: hsDummyImage
8+
version: 0.9.0
9+
description: Please see the README on GitHub at <https://github.com/DummyFiles/hsDummyImage#readme>
10+
homepage: https://github.com/DummyFiles/hsDummyImage#readme
11+
bug-reports: https://github.com/DummyFiles/hsDummyImage/issues
12+
author: S0D3S
13+
maintainer: S0D3S
14+
copyright: 2022 S0D3S
15+
license: Apache-2.0
16+
license-file: LICENSE
17+
build-type: Simple
18+
extra-source-files:
19+
README.md
20+
CHANGELOG.md
21+
22+
source-repository head
23+
type: git
24+
location: https://github.com/DummyFiles/hsDummyImage
25+
26+
library
27+
exposed-modules:
28+
JPHack
29+
Lib
30+
other-modules:
31+
Paths_hsDummyImage
32+
hs-source-dirs:
33+
src
34+
ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints src/Icon.o
35+
build-depends:
36+
JuicyPixels
37+
, base >=4.7 && <5
38+
, binary
39+
, bytestring
40+
, filepath
41+
, optparse-applicative
42+
, repa
43+
, vector
44+
, zlib
45+
default-language: Haskell2010
46+
47+
executable binary-exe
48+
main-is: Main.hs
49+
other-modules:
50+
Paths_hsDummyImage
51+
hs-source-dirs:
52+
app
53+
ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints src/Icon.o -threaded -rtsopts "-with-rtsopts=-N -T" -fllvm -O2 -optlo-O3
54+
build-depends:
55+
JuicyPixels
56+
, base >=4.7 && <5
57+
, binary
58+
, bytestring
59+
, filepath
60+
, hsDummyImage
61+
, optparse-applicative
62+
, repa
63+
, vector
64+
, zlib
65+
default-language: Haskell2010
66+
67+
test-suite hsDummyImage-test
68+
type: exitcode-stdio-1.0
69+
main-is: Spec.hs
70+
other-modules:
71+
Paths_hsDummyImage
72+
hs-source-dirs:
73+
test
74+
ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints src/Icon.o -threaded -rtsopts -with-rtsopts=-N
75+
build-depends:
76+
JuicyPixels
77+
, base >=4.7 && <5
78+
, binary
79+
, bytestring
80+
, filepath
81+
, hsDummyImage
82+
, optparse-applicative
83+
, repa
84+
, vector
85+
, zlib
86+
default-language: Haskell2010

‎package.yaml

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
name: hsDummyImage
2+
version: 0.9.0
3+
github: "DummyFiles/hsDummyImage"
4+
license: Apache-2.0
5+
author: "S0D3S"
6+
copyright: "2022 S0D3S"
7+
8+
extra-source-files:
9+
- README.md
10+
- CHANGELOG.md
11+
12+
# Metadata used when publishing your package
13+
# synopsis: Short description of your package
14+
# category: Web
15+
16+
# To avoid duplicated efforts in documentation and dealing with the
17+
# complications of embedding Haddock markup inside cabal files, it is
18+
# common to point users to the README.md file.
19+
description: Please see the README on GitHub at <https://github.com/DummyFiles/hsDummyImage#readme>
20+
21+
dependencies:
22+
- base >= 4.7 && < 5
23+
- JuicyPixels
24+
- optparse-applicative
25+
- repa
26+
- zlib
27+
- bytestring
28+
- filepath
29+
- binary
30+
- vector
31+
32+
ghc-options:
33+
- -Wall
34+
- -Wcompat
35+
- -Widentities
36+
- -Wincomplete-record-updates
37+
- -Wincomplete-uni-patterns
38+
- -Wmissing-export-lists
39+
- -Wmissing-home-modules
40+
- -Wpartial-fields
41+
- -Wredundant-constraints
42+
- src/Icon.o
43+
44+
library:
45+
source-dirs: src
46+
47+
executables:
48+
binary-exe:
49+
main: Main.hs
50+
source-dirs: app
51+
ghc-options:
52+
- -threaded
53+
- -rtsopts
54+
- '"-with-rtsopts=-N -T"'
55+
- -fllvm
56+
- -O2
57+
- -optlo-O3
58+
dependencies:
59+
- hsDummyImage
60+
61+
tests:
62+
hsDummyImage-test:
63+
main: Spec.hs
64+
source-dirs: test
65+
ghc-options:
66+
- -threaded
67+
- -rtsopts
68+
- -with-rtsopts=-N
69+
dependencies:
70+
- hsDummyImage

‎src/JPHack.hs

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
{-# LANGUAGE CPP #-}
2+
{-# LANGUAGE RankNTypes #-}
3+
{-# LANGUAGE TypeFamilies #-}
4+
{-# LANGUAGE ScopedTypeVariables #-}
5+
module JPHack
6+
(
7+
savePngImageWithoutCompression
8+
) where
9+
10+
import Codec.Picture
11+
import Data.Binary( encode )
12+
import Data.Word(Word8)
13+
import qualified Codec.Compression.Zlib as Z
14+
import qualified Data.ByteString as B
15+
import qualified Data.ByteString.Internal as BI
16+
import qualified Data.ByteString.Lazy as Lb
17+
import qualified Data.Vector.Storable as VS
18+
import qualified Data.ByteString.Lazy.Char8 as LbU
19+
20+
import Codec.Picture.Png.Internal.Type
21+
import Codec.Picture.Png.Internal.Metadata
22+
import Codec.Picture.Metadata( Metadatas )
23+
24+
import Foreign.Storable( Storable, sizeOf )
25+
26+
#if !MIN_VERSION_base(4,8,0)
27+
import Foreign.ForeignPtr.Safe( ForeignPtr, castForeignPtr )
28+
#else
29+
import Foreign.ForeignPtr( ForeignPtr, castForeignPtr )
30+
#endif
31+
32+
savePngImageWithoutCompression :: FilePath -> DynamicImage -> IO ()
33+
savePngImageWithoutCompression path img = Lb.writeFile path $ imageToPngWC img
34+
35+
imageToPngWC :: DynamicImage -> Lb.ByteString
36+
imageToPngWC (ImageRGB8 img) = genericEncodePngWC Nothing Nothing PngTrueColour mempty img
37+
imageToPngWC _ = LbU.pack "Unknown error"
38+
39+
-- ~ Copy & Paste from J.P ============================
40+
41+
-- -- Codec.Picture.VectorByteConversion
42+
mkBS :: ForeignPtr Word8 -> Int -> Int -> BI.ByteString
43+
#if MIN_VERSION_bytestring(0,11,0)
44+
mkBS fptr off = S.BS (fptr `S.plusForeignPtr` off)
45+
#else
46+
mkBS = BI.PS
47+
#endif
48+
49+
blitVector :: VS.Vector Word8 -> Int -> Int -> B.ByteString
50+
blitVector vec atIndex = mkBS ptr (offset + atIndex)
51+
where (ptr, offset, _length) = VS.unsafeToForeignPtr vec
52+
53+
toByteString :: forall a. (Storable a) => VS.Vector a -> B.ByteString
54+
toByteString vec = mkBS (castForeignPtr ptr) offset (len * size)
55+
where (ptr, offset, len) = VS.unsafeToForeignPtr vec
56+
size = sizeOf (undefined :: a)
57+
-- --
58+
59+
preparePalette :: Palette -> PngRawChunk
60+
preparePalette pal = PngRawChunk
61+
{ chunkLength = fromIntegral $ imageWidth pal * 3
62+
, chunkType = pLTESignature
63+
, chunkCRC = pngComputeCrc [pLTESignature, binaryData]
64+
, chunkData = binaryData
65+
}
66+
where binaryData = Lb.fromChunks [toByteString $ imageData pal]
67+
68+
preparePaletteAlpha :: VS.Vector Pixel8 -> PngRawChunk
69+
preparePaletteAlpha alphaPal = PngRawChunk
70+
{ chunkLength = fromIntegral $ VS.length alphaPal
71+
, chunkType = tRNSSignature
72+
, chunkCRC = pngComputeCrc [tRNSSignature, binaryData]
73+
, chunkData = binaryData
74+
}
75+
where binaryData = Lb.fromChunks [toByteString alphaPal]
76+
77+
type PaletteAlpha = VS.Vector Pixel8
78+
79+
preparePngHeader :: Image a -> PngImageType -> Word8 -> PngIHdr
80+
preparePngHeader (Image { imageWidth = w, imageHeight = h }) imgType depth = PngIHdr
81+
{ width = fromIntegral w
82+
, height = fromIntegral h
83+
, bitDepth = depth
84+
, colourType = imgType
85+
, compressionMethod = 0
86+
, filterMethod = 0
87+
, interlaceMethod = PngNoInterlace
88+
}
89+
90+
91+
endChunk :: PngRawChunk
92+
endChunk = mkRawChunk iENDSignature mempty
93+
94+
prepareIDatChunk :: Lb.ByteString -> PngRawChunk
95+
prepareIDatChunk = mkRawChunk iDATSignature
96+
97+
-- ~ ============================
98+
99+
genericEncodePngWC :: forall px. (Pixel px, PixelBaseComponent px ~ Word8)
100+
=> Maybe Palette
101+
-> Maybe PaletteAlpha
102+
-> PngImageType -> Metadatas -> Image px
103+
-> Lb.ByteString
104+
genericEncodePngWC palette palAlpha imgKind metas
105+
image@(Image { imageWidth = w, imageHeight = h, imageData = arr }) =
106+
encode PngRawImage { header = hdr
107+
, chunks = encodeMetadatas metas
108+
<> paletteChunk
109+
<> transpChunk
110+
<> [ prepareIDatChunk imgEncodedData
111+
, endChunk
112+
]}
113+
where
114+
hdr = preparePngHeader image imgKind 8
115+
zero = B.singleton 0
116+
compCount = componentCount (undefined :: px)
117+
118+
paletteChunk = case palette of
119+
Nothing -> []
120+
Just p -> [preparePalette p]
121+
122+
transpChunk = case palAlpha of
123+
Nothing -> []
124+
Just p -> [preparePaletteAlpha p]
125+
126+
lineSize = compCount * w
127+
encodeLine line = blitVector arr (line * lineSize) lineSize
128+
-- actually all changes was only for CompressionLevel 0
129+
imgEncodedData = Z.compressWith Z.defaultCompressParams { Z.compressLevel = Z.CompressionLevel 0}
130+
. Lb.fromChunks
131+
$ concat [[zero, encodeLine line] | line <- [0 .. h - 1]]

‎src/Lib.hs

Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
{-# LANGUAGE TypeOperators #-}
2+
3+
module Lib
4+
(
5+
savePngImageWithoutCompression,
6+
7+
availableGenFunctions,
8+
availableGenFunctionsStr,
9+
10+
availableUnits,
11+
availableUnitsStr,
12+
13+
calcSizeInBytes,
14+
15+
defaultDummyName,
16+
formatOutputName,
17+
18+
handleArgsAndGenPng,
19+
genAndSavePngByTargetSize,
20+
genAndSavePng
21+
) where
22+
23+
import JPHack(savePngImageWithoutCompression)
24+
25+
import Codec.Picture
26+
( generateImage,
27+
Pixel8,
28+
Image,
29+
PixelRGB8(..),
30+
DynamicImage(ImageRGB8) )
31+
32+
import GHC.Stats ( getRTSStats, RTSStats(elapsed_ns, cpu_ns) )
33+
34+
import Data.List ( elemIndex, intercalate )
35+
import Text.Printf (printf)
36+
import System.FilePath ( (</>) )
37+
38+
import Data.Array.Repa (Array, DIM2, U, D, Z (..), (:.)(..), (!))
39+
import qualified Data.Array.Repa as R -- for Repa
40+
41+
type RGB8 = (Pixel8, Pixel8, Pixel8)
42+
type GenFunc = Int -> Int -> (Z :. Int :. Int) -> RGB8
43+
type GenFuncMap = [(String, GenFunc)]
44+
45+
availableGenFunctions :: GenFuncMap
46+
availableGenFunctions = [("stains", stainsGenFunc),("hypnotoad", hypnotoadGenFunc),("fastest_mono", fastestMonoGenFunc),("alt_stains", altStainsGenFunc), ("matrix", matrixGenFunc), ("cold_grid", coldGridGenFunc), ("high_crosswalk", highCrossWalkGenFunc)]
47+
48+
availableGenFunctionsStr :: String
49+
availableGenFunctionsStr = "{" ++ grabGenFuncNames availableGenFunctions ++ "}"
50+
51+
grabGenFuncNames :: GenFuncMap -> String
52+
grabGenFuncNames [] = "ERROR"
53+
grabGenFuncNames ((name, _):xs) = if not (null xs) then name ++" | "++ grabGenFuncNames xs else name
54+
55+
findGenFuncByName' :: GenFuncMap -> String -> Maybe GenFunc
56+
findGenFuncByName' ((name, f'''):xs) str = if str==name then Just f''' else findGenFuncByName' xs str
57+
findGenFuncByName' [] _ = Nothing
58+
59+
findGenFuncByName :: String -> Maybe GenFunc
60+
findGenFuncByName = findGenFuncByName' availableGenFunctions
61+
62+
availableUnits :: [String]
63+
availableUnits = ["b", "kb", "mb", "gb"]
64+
65+
availableUnitsStr :: String
66+
availableUnitsStr = "{" ++ intercalate ", " availableUnits ++ "}"
67+
68+
calcSizeInBytes :: Int -> String -> Int
69+
calcSizeInBytes size units = do
70+
case elemIndex units availableUnits of
71+
Just multiplier -> size*(1024^multiplier)
72+
Nothing -> error $ "Incorrect units ["++units++"] select from available -> "++availableUnitsStr
73+
74+
countOfPH :: String -> Int
75+
countOfPH [] = 0
76+
countOfPH [_] = 0
77+
countOfPH (x:xx:xs) = (if x:xx:""=="%v" then 1 else 0) + countOfPH (if xx=='%' then xx:xs else xs)
78+
79+
defaultDummyName :: String
80+
defaultDummyName = "dummy_%v_%v.png"
81+
82+
formatOutputName :: String -> Int -> String -> String
83+
formatOutputName outputName oSize oUnits
84+
| null outputName = "dummy.png"
85+
| placeholdersCount==2 = printf outputName oSize oUnits
86+
| placeholdersCount==0 = outputName
87+
| otherwise = error "The name must contain 2 or 0 placeholders"
88+
where
89+
placeholdersCount = countOfPH outputName
90+
91+
checkDirPath :: FilePath -> FilePath
92+
checkDirPath dirPath = dirPath --TODO
93+
94+
-- ~ --------------------------------------------------------------------------------------------------
95+
96+
handleArgsAndGenPng :: Int -> String -> String -> String -> String -> IO ()
97+
handleArgsAndGenPng size units targetName targetDir genFuncName
98+
| size < 1 = error "Size must not be less than 1"
99+
| otherwise = genAndSavePngByTargetSize path size units genFunc
100+
where
101+
formatedName = formatOutputName targetName size units
102+
checkedDir = checkDirPath targetDir
103+
path = checkedDir </> formatedName
104+
genFunc = case findGenFuncByName genFuncName of
105+
Just gFunc -> gFunc
106+
Nothing -> error $ "Func {"++genFuncName++"} not found. Please select from "++availableGenFunctionsStr
107+
108+
genAndSavePngByTargetSize :: FilePath -> Int -> String -> GenFunc -> IO ()
109+
genAndSavePngByTargetSize path size units gFunc
110+
| targetSize < colorDepth = error $ printf "Equivalent size in bytes, must not be less than %d(received: %d)" colorDepth targetSize
111+
| otherwise = do
112+
out <- genAndSavePng path shapeX shapeY gFunc
113+
stats <- getRTSStats
114+
let
115+
elapsed_time :: Double
116+
elapsed_time = fromIntegral (elapsed_ns stats) * 1e-9
117+
cpu_time :: Double
118+
cpu_time = fromIntegral (cpu_ns stats) * 1e-9
119+
putStrLn $ printf "Image (~%d %s in %.4f sec., total: %.4f sec.)\nStored at: %s" size units elapsed_time cpu_time path
120+
return out
121+
where
122+
colorDepth = 8*3
123+
targetSize = calcSizeInBytes size units
124+
rShape = (floor . (sqrt :: Double -> Double) . fromIntegral) (targetSize `div` colorDepth * 8)
125+
shapeX = rShape
126+
shapeY = rShape
127+
128+
genAndSavePng :: FilePath -> Int -> Int -> GenFunc -> IO ()
129+
genAndSavePng path shX shY targetGenFunc = do
130+
img <- R.computeUnboxedP $ generateImg targetGenFunc shX shY
131+
(savePngImageWithoutCompression path . ImageRGB8 . toImage) img
132+
133+
134+
-- | Get image with true color pixels from manifest Repa array.
135+
toImage :: Array U DIM2 RGB8 -> Image PixelRGB8
136+
toImage a = generateImage gen width height
137+
where
138+
Z :. width :. height = R.extent a
139+
gen x y =
140+
let (r,g,b) = a ! (Z :. x :. y)
141+
in PixelRGB8 r g b
142+
143+
generateImg :: GenFunc -> Int -> Int -> Array D DIM2 RGB8
144+
generateImg genFunc shX shY= R.fromFunction (Z :. shX :. shY) (genFunc shX shY)
145+
146+
-- ~ --------------------------------------------------------------------------------------------------
147+
148+
stainsGenFunc :: GenFunc
149+
stainsGenFunc shX shY (Z :. x :. y) =
150+
let
151+
norm_x = x*0xff `div` shX
152+
norm_y = y*0xff `div` shY
153+
154+
lFuncRes = (norm_x*norm_x - norm_y*norm_y)
155+
gradientFuncRes = (norm_x + norm_y) `div` 2
156+
s a = fromIntegral $ mod a 0xff
157+
158+
in (s lFuncRes, s gradientFuncRes, 160)
159+
160+
altStainsGenFunc :: GenFunc
161+
altStainsGenFunc shX shY (Z :. x :. y) =
162+
let
163+
norm_x = x*0xff `div` shX
164+
norm_y = y*0xff `div` shY
165+
166+
lFuncRes = (norm_x*norm_x - norm_y*norm_y)
167+
gradientFuncRes = (norm_x + norm_y) `div` 2
168+
s a = fromIntegral $ mod a 0xff
169+
in (s (lFuncRes `div` 3), s (gradientFuncRes + lFuncRes), 0xff - s ( gradientFuncRes `div` 2))
170+
171+
coldGridGenFunc :: GenFunc
172+
coldGridGenFunc shX shY (Z :. x :. y) =
173+
let
174+
norm_x = x*0xff `div` shX
175+
norm_y = y*0xff `div` shY
176+
177+
grid :: Integer
178+
grid = (2^norm_x + 2^norm_y) `div` 2
179+
s a = fromIntegral $ mod a 0xff
180+
181+
in ((0xff - s grid) `div` 3, s grid * 3 `div` 2, 160)
182+
183+
hypnotoadGenFunc :: GenFunc
184+
hypnotoadGenFunc shX shY (Z :. x :. y) =
185+
let
186+
norm_x = x*0xff `div` shX
187+
norm_y = y*0xff `div` shY
188+
189+
grid = s (( norm_x*norm_x + norm_y*norm_y ) `div` 2)
190+
s a = fromIntegral $ mod a 0xff
191+
in ((0xff-grid) `div` 2, grid `div` 2, 200)
192+
193+
matrixGenFunc :: GenFunc
194+
matrixGenFunc shX shY (Z :. x :. y) =
195+
let
196+
norm_x = x*0xff `div` shX
197+
norm_y = y*0xff `div` shY
198+
matrix = (norm_x^norm_y)
199+
s a = fromIntegral $ mod a 0xff
200+
in (0, s matrix, 0)
201+
202+
fastestMonoGenFunc :: GenFunc
203+
fastestMonoGenFunc _ _ (Z :. _ :. _) = (255, 180, 180)
204+
205+
highCrossWalkGenFunc :: GenFunc
206+
highCrossWalkGenFunc _ _ (Z :. x :. y) =
207+
let
208+
(q, r) = x `quotRem` max 3 y
209+
s = fromIntegral . min 0xff
210+
in (s q, s r, s (q + r + 30))

‎stack.yaml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
packages:
2+
- .
3+
resolver: lts-19.20

‎stack.yaml.lock

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# This file was autogenerated by Stack.
2+
# You should not edit this file by hand.
3+
# For more information, please see the documentation at:
4+
# https://docs.haskellstack.org/en/stable/lock_files
5+
6+
packages: []
7+
snapshots:
8+
- completed:
9+
size: 619173
10+
url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/19/20.yaml
11+
sha256: be747117bed6d462806c883352c3206325b23480825103f5c87884e97e52819a
12+
original: lts-19.20

‎test/Spec.hs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
main :: IO ()
2+
main = putStrLn "Test suite not yet implemented"

0 commit comments

Comments
 (0)
Please sign in to comment.