Input:
import android.util.Log;
import android.util.SparseIntArray;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Toast;
import com.seleuco.mame4droid.Emulator;
import com.seleuco.mame4droid.MAME4droid;
import com.seleuco.mame4droid.helpers.DialogHelper;
import com.seleuco.mame4droid.helpers.MainHelper;
import com.seleuco.mame4droid.helpers.PrefsHelper;
import java.util.Arrays;

Context:
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/GameController.java

		resetAutodetected();
    }

	public static void resetAutodetected() {
		//id = 0;
		Arrays.fill(deviceIDs, -1);
		banDev.clear();
	}

	public static int getGamePadId(InputDevice id) {
		int iDeviceId = 0;
		int iControllerNumber = 0;

		try {
			if (!fakeID)
				iDeviceId = id.getId();
			else
				iDeviceId = 0;
		} catch (Exception ignored) {
		}

		if (!fakeID) {
			iControllerNumber = id.getControllerNumber();
			if (iControllerNumber > 0)
				iDeviceId = iControllerNumber;
		}
		return iDeviceId;
	}

	public static int makeKeyCodeWithDeviceID(InputDevice id, int iKeyCode) {
		int padid = 0;
		try {
			padid = getGamePadId(id);
		} catch (Exception ignored) {
		}

		return makeKeyCodeWithDeviceID(padid, iKeyCode);
	}

	public static int makeKeyCodeWithDeviceID(int iDeviceId, int iKeyCode) {
		int iRet = 0;

		//iRet = ((iDeviceId * 1000) + iKeyCode);//type 1

		//type 2
		iRet = iDeviceId;
		iRet = iRet << 16;
		iRet |= iKeyCode;
		//type 2 end

		return iRet;
	}

	public static void getInfoFromKeyCodeWithDeviceID(int iKeyCode, int[] iArrRet) {
		int iDeviceIdRet = 0;
		int iKeyCodeRet = 0;

		//type 1
		/*iDeviceIdRet = iKeyCode / 1000;
		iKeyCodeRet = iKeyCode % 1000;
		*/
		//type 1 end

		//type 2
		iDeviceIdRet = iKeyCode >> 16;
		iKeyCodeRet = iKeyCode & 0xFFFF;
		//type 2 end

		iArrRet[0] = iDeviceIdRet;
		iArrRet[1] = iKeyCodeRet;
	}

	public static int getDeviceIdFromKeyCodeWithDeviceID(int iKeyCode) {
		//return  iKeyCode / 1000; //type 1
		return iKeyCode >> 16; //type 2
	}

	public static int getKeyCodeFromKeyCodeWithDeviceID(int iKeyCode) {
		//return  iKeyCode % 1000;  //type 1
		return iKeyCode & 0xFFFF; //type 2
	}

	protected void setContollerData(int i, KeyEvent event, int data, int[]digital_data) {
		int action = event.getAction();
		if (action == KeyEvent.ACTION_DOWN)
			digital_data[i] |= data;
		else if (action == KeyEvent.ACTION_UP)
			digital_data[i] &= ~data;
	}

	protected boolean handleControllerKey(int value, KeyEvent event, int []digital_data) {

		int v = emulatorInputValues[value % emulatorInputValues.length];

		if (v == EXIT_VALUE) {
			if (event.getAction() == KeyEvent.ACTION_UP) {
				/*
				if (Emulator.isInMenu()) {
					Emulator.setValue(Emulator.EXIT_GAME, 1);
					try {
						Thread.sleep(InputHandler.PRESS_WAIT);
					} catch (InterruptedException ignored) {
					}
					Emulator.setValue(Emulator.EXIT_GAME, 0);
				} else if (!Emulator.isInGame()) {
					mm.showDialog(DialogHelper.DIALOG_EXIT);
				} else {
				*/
					Emulator.setValue(Emulator.EXIT_GAME, 1);
					try {
						Thread.sleep(InputHandler.PRESS_WAIT);
					} catch (InterruptedException e) {
					}
					Emulator.setValue(Emulator.EXIT_GAME, 0);
				//}
			}
		} else if (v == OPTION_VALUE ) {
			if (event.getAction() == KeyEvent.ACTION_UP && !Emulator.isInOptions()) {
				Emulator.setInOptions(true);

android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java
public class Emulator {

	//gets
	final static public int IN_MENU = 1;
	final static public int IN_GAME = 2;
	final static public int NUMBTNS = 3;
	final static public int NUMWAYS = 4;
	final static public int IS_LIGHTGUN = 5;

	//sets
	final static public int EXIT_GAME = 1;

	final static public int EXIT_PAUSE = 2;
    final static public int SHOW_FPS = 3;

	final static public int AUTO_FRAMESKIP = 4;
	final static public int CHEATS = 5;
	final static public int SKIP_GAMEINFO = 6;

	final static public int DISABLE_DRC = 7;

	final static public int DRC_USE_C = 8;

	final static public int SIMPLE_UI = 9;

    final static public int PAUSE = 11;
    final static public int SOUND_VALUE = 13;

    final static public int AUTOSAVE = 16;
    final static public int SAVESTATE = 17;
    final static public int LOADSTATE = 18;

	final static public int OSD_RESOLUTION = 20;
    final static public int EMU_RESOLUTION = 21;

	final static public int ZOOM_TO_WINDOW = 22;

    final static public int DOUBLE_BUFFER = 23;
    final static public int PXASP1 = 24;

    final static public int VBEAM2X = 34;
    final static public int VFLICKER = 36;
    final static public int SOUND_OPTIMAL_FRAMES = 48;
    final static public int SOUND_OPTIMAL_SAMPLERATE = 49;
    final static public int SOUND_ENGINE = 50;

    final static public int MOUSE = 60;
    final static public int REFRESH = 61;
    final static public int USING_SAF = 62;
    final static public int SAVESATES_IN_ROM_PATH = 63;

	final static public int WARN_ON_EXIT = 64;

	final static public int IS_MOUSE = 65;

	final static public int KEYBOARD = 66;

	final static public int ONE_PROCESSOR = 67;
	final static public int NODEADZONEANDSAT = 68;
	final static public int MAMEINI = 69;

	//set str
    final static public int SAF_PATH = 1;
    final static public int ROM_NAME = 2;
    final static public int VERSION = 3;
	final static public int OVERLAY_EFECT = 4;

	//get str
	final static public int MAME_VERSION = 1;

	//KEYS ACTIONS
	final static public int KEY_DOWN = 1;
	final static public int KEY_UP = 2;

	//MOUSE ACTIONS
	final static public int MOUSE_MOVE = 1;
	final static public int MOUSE_BTN_DOWN = 2;
	final static public int MOUSE_BTN_UP = 3;

    private static MAME4droid mm = null;

    private static boolean isEmulating = false;

    public static boolean isEmulating() {
        return isEmulating;
    }

    private static Object lock1 = new Object();

    private static ByteBuffer screenBuff = null;

    private static boolean emuFiltering = false;

    public static boolean isEmuFiltering() {
        return emuFiltering;
    }

	public static void setEmuFiltering(boolean value) {
		emuFiltering = value;
	}

	private static Paint debugPaint = new Paint();

    private static Matrix mtx = new Matrix();

    private static int window_width = 320;

    public static int getWindow_width() {
        return window_width;
    }

    private static int window_height = 240;

    public static int getWindow_height() {
        return window_height;
    }

    private static int emu_width = 320;
    private static int emu_height = 240;

    private static AudioTrack audioTrack = null;

    private static boolean isDebug = false;
    private static int videoRenderMode = PrefsHelper.PREF_RENDER_GL;

    private static boolean inMenu = false;
    private static boolean oldInMenu = false;

    public static boolean isInGame() {
        return Emulator.getValue(Emulator.IN_GAME) == 1;
    }

    public static boolean isInMenu() {
        return inMenu;
    }

	public static boolean isInGameButNotInMenu() {
		return isInGame() && !isInMenu();
	}

	private static boolean saveorload = false;
	public static void setSaveorload(boolean value){saveorload=value;}
	public static boolean isSaveorload(){return saveorload;};

	private static boolean inOptions = false;
	public static void setInOptions(boolean value){
		inOptions =value;}
	public static boolean isInOptions(){return inOptions;};

    private static boolean needsRestart = false;

    public static void setNeedRestart(boolean value) {
        needsRestart = value;
    }

    public static boolean isRestartNeeded() {
        return needsRestart;
    }

    private static boolean warnResChanged = false;

    public static boolean isWarnResChanged() {
        return warnResChanged;
    }

    public static void setWarnResChanged(boolean warnResChanged) {
        Emulator.warnResChanged = warnResChanged;
    }

    private static boolean paused = true;

    public static boolean isPaused() {
        return paused;
    }

    private static boolean portraitFull = false;

    public static boolean isPortraitFull() {
        return portraitFull;
    }

    public static void setPortraitFull(boolean portraitFull) {
        Emulator.portraitFull = portraitFull;
    }

    static {
        try {
            System.loadLibrary("mame4droid-jni");
        } catch (java.lang.Error e) {
            e.printStackTrace();
        }

        debugPaint.setARGB(255, 255, 255, 255);
        debugPaint.setStyle(Style.STROKE);
        debugPaint.setTextSize(16);
    }

    public static int getEmulatedWidth() {
        return emu_width;
    }

    public static int getEmulatedHeight() {
        return emu_height;
    }

    public static boolean isDebug() {
        return isDebug;
    }

    public static void setDebug(boolean isDebug) {
        Emulator.isDebug = isDebug;
    }

    public static int getVideoRenderMode() {
        return Emulator.videoRenderMode;
    }

    public static void setVideoRenderMode(int videoRenderMode) {
        Emulator.videoRenderMode = videoRenderMode;
    }

    public static Paint getDebugPaint() {
        return debugPaint;
    }

    public static Matrix getMatrix() {
        return mtx;
    }

    //synchronized
    public static ByteBuffer getScreenBuffer() {
        return screenBuff;
    }

    public static void setMAME4droid(MAME4droid mm) {
        Emulator.mm = mm;
    }

    //VIDEO
    public static void setWindowSize(int w, int h) {

        //System.out.println("window size "+w+" "+h);

        window_width = w;
        window_height = h;

        if (videoRenderMode == PrefsHelper.PREF_RENDER_GL)
            return;

        mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height));
    }

    //synchronized
    static void bitblt(ByteBuffer sScreenBuff) {

        //Log.d("Thread Video", "fuera lock");
        synchronized (lock1) {
            try {
                //Log.d("Thread Video", "dentro lock");
                screenBuff = sScreenBuff;
                Emulator.inMenu = Emulator.getValue(Emulator.IN_MENU) == 1;

                if (inMenu != oldInMenu) {

					if(!inMenu && isSaveorload())
						setSaveorload(false);

                    final View v = mm.getInputView();
                    if (v != null) {
                        mm.runOnUiThread(new Runnable() {
                            public void run() {
                                v.invalidate();
                            }
                        });
                    }
                }
                oldInMenu = inMenu;

                if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) {
                    ((EmulatorViewGL) mm.getEmuView()).requestRender();
                } else {
                    Log.e("Thread Video", "Renderer not supported.");
                }
                //Log.d("Thread Video", "fin lock");

            } catch (/*Throwable*/NullPointerException t) {
                Log.getStackTraceString(t);
                t.printStackTrace();
            }
        }
    }

    //synchronized
    static public void changeVideo(final int newWidth, final int newHeight) {

		Log.d("Thread Video", "changeVideo emu_width:"+emu_width+" emu_height: "+emu_height+" newWidth:"+newWidth+" newHeight: "+newHeight);
        synchronized (lock1) {

            mm.getInputHandler().resetInput();

            warnResChanged = emu_width != newWidth || emu_height != newHeight;

            //if(emu_width!=newWidth || emu_height!=newHeight)
            //{
            emu_width = newWidth;
            emu_height = newHeight;

            mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height));

            if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) {
                GLRenderer r = (GLRenderer) ((EmulatorViewGL) mm.getEmuView()).getRender();
                if (r != null) r.changedEmulatedSize();
            } else {
				Log.e("Thread Video", "Error renderer not supported");
            }

            mm.getMainHelper().updateEmuValues();

            mm.runOnUiThread(new Runnable() {
                public void run() {

                    //Toast.makeText(mm, "changeVideo newWidth:"+newWidth+" newHeight:"+newHeight+" newVisWidth:"+newVisWidth+" newVisHeight:"+newVisHeight,Toast.LENGTH_SHORT).show();
                    mm.overridePendingTransition(0, 0);
					/*
                    if (warnResChanged && videoRenderMode == PrefsHelper.PREF_RENDER_GL && Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1)
                        mm.getEmuView().setVisibility(View.INVISIBLE);
					*/

                    mm.getMainHelper().updateMAME4droid();
                    if (mm.getEmuView().getVisibility() != View.VISIBLE)
                        mm.getEmuView().setVisibility(View.VISIBLE);
                }
            });
            //}
        }

    }

	static public void initInput() {
		Log.d("initInput","initInput isInGame:"+isInGame()+" isInMenu:"+isInMenu());
		mm.runOnUiThread(new Runnable() {
			public void run() {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
				if ( /*Emulator.getValue(Emulator.IN_GAME) == 1 && Emulator.getValue(Emulator.IN_MENU) == 0
					&&*/ (((mm.getPrefsHelper().isTouchLightgun() || mm.getPrefsHelper().isTouchGameMouse())
					&& mm.getInputHandler()
					.getTouchController().getState() != TouchController.STATE_SHOWING_NONE) || mm
					.getPrefsHelper().isTiltSensorEnabled())) {

					CharSequence text = "";
					if(mm.getPrefsHelper().isTiltSensorEnabled())
						text = "Tilt sensor is enabled!";
					else if(mm.getPrefsHelper().isTouchLightgun())
						text = "Touch lightgun is enabled!";
					else if(mm.getPrefsHelper().isTouchGameMouse())
						text = "Touch mouse is enabled!";

					int duration = Toast.LENGTH_SHORT;
					Toast toast = Toast.makeText(mm, text, duration);
					toast.show();
					Log.d("initInput","virtual device: "+text);
				}

				mm.getMainHelper().updateMAME4droid();
			}
		});
	}

    //SOUND
    static public void initAudio(int freq, boolean stereo) {
        int sampleFreq = freq;

        int channelConfig = stereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;

        int bufferSize = AudioTrack.getMinBufferSize(sampleFreq, channelConfig, audioFormat);

        if (mm.getPrefsHelper().getSoundEngine() == PrefsHelper.PREF_SNDENG_AUDIOTRACK_HIGH)
            bufferSize += bufferSize / 4;

        //System.out.println("Buffer Size "+bufferSize);

        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                sampleFreq,
                channelConfig,
                audioFormat,
                bufferSize,
                AudioTrack.MODE_STREAM);

        audioTrack.play();
    }

    public static void endAudio() {
        if (audioTrack != null) {
            audioTrack.stop();
            audioTrack.release();
        }
        audioTrack = null;
    }

    public static void writeAudio(byte[] b, int sz) {
        //System.out.println("Envio "+sz+" "+audioTrack);
        if (audioTrack != null) {
			audioTrack.write(b, 0, sz);
        }
    }

    //LIVE CYCLE
    public static void pause() {
        //Log.d("EMULATOR", "PAUSE");

        if (isEmulating) {
            //pauseEmulation(true);
            Emulator.setValue(Emulator.PAUSE, 1);
            paused = true;
        }

        if (audioTrack != null) {
            try {
                audioTrack.pause();
            } catch (Throwable e) {
            }
        }
/*
        try {
            Thread.sleep(60);//ensure threads stop
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
*/
    }

    public static void resume() {
        //Log.d("EMULATOR", "RESUME");

        if (isRestartNeeded())
            return;

        if (audioTrack != null)
            audioTrack.play();

        if (isEmulating) {
            Emulator.setValue(Emulator.PAUSE, 0);
            Emulator.setValue(Emulator.EXIT_PAUSE, 1);
            paused = false;
        }
    }

    //EMULATOR
    public static void emulate(final String libPath, final String resPath) {

        //Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

        if (isEmulating) return;

        Thread t = new Thread(new Runnable() {

            public void run() {

                boolean extROM = false;
                isEmulating = true;
				Size sz = mm.getMainHelper().getWindowSize();
                init(libPath, resPath, Math.max(sz.getWidth(),sz.getHeight()), Math.min(sz.getWidth(),sz.getHeight()));
                final String versionName = mm.getMainHelper().getVersion();
                Emulator.setValueStr(Emulator.VERSION, versionName);

				boolean isUsingSaf = mm.getPrefsHelper().getROMsDIR() != null && mm.getPrefsHelper().getROMsDIR().length() != 0;
				if(isUsingSaf) {
					Emulator.setValue(Emulator.USING_SAF, 1);
					Emulator.setValueStr(Emulator.SAF_PATH, mm.getPrefsHelper().getROMsDIR());
					mm.getSAFHelper().listUriFiles(true);
				}

                Intent intent = mm.getIntent();
                String action = intent.getAction();
                //Uri pkg = null;
                String fileName = null;
                String path = null;
                boolean delete = false;
                if (Intent.ACTION_VIEW.equals(action)) {
                    //android.os.Debug.waitForDebugger();
                    //pkg = mm.getReferrer();
                    //System.out.println("PKG: "+pkg.getHost());

                    Uri _uri = intent.getData();
                    //System.out.println("URI: "+_uri.toString());
                    boolean error = false;

                    //String filePath = null;

                    //android.os.Debug.waitForDebugger();
                    Log.d("", "URI = " + _uri);
                    try {
                        if (_uri != null && "content".equalsIgnoreCase(_uri.getScheme())) {
                            //mm.safHelper.setURI(null);//disable SAF.
							//Log.d("SAF","Disabling SAF");
                            fileName = mm.getMainHelper().getFileName(_uri);
                            String state = Environment.getExternalStorageState();

                            if (Environment.MEDIA_MOUNTED.equals(state)) {
                                //path = mm.getExternalCacheDir().getPath();
                                path = mm.getPrefsHelper().getInstallationDIR()+"roms";
                                File f = new File(path+"/"+fileName);
                                if(!f.exists()) {
                                    java.io.InputStream input = mm.getContentResolver().openInputStream(_uri);
                                    error = mm.getMainHelper().copyFile(input, path, fileName);
                                    delete = true;
                                }
                            } else
                                error = true;
                        } else {
                            String filePath = _uri.getPath();
                            java.io.File f = new java.io.File(filePath);
                            fileName = f.getName();
                            path = f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf(File.separator));
                        }
                    } catch (Exception e) {
                        error = true;
                    }

                    if (error) {
                        mm.runOnUiThread(new Runnable() {
                            public void run() {
                                mm.getDialogHelper().setInfoMsg("Error opening file...");
                                mm.showDialog(DialogHelper.DIALOG_INFO);
                            }
                        });
                    } else {

                        Emulator.setValueStr(Emulator.ROM_NAME, fileName);
                        System.out.println("XX name: " + fileName);
                        System.out.println("XX path: " + path);
                        extROM = true;
                        final String name = fileName;
                        mm.runOnUiThread(new Runnable() {
                            public void run() {
                                //Toast.makeText(mm, Html.fromHtml("<background color='#0000FF' ><b>" + "MAME4droid (0.139) " + versionName + ".<br>Launching: " + name + "</b></font>"), Toast.LENGTH_LONG).show();
                                Toast.makeText(mm, "Launching: " + name + "\nMAME4droid 2024 " + versionName, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }

                mm.getMainHelper().updateEmuValues();

				runT();

                if (extROM) {
					/*
					if (pkg != null && "com.digdroid.alman.dig".equals(pkg.getHost())) {
						PackageManager pm = mm.getPackageManager();
						Intent intent2 = pm.getLaunchIntentForPackage("com.digdroid.alman.dig");
						mm.startActivity(intent2);
					}*/
                    if (delete) {
                        java.io.File f = new java.io.File(path, fileName);
                        f.delete();
                    }
                }
				mm.runOnUiThread(new Runnable() {
					public void run() {
						if (android.os.Build.VERSION.SDK_INT >= 21) {
							mm.finishAndRemoveTask();
						} else
							mm.finish();
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				});
            }
        }, "emulatorNativeMain-Thread");

        if (mm.getPrefsHelper().getMainThreadPriority() == PrefsHelper.LOW) {
            t.setPriority(Thread.MIN_PRIORITY);
        } else if (mm.getPrefsHelper().getMainThreadPriority() == PrefsHelper.NORMAL) {
            t.setPriority(Thread.NORM_PRIORITY);
        } else
            t.setPriority(Thread.MAX_PRIORITY);

        t.start();
    }

    public static int getValue(int key) {
        return getValue(key, 0);
    }

    public static String getValueStr(int key) {
        return getValueStr(key, 0);
    }

    public static void setValue(int key, int value) {
        setValue(key, 0, value);
    }

    public static void setValueStr(int key, String value) {
        setValueStr(key, 0, value);
    }

    static int safOpenFile(String pathName, String mode) {
        //System.out.println("-->Llaman a safOpenFile en java "+pathName+" "+mode);

        String file = "";

        String romPath = mm.getPrefsHelper().getROMsDIR();
        if (pathName.startsWith(romPath))
            file = pathName.substring(romPath.length() + 1, pathName.length());

        if(file.equals(""))
            return -1;

        //System.out.println("File with path "+file);

        return mm.getSAFHelper().openUriFd("/" + file, mode);
    }

    static int safReadDir(String dirName, int reload) {
        //System.out.println("Llaman a safReadDir en java "+dirName);

        //boolean res = mm.getSAFHelper().listUriFiles(reload == 1);

		String dirSAF = "";

		String romPath = mm.getPrefsHelper().getROMsDIR();
		if (dirName.startsWith(romPath)) {
			dirSAF = dirName.substring(romPath.length(), dirName.length());
			if(!dirSAF.startsWith("/")) dirSAF = "/"+dirSAF;
			if(!dirSAF.endsWith("/")) dirSAF = dirSAF +"/";
		}

		return mm.getSAFHelper().readDir(dirSAF);
    }

    static String safGetNextDirEntry(int dirId) {
        //System.out.println("Llaman a safGetNextDirEntry en java "+dirId);

        return mm.getSAFHelper().getNextDirName(dirId);
    }

    static void safCloseDir(int dirId) {
        //System.out.println("Llaman a safCloseDir en java "+dirId);

		mm.getSAFHelper().closeDir(dirId);
    }

    //native
    protected static native void init(String libPath, String resPath, int nativeWidth, int nativeHeight);

    protected static native void runT();

    //protected static native void runVideoT();

    synchronized public static native void setDigitalData(int i, long data);

    synchronized public static native void setAnalogData(int i, float v1, float v2);

    public static native int getValue(int key, int i);

    public static native String getValueStr(int key, int i);

    public static native void setValue(int key, int i, int value);

    public static native void setValueStr(int key, int i, String value);

	public static native int setKeyData(int keyCode, int keyAction, char keyChar);

	public static native int setMouseData(int i, int mouseAction,int button, float cx, float cy);

}

android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/PrefsHelper.java
public class PrefsHelper implements OnSharedPreferenceChangeListener {
    final static public String PREF_ROMsDIR = "PREF_ROMsDIR_2";
    final static public String PREF_SAF_URI = "PREF_SAF_URI";
    final static public String PREF_INSTALLATION_DIR = "PREF_INSTALLATION_DIR";
    final static public String PREF_OLD_INSTALLATION_DIR = "PREF_OLD_INSTALLATION_DIR";

    final static public String PREF_GLOBAL_VIDEO_RENDER_MODE = "PREF_GLOBAL_VIDEO_RENDER_MODE";

    final static public String PREF_EMU_RESOLUTION = "PREF_EMU_RESOLUTION_2";
	final static public String PREF_EMU_RESOLUTION_OSD = "PREF_EMU_RESOLUTION_OSD";
    final static public String PREF_EMU_SOUND = "PREF_EMU_SOUND";
    final static public String PREF_EMU_SHOW_FPS = "PREF_EMU_SHOW_FPS";
	final static public String PREF_ZOOM_TO_WINDOW = "PREF_ZOOM_TO_WINDOW";
	final static public String PREF_EMU_AUTO_FRAMESKIP = "PREF_EMU_AUTO_FRAMESKIP";
	final static public String CHEATS = "CHEATS";
	final static public String SKIP_GAMEINFO = "SKIP_GAMEINFO";
	final static public String PREF_EMU_DISABLE_DRC = "PREF_EMU_DISABLE_DRC_2";
	final static public String PREF_EMU_DRC_USR_C = "PREF_EMU_DRC_USR_C";
	final static public String PREF_EMU_ONE_PROCESSOR = "PREF_EMU_ONE_PROCESSOR";
	final static public String PREF_MAMEINI = "PREF_MAMEINI";

    final static public String PREF_GLOBAL_AUTOSAVE = "PREF_GLOBAL_AUTOSAVE";
    final static public String PREF_GLOBAL_DEBUG = "PREF_GLOBAL_DEBUG";

    final static public String PREF_GLOBAL_WARN_ON_EXIT = "PREF_GLOBAL_WARN_ON_EXIT";

    final static public String PREF_PORTRAIT_SCALING_MODE = "PREF_PORTRAIT_SCALING_MODE";
    final static public String PREF_PORTRAIT_TOUCH_CONTROLLER = "PREF_PORTRAIT_TOUCH_CONTROLLER";
    final static public String PREF_PORTRAIT_BITMAP_FILTERING = "PREF_PORTRAIT_BITMAP_FILTERING";
    final static public String PREF_PORTRAIT_FULLSCREEN = "PREF_PORTRAIT_FULLSCREEN";

    final static public String PREF_LANDSCAPE_SCALING_MODE = "PREF_LANDSCAPE_SCALING_MODE";
    final static public String PREF_LANDSCAPE_TOUCH_CONTROLLER = "PREF_LANDSCAPE_TOUCH_CONTROLLER";
    final static public String PREF_LANDSCAPE_BITMAP_FILTERING = "PREF_LANDSCAPE_BITMAP_FILTERING";
    final static public String PREF_LANDSCAPE_CONTROLLER_TYPE = "PREF_LANDSCAPE_CONTROLLER_TYPE";

    final static public String PREF_DEFINED_KEYS = "PREF_DEFINED_KEYS";

    final static public String PREF_DEFINED_CONTROL_LAYOUT = "PREF_DEFINED_CONTROL_LAYOUT";
    final static public String PREF_DEFINED_CONTROL_LAYOUT_P = "PREF_DEFINED_CONTROL_LAYOUT_P";

    final static public String PREF_DISABLE_RIGHT_STICK = "PREF_DISABLE_RIGHT_STICK";
    final static public String PREF_ANIMATED_INPUT = "PREF_ANIMATED_INPUT";
    final static public String PREF_TOUCH_LIGHTGUN = "PREF_TOUCH_LIGHTGUN";
	final static public String PREF_TOUCH_LIGHTGUN_FORCE = "PREF_TOUCH_LIGHTGUN_FORCE";
    final static public String PREF_TOUCH_DZ = "PREF_TOUCH_DZ";
    final static public String PREF_CONTROLLER_TYPE = "PREF_CONTROLLER_TYPE";
    final static public String PREF_STICK_TYPE = "PREF_STICK_TYPE";
    final static public String PREF_NUMBUTTONS = "PREF_NUMBUTTONS";
    final static public String PREF_CONTROLLER_AUTODETECT = "PREF_CONTROLLER_AUTODETECT";
    final static public String PREF_ANALOG_DZ = "PREF_ANALOG_DZ";
    final static public String PREF_GAMEPAD_DZ = "PREF_GAMEPAD_DZ";
    final static public String PREF_VIBRATE = "PREF_VIBRATE";
    final static public String PREF_MOUSE = "PREF_MOUSE";
	final static public String PREF_TOUCH_MOUSE = "PREF_TOUCH_MOUSE";
	final static public String PREF_TOUCH_GAME_MOUSE = "PREF_TOUCH_GAME_MOUSE";
	final static public String PREF_TOUCH_GAME_MOUSE_FORCE = "PREF_TOUCH_GAME_MOUSE_FORCE";
	final static public String PREF_KEYBOARD = "PREF_KEYBOARD";
	final static public String PREF_KEYBOARD_HIDE_CONTROLLER = "PREF_KEYBOARD_HIDE_CONTROLLER";
	final static public String PREF_VIRTUAL_KEYBOARD = "PREF_VIRTUAL_KEYBOARD";
    final static public String PREF_INPUT_FAKE_ID = "PREF_INPUT_FAKE_ID";

    final static public String PREF_TILT_SENSOR = "PREF_TILT_SENSOR";
    final static public String PREF_TILT_DZ = "PREF_TILT_DZ";
    final static public String PREF_TILT_SENSITIVITY = "PREF_TILT_SENSITIVITY";
    final static public String PREF_TILT_NEUTRAL = "PREF_TILT_NEUTRAL";
    final static public String PREF_TILT_ANALOG = "PREF_TILT_ANALOG";
    final static public String PREF_TILT_TOUCH = "PREF_TILT_TOUCH";
    final static public String PREF_TILT_SWAP_YZ = "PREF_TILT_SWAP_YZ";
    final static public String PREF_TILT_INVERT_X = "PREF_TILT_INVERT_X";

    final static public String PREF_HIDE_STICK = "PREF_HIDE_STICK";
    final static public String PREF_BUTTONS_SIZE = "PREF_BUTTONS_SIZE";
    final static public String PREF_STICK_SIZE = "PREF_STICK_SIZE";
    final static public String PREF_MAIN_THREAD_PRIORITY = "PREF_MAIN_THREAD_PRIORITY";
    final static public String PREF_SOUND_ENGINE = "PREF_SOUND_ENGINE";

    final static public String PREF_DOUBLE_BUFFER = "PREF_DOUBLE_BUFFER";

    final static public String PREF_FORCE_ALTGLPATH = "PREF_FORCE_ALTGLPATH";
    final static public String PREF_PXASP1 = "PREF_PXASP1";
	final static public String PREF_NODEADZONEANDSAT = "PREF_NODEADZONEANDSAT";
    final static public String SAVESATES_IN_ROM_PATH = "SAVESATES_IN_ROM_PATH";

    final static public String PREF_BEAM2X = "PREF_BEAM2X";
    final static public String PREF_FLICKER = "PREF_FLICKER";

    final static public String PREF_GLOBAL_NAVBAR_MODE = "PREF_GLOBAL_NAVBAR_MODE";
    final static public String PREF_GLOBAL_SCALE_BEYOND = "PREF_GLOBAL_SCALE_BEYOND";
    final static public String PREF_GLOBAL_OVERSCAN = "PREF_GLOBAL_OVERSCAN";
    final static public String PREF_GLOBAL_USE_NOTCH = "PREF_GLOBAL_USE_NOTCH";
	final static public String PREF_GLOBAL_SIMPLE_UI = "PREF_GLOBAL_SIMPLE_UI";
	final static public String PREF_OVERLAY = "PREF_OVERLAY";
	final static public String PREF_ORIENTATION = "PREF_ORIENTATION";

    final static public String PREF_MAME_DEFAULTS = "PREF_MAME_DEFAULTS";
	final static public String PREF_LIGHTGUN_LONGPRESS = "PREF_LIGHTGUN_LONGPRESS";
    final static public String PREF_BOTTOM_RELOAD = "PREF_BOTTOM_RELOAD";

    final static public int LOW = 1;
    final static public int NORMAL = 2;
    final static public int HIGHT = 2;

    final static public int PREF_RENDER_GL = 1;

    final static public int PREF_DIGITAL_DPAD = 1;
    final static public int PREF_DIGITAL_STICK = 2;
    final static public int PREF_ANALOG_STICK = 3;

    final static public int PREF_INPUT_NO_DETECT_CONTROLLER = 1;
    final static public int PREF_INPUT_DETECT_CONTROLLER = 2;

    final public static int PREF_ORIGINAL = 3;
    final public static int PREF_15X = 4;
    final public static int PREF_20X = 5;
    final public static int PREF_SCALE = 1;
    final public static int PREF_STRETCH = 2;
    final public static int PREF_SCALE_INTEGER = 14;
    final public static int PREF_SCALE_INTEGER_BEYOND = 15;

    final public static String PREF_OVERLAY_NONE = "none";

    final public static int PREF_AUTOMAP_THUMBS_DISABLED_L2R2_AS_L1R2 = 1;
    final public static int PREF_AUTOMAP_THUMBS_AS_COINSTART_L2R2_AS_L1R2 = 2;
    final public static int PREF_AUTOMAP_THUMBS_AS_COINSTART_L2R2_DISABLED = 3;
    final public static int PREF_AUTOMAP_THUMBS_DISABLED_L2R2_AS_COINSTART = 4;
    final public static int PREF_AUTOMAP_L1R1_AS_COINSTART_L2R2_AS_L1R1 = 5;
    final public static int PREF_AUTOMAP_L1R1_AS_EXITMENU_L2R2_AS_L1R1 = 6;

    final public static int PREF_SNDENG_AUDIOTRACK = 1;
    final public static int PREF_SNDENG_AUDIOTRACK_HIGH = 2;
    final public static int PREF_SNDENG_OPENSL = 3;
    final public static int PREF_SNDENG_OPENSL_LOW = 4;

    final public static int PREF_NAVBAR_VISIBLE = 0;
    final public static int PREF_NAVBAR_DIMM_OR_HIDE = 1;
    final public static int PREF_NAVBAR_IMMERSIVE = 2;

    protected MAME4droid mm = null;

    public PrefsHelper(MAME4droid value) {
        mm = value;
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
    }

    public void resume() {
        Context context = mm.getApplicationContext();
        SharedPreferences prefs =
                PreferenceManager.getDefaultSharedPreferences(context);
        prefs.registerOnSharedPreferenceChangeListener(this);
    }

    public void pause() {

        Context context = mm.getApplicationContext();
        SharedPreferences prefs =
                PreferenceManager.getDefaultSharedPreferences(context);
        prefs.unregisterOnSharedPreferenceChangeListener(this);
    }

    public SharedPreferences getSharedPreferences() {
        Context context = mm.getApplicationContext();
        return PreferenceManager.getDefaultSharedPreferences(context);
    }

    public int getPortraitScaleMode() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_PORTRAIT_SCALING_MODE, "1")).intValue();
    }

    public int getLandscapeScaleMode() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_LANDSCAPE_SCALING_MODE, "1")).intValue();
    }

	public String getOverlayFilterValue() {
		return getSharedPreferences().getString(PREF_OVERLAY, PrefsHelper.PREF_OVERLAY_NONE);
	}

	public int getOrientationMode() {
		return Integer.valueOf(getSharedPreferences().getString(PREF_ORIENTATION, "0")).intValue();
	}

	public boolean isPortraitTouchController() {
        return getSharedPreferences().getBoolean(PREF_PORTRAIT_TOUCH_CONTROLLER, true);
    }

    public boolean isPortraitBitmapFiltering() {
        return getSharedPreferences().getBoolean(PREF_PORTRAIT_BITMAP_FILTERING, true);
    }

    public boolean isPortraitFullscreen() {
        return getSharedPreferences().getBoolean(PREF_PORTRAIT_FULLSCREEN, false);
    }

    public boolean isLandscapeTouchController() {
        return getSharedPreferences().getBoolean(PREF_LANDSCAPE_TOUCH_CONTROLLER, true);
    }

    public boolean isLandscapeBitmapFiltering() {
        return getSharedPreferences().getBoolean(PREF_LANDSCAPE_BITMAP_FILTERING, true);
    }

    public String getDefinedKeys() {

        SharedPreferences p = getSharedPreferences();

        StringBuffer defaultKeys = new StringBuffer();

        for (int i = 0; i < GameController.defaultKeyMapping.length; i++)
            defaultKeys.append(GameController.defaultKeyMapping[i] + ":");

        return p.getString(PREF_DEFINED_KEYS, defaultKeys.toString());

    }

    public int getVideoRenderMode() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_GLOBAL_VIDEO_RENDER_MODE, "1")).intValue();
    }

    public int getEmulatedResolution() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_EMU_RESOLUTION, "1")).intValue();
    }

	public int getOSDResolution() {
		return Integer.valueOf(getSharedPreferences().getString(PREF_EMU_RESOLUTION_OSD, "0")).intValue();
	}

    public boolean isWarnOnExit() {
        return getSharedPreferences().getBoolean(PREF_GLOBAL_WARN_ON_EXIT, true);
    }

    public int getSoundValue() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_EMU_SOUND, "44100")).intValue();
    }

    public boolean isFPSShowed() {
        return getSharedPreferences().getBoolean(PREF_EMU_SHOW_FPS, false);
    }

	public boolean isZoomToWindow() {
		return getSharedPreferences().getBoolean(PREF_ZOOM_TO_WINDOW, true);
	}

	public boolean isAutoFrameSkip() {
		return getSharedPreferences().getBoolean(PREF_EMU_AUTO_FRAMESKIP, false);
	}

	public boolean isCheats() {
		return getSharedPreferences().getBoolean(CHEATS, false);
	}

	public boolean isSkipGameInfo() {
		return getSharedPreferences().getBoolean(SKIP_GAMEINFO, false);
	}

	public boolean isDisabledDRC() {
		return getSharedPreferences().getBoolean(PREF_EMU_DISABLE_DRC, true);
	}

	public boolean isDRCUseC() {
		return getSharedPreferences().getBoolean(PREF_EMU_DRC_USR_C, true);
	}

	public boolean isOneProcessor() {
		return getSharedPreferences().getBoolean(PREF_EMU_ONE_PROCESSOR, true);
	}

    public boolean isAutosave() {
        return getSharedPreferences().getBoolean(PREF_GLOBAL_AUTOSAVE, false);
    }

    public boolean isDebugEnabled() {
        return getSharedPreferences().getBoolean(PREF_GLOBAL_DEBUG, false);
    }

    public boolean isHideStick() {
        return getSharedPreferences().getBoolean(PREF_HIDE_STICK, false);
    }

    public boolean isDisabledRightStick() {
        return getSharedPreferences().getBoolean(PREF_DISABLE_RIGHT_STICK, false);
    }

    public boolean isAnimatedInput() {
        return getSharedPreferences().getBoolean(PREF_ANIMATED_INPUT, true);
    }

    public boolean isTouchDZ() {
        return getSharedPreferences().getBoolean(PREF_TOUCH_DZ, true);
    }

    public int getControllerType() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_CONTROLLER_TYPE, "1")).intValue();
    }

    public boolean isTouchLightgun() {

		if(!Emulator.isInGame())
			return false;

        boolean enabled = getSharedPreferences().getBoolean(PREF_TOUCH_LIGHTGUN, true);

        if (enabled &&

			(Emulator.getValue(Emulator.IS_LIGHTGUN) == 1 || getSharedPreferences().getBoolean(PREF_TOUCH_LIGHTGUN_FORCE, false))

			&& !this.isTiltSensorEnabled() && !mm.getInputHandler().getMouse().isEnabled())
            return true;

        return false;
    }

    public boolean isMouseEnabled() {
        return getSharedPreferences().getBoolean(PREF_MOUSE, true);
    }

	public boolean isTouchMouseEnabled() {
		if(mm.getInputHandler().getMouse().isEnabled())
			return false;

		return getSharedPreferences().getBoolean(PREF_TOUCH_MOUSE, true);
	}

	public boolean isTouchGameMouse() {

		if(!isTouchMouseEnabled())
			return false;

		if(!getSharedPreferences().getBoolean(PREF_TOUCH_GAME_MOUSE, true))
			return false;

		if(!Emulator.isInGame() && Emulator.isInMenu())
			return false;

		if(mm.getInputHandler().getTiltSensor().isEnabled())
			return false;

		if(mm.getInputHandler().getGameController().isEnabled())
			return false;

		if(mm.getInputHandler().getMouse().isEnabled())
			return false;

		if(isTouchLightgun())
			return false;

		return Emulator.getValue(Emulator.IS_MOUSE)==1 || getSharedPreferences().getBoolean(PREF_TOUCH_GAME_MOUSE_FORCE, false);

	}

	public boolean isKeyboardEnabled() {
		return getSharedPreferences().getBoolean(PREF_KEYBOARD, true);
	}

	public boolean isKeyboardHideController() {
		return getSharedPreferences().getBoolean(PREF_KEYBOARD_HIDE_CONTROLLER, true);
	}

	public boolean isVirtualKeyboardEnabled() {
		return getSharedPreferences().getBoolean(PREF_VIRTUAL_KEYBOARD, true);
	}

    public int getStickWays() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_STICK_TYPE, "-1")).intValue();
    }

    public int getNumButtons() {
        int n = Integer.valueOf(getSharedPreferences().getString(PREF_NUMBUTTONS, "-1")).intValue();
        if (n == 33) n = 3;
        return n;
    }

    public boolean isBplusX() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_NUMBUTTONS, "-1")).intValue() == 33;
    }

    public boolean isContollerAutodetect() {
		return getSharedPreferences().getBoolean(PREF_CONTROLLER_AUTODETECT, true);
    }

    public int getAnalogDZ() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_ANALOG_DZ, "2")).intValue();
    }

    public int getGamepadDZ() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_GAMEPAD_DZ, "3")).intValue();
    }

    public boolean isVibrate() {
        return getSharedPreferences().getBoolean(PREF_VIBRATE, false);
    }

    public String getROMsDIR() {
        return getSharedPreferences().getString(PREF_ROMsDIR, null);
    }

    public void setROMsDIR(String value) {
        //PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.putString(PREF_ROMsDIR, value);
        editor.commit();
    }

    public String getSAF_Uri() {
        return getSharedPreferences().getString(PREF_SAF_URI, null);
    }

    public void setSAF_Uri(String value) {
        //PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.putString(PREF_SAF_URI, value);
        editor.commit();
    }

    public String getInstallationDIR() {
        return getSharedPreferences().getString(PREF_INSTALLATION_DIR, null);
    }

    public void setInstallationDIR(String value) {
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.putString(PREF_INSTALLATION_DIR, value);
        editor.commit();
    }

    public String getOldInstallationDIR() {
        return getSharedPreferences().getString(PREF_OLD_INSTALLATION_DIR, null);
    }

    public void setOldInstallationDIR(String value) {
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.putString(PREF_OLD_INSTALLATION_DIR, value);
        editor.commit();
    }

    public String getDefinedControlLayoutLand() {
        return getSharedPreferences().getString(PREF_DEFINED_CONTROL_LAYOUT, null);
    }

    public void setDefinedControlLayoutLand(String value) {
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.putString(PREF_DEFINED_CONTROL_LAYOUT, value);
        editor.commit();
    }

    public String getDefinedControlLayoutPortrait() {
        return getSharedPreferences().getString(PREF_DEFINED_CONTROL_LAYOUT_P, null);
    }

    public void setDefinedControlLayoutPortrait(String value) {
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.putString(PREF_DEFINED_CONTROL_LAYOUT_P, value);
        editor.commit();
    }

    public boolean isTiltSensorEnabled() {

		if(mm.getInputHandler().getGameController().isEnabled())
			return false;

		if(mm.getInputHandler().getMouse().isEnabled())
			return false;

        return getSharedPreferences().getBoolean(PREF_TILT_SENSOR, false);
    }

    public int getTiltSensitivity() {
        return getSharedPreferences().getInt(PREF_TILT_SENSITIVITY, 6);
    }

    public int getTiltVerticalNeutralPos() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_TILT_NEUTRAL, "5")).intValue();
    }

    public int getTiltDZ() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_TILT_DZ, "3")).intValue();
    }

    public boolean isTiltAnalog() {
        return getSharedPreferences().getBoolean(PREF_TILT_ANALOG, true);
    }

    public boolean isTiltTouch() {
        return getSharedPreferences().getBoolean(PREF_TILT_TOUCH, false);
    }

    public boolean isTiltSwappedYZ() {
        return getSharedPreferences().getBoolean(PREF_TILT_SWAP_YZ, false);
    }

    public boolean isTiltInvertedX() {
        return getSharedPreferences().getBoolean(PREF_TILT_INVERT_X, false);
    }

    public int getButtonsSize() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_BUTTONS_SIZE, "3")).intValue();
    }

    public int getStickSize() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_STICK_SIZE, "3")).intValue();
    }

    public int getMainThreadPriority() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_MAIN_THREAD_PRIORITY, "2")).intValue();
    }

    public int getSoundEngine() {
        return Integer.valueOf(getSharedPreferences().getString(PREF_SOUND_ENGINE, "1")).intValue();
    }

    public boolean isDoubleBuffer() {
        return getSharedPreferences().getBoolean(PREF_DOUBLE_BUFFER, true);
    }

    public boolean isAltGLPath() {
        return getSharedPreferences().getBoolean(PREF_FORCE_ALTGLPATH, false);
    }

    public boolean areSavesInRomPath() {
        return getSharedPreferences().getBoolean(SAVESATES_IN_ROM_PATH, false);
    }

    public boolean isPlayerXasPlayer1() {
        return getSharedPreferences().getBoolean(PREF_PXASP1, false);
    }

	public boolean isOverrideDZandSAT() {
		return getSharedPreferences().getBoolean(PREF_NODEADZONEANDSAT, true);
	}

	public boolean isUsedMAMEini() {
		return getSharedPreferences().getBoolean(PREF_MAMEINI, false);
	}

    public boolean isVectorBeam2x() {
        return getSharedPreferences().getBoolean(PREF_BEAM2X, true);
    }

    public boolean isVectorFlicker() {
        return getSharedPreferences().getBoolean(PREF_FLICKER, false);
    }

	/*public int getEffectOverlayIntensity(){
		return Integer.valueOf(getSharedPreferences().getString(PREF_OVERLAY_INTENSITY,"3")).intValue();
	}*/

    public int getNavBarMode() {

        if (getSharedPreferences().getString(PREF_GLOBAL_NAVBAR_MODE, "").equals("")) {
            String value = PREF_NAVBAR_IMMERSIVE + "";
            SharedPreferences.Editor edit = getSharedPreferences().edit();
            edit.putString(PREF_GLOBAL_NAVBAR_MODE, value);
            edit.commit();
        }

        return Integer.valueOf(getSharedPreferences().getString(PREF_GLOBAL_NAVBAR_MODE, "1")).intValue();
    }

    public boolean isDefaultData() {

        boolean v = getSharedPreferences().getBoolean(PrefsHelper.PREF_MAME_DEFAULTS, false);

        if (v) {
            SharedPreferences.Editor editor = getSharedPreferences().edit();
            editor.putBoolean(PrefsHelper.PREF_MAME_DEFAULTS, false);
            editor.commit();
        }

        return v;
    }

    public boolean isScaleBeyondBoundaries() {
        return getSharedPreferences().getBoolean(PREF_GLOBAL_SCALE_BEYOND, true);
    }

    public boolean isOverscan() {
        return getSharedPreferences().getBoolean("PREF_GLOBAL_OVERSCAN", false);
    }

    public boolean isNotchUsed() {
        return getSharedPreferences().getBoolean(PREF_GLOBAL_USE_NOTCH, false);
    }

	public boolean isSimpleUI() {
		return getSharedPreferences().getBoolean(PREF_GLOBAL_SIMPLE_UI, false);
	}

    public boolean isBottomReload() {
        return getSharedPreferences().getBoolean("PREF_BOTTOM_RELOAD", true);
    }

	public boolean isLightgunLongPress() {
		return getSharedPreferences().getBoolean("PREF_LIGHTGUN_LONGPRESS", true);
	}

    public boolean isFakeID() {
        return getSharedPreferences().getBoolean(PREF_INPUT_FAKE_ID, false);
    }
}

