summaryrefslogtreecommitdiff
path: root/BenchmarkFramework/app/src/main/java/org/linaro/iasenov/benchmarkframework/MainActivity.java
blob: 1c00b44bae2766d7e1c5fdc9b1e92dd9cb762566 (plain)
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
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
package org.linaro.iasenov.benchmarkframework;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static String TAG = "BenchmarkFramework";

    private Button mStartButton;
    private Button mStartAutoButton;
    private Button mChartButton;
    private Button mInfo;
    private Button mShowHideDispay;
    private TextView mDisplayDetails;
    private static TextView mToolbarRepeatIndicator;
    public ProgressDialog progressDialog;

    private String mSelectedTest = "";
    private String mSelectedClassTest = "";
    public static String autoTestFileNameIdentifier = "Default";
    private String mTestResult = "";
    private String mAllTestsResult = "";
    public static String PACKAGE_NAME;
    private List<String> mAllTests;
    private ArrayList selectedClassTests;

    private static String KEY_REPEAT_NUMBER = "repeat-number";
    private static String KEY_FILE_FORMAT = "file-format";
    public static boolean IS_SHELL_CONTROL = false;
    public static String LOG_PATH = "";
    public static String EXECUTABLE_PATH = "";
    public static String SAVE_DATA_PATH = "";
    public static String TEMP_PATH = "";
    public static String mRepeatNumber="";
    public static String fileFormatFromSettings = "";

    private int nextTestIndex;
    private int allTestsCount;
    private int numberOfCheckedTests = 0;
    public int endTestCounter;

    private boolean isAuto = false;
    private boolean isSelected = false;
    public boolean isTempLogFileNeeded = false;
    public boolean isCanceled = false;

    private Context mContext;
    public static Activity mActivity;

    private static int pixWide;
    private static int pixHigh;
    private static int testDone = 0;

    private Typeface tf = Typeface.create("monospace", 0);
    public File autoTestFile; //file for auto saving tests results(when isAuto);

    private TaskCanceler taskCanceler;
    private Handler handler = new Handler();

    public static long elapsedTotalTime = 0;

    public static String runningTests = "";
    public static int APP_UID;

    public static String mStep;
    public static String mFrom;
    public static String mSelectedTxt;

    public static String GRAPHICS_ELAPSED_TIME = "graphics_elapsed_time";
    public static String GRAPHICS_ROUND = "graphics_round";

    public static Map<String, String> mapTimes = new HashMap<String, String>();
    //*************************
    private int count;

    private boolean[] testselection;
    private MyAdapter mGridViewAdapter;
    int pixMin;
    public GridView mListViewGrid;


    public static final Lock LOCK = new Lock();

    final String[] classNameTestItems = {"Test1",
                                        "Test2",
                                        "Test3",
                                        "Test4",
                                        "Test5",
                                        "Test6",
                                        "Test7",
                                        "Test8",
                                        "Test9",
                                        "Test10",
                                        "Test11",
                                        "Test12",
                                        "Test13",
                                        "Test14",
                                        "Test15",
                                        "Test16",
                                        "Test17",
                                        "Test18",
                                        "Test19",
                                        "Test20",
                                        "Test21",
                                        "Test22",
                                        "Test23",
                                        "Test24",
                                        "Test25"};

    //**********************************************************************************************
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Prevent screen off cause this will interrupt the some of tests running in own activity(GPU tests)
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        mContext = getApplicationContext();
        mActivity = this;

        APP_UID = android.os.Process.myUid();
        PACKAGE_NAME = getApplicationContext().getPackageName();

        mStartButton = (Button) findViewById(R.id.startButton);
        mStartButton.setOnClickListener(this);

        //***************************************************
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        //Load repeat number tests from preferences
        mRepeatNumber = prefs.getString(KEY_REPEAT_NUMBER,"1");
        //Load file format from preferences
        fileFormatFromSettings = prefs.getString(KEY_FILE_FORMAT,"html");

        // Find the toolbar view inside the activity layout
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        // Sets the Toolbar to act as the ActionBar for this Activity window.
        // Make sure the toolbar exists in the activity and is not null
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(" Benchmark Framework");
        //getSupportActionBar().setSubtitle(" Linaro Open source benchmarks");
        getSupportActionBar().setIcon(R.drawable.lmg_logo_toolbar);

        mToolbarRepeatIndicator = (TextView) findViewById(R.id.toolbar_repeat_indicator);
        mToolbarRepeatIndicator.setText("  "+mRepeatNumber+"  ");

        mStartAutoButton = (Button) findViewById(R.id.startAutoButton);
        mStartAutoButton.setOnClickListener(this);

        mChartButton = (Button) findViewById(R.id.chartButton);
        mChartButton.setOnClickListener(this);

        mInfo = (Button) findViewById(R.id.infoButton);
        mInfo.setOnClickListener(this);

        mShowHideDispay = (Button) findViewById(R.id.showHideDisplay);
        mShowHideDispay.setOnClickListener(this);

        mDisplayDetails = (TextView) findViewById(R.id.displayDetails);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mDisplayDetails.setTypeface(tf);

        pixHigh = metrics.heightPixels;
        pixWide = metrics.widthPixels;
        testDone = 0;

        pixMin = pixWide;
        if (pixHigh < pixMin) pixMin = pixHigh;

        mDisplayDetails.setTextSize(TypedValue.COMPLEX_UNIT_PX, getPixels(pixMin));

        mDisplayDetails.setTextColor(Color.rgb(102, 255, 51));
        mDisplayDetails.setBackgroundColor(Color.BLACK);

        mDisplayDetails.setMovementMethod(new ScrollingMovementMethod());


        //show listview with saved results files and give option to read them
        mDisplayDetails.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
                Intent i = new Intent(mActivity, Results.class);
                //Intent i = new Intent(mActivity, Chart.class);
                startActivity(i);
                return true;
            }
        });


        LOG_PATH = getFilesDir() + "/logss" + "/tmpLog.txt";
        EXECUTABLE_PATH = getFilesDir() + "/executable_file";
        SAVE_DATA_PATH =  getFilesDir() + "/download";
        TEMP_PATH = EXECUTABLE_PATH + "/temp";

        final String[] displayNames = {"MemSpeed",
                                        "RandMem",
                                        "Linaro-Libc-Bench",
                                        "Linaro-StringBench",
                                        "Linaro-Harness",
                                        "Linaro-Dhrystone",
                                        "Iozone",
                                        "Bonnie++",
                                        "Algorithm(ART)",
                                        "BMsGame(ART)",
                                        "Caffeine(ART)",
                                        "Jit-out(ART)",
                                        "Math(ART)",
                                        "Micro(ART)",
                                        "Stanford(ART)",
                                        "DrawArc(GPU)",
                                        "DrawCircle2(GPU)",
                                        "DrawImage(GPU)",
                                        "DrawRect(GPU)",
                                        "DrawText(GPU)",
                                        "DrawCircle(GPU)",
                                        "Kubench(GPU)",
                                        "Nehe08(GPU)",
                                        "Nehe16(GPU)",
                                        "TeapotES(GPU)"};


        //*******************GridView*******************
        this.count = displayNames.length;
        this.testselection = new boolean[count];

        mListViewGrid = (GridView) findViewById(R.id.listGrid);
        mGridViewAdapter = new MyAdapter(displayNames);
        mListViewGrid.setAdapter(mGridViewAdapter);
        //**********************************************

        IS_SHELL_CONTROL = false;
        //Check if shell control is used for tests

        //This fix issue with NullPointer on mListViewGrid(invoke isShellControl() when mListViewGrid layout is already inflate)
        mListViewGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @SuppressLint("NewApi")
            @Override
            public void onGlobalLayout() {
                //At this point the layout is complete and the
                //dimensions of myView and any child views are known.
                Log.i(TAG, "onGlobalLayout");
                mListViewGrid.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                isShellControl();
            }
        });


        //isShellControl();
    }
    //**********************************************************************************************


    //**********************************************************************************************
    @Override
    public void onResume() {
        super.onResume();
        // put your code here...
    }


    //**********************************************************************************************
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
            case (100) : {
                if (resultCode == Activity.RESULT_OK) {
                    // TODO Extract the data returned from the child Activity.
                    BaseBenchmark.elapsedFromActivityTest = data.getLongExtra(MainActivity. GRAPHICS_ELAPSED_TIME,0);
                    BaseBenchmark.mRound = data.getIntExtra(MainActivity.GRAPHICS_ROUND,0);
                    Log.i(TAG,"elapsed from activity test:" + BaseBenchmark.elapsedFromActivityTest);
                    synchronized (MainActivity.LOCK) {
                        MainActivity.LOCK.setCondition(true);
                        MainActivity.LOCK.notifyAll();
                    }

                }
                if (resultCode == Activity.RESULT_CANCELED) {
                    Log.i(TAG,"RESULT_CANCELED");

                    //Need to set isCanceled flag here
                    isCanceled = true;

                    //Simulate click on calcel button
                    progressDialog.show();
                    progressDialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick();

                    synchronized (MainActivity.LOCK) {
                        MainActivity.LOCK.setCondition(true);
                        MainActivity.LOCK.notifyAll();
                    }

                }
                break;
            }
        }
    }

    //**********************************************************************************************
    //Load benchmarks libraries when benchmark test is integrated as (*.so)
    //**********************************************************************************************
    static
    {
        System.loadLibrary("memspeedlib");
        System.loadLibrary("randmemlib");
        //System.loadLibrary("cbench");
        //System.loadLibrary("stringbench");
        //System.loadLibrary("harness");
    }


    //**********************************************************************************************
    @Override
    public void onClick(View v) {

        Log.i(TAG, "numberOfCheckedTests: " + numberOfCheckedTests);

        if (v.getId() == R.id.startButton && numberOfCheckedTests > 0) {
            isAuto = false;
            isSelected = true;

            //This check will be removed in future
            if (mSelectedClassTest.equals("Test4")) {
                isTempLogFileNeeded = true;
            } else {
                isTempLogFileNeeded = false;
            }

            runTests(Integer.parseInt(mRepeatNumber));

        } else if (v.getId() == R.id.startButton && numberOfCheckedTests == 0) {
            Toast.makeText(v.getContext(), "Please select test...",
                    Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.chartButton && testDone == 1) {
            //saveUIResultToFile();
            Intent i = new Intent(mActivity, Chart.class);
            startActivity(i);
        } else if (v.getId() == R.id.chartButton && testDone == 0) {
            Toast.makeText(v.getContext(), "No charts to show",
                    Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.startAutoButton) {
            isAuto = true;
            isSelected = false;
            runTests(Integer.parseInt(mRepeatNumber));

        } else if (v.getId() == R.id.infoButton) {
            String info = "[RUN TEST]: <font color=\"#6A996A\">Run selected tests</font><br><br> " +
                    "[RUN AUTO]: <font color=\"#6A996A\">Run all tests in row and save results to file automatically</font><br><br> " +
                    "[CHART]: <font color=\"#6A996A\">Create chart for executed tests</font><br><br> " +
                    "[Settings]: <br> - <font color=\"#6A996A\">Allow to control tests repeatability</font>" +
                    "<br><br> - <font color=\"#6A996A\">Clear Data</font>" +
                    "<br><br> - <font color=\"#6A996A\">File format</font>"+
                    "<br><br> - <font color=\"#6A996A\">Device info</font>";

            createAlertDialog("Help", info, false);
        } else if(v.getId() == R.id.showHideDisplay){
            //Log.i(TAG,"showHideDisplay");
            if(mDisplayDetails.getVisibility() == View.GONE){
                //Log.i(TAG,"set visible");
                mDisplayDetails.setVisibility(View.VISIBLE);
                ((Button)v).setText("HIDE DISPLAY");

            }else{
                mDisplayDetails.setVisibility(View.GONE);
                ((Button)v).setText("SHOW DISPLAY");
                //Log.i(TAG, "set gone");
            }
        }
    }


    //**********************************************************************************************
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


    //**********************************************************************************************
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            //showTestRepeatNumber();
            Intent i = new Intent(this, SettingsActivity.class);
            startActivity(i);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void displayResult(String result) {
        mDisplayDetails.setText(result);
    }
    //**********************************************************************************************



    //**********************************************************************************************
    public static Activity getActivity(){
        return mActivity;
    }
    //**********************************************************************************************



    //**********************************************************************************************
    //Show info about repeat indicator textview in toolbar
    //**********************************************************************************************
    public void onRepeatIndicatorClick(View v){

        int x = (int)v.getX();
        int y = (int)v.getY();

        Context context = mContext;
        CharSequence message = "Repeat indicator";
        int duration = Toast.LENGTH_SHORT;

        final Toast toastTop = Toast.makeText(context, message, duration);
        toastTop.setGravity(Gravity.TOP | Gravity.LEFT, x,y);

        toastTop.show();
    }



    //**********************************************************************************************
    //Calculate best text size depends on pixels
    //**********************************************************************************************
    public int getPixels(int pixMin) {
        int correction = 0;

        int pixels = 11+correction;

        if (pixMin < 401) {
            pixels = 12+correction;
        } else if (pixMin < 451) {
            pixels = 14+correction;
        } else if (pixMin < 501) {
            pixels = 15+correction;
        } else if (pixMin < 551) {
            pixels = 16+correction;
        } else if (pixMin < 601) {
            pixels = 18+correction;
        } else if (pixMin < 651) {
            pixels = 20+correction;
        } else if (pixMin < 721) {
            pixels = 22+correction;
        } else if (pixMin < 751) {
            pixels = 23+correction;
        } else if (pixMin < 801) {
            pixels = 24+correction;
        } else if (pixMin < 851) {
            pixels = 26+correction;
        } else if (pixMin < 901) {
            pixels = 28+correction;
        } else if (pixMin < 951) {
            pixels = 30+correction;
        } else {
            pixels = 32+correction;
        }

        return pixels;
    }



    //**********************************************************************************************
    //Save "mDisplayDetails" text to file
    //**********************************************************************************************
    public void saveUIResultToFile() {

        File dir = new File(getFilesDir() + "/download");
        dir.mkdirs();
        File file = new File(dir, "testUIData.txt");

        try {
            FileOutputStream f = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(f);
            pw.println(mDisplayDetails.getText().toString());
            pw.flush();
            pw.close();
            f.close();

            Log.i("IVO", getFilesDir() + " FilePath: " + file.getAbsolutePath());
            Toast.makeText(mContext, "Result was saved to file: " + file.getAbsolutePath(),
                    Toast.LENGTH_LONG).show();

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //**********************************************************************************************
    //Save results from Auto tests to text file with random name every time
    //**********************************************************************************************
    public void saveAutoTestResultToFile() {

        File dir = new File(getFilesDir() + "/download");
        dir.mkdirs();

        if(fileFormatFromSettings.equals("txt")) {
            autoTestFile = new File(dir, "testLogcatData_" + autoTestFileNameIdentifier + ".txt");
        }else if(fileFormatFromSettings.equals("html")){
            autoTestFile = new File(dir, "testLogcatData_" + autoTestFileNameIdentifier + ".html");
        }


        try {
            FileOutputStream f = new FileOutputStream(autoTestFile, true);//apppend=true
            PrintWriter pw = new PrintWriter(f);
            if(fileFormatFromSettings.equals("txt")) {
                pw.println(mTestResult/*mDisplayDetails.getText().toString()*/);
            }else if(fileFormatFromSettings.equals("html")){
                pw.println(HtmlUtil.resultHtmlString);
                HtmlUtil.clear();
            }
            pw.flush();
            pw.close();
            f.close();

            Log.i(TAG, getFilesDir() + " FilePath: " + autoTestFile.getAbsolutePath());

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //**********************************************************************************************
    //Run tests
    //**********************************************************************************************
    public void runTests(int timesToRun) {
        nextTestIndex = 0;
        allTestsCount = 0;
        elapsedTotalTime = 0;
        mAllTests = new ArrayList<String>();
        selectedClassTests = new ArrayList<String>();
        mAllTestsResult = "";
        selectedClassTests.clear();
        mAllTests.clear();

        //Clear chart data
        mapTimes.clear();

        //HTML BEGIN
        //Clear html string
        if(fileFormatFromSettings.equals("html")) {
            HtmlUtil.clear();
        }
        //HTML END


        runningTests = "";

        //reset cancel flag
        isCanceled = false;

        //Create taskCanceler
        taskCanceler = new TaskCanceler();


        mDisplayDetails.scrollTo(0, 0);

        //Show to async task when real end has come
        endTestCounter = timesToRun;


        if (isAuto) {
            for (int i = 0; i < mListViewGrid.getCount(); i++) {
                mAllTests.add((mGridViewAdapter.getTextByPosition(i)).toString());
            }
        }

        if (isSelected) {
            for (int i = 0; i < mListViewGrid.getCount(); i++) {
                if (testselection[i]) {
                    mAllTests.add((mGridViewAdapter.getTextByPosition(i)));
                    selectedClassTests.add(classNameTestItems[i]);
                }
            }
        }

        allTestsCount = mAllTests.size();
        if (isAuto) Log.i(TAG, "autoTest:" + allTestsCount);
        if (isSelected) Log.i(TAG, "Number of selected tests:" + allTestsCount);
        Log.i(TAG, "Repeat tests:" + timesToRun);

        if (mAllTests.size() > 0) {

            SecureRandom random = new SecureRandom();
            autoTestFileNameIdentifier = new BigInteger(11, random).toString(32);

            for(int counter = 0; counter < timesToRun; counter++) {
                //Clear test index on each repeat
                nextTestIndex = 0;

                for (int i = 0; i < allTestsCount; i++) {

                    isTempLogFileNeeded = false;//make it false for now

                    if (nextTestIndex < allTestsCount) {

                        if (isAuto) {
                            mSelectedTest = mAllTests.get(nextTestIndex);
                            mSelectedClassTest = classNameTestItems[nextTestIndex];
                        }

                        if (isSelected) {
                            mSelectedTest = mAllTests.get(nextTestIndex).toString();
                            mSelectedClassTest = selectedClassTests.get(nextTestIndex).toString();
                        }

                        String localSelectedTest = mSelectedTest;
                        String localSelectedClassTest = mSelectedClassTest;

                        //Add to summery string
                        if(counter == 0) { //Add test only once to summary
                            runningTests = runningTests + "," + localSelectedClassTest;
                        }

                        AsyncTaskRunner runner = new AsyncTaskRunner(localSelectedTest, localSelectedClassTest, counter+1, timesToRun);

                        //Prepeare it for cancel situation
                        taskCanceler.addAsyncTask(runner);

                        //runner.execute(mSelectedTest);
                        runner.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, localSelectedTest);
                        //}
                        nextTestIndex++;
                    }
                }
            }
        }
    }

    //**********************************************************************************************
    //Can Use this method when benchmark test take a lot of time and logcat dev/log/main ring buffer is overloaded
    //Reads only app logs
    //**********************************************************************************************
    public Process writeLogcatToFile() {

        Log.i(TAG, "writeLogcatToFile");
        Process process = null;

        try {
            Runtime.getRuntime().exec(new String[]{"logcat", "-c"});

            File dir = new File(getFilesDir() + "/logss");
            dir.mkdirs();
            File tempLogFile = new File(dir, "tmpLog.txt");
            tempLogFile.delete();
            tempLogFile = new File(dir, "tmpLog.txt");
            process = Runtime.getRuntime().exec("logcat -f " + tempLogFile.getAbsolutePath());


        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return process;
    }
    //**********************************************************************************************

    public void createAlertDialog(String title, String message, boolean isPositive) {
        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(Html.fromHtml(message));
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });


        if(isPositive) {
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OPEN",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            Uri internal = Uri.parse("content://org.linaro.iasenov.benchmarkframework/" + autoTestFile.getAbsolutePath());
                            intent.setDataAndType(internal, "text/plain");
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    });

        }
        alertDialog.show();
    }


    //Delete all files from dir
    //**********************************************************************************************
    public static void clearDirFiles(File dir) throws IOException {
        if (dir.isDirectory()) {
            for (File c : dir.listFiles()) {
                c.delete();
                Log.i(TAG,"Delete:"+c.getAbsolutePath());
            }
        }else{
           Log.i(TAG, "clearDataFiles: " + dir.getAbsolutePath() + " not exist or not a directory");
        }
    }

    //**********************************************************************************************
    //Show dialog with confirm issue when settings for clear data are clicked
    //**********************************************************************************************
    public static void clearDataDialog(Activity mActivity) {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                mActivity);

        final File dir_save_data = new File(SAVE_DATA_PATH);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                //Delete all data in SAVE_DATA_PATH
                                if (dir_save_data.exists()) {
                                    try {
                                        clearDirFiles(dir_save_data);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        //mActivity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(dir_save_data)));

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.setTitle(Html.fromHtml("<font color=\"#6A996A\">Clear data</font>"));
        alertDialog.setMessage("Once deleted data will not be restored!\n\nAre you sure?");

        // show it
        alertDialog.show();
    }



    //**********************************************************************************************
    //Update used file format chosen from Settings
    //**********************************************************************************************
    public static void updateFileFormat(String newValue){
        fileFormatFromSettings = newValue;

        SharedPreferences prefs = mActivity.getPreferences(MODE_PRIVATE);
        final SharedPreferences.Editor editor = mActivity.getPreferences(MODE_PRIVATE).edit();
        editor.putString(KEY_FILE_FORMAT, newValue);
        editor.apply();
    }


    //**********************************************************************************************
    //Show dialog with test repeat number when settings are clicked
    //**********************************************************************************************
    public static void repeatNumberDialog(Activity ac) {
        // get prompts.xml view
        LayoutInflater li = LayoutInflater.from(ac);
        View promptsView = li.inflate(R.layout.prompts, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                ac);

        // set prompts.xml to alertdialog builder
        alertDialogBuilder.setView(promptsView);

        //Important: use shared preferences of main activity (not ac) to get repeat number properly!!!
        SharedPreferences prefs = mActivity.getPreferences(MODE_PRIVATE);
        final SharedPreferences.Editor editor = mActivity.getPreferences(MODE_PRIVATE).edit();

        mRepeatNumber = prefs.getString(KEY_REPEAT_NUMBER,"1");


        final NumberPicker np = (NumberPicker) promptsView.findViewById(R.id.numberPicker1);
        np.setMinValue(1);
        np.setMaxValue(99);
        np.setWrapSelectorWheel(false);
        np.setValue(Integer.parseInt(mRepeatNumber));



        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // get user input and set it to result
                                // edit text
                                //result.setText(userInput.getText());
                                if (!mRepeatNumber.equals(np.getValue())) {//if user input not the same as from preferences
                                        mRepeatNumber = Integer.toString(np.getValue());
                                        editor.putString(KEY_REPEAT_NUMBER, Integer.toString(np.getValue()));
                                        editor.apply();


                                    mToolbarRepeatIndicator.setText("  "+mRepeatNumber+"  ");//change text in toolbar textview
                                }
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

        //Window window = alertDialog.getWindow();
        //window.setLayout(500, 500);
    }



    //**********************************************************************************************
    //Check adb shell params
    //**********************************************************************************************
    public boolean isShellParamsCorrect(String... params)
    {
       //Check tests are correct
        boolean isShellTestFind = false;
        String testsFromShell[] = params[0].split(":");
        String repeatShellTests = params[1];

        //******************Check is tests ok*******************
        for (String selected : testsFromShell) {
            for (String className : classNameTestItems) {
                if (className.equals(selected)) {
                    //Found it!
                    isShellTestFind = true;
                }
            }

            if(isShellTestFind){ //if test is found

                isShellTestFind = false;
            }else
            {
                //Set test as finished and put some info about the error
                writeToSocketFile("isFinished", "1");
                writeToSocketFile("info", "Error: [persist.sys.tests] is not set or is set in a wrong way. Please check the script and fix it!");
                return false;
            }
        }

        //******************Check is repeat number ok*******************
        if(repeatShellTests.length() == 0) {
            //Set test as finished and put some info about the error
            writeToSocketFile("isFinished", "1");
            writeToSocketFile("info", "Error: [persist.sys.repeat] is not set...");
            return false;
        }else if(repeatShellTests.length() > 0) {
            // Is a number
            if(!isNumeric(repeatShellTests)) {
                writeToSocketFile("isFinished", "1");
                writeToSocketFile("info", "Error: [persist.sys.repeat] is not numeric string...");
                return false;
            }

            if(repeatShellTests.equals("0")) {
                writeToSocketFile("isFinished", "1");
                writeToSocketFile("info", "Error: [persist.sys.repeat] is less than 1");
                return false;
            }
        }

        return true;
    }


    //**********************************************************************************************
    //Run tests in shell control
    //**********************************************************************************************
    public boolean isShellControl() {
        //Log.i(TAG, "isShellControl");
        boolean res = false;

        String control = Util.getProperty("persist.sys.control");
        String testsToBeRun = Util.getProperty("persist.sys.tests");
        String repeatShellTests = Util.getProperty("persist.sys.repeat");

        res = control.equals("shell");

        if (res) {

            //clear isFinished.txt
            writeToSocketFile("isFinished", "0");
            writeToSocketFile("info", "");


            //Let's check the shell parameters
            if(!isShellParamsCorrect(testsToBeRun, repeatShellTests)){
                return false;
            }



            String testsFromShell[] = testsToBeRun.split(":");

            //if property is not set by the adb shell set it to 1
            if(repeatShellTests.length() == 0)
            {
                repeatShellTests = "1";
            }

            Log.i(TAG, "control:" + control);
            Log.i(TAG, "testToBeRun:" + testsToBeRun);
            Log.i(TAG, "repeatShellTests:" + repeatShellTests);

            int mActivePosition = 0;


            //Do not need to remove checks in shell mode so commented!!!
            /*
            for (String className : classNameTestItems) {
                mGridViewAdapter.removeCheckAtPosition(mActivePosition, mListViewGrid);
                mActivePosition++;
            }
            */

            mActivePosition = 0;

            mGridViewAdapter.notifyDataSetChanged();

            for (String className : classNameTestItems) {
                for (String selected : testsFromShell) {
                    if (className.equals(selected)) {
                        //Click on the current test
                        testselection[mActivePosition] = true;
                        //mGridViewAdapter.performItemClick(mActivePosition, mListViewGrid);
                    }

                }
                mActivePosition++;
            }

            isAuto = false;
            isSelected = true;

            IS_SHELL_CONTROL = true;
            runTests(Integer.parseInt(repeatShellTests));

        }
        return res;
    }




    //**********************************************************************************************
    //Check if string contains only digits
    //**********************************************************************************************
    public static boolean isNumeric(String str)
    {
        for (char c : str.toCharArray())
        {
            if (!Character.isDigit(c)) return false;
        }
        return true;
    }



    //**********************************************************************************************
    //Create and write to file used by adb shell
    //**********************************************************************************************
    public Boolean writeToSocketFile(String fname, String fcontent) {
        try {

            File dir = new File(getFilesDir() + "/socket");
            dir.mkdirs();


            String fpath = getFilesDir() + "/socket/" + fname + ".txt";

            File file = new File(fpath);

            // If file does not exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fcontent);
            bw.close();

            Log.i("TAG", "Sucess");
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    //**********************************************************************************************
    //Get device information with html tags
    //**********************************************************************************************
    public static String getInfosAboutDeviceHTML(Activity a) {
        String s = "";
        try {
            PackageInfo pInfo = a.getPackageManager().getPackageInfo(
                    a.getPackageName(), PackageManager.GET_META_DATA);
            s += "<small>APP Package Name: <font color=\"#6A996A\">" + a.getPackageName()+"</font></small>";
            s += "<br><br><small>APP Version Name: <font color=\"#6A996A\">" + pInfo.versionName+"</font></small>";
            s += "<br><br><small>APP Version Code: <font color=\"#6A996A\">" + pInfo.versionCode+"</font></small>";
        } catch (PackageManager.NameNotFoundException e) {
        }
        s += "<br><br><small>OS Version: <font color=\"#6A996A\">" + System.getProperty("os.version") + " ("
                + android.os.Build.VERSION.INCREMENTAL + ")"+"</font></small>";
        s += "<br><br><small>OS API Level: <font color=\"#6A996A\">" + android.os.Build.VERSION.SDK+"</font></small>";
        s += "<br><br><small>Device: <font color=\"#6A996A\">" + android.os.Build.DEVICE+"</font></small>";
        s += "<br><br><small>Model (and Product): <font color=\"#6A996A\">" + android.os.Build.MODEL + " ("
                + android.os.Build.PRODUCT + ")"+"</font></small>";
        // TODO add application version!

        // more from
        // http://developer.android.com/reference/android/os/Build.html :
        s += "<br><br><small>Manufacturer: <font color=\"#6A996A\">" + android.os.Build.MANUFACTURER+"</font></small>";
        s += "<br><br><small>Other TAGS: <font color=\"#6A996A\">" + android.os.Build.TAGS+"</font></small>";

        s += "<br><br><small>screenWidth: <font color=\"#6A996A\">"
                + a.getWindow().getWindowManager().getDefaultDisplay()
                .getWidth()+"</font></small>";
        s += "<br><br><small>screenHeigth: <font color=\"#6A996A\">"
                + a.getWindow().getWindowManager().getDefaultDisplay()
                .getHeight()+"</font></small>";
        s += "<br><br><small>Keyboard available: <font color=\"#6A996A\">"
                + (a.getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS)+"</font></small>";

        s += "<br><br><small>Trackball available: <font color=\"#6A996A\">"
                + (a.getResources().getConfiguration().navigation == Configuration.NAVIGATION_TRACKBALL)+"</font></small>";
        s += "<br><br><small>SD Card state: <font color=\"#6A996A\">" + Environment.getExternalStorageState()+"</font></small>";
        Properties p = System.getProperties();
        Enumeration keys = p.keys();
        String key = "";
        while (keys.hasMoreElements()) {
            key = (String) keys.nextElement();
            s += "<br><br><small> - " + key + " = <font color=\"#6A996A\">" + (String) p.get(key)+"</font></small>";
        }

        return s;
    }

    //**********************************************************************************************
    //class TaskCanceler used for cancelling started tasks
    //**********************************************************************************************
    public class TaskCanceler implements Runnable{
        private List <AsyncTask> tasks;

        public TaskCanceler(){
            tasks = new ArrayList<AsyncTask>();
        }


        private void addAsyncTask(AsyncTask task){
            tasks.add(task);
        }

        @Override
        public void run() {
            for(AsyncTask at : tasks) {

                if (at.getStatus() == AsyncTask.Status.RUNNING || at.getStatus() == AsyncTask.Status.PENDING)
                    at.cancel(true);
            }
        }
    }


    //**********************************************************************************************
    //Async task for background test processing
    //**********************************************************************************************
    public class AsyncTaskRunner extends AsyncTask<String, String, String> {

        private String resp;
        //ProgressDialog progressDialog;
        String selectedTest;
        String selectedClassTest;
        int stepN;
        int repeatN;


        public AsyncTaskRunner(String test, String classTest, int step, int repeat) {
            super();
            selectedTest = test;
            selectedClassTest = classTest;
            stepN = step;
            repeatN = repeat;
        }

        //**********************************************************************************************
        @Override
        protected String doInBackground(String... params) {

            //Log.i(TAG,"isCanceled " + isCanceled);

            //if tests are canceled just return
            if(isCanceled) return "";


            //In BaseBenchmark clear() method will try "STEP_FROM" replacement again to be sure it will be done on one of both replace places
            mStep = Integer.toString(stepN);
            mFrom = Integer.toString(repeatN);
            mSelectedTxt = selectedTest;

            publishProgress(selectedTest, selectedClassTest, Integer.toString(stepN), Integer.toString(repeatN));

            try {

                testDone = 0;

                Class thisClass = Class.forName(PACKAGE_NAME + "." + selectedClassTest);
                Object iClass = thisClass.newInstance();
                Method thisMethod = thisClass.getMethod("startBenchmark", Integer.TYPE);

                mTestResult = (String) (thisMethod.invoke(iClass, 1));
                mAllTestsResult = mAllTestsResult + "\n\n" + mTestResult;

                //Save test result
                saveAutoTestResultToFile();

                testDone = 1;
                //progressDialog.dismiss();

            } catch (Exception e) {
                e.printStackTrace();
                resp = e.getMessage();
                //Get what we can from the output
                if(fileFormatFromSettings.equals("html")) {
                    HtmlUtil.addTemplateExecute();
                    HtmlUtil.replaceHtmlTag("EXECUTE", "");
                    HtmlUtil.addTemplateParagraph();
                    HtmlUtil.replaceHtmlTag("BODY", Interceptor.outputTxt);
                    Interceptor.clear();
                    HtmlUtil.addTemplateEnd();
                }

                mTestResult = Interceptor.outputTxt;
                mAllTestsResult = mAllTestsResult + "\n\n" + mTestResult;

                //Let's call GC
                System.gc();
            }

            return selectedClassTest;
        }

        //**********************************************************************************************
        @Override
        protected void onPostExecute(String result) {


            //Decrement numberOfCheckedTests(need that because test is auto checked previously)
            if(isAuto){
                //numberOfCheckedTests--;
            }

            progressDialog.dismiss();

            //displayResult(mTestResult); //UI display
            Log.i(TAG, mTestResult);    //adb logcat display

            String endTest = "";
            if (isAuto) {
                endTest = classNameTestItems[allTestsCount - 1];
            } else {
                endTest = selectedClassTests.get(allTestsCount - 1).toString();
            }

            //decrease the counter if endTest
            if (result.equals(endTest)) {
                endTestCounter--;
            }


            if (result.equals(endTest) && endTestCounter == 0 && !isCanceled) { //if last one is finished and counter is 0 and is not Canceled

                //Get total time at the end
                double totalTime = (double) (elapsedTotalTime) / 1000;
                //Inform shell that tests are done
                writeToSocketFile("isFinished", "1");

                //Set some info to shell about test status...where results are saved
                if(autoTestFile!=null) {
                    writeToSocketFile("info", "Save result to: " + autoTestFile.getAbsolutePath());
                }

                displayResult(mAllTestsResult);//UI display

                if(fileFormatFromSettings.equals("html")){
                    HtmlUtil.addTemplateSummary();
                    HtmlUtil.replaceHtmlTag("TOTAL_TIME", String.format("%5.4f", totalTime) + " seconds");
                    if(!IS_SHELL_CONTROL) {
                        HtmlUtil.replaceHtmlTag("REPEAT", mRepeatNumber + " time(s)");
                    }else{
                        HtmlUtil.replaceHtmlTag("REPEAT", mFrom + " time(s)");
                    }
                    HtmlUtil.replaceHtmlTag("TESTS", runningTests.substring(1));

                    saveAutoTestResultToFile();
                }

                String filepath = "<small><font color=\"#6A996A\">" + autoTestFile.getAbsolutePath() + "</font></small>";
                createAlertDialog("File with results created", filepath, true);
            }
        }

        //**********************************************************************************************
        @Override
        protected void onPreExecute() {

            //Decrement numberOfCheckedTests(need that because test is auto checked previously)
            if(isAuto){
                //numberOfCheckedTests = 0;
            }

            Log.i(TAG, "selectedTest:" + selectedTest);

            mDisplayDetails.setText(selectedTest + " is running please wait...");
        }

        //**********************************************************************************************
        @Override
        protected void onCancelled(String result) {
            // Runs on UI thread after cancel() is invoked
            // and doInBackground() has finished/returned
            //Log.i(TAG,"Cancel");


            //delete file with resutls
            if(autoTestFile !=null) {
                autoTestFile.delete();
                Log.i(TAG, "onCancelled: File: " + autoTestFile.getAbsolutePath() + " was deleted");
                autoTestFile = null;
            }

            //HTML BEGIN
            //Clear html string
            if(fileFormatFromSettings.equals("html")) {
                HtmlUtil.clear();
            }
            //HTML END

            testDone = 0;

            // dismiss the progress dialog
            progressDialog.dismiss();
        }

        //**********************************************************************************************
        @Override
        protected void onProgressUpdate(String... text) {


            mDisplayDetails.setText(text[0] + " is running please wait...");
            final String txt = text[0];

            String extraText = "";
            if (text[1].equals(("Test4"))) //set some extra text for this test to inform user for longer wait.
            {
                extraText = "\n\nNote: This test can take more than 30 min. so be patient...";
            }

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setTitle("Step " + text[2] + " From " + text[3]);
            progressDialog.setMessage(text[0] + " is running please wait..." + extraText);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCanceledOnTouchOutside(false);

            //Set test step in html file
            //if(fileFormatFromSettings.equals("html")){
            //    HtmlUtil.replaceHtmlTag("STEP_FROM", "Step " + text[2] + "("+text[3]+")");
            //}


            // Put a cancel button in progress dialog
            //TODO: Set Cancel button for cancelling the test
            progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                // Set a click listener for progress dialog cancel button
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //call stop benchmark method
                    try {
                        Class thisClass = Class.forName(PACKAGE_NAME + "." + selectedClassTest);
                        Object iClass = thisClass.newInstance();
                        Method thisMethod = thisClass.getMethod("stopBenchmark");
                        thisMethod.invoke(iClass);


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //Cancel all async tasks waiting in the queue
                    //handler.postDelayed(taskCanceler,0);
                    taskCanceler.run();

                    mDisplayDetails.setText(txt + " is canceled...\n\nWarning: File with results is deleted!!!");

                    // Tell the system about cancellation
                    isCanceled = true;

                    // dismiss the progress dialog
                    //progressDialog.dismiss();
                }
            });


            String testNumber = selectedClassTest.replace("Test", "");
            if(!(Integer.parseInt(testNumber) >=16 && Integer.parseInt(testNumber) <=25)) {
                progressDialog.show();
            }

            if (isAuto) {

                int mActivePosition = 0;

                //Do remove all checks here
                for (String className : classNameTestItems) {

                    //mGridViewAdapter.removeCheckAtPosition(mActivePosition, mListViewGrid);

                    if(testselection[mActivePosition] == true){
                        testselection[mActivePosition] = false;
                        numberOfCheckedTests--;
                    }
                    mActivePosition++;
                }

                mActivePosition = 0;

                mGridViewAdapter.notifyDataSetChanged();

                //Do auto click here
                for (String className : classNameTestItems) {
                    if (className.equals(text[1])) {
                        //Click on the current test
                        testselection[mActivePosition] = true;
                        numberOfCheckedTests++;
                        //mGridViewAdapter.performItemClick(mActivePosition,mListViewGrid);
                    }

                    mActivePosition++;
                }
            }
        }

    //**********************************************************************************************
    }//AsyncTaskRunner
    //**********************************************************************************************


    //**********************************************************************************************
    //Custom Adapter for GridView
    //**********************************************************************************************
    public class MyAdapter extends BaseAdapter {

        private LayoutInflater mInflater;
        String testsList[];

        public MyAdapter(String testsList[]) {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            this.testsList = testsList;
        }


        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public String getTextByPosition(int pos) {
            return testsList[pos];
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            //Log.i(TAG,"getView_position:" +position);

            ViewHolder holder;
            if (convertView == null) {
                //Log.i(TAG,"getView_position_null:" +position);
                holder = new ViewHolder();
                convertView = mInflater.inflate(
                        R.layout.listview, null);
                holder.textview = (TextView) convertView.findViewById(R.id.itemText);
                holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

                convertView.setTag(holder);
            }
            else {
                //Log.i(TAG,"getView_position_not_null:" +position);
                holder = (ViewHolder) convertView.getTag();
            }
            holder.checkbox.setId(position);
            holder.textview.setId(position);

            holder.textview.setText(testsList[position]);
            holder.textview.setTextSize(getPixels(pixMin));

            holder.checkbox.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (testselection[id]) {
                        cb.setChecked(false);
                        testselection[id] = false;
                        numberOfCheckedTests--;
                        //Log.i(TAG, "uncheck");
                    } else {
                        cb.setChecked(true);
                        testselection[id] = true;
                        numberOfCheckedTests++;
                        //Log.i(TAG, "check");
                    }
                }
            });


            holder.checkbox.setChecked(testselection[position]);
            holder.id = position;
            return convertView;
        }


        public void removeCheckAtPosition(int i, GridView gr) {

            //It is needed to check the max index used in getView method(because max index can be smaller than count of gridview elements)
            //So catch is used to prevent from crash when i is greater than max index used in getView
            try {
                //Log.i(TAG, "position:" + i);

                ViewGroup gridChild = (ViewGroup) gr.getChildAt(i);
                int childSize = gridChild.getChildCount();
                for (int k = 0; k < childSize; k++) {
                    if (gridChild.getChildAt(k) instanceof CheckBox) {
                        CheckBox cb = (CheckBox) gridChild.getChildAt(k);
                        //Log.i(TAG,""+i);
                        if (testselection[i]) {
                            cb.setChecked(false);
                            testselection[i] = false;
                            numberOfCheckedTests--;
                            //Log.i(TAG, "uncheck");
                        }
                    }
                }

            }catch(Exception e){
                Log.i(TAG, "(Expected error):removeCheckAtPosition:" + e.toString());
            }
        }


        public void performItemClick(int position, GridView gr){

            ViewGroup gridChild = (ViewGroup) gr.getChildAt(position);
            int childSize = gridChild.getChildCount();
            for(int k = 0; k < childSize; k++) {
                if(gridChild.getChildAt(k) instanceof CheckBox ) {
                    CheckBox cb = (CheckBox)gridChild.getChildAt(k);
                    cb.setChecked(true);
                    testselection[position] = true;
                    numberOfCheckedTests++;
                }
            }
        }

    //**********************************************************************************************
    }//MyAdapter
    //**********************************************************************************************

    class ViewHolder {
        TextView textview;
        CheckBox checkbox;
        int id;
    //**********************************************************************************************
    }//ViewHolder
    //**********************************************************************************************

    //Use object of this class for synchronization
    public static class Lock {
        private boolean condition;

        public boolean conditionMet() {
            return condition;
        }

        public void setCondition(boolean condition) {
            this.condition = condition;
        }
    }

//**********************************************************************************************
}//MainActivity
//**********************************************************************************************