summaryrefslogtreecommitdiffstats
path: root/gui/action.cpp
blob: 36f400613f48133a0b725d25c65c1a5b4703a1f6 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
/*
	Copyright 2013 bigbiff/Dees_Troy TeamWin
	This file is part of TWRP/TeamWin Recovery Project.

	TWRP 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 3 of the License, or
	(at your option) any later version.

	TWRP 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 TWRP.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <dirent.h>

#include <string>
#include <sstream>
#include "../partitions.hpp"
#include "../twrp-functions.hpp"
#include "../openrecoveryscript.hpp"

#include "../adb_install.h"
#ifndef TW_NO_SCREEN_TIMEOUT
#include "blanktimer.hpp"
#endif
extern "C" {
#include "../twcommon.h"
#include "../minuitwrp/minui.h"
#include "../variables.h"
#include "../twinstall.h"
#include "cutils/properties.h"
#include "../minadbd/adb.h"

int TWinstall_zip(const char* path, int* wipe_cache);
void run_script(const char *str1, const char *str2, const char *str3, const char *str4, const char *str5, const char *str6, const char *str7, int request_confirm);
int gui_console_only();
int gui_start();
};

#include "rapidxml.hpp"
#include "objects.hpp"

#ifndef TW_NO_SCREEN_TIMEOUT
extern blanktimer blankTimer;
#endif

void curtainClose(void);

GUIAction::GUIAction(xml_node<>* node)
	: Conditional(node)
{
	xml_node<>* child;
	xml_node<>* actions;
	xml_attribute<>* attr;

	mKey = 0;

	if (!node)  return;

	// First, get the action
	actions = node->first_node("actions");
	if (actions)	child = actions->first_node("action");
	else			child = node->first_node("action");

	if (!child) return;

	while (child)
	{
		Action action;

		attr = child->first_attribute("function");
		if (!attr)  return;
	
		action.mFunction = attr->value();
		action.mArg = child->value();
		mActions.push_back(action);

		child = child->next_sibling("action");
	}

	// Now, let's get either the key or region
	child = node->first_node("touch");
	if (child)
	{
		attr = child->first_attribute("key");
		if (attr)
		{
			std::string key = attr->value();
	
			mKey = getKeyByName(key);
		}
		else
		{
			attr = child->first_attribute("x");
			if (!attr)  return;
			mActionX = atol(attr->value());
			attr = child->first_attribute("y");
			if (!attr)  return;
			mActionY = atol(attr->value());
			attr = child->first_attribute("w");
			if (!attr)  return;
			mActionW = atol(attr->value());
			attr = child->first_attribute("h");
			if (!attr)  return;
			mActionH = atol(attr->value());
		}
	}
}

int GUIAction::NotifyTouch(TOUCH_STATE state, int x, int y)
{
	if (state == TOUCH_RELEASE)
		doActions();

	return 0;
}

int GUIAction::NotifyKey(int key)
{
	if (!mKey || key != mKey)
		return 1;

	doActions();
	return 0;
}

int GUIAction::NotifyVarChange(std::string varName, std::string value)
{
	if (varName.empty() && !isConditionValid() && !mKey && !mActionW)
		doActions();

	// This handles notifying the condition system of page start
	if (varName.empty() && isConditionValid())
		NotifyPageSet();

	if ((varName.empty() || IsConditionVariable(varName)) && isConditionValid() && isConditionTrue())
		doActions();

	return 0;
}

void GUIAction::simulate_progress_bar(void)
{
	gui_print("Simulating actions...\n");
	for (int i = 0; i < 5; i++)
	{
		usleep(500000);
		DataManager::SetValue("ui_progress", i * 20);
	}
}

int GUIAction::flash_zip(std::string filename, std::string pageName, const int simulate, int* wipe_cache)
{
	int ret_val = 0;

	DataManager::SetValue("ui_progress", 0);

	if (filename.empty())
	{
		LOGERR("No file specified.\n");
		return -1;
	}

	// We're going to jump to this page first, like a loading page
	gui_changePage(pageName);

	int fd = -1;
	ZipArchive zip;

	if (!PartitionManager.Mount_By_Path(filename, true))
		return -1;

	if (mzOpenZipArchive(filename.c_str(), &zip))
	{
		LOGERR("Unable to open zip file.\n");
		return -1;
	}

	// Check the zip to see if it has a custom installer theme
	const ZipEntry* twrp = mzFindZipEntry(&zip, "META-INF/teamwin/twrp.zip");
	if (twrp != NULL)
	{
		unlink("/tmp/twrp.zip");
		fd = creat("/tmp/twrp.zip", 0666);
	}
	if (fd >= 0 && twrp != NULL &&
		mzExtractZipEntryToFile(&zip, twrp, fd) &&
		!PageManager::LoadPackage("install", "/tmp/twrp.zip", "main"))
	{
		mzCloseZipArchive(&zip);
		PageManager::SelectPackage("install");
		gui_changePage("main");
	}
	else
	{
		// In this case, we just use the default page
		mzCloseZipArchive(&zip);
		gui_changePage(pageName);
	}
	if (fd >= 0)
		close(fd);

	if (simulate) {
		simulate_progress_bar();
	} else {
		ret_val = TWinstall_zip(filename.c_str(), wipe_cache);

		// Now, check if we need to ensure TWRP remains installed...
		struct stat st;
		string result;
		if (stat("/sbin/installTwrp", &st) == 0)
		{
			DataManager::SetValue("tw_operation", "Configuring TWRP");
			DataManager::SetValue("tw_partition", "");
			gui_print("Configuring TWRP...\n");
			if (TWFunc::Exec_Cmd("/sbin/installTwrp reinstall", result) < 0)
			{
				gui_print("Unable to configure TWRP with this kernel.\n");
			}
		}
	}

	// Done
	DataManager::SetValue("ui_progress", 100);
	DataManager::SetValue("ui_progress", 0);
	return ret_val;
}

int GUIAction::doActions()
{
	if (mActions.size() < 1)	return -1;
	if (mActions.size() == 1)
		return doAction(mActions.at(0), 0);

	// For multi-action, we always use a thread
	pthread_t t;
	pthread_attr_t tattr;

	if (pthread_attr_init(&tattr)) {
		LOGERR("Unable to pthread_attr_init\n");
		return -1;
	}
	if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_JOINABLE)) {
		LOGERR("Error setting pthread_attr_setdetachstate\n");
		return -1;
	}
	if (pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM)) {
		LOGERR("Error setting pthread_attr_setscope\n");
		return -1;
	}
	/*if (pthread_attr_setstacksize(&tattr, 524288)) {
		LOGERR("Error setting pthread_attr_setstacksize\n");
		return -1;
	}
	*/
	int ret = pthread_create(&t, &tattr, thread_start, this);
	if (ret) {
		LOGERR("Unable to create more threads for actions... continuing in same thread! %i\n", ret);
		thread_start(this);
	} else {
		if (pthread_join(t, NULL)) {
			LOGERR("Error joining threads\n");
		}
	}
	if (pthread_attr_destroy(&tattr)) {
		LOGERR("Failed to pthread_attr_destroy\n");
		return -1;
	}

	return 0;
}