android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/DialogHelper.java
public class DialogHelper {

	public static int savedDialog = DialogHelper.DIALOG_NONE;

	public final static int DIALOG_NONE = -1;
	public final static int DIALOG_EXIT = 1;
	public final static int DIALOG_ERROR_WRITING = 2;
	public final static int DIALOG_INFO = 3;
	public final static int DIALOG_OPTIONS = 5;
	public final static int DIALOG_FULLSCREEN = 7;
	public final static int DIALOG_FINISH_CUSTOM_LAYOUT = 10;
	public final static int DIALOG_EMU_RESTART = 11;
	public final static int DIALOG_NO_PERMISSIONS = 12;
	public final static int DIALOG_ROMs = 13;

	protected MAME4droid mm = null;

	static protected String errorMsg;
	static protected String infoMsg;

	public void setErrorMsg(String errorMsg) {
		DialogHelper.errorMsg = errorMsg;
	}

	public void setInfoMsg(String infoMsg) {
		DialogHelper.infoMsg = infoMsg;
	}

	public DialogHelper(MAME4droid value) {
		mm = value;
	}

	public Dialog createDialog(int id) {

		Dialog dialog;
		AlertDialog.Builder builder = new AlertDialog.Builder(mm);
		switch (id) {
			case DIALOG_FINISH_CUSTOM_LAYOUT:

				builder.setMessage("Do you want to save changes?")
					.setCancelable(false)
					.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							DialogHelper.savedDialog = DIALOG_NONE;
							mm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT);
							ControlCustomizer.setEnabled(false);
							mm.getInputHandler().getControlCustomizer().saveDefinedControlLayout();
							mm.getEmuView().setVisibility(View.VISIBLE);
							mm.getEmuView().requestFocus();
							Emulator.resume();
							mm.getInputView().invalidate();
						}
					})
					.setNegativeButton("No", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							DialogHelper.savedDialog = DIALOG_NONE;
							mm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT);
							ControlCustomizer.setEnabled(false);
							mm.getInputHandler().getControlCustomizer().discardDefinedControlLayout();
							mm.getEmuView().setVisibility(View.VISIBLE);
							mm.getEmuView().requestFocus();
							Emulator.resume();
							mm.getInputView().invalidate();
						}
					});
				dialog = builder.create();
				break;

			case DIALOG_ROMs:

				String message = "";

				message += "Where do you have stored or want to store your ROM files?\n\n" +
					"By default, an empty internal folder will be used (but you should manually copy your ROMs files there using a PC). You can also select a folder with ROMs files from your external storage which will "
					+ "need to be authorized in the next step so MAME4droid can read the ROMS from it.\n\n" +
					"Also, if you select an external storage folder, your ROMs files will not be deleted when the app is uninstalled and you can use an Android file manager to move your ROMs there without needing a PC.";

				builder.setMessage(message)
					.setCancelable(false)
					.setPositiveButton("Internal", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							DialogHelper.savedDialog = DIALOG_NONE;
							mm.removeDialog(DIALOG_ROMs);
							if (mm.getMainHelper().isAndroidTV())
								mm.getMainHelper().setInstallationDirType(MainHelper.INSTALLATION_DIR_MEDIA_FOLDER);
							else
								mm.getMainHelper().setInstallationDirType(MainHelper.INSTALLATION_DIR_FILES_DIR);
							mm.getPrefsHelper().setROMsDIR("");
							mm.getPrefsHelper().setSAF_Uri(null);

							Thread t = new Thread(new Runnable() { public void run() {
								mm.runMAME4droid();
							}});
							t.start();

							//mm.runMAME4droid();
						}
					})
					.setNegativeButton("External Storage", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							DialogHelper.savedDialog = DIALOG_NONE;
							mm.removeDialog(DIALOG_ROMs);

							try {
								Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
								mm.startActivityForResult(intent, MainHelper.REQUEST_CODE_OPEN_DIRECTORY);
								//throw new ActivityNotFoundException("TEST");
							} catch (ActivityNotFoundException e) {

								String msg = "Your device doesn't have the native android file manager needed to authorize external storage reading.";
								if (mm.getMainHelper().isAndroidTV())
									msg += "\n\nSome Android TV devices don't include the OS document picker which is needed to grant folder permissions for the apps on Android 11+. As an alternative, select default which use the App Media Folder which is supported on all devices and is created at Android/media/[app package name]. Move any emulator files into that folder with a file manager so the app can access them without any special permissions.";

								mm.getDialogHelper().showMessage(msg,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											android.os.Process.killProcess(android.os.Process.myPid());
										}
									});
							}
						}
					});
				dialog = builder.create();
				break;
			case DIALOG_EXIT:

				builder.setMessage("Are you sure you want to exit from app?")
					.setCancelable(false)
					.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							//System.exit(0);
							mm.finishAndRemoveTask();
							android.os.Process.killProcess(android.os.Process.myPid());
						}
					})
					.setNegativeButton("No", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							Emulator.resume();
							DialogHelper.savedDialog = DIALOG_NONE;
							mm.removeDialog(DIALOG_EXIT);
							//dialog.cancel();
						}
					});
				dialog = builder.create();
				break;
			case DIALOG_ERROR_WRITING:
				builder.setMessage("Error")
					.setCancelable(false)
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							//System.exit(0);
							DialogHelper.savedDialog = DIALOG_NONE;
							mm.removeDialog(DIALOG_ERROR_WRITING);
							mm.getMainHelper().restartApp();
							//mm.showDialog(DialogHelper.DIALOG_LOAD_FILE_EXPLORER);
						}
					});

				dialog = builder.create();
				break;
			case DIALOG_INFO:
				builder.setMessage("Info")
					.setCancelable(false)
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							DialogHelper.savedDialog = DIALOG_NONE;
							Emulator.resume();
							mm.removeDialog(DIALOG_INFO);
						}
					});

				dialog = builder.create();
				break;
			case DIALOG_OPTIONS:
			case DIALOG_FULLSCREEN:
				CharSequence[] items1 = {"Load State", "Save State", "Help", "Settings", "Keyboard"};
				CharSequence[] items2 = {"Help", "Settings", "Keyboard"};
				CharSequence[] items3 = {"Exit", "Load State", "Save State", "Help", "Settings", "Keyboard"};
				CharSequence[] items4 = {"Exit", "Help", "Settings", "Keyboard"};

				boolean saveload = Emulator.isInGameButNotInMenu() && Emulator.getValue(Emulator.PAUSE)!=1;

				final int a = id == DIALOG_FULLSCREEN ? 0 : 1;
				final int b =  saveload ? 0 : 2;

				if (a == 1)
					builder.setTitle("Choose an option from the menu.");

				CharSequence[] items = saveload ? (id == DIALOG_OPTIONS ? items1 : items3) : (id == DIALOG_OPTIONS ? items2 : items4);

				boolean notKeyboard = !mm.getPrefsHelper().isVirtualKeyboardEnabled() || mm.getInputHandler().getKeyboard().isKeyboardConnected() || mm.getMainHelper().isAndroidTV();

				if(notKeyboard)
					items = Arrays.copyOf(items, items.length-1);

				builder.setCancelable(true);
				builder.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {

						if (item == 0 && a == 0) {

							mm.showDialog(DialogHelper.DIALOG_EXIT);

							//if (Emulator.isInMenu()) {
							    /*
								Emulator.setValue(Emulator.EXIT_GAME, 1);
								Emulator.resume();
								try {
									Thread.sleep(PRESS_WAIT);
								} catch (InterruptedException e) {
								}
								Emulator.setValue(Emulator.EXIT_GAME, 0);
								*/

							/*
							} else if (!Emulator.isInGame())
								mm.showDialog(DialogHelper.DIALOG_EXIT);
							else {
								Emulator.setValue(Emulator.EXIT_GAME, 1);
								Emulator.resume();
								try {
									Thread.sleep(PRESS_WAIT);
								} catch (InterruptedException e) {
								}
								Emulator.setValue(Emulator.EXIT_GAME, 0);
							}
							 */
						} else if (item == 1 - a && b == 0) {
							Emulator.resume();
							Emulator.setValue(Emulator.LOADSTATE, 1);
							Emulator.setSaveorload(true);
							//Emulator.resume();
							try {
								Thread.sleep(PRESS_WAIT);
							} catch (InterruptedException e) {
							}
							Emulator.setValue(Emulator.LOADSTATE, 0);
						} else if (item == 2 - a && b == 0) {
							Emulator.resume();
							Emulator.setValue(Emulator.SAVESTATE, 1);
							Emulator.setSaveorload(true);
							//Emulator.resume();
							try {
								Thread.sleep(PRESS_WAIT);
							} catch (InterruptedException e) {
							}
							Emulator.setValue(Emulator.SAVESTATE, 0);
						} else if (item == 3 - a - b) {
							mm.getMainHelper().showHelp();
						} else if (item == 4 - a - b) {
							mm.getMainHelper().showSettings();
						} else if (item == 5 - a - b) {
							((IEmuView) mm.getEmuView()).showSoftKeyboard();
							Emulator.resume();
						}
						Emulator.setInOptions(false);

						DialogHelper.savedDialog = DIALOG_NONE;
						mm.removeDialog(DIALOG_OPTIONS);
						mm.removeDialog(DIALOG_FULLSCREEN);
					}
				});
				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {

						Emulator.resume();
						Emulator.setInOptions(false);

						DialogHelper.savedDialog = DIALOG_NONE;
						if (a != 0)
							mm.removeDialog(DIALOG_OPTIONS);
						else
							mm.removeDialog(DIALOG_FULLSCREEN);
					}
				});
				dialog = builder.create();
				break;
			case DIALOG_EMU_RESTART:
				builder.setTitle("Restart needed!")
					.setMessage("MAME4droid needs to restart for the changes to take effect.")
					.setCancelable(false)
					.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							mm.getMainHelper().restartApp();
						}
					});
				dialog = builder.create();
				break;
			case DIALOG_NO_PERMISSIONS:
				builder.setTitle("No permissions!")
					.setMessage("You don't have permission to read from external storage. Please, allow storage permission on Android applications settings.")
					.setCancelable(false)
					.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							android.os.Process.killProcess(android.os.Process.myPid());
						}
					});
				dialog = builder.create();
				break;
			default:
				dialog = null;
		}
	    /*
	    if(dialog!=null)
	    {
	    	dialog.setCanceledOnTouchOutside(false);
	    }*/
		return dialog;

	}

	public void prepareDialog(int id, Dialog dialog) {

		if (id == DIALOG_ERROR_WRITING) {
			((AlertDialog) dialog).setMessage(errorMsg);
			DialogHelper.savedDialog = DIALOG_ERROR_WRITING;
		} else if (id == DIALOG_INFO) {
			((AlertDialog) dialog).setMessage(infoMsg);
			Emulator.pause();
			DialogHelper.savedDialog = DIALOG_INFO;
		} else if (id == DIALOG_EXIT) {
			Emulator.pause();
			DialogHelper.savedDialog = DIALOG_EXIT;
		} else if (id == DIALOG_OPTIONS) {
			Emulator.pause();
			DialogHelper.savedDialog = DIALOG_OPTIONS;
		} else if (id == DIALOG_FULLSCREEN) {
			Emulator.pause();
			DialogHelper.savedDialog = DIALOG_FULLSCREEN;
		} else if (id == DIALOG_ROMs) {
			DialogHelper.savedDialog = DIALOG_ROMs;
		} else if (id == DIALOG_FINISH_CUSTOM_LAYOUT) {
			DialogHelper.savedDialog = DIALOG_FINISH_CUSTOM_LAYOUT;
		} else if (id == DIALOG_EMU_RESTART) {
			Emulator.pause();
		} else if (id == DIALOG_NO_PERMISSIONS) {
			DialogHelper.savedDialog = DIALOG_NO_PERMISSIONS;
		}

	}

	public void removeDialogs() {
		if (savedDialog == DIALOG_FINISH_CUSTOM_LAYOUT) {
			mm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT);
			DialogHelper.savedDialog = DIALOG_NONE;
		}
	}

	public void showMessage(String message, DialogInterface.OnClickListener okListener) {
		new AlertDialog.Builder(mm)
			.setMessage(message)
			.setCancelable(false)
			.setPositiveButton("OK", okListener)
			.create()
			.show();
	}

}

