Browse Source

format code using swiftformat

dignifiedquire 6 years ago
parent
commit
405d738f72

+ 13 - 17
deltachat-ios/AppCoordinator.swift

@@ -19,50 +19,46 @@ class AppCoordinator: Coordinator {
         window.rootViewController = AppTabBarController()
         window.makeKeyAndVisible()
         // window.backgroundColor = UIColor.white
-        
-        
-        
+
 //            setupInnerViewControllers()
 //        } else {
-////            let email = "alice@librechat.net"
-////            let password = "foobar"
-////            initCore(email: email, password: password)
+        ////            let email = "alice@librechat.net"
+        ////            let password = "foobar"
+        ////            initCore(email: email, password: password)
 //
 //            displayCredentialsController()
 //        }
     }
-    
-    func displayCredentialsController(message: String? = nil, isCancellable:Bool = false) {
+
+    func displayCredentialsController(message: String? = nil, isCancellable: Bool = false) {
         let credentialsController = CredentialsController(isCancellable: isCancellable)
-        
+
         let credentialsNav = UINavigationController(rootViewController: credentialsController)
-        
+
         if baseController.presentedViewController != nil {
             baseController.dismiss(animated: false, completion: nil)
         }
-        
+
         baseController.present(credentialsNav, animated: false) {
             if let message = message {
                 let alert = UIAlertController(title: "Warning", message: message, preferredStyle: .alert)
-                
+
                 alert.addAction(UIAlertAction(title: "Help / Provider Overview", style: UIAlertAction.Style.default, handler: {
                     _ in
                     let url = URL(string: "https://support.delta.chat/t/provider-overview/56/2")!
                     UIApplication.shared.open(url, options: [:])
                 }))
-                
+
                 alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
                 credentialsNav.present(alert, animated: false, completion: nil)
-                
             }
         }
     }
-    
-    func setupInnerViewControllers() {
 
+    func setupInnerViewControllers() {
         let chatListController = ChatListController()
         let chatNavigationController = UINavigationController(rootViewController: chatListController)
-        
+
         baseController.present(chatNavigationController, animated: false, completion: nil)
     }
 }

+ 35 - 38
deltachat-ios/AppDelegate.swift

@@ -6,14 +6,14 @@
 //  Copyright © 2017 Jonas Reinsch. All rights reserved.
 //
 
-import UIKit
 import AudioToolbox
-import UserNotifications
-import Reachability
 import DBDebugToolkit
+import Reachability
 import SwiftyBeaver
+import UIKit
+import UserNotifications
 
-var mailboxPointer:UnsafeMutablePointer<dc_context_t>!
+var mailboxPointer: UnsafeMutablePointer<dc_context_t>!
 let logger = SwiftyBeaver.self
 
 enum ApplicationState {
@@ -23,12 +23,11 @@ enum ApplicationState {
     case backgroundFetch
 }
 
-
 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate {
     static let appCoordinator = AppCoordinator()
-    static var progress:Float = 0
-    static var lastErrorDuringConfig:String? = nil
+    static var progress: Float = 0
+    static var lastErrorDuringConfig: String?
     static var cancellableCredentialsController = false
 
     var reachability = Reachability()!
@@ -36,14 +35,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
 
     var state = ApplicationState.stopped
 
-    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
+    func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
         DBDebugToolkit.setup()
-        
+
         let console = ConsoleDestination()
         logger.addDestination(console)
-        
-        logger.info( "launching")
-        
+
+        logger.info("launching")
+
         // Override point for customization after application launch.
 
         window = UIWindow(frame: UIScreen.main.bounds)
@@ -67,8 +66,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
         return true
     }
 
-    func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
-       logger.info( "---- background-fetch ----")
+    func application(_: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
+        logger.info("---- background-fetch ----")
 
         if mailboxPointer == nil {
             //       - second param remains nil (user data for more than one mailbox)
@@ -94,22 +93,22 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
         }
     }
 
-    func applicationWillEnterForeground(_ application: UIApplication) {
-       logger.info( "---- foreground ----")
+    func applicationWillEnterForeground(_: UIApplication) {
+        logger.info("---- foreground ----")
         start()
     }
 
-    func applicationDidEnterBackground(_ application: UIApplication) {
-       logger.info( "---- background ----")
-       
+    func applicationDidEnterBackground(_: UIApplication) {
+        logger.info("---- background ----")
+
         stop()
-        
+
         reachability.stopNotifier()
         NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)
     }
 
-    func applicationWillTerminate(_ application: UIApplication) {
-       logger.info( "---- terminate ----")
+    func applicationWillTerminate(_: UIApplication) {
+        logger.info("---- terminate ----")
         close()
     }
 
@@ -119,12 +118,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
         let dbfile = documentsPath + "/messenger.db"
         logger.info("open: \(dbfile)")
 
-        let _ = dc_open(mailboxPointer, dbfile, nil)
+        _ = dc_open(mailboxPointer, dbfile, nil)
     }
 
     func stop() {
         state = .background
-        
+
         dc_interrupt_imap_idle(mailboxPointer)
         dc_interrupt_smtp_idle(mailboxPointer)
         dc_interrupt_mvbox_idle(mailboxPointer)
@@ -133,7 +132,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
 
     private func close() {
         state = .stopped
-        
+
         dc_close(mailboxPointer)
         mailboxPointer = nil
 
@@ -142,7 +141,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
     }
 
     func start() {
-       logger.info( "---- start ----")
+        logger.info("---- start ----")
 
         if mailboxPointer == nil {
             //       - second param remains nil (user data for more than one mailbox)
@@ -187,7 +186,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
         do {
             try reachability.startNotifier()
         } catch {
-           logger.info( "could not start reachability notifier")
+            logger.info("could not start reachability notifier")
         }
     }
 
@@ -219,13 +218,13 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
     func registerForPushNotifications() {
         UNUserNotificationCenter.current()
             .requestAuthorization(options: [.alert, .sound, .badge]) {
-                granted, error in
+                granted, _ in
                 logger.info("permission granted: \(granted)")
-        }
+            }
     }
 }
 
-func initCore(withCredentials: Bool, advancedMode:Bool = false, model:CredentialsModel? = nil, cancellableCredentialsUponFailure: Bool = false) {
+func initCore(withCredentials: Bool, advancedMode: Bool = false, model: CredentialsModel? = nil, cancellableCredentialsUponFailure: Bool = false) {
     AppDelegate.cancellableCredentialsController = cancellableCredentialsUponFailure
 
     if withCredentials {
@@ -251,7 +250,6 @@ func initCore(withCredentials: Bool, advancedMode:Bool = false, model:Credential
                 dc_set_config(mailboxPointer, "mail_port", imapPort)
             }
 
-
             if let smtpLoginName = model.smtpLoginName {
                 dc_set_config(mailboxPointer, "send_user", smtpLoginName)
             }
@@ -265,8 +263,8 @@ func initCore(withCredentials: Bool, advancedMode:Bool = false, model:Credential
                 dc_set_config(mailboxPointer, "send_port", smtpPort)
             }
 
-            var flags:Int32 = 0
-            if (model.smtpSecurity == .automatic) && (model.imapSecurity == .automatic) {
+            var flags: Int32 = 0
+            if model.smtpSecurity == .automatic, (model.imapSecurity == .automatic) {
                 flags = DC_LP_AUTH_NORMAL
             } else {
                 if model.smtpSecurity == .off {
@@ -303,12 +301,11 @@ func initCore(withCredentials: Bool, advancedMode:Bool = false, model:Credential
     addVibrationOnIncomingMessage()
 }
 
-
 func addVibrationOnIncomingMessage() {
     let nc = NotificationCenter.default
-    nc.addObserver(forName:Notification.Name(rawValue:"MrEventIncomingMsg"),
-                   object:nil, queue:nil) {
-                    notification in
-                    AudioServicesPlaySystemSound(UInt32(kSystemSoundID_Vibrate))
+    nc.addObserver(forName: Notification.Name(rawValue: "MrEventIncomingMsg"),
+                   object: nil, queue: nil) {
+        _ in
+        AudioServicesPlaySystemSound(UInt32(kSystemSoundID_Vibrate))
     }
 }

+ 18 - 21
deltachat-ios/AppTabBarController.swift

@@ -9,59 +9,56 @@
 import UIKit
 
 class AppTabBarController: UITabBarController {
-
     override func viewDidLoad() {
         super.viewDidLoad()
 
         let contactListController = ContactListController()
         let contactNavigationController = NavigationController(rootViewController: contactListController)
         let contactImage = UIImage(named: "contacts")
-        contactNavigationController.tabBarItem = UITabBarItem.init(title: "Contacts", image: contactImage, tag: 0)
+        contactNavigationController.tabBarItem = UITabBarItem(title: "Contacts", image: contactImage, tag: 0)
 
         let mailboxController = ChatViewController(chatId: Int(DC_CHAT_ID_DEADDROP))
         mailboxController.disableWriting = true
         let mailboxNavigationController = NavigationController(rootViewController: mailboxController)
         let mailboxImage = UIImage(named: "message")
-        mailboxNavigationController.tabBarItem = UITabBarItem.init(title: "Mailbox", image: mailboxImage, tag: 1)
+        mailboxNavigationController.tabBarItem = UITabBarItem(title: "Mailbox", image: mailboxImage, tag: 1)
 
         let profileController = ProfileViewController()
         let profileNavigationController = NavigationController(rootViewController: profileController)
         let profileImage = UIImage(named: "report_card")
-        profileNavigationController.tabBarItem = UITabBarItem.init(title: "My Profile", image: profileImage, tag: 2)
+        profileNavigationController.tabBarItem = UITabBarItem(title: "My Profile", image: profileImage, tag: 2)
 
         let chatListController = ChatListController()
         let chatNavigationController = NavigationController(rootViewController: chatListController)
         let chatImage = UIImage(named: "chat")
-        chatNavigationController.tabBarItem = UITabBarItem.init(title: "Chats", image: chatImage, tag: 3)
+        chatNavigationController.tabBarItem = UITabBarItem(title: "Chats", image: chatImage, tag: 3)
 
         let settingsController = SettingsViewController()
         let settingsNavigationController = NavigationController(rootViewController: settingsController)
         let settingsImage = UIImage(named: "settings")
-        settingsNavigationController.tabBarItem = UITabBarItem.init(title: "Settings", image: settingsImage, tag: 4)
+        settingsNavigationController.tabBarItem = UITabBarItem(title: "Settings", image: settingsImage, tag: 4)
 
         let tabBarList = [
-          contactNavigationController,
-          mailboxNavigationController,
-          profileNavigationController,
-          chatNavigationController,
-          settingsNavigationController
+            contactNavigationController,
+            mailboxNavigationController,
+            profileNavigationController,
+            chatNavigationController,
+            settingsNavigationController,
         ]
 
         viewControllers = tabBarList
-        self.selectedIndex = 3
+        selectedIndex = 3
 
         tabBar.tintColor = Constants.primaryColor
     }
 
-
     /*
-    // MARK: - Navigation
-
-    // In a storyboard-based application, you will often want to do a little preparation before navigation
-    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
-        // Get the new view controller using segue.destination.
-        // Pass the selected object to the new view controller.
-    }
-    */
+     // MARK: - Navigation
 
+     // In a storyboard-based application, you will often want to do a little preparation before navigation
+     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
+     // Get the new view controller using segue.destination.
+     // Pass the selected object to the new view controller.
+     }
+     */
 }

+ 29 - 45
deltachat-ios/BaseController.swift

@@ -9,77 +9,67 @@
 import UIKit
 
 class ProgressViewContainer: UIView {
-    
     let progressView = UIProgressView(progressViewStyle: .default)
-    
+
     init() {
         super.init(frame: .zero)
-        self.backgroundColor = .lightGray
-        
+        backgroundColor = .lightGray
+
         let label = UILabel()
         label.translatesAutoresizingMaskIntoConstraints = false
-        self.addSubview(label)
+        addSubview(label)
         label.textAlignment = .center
-        label.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
-        label.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: -50).isActive = true
+        label.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
+        label.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -50).isActive = true
         label.textColor = .darkGray
         label.text = "Configuring…"
-        
+
         let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
         activityIndicator.translatesAutoresizingMaskIntoConstraints = false
-        self.addSubview(activityIndicator)
-        
-        activityIndicator.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
-        activityIndicator.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 50).isActive = true
+        addSubview(activityIndicator)
+
+        activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
+        activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 50).isActive = true
         activityIndicator.startAnimating()
-        
-        
+
         progressView.progressTintColor = .darkGray
         progressView.trackTintColor = .white
         progressView.progress = 0.0
-        
-        self.addSubview(progressView)
-        
+
+        addSubview(progressView)
+
         progressView.translatesAutoresizingMaskIntoConstraints = false
-        progressView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
-        progressView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10).isActive = true
-        progressView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
+        progressView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
+        progressView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
+        progressView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
     }
-    
-    
-    required init?(coder aDecoder: NSCoder) {
+
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
-    
 }
 
-
-
-
 class BaseController: UIViewController {
     let progressViewContainer = ProgressViewContainer()
     var progressChangedObserver: Any?
 
     override func loadView() {
-        self.view = progressViewContainer
+        view = progressViewContainer
     }
-    
-    override func viewDidLoad() {
 
-    }
-    
+    override func viewDidLoad() {}
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
         let nc = NotificationCenter.default
-        progressChangedObserver = nc.addObserver(forName:Notification.Name(rawValue:"ProgressUpdated"),
-                                            object:nil, queue:nil) {
-                                                notification in
-                                              logger.info( "----------- ProgressUpdated notification received --------")
-                                                self.progressViewContainer.progressView.progress = AppDelegate.progress
+        progressChangedObserver = nc.addObserver(forName: Notification.Name(rawValue: "ProgressUpdated"),
+                                                 object: nil, queue: nil) {
+            _ in
+            logger.info("----------- ProgressUpdated notification received --------")
+            self.progressViewContainer.progressView.progress = AppDelegate.progress
         }
     }
-    
+
     override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
         let nc = NotificationCenter.default
@@ -88,9 +78,3 @@ class BaseController: UIViewController {
         }
     }
 }
-
-
-
-
-
-

+ 176 - 195
deltachat-ios/ChatViewController.swift

@@ -6,39 +6,38 @@
 //  Copyright © 2017 Jonas Reinsch. All rights reserved.
 //
 
-import UIKit
-import MessageKit
 import MapKit
 import MessageInputBar
+import MessageKit
+import UIKit
 
 class ChatViewController: MessagesViewController {
     let outgoingAvatarOverlap: CGFloat = 17.5
 
     let chatId: Int
     let refreshControl = UIRefreshControl()
-    var messageIds:[Int] = []
+    var messageIds: [Int] = []
     var messageList: [Message] = []
 
     var msgChangedObserver: Any?
     var incomingMsgObserver: Any?
-    
+
     var disableWriting = false
-    
+
     init(chatId: Int) {
         self.chatId = chatId
         super.init(nibName: nil, bundle: nil)
         // self.getMessageIds()
-        
+
         /*
-        let chat = MRChat(id: chatId)
+         let chat = MRChat(id: chatId)
          let subtitle = dc_chat_get_subtitle(chat.chatPointer)!
 
-        let s = String(validatingUTF8: subtitle)
-      logger.info( s)
- */
-
+         let s = String(validatingUTF8: subtitle)
+         logger.info( s)
+         */
     }
-    
+
     @objc
     func loadMoreMessages() {
         DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
@@ -50,7 +49,7 @@ class ChatViewController: MessagesViewController {
             }
         }
     }
-    
+
     func loadFirstMessages() {
         DispatchQueue.global(qos: .userInitiated).async {
             self.getMessageIds()
@@ -62,14 +61,14 @@ class ChatViewController: MessagesViewController {
             }
         }
     }
-    
+
     private func idToMessage(messageId: Int) -> Message {
         let message = MRMessage(id: messageId)
         let contact = MRContact(id: message.fromContactId)
         let messageId = "\(messageId)"
         let date = Date(timeIntervalSince1970: Double(message.timestamp))
         let sender = Sender(id: "\(contact.id)", displayName: contact.name)
-        
+
         if message.isInfo {
             let text = NSAttributedString(string: message.text ?? "", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12), NSAttributedString.Key.foregroundColor: UIColor.darkGray])
             return Message(attributedText: text, sender: sender, messageId: messageId, date: date)
@@ -79,16 +78,16 @@ class ChatViewController: MessagesViewController {
             return Message(text: message.text ?? "- empty -", sender: sender, messageId: messageId, date: date)
         }
     }
-    
+
     private func messageToMRMessage(message: Message) -> MRMessage? {
         if let id = Int(message.messageId) {
             return MRMessage(id: id)
         }
-        
+
         return nil
     }
-    
-    var textDraft:String? {
+
+    var textDraft: String? {
         // FIXME: need to free pointer
         if let draft = dc_get_draft(mailboxPointer, UInt32(chatId)) {
             if let text = dc_msg_get_text(draft) {
@@ -99,62 +98,62 @@ class ChatViewController: MessagesViewController {
         }
         return nil
     }
-    
+
     func getMessageIds() {
-        let c_messageIds = dc_get_chat_msgs(mailboxPointer, UInt32(self.chatId), 0, 0)
+        let c_messageIds = dc_get_chat_msgs(mailboxPointer, UInt32(chatId), 0, 0)
         messageIds = Utils.copyAndFreeArray(inputArray: c_messageIds)
-        
+
         let ids: UnsafePointer = UnsafePointer(messageIds.map { id in
-            return UInt32(id)
+            UInt32(id)
         })
 
         dc_markseen_msgs(mailboxPointer, ids, Int32(messageIds.count))
     }
-    
-    required init?(coder aDecoder: NSCoder) {
+
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         let nc = NotificationCenter.default
-        msgChangedObserver = nc.addObserver(forName:dc_notificationChanged,
-                                            object:nil, queue: OperationQueue.main) {
-                                                notification in
-                                                if let ui = notification.userInfo {
-                                                    if self.chatId == ui["chat_id"] as! Int {
-                                                        self.updateMessage(ui["message_id"] as! Int)
-                                                    }
-                                                }
-        }
-        
-        incomingMsgObserver = nc.addObserver(forName:dc_notificationIncoming,
-                                             object:nil, queue: OperationQueue.main) {
-                                                notification in
-                                                if let ui = notification.userInfo {
-                                                    if self.chatId == ui["chat_id"] as! Int {
-                                                        let id = ui["message_id"] as! Int
-                                                        self.insertMessage(self.idToMessage(messageId: id))
-                                                    }
-                                                }
-        }
-    }
-    
+        msgChangedObserver = nc.addObserver(forName: dc_notificationChanged,
+                                            object: nil, queue: OperationQueue.main) {
+            notification in
+            if let ui = notification.userInfo {
+                if self.chatId == ui["chat_id"] as! Int {
+                    self.updateMessage(ui["message_id"] as! Int)
+                }
+            }
+        }
+
+        incomingMsgObserver = nc.addObserver(forName: dc_notificationIncoming,
+                                             object: nil, queue: OperationQueue.main) {
+            notification in
+            if let ui = notification.userInfo {
+                if self.chatId == ui["chat_id"] as! Int {
+                    let id = ui["message_id"] as! Int
+                    self.insertMessage(self.idToMessage(messageId: id))
+                }
+            }
+        }
+    }
+
     func setTextDraft() {
         if let text = self.messageInputBar.inputTextView.text {
             let draft = dc_msg_new(mailboxPointer, DC_MSG_TEXT)
             dc_msg_set_text(draft, text.cString(using: .utf8))
             dc_set_draft(mailboxPointer, UInt32(chatId), draft)
-            
+
             // cleanup
             dc_msg_unref(draft)
         }
     }
-    
+
     override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
-        
+
         setTextDraft()
         let nc = NotificationCenter.default
         if let msgChangedObserver = self.msgChangedObserver {
@@ -164,93 +163,91 @@ class ChatViewController: MessagesViewController {
             nc.removeObserver(incomingMsgObserver)
         }
     }
-    
+
     override var inputAccessoryView: UIView? {
         if disableWriting {
             return nil
         }
-        
+
         return messageInputBar
     }
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
 
-        let chat = MRChat(id: self.chatId)
+        let chat = MRChat(id: chatId)
         updateTitleView(title: chat.name, subtitle: nil)
-        
+
         configureMessageCollectionView()
         if !disableWriting {
             configureMessageInputBar()
             messageInputBar.inputTextView.text = textDraft
             messageInputBar.inputTextView.becomeFirstResponder()
         }
-        
+
         loadFirstMessages()
     }
-    
+
     func configureMessageCollectionView() {
         messagesCollectionView.messagesDataSource = self
         messagesCollectionView.messageCellDelegate = self
-        
+
         scrollsToBottomOnKeyboardBeginsEditing = true // default false
         maintainPositionOnKeyboardFrameChanged = true // default false
-        
+
         messagesCollectionView.addSubview(refreshControl)
         refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
-        
-        
+
         let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout
         layout?.sectionInset = UIEdgeInsets(top: 1, left: 8, bottom: 1, right: 8)
-        
+
         // Hide the outgoing avatar and adjust the label alignment to line up with the messages
         layout?.setMessageOutgoingAvatarSize(.zero)
         layout?.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
         layout?.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
-        
+
         // Set outgoing avatar to overlap with the message bubble
         layout?.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left, textInsets: UIEdgeInsets(top: 0, left: 18, bottom: outgoingAvatarOverlap, right: 0)))
         layout?.setMessageIncomingAvatarSize(CGSize(width: 30, height: 30))
         layout?.setMessageIncomingMessagePadding(UIEdgeInsets(top: -outgoingAvatarOverlap, left: -18, bottom: outgoingAvatarOverlap, right: 18))
-        
+
         layout?.setMessageIncomingAccessoryViewSize(CGSize(width: 30, height: 30))
         layout?.setMessageIncomingAccessoryViewPadding(HorizontalEdgeInsets(left: 8, right: 0))
         layout?.setMessageOutgoingAccessoryViewSize(CGSize(width: 30, height: 30))
         layout?.setMessageOutgoingAccessoryViewPadding(HorizontalEdgeInsets(left: 0, right: 8))
-        
+
         messagesCollectionView.messagesLayoutDelegate = self
         messagesCollectionView.messagesDisplayDelegate = self
-        
     }
-    
+
     func configureMessageInputBar() {
         messageInputBar.delegate = self
         messageInputBar.inputTextView.tintColor = Constants.primaryColor
         messageInputBar.sendButton.tintColor = Constants.primaryColor
-        
+
         messageInputBar.isTranslucent = true
         messageInputBar.separatorLine.isHidden = true
         messageInputBar.inputTextView.tintColor = Constants.primaryColor
-        
+
         messageInputBar.delegate = self
         scrollsToBottomOnKeyboardBeginsEditing = true
-        
-        messageInputBar.inputTextView.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
+
+        messageInputBar.inputTextView.backgroundColor = UIColor(red: 245 / 255, green: 245 / 255, blue: 245 / 255, alpha: 1)
         messageInputBar.inputTextView.placeholderTextColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
         messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
         messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
-        messageInputBar.inputTextView.layer.borderColor = UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1).cgColor
+        messageInputBar.inputTextView.layer.borderColor = UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1).cgColor
         messageInputBar.inputTextView.layer.borderWidth = 1.0
         messageInputBar.inputTextView.layer.cornerRadius = 16.0
         messageInputBar.inputTextView.layer.masksToBounds = true
         messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
         configureInputBarItems()
     }