void* GUIAction::thread_start(void *cookie)
{
	GUIAction* ourThis = (GUIAction*) cookie;

	DataManager::SetValue(TW_ACTION_BUSY, 1);

	if (ourThis->mActions.size() > 1)
	{
		std::vector<Action>::iterator iter;
		for (iter = ourThis->mActions.begin(); iter != ourThis->mActions.end(); iter++)
			ourThis->doAction(*iter, 1);
	}
	else
	{
		ourThis->doAction(ourThis->mActions.at(0), 1);
	}
	int check = 0;
	DataManager::GetValue("tw_background_thread_running", check);
	if (check == 0)
		DataManager::SetValue(TW_ACTION_BUSY, 0);
	return NULL;
}

void GUIAction::operation_start(const string operation_name)
{
	DataManager::SetValue(TW_ACTION_BUSY, 1);
	DataManager::SetValue("ui_progress", 0);
	DataManager::SetValue("tw_operation", operation_name);
	DataManager::SetValue("tw_operation_status", 0);
	DataManager::SetValue("tw_operation_state", 0);
}

void GUIAction::operation_end(const int operation_status, const int simulate)
{
	int simulate_fail;
	DataManager::SetValue("ui_progress", 100);
	if (simulate) {
		DataManager::GetValue(TW_SIMULATE_FAIL, simulate_fail);
		if (simulate_fail != 0)
			DataManager::SetValue("tw_operation_status", 1);
		else
			DataManager::SetValue("tw_operation_status", 0);
	} else {
		if (operation_status != 0) {
			DataManager::SetValue("tw_operation_status", 1);
		}
		else {
			DataManager::SetValue("tw_operation_status", 0);
		}
	}
	DataManager::SetValue("tw_operation_state", 1);
	DataManager::SetValue(TW_ACTION_BUSY, 0);
#ifndef TW_NO_SCREEN_TIMEOUT
	blankTimer.resetTimerAndUnblank();
#endif
}

