-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcanvas.go
480 lines (432 loc) · 12.4 KB
/
canvas.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package main
import (
"fmt"
. "gopaint/reza"
"image"
"image/draw"
"image/jpeg"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/shahfarhadreza/go-gdiplus"
win "github.com/lxn/win"
)
// DrawingCanvas is the main drawing canvas
type DrawingCanvas struct {
// Embed the Window interface
Window
// Double buffer data
mbitmap win.HBITMAP
mhdc win.HDC
context *gdiplus.Graphics
// Extras
gridPen *Pen
// Own data
image *DrawingImage
// test
firstMove bool
lastPt Point
}
func NewDrawingCanvas(parent Window) *DrawingCanvas {
canvas := &DrawingCanvas{Window: NewWindow()}
canvas.Init(parent)
return canvas
}
func (canvas *DrawingCanvas) Init(parent Window) {
logInfo("initializing canvas...")
canvas.firstMove = true
canvas.gridPen = NewDashPen(1, NewRgb(120, 120, 120))
canvas.Create("", win.WS_CHILD|win.WS_VISIBLE|win.WS_CLIPCHILDREN, 10, 10, 10, 10, parent)
canvas.SetPaintEventHandler(canvas.Paint)
canvas.SetMouseMoveEventHandler(canvas.MouseMove)
canvas.SetMouseDownEventHandler(canvas.MouseDown)
canvas.SetMouseUpEventHandler(canvas.MouseUp)
canvas.SetMouseWheelEventHandler(func(e *MouseWheelEvent) {
work := mainWindow.workspace
if e.WheelDelta > 0 {
work.ScrollUp()
} else {
work.ScrollDown()
}
})
canvas.SetMouseLeaveEventHandler(func() {
status := mainWindow.statusMousePos
status.Update("")
})
canvas.SetKeyPressEventHandler(func(keycode int) {
tool := mainWindow.tools.GetCurrentTool()
if tool != nil {
e := ToolKeyEvent{
keycode: keycode,
context: canvas.image.context,
image: canvas.image,
canvas: canvas,
}
tool.keyPressEvent(&e)
}
})
canvas.SetSetCursorEventHandler(canvas.UpdateCursor)
canvas.SetResizeEventHandler(canvas.OnResize)
logInfo("Done initializing canvas")
}
func (canvas *DrawingCanvas) Dispose() {
logInfo("Disposing canvas...")
if canvas.image != nil {
canvas.image.Dispose()
}
if canvas.context != nil {
canvas.context.Dispose()
}
if canvas.mhdc != 0 {
win.DeleteDC(canvas.mhdc)
}
if canvas.mbitmap != 0 {
win.DeleteObject(win.HGDIOBJ(canvas.mbitmap))
}
canvas.Window.Dispose()
if canvas.gridPen != nil {
canvas.gridPen.Dispose()
}
}
func (canvas *DrawingCanvas) UpdateCursor() bool {
tool := mainWindow.tools.GetCurrentTool()
if tool != nil {
var winpt win.POINT
win.GetCursorPos(&winpt)
win.ScreenToClient(canvas.GetHandle(), &winpt)
ptMouse := Point{X: int(winpt.X), Y: int(winpt.Y)}
toolCursor := tool.getCursor(&ptMouse)
win.SetCursor(toolCursor)
} else {
win.SetCursor(mainWindow.hCursorArrow)
}
return true
}
func (canvas *DrawingCanvas) NewImage(width, height int) {
logInfo("'NewImage' - Clear the canvas and create a blank white image...")
newImage := NewDrawingImage(width, height)
logInfo("Clear...")
newImage.filepath = ""
newImage.Clear(gdiplus.NewColor(255, 255, 255, 255))
/*
pen := gdiplus.NewPen(gdiplus.NewColor(0, 0, 0, 255), 7)
newImage.context.DrawLine(pen, 10.0, 210.0, 160.0, 400.0)
*/
//SavePNG("reza.png", newImage.hbitmap)
/*
color := Rgb(100, 0, 200)
gc.SetFillColor(color.AsRGBA())
gc.BeginPath() // Initialize a new path
gc.ArcTo(80, 80, 50, 50, 0, math.Pi*2)
gc.Close()
gc.FillStroke()
*/
if canvas.image != nil {
canvas.image.Dispose()
}
canvas.image = newImage
canvas.SetSize(width, height)
canvas.UpdateStatus()
}
func (canvas *DrawingCanvas) Resize(width, height int) {
prevWidth := canvas.GetSize().Width
prevHeight := canvas.GetSize().Height
log.Printf("Resizing from (%d x %d) to (%d x %d)...\n", prevWidth, prevHeight, width, height)
if prevWidth == width && prevHeight == height {
return
}
if width < 1 || height < 1 {
log.Panicf("INVALID RESIZE SIZE - (%d x %d)\n", width, height)
}
if canvas.image == nil {
log.Panicln("WHY is canvas image INVALID!!!")
}
// We allocate new data with given new size
// then we copy/draw the old data/image into it
newImage := NewDrawingImage(width, height)
color := GetColorBackground()
newImage.Clear(&color)
// Lets use BitBlt for copying. Faster than raw copy
g := newImage.context3
copyWidth := Min(prevWidth, width)
copyHeight := Min(prevHeight, height)
g.BitBlt(0, 0, copyWidth, copyHeight, canvas.image.memdc, 0, 0, win.SRCCOPY)
//rect2 := canvas.image.Bounds()
//draw.Draw(newImage, rect2, canvas.image, image.Point{}, draw.Src)
// Reserve the additional infos
newImage.filepath = canvas.image.filepath
newImage.sizeOnDisk = canvas.image.sizeOnDisk
newImage.lastSaved = canvas.image.lastSaved
canvas.image.Dispose()
canvas.image = newImage
canvas.SetSize(width, height)
canvas.UpdateStatus()
logInfo("Done resizing")
}
func (canvas *DrawingCanvas) OpenImage(filename string) bool {
log.Printf("Open image '%s'...\n", filename)
catFile, err := os.Open(filename)
if err != nil {
log.Println(err)
return false
}
defer catFile.Close()
// Obtain file size
fi, err := catFile.Stat()
if err != nil {
// Could not obtain stat, handle error
log.Println(err)
return false
}
filesize := fi.Size()
modDate := fi.ModTime().Format("01-Jan-01 1:00 PM")
log.Println("Decoding...")
var imageData image.Image
ext := filepath.Ext(filename)
if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") {
imageData, err = jpeg.Decode(catFile)
} else {
imageData, _, err = image.Decode(catFile)
}
if err != nil {
fmt.Println(err)
return false
}
log.Println("Done decoding!")
bounds := imageData.Bounds()
width, height := bounds.Size().X, bounds.Size().Y
newImage := NewDrawingImage(width, height)
logInfo("Copy image data into canvas image....")
draw.Draw(newImage, newImage.Bounds(), imageData, image.Point{}, draw.Src)
newImage.filepath = filename
newImage.sizeOnDisk = filesize
newImage.lastSaved = modDate
if canvas.image != nil {
canvas.image.Dispose()
}
canvas.image = newImage
canvas.SetSize(width, height)
canvas.UpdateStatus()
canvas.Repaint()
log.Println("Done opening image")
return true
}
func (canvas *DrawingCanvas) SaveImage(filePath string) bool {
log.Printf("Saving image '%s'...\n", filePath)
fd, err := os.Create(filePath)
if err != nil {
log.Println(err)
return false
}
defer fd.Close()
ext := filepath.Ext(filePath)
format := FindFormatFromExt(ext)
if format != nil {
format.Function(fd, canvas.image, true)
} else {
log.Printf("Unknown file format/extension (%s)\n", ext)
return false
}
log.Printf("Done Saving image\n")
return true
}
func (canvas *DrawingCanvas) UpdateStatus() {
size := canvas.GetSize()
scz := mainWindow.statusCanvasSize
if scz != nil {
scz.Update(strconv.Itoa(size.Width) + " x " + strconv.Itoa(size.Height) + "px")
}
sfz := mainWindow.statusFileSize
imageSize, available := canvas.image.SizeOnDisk()
if available {
sfz.SetVisible(true)
sfz.Update(imageSize)
} else {
sfz.SetVisible(false)
}
}
func (canvas *DrawingCanvas) UpdateMousePosStatus() {
status := mainWindow.statusMousePos
wndRect := canvas.GetWindowRect()
ptScreen := app.GetCursorPos()
if status != nil {
if wndRect.IsPointInside(&ptScreen) {
status.Update(strconv.Itoa(ptScreen.X) + ", " + strconv.Itoa(ptScreen.Y) + "px")
} else {
status.Update("")
}
}
}
func (canvas *DrawingCanvas) MouseDown(pt *Point, mbutton int) {
win.SetCapture(canvas.GetHandle())
tool := mainWindow.tools.GetCurrentTool()
if canvas.firstMove {
canvas.lastPt = *pt
canvas.firstMove = false
}
e := ToolMouseEvent{
pt: *pt,
lastPt: canvas.lastPt,
mbutton: mbutton,
context: canvas.image.context,
image: canvas.image,
canvas: canvas,
}
tool.mouseDownEvent(&e)
canvas.Repaint()
canvas.lastPt = *pt
}
func (canvas *DrawingCanvas) MouseUp(pt *Point, mbutton int) {
tool := mainWindow.tools.GetCurrentTool()
if canvas.firstMove {
canvas.lastPt = *pt
canvas.firstMove = false
}
e := ToolMouseEvent{
pt: *pt,
lastPt: canvas.lastPt,
mbutton: mbutton,
context: canvas.image.context,
image: canvas.image,
canvas: canvas,
}
tool.mouseUpEvent(&e)
canvas.RepaintVisible()
canvas.lastPt = *pt
win.ReleaseCapture()
}
func (canvas *DrawingCanvas) MouseMove(mousepoint *Point, mbutton int) {
pt := *mousepoint
tool := mainWindow.tools.GetCurrentTool()
if canvas.firstMove {
canvas.lastPt = pt
canvas.firstMove = false
}
e := ToolMouseEvent{
pt: pt,
lastPt: canvas.lastPt,
mbutton: mbutton,
context: canvas.image.context,
image: canvas.image,
canvas: canvas,
}
tool.mouseMoveEvent(&e)
canvas.UpdateMousePosStatus()
canvas.RepaintVisible()
canvas.lastPt = pt
}
func (canvas *DrawingCanvas) OnResize(rect *Rect) {
logInfo("canvas resize...")
if canvas.mhdc != 0 {
win.DeleteDC(canvas.mhdc)
}
if canvas.mbitmap != 0 {
win.DeleteObject(win.HGDIOBJ(canvas.mbitmap))
}
rcVisible := *rect ///canvas.GetVisibleRect()
hdc := win.GetDC(canvas.GetHandle())
canvas.mhdc = win.CreateCompatibleDC(hdc)
canvas.mbitmap = win.CreateCompatibleBitmap(hdc, int32(rcVisible.Width()), int32(rcVisible.Height()))
win.SelectObject(canvas.mhdc, win.HGDIOBJ(canvas.mbitmap))
win.ReleaseDC(canvas.GetHandle(), hdc)
brushBack := win.GetStockObject(win.BLACK_BRUSH)
wrect := rcVisible.AsRECT()
FillRect(canvas.mhdc, &wrect, win.HBRUSH(brushBack))
if canvas.context != nil {
canvas.context.Dispose()
}
canvas.context = gdiplus.NewGraphicsFromHDC(gdiplus.HDC(canvas.mhdc))
//canvas.context.SetSmoothingMode(gdiplus.SmoothingModeHighSpeed)
}
// This returns only the visible area of the canvas, not the whole client rect
func (canvas *DrawingCanvas) GetVisibleRect() Rect {
work := mainWindow.workspace
if work == nil {
return canvas.GetClientRect()
}
// Get Screen Space Rects
rcWork := work.GetWindowRect()
rcCanvas := canvas.GetWindowRect()
// See if some portion of the left or top side of the canvas is hidden/we scrolled
// the width and height of workspace area should be enough
// ---(that just also includes the workspace scrollbars sizes too which is not a big deal, i hope :)
canvasTotalWidth := rcCanvas.Width() + (canvasMargin * 2) // mul by 2 for both sides
canvasTotalHeight := rcCanvas.Height() + (canvasMargin * 2) // mul by 2 for both sides
var rcVisible Rect
// If the whole width fits the workspace we just assign the original width with left being 0
if canvasTotalWidth <= rcWork.Width() {
rcVisible.Right = rcCanvas.Width()
} else {
if rcCanvas.Left < rcWork.Left {
rcVisible.Left = rcWork.Left - rcCanvas.Left
}
rcVisible.Right = rcVisible.Left + rcWork.Width()
}
// If the whole height fits the workspace we just assign the original height with top being 0
if canvasTotalHeight <= rcWork.Height() {
rcVisible.Bottom = rcCanvas.Height()
} else {
if rcCanvas.Top < rcWork.Left {
rcVisible.Top = rcWork.Top - rcCanvas.Top
}
rcVisible.Bottom = rcVisible.Top + rcWork.Height()
}
return rcVisible
}
func (canvas *DrawingCanvas) RepaintVisible() {
rect := canvas.GetVisibleRect()
canvas.InvalidateRect(&rect, false)
}
func (canvas *DrawingCanvas) DrawGridLines(g *Graphics, rect *Rect, rcVisible *Rect) {
g.SelectObject(canvas.gridPen)
for x := 10; x <= rect.Right; x += 10 {
if x > rcVisible.Left && x < rcVisible.Right {
g.DrawLineOnly(x, 0, x, rect.Bottom)
}
}
for y := 10; y <= rect.Bottom; y += 10 {
if y > rcVisible.Top && y < rcVisible.Bottom {
g.DrawLineOnly(0, y, rect.Right, y)
}
}
}
func (canvas *DrawingCanvas) Paint(g *Graphics, rect *Rect) {
if canvas.context == nil {
return
}
image := canvas.image
if image == nil {
return
}
rcVisible := canvas.GetVisibleRect()
clip := CreateRectRgn(int32(rcVisible.Left), int32(rcVisible.Top), int32(rcVisible.Right), int32(rcVisible.Bottom))
SelectClipRgn(canvas.mhdc, clip)
gmem := NewGraphics(canvas.mhdc)
gmem.BitBlt(rcVisible.Left, rcVisible.Top,
rcVisible.Width(), rcVisible.Height(), image.memdc,
rcVisible.Left, rcVisible.Top, win.SRCCOPY)
//gmem.AlphaBlend(rcVisible.Left, rcVisible.Top, rcVisible.Width(), rcVisible.Height(),
//image.memdc, rcVisible.Left, rcVisible.Top, rcVisible.Width(), rcVisible.Height())
if mainWindow.bShowGridlines.IsToggled() {
canvas.DrawGridLines(gmem, rect, &rcVisible)
}
var winpt win.POINT
win.GetCursorPos(&winpt)
win.ScreenToClient(canvas.GetHandle(), &winpt)
ptMouse := Point{X: int(winpt.X), Y: int(winpt.Y)}
tool := mainWindow.tools.GetCurrentTool()
if tool != nil {
e := ToolDrawEvent{
gdi32: gmem,
graphics: canvas.context,
mouse: ptMouse,
}
tool.draw(&e)
}
g.BitBlt(rcVisible.Left, rcVisible.Top,
rcVisible.Width(), rcVisible.Height(),
canvas.mhdc, rcVisible.Left, rcVisible.Top, win.SRCCOPY)
win.DeleteObject(win.HGDIOBJ(clip))
}