-    
+
     private func configureInputBarItems() {
         messageInputBar.setLeftStackViewWidthConstant(to: 44, animated: false)
         messageInputBar.setRightStackViewWidthConstant(to: 36, animated: false)
-        
+
         let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
         messageInputBar.sendButton.image = sendButtonImage
         messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
@@ -260,9 +257,9 @@ class ChatViewController: MessagesViewController {
 
         messageInputBar.sendButton.title = nil
         messageInputBar.sendButton.layer.cornerRadius = 18
-        
+
         messageInputBar.textViewPadding.right = -40
-        
+
         let leftItems = [
             InputBarButtonItem()
                 .configure {
@@ -274,12 +271,12 @@ class ChatViewController: MessagesViewController {
                     $0.tintColor = Constants.primaryColor
                 }.onDeselected {
                     $0.tintColor = UIColor(white: 0.8, alpha: 1)
-                }.onTouchUpInside {  _ in
+                }.onTouchUpInside { _ in
                     self.didPressPhotoButton()
-                }
+                },
         ]
         messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
-        
+
         // This just adds some more flare
         messageInputBar.sendButton
             .onEnabled { item in
@@ -290,21 +287,20 @@ class ChatViewController: MessagesViewController {
                 UIView.animate(withDuration: 0.3, animations: {
                     item.backgroundColor = UIColor(white: 0.9, alpha: 1)
                 })
-        }
+            }
     }
-    
+
     // MARK: - UICollectionViewDataSource
-    
+
     public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
-        
         guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
             fatalError("Ouch. nil data source for messages")
         }
-        
+
         //        guard !isSectionReservedForTypingBubble(indexPath.section) else {
         //            return super.collectionView(collectionView, cellForItemAt: indexPath)
         //        }
