summaryrefslogtreecommitdiff
path: root/src/plugins/emulator/src/com/motorola/studio/android/emulator/ui/controls/skin/SkinComposite.java
blob: fa50267630e4517e37813f9837055e6ee8a650f6 (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
/*
* 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.ui.controls.skin;

import static com.motorola.studio.android.common.log.StudioLogger.debug;
import static com.motorola.studio.android.common.log.StudioLogger.error;
import static com.motorola.studio.android.common.log.StudioLogger.info;

import java.util.Collection;

import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.ui.PlatformUI;

import com.motorola.studio.android.adt.DDMSFacade;
import com.motorola.studio.android.common.utilities.EclipseUtils;
import com.motorola.studio.android.emulator.core.exception.InstanceStopException;
import com.motorola.studio.android.emulator.core.exception.SkinException;
import com.motorola.studio.android.emulator.core.model.IAndroidEmulatorInstance;
import com.motorola.studio.android.emulator.core.model.IInputLogic;
import com.motorola.studio.android.emulator.core.skin.AndroidPressKey;
import com.motorola.studio.android.emulator.core.skin.AndroidSkinBean;
import com.motorola.studio.android.emulator.core.skin.IAndroidKey;
import com.motorola.studio.android.emulator.core.skin.IAndroidSkin;
import com.motorola.studio.android.emulator.i18n.EmulatorNLS;
import com.motorola.studio.android.emulator.logic.AndroidLogicUtils;
import com.motorola.studio.android.emulator.ui.controls.IAndroidComposite;
import com.motorola.studio.android.emulator.ui.controls.UIHelper;
import com.motorola.studio.android.emulator.ui.handlers.IHandlerConstants;
import com.motorola.studio.android.nativeos.NativeUIUtils;

/**
 * DESCRIPTION: This class implements the UI part of the skin
 * 
 * RESPONSIBILITY: - Provide the skin image with correct layout - Provide means
 * for the user to send events to the emulator through the phone emulated
 * keyboard - Provide means for the user to change the zoom and window scrolling
 * properties
 * 
 * COLABORATORS: None.
 * 
 * USAGE: Create an instance of this class every time an phone instance is to be
 * displayed Call the public methods to interact with the skin.
 */
public class SkinComposite extends Composite implements IAndroidComposite
{
    // Constants for defining interval between keystrokes
    // when using long mouse click
    public static final int FIRST_REFRESH_DELAY_MS = 300;

    public static final int REFRESH_DELAY_PERIOD_MS = 100;

    // Minimum value to be used as zoom factor. This is necessary to avoid
    // divisions to zero
    private static final double MINIMUM_ZOOM_FACTOR = 0.0001;

    // The step increased or decreased from the zoom factor using mouse wheel
    private static final double ZOOM_STEP = 0.5;

    /**
     * A rectangle that represents the part of the currentSkin image that fits
     * into the view/screen. It must fit inside the currentSkinImage borders (0,
     * 0, current skin image width, current skin image height)
     */
    private final Rectangle displayRectangle = new Rectangle(0, 0, 0, 0);

    /**
     * The skin elements provider
     */
    private IAndroidSkin skin;

    /**
     * The image that is currently drawn at screen. It is one image provided by
     * the skin that is scaled by the current zoom factor
     */
    private Image currentSkinImage;

    /**
     * The key that mouse is over at the current moment
     */
    private IAndroidKey currentKey;

    /**
     * The flag indicating that Ctrl key is pressed
     */
    private boolean ctrlPressed = false;

    /**
     * SWT key pressed/released events listener
     */
    private KeyListener keyListener;

    private MouseListener mainDisplayMouseListener;

    private MouseMoveListener mainDisplayMouseMoveListener;

    /**
     * Flag that indicates if the skin can use the scroll bars to draw itself
     * bigger than the view client area
     */
    private boolean scrollBarsUsed = true;

    /**
     * True if the mouse left button is pressed. False otherwise
     */
    private boolean isMouseLeftButtonPressed;

    /**
     * True if the mouse right button is pressed. False otherwise
     */
    private boolean isMouseRightButtonPressed;

    /**
     * The zoom factor whose default value is 1.0 (100%)
     */
    private double zoomFactor = 1.0;

    private double embeddedViewScale = 1.0;

    private IInputLogic androidInput;

    private boolean isMouseMainDisplayLeftButtonPressed;

    IAndroidEmulatorInstance androidInstance;

    /**
     * Creates a SkinComposite This composite holds the screens in the correct
     * positions and maps the keys
     * 
     * @param parent
     *            The parent composite in which the UI part of the instance
     *            shall be created
     * @param androidSkin
     *            The skin object that contain data for getting skin information
     */
    public SkinComposite(Composite parent, IAndroidSkin androidSkin,
            IAndroidEmulatorInstance instance)
    {
        super(parent, SWT.BACKGROUND | SWT.H_SCROLL | SWT.V_SCROLL);
        skin = androidSkin;
        androidInstance = instance;

        // Add listeners
        addListeners();
        createListenersForMainDisplay();

        setToolTipText(null);

        androidInput = instance.getInputLogic();

        // Init the scroll bars
        initScrollBars();

        if (!Platform.getOS().equals(Platform.OS_MACOSX))
        {
            hideEmulatorWindow();
        }
    }

    private void hideEmulatorWindow()
    {
        int port =
                AndroidLogicUtils.getEmulatorPort(DDMSFacade.getSerialNumberByName(androidInstance
                        .getName()));
        long windowHandle = NativeUIUtils.getWindowHandle(androidInstance.getName(), port);
        androidInstance.setWindowHandle(windowHandle);
        NativeUIUtils.hideWindow(windowHandle);
    }

    /**
     * Add listeners to the skin composite
     */
    private void addListeners()
    {

        addPaintListener(new PaintListener()
        {
            /*
             * (non-Javadoc)
             * @see org.eclipse.swt.events.PaintListener#paintControl(org.eclipse.swt.events.PaintEvent)
             */
            public void paintControl(PaintEvent e)
            {
                // This listener is invoked when a regular SWT redraw is invoked. In this case, no keys 
                // have changed. That's why we pass "null" as parameter
                drawSkin(e.gc, null);
            }
        });

        addMouseListener(new MouseAdapter()
        {
            /*
             * (non-Javadoc)
             * @see org.eclipse.swt.events.MouseAdapter#mouseUp(org.eclipse.swt.events.MouseEvent)
             */
            @Override
            public void mouseUp(MouseEvent e)
            {
                if (e.button == 1)
                {
                    isMouseLeftButtonPressed = false;

                }
                else if (e.button == 3)
                {
                    isMouseRightButtonPressed = false;
                }

                // Handle left button mouse up event
                if (e.button == 1)
                {
                    cancelMouseSelection();
                }
            }

            /*
             * (non-Javadoc)
             * @see org.eclipse.swt.events.MouseAdapter#mouseDown(org.eclipse.swt.events.MouseEvent)
             */
            @Override
            public void mouseDown(MouseEvent e)
            {
                setFocus();
                if (e.button == 1)
                {
                    isMouseLeftButtonPressed = true;
                }
                else if (e.button == 3)
                {
                    isMouseRightButtonPressed = true;
                }

                if (currentKey != null)
                {
                    ImageData mergedImage = getKeyImageData(currentKey, false);
                    setSkinImage(mergedImage, currentKey, true);

                    // Handle left button mouse down event
                    if ((e.button == 1) && (!isMouseRightButtonPressed) && (currentKey != null))
                    {
                        androidInput.sendClick(currentKey.getKeysym(), true);
                    }

                    // Handle right button mouse down event
                    else if (e.button == 3)
                    {
                        cancelMouseSelection();
                    }

                }
            }
        });

        addMouseMoveListener(new MouseMoveListener()
        {
            /*
             * (non-Javadoc)
             * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
             */
            public void mouseMove(MouseEvent e)
            {
                int posX = (int) ((e.x + displayRectangle.x) / zoomFactor);
                int posY = (int) ((e.y + displayRectangle.y) / zoomFactor);
                IAndroidKey keyData = getSkinKey(posX, posY);

                if ((isMouseLeftButtonPressed) && (keyData != currentKey))
                {
                    cancelMouseSelection();
                }

                if (!isMouseLeftButtonPressed && (currentKey != keyData))
                {
                    changeCurrentKey(keyData);
                }
            }
        });

        // listener to change the zoom factor using Ctrl + Mouse Wheel
        addMouseWheelListener(new MouseWheelListener()
        {
            public void mouseScrolled(MouseEvent event)
            {
                if (ctrlPressed)
                {

                    // the floor and ceil are required if "fits to window" was
                    // checked.
                    double roundedZoomFactor = Math.floor(zoomFactor / ZOOM_STEP) * ZOOM_STEP;

                    if ((event.count > 0) && (roundedZoomFactor < IHandlerConstants.MAXIMUM_ZOOM))
                    {
                        // increase zoom factor
                        setZoomFactor(roundedZoomFactor + ZOOM_STEP);
                        applyZoomFactor();
                    }

                    else if ((event.count < 0)
                            && (roundedZoomFactor > IHandlerConstants.MINIMUM_ZOOM))
                    {
                        // decrease zoom factor
                        setZoomFactor(roundedZoomFactor - ZOOM_STEP);
                        applyZoomFactor();
                    }

                }
            }
        });

        addMouseTrackListener(new MouseTrackAdapter()
        {
            @Override
            public void mouseExit(MouseEvent mouseevent)
            {
                changeCurrentKey(null);
            }
        });

        addControlListener(new ControlAdapter()
        {
            /*
             * (non-Javadoc)
             * @see org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events.ControlEvent)
             */
            @Override
            public void controlResized(ControlEvent event)
            {
                if (scrollBarsUsed)
                {
                    synchronizeScrollBars();
                }
                else
                {
                    ImageData imageData = getImageData(false, false);
                    setSkinImage(imageData, null, false);
                }
            }
        });

    }

    public void applyLayout(String layoutName)
    {
        // Populate the attributes with information from skin
        AndroidSkinBean skinBean = null;

        try
        {
            skinBean = skin.getSkinBean(layoutName);
        }
        catch (SkinException e)
        {
            error("The skin data could not be retrieved from skin files. Cause: " + e.getMessage());
            EclipseUtils.showErrorDialog(e);
        }

        // Create layout and set it to composite
        if (skinBean != null)
        {
            // When changing to a new layout, the key may move to another position
            // It does not make sense to keep the old key object
            currentKey = null;

            // Change the background color to the one that applies to the layout being set
            RGB color = skin.getBackgroundColor(layoutName);
            setBackground(new Color(PlatformUI.getWorkbench().getDisplay(), color));

            Layout prevLayout = getLayout();
            if (prevLayout instanceof AndroidSkinLayout)
            {
                ((AndroidSkinLayout) prevLayout).dispose();
            }

            AndroidSkinLayout androidLayout =
                    new AndroidSkinLayout(skinBean, skin.isFlipSupported());
            setLayout(androidLayout);

            embeddedViewScale = skinBean.getEmbeddedViewScale();

            layout();
            redraw();
        }
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.swt.widgets.Widget#dispose()
     */
    @Override
    public void dispose()
    {
        if (androidInput != null)
        {
            androidInput.dispose();
        }

        if (currentSkinImage != null)
        {
            currentSkinImage.dispose();
        }

        Layout layout = getLayout();
        if (layout instanceof AndroidSkinLayout)
        {
            ((AndroidSkinLayout) layout).dispose();
        }

        skin = null;
        currentKey = null;
        keyListener = null;
        mainDisplayMouseListener = null;
        mainDisplayMouseMoveListener = null;

        if (!Platform.getOS().equals(Platform.OS_MACOSX))
        {
            long hnd = androidInstance.getWindowHandle();
            if (hnd > 0)
            {
                NativeUIUtils.showWindow(hnd);
                NativeUIUtils.restoreWindow(hnd);
            }

            //Force update on redrawing
            androidInstance.setWindowHandle(0);
        }

        super.dispose();
    }

    /**
     * Sets the zoom factor to use in the instance
     */
    public void applyZoomFactor()
    {
        if (getZoomFactor() == 0)
        {
            scrollBarsUsed = false;
            getVerticalBar().setEnabled(false);
            getHorizontalBar().setEnabled(false);
        }
        else
        {
            scrollBarsUsed = true;
            getVerticalBar().setEnabled(true);
            getHorizontalBar().setEnabled(true);
        }

        // Resets translation
        displayRectangle.x = 0;
        displayRectangle.y = 0;

        redrawReleasedImage();

    }

    /**
     * Sets the flip/slide status of the phone
     */
    private void redrawReleasedImage()
    {
        if (currentSkinImage != null)
        {
            ImageData imageData = getImageData(false, false);
            setSkinImage(imageData, null, false);
            layout();
            redraw();
        }

        if (scrollBarsUsed)
        {
            synchronizeScrollBars();
        }
    }

    /**
     * Performs the skin draw operation.
     * 
     * @param gcUsedToDraw
     *            The gc object associated with the skin composite that is used
     *            to draw the images
     */
    private void drawSkin(GC gcUsedToDraw, IAndroidKey changedKey)
    {
        if (currentSkinImage == null)
        {
            IAndroidEmulatorInstance instance = UIHelper.getInstanceAssociatedToControl(this);
            ImageData initialSkinImage = getImageData(false, false);
            setSkinImage(initialSkinImage, null, false);
            applyLayout(instance.getCurrentLayout());

            if (scrollBarsUsed)
            {
                synchronizeScrollBars();
            }
        }

        if (displayRectangle != null)
        {
            int srcXPos, srcYPos, srcWidth, srcHeight;
            int destXPos, destYPos, destWidth, destHeight;
            if (changedKey == null)
            {
                srcXPos = displayRectangle.x;
                srcYPos = displayRectangle.y;
                srcWidth = displayRectangle.width;
                srcHeight = displayRectangle.height;
                destXPos = 0;
                destYPos = 0;
                destWidth = Math.min(currentSkinImage.getImageData().width, displayRectangle.width);
                destHeight =
                        Math.min(currentSkinImage.getImageData().height, displayRectangle.height);
            }
            else
            {
                srcXPos =
                        ((int) (changedKey.getKeyArea().x > 0 ? changedKey.getKeyArea().x * zoomFactor
                                : 0));
                srcYPos =
                        ((int) (changedKey.getKeyArea().y > 0 ? changedKey.getKeyArea().y * zoomFactor
                                : 0));
                srcWidth = ((int) (changedKey.getKeyArea().width * zoomFactor));
                srcHeight = ((int) (changedKey.getKeyArea().height * zoomFactor));
                destXPos = srcXPos - displayRectangle.x;
                destYPos = srcYPos - displayRectangle.y;
                destWidth = srcWidth;
                destHeight = srcHeight;
            }

            gcUsedToDraw.drawImage(currentSkinImage, srcXPos, srcYPos, srcWidth, srcHeight,
                    destXPos, destYPos, destWidth, destHeight);
        }
    }

    /**
     * Loads a new screen image to the currentSkin attribute. This action
     * updates the skin image that is drawn as skin
     * 
     * @param imageToSet
     *            The new skin pixel data, as retrieved from the skin plugin
     * @param changedKey
     *            The key that has changed, if any. If one if provided, only the key area should be redrawn.
     *            Can be <code>null</code>.
     * @param forceDraw
     *            true if a draw is needed after setting the new image; false if replacing skin image only 
     *            will be performed.
     */
    private void setSkinImage(ImageData imageToSet, IAndroidKey changedKey, boolean forceDraw)
    {

        recalculateZoomFactor();

        if (imageToSet != null)
        {
            if (currentSkinImage != null)
            {
                currentSkinImage.dispose();
            }

            // Scales the chosen image and sets to currentSkin attribute
            //
            // NOTE: width and height cannot be equal to MINIMUM_ZOOM_FACTOR,
            // because this
            // will raise an IllegalArgumentException when constructing the
            // Image object
            int width =
                    (zoomFactor == MINIMUM_ZOOM_FACTOR ? 1 : (int) (imageToSet.width * zoomFactor));
            int height =
                    (zoomFactor == MINIMUM_ZOOM_FACTOR ? 1 : (int) (imageToSet.height * zoomFactor));
            currentSkinImage = new Image(getDisplay(), imageToSet.scaledTo(width, height));

            // It only makes sense to reset the translation if the skin image is really being changed
            // It will happen if we set a image data without specifying a changed key
            if (changedKey == null)
            {
                displayRectangle.x = 0;
                displayRectangle.y = 0;
            }

            if (forceDraw)
            {
                layout();

                GC gc = new GC(this);
                drawSkin(gc, changedKey);
                gc.dispose();
            }
        }
        else
        {
            info("It was requested to set a skin image that was null. Operation aborted.");
        }
    }

    /**
     * This method is responsible to set the scroll bar attributes so that they
     * reflect the size of the current image at the current zoom factor
     */
    private void synchronizeScrollBars()
    {
        // Syncronizing only makes sense if there is a skin being drawn
        if (currentSkinImage != null)
        {

            // Retrieves the current image and client area sizes
            Rectangle imageBound = currentSkinImage.getBounds();
            int cw = getClientArea().width;
            int ch = getClientArea().height;

            // Updates horizontal scroll bar attributes
            ScrollBar horizontal = getHorizontalBar();
            horizontal.setIncrement((cw / 100));
            horizontal.setPageIncrement((cw / 2));
            horizontal.setMaximum(imageBound.width);
            horizontal.setThumb(cw);
            horizontal.setSelection(displayRectangle.x);

            // Updates vertical scroll bar attributes
            ScrollBar vertical = getVerticalBar();
            vertical.setIncrement((ch / 100));
            vertical.setPageIncrement((ch / 2));
            vertical.setMaximum(imageBound.height);
            vertical.setThumb(ch);
            vertical.setSelection(displayRectangle.y);

            if (horizontal.getMaximum() > cw) // Image is wider than client area
            {
                horizontal.setEnabled(true);
            }
            else
            {
                horizontal.setEnabled(false);
            }

            if (vertical.getMaximum() > ch) // Image is wider than client area
            {
                vertical.setEnabled(true);
            }
            else
            {
                vertical.setEnabled(false);
            }

        }
    }

    /**
     * Initialize the scroll bars This include: a) setting the initial enabled
     * state b) adding the necessary listeners
     */
    private void initScrollBars()
    {

        ScrollBar horizontal = getHorizontalBar();
        horizontal.setEnabled(false);
        horizontal.addSelectionListener(new SelectionAdapter()
        {
            /**
             * @see org.eclipse.swt.events.SelectionListener#widgetSelected(SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent event)
            {
                // Updates the translation
                displayRectangle.x = ((ScrollBar) event.widget).getSelection();

                // Update the UI
                layout();
                redraw();
            }
        });

        ScrollBar vertical = getVerticalBar();
        vertical.setEnabled(false);
        vertical.addSelectionListener(new SelectionAdapter()
        {
            /**
             * @see org.eclipse.swt.events.SelectionListener#widgetSelected(SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent event)
            {
                // Updates the translation
                displayRectangle.y = ((ScrollBar) event.widget).getSelection();

                // Update the UI
                layout();
                redraw();
            }
        });

        debug("Initialized scroll bars");
    }

    /**
     * This method retrieves the key that is placed at the given x,y
     * coordinates, considering the flip status
     * 
     * @param x
     *            The X coordinate to use at key lookup
     * @param y
     *            The Y coordinate to use at key lookup
     * 
     * @return The key placed at the given coordinate, or null if none is found
     */
    private IAndroidKey getSkinKey(int x, int y)
    {
        IAndroidKey keyToReturn = null;
        IAndroidEmulatorInstance instance = UIHelper.getInstanceAssociatedToControl(this);

        Collection<IAndroidKey> keyAreas = skin.getKeyDataCollection(instance.getCurrentLayout());
        if (keyAreas != null)
        {
            for (IAndroidKey key : keyAreas)
            {
                if (key.isInsideKey(x, y))
                {
                    if (key instanceof AndroidPressKey)
                    {
                        AndroidPressKey defaultKeyData = (AndroidPressKey) key;

                        //if (!defaultKeyData.isFlipSlideValid(instance.isFlipSlideClosed()))
                        if (!defaultKeyData.isFlipSlideValid(false))
                        {
                            continue;
                        }

                    }

                    keyToReturn = key;
                    break;
                }
            }
        }

        return keyToReturn;
    }

    /**
     * Retrieves an image data. If it has never been used at the current
     * session, loads it from skin. Released image is retrieved if both parameters
     * are false.
     * 
     * @param isPressed
     *            true if the image to be retrieved is the pressed image 
     * @param isEnter
     *            true if the image to be retrieved is the enter image. It only has effect if
     *            isPressed == false
     *             
     * @return An image data containing the desired image pixels
     */
    private ImageData getImageData(boolean isPressed, boolean isEnter)
    {

        ImageData imageData = null;

        IAndroidEmulatorInstance instance = UIHelper.getInstanceAssociatedToControl(this);

        try
        {
            if (isPressed)
            {
                imageData = skin.getPressedImageData(instance.getCurrentLayout());

            }
            else
            {
                if (isEnter)
                {
                    imageData = skin.getEnterImageData(instance.getCurrentLayout());

                }
                else
                {
                    imageData = skin.getReleasedImageData(instance.getCurrentLayout());

                }
            }
        }
        catch (SkinException e)
        {
            error("The image requested from skin could not be retrieved. isPressed=" + isPressed
                    + "; message=" + e.getMessage());
            EclipseUtils.showErrorDialog(e);
            error("The skin could not provide an important resource. Stopping the instance");
            try
            {
                instance.stop(true);
            }
            catch (InstanceStopException e1)
            {
                error("Error while running service for stopping virtual machine");
                EclipseUtils.showErrorDialog(EmulatorNLS.GEN_Error,
                        EmulatorNLS.EXC_General_CannotRunStopService);
            }
        }

        return imageData;
    }

    /**
     * Builds an image data that is based on the released image but has the
     * pressed/enter key area painted with data from the pressed/enter image
     * 
     * @param key
     *            The pressed key
     * @param isEnter
     *            Whether the image being retrieved will be used for enter or pressed           
     * 
     * @return An image data built the way described at method description
     */
    private ImageData getKeyImageData(IAndroidKey key, boolean isEnter)
    {

        ImageData resultingImage;
        ImageData releasedImage = getImageData(false, false);
        ImageData keyImage = isEnter ? getImageData(false, true) : getImageData(true, false);

        resultingImage = (ImageData) releasedImage.clone();

        Rectangle keyArea = key.getKeyArea();
        int resultingImageSize = resultingImage.width * keyArea.height;
        int[] keyPixelBuffer = new int[resultingImageSize];

        int startY = keyArea.y < 0 ? 0 : keyArea.y;

        keyImage.getPixels(0, startY, resultingImageSize, keyPixelBuffer, 0);

        for (int line = 0; line < keyArea.height; line++)
        {
            int pos = (line * resultingImage.width) + Math.abs(keyArea.x);
            int startX = Math.abs(keyArea.x);
            startY = (keyArea.y < 0 ? 0 : keyArea.y) + line;
            if (startY < 0)
            {
                continue;
            }

            int putWidth = keyArea.x < 0 ? keyArea.width - startX : keyArea.width;
            resultingImage.setPixels(startX, startY, putWidth, keyPixelBuffer, pos);
        }

        return resultingImage;
    }

    /**
     * This method is called when a mouse selection needs to be canceled.
     * Pressing the right button, releasing the left button or leaving the key
     * area are examples of typical conditions.
     */
    private void cancelMouseSelection()
    {
        // If the mouse timer is different from null, that means that a key is
        // pressed
        // This check is important so that event messages are not sent by
        // mistake

        if (currentKey != null)
        {

            ImageData newImageData = getImageData(false, true);
            setSkinImage(newImageData, currentKey, true);
            androidInput.sendClick(currentKey.getKeysym(), false);
        }
    }

    private void changeCurrentKey(IAndroidKey newKey)
    {
        // The following actions are executed only if the key has changed since the last
        // time a mouse move event has happened. 
        ImageData newImage;

        if (currentKey != null)
        {
            // If currentKey is different from null, we know that the mouse cursor has
            // left the area defined by currentKey. That is because from the previous
            // if clause we know that the key has changed, and currentKey attribute  
            // state is out-dated until we reach the "currentKey = keyData" statement. 
            // In this case, we must draw the RELEASED image version of the key at the 
            // key location
            newImage = getImageData(false, false);
            setSkinImage(newImage, currentKey, true);
            setToolTipText(null);
        }

        if (newKey != null)
        {
            // If keyData is different from null, we know that the mouse cursor has
            // entered the area defined by keyData. 
            // In this case, we must draw the ENTER image version of the key at the 
            // key location
            newImage = getKeyImageData(newKey, true);
            setSkinImage(newImage, newKey, true);
            setToolTipText(newKey.getToolTip());
        }
        currentKey = newKey;
    }

    /**
     * Retrieves the display rectangle defined at the current moment.
     * 
     * @return The display rectangle
     */
    Rectangle getDisplayRectangle()
    {
        return displayRectangle;
    }

    /**
     * Updates the size and location of the display rectangle, based on the
     * current attributes of the skin (such as skin size and zoom factor) and
     * view size
     */
    void updateDisplayRectangle()
    {
        // Updating the display rectangle only makes sense if we have a skin
        // being drawn
        if (currentSkinImage != null)
        {

            // Collect the variables used in computation
            // 
            // - clientAreaWidth, clientAreaHeight: dimensions of the view,
            // measured from
            // the upper left corner point (0,0) to the lower right corner point
            // (width, height)
            // - currentSkinWidth, currentSkinHeight: dimensions of the skin
            // picture, already scaled
            // by the zoom factor
            int clientAreaWidth = getClientArea().width;
            int clientAreaHeight = getClientArea().height;
            int currentSkinHeight = currentSkinImage.getImageData().height;
            int currentSkinWidth = currentSkinImage.getImageData().width;

            // Updates the display rectangle y and height
            //
            // FIRST STEP: determine the position of the rectangle's y
            // coordinate.
            // - It starts by calculating if there is any blank area at the
            // bottom
            // of the view.
            // - If there is blank space (blankY > 0) then calculate which
            // point,
            // if set as the display rectangle's y coordinate, would make the
            // blank
            // space to disappear. Store this as a candidate Y.
            // - Check if the candidate Y is valid. If not valid (candidateY <
            // 0)
            // then use the image origin as the final y coordinate
            //
            // SECOND STEP: determine the width dimension of the rectangle
            // - It starts by calculating which would be the coordinate of the
            // lower point, assuming that the image is big enough to contain
            // that
            // coordinate. That value (vEdge) is the sum of the Y coordinate and
            // the view height.
            // - If vEdge is bigger than the current view height, that means
            // that the image will occupy part of the view. Itis necessary to
            // make the rectangle fit in the skin image by making it smaller in
            // height than the view height itself.
            // - If vEdge is smaller than the current view height, that means
            // that
            // the image will not fit in the view. The solution is to make the
            // display rectangle height the same size as the view height. In
            // this
            // second case, the display rectangle will fit in the view height,
            // but
            // will not be bigger than the skin image height itself
            int blankY = clientAreaHeight - (currentSkinHeight - displayRectangle.y);
            if (blankY > 0)
            {
                int candidateY = displayRectangle.y - blankY;
                if (candidateY > 0)
                {
                    displayRectangle.y = candidateY;
                }
                else
                {
                    displayRectangle.y = 0;
                }
            }
            int vEdge = displayRectangle.y + clientAreaHeight;
            if (vEdge > currentSkinHeight)
            {
                displayRectangle.height = currentSkinHeight - displayRectangle.y;
            }
            else
            {
                displayRectangle.height = clientAreaHeight;
            }

            // Updates the display rectangle x and width
            // NOTE: a similar logic to the previous one was applied in this
            // case
            int blankX = clientAreaWidth - (currentSkinWidth - displayRectangle.x);
            if (blankX > 0)
            {
                int candidateX = displayRectangle.x - blankX;
                if (candidateX > 0)
                {
                    displayRectangle.x = candidateX;
                }
                else
                {
                    displayRectangle.x = 0;
                }
            }
            int hEdge = displayRectangle.x + clientAreaWidth;
            if (hEdge > currentSkinWidth)
            {
                displayRectangle.width = currentSkinWidth - displayRectangle.x;
            }
            else
            {
                displayRectangle.width = clientAreaWidth;
            }

        }
    }

    /**
     * Recalculates the zoom factor. This is necessary when the screen or image
     * dimensions change.
     */
    void recalculateZoomFactor()
    {

        if (!scrollBarsUsed)
        {
            // Compute new zoom factor if the zoom mode is "Fit to Window"
            Rectangle clientArea = getClientArea();
            if ((clientArea.width == 0) || (clientArea.height == 0))
            {
                // zoom factor cannot be zero, otherwise an
                // IllegalArgumentException
                // is raised in some SWT methods
                setZoomFactor(MINIMUM_ZOOM_FACTOR);
            }
            else
            {
                ImageData currentSkin = getImageData(false, false);
                double widthRatio = (double) (clientArea.width) / currentSkin.width;
                double heightRatio = (double) (clientArea.height) / currentSkin.height;
                setZoomFactor(Math.min(widthRatio, heightRatio));
            }
        }

    }

    /**
     * Gets the current zoom factor.
     * 
     * @return the zoom factor
     */
    public double getZoomFactor()
    {
        return zoomFactor;
    }

    /**
     * Checks if the current zoom configuration is "fit to screen";
     * @return
     */
    public boolean isFitToWindowSelected()
    {
        return !scrollBarsUsed;
    }

    /**
     * Sets the zoom factor.
     * 
     * @param zoom
     *            the zoom factor
     */
    public void setZoomFactor(double zoom)
    {
        zoomFactor = zoom;
    }

    /**
     * Gets the listener that handles SWT key pressing and releasing events.
     * 
     * @return the KeyListener object
     */
    public KeyListener getKeyListener()
    {
        return keyListener;
    }

    /*
     * (non-Javadoc)
     * @see com.motorola.studio.android.emulator.ui.controls.IAndroidComposite#getMouseListener()
     */
    public MouseListener getMouseListener()
    {
        return mainDisplayMouseListener;
    }

    /*
     * (non-Javadoc)
     * @see com.motorola.studio.android.emulator.ui.controls.IAndroidComposite#getMouseMoveListener()
     */
    public MouseMoveListener getMouseMoveListener()
    {
        return mainDisplayMouseMoveListener;
    }

    private void createListenersForMainDisplay()
    {
        // create listener to handle keyboard key pressing highlighting the key
        // in the skin.
        keyListener = new KeyAdapter()
        {

            @Override
            public void keyPressed(KeyEvent arg0)
            {

                int keyCode = arg0.keyCode;

                if (keyCode == SWT.CTRL)
                {
                    ctrlPressed = true;
                }
                else
                {
                    if (keyCode == SWT.ARROW_DOWN || keyCode == SWT.ARROW_LEFT
                            || keyCode == SWT.ARROW_RIGHT || keyCode == SWT.ARROW_UP)
                    {
                        int dpadRotation = skin.getDpadRotation(androidInstance.getCurrentLayout());
                        keyCode = getRotatedKeyCode(keyCode, dpadRotation);
                    }
                    // send message to emulator
                    androidInput.sendKey(arg0.character, keyCode, skin.getKeyCodes());
                }

            }

            @Override
            public void keyReleased(KeyEvent arg0)
            {
                int keyCode = arg0.keyCode;

                if (keyCode == SWT.CTRL)
                {
                    ctrlPressed = false;
                }
            }

        };

        mainDisplayMouseMoveListener = new MouseMoveListener()
        {
            /**
             * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(MouseEvent)
             */
            public void mouseMove(MouseEvent e)
            {
                if (isMouseMainDisplayLeftButtonPressed)
                {
                    UIHelper.ajustCoordinates(e, SkinComposite.this);
                    androidInput.sendMouseMove((int) (e.x / embeddedViewScale),
                            (int) (e.y / embeddedViewScale));
                }
            }
        };

        mainDisplayMouseListener = new MouseAdapter()
        {
            /**
             * @see org.eclipse.swt.events.MouseListener#mouseUp(MouseEvent)
             */
            @Override
            public void mouseUp(MouseEvent e)
            {
                if (e.button == 1)
                {
                    isMouseMainDisplayLeftButtonPressed = false;

                    UIHelper.ajustCoordinates(e, SkinComposite.this);
                    androidInput.sendMouseUp((int) (e.x / embeddedViewScale),
                            (int) (e.y / embeddedViewScale));
                }
            }

            /**
             * @see org.eclipse.swt.events.MouseListener#mouseDown(MouseEvent)
             */
            @Override
            public void mouseDown(MouseEvent e)
            {
                if (e.button == 1)
                {
                    UIHelper.ajustCoordinates(e, SkinComposite.this);
                    androidInput.sendMouseDown((int) (e.x / embeddedViewScale),
                            (int) (e.y / embeddedViewScale));

                    isMouseMainDisplayLeftButtonPressed = true;
                }
            }
        };
    }

    private int getRotatedKeyCode(int keyCode, int dpadRotation)
    {
        switch (dpadRotation % 4)
        {
            case 1:
                switch (keyCode)
                {
                    case SWT.ARROW_DOWN:
                        keyCode = SWT.ARROW_RIGHT;
                        break;
                    case SWT.ARROW_LEFT:
                        keyCode = SWT.ARROW_DOWN;
                        break;
                    case SWT.ARROW_RIGHT:
                        keyCode = SWT.ARROW_UP;
                        break;
                    case SWT.ARROW_UP:
                        keyCode = SWT.ARROW_LEFT;
                        break;
                }
                break;
            case 2:
                switch (keyCode)
                {
                    case SWT.ARROW_DOWN:
                        keyCode = SWT.ARROW_UP;
                        break;
                    case SWT.ARROW_LEFT:
                        keyCode = SWT.ARROW_RIGHT;
                        break;
                    case SWT.ARROW_RIGHT:
                        keyCode = SWT.ARROW_LEFT;
                        break;
                    case SWT.ARROW_UP:
                        keyCode = SWT.ARROW_DOWN;
                        break;
                }
                break;
            case 3:
                switch (keyCode)
                {
                    case SWT.ARROW_DOWN:
                        keyCode = SWT.ARROW_LEFT;
                        break;
                    case SWT.ARROW_LEFT:
                        keyCode = SWT.ARROW_UP;
                        break;
                    case SWT.ARROW_RIGHT:
                        keyCode = SWT.ARROW_DOWN;
                        break;
                    case SWT.ARROW_UP:
                        keyCode = SWT.ARROW_RIGHT;
                        break;
                }
                break;
            default:
                //Does nothing, no rotation needed.
                break;
        }
        return keyCode;
    }
}