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