Debian Codegraph @

src/systeminfo/mac/qdeviceinfo_mac.mm

raw
1 /****************************************************************************
2 **
3 ** Copyright (C) 2018 The Qt Company Ltd and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtSystems module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 3 requirements
23 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24 **
25 ** GNU General Public License Usage
26 ** Alternatively, this file may be used under the terms of the GNU
27 ** General Public License version 2.0 or (at your option) the GNU General
28 ** Public license version 3 or any later version approved by the KDE Free
29 ** Qt Foundation. The licenses are as published by the Free Software
30 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31 ** included in the packaging of this file. Please review the following
32 ** information to ensure the GNU General Public License requirements will
33 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34 ** https://www.gnu.org/licenses/gpl-3.0.html.
35 **
36 ** $QT_END_LICENSE$
37 **
38 ****************************************************************************/
39
40 #include "qdeviceinfo_mac_p.h"
41
42 #include <QDebug>
43 #include <QSettings>
44 #include <QCryptographicHash>
45 #include <QtCore/private/qcore_mac_p.h>
46 #include <QSysInfo>
47
48 #include <CoreLocation/CLLocation.h>
49 #include <CoreLocation/CLLocationManager.h>
50 #include <ScreenSaver/ScreenSaverDefaults.h>
51 #include <CoreWLAN/CoreWLAN.h>
52 #include <CoreServices/CoreServices.h>
53 #include <CoreFoundation/CFNotificationCenter.h>
54 #include <IOBluetooth/IOBluetooth.h>
55 #if defined(slots)
56 #undef slots
57 #endif
58 #include <QTKit/QTKit.h>
59 #include <IOKit/pwr_mgt/IOPM.h>
60 #include <IOKit/pwr_mgt/IOPMLib.h>
61
62 #include <CoreFoundation/CFDictionary.h>
63
64 #include <sys/types.h>
65 #include <sys/sysctl.h>
66 #include <QMetaType>
67
68 bool hasIOServiceMatching(const QString &classstr)
69 {
70 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
71 io_iterator_t ioIterator = NULL;
72 IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceNameMatching(classstr.toLatin1()), &ioIterator);
73 if (ioIterator) {
74 [pool drain];
75 return true;
76 }
77 [pool drain];
78 return false;
79 }
80 QT_BEGIN_NAMESPACE
81
82 QDeviceInfoPrivate::QDeviceInfoPrivate(QDeviceInfo *parent)
83 : QObject(parent)
84 , q_ptr(parent)
85 ,btThread(0)
86 {
87 }
88
89 QDeviceInfoPrivate::~QDeviceInfoPrivate()
90 {
91 if (btThread->isRunning())
92 btThread->stop();
93 }
94
95 bool QDeviceInfoPrivate::hasFeature(QDeviceInfo::Feature feature)
96 {
97 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
98 bool featureSupported = false;
99 switch (feature) {
100 case QDeviceInfo::BluetoothFeature:
101 {
102 IOBluetoothHostController* controller = [IOBluetoothHostController defaultController];
103 if (controller != NULL) {
104 featureSupported = true;
105 }
106 }
107 break;
108 case QDeviceInfo::CameraFeature:
109 {
110 NSArray * videoDevices;
111 videoDevices = [[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeVideo] arrayByAddingObjectsFromArray:[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeMuxed]];
112 if ([videoDevices count] > 0) {
113 featureSupported = true;
114 }
115 }
116 break;
117 case QDeviceInfo::FmRadioFeature:
118 case QDeviceInfo::FmTransmitterFeature:
119 break;
120 case QDeviceInfo::InfraredFeature:
121 {
122 if (hasIOServiceMatching("AppleIRController")) {
123 featureSupported = true;
124 }
125 }
126 break;
127 case QDeviceInfo::LedFeature:
128 {
129 //kHIDPage_LEDs
130 }
131 break;
132 case QDeviceInfo::MemoryCardFeature:
133 {
134 // IOSCSIPeripheralDeviceType0E
135 if (hasIOServiceMatching("IOUSBMassStorageClass")) {
136 featureSupported = true;
137 }
138 }
139 break;
140 case QDeviceInfo::UsbFeature:
141 {
142 if (hasIOServiceMatching("AppleUSBOHCI")) {
143 featureSupported = true;
144 }
145 if (hasIOServiceMatching("AppleUSBEHCI")) {
146 featureSupported = true;
147 }
148 }
149 break;
150 case QDeviceInfo::VibrationFeature:
151 {
152 }
153 break;
154 case QDeviceInfo::WlanFeature:
155 {
156 NSArray *wifiInterfaces = [CWInterface supportedInterfaces];
157 if (wifiInterfaces || wifiInterfaces.count > 0)
158 featureSupported = true;
159 }
160 break;
161 case QDeviceInfo::SimFeature:
162 {
163 }
164 break;
165 case QDeviceInfo::PositioningFeature:
166 {
167 if ([CLLocationManager locationServicesEnabled]) {
168 featureSupported = true;
169 }
170 }
171 break;
172 case QDeviceInfo::VideoOutFeature:
173 {
174 ComponentDescription description = {'vout', 0, 0, 0L, 1L << 0};
175 if ( ::CountComponents(&description) > 0) {
176 featureSupported = true;
177 }
178 }
179 break;
180 case QDeviceInfo::HapticsFeature:
181 case QDeviceInfo::NfcFeature:
182 break;
183 default:
184 featureSupported = false;
185 break;
186 };
187 [pool drain];
188 return featureSupported;
189 }
190
191 int QDeviceInfoPrivate::imeiCount()
192 {
193 return -1;
194 }
195
196 QDeviceInfo::LockTypeFlags QDeviceInfoPrivate::activatedLocks()
197 {
198 // QSettings seems to not work on mac.
199 // FIXME
200 // // find out if auto login is being used.
201 // QSettings loginSettings("/Library/Preferences/com.apple.loginwindow.plist", QSettings::NativeFormat);
202 // QString autologinname = loginSettings.value("autoLoginUser").toString();
203
204 // QSettings zwoptexList("/Library/Preferences/com.apple.screensaver.plist",QSettings::NativeFormat);
205 // QStringList keys = zwoptexList.allKeys();
206 // qDebug() << "keys" << keys;
207 // for (int i = 0; i < keys.size(); i++) {
208 // QString tempString = keys.at(i);
209 // qDebug() << tempString;
210 // }
211
212 //// find out if locked screensaver is used.
213 // int passWordProtected = 0;
214 ////#if defined(QT_ARCH_X86_64) && !defined(MAC_SDK_10_6)
215 // QSettings screensaverSettings("/Library/Preferences/com.apple.screensaver.plist", QSettings::NativeFormat);
216 // passWordProtected = screensaverSettings.value("askForPassword").toInt();
217
218 //// ScreenSaverDefaults *ssDefaults;
219 //// ssDefaults = [ScreenSaverDefaults defaultsForModuleWithName:@"com.apple.screensaver"];
220 //// passWordProtected = [ssDefaults integerForKey:@"askForPassword"];
221 ////#endif
222 // qDebug() <<passWordProtected;
223 // if (autologinname.isEmpty() || passWordProtected == 1) {
224 return QDeviceInfo::UnknownLock;
225 // }
226
227 // return QDeviceInfo::NoLock;
228 }
229
230 QDeviceInfo::LockTypeFlags QDeviceInfoPrivate::enabledLocks()
231 {
232 return QDeviceInfo::UnknownLock;
233 }
234
235 QDeviceInfo::ThermalState QDeviceInfoPrivate::thermalState()
236 {
237 // TODO fixme
238 // int value = 0;
239 // int it = 0;
240 // kern_return_t kr;
241 // io_iterator_t hwSensors;
242 // io_service_t hwSensorService;
243 // CFMutableDictionaryRef sensorDict;
244
245 // kr = IOServiceGetMatchingServices(kIOMasterPortDefault,
246 // IOServiceNameMatching("IOHWSensor"), &hwSensors);
247
248 // while ((hwSensorService = IOIteratorNext(hwSensors))) {
249 // kr = IORegistryEntryCreateCFProperties(hwSensorService, &sensorDict, kCFAllocatorDefault, kNilOptions);
250 // if (kr == KERN_SUCCESS) {
251 // SInt32 currentValue;
252 // CFNumberRef sensorValue;
253 // CFStringRef sensorType;
254 // if (CFStringCompare(sensorType, CFSTR("temperature"), 0) != kCFCompareEqualTo)
255 // continue;
256
257 // sensorValue = (const __CFNumber *)CFDictionaryGetValue((CFDictionaryRef)sensorDict,
258 // CFSTR("current-value"));
259
260 // (void)CFNumberGetValue(sensorValue, kCFNumberSInt32Type,
261 // (void *)&currentValue);
262 // value += currentValue;
263 // it++;
264 // }
265 // CFRelease(sensorDict);
266 // IOObjectRelease(hwSensorService);
267 // }
268
269 // IOObjectRelease(hwSensors);
270
271 // qDebug() << "average value" << (value / it) / 65536;
272
273 // IOServiceMatching("IOHWSensor");
274 // static io_connect_t dataPort = 0;
275
276 // kern_return_t kreturn;
277 // io_service_t ioService;
278
279 // ioService = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOHWSensor"));
280 // if (!ioService) {
281 // qDebug() << "IOHWSensor error";
282 // return QDeviceInfo::UnknownThermal;
283 // }
284
285 // qDebug() << ioService->getProperty("current-value");;
286
287 // kreturn = IOServiceOpen(ioService, mach_task_self(), 0, &dataPort);
288 // IOObjectRelease(ioService);
289 // if (kreturn != KERN_SUCCESS) {
290 // qDebug() << "IOServiceOpen "<< kreturn;
291 // return QDeviceInfo::UnknownThermal;
292 // }
293
294 // uint64_t inputValues[1] = {0};
295
296 // uint32_t outputCount = 1;
297 // uint64_t outputValues[1];
298
299 // kreturn = IOConnectCallScalarMethod(dataPort,1,inputValues,1,outputValues,&outputCount);
300 // if (kreturn != KERN_SUCCESS) {
301 // qDebug() << "keyboard error";
302 // return QDeviceInfo::UnknownThermal;
303 // }
304
305 // uint32_t getlevel = 0;
306 // CFStringRef thermal_key = NULL;
307 // IOReturn ret = kIOReturnError;
308
309 // ret = IOPMGetThermalWarningLevel(&getlevel);
310 // if ((kIOReturnSuccess == ret)) {
311 // qDebug() << getlevel;
312 // }
313 return QDeviceInfo::UnknownThermal;
314 }
315
316 QString QDeviceInfoPrivate::imei(int)
317 {
318 return QString();
319 }
320
321 QString QDeviceInfoPrivate::manufacturer()
322 {
323 return QLatin1String("Apple"); //pretty sure we can hardcode this one
324 }
325
326 QString QDeviceInfoPrivate::model()
327 {
328 char modelBuffer[256];
329 QString model;
330 size_t sz = sizeof(modelBuffer);
331 if (0 == sysctlbyname("hw.model", modelBuffer, &sz, NULL, 0)) {
332 model = QLatin1String(modelBuffer);
333 }
334 return model;
335 }
336
337 QString QDeviceInfoPrivate::productName()
338 {
339 char modelBuffer[256];
340 QString model;
341 size_t sz = sizeof(modelBuffer);
342 if (0 == sysctlbyname("hw.model", modelBuffer, &sz, NULL, 0)) {
343 model = QLatin1String(modelBuffer);
344 }
345 if (model.count() > 3)
346 model = model.left(model.count() - 3);
347 bool ok;
348 model.right(1).toInt(&ok);
349 if (ok)
350 model.chop(1);
351 return model;
352 }
353
354 QString QDeviceInfoPrivate::uniqueDeviceID()
355 {
356 CFStringRef uuidKey = CFSTR(kIOPlatformUUIDKey);
357 io_service_t ioService = IOServiceGetMatchingService(kIOMasterPortDefault,
358 IOServiceMatching("IOPlatformExpertDevice"));
359 QCryptographicHash hash(QCryptographicHash::Sha1);
360 if (ioService) {
361 CFTypeRef cfStringKey = IORegistryEntryCreateCFProperty(ioService, uuidKey, kCFAllocatorDefault, 0);
362
363 hash.addData(QCFString::toQString((const __CFString*)cfStringKey).toLocal8Bit());
364 return QString::fromLatin1(hash.result().toHex());
365 }
366 hash.addData(QString::number(gethostid()).toLocal8Bit());
367 return QString::fromLatin1(hash.result().toHex());
368 }
369
370 QString QDeviceInfoPrivate::version(QDeviceInfo::Version type)
371 {
372 switch (type) {
373 case QDeviceInfo::Os:
374 {
375 // QSettings versionSettings("/System/Library/CoreServices/SystemVersion.plist", QSettings::NativeFormat);
376 // return versionSettings.value("ProductVersion").toString();
377 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
378 QString ver = QCFString::toQString([[NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"] objectForKey:@"ProductVersion"]);
379 [pool drain];
380 return ver;
381 }
382 break;
383 case QDeviceInfo::Firmware:
384 {
385 char firmwareBuffer[256];
386 QString firmware;
387 size_t sz = sizeof(firmwareBuffer);
388 if (0 == sysctlbyname("kern.version", firmwareBuffer, &sz, NULL, 0)) {
389 firmware = QLatin1String(firmwareBuffer);
390 }
391 return firmware;
392 }
393 break;
394 };
395 return QString();
396 }
397
398 QString QDeviceInfoPrivate::operatingSystemName()
399 {
400 const QString ver = version(QDeviceInfo::Os);
401
402 if (ver.left(4) == QStringLiteral("10.6"))
403 return QStringLiteral("Snow Leopard");
404 if (ver.left(4) == QStringLiteral("10.7"))
405 return QStringLiteral("Lion");
406 if (ver.left(4) == QStringLiteral("10.8"))
407 return QStringLiteral("Mountain Lion");
408 if (ver.left(4) == QStringLiteral("10.9"))
409 return QStringLiteral("Mavericks");
410 return ver;
411 }
412
413 QString QDeviceInfoPrivate::boardName()
414 {
415 // I suspect boardname and product are the same for macs.
416 return model();
417 }
418
419 static bool isBtPowerOn()
420 {
421 CFMutableDictionaryRef matching = NULL;
422 CFMutableDictionaryRef btDictionary = NULL;
423 io_registry_entry_t entry = 0;
424 matching = IOServiceMatching("IOBluetoothHCIController");
425 entry = IOServiceGetMatchingService(kIOMasterPortDefault,matching);
426 IORegistryEntryCreateCFProperties(entry, &btDictionary,NULL,0);
427 bool powerOn = false;
428
429 if ([[(NSDictionary*)btDictionary objectForKey:@"HCIControllerPowerIsOn"] boolValue]) {
430 powerOn = true;
431 }
432 CFRelease(btDictionary);
433 return powerOn;
434 }
435
436 bool QDeviceInfoPrivate::currentBluetoothPowerState()
437 {
438 if (isBtPowerOn())
439 return true;
440 return false;
441 }
442
443 void QDeviceInfoPrivate::connectNotify(const QMetaMethod &signal)
444 {
445 static const QMetaMethod bluetoothStateChanged = QMetaMethod::fromSignal(&QDeviceInfoPrivate::bluetoothStateChanged);
446 if (signal == bluetoothStateChanged) {
447 if (!btThread) {
448 btThread = new QBluetoothListenerThread();
449 btThreadOk = true;
450 connect(btThread,SIGNAL(bluetoothPower(bool)), this, SIGNAL(bluetoothStateChanged(bool)),Qt::UniqueConnection);
451 }
452 btThread->start();
453 }
454 }
455
456 void QDeviceInfoPrivate::disconnectNotify(const QMetaMethod &signal)
457 {
458 static const QMetaMethod bluetoothStateChanged = QMetaMethod::fromSignal(&QDeviceInfoPrivate::bluetoothStateChanged);
459 if (signal == bluetoothStateChanged) {
460 btThread->stop();
461 }
462 }
463
464 void btPowerStateChange(void *ref, io_service_t /*service*/, natural_t messageType, void */*info*/)
465 {
466 QBluetoothListenerThread * thread = reinterpret_cast< QBluetoothListenerThread *>(ref);
467 switch (messageType) {
468 case 3758227457:
469 case kIOMessageDeviceWillPowerOff:
470 {
471 thread->emitBtPower(false);
472 }
473 break;
474 case 3758227458:
475 case kIOMessageDeviceHasPoweredOn:
476 {
477 thread->emitBtPower(true);
478 }
479 break;
480 }
481 }
482
483 QBluetoothListenerThread::QBluetoothListenerThread(QObject *parent)
484 :QThread(parent)
485 {
486 mutex.lock();
487 keepRunning = true;
488 mutex.unlock();
489 }
490
491 QBluetoothListenerThread::~QBluetoothListenerThread()
492 {
493 }
494
495 void QBluetoothListenerThread::stop()
496 {
497 mutex.lock();
498 keepRunning = false;
499 mutex.unlock();
500 wait();
501 }
502
503 void QBluetoothListenerThread::run()
504 {
505 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
506
507 io_object_t notifyObject;
508 io_service_t bluetoothservice;
509
510 io_iterator_t ioIterator;
511 mach_port_t masterPort;
512 CFMutableDictionaryRef serviceMatchDict;
513
514 if (0 != IOMasterPort(MACH_PORT_NULL, &masterPort)) {
515 qDebug() << "IOMasterPort failed";
516 }
517
518 serviceMatchDict = IOServiceMatching("IOBluetoothHCIController");
519 if (NULL == serviceMatchDict) {
520 qDebug() << "IOServiceMatching failed";
521 }
522
523 if (0 != IOServiceGetMatchingServices(masterPort, serviceMatchDict, &ioIterator)) {
524 qDebug() << "IOServiceGetMatchingServices failed";
525 }
526
527 IOReturn ret;
528
529 bluetoothservice = IOIteratorNext(ioIterator);
530 if (0 == bluetoothservice) {
531 IOObjectRelease(ioIterator);
532 qDebug() << "IOIteratorNext failed";
533 }
534 IOObjectRelease(ioIterator);
535
536 port = IONotificationPortCreate(masterPort);
537 if (0 == port) {
538 qDebug() << "IONotificationPortCreate failed";
539 }
540
541 ret = IOServiceAddInterestNotification(port, bluetoothservice,
542 kIOGeneralInterest, btPowerStateChange,
543 this, &notifyObject);
544 if (ret != kIOReturnSuccess) {
545 qDebug() << "IOServiceAddInterestNotification failed";
546 return;
547 }
548
549 rl = CFRunLoopGetCurrent();
550 rls = IONotificationPortGetRunLoopSource(port);
551
552 CFRunLoopAddSource(rl,
553 rls,
554 kCFRunLoopDefaultMode);
555 SInt32 result;
556 while (keepRunning &&
557 (result = CFRunLoopRunInMode(kCFRunLoopDefaultMode ,1, NO))) {
558 }
559
560 CFRunLoopStop(rl);
561
562 IOObjectRelease(bluetoothservice);
563 CFRunLoopRemoveSource(rl,
564 rls,
565 kCFRunLoopDefaultMode);
566 IONotificationPortDestroy(port);
567 [pool release];
568 }
569
570 void QBluetoothListenerThread::setupConnectNotify()
571 {
572 //btConnListener = [[QtBtConnectListener alloc] init];
573 }
574
575 void QBluetoothListenerThread::emitBtPower(bool b)
576 {
577 Q_EMIT bluetoothPower(b);
578 }
579
580
581 QT_END_NAMESPACE