/
XBMCApp.cpp
650 lines (560 loc) · 17.3 KB
/
XBMCApp.cpp
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
/*
* Copyright (C) 2012-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <sstream>
#include <unistd.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <string.h>
#include <android/native_window.h>
#include <android/configuration.h>
#include <jni.h>
#include "XBMCApp.h"
#include "input/MouseStat.h"
#include "input/XBMC_keysym.h"
#include "guilib/Key.h"
#include "windowing/XBMC_events.h"
#include <android/log.h>
#include "Application.h"
#include "settings/AdvancedSettings.h"
#include "xbmc.h"
#include "windowing/WinEvents.h"
#include "guilib/GUIWindowManager.h"
#include "utils/log.h"
#include "ApplicationMessenger.h"
#include "utils/StringUtils.h"
#include "AppParamParser.h"
#include "XbmcContext.h"
#include <android/bitmap.h>
#include "android/jni/JNIThreading.h"
#include "android/jni/BroadcastReceiver.h"
#include "android/jni/Intent.h"
#include "android/jni/PackageManager.h"
#include "android/jni/Context.h"
#include "android/jni/AudioManager.h"
#include "android/jni/PowerManager.h"
#include "android/jni/WakeLock.h"
#include "android/jni/Environment.h"
#include "android/jni/File.h"
#include "android/jni/IntentFilter.h"
#include "android/jni/NetworkInfo.h"
#include "android/jni/ConnectivityManager.h"
#include "android/jni/System.h"
#include "android/jni/ApplicationInfo.h"
#include "android/jni/StatFs.h"
#include "android/jni/BitmapDrawable.h"
#include "android/jni/Bitmap.h"
#include "android/jni/CharSequence.h"
#include "android/jni/URI.h"
#include "android/jni/Cursor.h"
#include "android/jni/ContentResolver.h"
#include "android/jni/MediaStore.h"
#define GIGABYTES 1073741824
using namespace std;
template<class T, void(T::*fn)()>
void* thread_run(void* obj)
{
(static_cast<T*>(obj)->*fn)();
return NULL;
}
CEvent CXBMCApp::m_windowCreated;
ANativeActivity *CXBMCApp::m_activity = NULL;
ANativeWindow* CXBMCApp::m_window = NULL;
int CXBMCApp::m_batteryLevel = 0;
int CXBMCApp::m_initialVolume = 0;
CXBMCApp::CXBMCApp(ANativeActivity* nativeActivity)
: CJNIContext(nativeActivity)
, CJNIBroadcastReceiver("org/xbmc/xbmc/XBMCBroadcastReceiver")
, m_wakeLock(NULL)
{
m_activity = nativeActivity;
m_firstrun = true;
m_exiting=false;
if (m_activity == NULL)
{
android_printf("CXBMCApp: invalid ANativeActivity instance");
exit(1);
return;
}
}
CXBMCApp::~CXBMCApp()
{
}
void CXBMCApp::onStart()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
if (!m_firstrun)
{
android_printf("%s: Already running, ignoring request to start", __PRETTY_FUNCTION__);
return;
}
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&m_thread, &attr, thread_run<CXBMCApp, &CXBMCApp::run>, this);
pthread_attr_destroy(&attr);
}
void CXBMCApp::onResume()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
CJNIIntentFilter batteryFilter;
batteryFilter.addAction("android.intent.action.BATTERY_CHANGED");
registerReceiver(*this, batteryFilter);
}
void CXBMCApp::onPause()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
// Restore volume
SetSystemVolume(m_initialVolume);
unregisterReceiver(*this);
}
void CXBMCApp::onStop()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
}
void CXBMCApp::onDestroy()
{
android_printf("%s", __PRETTY_FUNCTION__);
// If android is forcing us to stop, ask XBMC to exit then wait until it's
// been destroyed.
if (!m_exiting)
{
XBMC_Stop();
pthread_join(m_thread, NULL);
android_printf(" => XBMC finished");
}
if (m_wakeLock != NULL && m_activity != NULL)
{
delete m_wakeLock;
m_wakeLock = NULL;
}
}
void CXBMCApp::onSaveState(void **data, size_t *size)
{
android_printf("%s: ", __PRETTY_FUNCTION__);
// no need to save anything as XBMC is running in its own thread
}
void CXBMCApp::onConfigurationChanged()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
// ignore any configuration changes like screen rotation etc
}
void CXBMCApp::onLowMemory()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
// can't do much as we don't want to close completely
}
void CXBMCApp::onCreateWindow(ANativeWindow* window)
{
android_printf("%s: ", __PRETTY_FUNCTION__);
if (window == NULL)
{
android_printf(" => invalid ANativeWindow object");
return;
}
m_window = window;
m_windowCreated.Set();
if (getWakeLock() && m_wakeLock)
m_wakeLock->acquire();
if(!m_firstrun)
{
XBMC_SetupDisplay();
XBMC_Pause(false);
}
}
void CXBMCApp::onResizeWindow()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
m_window=NULL;
m_windowCreated.Reset();
// no need to do anything because we are fixed in fullscreen landscape mode
}
void CXBMCApp::onDestroyWindow()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
// If we have exited XBMC, it no longer exists.
if (!m_exiting)
{
XBMC_DestroyDisplay();
XBMC_Pause(true);
}
if (m_wakeLock)
m_wakeLock->release();
}
void CXBMCApp::onGainFocus()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
}
void CXBMCApp::onLostFocus()
{
android_printf("%s: ", __PRETTY_FUNCTION__);
}
bool CXBMCApp::getWakeLock()
{
if (m_wakeLock)
return true;
m_wakeLock = new CJNIWakeLock(CJNIPowerManager(getSystemService("power")).newWakeLock("org.xbmc.xbmc"));
return true;
}
void CXBMCApp::run()
{
int status = 0;
SetupEnv();
XBMC::Context context;
m_initialVolume = GetSystemVolume();
CJNIIntent startIntent = getIntent();
android_printf("XBMC Started with action: %s\n",startIntent.getAction().c_str());
std::string filenameToPlay = GetFilenameFromIntent(startIntent);
if (!filenameToPlay.empty())
{
int argc = 2;
const char** argv = (const char**) malloc(argc*sizeof(char*));
std::string exe_name("XBMC");
argv[0] = exe_name.c_str();
argv[1] = filenameToPlay.c_str();
CAppParamParser appParamParser;
appParamParser.Parse((const char **)argv, argc);
free(argv);
}
m_firstrun=false;
android_printf(" => running XBMC_Run...");
try
{
status = XBMC_Run(true);
android_printf(" => XBMC_Run finished with %d", status);
}
catch(...)
{
android_printf("ERROR: Exception caught on main loop. Exiting");
}
// If we are have not been force by Android to exit, notify its finish routine.
// This will cause android to run through its teardown events, it calls:
// onPause(), onLostFocus(), onDestroyWindow(), onStop(), onDestroy().
ANativeActivity_finish(m_activity);
m_exiting=true;
}
void CXBMCApp::XBMC_Pause(bool pause)
{
android_printf("XBMC_Pause(%s)", pause ? "true" : "false");
// Only send the PAUSE action if we are pausing XBMC and something is currently playing
if (pause && g_application.m_pPlayer->IsPlaying() && !g_application.m_pPlayer->IsPaused())
CApplicationMessenger::Get().SendAction(CAction(ACTION_PAUSE), WINDOW_INVALID, true);
}
void CXBMCApp::XBMC_Stop()
{
CApplicationMessenger::Get().Quit();
}
bool CXBMCApp::XBMC_SetupDisplay()
{
android_printf("XBMC_SetupDisplay()");
return CApplicationMessenger::Get().SetupDisplay();
}
bool CXBMCApp::XBMC_DestroyDisplay()
{
android_printf("XBMC_DestroyDisplay()");
return CApplicationMessenger::Get().DestroyDisplay();
}
int CXBMCApp::SetBuffersGeometry(int width, int height, int format)
{
return ANativeWindow_setBuffersGeometry(m_window, width, height, format);
}
int CXBMCApp::android_printf(const char *format, ...)
{
// For use before CLog is setup by XBMC_Run()
va_list args;
va_start(args, format);
int result = __android_log_vprint(ANDROID_LOG_VERBOSE, "XBMC", format, args);
va_end(args);
return result;
}
int CXBMCApp::GetDPI()
{
if (m_activity == NULL || m_activity->assetManager == NULL)
return 0;
// grab DPI from the current configuration - this is approximate
// but should be close enough for what we need
AConfiguration *config = AConfiguration_new();
AConfiguration_fromAssetManager(config, m_activity->assetManager);
int dpi = AConfiguration_getDensity(config);
AConfiguration_delete(config);
return dpi;
}
bool CXBMCApp::ListApplications(vector<androidPackage> *applications)
{
CJNIList<CJNIApplicationInfo> packageList = GetPackageManager().getInstalledApplications(CJNIPackageManager::GET_ACTIVITIES);
int numPackages = packageList.size();
for (int i = 0; i < numPackages; i++)
{
androidPackage newPackage;
newPackage.packageName = packageList.get(i).packageName;
newPackage.packageLabel = GetPackageManager().getApplicationLabel(packageList.get(i)).toString();
CJNIIntent intent = GetPackageManager().getLaunchIntentForPackage(newPackage.packageName);
if (!intent || !intent.hasCategory("android.intent.category.LAUNCHER"))
continue;
applications->push_back(newPackage);
}
return true;
}
bool CXBMCApp::GetIconSize(const string &packageName, int *width, int *height)
{
JNIEnv* env = xbmc_jnienv();
AndroidBitmapInfo info;
CJNIBitmapDrawable drawable = (CJNIBitmapDrawable)GetPackageManager().getApplicationIcon(packageName);
CJNIBitmap icon(drawable.getBitmap());
AndroidBitmap_getInfo(env, icon.get_raw(), &info);
*width = info.width;
*height = info.height;
return true;
}
bool CXBMCApp::GetIcon(const string &packageName, void* buffer, unsigned int bufSize)
{
void *bitmapBuf = NULL;
JNIEnv* env = xbmc_jnienv();
CJNIBitmapDrawable drawable = (CJNIBitmapDrawable)GetPackageManager().getApplicationIcon(packageName);
CJNIBitmap bitmap(drawable.getBitmap());
AndroidBitmap_lockPixels(env, bitmap.get_raw(), &bitmapBuf);
if (bitmapBuf)
{
memcpy(buffer, bitmapBuf, bufSize);
AndroidBitmap_unlockPixels(env, bitmap.get_raw());
return true;
}
return false;
}
bool CXBMCApp::HasLaunchIntent(const string &package)
{
return GetPackageManager().getLaunchIntentForPackage(package) != NULL;
}
// Note intent, dataType, dataURI all default to ""
bool CXBMCApp::StartActivity(const string &package, const string &intent, const string &dataType, const string &dataURI)
{
CJNIIntent newIntent = intent.empty() ?
GetPackageManager().getLaunchIntentForPackage(package) :
CJNIIntent(intent);
if (!newIntent)
return false;
if (!dataURI.empty())
{
CJNIURI jniURI = CJNIURI::parse(dataURI);
if (!jniURI)
return false;
newIntent.setDataAndType(jniURI, dataType);
}
newIntent.setPackage(package);
startActivity(newIntent);
if (xbmc_jnienv()->ExceptionOccurred())
{
CLog::Log(LOGERROR, "CXBMCApp::StartActivity - ExceptionOccurred launching %s", package.c_str());
xbmc_jnienv()->ExceptionClear();
return false;
}
return true;
}
int CXBMCApp::GetBatteryLevel()
{
return m_batteryLevel;
}
bool CXBMCApp::GetExternalStorage(std::string &path, const std::string &type /* = "" */)
{
std::string sType;
std::string mountedState;
bool mounted = false;
if(type == "files" || type.empty())
{
CJNIFile external = CJNIEnvironment::getExternalStorageDirectory();
if (external)
path = external.getAbsolutePath();
}
else
{
if (type == "music")
sType = "Music"; // Environment.DIRECTORY_MUSIC
else if (type == "videos")
sType = "Movies"; // Environment.DIRECTORY_MOVIES
else if (type == "pictures")
sType = "Pictures"; // Environment.DIRECTORY_PICTURES
else if (type == "photos")
sType = "DCIM"; // Environment.DIRECTORY_DCIM
else if (type == "downloads")
sType = "Download"; // Environment.DIRECTORY_DOWNLOADS
if (!sType.empty())
{
CJNIFile external = CJNIEnvironment::getExternalStoragePublicDirectory(sType);
if (external)
path = external.getAbsolutePath();
}
}
mountedState = CJNIEnvironment::getExternalStorageState();
mounted = (mountedState == "mounted" || mountedState == "mounted_ro");
return mounted && !path.empty();
}
bool CXBMCApp::GetStorageUsage(const std::string &path, std::string &usage)
{
if (path.empty())
{
std::ostringstream fmt;
fmt.width(24); fmt << std::left << "Filesystem";
fmt.width(12); fmt << std::right << "Size";
fmt.width(12); fmt << "Used";
fmt.width(12); fmt << "Avail";
fmt.width(12); fmt << "Use %";
usage = fmt.str();
return false;
}
CJNIStatFs fileStat(path);
int blockSize = fileStat.getBlockSize();
int blockCount = fileStat.getBlockCount();
int freeBlocks = fileStat.getFreeBlocks();
if (blockSize <= 0 || blockCount <= 0 || freeBlocks < 0)
return false;
float totalSize = (float)blockSize * blockCount / GIGABYTES;
float freeSize = (float)blockSize * freeBlocks / GIGABYTES;
float usedSize = totalSize - freeSize;
float usedPercentage = usedSize / totalSize * 100;
std::ostringstream fmt;
fmt << std::fixed;
fmt.precision(1);
fmt.width(24); fmt << std::left << path;
fmt.width(12); fmt << std::right << totalSize << "G"; // size in GB
fmt.width(12); fmt << usedSize << "G"; // used in GB
fmt.width(12); fmt << freeSize << "G"; // free
fmt.precision(0);
fmt.width(12); fmt << usedPercentage << "%"; // percentage used
usage = fmt.str();
return true;
}
// Used in Application.cpp to figure out volume steps
int CXBMCApp::GetMaxSystemVolume()
{
JNIEnv* env = xbmc_jnienv();
static int maxVolume = -1;
if (maxVolume == -1)
{
maxVolume = GetMaxSystemVolume(env);
}
//android_printf("CXBMCApp::GetMaxSystemVolume: %i",maxVolume);
return maxVolume;
}
int CXBMCApp::GetMaxSystemVolume(JNIEnv *env)
{
CJNIAudioManager audioManager(getSystemService("audio"));
if (audioManager)
return audioManager.getStreamMaxVolume();
android_printf("CXBMCApp::SetSystemVolume: Could not get Audio Manager");
return 0;
}
int CXBMCApp::GetSystemVolume()
{
CJNIAudioManager audioManager(getSystemService("audio"));
if (audioManager)
return audioManager.getStreamVolume();
else
{
android_printf("CXBMCApp::GetSystemVolume: Could not get Audio Manager");
return 0;
}
}
void CXBMCApp::SetSystemVolume(int val)
{
CJNIAudioManager audioManager(getSystemService("audio"));
if (audioManager)
audioManager.setStreamVolume(val);
else
android_printf("CXBMCApp::SetSystemVolume: Could not get Audio Manager");
}
void CXBMCApp::SetSystemVolume(JNIEnv *env, float percent)
{
CJNIAudioManager audioManager(getSystemService("audio"));
int maxVolume = (int)(GetMaxSystemVolume() * percent);
if (audioManager)
audioManager.setStreamVolume(maxVolume);
else
android_printf("CXBMCApp::SetSystemVolume: Could not get Audio Manager");
}
void CXBMCApp::onReceive(CJNIIntent intent)
{
std::string action = intent.getAction();
android_printf("CXBMCApp::onReceive Got intent. Action: %s", action.c_str());
if (action == "android.intent.action.BATTERY_CHANGED")
m_batteryLevel = intent.getIntExtra("level",-1);
}
void CXBMCApp::onNewIntent(CJNIIntent intent)
{
std::string action = intent.getAction();
if (action == "android.intent.action.VIEW")
{
std::string playFile = GetFilenameFromIntent(intent);
CApplicationMessenger::Get().MediaPlay(playFile);
}
}
void CXBMCApp::SetupEnv()
{
setenv("XBMC_ANDROID_SYSTEM_LIBS", CJNISystem::getProperty("java.library.path").c_str(), 0);
setenv("XBMC_ANDROID_DATA", getApplicationInfo().dataDir.c_str(), 0);
setenv("XBMC_ANDROID_LIBS", getApplicationInfo().nativeLibraryDir.c_str(), 0);
setenv("XBMC_ANDROID_APK", getPackageResourcePath().c_str(), 0);
std::string cacheDir = getCacheDir().getAbsolutePath();
setenv("XBMC_BIN_HOME", (cacheDir + "/apk/assets").c_str(), 0);
setenv("XBMC_HOME", (cacheDir + "/apk/assets").c_str(), 0);
std::string externalDir;
CJNIFile androidPath = getExternalFilesDir("");
if (!androidPath)
androidPath = getDir("org.xbmc.xbmc", 1);
if (androidPath)
externalDir = androidPath.getAbsolutePath();
if (!externalDir.empty())
setenv("HOME", externalDir.c_str(), 0);
else
setenv("HOME", getenv("XBMC_TEMP"), 0);
}
std::string CXBMCApp::GetFilenameFromIntent(const CJNIIntent &intent)
{
std::string ret;
if (!intent)
return ret;
CJNIURI data = intent.getData();
if (!data)
return ret;
std::string scheme = data.getScheme();
StringUtils::ToLower(scheme);
if (scheme == "content")
{
std::vector<std::string> filePathColumn;
filePathColumn.push_back(CJNIMediaStoreMediaColumns::DATA);
CJNICursor cursor = getContentResolver().query(data, filePathColumn, std::string(), std::vector<std::string>(), std::string());
if(cursor.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
ret = cursor.getString(columnIndex);
}
cursor.close();
}
else if(scheme == "file")
ret = data.getPath();
else
ret = data.toString();
return ret;
}
const ANativeWindow** CXBMCApp::GetNativeWindow(int timeout)
{
if (m_window)
return (const ANativeWindow**)&m_window;
m_windowCreated.WaitMSec(timeout);
return (const ANativeWindow**)&m_window;
}