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