android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/MAME4droid.java
public class MAME4droid extends Activity {

    protected View emuView = null;

    protected InputView inputView = null;

    protected MainHelper mainHelper = null;
    protected PrefsHelper prefsHelper = null;
    protected DialogHelper dialogHelper = null;
    protected SAFHelper safHelper = null;

    protected InputHandler inputHandler = null;

    public PrefsHelper getPrefsHelper() {
        return prefsHelper;
    }

    public MainHelper getMainHelper() {
        return mainHelper;
    }

    public DialogHelper getDialogHelper() {
        return dialogHelper;
    }

    public SAFHelper getSAFHelper() {
        return safHelper;
    }

    public View getEmuView() {
        return emuView;
    }

    public InputView getInputView() {
        return inputView;
    }

    public InputHandler getInputHandler() {
        return inputHandler;
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //android.os.Debug.waitForDebugger();

        Log.d("EMULATOR", "onCreate " + this);
        System.out.println("onCreate intent:" + getIntent().getAction());

        overridePendingTransition(0, 0);
        getWindow().setWindowAnimations(0);

        prefsHelper = new PrefsHelper(this);

        dialogHelper = new DialogHelper(this);

        mainHelper = new MainHelper(this);

        safHelper = new SAFHelper(this);

        inputHandler = new InputHandler(this);

        mainHelper.detectDevice();

        inflateViews();

        Emulator.setMAME4droid(this);

        mainHelper.updateMAME4droid();

		String uri = getPrefsHelper().getSAF_Uri();
		if (uri != null) {
			safHelper.setURI(uri);
		}

        initMame4droid();
    }

