-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppDelegate.swift
3319 lines (2946 loc) · 142 KB
/
AppDelegate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// AppDelegate.swift
// Meteorologist
//
// Swift code written by Ed Danley on 9/19/15.
// Copyright © 2015 The Meteorologist Group, LLC. All rights reserved.
//
// Original source by Joe Crobak and Meteorologist Group
// Some new graphics by Matthew Fahrenbacher
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
// OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// A couple of problems were encountered with 10.9.
// 1. The labelColor font attribute was on for all labels in MainMenu.xib.
// Had to update both the TEXT and BACKCOLOR to default.
// No clue why but we're not alone. It's an Apple bug somewhere.
// 2. Fixed the font problem above then started getting another Apple crash.
// Found this link, downloaded the Mavericks10.9.imageset file from this URL and it magically solved the problem.
// http://stackoverflow.com/questions/39616332/tokencount-maxcountincludingzeroterminator-assertion-osx-10-9
//
// http://www.johnmullins.co/blog/2014/08/08/menubar-app/
// http://acapio.de/Programmierung/XCode/Swift_-_Display_window_as_modal/index.html
// http://footle.org/WeatherBar/
// https://developer.yahoo.com/weather/
// http://www.programmableweb.com/news/top-10-weather-apis/analysis/2014/11/13
//
// Future weather feeds?
// http://www.myweather2.com/developer/
// http://www.worldweatheronline.com/api/local-city-town-weather-api.aspx
// https://www.weatherbit.io/api
//
// Preferences have been cached since 10.9
// https://forums.developer.apple.com/message/65946#65946
// killall -u $USER cfprefsd
//
// http://stackoverflow.com/questions/26340670/issue-with-genstrings-for-swift-file
//
import Cocoa
import WebKit
import CoreLocation
// This isn't needed but kept here for future reference
#if os(iOS)
#elseif os(OSX)
#endif
let DEFAULT_CITY = "<here>"
let DEFAULT_CITY2 = "Cupertino, CA"
let DEFAULT_INTERVAL = "60"
let YAHOO_WEATHER = "0"
let OPENWEATHERMAP = "1"
let THEWEATHER = "2"
let WEATHERUNDERGROUND = "3"
let AERISWEATHER = "4"
let WORLDWEATHERONLINE = "5"
let DARKSKY = "6"
let APIXU = "7"
let CANADAGOV = "8"
let NOAAWEATHER = "9"
let MAX_LOCATIONS = 8
var DEFAULT_PREFERENCE_VERSION = String()
var NoInternetConnectivity = Int()
// http://stackoverflow.com/questions/24196689/how-to-get-the-power-of-some-integer-in-swift-language
// Put this at file level anywhere in your project
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ** : PowerPrecedence
func ** (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
func ** (radix: Double, power: Double) -> Double
{
return pow(radix, power)
}
func ** (radix: Int, power: Int ) -> Double
{
return pow(Double(radix), Double(power))
}
func ** (radix: Float, power: Float ) -> Double
{
return pow(Double(radix), Double(power))
}
// https://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string
extension String
{
func replace(target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
// https://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift
subscript(_ range: CountableRange<Int>) -> String {
let idx1 = index(startIndex, offsetBy: max(0, range.lowerBound))
let idx2 = index(startIndex, offsetBy: min(self.count, range.upperBound))
return String(self[idx1..<idx2])
}
} // extension String
// https://bluelemonbits.com/index.php/2015/08/20/evaluate-string-width-and-return-cgfloat-swift-osx/
func evaluateStringWidth (textToEvaluate: String) -> CGFloat{
let defaults = UserDefaults.standard
var font = NSFont()
let m = NumberFormatter().number(from: defaults.string(forKey: "fontsize")!)!
if (defaults.string(forKey: "fontDefault") == "1") {
font = NSFont.systemFont(ofSize: CGFloat(truncating: m))
}
else {
font = NSFont(name: defaults.string(forKey: "font")!, size: CGFloat(truncating: m))!
}
let attributes = NSDictionary(object: font, forKey:NSAttributedString.Key.font as NSCopying)
let sizeOfText = textToEvaluate.size(withAttributes: (attributes as! [NSAttributedString.Key : Any]))
//let sizeOfText = textToEvaluate.size(withAttributes: (attributes as! [String : AnyObject]))
return sizeOfText.width
} // evaluateStringWidth
func localizedString(forKey key: String) -> String {
var result = Bundle.main.localizedString(forKey: key, value: nil, table: nil)
if result == key {
result = Bundle.main.localizedString(forKey: key, value: nil, table: "Default")
}
return result
} // localizedString
struct WeatherFields {
// TODO Change data to metric (standard)
var title1 = String()
var date = String() // In UTC
var latitude = String()
var longitude = String()
//var windChill = String()
var windSpeed = String() // mph
var windGust = String() // mph
var windDirection = String() // degrees
var altitude = String() // meters
var humidity = String() // percent
var pressure = String() // millibars
var visibility = String() // miles
var UVIndex = String() // Int
var sunrise = String() // UTC "mm:dd:yyyy'T'hh:MM:ss"
var sunset = String() // UTC "mm:dd:yyyy'T'hh:MM:ss"
var currentLink = String()
var currentTemp = String() // *F
var currentCode = String() // Abbreviated Conditions
var currentConditions = String() // Full Conditions
// http://stackoverflow.com/questions/30430550/how-to-create-an-empty-array-in-swift
var forecastCounter = 0
var forecastDate = [String]() // 31
var forecastDay = [String]() // Monday
var forecastHigh = [String]() // *F
var forecastLow = [String]() // *F
var forecastCode = [String]() // Abbreviated Conditions
var forecastConditions = [String]() // Full Condition
var URL = String()
var weatherTag = String()
} // WeatherFields
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, CLLocationManagerDelegate
{
// https://github.com/soffes/clock-saver/blob/master/ClockDemo/Classes/AppDelegate.swift
@IBOutlet weak var tabView: NSTabView!
@IBOutlet weak var locationsTab: NSTabViewItem!
@IBOutlet weak var optionsTab: NSTabViewItem!
@IBOutlet weak var globalTab: NSTabViewItem!
@IBOutlet weak var keyTab: NSTabViewItem!
@IBOutlet weak var helpTab: NSTabViewItem!
@IBOutlet var helpView: NSTextView!
@IBOutlet weak var scrollView: NSScrollView!
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var newVersion: NSButton!
@IBOutlet weak var logMessages: NSButton!
@IBOutlet weak var allowLocation: NSButton!
@IBOutlet weak var cityNameLabel: NSTextField!
@IBOutlet weak var cityDisplayNameLabel: NSTextField!
@IBOutlet weak var weatherSourceLabel: NSTextField!
@IBOutlet weak var API_Key_Label1: NSTextField!
@IBOutlet weak var API_Key_Label2: NSTextField!
@IBOutlet weak var cityTextField: NSTextField!
@IBOutlet weak var cityDisplayTextField: NSTextField!
@IBOutlet weak var weatherSource_1: NSPopUpButton!
@IBOutlet weak var API_Key_Data1_1: NSTextField!
@IBOutlet weak var API_Key_Data2_1: NSTextField!
@IBOutlet weak var cityTextField2: NSTextField!
@IBOutlet weak var cityDisplayTextField2: NSTextField!
@IBOutlet weak var weatherSource_2: NSPopUpButton!
@IBOutlet weak var API_Key_Data1_2: NSTextField!
@IBOutlet weak var API_Key_Data2_2: NSTextField!
@IBOutlet weak var cityTextField3: NSTextField!
@IBOutlet weak var cityDisplayTextField3: NSTextField!
@IBOutlet weak var weatherSource_3: NSPopUpButton!
@IBOutlet weak var API_Key_Data1_3: NSTextField!
@IBOutlet weak var API_Key_Data2_3: NSTextField!
@IBOutlet weak var cityTextField4: NSTextField!
@IBOutlet weak var cityDisplayTextField4: NSTextField!
@IBOutlet weak var weatherSource_4: NSPopUpButton!
@IBOutlet weak var API_Key_Data1_4: NSTextField!
@IBOutlet weak var API_Key_Data2_4: NSTextField!
@IBOutlet weak var cityTextField5: NSTextField!
@IBOutlet weak var cityDisplayTextField5: NSTextField!
@IBOutlet weak var weatherSource_5: NSPopUpButton!
@IBOutlet weak var API_Key_Data1_5: NSTextField!
@IBOutlet weak var API_Key_Data2_5: NSTextField!
@IBOutlet weak var cityTextField6: NSTextField!
@IBOutlet weak var cityDisplayTextField6: NSTextField!
@IBOutlet weak var weatherSource_6: NSPopUpButton!
@IBOutlet weak var API_Key_Data1_6: NSTextField!
@IBOutlet weak var API_Key_Data2_6: NSTextField!
@IBOutlet weak var cityTextField7: NSTextField!
@IBOutlet weak var cityDisplayTextField7: NSTextField!
@IBOutlet weak var weatherSource_7: NSPopUpButton!
@IBOutlet weak var API_Key_Data1_7: NSTextField!
@IBOutlet weak var API_Key_Data2_7: NSTextField!
@IBOutlet weak var cityTextField8: NSTextField!
@IBOutlet weak var cityDisplayTextField8: NSTextField!
@IBOutlet weak var weatherSource_8: NSPopUpButton!
@IBOutlet weak var API_Key_Data1_8: NSTextField!
@IBOutlet weak var API_Key_Data2_8: NSTextField!
@IBOutlet weak var menuBarFontLabel: NSTextField!
@IBOutlet weak var menuBarFontButton: NSButton!
@IBOutlet weak var fontLabel: NSTextField!
@IBOutlet weak var fontButton: NSButton!
@IBOutlet weak var updateFrequencyLabel: NSTextField!
@IBOutlet weak var updateFrequenceMinutesLabel: NSTextField!
@IBOutlet weak var updateFrequencyTextField: NSTextField!
@IBOutlet weak var delayFrequencyLabel: NSTextField!
@IBOutlet weak var delayFrequencySecondsLabel: NSTextField!
@IBOutlet weak var delayFrequencyTextField: NSTextField!
@IBOutlet weak var globalUnitsLabel: NSTextField!
@IBOutlet weak var degreesLabel: NSTextField!
@IBOutlet weak var degreesUnit: NSPopUpButton!
@IBOutlet weak var distanceLabel: NSTextField!
@IBOutlet weak var distanceUnit: NSPopUpButton!
@IBOutlet weak var speedLabel: NSTextField!
@IBOutlet weak var speedUnit: NSPopUpButton!
@IBOutlet weak var pressureLabel: NSTextField!
@IBOutlet weak var pressureUnit: NSPopUpButton!
@IBOutlet weak var directionLabel: NSTextField!
@IBOutlet weak var directionUnit: NSPopUpButton!
@IBOutlet weak var convertQFEtoQNH: NSButton!
@IBOutlet weak var forecastLabel: NSTextField!
@IBOutlet weak var forecastDays: NSPopUpButton!
@IBOutlet weak var controlsInSubmenu: NSButton!
@IBOutlet weak var displayHumidity: NSButton!
@IBOutlet weak var displayDegreeType: NSButton!
@IBOutlet weak var displayWeatherIcon: NSButton!
@IBOutlet weak var displayCityName: NSButton!
@IBOutlet weak var displayFeelsLike: NSButton!
@IBOutlet weak var useNewWeatherIcons: NSButton! //Added this to give choice between color and monochrome icons
@IBOutlet weak var currentWeatherInSubmenu: NSButton!
@IBOutlet weak var viewExtendedForecast: NSButton!
@IBOutlet weak var extendedForecastInSubmenu: NSButton!
@IBOutlet weak var extendedForecastIcons: NSButton!
@IBOutlet weak var extendedForecastSingleLine: NSButton!
@IBOutlet weak var extendedForecastDisplayDate: NSButton!
@IBOutlet weak var rotateWeatherLocations: NSButton!
@IBOutlet weak var versionTextLabel: NSTextField!
@IBOutlet weak var apiKeyLabel: NSTextField!
@IBOutlet weak var resetPrefsButton: NSButton!
@IBOutlet weak var latLongFormat: NSTextField!
@IBOutlet weak var theWeatherLocation: NSTextField!
@IBOutlet weak var openWeatherMapLocation: NSTextField!
@IBOutlet weak var yahooLocation: NSTextField!
@IBOutlet weak var wundergroundLocation: NSTextField!
@IBOutlet weak var aerisLocation: NSTextField!
@IBOutlet weak var worldWeatherLocation: NSTextField!
@IBOutlet weak var darkSkyLocation: NSTextField!
@IBOutlet weak var APIXULocation: NSTextField!
@IBOutlet weak var canadaGovLocation: NSTextField!
@IBOutlet weak var noaaWeatherLocation: NSTextField!
@IBOutlet weak var theWeatherURL: NSButton!
@IBOutlet weak var openWeatherMapURL: NSButton!
@IBOutlet weak var yahooURL: NSButton!
@IBOutlet weak var wundergroundURL: NSButton!
@IBOutlet weak var aerisURL: NSButton!
@IBOutlet weak var worldWeatherURL: NSButton!
@IBOutlet weak var darkSkyURL: NSButton!
@IBOutlet weak var apixuURL: NSButton!
@IBOutlet weak var canadaGovURL: NSButton!
@IBOutlet weak var noaaWeatherURL: NSButton!
var buttonPresses = 0
var modalMenuBar = ColorPickerWindow(windowNibName: "ColorPickerWindow")
var modalDisplay = ColorPickerWindow(windowNibName: "ColorPickerWindow")
var radarWindow = RadarWindow()
var statusBar = NSStatusBar.system
//var statusBarItem : NSStatusItem = NSStatusItem()
var statusBarItem = NSStatusItem()
var menu: NSMenu = NSMenu()
let yahooWeatherAPI = YahooWeatherAPI() // https://developer.yahoo.com/weather/
let openWeatherMapAPI = OpenWeatherMapAPI() // http://www.openweathermap.org
let theWeatherAPI = TheWeatherAPI()
let weatherUndergroundAPI = WeatherUndergroundAPI()
let darkSkyAPI = DarkSkyAPI()
let aerisWeatherAPI = AerisWeatherAPI()
let worldWeatherOnlineAPI = WorldWeatherOnlineAPI()
let ApiXUApi = APIXUAPI()
let canadaWeatherAPI = CanadaWeatherAPI()
let noaaWeatherAPI = NOAAWeatherAPI()
var myTimer = Timer() // http://ios-blog.co.uk/tutorials/swift-nstimer-tutorial-lets-create-a-counter-application/
var loadTimer: Timer! //For loading animation
let defaults = UserDefaults.standard
// Logging: https://gist.github.com/vtardia/3f7d17efd7b258e82b62
var appInfo: Dictionary<NSObject,AnyObject>
var appName: String!
var weatherFields: WeatherFields
var whichWeatherFirst = 0
var locationInformationArray: [[String]] = []
var weatherArray = [WeatherFields]()
let locationManager = CLLocationManager()
var myLatitude = ""
var myLongitude = ""
var myCity = ""
var myState = ""
var firstTime = false
var locationAltitude = "9999" // meters
override init()
{
DEFAULT_PREFERENCE_VERSION = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
// Init local parameters
self.appInfo = CFBundleGetInfoDictionary(CFBundleGetMainBundle()) as Dictionary
self.appName = appInfo[kCFBundleNameKey] as? String
weatherFields = WeatherFields()
// Init parent
super.init()
// Other init below...
defaultPreferences()
initPrefs()
// Library/Logs/Meteo.log
SetCustomLogFilename(self.appName)
let defaults = UserDefaults.standard
if ((defaults.string(forKey: "logMessages") != nil) &&
(defaults.string(forKey: "logMessages")! == "1"))
{
InfoLog(String(format:"Application %@ starting", self.appName))
}
if ((defaults.string(forKey: "allowLocation") != nil) &&
(defaults.string(forKey: "allowLocation")! == "1")) {
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
} // init
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
InfoLog("location manager auth status changed to:" )
switch status {
case .restricted:
InfoLog("status restricted")
_ = "status restricted"
case .denied:
InfoLog("status denied")
_ = "status denied"
case .authorized:
InfoLog("status authorized")
let location = locationManager.location
if (location != nil) {
self.myLatitude = String(format: "%f", location?.coordinate.latitude ?? "")
self.myLongitude = String(format: "%f", location?.coordinate.longitude ?? "")
// <here>
locationAltitude = String(format: "%.2f", location?.altitude ?? "")
InfoLog("")
InfoLog("This stuff is spooky, macOS knowing all this. But we're using parts of it...")
InfoLog("")
InfoLog("location data:")
InfoLog("latitude: " + String(format: "%.4f", location?.coordinate.latitude ?? ""))
InfoLog("longitude: " + String(format: "%.4f", location?.coordinate.longitude ?? ""))
InfoLog("altitude: " + String(format: "%.2f", location?.altitude ?? "") + " meters")
//InfoLog("floor: " + String(format: "%.2f", location?.floor ?? "")) // Not in macOS
InfoLog("horizontalAccuracy: " + String(format: "%.2f", location?.horizontalAccuracy ?? "") + " meters")
InfoLog("verticalAccuracy: " + String(format: "%.2f", location?.verticalAccuracy ?? "") + " meters")
InfoLog("speed: " + String(format: "%.2f", location?.speed ?? "") + " meters/second")
InfoLog("course: " + String(format: "%.2f", location?.course ?? "") + "˚")
let geocoder = CLGeocoder()
// Geocode Location
if (location != nil) {
geocoder.reverseGeocodeLocation(location!) { (placemarks, error) in
// Process Response
self.processResponse(withPlacemarks: placemarks, error: error)
}
}
} else {
InfoLog("Location data not available")
myCity = "Location unavailable"
}
//case .authorizedAlways:
//InfoLog("status authorized always")
//_ = "status authorized always"
default:
//case .notDetermined:
InfoLog("status not yet determined")
_ = "status not yet determined"
}
locationManager.stopUpdatingLocation()
} // locationManager
private func processResponse(withPlacemarks placemarks: [CLPlacemark]?, error: Error?) {
if let error = error {
InfoLog("Unable to Reverse Geocode Location (\(error))")
myCity = "Location not available"
} else {
if let placemarks = placemarks, let placemark = placemarks.first {
myCity = placemark.locality ?? "anytown"
myState = placemark.administrativeArea ?? "??"
// https://developer.apple.com/documentation/corelocation/clplacemark
InfoLog("")
InfoLog("placemark data:")
InfoLog("locality " + (placemark.locality ?? "unknown")) // City name
InfoLog("administrativeArea " + (placemark.administrativeArea ?? "unknown")) // State/Province name
//InfoLog("location " + (placemark.location ?? "unknown"))
InfoLog("name " + (placemark.name ?? "unknown"))
InfoLog("isoCountryCode " + (placemark.isoCountryCode ?? "unknown")) // ISO Country Code
InfoLog("country " + (placemark.country ?? "unknown")) // Country Name
InfoLog("postalCode " + (placemark.postalCode ?? "unknown"))
InfoLog("subAdministrativeArea " + (placemark.subAdministrativeArea ?? "unknown"))
InfoLog("subLocality " + (placemark.subLocality ?? "unknown"))
InfoLog("thoroughfare " + (placemark.thoroughfare ?? "unknown"))
InfoLog("subThoroughfare " + (placemark.subThoroughfare ?? "unknown"))
InfoLog("region " + (placemark.region?.identifier ?? "unknown"))
//InfoLog("timeZone " + (placemark.timeZone?.identifier ?? "unknown")) // 10.11
//InfoLog("postalAddress " + (placemark.postalAddress ?? "unknown")) // 10.13
InfoLog("inlandWater " + (placemark.inlandWater ?? "unknown"))
InfoLog("ocean " + (placemark.ocean ?? "unknown"))
var i = 0
while (i < placemark.areasOfInterest?.count ?? 0) {
InfoLog("areasOfInterest " + (placemark.areasOfInterest?[i] ?? "unknown"))
i = i + 1
}
InfoLog("")
} else {
myCity = "unknown3"
}
}
} // processResponse
func applicationDidFinishLaunching(_ aNotification: Notification)
{
// let icon = NSImage(named: "Loading-1")
// icon?.template = true // best for dark mode
// statusItem.image = icon
// statusItem.menu = statusMenu
}
func applicationWillTerminate(_ aNotification: Notification)
{
// Insert code here to tear down your application
}
override func awakeFromNib()
{
let defaults = UserDefaults.standard
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
/*
* Project settings/Target/Build Settings/Swift Compiler - Custom Flags/Other Swift Flags
* -DAPP_STORE
*/
#if APP_STORE
API_Key_Data1_1.isHidden = true
API_Key_Data2_1.isHidden = true
API_Key_Data1_2.isHidden = true
API_Key_Data2_2.isHidden = true
API_Key_Data1_3.isHidden = true
API_Key_Data2_3.isHidden = true
API_Key_Data1_4.isHidden = true
API_Key_Data2_4.isHidden = true
API_Key_Data1_5.isHidden = true
API_Key_Data2_5.isHidden = true
API_Key_Data1_6.isHidden = true
API_Key_Data2_6.isHidden = true
API_Key_Data1_7.isHidden = true
API_Key_Data2_7.isHidden = true
API_Key_Data1_8.isHidden = true
API_Key_Data2_8.isHidden = true
API_Key_Label1.isHidden = true
API_Key_Label2.isHidden = true
apiKeyLabel.isHidden = true
theWeatherLocation.isHidden = true
openWeatherMapLocation.isHidden = true
yahooLocation.isHidden = true
wundergroundLocation.isHidden = true
aerisLocation.isHidden = true
worldWeatherLocation.isHidden = true
theWeatherURL.isHidden = true
openWeatherMapURL.isHidden = true
yahooURL.isHidden = true
wundergroundURL.isHidden = true
aerisURL.isHidden = true
worldWeatherURL.isHidden = true
darkSkyURL.isHidden = true
apixuURL.isHidden = true
canadaGovURL.isHidden = true
noaaWeatherURL.isHidden = true
#else
#endif
statusBarItem = statusBar.statusItem(withLength: -1)
statusBarItem.menu = menu
statusBarItem.title = localizedString(forKey: "Loading_") + "..."
statusBarItem.image = NSImage(named: "Loading-1")!
loadTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(AppDelegate.runTimedCode), userInfo: nil, repeats: true) //Start animating the menubar icon
let newItem : NSMenuItem = NSMenuItem(title: localizedString(forKey: "PleaseWait_"), action: #selector(AppDelegate.dummy(_:)), keyEquivalent: "")
newItem.target=self
menu.addItem(newItem)
addControlOptions()
initWindowPrefs()
var launchDelay = 10.0
if (defaults.string(forKey: "launchDelay") != nil)
{
launchDelay = Double(defaults.string(forKey: "launchDelay")!)!
}
if ((defaults.string(forKey: "logMessages") != nil) &&
(defaults.string(forKey: "logMessages")! == "1") &&
(launchDelay > 0.00))
{
InfoLog(String(format:"Sleeping for %.0f second(s) to allow WiFi to get started", launchDelay))
}
//firstTime = true // Force TRUE for debuging Preference Pane
if (firstTime)
{
//tabView.activeTab = 4 // Help Panel
showPreferencePane()
}
// Sleep for a few seconds to allow WiFi to get started
if (launchDelay == 0.0) {
launchDelay = 0.1
}
Timer.scheduledTimer(timeInterval: launchDelay, target: self, selector: #selector(AppDelegate.launchWeather), userInfo: nil, repeats: false)
} // awakeFromNib
// This gets called when we Wake from sleep. See the setup below
// https://stackoverflow.com/questions/9247710/what-event-is-fired-when-mac-is-back-from-sleep
@objc func onWakeNote(note: NSNotification) {
let defaults = UserDefaults.standard
var launchDelay = 10.0
if ((defaults.string(forKey: "logMessages") != nil) &&
(defaults.string(forKey: "logMessages")! == "1")) {
InfoLog("Received wake notice: \(note.name)")
if (defaults.string(forKey: "launchDelay") != nil)
{
launchDelay = Double(defaults.string(forKey: "launchDelay")!)!
}
}
if (loadTimer != nil)
{
loadTimer.invalidate()
loadTimer = nil
}
let uwTimer = myTimer
if uwTimer == myTimer
{
if uwTimer.isValid
{
uwTimer.invalidate()
}
}
if (launchDelay < 10.0) {
launchDelay = launchDelay * 2 // Waking up takes twice as long as starting up
}
if (launchDelay > 0.0)
{
InfoLog(String(format:"Sleeping for %.0f second(s) to allow WiFi to get started", launchDelay))
}
// Sleep XX seconds for WiFi to wake up again
if (launchDelay == 0.0) {
launchDelay = 0.1
}
myTimer = Timer.scheduledTimer(timeInterval: Double(launchDelay), target:self, selector: #selector(AppDelegate.updateWeather), userInfo: nil, repeats: false)
} // onWakeNote
@objc func launchWeather() {
// This actually lets us get notified when we Wake from sleep
// https://stackoverflow.com/questions/9247710/what-event-is-fired-when-mac-is-back-from-sleep
NSWorkspace.shared.notificationCenter.addObserver(
self, selector: #selector(onWakeNote(note:)),
name: NSWorkspace.didWakeNotification, object: nil)
var webVERSION = ""
let newVersion = defaults.string(forKey: "newVersion")
var whatChanged = ""
if ((newVersion != nil) && (newVersion! == "1"))
{
// Check for updates
if let url = URL(string: "http://heat-meteo.sourceforge.net/" + "VERSION2") {
do
{
webVERSION = try NSString(contentsOf: url, usedEncoding: nil) as String
webVERSION = webVERSION.replacingOccurrences(of: "\n", with: "", options: .regularExpression)
if (webVERSION.count > 6) {
ErrorLog("http://heat-meteo.sourceforge.net/" + "VERSION2" + " not in the proper format\n" + webVERSION)
webVERSION = ""
}
}
catch
{
// contents could not be loaded
webVERSION = ""
}
}
else
{
// the URL was bad!
webVERSION = ""
}
let bundleVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
var version = ""
if (bundleVersion.count > 4) {
version = String(bundleVersion[bundleVersion.startIndex..<bundleVersion.index(bundleVersion.startIndex, offsetBy: 5)])
}
if ((version > webVERSION) && (bundleVersion.count > 5)) {
// Once released, don't allow beta's
version = webVERSION
} else if ((version == webVERSION) && (bundleVersion.count > 5)) {
// Allow beta versions until release
version = ""
}
if ((version < webVERSION) && (webVERSION != ""))
{
// New version!
if let url = URL(string: "http://heat-meteo.sourceforge.net/" + "CHANGELOG2")
{
do
{
whatChanged = try NSString(contentsOf: url, usedEncoding: nil) as String
//if (whatChanged[0] == '<') {
// ErrorLog (whatChanged)
//}
}
catch
{
}
}
let myPopup: NSAlert = NSAlert()
myPopup.messageText = localizedString(forKey: "NewVersionAvailable_") + "\n\n" + whatChanged
myPopup.informativeText = localizedString(forKey: "Download?_")
myPopup.alertStyle = NSAlert.Style.warning
myPopup.addButton(withTitle: localizedString(forKey: "Yes_"))
// http://swiftrien.blogspot.com/2015/03/code-sample-swift-nsalert_5.html
// If any button is created with the title "Cancel" then that has the key "Escape" associated with it
myPopup.addButton(withTitle: localizedString(forKey: "Cancel_"))
let res = myPopup.runModal()
if res == NSApplication.ModalResponse.alertFirstButtonReturn
{
let myUrl = "http://heat-meteo.sourceforge.net"
if let checkURL = URL(string: myUrl as String)
{
if NSWorkspace.shared.open(checkURL)
{
InfoLog("New version URL successfully opened:" + (myUrl as String))
exit(0)
}
}
else
{
InfoLog("New Version Invalid URL:" + (myUrl as String))
}
}
}
}
var m = (15 as NSNumber)
var font = NSFont(name: "Tahoma", size: 15)
if ((defaults.string(forKey: "font") != nil) &&
(defaults.string(forKey: "fontsize") != nil))
{
m = NumberFormatter().number(from: defaults.string(forKey: "fontsize")!)!
if (defaults.string(forKey: "fontDefault") == "1")
{
font = NSFont.systemFont(ofSize: CGFloat(truncating: m))
}
else
{
font = NSFont(name: defaults.string(forKey: "font")!, size: CGFloat(truncating: m))
}
}
menu.font = font
m = (15 as NSNumber)
font = NSFont(name: "Tahoma", size: 15)
if ((defaults.string(forKey: "menuBarFont") != nil) &&
(defaults.string(forKey: "menuBarFontsize") != nil))
{
m = NumberFormatter().number(from: defaults.string(forKey: "menuBarFontsize")!)!
// statusBarItem.image = nil
if (defaults.string(forKey: "menuBarFontDefault") == "1")
{
font = NSFont.systemFont(ofSize: CGFloat(truncating: m))
}
else
{
font = NSFont(name: defaults.string(forKey: "menuBarFont")!, size: CGFloat(truncating: m))
}
}
// Todo - Do we have a problem or not?
// http://stackoverflow.com/questions/19487369/center-two-different-size-font-vertically-in-a-nsattributedstring
if (webVERSION == "")
{
statusBarItem.attributedTitle = NSMutableAttributedString(attributedString: NSMutableAttributedString(string:
localizedString(forKey: "NetworkFailure_"),
attributes:[NSAttributedString.Key.font : font!]))
}
else
{
statusBarItem.attributedTitle = NSMutableAttributedString(attributedString: NSMutableAttributedString(string:
localizedString(forKey: "Loading_") + "...",
attributes:[NSAttributedString.Key.font : font!]))
}
let preferenceVersion = defaults.string(forKey: "preferenceVersion")
if ((preferenceVersion == nil) || (preferenceVersion! != DEFAULT_PREFERENCE_VERSION))
{
//self.window!.orderOut(self)
defaults.setValue(DEFAULT_PREFERENCE_VERSION, forKey: "preferenceVersion")
self.window!.makeKeyAndOrderFront(self.window!)
NSApp.activate(ignoringOtherApps: true)
}
updateWeather()
} // launchWeather
@objc func runTimedCode() //Animate the icon while loading
{
if (statusBarItem.image == NSImage(named: "Loading-8"))
{
statusBarItem.image = NSImage(named: "Loading-1")!
}
else if (statusBarItem.image == NSImage(named: "Loading-1"))
{
statusBarItem.image = NSImage(named: "Loading-2")!
}
else if (statusBarItem.image == NSImage(named: "Loading-2"))
{
statusBarItem.image = NSImage(named: "Loading-3")!
}
else if (statusBarItem.image == NSImage(named: "Loading-3"))
{
statusBarItem.image = NSImage(named: "Loading-4")!
}
else if (statusBarItem.image == NSImage(named: "Loading-4"))
{
statusBarItem.image = NSImage(named: "Loading-5")!
}
else if (statusBarItem.image == NSImage(named: "Loading-5"))
{
statusBarItem.image = NSImage(named: "Loading-6")!
}
else if (statusBarItem.image == NSImage(named: "Loading-6"))
{
statusBarItem.image = NSImage(named: "Loading-7")!
}
else
{
statusBarItem.image = NSImage(named: "Loading-8")!
}
} // runTimedCode
func myMenuItem(_ string: String, url: String?, key: String, newItem: inout NSMenuItem)
{
let defaults = UserDefaults.standard
let attributedTitle: NSMutableAttributedString
if (defaults.string(forKey: "fontRedText") == nil)
{
modalDisplay.setFont("font")
modalDisplay.initPrefs()
}
let m = NumberFormatter().number(from: defaults.string(forKey: "fontsize")!)!
if (url == nil)
{
newItem = NSMenuItem(title: "", action: nil, keyEquivalent: key)
}
else
{
newItem = NSMenuItem(title: "", action: Selector(url!), keyEquivalent: key)
}
if (defaults.string(forKey: "fontDefault") == "1")
{
attributedTitle = NSMutableAttributedString(attributedString: NSMutableAttributedString(string:
string,
attributes:[NSAttributedString.Key.font : NSFont.systemFont(ofSize: CGFloat(truncating: m))]))
}
else
{
var textColor = NSColor()
if #available(iOS 10, *)
{
ErrorLog(String(format:"iOS 10", self.appName))
textColor = NSColor(red: CGFloat(Float(defaults.string(forKey: "fontRedText")!)!)/255,
green: CGFloat(Float(defaults.string(forKey: "fontGreenText")!)!)/255,
blue: CGFloat(Float(defaults.string(forKey: "fontBlueText")!)!)/255, alpha: 1.0)
}
else
{
ErrorLog(String(format:"iOS 9", self.appName))
textColor = NSColor(red: CGFloat(Float(defaults.string(forKey: "fontRedText")!)!),
green: CGFloat(Float(defaults.string(forKey: "fontGreenText")!)!),
blue: CGFloat(Float(defaults.string(forKey: "fontBlueText")!)!),
alpha: 1.0)
}
if (defaults.string(forKey: "fontTransparency")! == "1")
{
attributedTitle = NSMutableAttributedString(attributedString: NSMutableAttributedString(string:
string,
attributes:[NSAttributedString.Key.font : NSFont(name: defaults.string(forKey: "font")!, size: CGFloat(truncating: m))!,
NSAttributedString.Key.foregroundColor : textColor]))
}
else
{
var backgroundColor = NSColor()
if #available(iOS 10, *)
{
backgroundColor = NSColor(
red: CGFloat(Float(defaults.string(forKey: "fontRedBackground")!)!)/255,
green: CGFloat(Float(defaults.string(forKey: "fontGreenBackground")!)!)/255,
blue: CGFloat(Float(defaults.string(forKey: "fontBlueBackground")!)!)/255, alpha: 1.0)
}
else
{
backgroundColor = NSColor(
red: CGFloat(Float(defaults.string(forKey: "fontRedBackground")!)!),
green: CGFloat(Float(defaults.string(forKey: "fontGreenBackground")!)!),
blue: CGFloat(Float(defaults.string(forKey: "fontBlueBackground")!)!), alpha: 1.0)
}
attributedTitle = NSMutableAttributedString(attributedString: NSMutableAttributedString(string:
string,
attributes:[NSAttributedString.Key.font : NSFont(name: defaults.string(forKey: "font")!, size: CGFloat(truncating: m))!,
NSAttributedString.Key.foregroundColor : textColor,
NSAttributedString.Key.backgroundColor : backgroundColor]))
}
}
newItem.attributedTitle = attributedTitle
newItem.target=self
} // myMenuItem
func addControlOptions()
{
var controlsMenu = NSMenu()
var newItem = NSMenuItem()
if ((defaults.string(forKey: "controlsInSubmenu") == nil) || (defaults.string(forKey: "controlsInSubmenu")! == "1"))
{
myMenuItem(localizedString(forKey: "Controls_"), url: nil, key: "", newItem: &newItem)
menu.addItem(newItem)
menu.setSubmenu(controlsMenu, for: newItem)
}
else
{
controlsMenu = menu
}
myMenuItem(localizedString(forKey: "Refresh_"), url: "weatherRefresh:", key: "r", newItem: &newItem)
controlsMenu.addItem(newItem)
myMenuItem(localizedString(forKey: "Preferences_"), url: "preferences:", key: ",", newItem: &newItem)
controlsMenu.addItem(newItem)
// https://gist.github.com/ericdke/75a42dc8d4c5f61df7d9
myMenuItem(localizedString(forKey: "Relaunch_"), url: "Relaunch:", key: "`", newItem: &newItem)
controlsMenu.addItem(newItem)
myMenuItem(localizedString(forKey: "Quit_"), url: "terminate:", key: "q", newItem: &newItem)
newItem.target=nil
controlsMenu.addItem(newItem)
} // addControlOptions
func initWeatherFields(weatherFields: inout WeatherFields)
{
weatherFields.title1 = ""
weatherFields.date = ""
weatherFields.latitude = ""
weatherFields.longitude = ""
weatherFields.windDirection = ""
weatherFields.windSpeed = ""
weatherFields.windGust = ""
weatherFields.humidity = ""
weatherFields.pressure = ""
weatherFields.visibility = ""
weatherFields.UVIndex = ""
weatherFields.sunrise = ""
weatherFields.sunset = ""
weatherFields.currentCode = ""
weatherFields.currentTemp = ""
weatherFields.currentConditions = ""
weatherFields.weatherTag = ""