├── SamplePhotonFiles
├── readme.md
├── Smilie.photon
├── 3DBenchy.photon
├── resin-test-25u.B100.2-20.photon
└── resin-test-50u.B100.2-20.photon
├── .travis.yml
├── screenshot.jpg
├── Screenshot1.png
├── Screenshot2.png
├── resources
├── cut.png
├── copy.png
├── paste.png
├── arrow-up.png
├── button.png
├── arrow-down.png
├── copy-hover.png
├── cut-hover.png
├── duplicate.png
├── newfile.photon
├── paste-hover.png
├── arrow-up-hover.png
├── duplicate-hover.png
├── MasterDocs
│ ├── icons.pptx
│ ├── copy - kopie.png
│ ├── cut - kopie.png
│ ├── delete - kopie.png
│ ├── paste - kopie.png
│ ├── arrow-up - kopie.png
│ ├── cut-hover - kopie.png
│ ├── duplicate - kopie.png
│ ├── arrow-down - kopie.png
│ ├── copy-hover - kopie.png
│ ├── paste-hover - kopie.png
│ ├── arrow-up-hover - kopie.png
│ ├── delete-hover - kopie.png
│ ├── arrow-down-hover - kopie.png
│ └── duplicate-hover - kopie.png
├── arrow-down-hover.png
├── sources.txt
└── resins.txt
├── PhotonEditor32x32.png
├── requirements.txt
├── PopupDialog.py
├── README.md
├── GUIhelpers.py
├── MessageDialog.py
├── FileDialog.py
├── LICENSE
├── PhotonFile.py
└── PhotonEditor.py
/SamplePhotonFiles/readme.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | branches:
2 | only:
3 | - issue-14
--------------------------------------------------------------------------------
/screenshot.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/screenshot.jpg
--------------------------------------------------------------------------------
/Screenshot1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/Screenshot1.png
--------------------------------------------------------------------------------
/Screenshot2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/Screenshot2.png
--------------------------------------------------------------------------------
/resources/cut.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/cut.png
--------------------------------------------------------------------------------
/resources/copy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/copy.png
--------------------------------------------------------------------------------
/resources/paste.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/paste.png
--------------------------------------------------------------------------------
/PhotonEditor32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/PhotonEditor32x32.png
--------------------------------------------------------------------------------
/resources/arrow-up.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/arrow-up.png
--------------------------------------------------------------------------------
/resources/button.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/button.png
--------------------------------------------------------------------------------
/resources/arrow-down.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/arrow-down.png
--------------------------------------------------------------------------------
/resources/copy-hover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/copy-hover.png
--------------------------------------------------------------------------------
/resources/cut-hover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/cut-hover.png
--------------------------------------------------------------------------------
/resources/duplicate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/duplicate.png
--------------------------------------------------------------------------------
/resources/newfile.photon:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/newfile.photon
--------------------------------------------------------------------------------
/resources/paste-hover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/paste-hover.png
--------------------------------------------------------------------------------
/resources/arrow-up-hover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/arrow-up-hover.png
--------------------------------------------------------------------------------
/resources/duplicate-hover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/duplicate-hover.png
--------------------------------------------------------------------------------
/SamplePhotonFiles/Smilie.photon:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/SamplePhotonFiles/Smilie.photon
--------------------------------------------------------------------------------
/resources/MasterDocs/icons.pptx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/icons.pptx
--------------------------------------------------------------------------------
/resources/arrow-down-hover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/arrow-down-hover.png
--------------------------------------------------------------------------------
/SamplePhotonFiles/3DBenchy.photon:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/SamplePhotonFiles/3DBenchy.photon
--------------------------------------------------------------------------------
/resources/MasterDocs/copy - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/copy - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/cut - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/cut - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/delete - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/delete - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/paste - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/paste - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/arrow-up - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/arrow-up - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/cut-hover - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/cut-hover - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/duplicate - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/duplicate - kopie.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # cat requirements.txt
2 | # USAGE: pip install -r requirements.txt
3 | pygame
4 | opencv-python
5 | numpy
6 | PyOpenGL
7 | scipy
--------------------------------------------------------------------------------
/resources/MasterDocs/arrow-down - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/arrow-down - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/copy-hover - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/copy-hover - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/paste-hover - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/paste-hover - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/arrow-up-hover - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/arrow-up-hover - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/delete-hover - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/delete-hover - kopie.png
--------------------------------------------------------------------------------
/SamplePhotonFiles/resin-test-25u.B100.2-20.photon:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/SamplePhotonFiles/resin-test-25u.B100.2-20.photon
--------------------------------------------------------------------------------
/SamplePhotonFiles/resin-test-50u.B100.2-20.photon:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/SamplePhotonFiles/resin-test-50u.B100.2-20.photon
--------------------------------------------------------------------------------
/resources/MasterDocs/arrow-down-hover - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/arrow-down-hover - kopie.png
--------------------------------------------------------------------------------
/resources/MasterDocs/duplicate-hover - kopie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Photonsters/PhotonFileEditor/HEAD/resources/MasterDocs/duplicate-hover - kopie.png
--------------------------------------------------------------------------------
/resources/sources.txt:
--------------------------------------------------------------------------------
1 | All icons are heavily based on the design of https://thenounproject.com/aathis/uploads/
2 | Due to missing icons, they were redesigned by Nard Janssens
3 | .
4 |
--------------------------------------------------------------------------------
/resources/resins.txt:
--------------------------------------------------------------------------------
1 | Brand,Type,Layer,NormalExpTime,OffTime,BottomExp,BottomLayers
2 | 3D-Okay,Black,0.030,10,1,60,8
3 | Ameralabs,AMD 3 LED, 0.040,5,1,50,8
4 | Anycubic, Green, 0.070,12,1,55,8
5 | Formlabs, V4 Clear, 0.040,28,1.5,120,8
6 | Fun To Do, Catable, 0.030,10,2,60,5
7 |
--------------------------------------------------------------------------------
/PopupDialog.py:
--------------------------------------------------------------------------------
1 | """
2 | Shows message dialog to user
3 | """
4 |
5 | __version__ = "alpha"
6 | __author__ = "Nard Janssens, Vinicius Silva, Robert Gowans, Ivan Antalec, Leonardo Marques - See Github PhotonFileUtils"
7 |
8 |
9 | import os
10 |
11 | import pygame
12 | from pygame.locals import *
13 |
14 | from GUI import *
15 |
16 | ########################################################################################################################
17 | ## Class PopupDialog
18 | ########################################################################################################################
19 |
20 | class PopupDialog():
21 | winrect=None
22 | titlerect=None
23 | margins=GRect(8,4,4,4)
24 | waiting=False
25 | dragDiff = None
26 |
27 | bordercolor=(0,0,0)
28 | titlebackcolor=defTitlebarBackground
29 | titletextcolor=(0,0,0)
30 | formcolor=defFormBackground
31 | fontname = defFontName
32 | fontsize = defFontSize
33 | listbox=None
34 | btnOK=None
35 | titleheight=24
36 | footerHeight=40
37 | buttonHeight=28
38 | buttonWidth=64
39 | controls=[]
40 |
41 |
42 | def reposControls(self): #called after winrect is moved
43 | """ Recalculates all positions after moving dialog box. """
44 | self.titlerect = GRect(self.winrect.x, self.winrect.y, self.winrect.width, self.titleheight)
45 | self.footerTop = self.winrect.y + self.winrect.height - self.margins.height - self.footerHeight
46 | x=self.winrect.x+self.margins.x
47 | y=self.winrect.y + self.titleheight + self.margins.y
48 | w=self.winrect.width - self.margins.x - self.margins.width
49 | h=self.winrect.height - self.titleheight - self.margins.y - self.footerHeight- self.margins.height
50 | self.label.rect=GRect(x,y, w, h)
51 | self.label.setText(self.message)
52 |
53 |
54 | def __init__(self, pyscreen, pos, title="Message Dialog",message="Read this carefully... \n ...before entering Ok!", dfontname=defFontName, dfontsize=defFontSize):
55 | """ Saves all values to internal variables and calculates some extra internal vars. """
56 | self.pyscreen = pyscreen
57 | #self.parentRedraw=parentRedraw
58 | self.winrect=GRect(pos[0], pos[1], 300, 160)
59 | self.title=title
60 | self.message=message
61 | self.font = pygame.font.SysFont(dfontname, dfontsize)
62 |
63 | # Calculate extra variables
64 | dummy, textheight = self.font.size("MinimalText")
65 | self.titleheight=textheight +self.margins.y+self.margins.height
66 | self.footerTop = self.winrect.y + self.winrect.height - self.margins.height - self.footerHeight
67 |
68 | # Add GUI.Label
69 | self.label=Label(pyscreen,text=message,fontname=dfontname,fontsize=dfontsize,rect=GRect(),autoheight=False,center=True,backcolor=self.formcolor,autowrap=True)
70 | self.controls.append(self.label)
71 |
72 | # (Re)calculate remaining variables
73 | self.reposControls()
74 |
75 |
76 | def show(self):
77 | """ Just draw me. """
78 | self.redraw()
79 |
80 |
81 | def hide(self):
82 | """ Do nothing. """
83 | return
84 |
85 |
86 | def redraw(self):
87 | """ Redraws dialogbox. """
88 |
89 | # Draw form background
90 | pygame.draw.rect(self.pyscreen, self.formcolor, self.winrect.tuple(), 0)
91 |
92 | # Draw title bar
93 | pygame.draw.rect(self.pyscreen, self.titlebackcolor,self.titlerect.tuple(), 0)
94 | self.font.set_bold(True)
95 | textsurface = self.font.render(self.title, True, self.titletextcolor)
96 | self.pyscreen.blit(textsurface, (self.winrect.x + self.margins.x, self.winrect.y + self.margins.y))
97 | self.font.set_bold(False)
98 |
99 | # Draw form border
100 | pygame.draw.rect(self.pyscreen, self.bordercolor, self.winrect.tuple(), 1)
101 |
102 | # Draw message
103 | self.label.redraw()
104 | pygame.display.flip()
105 |
106 |
107 |
108 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PhotonFileEditor
2 |
3 | The PhotonFileEditor is a utility to display, make and edit files for the Anycubic Photon printer. The current version is beta. This means that you may encounter bugs. __Some bugs can potentially harm your printer__, imagine for instance a buggy photonfile which tells your printer to move down instead of up after printing a layer!
4 |
5 | PhotonFileEditor is programmed in Python 3.6 and uses one mandatory library, pygame, and two optional libraries (numpy and pyOpenGL).
6 |
7 | ---
8 |
9 | ## Installation
10 | You can run PhotonFileEditor in Windows, OSX and Linux.
11 |
12 | All the releases can be found at https://github.com/Photonsters/PhotonFileEditor/releases
13 |
14 | For Windows an easy install package is available. For Linux and OSX you have to install python and some libraries.
15 |
16 | ### Windows:
17 | - Download the MSI file and run it.
18 | - If you want to run the latest version check the step-by-step in issue [#24](https://github.com/Photonsters/PhotonFileEditor/issues/24)
19 |
20 | ### OSX/Linux:
21 | 0) Download the source code in zip or tar.gz.
22 | 1) Install Python **3** from https://www.python.org/downloads/
23 | __or__ install Anaconda 3.6 https://www.anaconda.com/download/
24 | 2) Check the python version is above 3 by typing in the command line 'python --version'
25 | 3) Install the pygame library (https://www.pygame.org/wiki/GettingStarted) by
26 | * opening a dos prompt/linux terminal
27 | __or__ if using Anaconda use the windows start menu, type/find 'anaconda' and run the anaconda prompt
28 | * type 'python -m pip install -U pygame --user' to install the required library
29 | 4) Recommended: with numpy installed a number of actions will be a lot faster, like importing and exporting of images and also updating the layer image when navigating.(Anaconda installations already comes with Numpy 1.14.3 installed, however better to be safe than sorry, so...)
30 | * type 'python -m pip install -U numpy --user'
31 | 5) Optional: with opengl installed you can (in a future release) view and slice STL files.
32 | * python -m pip install PyOpenGL
33 | 6) Download this repository as a zip file and extract
34 | 7) You have two options to run PhotonFileEditor:
35 | * from your file explorer find and run PhotonEditor.py
36 | * from a dos prompt/linux terminal, navigate to the directory where you extracted the zip file and type 'phyton PhotonEditor.py'
37 |
38 | **Attention: PhotonFileEditor will not work with Python 2! [Read Issue #3](https://github.com/NardJ/PhotonFileUtils/issues/3)**
39 |
40 | ---
41 |
42 | ## How to help with the development
43 | There are a few things you could do to help me out with developing this program further:
44 |
45 | #### Programming
46 | The core programming team currently only consists of 1 programmer (me). Some extra hands are needed to make some faster progress. Please let me (GitHub alias NardJ) know.
47 |
48 | #### Bugfixing
49 | 1) Test PhotonFileEditor with your own (large) Photon files.
50 | 3) Check if edited/saved Photon files print as expected on your Photon printer.
51 | 3) Let me know of any bugs you find by posting a issue [here](https://github.com/Photonsters/PhotonFileEditor/issues)
52 |
53 | #### GUI
54 | The User Interface and its esthetics always could benefit from further improvements. Any suggestions are more than welcome!
55 |
56 | #### Functionality
57 | If you are missing functionality which is not mentioned below, please let me know [here](https://github.com/Photonsters/PhotonFileEditor/issues/).
58 |
59 | Since this is very much an alpha version (or rather an alpha *of* an alpha version), all suggestions of any kind are more than welcome!
60 |
61 | ---
62 |
63 | ## Implemented functionality
64 | Currently the following functionality is implemented:
65 | 1. Viewing all data from a .Photon file, including encapsulated sliced bitmaps, generic info, meta-info and preview images/thumbnails.
66 | 2. Editing all numeric data of the Photon File. Data-bytes which are internally used (location of bitmaps etc) are shown but readonly.
67 | 3. Basic editing of individual layer images and multiple layers at once.
68 | 4. Delete/Duplicate/Copy Layers
69 | 5. Exporting all images
70 | 6. Importing bitmaps (.e.g. from Povray as png-files) in an exisiting Photon File (which is thus used as a template)
71 | 7. Undo before mentioned actions Delete/Duplicate/Copy.
72 | 8. Apply new resin settings to the photon file
73 | 9. Starting fresh with a new .Photon file
74 | 10. Saving to a .Photon file.
75 |
76 | ---
77 |
78 | ## Functionality under development
79 | The following functionality will be implemented soon:
80 | 1. Improved layer editing
81 | 2. Slicing STL's to layer images
82 | 3. 3D view of bitmap data
83 | 4. Improved GUI
84 |
85 | ---
86 |
87 | ## Current screenshot
88 | ### Basic settings view
89 | 
90 | ### Advanced settings view
91 | 
92 | ### Layer editing
93 | 
94 |
95 |
96 |
97 |
--------------------------------------------------------------------------------
/GUIhelpers.py:
--------------------------------------------------------------------------------
1 | """
2 | Helper classes for GUI module
3 | """
4 |
5 | __version__ = "alpha"
6 | __author__ = "Nard Janssens, Vinicius Silva, Robert Gowans, Ivan Antalec, Leonardo Marques - See Github PhotonFileUtils"
7 |
8 | import math
9 |
10 | ########################################################################################################################
11 | ## Class GPoint
12 | ########################################################################################################################
13 |
14 | class GPoint():
15 | __x=0
16 | __y=0
17 |
18 | def __init__(self,x=0,y=0):
19 | """ Saves all values to internal variables. """
20 | self.__x = x
21 | self.__y = y
22 |
23 | @property
24 | def x(self):return self.__x
25 |
26 | @property
27 | def y(self):return self.__y
28 |
29 | @x.setter
30 | def x(self, x):self.__x = x
31 | @y.setter
32 | def y(self, y):self.__y = y
33 |
34 | @staticmethod
35 | def fromTuple(pos):
36 | return GPoint(pos[0],pos[1])
37 | @property
38 | def tuple(self):return (self.x, self.y)
39 |
40 | def __str__(self):return (str(self.x) + " , " + str(self.y) )
41 |
42 | def inGRect(self,GRect):
43 | """ Check if this GPoint is in given GRect. """
44 | return self.x>=GRect.left and self.x<=GRect.right and self.y >= GRect.top and self.y <= GRect.bottom
45 |
46 | def copy(self):
47 | """ Make a copy we can edit without affecting this instance. """
48 | newG=GPoint(self.x,self.y)
49 | return newG
50 |
51 | def __add__(self, other): return GPoint(self.x+other.x,self.y+other.y)
52 | def __sub__(self, other): return GPoint(self.x-other.x,self.y-other.y)
53 | def __mul__(self, other): return GPoint(self.x * other, self.y * other)
54 | def __gt__(self, other): return (self.x > other.x and self.y > other.y)
55 | def __lt__(self, other): return (self.x < other.x and self.y < other.y)
56 | def __eq__(self, other):
57 | try:
58 | #print ("comp to gpoints")
59 | return (self.x == other.x and self.y == other.y)
60 | except:
61 | #print ("error - compare types")
62 | return type(self)==type(other)
63 | def __len__(self): return (math.sqrt(self.x^2 + self.y^2))
64 |
65 |
66 | ########################################################################################################################
67 | ## Class GLine
68 | ########################################################################################################################
69 |
70 | class GLine():
71 | x1 = 0
72 | y1 = 0
73 | x2 = 0
74 | y2 = 0
75 |
76 | def __init__(self, x1=0, y1=0, x2=0, y2=0):
77 | """ Saves all values to internal variables. """
78 | self.x1 = x1
79 | self.y1 = y1
80 | self.x2 = x2
81 | self.y2 = y2
82 | @property
83 | def width(self):return self.x2-self.x1
84 | @property
85 | def height(self):return self.y2 - self.y1
86 | @property
87 | def length(self): return (math.sqrt(self.width + self.height))
88 |
89 | def copy(self):
90 | """ Make a copy we can edit without affecting this instance. """
91 | newG=GLine(self.x1,self.y1)
92 | return newG
93 |
94 |
95 | ########################################################################################################################
96 | ## Class GRect
97 | ########################################################################################################################
98 |
99 | class GRect():
100 | __x = 0
101 | __y = 0
102 | __width = 0
103 | __height = 0
104 |
105 | def __init__(self, x=0, y=0, width=0, height=0):
106 | """ Saves all values to internal variables. """
107 | self.__x = x
108 | self.__y = y
109 | self.__width = width
110 | self.__height = height
111 |
112 | @property
113 | def x(self):return self.__x
114 | @property
115 | def y(self):return self.__y
116 | @property
117 | def left(self):return self.__x
118 | @property
119 | def top(self):return self.__y
120 | @property
121 | def right(self):return self.__x+self.__width
122 | @property
123 | def bottom(self):return self.__y+self.__height
124 | @property
125 | def width(self):return self.__width
126 | @property
127 | def height(self):return self.__height
128 |
129 | @property
130 | def p1(self):return GPoint(self.left,self.top)
131 | @property
132 | def p2(self):return GPoint(self.right,self.top)
133 | @property
134 | def p3(self):return GPoint(self.right,self.bottom)
135 | @property
136 | def p4(self):return GPoint(self.left,self.bottom)
137 |
138 | @x.setter
139 | def x(self, x):self.__x = x
140 | @y.setter
141 | def y(self, y):self.__y = y
142 | @left.setter
143 | def left(self, x):self.__x = x
144 | @top.setter
145 | def top(self, y):self.__y = y
146 | @right.setter
147 | def right(self,r):self.__width=r-self.x
148 | @bottom.setter
149 | def bottom(self,b):self.__width=b-self.y
150 | @width.setter
151 | def width(self, w):self.__width = w
152 | @height.setter
153 | def height(self, h):self.__height = h
154 | @p1.setter
155 | def p1(self, p):
156 | self.__x = p.x
157 | self.__y = p.y
158 |
159 | @property
160 | def topline(self):return GLine(self.x1,self.y1,self.x2,self.y1)
161 | @property
162 | def bottomline(self):return GLine(self.x1,self.y2,self.x2,self.y2)
163 | @property
164 | def leftline(self):return GLine(self.x1,self.y1,self.x1,self.y2)
165 | @property
166 | def rightline(self):return GLine(self.x2,self.y1,self.x2,self.y2)
167 |
168 | def copy(self):
169 | """ Make a copy we can edit without affecting this instance. """
170 | newG=GRect(self.x,self.y,self.width,self.height)
171 | return newG
172 |
173 | def move(self,gpos):
174 | """ Move this rect by distance in GPoint. """
175 | self.x=self.x+gpos.x
176 | self.y=self.y+gpos.y
177 |
178 | def moveto(self,gpos):
179 | """ Move this rect upperleft corner to GPoint. """
180 | self.x=gpos.x
181 | self.y=gpos.y
182 |
183 | def shrink(self,grect):
184 | """ Add self.x to GRect.x, Add self.y to GRect.y, Substract GRect.width from self.width, Substract GRect.height from self.height."""
185 | self.x=self.x+grect.x
186 | self.y=self.y+grect.y
187 | self.width=self.width-grect.x-grect.width
188 | self.height=self.height-grect.y-grect.height
189 |
190 | def tuple(self):
191 | return (self.x, self.y, self.width, self.height)
192 |
193 | def __str__(self):
194 | return (str(self.x) + " , " + str(self.y) + " , " + str(self.width) + " , " + str(self.height))
195 |
196 |
--------------------------------------------------------------------------------
/MessageDialog.py:
--------------------------------------------------------------------------------
1 | """
2 | Shows message dialog to user
3 | """
4 |
5 | __version__ = "alpha"
6 | __author__ = "Nard Janssens, Vinicius Silva, Robert Gowans, Ivan Antalec, Leonardo Marques - See Github PhotonFileUtils"
7 |
8 | import os
9 |
10 | import pygame
11 | from pygame.locals import *
12 |
13 | from GUI import *
14 |
15 |
16 | ########################################################################################################################
17 | ## Class MessageDialog
18 | ########################################################################################################################
19 |
20 | class MessageDialog():
21 | #Button constants
22 | OK=0
23 | YESNO=1
24 | OKCANCEL=2
25 | buttonChoice=OK
26 |
27 | winrect=None
28 | titlerect=None
29 | margins=GRect(8,4,4,4)
30 | waiting=False
31 | dragDiff = None
32 |
33 | bordercolor=(0,0,0)
34 | titlebackcolor=defTitlebarBackground
35 | titletextcolor=(0,0,0)
36 | formcolor=defFormBackground
37 | fontname = defFontName
38 | fontsize = defFontSize
39 | listbox=None
40 | btnRight=None
41 | titleheight=24
42 | footerHeight=40
43 | buttonHeight=28
44 | buttonWidth=64
45 | controls=[]
46 |
47 | def reposControls(self): #called initially and after winrect is moved
48 | """ Recalculates all positions after moving dialog box. """
49 | self.winrect.height=self.titleheight+self.margins.y+self.label.rect.height+self.footerHeight+self.margins.height
50 | self.titlerect = GRect(self.winrect.x, self.winrect.y, self.winrect.width, self.titleheight)
51 | self.footerTop = self.winrect.y + self.winrect.height - self.margins.height - self.footerHeight
52 | self.label.rect.x=self.winrect.x+self.margins.x
53 | self.label.rect.y=self.winrect.y+self.titleheight+self.margins.y
54 | self.btnRight.rect=GRect(self.winrect.x + self.winrect.width - self.margins.width - self.buttonWidth, self.footerTop + self.margins.x, self.buttonWidth, self.buttonHeight)
55 | if not self.buttonChoice==self.OK: # two buttons
56 | self.btnLeft.rect=GRect.copy(self.btnRight.rect)
57 | self.btnLeft.rect.left=self.btnLeft.rect.left-self.margins.width - self.buttonWidth
58 |
59 | def __init__(self, pyscreen,
60 | pos, width=300,
61 | center=True,
62 | title="Message Dialog",message="Read this carefully... \n ...before entering Ok!",
63 | dfontname=defFontName, dfontsize=defFontSize,
64 | buttonChoice=OK,
65 | handleOK=None,
66 | handleCANCEL = None,
67 | handleYES = None,
68 | handleNO = None,
69 | parentRedraw=None):
70 | """ Saves all values to internal variables and calculates some extra internal vars. """
71 | # Save variables
72 | self.pyscreen = pyscreen
73 | self.parentRedraw=parentRedraw
74 | self.winrect=GRect(pos[0], pos[1], width, 160)
75 | self.title=title
76 | self.message=message
77 | self.font = pygame.font.SysFont(dfontname, dfontsize)
78 | self.buttonChoice=buttonChoice
79 | self.handleOK=handleOK
80 | self.handleCANCEL=handleCANCEL
81 | self.handleNO = handleNO
82 | self.handleYES = handleYES
83 |
84 | # Calculate extra variables
85 | dummy, textheight = self.font.size("MinimalText")
86 | self.titleheight=textheight+self.margins.y+self.margins.height
87 | self.footerTop = self.winrect.y + self.winrect.height - self.margins.height - self.footerHeight
88 |
89 | # Add GUI.Label and GUI.Button(s)
90 | rectLabel=GRect(0,0,self.winrect.width-self.margins.x-self.margins.width,0)
91 | self.label=Label(pyscreen,text=message,fontname=dfontname,fontsize=dfontsize,rect=rectLabel,autoheight=True,center=center,backcolor=self.formcolor,autowrap=True)
92 | self.controls.append(self.label)
93 | self.btnRight=Button(pyscreen, text="OK", func_on_click=self.handleRight, rect=GRect())
94 | self.controls.append(self.btnRight)
95 | if buttonChoice==self.YESNO:
96 | self.btnLeft = Button(pyscreen, text="YES", func_on_click=self.handleLeft, rect=GRect())
97 | self.btnRight = Button(pyscreen, text="NO", func_on_click=self.handleRight, rect=GRect())
98 | self.controls.append(self.btnLeft)
99 | self.controls.append(self.btnRight)
100 | if buttonChoice == self.OKCANCEL:
101 | self.btnLeft = Button(pyscreen, text="OK", func_on_click=self.handleLeft, rect=GRect())
102 | self.btnRight=Button(pyscreen, text="CANCEL", func_on_click=self.handleRight, rect=GRect())
103 | self.controls.append(self.btnLeft)
104 | self.controls.append(self.btnRight)
105 |
106 | # (Re)calculate remaining variables
107 | self.reposControls()
108 |
109 |
110 | def show(self):
111 | """ Returns selected button and closes dialog. """
112 | self.waiting=True
113 | self.waitforuser()
114 | return self.lastaction
115 |
116 | def redraw(self):
117 | """ Redraws dialogbox. """
118 |
119 | # First call parent / window to redraw itself
120 | self.parentRedraw()
121 |
122 | # Draw form background
123 | pygame.draw.rect(self.pyscreen, self.formcolor, self.winrect.tuple(), 0)
124 |
125 | # Draw title bar including title text
126 | pygame.draw.rect(self.pyscreen, self.titlebackcolor,self.titlerect.tuple(), 0)
127 | self.font.set_bold(True)
128 | textsurface = self.font.render(self.title, True, self.titletextcolor)
129 | self.pyscreen.blit(textsurface, (self.winrect.x + self.margins.x, self.winrect.y + self.margins.y))
130 | self.font.set_bold(False)
131 |
132 | # Draw form border
133 | pygame.draw.rect(self.pyscreen, self.bordercolor, self.winrect.tuple(), 1)
134 |
135 | # Call upon label and button to redraw themselves.
136 | self.label.redraw()
137 | self.btnRight.redraw()
138 | if not self.buttonChoice==self.OK: self.btnLeft.redraw()
139 |
140 |
141 | def waitforuser(self):
142 | """ Blocks all events to Main window and wait for user to click OK. """
143 |
144 | while self.waiting:
145 | self.redraw()
146 | pygame.display.flip()
147 |
148 | for event in pygame.event.get():
149 | pos = pygame.mouse.get_pos()
150 | gpos=GPoint().fromTuple(pos)
151 |
152 | if event.type == pygame.MOUSEBUTTONUP:
153 | if self.dragDiff==None:
154 | for ctrl in self.controls:
155 | ctrl.handleMouseUp(pos,event.button)
156 | else: # handle window move
157 | self.dragDiff=None
158 |
159 | if event.type == pygame.MOUSEBUTTONDOWN:
160 | if gpos.inGRect(self.titlerect):
161 | self.dragDiff = gpos - self.winrect.p1
162 | else:
163 | for ctrl in self.controls:
164 | ctrl.handleMouseDown(pos,event.button)
165 |
166 | if event.type == pygame.MOUSEMOTION:
167 | if not self.dragDiff==None:
168 | self.winrect.p1=gpos-self.dragDiff
169 | self.reposControls()
170 | else:
171 | for ctrl in self.controls:
172 | ctrl.handleMouseMove(pos)
173 |
174 | if event.type == pygame.KEYDOWN:
175 | if event.key == pygame.K_ESCAPE:
176 | print("Escape key pressed down.")
177 | self.waiting = False
178 |
179 |
180 | def handleRight(self):
181 | """ If OK we tell main loop we are ready waiting. """
182 | if self.buttonChoice==self.OK: self.lastaction="OK"
183 | if self.buttonChoice==self.OKCANCEL: self.lastaction="CANCEL"
184 | if self.buttonChoice == self.YESNO: self.lastaction = "NO"
185 | self.waiting=False
186 |
187 | def handleLeft(self):
188 | """ If OK we tell main loop we are ready waiting. """
189 | if self.buttonChoice==self.OKCANCEL: self.lastaction="OK"
190 | if self.buttonChoice == self.YESNO: self.lastaction = "YES"
191 | self.waiting=False
192 |
193 |
--------------------------------------------------------------------------------
/FileDialog.py:
--------------------------------------------------------------------------------
1 | """
2 | Shows message dialog to user
3 | """
4 |
5 | __version__ = "alpha"
6 | __author__ = "Nard Janssens, Vinicius Silva, Robert Gowans, Ivan Antalec, Leonardo Marques - See Github PhotonFileUtils"
7 |
8 | import os
9 |
10 | import pygame
11 | from pygame.locals import *
12 |
13 | from GUI import *
14 |
15 | ########################################################################################################################
16 | ## Class FileDialog
17 | ########################################################################################################################
18 |
19 | class FileDialog():
20 | winrect=None
21 | titlerect=None
22 | filerect=None
23 | margins=GRect(8,4,4,4)
24 | waiting=False
25 | dragDiff = None
26 |
27 | bordercolor=(0,0,0)
28 | titlebackcolor=defTitlebarBackground
29 | titletextcolor=(0,0,0)
30 | formcolor=defFormBackground
31 | filebackcolor=defEditorBackground
32 | filetextcolor=(0,0,0)
33 | fontname = defFontName
34 | fontsize = defFontSize
35 | listbox=None
36 | btnOK=None
37 | btnCancel=None
38 | tbFilename=None
39 | titleheight=24
40 | footerHeight=40
41 | buttonHeight=28
42 | buttonWidth=64
43 | controls=[]
44 | ext="*"
45 | startdir=""
46 | selFilename="None selected"
47 | selDirectory = "None selected"
48 | showFilenames=True
49 | lastaction=""
50 |
51 |
52 | def reposControls(self): #called after winrect is moved
53 | """ Recalculates all positions after moving dialog box. """
54 | self.titlerect = GRect(self.winrect.x, self.winrect.y, self.winrect.width, self.titleheight)
55 | self.footerTop = self.winrect.y + self.winrect.height - self.margins.height - self.footerHeight
56 | x=self.winrect.x+self.margins.x
57 | y=self.winrect.y + self.titleheight + self.margins.y
58 | w=self.winrect.width - self.margins.x - self.margins.width
59 | h=self.winrect.height - self.titleheight - self.margins.y - self.footerHeight- self.margins.height
60 | self.listbox.rect=GRect(x,y, w, h)
61 | self.btnOK.rect=GRect(self.winrect.x+self.winrect.width-self.margins.width-self.buttonWidth,self.footerTop+self.margins.x,self.buttonWidth,self.buttonHeight)
62 | self.btnCancel.rect= GRect(self.winrect.x + self.winrect.width - 2*self.margins.width - 2*self.buttonWidth,self.footerTop + self.margins.x, self.buttonWidth, self.buttonHeight)
63 | self.tbFilename.rect =GRect(self.winrect.x+self.margins.x,self.footerTop+self.margins.x,self.winrect.width-4*self.margins.x-2*self.buttonWidth,self.buttonHeight)
64 |
65 |
66 | def __init__(self, pyscreen, pos, height=300,startdir=None, title="Open File Dialog",defFilename="newfile.txt", dfontname=defFontName, dfontsize=defFontSize, ext="*",parentRedraw=None):
67 | """ Saves all values to internal variables and calculates some extra internal vars. """
68 | # Save variables
69 | self.pyscreen = pyscreen
70 | self.parentRedraw=parentRedraw
71 | if startdir==None: self.startdir=os.getcwd()
72 | self.ext=ext
73 | self.winrect=GRect(pos[0], pos[1], 350, height)
74 | self.title=title
75 | self.defFilename=defFilename
76 | self.font = pygame.font.SysFont(dfontname, dfontsize)
77 |
78 | # Calculate extra variables
79 | dummy, textheight = self.font.size("MinimalText")
80 | self.titleheight=textheight +self.margins.y+self.margins.height
81 | self.footerTop = self.winrect.y + self.winrect.height - self.margins.height - self.footerHeight
82 |
83 | # Add GUI.Listbox, GUI.Textbox and GUI.Buttons
84 | self.listbox=ListBox(pyscreen,fontname=dfontname,fontsize=dfontsize,func_on_click=self.handleListboxSelect, rect=GRect())
85 | self.btnOK=Button(pyscreen,text="OK",func_on_click=self.handleOK, rect=GRect())
86 | self.btnCancel = Button(pyscreen, text="Cancel",func_on_click=self.handleCancel, rect=GRect())
87 | self.tbFilename= TextBox(pyscreen,backcolor=(255,255,255),textcolor=(0,0,0),bordercolor=(0,0,0),rect=GRect(),text=defFilename)
88 | self.controls.append(self.listbox)
89 | self.controls.append(self.tbFilename)
90 | self.controls.append(self.btnOK)
91 | self.controls.append(self.btnCancel)
92 |
93 | # (Re)calculate remaining variables
94 | self.reposControls()
95 |
96 | # Fill listbox with directory items
97 | self.readDirectory()
98 | self.listbox.setItems(self.dirsandfiles)
99 |
100 | #print ("starting with: ", self.startdir)
101 |
102 |
103 | def getFile(self):
104 | """ Get Existing Filename from user. """
105 | # Hide texbox to input filename and show files in listbox
106 | self.tbFilename.visible=False
107 | self.showFilenames=True
108 | # Read content of directory and update self.dirsandfiles variable to show in listbox
109 | self.readDirectory()
110 | # Wait for user to select file and press OK
111 | self.waiting=True
112 | self.waitforuser()
113 | if self.lastaction=="OK":
114 | fullpath = os.path.join(self.startdir, self.selFilename)
115 | return fullpath
116 | else:
117 | return None
118 |
119 |
120 | def getDirectory(self):
121 | """ Get Directory from user. """
122 | # Hide texbox to input filename and hide files in listbox
123 | self.tbFilename.visible=False
124 | self.showFilenames=False
125 | # Read content of directory and update self.dirsandfiles variable to show in listbox
126 | self.readDirectory()
127 | # Wait for user to select file and press OK
128 | self.waiting=True
129 | self.waitforuser()
130 | if self.lastaction=="OK":
131 | return self.selDirectory
132 | else:
133 | return None
134 |
135 |
136 | def newFile(self):
137 | """ Get New Filename from user. """
138 | # Show texbox to input filename and show files in listbox
139 | self.tbFilename.visible=True
140 | self.showFilenames=True
141 | # Read content of directory and update self.dirsandfiles variable to show in listbox
142 | self.readDirectory()
143 | # Wait for user to select file and press OK
144 | self.waiting=True
145 | self.waitforuser()
146 | if self.lastaction=="OK":
147 | fullpath = os.path.join(self.startdir, self.tbFilename.text)
148 | return fullpath
149 | else:
150 | return None
151 |
152 |
153 | def readDirectory(self):
154 | """ Read content of directory and update self.dirsandfiles variable to use on redraw. """
155 |
156 | # Always make sure we can go back
157 | dirs = [".."]
158 |
159 | # Check if we have access to dir
160 | hasAccess=os.access(self.startdir,os.R_OK)
161 | if not hasAccess:
162 | print ("User has no access to "+self.startdir)
163 | self.dirsandfiles=dirs
164 | return
165 |
166 | # Read dirs and files
167 | direntries = os.listdir(self.startdir)
168 |
169 | # Extract dirs
170 | for entry in direntries:
171 | if not entry.startswith("$"): # recycle bin in windows
172 | fullname = os.path.join(self.startdir, entry)
173 | if os.path.isdir(fullname): dirs.append(entry + "/")
174 | dirs.sort(key=str.lower)
175 |
176 | # Extract files and apply filter
177 | files = []
178 | if self.showFilenames:
179 | if not self.ext == "*":
180 | for entry in direntries:
181 | if entry.endswith(self.ext): files.append(entry)
182 | files.sort(key=str.lower)
183 |
184 | # Make one list of dirs and files
185 | self.dirsandfiles = dirs + files
186 | #print("dirs : ",dirs)
187 | #print("files: ", files)
188 |
189 |
190 | def redraw(self):
191 | """ Redraws filedialog. """
192 |
193 | # First call parent / window to redraw itself
194 | self.parentRedraw()
195 |
196 | # Draw form background
197 | pygame.draw.rect(self.pyscreen, self.formcolor, self.winrect.tuple(), 0)
198 |
199 | # Draw title bar including title text
200 | pygame.draw.rect(self.pyscreen, self.titlebackcolor,self.titlerect.tuple(), 0)
201 | self.font.set_bold(True)
202 | textsurface = self.font.render(self.title, True, self.titletextcolor)
203 | self.pyscreen.blit(textsurface, (self.winrect.x + self.margins.x, self.winrect.y + self.margins.y))
204 | self.font.set_bold(False)
205 |
206 | # Draw form border
207 | pygame.draw.rect(self.pyscreen, self.bordercolor, self.winrect.tuple(), 1)
208 |
209 | # Call upon label and button to redraw themselves.
210 | self.listbox.redraw()
211 | self.btnCancel.redraw()
212 | self.btnOK.redraw()
213 | self.tbFilename.redraw()
214 |
215 |
216 | def waitforuser(self):
217 | """ Blocks all events to Main window and wait for user to click OK. """
218 |
219 | while self.waiting:
220 | self.redraw()
221 | pygame.display.flip()
222 |
223 | for event in pygame.event.get():
224 | pos = pygame.mouse.get_pos()
225 | gpos=GPoint().fromTuple(pos)
226 |
227 | if event.type == pygame.MOUSEBUTTONUP:
228 | if self.dragDiff==None:
229 | for ctrl in self.controls:
230 | ctrl.handleMouseUp(pos,event.button)
231 | else: # handle window move
232 | self.dragDiff=None
233 |
234 | if event.type == pygame.MOUSEBUTTONDOWN:
235 | if gpos.inGRect(self.titlerect):
236 | self.dragDiff = gpos - self.winrect.p1
237 | else:
238 | for ctrl in self.controls:
239 | ctrl.handleMouseDown(pos,event.button)
240 |
241 | if event.type == pygame.MOUSEMOTION:
242 | if not self.dragDiff==None:
243 | self.winrect.p1=gpos-self.dragDiff
244 | self.reposControls()
245 | else:
246 | for ctrl in self.controls:
247 | ctrl.handleMouseMove(pos)
248 |
249 | if event.type == pygame.KEYDOWN:
250 | if event.key == pygame.K_ESCAPE:
251 | print("Escape key pressed down.")
252 | self.waiting = False
253 | else:
254 | self.tbFilename.handleKeyDown(event.key, event.unicode)
255 |
256 |
257 | def handleListboxSelect(self,text):
258 | """ If Listbox item selected and directory, we read new directory of if not put filename in textbox. """
259 |
260 | #print ("[handleListboxSelect]")
261 | #text=self.listbox.activeText()
262 | #print (" parse: ", text)
263 | #print (" direct:", itext)
264 |
265 | # Check if user wants to go up.
266 | if text=="..":
267 | self.startdir=os.path.dirname(self.startdir)
268 | self.selDirectory = self.startdir
269 | self.readDirectory()
270 | self.listbox.setItems(self.dirsandfiles)
271 | # Check if user selects a directory
272 | elif text.endswith("/"):
273 | self.startdir=os.path.join(self.startdir,text[:-1])
274 | self.selDirectory = self.startdir
275 | self.readDirectory()
276 | self.listbox.setItems(self.dirsandfiles)
277 | print ("Nav to dir: ",self.selDirectory)
278 | # Else user selected a file
279 | else:
280 | self.tbFilename.text=self.listbox.activeText()
281 | self.selFilename=self.listbox.activeText()
282 | #print ("Selected: ",self.selFilename," -> ", self.selDirectory,self.selFilename)
283 |
284 | def handleCancel(self):
285 | """ If Cancel we tell main loop we are ready waiting. """
286 | self.lastaction="Cancel"
287 | self.waiting=False
288 |
289 |
290 | def handleOK(self):
291 | """ If OK we tell main loop we are ready waiting. """
292 | self.lastaction = "OK"
293 | self.waiting=False
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/PhotonFile.py:
--------------------------------------------------------------------------------
1 | """
2 | Loads/Save .photon files (from the Anycubic Photon Slicer) in memory and allows editing of settings and bitmaps.
3 | """
4 |
5 | __version__ = "alpha"
6 | __author__ = "Nard Janssens, Vinicius Silva, Robert Gowans, Ivan Antalec, Leonardo Marques - See Github PhotonFileUtils"
7 |
8 | import os
9 | import copy
10 | import math
11 | import struct
12 | from math import *
13 |
14 | import pygame
15 | from pygame.locals import *
16 |
17 | try:
18 | import numpy
19 | numpyAvailable = True
20 | print("Numpy library available.")
21 | except ImportError:
22 | numpyAvailable = False
23 | print ("Numpy library not found.")
24 |
25 |
26 | ########################################################################################################################
27 | ## Convert byte string to hex string
28 | ########################################################################################################################
29 |
30 | def hexStr(bytes):
31 | if isinstance(bytes, bytearray):
32 | return ' '.join(format(h, '02X') for h in bytes)
33 | if isinstance(bytes, int):
34 | return format(bytes, '02X')
35 | return ("No Byte (string)")
36 |
37 |
38 | ########################################################################################################################
39 | ## Class PhotonFile
40 | ########################################################################################################################
41 |
42 | class PhotonFile:
43 | isDrawing = False # Navigation can call upon retrieving bitmaps frequently. This var prevents multiple almost parallel loads
44 | nrLayersString = "# Layers" #String is used in multiple locations and thus can be edited here
45 |
46 | # Data type constants
47 | tpByte = 0
48 | tpChar = 1
49 | tpInt = 2
50 | tpFloat = 3
51 |
52 | # Clipboard Vars to copy/cut and paste layer settinngs/imagedata
53 | clipboardDef = None
54 | clipboardData = None
55 |
56 | # This is the data structure of photon file. For each variable we need to know
57 | # Title string to display user, nr bytes to read/write, type of data stored, editable
58 | # Each file consists of
59 | # - General info ( pfStruct_Header, Header)
60 | # - Two previews which contain meta-info an raw image data ( pfStruct_Previews, Previews)
61 | # - For each layer meta-info ( pfStruct_LayerDefs, LayerDefs)
62 | # - For each layer raw image data ( pfStruct_LayerData, LayerData)
63 | pfStruct_Header = [
64 | ("Header", 8, tpByte, False, ""),
65 | ("Bed X (mm)", 4, tpFloat, True, "Short side of the print bed."),
66 | ("Bed Y (mm)", 4, tpFloat, True, "Long side of the print bed."),
67 | ("Bed Z (mm)", 4, tpFloat, True, "Maximum height the printer can print."),
68 | ("padding0", 3 * 4, tpByte, False, ""), # 3 ints
69 | ("Layer height (mm)", 4, tpFloat, True, "Default layer height."),
70 | ("Exp. time (s)", 4, tpFloat, True, "Default exposure time."),
71 | ("Exp. bottom (s)", 4, tpFloat, True, "Exposure time for bottom layers."),
72 | ("Off time (s)", 4, tpFloat, True, "Time UV is turned of between layers."),
73 | ("# Bottom Layers", 4, tpInt, True, "Number of bottom layers.\n (These have different exposure time.)"),
74 | ("Resolution X", 4, tpInt, True, "X-Resolution of the screen through \n which the layer image is projected."),
75 | ("Resolution Y", 4, tpInt, True, "Y-Resolution of the screen through \n which the layer image is projected." ),
76 | ("Preview 0 (addr)", 4, tpInt, False, "Address where the metadata \n of the High Res preview image can be found."), # start of preview 0
77 | ("Layer Defs (addr)", 4, tpInt, False, "Address where the metadata \n for the layer images can be found."), # start of layerDefs
78 | (nrLayersString, 4, tpInt, False, "Number of layers this file has."),
79 | ("Preview 1 (addr)", 4, tpInt, False, "Address where the metadata \n of the Low Res preview image can be found."), # start of preview 1
80 | ("unknown6", 4, tpInt, False, ""),
81 | ("Proj.type-Cast/Mirror", 4, tpInt, False, "LightCuring/Projection type:\n 1=LCD_X_MIRROR \n 0=CAST"), #LightCuring/Projection type // (1=LCD_X_MIRROR, 0=CAST)
82 | ("padding1", 6 * 4, tpByte, False, "") # 6 ints
83 | ]
84 |
85 | pfStruct_Previews = [
86 | ("Resolution X", 4, tpInt, False, "X-Resolution of preview pictures."),
87 | ("Resolution Y", 4, tpInt, False, "Y-Resolution of preview pictures."),
88 | ("Image Address", 4, tpInt, False, "Address where the raw image can be found."), # start of rawData0
89 | ("Data Length", 4, tpInt, False, "Size (in bytes) of the raw image."), # size of rawData0
90 | ("padding", 4 * 4, tpByte, False, ""), # 4 ints
91 | ("Image Data", -1, tpByte, False, "The raw image."),
92 | ]
93 |
94 | pfStruct_LayerDef = [
95 | ("Layer height (mm)", 4, tpFloat, True, "Height at which this layer should be printed."),
96 | ("Exp. time (s)", 4, tpFloat, True, "Exposure time for this layer."),
97 | ("Off time (s)", 4, tpFloat, True, "Off time for this layer."),
98 | ("Image Address", 4, tpInt, False, "Address where the raw image can be found."),#dataStartPos -> Image Address
99 | ("Data Length", 4, tpInt, False, "Size (in bytes) of the raw image."), #size of rawData+lastByte(1)
100 | ("padding", 4 * 4, tpByte, False, "") # 4 ints
101 | ]
102 |
103 | # pfStruct_LayerData =
104 | # rawData - rle encoded bytes except last one
105 | # lastByte - last byte of encoded bitmap data
106 |
107 | Header = {}
108 | Previews = [{},{}]
109 | LayerDefs = []
110 | LayerData = []
111 |
112 | History=[]
113 | HistoryMaxDepth = 10
114 |
115 |
116 | ########################################################################################################################
117 | ## Methods to convert bytes (strings) to python variables and back again
118 | ########################################################################################################################
119 |
120 | @staticmethod
121 | def bytes_to_int(bytes):
122 | """ Converts list or array of bytes to an int. """
123 | result = 0
124 | for b in reversed(bytes):
125 | result = result * 256 + int(b)
126 | return result
127 |
128 | @staticmethod
129 | def bytes_to_float(inbytes):
130 | """ Converts list or array of bytes to an float. """
131 | bits = PhotonFile.bytes_to_int(inbytes)
132 | mantissa = ((bits & 8388607) / 8388608.0)
133 | exponent = (bits >> 23) & 255
134 | sign = 1.0 if bits >> 31 == 0 else -1.0
135 | if exponent != 0:
136 | mantissa += 1.0
137 | elif mantissa == 0.0:
138 | return sign * 0.0
139 | return sign * pow(2.0, exponent - 127) * mantissa
140 |
141 | @staticmethod
142 | def bytes_to_hex(bytes):
143 | """ Converts list or array of bytes to an hex. """
144 | return ' '.join(format(h, '02X') for h in bytes)
145 |
146 | @staticmethod
147 | def hex_to_bytes(hexStr):
148 | """ Converts hex to array of bytes. """
149 | return bytearray.fromhex(hexStr)
150 |
151 | @staticmethod
152 | def int_to_bytes(intVal):
153 | """ Converts POSITIVE int to bytes. """
154 | return intVal.to_bytes(4, byteorder='little')
155 |
156 | @staticmethod
157 | def float_to_bytes(floatVal):
158 | """ Converts POSITIVE floats to bytes.
159 | Based heavily upon http: //www.simplymodbus.ca/ieeefloats.xls
160 | """
161 | # Error when floatVal=0.5
162 | return struct.pack('f',floatVal)
163 |
164 | if floatVal == 0: return (0).to_bytes(4, byteorder='big')
165 |
166 | sign = -1 if floatVal < 0 else 1
167 | firstBit = 0 if sign == 1 else 1
168 | exponent = -127 if abs(floatVal) < 1.1754943E-38 else floor(log(abs(floatVal), 10) / log(2, 10))
169 | exponent127 = exponent + 127
170 | mantissa = floatVal / pow(2, exponent) / sign
171 | substract = mantissa - 1
172 | multiply = round(substract * 8388608)
173 | div256_1 = multiply / 256
174 | divint_1 = int(div256_1)
175 | rem_1 = int((div256_1 - divint_1) * 256)
176 | div256_2 = divint_1 / 256
177 | divint_2 = int(div256_2)
178 | rem_2 = int((div256_2 - divint_2) * 256)
179 |
180 | bin1 = (exponent127 & 0b11111110) >> 1 | firstBit << 7
181 | bin2 = (exponent127 & 0b00000001) << 7 | divint_2
182 | bin3 = rem_2
183 | bin4 = rem_1
184 | # print ("ALT: ",bin(bin1_new), bin(bin2_new),bin(bin3_new),bin(bin4_new))
185 | bin1234 = bin1 | bin2 << 8 | bin3 << 16 | bin4 << 24
186 | return bin1234.to_bytes(4, byteorder='big')
187 |
188 | @staticmethod
189 | def convBytes(bytes, bType):
190 | """ Converts all photonfile types to bytes. """
191 | nr = None
192 | if bType == PhotonFile.tpInt:
193 | nr = PhotonFile.bytes_to_int(bytes)
194 | if bType == PhotonFile.tpFloat:
195 | nr = PhotonFile.bytes_to_float(bytes)
196 | if bType == PhotonFile.tpByte:
197 | nr = PhotonFile.bytes_to_hex(bytes)
198 | return nr
199 |
200 |
201 | ########################################################################################################################
202 | ## History methods
203 | ########################################################################################################################
204 |
205 |
206 | def realDeepCopy(self,dictionary):
207 | return #probable not needed
208 | """ Makes a real copy of a dictionary consisting of bytes strings
209 | """
210 | hC = copy.deepcopy(self.Header)
211 | for key,byteString in dictionary.items():
212 | dictionary[key]=(byteString+b'\x00')[:-1] # Force to make a real copy
213 |
214 |
215 | def saveToHistory(self, action, layerNr):
216 | """ Makes a copy of current /Layer Data to memory
217 | Since all are bytearrays no Copy.Deepcopy is needed.
218 | """
219 |
220 | # Copy LayerDefs and LayerData
221 | layerDef=copy.deepcopy(self.LayerDefs[layerNr])
222 | layerData=copy.deepcopy(self.LayerData[layerNr])
223 | self.realDeepCopy(layerDef)
224 | self.realDeepCopy(layerData)
225 |
226 | # Append to history stack/array
227 | newH = {"Action":action,"LayerNr":layerNr,"LayerDef":layerDef,"LayerData":layerData}
228 | print("Stored:",newH,id(layerDef),id(layerData))
229 | self.History.append(newH)
230 | if len(self.History)>self.HistoryMaxDepth:
231 | self.History.remove(self.History[0])
232 |
233 |
234 | def loadFromHistory(self):
235 | """ Load a copy of current Header/Preview/Layer Data to memory
236 | We copy by reference and remove item from history stack.
237 | """
238 |
239 | if len(self.History)==0:
240 | raise Exception("You have reached the maximum depth to undo.")
241 |
242 | # Find last item added to History
243 | idxLastAdded=len(self.History)-1
244 | lastItemAdded=self.History[idxLastAdded]
245 | action=lastItemAdded["Action"]
246 | layerNr =lastItemAdded["LayerNr"]
247 | layerDef = lastItemAdded["LayerDef"]
248 | layerData = lastItemAdded["LayerData"]
249 | print("Found:", self.History[idxLastAdded])
250 |
251 | # Reverse the actions
252 | if action=="insert":
253 | self.deleteLayer(layerNr, saveToHistory=False)
254 | elif action=="delete":
255 | self.clipboardDef=layerDef
256 | self.clipboardData=layerData
257 | self.insertLayerBefore(layerNr,fromClipboard=True, saveToHistory=False)
258 | elif action=="replace":
259 | self.clipboardDef=layerDef
260 | self.clipboardData=layerData
261 | self.deleteLayer(layerNr)
262 | self.insertLayerBefore(layerNr,fromClipboard=True, saveToHistory=False)
263 |
264 | # Remove this item
265 | self.History.remove(lastItemAdded)
266 |
267 | #Make alias for loadFromHistory
268 | undo = loadFromHistory
269 |
270 | ########################################################################################################################
271 | ## Class methods
272 | ########################################################################################################################
273 |
274 | def __init__(self, photonfilename):
275 | """ Just stores photon filename. """
276 | self.filename = photonfilename
277 |
278 |
279 | def nrLayers(self):
280 | """ Returns 4 bytes for number of layers as int. """
281 | return PhotonFile.bytes_to_int(self.Header[self.nrLayersString])
282 |
283 |
284 | def readFile(self):
285 | """ Reads the photofile from disk to memory. """
286 |
287 | with open(self.filename, "rb") as binary_file:
288 |
289 | # Start at beginning
290 | binary_file.seek(0)
291 |
292 | # Read HEADER / General settings
293 | for bTitle, bNr, bType, bEditable,bHint in self.pfStruct_Header:
294 | self.Header[bTitle] = binary_file.read(bNr)
295 |
296 | # Read PREVIEWS settings and raw image data
297 | prevAddr=[]
298 | prevAddr.append(PhotonFile.bytes_to_int(self.Header["Preview 0 (addr)"]))
299 | prevAddr.append(PhotonFile.bytes_to_int(self.Header["Preview 1 (addr)"]))
300 |
301 | for previewNr in (0,1):
302 | binary_file.seek(prevAddr[previewNr])
303 | for bTitle, bNr, bType, bEditable, bHint in self.pfStruct_Previews:
304 | # if rawData0 or rawData1 the number bytes to read is given bij dataSize0 and dataSize1
305 | if bTitle == "Image Data": bNr = dataSize
306 | self.Previews[previewNr][bTitle] = binary_file.read(bNr)
307 | if bTitle == "Data Length": dataSize = PhotonFile.bytes_to_int(self.Previews[previewNr][bTitle])
308 |
309 | layerDefAddr=PhotonFile.bytes_to_int(self.Header["Layer Defs (addr)"])
310 | binary_file.seek(layerDefAddr)
311 |
312 | # Read LAYERDEFS settings
313 | nLayers = PhotonFile.bytes_to_int(self.Header[self.nrLayersString])
314 | self.LayerDefs = [dict() for x in range(nLayers)]
315 | # print("nLayers:", nLayers)
316 | # print(" hex:", ' '.join(format(x, '02X') for x in self.Header[self.nrLayersString]))
317 | # print(" dec:", nLayers)
318 | # print("Reading layer meta-info")
319 | for lNr in range(0, nLayers):
320 | # print(" layer: ", lNr)
321 | for bTitle, bNr, bType, bEditable, bHint in self.pfStruct_LayerDef:
322 | self.LayerDefs[lNr][bTitle] = binary_file.read(bNr)
323 |
324 | # Read LAYERRAWDATA image data
325 | # print("Reading layer image-info")
326 | self.LayerData = [dict() for x in range(nLayers)]
327 | for lNr in range(0, nLayers):
328 | rawDataAddr = PhotonFile.bytes_to_int(self.LayerDefs[lNr]["Image Address"])
329 | rawDataSize = PhotonFile.bytes_to_int(self.LayerDefs[lNr]["Data Length"])
330 | binary_file.seek(rawDataAddr)
331 | # print(" layer: ", lNr, " size: ",rawDataSize)
332 | self.LayerData[lNr]["Raw"] = binary_file.read(rawDataSize - 1) # b'}}}}}}}}}}
333 | # -1 because we don count byte for endOfLayer
334 | self.LayerData[lNr]["EndOfLayer"] = binary_file.read(1)
335 |
336 | # print (' '.join(format(x, '02X') for x in header))
337 |
338 | # Clear History for this new file
339 | self.History = []
340 |
341 |
342 | def writeFile(self, newfilename=None):
343 | """ Writes the photofile from memory to disk. """
344 |
345 | # Check if other filename is given to save to, otherwise use filename used to load file.
346 | if newfilename == None: newfilename = self.filename
347 |
348 |
349 | with open(newfilename, "wb") as binary_file:
350 |
351 | # Start at beginning
352 | binary_file.seek(0)
353 |
354 | # Write HEADER / General settings
355 | for bTitle, bNr, bType, bEditable,bHint in self.pfStruct_Header:
356 | binary_file.write(self.Header[bTitle])
357 |
358 | # Write PREVIEWS settings and raw image data
359 | for previewNr in (0, 1):
360 | for bTitle, bNr, bType, bEditable, bHint in self.pfStruct_Previews:
361 | #print ("Save: ",bTitle)
362 | binary_file.write(self.Previews[previewNr][bTitle])
363 |
364 | # Read LAYERDEFS settings
365 | nLayers = PhotonFile.bytes_to_int(self.Header[self.nrLayersString])
366 | for lNr in range(0, nLayers):
367 | #print(" layer: ", lNr)
368 | #print(" def: ", self.LayerDefs[lNr])
369 | for bTitle, bNr, bType, bEditable, bHint in self.pfStruct_LayerDef:
370 | binary_file.write(self.LayerDefs[lNr][bTitle])
371 |
372 | # Read LAYERRAWDATA image data
373 | # print("Reading layer image-info")
374 | for lNr in range(0, nLayers):
375 | binary_file.write(self.LayerData[lNr]["Raw"])
376 | binary_file.write(self.LayerData[lNr]["EndOfLayer"])
377 |
378 |
379 | ########################################################################################################################
380 | ## Encoding
381 | ########################################################################################################################
382 |
383 | def encodedBitmap_Bytes_withnumpy(filename):
384 | """ Converts image data from file on disk to RLE encoded byte string.
385 | Uses Numpy library - Fast
386 | Based on https://gist.github.com/itdaniher/3f57be9f95fce8daaa5a56e44dd13de5
387 | Encoding scheme:
388 | Highest bit of each byte is color (black or white)
389 | Lowest 7 bits of each byte is repetition of that color, with max of 125 / 0x7D
390 | """
391 |
392 | # Load image and check if size is correct (1440 x 2560)
393 | imgsurf = pygame.image.load(filename)
394 | (width, height) = imgsurf.get_size()
395 | if not (width, height) == (1440, 2560):
396 | raise Exception("Your image dimensions are off and should be 1440x2560")
397 |
398 | # Convert image data to Numpy 1-dimensional array
399 | imgarr = pygame.surfarray.array2d(imgsurf)
400 | imgarr = numpy.rot90(imgarr,axes=(1,0))
401 | imgarr = numpy.fliplr(imgarr) # reverse/mirror array
402 | x = numpy.asarray(imgarr).flatten(0)
403 |
404 | # Encoding magic
405 | where = numpy.flatnonzero
406 | x = numpy.asarray(x)
407 | n = len(x)
408 | if n == 0:
409 | return numpy.array([], dtype=numpy.int)
410 | starts = numpy.r_[0, where(~numpy.isclose(x[1:], x[:-1], equal_nan=True)) + 1]
411 | lengths = numpy.diff(numpy.r_[starts, n])
412 | values = x[starts]
413 | #ret=np.dstack((lengths, values))[0]
414 |
415 | # Reduce repetitions of color to max 0x7D/125 and store in bytearray
416 | rleData = bytearray()
417 | for (nr, col) in zip(lengths,values):
418 | color = (col>0)
419 | while nr > 0x7D:
420 | encValue = (color << 7) | 0x7D
421 | rleData.append(encValue)
422 | nr = nr - 0x7D
423 | encValue = (color << 7) | nr
424 | rleData.append(encValue)
425 |
426 | # Needed is an byte string, so convert
427 | return bytes(rleData)
428 |
429 |
430 | def encodedBitmap_Bytes_nonumpy(filename):
431 | """ Converts image data from file on disk to RLE encoded byte string.
432 | Processes pixels one at a time (pygame.get_at) - Slow
433 | Encoding scheme:
434 | Highest bit of each byte is color (black or white)
435 | Lowest 7 bits of each byte is repetition of that color, with max of 125 / 0x7D
436 | """
437 |
438 | # Load image and check if size is correct (1440 x 2560)
439 | imgsurf = pygame.image.load(filename)
440 | #bitDepth = imgsurf.get_bitsize()
441 | #bytePerPixel = imgsurf.get_bytesize()
442 | (width, height) = imgsurf.get_size()
443 | if not (width, height) == (1440,2560):
444 | raise Exception("Your image dimensions are off and should be 1440x2560")
445 |
446 | # Count number of pixels with same color up until 0x7D/125 repetitions
447 | rleData = bytearray()
448 | color = 0
449 | black = 0
450 | white = 1
451 | nrOfColor = 0
452 | prevColor=None
453 | for y in range(height):
454 | for x in range(width):
455 | # print (imgsurf.get_at((x, y)))
456 | (r, g, b, a) = imgsurf.get_at((x, y))
457 | if ((r + g + b) // 3) < 128:
458 | color = black
459 | else:
460 | color = white
461 | if prevColor == None: prevColor = color
462 | isLastPixel = (x == (width - 1) and y == (height - 1))
463 | if color == prevColor and nrOfColor < 0x7D and not isLastPixel:
464 | nrOfColor = nrOfColor + 1
465 | else:
466 | #print (color,nrOfColor,nrOfColor<<1)
467 | encValue = (prevColor << 7) | nrOfColor # push color (B/W) to highest bit and repetitions to lowest 7 bits.
468 | rleData.append(encValue)
469 | prevColor = color
470 | nrOfColor = 1
471 | return bytes(rleData)
472 |
473 |
474 | def encodedBitmap_Bytes(filename):
475 | """ Depening on availability of Numpy, calls upon correct Encoding method."""
476 | if numpyAvailable:
477 | return PhotonFile.encodedBitmap_Bytes_withnumpy(filename)
478 | else:
479 | return PhotonFile.encodedBitmap_Bytes_nonumpy(filename)
480 |
481 |
482 | ########################################################################################################################
483 | ## Decoding
484 | ########################################################################################################################
485 |
486 | def getBitmap_withnumpy(self, layerNr, forecolor=(128,255,128), backcolor=(0,0,0),scale=(0.25,0.25)):
487 | """ Decodes a RLE byte array from PhotonFile object to a pygame surface.
488 | Based on: https://gist.github.com/itdaniher/3f57be9f95fce8daaa5a56e44dd13de5
489 | Encoding scheme:
490 | Highest bit of each byte is color (black or white)
491 | Lowest 7 bits of each byte is repetition of that color, with max of 125 / 0x7D
492 | """
493 |
494 | # Tell PhotonFile we are drawing so GUI can prevent too many calls on getBitmap
495 | memory = pygame.Surface((int(1440 * scale[0]), int(2560 * scale[1])))
496 | if self.nrLayers()==0: return memory #could occur if loading new file
497 | self.isDrawing = True
498 |
499 | # Retrieve raw image data and add last byte to complete the byte array
500 | bA = self.LayerData[layerNr]["Raw"]
501 | # add endOfLayer Byte
502 | bA = bA + self.LayerData[layerNr]["EndOfLayer"]
503 |
504 | # Convert bytes to numpy 1 dimensional array
505 | bN =numpy.fromstring(bA,dtype=numpy.uint8)
506 |
507 |
508 | # Extract color value (highest bit) and nr of repetitions (lowest 7 bits)
509 | valbin = bN >> 7 # only read 1st bit
510 | nr = bN & ~(1 << 7) # turn highest bit of
511 |
512 | # Replace 0's en 1's with correct colors
513 | forecolor_int = (forecolor[0] << 16) + (forecolor[1] << 8) + forecolor[2]
514 | backcolor_int = backcolor[0] << 16 + backcolor[1] << 8 + backcolor[2]
515 | val = numpy.array([{0: backcolor_int, 1: forecolor_int}[x] for x in valbin])
516 |
517 | # Make a 2d array like [ [3,0] [2,1], [nr_i,val_i]...] using the colorvalues (val) and repetitions(nr)
518 | runs = numpy.column_stack((nr, val))
519 |
520 | # Decoding magic
521 | runs_t = numpy.transpose(runs)
522 | lengths = runs_t[0].astype(int)
523 | values = runs_t[1].astype(int)
524 | starts = numpy.concatenate(([0], numpy.cumsum(lengths)[:-1]))
525 | starts, lengths, values = map(numpy.asarray, (starts, lengths, values))
526 | ends = starts + lengths
527 | n = ends[-1]
528 | x = numpy.full(n, 0)
529 | for lo, hi, val in zip(starts, ends, values):
530 | x[lo:hi] = val
531 |
532 | # Make sure we have a bitmap of the correct size and if not pad with black pixels
533 | if not len(x) == 3686400: print ("Warning: The file decoded with less bytes than needed. Will pad the file with zero bytes.")
534 | while not len(x)==3686400:
535 | x=numpy.append(x,(0,))
536 |
537 | # Convert 1-dim array to matrix
538 | rgb2d=x.reshape((2560,1440)) # data is stored in rows of 2560
539 | rgb2d = numpy.rot90(rgb2d, axes=(1, 0)) # we need 1440x2560
540 | rgb2d = numpy.fliplr(rgb2d) # however data us mirrored along x axis
541 | picture=pygame.surfarray.make_surface(rgb2d)# convert numpy array to pygame surface
542 | memory=pygame.transform.scale(picture, (int(1440*scale[0]), int(2560*scale[1]))) # rescale for display in window
543 |
544 | # Done drawing so next caller knows that next call can be made.
545 | self.isDrawing = False
546 | return memory
547 |
548 |
549 | def getBitmap_nonumpy(self, layerNr, forecolor=(128,255,128), backcolor=(0,0,0),scale=(0.25,0.25)):
550 | """ Decodes a RLE byte array from PhotonFile object to a pygame surface.
551 | Based on: https://gist.github.com/itdaniher/3f57be9f95fce8daaa5a56e44dd13de5
552 | Encoding scheme:
553 | Highest bit of each byte is color (black or white)
554 | Lowest 7 bits of each byte is repetition of that color, with max of 125 / 0x7D
555 | """
556 |
557 | # Tell PhotonFile we are drawing so GUI can prevent too many calls on getBitmap
558 | memory = pygame.Surface((int(1440 * scale[0]), int(2560 * scale[1])))
559 | if self.nrLayers()==0: return memory #could occur if loading new file
560 | self.isDrawing = True
561 |
562 | # Retrieve raw image data and add last byte to complete the byte array
563 | bA = self.LayerData[layerNr]["Raw"]
564 | # add endOfLayer Byte
565 | bA = bA + self.LayerData[layerNr]["EndOfLayer"]
566 |
567 | # Decode bytes to colors and draw lines of that color on the pygame surface
568 | x = 0
569 | y = 0
570 | for idx, b in enumerate(bA):
571 | # From each byte retrieve color (highest bit) and number of pixels of that color (lowest 7 bits)
572 | nr = b & ~(1 << 7) # turn highest bit of
573 | val = b >> 7 # only read 1st bit
574 |
575 | # The surface to draw on is smaller (scale) than the file (1440x2560 pixels)
576 | x1 = int(x *scale[0])
577 | y1 = int(y *scale[1])
578 | x2 = int((x + nr) *scale[0])
579 | y2 = y1
580 | if val==0:
581 | col= backcolor
582 | else:
583 | col=forecolor
584 | # Bytes and repetions of pixels with same color can span muliple lines (y-values)
585 | if x2 > int(1440 *scale[0]): x2 = int(1440 *scale[1])
586 | pygame.draw.line(memory, col, (x1, y1), (x2, y2))
587 | # debug nr2=nr-(x+nr-1440) if (x+nr)>=1440 else nr
588 | # debug print("draw line: ", x, y, " - ", nr2)
589 | x = x + nr
590 | if x >= 1440:
591 | nr = x - 1440
592 | x = 0
593 | y = y + 1
594 | x1 = int(x *scale[0])
595 | y1 = int(y *scale[1])
596 | x2 = int((x + nr) *scale[0])
597 | y2 = y1
598 | pygame.draw.line(memory, col, (x1, y1), (x2, y2))
599 | # debug print ("draw line: ",x,y," - ",nr)
600 | x = x + nr
601 | #print("Screen Drawn")
602 | # debug print ("layer: ", layerNr)
603 | # debug print ("lastByte:", self.LayerData[layerNr]["EndOfLayer"])
604 |
605 | # Done drawing so next caller knows that next call can be made.
606 | self.isDrawing = False
607 | return memory
608 |
609 |
610 | def getBitmap(self, layerNr, forecolor=(128, 255, 128), backcolor=(0, 0, 0), scale=(0.25, 0.25)):
611 | """ Depending on availability of Numpy, calls upon correct Decoding method."""
612 | if numpyAvailable:
613 | return self.getBitmap_withnumpy(layerNr,forecolor,backcolor,scale)
614 | else:
615 | return self.getBitmap_nonumpy(layerNr,forecolor,backcolor,scale)
616 |
617 |
618 | def getPreviewBitmap(self, prevNr):
619 | """ Decodes a RLE byte array from PhotonFile object to a pygame surface.
620 | Based on https://github.com/Reonarudo/pcb2photon/issues/2
621 | Encoding scheme:
622 | The color (R,G,B) of a pixel spans 2 bytes (little endian) and each color component is 5 bits: RRRRR GGG GG X BBBBB
623 | If the X bit is set, then the next 2 bytes (little endian) masked with 0xFFF represents how many more times to repeat that pixel.
624 | """
625 |
626 | # Tell PhotonFile we are drawing so GUI can prevent too many calls on getBitmap
627 | self.isDrawing = True
628 |
629 | # Retrieve resolution of preview image and set pygame surface to that size.
630 | w = PhotonFile.bytes_to_int(self.Previews[prevNr]["Resolution X"])
631 | h = PhotonFile.bytes_to_int(self.Previews[prevNr]["Resolution Y"])
632 | s = PhotonFile.bytes_to_int(self.Previews[prevNr]["Data Length"])
633 | scale = ((1440 / 4) / w, (1440 / 4) / w)
634 | memory = pygame.Surface((int(w), int(h)))
635 | if w == 0 or h == 0: return memory # if size is (0,0) we return empty surface
636 |
637 | # Retrieve raw image data and add last byte to complete the byte array
638 | bA = self.Previews[prevNr]["Image Data"]
639 |
640 | # Decode bytes to colors and draw lines of that color on the pygame surface
641 | idx = 0
642 | pixelIdx = 0
643 | while idx < len(bA):
644 | # Combine 2 bytes Little Endian so we get RRRRR GGG GG X BBBBB (and advance read byte counter)
645 | b12 = bA[idx + 1] << 8 | bA[idx + 0]
646 | idx += 2
647 | # Retrieve colr components and make pygame color tuple
648 | red = math.floor(((b12 >> 11) & 0x1F) / 31 * 255)
649 | green = math.floor(((b12 >> 6) & 0x1F) / 31 * 255)
650 | blue = math.floor(((b12 >> 0) & 0x1F) / 31 * 255)
651 | col = (red, green, blue)
652 |
653 | # If the X bit is set, then the next 2 bytes (little endian) masked with 0xFFF represents how many more times to repeat that pixel.
654 | nr = 1
655 | if b12 & 0x20:
656 | nr12 = bA[idx + 1] << 8 | bA[idx + 0]
657 | idx += 2
658 | nr += nr12 & 0x0FFF
659 |
660 | # Draw (nr) many pixels of the color
661 | for i in range(0, nr, 1):
662 | x = int((pixelIdx % w))
663 | y = int((pixelIdx / w))
664 | memory.set_at((x, y), col)
665 | pixelIdx += 1
666 |
667 | # Scale the surface to the wanted resolution
668 | memory = pygame.transform.scale(memory, (int(w * scale[0]), int(h * scale[1])))
669 |
670 | # Done drawing so next caller knows that next call can be made.
671 | self.isDrawing = False
672 | return memory
673 |
674 |
675 | ########################################################################################################################
676 | ## Layer (Image) Operations
677 | ########################################################################################################################
678 |
679 | def layerHeight(self,layerNr):
680 | """ Return height between two layers
681 | """
682 | # We retrieve layer height from previous layer
683 | if layerNr>0:
684 | curLayerHeight = self.bytes_to_float(self.LayerDefs[layerNr]["Layer height (mm)"])
685 | prevLayerHeight = self.bytes_to_float(self.LayerDefs[layerNr-1]["Layer height (mm)"])
686 | else:
687 | if self.nrLayers()>1:
688 | curLayerHeight = self.bytes_to_float(self.LayerDefs[layerNr+1]["Layer height (mm)"])
689 | prevLayerHeight=0
690 | else:
691 | curLayerHeight=self.bytes_to_float(self.Header["Layer height (mm)"])
692 | prevLayerHeight = 0
693 | return curLayerHeight-prevLayerHeight
694 | #print ("Delta:", deltaHeight)
695 |
696 |
697 | def deleteLayer(self, layerNr, saveToHistory=True):
698 | """ Deletes layer and its image data in the PhotonFile object, but store in clipboard for paste. """
699 |
700 | # Store all data to history
701 | if saveToHistory: self.saveToHistory("delete",layerNr)
702 |
703 | #deltaHeight=self.bytes_to_float(self.LayerDefs[layerNr]["Layer height (mm)"])
704 | deltaHeight =self.layerHeight(layerNr)
705 | print ("deltaHeight:",deltaHeight)
706 |
707 | # Update start addresses of RawData of before deletion with size of one extra layerdef (36 bytes)
708 | for rLayerNr in range(0,layerNr):
709 | # Adjust image address for removal of image raw data and end byte
710 | curAddr=self.bytes_to_int(self.LayerDefs[rLayerNr]["Image Address"])
711 | newAddr=curAddr-36 # size of layerdef
712 | self.LayerDefs[rLayerNr]["Image Address"]= self.int_to_bytes(newAddr)
713 |
714 | # Update start addresses of RawData of after deletion with size of image and layerdef
715 | deltaLength = self.bytes_to_int(self.LayerDefs[layerNr]["Data Length"]) + 36 # +1 for len(EndOfLayer)
716 | nLayers=self.nrLayers()
717 | for rLayerNr in range(layerNr+1,nLayers):
718 | # Adjust image address for removal of image raw data and end byte
719 | curAddr=self.bytes_to_int(self.LayerDefs[rLayerNr]["Image Address"])
720 | newAddr=curAddr-deltaLength
721 | #print ("layer, cur, new: ",rLayerNr,curAddr,newAddr)
722 | self.LayerDefs[rLayerNr]["Image Address"]= self.int_to_bytes(newAddr)
723 |
724 | # Adjust layer starting height for removal of layer
725 | curHeight=self.bytes_to_float(self.LayerDefs[rLayerNr]["Layer height (mm)"])
726 | newHeight=curHeight-deltaHeight
727 | self.LayerDefs[rLayerNr]["Layer height (mm)"] =self.float_to_bytes(newHeight)
728 |
729 | # Store deleted layer in clipboard
730 | self.clipboardDef=self.LayerDefs[layerNr].copy()
731 | self.clipboardData=self.LayerData[layerNr].copy()
732 |
733 | # Delete layer settings and data and reduce number of layers in header
734 | self.LayerDefs.remove(self.LayerDefs[layerNr])
735 | self.LayerData.remove(self.LayerData[layerNr])
736 | self.Header[self.nrLayersString]=self.int_to_bytes(self.nrLayers()-1)
737 |
738 | def insertLayerBefore(self, layerNr, fromClipboard=False, saveToHistory=True):
739 | """ Inserts layer copying data of the previous layer or the clipboard. """
740 | if fromClipboard and self.clipboardDef==None: raise Exception("Clipboard is empty!")
741 |
742 | # Store all data to history
743 | if saveToHistory: self.saveToHistory("insert",layerNr)
744 |
745 | # Check if layerNr in range, could occur on undo after deleting last layer
746 | # print(layerNr, "/", self.nrLayers())
747 | insertLast=False
748 | if layerNr>self.nrLayers(): layerNr=self.nrLayers()
749 | if layerNr == self.nrLayers():
750 | layerNr=layerNr-1 # temporary reduce layerNr
751 | insertLast=True
752 |
753 | # Check deltaHeight
754 | deltaHeight = self.layerHeight(layerNr)
755 |
756 | # Make duplicate of layerDef and layerData if not pasting from clipboard
757 | if fromClipboard == False:
758 | self.clipboardDef=self.LayerDefs[layerNr].copy()
759 | self.clipboardData=self.LayerData[layerNr].copy()
760 |
761 | # Set layerheight correctly
762 | if layerNr==0: # if first layer than the height should start at 0
763 | self.clipboardDef["Layer height (mm)"] = self.float_to_bytes(0)
764 | else: # start at layer height of layer at which we insert
765 | curLayerHeight = self.bytes_to_float(self.LayerDefs[layerNr]["Layer height (mm)"])
766 | self.clipboardDef["Layer height (mm)"]=self.float_to_bytes(curLayerHeight)
767 |
768 | # Set start addresses of layer in clipboard, we add 1 layer(def) so add 36 bytes
769 | lA=self.bytes_to_int(self.LayerDefs[layerNr]["Image Address"])+36
770 | # if lastlayer we need to add last image length
771 | if insertLast: lA=lA+self.bytes_to_int(self.LayerDefs[layerNr]["Data Length"])
772 | self.clipboardDef["Image Address"]=self.int_to_bytes(lA)
773 |
774 | # If we inserting last layer, we correct layerNr
775 | if insertLast: layerNr = layerNr + 1 # fix temporary reduced layerNr
776 |
777 | # Update start addresses of RawData of before insertion with size of one extra layerdef (36 bytes)
778 | for rLayerNr in range(0,layerNr):
779 | # Adjust image address for removal of image raw data and end byte
780 | curAddr=self.bytes_to_int(self.LayerDefs[rLayerNr]["Image Address"])
781 | newAddr=curAddr+36 # size of layerdef
782 | self.LayerDefs[rLayerNr]["Image Address"]= self.int_to_bytes(newAddr)
783 |
784 | # Update start addresses of RawData of after insertion with size of image and layerdef
785 | # Calculate how much room we need in between. We insert an extra layerdef (36 bytes) and a extra image
786 | deltaLayerImgAddress = self.bytes_to_int(self.clipboardDef["Data Length"]) + 36
787 | nLayers=self.nrLayers()
788 | # remove
789 | for rLayerNr in range(layerNr,nLayers):
790 | # Adjust image address for removal of image raw data and end byte
791 | curAddr=self.bytes_to_int(self.LayerDefs[rLayerNr]["Image Address"])
792 | newAddr=curAddr+deltaLayerImgAddress
793 | self.LayerDefs[rLayerNr]["Image Address"]= self.int_to_bytes(newAddr)
794 |
795 | # Adjust layer starting height for removal of layer
796 | curHeight=self.bytes_to_float(self.LayerDefs[rLayerNr]["Layer height (mm)"])
797 | newHeight=curHeight+deltaHeight
798 | self.LayerDefs[rLayerNr]["Layer height (mm)"] =self.float_to_bytes(newHeight)
799 | #print ("layer, cur, new: ",rLayerNr,curAddr,newAddr, "|", curHeight,newHeight ,">",self.bytes_to_float(self.LayerDefs[rLayerNr]["Layer height (mm)"]))
800 |
801 | # Insert layer settings and data and reduce number of layers in header
802 | self.LayerDefs.insert(layerNr, self.clipboardDef)
803 | self.LayerData.insert(layerNr, self.clipboardData)
804 |
805 | self.Header[self.nrLayersString]=self.int_to_bytes(self.nrLayers()+1)
806 |
807 | # Make new copy so second paste will not reference this inserted objects
808 | self.clipboardDef = self.LayerDefs[layerNr].copy()
809 | self.clipboardData = self.LayerData[layerNr].copy()
810 |
811 |
812 | def copyLayer(self,layerNr):
813 | # Make duplicate of layerDef and layerData
814 | self.clipboardDef=self.LayerDefs[layerNr].copy()
815 | self.clipboardData=self.LayerData[layerNr].copy()
816 |
817 |
818 | def replaceBitmap(self, layerNr,filePath, saveToHistory=True):
819 | """ Replace image data in PhotonFile object with new (encoded data of) image on disk."""
820 |
821 | print(" ", layerNr, "/", filePath)
822 |
823 | # Store all data to history
824 | if saveToHistory: self.saveToHistory("replace",layerNr)
825 |
826 | # Get/encode raw data
827 | rawData = PhotonFile.encodedBitmap_Bytes(filePath)
828 |
829 | # Last byte is stored seperately
830 | rawDataTrunc = rawData[:-1]
831 | rawDataLastByte = rawData[-1:]
832 |
833 | # Get change in image rawData size so we can correct starting addresses of higher layer images
834 | oldLength=self.bytes_to_int(self.LayerDefs[layerNr]["Data Length"]) #"Data Length" = len(rawData)+len(EndOfLayer)
835 | newLength=len(rawData)
836 | deltaLength=newLength-oldLength
837 | #print ("old, new, delta:",oldLength,newLength,deltaLength)
838 |
839 | # Update image settings and raw data of layer to be replaced
840 | self.LayerDefs[layerNr]["Data Length"] = self.int_to_bytes(len(rawData))
841 | self.LayerData[layerNr]["Raw"] = rawDataTrunc
842 | self.LayerData[layerNr]["EndOfLayer"] = rawDataLastByte
843 |
844 | # Update start addresses of RawData of all following images
845 | nLayers=self.nrLayers()
846 | for rLayerNr in range(layerNr+1,nLayers):
847 | curAddr=self.bytes_to_int(self.LayerDefs[rLayerNr]["Image Address"])
848 | newAddr=curAddr+deltaLength
849 | #print ("layer, cur, new: ",rLayerNr,curAddr,newAddr)
850 | self.LayerDefs[rLayerNr]["Image Address"]= self.int_to_bytes(newAddr)
851 |
852 |
853 | def replaceBitmaps(self, dirPath):
854 | """ Delete all images in PhotonFile object and add images in directory."""
855 |
856 | # Get all files, filter png-files and sort them alphabetically
857 | direntries = os.listdir(dirPath)
858 | files = []
859 | for entry in direntries:
860 | fullpath = os.path.join(dirPath, entry)
861 | if entry.endswith("png"):
862 | if not entry.startswith("_"): # on a export of images from a photon file, the preview image starts with _
863 | files.append(fullpath)
864 | files.sort()
865 |
866 | print("Following files will be inserted:")
867 | for fullpath in files:
868 | print(" ", fullpath)
869 |
870 | # Check if there are files available and if so check first file for correct dimensions
871 | if len(files) == 0: raise Exception("No files of type png are found!")
872 | rawData = PhotonFile.encodedBitmap_Bytes(files[0])
873 |
874 | # Remove old data in PhotonFile object
875 | nLayers = len(files)
876 | self.Header[self.nrLayersString] = self.int_to_bytes(nLayers)
877 | #oldLayerDef = self.LayerDefs[0]
878 | self.LayerDefs = [dict() for x in range(nLayers)]
879 | self.LayerData = [dict() for x in range(nLayers)]
880 |
881 | # Depending on nr of new images, set nr of bottom layers and total layers in Header
882 | # If only one image is supplied the file should be set as 0 base layers and 1 normal layer
883 | if nLayers == 1:
884 | self.Header["# Bottom Layers"] = self.int_to_bytes(0)
885 | # We can't have more bottom layers than total nr of layers
886 | nrBottomLayers=self.bytes_to_int(self.Header["# Bottom Layers"])
887 | if nrBottomLayers>nLayers: nrBottomLayers=nLayers-1
888 | self.Header["# Bottom Layers"] = self.int_to_bytes(nrBottomLayers)
889 | # Set total number of layers
890 | self.Header["# Layers"] = self.int_to_bytes(nLayers)
891 |
892 | # Calculate the start position of raw imagedata of the FIRST layer
893 | rawDataStartPos = 0
894 | for bTitle, bNr, bType, bEditable,bHint in self.pfStruct_Header:
895 | rawDataStartPos = rawDataStartPos + bNr
896 | for previewNr in (0,1):
897 | for bTitle, bNr, bType, bEditable, bHint in self.pfStruct_Previews:
898 | if bTitle == "Image Data": bNr = dataSize
899 | rawDataStartPos = rawDataStartPos + bNr
900 | if bTitle == "Data Length": dataSize = PhotonFile.bytes_to_int(self.Previews[previewNr][bTitle])
901 | for bTitle, bNr, bType, bEditable, bHint in self.pfStruct_LayerDef:
902 | rawDataStartPos = rawDataStartPos + bNr * nLayers
903 |
904 | # For each image file, get encoded raw image data and store in Photon File object, copying layer settings from Header/General settings.
905 | curLayerHeight=0.0
906 | deltaLayerHeight=self.bytes_to_float(self.Header["Layer height (mm)"])
907 | print("Processing:")
908 | for layerNr, file in enumerate(files):
909 | print(" ", layerNr,"/",nLayers, file)
910 | # Get encoded raw data
911 | rawData = PhotonFile.encodedBitmap_Bytes(file)
912 | rawDataTrunc = rawData[:-1]
913 | rawDataLastByte = rawData[-1:]
914 |
915 | # Update layer settings (LayerDef)
916 | # todo: following should be better coded
917 | self.LayerDefs[layerNr]["Layer height (mm)"] = self.float_to_bytes(curLayerHeight)
918 | if layerNr 0.25
1051 | for i in range (0,20):
1052 | bA=PhotonFile.float_to_bytes(c)
1053 | bHA=PhotonFile.bytes_to_hex(bA)
1054 | bB=PhotonFile.bytes_to_float(bA)
1055 | print (i,bA,bHA, bB)
1056 | c = c + 0.05
1057 | #quit()
1058 | '''
1059 | '''
1060 | files=("SamplePhotonFiles/Debug/debug 0.05mm (err).photon",
1061 | "SamplePhotonFiles/Debug/debug 0.07mm (err).photon",
1062 | "SamplePhotonFiles/Debug/debug 0.08mm (err).photon",
1063 | "SamplePhotonFiles/Debug/debug 0.09mm (err).photon",
1064 | "SamplePhotonFiles/Debug/debug 0.10mm.photon",
1065 | "SamplePhotonFiles/Debug/debug 0.11mm.photon",
1066 | "SamplePhotonFiles/Debug/debug 0.12mm.photon",
1067 | "SamplePhotonFiles/Debug/debug 0.13mm.photon",
1068 | "SamplePhotonFiles/Debug/debug 0.14mm.photon",
1069 | "SamplePhotonFiles/Debug/debug 0.15mm (err).photon",
1070 | "SamplePhotonFiles/Debug/debug 0.20mm.photon",
1071 | "SamplePhotonFiles/Debug/debug 0.25mm.photon",
1072 | "SamplePhotonFiles/Debug/debug 0.30mm.photon",
1073 | "SamplePhotonFiles/Debug/debug 0.35mm.photon",
1074 | "SamplePhotonFiles/Debug/debug 0.40mm.photon",
1075 | "SamplePhotonFiles/Debug/debug 0.45mm.photon",
1076 | "SamplePhotonFiles/Debug/debug 0.50mm.photon",
1077 | "SamplePhotonFiles/Debug/debug 0.55mm (err).photon",
1078 | "SamplePhotonFiles/Debug/debug 0.60mm.photon",
1079 | "SamplePhotonFiles/Debug/debug 0.65mm.photon",
1080 | "SamplePhotonFiles/Debug/debug 0.70mm.photon",
1081 | "SamplePhotonFiles/Debug/debug 0.75mm.photon",
1082 | "SamplePhotonFiles/Debug/debug 0.80mm.photon",
1083 | )
1084 | '''
1085 | '''
1086 | files=("SamplePhotonFiles/Debug/debug 0.65mm test.photon",)
1087 | for file in files:
1088 | ph=PhotonFile(file)
1089 | ph.readFile()
1090 | print ( file[30:34],':',
1091 | PhotonFile.bytes_to_int(ph.Header["# Layers"]),
1092 | PhotonFile.bytes_to_int(ph.Header["Preview 0 (addr)"]),
1093 | PhotonFile.bytes_to_int(ph.Header["Preview 1 (addr)"]),
1094 | PhotonFile.bytes_to_int(ph.Previews[0]["Image Address"]),
1095 | PhotonFile.bytes_to_int(ph.Previews[0]["Data Length"]),
1096 | PhotonFile.bytes_to_int(ph.Previews[1]["Image Address"]),
1097 | PhotonFile.bytes_to_int(ph.Previews[1]["Data Length"]),
1098 | PhotonFile.bytes_to_int(ph.Header["Layer Defs (addr)"]),
1099 | )
1100 | '''
1101 |
1102 | """
1103 | ("Header", 8, tpByte, False),
1104 | ("Bed X (mm)", 4, tpFloat, True),
1105 | ("Bed Y (mm)", 4, tpFloat, True),
1106 | ("Bed Z (mm)", 4, tpFloat, True),
1107 | ("padding0", 3 * 4, tpByte, False), # 3 ints
1108 | ("Layer height (mm)", 4, tpFloat, True),
1109 | ("Exp. time (s)", 4, tpFloat, True),
1110 | ("Exp. bottom (s)", 4, tpFloat, True),
1111 | ("Off time (s)", 4, tpFloat, True),
1112 | ("# Bottom Layers", 4, tpInt, True),
1113 | ("Resolution X", 4, tpInt, True),
1114 | ("Resolution Y", 4, tpInt, True),
1115 | ("Preview 0 (addr)", 4, tpInt, False), # start of preview 0
1116 | ("Layer Defs (addr)", 4, tpInt, False), # start of layerDefs
1117 | (nrLayersString, 4, tpInt, False),
1118 | ("Preview 1 (addr)", 4, tpInt, False), # start of preview 1
1119 | ("unknown6", 4, tpInt, False),
1120 | ("Proj.type-Cast/Mirror", 4, tpInt, False), # LightCuring/Projection type // (1=LCD_X_MIRROR, 0=CAST)
1121 | ("padding1", 6 * 4, tpByte, False) # 6 ints
1122 | ]
1123 |
1124 | pfStruct_Previews = [
1125 | ("Resolution X", 4, tpInt, False),
1126 | ("Resolution Y", 4, tpInt, False),
1127 | ("Image Address", 4, tpInt, False), # start of rawData0
1128 | ("Data Length", 4, tpInt, False), # size of rawData0
1129 | ("padding", 4 * 4, tpByte, False), # 4 ints
1130 | ("Image Data", -1, tpByte, False),
1131 | ]
1132 |
1133 | pfStruct_LayerDef = [
1134 | ("Layer height (mm)", 4, tpFloat, True),
1135 | ("Exp. time (s)", 4, tpFloat, True),
1136 | ("Off time (s)", 4, tpFloat, True),
1137 | ("Image Address", 4, tpInt, False), # dataStartPos -> Image Address
1138 | ("Data Length", 4, tpInt, False), # size of rawData+lastByte(1)
1139 | ("padding", 4 * 4, tpByte, False) # 4 ints
1140 | """
1141 |
1142 | #quit()
--------------------------------------------------------------------------------
/PhotonEditor.py:
--------------------------------------------------------------------------------
1 | """
2 | Main program and initializes window, adds controls, contains redraw loop and retrieves user-input
3 | """
4 |
5 | __version__ = "alpha"
6 | __author__ = "Nard Janssens, Vinicius Silva, Robert Gowans, Ivan Antalec, Leonardo Marques - See Github PhotonFileUtils"
7 |
8 | import os
9 | import datetime
10 | import time
11 |
12 | import pygame
13 | from pygame.locals import *
14 |
15 | from GUI import *
16 | from PhotonFile import *
17 | from FileDialog import *
18 | from MessageDialog import *
19 | from PopupDialog import *
20 |
21 | #TODO LIST
22 | #todo: file dialog edit box not always working correctly, cursor mismatch and text overflow not handled
23 | #todo: check on save if layerheighs are consecutive and printer does not midprint go down
24 | #todo: replace preview images (Menu item Replace Bitmap should act on (layer/preview) images shown.)
25 | #todo: button.png should be used in scrollbarv
26 | #todo: PhotonFile float_to_bytes(floatVal) does not work correctie if floatVal=0.5 - now struct library used
27 | #todo: process cursor keys for menu
28 | #todo: The exposure time, off times in layerdefs are ignored by Photon printer, however layerheight not (so first two are just placeholders for future firmware.)
29 | #todo: hex_to_bytes(hexStr) et al. return a bytearray, should we convert this to bytes by using bytes(bytearray)?
30 | #todo: beautify layer bar at right edge of slice image
31 | #todo: Exe/distribution made with
32 | #todo: drag GUI-scrollbar is not implementend
33 | #todo: Numpy in Linux is slow: https://stackoverflow.com/questions/26609475/numpy-performance-differences-between-linux-and-windows
34 |
35 |
36 |
37 | ########################################################################################################################
38 | ## Variables
39 | ########################################################################################################################
40 |
41 | # Class which holds all data from photon file
42 | photonfile=None
43 |
44 | # Regarding image data to display
45 | screen=None
46 | layerimg=None
47 | previmg=[None,None]
48 | layerForecolor=(89,56,199) #I changed this to aproximate UV color what the machine shows X3msnake
49 | layerBackcolor=(0,0,0)
50 | layerLabel=None #Scroll chevrons at top left
51 | layerNr = 0
52 | prevNr=0
53 |
54 | # Dimensional constants for settings
55 | settingscolwidth=250
56 | settingslabelwidth=160
57 | settingslabelmargin=10
58 | settingstextboxmargin=10
59 | settingsrowheight=16
60 | settingsrowspacing=28
61 | settingstextboxwidth=settingscolwidth-settingslabelmargin-settingslabelwidth-settingstextboxmargin
62 | settingswidth = settingscolwidth* 2 # 2 columns
63 | settingsleft = int(1440 / 4)
64 | windowwidth=int(1440 / 4) + settingswidth
65 | windowheight=int(2560 / 4)
66 |
67 | # GUI controls
68 | menubar=None
69 | controls=[]
70 | firstHeaderTextbox=-1
71 | firstPreviewTextbox=-1
72 | firstLayerTextbox=-1
73 |
74 | # Scroll bar to the right
75 | mouseDrag=False
76 | scrollLayerWidth=30
77 | scrollLayerVMargin=30
78 | scrollLayerRect=GRect(1440/4-scrollLayerWidth,scrollLayerVMargin,scrollLayerWidth,2560/4-scrollLayerVMargin*2)
79 | layerCursorActive=True
80 | layerCursorRect=GRect(1440/4-scrollLayerWidth,scrollLayerVMargin+2,scrollLayerWidth,4)
81 |
82 | # Resin settings
83 | resins=None
84 | resincombo=None
85 |
86 | ########################################################################################################################
87 | ## Message boxes
88 | ########################################################################################################################
89 |
90 | def infoMessageBox(title, message):
91 | dialog = MessageDialog(screen, pos=(140, 140),
92 | title=title,
93 | message=message,
94 | parentRedraw=redrawWindow)
95 | dialog.show()
96 |
97 |
98 | def errMessageBox(errormessage):
99 | dialog = MessageDialog(screen, pos=(140, 140),
100 | title="Error",
101 | message=errormessage,
102 | parentRedraw=redrawWindow)
103 | dialog.show()
104 |
105 | def checkLoadedPhotonfile(title,message):
106 | if photonfile == None:
107 | print(title+": "+message)
108 | infoMessageBox(title,message)
109 | return False
110 | else:
111 | return True
112 |
113 |
114 | ########################################################################################################################
115 | ## Navigation Buttons
116 | ########################################################################################################################
117 |
118 | def prevUp():
119 | """ Shows next Preview Image from photonfile """
120 | global prevNr
121 | global dispimg
122 | if prevNr == 0: prevNr = 1
123 | dispimg = previmg[prevNr]
124 | refreshPreviewSettings()
125 |
126 |
127 | def prevDown():
128 | """ Shows previous Preview Image from photonfile """
129 | global prevNr
130 | global dispimg
131 | if prevNr == 1: prevNr = 0
132 | dispimg = previmg[prevNr]
133 | refreshPreviewSettings()
134 |
135 | def layerDown(delta:int=1):
136 | """ Go a number of layers (delta) back and display image and settings """
137 | global layerNr, dispimg, layerimg, photonfile
138 | if photonfile == None: return
139 | saveLayerSettings2PhotonFile()
140 |
141 | layerNr = layerNr - delta
142 | if layerNr < 0: layerNr = 0
143 | layerimg = photonfile.getBitmap(layerNr, layerForecolor, layerBackcolor)
144 | dispimg = layerimg
145 | refreshLayerSettings()
146 | setLayerSliderFromLayerNr()
147 | return
148 |
149 |
150 | def layerUp(delta=1):
151 | """ Go a number of layers (delta) forward and display image and settings """
152 | global layerNr, dispimg, layerimg, photonfile
153 | if photonfile == None: return
154 | # print ("saveLayerSettings2PhotonFile()")
155 | saveLayerSettings2PhotonFile()
156 |
157 | maxLayer = photonfile.nrLayers()
158 | layerNr = layerNr + delta
159 | if layerNr >= maxLayer: layerNr = maxLayer - 1
160 | # print("photonfile.getBitmap()")
161 | layerimg = photonfile.getBitmap(layerNr, layerForecolor, layerBackcolor)
162 | dispimg = layerimg
163 | # print("refreshLayerSettings()")
164 | refreshLayerSettings()
165 | setLayerSliderFromLayerNr()
166 | return
167 |
168 |
169 | ########################################################################################################################
170 | ## Create Menu and menu handlers
171 | ########################################################################################################################
172 |
173 | def newFile():
174 | """ start new file by loading empty photon file with default settings """
175 | global filename
176 |
177 | # open file and update window title to reflect a new unique (with date and time) filename
178 | openPhotonFile("resources/newfile.photon")
179 | barefilename = ("New file "+str(datetime.datetime.now().date())+" "+str(datetime.datetime.now().time())[:8])
180 | barefilename = barefilename.replace(":","-")
181 | filename = os.path.join(os.getcwd(),barefilename )
182 | print (filename)
183 | pygame.display.set_caption("Photon File Editor - " + barefilename)
184 |
185 | def doNothing():
186 | """ Placeholder for menu items without functionality """
187 | infoMessageBox("Not yet implemented", "This feature is under development. If you want to help please visit our github page NardJ/PhotonFileUtils.")
188 | return
189 |
190 | def exitFile():
191 | """ Exits program. """
192 | global running
193 | running=False
194 | print("Menu Exit was selected. Exit!")
195 | return
196 |
197 | def saveFile():
198 | """ Asks for a filename and tells the PhotonFile object to save it . """
199 |
200 | global filename
201 |
202 | # Check if photonfile is loaded to prevent errors when operating on empty photonfile
203 | if not checkLoadedPhotonfile("No photon file loaded!","There is no .photon file loaded to save."): return
204 |
205 | # Write all values on the screen to the photonfile object
206 | saveGeneralSettings2PhotonFile()
207 | savePreviewSettings2PhotonFile()
208 | saveLayerSettings2PhotonFile()
209 |
210 | # Ask user for filename and if exists to confirm overwrite resulting in okUser=True
211 | okUser=False
212 | retfilename=""
213 | while not okUser:
214 | # Get filename
215 | dialog = FileDialog(screen, (40, 40), ext=".photon",title="Save Photon File", defFilename="newfile.photon", parentRedraw=redrawWindow)
216 | retfilename=dialog.newFile()
217 | # If user canceled saveFile on FileDialog, retfilename=None and we should continue and thus set okUser to true
218 | if retfilename == None:
219 | okUser = True
220 | # If user selected filename, we check if filename exists (if exists okUser set to False, if not okUser is True)
221 | else:
222 | okUser = not os.path.isfile(retfilename)
223 | # If fileexists or user canceled saveFile on FileDialog
224 | if not okUser:
225 | dialog = MessageDialog(screen, pos=(140, 140), width=400,
226 | title="Please confirm",
227 | message="This file already exists. Do you want to continue?",
228 | center=True,
229 | buttonChoice=MessageDialog.OKCANCEL,
230 | parentRedraw=redrawWindow)
231 | ret = dialog.show()
232 | #if user selected ok, the users want to overwrite file so set okUser to True
233 | if ret=="OK": okUser=True
234 |
235 | # Check if user pressed Cancel
236 | if not retfilename==None:
237 | filename=retfilename
238 | print ("Returned: ",filename)
239 | try:
240 | # Write file and update window title to reflect new filename
241 | photonfile.writeFile(filename)
242 | barefilename = (os.path.basename(filename))
243 | pygame.display.set_caption("Photon File Editor - " + barefilename)
244 | except Exception as err:
245 | print (err)
246 | errMessageBox(str(err))
247 | else:
248 | print("User Canceled")
249 | return
250 |
251 |
252 | def loadFile():
253 | """ Asks for a filename and tells the PhotonFile object to load it . """
254 |
255 | global filename
256 |
257 | # Ask user for filename
258 | dialog = FileDialog(screen, (40, 40), ext=".photon",title="Load Photon File", parentRedraw=redrawWindow)
259 | retfilename=dialog.getFile()
260 |
261 | # Check if user pressed Cancel
262 | if not retfilename==None:
263 | filename = retfilename
264 | print ("Returned: ",filename)
265 | try:
266 | # Open file and update window title to reflect new filename
267 | openPhotonFile(filename)
268 | barefilename = (os.path.basename(filename))
269 | pygame.display.set_caption("Photon File Editor - " + barefilename)
270 | except Exception as err:
271 | print (err)
272 | errMessageBox(str(err))
273 | else:
274 | print ("User Canceled")
275 | return
276 |
277 |
278 | def undo():
279 | """ Undo by replacing all data with data from history. """
280 |
281 | global dispimg
282 | global layerimg
283 | global photonfile
284 | global layerNr
285 |
286 | # Check if photonfile is loaded to prevent errors when operating on empty photonfile
287 | if not checkLoadedPhotonfile("No photon file loaded!","There is nothing to undo."): return
288 |
289 | # Insert layer
290 | try:
291 | photonfile.undo()
292 | if layerNr >= photonfile.nrLayers():
293 | layerNr = photonfile.nrLayers() - 1
294 | setLayerSliderFromLayerNr()
295 | print("Undo")
296 | # Refresh data from layer in sidebar (data length is possible changed)
297 | refreshLayerSettings()
298 | refreshHeaderSettings() # number layers could have changed
299 | # Update current layer image with new bitmap retrieved from photonfile
300 | layerimg = photonfile.getBitmap(layerNr, layerForecolor, layerBackcolor)
301 | dispimg = layerimg
302 | except Exception as err: # if clipboard is empty
303 | print(err)
304 | errMessageBox(str(err))
305 |
306 | def deleteLayer():
307 | """ Deletes current layer, but stores in memory/clipboard, ready for pasting """
308 |
309 | global dispimg
310 | global layerimg
311 | global photonfile
312 | global layerNr
313 |
314 | # Check if photonfile is loaded to prevent errors when operating on empty photonfile
315 | if not checkLoadedPhotonfile("No photon file loaded!","A .photon file is needed to delete layers."): return
316 |
317 | # Check of nrLayers at least 2, there must remain 1
318 | if photonfile.nrLayers()==1:
319 | dialog = MessageDialog(screen, pos=(140, 140),width=400,
320 | title="No layers to delete!",
321 | message="A .photon file must have at least 1 layer. \n\n You can however replace this layer with another bitmap or edit its settings.",
322 | center = True,
323 | parentRedraw = redrawWindow)
324 | dialog.show()
325 | return
326 |
327 | # Check if user is sure
328 | dialog = MessageDialog(screen, pos=(140, 140),width=400,
329 | title="Please confirm",
330 | message="Deleting only one layer can be undone. Are you sure?",
331 | center=True,
332 | buttonChoice=MessageDialog.OKCANCEL,
333 | parentRedraw=redrawWindow)
334 | ret=dialog.show()
335 |
336 | # Delete if user confirmed
337 | if ret=="OK":
338 | photonfile.deleteLayer(layerNr)
339 | print("Layer "+str(layerNr)+ " deleted.")
340 | # Check if we deleted last layer and if so reduce layerNr
341 | if layerNr >= photonfile.nrLayers(): layerNr = layerNr - 1
342 | # Update layer settings with new layer
343 | layerimg = photonfile.getBitmap(layerNr, layerForecolor, layerBackcolor)
344 | dispimg = layerimg
345 | refreshLayerSettings()
346 | refreshHeaderSettings() # number layers changed
347 | else:
348 | print ("User canceled deleting a layer.")
349 |
350 |
351 | def copyLayer():
352 | """ Copies layer to memory/clipboard, ready for pasting """
353 | global photonfile
354 | global layerNr
355 |
356 | # Check if photonfile is loaded to prevent errors when operating on empty photonfile
357 | if not checkLoadedPhotonfile("No photon file loaded!","A .photon file is needed to duplicate layers."): return
358 |
359 | # Copy to memory
360 | photonfile.copyLayer(layerNr)
361 |
362 |
363 | def duplicateLayer():
364 | """ Inserts layer before current layer (duplicate current Layer) """
365 |
366 | global dispimg
367 | global layerimg
368 | global photonfile
369 | global layerNr
370 |
371 | # Check if photonfile is loaded to prevent errors when operating on empty photonfile
372 | if not checkLoadedPhotonfile("No photon file loaded!","A .photon file is needed to duplicate layers."): return
373 |
374 | # Insert layer
375 | photonfile.insertLayerBefore(layerNr,False)
376 | print("Layer "+str(layerNr)+ " inserted.")
377 | # Update layer settings with new layer
378 | refreshLayerSettings()
379 | refreshHeaderSettings() # number layers changed
380 | # Update current layer image with new bitmap retrieved from photonfile
381 | layerimg = photonfile.getBitmap(layerNr, layerForecolor, layerBackcolor)
382 | dispimg = layerimg
383 |
384 |
385 | def pasteLayer():
386 | """ Inserts layer before current layer (duplicate current Layer) """
387 |
388 | global dispimg
389 | global layerimg
390 | global photonfile
391 | global layerNr
392 |
393 | # Check if photonfile is loaded to prevent errors when operating on empty photonfile
394 | if not checkLoadedPhotonfile("No photon file loaded!","A .photon file is needed to duplicate layers."): return
395 |
396 | # Insert layer
397 | try:
398 | photonfile.insertLayerBefore(layerNr,fromClipboard=True)
399 | print("Layer "+str(layerNr)+ " inserted.")
400 | # Refresh data from layer in sidebar (data length is possible changed)
401 | refreshLayerSettings()
402 | refreshHeaderSettings() # number layers changed
403 | # Update current layer image with new bitmap retrieved from photonfile
404 | layerimg = photonfile.getBitmap(layerNr, layerForecolor, layerBackcolor)
405 | dispimg = layerimg
406 | except Exception as err: # if clipboard is empty
407 | print(err)
408 | errMessageBox(str(err))
409 |
410 | def replaceBitmap():
411 | """ Replace bitmap of current layer with new bitmap from disk selected by the user """
412 |
413 | global filename
414 | global dispimg
415 | global layerimg
416 |
417 | # Check if photonfile is loaded to prevent errors when operating on empty photonfile
418 | if not checkLoadedPhotonfile("No photon file loaded!","A .photon file is needed to load the bitmap in."): return
419 |
420 | # Ask user for filename
421 | dialog = FileDialog(screen, (40, 40), ext=".png",title="Load Image File", parentRedraw=redrawWindow)
422 | retfilename=dialog.getFile()
423 |
424 | # Check if user pressed Cancel
425 | if not retfilename==None:
426 | filename = retfilename
427 | print ("Returned: ",filename)
428 | # since import can take a while (although faster with numpy library available) show a be-patient message
429 | popup = PopupDialog(screen, pos=(140, 140),
430 | title="Please wait...",
431 | message="Photon File Editor is importing your images.")
432 | popup.show()
433 | try:
434 | # Ask PhotonFile object to replace bitmap
435 | photonfile.replaceBitmap(layerNr,filename)
436 | # Refresh data from layer in sidebar (data length is possible changed)
437 | refreshLayerSettings()
438 | # Update current layer image with new bitmap retrieved from photonfile
439 | layerimg = photonfile.getBitmap(layerNr, layerForecolor, layerBackcolor)
440 | dispimg = layerimg
441 | except Exception as err:
442 | print (err)
443 | errMessageBox(str(err))
444 | else:
445 | print ("User Canceled")
446 | return
447 |
448 |
449 | def importBitmaps():
450 | """ Replace all bitmaps with all bitmap found in a directory selected by the user """
451 | global photonfile
452 | global layerNr
453 | global dispimg
454 | global layerimg
455 |
456 | # Check if photonfile is loaded to prevent errors when operating on empty photonfile
457 | if not checkLoadedPhotonfile("No photon file loaded!","A .photon file is needed as template to load the bitmaps in."):return
458 |
459 | # Ask user for filename
460 | dialog = FileDialog(screen, (40, 40), ext=".png", title="Select directory with png files", parentRedraw=redrawWindow)
461 | directory = dialog.getDirectory()
462 |
463 | # Check if user pressed Cancel
464 | if not directory == None:
465 | print("Returned: ", directory)
466 | # Since import WILL take a while (although faster with numpy library available) show a be-patient message
467 | popup = PopupDialog(screen, pos=(140, 140),
468 | title="Please wait...",
469 | message="Photon File Editor is importing your images.")
470 | popup.show()
471 | try:
472 | # Ask PhotonFile object to replace bitmaps
473 | photonfile.replaceBitmaps(directory)
474 | # Refresh header settings which contains number of layers
475 | refreshHeaderSettings()
476 | # No preview data is changed
477 | #
478 | # Start again at layer 0 and refresh layer settings
479 | layerNr=0
480 | refreshLayerSettings()
481 | # Update current layer image with new bitmap retrieved from photonfile
482 | layerimg = photonfile.getBitmap(layerNr,layerForecolor,layerBackcolor)
483 | dispimg = layerimg
484 | except Exception as err:
485 | print (err)
486 | errMessageBox(str(err))
487 | else:
488 | print("User Canceled")
489 | return
490 |
491 | def exportBitmaps():
492 | """ Export all bitmaps from a loaded photon file to a directory selected by the user """
493 | global filename
494 | global photonfile
495 |
496 | # Check if photonfile is loaded to prevent errors when operating on empty photonfile
497 | if not checkLoadedPhotonfile("No photon file loaded!","A .photon file is needed to export bitmaps from."):return
498 |
499 | # Ask user for filename
500 | barefilename = (os.path.basename(filename))
501 | barenotextfilename=os.path.splitext(barefilename)[0]
502 | dirname=(os.path.dirname(filename))
503 | newdirname=os.path.join(dirname,barenotextfilename+".bitmaps" )
504 | if not os.path.isdir(newdirname):
505 | os.mkdir(newdirname)
506 |
507 | # Since import WILL take a while (although faster with numpy library available) show a be-patient message
508 | popup=PopupDialog(screen, pos=(140, 140),
509 | title="Please wait...",
510 | message="Photon File Editor is exporting your images.")
511 | popup.show()
512 | try:
513 | # Ask PhotonFile object to replace bitmaps
514 | photonfile.exportBitmaps(newdirname,"slice_")
515 | except Exception as err:
516 | print(err)
517 | errMessageBox(str(err))
518 | del popup
519 |
520 | #print (barefilename,filename,newdirname)
521 |
522 |
523 | def about():
524 | """ Displays about box """
525 | dialog = MessageDialog(screen, pos=(140, 140),width=400,
526 | title="About Photon File Editor",
527 | #message="Version Alpha \n \n Github: PhotonFileUtils \n\n o Nard Janssens (NardJ) \n o Vinicius Silva (X3msnake) \n o Robert Gowans (Rob2048) \n o Ivan Antalec (Antharon) \n o Leonardo Marques (Reonarudo) \n \n License: Free for non-commerical use.",
528 | message="Version Alpha \n \n Github: PhotonFileUtils \n\n NardJ, X3msnake, Rob2048, \n Antharon, Reonarudo \n \n License: Free for non-commerical use.",
529 | center=False,
530 | parentRedraw=redrawWindow)
531 | dialog.show()
532 |
533 | def showSlices():
534 | """ Let user switch (from preview images) to slice view """
535 | global dispimg
536 | dispimg=layerimg
537 |
538 | def showPrev0():
539 | """ Let user switch (from slice image view) to preview image """
540 | global dispimg
541 | dispimg = previmg[0]
542 |
543 | def showPrev1():
544 | """ Let user switch (from slice image view) to preview image """
545 | global dispimg
546 | dispimg = previmg[1]
547 |
548 |
549 |
550 | def createMenu():
551 | global menubar
552 | global screen
553 |
554 | # Create the menu
555 | menubar=MenuBar(screen)
556 | menubar.addMenu("File","F")
557 | menubar.addItem("File", "New", newFile)
558 | menubar.addItem("File","Load",loadFile)
559 | menubar.addItem("File","Save As",saveFile)
560 | menubar.addItem("File","Exit",exitFile)
561 | menubar.addMenu("Edit", "E")
562 | menubar.addItem("Edit", "Undo", undo)
563 | menubar.addItem("Edit", "______________", None)
564 | menubar.addItem("Edit", "Cut Layer", deleteLayer)
565 | menubar.addItem("Edit", "Copy Layer", copyLayer)
566 | menubar.addItem("Edit", "Paste Layer", pasteLayer)
567 | menubar.addItem("Edit", "Duplicate Layer", duplicateLayer)
568 | menubar.addItem("Edit", "______________", None)
569 | menubar.addItem("Edit", "Replace Bitmap", replaceBitmap)
570 | menubar.addItem("Edit", "______________", None)
571 | menubar.addItem("Edit", "Import Bitmaps", importBitmaps)
572 | menubar.addItem("Edit", "Export Bitmaps", exportBitmaps)
573 | menubar.addMenu("View", "V")
574 | menubar.addItem("View", "Slices", showSlices)
575 | menubar.addItem("View", "Preview 0", showPrev0)
576 | menubar.addItem("View", "Preview 1",showPrev1)
577 | menubar.addItem("View", "..3D", doNothing)
578 | menubar.addMenu("Help", "H")
579 | menubar.addItem("Help", "About",about)
580 |
581 |
582 | def createLayerOperations():
583 | """ Create the layer modification buttons pointing to Edit menu layer options """
584 | global controls
585 | global menubar
586 | viewport_yoffset = 8
587 | iconsize=(46,59)
588 | icondist=iconsize[0]+16
589 | controls.append(ImgBox(screen, filename="resources/cut.png", filename_hover="resources/cut-hover.png",
590 | pos=(20+0*icondist,2560/4-iconsize[1]-viewport_yoffset),
591 | borderhovercolor=(0,0,0),toolTip="Cut (and store in clipboard)",
592 | func_on_click=deleteLayer))
593 | controls.append(ImgBox(screen, filename="resources/copy.png", filename_hover="resources/copy-hover.png",
594 | pos=(20+1*icondist, 2560 / 4 - iconsize[1] - viewport_yoffset),
595 | borderhovercolor=(0, 0, 0),toolTip="Copy (to clipboard)",
596 | func_on_click=copyLayer))
597 | controls.append(ImgBox(screen, filename="resources/paste.png", filename_hover="resources/paste-hover.png",
598 | pos=(20+2*icondist, 2560 / 4 - iconsize[1] - viewport_yoffset),
599 | borderhovercolor=(0, 0, 0), toolTip="Paste (from clipboard)",
600 | func_on_click=pasteLayer))
601 | controls.append(ImgBox(screen, filename="resources/duplicate.png", filename_hover="resources/duplicate-hover.png",
602 | pos=(20+3*icondist, 2560 / 4 - iconsize[1] - viewport_yoffset),
603 | borderhovercolor=(0, 0, 0), toolTip="Duplicate (current layer)",
604 | func_on_click=duplicateLayer))
605 |
606 |
607 | def createLayernavigation():
608 | """ Create the layer navigation buttons (Up/Down) """
609 | global layerLabel
610 | global menubar
611 | global controls
612 | global layerNr
613 |
614 | # Add two imageboxes to control as layer nav buttons
615 | viewport_yoffset=menubar.height+8
616 | controls.append(ImgBox(screen, filename="resources/arrow-up.png", filename_hover="resources/arrow-up-hover.png", pos=(20,20+viewport_yoffset), borderhovercolor=(0,0,0),func_on_click=layerDown))
617 | controls.append(ImgBox(screen, filename="resources/arrow-down.png", filename_hover="resources/arrow-down-hover.png", pos=(20,80+viewport_yoffset), borderhovercolor=(0,0,0),func_on_click=layerUp))
618 | layerLabel=Label(screen,GRect(26,80,52,40),textcolor=(255,255,255),fontsize=24,text="",istransparent=True,center=True)
619 | layerLabel.font.set_bold(True)
620 | controls.append(layerLabel)
621 |
622 | layerNr=0
623 | setLayerSliderFromLayerNr()
624 |
625 | def createSidebar():
626 | """ Create all labels and input boxes to edit the general, preview and current layer settings of the photonfile. """
627 | global menubar
628 | global screen
629 | global controls
630 |
631 | global settingscolwidth
632 | global settingslabelwidth
633 | global settingslabelmargin
634 | global settingstextboxmargin
635 | global settingsrowheight
636 | global settingsrowspacing
637 | global settingstextboxwidth
638 | global settingswidth
639 | global settingsleft
640 |
641 | global firstHeaderTextbox
642 | global firstPreviewTextbox
643 | global firstLayerTextbox
644 |
645 | global resins
646 | global resincombo
647 |
648 | # The controls are placed below the menubar
649 | viewport_yoffset=menubar.height+8
650 |
651 | # We need to translate the datatype of the photon settings to the datatypes an inputbox recognizes and enforces from the user
652 | transTypes={PhotonFile.tpByte: TextBox.HEX,PhotonFile.tpInt: TextBox.INT,PhotonFile.tpFloat: TextBox.FLOAT,PhotonFile.tpChar: TextBox.HEX}
653 |
654 | # Add General data fields
655 | # Start with the title of this settingsgroup
656 | row=0
657 | titlebox=Label(screen,text="General", rect=GRect(settingsleft + settingslabelmargin, 10 + row * 24 + viewport_yoffset, settingscolwidth, 16),drawBorder=False)
658 | titlebox.font.set_bold(True)
659 | controls.append(titlebox)
660 | # Add all labels for the settings we want to add
661 | for row, (bTitle, bNr, bType, bEditable,bHint) in enumerate(PhotonFile.pfStruct_Header,1):#enum start at 1
662 | controls.append(Label(screen, text=bTitle, rect=GRect(settingsleft+settingslabelmargin,10+row*settingsrowspacing+viewport_yoffset,settingslabelwidth,settingsrowheight)))
663 | # Add all input boxes for the settings we want to add
664 | firstHeaderTextbox=len(controls)
665 | for row, (bTitle, bNr, bType,bEditable,bHint) in enumerate(PhotonFile.pfStruct_Header,1):#enum start at 1
666 | tbType = transTypes[bType]
667 | bcolor=(255,255,255) if bEditable else (128,128,128)
668 | controls.append(TextBox(screen, text="", \
669 | rect=GRect(settingsleft+settingslabelwidth+settingstextboxmargin, 10 + row * settingsrowspacing+viewport_yoffset, settingstextboxwidth, settingsrowheight),\
670 | editable=bEditable, \
671 | backcolor=bcolor, \
672 | textcolor=(0,0,0),\
673 | inputType=tbType, \
674 | toolTip=bHint, \
675 | onEnter=updateTextBox2PhotonFile, \
676 | linkedData={"VarGroup":"Header","Title":bTitle,"NrBytes":bNr,"Type":bType} \
677 | ))
678 |
679 | # Add Preview data fields
680 | # Start with the title of this settingsgroup
681 | row=0
682 | settingsleft = settingsleft+settingscolwidth
683 | titlebox = Label(screen, text="Preview", rect=GRect(settingsleft+settingslabelmargin,10+row*settingsrowspacing+viewport_yoffset,settingscolwidth,settingsrowheight))
684 | titlebox.font.set_bold(True)
685 | controls.append(titlebox)
686 | # Add all labels for the settings we want to add
687 | for row, (bTitle, bNr, bType,bEditable, bHint) in enumerate(PhotonFile.pfStruct_Previews, 1):
688 | controls.append(Label(screen, text=bTitle, rect=GRect(settingsleft+settingslabelmargin,10+row*settingsrowspacing+viewport_yoffset,settingslabelwidth,settingsrowheight)))
689 | # We also need navigation buttons for previewNr
690 | row = 0
691 | controls.append(Button(screen, rect=GRect(settingsleft + settingslabelwidth + settingstextboxmargin + settingstextboxwidth - 40,10 + row * settingsrowspacing + viewport_yoffset, 18, 20), text="<",func_on_click=prevDown))
692 | controls.append(Button(screen,rect=GRect(settingsleft+settingslabelwidth+settingstextboxmargin+settingstextboxwidth-18,10+row*settingsrowspacing+viewport_yoffset,18,20),text=">",func_on_click=prevUp))
693 | firstPreviewTextbox = len(controls)
694 | controls.append(Label(screen, text=str(prevNr),rect=GRect(settingsleft+settingslabelwidth+settingstextboxmargin, 10 + row * settingsrowspacing + viewport_yoffset, settingstextboxwidth-40, settingsrowheight)))
695 | # Add all input boxes for the settings we want to add
696 | for row, (bTitle, bNr, bType,bEditable, bHint) in enumerate(PhotonFile.pfStruct_Previews, 1):
697 | tbType = transTypes[bType]
698 | bcolor = (255, 255, 255) if bEditable else (128, 128, 128)
699 | controls.append(TextBox(screen, text="", \
700 | rect=GRect(settingsleft+settingslabelwidth+settingstextboxmargin, 10 + row * settingsrowspacing+viewport_yoffset, settingstextboxwidth, settingsrowheight),\
701 | editable=bEditable, \
702 | backcolor=bcolor, \
703 | textcolor=(0, 0, 0), \
704 | inputType=tbType, \
705 | toolTip=bHint, \
706 | onEnter=updateTextBox2PhotonFile, \
707 | linkedData={"VarGroup": "Preview", "Title": bTitle, "NrBytes": bNr, "Type": bType} \
708 | ))
709 |
710 | # Add Current Layer meta fields
711 | # Start with the title of this settingsgroup
712 | row=8
713 | titlebox = Label(screen, text="Layer", rect=GRect(settingsleft+settingslabelmargin,10+row*settingsrowspacing+viewport_yoffset,settingscolwidth,settingsrowheight))
714 | titlebox.font.set_bold(True)
715 | controls.append(titlebox)
716 | # Add all labels for the settings we want to add
717 | for row, (bTitle, bNr, bType,bEditable, bHint) in enumerate(PhotonFile.pfStruct_LayerDef,9):
718 | controls.append(Label(screen, text=bTitle, rect=GRect(settingsleft+settingslabelmargin,10+row*settingsrowspacing+viewport_yoffset,120,16)))
719 | row=8
720 | # Add all input boxes for the settings we want to add
721 | firstLayerTextbox = len(controls)
722 | controls.append(Label(screen, text=str(layerNr), rect=GRect(settingsleft + settingslabelwidth+settingstextboxmargin, 10 + row * settingsrowspacing+viewport_yoffset, settingstextboxwidth, settingsrowheight)))
723 | for row, (bTitle, bNr, bType,bEditable, bHint) in enumerate(PhotonFile.pfStruct_LayerDef, 9):
724 | tbType = transTypes[bType]
725 | bcolor = (255, 255, 255) if bEditable else (128, 128, 128)
726 | controls.append(TextBox(screen, text="", \
727 | rect=GRect(settingsleft + settingslabelwidth+settingstextboxmargin, 10 + row * settingsrowspacing+viewport_yoffset, settingstextboxwidth, settingsrowheight),\
728 | editable=bEditable, \
729 | backcolor=bcolor, \
730 | textcolor=(0, 0, 0), \
731 | inputType=tbType,\
732 | toolTip=bHint, \
733 | onEnter=updateTextBox2PhotonFile, \
734 | linkedData={"VarGroup": "LayerDef", "Title": bTitle, "NrBytes": bNr, "Type": bType} \
735 | ))
736 |
737 | # Add Resin Presets Chooser
738 | # First read settings from file
739 | # columns are Brand,Type,Layer,NormalExpTime,OffTime,BottomExp,BottomLayers
740 | ifile = open("resources/resins.txt", "r")
741 | lines = ifile.readlines()
742 | resins = [tuple(line.strip().split(",")) for line in lines]
743 | resinnames=[]
744 | for resin in resins:
745 | resinnames.append(resin[0])
746 |
747 | # Start with the title of this settingsgroup
748 | row=16
749 | titlebox = Label(screen, text="Resin Presets", rect=GRect(settingsleft+settingslabelmargin,10+row*settingsrowspacing+viewport_yoffset,settingscolwidth,settingsrowheight))
750 | titlebox.font.set_bold(True)
751 | controls.append(titlebox)
752 |
753 | # Make combobox (add last, so always on top)
754 | row=row+1
755 | resincombo=Combobox(screen,
756 | rect=GRect(settingsleft + settingslabelmargin, 10 + row * settingsrowspacing+viewport_yoffset, settingstextboxwidth+settingslabelwidth, settingsrowheight),\
757 | items=resinnames,
758 | defitemnr=0,
759 | )
760 |
761 | # Add apply button
762 | row=row+1+0.4 # combo is larger than normal
763 | controls.append( Button(screen,
764 | rect=GRect(settingsleft + settingslabelwidth + settingstextboxmargin, 10 + row * settingsrowspacing + viewport_yoffset, settingstextboxwidth,settingsrowheight*1.6), \
765 | text="Apply", func_on_click=ApplyResinSettings
766 | ))
767 |
768 | # Add combobox to controls
769 | controls.append(resincombo)
770 |
771 |
772 | def ApplyResinSettings():
773 | """ Applies the selected resin settings.
774 | """
775 | global resins
776 | global resincombo
777 | global photonfile
778 |
779 | # Check if photonfile is loaded
780 | if photonfile==None: return
781 |
782 | # Check if user didn't select title (first item)
783 | resinname=resincombo.text
784 | if resinname=="Brand": return
785 |
786 | # columns are Brand,Type,Layer Height,NormalExpTime,OffTime,BottomExp,BottomLayers
787 | for (sBrand,sType,sLayerHeight,sNormalExpTime,sOffTime,sBottomExp,sBottomLayers) in resins:
788 | if sBrand == resinname:
789 | # Convert all strings to floats/int
790 | rLayerHeight=float(sLayerHeight)
791 | rNormalExpTime = float(sNormalExpTime)
792 | rOffTime=float(sOffTime)
793 | rBottomExp=float(sBottomExp)
794 | rBottomLayers=int(sBottomLayers)
795 | #print (sBrand, rLayerHeight,rNormalExpTime, rOffTime, rBottomExp, rBottomLayers)
796 |
797 | # Set Header/General settings
798 | photonfile.Header["Layer height (mm)"]=PhotonFile.float_to_bytes(rLayerHeight)
799 | photonfile.Header["Exp. time (s)"] = PhotonFile.float_to_bytes(rNormalExpTime)
800 | photonfile.Header["Off time (s)"] = PhotonFile.float_to_bytes(rOffTime)
801 | photonfile.Header["Exp. bottom (s)"] = PhotonFile.float_to_bytes(rBottomExp)
802 | photonfile.Header["# Bottom Layers"] = PhotonFile.int_to_bytes(rBottomLayers)
803 |
804 | # Set settings of each layer
805 | cLayerHeight=0
806 | for layerNr, layerDef in enumerate(photonfile.LayerDefs):
807 | layerDef["Layer height (mm)"]=PhotonFile.float_to_bytes(cLayerHeight)
808 | cLayerHeight=cLayerHeight+rLayerHeight
809 | if layerNr1:
1095 | relY = layerNr / int(photonfile.nrLayers() - 1)
1096 | else: relY=0
1097 | else: relY=0
1098 | scrnY=relY * (2560 / 4 - scrollLayerVMargin * 2)+scrollLayerVMargin
1099 | layerCursorRect = scrollLayerRect.copy()
1100 | layerCursorRect.y = scrnY - 2
1101 | layerCursorRect.height = 4
1102 |
1103 |
1104 | imgPrevLoadTime=0 # keeps time since last img load and used to prevent to many image load
1105 | def handleLayerSlider(checkRect=True):
1106 | """ Checks if layerslider is used (dragged by mouse) and updates layer image and settings"""
1107 |
1108 | global photonfile
1109 | global dispimg
1110 | global layerimg
1111 | global layerBackcolor
1112 | global layerForecolor
1113 | global layerNr
1114 | global scrollLayerRect
1115 | global scrollLayerVMargin
1116 | global scrollLayerWidth
1117 | global layerCursorRect
1118 | global imgPrevLoadTime
1119 |
1120 |
1121 | # Check if mouse is in area of layerSlider (only needed on mousedown) of check is not needed (checkOk==Truel; if mouse dragged)
1122 | checkOk=True
1123 | pos = pygame.mouse.get_pos()
1124 | mousePoint = GPoint.fromTuple(pos)
1125 | if checkRect: checkOk=mousePoint.inGRect(scrollLayerRect)
1126 |
1127 | # If no photonfile we have nothing to do
1128 | if not photonfile == None:
1129 | if checkOk:
1130 | # Calc position of layerCursor based on Y of mouse cursor and from this the selected layer number
1131 | relY = (mousePoint.y - scrollLayerVMargin) / (2560 / 4 - scrollLayerVMargin * 2)
1132 | if relY<0: relY=0
1133 | if relY>1: relY=1
1134 | layerNr = round((photonfile.nrLayers() - 1) * relY)
1135 | layerCursorRect = scrollLayerRect.copy()
1136 | layerCursorRect.y = (relY*(2560 / 4 - scrollLayerVMargin * 2)+scrollLayerVMargin) - 2
1137 | layerCursorRect.height = 4
1138 | # Get image of new layer, display and update layer settings
1139 | secSincePrevLoad = time.time()-imgPrevLoadTime
1140 | if secSincePrevLoad>0.1: # to not overload the pc, we have a minimal interval between images (in sec)
1141 | waitForImg=True
1142 | layerimg = photonfile.getBitmap(layerNr, layerForecolor, layerBackcolor)
1143 | dispimg = layerimg
1144 | refreshLayerSettings()
1145 | imgPrevLoadTime = time.time()
1146 | return True
1147 | else:
1148 | return False
1149 | # layerCursorActive=False
1150 | # print (event.button)
1151 |
1152 |
1153 | def activeControlIdx():
1154 | """ Returns first textbox in controls where cursorActive is True. """
1155 | for idx, control in enumerate(controls):
1156 | if type(control) == TextBox:
1157 | if control.cursorActive == True: return idx
1158 | return None
1159 |
1160 | # Define a variable to control the main loop
1161 | running = True
1162 |
1163 | def main():
1164 | """ Entrypoint and controls the rest """
1165 |
1166 | global controls
1167 | global menubar
1168 | global mouseDrag
1169 | global running
1170 | global photonfile
1171 | lastpos=(0,0) # stores last position for tooltip
1172 |
1173 | # Initialize the pygame module and create the window
1174 | createWindow()
1175 |
1176 | # Main loop
1177 | while running:
1178 | # Redraw the window (in background) and tell pygame to show it (bring to foreground)
1179 | redrawWindow()
1180 | # Check for tooltips to draw
1181 | for ctrl in controls:
1182 | hasToolTip = getattr(ctrl, "handleToolTips", False)
1183 | if hasToolTip:
1184 | ret = ctrl.handleToolTips(lastpos)
1185 | if not ret==None :
1186 | ret.redraw()
1187 |
1188 | pygame.display.flip()
1189 |
1190 |
1191 | # Event handling, gets all event from the eventqueue
1192 | for event in pygame.event.get():
1193 |
1194 | pos = pygame.mouse.get_pos()
1195 | lastpos=pos
1196 |
1197 | if event.type == pygame.QUIT:
1198 | print("Window was closed. Exit!")
1199 | running = False # change the value to False, to exit the main loop
1200 |
1201 | if event.type == pygame.MOUSEBUTTONUP:
1202 | mouseDrag=False
1203 | if not menubar.handleMouseUp(pos,event.button):
1204 | for ctrl in controls:
1205 | ctrl.handleMouseUp(pos,event.button)
1206 |
1207 | if event.type == pygame.MOUSEBUTTONDOWN:
1208 | mouseDrag=handleLayerSlider()
1209 | if not menubar.handleMouseDown(pos,event.button):
1210 | for ctrl in controls:
1211 | ctrl.handleMouseDown(pos,event.button)
1212 |
1213 | if event.type == pygame.MOUSEMOTION:
1214 | if mouseDrag: handleLayerSlider(False)
1215 | if not menubar.handleMouseMove(pos):
1216 | for ctrl in controls:
1217 | ctrl.handleMouseMove(pos)
1218 |
1219 | if event.type == pygame.KEYDOWN :
1220 | #If numlock on then we use it to navigate layers
1221 | if not photonfile==None:
1222 | isNumlockOn = (pygame.key.get_mods() & pygame.KMOD_NUM) == 4096
1223 | if not isNumlockOn:
1224 | maxLayer = photonfile.nrLayers()
1225 | page=int(maxLayer/10)
1226 | if event.key == pygame.K_KP8: layerDown()
1227 | if event.key == pygame.K_KP9: layerDown(page)
1228 | if event.key == pygame.K_KP2: layerUp()
1229 | if event.key == pygame.K_KP3: layerUp(page)
1230 | if event.key == pygame.K_UP: layerDown()
1231 | if event.key == pygame.K_DOWN: layerUp()
1232 |
1233 | #We use tab to navigate the textboxes in controls
1234 | if event.key == pygame.K_TAB:
1235 | # Check shift state, without we move to next, with to previous control
1236 | isLShift = (pygame.key.get_mods() & pygame.KMOD_LSHIFT)
1237 | dir=1 if not isLShift else -1
1238 | # Get control with active cursor
1239 | prevActive=activeControlIdx()
1240 | # Check because maybe there is none active
1241 | if not prevActive==None:
1242 | # Remove cursor from found control
1243 | controls[prevActive].cursorActive=False
1244 | # Make first editable textbox we find in direction of dir
1245 | fnd=False
1246 | idx=prevActive+dir
1247 | while not fnd:
1248 | if type(controls[idx]) == TextBox and controls[idx].editable and not fnd:
1249 | controls[idx].cursorActive = True
1250 | fnd=True
1251 | idx=idx+dir
1252 | if idx>=len(controls): idx=0
1253 | if idx<0: idx=len(controls)-1
1254 |
1255 | if event.key == pygame.K_ESCAPE :
1256 | print ("Escape key pressed down. Exit!")
1257 | running = False
1258 | else:
1259 | if not menubar.handleKeyDown(event.key,event.unicode):
1260 | for ctrl in controls:
1261 | ctrl.handleKeyDown(event.key,event.unicode)
1262 |
1263 | pygame.quit()
1264 |
1265 | main()
1266 |
1267 |
--------------------------------------------------------------------------------