int GUIAction::doAction(Action action, int isThreaded /* = 0 */)
{
	static string zip_queue[10];
	static int zip_queue_index;
	static pthread_t terminal_command;
	int simulate;

	std::string arg = gui_parse_text(action.mArg);

	std::string function = gui_parse_text(action.mFunction);

	DataManager::GetValue(TW_SIMULATE_ACTIONS, simulate);

	if (function == "reboot")
	{
			//curtainClose(); this sometimes causes a crash

		sync();
		DataManager::SetValue("tw_gui_done", 1);
		DataManager::SetValue("tw_reboot_arg", arg);

		return 0;
	}
	if (function == "home")
	{
		PageManager::SelectPackage("TWRP");
		gui_changePage("main");
		return 0;
	}

	if (function == "key")
	{
		PageManager::NotifyKey(getKeyByName(arg));
		return 0;
	}

	if (function == "page") {
		std::string page_name = gui_parse_text(arg);
		return gui_changePage(page_name);
	}

	if (function == "reload") {
		int check = 0, ret_val = 0;
		std::string theme_path;

		operation_start("Reload Theme");
		theme_path = DataManager::GetSettingsStoragePath();
		if (PartitionManager.Mount_By_Path(theme_path.c_str(), 1) < 0) {
			LOGERR("Unable to mount %s during reload function startup.\n", theme_path.c_str());
			check = 1;
		}

		theme_path += "/TWRP/theme/ui.zip";
		if (check != 0 || PageManager::ReloadPackage("TWRP", theme_path) != 0)
		{
			// Loading the custom theme failed - try loading the stock theme
			LOGINFO("Attempting to reload stock theme...\n");
			if (PageManager::ReloadPackage("TWRP", "/res/ui.xml"))
			{
				LOGERR("Failed to load base packages.\n");
				ret_val = 1;
			}
		}
		operation_end(ret_val, simulate);
		return 0;
	}

	if (function == "readBackup")
	{
		string Restore_Name;
		DataManager::GetValue("tw_restore", Restore_Name);
		PartitionManager.Set_Restore_Files(Restore_Name);
		return 0;
	}

	if (function == "set")
	{
		if (arg.find('=') != string::npos)
		{
			string varName = arg.substr(0, arg.find('='));
			string value = arg.substr(arg.find('=') + 1, string::npos);

			DataManager::GetValue(value, value);
			DataManager::SetValue(varName, value);
		}
		else
			DataManager::SetValue(arg, "1");
		return 0;
	}
	if (function == "clear")
	{
		DataManager::SetValue(arg, "0");
		return 0;
	}

	if (function == "mount")
	{
		if (arg == "usb")
		{
			DataManager::SetValue(TW_ACTION_BUSY, 1);
			if (!simulate)
				PartitionManager.usb_storage_enable();
			else
				gui_print("Simulating actions...\n");
		}
		else if (!simulate)
		{
			string cmd;
			if (arg == "EXTERNAL")
				PartitionManager.Mount_By_Path(DataManager::GetStrValue(TW_EXTERNAL_MOUNT), true);
			else if (arg == "INTERNAL")
				PartitionManager.Mount_By_Path(DataManager::GetStrValue(TW_INTERNAL_MOUNT), true);
			else
				PartitionManager.Mount_By_Path(arg, true);
		} else
			gui_print("Simulating actions...\n");
		return 0;
	}

	if (function == "umount" || function == "unmount")
	{
		if (arg == "usb")
		{
			if (!simulate)
				PartitionManager.usb_storage_disable();
			else
				gui_print("Simulating actions...\n");
			DataManager::SetValue(TW_ACTION_BUSY, 0);
		}
		else if (!simulate)
		{
			string cmd;
			if (arg == "EXTERNAL")
				PartitionManager.UnMount_By_Path(DataManager::GetStrValue(TW_EXTERNAL_MOUNT), true);
			else if (arg == "INTERNAL")
				PartitionManager.UnMount_By_Path(DataManager::GetStrValue(TW_INTERNAL_MOUNT), true);
			else
				PartitionManager.UnMount_By_Path(arg, true);
		} else
			gui_print("Simulating actions...\n");
		return 0;
	}
	
	if (function == "restoredefaultsettings")
	{
		operation_start("Restore Defaults");
		if (simulate) // Simulated so that people don't accidently wipe out the "simulation is on" setting
			gui_print("Simulating actions...\n");
		else {
			DataManager::ResetDefaults();
			PartitionManager.Update_System_Details();
			PartitionManager.Mount_Current_Storage(true);
		}
		operation_end(0, simulate);
		return 0;
	}
	
	if (function == "copylog")
	{
		operation_start("Copy Log");
		if (!simulate)
		{
			string dst;
			PartitionManager.Mount_Current_Storage(true);
			dst = DataManager::GetCurrentStoragePath() + "/recovery.log";
			TWFunc::copy_file("/tmp/recovery.log", dst.c_str(), 0755);
			sync();
			gui_print("Copied recovery log to %s.\n", DataManager::GetCurrentStoragePath().c_str());
		} else
			simulate_progress_bar();
		operation_end(0, simulate);
		return 0;
	}
	
	if (function == "compute" || function == "addsubtract")
	{
		if (arg.find("+") != string::npos)
		{
			string varName = arg.substr(0, arg.find('+'));
			string string_to_add = arg.substr(arg.find('+') + 1, string::npos);
			int amount_to_add = atoi(string_to_add.c_str());
			int value;

			DataManager::GetValue(varName, value);
			DataManager::SetValue(varName, value + amount_to_add);
			return 0;
		}
		if (arg.find("-") != string::npos)
		{
			string varName = arg.substr(0, arg.find('-'));
			string string_to_subtract = arg.substr(arg.find('-') + 1, string::npos);
			int amount_to_subtract = atoi(string_to_subtract.c_str());
			int value;

			DataManager::GetValue(varName, value);
			value -= amount_to_subtract;
			if (value <= 0)
				value = 0;
			DataManager::SetValue(varName, value);
			return 0;
		}
		if (arg.find("*") != string::npos)
		{
			string varName = arg.substr(0, arg.find('*'));
			string multiply_by_str = gui_parse_text(arg.substr(arg.find('*') + 1, string::npos));
			int multiply_by = atoi(multiply_by_str.c_str());
			int value;

			DataManager::GetValue(varName, value);
			DataManager::SetValue(varName, value*multiply_by);
			return 0;
		}
		if (arg.find("/") != string::npos)
		{
			string varName = arg.substr(0, arg.find('/'));
			string divide_by_str = gui_parse_text(arg.substr(arg.find('/') + 1, string::npos));
			int divide_by = atoi(divide_by_str.c_str());
			int value;

			if(divide_by != 0)
			{
				DataManager::GetValue(varName, value);
				DataManager::SetValue(varName, value/divide_by);
			}
			return 0;
		}
		LOGERR("Unable to perform compute '%s'\n", arg.c_str());
		return -1;
	}
	
	if (function == "setguitimezone")
	{
		string SelectedZone;
		DataManager::GetValue(TW_TIME_ZONE_GUISEL, SelectedZone); // read the selected time zone into SelectedZone
		string Zone = SelectedZone.substr(0, SelectedZone.find(';')); // parse to get time zone
		string DSTZone = SelectedZone.substr(SelectedZone.find(';') + 1, string::npos); // parse to get DST component
		
		int dst;
		DataManager::GetValue(TW_TIME_ZONE_GUIDST, dst); // check wether user chose to use DST
		
		string offset;
		DataManager::GetValue(TW_TIME_ZONE_GUIOFFSET, offset); // pull in offset
		
		string NewTimeZone = Zone;
		if (offset != "0")
			NewTimeZone += ":" + offset;
		
		if (dst != 0)
			NewTimeZone += DSTZone;
		
		DataManager::SetValue(TW_TIME_ZONE_VAR, NewTimeZone);
		DataManager::update_tz_environment_variables();
		return 0;
	}

	if (function == "togglestorage") {
		LOGERR("togglestorage action was deprecated from TWRP\n");
		if (arg == "internal") {
			DataManager::SetValue(TW_USE_EXTERNAL_STORAGE, 0);
		} else if (arg == "external") {
			DataManager::SetValue(TW_USE_EXTERNAL_STORAGE, 1);
		}
		if (PartitionManager.Mount_Current_Storage(true)) {
			if (arg == "internal") {
				string zip_path, zip_root;
				DataManager::GetValue(TW_ZIP_INTERNAL_VAR, zip_path);
				zip_root = TWFunc::Get_Root_Path(zip_path);
#ifdef RECOVERY_SDCARD_ON_DATA
	#ifndef TW_EXTERNAL_STORAGE_PATH
				if (zip_root != "/sdcard")
					DataManager::SetValue(TW_ZIP_INTERNAL_VAR, "/sdcard");
	#else
				if (strcmp(EXPAND(TW_EXTERNAL_STORAGE_PATH), "/sdcard") == 0) {
					if (zip_root != "/emmc")
						DataManager::SetValue(TW_ZIP_INTERNAL_VAR, "/emmc");
				} else {
					if (zip_root != "/sdcard")
						DataManager::SetValue(TW_ZIP_INTERNAL_VAR, "/sdcard");
				}
	#endif
#else
				if (zip_root != DataManager::GetCurrentStoragePath())
					DataManager::SetValue(TW_ZIP_LOCATION_VAR, DataManager::GetCurrentStoragePath());
#endif
				// Save the current zip location to the external variable
				DataManager::SetValue(TW_ZIP_EXTERNAL_VAR, DataManager::GetStrValue(TW_ZIP_LOCATION_VAR));
				// Change the current zip location to the internal variable
				DataManager::SetValue(TW_ZIP_LOCATION_VAR, DataManager::GetStrValue(TW_ZIP_INTERNAL_VAR));
			} else if (arg == "external") {
				string zip_path, zip_root;
				DataManager::GetValue(TW_ZIP_EXTERNAL_VAR, zip_path);
				zip_root = TWFunc::Get_Root_Path(zip_path);
				if (zip_root != DataManager::GetCurrentStoragePath()) {
					DataManager::SetValue(TW_ZIP_EXTERNAL_VAR, DataManager::GetCurrentStoragePath());
				}
				// Save the current zip location to the internal variable
				DataManager::SetValue(TW_ZIP_INTERNAL_VAR, DataManager::GetStrValue(TW_ZIP_LOCATION_VAR));
				// Change the current zip location to the external variable
				DataManager::SetValue(TW_ZIP_LOCATION_VAR, DataManager::GetStrValue(TW_ZIP_EXTERNAL_VAR));
			}
		} else {
			// We weren't able to toggle for some reason, restore original setting
			if (arg == "internal") {
				DataManager::SetValue(TW_USE_EXTERNAL_STORAGE, 1);
			} else if (arg == "external") {
				DataManager::SetValue(TW_USE_EXTERNAL_STORAGE, 0);
			}
		}
		return 0;
	}
	
	if (function == "overlay")
		return gui_changeOverlay(arg);

	if (function == "queuezip")
	{
		if (zip_queue_index >= 10) {
			gui_print("Maximum zip queue reached!\n");
			return 0;
		}
		DataManager::GetValue("tw_filename", zip_queue[zip_queue_index]);
		if (strlen(zip_queue[zip_queue_index].c_str()) > 0) {
			zip_queue_index++;
			DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index);
		}
		return 0;
	}

	if (function == "cancelzip")
	{
		if (zip_queue_index <= 0) {
			gui_print("Minimum zip queue reached!\n");
			return 0;
		} else {
			zip_queue_index--;
			DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index);
		}
		return 0;
	}

	if (function == "queueclear")
	{
		zip_queue_index = 0;
		DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index);
		return 0;
	}

	if (function == "sleep")
	{
		operation_start("Sleep");
		usleep(atoi(arg.c_str()));
		operation_end(0, simulate);
		return 0;
	}

	if (function == "appenddatetobackupname")
	{
		operation_start("AppendDateToBackupName");
		string Backup_Name;
		DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
		Backup_Name += TWFunc::Get_Current_Date();
		if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
			Backup_Name.resize(MAX_BACKUP_NAME_LEN);
		DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
		operation_end(0, simulate);
		return 0;
	}

	if (function == "generatebackupname")
	{
		operation_start("GenerateBackupName");
		TWFunc::Auto_Generate_Backup_Name();
		operation_end(0, simulate);
		return 0;
	}

	if (isThreaded)
	{
		if (function == "fileexists")
		{
			struct stat st;
			string newpath = arg + "/.";

			operation_start("FileExists");
			if (stat(arg.c_str(), &st) == 0 || stat(newpath.c_str(), &st) == 0)
				operation_end(0, simulate);
			else
				operation_end(1, simulate);
			return 0;
		}

		if (function == "flash")
		{
			int i, ret_val = 0, wipe_cache = 0;

			for (i=0; i<zip_queue_index; i++) {
				operation_start("Flashing");
				DataManager::SetValue("tw_filename", zip_queue[i]);
				DataManager::SetValue(TW_ZIP_INDEX, (i + 1));

				ret_val = flash_zip(zip_queue[i], arg, simulate, &wipe_cache);
				if (ret_val != 0) {
					gui_print("Error flashing zip '%s'\n", zip_queue[i].c_str());
					i = 10; // Error flashing zip - exit queue
					ret_val = 1;
				}
			}
			zip_queue_index = 0;
			DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index);

			if (wipe_cache)
				PartitionManager.Wipe_By_Path("/cache");
			string result;
			if (DataManager::GetIntValue(TW_HAS_INJECTTWRP) == 1 && DataManager::GetIntValue(TW_INJECT_AFTER_ZIP) == 1) {
				operation_start("ReinjectTWRP");
				gui_print("Injecting TWRP into boot image...\n");
				if (simulate) {
					simulate_progress_bar();
				} else {
					TWPartition* Boot = PartitionManager.Find_Partition_By_Path("/boot");
					if (Boot == NULL || Boot->Current_File_System != "emmc")
						TWFunc::Exec_Cmd("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash", result);
					else {
						string injectcmd = "injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash bd=" + Boot->Actual_Block_Device;
						TWFunc::Exec_Cmd(injectcmd, result);
					}
					gui_print("TWRP injection complete.\n");
				}
			}
			PartitionManager.Update_System_Details();
			operation_end(ret_val, simulate);
			return 0;
		}
		if (function == "wipe")
		{
			operation_start("Format");
			DataManager::SetValue("tw_partition", arg);

			int ret_val = false;

			if (simulate) {
				simulate_progress_bar();
			} else {
				if (arg == "data")
					ret_val = PartitionManager.Factory_Reset();
				else if (arg == "battery")
					ret_val = PartitionManager.Wipe_Battery_Stats();
				else if (arg == "rotate")
					ret_val = PartitionManager.Wipe_Rotate_Data();
				else if (arg == "dalvik")
					ret_val = PartitionManager.Wipe_Dalvik_Cache();
				else if (arg == "DATAMEDIA") {
					ret_val = PartitionManager.Format_Data();
				} else if (arg == "INTERNAL") {
					int has_datamedia, dual_storage;

					DataManager::GetValue(TW_HAS_DATA_MEDIA, has_datamedia);
					if (has_datamedia) {
						ret_val = PartitionManager.Wipe_Media_From_Data();
					} else {
						ret_val = PartitionManager.Wipe_By_Path(DataManager::GetSettingsStoragePath());
					}
				} else if (arg == "EXTERNAL") {
					string External_Path;

					DataManager::GetValue(TW_EXTERNAL_PATH, External_Path);
					ret_val = PartitionManager.Wipe_By_Path(External_Path);
				} else if (arg == "ANDROIDSECURE") {
					ret_val = PartitionManager.Wipe_Android_Secure();
				} else if (arg == "LIST") {
					string Wipe_List, wipe_path;
					bool skip = false;
					ret_val = true;
					TWPartition* wipe_part = NULL;

					DataManager::GetValue("tw_wipe_list", Wipe_List);
					LOGINFO("wipe list '%s'\n", Wipe_List.c_str());
					if (!Wipe_List.empty()) {
						size_t start_pos = 0, end_pos = Wipe_List.find(";", start_pos);
						while (end_pos != string::npos && start_pos < Wipe_List.size()) {
							wipe_path = Wipe_List.substr(start_pos, end_pos - start_pos);
							LOGINFO("wipe_path '%s'\n", wipe_path.c_str());
							if (wipe_path == "/and-sec") {
								if (!PartitionManager.Wipe_Android_Secure()) {
									LOGERR("Unable to wipe android secure\n");
									ret_val = false;
									break;
								} else {
									skip = true;
								}
							} else if (wipe_path == "DALVIK") {
								if (!PartitionManager.Wipe_Dalvik_Cache()) {
									LOGERR("Failed to wipe dalvik\n");
									ret_val = false;
									break;
								} else {
									skip = true;
								}
							} else if (wipe_path == "INTERNAL") {
								if (!PartitionManager.Wipe_Media_From_Data()) {
									ret_val = false;
									break;
								} else {
									skip = true;
								}
							}
							if (!skip) {
								if (!PartitionManager.Wipe_By_Path(wipe_path)) {
									LOGERR("Unable to wipe '%s'\n", wipe_path.c_str());
									ret_val = false;
									break;
								} else if (wipe_path == DataManager::GetSettingsStoragePath()) {
									arg = wipe_path;
								}
							} else {
								skip = false;
							}
							start_pos = end_pos + 1;
							end_pos = Wipe_List.find(";", start_pos);
						}
					}
				} else
					ret_val = PartitionManager.Wipe_By_Path(arg);

				if (arg == DataManager::GetSettingsStoragePath()) {
					// If we wiped the settings storage path, recreate the TWRP folder and dump the settings
					string Storage_Path = DataManager::GetSettingsStoragePath();

					if (PartitionManager.Mount_By_Path(Storage_Path, true)) {
						LOGINFO("Making TWRP folder and saving settings.\n");
						Storage_Path += "/TWRP";
						mkdir(Storage_Path.c_str(), 0777);
						DataManager::Flush();
					} else {
						LOGERR("Unable to recreate TWRP folder and save settings.\n");
					}
				}
			}
			PartitionManager.Update_System_Details();
			if (ret_val)
				ret_val = 0; // 0 is success
			else
				ret_val = 1; // 1 is failure
			operation_end(ret_val, simulate);
			return 0;
		}
		if (function == "refreshsizes")
		{
			operation_start("Refreshing Sizes");
			if (simulate) {
				simulate_progress_bar();
			} else
				PartitionManager.Update_System_Details();
			operation_end(0, simulate);
			return 0;
		}
		if (function == "nandroid")
		{
			operation_start("Nandroid");
			int ret = 0;

			if (simulate) {
				DataManager::SetValue("tw_partition", "Simulation");
				simulate_progress_bar();
			} else {
				if (arg == "backup") {
					string Backup_Name;
					DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
					if (Backup_Name == "(Auto Generate)" || Backup_Name == "(Current Date)" || Backup_Name == "0" || Backup_Name == "(" || PartitionManager.Check_Backup_Name(true) == 0) {
						ret = PartitionManager.Run_Backup();
					}
					else {
						operation_end(1, simulate);
						return -1;
					}
					DataManager::SetValue(TW_BACKUP_NAME, "(Auto Generate)");
				} else if (arg == "restore") {
					string Restore_Name;
					DataManager::GetValue("tw_restore", Restore_Name);
					ret = PartitionManager.Run_Restore(Restore_Name);
				} else {
					operation_end(1, simulate);
					return -1;
				}
			}
			DataManager::SetValue("tw_encrypt_backup", 0);
			if (ret == false)
				ret = 1; // 1 for failure
			else
				ret = 0; // 0 for success
			operation_end(ret, simulate);
			return 0;
		}
		if (function == "fixpermissions")
		{
			operation_start("Fix Permissions");
			LOGINFO("fix permissions started!\n");
			if (simulate) {
				simulate_progress_bar();
			} else {
				int op_status = PartitionManager.Fix_Permissions();
				if (op_status != 0)
					op_status = 1; // failure
				operation_end(op_status, simulate);
			}
			return 0;
		}
		if (function == "dd")
		{
			operation_start("imaging");

			if (simulate) {
				simulate_progress_bar();
			} else {
				string result;
				string cmd = "dd " + arg;
				TWFunc::Exec_Cmd(cmd, result);
			}
			operation_end(0, simulate);
			return 0;
		}
		if (function == "partitionsd")
		{
			operation_start("Partition SD Card");
			int ret_val = 0;

			if (simulate) {
				simulate_progress_bar();
			} else {
				int allow_partition;
				DataManager::GetValue(TW_ALLOW_PARTITION_SDCARD, allow_partition);
				if (allow_partition == 0) {
					gui_print("This device does not have a real SD Card!\nAborting!\n");
				} else {
					if (!PartitionManager.Partition_SDCard())
						ret_val = 1; // failed
				}
			}
			operation_end(ret_val, simulate);
			return 0;
		}
		if (function == "installhtcdumlock")
		{
			operation_start("Install HTC Dumlock");
			if (simulate) {
				simulate_progress_bar();
			} else
				TWFunc::install_htc_dumlock();

			operation_end(0, simulate);
			return 0;
		}
		if (function == "htcdumlockrestoreboot")
		{
			operation_start("HTC Dumlock Restore Boot");
			if (simulate) {
				simulate_progress_bar();
			} else
				TWFunc::htc_dumlock_restore_original_boot();

			operation_end(0, simulate);
			return 0;
		}
		if (function == "htcdumlockreflashrecovery")
		{
			operation_start("HTC Dumlock Reflash Recovery");
			if (simulate) {
				simulate_progress_bar();
			} else
				TWFunc::htc_dumlock_reflash_recovery_to_boot();

			operation_end(0, simulate);
			return 0;
		}
		if (function == "cmd")
		{
			int op_status = 0;
			string result;

			operation_start("Command");
			LOGINFO("Running command: '%s'\n", arg.c_str());
			if (simulate) {
				simulate_progress_bar();
			} else {
				op_status = TWFunc::Exec_Cmd(arg, result);
				if (op_status != 0)
					op_status = 1;
			}

			operation_end(op_status, simulate);
			return 0;
		}
		if (function == "terminalcommand")
		{
			int op_status = 0;
			string cmdpath, command;

			DataManager::GetValue("tw_terminal_location", cmdpath);
			operation_start("CommandOutput");
			gui_print("%s # %s\n", cmdpath.c_str(), arg.c_str());
			if (simulate) {
				simulate_progress_bar();
				operation_end(op_status, simulate);
			} else {
				command = "cd \"" + cmdpath + "\" && " + arg + " 2>&1";;
				LOGINFO("Actual command is: '%s'\n", command.c_str());
				DataManager::SetValue("tw_terminal_command_thread", command);
				DataManager::SetValue("tw_terminal_state", 1);
				DataManager::SetValue("tw_background_thread_running", 1);
				op_status = pthread_create(&terminal_command, NULL, command_thread, NULL);
				if (op_status != 0) {
					LOGERR("Error starting terminal command thread, %i.\n", op_status);
					DataManager::SetValue("tw_terminal_state", 0);
					DataManager::SetValue("tw_background_thread_running", 0);
					operation_end(1, simulate);
				}
			}
			return 0;
		}
		if (function == "killterminal")
		{
			int op_status = 0;

			LOGINFO("Sending kill command...\n");
			operation_start("KillCommand");
			DataManager::SetValue("tw_operation_status", 0);
			DataManager::SetValue("tw_operation_state", 1);
			DataManager::SetValue("tw_terminal_state", 0);
			DataManager::SetValue("tw_background_thread_running", 0);
			DataManager::SetValue(TW_ACTION_BUSY, 0);
			return 0;
		}
		if (function == "reinjecttwrp")
		{
			int op_status = 0;
			string result;
			operation_start("ReinjectTWRP");
			gui_print("Injecting TWRP into boot image...\n");
			if (simulate) {
				simulate_progress_bar();
			} else {
				TWFunc::Exec_Cmd("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash", result);
				gui_print("TWRP injection complete.\n");
			}

			operation_end(op_status, simulate);
			return 0;
		}
		if (function == "checkbackupname")
		{
			int op_status = 0;

			operation_start("CheckBackupName");
			if (simulate) {
				simulate_progress_bar();
			} else {
				op_status = PartitionManager.Check_Backup_Name(true);
				if (op_status != 0)
					op_status = 1;
			}

			operation_end(op_status, simulate);
			return 0;
		}
		if (function == "decrypt")
		{
			int op_status = 0;

			operation_start("Decrypt");
			if (simulate) {
				simulate_progress_bar();
			} else {
				string Password;
				DataManager::GetValue("tw_crypto_password", Password);
				op_status = PartitionManager.Decrypt_Device(Password);
				if (op_status != 0)
					op_status = 1;
				else {
					int load_theme = 1;

					DataManager::SetValue(TW_IS_ENCRYPTED, 0);

					if (load_theme) {
						int has_datamedia;

						// Check for a custom theme and load it if exists
						DataManager::GetValue(TW_HAS_DATA_MEDIA, has_datamedia);
						if (has_datamedia != 0) {
							struct stat st;
							int check = 0;
							std::string theme_path;

							theme_path = DataManager::GetSettingsStoragePath();
							if (PartitionManager.Mount_By_Path(theme_path.c_str(), 1) < 0) {
								LOGERR("Unable to mount %s during reload function startup.\n", theme_path.c_str());
								check = 1;
							}

							theme_path += "/TWRP/theme/ui.zip";
							if (check == 0 && stat(theme_path.c_str(), &st) == 0) {
								if (PageManager::ReloadPackage("TWRP", theme_path) != 0)
								{
									// Loading the custom theme failed - try loading the stock theme
									LOGINFO("Attempting to reload stock theme...\n");
									if (PageManager::ReloadPackage("TWRP", "/res/ui.xml"))
									{
										LOGERR("Failed to load base packages.\n");
									}
								}
							}
						}
					}
				}
			}

			operation_end(op_status, simulate);
			return 0;
		}
		if (function == "adbsideload")
		{
			int ret = 0;

			operation_start("Sideload");
			if (simulate) {
				simulate_progress_bar();
			} else {
				int wipe_cache = 0;
				int wipe_dalvik = 0;
				string result, Sideload_File;

				if (!PartitionManager.Mount_Current_Storage(true)) {
					operation_end(1, simulate);
					return 0;
				}
				Sideload_File = DataManager::GetCurrentStoragePath() + "/sideload.zip";
				if (TWFunc::Path_Exists(Sideload_File)) {
					unlink(Sideload_File.c_str());
				}
				gui_print("Starting ADB sideload feature...\n");
				DataManager::GetValue("tw_wipe_dalvik", wipe_dalvik);
				ret = apply_from_adb(Sideload_File.c_str());
				DataManager::SetValue("tw_has_cancel", 0); // Remove cancel button from gui now that the zip install is going to start
				if (ret != 0) {
					ret = 1; // failure
				} else if (TWinstall_zip(Sideload_File.c_str(), &wipe_cache) == 0) {
					if (wipe_cache || DataManager::GetIntValue("tw_wipe_cache"))
						PartitionManager.Wipe_By_Path("/cache");
					if (wipe_dalvik)
						PartitionManager.Wipe_Dalvik_Cache();
				} else {
					ret = 1; // failure
				}
				if (DataManager::GetIntValue(TW_HAS_INJECTTWRP) == 1 && DataManager::GetIntValue(TW_INJECT_AFTER_ZIP) == 1) {
					operation_start("ReinjectTWRP");
					gui_print("Injecting TWRP into boot image...\n");
					if (simulate) {
						simulate_progress_bar();
					} else {
						TWPartition* Boot = PartitionManager.Find_Partition_By_Path("/boot");
						if (Boot == NULL || Boot->Current_File_System != "emmc")
							TWFunc::Exec_Cmd("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash", result);
						else {
							string injectcmd = "injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash bd=" + Boot->Actual_Block_Device;
							TWFunc::Exec_Cmd(injectcmd, result);
						}
						gui_print("TWRP injection complete.\n");
					}
				}
			}
			operation_end(ret, simulate);
			return 0;
		}
		if (function == "adbsideloadcancel")
		{
			int child_pid;
			char child_prop[PROPERTY_VALUE_MAX];
			string Sideload_File;
			Sideload_File = DataManager::GetCurrentStoragePath() + "/sideload.zip";
			unlink(Sideload_File.c_str());
			property_get("tw_child_pid", child_prop, "error");
			if (strcmp(child_prop, "error") == 0) {
				LOGERR("Unable to get child ID from prop\n");
				return 0;
			}
			child_pid = atoi(child_prop);
			gui_print("Cancelling ADB sideload...\n");
			kill(child_pid, SIGTERM);
			DataManager::SetValue("tw_page_done", "1"); // For OpenRecoveryScript support
			return 0;
		}
		if (function == "openrecoveryscript") {
			operation_start("OpenRecoveryScript");
			if (simulate) {
				simulate_progress_bar();
			} else {
				// Check for the SCRIPT_FILE_TMP first as these are AOSP recovery commands
				// that we converted to ORS commands during boot in recovery.cpp.
				// Run those first.
				int reboot = 0;
				if (TWFunc::Path_Exists(SCRIPT_FILE_TMP)) {
					gui_print("Processing AOSP recovery commands...\n");
					if (OpenRecoveryScript::run_script_file() == 0) {
						reboot = 1;
					}
				}
				// Check for the ORS file in /cache and attempt to run those commands.
				if (OpenRecoveryScript::check_for_script_file()) {
					gui_print("Processing OpenRecoveryScript file...\n");
					if (OpenRecoveryScript::run_script_file() == 0) {
						reboot = 1;
					}
				}
				if (reboot) {
					usleep(2000000); // Sleep for 2 seconds before rebooting
					TWFunc::tw_reboot(rb_system);
				} else {
					DataManager::SetValue("tw_page_done", 1);
				}
			}
			return 0;
		}
		if (function == "installsu")
		{
			int op_status = 0;

			operation_start("Install SuperSU");
			if (simulate) {
				simulate_progress_bar();
			} else {
				if (!TWFunc::Install_SuperSU())
					op_status = 1;
			}

			operation_end(op_status, simulate);
			return 0;
		}
		if (function == "fixsu")
		{
			int op_status = 0;

			operation_start("Fixing Superuser Permissions");
			if (simulate) {
				simulate_progress_bar();
			} else {
				LOGERR("Fixing su permissions was deprecated from TWRP.\n");
				LOGERR("4.3+ ROMs with SELinux will always lose su perms.\n");
			}

			operation_end(op_status, simulate);
			return 0;
		}
		if (function == "decrypt_backup")
		{
			int op_status = 0;

			operation_start("Try Restore Decrypt");
			if (simulate) {
				simulate_progress_bar();
			} else {
				string Restore_Path, Filename, Password;
				DataManager::GetValue("tw_restore", Restore_Path);
				Restore_Path += "/";
				DataManager::GetValue("tw_restore_password", Password);
				if (TWFunc::Try_Decrypting_Backup(Restore_Path, Password))
					op_status = 0; // success
				else
					op_status = 1; // fail
			}

			operation_end(op_status, simulate);
			return 0;
		}
	}
	else
	{
		pthread_t t;
		pthread_create(&t, NULL, thread_start, this);
		return 0;
	}
	LOGERR("Unknown action '%s'\n", function.c_str());
	return -1;
}

