Browse Source

Merge pull request #579 from AtomicGameEngine/JME-ATOMIC-575

Better preference handling with defaults
JoshEngebretson 10 years ago
parent
commit
2fe729e014

+ 3 - 2
CMakeLists.txt

@@ -19,7 +19,8 @@ if (ATOMIC_DEV_BUILD)
     add_definitions("-DATOMIC_DEV_BUILD=1")
 endif()
 
-add_definitions("-DATOMIC_SOURCE_BUILD=1")
+# Disable until https://github.com/AtomicGameEngine/AtomicGameEngine/issues/554 is addressed
+# add_definitions("-DATOMIC_SOURCE_BUILD=1")
 
 # this is here as QtCreator is having trouble picking up #include <Atomic/*> without it
 include_directories(${CMAKE_SOURCE_DIR}/Source ${CMAKE_SOURCE_DIR}/Source/AtomicEditor/Source)
@@ -67,7 +68,7 @@ endif()
 find_program(CLDOC cldoc)
 if(CLDOC)
 
-   add_custom_target(docs 
+   add_custom_target(docs
     DEPENDS AtomicEngineDocs
     )
 endif()

+ 3 - 2
Script/AtomicEditor/editor/Editor.ts

@@ -61,8 +61,9 @@ class Editor extends Atomic.ScriptObject {
                 playerWindow.y = data.posY;
                 playerWindow.monitor = data.monitor;
                 playerWindow.maximized = true;
+                playerWindow.centered = false;
             } else {
-                playerWindow = {x: data.posX, y: data.posY, width: data.width, height: data.height, monitor: data.monitor, maximized: data.maximized};
+                playerWindow = {x: data.posX, y: data.posY, width: data.width, height: data.height, monitor: data.monitor, maximized: data.maximized, centered: false};
             }
             Preferences.getInstance().savePlayerWindowData(playerWindow);
         });
@@ -115,7 +116,7 @@ class Editor extends Atomic.ScriptObject {
             editorWindowData.maximized = true;
             editorWindowData.monitor = monitor;
         } else {
-            editorWindowData = {x: pos[0], y: pos[1], width: width, height: height, monitor: monitor, maximized: false}
+            editorWindowData = {x: pos[0], y: pos[1], width: width, height: height, monitor: monitor, maximized: false, centered: false}
         }
 
         Preferences.getInstance().saveEditorWindowData(editorWindowData);

+ 56 - 18
Script/AtomicEditor/editor/Preferences.ts

