Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept ROM Document Type #9

Merged
merged 7 commits into from
Mar 23, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions gambatte_watchOS/Game.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ public struct Game {
public let path: String

public init?(dictionary: [String: Any]) {
guard let name = dictionary["name"] as? String,
let path = dictionary["path"] as? String
guard let name = dictionary["name"] as? String, !name.isEmpty,
let path = dictionary["path"] as? String, !path.isEmpty
else {
return nil
}
Expand Down
32 changes: 25 additions & 7 deletions gambatte_watchOS/GameLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ public class GameLoader: NSObject {

var activationCompletion: ((Error?) -> Void)?

var gameResponse: ((String) -> Void)?
fileprivate var gameResponse: ((String) -> Void)?

var gamesUpdated: (([Game]) -> Void)?

static let shared = GameLoader()

Expand Down Expand Up @@ -104,13 +106,12 @@ public class GameLoader: NSObject {

func requestGames(_ success: @escaping (([Game]) -> Void), failure: @escaping ((Error) -> Void)) {

let replyHandler: (([String: Any]) -> Void) = { (response) in
guard let gamesRaw = response["games"] as? [[String: Any]] else {
let replyHandler: (([String: Any]) -> Void) = { [unowned self] (response) in
if let games = self.createGames(from: response) {
success(games)
} else {
failure(GameLoaderError(reason: "bad response"))
return
}
let games = gamesRaw.flatMap { Game(dictionary: $0) }
success(games)
}

session.sendMessage(["requestGames": 1], replyHandler: replyHandler, errorHandler: failure)
Expand All @@ -136,7 +137,11 @@ public class GameLoader: NSObject {
func cachedURL(for game: Game) -> URL? {
do {
let contents = try FileManager.default.contentsOfDirectory(at: cacheURL!, includingPropertiesForKeys: nil, options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles])
return contents.first(where: { $0.lastPathComponent.contains(game.name) })
return contents.first(where: { url -> Bool in
let matchingName = url.lastPathComponent.contains(game.name)
let matchingExtension = (url.pathExtension == URL(string: game.path)!.pathExtension)// .isValidROMExtension
return matchingName && matchingExtension
})
} catch {
return nil
}
Expand All @@ -145,10 +150,23 @@ public class GameLoader: NSObject {
var cacheURL: URL? {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
}

func createGames(from response: [String: Any]) -> [Game]? {
guard let gamesRaw = response["games"] as? [[String: Any]] else {
return nil
}
return gamesRaw.flatMap { Game(dictionary: $0) }
}
}

extension GameLoader: WCSessionDelegate {

public func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
if let games = createGames(from: message), let handler = gamesUpdated {
handler(games)
}
}

public func session(_ session: WCSession, didReceive file: WCSessionFile) {
print("received \(file)")

Expand Down
4 changes: 3 additions & 1 deletion giovanni WatchKit Extension/GameplayController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,9 @@ class GameplayController: WKInterfaceController {
// }
// lastSnapshot = snapshot

self.image.setImage(snapshot)
DispatchQueue.main.async {
self.image.setImage(snapshot)
}
tick = 0
}

Expand Down
18 changes: 17 additions & 1 deletion giovanni WatchKit Extension/LibraryController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class LibraryController: WKInterfaceController {
var games: [Game]? {
didSet {
if let games = games {
noGamesFound = games.count == 0
populateTable(with: games)
}
}
Expand All @@ -51,24 +52,39 @@ class LibraryController: WKInterfaceController {

override func awake(withContext context: Any?) {
super.awake(withContext: context)

reloadGames()
}

override func willActivate() {
super.willActivate()

GameLoader.shared.gamesUpdated = { [unowned self] games in
self.games = games
}

guard let cacheURL = GameLoader.shared.cacheURL else {
return
}
print("WATCH ROM URL: , \(cacheURL.absoluteString)")
// Auto-loads the last played game
// if let game = UserDefaults.standard.lastPlayed {
// presentGame(game)
// }
}

override func didDeactivate() {
super.didDeactivate()

GameLoader.shared.gamesUpdated = nil
}

func reloadGames() {

noGamesFound = false
populateTable(with: [])

let success: (([Game]) -> Void) = { [unowned self] games in
self.noGamesFound = games.count == 0
self.games = games
}

Expand Down
4 changes: 4 additions & 0 deletions giovanni.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@
B2DF6DA01E614C69001A811B /* GameRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2DF6D9F1E614C69001A811B /* GameRow.swift */; };
B2DF6DA21E619D16001A811B /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = B2DC85111E5DC6CC00CC1028 /* Interface.storyboard */; };
B2FC9BDE1E608AD5004D19C0 /* GameplayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2FC9BDD1E608AD5004D19C0 /* GameplayController.swift */; };
B2FCD4571E813EE900718BCF /* FileManagerAdditions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2FCD4561E813EE900718BCF /* FileManagerAdditions.swift */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -409,6 +410,7 @@
B2DF6DD21E61C3D3001A811B /* Game.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Game.swift; path = ../gambatte_watchOS/Game.swift; sourceTree = "<group>"; };
B2DF6DD31E61C3D3001A811B /* GameLoader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = GameLoader.swift; path = ../gambatte_watchOS/GameLoader.swift; sourceTree = "<group>"; };
B2FC9BDD1E608AD5004D19C0 /* GameplayController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GameplayController.swift; sourceTree = "<group>"; };
B2FCD4561E813EE900718BCF /* FileManagerAdditions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileManagerAdditions.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -726,6 +728,7 @@
children = (
B2DC84FD1E5DC6CB00CC1028 /* AppDelegate.swift */,
B2DC84FF1E5DC6CB00CC1028 /* ViewController.swift */,
B2FCD4561E813EE900718BCF /* FileManagerAdditions.swift */,
B2DC85011E5DC6CB00CC1028 /* Main.storyboard */,
B2DC85041E5DC6CB00CC1028 /* Assets.xcassets */,
B2DC85061E5DC6CB00CC1028 /* LaunchScreen.storyboard */,
Expand Down Expand Up @@ -1086,6 +1089,7 @@
files = (
B2DC85001E5DC6CB00CC1028 /* ViewController.swift in Sources */,
B2DC84FE1E5DC6CB00CC1028 /* AppDelegate.swift in Sources */,
B2FCD4571E813EE900718BCF /* FileManagerAdditions.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
24 changes: 24 additions & 0 deletions giovanni_iOS/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,30 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

guard let rootController = UIApplication.shared.keyWindow?.rootViewController as? ViewController else {
return false
}

return FileManager.default.receiveFile(at: url, completion: { (name) -> Bool in
let alert = UIAlertController(title: "Received \(name)",
message: "",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close", style: .default, handler: nil))
rootController.present(alert, animated: true, completion: nil)
rootController.sendGamesList()
return true
}) { (error) -> Bool in
let alert = UIAlertController(title: "Error Receiving File",
message: error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close", style: .default, handler: nil))
rootController.present(alert, animated: true, completion: nil)
return false
}
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
Expand Down
75 changes: 75 additions & 0 deletions giovanni_iOS/FileManagerAdditions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//
// FileManagerAdditions.swift
// GIOVANNI
//
// Copyright (c) <2017>, Gabriel O'Flaherty-Chan
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. All advertising materials mentioning features or use of this software
// must display the following acknowledgement:
// This product includes software developed by skysent.
// 4. Neither the name of the skysent nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY skysent ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL skysent BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

import Foundation

extension String {
var isValidROMExtension: Bool {
return ["gb", "gbc", "zip"].contains(self)
}
}

extension FileManager {

enum FileError: LocalizedError {
case invalidExtension

public var errorDescription: String? {
switch self {
case .invalidExtension:
return "Not a valid ROM file"
}
}
}

var documentsDirectory: URL? {
let directory: FileManager.SearchPathDirectory = .documentDirectory
return FileManager.default.urls(for: directory, in: .userDomainMask).first as URL?
}

func receiveFile(at fileURL: URL, completion: ((String) -> Bool), failure: ((Error) -> Bool)) -> Bool {

guard fileURL.pathExtension.isValidROMExtension else {
return failure(FileError.invalidExtension)
}

do {
let name = fileURL.lastPathComponent
let destinationPath = documentsDirectory!.appendingPathComponent(name)
try FileManager.default.moveItem(at: fileURL, to: destinationPath)
return completion(name)
} catch (let error) {
return failure(error)
}
}
}
14 changes: 14 additions & 0 deletions giovanni_iOS/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@
<string>en</string>
<key>CFBundleDisplayName</key>
<string>GIOVANNI</string>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeIconFiles</key>
<array/>
<key>CFBundleTypeName</key>
<string>ROM</string>
<key>LSItemContentTypes</key>
<array>
<string>public.data</string>
<string>public.content</string>
</array>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
Expand Down
27 changes: 18 additions & 9 deletions giovanni_iOS/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class ViewController: UIViewController {

prepareSession()

if let documentsDirectory = documentsDirectory {
if let documentsDirectory = FileManager.default.documentsDirectory {
print("ROM URL: \(documentsDirectory)")
}
}
Expand All @@ -58,31 +58,29 @@ class ViewController: UIViewController {
return .lightContent
}

var documentsDirectory: URL? {
let directory: FileManager.SearchPathDirectory = .documentDirectory
return FileManager.default.urls(for: directory, in: .userDomainMask).first as URL?
}


func loadGames() -> [[String: String]]? {

guard let documentsDirectory = documentsDirectory else {
guard let documentsDirectory = FileManager.default.documentsDirectory else {
return nil
}

do {
let URLs = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles])
let URLs = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants])
return encodeFiles(with: URLs)
} catch {
return nil
}
}

func encodeFiles(with URLs: [URL]) -> [[String: String]] {
return URLs.reduce([[String: String]]()) {
return URLs.filter { $0.pathExtension.isValidROMExtension }.reduce([[String: String]]()) {

var games = $0.0

let path = $0.1

let name = path
.lastPathComponent
.components(separatedBy: ".")
Expand Down Expand Up @@ -143,4 +141,15 @@ extension ViewController: WCSessionDelegate {
}
}

func sendGamesList() {
guard let games = loadGames() else {
return
}

if WCSession.default().activationState != .activated {
prepareSession()
}

WCSession.default().sendMessage(["games": games], replyHandler: nil, errorHandler: nil)
}
}