1 // Copyright 2015-present 650 Industries. All rights reserved.
2 
3 import Foundation
4 import UIKit
5 
6 @objc
7 open class DevMenuAction: DevMenuScreenItem, DevMenuCallableProvider {
8   @objc
9   public var callable: DevMenuExportedAction
10 
11   @objc
12   public var action: () -> Void {
13     get { return self.callable.action }
14     set { self.callable.action = newValue }
15   }
16 
17   @objc
18   open var isAvailable: () -> Bool {
19     get {
20       return self.callable.isAvailable
21     }
22     set {
23       self.callable.isAvailable = newValue
24     }
25   }
26 
27   @objc
28   open var isEnabled: () -> Bool = { false }
29 
30   @objc
31   open var label: () -> String = { "" }
32 
33   @objc
34   open var detail: () -> String = { "" }
35 
36   @objc
37   open var glyphName: () -> String = { "" }
38 
39   @objc
40   public init(withId id: String) {
41     self.callable = DevMenuExportedAction(withId: id, withAction: {})
42     super.init(type: .Action)
43   }
44 
45   @objc
46   public convenience init(withId id: String, action: @escaping () -> ()) {
47     self.init(withId: id)
48     self.callable.action = action
49   }
50 
51   public func registerCallable() -> DevMenuExportedCallable? {
52     return self.callable
53   }
54 
55   @objc
56   open func registerKeyCommand(input: String, modifiers: UIKeyModifierFlags) {
57     self.callable.registerKeyCommand(input: input, modifiers: modifiers)
58   }
59 
60   @objc
61   open override func serialize() -> [String : Any] {
62     var dict = super.serialize()
63     dict["actionId"] = self.callable.id
64     dict["keyCommand"] = self.callable.keyCommand == nil ? nil : [
65       "input": self.callable.keyCommand!.input!,
66       "modifiers": exportKeyCommandModifiers()
67     ]
68 
69     dict["isAvailable"] = isAvailable()
70     dict["isEnabled"] = isAvailable()
71     dict["label"] = label()
72     dict["detail"] = detail()
73     dict["glyphName"] = glyphName()
74 
75     return dict
76   }
77 
78   private func exportKeyCommandModifiers() -> Int {
79     var exportedValue = 0;
80     let keyCommand = self.callable.keyCommand!
81 
82     if keyCommand.modifierFlags.contains(.control) {
83       exportedValue += 1 << 0;
84     }
85 
86     if keyCommand.modifierFlags.contains(.alternate) {
87       exportedValue += 1 << 1;
88     }
89 
90     if keyCommand.modifierFlags.contains(.command) {
91       exportedValue += 1 << 2;
92     }
93 
94     if keyCommand.modifierFlags.contains(.shift) {
95       exportedValue += 1 << 3;
96     }
97 
98     return exportedValue
99   }
100 }
101