a71aa96e068d0379a09ff3992bac29d6ad6baeef
[master-thesis.git] / Parasitemia / ParasitemiaUI / GUI.fs
1 module ParasitemiaUI.GUI
2
3 open System
4 open System.IO
5 open System.Linq
6 open System.Windows
7 open System.Windows.Media
8 open System.Windows.Markup
9 open System.Windows.Shapes
10 open System.Windows.Controls
11 open System.Diagnostics
12 open Microsoft.Win32 // For the common dialogs.
13
14 open Emgu.CV.WPF
15
16 open Logger
17
18 open ParasitemiaCore.Config
19 open ParasitemiaCore.Utils
20 open Types
21
22 let run (defaultConfig: Config) (fileToOpen: string option) =
23 let app = new Application()
24 let mainWindow = Views.MainWindow()
25 let ctrl (name: string): 'a = mainWindow.Root.FindName(name) :?> 'a
26
27 let colorRBCHealthy = Brushes.YellowGreen
28 let colorRBCInfected = Brushes.Red
29
30 let state = State.State()
31 let mutable currentScale = 1.
32 let mutable displayHealthy = false
33
34 let menuExit: MenuItem = ctrl "menuExit"
35 let menuSaveFile: MenuItem = ctrl "menuSave"
36 let menuSaveAsFile: MenuItem = ctrl "menuSaveAs"
37 let menuLoadFile: MenuItem = ctrl "menuOpen"
38 let menuNewFile: MenuItem = ctrl "menuNew"
39 let menuAddSourceImage: MenuItem = ctrl "menuAddSourceImage"
40 let menuAnalysis: MenuItem = ctrl "menuAnalysis"
41 let menuStartAnalysis: MenuItem = ctrl "menuStartAnalysis"
42 let menuView: MenuItem = ctrl "menuView"
43 let menuHightlightRBC: MenuItem = ctrl "menuHightlightRBC"
44 let menuAbout: MenuItem = ctrl "menuAbout"
45
46 let txtDocumentStatus: TextBlock = ctrl "txtDocumentStatus"
47 let txtMessageStatus: TextBlock = ctrl "txtMessageStatus"
48
49 let txtPatient: TextBox = ctrl "txtPatient"
50 let txtGlobalParasitemia: TextBox = ctrl "txtGlobalParasitemia"
51
52 let stackPreviews: StackPanel = ctrl "stackPreviews"
53
54 let scrollViewCurrentImage: ScrollViewer = ctrl "scrollViewCurrentImage"
55 let borderCurrentImage: Border = ctrl "borderCurrentImage"
56 let canvasCurrentImage: Canvas = ctrl "canvasCurrentImage"
57 let txtImageInformation1: TextBlock = ctrl "txtImageInformation1"
58 let txtImageInformation2: TextBlock = ctrl "txtImageInformation2"
59
60 let scrollRBC: ScrollViewer = ctrl "scrollRBC"
61 let stackRBC: StackPanel = ctrl "stackRBC"
62
63 let imgLogos: Border = ctrl "imgLogos"
64
65 // Initializations.
66 let canvasCurrentImageColor = canvasCurrentImage.Background
67 menuHightlightRBC.IsChecked <- displayHealthy
68
69 // Utils.
70 let extractRBCPreview (img: Emgu.CV.Image<Emgu.CV.Structure.Bgr, byte>) (rbc: RBC) : Emgu.CV.Image<Emgu.CV.Structure.Bgr, byte> =
71 let rbcWidth = rbc.size.Width
72 let rbcHeight = rbc.size.Height
73 let x = rbc.center.X - rbcWidth / 2. |> roundInt
74 let y = rbc.center.Y - rbcHeight / 2. |> roundInt
75 let w = roundInt rbcWidth
76 let h = roundInt rbcHeight
77 img.GetSubRect(System.Drawing.Rectangle(System.Drawing.Point((if x < 0 then 0 else x), (if y < 0 then 0 else y)),
78 System.Drawing.Size((if x + w >= img.Width then img.Width - x else w),
79 (if y + h >= img.Height then img.Height - y else h))))
80
81 let setRBCFrameStyle (rbc: RBC) (frame: Views.RBCFrame) =
82 frame.Opacity <- if displayHealthy || rbc.setManually || rbc.infected then 1. else 0.
83 let color = if rbc.infected then colorRBCInfected else colorRBCHealthy
84 frame.manuallyAdded.Visibility <- if rbc.setManually then Visibility.Visible else Visibility.Hidden
85 frame.manuallyAdded.Fill <- color
86 frame.border.Stroke <- color
87
88 let RBCFrameFromExisting (rbc: RBC) (frame: Views.RBCFrame) : Views.RBCFrame =
89 frame.Visibility <- Visibility.Visible
90 frame.Height <- rbc.size.Height
91 frame.Width <- rbc.size.Width
92 frame.Tag <- rbc
93 setRBCFrameStyle rbc frame
94 frame.border.StrokeThickness <- 1.
95 frame.txtRBCNumber.Text <- rbc.num.ToString()
96 frame
97
98 let updateDocumentStatus () =
99 txtDocumentStatus.Text <- if state.FilePath = "" then "<New document>" else state.FilePath
100
101 let statusMessageTimer = Threading.DispatcherTimer()
102 statusMessageTimer.Tick.AddHandler(fun obj args -> statusMessageTimer.Stop(); txtMessageStatus.Text <- "")
103 statusMessageTimer.Interval <- TimeSpan(0, 0, 2)
104 let displayStatusMessage (message: string) =
105 txtMessageStatus.Text <- message
106 statusMessageTimer.Stop()
107 statusMessageTimer.Start()
108
109 let highlightRBCFrame (frame: Views.RBCFrame) (highlight: bool) =
110 let rbc = frame.Tag :?> RBC
111 if highlight
112 then
113 frame.border.StrokeThickness <- 3.
114 if not rbc.infected && not rbc.setManually && not displayHealthy then frame.Opacity <- 1.
115 else
116 frame.border.StrokeThickness <- 1.
117 if not rbc.infected && not rbc.setManually && not displayHealthy then frame.Opacity <- 0.
118
119 let zoomToRBC (rbc: RBC) =
120 scrollViewCurrentImage.ScrollToHorizontalOffset(rbc.center.X * currentScale - scrollViewCurrentImage.ViewportWidth / 2. + borderCurrentImage.BorderThickness.Left)
121 scrollViewCurrentImage.ScrollToVerticalOffset(rbc.center.Y * currentScale - scrollViewCurrentImage.ViewportHeight / 2. + borderCurrentImage.BorderThickness.Top)
122
123 let percentText (nbTotal: int, nb: int) : string =
124 if nbTotal = 0
125 then
126 ""
127 else
128 let percent = 100. * (float nb) / (float nbTotal)
129 sprintf "%.1f %% (%d / %d)" percent nb nbTotal
130
131 let updateCurrentImageInformation () =
132 txtImageInformation1.Inlines.Clear()
133 txtImageInformation2.Inlines.Clear()
134
135 match state.CurrentImage with
136 | Some srcImg ->
137 let parasitemiaStr = percentText (state.ImageParasitemia srcImg)
138 txtImageInformation1.Inlines.Add(Documents.Run("Parasitemia: ", FontWeight = FontWeights.Bold))
139 txtImageInformation1.Inlines.Add(parasitemiaStr)
140 txtImageInformation1.Inlines.Add(Documents.LineBreak())
141
142 txtImageInformation1.Inlines.Add(Documents.Run("Last analysis: ", FontWeight = FontWeights.Bold))
143 txtImageInformation1.Inlines.Add(Documents.Run(if srcImg.dateLastAnalysis.Ticks = 0L then "<Never>" else srcImg.dateLastAnalysis.ToLocalTime().ToString()))
144
145 let alteredStr = percentText (state.ImageNbAltered srcImg)
146 txtImageInformation2.Inlines.Add(Documents.Run("Number of erytrocytes manually altered: ", FontWeight = FontWeights.Bold))
147 txtImageInformation2.Inlines.Add(Documents.Run(alteredStr))
148 txtImageInformation2.Inlines.Add(Documents.LineBreak())
149
150 txtImageInformation2.Inlines.Add(Documents.Run("Average erytrocyte diameter: ", FontWeight = FontWeights.Bold))
151 txtImageInformation2.Inlines.Add(Documents.Run(srcImg.config.RBCRadius.ToString()))
152 | _ -> ()
153
154 let updateGlobalParasitemia () =
155 txtGlobalParasitemia.Text <- percentText state.GlobalParasitemia
156
157 let updateViewportPreview () =
158 for preview in stackPreviews.Children |> Seq.cast<Views.ImageSourcePreview> do
159 let srcImg = preview.Tag :?> SourceImage
160 if Some srcImg = state.CurrentImage then
161 preview.viewport.Visibility <- Visibility.Visible
162
163 let canvasWidth = canvasCurrentImage.ActualWidth * currentScale
164 let canvasHeight = canvasCurrentImage.ActualHeight * currentScale
165 let previewWidth = (preview.ActualWidth - preview.BorderThickness.Left - preview.BorderThickness.Right)
166 let previewHeight = (preview.ActualHeight - preview.BorderThickness.Top - preview.BorderThickness.Bottom)
167
168 let marginLeft = previewWidth * (scrollViewCurrentImage.HorizontalOffset - borderCurrentImage.BorderThickness.Left) / canvasWidth - 2.
169 let marginRight = previewWidth * (canvasWidth - (scrollViewCurrentImage.HorizontalOffset - borderCurrentImage.BorderThickness.Right) - scrollViewCurrentImage.ViewportWidth) / canvasWidth - 2.
170 let marginTop = previewHeight * (scrollViewCurrentImage.VerticalOffset - borderCurrentImage.BorderThickness.Top) / canvasHeight - 2.
171 let marginBottom = previewHeight * (canvasHeight - (scrollViewCurrentImage.VerticalOffset - borderCurrentImage.BorderThickness.Bottom) - scrollViewCurrentImage.ViewportHeight) / canvasHeight - 2.
172
173 preview.viewport.Margin <-
174 Thickness(
175 marginLeft,
176 marginTop,
177 marginRight,
178 marginBottom)
179 else
180 preview.viewport.Visibility <- Visibility.Hidden
181
182 let rec setAsInfected (rbc: RBC) (infected: bool) =
183 state.SetAsInfected rbc infected
184 canvasCurrentImage.Children
185 |> Seq.cast<Views.RBCFrame>
186 |> Seq.iter
187 (fun frame ->
188 if (frame.Tag :?> RBC) = rbc
189 then
190 setRBCFrameStyle rbc frame)
191 updateRBCFramesPreview ()
192 updateCurrentImageInformation ()
193 updateGlobalParasitemia ()
194
195 and RBCFrame (rbc: RBC) : Views.RBCFrame =
196 let frame = RBCFrameFromExisting rbc (Views.RBCFrame())
197 frame.SetValue(Panel.ZIndexProperty, Int32.MaxValue - rbc.num) // To be sure the
198 frame.menuRBCSetAsHealthy.Click.AddHandler(fun obj args -> setAsInfected (frame.Tag :?> RBC) false)
199 frame.menuRBCSetAsInfected.Click.AddHandler(fun obj args -> setAsInfected (frame.Tag :?> RBC) true)
200 frame.ContextMenuOpening.AddHandler(
201 fun obj args ->
202 if (frame.Tag :?> RBC).infected
203 then
204 frame.menuRBCSetAsHealthy.Visibility <- Visibility.Visible
205 frame.menuRBCSetAsInfected.Visibility <- Visibility.Collapsed
206 else
207 frame.menuRBCSetAsHealthy.Visibility <- Visibility.Collapsed
208 frame.menuRBCSetAsInfected.Visibility <- Visibility.Visible)
209
210 frame.ContextMenuClosing.AddHandler(fun obj args -> if not frame.IsMouseOver then highlightRBCFrame frame false )
211 frame.MouseEnter.AddHandler(fun obj args -> highlightRBCFrame frame true)
212 frame.MouseLeave.AddHandler(fun obj args -> if not frame.grid.ContextMenu.IsOpen then highlightRBCFrame frame false)
213 frame
214
215 and updateRBCFramesPreview () =
216 match state.CurrentImage with
217 | Some srcImg ->
218 let mutable currentPreview = 0
219 for rbc in srcImg.rbcs |> List.filter (fun rbc -> displayHealthy || rbc.infected) do
220 let previewInfected =
221 if currentPreview < stackRBC.Children.Count
222 then
223 RBCFrameFromExisting rbc (stackRBC.Children.[currentPreview] :?> Views.RBCFrame)
224 else
225 let f = RBCFrame rbc
226 f.MouseLeftButtonUp.AddHandler(fun obj args -> zoomToRBC (f.Tag :?> RBC))
227 stackRBC.Children.Add(f) |> ignore
228 f
229
230 currentPreview <- currentPreview + 1
231
232 previewInfected.Height <- stackRBC.ActualHeight
233 previewInfected.Width <- stackRBC.ActualHeight * rbc.size.Width / rbc.size.Height
234 previewInfected.border.Fill <- ImageBrush(BitmapSourceConvert.ToBitmapSource(extractRBCPreview srcImg.img rbc))
235
236 stackRBC.Children.RemoveRange(currentPreview, stackRBC.Children.Count - currentPreview)
237 | _ -> ()
238
239 updateViewportPreview ()
240
241 let updateRBCFramesCurrent () =
242 match state.CurrentImage with
243 | Some srcImg ->
244 let mutable currentCanvas = 0
245 for rbc in srcImg.rbcs do
246 let frame =
247 if currentCanvas < canvasCurrentImage.Children.Count
248 then
249 RBCFrameFromExisting rbc (canvasCurrentImage.Children.[currentCanvas] :?> Views.RBCFrame)
250 else
251 let f = RBCFrame rbc
252 f.Root.Opacity <- 0.7
253 canvasCurrentImage.Children.Add(f) |> ignore
254 f
255
256 currentCanvas <- currentCanvas + 1
257
258 Canvas.SetLeft(frame, rbc.center.X - rbc.size.Width / 2.)
259 Canvas.SetTop(frame, rbc.center.Y - rbc.size.Height / 2.)
260
261 for i in currentCanvas .. canvasCurrentImage.Children.Count - 1 do
262 canvasCurrentImage.Children.[i].Visibility <- Visibility.Hidden
263 | _ -> ()
264
265 let askDocumentPathToSave () : string option =
266 let dialog = SaveFileDialog(AddExtension = true, DefaultExt = PiaZ.extension, Filter = PiaZ.filter)
267
268 if state.FilePath <> ""
269 then
270 dialog.FileName <- FileInfo(state.FilePath).Name
271 elif state.PatientID <> ""
272 then
273 dialog.FileName <- state.PatientID + PiaZ.extension
274
275 let res = dialog.ShowDialog()
276 if res.HasValue && res.Value then
277 Some dialog.FileName
278 else
279 None
280
281 let saveCurrentDocument () =
282 try
283 if state.FilePath = ""
284 then
285 match askDocumentPathToSave () with
286 | Some filepath ->
287 state.FilePath <- filepath
288 state.Save()
289 | _ -> ()
290 else
291 state.Save()
292 updateDocumentStatus ()
293 displayStatusMessage "Document saved"
294 with
295 | :? IOException as ex ->
296 Log.Error(ex.ToString())
297 MessageBox.Show(sprintf "The document cannot be save in '%s'" state.FilePath, "Error saving the document", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore
298
299 let saveCurrentDocumentAsNewFile () =
300 match askDocumentPathToSave () with
301 | Some filepath ->
302 state.FilePath <- filepath
303 saveCurrentDocument ()
304 | _ -> ()
305
306 // Ask the use to save the current document if neccessary.
307 let askSaveCurrent () =
308 if state.AlteredSinceLastSave
309 then
310 match MessageBox.Show("Would you like to save the current document?", "Saving the current document", MessageBoxButton.YesNo, MessageBoxImage.Question) with
311 | MessageBoxResult.Yes -> saveCurrentDocument ()
312 | _ -> ()
313
314 let updateCurrentImage () =
315 match state.CurrentImage with
316 | Some srcImg ->
317 imgLogos.Visibility <- Visibility.Collapsed
318
319 // Highlight the preview.
320 stackPreviews.Children
321 |> Seq.cast<Views.ImageSourcePreview>
322 |> Seq.iter (fun preview -> preview.border.BorderThickness <- Thickness(if preview.Tag = (srcImg :> Object) then 3. else 0.))
323
324 canvasCurrentImage.Height <- float srcImg.img.Height
325 canvasCurrentImage.Width <- float srcImg.img.Width
326 canvasCurrentImage.Background <- ImageBrush(BitmapSourceConvert.ToBitmapSource(srcImg.img))
327
328 updateRBCFramesCurrent ()
329 updateRBCFramesPreview ()
330 | None ->
331 imgLogos.Visibility <- Visibility.Visible
332 stackRBC.Children.Clear()
333 canvasCurrentImage.Children.Clear()
334 canvasCurrentImage.Background <- canvasCurrentImageColor
335
336 updateCurrentImageInformation ()
337
338 let setCurrentImage (srcImg: SourceImage) =
339 if state.CurrentImage.IsNone || state.CurrentImage.Value <> srcImg
340 then
341 state.CurrentImage <- Some srcImg
342 updateCurrentImage ()
343
344 let addPreview (srcImg: SourceImage) =
345 let imgCtrl = Views.ImageSourcePreview(Margin = Thickness(3.))
346
347 imgCtrl.menuRemoveImage.Click.AddHandler(fun obj args ->
348 stackPreviews.Children.Remove(imgCtrl)
349 let srcImg = imgCtrl.Tag :?> SourceImage
350 let currentRemoved = Some srcImg = state.CurrentImage
351 state.RemoveSourceImage srcImg
352 if currentRemoved
353 then
354 updateCurrentImage()
355
356 updateGlobalParasitemia()
357
358 // Update image numbers.
359 stackPreviews.Children |> Seq.cast<Views.ImageSourcePreview> |> Seq.iter (fun imgPreview -> imgPreview.txtImageNumber.Text <- (imgPreview.Tag :?> SourceImage).num.ToString()))
360
361 imgCtrl.Tag <- srcImg
362 imgCtrl.txtImageNumber.Text <- srcImg.num.ToString()
363 let width = 200
364 let height = srcImg.img.Height * width / srcImg.img.Width
365 imgCtrl.imagePreview.Source <- BitmapSourceConvert.ToBitmapSource(srcImg.img.Resize(width, height, Emgu.CV.CvEnum.Inter.Cubic))
366 stackPreviews.Children.Add(imgCtrl) |> ignore
367
368 // Zoom to a mouse position into the control 'imgCtrl'.
369 let zoomTo (mousePos: Point) =
370 let canvasW = canvasCurrentImage.ActualWidth * currentScale
371 let canvasH = canvasCurrentImage.ActualHeight * currentScale
372 let centerX = (mousePos.X - imgCtrl.BorderThickness.Left) / (imgCtrl.ActualWidth - imgCtrl.BorderThickness.Left) * canvasW
373 let centerY = (mousePos.Y - imgCtrl.BorderThickness.Top) / (imgCtrl.ActualHeight - imgCtrl.BorderThickness.Top) * canvasH
374 scrollViewCurrentImage.ScrollToHorizontalOffset(centerX - scrollViewCurrentImage.ViewportWidth / 2. + borderCurrentImage.BorderThickness.Left)
375 scrollViewCurrentImage.ScrollToVerticalOffset(centerY - scrollViewCurrentImage.ViewportHeight / 2. + borderCurrentImage.BorderThickness.Top)
376
377 imgCtrl.MouseLeftButtonDown.AddHandler(fun obj args ->
378 setCurrentImage (state.SourceImages |> Seq.find (fun srcImg -> (srcImg :> Object) = imgCtrl.Tag))
379 imgCtrl.UpdateLayout()
380 zoomTo (args.GetPosition(imgCtrl))
381 imgCtrl.CaptureMouse() |> ignore)
382
383 imgCtrl.MouseMove.AddHandler(fun obj args ->
384 if imgCtrl.IsMouseCaptured
385 then
386 zoomTo (args.GetPosition(imgCtrl)))
387
388 imgCtrl.MouseLeftButtonUp.AddHandler(fun obj args ->
389 if imgCtrl.IsMouseCaptured
390 then
391 imgCtrl.ReleaseMouseCapture())
392
393 let updatePreviews () =
394 stackPreviews.Children.Clear ()
395 for srcImg in state.SourceImages do
396 addPreview srcImg
397 updateCurrentImage ()
398
399 let updateGUI () =
400 txtPatient.Text <- state.PatientID
401 updatePreviews ()
402 updateGlobalParasitemia ()
403 updateDocumentStatus ()
404
405 let loadFile (filepath: string) =
406 askSaveCurrent ()
407 let previousFilePath = state.FilePath
408 try
409 state.FilePath <- filepath
410 state.Load()
411 updateGUI ()
412 with
413 | :? IOException as ex ->
414 Log.Error(ex.ToString())
415 state.FilePath <- previousFilePath
416 MessageBox.Show(sprintf "The document cannot be loaded from '%s'" state.FilePath, "Error loading the document", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore
417
418 let askLoadFile () =
419 let dialog = OpenFileDialog(Filter = PiaZ.filter)
420 let res = dialog.ShowDialog()
421 if res.HasValue && res.Value
422 then loadFile dialog.FileName
423
424 let newFile () =
425 askSaveCurrent ()
426 state.Reset()
427 updateGUI()
428
429 txtPatient.TextChanged.AddHandler(fun obj args -> state.PatientID <- txtPatient.Text)
430
431 menuExit.Click.AddHandler(fun obj args -> mainWindow.Root.Close())
432 menuSaveFile.Click.AddHandler(fun obj args -> saveCurrentDocument ())
433 menuSaveAsFile.Click.AddHandler(fun obj args -> saveCurrentDocumentAsNewFile ())
434 menuLoadFile.Click.AddHandler(fun obj args -> askLoadFile ())
435 menuNewFile.Click.AddHandler(fun obj args -> newFile ())
436
437 menuAddSourceImage.Click.AddHandler(fun obj args ->
438 let dialog = OpenFileDialog(Filter = "Image Files|*.png;*.jpg;*.tif;*.tiff", Multiselect = true)
439 let res = dialog.ShowDialog()
440 if res.HasValue && res.Value
441 then
442 let noSourceImage = state.SourceImages.Count() = 0
443
444 for filename in dialog.FileNames do
445 try
446 let srcImg = state.AddSourceImage filename defaultConfig
447 addPreview srcImg
448 with
449 | _ as ex ->
450 Log.Error(ex.ToString())
451 MessageBox.Show(sprintf "Unable to read the image from '%s'" filename, "Error adding an image", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore
452
453 updateGlobalParasitemia ()
454
455 if noSourceImage
456 then
457 updateCurrentImage ())
458
459 menuAnalysis.SubmenuOpened.AddHandler(fun obj args -> menuStartAnalysis.IsEnabled <- state.SourceImages.Count() > 0)
460
461 menuStartAnalysis.Click.AddHandler(fun obj args ->
462 if Analysis.showWindow mainWindow.Root state
463 then
464 updateGlobalParasitemia ()
465 updateCurrentImage ())
466
467 menuHightlightRBC.Click.AddHandler(fun obj args ->
468 displayHealthy <- menuHightlightRBC.IsChecked
469 updateRBCFramesPreview ()
470 updateRBCFramesCurrent ())
471
472 menuAbout.Click.AddHandler(fun obj args -> About.showWindow mainWindow.Root)
473
474 mainWindow.Root.Closing.AddHandler(fun obj args -> askSaveCurrent ())
475
476 // Zoom on the current image.
477 let adjustCurrentImageBorders (deltaX: float) (deltaY: float) =
478 borderCurrentImage.BorderThickness <-
479 Thickness(
480 (scrollViewCurrentImage.ViewportWidth + deltaX) / 2.,
481 (scrollViewCurrentImage.ViewportHeight + deltaY) / 2.,
482 (scrollViewCurrentImage.ViewportWidth + deltaX) / 2.,
483 (scrollViewCurrentImage.ViewportHeight + deltaY) / 2.)
484
485 canvasCurrentImage.SizeChanged.AddHandler(fun obj args ->
486 let deltaX = args.NewSize.Width - args.PreviousSize.Width
487 let deltaY = args.NewSize.Height - args.PreviousSize.Height
488 if deltaX > 0.5 || deltaY > 0.5
489 then
490 adjustCurrentImageBorders 0.0 0.0
491 // Center the view at the center of the image initialy.
492 scrollViewCurrentImage.UpdateLayout()
493 scrollViewCurrentImage.ScrollToHorizontalOffset(borderCurrentImage.ActualWidth / 2. - scrollViewCurrentImage.ViewportWidth / 2.)
494 scrollViewCurrentImage.ScrollToVerticalOffset(borderCurrentImage.ActualHeight / 2. - scrollViewCurrentImage.ViewportHeight / 2.))
495
496 scrollViewCurrentImage.SizeChanged.AddHandler(fun obj args ->
497 let deltaX = args.NewSize.Width - args.PreviousSize.Width
498 let deltaY = args.NewSize.Height - args.PreviousSize.Height
499 adjustCurrentImageBorders deltaX deltaY
500 scrollViewCurrentImage.ScrollToHorizontalOffset(scrollViewCurrentImage.HorizontalOffset + deltaX / 8.)
501 scrollViewCurrentImage.ScrollToVerticalOffset(scrollViewCurrentImage.VerticalOffset + deltaY / 8.))
502
503 let mutable maxScale = 4.
504 let mutable minScale = 0.25
505 let currentImageScaleTransform = ScaleTransform()
506 canvasCurrentImage.LayoutTransform <- currentImageScaleTransform
507 borderCurrentImage.PreviewMouseWheel.AddHandler(fun obj args ->
508 let scaleFactor = if args.Delta > 0 then 2.0 else 0.5
509 if scaleFactor > 1. && currentScale < maxScale || scaleFactor < 1. && currentScale > minScale
510 then
511 let previousScale = currentScale
512 currentScale <-
513 let newScale = currentScale * scaleFactor
514 if newScale > maxScale then maxScale elif newScale < minScale then minScale else newScale
515 let realScaleFactor = currentScale / previousScale
516
517 let centerX = scrollViewCurrentImage.HorizontalOffset + scrollViewCurrentImage.ViewportWidth / 2. - borderCurrentImage.BorderThickness.Left
518 let centerY = scrollViewCurrentImage.VerticalOffset + scrollViewCurrentImage.ViewportHeight / 2. - borderCurrentImage.BorderThickness.Top
519
520 currentImageScaleTransform.ScaleX <- currentScale
521 currentImageScaleTransform.ScaleY <- currentScale
522
523 scrollViewCurrentImage.ScrollToHorizontalOffset(centerX * realScaleFactor - scrollViewCurrentImage.ViewportWidth / 2. + borderCurrentImage.BorderThickness.Left)
524 scrollViewCurrentImage.ScrollToVerticalOffset(centerY * realScaleFactor - scrollViewCurrentImage.ViewportHeight / 2. + borderCurrentImage.BorderThickness.Top)
525
526 args.Handled <- true)
527
528 // Pan on the current image.
529 let mutable scrollStartPosition = Point(0., 0.)
530 let mutable scrollStartOffsetX = 0.
531 let mutable scrollStartOffsetY = 0.
532 borderCurrentImage.PreviewMouseLeftButtonDown.AddHandler(fun obj args ->
533 scrollStartPosition <- args.GetPosition(scrollViewCurrentImage)
534 scrollStartOffsetX <- scrollViewCurrentImage.HorizontalOffset
535 scrollStartOffsetY <- scrollViewCurrentImage.VerticalOffset
536 borderCurrentImage.Cursor <- Input.Cursors.ScrollAll
537 borderCurrentImage.CaptureMouse() |> ignore
538 args.Handled <- true)
539
540 borderCurrentImage.PreviewMouseMove.AddHandler(fun obj args ->
541 if borderCurrentImage.IsMouseCaptured
542 then
543 let position = args.GetPosition(scrollViewCurrentImage)
544 let deltaX = scrollStartPosition.X - position.X
545 let deltaY = scrollStartPosition.Y - position.Y
546 scrollViewCurrentImage.ScrollToHorizontalOffset(deltaX + scrollStartOffsetX)
547 scrollViewCurrentImage.ScrollToVerticalOffset(deltaY + scrollStartOffsetY)
548
549 args.Handled <- true)
550
551 borderCurrentImage.PreviewMouseLeftButtonUp.AddHandler(fun obj args ->
552 if borderCurrentImage.IsMouseCaptured
553 then
554 borderCurrentImage.Cursor <- Input.Cursors.Arrow
555 borderCurrentImage.ReleaseMouseCapture()
556 args.Handled <- true)
557
558 // Shortcuts.
559 // Save.
560 mainWindow.Root.InputBindings.Add(
561 Input.KeyBinding(
562 FSharp.ViewModule.FunCommand((fun obj -> saveCurrentDocument ()), (fun obj -> true)),
563 Input.KeyGesture(Input.Key.S, Input.ModifierKeys.Control))) |> ignore
564
565 // Save as.
566 mainWindow.Root.InputBindings.Add(
567 Input.KeyBinding(
568 FSharp.ViewModule.FunCommand((fun obj -> saveCurrentDocumentAsNewFile ()), (fun obj -> true)),
569 Input.KeyGesture(Input.Key.S, Input.ModifierKeys.Control ||| Input.ModifierKeys.Shift))) |> ignore
570
571 // Open.
572 mainWindow.Root.InputBindings.Add(
573 Input.KeyBinding(
574 FSharp.ViewModule.FunCommand((fun obj -> askLoadFile ()), (fun obj -> true)),
575 Input.KeyGesture(Input.Key.O, Input.ModifierKeys.Control))) |> ignore
576
577 // New file.
578 mainWindow.Root.InputBindings.Add(
579 Input.KeyBinding(
580 FSharp.ViewModule.FunCommand((fun obj -> newFile ()), (fun obj -> true)),
581 Input.KeyGesture(Input.Key.N, Input.ModifierKeys.Control))) |> ignore
582
583 // Viewport preview.
584 scrollViewCurrentImage.ScrollChanged.AddHandler(fun obj args -> updateViewportPreview ())
585
586 updateDocumentStatus ()
587
588 mainWindow.Root.Show()
589
590 match fileToOpen with
591 | Some filepath -> loadFile filepath
592 | None -> ()
593
594 app.Run()