summaryrefslogtreecommitdiff
path: root/src/plugins/emulator/src/com/motorola/studio/android/emulator/device/instance/options/StartupOptionsMgt.java
blob: bd5710d745547b4c769b3d527fd6ec5bc3f194a5 (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
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.motorola.studio.android.emulator.device.instance.options;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.motorola.studio.android.common.log.StudioLogger;
import com.motorola.studio.android.emulator.EmulatorPlugin;
import com.motorola.studio.android.emulator.i18n.EmulatorNLS;

/**
 * This class provides methods to manage startup options
 * 
 */
public class StartupOptionsMgt implements IStartupOptionsConstants
{

    /**
     * List of all startup options groups (the startup options themselves will
     * be accessed through the use of a method in the group object that returns
     * the startup options in that group)
     */
    private static List<StartupOptionsGroup> startupOptionsGroupsList = null;

    /**
     * List of all startup options, indexed by their names, for fast access
     */
    private static Map<String, StartupOption> startupOptionsMap =
            new HashMap<String, StartupOption>();

    /*
     * Load the startup options / groups list
     */
    static
    {
        load();
    }

    /**
     * Get the startup options groups list
     * 
     * @return startup options groups list
     */
    public static List<StartupOptionsGroup> getStartupOptionsGroupsList()
    {
        return startupOptionsGroupsList;
    }

    /**
     * Read all groups and startup options available for editing from a XML
     * and stores the information in the correspondent beans
     */
    public static void load()
    {

        try
        {
            // Clear startup options groups list
            startupOptionsGroupsList = new ArrayList<StartupOptionsGroup>();

            // Define XML path
            InputStream xmlStream =
                    EmulatorPlugin.getDefault().getBundle().getEntry(STARTUP_OPTIONS_XML_PATH)
                            .openStream();

            // Load XML
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(xmlStream);

            /*
             * Iterate through Startup Groups 
             */
            Element rootNode = document.getDocumentElement();
            NodeList startupOptionsGroups = rootNode.getElementsByTagName(GROUP_TAG);
            for (int i = 0; i < startupOptionsGroups.getLength(); i++)
            {
                /*
                 * Create group
                 */
                Element group = (Element) startupOptionsGroups.item(i);

                String strKey = group.getAttributeNode(GROUP_TAG_ID).getNodeValue();
                strKey =
                        Platform.getResourceString(EmulatorPlugin.getDefault().getBundle(), strKey);

                StartupOptionsGroup startupOptionsGroup = new StartupOptionsGroup(strKey);
                startupOptionsGroup.setTitle(startupOptionsGroup.getId());

                /*
                 * Iterate through Startup Options in this group
                 */
                NodeList startupOptions = group.getElementsByTagName(STARTUP_OPT_TAG);
                startupOptionsGroup.setStartupOptions(new ArrayList<StartupOption>()); // clear startup options 
                for (int j = 0; j < startupOptions.getLength(); j++)
                {
                    /*
                     * Create startup option
                     */
                    Element option = (Element) startupOptions.item(j);
                    StartupOption startupOption =
                            new StartupOption(option.getAttributeNode(STARTUP_OPT_TAG_NAME)
                                    .getNodeValue(), getStartupOptionType(option.getAttributeNode(
                                    STARTUP_OPT_TAG_TYPE).getNodeValue())); // name and type
                    strKey = option.getAttributeNode(STARTUP_OPT_TAG_FRIENDLY_NAME).getNodeValue();

                    strKey =
                            Platform.getResourceString(EmulatorPlugin.getDefault().getBundle(),
                                    strKey);

                    startupOption.setUserFriendlyName(strKey); // friendly name

                    strKey =
                            option.getElementsByTagName(STARTUP_OPT_TAG_DESCRIPTION).item(0)
                                    .getTextContent();

                    strKey =
                            Platform.getResourceString(EmulatorPlugin.getDefault().getBundle(),
                                    strKey);

                    startupOption.setDescription(strKey); // description

                    if (option.getAttributeNode(STARTUP_OPT_TAG_TYPE_DETAILS) != null)
                    {
                        startupOption.setTypeDetails(option.getAttributeNode(
                                STARTUP_OPT_TAG_TYPE_DETAILS).getNodeValue()); // type details
                    }
                    // Iterate through startup option pre-defined values, if any
                    NodeList preDefinedValuesContainer =
                            option.getElementsByTagName(PREDEFINED_VALUES_TAG);
                    startupOption.setPreDefinedValues(new ArrayList<String>()); // clear pre-defined values
                    if (preDefinedValuesContainer.getLength() > 0)
                    {
                        NodeList preDefinedValues =
                                ((Element) preDefinedValuesContainer.item(0))
                                        .getElementsByTagName(PREDEFINED_VALUE_TAG);
                        for (int k = 0; k < preDefinedValues.getLength(); k++)
                        {
                            // Add pre-defined values to the option
                            Element preDefinedValue = (Element) preDefinedValues.item(k);
                            startupOption.getPreDefinedValues().add(
                                    preDefinedValue.getTextContent());
                        }
                    }

                    /*
                     * Add startup options to the group
                     */
                    startupOptionsGroup.getStartupOptions().add(startupOption);

                    startupOptionsMap.put(startupOption.getName(), startupOption);

                }

                /*
                 * Add groups to the groups list
                 */
                startupOptionsGroupsList.add(startupOptionsGroup);
            }

        }
        catch (Exception e)
        {
            StudioLogger.error("Failed to load startup options");
        }

    }

    /**
     * Validate the values assigned for the startup options marked as checked (the ones that are
     * being used), according to its type and type details.
     * 
     * @return Status object with the result of the validation
     */
    public static Status validate()
    {
        Status status = (Status) Status.OK_STATUS;
        String msg = null;

        /*
         * Iterate through Startup Groups 
         */
        for (StartupOptionsGroup group : getStartupOptionsGroupsList())
        {
            /*
             * Iterate through Startup Options in this group
             */
            for (StartupOption startupOption : group.getStartupOptions())
            {
                /*
                 * Check if the Startup Option is checked
                 */
                if (startupOption.isChecked() && (status.isOK()))
                {

                    String name = startupOption.getName(); // startup option name
                    String ufname = startupOption.getUserFriendlyName(); // user-friendly startup option name
                    String value = startupOption.getValue(); // startup option value
                    String typeDetails = startupOption.getTypeDetails(); // startup option type detail

                    /*
                     * General validation: no quotes in values
                     */
                    if ((!startupOption.getName().equals(OTHERS_OTHER))
                            && (value.indexOf("\"") >= 0))
                    {
                        msg =
                                NLS.bind(
                                        EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_NoQuotes,
                                        ufname);
                    }
                    else
                    {

                        /*
                         * Call the appropriate validation method
                         */
                        switch (startupOption.getType())
                        {
                            case TYPE_TEXT:
                                msg = validateTextField(name, ufname, value, typeDetails);
                                break;

                            case TYPE_NUMBER:
                                msg = validadeNumberField(name, ufname, value, typeDetails);
                                break;

                            case TYPE_PATH:
                                msg = validadePathField(name, ufname, value, typeDetails);
                                break;
                        }
                    }

                    /*
                     * If some validation has failed, return with an error message
                     */
                    if (msg != null)
                    {
                        status = new Status(Status.ERROR, EmulatorPlugin.PLUGIN_ID, msg);
                        break;
                    }

                }
            }
        }

        return status;

    }

    /**
     * Validate the startup option value for an startup option of "text" type
     * 
     * @param name the startup option name
     * @param ufname the user-friendly startup option name
     * @param value the current assigned value for the startup option
     * @param typeDetails any special requirements that the assigned value must be match
     * @return null if the value assigned for the startup option is a valid one or an error message otherwise
     */
    private static String validateTextField(String name, String ufName, String value,
            String typeDetails)
    {
        String msg = null;

        // Check if the value is blank
        if ((value == null) || (value.equals("")))
        {
            msg = NLS.bind(EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_TextBlank, ufName);
        }

        return msg;

    }

    /**
     * Validate the startup option value for an startup option of "number" type
     * 
     * @param name the startup option name
     * @param ufname the user-friendly startup option name
     * @param value the current assigned value for the startup option
     * @param typeDetails any special requirements that the assigned value must be match
     * @return null if the value assigned for the startup option is a valid one or an error message otherwise
     */
    private static String validadeNumberField(String name, String ufName, String value,
            String typeDetails)
    {
        String msg = null;

        // Check if the value is blank
        if ((value == null) || (value.equals("")))
        {
            msg =
                    NLS.bind(EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_NumberRequired,
                            ufName);
        }
        else
        {

            try
            {
                /*
                 * Check if it's an Integer.
                 * If it's not, an exception will be thrown
                 */
                int intValue = Integer.parseInt(value);

                /*
                 * Check if it's positive
                 */
                if (intValue < 0)
                {
                    msg =
                            NLS.bind(
                                    EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_NumberMustBePositiveInteger,
                                    ufName);
                }
                else
                {

                    /*
                     * Check if the value is in the correct range
                     */
                    if (typeDetails != null)
                    {
                        String[] valueRange = typeDetails.split(";");
                        if ((intValue < Integer.parseInt(valueRange[0]))
                                || (intValue > Integer.parseInt(valueRange[1])))
                        {
                            // the value is not in the correct range
                            msg =
                                    NLS.bind(
                                            EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_NumberIntRange,
                                            new String[]
                                            {
                                                    ufName, valueRange[0], valueRange[1]
                                            });
                        }
                    }
                }

            }
            catch (NumberFormatException ex)
            {
                // it's not a number
                msg =
                        NLS.bind(
                                EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_NumberMustBeInteger,
                                ufName);
            }
        }

        return msg;

    }

    /**
     * Validate the startup option value for an startup option of "path" type
     * 
     * @param name the startup option name
     * @param ufname the user-friendly startup option name
     * @param value the current assigned value for the startup option
     * @param typeDetails any special requirements that the assigned value must be match
     * @return null if the value assigned for the startup option is a valid one or an error message otherwise
     */
    private static String validadePathField(String name, String ufName, String value,
            String typeDetails)
    {
        String msg = null;

        if ((value == null) || (value.equals("")))
        {
            msg = NLS.bind(EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_PathRequired, ufName);
        }
        else
        {

            File file = new File(value);

            /*
             * Validate folder
             */
            if (typeDetails.equals(TYPE_PATH_DIR))
            {
                /*
                 * Check if the path exists
                 */
                if (!file.exists())
                {
                    // the folder doesn't exist
                    msg =
                            NLS.bind(
                                    EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_PathDirNotExist,
                                    ufName);
                }
                else
                {
                    if (file.isFile())
                    {
                        // it's not a folder
                        msg =
                                NLS.bind(
                                        EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_PathMustBeDir,
                                        ufName);
                    }
                }
            }
            /*
             * Validate file
             */
            else
            {
                if (!file.exists())
                {
                    // the file doesn't exist
                    msg =
                            NLS.bind(
                                    EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_PathFileNotExist,
                                    ufName);
                }
                else
                {
                    // it's not a file
                    if (file.isDirectory())
                    {
                        msg =
                                NLS.bind(
                                        EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_PathMustBeFile,
                                        ufName);
                    }
                    // it doesn't have the correct extension
                    else
                    {
                        if (!typeDetails.equals("." + (new Path(value)).getFileExtension()))
                        {
                            msg =
                                    NLS.bind(
                                            EmulatorNLS.ERR_PropertiesMainComposite_StartupOpt_PathIncorrectFileType,
                                            new String[]
                                            {
                                                    ufName, typeDetails
                                            });
                        }
                    }
                }
            }
        }
        return msg;

    }

    /**
     * Generates the list of parameters that shall to be sent to the Emulator
     * 
     * @return the list of parameters that shall to be sent to the Emulator
     */
    public static String getParamList()
    {
        String paramList = "";

        /*
         * Iterate through Startup Groups 
         */
        for (StartupOptionsGroup group : getStartupOptionsGroupsList())
        {
            /*
             * Iterate through Startup Options in this group
             */
            int startupOptionType;
            for (StartupOption startupOption : group.getStartupOptions())
            {
                startupOptionType = startupOption.getType();
                if (startupOption.isChecked()) // check if the startup option is being used
                {
                    if (startupOptionType == TYPE_NONE)
                    {
                        paramList += ((paramList.equals("")) ? "" : " ") + startupOption.getName();
                    }
                    else
                    {
                        if ((startupOption.getName().equals(OTHERS_OTHER)))
                        {

                            paramList +=
                                    ((paramList.equals("")) ? "" : " ") + startupOption.getValue();

                        }
                        else
                        {
                            String value = startupOption.getValue();

                            if (Platform.getOS().equals(Platform.OS_WIN32))
                            {
                                if (value.contains(" "))
                                {
                                    value = "\"" + value + "\"";
                                }
                            }
                            else
                            {
                                if (value.contains("\\"))
                                {
                                    value = value.replace("\\", "\\\\");
                                }

                                if (value.contains(" "))
                                {
                                    value = value.replace(" ", "\\ ");
                                }
                            }

                            paramList +=
                                    ((paramList.equals("")) ? "" : " ") + startupOption.getName()
                                            + (value.trim().length() > 0 ? " " + value : "");
                        }
                    }
                }
            }
        }

        return paramList;

    }

    /**
     * Load values from a Properties object
     * 
     * @param properties properties object containing the values that must be loaded into de model
     */
    private static void loadValues(Properties properties)
    {
        /*
         * Iterate through Startup Groups 
         */
        for (StartupOptionsGroup group : getStartupOptionsGroupsList())
        {
            /*
             * Iterate through Startup Options in this group
             */
            String soValue = "";
            for (StartupOption startupOption : group.getStartupOptions())
            {
                soValue = properties.getProperty(startupOption.getName());
                if (soValue != null)
                {
                    startupOption.setChecked(true);
                    startupOption.setValue(soValue);
                }
                else
                {
                    startupOption.setChecked(false);
                    startupOption.setValue("");
                }
                startupOption.updateUI();
            }
        }

    }

    /**
     * Create a properties object with the information contained in a command line
     * 
     * @param commandLine the command line used to start the emulator
     * @return properties object with the information contained in a command line
     */
    public static Properties parseCommandLine(String commandLine)
    {
        Properties properties = new Properties();

        if (!commandLine.equals(""))
        {

            /*
             * Iterate through Startup Groups 
             */
            for (StartupOptionsGroup group : getStartupOptionsGroupsList())
            {
                /*
                 * Iterate through Startup Options in this group
                 */
                String soName, soValue = "";
                int soType, shift = 0;
                for (StartupOption startupOption : group.getStartupOptions())
                {
                    soName = startupOption.getName();
                    soType = startupOption.getType();
                    if (commandLine.startsWith(soName))
                    {
                        if (soType == TYPE_NONE)
                        {
                            soValue = new Boolean(true).toString();
                            shift = soName.length() + 1;
                        }
                        else
                        {
                            commandLine =
                                    commandLine
                                            .substring(soName.length() + 1, commandLine.length());
                            //int endValueIndex = commandLine.indexOf("\"");
                            ParameterBean param = getNextParameterValue(commandLine);
                            soValue = param.getValue();
                            shift = param.getLastPosition() + 1;
                        }

                        properties.put(startupOption.getName(), soValue);

                        if (shift < commandLine.length() - 1)
                        {
                            commandLine = commandLine.substring(shift, commandLine.length());
                        }
                        else
                        {
                            commandLine = "";
                        }
                    }
                }
            }

            if (!commandLine.equals(""))
            {
                properties.put(OTHERS_OTHER, commandLine);
            }
        }

        return properties;

    }

    /**
     * Load values from a command line
     * 
     * @param commandLine the command line used to start the emulator
     */
    public static void loadFromCommandLine(String commandLine)
    {
        loadValues(parseCommandLine(commandLine));
    }

    /**
     * Convert the type of the startup option from a string
     * to a number
     * 
     * @param type string that represents the type
     * @return number that represents the type 
     */
    private static int getStartupOptionType(String type)
    {
        return (TYPE_MAP.get(type)).intValue();
    }

    /**
     * Parses the next parameter value on a command line
     * 
     * @param commandLine the command line
     * 
     * @return a bean containing the parameter value and the last position looked at
     *         the command line
     */
    private static ParameterBean getNextParameterValue(String commandLine)
    {
        boolean isWin32 = Platform.getOS().equals(Platform.OS_WIN32);
        boolean escaped = false;
        boolean quoted = false;

        char c;
        String value = "";
        int i;

        for (i = 0; i < commandLine.length(); i++)
        {
            c = commandLine.charAt(i);

            if (escaped)
            {
                value += c;
                escaped = false;
            }
            else if (c == '\\' && !isWin32)
            {
                escaped = true;
            }
            else if (c == '"' && isWin32)
            {
                if (value.length() == 0)
                {
                    quoted = true;
                }
                else if (quoted)
                {
                    break;
                }
                else
                {
                    value += c;
                }
            }
            else if ((c == ' ') && (!quoted))
            {
                break;
            }
            else
            {
                value += c;
            }
        }

        return new ParameterBean(value, ((quoted) ? i + 1 : i));
    }

    /**
     * Bean used to identify a parameter value when parsing the
     * startup options
     *  
     */
    private static class ParameterBean
    {
        private final String value;

        private final int lastPosition;

        /**
         * Constructor
         * 
         * @param value The parameter value
         * @param lastPosition The last position looked at the command line before stopping
         *        the parse operation
         */
        public ParameterBean(String value, int lastPosition)
        {
            this.value = value;
            this.lastPosition = lastPosition;
        }

        /**
         * Retrieves the parameter value
         * 
         * @return the parameter value
         */
        public String getValue()
        {
            return value;
        }

        /**
         * Retrieves the last position looked at the command line before stopping
         *           the parse operation
         * 
         * @return the last position looked at the command line before stopping
         *         the parse operation
         */
        public int getLastPosition()
        {
            return lastPosition;
        }
    }
}