int GUIAction::getKeyByName(std::string key)
{
	if (key == "home")			return KEY_HOME;
	else if (key == "menu")		return KEY_MENU;
	else if (key == "back")	 	return KEY_BACK;
	else if (key == "search")	return KEY_SEARCH;
	else if (key == "voldown")	return KEY_VOLUMEDOWN;
	else if (key == "volup")	return KEY_VOLUMEUP;
	else if (key == "power") {
		int ret_val;
		DataManager::GetValue(TW_POWER_BUTTON, ret_val);
		if (!ret_val)
			return KEY_POWER;
		else
			return ret_val;
	}

	return atol(key.c_str());
}

void* GUIAction::command_thread(void *cookie)
{
	string command;
	FILE* fp;
	char line[512];

	DataManager::GetValue("tw_terminal_command_thread", command);
	fp = popen(command.c_str(), "r");
	if (fp == NULL) {
		LOGERR("Error opening command to run.\n");
	} else {
		int fd = fileno(fp), has_data = 0, check = 0, keep_going = -1, bytes_read = 0;
		struct timeval timeout;
		fd_set fdset;

		while(keep_going)
		{
			FD_ZERO(&fdset);
			FD_SET(fd, &fdset);
			timeout.tv_sec = 0;
			timeout.tv_usec = 400000;
			has_data = select(fd+1, &fdset, NULL, NULL, &timeout);
			if (has_data == 0) {
				// Timeout reached
				DataManager::GetValue("tw_terminal_state", check);
				if (check == 0) {
					keep_going = 0;
				}
			} else if (has_data < 0) {
				// End of execution
				keep_going = 0;
			} else {
				// Try to read output
				memset(line, 0, sizeof(line));
				bytes_read = read(fd, line, sizeof(line));
				if (bytes_read > 0)
					gui_print("%s", line); // Display output
				else
					keep_going = 0; // Done executing
			}
		}
		fclose(fp);
	}
	DataManager::SetValue("tw_operation_status", 0);
	DataManager::SetValue("tw_operation_state", 1);
	DataManager::SetValue("tw_terminal_state", 0);
	DataManager::SetValue("tw_background_thread_running", 0);
	DataManager::SetValue(TW_ACTION_BUSY, 0);
	return NULL;
}