@@ -60,24 +60,30 @@ class Preferences {
     read(): void {
         var filePath = this.getPreferencesFullPath();
         var jsonFile;
-        //check if file doesn't exists, create an empty JSON file
+
+        //check if file doesn't exist, create default json
         if (!this.fileSystem.fileExists(filePath)) {
-            jsonFile = new Atomic.File(filePath, Atomic.FILE_WRITE);
-            jsonFile.writeString("{}");
-            jsonFile.close();
+            this.useDefaultConfig();
+            this.write();
+            return;
         }
+
         //Read file
         jsonFile = new Atomic.File(filePath, Atomic.FILE_READ);
+
         var prefs;
+
         try {
-          prefs = <PreferencesFormat>JSON.parse(jsonFile.readText());
-        } catch (e){
-          console.log("Editor preference file invalid, regenerating default configuration");
-          prefs = null;
-          this.useDefaultConfig();
+
+            prefs = <PreferencesFormat>JSON.parse(jsonFile.readText());
+
+        } catch (e) {
+            console.log("Editor preference file invalid, regenerating default configuration");
+            this.useDefaultConfig();
+            this.write();
         }
+
         if (prefs) {
-            if (!prefs.recentProjects) prefs.recentProjects = [""];
             this._prefs = prefs;
         }
 
@@ -90,30 +96,29 @@ class Preferences {
         jsonFile.writeString(JSON.stringify(this._prefs, null, 2));
     }
 
-    saveEditorWindowData(windowData:WindowData) {
+    saveEditorWindowData(windowData: WindowData) {
         this._prefs.editorWindow = windowData;
         this.write();
     }
 
-    savePlayerWindowData(windowData:WindowData) {
+    savePlayerWindowData(windowData: WindowData) {
         this._prefs.playerWindow = windowData;
         this.write();
     }
 
-    useDefaultConfig():void {
+    useDefaultConfig(): void {
         this._prefs = new PreferencesFormat();
-        if (!this._prefs.recentProjects) this._prefs.recentProjects = [""];
     }
 
-    get editorWindow():WindowData {
+    get editorWindow(): WindowData {
         return this._prefs.editorWindow;
     }
 
-    get playerWindow():WindowData {
+    get playerWindow(): WindowData {
         return this._prefs.playerWindow;
     }
 
-    get recentProjects(): [string] {
+    get recentProjects(): string[] {
         return this._prefs.recentProjects;
     }
 
@@ -129,10 +134,43 @@ interface WindowData {
     height: number;
     monitor: number;
     maximized: boolean;
+    centered: boolean;
 }
 
 class PreferencesFormat {
-    recentProjects: [string];
+
+    constructor() {
+
+        this.setDefault();
+    }
+
+    setDefault() {
+
+        this.recentProjects = [];
+
+        this.editorWindow = {
+            x: 0,
+            y: 0,
+            width: 0,
+            height: 0,
+            monitor: 0,
+            maximized: true,
+            centered: false
+        }
+
+        this.playerWindow = {
+            x: 0,
+            y: 0,
+            width: 1280,
+            height: 720,
+            monitor: 0,
+            maximized: false,
+            centered: true
+        }
+
+    }
+
+    recentProjects: string[];
     editorWindow: WindowData;
     playerWindow: WindowData;
 }

+ 3 - 0
Script/AtomicEditor/ui/Shortcuts.ts

@@ -39,6 +39,9 @@ class Shortcuts extends Atomic.ScriptObject {
                     if (playerWindow.maximized) {
                         args += " --maximize";
                     }
+                    if (playerWindow.centered) {
+                        args += " --center";
+                    }
                     Atomic.editorMode.playProject(args, debug);
                 }
             } else {

+ 2 - 1
Source/Atomic/Engine/Engine.cpp

@@ -376,7 +376,8 @@ bool Engine::Initialize(const VariantMap& parameters)
             GetParameter(parameters, "VSync", false).GetBool(),
             GetParameter(parameters, "TripleBuffer", false).GetBool(),
             GetParameter(parameters, "MultiSample", 1).GetInt(),
-            GetParameter(parameters, "WindowMaximized", false).GetBool()
+            GetParameter(parameters, "WindowMaximized", false).GetBool(),
+            GetParameter(parameters, "WindowCentered", false).GetBool()
         ))
             return false;
 

+ 1 - 1
Source/Atomic/Graphics/Direct3D11/D3D11Graphics.cpp

@@ -425,7 +425,7 @@ bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless,
     // If zero dimensions in windowed mode, set windowed mode to maximize and set a predefined default restored window size. If zero in fullscreen, use desktop mode
     if (!width || !height)
     {
-        if (fullscreen || borderless)
+        if (fullscreen || borderless || maximize)
         {
             width = mode.w;
             height = mode.h;

+ 9 - 6
Source/Atomic/Graphics/Direct3D9/D3D9Graphics.cpp

@@ -405,7 +405,7 @@ void Graphics::RaiseWindow()
         SDL_RaiseWindow(impl_->window_);
 }
 bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer,
-    int multiSample, bool maximize)
+    int multiSample, bool maximize, bool center)
 {
     PROFILE(SetScreenMode);
 
@@ -417,7 +417,7 @@ bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless,
     // If zero dimensions in windowed mode, set windowed mode to maximize and set a predefined default restored window size. If zero in fullscreen, use desktop mode
     if (!width || !height)
     {
-        if (fullscreen || borderless)
+        if (fullscreen || borderless || maximize)
         {
             width = mode.w;
             height = mode.h;
@@ -448,7 +448,7 @@ bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless,
 
     if (!impl_->window_)
     {
-        if (!OpenWindow(width, height, resizable, borderless))
+        if (!OpenWindow(width, height, resizable, borderless, center))
             return false;
     }
 
@@ -599,7 +599,7 @@ bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless,
 
 bool Graphics::SetMode(int width, int height)
 {
-    return SetMode(width, height, fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_, false);
+    return SetMode(width, height, fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_, false, false);
 }
 
 void Graphics::SetSRGB(bool enable)
@@ -620,7 +620,7 @@ void Graphics::SetOrientations(const String& orientations)
 
 bool Graphics::ToggleFullscreen()
 {
-    return SetMode(width_, height_, !fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_, false);
+    return SetMode(width_, height_, !fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_, false, false);
 }
 
 void Graphics::Close()
@@ -2380,7 +2380,7 @@ void Graphics::ResetStreamFrequencies()
     }
 }
 
-bool Graphics::OpenWindow(int width, int height, bool resizable, bool borderless)
+bool Graphics::OpenWindow(int width, int height, bool resizable, bool borderless, bool center)
 {
     if (!externalWindow_)
     {
@@ -2401,6 +2401,9 @@ bool Graphics::OpenWindow(int width, int height, bool resizable, bool borderless
         return false;
     }
 
+    if (center)
+        CenterWindow();
+
     SDL_GetWindowPosition(impl_->window_, &position_.x_, &position_.y_);
 
     CreateWindowIcon();

+ 2 - 3
Source/Atomic/Graphics/Direct3D9/D3D9Graphics.h

@@ -104,8 +104,7 @@ public:
     /// Bring the window to front with focus
     void RaiseWindow();
     /// Set screen mode. Return true if successful.
-    bool SetMode
-        (int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer, int multiSample, bool maximize);
+    bool SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer, int multiSample, bool maximize, bool center);
     /// Set screen resolution only. Return true if successful.
     bool SetMode(int width, int height);
     /// Set whether the main window uses sRGB conversion on write.
@@ -508,7 +507,7 @@ private:
     /// Reset stream frequencies.
     void ResetStreamFrequencies();
     /// Create the application window.
-    bool OpenWindow(int width, int height, bool resizable, bool borderless);
+    bool OpenWindow(int width, int height, bool resizable, bool borderless, bool center);
     /// Create the application window icon.
     void CreateWindowIcon();
     /// Adjust the window for new resolution and fullscreen mode.

+ 9 - 6
Source/Atomic/Graphics/OpenGL/OGLGraphics.cpp

@@ -334,7 +334,7 @@ void* Graphics::GetSDLWindow()
 }
 
 bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer,
-    int multiSample, bool maximize)
+    int multiSample, bool maximize, bool center)
 {
     PROFILE(SetScreenMode);
 
@@ -365,7 +365,7 @@ bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless,
     // If zero in fullscreen, use desktop mode
     if (!width || !height)
     {
-        if (fullscreen || borderless)
+        if (fullscreen || borderless || maximize)
         {
             SDL_DisplayMode mode;
             SDL_GetDesktopDisplayMode(0, &mode);
@@ -508,9 +508,12 @@ bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless,
 
         CreateWindowIcon();
 
-        if (maximize)
+        if (maximize || center)
         {
-            Maximize();
+            if (maximize)
+                Maximize();
+            else if (center)
+                CenterWindow();
             SDL_GetWindowSize(impl_->window_, &width, &height);
         }
 
@@ -577,7 +580,7 @@ bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless,
 
 bool Graphics::SetMode(int width, int height)
 {
-    return SetMode(width, height, fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_, false);
+    return SetMode(width, height, fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_, false, false);
 }
 
 void Graphics::SetSRGB(bool enable)
@@ -614,7 +617,7 @@ void Graphics::SetOrientations(const String& orientations)
 
 bool Graphics::ToggleFullscreen()
 {
-    return SetMode(width_, height_, !fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_, false);
+    return SetMode(width_, height_, !fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_, false, false);
 }
 
 void Graphics::Close()

+ 1 - 2
Source/Atomic/Graphics/OpenGL/OGLGraphics.h

@@ -103,8 +103,7 @@ public:
     /// Get the SDL_Window as a void* to avoid having to include the graphics implementation
     void* GetSDLWindow();
     /// Set screen mode. Return true if successful.
-    bool SetMode
-        (int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer, int multiSample, bool maximize);
+    bool SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer, int multiSample, bool maximize, bool center);
     /// Set screen resolution only. Return true if successful.
     bool SetMode(int width, int height);
     /// Set whether the main window uses sRGB conversion on write.

+ 1 - 15
Source/AtomicEditor/Application/AEEditorApp.cpp

@@ -109,22 +109,8 @@ void AEEditorApp::Setup()
 
 #endif // ATOMIC_DEV_BUILD
 
-    String prefsPath = filesystem->GetAppPreferencesDir("AtomicEditor", "Preferences");
-    prefsPath += "prefs.json";
+    ReadPreferences();
 
-    JSONValue editorWindow;
-
-    if (ReadPreferences(prefsPath, editorWindow, "editorWindow"))
-    {
-        if (editorWindow.IsObject())
-        {
-            engineParameters_["WindowPositionX"] = editorWindow.Get("x").GetUInt();
-            engineParameters_["WindowPositionY"] = editorWindow.Get("y").GetUInt();
-            engineParameters_["WindowWidth"] = editorWindow.Get("width").GetUInt();
-            engineParameters_["WindowHeight"] = editorWindow.Get("height").GetUInt();
-            engineParameters_["WindowMaximized"] = editorWindow.Get("maximized").GetBool();
-        }
-    }
 }
 
 void AEEditorApp::Stop()

+ 82 - 13
Source/AtomicEditor/Application/AEEditorCommon.cpp

@@ -156,34 +156,103 @@ void AEEditorCommon::Stop()
 #endif
 }
 
-
-bool AEEditorCommon::ReadPreferences(String& path, JSONValue& prefs, const String& propertyName)
+bool AEEditorCommon::CreateDefaultPreferences(String& path, JSONValue& prefs)
 {
-    if (!path.EndsWith(".json"))
-        path.Append(".json");
+    // Note there is some duplication here with the editor's
+    // TypeScript preference code, this is due to the preferences for
+    // the editor window needing to be available at window creation time
+    // It could be better to split this all out to a native, scriptable
+    // preferences object
 
-    SharedPtr<File> file(new File(context_, path, FILE_READ));
+    LOGINFOF("Creating default Atomic Editor preferences: %s", path.CString());
 
     SharedPtr<JSONFile> jsonFile(new JSONFile(context_));
 
-    if (!jsonFile->BeginLoad(*file))
+    JSONValue& root = jsonFile->GetRoot();
+
+    root.Clear();
+    root["recentProjects"] = JSONArray();
+
+    JSONValue editorWindow;
+    editorWindow["x"] = 0;
+    editorWindow["y"] = 0;
+    editorWindow["width"] = 0;
+    editorWindow["height"] = 0;
+    editorWindow["monitor"] = 0;
+    editorWindow["maximized"] = true;
+    editorWindow["centered"] = false;
+
+    JSONValue playerWindow;
+    playerWindow["x"] = 0;
+    playerWindow["y"] = 0;
+    playerWindow["width"] = 1280;
+    playerWindow["height"] = 720;
+    playerWindow["monitor"] = 0;
+    playerWindow["maximized"] = false;
+    playerWindow["centered"] = true;
+
+    root["editorWindow"] = editorWindow;
+    root["playerWindow"] = playerWindow;
+
+    SharedPtr<File> file(new File(context_, path, FILE_WRITE));
+
+    if (!file->IsOpen())
+    {
+        LOGERRORF("Unable to open Atomic Editor preferences for writing: %s", path.CString());
         return false;
+    }
+
+    jsonFile->Save(*file, "   ");
+
+    prefs = root;
+
+    return true;
+}
+
+bool AEEditorCommon::ReadPreferences()
+{
+    FileSystem* fileSystem = GetSubsystem<FileSystem>();
+    String path = fileSystem->GetAppPreferencesDir("AtomicEditor", "Preferences");
+    path += "prefs.json";
 
-    JSONValue root = jsonFile->GetRoot();
+    JSONValue prefs;
 
-    if (propertyName.Length() > 0)
+    if (!fileSystem->FileExists(path))
     {
-        if (root.Contains(propertyName))
+        if (!CreateDefaultPreferences(path, prefs))
+            return false;
+    }
+    else
+    {
+        SharedPtr<File> file(new File(context_, path, FILE_READ));
+        SharedPtr<JSONFile> jsonFile(new JSONFile(context_));
+
+        if (!jsonFile->BeginLoad(*file))
         {
-            prefs = root.Get(propertyName);
+            file->Close();
+            if (!CreateDefaultPreferences(path, prefs))
+                return false;
         }
+        else
+        {
+            prefs = jsonFile->GetRoot();
+        }
+
     }
-    else
+
+    if (!prefs.IsObject() || !prefs["editorWindow"].IsObject())
     {
-        prefs = root;
+        if (!CreateDefaultPreferences(path, prefs))
+            return false;
     }
 
-    file->Close();
+    JSONValue& editorWindow = prefs["editorWindow"];
+
+    engineParameters_["WindowPositionX"] = editorWindow["x"].GetUInt();
+    engineParameters_["WindowPositionY"] = editorWindow["y"].GetUInt();
+    engineParameters_["WindowWidth"] = editorWindow["width"].GetUInt();
+    engineParameters_["WindowHeight"] = editorWindow["height"].GetUInt();
+    engineParameters_["WindowMaximized"] = editorWindow["maximized"].GetBool();
 
     return true;
 }

+ 2 - 1
Source/AtomicEditor/Application/AEEditorCommon.h

@@ -37,7 +37,8 @@ public:
 
 protected:
 
-    bool ReadPreferences(String& path, JSONValue& prefs, const String& propertyName = "");
+    bool CreateDefaultPreferences(String& path, JSONValue& prefs);
+    bool ReadPreferences();
     
     SharedPtr<JSVM> vm_;
 

+ 4 - 0
Source/AtomicEditor/Application/AEPlayerApp.cpp

@@ -179,6 +179,10 @@ void AEPlayerApplication::Setup()
             {
                 engineParameters_["WindowMaximized"] = true;
             }
+            else if (argument == "--center")
+            {
+                engineParameters_["WindowCentered"] = true;
+            }
         }
     }