AppDelegate.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. /*
  2. *
  3. * Copyright 2016, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. import Cocoa
  34. import gRPC
  35. import QuickProto
  36. @NSApplicationMain
  37. class AppDelegate: NSObject, NSApplicationDelegate {
  38. @IBOutlet weak var window: NSWindow!
  39. func applicationDidFinishLaunching(_ aNotification: Notification) {
  40. startServer(address:"localhost:8081")
  41. }
  42. func log(_ message: String) {
  43. print(message)
  44. }
  45. func startServer(address:String) {
  46. if let fileDescriptorSetProto =
  47. NSData(contentsOfFile:Bundle.main.path(forResource: "stickynote", ofType: "out")!) {
  48. // load a FileDescriptorSet that includes a descriptor for the message to be created
  49. let fileDescriptorSet = FileDescriptorSet(proto:fileDescriptorSetProto)
  50. DispatchQueue.global().async {
  51. self.log("Server Starting")
  52. self.log("GRPC version " + gRPC.version())
  53. let server = gRPC.Server(address:address)
  54. server.start()
  55. var requestCount = 0
  56. while(true) {
  57. let (callError, completionType, requestHandler) = server.getNextRequest(timeout:1.0)
  58. if (callError != GRPC_CALL_OK) {
  59. self.log("\(requestCount): Call error \(callError)")
  60. self.log("------------------------------")
  61. } else if (completionType == GRPC_OP_COMPLETE) {
  62. if let requestHandler = requestHandler {
  63. requestCount += 1
  64. self.log("\(requestCount): Received request " + requestHandler.host() + " " + requestHandler.method() + " from " + requestHandler.caller())
  65. let initialMetadata = requestHandler.requestMetadata
  66. for i in 0..<initialMetadata.count() {
  67. self.log("\(requestCount): Received initial metadata -> " + initialMetadata.key(index:i) + ":" + initialMetadata.value(index:i))
  68. }
  69. let initialMetadataToSend = Metadata()
  70. initialMetadataToSend.add(key:"a", value:"Apple")
  71. initialMetadataToSend.add(key:"b", value:"Banana")
  72. initialMetadataToSend.add(key:"c", value:"Cherry")
  73. let (_, _, message) = requestHandler.receiveMessage(initialMetadata:initialMetadataToSend)
  74. if let message = message {
  75. self.log("\(requestCount): Received message: \(message.data())")
  76. let requestMessage = fileDescriptorSet.readMessage(name:"StickyNoteRequest", proto:message.data())
  77. requestMessage?.forOneField(name:"message") {(field) in
  78. let imageData = self.drawImage(message: field.string())
  79. // construct an internal representation of the message
  80. let replyMessage = fileDescriptorSet.createMessage(name:"StickyNoteResponse")!
  81. replyMessage.addField(name:"image") {(field) in field.setData(imageData)}
  82. let trailingMetadataToSend = Metadata()
  83. trailingMetadataToSend.add(key:"0", value:"zero")
  84. trailingMetadataToSend.add(key:"1", value:"one")
  85. trailingMetadataToSend.add(key:"2", value:"two")
  86. let (_, _) = requestHandler.sendResponse(message:ByteBuffer(data:replyMessage.serialize()),
  87. trailingMetadata:trailingMetadataToSend)
  88. self.log("------------------------------")
  89. }
  90. }
  91. }
  92. } else if (completionType == GRPC_QUEUE_TIMEOUT) {
  93. // everything is fine
  94. } else if (completionType == GRPC_QUEUE_SHUTDOWN) {
  95. // we should stop
  96. }
  97. }
  98. }
  99. }
  100. }
  101. func drawImage(message: String) -> NSData {
  102. let image = NSImage.init(size: NSSize.init(width: 400, height: 400),
  103. flipped: false,
  104. drawingHandler: { (rect) -> Bool in
  105. NSColor.yellow.set()
  106. NSRectFill(rect)
  107. NSColor.black.set()
  108. let string = NSString(string:message)
  109. var s = CGFloat(300.0)
  110. let trialFont = NSFont.userFont(ofSize:s)!
  111. let trialAttributes = [NSFontAttributeName: trialFont]
  112. let trialSize = string.size(withAttributes: trialAttributes)
  113. s = s * 300 / trialSize.width;
  114. let font = NSFont.userFont(ofSize:s)!
  115. let attributes = [NSFontAttributeName: font]
  116. let size = string.size(withAttributes: attributes)
  117. let x = rect.origin.x + 0.5*(rect.size.width - size.width)
  118. let y = rect.origin.y + 0.5*(rect.size.height - size.height)
  119. let r = NSMakeRect(x, y, size.width, size.height)
  120. string.draw(in: r, withAttributes:attributes)
  121. return true})
  122. let imgData: Data! = image.tiffRepresentation!
  123. let bitmap: NSBitmapImageRep! = NSBitmapImageRep(data: imgData)
  124. let pngImage = bitmap!.representation(using:NSBitmapImageFileType.PNG, properties:[:])
  125. return NSData(data:pngImage!)
  126. }
  127. }