    protected void initMame4droid() {
        if (!Emulator.isEmulating()) {

            if (getPrefsHelper().getInstallationDIR()==null || prefsHelper.getROMsDIR() == null ) {
                if (DialogHelper.savedDialog == DialogHelper.DIALOG_NONE) {
					    showDialog(DialogHelper.DIALOG_ROMs);
				}
            } else { //roms dir no es null es que previamente hemos puesto "" o un path especifico. Venimos del recreate y si ha cambiado el installation path hay que actuzalizarlo

                boolean res = getMainHelper().ensureInstallationDIR(mainHelper.getInstallationDIR());
                if (res == false) {
                    this.getPrefsHelper().setInstallationDIR(this.getPrefsHelper().getOldInstallationDIR());//revert
                } else {
                    runMAME4droid();//MAIN ENTRY POINT
                }
            }
        }
    }

    public void inflateViews() {

		if(getPrefsHelper().getOrientationMode()!=0) {
			int mode = getMainHelper().getScreenOrientation();
			this.setRequestedOrientation(mode);
		}

        if (getPrefsHelper().isNotchUsed()) {
            getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
        inputHandler.unsetInputListeners();

        Emulator.setPortraitFull(getPrefsHelper().isPortraitFullscreen());

        boolean full = false;
        if (prefsHelper.isPortraitFullscreen() && mainHelper.getscrOrientation() == Configuration.ORIENTATION_PORTRAIT) {
            setContentView(R.layout.main_fullscreen);
            full = true;
        } else {
            setContentView(R.layout.main);
        }

        FrameLayout fl = (FrameLayout) this.findViewById(R.id.EmulatorFrame);

        Emulator.setVideoRenderMode(getPrefsHelper().getVideoRenderMode());

        if (prefsHelper.getVideoRenderMode() == PrefsHelper.PREF_RENDER_GL) {

            if (prefsHelper.getNavBarMode() != PrefsHelper.PREF_NAVBAR_VISIBLE)
                this.getLayoutInflater().inflate(R.layout.emuview_gl_ext, fl);
            else
                this.getLayoutInflater().inflate(R.layout.emuview_gl, fl);

            emuView = this.findViewById(R.id.EmulatorViewGL);
        }

        if (full && prefsHelper.isPortraitTouchController()) {
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) emuView.getLayoutParams();
            lp.gravity = Gravity.TOP | Gravity.CENTER;
        }

        inputView = (InputView) this.findViewById(R.id.InputView);

        ((IEmuView) emuView).setMAME4droid(this);

        inputView.setMAME4droid(this);

        View frame = this.findViewById(R.id.EmulatorFrame);
        frame.setOnTouchListener(inputHandler);

        inputHandler.setInputListeners();
    }