-        
+
         let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
         if case .custom = message.kind {
             let cell = messagesCollectionView.dequeueReusableCell(CustomCell.self, for: indexPath)
@@ -318,38 +314,37 @@ class ChatViewController: MessagesViewController {
 // MARK: - MessagesDataSource
 
 extension ChatViewController: MessagesDataSource {
-    func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
+    func numberOfSections(in _: MessagesCollectionView) -> Int {
         return messageList.count
     }
-    
+
     func currentSender() -> Sender {
-        
         let currentSender = Sender(id: "1", displayName: "Alice")
         return currentSender
     }
-    
-    func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
+
+    func messageForItem(at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageType {
         return messageList[indexPath.section]
     }
-    
-    func avatar(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> Avatar {
+
+    func avatar(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> Avatar {
         if let id = Int(messageList[indexPath.section].messageId) {
             let message = MRMessage(id: id)
             let contact = message.fromContact
             return Avatar(image: contact.profileImage, initials: Utils.getInitials(inputName: contact.name))
         }
-        
+
         return Avatar(image: nil, initials: "?")
     }
-    
+
     func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
         if isTimeLabelVisible(at: indexPath) {
             return NSAttributedString(string: MessageKitDateFormatter.shared.string(from: message.sentDate), attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10), NSAttributedString.Key.foregroundColor: UIColor.darkGray])
         }
-        
+
         return nil
     }
-    
+
     func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
         if !isPreviousMessageSameSender(at: indexPath) {
             let name = message.sender.displayName
@@ -358,45 +353,42 @@ extension ChatViewController: MessagesDataSource {
         return nil
     }
 
-    
     func isTimeLabelVisible(at indexPath: IndexPath) -> Bool {
         // TODO: better heuristic when to show the time label
         return indexPath.section % 3 == 0 && !isPreviousMessageSameSender(at: indexPath)
     }
-    
+
     func isPreviousMessageSameSender(at indexPath: IndexPath) -> Bool {
         guard indexPath.section - 1 >= 0 else { return false }
         return messageList[indexPath.section].sender == messageList[indexPath.section - 1].sender
     }
-    
+
     func isInfoMessage(at indexPath: IndexPath) -> Bool {
         if let id = Int(messageList[indexPath.section].messageId) {
             return MRMessage(id: id).isInfo
         }
-        
+
         return false
     }
-        
-    
+
     func isNextMessageSameSender(at indexPath: IndexPath) -> Bool {
         guard indexPath.section + 1 < messageList.count else { return false }
         return messageList[indexPath.section].sender == messageList[indexPath.section + 1].sender
     }
-    
-    func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
 
+    func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
         guard indexPath.section < messageList.count else { return nil }
         if let m = messageToMRMessage(message: messageList[indexPath.section]) {
-            if !isNextMessageSameSender(at: indexPath) && isFromCurrentSender(message: message) {
+            if !isNextMessageSameSender(at: indexPath), isFromCurrentSender(message: message) {
                 return NSAttributedString(string: m.stateOutDescription(), attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption1)])
             }
         }
         return nil
     }
-    
+
     func updateMessage(_ messageId: Int) {
         let messageIdStr = String(messageId)
-        if let index = messageList.firstIndex(where:{$0.messageId == messageIdStr}) {
+        if let index = messageList.firstIndex(where: { $0.messageId == messageIdStr }) {
             messageList[index] = idToMessage(messageId: messageId)
             // Reload section to update header/footer labels
             messagesCollectionView.performBatchUpdates({
@@ -416,7 +408,7 @@ extension ChatViewController: MessagesDataSource {
             insertMessage(idToMessage(messageId: messageId))
         }
     }
-    
+
     func insertMessage(_ message: Message) {
         messageList.append(message)
         // Reload last section to update header/footer labels and insert a new one
@@ -431,10 +423,10 @@ extension ChatViewController: MessagesDataSource {
             }
         })
     }
-    
+
     func isLastSectionVisible() -> Bool {
         guard !messageList.isEmpty else { return false }
-        
+
         let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1)
         return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
     }
@@ -443,32 +435,29 @@ extension ChatViewController: MessagesDataSource {
 // MARK: - MessagesDisplayDelegate
 
 extension ChatViewController: MessagesDisplayDelegate {
-    
     // MARK: - Text Messages
-    
-    func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
+
+    func textColor(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
         return .darkText
     }
-    
+
     // MARK: - All Messages
-    
-    func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
+
+    func backgroundColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
         return isFromCurrentSender(message: message) ? Constants.messagePrimaryColor : Constants.messageSecondaryColor
     }
-    
-    func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
 
+    func messageStyle(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageStyle {
         if isInfoMessage(at: indexPath) {
             return .custom { view in
                 view.style = .none
                 view.backgroundColor = UIColor(alpha: 0, red: 0, green: 0, blue: 0)
                 view.center.x = self.view.center.x
-
             }
         }
-        
+
         var corners: UIRectCorner = []
-        
+
         if isFromCurrentSender(message: message) {
             corners.formUnion(.topLeft)
             corners.formUnion(.bottomLeft)
@@ -488,7 +477,7 @@ extension ChatViewController: MessagesDisplayDelegate {
                 corners.formUnion(.bottomLeft)
             }
         }
-        
+
         return .custom { view in
             let radius: CGFloat = 16
             let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
@@ -497,9 +486,8 @@ extension ChatViewController: MessagesDisplayDelegate {
             view.layer.mask = mask
         }
     }
-    
-    func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
-        
+
+    func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) {
         if let id = Int(messageList[indexPath.section].messageId) {
             let message = MRMessage(id: id)
             let contact = message.fromContact
@@ -508,8 +496,8 @@ extension ChatViewController: MessagesDisplayDelegate {
             avatarView.isHidden = isNextMessageSameSender(at: indexPath) || message.isInfo
         }
     }
-    
-    func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType] {
+
+    func enabledDetectors(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> [DetectorType] {
         return [.url, .date, .phoneNumber, .address]
     }
 }
@@ -517,35 +505,33 @@ extension ChatViewController: MessagesDisplayDelegate {
 // MARK: - MessagesLayoutDelegate
 
 extension ChatViewController: MessagesLayoutDelegate {
-    
-    func cellTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
+    func cellTopLabelHeight(for _: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
         if isTimeLabelVisible(at: indexPath) {
             return 18
         }
         return 0
     }
-    
-    func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
+
+    func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
         if isFromCurrentSender(message: message) {
             return !isPreviousMessageSameSender(at: indexPath) ? 20 : 0
         } else {
             return !isPreviousMessageSameSender(at: indexPath) ? (20 + outgoingAvatarOverlap) : 0
         }
     }
-    
-    func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
+
+    func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
         return (!isNextMessageSameSender(at: indexPath) && isFromCurrentSender(message: message)) && !isInfoMessage(at: indexPath) ? 16 : 0
     }
 
-    func heightForLocation(message: MessageType, at indexPath: IndexPath, with maxWidth: CGFloat, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
+    func heightForLocation(message _: MessageType, at _: IndexPath, with _: CGFloat, in _: MessagesCollectionView) -> CGFloat {
         return 40
     }
-    
-    func footerViewSize(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGSize {
-        
+
+    func footerViewSize(for _: MessageType, at _: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGSize {
         return CGSize(width: messagesCollectionView.bounds.width, height: 10)
     }
-    
+
     @objc func didPressPhotoButton() {
         if UIImagePickerController.isSourceTypeAvailable(.camera) {
             let imagePicker = UIImagePickerController()
@@ -553,49 +539,49 @@ extension ChatViewController: MessagesLayoutDelegate {
             imagePicker.cameraDevice = .rear
             imagePicker.delegate = self
             imagePicker.allowsEditing = true
-            self.present(imagePicker, animated: true, completion: nil)
+            present(imagePicker, animated: true, completion: nil)
         } else {
-          logger.info( "no camera available")
+            logger.info("no camera available")
         }
     }
-    
+
     fileprivate func saveImage(image: UIImage) -> String? {
         guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
             return nil
         }
-        
+
         let size = image.size.applying(CGAffineTransform(scaleX: 0.2, y: 0.2))
         let hasAlpha = false
         let scale: CGFloat = 0.0
-        
+
         UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
         image.draw(in: CGRect(origin: CGPoint.zero, size: size))
-        
+
         let _scaledImage = UIGraphicsGetImageFromCurrentImageContext()
         UIGraphicsEndImageContext()
-        
+
         guard let scaledImage = _scaledImage else {
             return nil
         }
-        
+
         guard let data = scaledImage.jpegData(compressionQuality: 0.9) else {
             return nil
         }
-        
+
         do {
-            let timestamp = Int(Date().timeIntervalSince1970) 
+            let timestamp = Int(Date().timeIntervalSince1970)
             let path = directory.appendingPathComponent("\(chatId)_\(timestamp).jpg")
             try data.write(to: path!)
             return path?.relativePath
         } catch {
-          logger.info( error.localizedDescription)
+            logger.info(error.localizedDescription)
             return nil
         }
     }
 }
 
 extension ChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
-    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
+    func imagePickerController(_: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
         DispatchQueue.global().async {
             if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage,
                 let width = Int32(exactly: pickedImage.size.width),
@@ -605,43 +591,40 @@ extension ChatViewController: UIImagePickerControllerDelegate, UINavigationContr
                 dc_msg_set_file(msg, path, "image/jpeg")
                 dc_msg_set_dimension(msg, width, height)
                 dc_send_msg(mailboxPointer, UInt32(self.chatId), msg)
-                
+
                 // cleanup
                 dc_msg_unref(msg)
             }
         }
-        
+
         dismiss(animated: true, completion: nil)
     }
 }
 
-
 // MARK: - MessageCellDelegate
 
 extension ChatViewController: MessageCellDelegate {
-    func didTapMessage(in cell: MessageCollectionViewCell) {
-      logger.info( "Message tapped")
+    func didTapMessage(in _: MessageCollectionViewCell) {
+        logger.info("Message tapped")
     }
-    
-    func didTapAvatar(in cell: MessageCollectionViewCell) {
-      logger.info( "Avatar tapped")
-    
+
+    func didTapAvatar(in _: MessageCollectionViewCell) {
+        logger.info("Avatar tapped")
     }
-    
-    @objc(didTapCellTopLabelIn:) func didTapCellTopLabel(in cell: MessageCollectionViewCell) {
-      logger.info( "Top label tapped")
+
+    @objc(didTapCellTopLabelIn:) func didTapCellTopLabel(in _: MessageCollectionViewCell) {
+        logger.info("Top label tapped")
     }
 
-    func didTapBottomLabel(in cell: MessageCollectionViewCell) {
-        print ("Bottom label tapped")
+    func didTapBottomLabel(in _: MessageCollectionViewCell) {
+        print("Bottom label tapped")
     }
 }
 
 // MARK: - MessageLabelDelegate
 
 extension ChatViewController: MessageLabelDelegate {
-    
-    func didSelectAddress(_ addressComponents: [String : String]) {
+    func didSelectAddress(_ addressComponents: [String: String]) {
         let mapAddress = Utils.formatAddressForQuery(address: addressComponents)
         if let escapedMapAddress = mapAddress.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
             // Use query, to handle malformed addresses
@@ -650,58 +633,56 @@ extension ChatViewController: MessageLabelDelegate {
             }
         }
     }
-    
+
     func didSelectDate(_ date: Date) {
         let interval = date.timeIntervalSinceReferenceDate
         if let url = NSURL(string: "calshow:\(interval)") {
             UIApplication.shared.open(url as URL)
         }
     }
-    
+
     func didSelectPhoneNumber(_ phoneNumber: String) {
-      logger.info( "phone open", phoneNumber)
+        logger.info("phone open", phoneNumber)
         if let escapedPhoneNumber = phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
             if let url = NSURL(string: "tel:\(escapedPhoneNumber)") {
                 UIApplication.shared.open(url as URL)
             }
         }
     }
-    
+
     func didSelectURL(_ url: URL) {
         UIApplication.shared.open(url)
     }
 }
 
 // MARK: - LocationMessageDisplayDelegate
+
 /*
-extension ChatViewController: LocationMessageDisplayDelegate {
-    func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
-        let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
-        let pinImage = #imageLiteral(resourceName: "ic_block_36pt").withRenderingMode(.alwaysTemplate)
-        annotationView.image = pinImage
-        annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
-        return annotationView
-    }
-    
-    func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
-        return { view in
-            view.layer.transform = CATransform3DMakeScale(0, 0, 0)
-            view.alpha = 0.0
-            UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
-                view.layer.transform = CATransform3DIdentity
-                view.alpha = 1.0
-            }, completion: nil)
-        }
-    }
-}
-*/
+ extension ChatViewController: LocationMessageDisplayDelegate {
+ func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
+ let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
+ let pinImage = #imageLiteral(resourceName: "ic_block_36pt").withRenderingMode(.alwaysTemplate)
+ annotationView.image = pinImage
+ annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
+ return annotationView
+ }
 
+ func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
+ return { view in
+ view.layer.transform = CATransform3DMakeScale(0, 0, 0)
+ view.alpha = 0.0
+ UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
+ view.layer.transform = CATransform3DIdentity
+ view.alpha = 1.0
+ }, completion: nil)
+ }
+ }
+ }
+ */
 
 // MARK: - MessageInputBarDelegate
- 
 
 extension ChatViewController: MessageInputBarDelegate {
-    
     func messageInputBar(_ inputBar: MessageInputBar, didPressSendButtonWith text: String) {
         DispatchQueue.global().async {
             dc_send_text_msg(mailboxPointer, UInt32(self.chatId), text)

+ 8 - 9
deltachat-ios/Constants.swift

@@ -10,22 +10,21 @@ import UIKit
 
 struct Constants {
     // see: https://core.telegram.org/blackberry/chat
-    static let chatColors:[UIColor] = ["#ee4928", "#41a903", "#e09602", "#0f94ed", "#8f3bf7", "#fc4380", "#00a1c4", "#eb7002"].map {s in UIColor(hexString: s)}
-     struct Color {
-        static let bubble = UIColor(netHex: 0xefffde)
+    static let chatColors: [UIColor] = ["#ee4928", "#41a903", "#e09602", "#0f94ed", "#8f3bf7", "#fc4380", "#00a1c4", "#eb7002"].map { s in UIColor(hexString: s) }
+    struct Color {
+        static let bubble = UIColor(netHex: 0xEFFFDE)
     }
-    
+
     struct Keys {
         static let deltachatUserProvidedCredentialsKey = "__DELTACHAT_USER_PROVIDED_CREDENTIALS_KEY__"
         static let deltachatImapEmailKey = "__DELTACHAT_IMAP_EMAIL_KEY__"
         static let deltachatImapPasswordKey = "__DELTACHAT_IMAP_PASSWORD_KEY__"
     }
-    
-    static let primaryColor = UIColor(red: 81/255, green: 73/255, blue: 255/255, alpha: 1)
+
+    static let primaryColor = UIColor(red: 81 / 255, green: 73 / 255, blue: 255 / 255, alpha: 1)
     static let messagePrimaryColor = Constants.primaryColor.withAlphaComponent(0.5)
-    static let messageSecondaryColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
-    
+    static let messageSecondaryColor = UIColor(red: 245 / 255, green: 245 / 255, blue: 245 / 255, alpha: 1)
+
     static let defaultShadow = UIImage(color: UIColor(hexString: "ff2b82"), size: CGSize(width: 1, height: 1))
     static let onlineShadow = UIImage(color: UIColor(hexString: "3ed67e"), size: CGSize(width: 1, height: 1))
 }
-

+ 20 - 25
deltachat-ios/ContactCell.swift

@@ -9,10 +9,10 @@
 import UIKit
 
 class ContactCell: UITableViewCell {
-    let initialsLabel:UILabel = UILabel()
+    let initialsLabel: UILabel = UILabel()
     let nameLabel = UILabel()
     let emailLabel = UILabel()
-    
+
     var darkMode: Bool = false {
         didSet {
             if darkMode {
@@ -22,13 +22,13 @@ class ContactCell: UITableViewCell {
             }
         }
     }
-    
+
     override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
         super.init(style: style, reuseIdentifier: reuseIdentifier)
-   
+
         // configure and layout initialsLabel
         let initialsLabelSize: CGFloat = 48
-        let initialsLabelCornerRadius = initialsLabelSize/2
+        let initialsLabelCornerRadius = initialsLabelSize / 2
         let margin: CGFloat = 15
         initialsLabel.textAlignment = NSTextAlignment.center
         initialsLabel.textColor = UIColor.white
@@ -37,58 +37,53 @@ class ContactCell: UITableViewCell {
         initialsLabel.widthAnchor.constraint(equalToConstant: initialsLabelSize).isActive = true
         initialsLabel.heightAnchor.constraint(equalToConstant: initialsLabelSize).isActive = true
         initialsLabel.backgroundColor = UIColor.green
-        
+
         initialsLabel.layer.cornerRadius = initialsLabelCornerRadius
         initialsLabel.clipsToBounds = true
-        
-        
-        self.contentView.addSubview(initialsLabel)
+
+        contentView.addSubview(initialsLabel)
         initialsLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: margin).isActive = true
-        initialsLabel.center = self.contentView.center
+        initialsLabel.center = contentView.center
         initialsLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: margin).isActive = true
         initialsLabel.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -margin).isActive = true
-        
+
         let myStackView = UIStackView()
         myStackView.translatesAutoresizingMaskIntoConstraints = false
         myStackView.clipsToBounds = true
-        
-        self.contentView.addSubview(myStackView)
+
+        contentView.addSubview(myStackView)
         myStackView.leadingAnchor.constraint(equalTo: initialsLabel.trailingAnchor, constant: margin).isActive = true
         myStackView.centerYAnchor.constraint(equalTo: initialsLabel.centerYAnchor).isActive = true
         myStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -margin).isActive = true
         myStackView.axis = .vertical
         myStackView.addArrangedSubview(nameLabel)
         myStackView.addArrangedSubview(emailLabel)
-        
+
         nameLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
         nameLabel.lineBreakMode = .byTruncatingTail
         nameLabel.textColor = UIColor(hexString: "2f3944")
-        
+
         emailLabel.font = UIFont.systemFont(ofSize: 14)
         emailLabel.textColor = UIColor(hexString: "848ba7")
         emailLabel.lineBreakMode = .byTruncatingTail
     }
-    
+
     func setImage(_ img: UIImage) {
         let attachment = NSTextAttachment()
         attachment.image = img
         initialsLabel.attributedText = NSAttributedString(attachment: attachment)
     }
-    
+
     func setBackupImage(name: String, color: UIColor) {
         initialsLabel.text = Utils.getInitials(inputName: name)
         setColor(color)
     }
-    
+
     func setColor(_ color: UIColor) {
-        self.initialsLabel.backgroundColor = color
+        initialsLabel.backgroundColor = color
     }
-    
-    required init?(coder aDecoder: NSCoder) {
+
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
 }
-
-
-
-

+ 25 - 26
deltachat-ios/ContactProfileViewController.swift

@@ -14,29 +14,29 @@ class ContactProfileViewController: UITableViewController {
     var contact: MRContact {
         return MRContact(id: contactId)
     }
-    
+
     init(contactId: Int) {
         self.contactId = contactId
         super.init(style: .plain)
     }
-    
-    required init?(coder aDecoder: NSCoder) {
+
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
-    override func viewWillAppear(_ animated: Bool) {
+
+    override func viewWillAppear(_: Bool) {
         navigationController?.navigationBar.prefersLargeTitles = false
         tableView.reloadData()
     }
-    
+
     func displayNewChat(contactId: Int) {
         let chatId = dc_create_chat_by_contact_id(mailboxPointer, UInt32(contactId))
         let chatVC = ChatViewController(chatId: Int(chatId))
-        
+
         chatVC.hidesBottomBarWhenPushed = true
-        self.navigationController?.pushViewController(chatVC, animated: true)
+        navigationController?.pushViewController(chatVC, animated: true)
     }
-    
+
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
         // Dispose of any resources that can be recreated.
@@ -44,21 +44,21 @@ class ContactProfileViewController: UITableViewController {
 
     // MARK: - Table view data source
 
-    override func numberOfSections(in tableView: UITableView) -> Int {
+    override func numberOfSections(in _: UITableView) -> Int {
         return 1
     }
 
-    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+    override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
         if section == 0 {
             return 3
         }
-        
+
         return 0
     }
 
-    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
+    override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let row = indexPath.row
-        
+
         let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
 
         let settingsImage = #imageLiteral(resourceName: "baseline_settings_black_18pt").withRenderingMode(.alwaysTemplate)
@@ -78,11 +78,10 @@ class ContactProfileViewController: UITableViewController {
         }
         return cell
     }
-    
-    
-    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
+
+    override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
         let row = indexPath.row
-        
+
         if row == 1 {
             let alert = UIAlertController(title: "Not implemented", message: "Settings are not implemented yet.", preferredStyle: .alert)
             alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
@@ -96,13 +95,13 @@ class ContactProfileViewController: UITableViewController {
             displayNewChat(contactId: contactId)
         }
     }
-    
-    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
+
+    override func tableView(_: UITableView, heightForHeaderInSection _: Int) -> CGFloat {
         return 80
     }
-    
-    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
-        let bg = UIColor(red: 248/255, green: 248/255, blue: 255/255, alpha: 1.0)
+
+    override func tableView(_: UITableView, viewForHeaderInSection section: Int) -> UIView? {
+        let bg = UIColor(red: 248 / 255, green: 248 / 255, blue: 255 / 255, alpha: 1.0)
         if section == 0 {
             let contactCell = ContactCell()
             contactCell.backgroundColor = bg
@@ -115,13 +114,13 @@ class ContactProfileViewController: UITableViewController {
             } else {
                 contactCell.setBackupImage(name: contact.name, color: contact.color)
             }
-            
+
             return contactCell
         }
-        
+
         let vw = UIView()
         vw.backgroundColor = bg
-        
+
         return vw
     }
 }

+ 36 - 30
deltachat-ios/CredentialsController.swift

@@ -17,20 +17,19 @@ enum SecurityMode: String, CaseIterable {
 }
 
 typealias CredentialsModel = (
-    email:String,
-    password:String,
-    imapLoginName:String?,
-    imapServer:String?,
-    imapPort:String?,
-    imapSecurity:SecurityMode,
-    smtpLoginName:String?,
-    smtpPassword:String?,
-    smtpServer:String?,
-    smtpPort:String?,
-    smtpSecurity:SecurityMode
+    email: String,
+    password: String,
+    imapLoginName: String?,
+    imapServer: String?,
+    imapPort: String?,
+    imapSecurity: SecurityMode,
+    smtpLoginName: String?,
+    smtpPassword: String?,
+    smtpServer: String?,
+    smtpPort: String?,
+    smtpSecurity: SecurityMode
 )
 
-
 class CredentialsController: UITableViewController {
     let emailCell = TextFieldCell.makeEmailCell()
     let passwordCell = TextFieldCell.makePasswordCell()
@@ -46,8 +45,8 @@ class CredentialsController: UITableViewController {
     let smtpCellPort = TextFieldCell.makeConfigCell(label: "SMTP Port", placeholder: "Automatic")
     let smtpCellSecurity = UITableViewCell(style: UITableViewCell.CellStyle.value1, reuseIdentifier: nil)
 
-    var doneButton:UIBarButtonItem?
-    var advancedButton:UIBarButtonItem?
+    var doneButton: UIBarButtonItem?
+    var advancedButton: UIBarButtonItem?
     let progressBar = UIProgressView(progressViewStyle: .default)
 
     func readyForLogin() -> Bool {
@@ -64,7 +63,8 @@ class CredentialsController: UITableViewController {
             tableView.reloadData()
         }
     }
-    var model:CredentialsModel = ("", "", nil, nil, nil, SecurityMode.automatic, nil, nil, nil, nil, SecurityMode.automatic) {
+
+    var model: CredentialsModel = ("", "", nil, nil, nil, SecurityMode.automatic, nil, nil, nil, nil, SecurityMode.automatic) {
         didSet {
             if readyForLogin() {
                 doneButton?.isEnabled = true
@@ -73,14 +73,14 @@ class CredentialsController: UITableViewController {
             }
             smtpCellSecurity.detailTextLabel?.text = model.smtpSecurity.rawValue
             imapCellSecurity.detailTextLabel?.text = model.imapSecurity.rawValue
-            logger.info( "model: \(model)")
+            logger.info("model: \(model)")
         }
     }
 
-    let cells:[UITableViewCell]
-    let isCancellable:Bool
+    let cells: [UITableViewCell]
+    let isCancellable: Bool
 
-    init(isCancellable:Bool = false) {
+    init(isCancellable: Bool = false) {
         cells = [emailCell, passwordCell]
         self.isCancellable = isCancellable
 
@@ -119,7 +119,7 @@ class CredentialsController: UITableViewController {
         passwordCell.textField.returnKeyType = .done
     }
 
-    override func viewDidAppear(_ animated: Bool) {
+    override func viewDidAppear(_: Bool) {
         emailCell.textField.becomeFirstResponder()
     }
 
@@ -141,7 +141,7 @@ class CredentialsController: UITableViewController {
         advancedMode = !advancedMode
     }
 
-    required init?(coder aDecoder: NSCoder) {
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
 
@@ -152,11 +152,11 @@ class CredentialsController: UITableViewController {
         navigationController?.navigationBar.prefersLargeTitles = true
     }
 
-    override func numberOfSections(in tableView: UITableView) -> Int {
+    override func numberOfSections(in _: UITableView) -> Int {
         return advancedMode ? 3 : 1
     }
 
-    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+    override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
         if section == 0 {
             return cells.count
         }
@@ -169,7 +169,7 @@ class CredentialsController: UITableViewController {
         return 0 // should never happen
     }
 
-    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
+    override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
         if section == 1 {
             return "IMAP"
         }
@@ -196,19 +196,18 @@ class CredentialsController: UITableViewController {
                     }
                 }))
             }
-            actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {a in}))
+            actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in }))
 
             if let popoverController = actionSheet.popoverPresentationController {
                 if let cell = tableView.cellForRow(at: indexPath) {
                     popoverController.sourceView = cell.detailTextLabel
                 }
             }
-            self.present(actionSheet, animated: true, completion: {})
+            present(actionSheet, animated: true, completion: {})
         }
     }
 
-
-    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
+    override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let section = indexPath.section
         let row = indexPath.row
 
@@ -252,7 +251,6 @@ class CredentialsController: UITableViewController {
             }
         }
         return UITableViewCell()
-
     }
 
     override func didReceiveMemoryWarning() {
@@ -273,7 +271,7 @@ extension CredentialsController: UITextFieldDelegate {
         }
         if textField == passwordCell.textField {
             if readyForLogin() {
-                self.didPressSaveAccountButton()
+                didPressSaveAccountButton()
             }
         }
 
@@ -287,29 +285,37 @@ extension CredentialsController {
 
         model.email = emailText
     }
+
     @objc func passwordTextChanged() {
         let passwordText = passwordCell.textField.text ?? ""
 
         model.password = passwordText
     }
+
     @objc func imapLoginNameChanged() {
         model.imapLoginName = imapCellLoginName.textField.text
     }
+
     @objc func imapServerChanged() {
         model.imapServer = imapCellServer.textField.text
     }
+
     @objc func imapPortChanged() {
         model.imapPort = imapCellPort.textField.text
     }
+
     @objc func smtpLoginNamedChanged() {
         model.smtpLoginName = smtpCellLoginName.textField.text
     }
+
     @objc func smtpPasswordChanged() {
         model.smtpPassword = smtpCellPassword.textField.text
     }
+
     @objc func smtpServerChanged() {
         model.smtpServer = smtpCellServer.textField.text
     }
+
     @objc func smtpPortChanged() {
         model.smtpPort = smtpCellPort.textField.text
     }

+ 8 - 10
deltachat-ios/CustomCell.swift

@@ -1,4 +1,5 @@
 //
+import MessageKit
 //  CustomCell.swift
 //  deltachat-ios
 //
@@ -6,42 +7,39 @@
 //  Copyright © 2018 Jonas Reinsch. All rights reserved.
 //
 import UIKit
-import MessageKit
 
 open class CustomCell: UICollectionViewCell {
-    
     let label = UILabel()
-    
+
     public override init(frame: CGRect) {
         super.init(frame: frame)
         setupSubviews()
     }
-    
+
     public required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
         setupSubviews()
     }
-    
+
     open func setupSubviews() {
         contentView.addSubview(label)
         label.textAlignment = .center
         label.font = UIFont.italicSystemFont(ofSize: 13)
     }
-    
+
     open override func layoutSubviews() {
         super.layoutSubviews()
         label.frame = contentView.bounds
     }
-    
-    open func configure(with message: MessageType, at indexPath: IndexPath, and messagesCollectionView: MessagesCollectionView) {
+
+    open func configure(with message: MessageType, at _: IndexPath, and _: MessagesCollectionView) {
         // Do stuff
         switch message.kind {
-        case .custom(let data):
+        case let .custom(data):
             guard let systemMessage = data as? String else { return }
             label.text = systemMessage
         default:
             break
         }
     }
-    
 }

+ 6 - 7
deltachat-ios/Extensions/UIImage+Extension.swift

@@ -9,18 +9,17 @@
 import UIKit
 
 extension UIImage {
-    
-    func imageResize (sizeChange: CGSize)-> UIImage{
-        
+    func imageResize(sizeChange: CGSize) -> UIImage {
         let hasAlpha = true
         let scale: CGFloat = 0.0 // Use scale factor of main screen
-        
+
         UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
-        self.draw(in: CGRect(origin: CGPoint.zero, size: sizeChange))
-        
+        draw(in: CGRect(origin: CGPoint.zero, size: sizeChange))
+
         let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
         return scaledImage!
     }
+
     public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
         let rect = CGRect(origin: .zero, size: size)
         UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
@@ -28,7 +27,7 @@ extension UIImage {
         UIRectFill(rect)
         let image = UIGraphicsGetImageFromCurrentImageContext()
         UIGraphicsEndImageContext()
-    
+
         guard let cgImage = image?.cgImage else { return nil }
         self.init(cgImage: cgImage)
     }

+ 3 - 7
deltachat-ios/Extensions/UIViewController+Extension.swift

@@ -8,11 +8,8 @@
 
 import UIKit
 
-
 extension UIViewController {
-    
     func updateTitleView(title: String, subtitle: String?, baseColor: UIColor = .darkText) {
-        
         let titleLabel = UILabel(frame: CGRect(x: 0, y: -2, width: 0, height: 0))
         titleLabel.backgroundColor = UIColor.clear
         titleLabel.textColor = baseColor
@@ -21,7 +18,7 @@ extension UIViewController {
         titleLabel.textAlignment = .center
         titleLabel.adjustsFontSizeToFitWidth = true
         titleLabel.sizeToFit()
-        
+
         let subtitleLabel = UILabel(frame: CGRect(x: 0, y: 18, width: 0, height: 0))
         subtitleLabel.textColor = baseColor.withAlphaComponent(0.95)
         subtitleLabel.font = UIFont.systemFont(ofSize: 12)
@@ -29,7 +26,7 @@ extension UIViewController {
         subtitleLabel.textAlignment = .center
         subtitleLabel.adjustsFontSizeToFitWidth = true
         subtitleLabel.sizeToFit()
-        
+
         let titleView = UIView(frame: CGRect(x: 0, y: 0, width: max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 30))
         titleView.addSubview(titleLabel)
         if subtitle != nil {
@@ -45,8 +42,7 @@ extension UIViewController {
             let newX = widthDiff / 2
             titleLabel.frame.origin.x = newX
         }
-        
+
         navigationItem.titleView = titleView
     }
-    
 }

+ 16 - 22
deltachat-ios/GroupNameController.swift

@@ -9,30 +9,30 @@
 import UIKit
 
 class GroupNameController: UIViewController {
-    var doneButton:UIBarButtonItem!
+    var doneButton: UIBarButtonItem!
     let groupNameTextField = UITextField()
-    let contactIdsForGroup:Set<Int>
+    let contactIdsForGroup: Set<Int>
     var groupName = "" {
         didSet {
             if groupName.isEmpty {
-              logger.info( "empty")
+                logger.info("empty")
                 doneButton.isEnabled = false
             } else {
-              logger.info( "something")
+                logger.info("something")
                 doneButton.isEnabled = true
             }
         }
     }
-    
-    init(contactIdsForGroup:Set<Int>) {
+
+    init(contactIdsForGroup: Set<Int>) {
         self.contactIdsForGroup = contactIdsForGroup
         super.init(nibName: nil, bundle: nil)
     }
-    
-    required init?(coder aDecoder: NSCoder) {
+
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
+
     func layoutTextField() {
         groupNameTextField.translatesAutoresizingMaskIntoConstraints = false
         view.addSubview(groupNameTextField)
@@ -41,27 +41,27 @@ class GroupNameController: UIViewController {
         groupNameTextField.placeholder = "Group Name"
         groupNameTextField.becomeFirstResponder()
     }
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
         title = "Group Name"
         groupNameTextField.delegate = self
         layoutTextField()
-        
+
         doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(didPressDoneButton))
         navigationItem.rightBarButtonItem = doneButton
         doneButton.isEnabled = false
     }
-    
+
     @objc func didPressDoneButton() {
-      logger.info( "Done Button pressed")
+        logger.info("Done Button pressed")
         let groupChatId = dc_create_group_chat(mailboxPointer, 0, groupName)
         for contactId in contactIdsForGroup {
             let success = dc_add_contact_to_chat(mailboxPointer, groupChatId, UInt32(contactId))
             if success == 1 {
-              logger.info( "successfully added \(contactId) to group \(groupName)")
+                logger.info("successfully added \(contactId) to group \(groupName)")
             } else {
-                // FIXME
+                // FIXME:
                 fatalError("failed to add \(contactId) to group \(groupName)")
             }
         }
@@ -73,9 +73,6 @@ class GroupNameController: UIViewController {
                 navigationRoot.pushViewController(chatVC, animated: true)
             }
         }
-        
-        
-        
     }
 
     override func didReceiveMemoryWarning() {
@@ -88,10 +85,7 @@ extension GroupNameController: UITextFieldDelegate {
     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
         groupName = text
-        
+
         return true
     }
-    
-    
-    
 }

+ 16 - 19
deltachat-ios/Message.swift

@@ -6,29 +6,28 @@
 //  Copyright © 2017 Jonas Reinsch. All rights reserved.
 //
 
+import CoreLocation
 import Foundation
 import MessageKit
-import CoreLocation
 
 struct Location: LocationItem {
     var location: CLLocation
-    
+
     var size: CGSize
-    
+
     init(location: CLLocation, size: CGSize) {
         self.location = location
         self.size = size
     }
-    
 }
 
 struct Media: MediaItem {
-    var url: URL? = nil
-    
+    var url: URL?
+
     var image: UIImage?
-    
+
     var placeholderImage: UIImage = UIImage(named: "ic_attach_file_36pt")!
-    
+
     var size: CGSize {
         if let image = image {
             return image.size
@@ -36,7 +35,7 @@ struct Media: MediaItem {
             return placeholderImage.size
         }
     }
-    
+
     init(url: URL? = nil, image: UIImage? = nil) {
         self.url = url
         self.image = image
@@ -44,45 +43,43 @@ struct Media: MediaItem {
 }
 
 struct Message: MessageType {
-    
     var messageId: String
     var sender: Sender
     var sentDate: Date
     var kind: MessageKind
-    
+
     init(kind: MessageKind, sender: Sender, messageId: String, date: Date) {
         self.kind = kind
         self.sender = sender
         self.messageId = messageId
-        self.sentDate = date
+        sentDate = date
     }
-    
+
     init(text: String, sender: Sender, messageId: String, date: Date) {
         self.init(kind: .text(text), sender: sender, messageId: messageId, date: date)
     }
-    
+
     init(attributedText: NSAttributedString, sender: Sender, messageId: String, date: Date) {
         self.init(kind: .attributedText(attributedText), sender: sender, messageId: messageId, date: date)
     }
-    
+
     init(image: UIImage, sender: Sender, messageId: String, date: Date) {
         let media = Media(image: image)
         self.init(kind: .photo(media), sender: sender, messageId: messageId, date: date)
     }
-    
+
     init(thumbnail: UIImage, sender: Sender, messageId: String, date: Date) {
         let url = URL(fileURLWithPath: "")
         let media = Media(url: url, image: thumbnail)
         self.init(kind: .video(media), sender: sender, messageId: messageId, date: date)
     }
-    
+
     init(location: CLLocation, sender: Sender, messageId: String, date: Date) {
         let locationItem = Location(location: location, size: CGSize(width: 100, height: 50))
         self.init(kind: .location(locationItem), sender: sender, messageId: messageId, date: date)
     }
-    
+
     init(emoji: String, sender: Sender, messageId: String, date: Date) {
         self.init(kind: .emoji(emoji), sender: sender, messageId: messageId, date: date)
     }
-    
 }

+ 13 - 12
deltachat-ios/NavigationController.swift

@@ -10,30 +10,31 @@ import UIKit
 
 final class NavigationController: UINavigationController {
     var stateChangedObserver: Any?
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
-       
+
         if #available(iOS 11.0, *) {
             navigationBar.prefersLargeTitles = true
         } else {
             navigationBar.setBackgroundImage(UIImage(), for: .default)
         }
 
-        self.setShadow(nil)
-        
+        setShadow(nil)
+
         let nc = NotificationCenter.default
         stateChangedObserver = nc.addObserver(
             forName: dc_notificationStateChanged,
             object: nil,
-            queue: nil) {
-                notification in
-                if let state = notification.userInfo?["state"] {
-                    self.setShadow(state as? String)
-                }
+            queue: nil
+        ) {
+            notification in
+            if let state = notification.userInfo?["state"] {
+                self.setShadow(state as? String)
+            }
         }
     }
-    
+
     private func setShadow(_ state: String?) {
         switch state {
         case "offline":
@@ -44,10 +45,10 @@ final class NavigationController: UINavigationController {
             navigationBar.shadowImage = Constants.defaultShadow
         }
     }
-    
+
     override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
-        
+
         let nc = NotificationCenter.default
         if let stateChangedObserver = self.stateChangedObserver {
             nc.removeObserver(stateChangedObserver)

+ 23 - 24
deltachat-ios/NewChatViewController.swift

@@ -17,21 +17,21 @@ class NewChatViewController: UITableViewController {
     weak var chatDisplayer: ChatDisplayer?
 
     override func viewDidLoad() {
-        //super.viewDidLoad()
+        // super.viewDidLoad()
 
         title = "New Chat"
         navigationController?.navigationBar.prefersLargeTitles = true
-        
+
         let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(NewChatViewController.cancelButtonPressed))
-        
+
         navigationItem.rightBarButtonItem = cancelButton
     }
-    
-    override func viewDidAppear(_ animated: Bool) {
+
+    override func viewDidAppear(_: Bool) {
         contactIds = Utils.getContactIds()
         tableView.reloadData()
     }
-    
+
     @objc func cancelButtonPressed() {
         dismiss(animated: true, completion: nil)
     }
@@ -43,51 +43,50 @@ class NewChatViewController: UITableViewController {
 
     // MARK: - Table view data source
 
-    override func numberOfSections(in tableView: UITableView) -> Int {
+    override func numberOfSections(in _: UITableView) -> Int {
         return 1
     }
 
-    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
-        return self.contactIds.count + 2
+    override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
+        return contactIds.count + 2
     }
 
-
     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let row = indexPath.row
         if row == 0 {
             // new group row
-            let cell:UITableViewCell
+            let cell: UITableViewCell
             if let c = tableView.dequeueReusableCell(withIdentifier: "newContactCell") {
                 cell = c
             } else {
                 cell = UITableViewCell(style: .default, reuseIdentifier: "newContactCell")
             }
             cell.textLabel?.text = "New Group"
-            cell.textLabel?.textColor = self.view.tintColor
-            
+            cell.textLabel?.textColor = view.tintColor
+
             return cell
         }
         if row == 1 {
             // new contact row
-            let cell:UITableViewCell
+            let cell: UITableViewCell
             if let c = tableView.dequeueReusableCell(withIdentifier: "newContactCell") {
                 cell = c
             } else {
                 cell = UITableViewCell(style: .default, reuseIdentifier: "newContactCell")
             }
             cell.textLabel?.text = "New Contact"
-            cell.textLabel?.textColor = self.view.tintColor
-            
+            cell.textLabel?.textColor = view.tintColor
+
             return cell
         }
-        
-        let cell:ContactCell
+
+        let cell: ContactCell
         if let c = tableView.dequeueReusableCell(withIdentifier: "contactCell") as? ContactCell {
             cell = c
         } else {
             cell = ContactCell(style: .default, reuseIdentifier: "contactCell")
         }
-        
+
         let contactRow = row - 2
 
         let contact = MRContact(id: contactIds[contactRow])
@@ -95,12 +94,12 @@ class NewChatViewController: UITableViewController {
         cell.emailLabel.text = contact.email
         cell.initialsLabel.text = Utils.getInitials(inputName: contact.name)
         cell.setColor(contact.color)
-        
+
         cell.accessoryType = .detailDisclosureButton
         return cell
     }
-    
-    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
+
+    override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
         let row = indexPath.row
         if row == 0 {
             let newGroupController = NewGroupViewController()
@@ -118,8 +117,8 @@ class NewChatViewController: UITableViewController {
             }
         }
     }
-    
-    override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
+
+    override func tableView(_: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
         let row = indexPath.row
         if row > 1 {
             let contactIndex = row - 2

+ 34 - 35
deltachat-ios/NewContactController.swift

@@ -11,14 +11,14 @@ import UIKit
 class NewContactController: UITableViewController {
     let emailCell = TextFieldCell.makeEmailCell()
     let nameCell = TextFieldCell.makeNameCell()
-    var doneButton:UIBarButtonItem?
-    var cancelButton:UIBarButtonItem?
-    
+    var doneButton: UIBarButtonItem?
+    var cancelButton: UIBarButtonItem?
+
     func contactIsValid() -> Bool {
         return Utils.isValid(model.email)
     }
-    
-    var model:(name:String, email:String) = ("", "") {
+
+    var model: (name: String, email: String) = ("", "") {
         didSet {
             if contactIsValid() {
                 doneButton?.isEnabled = true
@@ -27,9 +27,9 @@ class NewContactController: UITableViewController {
             }
         }
     }
-    
-    let cells:[UITableViewCell]
-    
+
+    let cells: [UITableViewCell]
+
     // for editing existing contacts (only
     // the name may be edited, therefore disable
     // the email field)
@@ -42,7 +42,7 @@ class NewContactController: UITableViewController {
         emailCell.textField.text = contact.email
         emailCell.textField.isEnabled = false
         emailCell.contentView.alpha = 0.3
-        
+
         model.name = contact.name
         model.email = contact.email
 
@@ -50,86 +50,85 @@ class NewContactController: UITableViewController {
             doneButton?.isEnabled = true
         }
     }
-    
-    override func viewWillAppear(_ animated: Bool) {
+
+    override func viewWillAppear(_: Bool) {
         navigationController?.setNavigationBarHidden(false, animated: false)
     }
-    
+
     // for creating a new contact
     init() {
         cells = [emailCell, nameCell]
         super.init(style: .grouped)
         emailCell.textField.delegate = self
         nameCell.textField.delegate = self
-        
-        
+
         // always show return key with name field, because
         // name is optional
         nameCell.textField.enablesReturnKeyAutomatically = false
         emailCell.textField.returnKeyType = .next
         nameCell.textField.returnKeyType = .done
-        
+
         title = "New Contact"
         doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(NewContactController.saveContactButtonPressed))
         doneButton?.isEnabled = false
         navigationItem.rightBarButtonItem = doneButton
-        
+
         cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(NewContactController.cancelButtonPressed))
         navigationItem.leftBarButtonItem = cancelButton
 
         emailCell.textField.addTarget(self, action: #selector(NewContactController.emailTextChanged), for: UIControl.Event.editingChanged)
         nameCell.textField.addTarget(self, action: #selector(NewContactController.nameTextChanged), for: UIControl.Event.editingChanged)
     }
-    
-    override func viewDidAppear(_ animated: Bool) {
+
+    override func viewDidAppear(_: Bool) {
         if emailCell.textField.isEnabled {
             emailCell.textField.becomeFirstResponder()
         } else {
             nameCell.textField.becomeFirstResponder()
         }
     }
-    
+
     @objc func emailTextChanged() {
         let emailText = emailCell.textField.text ?? ""
-        
+
         model.email = emailText
     }
-                
+
     @objc func nameTextChanged() {
         let nameText = nameCell.textField.text ?? ""
-        
+
         model.name = nameText
     }
-    
+
     @objc func saveContactButtonPressed() {
-        dc_create_contact(mailboxPointer, self.model.name, self.model.email)
+        dc_create_contact(mailboxPointer, model.name, model.email)
         navigationController?.popViewController(animated: true)
     }
-    
+
     @objc func cancelButtonPressed() {
         navigationController?.popViewController(animated: true)
     }
-    
-    required init?(coder aDecoder: NSCoder) {
+
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
-        
+
         navigationController?.navigationBar.prefersLargeTitles = true
     }
-    
-    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+
+    override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
         return cells.count
     }
-    
-    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
+
+    override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let row = indexPath.row
-        
+
         return cells[row]
     }
-    
+
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
         // Dispose of any resources that can be recreated.

+ 21 - 28
deltachat-ios/NewGroupMemberChoiceController.swift

@@ -11,18 +11,18 @@ import UIKit
 class ViewController: UIViewController {
     override func viewDidLoad() {
         super.viewDidLoad()
-        
-        let n:CGFloat = 150
-        let l:CGFloat = 40
+
+        let n: CGFloat = 150
+        let l: CGFloat = 40
         let generalView = UIView()
         let square = UIView()
-        square.layer.cornerRadius = n/2
+        square.layer.cornerRadius = n / 2
         let nameLabel = UILabel()
         nameLabel.text = "Alic Doe"
         square.translatesAutoresizingMaskIntoConstraints = false
         nameLabel.translatesAutoresizingMaskIntoConstraints = false
         generalView.translatesAutoresizingMaskIntoConstraints = false
-        
+
         view.addSubview(generalView)
         view.addSubview(square)
         view.addSubview(nameLabel)
@@ -32,7 +32,7 @@ class ViewController: UIViewController {
         square.centerYAnchor.constraint(equalTo: generalView.centerYAnchor).isActive = true
         nameLabel.topAnchor.constraint(equalTo: square.bottomAnchor).isActive = true
         nameLabel.leadingAnchor.constraint(equalTo: square.leadingAnchor).isActive = true
-        
+
         square.widthAnchor.constraint(equalToConstant: n).isActive = true
         square.heightAnchor.constraint(equalToConstant: n).isActive = true
         nameLabel.widthAnchor.constraint(equalToConstant: n).isActive = true
@@ -44,35 +44,35 @@ class ViewController: UIViewController {
         generalView.backgroundColor = UIColor.cyan
         nameLabel.textColor = UIColor.white
         nameLabel.font = UIFont.systemFont(ofSize: 14)
-        
+
         let deleteButton = UIButton()
         deleteButton.translatesAutoresizingMaskIntoConstraints = false
-        
-        let sin45:CGFloat = 0.7071
-        let squareRadius:CGFloat = n/2
-        let deltaX:CGFloat = sin45 * squareRadius
-        let deltaY:CGFloat = squareRadius - deltaX
-        let deleteButtonWidth:CGFloat = deltaX
-        let deleteButtonHeight:CGFloat = deltaX
-        deleteButton.layer.cornerRadius = deleteButtonWidth/2
-        
+
+        let sin45: CGFloat = 0.7071
+        let squareRadius: CGFloat = n / 2
+        let deltaX: CGFloat = sin45 * squareRadius
+        let deltaY: CGFloat = squareRadius - deltaX
+        let deleteButtonWidth: CGFloat = deltaX
+        let deleteButtonHeight: CGFloat = deltaX
+        deleteButton.layer.cornerRadius = deleteButtonWidth / 2
+
         deleteButton.widthAnchor.constraint(equalToConstant: deleteButtonWidth).isActive = true
         deleteButton.heightAnchor.constraint(equalToConstant: deleteButtonHeight).isActive = true
         deleteButton.backgroundColor = UIColor.gray
         deleteButton.clipsToBounds = true
-        
+
         deleteButton.layer.borderWidth = 3
         deleteButton.layer.borderColor = UIColor.white.cgColor
         deleteButton.setTitle("✕", for: .normal)
         deleteButton.titleLabel?.font = UIFont.systemFont(ofSize: 30)
-        
+
         deleteButton.addTarget(self, action: #selector(didPressDeleteButton), for: .touchUpInside)
-        
+
         square.addSubview(deleteButton)
         deleteButton.centerYAnchor.constraint(equalTo: square.topAnchor, constant: deltaY).isActive = true
         deleteButton.centerXAnchor.constraint(equalTo: square.centerXAnchor, constant: deltaX).isActive = true
     }
-    
+
     @objc func didPressDeleteButton() {
         if view.backgroundColor == UIColor.red {
             view.backgroundColor = UIColor.white
@@ -80,15 +80,8 @@ class ViewController: UIViewController {
             view.backgroundColor = UIColor.red
         }
     }
-    
+
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
     }
 }
-
-
-
-
-
-
-

+ 11 - 17
deltachat-ios/NewGroupViewController.swift

@@ -9,49 +9,46 @@
 import UIKit
 
 class NewGroupViewController: UITableViewController {
-
     let contactCellReuseIdentifier = "xyz"
     var contactIds: [Int] = Utils.getContactIds()
     var contactIdsForGroup: Set<Int> = [] {
         didSet {
             let c = contactIdsForGroup.count
-            self.navigationItem.prompt = "\(c) members and me"
+            navigationItem.prompt = "\(c) members and me"
         }
     }
-    
+
     @objc func didPressGroupCreationNextButton() {
         navigationController?.pushViewController(GroupNameController(contactIdsForGroup: contactIdsForGroup), animated: true)
     }
+
     override func viewDidLoad() {
         super.viewDidLoad()
-        self.title = "New Group"
-        self.navigationItem.prompt = "0 members and me"
+        title = "New Group"
+        navigationItem.prompt = "0 members and me"
         tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
         navigationController?.navigationBar.prefersLargeTitles = false
         let groupCreationNextButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(didPressGroupCreationNextButton))
         navigationItem.rightBarButtonItem = groupCreationNextButton
     }
 
-
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
     }
 
-
-    override func numberOfSections(in tableView: UITableView) -> Int {
+    override func numberOfSections(in _: UITableView) -> Int {
         return 1
     }
 
-    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+    override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
         return contactIds.count
     }
 
-  
     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
-        guard let cell:ContactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell else {
+        guard let cell: ContactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell else {
             fatalError("shouldn't happen")
         }
-        
+
         let row = indexPath.row
         let contactRow = row
 
@@ -60,10 +57,10 @@ class NewGroupViewController: UITableViewController {
         cell.emailLabel.text = contact.email
         cell.initialsLabel.text = Utils.getInitials(inputName: contact.name)
         cell.setColor(contact.color)
-        
+
         return cell
     }
-    
+
     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         let row = indexPath.row
         if let cell = tableView.cellForRow(at: indexPath) {
@@ -77,8 +74,5 @@ class NewGroupViewController: UITableViewController {
                 cell.accessoryType = .checkmark
             }
         }
-            
     }
- 
-
 }

+ 13 - 13
deltachat-ios/QrCodeView.swift

@@ -10,41 +10,41 @@ import UIKit
 class QRCodeView: UIView {
     lazy var filter = CIFilter(name: "CIQRCodeGenerator")
     lazy var imageView = UIImageView()
-    
+
     override init(frame: CGRect) {
         super.init(frame: frame)
         addSubview(imageView)
     }
-    
-    required init?(coder aDecoder: NSCoder) {
+
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
+
     override func layoutSubviews() {
         super.layoutSubviews()
         imageView.frame = bounds
     }
-    
+
     func generateCode(_ string: String, foregroundColor: UIColor = .black, backgroundColor: UIColor = .white) {
         guard let filter = filter,
             let data = string.data(using: .isoLatin1, allowLossyConversion: false) else {
-                return
+            return
         }
-        
+
         filter.setValue(data, forKey: "inputMessage")
-        
+
         guard let ciImage = filter.outputImage else {
             return
         }
-        
-        let transformed = ciImage.transformed(by: CGAffineTransform.init(scaleX: 10, y: 10))
+
+        let transformed = ciImage.transformed(by: CGAffineTransform(scaleX: 10, y: 10))
         let invertFilter = CIFilter(name: "CIColorInvert")
         invertFilter?.setValue(transformed, forKey: kCIInputImageKey)
-        
+
         let alphaFilter = CIFilter(name: "CIMaskToAlpha")
         alphaFilter?.setValue(invertFilter?.outputImage, forKey: kCIInputImageKey)
-        
-        if let outputImage = alphaFilter?.outputImage  {
+
+        if let outputImage = alphaFilter?.outputImage {
             imageView.tintColor = foregroundColor
             imageView.backgroundColor = backgroundColor
             imageView.image = UIImage(ciImage: outputImage, scale: 2.0, orientation: .up)

+ 13 - 14
deltachat-ios/TableViewCell.swift

@@ -9,38 +9,37 @@
 import UIKit
 
 internal class TextFieldTableViewCell: UITableViewCell {
-    
     static let identifier = "TextFieldTableViewCellIdentifier"
-    
+
     var mainLabel = UILabel()
     var textField = UITextField()
-    
+
     // MARK: - View lifecycle
-    
+
     override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
         super.init(style: style, reuseIdentifier: reuseIdentifier)
-        
+
         mainLabel.translatesAutoresizingMaskIntoConstraints = false
         textField.translatesAutoresizingMaskIntoConstraints = false
-        
+
         contentView.addSubview(mainLabel)
         contentView.addSubview(textField)
-        
+
         NSLayoutConstraint.activate([
             mainLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
             mainLabel.widthAnchor.constraint(equalToConstant: 200),
             mainLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
-            
+
             textField.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
-            
+
             textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20),
-            textField.widthAnchor.constraint(equalToConstant: 50)
-            ])
-        
+            textField.widthAnchor.constraint(equalToConstant: 50),
+        ])
+
         textField.textAlignment = .right
     }
-    
-    required init?(coder aDecoder: NSCoder) {
+
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
 }

+ 24 - 25
deltachat-ios/TextFieldCell.swift

@@ -8,17 +8,17 @@
 
 import UIKit
 
-class TextFieldCell:UITableViewCell {
+class TextFieldCell: UITableViewCell {
     let textField = UITextField()
-    
+
     init(description: String, placeholder: String) {
         super.init(style: .value1, reuseIdentifier: nil)
-        
+
         textLabel?.text = "\(description):"
         contentView.addSubview(textField)
-        
+
         textField.translatesAutoresizingMaskIntoConstraints = false
-        
+
         // see: https://stackoverflow.com/a/35903650
         // this makes the textField respect the trailing margin of
         // the table view cell
@@ -27,68 +27,67 @@ class TextFieldCell:UITableViewCell {
         textField.trailingAnchor.constraint(equalTo: trailing).isActive = true
         textField.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
         textField.textAlignment = .right
-        
+
         textField.placeholder = placeholder
-        
+
         selectionStyle = .none
-        
+
         textField.enablesReturnKeyAutomatically = true
     }
-    
-    
-    override func setSelected(_ selected: Bool, animated: Bool) {
+
+    override func setSelected(_ selected: Bool, animated _: Bool) {
         if selected {
             textField.becomeFirstResponder()
         }
     }
-    
-    required init?(coder aDecoder: NSCoder) {
+
+    required init?(coder _: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
-    
+
     static func makeEmailCell() -> TextFieldCell {
         let emailCell = TextFieldCell(description: "Email", placeholder: "you@example.com")
-        
+
         emailCell.textField.keyboardType = .emailAddress
         // switch off quicktype
         emailCell.textField.autocorrectionType = .no
         emailCell.textField.autocapitalizationType = .none
-        
+
         return emailCell
     }
-    
+
     static func makePasswordCell() -> TextFieldCell {
         let passwordCell = TextFieldCell(description: "Password", placeholder: "your IMAP password")
-        
+
         passwordCell.textField.textContentType = UITextContentType.password
         passwordCell.textField.isSecureTextEntry = true
-        
+
         return passwordCell
     }
-    
+
     static func makeNameCell() -> TextFieldCell {
         let nameCell = TextFieldCell(description: "Name", placeholder: "new contacts nickname")
-        
+
         nameCell.textField.autocapitalizationType = .words
         nameCell.textField.autocorrectionType = .no
         // .namePhonePad doesn't support autocapitalization
         // see: https://stackoverflow.com/a/36365399
         // therefore we use .default to capitalize the first character of the name
         nameCell.textField.keyboardType = .default
-        
+
         return nameCell
     }
-    
+
     static func makeConfigCell(label: String, placeholder: String) -> TextFieldCell {
         let nameCell = TextFieldCell(description: label, placeholder: placeholder)
-        
+
         nameCell.textField.autocapitalizationType = .words
         nameCell.textField.autocorrectionType = .no
         // .namePhonePad doesn't support autocapitalization
         // see: https://stackoverflow.com/a/36365399
         // therefore we use .default to capitalize the first character of the name
         nameCell.textField.keyboardType = .default
-        
+
         return nameCell
     }
 }

+ 45 - 52
deltachat-ios/TopViews/ChatListController.swift

@@ -8,67 +8,66 @@
 
 import UIKit
 
-
 class ChatListController: UIViewController {
-    var chatList:MRChatList?
+    var chatList: MRChatList?
 
     let chatTable = UITableView()
-    
+
     let chatTableDataSource = ChatTableDataSource()
     let chatTableDelegate = ChatTableDelegate()
 
     var msgChangedObserver: Any?
     var incomingMsgObserver: Any?
-    
+
     var newButton: UIBarButtonItem!
-    
+
     func getChatList() {
         guard let chatlistPointer = dc_get_chatlist(mailboxPointer, DC_GCL_NO_SPECIALS, nil, 0) else {
             fatalError("chatlistPointer was nil")
         }
         // ownership of chatlistPointer transferred here to ChatList object
-        self.chatList = MRChatList(chatListPointer: chatlistPointer)
-        
-        chatTableDataSource.chatList = self.chatList
+        chatList = MRChatList(chatListPointer: chatlistPointer)
+
+        chatTableDataSource.chatList = chatList
         chatTable.reloadData()
     }
-    
+
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
-        
+
         if #available(iOS 11.0, *) {
             navigationController?.navigationBar.prefersLargeTitles = true
         }
-        
+
         getChatList()
     }
-    
+
     override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
         if #available(iOS 11.0, *) {
             navigationController?.navigationBar.prefersLargeTitles = false
         }
     }
-    
+
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
         let nc = NotificationCenter.default
-        msgChangedObserver = nc.addObserver(forName:dc_notificationChanged,
-                                            object:nil, queue:nil) {
-                                                notification in
-                                                self.getChatList()
+        msgChangedObserver = nc.addObserver(forName: dc_notificationChanged,
+                                            object: nil, queue: nil) {
+            _ in
+            self.getChatList()
         }
-        
-        incomingMsgObserver = nc.addObserver(forName:dc_notificationIncoming,
-                                             object:nil, queue:nil) {
-                                                notification in
-                                                self.getChatList()
+
+        incomingMsgObserver = nc.addObserver(forName: dc_notificationIncoming,
+                                             object: nil, queue: nil) {
+            _ in
+            self.getChatList()
         }
     }
-    
+
     override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
-        
+
         let nc = NotificationCenter.default
         if let msgChangedObserver = self.msgChangedObserver {
             nc.removeObserver(msgChangedObserver)
@@ -77,7 +76,7 @@ class ChatListController: UIViewController {
             nc.removeObserver(incomingMsgObserver)
         }
     }
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
         title = "Chats"
@@ -91,17 +90,16 @@ class ChatListController: UIViewController {
         chatTable.dataSource = chatTableDataSource
         chatTableDelegate.chatPresenter = self
         chatTable.delegate = chatTableDelegate
-        
+
         chatTable.rowHeight = 80
-        
+
         let newImage = UIImage(named: "create_new")!
         newButton = UIBarButtonItem(image: newImage, landscapeImagePhone: nil, style: .plain, target: self, action: #selector(didPressNewChat))
-    
+
         newButton.tintColor = Constants.primaryColor
         navigationItem.rightBarButtonItem = newButton
     }
-    
-    
+
     @objc func didPressNewChat() {
         let ncv = NewChatViewController()
         ncv.chatDisplayer = self
@@ -111,18 +109,16 @@ class ChatListController: UIViewController {
 }
 
 extension ChatListController: ChatPresenter {
-
     func displayChat(index: Int) {
         guard let chatList = self.chatList else {
             fatalError("chatList was nil in ChatPresenter extension")
         }
-        
+
         let chatId = chatList.getChatId(index: index)
         let chatVC = ChatViewController(chatId: chatId)
-        
 
-        chatVC.hidesBottomBarWhenPushed = true 
-        self.navigationController?.pushViewController(chatVC, animated: true)
+        chatVC.hidesBottomBarWhenPushed = true
+        navigationController?.pushViewController(chatVC, animated: true)
     }
 }
 
@@ -130,32 +126,30 @@ extension ChatListController: ChatDisplayer {
     func displayNewChat(contactId: Int) {
         let chatId = dc_create_chat_by_contact_id(mailboxPointer, UInt32(contactId))
         let chatVC = ChatViewController(chatId: Int(chatId))
-        
+
         chatVC.hidesBottomBarWhenPushed = true
-        self.navigationController?.pushViewController(chatVC, animated: true)
+        navigationController?.pushViewController(chatVC, animated: true)
     }
-    
 }
 
+class ChatTableDataSource: NSObject, UITableViewDataSource {
+    weak var chatList: MRChatList?
 
-class ChatTableDataSource: NSObject, UITableViewDataSource  {
-    weak var chatList:MRChatList?
-    
-    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+    func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
         guard let chatList = self.chatList else {
             fatalError("chatList was nil in data source")
         }
 
         return chatList.length
     }
-    
+
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let row = indexPath.row
         guard let chatList = self.chatList else {
             fatalError("chatList was nil in data source")
         }
-        
-        let cell:ContactCell
+
+        let cell: ContactCell
         if let c = tableView.dequeueReusableCell(withIdentifier: "ChatCell") as? ContactCell {
             cell = c
         } else {
@@ -165,7 +159,7 @@ class ChatTableDataSource: NSObject, UITableViewDataSource  {
         let chatId = chatList.getChatId(index: row)
         let chat = MRChat(id: chatId)
         let summary = chatList.summary(index: row)
-        
+
         cell.nameLabel.text = chat.name
         if let img = chat.profileImage {
             cell.setImage(img)
@@ -175,13 +169,13 @@ class ChatTableDataSource: NSObject, UITableViewDataSource  {
 
         let result1 = summary.text1 ?? ""
         let result2 = summary.text2 ?? ""
-        let result:String
-        if !result1.isEmpty && !result2.isEmpty {
+        let result: String
+        if !result1.isEmpty, !result2.isEmpty {
             result = "\(result1): \(result2)"
         } else {
             result = "\(result1)\(result2)"
         }
-        
+
         cell.emailLabel.text = result
         return cell
     }
@@ -192,10 +186,9 @@ protocol ChatPresenter: class {
 }
 
 class ChatTableDelegate: NSObject, UITableViewDelegate {
-    
     weak var chatPresenter: ChatPresenter?
-    
-    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
+
+    func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
         let row = indexPath.row
         chatPresenter?.displayChat(index: row)
     }

+ 17 - 19
deltachat-ios/TopViews/ContactListController.swift

@@ -9,37 +9,35 @@
 import UIKit
 
 class ContactListController: UITableViewController {
-
     let contactCellReuseIdentifier = "xyz"
     var contactIds: [Int] = Utils.getContactIds()
     var contactIdsForGroup: Set<Int> = []
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
-        self.title = "Contacts"
+        title = "Contacts"
         navigationController?.navigationBar.prefersLargeTitles = true
-        
+
         contactIds = Utils.getContactIds()
-        
+
         tableView.rowHeight = 80
         tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
     }
-    
-    
+
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
     }
-    
-    override func numberOfSections(in tableView: UITableView) -> Int {
+
+    override func numberOfSections(in _: UITableView) -> Int {
         return 1
     }
-    
-    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+
+    override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
         return contactIds.count
     }
-    
+
     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
-        let cell:ContactCell
+        let cell: ContactCell
         if let c = tableView.dequeueReusableCell(withIdentifier: "ChatCell") as? ContactCell {
             cell = c
         } else {
@@ -47,24 +45,24 @@ class ContactListController: UITableViewController {
         }
         let row = indexPath.row
         let contactRow = row
-        
+
         let contact = MRContact(id: contactIds[contactRow])
         cell.nameLabel.text = contact.name
         cell.emailLabel.text = contact.email
-        
+
         // TODO: provider a nice selection
         cell.selectionStyle = .none
-        
+
         if let img = contact.profileImage {
             cell.setImage(img)
         } else {
             cell.setBackupImage(name: contact.name, color: contact.color)
         }
-        
+
         return cell
     }
-    
-    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
+
+    override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
         let contactId = contactIds[indexPath.row]
         let contactProfileController = ContactProfileViewController(contactId: contactId)
         navigationController?.pushViewController(contactProfileController, animated: true)

+ 119 - 120
deltachat-ios/TopViews/ProfileViewController.swift

@@ -9,140 +9,139 @@
 import UIKit
 
 class ProfileViewController: UITableViewController {
-        var contact: MRContact {
-            return MRContact(id: Int(DC_CONTACT_ID_SELF))
-        }
-    
-        init() {
-            super.init(style: .plain)
-        }
-    
-        required init?(coder aDecoder: NSCoder) {
-            fatalError("init(coder:) has not been implemented")
-        }
-    
-        override func viewDidLoad() {
-            super.viewDidLoad()
-            title = "My Profile"
-        }
-    
-        override func viewWillAppear(_ animated: Bool) {
-            navigationController?.navigationBar.prefersLargeTitles = false
-            tableView.reloadData()
-        }
-        
-        func displayNewChat(contactId: Int) {
-            let chatId = dc_create_chat_by_contact_id(mailboxPointer, UInt32(contactId))
-            let chatVC = ChatViewController(chatId: Int(chatId))
-            
-            chatVC.hidesBottomBarWhenPushed = true
-            self.navigationController?.pushViewController(chatVC, animated: true)
+    var contact: MRContact {
+        return MRContact(id: Int(DC_CONTACT_ID_SELF))
+    }
+
+    init() {
+        super.init(style: .plain)
+    }
+
+    required init?(coder _: NSCoder) {
+        fatalError("init(coder:) has not been implemented")
+    }
+
+    override func viewDidLoad() {
+        super.viewDidLoad()
+        title = "My Profile"
+    }
+
+    override func viewWillAppear(_: Bool) {
+        navigationController?.navigationBar.prefersLargeTitles = false
+        tableView.reloadData()
+    }
+
+    func displayNewChat(contactId: Int) {
+        let chatId = dc_create_chat_by_contact_id(mailboxPointer, UInt32(contactId))
+        let chatVC = ChatViewController(chatId: Int(chatId))
+
+        chatVC.hidesBottomBarWhenPushed = true
+        navigationController?.pushViewController(chatVC, animated: true)
+    }
+
+    override func didReceiveMemoryWarning() {
+        super.didReceiveMemoryWarning()
+        // Dispose of any resources that can be recreated.
+    }
+
+    // MARK: - Table view data source
+
+    override func numberOfSections(in _: UITableView) -> Int {
+        return 1
+    }
+
+    override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
+        if section == 0 {
+            return 4
         }
-        
-        override func didReceiveMemoryWarning() {
-            super.didReceiveMemoryWarning()
-            // Dispose of any resources that can be recreated.
+
+        return 0
+    }
+
+    override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
+        let row = indexPath.row
+
+        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
+
+        let settingsImage = #imageLiteral(resourceName: "baseline_settings_black_18pt").withRenderingMode(.alwaysTemplate)
+        cell.imageView?.image = settingsImage
+        cell.imageView?.tintColor = UIColor.clear
+
+        if row == 0 {
+            cell.textLabel?.text = "Settings"
+            cell.imageView?.tintColor = UIColor.gray
         }
-        
-        // MARK: - Table view data source
-        
-        override func numberOfSections(in tableView: UITableView) -> Int {
-            return 1
+        if row == 1 {
+            cell.textLabel?.text = "Edit name"
         }
-        
-        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
-            if section == 0 {
-                return 4
-            }
-            
-            return 0
+
+        if row == 2 {
+            cell.textLabel?.text = "New chat"
         }
-        
-        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
-            let row = indexPath.row
-            
-            let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
-            
-            let settingsImage = #imageLiteral(resourceName: "baseline_settings_black_18pt").withRenderingMode(.alwaysTemplate)
-            cell.imageView?.image = settingsImage
-            cell.imageView?.tintColor = UIColor.clear
-            
-            if row == 0 {
-                cell.textLabel?.text = "Settings"
-                cell.imageView?.tintColor = UIColor.gray
-            }
-            if row == 1 {
-                cell.textLabel?.text = "Edit name"
-            }
-            
-            if row == 2 {
-                cell.textLabel?.text = "New chat"
-            }
-            
-            if row == 3 {
-                if let fingerprint = dc_get_securejoin_qr(mailboxPointer, 0) {
-                    let textView = UITextView()
-                    textView.text = "Fingerprint: \(fingerprint)"
-                    textView.heightAnchor.constraint(equalToConstant: 20).isActive = true
-                    cell.addSubview(textView)
-                    
-                    let frame = CGRect(origin: .zero, size: .init(width: 100, height: 100))
-                    let imageView = QRCodeView(frame: frame)
-                    imageView.generateCode(
-                        String(cString: fingerprint),
-                        foregroundColor: .darkText,
-                        backgroundColor: .white
+
+        if row == 3 {
+            if let fingerprint = dc_get_securejoin_qr(mailboxPointer, 0) {
+                let textView = UITextView()
+                textView.text = "Fingerprint: \(fingerprint)"
+                textView.heightAnchor.constraint(equalToConstant: 20).isActive = true
+                cell.addSubview(textView)
+
+                let frame = CGRect(origin: .zero, size: .init(width: 100, height: 100))
+                let imageView = QRCodeView(frame: frame)
+                imageView.generateCode(
+                    String(cString: fingerprint),
+                    foregroundColor: .darkText,
+                    backgroundColor: .white
+                )
+
+                cell.addSubview(imageView)
+                let viewsDictionary = ["textView": textView, "imageView": imageView]
+                cell.addConstraints(
+                    NSLayoutConstraint.constraints(
+                        withVisualFormat: "V:|[textView]-5-[imageView]|", metrics: nil, views: viewsDictionary
                     )
-                    
-                    cell.addSubview(imageView)
-                    let viewsDictionary = ["textView": textView, "imageView": imageView]
-                    cell.addConstraints(
-                        NSLayoutConstraint.constraints(
-                            withVisualFormat: "V:|[textView]-5-[imageView]|", metrics: nil, views: viewsDictionary))
-                }
+                )
             }
-            
-            return cell
         }
-        
-        
-        override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 
-        }
-        
-        override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
-            return 80
-        }
+        return cell
+    }
+
+    override func tableView(_: UITableView, didSelectRowAt _: IndexPath) {}
+
+    override func tableView(_: UITableView, heightForHeaderInSection _: Int) -> CGFloat {
+        return 80
+    }
 
-    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
+    override func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         if indexPath.row == 3 {
             return 200
         }
-        
+
         return 46
     }
-        
-        override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
-            let bg = UIColor(red: 248/255, green: 248/255, blue: 255/255, alpha: 1.0)
-            if section == 0 {
-                let contactCell = ContactCell()
-                contactCell.backgroundColor = bg
-                contactCell.nameLabel.text = contact.name
-                contactCell.emailLabel.text = contact.email
-                contactCell.darkMode = false
-                contactCell.selectionStyle = .none
-                if let img = contact.profileImage {
-                    contactCell.setImage(img)
-                } else {
-                    contactCell.setBackupImage(name: contact.name, color: contact.color)
-                }
-                
-                return contactCell
+
+    override func tableView(_: UITableView, viewForHeaderInSection section: Int) -> UIView? {
+        let bg = UIColor(red: 248 / 255, green: 248 / 255, blue: 255 / 255, alpha: 1.0)
+        if section == 0 {
+            let contactCell = ContactCell()
+            contactCell.backgroundColor = bg
+            contactCell.nameLabel.text = contact.name
+            contactCell.emailLabel.text = contact.email
+            contactCell.darkMode = false
+            contactCell.selectionStyle = .none
+            if let img = contact.profileImage {
+                contactCell.setImage(img)
+            } else {
+                contactCell.setBackupImage(name: contact.name, color: contact.color)
             }
-            
-            let vw = UIView()
-            vw.backgroundColor = bg
-            
-            return vw
+
+            return contactCell
         }
+
+        let vw = UIView()
+        vw.backgroundColor = bg
+
+        return vw
+    }
 }

+ 128 - 118
deltachat-ios/TopViews/SettingsController.swift

@@ -6,18 +6,18 @@
 //  Copyright © 2018 Jonas Reinsch. All rights reserved.
 //
 
-import UIKit
-import MessageKit
+import JGProgressHUD
 import MessageInputBar
+import MessageKit
 import QuickTableViewController
-import JGProgressHUD
+import UIKit
 
-final internal class SettingsViewController: QuickTableViewController {
+internal final class SettingsViewController: QuickTableViewController {
     let documentInteractionController = UIDocumentInteractionController()
     var backupProgressObserver: Any?
     var configureProgressObserver: Any?
     var backupHud: JGProgressHUD?
-  
+
     // MARK: - View lifecycle
 
     override func viewDidLoad() {
@@ -25,81 +25,86 @@ final internal class SettingsViewController: QuickTableViewController {
         title = "Settings"
 
         documentInteractionController.delegate = self as? UIDocumentInteractionControllerDelegate
-        
-        
+
         setTable()
     }
+
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
         let nc = NotificationCenter.default
         backupProgressObserver = nc.addObserver(
             forName: dc_notificationBackupProgress,
             object: nil,
-            queue: nil) {
-                notification in
-                if let ui = notification.userInfo {
-                    if ui["error"] as! Bool {
-                        self.setHudError(ui["errorMessage"] as? String)
-                    } else if ui["done"] as! Bool {
-                        self.setHudDone()
-                    } else {
-                        self.setHudProgress(ui["progress"] as! Int)
-                    }
+            queue: nil
+        ) {
+            notification in
+            if let ui = notification.userInfo {
+                if ui["error"] as! Bool {
+                    self.setHudError(ui["errorMessage"] as? String)
+                } else if ui["done"] as! Bool {
+                    self.setHudDone()
+                } else {
+                    self.setHudProgress(ui["progress"] as! Int)
                 }
             }
+        }
         configureProgressObserver = nc.addObserver(
             forName: dc_notificationConfigureProgress,
             object: nil,
-            queue: nil) {
-                notification in
-                if let ui = notification.userInfo {
-                    if ui["error"] as! Bool {
-                        self.setHudError(ui["errorMessage"] as? String)
-                    } else if ui["done"] as! Bool {
-                        self.setHudDone()
-                    } else {
-                        self.setHudProgress(ui["progress"] as! Int)
-                    }
+            queue: nil
+        ) {
+            notification in
+            if let ui = notification.userInfo {
+                if ui["error"] as! Bool {
+                    self.setHudError(ui["errorMessage"] as? String)
+                } else if ui["done"] as! Bool {
+                    self.setHudDone()
+                } else {
+                    self.setHudProgress(ui["progress"] as! Int)
                 }
+            }
         }
-        
     }
 
     private func setHudError(_ message: String?) {
         if let hud = self.backupHud {
             DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
-                UIView.animate(withDuration: 0.1, animations: {
-                    hud.textLabel.text = message ?? "Error"
-                    hud.detailTextLabel.text = nil
-                    hud.indicatorView = JGProgressHUDErrorIndicatorView()
-                })
-                
+                UIView.animate(
+                    withDuration: 0.1, animations: {
+                        hud.textLabel.text = message ?? "Error"
+                        hud.detailTextLabel.text = nil
+                        hud.indicatorView = JGProgressHUDErrorIndicatorView()
+                    }
+                )
+
                 hud.dismiss(afterDelay: 1.0)
             }
         }
     }
-    
+
     private func setHudDone() {
         if let hud = self.backupHud {
             DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
-                UIView.animate(withDuration: 0.1, animations: {
-                    hud.textLabel.text = "Success"
-                    hud.detailTextLabel.text = nil
+                UIView.animate(
+                    withDuration: 0.1, animations: {
+                        hud.textLabel.text = "Success"
+                        hud.detailTextLabel.text = nil
                         hud.indicatorView = JGProgressHUDSuccessIndicatorView()
-                })
+                    }
+                )
 
                 hud.dismiss(afterDelay: 1.0)
             }
         }
     }
-    
+
     private func setHudProgress(_ progress: Int) {
         if let hud = self.backupHud {
-            hud.progress = Float(progress)/1000.0
-            hud.detailTextLabel.text = "\(progress/10)% Complete"
+            hud.progress = Float(progress) / 1000.0
+            hud.detailTextLabel.text = "\(progress / 10)% Complete"
         }
     }
-    
+
     private func showBackupHud(_ text: String) {
         let hud = JGProgressHUD(style: .dark)
         hud.vibrancyEnabled = true
@@ -107,14 +112,14 @@ final internal class SettingsViewController: QuickTableViewController {
 
         hud.detailTextLabel.text = "0% Complete"
         hud.textLabel.text = text
-        hud.show(in: self.view)
-        
+        hud.show(in: view)
+
         backupHud = hud
     }
-    
+
     override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
-        
+
         let nc = NotificationCenter.default
         if let backupProgressObserver = self.backupProgressObserver {
             nc.removeObserver(backupProgressObserver)
@@ -123,64 +128,69 @@ final internal class SettingsViewController: QuickTableViewController {
             nc.removeObserver(configureProgressObserver)
         }
     }
+
     private func setTable() {
         var basicsRows: [Row & RowStyle] = [
             NavigationRow(title: "Email", subtitle: .rightAligned(MRConfig.addr ?? ""), action: { _ in }),
             NavigationRow(title: "Password", subtitle: .rightAligned("********"), action: editCell()),
-            TapActionRow(title: "Configure", action: { [weak self] in self?.configure($0) })
+            TapActionRow(title: "Configure", action: { [weak self] in self?.configure($0) }),
         ]
         var backupRows = [
             TapActionRow(title: "Create backup", action: { [weak self] in self?.createBackup($0) }),
-            TapActionRow(title: "Restore from backup", action: { [weak self] in self?.restoreBackup($0) })
+            TapActionRow(title: "Restore from backup", action: { [weak self] in self?.restoreBackup($0) }),
         ]
-        
+
         let ud = UserDefaults.standard
         if ud.bool(forKey: Constants.Keys.deltachatUserProvidedCredentialsKey) {
             basicsRows.removeLast()
             backupRows.removeLast()
         }
-        
+
         tableContents = [
-          Section(
-            title: "Basics",
-            rows: basicsRows
-          ),
-
-          Section(
-            title: "User Details",
-            rows: [
-              NavigationRow(title: "Display Name", subtitle: .rightAligned(MRConfig.displayname ?? ""), action: editCell()),
-              NavigationRow(title: "Status", subtitle: .rightAligned(MRConfig.selfstatus ?? ""), action: editCell()),
-            ]),
-
-          Section(
-            title: "Advanced",
-            rows: [
-              NavigationRow(title: "IMAP Server", subtitle: .rightAligned(MRConfig.mailServer ?? ""), action: editCell()),
-              NavigationRow(title: "IMAP User", subtitle: .rightAligned(MRConfig.mailUser ?? ""), action: editCell()),
-              NavigationRow(title: "IMAP Port", subtitle: .rightAligned(MRConfig.mailPort ?? ""), action: editCell()),
-       
-              NavigationRow(title: "SMTP Server", subtitle: .rightAligned(MRConfig.sendServer ?? ""), action: editCell()),
-              NavigationRow(title: "SMTP User", subtitle: .rightAligned(MRConfig.sendUser ?? ""), action: editCell()),
-              NavigationRow(title: "SMTP Port", subtitle: .rightAligned(MRConfig.sendPort ?? ""), action: editCell()),
-              NavigationRow(title: "SMTP Password", subtitle: .rightAligned("********"), action: editCell()),
-              ]),
-          
-          Section(
-            title: "Flags",
-            rows: [
-              SwitchRow(title: "E2EE enabled", switchValue: MRConfig.e2eeEnabled, action: editCell()),
-              SwitchRow(title: "MDNS enabled", switchValue: MRConfig.mdnsEnabled, action: editCell()),
-              SwitchRow(title: "Watch Inbox", switchValue: MRConfig.inboxWatch, action: editCell()),
-              SwitchRow(title: "Watch Sentbox", switchValue: MRConfig.sentboxWatch, action: editCell()),
-              SwitchRow(title: "Watch Mvbox", switchValue: MRConfig.mvboxWatch, action: editCell()),
-              SwitchRow(title: "Move to Mvbox", switchValue: MRConfig.mvboxMove, action: editCell()),
-              SwitchRow(title: "Save Mime Headers", switchValue: MRConfig.saveMimeHeaders, action: editCell()),
-            ]),
-
-          Section(
-            title: "Backup",
-            rows: backupRows),
+            Section(
+                title: "Basics",
+                rows: basicsRows
+            ),
+
+            Section(
+                title: "User Details",
+                rows: [
+                    NavigationRow(title: "Display Name", subtitle: .rightAligned(MRConfig.displayname ?? ""), action: editCell()),
+                    NavigationRow(title: "Status", subtitle: .rightAligned(MRConfig.selfstatus ?? ""), action: editCell()),
+                ]
+            ),
+
+            Section(
+                title: "Advanced",
+                rows: [
+                    NavigationRow(title: "IMAP Server", subtitle: .rightAligned(MRConfig.mailServer ?? ""), action: editCell()),
+                    NavigationRow(title: "IMAP User", subtitle: .rightAligned(MRConfig.mailUser ?? ""), action: editCell()),
+                    NavigationRow(title: "IMAP Port", subtitle: .rightAligned(MRConfig.mailPort ?? ""), action: editCell()),
+
+                    NavigationRow(title: "SMTP Server", subtitle: .rightAligned(MRConfig.sendServer ?? ""), action: editCell()),
+                    NavigationRow(title: "SMTP User", subtitle: .rightAligned(MRConfig.sendUser ?? ""), action: editCell()),
+                    NavigationRow(title: "SMTP Port", subtitle: .rightAligned(MRConfig.sendPort ?? ""), action: editCell()),
+                    NavigationRow(title: "SMTP Password", subtitle: .rightAligned("********"), action: editCell()),
+                ]
+            ),
+
+            Section(
+                title: "Flags",
+                rows: [
+                    SwitchRow(title: "E2EE enabled", switchValue: MRConfig.e2eeEnabled, action: editCell()),
+                    SwitchRow(title: "MDNS enabled", switchValue: MRConfig.mdnsEnabled, action: editCell()),
+                    SwitchRow(title: "Watch Inbox", switchValue: MRConfig.inboxWatch, action: editCell()),
+                    SwitchRow(title: "Watch Sentbox", switchValue: MRConfig.sentboxWatch, action: editCell()),
+                    SwitchRow(title: "Watch Mvbox", switchValue: MRConfig.mvboxWatch, action: editCell()),
+                    SwitchRow(title: "Move to Mvbox", switchValue: MRConfig.mvboxMove, action: editCell()),
+                    SwitchRow(title: "Save Mime Headers", switchValue: MRConfig.saveMimeHeaders, action: editCell()),
+                ]
+            ),
+
+            Section(
+                title: "Backup",
+                rows: backupRows
+            ),
         ]
     }
 
@@ -188,16 +198,16 @@ final internal class SettingsViewController: QuickTableViewController {
 
     private func editCell() -> (Row) -> Void {
         return { [weak self] sender in
-          logger.info( "row edit", sender.title)
+            logger.info("row edit", sender.title)
 
             let title = sender.title
             let subtitle: String = sender.subtitle?.text ?? ""
             let alertController = UIAlertController(title: title, message: nil, preferredStyle: .alert)
 
             if let sender = sender as? SwitchRow {
-              logger.info( "got bool switch")
+                logger.info("got bool switch")
                 let value = sender.switchValue
-                
+
                 switch title {
                 case "E2EE enabled":
                     MRConfig.e2eeEnabled = value
@@ -214,14 +224,14 @@ final internal class SettingsViewController: QuickTableViewController {
                 case "Save Mime Headers":
                     MRConfig.saveMimeHeaders = value
                 default:
-                  logger.info( "unknown title", title)
+                    logger.info("unknown title", title)
                 }
                 return
             }
 
-            let confirmAction = UIAlertAction(title: "Save", style: .default) { (_) in
+            let confirmAction = UIAlertAction(title: "Save", style: .default) { _ in
                 guard let textFields = alertController.textFields,
-                      textFields.count > 0 else {
+                    textFields.count > 0 else {
                     // Could not find textfield
                     return
                 }
@@ -261,7 +271,7 @@ final internal class SettingsViewController: QuickTableViewController {
                 case "SMTP Password":
                     MRConfig.sendPw = field.text
                 default:
-                  logger.info( "unknown title", title)
+                    logger.info("unknown title", title)
                 }
 
                 if needRefresh {
@@ -270,11 +280,11 @@ final internal class SettingsViewController: QuickTableViewController {
                 }
             }
 
-            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
-              logger.info( "canceled")
+            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
+                logger.info("canceled")
             }
 
-            alertController.addTextField { (textField) in
+            alertController.addTextField { textField in
                 textField.placeholder = subtitle
             }
 
@@ -285,22 +295,22 @@ final internal class SettingsViewController: QuickTableViewController {
         }
     }
 
-    private func createBackup(_ sender: Row) {
+    private func createBackup(_: Row) {
         if let documents = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.delta.chat.ios")?.path {
-            logger.info( "create backup in", documents)
+            logger.info("create backup in", documents)
             dc_imex(mailboxPointer, DC_IMEX_EXPORT_BACKUP, documents, nil)
             showBackupHud("Creating Backup")
         }
     }
 
-    private func restoreBackup(_ sender: Row) {
+    private func restoreBackup(_: Row) {
         let ud = UserDefaults.standard
         if ud.bool(forKey: Constants.Keys.deltachatUserProvidedCredentialsKey) {
             return
         }
-        
+
         if let documents = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.delta.chat.ios")?.path {
-            logger.info( "looking for backup in", documents)
+            logger.info("looking for backup in", documents)
 
             if let file = dc_imex_has_backup(mailboxPointer, documents) {
                 // Close as we are resetting the world
@@ -311,37 +321,37 @@ final internal class SettingsViewController: QuickTableViewController {
                     fatalError("Error: dc_context_new returned nil")
                 }
 
-                // TODO: open 
-                
+                // TODO: open
+
                 let hud = JGProgressHUD(style: .dark)
                 hud.textLabel.text = "Restoring Backup"
-                hud.show(in: self.view)
-                
+                hud.show(in: view)
+
                 dc_imex(mailboxPointer, DC_IMEX_IMPORT_BACKUP, file, nil)
 
                 hud.dismiss(afterDelay: 1.0)
             } else {
                 let alert = UIAlertController(title: "Can not restore", message: "No Backup found", preferredStyle: .alert)
-                self.present(alert, animated: true, completion: nil)
+                present(alert, animated: true, completion: nil)
             }
         }
     }
-    
-    private func configure(_ sender: Row) {
+
+    private func configure(_: Row) {
         let ud = UserDefaults.standard
         if ud.bool(forKey: Constants.Keys.deltachatUserProvidedCredentialsKey) {
             return
         }
-        
+
         let appDelegate = UIApplication.shared.delegate as! AppDelegate
         showBackupHud("Configuring account")
         appDelegate.stop()
         dc_configure(mailboxPointer)
-        
+
         // refresh our view
-        self.setTable()
-        self.tableView.reloadData()
-        
+        setTable()
+        tableView.reloadData()
+
         appDelegate.start()
     }
 }

+ 17 - 19
deltachat-ios/Utils.swift

@@ -15,15 +15,15 @@ struct Utils {
         return Utils.copyAndFreeArray(inputArray: c_contacts)
     }
 
-    static func getInitials(inputName:String) -> String {
+    static func getInitials(inputName: String) -> String {
         let nameParts = inputName.split(separator: " ")
-        let initials:[Character] = nameParts.compactMap {part in part.capitalized.first}
-        let initialsString:String = String(initials)
+        let initials: [Character] = nameParts.compactMap { part in part.capitalized.first }
+        let initialsString: String = String(initials)
         return initialsString
     }
 
-    static func copyAndFreeArray(inputArray:UnsafeMutablePointer<dc_array_t>?) -> [Int] {
-        var acc:[Int] = []
+    static func copyAndFreeArray(inputArray: UnsafeMutablePointer<dc_array_t>?) -> [Int] {
+        var acc: [Int] = []
         let len = dc_array_get_cnt(inputArray)
         for i in 0 ..< len {
             let e = dc_array_get_id(inputArray, i)
@@ -32,19 +32,18 @@ struct Utils {
         dc_array_unref(inputArray)
         return acc
     }
-    
-    
+
     static func isValid(_ email: String) -> Bool {
-        let emailRegEx = "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"+"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"+"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"+"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"+"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"+"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"+"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
-        
-        let emailTest = NSPredicate(format:"SELF MATCHES[c] %@", emailRegEx)
+        let emailRegEx = "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}" + "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" + "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-" + "z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5" + "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" + "9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" + "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
+
+        let emailTest = NSPredicate(format: "SELF MATCHES[c] %@", emailRegEx)
         return emailTest.evaluate(with: email)
     }
-    
-    static func formatAddressForQuery(address: [String : String]) -> String {
+
+    static func formatAddressForQuery(address: [String: String]) -> String {
         // Open address in Apple Maps app.
         var addressParts = [String]()
-        let addAddressPart: ((String?) -> Void) = { (part) in
+        let addAddressPart: ((String?) -> Void) = { part in
             guard let part = part else {
                 return
             }
@@ -63,23 +62,22 @@ struct Utils {
     }
 }
 
-
 extension UIColor {
     convenience init(alpha: Int, red: Int, green: Int, blue: Int) {
         assert(red >= 0 && red <= 255, "Invalid red component")
         assert(green >= 0 && green <= 255, "Invalid green component")
         assert(blue >= 0 && blue <= 255, "Invalid blue component")
-        
+
         self.init(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: CGFloat(alpha) / 255)
     }
-    
+
     convenience init(netHex: Int) {
-        var alpha = (netHex >> 24) & 0xff
+        var alpha = (netHex >> 24) & 0xFF
         if alpha == 0 {
             alpha = 255
         }
-        
-        self.init(alpha: alpha, red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
+
+        self.init(alpha: alpha, red: (netHex >> 16) & 0xFF, green: (netHex >> 8) & 0xFF, blue: netHex & 0xFF)
     }
 
     // see: https://stackoverflow.com/a/33397427

+ 19 - 22
deltachat-ios/Wrapper.swift

@@ -42,7 +42,7 @@ class MRContact {
         let file = dc_contact_get_profile_image(contactPointer)
         if let cFile = file {
             let filename = String(cString: cFile)
-            let path: URL = URL.init(fileURLWithPath: filename, isDirectory: false)
+            let path: URL = URL(fileURLWithPath: filename, isDirectory: false)
             if path.isFileURL {
                 do {
                     let data = try Data(contentsOf: path)
@@ -76,7 +76,6 @@ class MRContact {
     }
 }
 
-
 class MRMessage {
     private var messagePointer: UnsafeMutablePointer<dc_msg_t>
 
@@ -89,7 +88,7 @@ class MRMessage {
     }
 
     lazy var fromContact: MRContact = {
-        return MRContact(id: fromContactId)
+        MRContact(id: fromContactId)
     }()
 
     var toContactId: Int {
@@ -114,14 +113,14 @@ class MRMessage {
         let file = dc_msg_get_file(messagePointer)
         if let cFile = file, filetype == DC_MSG_IMAGE {
             let filename = String(cString: cFile)
-            let path: URL = URL.init(fileURLWithPath: filename, isDirectory: false)
+            let path: URL = URL(fileURLWithPath: filename, isDirectory: false)
             if path.isFileURL {
                 do {
                     let data = try Data(contentsOf: path)
                     let image = UIImage(data: data)
                     return image
                 } catch {
-                    logger.warning( "failed to load image: \(filename), \(error)")
+                    logger.warning("failed to load image: \(filename), \(error)")
                     return nil
                 }
             }
@@ -144,9 +143,9 @@ class MRMessage {
     func stateOutDescription() -> String {
         switch Int32(state) {
         case DC_STATE_OUT_DRAFT:
-                return "Draft"
+            return "Draft"
         case DC_STATE_OUT_PENDING:
-                return "Pending"
+            return "Pending"
         case DC_STATE_OUT_DELIVERED:
             return "Sent"
         case DC_STATE_OUT_MDN_RCVD:
@@ -159,7 +158,7 @@ class MRMessage {
     var timestamp: Int64 {
         return Int64(messagePointer.pointee.timestamp)
     }
-    
+
     var isInfo: Bool {
         return dc_msg_is_info(messagePointer) == 1
     }
@@ -180,7 +179,6 @@ class MRMessage {
 }
 
 class MRChat {
-
     var chatPointer: UnsafeMutablePointer<dc_chat_t>
 
     var id: Int {
@@ -206,14 +204,14 @@ class MRChat {
         let file = dc_chat_get_profile_image(chatPointer)
         if let cFile = file {
             let filename = String(cString: cFile)
-            let path: URL = URL.init(fileURLWithPath: filename, isDirectory: false)
+            let path: URL = URL(fileURLWithPath: filename, isDirectory: false)
             if path.isFileURL {
                 do {
                     let data = try Data(contentsOf: path)
                     let image = UIImage(data: data)
                     return image
                 } catch {
-                    logger.warning( "failed to load image: \(filename), \(error)")
+                    logger.warning("failed to load image: \(filename), \(error)")
                     return nil
                 }
             }
@@ -233,7 +231,6 @@ class MRChat {
 }
 
 class MRPoorText {
-
     private var poorTextPointer: UnsafeMutablePointer<dc_lot_t>
 
     var text1: String? {
@@ -273,12 +270,11 @@ class MRPoorText {
 }
 
 class MRChatList {
-
     private var chatListPointer: UnsafeMutablePointer<dc_chatlist_t>
 
     var length: Int {
         return dc_chatlist_get_cnt(chatListPointer)
-        //return Int(chatListPointer.pointee.m_cnt)
+        // return Int(chatListPointer.pointee.m_cnt)
     }
 
     // takes ownership of specified pointer
@@ -287,11 +283,11 @@ class MRChatList {
     }
 
     func getChatId(index: Int) -> Int {
-        return Int(dc_chatlist_get_chat_id(self.chatListPointer, index))
+        return Int(dc_chatlist_get_chat_id(chatListPointer, index))
     }
 
     func getMessageId(index: Int) -> Int {
-        return Int(dc_chatlist_get_msg_id(self.chatListPointer, index))
+        return Int(dc_chatlist_get_msg_id(chatListPointer, index))
     }
 
     func summary(index: Int) -> MRPoorText {
@@ -318,7 +314,7 @@ func strToBool(_ value: String?) -> Bool {
 }
 
 class MRConfig {
-    class private func getOptStr(_ key: String) -> String? {
+    private class func getOptStr(_ key: String) -> String? {
         let p = dc_get_config(mailboxPointer, key)
 
         if let pSafe = p {
@@ -328,19 +324,19 @@ class MRConfig {
         return nil
     }
 
-    class private func setOptStr(_ key: String, _ value: String?) {
+    private class func setOptStr(_ key: String, _ value: String?) {
         if let v = value {
             dc_set_config(mailboxPointer, key, v)
         }
     }
 
-    class private func getBool(_ key: String) -> Bool {
-        return strToBool(self.getOptStr(key))
+    private class func getBool(_ key: String) -> Bool {
+        return strToBool(getOptStr(key))
     }
 
-    class private func setBool(_ key: String, _ value: Bool) {
+    private class func setBool(_ key: String, _ value: Bool) {
         let vStr = value ? "1" : "0"
-        self.setOptStr(key, vStr)
+        setOptStr(key, vStr)
     }
 
     /**
@@ -414,6 +410,7 @@ class MRConfig {
             return getOptStr("send_server")
         }
     }
+
     /**
      *  SMTP-user, guessed if left out
      */

+ 29 - 28
deltachat-ios/events.swift

@@ -8,16 +8,15 @@
 
 import UserNotifications
 
-let dc_notificationChanged = Notification.Name(rawValue:"MrEventMsgsChanged")
-let dc_notificationStateChanged = Notification.Name(rawValue:"MrEventStateChanged")
-let dc_notificationIncoming = Notification.Name(rawValue:"MrEventIncomingMsg")
-let dc_notificationBackupProgress = Notification.Name(rawValue:"MrEventBackupProgress")
-let dc_notificationConfigureProgress = Notification.Name(rawValue:"MrEventConfigureProgress")
+let dc_notificationChanged = Notification.Name(rawValue: "MrEventMsgsChanged")
+let dc_notificationStateChanged = Notification.Name(rawValue: "MrEventStateChanged")
+let dc_notificationIncoming = Notification.Name(rawValue: "MrEventIncomingMsg")
+let dc_notificationBackupProgress = Notification.Name(rawValue: "MrEventBackupProgress")
+let dc_notificationConfigureProgress = Notification.Name(rawValue: "MrEventConfigureProgress")
 
 @_silgen_name("callbackSwift")
 
 public func callbackSwift(event: CInt, data1: CUnsignedLong, data2: CUnsignedLong, data1String: UnsafePointer<Int8>, data2String: UnsafePointer<Int8>) -> UnsafePointer<Int8>? {
-    
     switch event {
     case DC_EVENT_HTTP_GET:
         let urlString = String(cString: data1String)
@@ -28,7 +27,7 @@ public func callbackSwift(event: CInt, data1: CUnsignedLong, data2: CUnsignedLon
         guard let configText = try? String(contentsOf: url) else {
             return nil
         }
-        
+
         // see the strdup tip here: https://oleb.net/blog/2016/10/swift-array-of-c-strings/#alternative-strdup-and-free
         let p = UnsafePointer(strdup(configText))
         return p
@@ -42,15 +41,15 @@ public func callbackSwift(event: CInt, data1: CUnsignedLong, data2: CUnsignedLon
         let s = String(cString: data2String)
         AppDelegate.lastErrorDuringConfig = s
         logger.error("event: \(s)")
-        // TODO
-        // check online state, return
-        // - 0 when online
-        // - 1 when offline
+    // TODO:
+    // check online state, return
+    // - 0 when online
+    // - 1 when offline
     case DC_EVENT_CONFIGURE_PROGRESS:
         let nc = NotificationCenter.default
         DispatchQueue.main.async {
             let done = Int(data1) == 1000
-            
+
             nc.post(
                 name: dc_notificationConfigureProgress,
                 object: nil,
@@ -58,9 +57,10 @@ public func callbackSwift(event: CInt, data1: CUnsignedLong, data2: CUnsignedLon
                     "progress": Int(data1),
                     "error": Int(data1) == 0,
                     "done": done,
-                    "errorMessage": AppDelegate.lastErrorDuringConfig
-                ])
-            
+                    "errorMessage": AppDelegate.lastErrorDuringConfig,
+                ]
+            )
+
             if done {
                 UserDefaults.standard.set(true, forKey: Constants.Keys.deltachatUserProvidedCredentialsKey)
                 UserDefaults.standard.synchronize()
@@ -72,7 +72,7 @@ public func callbackSwift(event: CInt, data1: CUnsignedLong, data2: CUnsignedLon
         if data1 == 1 {
             // TODO: report to the user!
         }
-      
+
         let nc = NotificationCenter.default
         DispatchQueue.main.async {
             nc.post(name: dc_notificationStateChanged,
@@ -93,29 +93,29 @@ public func callbackSwift(event: CInt, data1: CUnsignedLong, data2: CUnsignedLon
         // e.g. when message appears that is not new, i.e. no need
         // to set badge / notification
         logger.info("change: \(event)")
-        
+
         let nc = NotificationCenter.default
-        
+
         DispatchQueue.main.async {
-            nc.post(name:dc_notificationChanged,
+            nc.post(name: dc_notificationChanged,
                     object: nil,
                     userInfo: [
                         "message_id": Int(data2),
                         "chat_id": Int(data1),
-                        "date": Date()
-                ])
+                        "date": Date(),
+            ])
         }
     case DC_EVENT_INCOMING_MSG:
         let nc = NotificationCenter.default
 
         DispatchQueue.main.async {
-            nc.post(name:dc_notificationIncoming,
+            nc.post(name: dc_notificationIncoming,
                     object: nil,
                     userInfo: [
                         "message_id": Int(data2),
                         "chat_id": Int(data1),
-                        "date": Date()
-                ])
+                        "date": Date(),
+            ])
         }
     case DC_EVENT_SMTP_MESSAGE_SENT:
         logger.info("network: \(String(cString: data2String))")
@@ -131,8 +131,9 @@ public func callbackSwift(event: CInt, data1: CUnsignedLong, data2: CUnsignedLon
                     "progress": Int(data1),
                     "error": Int(data1) == 0,
                     "done": Int(data1) == 1000,
-                    "errorMessage": AppDelegate.lastErrorDuringConfig
-                ])
+                    "errorMessage": AppDelegate.lastErrorDuringConfig,
+                ]
+            )
         }
     case DC_EVENT_IMEX_FILE_WRITTEN:
         logger.info("backup file written: \(String(cString: data1String))")
@@ -140,8 +141,8 @@ public func callbackSwift(event: CInt, data1: CUnsignedLong, data2: CUnsignedLon
         // nothing to do for now
         break
     default:
-       logger.warning("unknown event: \(event)")
+        logger.warning("unknown event: \(event)")
     }
-    
+
     return nil
 }