source: launchers/macosx/I2PLauncher/userinterface/LogViewController.swift @ b5497ef

Last change on this file since b5497ef was b5497ef, checked in by meeh <meeh@…>, 2 years ago

Mac OSX Launcher: Cancel stream that can cause high cpu load on router stop.

  • Property mode set to 100644
File size: 1.9 KB
Line 
1//
2//  LogViewController.swift
3//  I2PLauncher
4//
5//  Created by Mikal Villa on 18/09/2018.
6//  Copyright © 2018 The I2P Project. All rights reserved.
7//
8
9import Foundation
10import AppKit
11
12class LogViewerViewController : NSTabViewItem {
13 
14  @IBOutlet var scrollView: NSScrollView?
15  @IBOutlet var textFieldView: NSTextView?
16 
17  private var outputPipe : Pipe?
18 
19  override init(identifier: Any?) {
20    super.init(identifier: identifier)
21    self.captureStandardOutputAndRouteToTextView()
22  }
23 
24  required init?(coder aDecoder: NSCoder) {
25    super.init(coder: aDecoder)
26    self.captureStandardOutputAndRouteToTextView()
27  }
28 
29 
30  func captureStandardOutputAndRouteToTextView() {
31    outputPipe = RouterManager.shared().getRouterTask()?.processPipe
32    outputPipe?.fileHandleForReading.waitForDataInBackgroundAndNotify()
33   
34    NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outputPipe?.fileHandleForReading , queue: nil) {
35      notification in
36
37      let output = self.outputPipe?.fileHandleForReading.availableData
38      let outputString = String(data: output!, encoding: String.Encoding.utf8) ?? ""
39      let workTask = DispatchWorkItem {
40        let previousOutput = self.textFieldView?.string ?? ""
41        let nextOutput = previousOutput + "\n" + outputString
42        self.textFieldView?.string = nextOutput
43       
44        let range = NSRange(location:nextOutput.characters.count,length:0)
45        self.textFieldView?.scrollRangeToVisible(range)
46      }
47      DispatchQueue.main.async(execute: workTask)
48     
49      // When router stop, stop the stream as well. If not it will go wild and create high cpu load
50      RouterManager.shared().eventManager.listenTo(eventName: "router_stop", action: {
51        NSLog("Time to cancel stream!")
52        workTask.cancel()
53      })
54     
55     
56      self.outputPipe?.fileHandleForReading.waitForDataInBackgroundAndNotify()
57    }
58   
59  }
60}
61
62
Note: See TracBrowser for help on using the repository browser.