    public void runMAME4droid() {

        getMainHelper().copyFiles();
        getMainHelper().removeFiles();

        Emulator.emulate(mainHelper.getLibDir(), mainHelper.getInstallationDIR());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
		Log.d("EMULATOR", "onConfigurationChanged " + this);

        super.onConfigurationChanged(newConfig);

        overridePendingTransition(0, 0);

        inflateViews();

        getMainHelper().updateMAME4droid();

        overridePendingTransition(0, 0);
    }

    //ACTIVITY
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mainHelper != null)
            mainHelper.activityResult(requestCode, resultCode, data);
    }

    //LIVE CYCLE
    @Override
    protected void onResume() {
        Log.d("EMULATOR", "onResume " + this);
        super.onResume();

        if (prefsHelper != null)
            prefsHelper.resume();

        if (DialogHelper.savedDialog != -1)
            showDialog(DialogHelper.savedDialog);
        else if (!ControlCustomizer.isEnabled())
            Emulator.resume();

        if (inputHandler != null) {
            if (inputHandler.getTiltSensor() != null)
                inputHandler.getTiltSensor().enable();
        }

        //System.out.println("OnResume");
    }

    @Override
    protected void onPause() {
        Log.d("EMULATOR", "onPause " + this);
        super.onPause();
        if (prefsHelper != null)
            prefsHelper.pause();
        if (!ControlCustomizer.isEnabled())
            Emulator.pause();
        if (inputHandler != null) {
            if (inputHandler.getTiltSensor() != null)
                inputHandler.getTiltSensor().disable();
        }

        if (dialogHelper != null) {
            dialogHelper.removeDialogs();
        }

        //System.out.println("OnPause");
    }

    @Override
    protected void onStart() {
        Log.d("EMULATOR", "onStart " + this);
        super.onStart();
        try {
            GameController.resetAutodetected();
        } catch (Throwable e) {
        }
        ;
        //System.out.println("OnStart");
    }

    @Override
    protected void onStop() {
        Log.d("EMULATOR", "onStop " + this);
        super.onStop();
        //System.out.println("OnStop");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d("EMULATOR", "onNewIntent " + this);
        System.out.println("onNewIntent action:" + intent.getAction());
        mainHelper.checkNewViewIntent(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("EMULATOR", "onDestroy " + this);

        View frame = this.findViewById(R.id.EmulatorFrame);
        if (frame != null)
            frame.setOnTouchListener(null);

        if (inputHandler != null) {
            inputHandler.unsetInputListeners();

            if (inputHandler.getTiltSensor() != null)
                inputHandler.getTiltSensor().disable();
        }

        if (emuView != null)
            ((IEmuView) emuView).setMAME4droid(null);

        /*
        if(inputView!=null)
           inputView.setMAME4droid(null);

        if(filterView!=null)
           filterView.setMAME4droid(null);

        prefsHelper = null;

        dialogHelper = null;

        mainHelper = null;

        inputHandler = null;

        inputView = null;

        emuView = null;

        filterView = null; */
    }

    //Dialog Stuff
    @Override
    protected Dialog onCreateDialog(int id) {

        if (dialogHelper != null) {
            Dialog d = dialogHelper.createDialog(id);
            if (d != null) return d;
        }
        return super.onCreateDialog(id);
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        if (dialogHelper != null)
            dialogHelper.prepareDialog(id, dialog);
    }

    @Override
    public boolean dispatchGenericMotionEvent(MotionEvent event) {
        if (inputHandler != null)
            return inputHandler.genericMotion(event);
        return false;
    }

	@Override
	public void onPointerCaptureChanged(boolean hasCapture) {
		super.onPointerCaptureChanged(hasCapture);
	}

	@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults == null || grantResults.length == 0) {
                    //this.showDialog(DialogHelper.DIALOG_NO_PERMISSIONS);
                    System.out.println("***1");
                } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    System.out.println("***2");
                    initMame4droid();
                } else {
                    System.out.println("***3");
                    this.showDialog(DialogHelper.DIALOG_NO_PERMISSIONS);
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

}

Answer: mm.showDialog(DialogHelper.DIALOG_OPTIONS);

<think>
The code is handling the OPTION_VALUE case inside handleControllerKey. After detecting the option button release and confirming the emulator is not already in the options menu, it sets the in‑options flag to true. The next logical step is to actually display the options dialog, which elsewhere in the project is done via mm.showDialog with the DIALOG_OPTIONS constant.
</think>
mm.showDialog(DialogHelper.DIALOG_OPTIONS);